pyqrack-complex128 2.30.3__tar.gz → 2.30.4__tar.gz

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.
Files changed (33) hide show
  1. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/Makefile +1 -1
  2. {pyqrack_complex128-2.30.3/pyqrack_complex128.egg-info → pyqrack_complex128-2.30.4}/PKG-INFO +1 -1
  3. pyqrack_complex128-2.30.4/pyqrack/qrack_bridge.py +297 -0
  4. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_system/qrack_system.py +84 -0
  5. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4/pyqrack_complex128.egg-info}/PKG-INFO +1 -1
  6. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/setup.py +1 -1
  7. pyqrack_complex128-2.30.3/pyqrack/qrack_bridge.py +0 -551
  8. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/LICENSE +0 -0
  9. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/MANIFEST.in +0 -0
  10. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/README.md +0 -0
  11. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyproject.toml +0 -0
  12. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/__init__.py +0 -0
  13. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/neuron_activation_fn.py +0 -0
  14. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/pauli.py +0 -0
  15. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_ace_backend.py +0 -0
  16. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_ace_mps_backend.py +0 -0
  17. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_circuit.py +0 -0
  18. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_near_clifford_qec_backend.py +0 -0
  19. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_neuron.py +0 -0
  20. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_neuron_torch_layer.py +0 -0
  21. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_simulator.py +0 -0
  22. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_stabilizer.py +0 -0
  23. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/qrack_system/__init__.py +0 -0
  24. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/quimb_circuit_type.py +0 -0
  25. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/stats/__init__.py +0 -0
  26. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/stats/load_quantized_data.py +0 -0
  27. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack/stats/quantize_by_range.py +0 -0
  28. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack_complex128.egg-info/SOURCES.txt +0 -0
  29. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack_complex128.egg-info/dependency_links.txt +0 -0
  30. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack_complex128.egg-info/not-zip-safe +0 -0
  31. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack_complex128.egg-info/requires.txt +0 -0
  32. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/pyqrack_complex128.egg-info/top_level.txt +0 -0
  33. {pyqrack_complex128-2.30.3 → pyqrack_complex128-2.30.4}/setup.cfg +0 -0
@@ -30,7 +30,7 @@ build-deps:
30
30
  rm -rf pyqrack/qrack_system/qrack_cl_precompile
31
31
  ifneq ($(OS),Windows_NT)
32
32
  ifeq ($(QRACK_PRESENT),)
33
- git clone https://github.com/unitaryfund/qrack.git; cd qrack; git checkout 98b474070d3b4ee373d8645ee413f26f4b81c2b4; cd ..
33
+ git clone https://github.com/unitaryfund/qrack.git; cd qrack; git checkout 2fda2a7cebcff4c6e0a2c500380a30cf0e11c6ae; cd ..
34
34
  endif
35
35
  mkdir -p qrack/build
36
36
  ifeq ($(UNAME_S),Linux)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-complex128
3
- Version: 2.30.3
3
+ Version: 2.30.4
4
4
  Summary: pyqrack - Pure Python vm6502q/qrack Wrapper
5
5
  Home-page: https://github.com/vm6502q/pyqrack
6
6
  Author: Daniel Strano
