This repository was archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathtest_iqsharp.py
More file actions
372 lines (307 loc) · 11.7 KB
/
test_iqsharp.py
File metadata and controls
372 lines (307 loc) · 11.7 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/bin/env python
# -*- coding: utf-8 -*-
##
# test_iqsharp.py: Tests basic Q#/Python interop functionality.
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
## IMPORTS ##
import json
import numpy as np
import os
import pytest
import qsharp
import qsharp.experimental
qsharp.experimental.enable_noisy_simulation()
from .utils import set_environment_variables
print ( qsharp.component_versions() )
## SETUP ##
@pytest.fixture(scope="session", autouse=True)
def session_setup():
set_environment_variables()
try:
import qutip as qt
except ImportError:
qt = None
skip_if_no_qutip = pytest.mark.skipif(qt is None, reason="Test requires QuTiP.")
# If we can't import Microsoft as a Python package, then that means that
# the Q# workspace isn't present — probably because the qsharp-core package
# has been installed, since `Operations.qs` isn't part of the package data.
try:
import Microsoft.Quantum.SanityTests
workspace_present = True
except ImportError:
workspace_present = False
skip_if_no_workspace = pytest.mark.skipif(not workspace_present, reason="Local Q# workspace not available in installed package.")
# Finally, not all tests work well from within conda build environments, so
# we disable those tests here.
is_conda = getattr(qsharp.__version__, "is_conda", False) or os.environ.get("QSHARP_PY_ISCONDA", "False").lower() == "true"
skip_if_conda = pytest.mark.skipif(is_conda, reason="Test is not supported from conda-build.")
## TESTS ##
@skip_if_no_workspace
def test_simulate():
"""
Checks that a simple simulate works correctly, both using callable() and
callable.simulate()
"""
from Microsoft.Quantum.SanityTests import HelloQ, HelloAgain
assert HelloQ() == HelloQ.simulate() == ()
assert HelloAgain(
count=1, name="Ada") == HelloAgain.simulate(count=1, name="Ada")
def test_failing_simulate():
"""
Checks that fail statements in Q# operations are translated into Python
exceptions.
"""
print(qsharp)
fails = qsharp.compile("""
function Fails() : Unit {
fail "Failure message.";
}
""")
with pytest.raises(qsharp.ExecutionFailedException) as exc_info:
fails()
assert exc_info.type is qsharp.ExecutionFailedException
assert exc_info.value.args[0].split('\n')[0] == "Q# execution failed: Failure message."
@skip_if_no_workspace
def test_toffoli_simulate():
from Microsoft.Quantum.SanityTests import MeasureOne
assert MeasureOne.toffoli_simulate() == 1
@skip_if_no_workspace
def test_tuples():
"""
Checks that tuples are correctly encoded both ways.
"""
from Microsoft.Quantum.SanityTests import IndexIntoTuple
r = IndexIntoTuple.simulate(count=2, tuples=[(0, "Zero"), (1, "One"), (0, "Two"), (0, "Three")])
assert r == (0, "Two")
@skip_if_no_workspace
def test_numpy_types():
"""
Checks that numpy types are correctly encoded.
"""
from Microsoft.Quantum.SanityTests import IndexIntoNestedArray, IndexIntoTuple
r = IndexIntoNestedArray.simulate(index1=1, index2=0, nestedArray=np.array([[100, 101], np.array([110, 111], dtype=np.int64)]))
assert r == 110
tuples = [(0, "Zero"), (1, "One")]
tuples_array = np.empty(len(tuples), dtype=object)
tuples_array[:] = tuples
r = IndexIntoTuple.simulate(count=1, tuples=tuples_array)
assert r == (1, "One")
@skip_if_no_workspace
def test_result():
"""
Checks that Result-type arguments are handled correctly.
"""
from Microsoft.Quantum.SanityTests import EchoResult
r = EchoResult.simulate(input=qsharp.Result.One)
assert r == qsharp.Result.One
r = EchoResult.simulate(input=1)
assert r == qsharp.Result.One
# Current behavior is that non-integer values will get rounded to
# the nearest integer then converted to a Result. Once that behavior
# is fixed, this test should be updated to ensure that the following
# code throws a qsharp.IQSharpError exception.
# See https://github.com/microsoft/qsharp-runtime/issues/376.
r = EchoResult.simulate(input=0.2)
assert r == qsharp.Result.Zero
@skip_if_no_workspace
def test_long_tuple():
"""
Checks that a 10-tuple argument and return value are handled correctly.
"""
ten_tuple = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
from Microsoft.Quantum.SanityTests import IndexIntoTenTuple
r = IndexIntoTenTuple.simulate(index=3, tenTuple=ten_tuple)
assert r == 30
r = IndexIntoTenTuple.simulate(index=8, tenTuple=ten_tuple)
assert r == 80
from Microsoft.Quantum.SanityTests import EchoTenTuple
r = EchoTenTuple.simulate(tenTuple=ten_tuple)
assert r == ten_tuple
@skip_if_no_workspace
def test_paulis():
"""
Checks that Pauli-type and arrays of Pauli-type arguments are handled correctly.
"""
from Microsoft.Quantum.SanityTests import SwapFirstPauli
paulis = [qsharp.Pauli.Z, qsharp.Pauli.Z, qsharp.Pauli.Z]
pauliToSwap = qsharp.Pauli.X
r = SwapFirstPauli.simulate(paulis=paulis, pauliToSwap=pauliToSwap)
assert r[0] == [qsharp.Pauli.X, qsharp.Pauli.Z, qsharp.Pauli.Z]
assert r[1] == qsharp.Pauli.Z
# Should also work with string representation
paulis = ["PauliZ", "PauliZ", "PauliZ"]
pauliToSwap = "PauliX"
r = SwapFirstPauli.simulate(paulis=paulis, pauliToSwap=pauliToSwap)
assert r[0] == [qsharp.Pauli.X, qsharp.Pauli.Z, qsharp.Pauli.Z]
assert r[1] == qsharp.Pauli.Z
@skip_if_no_workspace
def test_estimate():
"""
Verifies that resource estimation works.
"""
from Microsoft.Quantum.SanityTests import HelloAgain
r = HelloAgain.estimate_resources(count=4, name="estimate test")
assert r['Measure'] == 8
assert r['QubitClifford'] == 1
assert r['BorrowedWidth'] == 0
@skip_if_no_workspace
def test_trace():
"""
Verifies the trace commands works.
"""
from Microsoft.Quantum.SanityTests import HelloAgain
r = HelloAgain.trace(count=1, name="trace test")
print(r)
assert len(r['qubits']) == 1
assert len(r['operations']) == 1
assert len(r['operations'][0]['children']) == 2
assert r['operations'][0]['gate'] == 'HelloAgain'
assert r['operations'][0]['children'][0]['gate'] == 'M'
assert r['operations'][0]['children'][1]['gate'] == 'Reset'
def test_simple_compile():
"""
Verifies that compile works
"""
op = qsharp.compile( """
operation HelloQ() : Result {
Message($"Hello from quantum world!");
return Zero;
}
""")
r = op.simulate()
assert r == 0
def test_multi_compile():
"""
Verifies that compile works and that operations
are returned in the correct order
"""
ops = qsharp.compile( """
operation HelloQ() : Result {
Message($"Hello from quantum world!");
return One;
}
operation Hello2() : Result {
Message($"Will call hello.");
return HelloQ();
}
""")
assert "HelloQ" == ops[0]._name
assert "Hello2" == ops[1]._name
r = ops[1].simulate()
assert r == qsharp.Result.One
def test_config():
"""
Verifies get and set of config settings of various types
"""
qsharp.config["dump.basisStateLabelingConvention"] = "Bitstring"
qsharp.config["dump.truncateSmallAmplitudes"] = True
qsharp.config["dump.truncationThreshold"] = 1e-6
assert qsharp.config["dump.basisStateLabelingConvention"] == "Bitstring"
assert qsharp.config["dump.truncateSmallAmplitudes"] == True
assert qsharp.config["dump.truncationThreshold"] == 1e-6
@skip_if_conda
def test_packages():
"""
Verifies default package command
"""
pkg_count = len(qsharp.packages._client.get_packages())
with pytest.raises(Exception):
qsharp.packages.add('Invalid.Package.!!!!!!')
assert pkg_count == len(qsharp.packages._client.get_packages())
# We test using a non-QDK package name to avoid possible version conflicts.
qsharp.packages.add('Microsoft.Extensions.Logging')
assert (pkg_count+1) == len(qsharp.packages._client.get_packages())
def test_projects(tmp_path):
"""
Verifies default project command
"""
assert 0 == len(qsharp.projects._client.get_projects())
with pytest.raises(Exception):
qsharp.projects.add('../InvalidPath/InvalidProject.txt')
assert 0 == len(qsharp.projects._client.get_projects())
temp_project_path = tmp_path / 'temp_iqsharp_pytest_project.csproj'
temp_project_path.write_text(f'''
<Project Sdk="Microsoft.Quantum.Sdk/0.12.20072031">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<IncludeQsharpCorePackages>false</IncludeQsharpCorePackages>
</PropertyGroup>
</Project>
''')
qsharp.projects.add(str(temp_project_path))
assert 1 == len(qsharp.projects._client.get_projects())
class TestCaptureDiagnostics:
def test_basic_capture(self):
dump_plus = qsharp.compile("""
open Microsoft.Quantum.Diagnostics;
operation DumpPlus() : Unit {
use qs = Qubit[2];
within {
H(qs[0]);
H(qs[1]);
} apply {
DumpMachine();
}
}
""")
with qsharp.capture_diagnostics(as_qobj=False) as captured:
dump_plus.simulate()
assert 1 == len(captured)
expected = """
{
"diagnostic_kind": "state-vector",
"qubit_ids": [0, 1],
"n_qubits": 2,
"amplitudes": {"0": {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, "1": {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, "2": {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, "3": {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}}
}
"""
assert json.dumps(json.loads(expected)) == json.dumps(captured[0])
@skip_if_no_qutip
def test_capture_diagnostics_as_qobj(self):
dump_plus = qsharp.compile("""
open Microsoft.Quantum.Diagnostics;
operation DumpPlus() : Unit {
use qs = Qubit[2];
within {
H(qs[0]);
H(qs[1]);
} apply {
DumpMachine();
}
}
""")
with qsharp.capture_diagnostics(as_qobj=True) as captured:
dump_plus.simulate()
assert 1 == len(captured)
assert abs(1.0 - captured[0].norm()) <= 1e-8
import qutip as qt
expected = qt.Qobj([[1], [1], [1], [1]], dims=[[2, 2], [1, 1]]).unit()
assert (expected - captured[0]).norm() <= 1e-8
@skip_if_no_qutip
def test_capture_experimental_diagnostics_as_qobj(self):
dump_plus = qsharp.compile("""
open Microsoft.Quantum.Diagnostics;
operation DumpPlus() : Unit {
use qs = Qubit[2];
within {
H(qs[0]);
H(qs[1]);
} apply {
DumpMachine();
}
}
""")
qsharp.experimental.set_noise_model_by_name('ideal')
qsharp.config['experimental.simulators.nQubits'] = 2
qsharp.config['experimental.simulators.representation'] = 'mixed'
with qsharp.capture_diagnostics(as_qobj=True) as captured:
dump_plus.simulate_noise()
assert 1 == len(captured)
assert abs(1.0 - captured[0].tr()) <= 1e-8
import qutip as qt
expected = qt.Qobj([[1], [1], [1], [1]], dims=[[2, 2], [1, 1]]).unit()
expected = expected * expected.dag()
assert (expected - captured[0]).norm() <= 1e-8