forked from stevewithington/QuantumKatas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tests.qs
323 lines (279 loc) · 13.4 KB
/
Tests.qs
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
//////////////////////////////////////////////////////////////////////
// This file contains testing harness for all tasks.
// You should not modify anything in this file.
// The tasks themselves can be found in Tasks.qs file.
//////////////////////////////////////////////////////////////////////
namespace Quantum.Kata.MagicSquareGame {
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Random;
function SignFromBool (input : Bool) : Int {
return input ? 1 | -1;
}
@Test("QuantumSimulator")
operation T111_ValidAliceMove () : Unit {
// Try all moves with +1 and -1.
for (i in 0..1 <<< 3 - 1) {
let cells = Mapped(SignFromBool, IntAsBoolArray(i, 3));
Fact(ValidAliceMove(cells) == ValidAliceMove_Reference(cells),
$"Incorrect Alice move validity for {cells}");
}
// Moves with numbers other than +1 and -1 should be rejected.
for (cellsOutOfRange in [[1, -2, 10], [-3, 0, -2], [-1, 2, 1], [2, 3, 4]]) {
Fact(ValidAliceMove(cellsOutOfRange) == false,
$"Invalid Alice move judged valid for {cellsOutOfRange}");
}
}
@Test("QuantumSimulator")
operation T112_ValidBobMove () : Unit {
// Try all moves with +1 and -1.
for (i in 0..1 <<< 3 - 1) {
let cells = Mapped(SignFromBool, IntAsBoolArray(i, 3));
Fact(ValidBobMove(cells) == ValidBobMove_Reference(cells),
$"Incorrect Bob move validity for {cells}");
}
// Moves with numbers other than +1 and -1 should be rejected.
for (cellsOutOfRange in [[1, -2, 10], [-3, 0, -2], [-1, 2, 1], [2, 3, 4]]) {
Fact(ValidBobMove(cellsOutOfRange) == false,
$"Invalid Bob move judged valid for {cellsOutOfRange}");
}
}
// ------------------------------------------------------
@Test("QuantumSimulator")
operation T12_WinCondition () : Unit {
// Try all moves with +1 and -1.
for (i in 0..1 <<< 3 - 1) {
for (j in 0..1 <<< 3 - 1) {
for (rowIndex in 0..2) {
for (columnIndex in 0..2) {
let row = Mapped(SignFromBool, IntAsBoolArray(i, 3));
let column = Mapped(SignFromBool, IntAsBoolArray(j, 3));
Fact(
WinCondition(rowIndex, columnIndex, row, column) ==
WinCondition_Reference(rowIndex, columnIndex, row, column),
$"Incorrect win condition for rowIndex={rowIndex}, columnIndex={columnIndex}, " +
$" row={row}, column={column}");
}
}
}
}
// Moves with numbers other than +1 and -1 should be rejected.
let aliceOutOfRange = [-1, -1, 7];
let bobInRange = [-1, 1, 1];
Fact(not WinCondition(0, 0, aliceOutOfRange, bobInRange),
$"Win condition is wrong for Alice={aliceOutOfRange}, row=0, Bob={bobInRange}, column=0");
}
// ------------------------------------------------------
operation RunTrials (n : Int, moves : ((Int, Int) => (Int[], Int[]))) : Int {
mutable wins = 0;
for (i in 1..n) {
let rowIndex = DrawRandomInt(0, 2);
let columnIndex = DrawRandomInt(0, 2);
let (alice, bob) = moves(rowIndex, columnIndex);
if (WinCondition_Reference(rowIndex, columnIndex, alice, bob)) {
set wins += 1;
}
}
return wins;
}
operation ClassicalRunner (rowIndex : Int, columnIndex : Int) : (Int[], Int[]) {
return (AliceClassical(rowIndex), BobClassical(columnIndex));
}
@Test("QuantumSimulator")
operation T13_ClassicalStrategy() : Unit {
let wins = RunTrials(1000, ClassicalRunner);
Fact(wins >= 850, $"The classical strategy implemented is not optimal: win rate {IntAsDouble(wins) / 1000.}");
}
// ------------------------------------------------------
operation AssertEqualOnZeroState (N : Int, taskImpl : (Qubit[] => Unit),
refImpl : (Qubit[] => Unit is Adj)) : Unit {
using (qs = Qubit[N]) {
// apply operation that needs to be tested
taskImpl(qs);
// apply adjoint reference operation and check that the result is |0^N⟩
Adjoint refImpl(qs);
// assert that all qubits end up in |0⟩ state
AssertAllZero(qs);
}
}
@Test("QuantumSimulator")
operation T21_CreateEntangledState () : Unit {
AssertEqualOnZeroState(4, CreateEntangledState, CreateEntangledState_Reference);
}
// ------------------------------------------------------
function Pairs<'T> (array : 'T[]) : ('T, 'T)[] {
let N = Length(array);
let length = N * (N - 1) / 2;
mutable pairs = new ('T, 'T)[length];
mutable i = 0;
for (j in 0..N - 1) {
for (k in j + 1..N - 1) {
set pairs w/= i <- (array[j], array[k]);
set i += 1;
}
}
return pairs;
}
operation ControlledWrapper (op : (Qubit[] => Unit is Adj+Ctl), qs : Qubit[]) : Unit is Adj+Ctl {
Controlled op([Head(qs)], Rest(qs));
}
operation AssertOperationsEqualWithPhase (N : Int, op1 : (Qubit[] => Unit is Adj+Ctl), op2 : (Qubit[] => Unit is Adj+Ctl)) : Unit {
// To check that the operations don't introduce a phase, compare their controlled versions
AssertOperationsEqualReferenced(N + 1, ControlledWrapper(op1, _), ControlledWrapper(op2, _));
}
// Helper function to checks that each pair of operations in the array commutes (i.e., AB = BA)
operation AssertOperationsMutuallyCommute (operations : (Qubit[] => Unit is Adj+Ctl)[]) : Unit {
for ((a, b) in Pairs(operations)) {
AssertOperationsEqualWithPhase(2, BoundCA([a, b]), BoundCA([b, a]));
}
}
operation MinusI (qs : Qubit[]) : Unit is Adj+Ctl {
Z(qs[0]);
X(qs[0]);
Z(qs[0]);
X(qs[0]);
// An alternative approach is to use R(PauliI, 2 * PI(), _)
}
function ApplyObservablesImpl (row : Int, column : Int) : (Qubit[] => Unit is Adj+Ctl) {
return ApplyMagicObservables_Reference(GetMagicObservables(row, column), _);
}
@Test("QuantumSimulator")
operation T22_GetMagicObservables () : Unit {
// Since there can be multiple magic squares with different observables,
// the test checks the listed properties of the return values rather than the values themselves.
for (row in 0..2) {
let observables = Mapped(ApplyObservablesImpl(row, _), RangeAsIntArray(0..2));
// The product of observables in each row should be I.
AssertOperationsEqualWithPhase(2, BoundCA(observables), ApplyToEachCA(I, _));
AssertOperationsMutuallyCommute(observables);
}
for (column in 0..2) {
let observables = Mapped(ApplyObservablesImpl(_, column), RangeAsIntArray(0..2));
// The product of observables in each column should be -I.
AssertOperationsEqualWithPhase(2, BoundCA(observables), MinusI);
AssertOperationsMutuallyCommute(observables);
}
}
// ------------------------------------------------------
@Test("QuantumSimulator")
operation T23_ApplyMagicObservables () : Unit {
// Try all pairs of observables and all signs, and check the unitary equality
for (sign in [-1, 1]) {
for (obs1 in [PauliI, PauliX, PauliY, PauliZ]) {
for (obs2 in [PauliI, PauliX, PauliY, PauliZ]) {
let obs = (sign, [obs1, obs2]);
AssertOperationsEqualWithPhase(2, ApplyMagicObservables(obs, _), ApplyMagicObservables_Reference(obs, _));
}
}
}
}
// ------------------------------------------------------
@Test("QuantumSimulator")
operation T24_MeasureObservables () : Unit {
using (qs = Qubit[2]) {
for (sign in [-1, 1]) {
for (obs1 in [PauliI, PauliX, PauliY, PauliZ]) {
for (obs2 in [PauliI, PauliX, PauliY, PauliZ]) {
for (i in 1..100) {
// Start by preparing the qubits in a uniform superposition with some signs
if ((i % 4) / 2 == 1) {
X(qs[0]);
}
if ((i % 4) % 2 == 1) {
X(qs[1]);
}
ApplyToEach(H, qs);
// Use the reference implementation of observable measurement to project the register into an eigenstate of the operator
let observable = (sign, [obs1, obs2]);
let result = MeasureObservable_Reference(observable, qs);
// Make sure the task implementation gets the same result.
// If the implementation is wrong, it could pass accidentally,
// but with multiple operators and multiple attempts on each this should fail at some point.
Fact(MeasureObservable(observable, qs) == result,
$"Observable measurement result differs from the reference result for observable {observable}");
ResetAll(qs);
}
}
}
}
}
}
// ------------------------------------------------------
@Test("QuantumSimulator")
operation T25_MeasureOperator () : Unit {
using (qs = Qubit[2]) {
for (sign in [-1, 1]) {
for (obs1 in [PauliI, PauliX, PauliY, PauliZ]) {
for (obs2 in [PauliI, PauliX, PauliY, PauliZ]) {
for (i in 1..100) {
// Start by preparing the qubits in a uniform superposition with some signs
if ((i % 4) / 2 == 1) {
X(qs[0]);
}
if ((i % 4) % 2 == 1) {
X(qs[1]);
}
ApplyToEach(H, qs);
// Use the reference implementation of operator measurement to project the register into an eigenstate of the operator
let observable = (sign, [obs1, obs2]);
let op = ApplyMagicObservables_Reference(observable, _);
let result = MeasureOperator_Reference(op, qs);
// Make sure the task implementation gets the same result.
// If the implementation is wrong, it could pass accidentally,
// but with multiple operators and multiple attempts on each this should fail at some point.
Fact(MeasureOperator(op, qs) == result,
$"Operator measurement result differs from the reference result for observable {observable}");
ResetAll(qs);
}
}
}
}
}
}
// ------------------------------------------------------
operation QuantumRunner (referee : (((Qubit[] => Int[]), (Qubit[] => Int[])) => (Int[], Int[])),
rowIndex : Int,
columnIndex : Int) : (Int[], Int[]) {
return referee(AliceQuantum(rowIndex, _), BobQuantum(columnIndex, _));
}
@Test("QuantumSimulator")
operation T26_QuantumStrategy () : Unit {
let N = 1000;
let wins = RunTrials(N, QuantumRunner(PlayQuantumMagicSquare_Reference, _, _));
Fact(wins == N, $"Alice and Bob's quantum strategy is not optimal: win rate {IntAsDouble(wins) / IntAsDouble(N)}");
}
// ------------------------------------------------------
@Test("QuantumSimulator")
operation T27_PlayQuantumMagicSquare () : Unit {
let N = 1000;
let wins = RunTrials(N, QuantumRunner(PlayQuantumMagicSquare, _, _));
Message($"Win rate {IntAsDouble(wins) / IntAsDouble(N)}");
Fact(wins == N, $"Alice and Bob's quantum strategy is not optimal: win rate {IntAsDouble(wins) / IntAsDouble(N)}");
}
// ------------------------------------------------------
function DrawMagicSquare (alice : Int[], row : Int, bob : Int[], column : Int) : Unit {
for (i in 0..2) {
mutable line = new String[3];
for (j in 0..2) {
if (i == row and j == column and alice[j] != bob[i]) {
set line w/= j <- "±";
} elif (i == row) {
set line w/= j <- alice[j] == 1 ? "+" | (alice[j] == -1 ? "-" | "?");
} elif (j == column) {
set line w/= j <- bob[i] == 1 ? "+" | (bob[i] == -1 ? "-" | "?");
} else {
set line w/= j <- " ";
}
}
Message("-------");
Message($"|{line[0]}|{line[1]}|{line[2]}|");
}
Message("-------");
}
}