@@ -0,0 +1,297 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2026. All rights reserved.
2
+ #
3
+ # QrackBridge: bridged patching, backed by Qrack's native QBridge.
4
+ #
5
+ # By (Anthropic) Claude and Dan Strano
6
+ #
7
+ # The qubits are split into `patches` contiguous blocks (equal up to the remainder; the last
8
+ # qubit_count % patches blocks get one more), each simulated exactly by its own Qrack engine. Patches
9
+ # sit on a 1D chain (a ring with wrap=True and 3+ patches) and share "bond" qubits only with their
10
+ # nearest neighbours: the state is a matrix-product state whose sites are whole state-vector simulators.
11
+ # Gates within a patch run natively; gates between patches are teleported through fresh bond pairs and
12
+ # each cut is recompressed to at most 2^max_bonds Schmidt components (greedy, or Born-rule groups).
13
+ #
14
+ # Same API as the pure-Python reference implementation (pyqrack.QrackPyBridge), plus pauli_expectation().
15
+ # If the loaded Qrack library predates QBridge, pyqrack.QrackBridge is QrackPyBridge instead.
16
+ #
17
+ # Use of this source code is governed by an MIT-style license that can be
18
+ # found in the LICENSE file or at https://opensource.org/licenses/MIT.
19
+
20
+ import contextlib
21
+ import ctypes
22
+ import math
23
+ import os
24
+
25
+ import numpy as np
26
+
27
+ from .qrack_system import Qrack
28
+
29
+ _SQ = 1 / math.sqrt(2)
30
+ _X = [0, 1, 1, 0]
31
+ _Y = [0, -1j, 1j, 0]
32
+ _Z = [1, 0, 0, -1]
33
+ _H = [_SQ, _SQ, _SQ, -_SQ]
34
+ _S = [1, 0, 0, 1j]
35
+ _ADJS = [1, 0, 0, -1j]
36
+ _T = [1, 0, 0, complex(_SQ, _SQ)]
37
+ _ADJT = [1, 0, 0, complex(_SQ, -_SQ)]
38
+
39
+
40
+ def _mtrx_byref(m):
41
+ flat = []
42
+ for c in m:
43
+ c = complex(c)
44
+ flat += [c.real, c.imag]
45
+ return (ctypes.c_double * 8)(*flat)
46
+
47
+
48
+ def _ulonglong_byref(a):
49
+ return (ctypes.c_ulonglong * len(a))(*a)
50
+
51
+
52
+ class QrackBridge:
53
+ """Bridged patching on native Qrack patches (see module docstring).
54
+
55
+ Args:
56
+ qubit_count: number of logical qubits
57
+ max_bonds: bond qubits per cut (bond dimension 2^max_bonds)
58
+ seed: sampler seed (None: random)
59
+ truncation: "greedy" (keep the largest Schmidt values) or "born" (Born-rule group selection)
60
+ patches: number of patches (default 2: one cut, all-to-all coupling)
61
+ wrap: close the patch chain into a ring (3+ patches)
62
+ lazy_bonds: extra bond qubits a cut may buffer before a truncating sweep (0 = eager)
63
+ max_patch_qubits: optional cap on any patch's total width that also forces a sweep
64
+ is_*: engine layers for every patch, as for QrackSimulator
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ qubit_count,
70
+ max_bonds=6,
71
+ seed=None,
72
+ truncation="greedy",
73
+ patches=2,
74
+ wrap=False,
75
+ lazy_bonds=0,
76
+ max_patch_qubits=None,
77
+ _clone=None,
78
+ is_tensor_network=True,
79
+ is_schmidt_decompose=True,
80
+ is_schmidt_decompose_multi=False,
81
+ is_stabilizer_hybrid=False,
82
+ is_binary_decision_tree=False,
83
+ is_paged=True,
84
+ is_cpu_gpu_hybrid=True,
85
+ is_gpu=True,
86
+ ):
87
+ self.bid = None
88
+ if _clone is not None:
89
+ self.bid = Qrack.qrack_lib.init_qbridge_clone(_clone.bid)
90
+ for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation"):
91
+ setattr(self, k, getattr(_clone, k))
92
+ self._throw_if_error()
93
+ self._partition()
94
+ return
95
+ if truncation not in ("greedy", "born"):
96
+ raise ValueError("truncation must be 'greedy' or 'born'")
97
+ if not 1 <= patches <= qubit_count:
98
+ raise ValueError("need 1 <= patches <= qubit_count")
99
+ if lazy_bonds < 0:
100
+ raise ValueError("lazy_bonds must be >= 0")
101
+ self.n = qubit_count
102
+ self.P = patches
103
+ self.ring = bool(wrap) and patches >= 3
104
+ self.max_bonds = max_bonds
105
+ self.lazy_bonds = lazy_bonds
106
+ self.max_patch_qubits = max_patch_qubits
107
+ self.truncation = truncation
108
+ if seed is None:
109
+ seed = int.from_bytes(os.urandom(8), "little")
110
+ self.bid = Qrack.qrack_lib.init_qbridge(
111
+ qubit_count,
112
+ max_bonds,
113
+ patches,
114
+ bool(wrap),
115
+ truncation == "born",
116
+ lazy_bonds,
117
+ max_patch_qubits or 0,
118
+ seed & ((1 << 64) - 1),
119
+ is_tensor_network,
120
+ is_schmidt_decompose_multi,
121
+ is_schmidt_decompose,
122
+ is_stabilizer_hybrid,
123
+ is_binary_decision_tree,
124
+ is_paged,
125
+ is_cpu_gpu_hybrid,
126
+ is_gpu,
127
+ )
128
+ self._throw_if_error()
129
+ self._partition()
130
+
131
+ def _partition(self):
132
+ base, rem = divmod(self.n, self.P)
133
+ sizes = [base + (1 if p >= self.P - rem else 0) for p in range(self.P)]
134
+ self.start = [sum(sizes[:p]) for p in range(self.P)]
135
+ self.part = [list(range(self.start[p], self.start[p] + sizes[p])) for p in range(self.P)]
136
+ self.side = {q: (p, i) for p, qs in enumerate(self.part) for i, q in enumerate(qs)}
137
+
138
+ def __del__(self):
139
+ if getattr(self, "bid", None) is not None:
140
+ Qrack.qrack_lib.destroy_qbridge(self.bid)
141
+ self.bid = None
142
+
143
+ def _throw_if_error(self):
144
+ if Qrack.qrack_lib.get_qbridge_error(self.bid) != 0:
145
+ raise RuntimeError("QrackBridge C++ library raised exception.")
146
+
147
+ def clone(self):
148
+ return QrackBridge(None, _clone=self)
149
+
150
+ def num_qubits(self):
151
+ return self.n
152
+
153
+ # --- statistics ----------------------------------------------------------
154
+
155
+ @property
156
+ def fidelity_estimate(self):
157
+ return Qrack.qrack_lib.qbridge_get_fidelity_estimate(self.bid)
158
+
159
+ @property
160
+ def truncations(self):
161
+ return Qrack.qrack_lib.qbridge_get_truncations(self.bid)
162
+
163
+ @property
164
+ def flushes(self):
165
+ return Qrack.qrack_lib.qbridge_get_flushes(self.bid)
166
+
167
+ @property
168
+ def peak_bonds(self):
169
+ return Qrack.qrack_lib.qbridge_get_peak_bonds(self.bid)
170
+
171
+ @property
172
+ def bond(self):
173
+ """Live bond qubits per cut (cut c joins patch c to patch c + 1, mod P on a ring)."""
174
+ c = Qrack.qrack_lib.qbridge_get_cut_count(self.bid)
175
+ out = (ctypes.c_ulonglong * max(c, 1))()
176
+ Qrack.qrack_lib.qbridge_get_bonds(self.bid, out)
177
+ return [int(out[i]) for i in range(c)]
178
+
179
+ # --- single-qubit gates --------------------------------------------------
180
+
181
+ def mtrx(self, m, q):
182
+ Qrack.qrack_lib.qbridge_mtrx(self.bid, _mtrx_byref(m), q)
183
+ self._throw_if_error()
184
+
185
+ def u(self, q, th, ph, lm):
186
+ Qrack.qrack_lib.qbridge_u(self.bid, q, th, ph, lm)
187
+ self._throw_if_error()
188
+
189
+ def x(self, q):
190
+ self.mtrx(_X, q)
191
+
192
+ def y(self, q):
193
+ self.mtrx(_Y, q)
194
+
195
+ def z(self, q):
196
+ self.mtrx(_Z, q)
197
+
198
+ def h(self, q):
199
+ self.mtrx(_H, q)
200
+
201
+ def s(self, q):
202
+ self.mtrx(_S, q)
203
+
204
+ def adjs(self, q):
205
+ self.mtrx(_ADJS, q)
206
+
207
+ def t(self, q):
208
+ self.mtrx(_T, q)
209
+
210
+ def adjt(self, q):
211
+ self.mtrx(_ADJT, q)
212
+
213
+ # --- controlled gates, local or bridged ----------------------------------
214
+ # One control across patches; several controls only when all qubits share a patch.
215
+
216
+ def mcmtrx(self, c, m, t):
217
+ Qrack.qrack_lib.qbridge_mcmtrx(self.bid, len(c), _ulonglong_byref(c), _mtrx_byref(m), t)
218
+ self._throw_if_error()
219
+
220
+ def macmtrx(self, c, m, t):
221
+ Qrack.qrack_lib.qbridge_macmtrx(self.bid, len(c), _ulonglong_byref(c), _mtrx_byref(m), t)
222
+ self._throw_if_error()
223
+
224
+ def mcx(self, c, t): self.mcmtrx(c, _X, t)
225
+ def mcy(self, c, t): self.mcmtrx(c, _Y, t)
226
+ def mcz(self, c, t): self.mcmtrx(c, _Z, t)
227
+ def macx(self, c, t): self.macmtrx(c, _X, t)
228
+ def macy(self, c, t): self.macmtrx(c, _Y, t)
229
+ def macz(self, c, t): self.macmtrx(c, _Z, t)
230
+
231
+ def cx(self, a, b): self.mcx([a], b)
232
+ def cy(self, a, b): self.mcy([a], b)
233
+ def cz(self, a, b): self.mcz([a], b)
234
+
235
+ # --- two-qubit gates (ship-and-return across patches: 2 bonds per cut, one sweep) ----------
236
+
237
+ def swap(self, a, b):
238
+ Qrack.qrack_lib.qbridge_swap(self.bid, a, b)
239
+ self._throw_if_error()
240
+
241
+ def iswap(self, a, b):
242
+ Qrack.qrack_lib.qbridge_iswap(self.bid, a, b)
243
+ self._throw_if_error()
244
+
245
+ def adjiswap(self, a, b):
246
+ Qrack.qrack_lib.qbridge_adjiswap(self.bid, a, b)
247
+ self._throw_if_error()
248
+
249
+ def fsim(self, th, ph, a, b):
250
+ Qrack.qrack_lib.qbridge_fsim(self.bid, th, ph, a, b)
251
+ self._throw_if_error()
252
+
253
+ # --- truncation control --------------------------------------------------
254
+
255
+ @contextlib.contextmanager
256
+ def deferred(self):
257
+ """Truncate once, after the whole block, never inside it (e.g. around a transversal logical
258
+ gate); inside, bridged gates are recompressed only exactly. Nests."""
259
+ Qrack.qrack_lib.qbridge_begin_deferred(self.bid)
260
+ try:
261
+ yield self
262
+ finally:
263
+ Qrack.qrack_lib.qbridge_end_deferred(self.bid)
264
+ self._throw_if_error()
265
+
266
+ def flush(self):
267
+ """Truncate any buffered bonds back to max_bonds now (readout does this automatically)."""
268
+ Qrack.qrack_lib.qbridge_flush(self.bid)
269
+ self._throw_if_error()
270
+
271
+ # --- readout -----------------------------------------------------------------
272
+
273
+ def measure_shots(self, qubits, shots):
274
+ """Exact samples of the stored state; bit j of each result is qubits[j]."""
275
+ out = (ctypes.c_ulonglong * shots)()
276
+ Qrack.qrack_lib.qbridge_measure_shots(self.bid, len(qubits), _ulonglong_byref(qubits), shots, out)
277
+ self._throw_if_error()
278
+ return list(out)
279
+
280
+ def pauli_expectation(self, q, b):
281
+ """Exact <P> for the Pauli product with basis b[i] (pyqrack.Pauli) on qubit q[i]."""
282
+ if len(q) != len(b):
283
+ raise RuntimeError("pauli_expectation argument lengths do not match.")
284
+ result = Qrack.qrack_lib.qbridge_pauli_expectation(
285
+ self.bid, len(q), _ulonglong_byref(q), _ulonglong_byref([int(x) for x in b])
286
+ )
287
+ self._throw_if_error()
288
+ return result
289
+
290
+ def out_ket(self):
291
+ """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
292
+ real = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
293
+ buf = (real * (2 << self.n))()
294
+ Qrack.qrack_lib.qbridge_out_ket(self.bid, buf)
295
+ self._throw_if_error()
296
+ a = np.frombuffer(buf, dtype=np.float32 if Qrack.fppow < 6 else np.float64)
297
+ return a[0::2].astype(float) + 1j * a[1::2].astype(float)
@@ -1400,3 +1400,87 @@ class QrackSystem:
1400
1400
 
