microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
iadavis/qasm-playground

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

source/npm/qsharp/src/compiler/common.ts

108lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4import { type VSDiagnostic } from "../../lib/web/qsc_wasm.js";
5
6// Each DumpMachine output is represented as an object where each key is a basis
7// state, e.g., "|3>" and the value is the [real, imag] parts of the complex amplitude.
8export type Dump = {
9 [index: string]: [number, number];
10};
11
12export type Result =
13 | { success: true; value: string }
14 | { success: false; value: VSDiagnostic };
15
16interface DumpMsg {
17 type: "DumpMachine";
18 state: Dump;
19 stateLatex: string | null;
20 qubitCount: number;
21}
22
23interface MatrixMsg {
24 type: "Matrix";
25 matrix: number[][][]; // Array or rows, which are an array of elements, which are complex numbers as [re, im]
26 matrixLatex: string;
27}
28
29interface MessageMsg {
30 type: "Message";
31 message: string;
32}
33
34interface ResultMsg {
35 type: "Result";
36 result: Result;
37}
38
39type EventMsg = ResultMsg | DumpMsg | MatrixMsg | MessageMsg;
40
41function outputAsResult(msg: string): ResultMsg | null {
42 try {
43 const obj = JSON.parse(msg);
44 if (obj?.type == "Result" && typeof obj.success == "boolean") {
45 return {
46 type: "Result",
47 result: {
48 success: obj.success,
49 value: obj.result,
50 },
51 };
52 }
53 } catch {
54 return null;
55 }
56 return null;
57}
58
59function outputAsMessage(msg: string): MessageMsg | null {
60 try {
61 const obj = JSON.parse(msg);
62 if (obj?.type == "Message" && typeof obj.message == "string") {
63 return obj as MessageMsg;
64 }
65 } catch {
66 return null;
67 }
68 return null;
69}
70
71function outputAsDump(msg: string): DumpMsg | null {
72 try {
73 const obj = JSON.parse(msg);
74 if (obj?.type == "DumpMachine" && typeof obj.state == "object") {
75 return obj as DumpMsg;
76 }
77 } catch {
78 return null;
79 }
80 return null;
81}
82
83function outputAsMatrix(msg: string): MatrixMsg | null {
84 try {
85 const obj = JSON.parse(msg);
86 if (obj?.type == "Matrix" && Array.isArray(obj.matrix)) {
87 return obj as MatrixMsg;
88 }
89 } catch {
90 return null;
91 }
92 return null;
93}
94
95export function eventStringToMsg(msg: string): EventMsg | null {
96 return (
97 outputAsResult(msg) ||
98 outputAsMessage(msg) ||
99 outputAsDump(msg) ||
100 outputAsMatrix(msg)
101 );
102}
103
104export type ShotResult = {
105 success: boolean;
106 result: string | VSDiagnostic;
107 events: Array<MessageMsg | DumpMsg | MatrixMsg>;
108};
109