tensorcircuit-nightly 1.2.0.dev20250326__py3-none-any.whl → 1.4.0.dev20251128__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tensorcircuit-nightly might be problematic. Click here for more details.

Files changed (77) hide show
  1. tensorcircuit/__init__.py +5 -1
  2. tensorcircuit/abstractcircuit.py +4 -0
  3. tensorcircuit/analogcircuit.py +413 -0
  4. tensorcircuit/applications/layers.py +1 -1
  5. tensorcircuit/applications/van.py +1 -1
  6. tensorcircuit/backends/abstract_backend.py +312 -5
  7. tensorcircuit/backends/cupy_backend.py +3 -1
  8. tensorcircuit/backends/jax_backend.py +100 -4
  9. tensorcircuit/backends/jax_ops.py +108 -0
  10. tensorcircuit/backends/numpy_backend.py +49 -3
  11. tensorcircuit/backends/pytorch_backend.py +92 -3
  12. tensorcircuit/backends/tensorflow_backend.py +102 -3
  13. tensorcircuit/basecircuit.py +157 -98
  14. tensorcircuit/circuit.py +115 -57
  15. tensorcircuit/cloud/local.py +1 -1
  16. tensorcircuit/cloud/quafu_provider.py +1 -1
  17. tensorcircuit/cloud/tencent.py +1 -1
  18. tensorcircuit/compiler/simple_compiler.py +2 -2
  19. tensorcircuit/cons.py +105 -23
  20. tensorcircuit/densitymatrix.py +16 -11
  21. tensorcircuit/experimental.py +733 -153
  22. tensorcircuit/fgs.py +254 -73
  23. tensorcircuit/gates.py +66 -22
  24. tensorcircuit/interfaces/jax.py +5 -3
  25. tensorcircuit/interfaces/tensortrans.py +6 -2
  26. tensorcircuit/interfaces/torch.py +14 -4
  27. tensorcircuit/keras.py +3 -3
  28. tensorcircuit/mpscircuit.py +154 -65
  29. tensorcircuit/quantum.py +698 -134
  30. tensorcircuit/quditcircuit.py +733 -0
  31. tensorcircuit/quditgates.py +618 -0
  32. tensorcircuit/results/counts.py +131 -18
  33. tensorcircuit/results/readout_mitigation.py +4 -1
  34. tensorcircuit/shadows.py +1 -1
  35. tensorcircuit/simplify.py +3 -1
  36. tensorcircuit/stabilizercircuit.py +29 -17
  37. tensorcircuit/templates/__init__.py +2 -0
  38. tensorcircuit/templates/blocks.py +2 -2
  39. tensorcircuit/templates/hamiltonians.py +174 -0
  40. tensorcircuit/templates/lattice.py +1789 -0
  41. tensorcircuit/timeevol.py +896 -0
  42. tensorcircuit/translation.py +10 -3
  43. tensorcircuit/utils.py +7 -0
  44. {tensorcircuit_nightly-1.2.0.dev20250326.dist-info → tensorcircuit_nightly-1.4.0.dev20251128.dist-info}/METADATA +66 -29
  45. tensorcircuit_nightly-1.4.0.dev20251128.dist-info/RECORD +96 -0
  46. {tensorcircuit_nightly-1.2.0.dev20250326.dist-info → tensorcircuit_nightly-1.4.0.dev20251128.dist-info}/WHEEL +1 -1
  47. {tensorcircuit_nightly-1.2.0.dev20250326.dist-info → tensorcircuit_nightly-1.4.0.dev20251128.dist-info}/top_level.txt +0 -1
  48. tensorcircuit_nightly-1.2.0.dev20250326.dist-info/RECORD +0 -118
  49. tests/__init__.py +0 -0
  50. tests/conftest.py +0 -67
  51. tests/test_backends.py +0 -1035
  52. tests/test_calibrating.py +0 -149
  53. tests/test_channels.py +0 -409
  54. tests/test_circuit.py +0 -1699
  55. tests/test_cloud.py +0 -219
  56. tests/test_compiler.py +0 -147
  57. tests/test_dmcircuit.py +0 -555
  58. tests/test_ensemble.py +0 -72
  59. tests/test_fgs.py +0 -310
  60. tests/test_gates.py +0 -156
  61. tests/test_interfaces.py +0 -562
  62. tests/test_keras.py +0 -160
  63. tests/test_miscs.py +0 -282
  64. tests/test_mpscircuit.py +0 -341
  65. tests/test_noisemodel.py +0 -156
  66. tests/test_qaoa.py +0 -86
  67. tests/test_qem.py +0 -152
  68. tests/test_quantum.py +0 -549
  69. tests/test_quantum_attr.py +0 -42
  70. tests/test_results.py +0 -380
  71. tests/test_shadows.py +0 -160
  72. tests/test_simplify.py +0 -46
  73. tests/test_stabilizer.py +0 -217
  74. tests/test_templates.py +0 -218
  75. tests/test_torchnn.py +0 -99
  76. tests/test_van.py +0 -102
  77. {tensorcircuit_nightly-1.2.0.dev20250326.dist-info → tensorcircuit_nightly-1.4.0.dev20251128.dist-info}/licenses/LICENSE +0 -0