1401
1401
  self.qrack_lib.qcircuit_out_to_string.restype = None
1402
1402
  self.qrack_lib.qcircuit_out_to_string.argtypes = [c_ulonglong, c_char_p]
1403
+
1404
+ # QBridge (bridged patching); absent from Qrack libraries that predate it.
1405
+ self.has_qbridge = hasattr(self.qrack_lib, "init_qbridge")
1406
+ if self.has_qbridge:
1407
+ self.qrack_lib.init_qbridge.restype = c_ulonglong
1408
+ self.qrack_lib.init_qbridge.argtypes = [
1409
+ c_ulonglong, # qubits
1410
+ c_ulonglong, # max bonds
1411
+ c_ulonglong, # patches
1412
+ c_bool, # wrap
1413
+ c_bool, # Born-rule truncation
1414
+ c_ulonglong, # lazy bonds
1415
+ c_ulonglong, # max patch qubits (0 = none)
1416
+ c_ulonglong, # sampler seed
1417
+ c_bool, # tn
1418
+ c_bool, # md
1419
+ c_bool, # sd
1420
+ c_bool, # sh
1421
+ c_bool, # bdt
1422
+ c_bool, # pg
1423
+ c_bool, # hy
1424
+ c_bool, # oc
1425
+ ]
1426
+ self.qrack_lib.init_qbridge_clone.restype = c_ulonglong
1427
+ self.qrack_lib.init_qbridge_clone.argtypes = [c_ulonglong]
1428
+ self.qrack_lib.destroy_qbridge.restype = None
1429
+ self.qrack_lib.destroy_qbridge.argtypes = [c_ulonglong]
1430
+ self.qrack_lib.get_qbridge_error.restype = c_int
1431
+ self.qrack_lib.get_qbridge_error.argtypes = [c_ulonglong]
1432
+ self.qrack_lib.get_qbridge_qubit_count.restype = c_ulonglong
1433
+ self.qrack_lib.get_qbridge_qubit_count.argtypes = [c_ulonglong]
1434
+ self.qrack_lib.qbridge_mtrx.restype = None
1435
+ self.qrack_lib.qbridge_mtrx.argtypes = [c_ulonglong, POINTER(c_double), c_ulonglong]
1436
+ self.qrack_lib.qbridge_u.restype = None
1437
+ self.qrack_lib.qbridge_u.argtypes = [c_ulonglong, c_ulonglong, c_double, c_double, c_double]
1438
+ for fn in ("qbridge_mcmtrx", "qbridge_macmtrx"):
1439
+ getattr(self.qrack_lib, fn).restype = None
1440
+ getattr(self.qrack_lib, fn).argtypes = [
1441
+ c_ulonglong,
1442
+ c_ulonglong,
1443
+ POINTER(c_ulonglong),
1444
+ POINTER(c_double),
1445
+ c_ulonglong,
1446
+ ]
1447
+ for fn in ("qbridge_swap", "qbridge_iswap", "qbridge_adjiswap"):
1448
+ getattr(self.qrack_lib, fn).restype = None
1449
+ getattr(self.qrack_lib, fn).argtypes = [c_ulonglong, c_ulonglong, c_ulonglong]
1450
+ self.qrack_lib.qbridge_fsim.restype = None
1451
+ self.qrack_lib.qbridge_fsim.argtypes = [c_ulonglong, c_double, c_double, c_ulonglong, c_ulonglong]
1452
+ for fn in ("qbridge_begin_deferred", "qbridge_end_deferred", "qbridge_flush"):
1453
+ getattr(self.qrack_lib, fn).restype = None
1454
+ getattr(self.qrack_lib, fn).argtypes = [c_ulonglong]
1455
+ self.qrack_lib.qbridge_measure_shots.restype = None
1456
+ self.qrack_lib.qbridge_measure_shots.argtypes = [
1457
+ c_ulonglong,
1458
+ c_ulonglong,
1459
+ POINTER(c_ulonglong),
1460
+ c_ulonglong,
1461
+ POINTER(c_ulonglong),
1462
+ ]
1463
+ self.qrack_lib.qbridge_pauli_expectation.restype = c_double
1464
+ self.qrack_lib.qbridge_pauli_expectation.argtypes = [
1465
+ c_ulonglong,
1466
+ c_ulonglong,
1467
+ POINTER(c_ulonglong),
1468
+ POINTER(c_ulonglong),
1469
+ ]
1470
+ self.qrack_lib.qbridge_out_ket.restype = None
1471
+ self.qrack_lib.qbridge_out_ket.argtypes = [
1472
+ c_ulonglong,
1473
+ POINTER(c_float) if self.fppow < 6 else POINTER(c_double),
1474
+ ]
1475
+ self.qrack_lib.qbridge_get_fidelity_estimate.restype = c_double
1476
+ self.qrack_lib.qbridge_get_fidelity_estimate.argtypes = [c_ulonglong]
1477
+ for fn in (
1478
+ "qbridge_get_truncations",
1479
+ "qbridge_get_flushes",
1480
+ "qbridge_get_peak_bonds",
1481
+ "qbridge_get_cut_count",
1482
+ ):
1483
+ getattr(self.qrack_lib, fn).restype = c_ulonglong
1484
+ getattr(self.qrack_lib, fn).argtypes = [c_ulonglong]
1485
+ self.qrack_lib.qbridge_get_bonds.restype = None
1486
+ self.qrack_lib.qbridge_get_bonds.argtypes = [c_ulonglong, POINTER(c_ulonglong)]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrack-complex128
3
- Version: 2.30.3
3
+ Version: 2.30.4
4
4
  Summary: pyqrack - Pure Python vm6502q/qrack Wrapper
