forked from microsoft/Quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateVisualizer.cs
185 lines (158 loc) · 6.39 KB
/
StateVisualizer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace Microsoft.Quantum.Samples.StateVisualizer
{
internal class StateVisualizer
{
private readonly QuantumSimulator simulator;
private readonly StateDumper stateDumper;
private readonly IWebHost host;
private readonly IHubContext<StateVisualizerHub> context;
private readonly ManualResetEvent advanceEvent = new ManualResetEvent(true);
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly IList<(string method, object[] args)> history = new List<(string, object[])>();
public StateVisualizer(QuantumSimulator simulator)
{
if (simulator == null)
{
throw new ArgumentNullException(nameof(simulator));
}
this.simulator = simulator;
simulator.OnOperationStart += OnOperationStartHandler;
simulator.OnOperationEnd += OnOperationEndHandler;
simulator.AfterAllocateQubits += AfterAllocateQubitsHandler;
simulator.AfterBorrowQubits += AfterBorrowQubitsHandler;
simulator.BeforeReleaseQubits += BeforeReleaseQubitsHandler;
simulator.BeforeReturnQubits += BeforeReturnQubitsHandler;
stateDumper = new StateDumper(simulator);
host = WebHost
.CreateDefaultBuilder()
.UseStartup<Startup>()
.ConfigureServices(services =>
{
// Register ourselves as a service so that the different
// hubs and controllers can use us through DI.
services.AddSingleton(typeof(StateVisualizer), this);
})
.UseUrls("http://localhost:5000")
.UseKestrel()
.Build();
new Thread(host.Run).Start();
context = GetService<IHubContext<StateVisualizerHub>>();
}
public async Task Run(Func<IOperationFactory, Task<QVoid>> operation)
{
await operation(simulator);
}
public async Task<O> Run<I, O>(Func<IOperationFactory, I, Task<O>> operation, I args) =>
await operation(simulator, args);
public bool Advance() => advanceEvent.Set();
public void Stop()
{
cancellationTokenSource.Cancel();
advanceEvent.Set();
}
public async Task ReplayHistory(IClientProxy client)
{
foreach (var (method, args) in history)
{
await client.SendCoreAsync(method, args);
}
}
private T GetService<T>() =>
(T) host.Services.GetService(typeof(T));
private async Task BroadcastAsync(string method, params object[] args)
{
history.Add((method, args));
await context.Clients.All.SendCoreAsync(method, args);
}
private async Task WaitForAdvance() =>
await Task.Run(() =>
{
advanceEvent.Reset();
advanceEvent.WaitOne();
}, cancellationTokenSource.Token);
private void OnOperationStartHandler(ICallable operation, IApplyData arguments)
{
var variant = operation.Variant == OperationFunctor.Body ? "" : operation.Variant.ToString();
var qubits = arguments.Qubits?.Select(q => q.Id).ToArray() ?? Array.Empty<int>();
BroadcastAsync(
"OperationStarted",
$"{variant} {operation.Name}",
qubits,
stateDumper.DumpAndGetAmplitudes()
).Wait();
WaitForAdvance().Wait();
}
private void OnOperationEndHandler(ICallable operation, IApplyData result)
{
BroadcastAsync("OperationEnded", result?.Value?.ToString(), stateDumper.DumpAndGetAmplitudes()).Wait();
WaitForAdvance().Wait();
}
private void AfterAllocateQubitsHandler(IQArray<Qubit> qubits)
{
BroadcastAsync("Log", $"Allocate {qubits.Length} qubit(s)", stateDumper.DumpAndGetAmplitudes()).Wait();
WaitForAdvance().Wait();
}
private void AfterBorrowQubitsHandler(IQArray<Qubit> qubits)
{
BroadcastAsync("Log", $"Borrow {qubits.Length} qubit(s)", stateDumper.DumpAndGetAmplitudes()).Wait();
WaitForAdvance().Wait();
}
private void BeforeReleaseQubitsHandler(IQArray<Qubit> qubits)
{
BroadcastAsync(
"Log",
$"Release qubit(s) {string.Join(", ", qubits.Select(q => q.Id))}",
stateDumper.DumpAndGetAmplitudes()
).Wait();
WaitForAdvance().Wait();
}
private void BeforeReturnQubitsHandler(IQArray<Qubit> qubits)
{
BroadcastAsync(
"Log",
$"Return qubit(s) {string.Join(", ", qubits.Select(q => q.Id))}",
stateDumper.DumpAndGetAmplitudes()
).Wait();
WaitForAdvance().Wait();
}
}
internal class StateDumper : QuantumSimulator.StateDumper
{
private List<Complex> amplitudes = new List<Complex>();
public StateDumper(QuantumSimulator simulator) : base(simulator)
{
}
public override bool Callback([MarshalAs(UnmanagedType.LPStr)] string idx, double real, double imaginary)
{
amplitudes.Add(new Complex(real, imaginary));
return true;
}
public override bool Dump(IQArray<Qubit> qubits = null)
{
amplitudes = new List<Complex>();
return base.Dump(qubits);
}
public Complex[] GetAmplitudes() => amplitudes.ToArray();
public Complex[] DumpAndGetAmplitudes(IQArray<Qubit> qubits = null)
{
Dump(qubits);
return GetAmplitudes();
}
}
}