tests/test_dmcircuit.py DELETED
@@ -1,555 +0,0 @@
1
- import sys
2
- import os
3
- import numpy as np
4
- import pytest
5
- from pytest_lazyfixture import lazy_fixture as lf
6
- import tensorflow as tf
7
-
8
- thisfile = os.path.abspath(__file__)
9
- modulepath = os.path.dirname(os.path.dirname(thisfile))
10
-
11
- sys.path.insert(0, modulepath)
12
- import tensorcircuit as tc
13
- from tensorcircuit.channels import (
14
- depolarizingchannel,
15
- single_qubit_kraus_identity_check,
16
- )
17
-
18
-
19
- def test_gate_dm():
20
- c = tc.DMCircuit(3)
21
- c.H(0)
22
- c.rx(1, theta=tc.num_to_tensor(np.pi))
23
- np.testing.assert_allclose(c.expectation((tc.gates.z(), [0])), 0.0, atol=1e-4)
24
- np.testing.assert_allclose(c.expectation((tc.gates.z(), [1])), -1.0, atol=1e-4)
25
-
26
-
27
- def test_state_inputs():
28
- w = np.zeros([8])
29
- w[1] = 1.0
30
- c = tc.DMCircuit(3, inputs=w)
31
- c.cnot(2, 1)
32
- np.testing.assert_allclose(c.expectation((tc.gates.z(), [1])), -1.0)
33
- np.testing.assert_allclose(c.expectation((tc.gates.z(), [2])), -1.0)
34
- np.testing.assert_allclose(c.expectation((tc.gates.z(), [0])), 1.0)
35
-
36
- s2 = np.sqrt(2.0)
37
- w = np.array([1 / s2, 0, 0, 1.0j / s2])
38
- c = tc.DMCircuit(2, inputs=w)
39
- c.Y(0)
40
- answer = np.array(
41
- [[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]
42
- )
43
- print(c.densitymatrix())
44
- np.testing.assert_allclose(c.densitymatrix(), answer)
45
-
46
- c = tc.DMCircuit(2, inputs=w)
47
- c.Y(0)
48
- print(c.densitymatrix())
49
- np.testing.assert_allclose(c.densitymatrix(), answer)
50
-
51
-
52
- @pytest.mark.parametrize("backend", [lf("npb"), lf("jaxb"), lf("tfb")])
53
- def test_dm_inputs(backend):
54
- rho0 = np.array([[0, 0, 0, 0], [0, 0.5, 0, -0.5j], [0, 0, 0, 0], [0, 0.5j, 0, 0.5]])
55
- b1 = np.array([[0, 1.0j], [0, 0]])
56
- b2 = np.array([[0, 0], [1.0j, 0]])
57
- ib1 = np.kron(np.eye(2), b1)
58
- ib2 = np.kron(np.eye(2), b2)
59
- rho1 = ib1 @ rho0 @ np.transpose(np.conj(ib1)) + ib2 @ rho0 @ np.transpose(
60
- np.conj(ib2)
61
- )
62
- iy = np.kron(np.eye(2), np.array([[0, -1.0j], [1.0j, 0]]))
63
- rho2 = iy @ rho1 @ np.transpose(np.conj(iy))
64
- rho0 = rho0.astype(np.complex64)
65
- b1 = b1.astype(np.complex64)
66
- b2 = b2.astype(np.complex64)
67
- c = tc.DMCircuit(nqubits=2, dminputs=rho0)
68
- c.apply_general_kraus([tc.gates.Gate(b1), tc.gates.Gate(b2)], [(1,)])
69
- np.testing.assert_allclose(c.densitymatrix(), rho1, atol=1e-4)
70
- c.y(1)
71
- np.testing.assert_allclose(c.densitymatrix(), rho2, atol=1e-4)
72
-
73
-
74
- def test_inputs_and_kraus():
75
- rho0 = np.array([[0, 0, 0, 0], [0, 0.5, 0, -0.5j], [0, 0, 0, 0], [0, 0.5j, 0, 0.5]])
76
- b1 = np.array([[0, 1.0j], [0, 0]])
77
- b2 = np.array([[0, 0], [1.0j, 0]])
78
- single_qubit_kraus_identity_check([tc.gates.Gate(b1), tc.gates.Gate(b2)])
79
- ib1 = np.kron(np.eye(2), b1)
80
- ib2 = np.kron(np.eye(2), b2)
81
- rho1 = ib1 @ rho0 @ np.transpose(np.conj(ib1)) + ib2 @ rho0 @ np.transpose(
82
- np.conj(ib2)
83
- )
84
- iy = np.kron(np.eye(2), np.array([[0, -1.0j], [1.0j, 0]]))
85
- rho2 = iy @ rho1 @ np.transpose(np.conj(iy))
86
- s2 = np.sqrt(2.0)
87
- w = np.array([1 / s2, 0, 0, 1.0j / s2])
88
-
89
- c = tc.DMCircuit(2, inputs=w)
90
- c.y(0)
91
- c.cnot(0, 1)
92
- np.testing.assert_allclose(c.densitymatrix(), rho0, atol=1e-4)
93
- c.apply_general_kraus([tc.gates.Gate(b1), tc.gates.Gate(b2)], 1)
94
- np.testing.assert_allclose(c.densitymatrix(), rho1, atol=1e-4)
95
- c.y(1)
96
- np.testing.assert_allclose(c.densitymatrix(), rho2, atol=1e-4)
97
-
98
- c = tc.DMCircuit(2, inputs=w)
99
- c.y(0)
100
- c.cnot(0, 1)
101
- np.testing.assert_allclose(c.densitymatrix(), rho0, atol=1e-4)
102
- c.apply_general_kraus([tc.gates.Gate(b1), tc.gates.Gate(b2)], [(1,)])
103
- np.testing.assert_allclose(c.densitymatrix(), rho1, atol=1e-4)
104
- c.y(1)
105
- np.testing.assert_allclose(c.densitymatrix(), rho2, atol=1e-4)
106
-
107
-
108
- def test_gate_depolarizing():
109
- ans = np.array(
110
- [[0.4, 0, 0.4, 0], [0, 0.1, 0, 0.1], [0.4, 0, 0.4, 0], [0, 0.1, 0, 0.1]]
111
- )
112
-
113
- def check_template(c, api="v1"):
114
- c.H(0)
115
- if api == "v1":
116
- kraus = depolarizingchannel(0.1, 0.1, 0.1)
117
- c.apply_general_kraus(kraus, [(1,)])
118
- else:
119
- c.depolarizing(1, px=0.1, py=0.1, pz=0.1)
120
- np.testing.assert_allclose(
121
- c.densitymatrix(check=True),
122
- ans,
123
- atol=1e-5,
124
- )
125
-
126
- for c, v in zip([tc.DMCircuit(2), tc.DMCircuit_reference(2)], ["v1", "v2"]):
127
- check_template(c, v)
128
-
129
-
130
- @pytest.mark.parametrize("backend", [lf("jaxb"), lf("tfb")])
131
- def test_mult_qubit_kraus(backend):
132
- xx = np.array(
133
- [[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]], dtype=np.complex64
134
- ) / np.sqrt(2)
135
- yz = np.array(
136
- [[0, 0, -1.0j, 0], [0, 0, 0, 1.0j], [1.0j, 0, 0, 0], [0, -1.0j, 0, 0]],
137
- dtype=np.complex64,
138
- ) / np.sqrt(2)
139
-
140
- def forward(theta):
141
- c = tc.DMCircuit_reference(3)
142
- c.H(0)
143
- c.rx(1, theta=theta)
144
- c.apply_general_kraus(
145
- [
146
- tc.gates.Gate(xx.reshape([2, 2, 2, 2])),
147
- tc.gates.Gate(yz.reshape([2, 2, 2, 2])),
148
- ],
149
- [(0, 1), (0, 1)],
150
- )
151
- c.H(1)
152
- return tc.backend.real(tc.backend.sum(c.densitymatrix()))
153
-
154
- theta = tc.num_to_tensor(0.2)
155
- vg = tc.backend.value_and_grad(forward)
156
- _, g1 = vg(theta)
157
- np.testing.assert_allclose(tc.backend.numpy(g1), 0.199, atol=1e-2)
158
-
159
- def forward2(theta):
160
- c = tc.DMCircuit(3)
161
- c.H(0)
162
- c.rx(1, theta=theta)
163
- c.apply_general_kraus(
164
- [tc.gates.Gate(xx), tc.gates.Gate(yz)],
165
- 0,
166
- 1,
167
- )
168
- c.H(1)
169
- return tc.backend.real(tc.backend.sum(c.densitymatrix()))
170
-
171
- theta = tc.num_to_tensor(0.2)
172
- vg2 = tc.backend.value_and_grad(forward2)
173
- _, g2 = vg2(theta)
174
- np.testing.assert_allclose(tc.backend.numpy(g2), 0.199, atol=1e-2)
175
-
176
-
177
- @pytest.mark.parametrize("backend", [lf("jaxb"), lf("tfb")])
178
- def test_noise_param_ad(backend):
179
- def forward(p):
180
- c = tc.DMCircuit(2)
181
- c.X(1)
182
- c.depolarizing(1, px=p, py=p, pz=p)
183
- return tc.backend.real(
184
- c.expectation(
185
- (
186
- tc.gates.z(),
187
- [
188
- 1,
189
- ],
190
- )
191
- )
192
- )
193
-
194
- theta = tc.num_to_tensor(0.1)
195
- vg = tc.backend.value_and_grad(forward)
196
- v, g = vg(theta)
197
- np.testing.assert_allclose(v, -0.6, atol=1e-2)
198
- np.testing.assert_allclose(g, 4, atol=1e-2)
199
-
200
-
201
- def test_ad_channel(tfb):
202
- p = tf.Variable(initial_value=0.1, dtype=tf.float32)
203
- theta = tf.Variable(initial_value=0.1, dtype=tf.complex64)
204
- with tf.GradientTape() as tape:
205
- tape.watch(p)
206
- c = tc.DMCircuit(3)
207
- c.rx(1, theta=theta)
208
- c.apply_general_kraus(depolarizingchannel(p, 0.2 * p, p), [(1,)])
209
- c.H(0)
210
- loss = c.expectation((tc.gates.z(), [1]))
211
- g = tape.gradient(loss, p)
212
- np.testing.assert_allclose(loss.numpy(), 0.7562, atol=1e-4)
213
- np.testing.assert_allclose(g.numpy(), -2.388, atol=1e-4)
214
-
215
-
216
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb"), lf("torchb")])
217
- def test_inputs_pipeline(backend):
218
- dm = 0.25 * np.eye(4)
219
- c = tc.DMCircuit(2, dminputs=dm)
220
- c.H(0)
221
- c.general_kraus(
222
- [np.sqrt(0.5) * tc.gates._i_matrix, np.sqrt(0.5) * tc.gates._x_matrix], 1
223
- )
224
- r = c.expectation_ps(z=[0])
225
- np.testing.assert_allclose(r, 0.0, atol=1e-5)
226
-
227
-
228
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
229
- def test_measure(backend):
230
- key = tc.backend.get_random_state(42)
231
-
232
- @tc.backend.jit
233
- def r(key):
234
- tc.backend.set_random_state(key)
235
- c = tc.DMCircuit(2)
236
- c.depolarizing(0, px=0.2, py=0.2, pz=0.2)
237
- rs = c.measure(0, with_prob=True)
238
- return rs
239
-
240
- key1, key2 = tc.backend.random_split(key)
241
- rs1, rs2 = r(key1), r(key2)
242
- assert rs1[0] != rs2[0]
243
- print(rs1[1], rs2[1])
244
-
245
-
246
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
247
- def test_mpo_dm(backend, highp):
248
- c = tc.DMCircuit(3)
249
- c.H(1)
250
- c.depolarizing(0, px=0.05, py=0.02, pz=0.02)
251
- c.multicontrol(1, 0, 2, ctrl=[1, 1], unitary=tc.gates.x())
252
- r = tc.backend.real(c.expectation_ps(z=[2]))
253
- np.testing.assert_allclose(r, 0.93, atol=1e-8)
254
-
255
-
256
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
257
- def test_to_circuit(backend):
258
- c = tc.DMCircuit(2)
259
- c.X(0)
260
- c.depolarizing(0, px=0.1, py=0.1, pz=0.1)
261
- c.cnot(0, 1)
262
- np.testing.assert_allclose(
263
- tc.backend.real(c.expectation_ps(z=[1])), -0.6, atol=1e-5
264
- )
265
- c2 = c.to_circuit()
266
- np.testing.assert_allclose(
267
- tc.backend.real(c2.expectation_ps(z=[1])), -1.0, atol=1e-5
268
- )
269
-
270
-
271
- def test_dmcircuit_inverse():
272
- c = tc.DMCircuit2(3)
273
- c.h(0)
274
- c.rx(1, theta=0.5)
275
- c.amplitudedamping(1, gamma=0.1, p=0.9)
276
- c.amplitudedamping(2, gamma=0.1, p=0.9)
277
- c.rzz(0, 2, theta=-1.0)
278
- ci = c.inverse()
279
- r = tc.backend.real(ci.expectation_ps(z=[2]))
280
- c2 = tc.DMCircuit2(3)
281
- c2.rzz(0, 2, theta=1.0)
282
- c2.rx(1, theta=-0.5)
283
- c2.h(0)
284
- r2 = tc.backend.real(c2.expectation_ps(z=[2]))
285
- np.testing.assert_allclose(r, r2, atol=1e-5)
286
-
287
-
288
- @pytest.mark.parametrize("backend", [lf("tfb"), lf("jaxb")])
289
- def test_perfect_sampling_with_status(backend):
290
- n = 3
291
-
292
- @tc.backend.jit
293
- def m(s):
294
- c = tc.DMCircuit(n)
295
- for i in range(n):
296
- c.H(i)
297
- for i in range(n):
298
- c.amplitudedamping(i, p=1.0, gamma=0.1)
299
- return c.perfect_sampling(s)
300
-
301
- s, p = m(tc.backend.convert_to_tensor(np.array([0.9, 0.5, 0.7])))
302
- np.testing.assert_allclose(s, np.array([1, 0, 1]))
303
- np.testing.assert_allclose(p, 0.111375, atol=1e-5)
304
-
305
-
306
- def test_dm_circuit_draw():
307
- c = tc.DMCircuit(3)
308
- c.H(0)
309
- c.cnot(0, 2)
310
- c.depolarizing(1, px=0.1, py=0.1, pz=0.1)
311
- c.rxx(1, 2, theta=0.5)
312
- print("\n")
313
- print(c.draw())
314
-
315
-
316
- def test_dm_qiskit():
317
- try:
318
- import qiskit
319
-
320
- print(qiskit.__version__)
321
- except ImportError:
322
- pytest.skip("qiskit is not installed")
323
- n = 4
324
- c = tc.DMCircuit(n)
325
- c.ryy(0, 1, theta=1.3)
326
- c.td(1)
327
- c.h(2)
328
- c.cnot(3, 0)
329
- c.cry(0, 1, theta=0.3)
330
- c.multicontrol(1, 2, 0, 3, ctrl=[0, 1], unitary=tc.gates._zz_matrix)
331
- c.cswap(1, 2, 3)
332
- qc = c.to_qiskit()
333
- c1 = tc.DMCircuit.from_qiskit(qc)
334
- r0 = sum(
335
- [c.expectation_ps(z=[i]) for i in range(n)]
336
- + [c.expectation_ps(y=[i]) for i in range(n)]
337
- )
338
- r1 = sum(
339
- [c1.expectation_ps(z=[i]) for i in range(n)]
340
- + [c1.expectation_ps(y=[i]) for i in range(n)]
341
- )
342
- np.testing.assert_allclose(r0, r1, atol=1e-5)
343
-
344
-
345
- @pytest.mark.parametrize("backend", [lf("tfb"), lf("jaxb")])
346
- def test_dmcircuit_split(backend):
347
- n = 4
348
-
349
- def f(param, max_singular_values=None, max_truncation_err=None, fixed_choice=None):
350
- if (max_singular_values is None) and (max_truncation_err is None):
351
- split = None
352
- else:
353
- split = {
354
- "max_singular_values": max_singular_values,
355
- "max_truncation_err": max_truncation_err,
356
- "fixed_choice": fixed_choice,
357
- }
358
- c = tc.DMCircuit(
359
- n,
360
- split=split,
361
- )
362
- for i in range(n):
363
- c.H(i)
364
- for j in range(2):
365
- for i in range(n - 1):
366
- c.exp1(i, i + 1, theta=param[2 * j, i], unitary=tc.gates._zz_matrix)
367
- for i in range(n):
368
- c.rx(i, theta=param[2 * j + 1, i])
369
- loss = c.expectation_ps(z=[1, 2])
370
- return tc.backend.real(loss)
371
-
372
- s1 = f(tc.backend.ones([4, n]))
373
- s2 = f(tc.backend.ones([4, n]), max_truncation_err=1e-5)
374
- s3 = f(tc.backend.ones([4, n]), max_singular_values=2, fixed_choice=1)
375
- np.testing.assert_allclose(s1, s2, atol=1e-5)
376
- np.testing.assert_allclose(s1, s3, atol=1e-5)
377
-
378
- # np.testing.assert_allclose(s1, s2, atol=1e-5)
379
- np.testing.assert_allclose(s1, s3, atol=1e-5)
380
-
381
- f_vg = tc.backend.jit(
382
- tc.backend.value_and_grad(f, argnums=0), static_argnums=(1, 2, 3)
383
- )
384
-
385
- s1, g1 = f_vg(tc.backend.ones([4, n]))
386
- s3, g3 = f_vg(tc.backend.ones([4, n]), max_singular_values=2, fixed_choice=1)
387
-
388
- np.testing.assert_allclose(s1, s3, atol=1e-5)
389
- np.testing.assert_allclose(g1, g3, atol=1e-5)
390
-
391
-
392
- def test_dm_amplitude():
393
- c = tc.DMCircuit(2)
394
- c.H(0)
395
- c.cnot(0, 1)
396
- np.testing.assert_allclose(c.amplitude("11"), 0.5, atol=1e-5)
397
- c.depolarizing(1, px=0.2, py=0, pz=0)
398
- np.testing.assert_allclose(c.amplitude("11"), 0.4, atol=1e-5)
399
-
400
-
401
- @pytest.mark.parametrize("backend", [lf("tfb"), lf("jaxb")])
402
- def test_dm_amplitude_jit(backend):
403
- @tc.backend.jit
404
- def m(s):
405
- c = tc.DMCircuit(2)
406
- c.H(0)
407
- c.cnot(0, 1)
408
- c.depolarizing(1, px=0.2, py=0.0, pz=0.0)
409
- return c.amplitude(s)
410
-
411
- np.testing.assert_allclose(m(tc.array_to_tensor([1, 1])), 0.4, atol=1e-5)
412
- np.testing.assert_allclose(m(tc.array_to_tensor([1, 0])), 0.1, atol=1e-5)
413
-
414
-
415
- def test_sample():
416
- c = tc.DMCircuit(2)
417
- c.H(0)
418
- c.cnot(0, 1)
419
- c.depolarizing(1, px=0.2, py=0.0, pz=0.0)
420
- print(c.sample(batch=10))
421
- print(c.sample(batch=20, allow_state=True))
422
-
423
-
424
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
425
- def test_dm_mps_inputs(backend):
426
- ns = [tc.gates.Gate(np.array([0.0, 1.0])) for _ in range(3)]
427
- mps = tc.quantum.QuVector([n[0] for n in ns])
428
- c = tc.DMCircuit(3, mps_inputs=mps)
429
- c.cnot(0, 1)
430
- c.depolarizing(1, px=0.2, py=0, pz=0)
431
- np.testing.assert_allclose(c.expectation_ps(z=[1]), 0.6, atol=1e-5)
432
- np.testing.assert_allclose(c.expectation_ps(z=[2]), -1.0, atol=1e-5)
433
-
434
-
435
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
436
- def test_dm_mpo_inputs(backend):
437
- n = 4
438
- nodes = [tc.Gate(np.eye(2) / 2.0) for _ in range(n)]
439
- mpo = tc.quantum.QuOperator([n[0] for n in nodes], [n[1] for n in nodes])
440
- print(len(mpo.nodes))
441
- np.testing.assert_allclose(tc.backend.trace(mpo.eval_matrix()), 1.0, atol=1e-5)
442
- c = tc.DMCircuit(4, mpo_dminputs=mpo)
443
- for i in range(n):
444
- c.x(i)
445
- c.depolarizing(i, px=0.1, py=0.1, pz=0.1)
446
- np.testing.assert_allclose(c.state(), np.eye(2**n) / 2**n, atol=1e-5)
447
- print(len(c._nodes), len(c._front))
448
-
449
-
450
- def test_dm_cond_measure():
451
- c = tc.DMCircuit(2)
452
- c.H(0)
453
- np.testing.assert_allclose(c.expectation_ps(x=[0]), 1.0, atol=1e-5)
454
- c.cond_measure(0)
455
- np.testing.assert_allclose(c.expectation_ps(x=[0]), 0.0, atol=1e-5)
456
-
457
-
458
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
459
- def test_prepend_dmcircuit(backend):
460
- c = tc.DMCircuit(2)
461
- c.H(0)
462
- c1 = tc.DMCircuit(2)
463
- c1.cnot(0, 1)
464
- c2 = c1.append(c)
465
- c3 = c2.prepend(c)
466
- qir = c3.to_qir()
467
- for n, n0 in zip(qir, ["h", "cnot", "h"]):
468
- assert n["name"] == n0
469
- s = c3.wavefunction()
470
- np.testing.assert_allclose(s[0], s[1], atol=1e-5)
471
-
472
-
473
- @pytest.mark.parametrize("backend", [lf("npb"), lf("tfb"), lf("jaxb")])
474
- def test_dm_sexpps(backend):
475
- c = tc.DMCircuit(1, inputs=1 / np.sqrt(2) * np.array([1.0, 1.0j]))
476
- y = c.sample_expectation_ps(y=[0])
477
- ye = c.expectation_ps(y=[0])
478
- np.testing.assert_allclose(y, 1.0, atol=1e-5)
479
- np.testing.assert_allclose(ye, 1.0, atol=1e-5)
480
-
481
- c = tc.DMCircuit(4)
482
- c.H(0)
483
- c.H(1)
484
- c.X(2)
485
- c.Y(3)
486
- c.cnot(0, 1)
487
- c.depolarizing(1, px=0.05, py=0.05, pz=0.1)
488
- c.rx(1, theta=0.3)
489
- c.ccnot(2, 3, 1)
490
- c.depolarizing(0, px=0.05, py=0.0, pz=0.1)
491
- c.rzz(0, 3, theta=0.5)
492
- c.ry(3, theta=2.2)
493
- c.amplitudedamping(2, gamma=0.1, p=0.95)
494
- c.s(1)
495
- c.td(2)
496
- c.cswap(3, 0, 1)
497
- y = c.sample_expectation_ps(x=[1], y=[0], z=[2, 3])
498
- ye = c.expectation_ps(x=[1], y=[0], z=[2, 3])
499
- np.testing.assert_allclose(ye, y, atol=1e-5)
500
- y2 = c.sample_expectation_ps(x=[1], y=[0], z=[2, 3], shots=81920)
501
- print(y, y2)
502
- assert np.abs(y2 - y) < 0.015
503
-
504
-
505
- def test_dm_sexpps_jittable_vamppable(jaxb):
506
- n = 4
507
- m = 2
508
-
509
- def f(param, key):
510
- c = tc.DMCircuit(n)
511
- for j in range(m):
512
- for i in range(n - 1):
513
- c.cnot(i, i + 1)
514
- for i in range(n):
515
- c.rx(i, theta=param[i, j])
516
- return tc.backend.real(
517
- c.sample_expectation_ps(y=[n // 2], shots=8192, random_generator=key)
518
- )
519
-
520
- vf = tc.backend.jit(tc.backend.vmap(f, vectorized_argnums=(0, 1)))
521
- r = vf(
522
- tc.backend.ones([2, n, m], dtype="float32"),
523
- tc.backend.stack(
524
- [
525
- tc.backend.get_random_state(42),
526
- tc.backend.get_random_state(43),
527
- ]
528
- ),
529
- )
530
- assert np.abs(r[0] - r[1]) > 1e-4
531
-
532
- print(r)
533
-
534
-
535
- def test_dm_sexpps_jittable_vamppable_tf(tfb):
536
- # finally giving up backend agnosticity
537
- # and not sure the effciency and the safety of vmap random in tf
538
- n = 4
539
- m = 2
540
-
541
- def f(param):
542
- c = tc.DMCircuit(n)
543
- for j in range(m):
544
- for i in range(n - 1):
545
- c.cnot(i, i + 1)
546
- for i in range(n):
547
- c.rx(i, theta=param[i, j])
548
- return tc.backend.real(c.sample_expectation_ps(y=[n // 2], shots=8192))
549
-
550
- vf = tc.backend.jit(tc.backend.vmap(f, vectorized_argnums=0))
551
- r = vf(tc.backend.ones([2, n, m]))
552
- r1 = vf(tc.backend.ones([2, n, m]))
553
- assert np.abs(r[0] - r[1]) > 1e-5
554
- assert np.abs(r[0] - r1[0]) > 1e-5
555
- print(r, r1)
tests/test_ensemble.py DELETED
@@ -1,72 +0,0 @@
1
- import os
2
- import sys
3
- import tensorflow as tf
4
- import numpy as np
5
- import pytest
6
-
7
- thisfile = os.path.abspath(__file__)
8
- modulepath = os.path.dirname(os.path.dirname(thisfile))
9
-
10
- sys.path.insert(0, modulepath)
11
-
12
- from tensorcircuit.applications.ai.ensemble import bagging
13
-
14
-
15
- @pytest.mark.xfail(
16
- int(tf.__version__.split(".")[1]) >= 16, reason="legacy optimizer fails tf>=2.16"
17
- )
18
- def test_ensemble_bagging():
19
- data_amount = 100 # Amount of data to be used
20
- linear_dimension = 4 # linear demension of the data
21
- epochs = 10
22
- batch_size = 32
23
- lr = 1e-3
24
-
25
- x_train, y_train = (
26
- np.ones([data_amount, linear_dimension]),
27
- np.ones([data_amount, 1]),
28
- )
29
-
30
- obj_bagging = bagging()
31
-
32
- def model():
33
- DROP = 0.1
34
-
35
- activation = "selu"
36
- inputs = tf.keras.Input(shape=(linear_dimension,), name="digits")
37
- x0 = tf.keras.layers.Dense(
38
- 1,
39
- kernel_regularizer=tf.keras.regularizers.l2(9.613e-06),
40
- activation=activation,
41
- )(inputs)
42
- x0 = tf.keras.layers.Dropout(DROP)(x0)
43
-
44
- x = tf.keras.layers.Dense(
45
- 1,
46
- kernel_regularizer=tf.keras.regularizers.l2(1e-07),
47
- activation="sigmoid",
48
- )(x0)
49
-
50
- model = tf.keras.Model(inputs, x)
51
-
52
- return model
53
-
54
- obj_bagging.append(model(), False)
55
- obj_bagging.append(model(), False)
56
- obj_bagging.append(model(), False)
57
- obj_bagging.compile(
58
- loss=tf.keras.losses.BinaryCrossentropy(),
59
- optimizer=tf.keras.optimizers.legacy.Adam(lr),
60
- metrics=[tf.keras.metrics.AUC(), "acc"],
61
- )
62
- obj_bagging.train(
63
- x=x_train, y=y_train, epochs=epochs, batch_size=batch_size, verbose=0
64
- )
65
-
66
- v_weight = obj_bagging.predict(x_train, "weight")
67
- v_average = obj_bagging.predict(x_train, "average")
68
- v_most = obj_bagging.predict(x_train, "most")
69
- validation_data = []
70
- validation_data.append(obj_bagging.eval([y_train, v_weight], "acc"))
71
- validation_data.append(obj_bagging.eval([y_train, v_average], "auc"))
72
- validation_data.append(obj_bagging.eval([y_train, v_most], "acc"))