5
5
  Home-page: https://github.com/vm6502q/pyqrack
6
6
  Author: Daniel Strano
@@ -7,7 +7,7 @@ from setuptools import setup
7
7
  from setuptools.command.build_py import build_py
8
8
 
9
9
 
10
- VERSION = "2.30.3"
10
+ VERSION = "2.30.4"
11
11
 
12
12
  # Read long description from README.
13
13
  README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')
@@ -1,551 +0,0 @@
1
- # Bridged patching on QrackSimulator patches, recompressed through out_ket()/in_ket().
2
- #
3
- # By (Anthropic) Claude and Dan Strano
4
- #
5
- # Patches. `patches` (default 2) contiguous blocks of logical qubits, equal up to the rounding
6
- # remainder: every patch gets n // patches qubits and the LAST n % patches patches get one more (so
7
- # for 2 patches the first is rounded down, as before). Patches sit on a 1D chain; only direct
8
- # nearest-neighbour patches share bonds. With wrap=True and 3+ patches, the chain closes into a ring
9
- # (patch P-1 shares bonds with patch 0). With 2 patches there is one cut and all-to-all coupling.
10
- #
11
- # Representation. Each patch is ONE QrackSimulator holding its data qubits plus its live bond qubits:
12
- # "L" bonds on the cut to its left neighbour and "R" bonds on the cut to its right neighbour. Bond j
13
- # on the right of patch p is paired with bond j on the left of patch p+1. The represented state is
14
- # all patch kets contracted on every live bond pair with the unnormalized virtual Bell projection
15
- # sum_k <k|<k|. Reading patch p's ket as a tensor A_p[l, d, r] (left bonds, data, right bonds), the
16
- # state is the matrix-product contraction A_0 A_1 ... A_{P-1} (traced through the wrap cut on a ring).
17
- # Every in-patch gate is applied natively, once, to all bond branches at once.
18
- #
19
- # Cross-patch gates by gate teleportation along the chain (exact, gates only). Controlled-U from c
20
- # (patch pc) to t (patch pt), along the shorter way round on a ring:
21
- # control patch: CNOT c -> fresh bond on the first cut (copy the control)
22
- # each relay patch: H incoming bond ; CNOT incoming -> fresh bond on the next cut
23
- # target patch: H incoming bond ; controlled-U incoming -> t
24
- # Contracting on each bond pair enforces equality, so every relay bond carries a copy of c and the
25
- # result is exactly controlled-U(c -> t). A gate between patches k apart costs one bond on each of
26
- # the k cuts in between; nothing ever couples non-adjacent patches directly.
27
- # SWAP, iSWAP and iSWAP^dagger (any two-qubit gate) cross by "ship and return": a's state is
28
- # teleported along the chain onto a scratch qubit in b's patch (a SWAPped onto the outgoing bond,
29
- # identity-wire relays, Bell pairing at the destination), the gate is applied there natively, and the
30
- # scratch qubit is teleported back onto a. Exactly 2 bonds per cut crossed, one recompression per gate.
31
- #
32
- # Recompression after each bridged two-qubit gate (one MPS-style sweep over the touched segment):
33
- # - Gates on data qubits are unitary on each patch's (left, data) and (data, right) row spaces, so
34
- # they preserve left/right isometry. Only patches on a gate's path lose it.
35
- # - An orthogonality centre is tracked. QR-sweep left-to-right over the touched segment (and up to
36
- # the centre), then SVD-sweep right-to-left, keeping the largest singular values per cut (exact
37
- # when only zeros are dropped; above max_bonds, greedy or Born-rule group selection).
38
- # - On an open chain the environment is isometric at every SVD, so these are the true Schmidt values
39
- # of the state and each truncation is the optimal one for that cut, as with 2 patches.
40
- # - On a ring, the wrap cut is first recompressed between patches P-1 and 0 locally (QR of both
41
- # sides, SVD of the core), then the open sweep runs with the wrap bond treated as a physical leg.
42
- # Dropping only zeros is still exact. Truncating the wrap cut, and truncating inner cuts while wrap
43
- # bonds are live, is locally optimal but not globally optimal (a periodic MPS has no canonical
44
- # form), so fidelity_estimate is an estimate there and not the kept Schmidt weight.
45
- # Nothing larger than the patch kets and per-cut cores is ever formed: no density matrix.
46
- #
47
- # Lazy bond buffering (lazy_bonds > 0). Each ket round-trip costs O(patch ket), so instead of
48
- # recompressing after every bridged gate, bridged gates pile up as raw bond qubits until some cut
49
- # exceeds max_bonds + lazy_bonds (or some patch exceeds max_patch_qubits, if set); then ONE sweep
50
- # truncates the whole batch back to max_bonds. Truncating the accumulated state once is the optimal
51
- # truncation of that state, rather than a sequence of per-gate truncations. Heap cost: each buffered
52
- # bond qubit doubles the patches on that cut, so a patch can reach
53
- # n_patch + 2 * (max_bonds + lazy_bonds) + 3 qubits (one gate's 2 bonds and 1 scratch qubit in
54
- # flight). lazy_bonds=0 is the eager behaviour. Readout (measure_shots, out_ket) flushes first;
55
- # flush() does it on demand. On random circuits, lazy buffering mostly pays when consecutive gates
56
- # cross the same cut on the same pair (e.g. CZ then SWAP); otherwise a larger max_bonds at the same
57
- # heap is the better use of memory.
58
- #
59
- # Linear algebra: the sweeps use Gram matrices (one BLAS product and a small Hermitian eigensolve per
60
- # cut) instead of LAPACK QR/SVD on the whole patch tensor, and plain matmuls instead of einsum.
61
- #
62
- # Readout. Exact for the stored state: sequential conditional sampling, patch by patch, from the
63
- # exported kets, with shots grouped by prefix. On an open chain the canonical form (centre at patch 0)
64
- # makes each step a local marginal. On a ring, right environments carry the open wrap index, at a cost
65
- # of (chi * chi_wrap)^2 per environment.
66
- #
67
- # fidelity_estimate multiplies the kept Schmidt weight (greedy) or sum_g p_g^2 (born) per truncation.
68
-
69
- import contextlib
70
- import ctypes
71
- import math
72
-
73
- import numpy as np
74
- from .qrack_simulator import QrackSimulator
75
- from .qrack_system import Qrack
76
-
77
- # Ket I/O straight into/out of numpy buffers (PyQrack's out_ket()/in_ket() round-trip through Python
78
- # lists of complex, which dominated runtime). Same library calls, OutKet/InKet, without the copies.
79
- _REAL = np.float32 if Qrack.fppow < 6 else np.float64
80
- _CREAL = ctypes.c_float if Qrack.fppow < 6 else ctypes.c_double
81
-
82
-
83
- def _out_ket(sim):
84
- buf = np.empty(2 << sim.num_qubits(), dtype=_REAL)
85
- Qrack.qrack_lib.OutKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
86
- sim._throw_if_error()
87
- return buf.view(np.complex64 if _REAL is np.float32 else np.complex128).astype(complex)
88
-
89
-
90
- def _in_ket(sim, v):
91
- buf = np.ascontiguousarray(np.asarray(v, dtype=complex).view(np.float64).astype(_REAL))
92
- Qrack.qrack_lib.InKet(sim.sid, buf.ctypes.data_as(ctypes.POINTER(_CREAL)))
93
- sim._throw_if_error()
94
-
95
-
96
- def _bits(dim):
97
- """Bond qubits needed for bond dimension dim."""
98
- return (max(int(dim), 1) - 1).bit_length()
99
-
100
-
101
- def _gram_svd(m):
102
- """Left singular vectors and values of a short-wide m (rows <= 2^bonds) via its rows x rows Gram
103
- matrix: one BLAS product plus a tiny Hermitian eigensolve, instead of a LAPACK SVD of the whole
104
- patch. Double precision Gram keeps singular values to ~1e-8 relative, well under _TOL."""
105
- lam, u = np.linalg.eigh(m @ m.conj().T)
106
- order = np.argsort(lam)[::-1]
107
- return u[:, order], np.sqrt(np.clip(lam[order], 0, None))
108
-
109
-
110
- def _left_factor(a):
111
- """a = q @ r with q's columns orthonormal, through a's columns x columns Gram matrix; modes with
112
- zero weight are dropped (exactly), so the bond only ever shrinks here."""
113
- lam, v = np.linalg.eigh(a.conj().T @ a)
114
- keep = lam > (_TOL * _TOL) * lam[-1]
115
- keep[-1] = True # never an empty bond (lam[-1] > 0 for a live state)
116
- s = np.sqrt(lam[keep])
117
- v = v[:, keep]
118
- return (a @ v) / s[None, :], s[:, None] * v.conj().T
119
-
120
-
121
- _X = [0, 1, 1, 0]
122
- _Y = [0, -1j, 1j, 0]
123
- _Z = [1, 0, 0, -1]
124
- _TOL = 1e-6 # relative singular-value floor treated as exactly zero (Qrack is single precision)
125
-
126
-
127
- class QrackBridge:
128
- def __init__(self, qubit_count, max_bonds=6, seed=None, truncation="greedy", patches=2, wrap=False,
129
- lazy_bonds=0, max_patch_qubits=None, _clone=None):
130
- if _clone is not None:
131
- src = _clone
132
- for k in ("n", "P", "ring", "max_bonds", "lazy_bonds", "max_patch_qubits", "truncation",
133
- "fidelity_estimate", "truncations", "flushes",
134
- "peak_bonds", "center", "_wrap_touched"):
135
- setattr(self, k, getattr(src, k))
136
- self.part = [list(x) for x in src.part]
137
- self.start = list(src.start)
138
- self.side = dict(src.side)
139
- self.layout = [list(x) for x in src.layout]
140
- self.bond = list(src.bond)
141
- self.sim = [s.clone() for s in src.sim]
142
- self._touched = set(src._touched)
143
- self._deferring = 0
144
- self.rng = np.random.default_rng(int(src.rng.integers(1 << 62)))
145
- return
146
- if truncation not in ("greedy", "born"):
147
- raise ValueError("truncation must be 'greedy' or 'born'")
148
- if not 1 <= patches <= qubit_count:
149
- raise ValueError("need 1 <= patches <= qubit_count")
150
- self.n = qubit_count
151
- self.P = patches
152
- self.ring = bool(wrap) and patches >= 3
153
- base, rem = divmod(qubit_count, patches)
154
- sizes = [base + (1 if p >= patches - rem else 0) for p in range(patches)]
155
- self.start = [sum(sizes[:p]) for p in range(patches)]
156
- self.part = [list(range(self.start[p], self.start[p] + sizes[p])) for p in range(patches)]
157
- self.side = {q: (p, i) for p, qs in enumerate(self.part) for i, q in enumerate(qs)}
158
- # internal qubit order of each patch sim: ("d", i) data, ("L", j) / ("R", j) bond slots
159
- self.layout = [[("d", i) for i in range(len(qs))] for qs in self.part]
160
- self.sim = [QrackSimulator(len(qs)) for qs in self.part]
161
- self.bond = [0] * (patches if self.ring else patches - 1) # cut c joins patch c (R) to c+1 (L)
162
- self.max_bonds = max_bonds
163
- if lazy_bonds < 0:
164
- raise ValueError("lazy_bonds must be >= 0")
165
- self.lazy_bonds = lazy_bonds
166
- self.max_patch_qubits = max_patch_qubits
167
- self.flushes = 0
168
- self._deferring = 0
169
- self.truncation = truncation
170
- self.fidelity_estimate = 1.0
171
- self.truncations = 0
172
- self.peak_bonds = 0
173
- self.center = 0
174
- self._touched = set()
175
- self._wrap_touched = False
176
- self.rng = np.random.default_rng(seed)
177
-
178
- def clone(self):
179
- return QrackBridge(None, _clone=self)
180
-
181
- # --- chain geometry --------------------------------------------------------
182
-
183
- def _nd(self, p):
184
- return len(self.part[p])
185
-
186
- def _lcut(self, p):
187
- if p > 0:
188
- return p - 1
189
- return self.P - 1 if self.ring else None
190
-
191
- def _rcut(self, p):
192
- return p if (p < self.P - 1 or self.ring) else None
193
-
194
- def _dims(self, p):
195
- lc, rc = self._lcut(p), self._rcut(p)
196
- bl = 0 if lc is None else self.bond[lc]
197
- br = 0 if rc is None else self.bond[rc]
198
- return bl, br
199
-
200
- def _path(self, pa, pb):
201
- """Patches visited from pa to pb along the chain (shorter way round on a ring)."""
202
- step = 1 if pb > pa else -1
203
- if self.ring:
204
- right = (pb - pa) % self.P
205
- step = 1 if right <= self.P - right else -1
206
- path = [pa]
207
- while path[-1] != pb:
208
- path.append((path[-1] + step) % self.P)
209
- return path
210
-
211
- def _new_bond(self, here, there):
212
- """Fresh bond pair on the cut between adjacent patches here and there; returns (id here, id there)."""
213
- rightward = there == ((here + 1) % self.P if self.ring else here + 1)
214
- c = here if rightward else there
215
- j = self.bond[c]
216
- self.bond[c] += 1
217
- self.peak_bonds = max(self.peak_bonds, self.bond[c])
218
- if self.ring and c == self.P - 1:
219
- self._wrap_touched = True
220
- ids = {}
221
- for p, tag in ((c, ("R", j)), ((c + 1) % self.P, ("L", j))):
222
- qid = len(self.layout[p])
223
- self.sim[p].allocate_qubit(qid)
224
- self.layout[p].append(tag)
225
- ids[p] = qid
226
- return ids[here], ids[there]
227
-
228
- def _new_scratch(self, p):
229
- """Fresh |0> working qubit in patch p; it is returned to |0> before any recompression."""
230
- qid = len(self.layout[p])
231
- self.sim[p].allocate_qubit(qid)
232
- self.layout[p].append(("0", qid))
233
- return qid
234
-
235
- def _ship(self, path, src):
236
- """Teleport the state of qubit src (in patch path[0]) onto a fresh scratch qubit in patch
237
- path[-1], through one new bond per cut: src is SWAPped onto the outgoing bond (src left |0>),
238
- relays are identity wires (H in; CNOT in -> out), and the destination Bell-pairs its incoming
239
- bond with the scratch qubit (H in; CNOT in -> scratch). Returns the scratch qubit's id."""
240
- out, inc = self._new_bond(path[0], path[1])
241
- self.sim[path[0]].swap(src, out)
242
- for k in range(1, len(path) - 1):
243
- s = self.sim[path[k]]
244
- s.h(inc)
245
- out, nxt = self._new_bond(path[k], path[k + 1])
246
- s.mcx([inc], out)
247
- inc = nxt
248
- s = self.sim[path[-1]]
249
- z = self._new_scratch(path[-1])
250
- s.h(inc)
251
- s.mcx([inc], z)
252
- return z
253
-
254
- def _unship(self, path, z, dst):
255
- """Teleport scratch qubit z (in patch path[0]) back onto qubit dst (|0>, in patch path[-1])."""
256
- out, inc = self._new_bond(path[0], path[1])
257
- self.sim[path[0]].swap(z, out) # z back to |0>
258
- for k in range(1, len(path) - 1):
259
- s = self.sim[path[k]]
260
- s.h(inc)
261
- out, nxt = self._new_bond(path[k], path[k + 1])
262
- s.mcx([inc], out)
263
- inc = nxt
264
- s = self.sim[path[-1]]
265
- s.h(inc)
266
- s.mcx([inc], dst)
267
-
268
- def _loc(self, q):
269
- p, i = self.side[q]
270
- return self.sim[p], p, i
271
-
272
- # --- local gates ---------------------------------------------------------
273
-
274
- def u(self, q, th, ph, lm):
275
- s, _, i = self._loc(q)
276
- s.u(i, th, ph, lm)
277
-
278
- def x(self, q):
279
- s, _, i = self._loc(q)
280
- s.x(i)
281
-
282
- def h(self, q):
283
- s, _, i = self._loc(q)
284
- s.h(i)
285
-
286
- def s(self, q):
287
- s, _, i = self._loc(q)
288
- s.s(i)
289
-
290
- def adjs(self, q):
291
- s, _, i = self._loc(q)
292
- s.adjs(i)
293
-
294
- # --- controlled gates, local or bridged ----------------------------------
295
-
296
- def _controlled(self, c, t, mtrx, anti):
297
- sc, pc, ic = self._loc(c)
298
- st, pt, it = self._loc(t)
299
- if pc == pt:
300
- (sc.macmtrx if anti else sc.mcmtrx)([ic], mtrx, it)
301
- return
302
- path = self._path(pc, pt)
303
- out, inc = self._new_bond(path[0], path[1])
304
- (sc.macx if anti else sc.mcx)([ic], out)
305
- for k in range(1, len(path) - 1): # relay patches: pass the copy of c along
306
- s = self.sim[path[k]]
307
- s.h(inc)
308
- out, nxt = self._new_bond(path[k], path[k + 1])
309
- s.mcx([inc], out)
310
- inc = nxt
311
- st.h(inc)
312
- st.mcmtrx([inc], mtrx, it)
313
- self._touched.update(path)
314
- self._maybe_compress()
315
-
316
- def mcx(self, c, t): self._controlled(c[0], t, _X, False)
317
- def mcy(self, c, t): self._controlled(c[0], t, _Y, False)
318
- def mcz(self, c, t): self._controlled(c[0], t, _Z, False)
319
- def macx(self, c, t): self._controlled(c[0], t, _X, True)
320
- def macy(self, c, t): self._controlled(c[0], t, _Y, True)
321
- def macz(self, c, t): self._controlled(c[0], t, _Z, True)
322
-
323
- def cx(self, a, b): self.mcx([a], b)
324
- def cy(self, a, b): self.mcy([a], b)
325
- def cz(self, a, b): self.mcz([a], b)
326
-
327
- def _pair_gate(self, a, b, op):
328
- """Any two-qubit gate across patches: ship a's state into b's patch, apply the gate natively
329
- there, ship it back. Exactly two bonds per cut crossed (operator-Schmidt rank <= 4), and one
330
- recompression for the whole gate."""
331
- sa, pa, ia = self._loc(a)
332
- sb, pb, ib = self._loc(b)
333
- if pa == pb:
334
- getattr(sa, op)(ia, ib)
335
- return
336
- path = self._path(pa, pb)
337
- z = self._ship(path, ia)
338
- getattr(sb, op)(z, ib)
339
- self._unship(path[::-1], z, ia)
340
- self._touched.update(path)
341
- self._maybe_compress()
342
-
343
- def swap(self, a, b): self._pair_gate(a, b, "swap")
344
- def iswap(self, a, b): self._pair_gate(a, b, "iswap")
345
- def adjiswap(self, a, b): self._pair_gate(a, b, "adjiswap")
346
-
347
- # --- patch tensors through the kets --------------------------------------
348
-
349
- def _tensor(self, p):
350
- """Patch p's ket as A[l, d, r] (left bonds, data, right bonds), whatever its internal order."""
351
- lay = self.layout[p]
352
- k = len(lay)
353
- bl, br = self._dims(p)
354
- nd = self._nd(p)
355
- v = _out_ket(self.sim[p])
356
- order = ([("L", j) for j in reversed(range(bl))] + [("d", i) for i in reversed(range(nd))]
357
- + [("R", j) for j in reversed(range(br))])
358
- t = v.reshape([2] * k)
359
- if any(tag[0] == "0" for tag in lay): # scratch qubits are back in |0>: project them out
360
- t = t[tuple(0 if lay[k - 1 - x][0] == "0" else slice(None) for x in range(k))]
361
- lay = [tag for tag in lay if tag[0] != "0"]
362
- k = len(lay)
363
- pos = {tag: x for x, tag in enumerate(lay)}
364
- t = t.transpose([k - 1 - pos[tag] for tag in order])
365
- return t.reshape(1 << bl, 1 << nd, 1 << br)
366
-
367
- def _store(self, p, a):
368
- """Write A[l, d, r] back as a fresh patch sim: data low, then L bonds, then R bonds."""
369
- bl, br = self._dims(p)
370
- nd = self._nd(p)
371
- full = np.zeros((1 << bl, 1 << nd, 1 << br), dtype=complex)
372
- full[: a.shape[0], :, : a.shape[2]] = a
373
- v = full.transpose(2, 0, 1).reshape(-1)
374
- v = v / np.linalg.norm(v)
375
- self.layout[p] = [("d", i) for i in range(nd)] + [("L", j) for j in range(bl)] + [("R", j) for j in range(br)]
376
- self.sim[p] = QrackSimulator(nd + bl + br)
377
- _in_ket(self.sim[p], v)
378
-
379
- # --- recompression -------------------------------------------------------
380
-
381
- def _select(self, sv, exact_only):
382
- if sv[0] <= 0:
383
- return np.arange(1)
384
- live = int(np.sum(sv > _TOL * sv[0]))
385
- b_exact = _bits(live)
386
- b_new = b_exact if exact_only else min(b_exact, self.max_bonds)
387
- keep = min(live, 1 << b_new)
388
- if keep >= live:
389
- return np.arange(keep)
390
- w = sv[:live] ** 2
391
- self.truncations += 1
392
- if self.truncation == "greedy":
393
- self.fidelity_estimate *= float(np.sum(w[:keep]) / np.sum(w))
394
- return np.arange(keep)
395
- groups = [np.arange(i, min(i + keep, live)) for i in range(0, live, keep)]
396
- pg = np.array([np.sum(w[g]) for g in groups]) / np.sum(w)
397
- self.fidelity_estimate *= float(np.sum(pg ** 2))
398
- return groups[int(self.rng.choice(len(groups), p=pg))]
399
-
400
- def _sweep(self, lo, hi, exact_only):
401
- """Canonicalize and truncate inner cuts over [lo, hi] (plus up to the centre); centre ends at lo."""
402
- start, end = min(lo, self.center), max(hi, self.center)
403
- if start == end:
404
- self.center = lo
405
- return
406
- T = {k: self._tensor(k) for k in range(start, end + 1)}
407
- for k in range(start, end): # left-isometric up to the centre at `end`
408
- l, d, r = T[k].shape
409
- q, rr = _left_factor(T[k].reshape(l * d, r)) # exact; also drops zero modes
410
- T[k] = q.reshape(l, d, -1)
411
- nl, nd_, nr = T[k + 1].shape
412
- T[k + 1] = (rr @ T[k + 1].reshape(nl, nd_ * nr)).reshape(-1, nd_, nr)
413
- self.bond[k] = _bits(q.shape[1])
414
- for k in range(end, lo, -1): # right-isometric back down to `lo`
415
- l, d, r = T[k].shape
416
- m = T[k].reshape(l, d * r)
417
- u, sv = _gram_svd(m)
418
- idx = self._select(sv, exact_only)
419
- us = u[:, idx]
420
- T[k] = ((us.conj().T @ m) / sv[idx][:, None]).reshape(len(idx), d, r)
421
- pl, pd, pr = T[k - 1].shape
422
- T[k - 1] = (T[k - 1].reshape(pl * pd, pr) @ (us * sv[idx][None, :])).reshape(pl, pd, -1)
423
- self.bond[k - 1] = _bits(len(idx))
424
- for k, a in T.items():
425
- self._store(k, a)
426
- self.center = lo
427
-
428
- def _compress_wrap(self, exact_only):
429
- """Ring only: recompress the wrap cut (P-1 | 0) locally, QR both sides and SVD of the core."""
430
- P = self.P
431
- a, b = self._tensor(P - 1), self._tensor(0)
432
- l, d, w = a.shape
433
- _, d0, r0 = b.shape
434
- qa, ra = np.linalg.qr(a.reshape(l * d, w))
435
- qb, rb = np.linalg.qr(b.reshape(w, d0 * r0).T)
436
- u, sv, vh = np.linalg.svd(ra @ rb.T)
437
- idx = self._select(sv, exact_only)
438
- self.bond[P - 1] = _bits(len(idx))
439
- self._store(P - 1, ((qa @ u[:, idx]) * sv[idx][None, :]).reshape(l, d, -1))
440
- self._store(0, (qb @ vh[idx, :].T).T.reshape(-1, d0, r0))
441
-
442
- def _over_budget(self):
443
- """Lazy mode: has any cut, or any patch's total width, outgrown its buffer?"""
444
- if any(b > self.max_bonds + self.lazy_bonds for b in self.bond):
445
- return True
446
- if self.max_patch_qubits is not None:
447
- return any(len(lay) > self.max_patch_qubits for lay in self.layout)
448
- return False
449
-
450
- def _maybe_compress(self):
451
- if self._deferring:
452
- # Inside deferred(): keep only the exact rank (drop zero singular values); never truncate.
453
- if not self.lazy_bonds or self._over_budget():
454
- self._compress(exact_only=True)
455
- return
456
- if not self.lazy_bonds:
457
- self._compress() # eager: one sweep per bridged gate
458
- return
459
- # Lazy: let bridged gates pile up as raw bond qubits and truncate the whole batch in one sweep,
460
- # only when a cut exceeds max_bonds + lazy_bonds (or a patch exceeds max_patch_qubits).
461
- if self._over_budget():
462
- self._compress()
463
-
464
- @contextlib.contextmanager
465
- def deferred(self):
466
- """Truncate once, after the whole block, never inside it:
467
-
468
- with sim.deferred():
469
- for i in range(9):
470
- sim.mcx([b[i]], a[i]) # e.g. a transversal logical CNOT
471
-
472
- Inside, bridged gates are recompressed only exactly, so bonds carry the full transient
473
- entanglement of the block; on exit one sweep truncates to max_bonds. Use it around any
474
- multi-gate operation whose intermediate states are more entangled than its result
475
- (transversal logical gates, decode/encode, gate decompositions). Heap grows with the
476
- transient rank inside the block. Nests; only the outermost exit truncates."""
477
- self._deferring += 1
478
- try:
479
- yield self
480
- finally:
481
- self._deferring -= 1
482
- if not self._deferring:
483
- self._maybe_compress()
484
-
485
- def flush(self):
486
- """Truncate any buffered bonds back to max_bonds now (readout does this automatically)."""
487
- self._compress()
488
-
489
- def _compress(self, exact_only=False):
490
- if not self._touched:
491
- return
492
- if self._wrap_touched:
493
- self._compress_wrap(exact_only)
494
- self._touched.update((0, self.P - 1))
495
- self._sweep(min(self._touched), max(self._touched), exact_only)
496
- if not exact_only:
497
- self.flushes += 1
498
- self._touched.clear()
499
- self._wrap_touched = False
500
-
501
- # --- readout -----------------------------------------------------------------
502
-
503
- def measure_shots(self, qubits, shots):
504
- self._compress()
505
- self._sweep(0, 0, exact_only=True) # centre at patch 0: patches 1.. right-isometric
506
- T = [self._tensor(p) for p in range(self.P)]
507
- R = None
508
- if self.ring: # right environments with the wrap index open
509
- cw = T[0].shape[0]
510
- eye = np.eye(cw)
511
- R = [None] * (self.P + 1)
512
- R[self.P] = np.einsum("rw,sv->rwsv", eye, eye)
513
- for k in range(self.P - 1, 0, -1):
514
- R[k] = np.einsum("ldr,rwsv,mds->lwmv", T[k], R[k + 1], T[k].conj(), optimize=True)
515
- groups = [(eye, shots, 0)]
516
- else:
517
- groups = [(np.ones((1, 1)), shots, 0)]
518
- for k in range(self.P):
519
- nxt = []
520
- for X, cnt, bits in groups:
521
- M = np.einsum("wl,ldr->wdr", X, T[k])
522
- if R is None:
523
- p = np.sum(np.abs(M) ** 2, axis=(0, 2))
524
- else:
525
- p = np.einsum("wdr,rwsv,vds->d", M, R[k + 1], M.conj(), optimize=True).real
526
- p = np.clip(p, 0, None)
527
- p /= p.sum()
528
- for d, c in enumerate(self.rng.multinomial(cnt, p)):
529
- if c:
530
- Y = M[:, d, :]
531
- nxt.append((Y / np.linalg.norm(Y), int(c), bits | (d << self.start[k])))
532
- groups = nxt
533
- out = []
534
- for _, c, full in groups:
535
- out += [sum(((full >> q) & 1) << j for j, q in enumerate(qubits))] * c
536
- self.rng.shuffle(out)
537
- return out
538
-
539
- def out_ket(self):
540
- """Dense contracted state (2^n), little-endian over logical qubits; for testing."""
541
- self._compress() # same (flushed) state that measure_shots samples
542
- C = None
543
- for p in range(self.P):
544
- A = self._tensor(p)
545
- if C is None:
546
- C = np.einsum("wl,ldr->wdr", np.eye(A.shape[0]), A)
547
- else:
548
- w, D, _ = C.shape
549
- C = np.einsum("wDr,rdq->wdDq", C, A).reshape(w, -1, A.shape[2])
550
- v = np.einsum("wDw->D", C)
551
- return v / np.linalg.norm(v)