pyqrack-cpu-complex128 1.58.0__py3-none-win_amd64.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 pyqrack-cpu-complex128 might be problematic. Click here for more details.

@@ -0,0 +1,4430 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2025. All rights reserved.
2
+ #
3
+ # Use of this source code is governed by an MIT-style license that can be
4
+ # found in the LICENSE file or at https://opensource.org/licenses/MIT.
5
+
6
+ import copy
7
+ import ctypes
8
+ import math
9
+ import os
10
+ import re
11
+ from .qrack_system import Qrack
12
+ from .pauli import Pauli
13
+
14
+ _IS_QISKIT_AVAILABLE = True
15
+ try:
16
+ from qiskit.circuit.quantumcircuit import QuantumCircuit
17
+ from qiskit.compiler import transpile
18
+ from qiskit.quantum_info.operators.symplectic.clifford import Clifford
19
+ except ImportError:
20
+ _IS_QISKIT_AVAILABLE = False
21
+
22
+ try:
23
+ from qiskit import qasm3
24
+ except ImportError:
25
+ pass
26
+
27
+ _IS_NUMPY_AVAILABLE = True
28
+ try:
29
+ import numpy as np
30
+ except:
31
+ _IS_NUMPY_AVAILABLE = False
32
+
33
+
34
+ class QrackSimulator:
35
+ """Interface for all the Qrack functionality.
36
+
37
+ Attributes:
38
+ sid(int): Corresponding simulator id.
39
+ """
40
+
41
+ def _get_error(self):
42
+ return Qrack.qrack_lib.get_error(self.sid)
43
+
44
+ def _throw_if_error(self):
45
+ if self._get_error() != 0:
46
+ raise RuntimeError("QrackSimulator C++ library raised exception.")
47
+
48
+ def __init__(
49
+ self,
50
+ qubitCount=-1,
51
+ cloneSid=-1,
52
+ isTensorNetwork=True,
53
+ isSchmidtDecomposeMulti=False,
54
+ isSchmidtDecompose=True,
55
+ isStabilizerHybrid=False,
56
+ isBinaryDecisionTree=False,
57
+ isPaged=True,
58
+ isCpuGpuHybrid=True,
59
+ isOpenCL=True,
60
+ isHostPointer=(
61
+ True if os.environ.get("PYQRACK_HOST_POINTER_DEFAULT_ON") else False
62
+ ),
63
+ noise=0,
64
+ pyzxCircuit=None,
65
+ qiskitCircuit=None,
66
+ ):
67
+ self.sid = None
68
+
69
+ if pyzxCircuit is not None:
70
+ qubitCount = pyzxCircuit.qubits
71
+ elif qiskitCircuit is not None and qubitCount < 0:
72
+ raise RuntimeError(
73
+ "Must specify qubitCount with qiskitCircuit parameter in QrackSimulator constructor!"
74
+ )
75
+
76
+ if qubitCount > -1 and cloneSid > -1:
77
+ raise RuntimeError(
78
+ "Cannot clone a QrackSimulator and specify its qubit length at the same time, in QrackSimulator constructor!"
79
+ )
80
+
81
+ self.is_tensor_network = isTensorNetwork
82
+ self.is_pure_stabilizer = False
83
+
84
+ if cloneSid > -1:
85
+ self.sid = Qrack.qrack_lib.init_clone(cloneSid)
86
+ else:
87
+ if qubitCount < 0:
88
+ qubitCount = 0
89
+
90
+ self.sid = Qrack.qrack_lib.init_count_type(
91
+ qubitCount,
92
+ isTensorNetwork,
93
+ isSchmidtDecomposeMulti,
94
+ isSchmidtDecompose,
95
+ isStabilizerHybrid,
96
+ isBinaryDecisionTree,
97
+ isPaged,
98
+ (noise > 0),
99
+ isCpuGpuHybrid,
100
+ isOpenCL,
101
+ isHostPointer,
102
+ )
103
+
104
+ self._throw_if_error()
105
+
106
+ if noise > 0:
107
+ self.set_noise_parameter(noise)
108
+
109
+ if pyzxCircuit is not None:
110
+ self.run_pyzx_gates(pyzxCircuit.gates)
111
+ elif qiskitCircuit is not None:
112
+ self.run_qiskit_circuit(qiskitCircuit)
113
+
114
+ def __del__(self):
115
+ if self.sid is not None:
116
+ Qrack.qrack_lib.destroy(self.sid)
117
+ self.sid = None
118
+
119
+ def _int_byref(self, a):
120
+ return (ctypes.c_int * len(a))(*a)
121
+
122
+ def _ulonglong_byref(self, a):
123
+ return (ctypes.c_ulonglong * len(a))(*a)
124
+
125
+ def _longlong_byref(self, a):
126
+ return (ctypes.c_longlong * len(a))(*a)
127
+
128
+ def _double_byref(self, a):
129
+ return (ctypes.c_double * len(a))(*a)
130
+
131
+ def _complex_byref(self, a):
132
+ t = [(c.real, c.imag) for c in a]
133
+ return self._double_byref([float(item) for sublist in t for item in sublist])
134
+
135
+ def _real1_byref(self, a):
136
+ # This needs to be c_double, if PyQrack is built with fp64.
137
+ if Qrack.fppow < 6:
138
+ return (ctypes.c_float * len(a))(*a)
139
+ return (ctypes.c_double * len(a))(*a)
140
+
141
+ def _bool_byref(self, a):
142
+ return (ctypes.c_bool * len(a))(*a)
143
+
144
+ def _qrack_complex_byref(self, a):
145
+ t = [(c.real, c.imag) for c in a]
146
+ return self._real1_byref([float(item) for sublist in t for item in sublist])
147
+
148
+ def _to_ubyte(self, nv, v):
149
+ c = math.floor((nv - 1) / 8) + 1
150
+ b = (ctypes.c_ubyte * (c * (1 << nv)))()
151
+ n = 0
152
+ for u in v:
153
+ for _ in range(c):
154
+ b[n] = u & 0xFF
155
+ u >>= 8
156
+ n += 1
157
+
158
+ return b
159
+
160
+ def _to_ulonglong(self, m, v):
161
+ b = (ctypes.c_ulonglong * (m * len(v)))()
162
+ n = 0
163
+ for u in v:
164
+ for _ in range(m):
165
+ b[n] = u & 0xFFFFFFFFFFFFFFFF
166
+ u >>= 64
167
+ n += 1
168
+
169
+ return b
170
+
171
+ # See https://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list#answer-30426000
172
+ def _pairwise(self, it):
173
+ it = iter(it)
174
+ while True:
175
+ try:
176
+ yield next(it), next(it)
177
+ except StopIteration:
178
+ # no more elements in the iterator
179
+ return
180
+
181
+ # non-quantum
182
+ def seed(self, s):
183
+ Qrack.qrack_lib.seed(self.sid, s)
184
+ self._throw_if_error()
185
+
186
+ def set_concurrency(self, p):
187
+ """Set the CPU parallel thread count"""
188
+ Qrack.qrack_lib.set_concurrency(self.sid, p)
189
+ self._throw_if_error()
190
+
191
+ def set_device(self, d):
192
+ """Set the GPU device ID"""
193
+ Qrack.qrack_lib.set_device(self.sid, d)
194
+ self._throw_if_error()
195
+
196
+ def set_device_list(self, d):
197
+ """Set the GPU device ID"""
198
+ Qrack.qrack_lib.set_device_list(self.sid, len(d), self._longlong_byref(d))
199
+ self._throw_if_error()
200
+
201
+ def clone(self):
202
+ return QrackSimulator(cloneSid=self.sid)
203
+
204
+ # standard gates
205
+
206
+ ## single-qubits gates
207
+ def x(self, q):
208
+ """Applies X gate.
209
+
210
+ Applies the Pauli “X” operator to the qubit at position “q.”
211
+ The Pauli “X” operator is equivalent to a logical “NOT.”
212
+
213
+ Args:
214
+ q: the qubit number on which the gate is applied to.
215
+
216
+ Raises:
217
+ RuntimeError: QrackSimulator raised an exception.
218
+ """
219
+ Qrack.qrack_lib.X(self.sid, q)
220
+ self._throw_if_error()
221
+
222
+ def y(self, q):
223
+ """Applies Y gate.
224
+
225
+ Applies the Pauli “Y” operator to the qubit at “q.”
226
+ The Pauli “Y” operator is equivalent to a logical “NOT" with
227
+ permutation phase.
228
+
229
+ Args:
230
+ q: the qubit number on which the gate is applied to.
231
+
232
+ Raises:
233
+ RuntimeError: QrackSimulator raised an exception.
234
+ """
235
+ Qrack.qrack_lib.Y(self.sid, q)
236
+ self._throw_if_error()
237
+
238
+ def z(self, q):
239
+ """Applies Z gate.
240
+
241
+ Applies the Pauli “Z” operator to the qubit at “q.”
242
+ The Pauli “Z” operator flips the phase of `|1>`
243
+
244
+ Args:
245
+ q: the qubit number on which the gate is applied to.
246
+
247
+ Raises:
248
+ RuntimeError: QrackSimulator raised an exception.
249
+ """
250
+ Qrack.qrack_lib.Z(self.sid, q)
251
+ self._throw_if_error()
252
+
253
+ def h(self, q):
254
+ """Applies H gate.
255
+
256
+ Applies the Hadarmard operator to the qubit at “q.”
257
+
258
+ Args:
259
+ q: the qubit number on which the gate is applied to.
260
+
261
+ Raises:
262
+ RuntimeError: QrackSimulator raised an exception.
263
+ """
264
+ Qrack.qrack_lib.H(self.sid, q)
265
+ self._throw_if_error()
266
+
267
+ def s(self, q):
268
+ """Applies S gate.
269
+
270
+ Applies the 1/4 phase rotation to the qubit at “q.”
271
+
272
+ Args:
273
+ q: the qubit number on which the gate is applied to.
274
+
275
+ Raises:
276
+ RuntimeError: QrackSimulator raised an exception.
277
+ """
278
+ Qrack.qrack_lib.S(self.sid, q)
279
+ self._throw_if_error()
280
+
281
+ def t(self, q):
282
+ """Applies T gate.
283
+
284
+ Applies the 1/8 phase rotation to the qubit at “q.”
285
+
286
+ Args:
287
+ q: the qubit number on which the gate is applied to.
288
+
289
+ Raises:
290
+ RuntimeError: QrackSimulator raised an exception.
291
+ """
292
+ Qrack.qrack_lib.T(self.sid, q)
293
+ self._throw_if_error()
294
+
295
+ def adjs(self, q):
296
+ """Adjoint of S gate
297
+
298
+ Applies the gate equivalent to the inverse of S gate.
299
+
300
+ Args:
301
+ q: the qubit number on which the gate is applied to.
302
+
303
+ Raises:
304
+ RuntimeError: QrackSimulator raised an exception.
305
+ """
306
+ Qrack.qrack_lib.AdjS(self.sid, q)
307
+ self._throw_if_error()
308
+
309
+ def adjt(self, q):
310
+ """Adjoint of T gate
311
+
312
+ Applies the gate equivalent to the inverse of T gate.
313
+
314
+ Args:
315
+ q: the qubit number on which the gate is applied to.
316
+
317
+ Raises:
318
+ RuntimeError: QrackSimulator raised an exception.
319
+ """
320
+ Qrack.qrack_lib.AdjT(self.sid, q)
321
+ self._throw_if_error()
322
+
323
+ def u(self, q, th, ph, la):
324
+ """General unitary gate.
325
+
326
+ Applies a gate guaranteed to be unitary.
327
+ Spans all possible single bit unitary gates.
328
+
329
+ `U(theta, phi, lambda) = RZ(phi + pi/2)RX(theta)RZ(lambda - pi/2)`
330
+
331
+ Args:
332
+ q: the qubit number on which the gate is applied to.
333
+ th: theta
334
+ ph: phi
335
+ la: lambda
336
+
337
+ Raises:
338
+ RuntimeError: QrackSimulator raised an exception.
339
+ """
340
+ Qrack.qrack_lib.U(
341
+ self.sid, q, ctypes.c_double(th), ctypes.c_double(ph), ctypes.c_double(la)
342
+ )
343
+ self._throw_if_error()
344
+
345
+ def mtrx(self, m, q):
346
+ """Operation from matrix.
347
+
348
+ Applies arbitrary operation defined by the given matrix.
349
+
350
+ Args:
351
+ m: row-major complex list representing the operator.
352
+ q: the qubit number on which the gate is applied to.
353
+
354
+ Raises:
355
+ ValueError: 2x2 matrix 'm' in QrackSimulator.mtrx() must contain at least 4 elements.
356
+ RuntimeError: QrackSimulator raised an exception.
357
+ """
358
+ if len(m) < 4:
359
+ raise ValueError(
360
+ "2x2 matrix 'm' in QrackSimulator.mtrx() must contain at least 4 elements."
361
+ )
362
+ Qrack.qrack_lib.Mtrx(self.sid, self._complex_byref(m), q)
363
+ self._throw_if_error()
364
+
365
+ def r(self, b, ph, q):
366
+ """Rotation gate.
367
+
368
+ Rotate the qubit along the given pauli basis by the given angle.
369
+
370
+
371
+ Args:
372
+ b: Pauli basis
373
+ ph: rotation angle
374
+ q: the qubit number on which the gate is applied to
375
+
376
+ Raises:
377
+ RuntimeError: QrackSimulator raised an exception.
378
+ """
379
+ Qrack.qrack_lib.R(self.sid, ctypes.c_ulonglong(b), ctypes.c_double(ph), q)
380
+ self._throw_if_error()
381
+
382
+ def exp(self, b, ph, q):
383
+ """Arbitrary exponentiation
384
+
385
+ `exp(b, theta) = e^{i*theta*[b_0 . b_1 ...]}`
386
+ where `.` is the tensor product.
387
+
388
+
389
+ Args:
390
+ b: Pauli basis
391
+ ph: coefficient of exponentiation
392
+ q: the qubit number on which the gate is applied to
393
+
394
+ Raises:
395
+ RuntimeError: QrackSimulator raised an exception.
396
+ """
397
+ if len(b) != len(q):
398
+ raise RuntimeError("Lengths of list parameters are mismatched.")
399
+ Qrack.qrack_lib.Exp(
400
+ self.sid,
401
+ len(b),
402
+ self._ulonglong_byref(b),
403
+ ctypes.c_double(ph),
404
+ self._ulonglong_byref(q),
405
+ )
406
+ self._throw_if_error()
407
+
408
+ ## multi-qubit gates
409
+ def mcx(self, c, q):
410
+ """Multi-controlled X gate
411
+
412
+ If all controlled qubits are `|1>` then the target qubit is flipped.
413
+
414
+ Args:
415
+ c: list of controlled qubits.
416
+ q: target qubit.
417
+
418
+ Raises:
419
+ RuntimeError: QrackSimulator raised an exception.
420
+ """
421
+ Qrack.qrack_lib.MCX(self.sid, len(c), self._ulonglong_byref(c), q)
422
+ self._throw_if_error()
423
+
424
+ def mcy(self, c, q):
425
+ """Multi-controlled Y gate
426
+
427
+ If all controlled qubits are `|1>` then the Pauli "Y" gate is applied to
428
+ the target qubit.
429
+
430
+ Args:
431
+ c: list of controlled qubits.
432
+ q: target qubit.
433
+
434
+ Raises:
435
+ RuntimeError: QrackSimulator raised an exception.
436
+ """
437
+ Qrack.qrack_lib.MCY(self.sid, len(c), self._ulonglong_byref(c), q)
438
+ self._throw_if_error()
439
+
440
+ def mcz(self, c, q):
441
+ """Multi-controlled Z gate
442
+
443
+ If all controlled qubits are `|1>` then the Pauli "Z" gate is applied to
444
+ the target qubit.
445
+
446
+ Args:
447
+ c: list of controlled qubits.
448
+ q: target qubit.
449
+
450
+ Raises:
451
+ RuntimeError: QrackSimulator raised an exception.
452
+ """
453
+ Qrack.qrack_lib.MCZ(self.sid, len(c), self._ulonglong_byref(c), q)
454
+ self._throw_if_error()
455
+
456
+ def mch(self, c, q):
457
+ """Multi-controlled H gate
458
+
459
+ If all controlled qubits are `|1>` then the Hadarmard gate is applied to
460
+ the target qubit.
461
+
462
+ Args:
463
+ c: list of controlled qubits.
464
+ q: target qubit.
465
+
466
+ Raises:
467
+ RuntimeError: QrackSimulator raised an exception.
468
+ """
469
+ Qrack.qrack_lib.MCH(self.sid, len(c), self._ulonglong_byref(c), q)
470
+ self._throw_if_error()
471
+
472
+ def mcs(self, c, q):
473
+ """Multi-controlled S gate
474
+
475
+ If all controlled qubits are `|1>` then the "S" gate is applied to
476
+ the target qubit.
477
+
478
+ Args:
479
+ c: list of controlled qubits.
480
+ q: target qubit.
481
+
482
+ Raises:
483
+ RuntimeError: QrackSimulator raised an exception.
484
+ """
485
+ Qrack.qrack_lib.MCS(self.sid, len(c), self._ulonglong_byref(c), q)
486
+ self._throw_if_error()
487
+
488
+ def mct(self, c, q):
489
+ """Multi-controlled T gate
490
+
491
+ If all controlled qubits are `|1>` then the "T" gate is applied to
492
+ the target qubit.
493
+
494
+ Args:
495
+ c: list of controlled qubits.
496
+ q: target qubit.
497
+
498
+ Raises:
499
+ RuntimeError: QrackSimulator raised an exception.
500
+ """
501
+ Qrack.qrack_lib.MCT(self.sid, len(c), self._ulonglong_byref(c), q)
502
+ self._throw_if_error()
503
+
504
+ def mcadjs(self, c, q):
505
+ """Multi-controlled adjs gate
506
+
507
+ If all controlled qubits are `|1>` then the adjs gate is applied to
508
+ the target qubit.
509
+
510
+ Args:
511
+ c: list of controlled qubits.
512
+ q: target qubit.
513
+
514
+ Raises:
515
+ RuntimeError: QrackSimulator raised an exception.
516
+ """
517
+ Qrack.qrack_lib.MCAdjS(self.sid, len(c), self._ulonglong_byref(c), q)
518
+ self._throw_if_error()
519
+
520
+ def mcadjt(self, c, q):
521
+ """Multi-controlled adjt gate
522
+
523
+ If all controlled qubits are `|1>` then the adjt gate is applied to
524
+ the target qubit.
525
+
526
+ Args:
527
+ c: list of controlled qubits.
528
+ q: target qubit.
529
+
530
+ Raises:
531
+ RuntimeError: QrackSimulator raised an exception.
532
+ """
533
+ Qrack.qrack_lib.MCAdjT(self.sid, len(c), self._ulonglong_byref(c), q)
534
+ self._throw_if_error()
535
+
536
+ def mcu(self, c, q, th, ph, la):
537
+ """Multi-controlled arbitraty unitary
538
+
539
+ If all controlled qubits are `|1>` then the unitary gate described by
540
+ parameters is applied to the target qubit.
541
+
542
+ Args:
543
+ c: list of controlled qubits.
544
+ q: target qubit.
545
+ th: theta
546
+ ph: phi
547
+ la: lambda
548
+
549
+ Raises:
550
+ RuntimeError: QrackSimulator raised an exception.
551
+ """
552
+ Qrack.qrack_lib.MCU(
553
+ self.sid,
554
+ len(c),
555
+ self._ulonglong_byref(c),
556
+ q,
557
+ ctypes.c_double(th),
558
+ ctypes.c_double(ph),
559
+ ctypes.c_double(la),
560
+ )
561
+ self._throw_if_error()
562
+
563
+ def mcmtrx(self, c, m, q):
564
+ """Multi-controlled arbitrary operator
565
+
566
+ If all controlled qubits are `|1>` then the arbitrary operation by
567
+ parameters is applied to the target qubit.
568
+
569
+ Args:
570
+ c: list of controlled qubits
571
+ m: row-major complex list representing the operator.
572
+ q: target qubit
573
+
574
+ Raises:
575
+ ValueError: 2x2 matrix 'm' in QrackSimulator.mcmtrx() must contain at least 4 elements.
576
+ RuntimeError: QrackSimulator raised an exception.
577
+ """
578
+ if len(m) < 4:
579
+ raise ValueError(
580
+ "2x2 matrix 'm' in QrackSimulator.mcmtrx() must contain at least 4 elements."
581
+ )
582
+ Qrack.qrack_lib.MCMtrx(
583
+ self.sid, len(c), self._ulonglong_byref(c), self._complex_byref(m), q
584
+ )
585
+ self._throw_if_error()
586
+
587
+ def macx(self, c, q):
588
+ """Anti multi-controlled X gate
589
+
590
+ If all controlled qubits are `|0>` then the target qubit is flipped.
591
+
592
+ Args:
593
+ c: list of controlled qubits.
594
+ q: target qubit.
595
+
596
+ Raises:
597
+ RuntimeError: QrackSimulator raised an exception.
598
+ """
599
+ Qrack.qrack_lib.MACX(self.sid, len(c), self._ulonglong_byref(c), q)
600
+ self._throw_if_error()
601
+
602
+ def macy(self, c, q):
603
+ """Anti multi-controlled Y gate
604
+
605
+ If all controlled qubits are `|0>` then the Pauli "Y" gate is applied to
606
+ the target qubit.
607
+
608
+ Args:
609
+ c: list of controlled qubits.
610
+ q: target qubit.
611
+
612
+ Raises:
613
+ RuntimeError: QrackSimulator raised an exception.
614
+ """
615
+ Qrack.qrack_lib.MACY(self.sid, len(c), self._ulonglong_byref(c), q)
616
+ self._throw_if_error()
617
+
618
+ def macz(self, c, q):
619
+ """Anti multi-controlled Z gate
620
+
621
+ If all controlled qubits are `|0>` then the Pauli "Z" gate is applied to
622
+ the target qubit.
623
+
624
+ Args:
625
+ c: list of controlled qubits.
626
+ q: target qubit.
627
+
628
+ Raises:
629
+ RuntimeError: QrackSimulator raised an exception.
630
+ """
631
+ Qrack.qrack_lib.MACZ(self.sid, len(c), self._ulonglong_byref(c), q)
632
+ self._throw_if_error()
633
+
634
+ def mach(self, c, q):
635
+ """Anti multi-controlled H gate
636
+
637
+ If all controlled qubits are `|0>` then the Hadarmard gate is applied to
638
+ the target qubit.
639
+
640
+ Args:
641
+ c: list of controlled qubits.
642
+ q: target qubit.
643
+
644
+ Raises:
645
+ RuntimeError: QrackSimulator raised an exception.
646
+ """
647
+ Qrack.qrack_lib.MACH(self.sid, len(c), self._ulonglong_byref(c), q)
648
+ self._throw_if_error()
649
+
650
+ def macs(self, c, q):
651
+ """Anti multi-controlled S gate
652
+
653
+ If all controlled qubits are `|0>` then the "S" gate is applied to
654
+ the target qubit.
655
+
656
+ Args:
657
+ c: list of controlled qubits.
658
+ q: target qubit.
659
+
660
+ Raises:
661
+ RuntimeError: QrackSimulator raised an exception.
662
+ """
663
+ Qrack.qrack_lib.MACS(self.sid, len(c), self._ulonglong_byref(c), q)
664
+ self._throw_if_error()
665
+
666
+ def mact(self, c, q):
667
+ """Anti multi-controlled T gate
668
+
669
+ If all controlled qubits are `|0>` then the "T" gate is applied to
670
+ the target qubit.
671
+
672
+ Args:
673
+ c: list of controlled qubits.
674
+ q: target qubit.
675
+
676
+ Raises:
677
+ RuntimeError: QrackSimulator raised an exception.
678
+ """
679
+ Qrack.qrack_lib.MACT(self.sid, len(c), self._ulonglong_byref(c), q)
680
+ self._throw_if_error()
681
+
682
+ def macadjs(self, c, q):
683
+ """Anti multi-controlled adjs gate
684
+
685
+ If all controlled qubits are `|0>` then the adjs gate is applied to
686
+ the target qubit.
687
+
688
+ Args:
689
+ c: list of controlled qubits.
690
+ q: target qubit.
691
+
692
+ Raises:
693
+ RuntimeError: QrackSimulator raised an exception.
694
+ """
695
+ Qrack.qrack_lib.MACAdjS(self.sid, len(c), self._ulonglong_byref(c), q)
696
+ self._throw_if_error()
697
+
698
+ def macadjt(self, c, q):
699
+ """Anti multi-controlled adjt gate
700
+
701
+ If all controlled qubits are `|0>` then the adjt gate is applied to
702
+ the target qubit.
703
+
704
+ Args:
705
+ c: list of controlled qubits.
706
+ q: target qubit.
707
+
708
+ Raises:
709
+ RuntimeError: QrackSimulator raised an exception.
710
+ """
711
+ Qrack.qrack_lib.MACAdjT(self.sid, len(c), self._ulonglong_byref(c), q)
712
+ self._throw_if_error()
713
+
714
+ def macu(self, c, q, th, ph, la):
715
+ """Anti multi-controlled arbitraty unitary
716
+
717
+ If all controlled qubits are `|0>` then the unitary gate described by
718
+ parameters is applied to the target qubit.
719
+
720
+ Args:
721
+ c: list of controlled qubits.
722
+ q: target qubit.
723
+ th: theta
724
+ ph: phi
725
+ la: lambda
726
+
727
+ Raises:
728
+ RuntimeError: QrackSimulator raised an exception.
729
+ """
730
+ Qrack.qrack_lib.MACU(
731
+ self.sid,
732
+ len(c),
733
+ self._ulonglong_byref(c),
734
+ q,
735
+ ctypes.c_double(th),
736
+ ctypes.c_double(ph),
737
+ ctypes.c_double(la),
738
+ )
739
+ self._throw_if_error()
740
+
741
+ def macmtrx(self, c, m, q):
742
+ """Anti multi-controlled arbitraty operator
743
+
744
+ If all controlled qubits are `|0>` then the arbitrary operation by
745
+ parameters is applied to the target qubit.
746
+
747
+ Args:
748
+ c: list of controlled qubits.
749
+ m: row-major complex matrix which defines the operator.
750
+ q: target qubit.
751
+
752
+ Raises:
753
+ ValueError: 2x2 matrix 'm' in QrackSimulator.macmtrx() must contain at least 4 elements.
754
+ RuntimeError: QrackSimulator raised an exception.
755
+ """
756
+ if len(m) < 4:
757
+ raise ValueError(
758
+ "2x2 matrix 'm' in QrackSimulator.macmtrx() must contain at least 4 elements."
759
+ )
760
+ Qrack.qrack_lib.MACMtrx(
761
+ self.sid, len(c), self._ulonglong_byref(c), self._complex_byref(m), q
762
+ )
763
+ self._throw_if_error()
764
+
765
+ def ucmtrx(self, c, m, q, p):
766
+ """Multi-controlled arbitrary operator with arbitrary controls
767
+
768
+ If all control qubits match 'p' permutation by bit order, then the arbitrary
769
+ operation by parameters is applied to the target qubit.
770
+
771
+ Args:
772
+ c: list of control qubits
773
+ m: row-major complex list representing the operator.
774
+ q: target qubit
775
+ p: permutation of list of control qubits
776
+
777
+ Raises:
778
+ ValueError: 2x2 matrix 'm' in QrackSimulator.ucmtrx() must contain at least 4 elements.
779
+ RuntimeError: QrackSimulator raised an exception.
780
+ """
781
+ if len(m) < 4:
782
+ raise ValueError(
783
+ "2x2 matrix 'm' in QrackSimulator.ucmtrx() must contain at least 4 elements."
784
+ )
785
+ Qrack.qrack_lib.UCMtrx(
786
+ self.sid, len(c), self._ulonglong_byref(c), self._complex_byref(m), q, p
787
+ )
788
+ self._throw_if_error()
789
+
790
+ def multiplex1_mtrx(self, c, q, m):
791
+ """Multiplex gate
792
+
793
+ A multiplex gate with a single target and an arbitrary number of
794
+ controls.
795
+
796
+ Args:
797
+ c: list of controlled qubits.
798
+ m: row-major complex matrix which defines the operator.
799
+ q: target qubit.
800
+
801
+ Raises:
802
+ ValueError: Multiplex matrix 'm' in QrackSimulator.multiplex1_mtrx() must contain at least 4 elements.
803
+ RuntimeError: QrackSimulator raised an exception.
804
+ """
805
+ if len(m) < ((1 << len(c)) * 4):
806
+ raise ValueError(
807
+ "Multiplex matrix 'm' in QrackSimulator.multiplex1_mtrx() must contain at least (4 * 2 ** len(c)) elements."
808
+ )
809
+ Qrack.qrack_lib.Multiplex1Mtrx(
810
+ self.sid, len(c), self._ulonglong_byref(c), q, self._complex_byref(m)
811
+ )
812
+ self._throw_if_error()
813
+
814
+ def mx(self, q):
815
+ """Multi X-gate
816
+
817
+ Applies the Pauli “X” operator on all qubits.
818
+
819
+ Args:
820
+ q: list of qubits to apply X on.
821
+
822
+ Raises:
823
+ RuntimeError: QrackSimulator raised an exception.
824
+ """
825
+ Qrack.qrack_lib.MX(self.sid, len(q), self._ulonglong_byref(q))
826
+ self._throw_if_error()
827
+
828
+ def my(self, q):
829
+ """Multi Y-gate
830
+
831
+ Applies the Pauli “Y” operator on all qubits.
832
+
833
+ Args:
834
+ q: list of qubits to apply Y on.
835
+
836
+ Raises:
837
+ RuntimeError: QrackSimulator raised an exception.
838
+ """
839
+ Qrack.qrack_lib.MY(self.sid, len(q), self._ulonglong_byref(q))
840
+ self._throw_if_error()
841
+
842
+ def mz(self, q):
843
+ """Multi Z-gate
844
+
845
+ Applies the Pauli “Z” operator on all qubits.
846
+
847
+ Args:
848
+ q: list of qubits to apply Z on.
849
+
850
+ Raises:
851
+ RuntimeError: QrackSimulator raised an exception.
852
+ """
853
+ Qrack.qrack_lib.MZ(self.sid, len(q), self._ulonglong_byref(q))
854
+ self._throw_if_error()
855
+
856
+ def mcr(self, b, ph, c, q):
857
+ """Multi-controlled arbitrary rotation.
858
+
859
+ If all controlled qubits are `|1>` then the arbitrary rotation by
860
+ parameters is applied to the target qubit.
861
+
862
+ Args:
863
+ b: Pauli basis
864
+ ph: coefficient of exponentiation.
865
+ c: list of controlled qubits.
866
+ q: the qubit number on which the gate is applied to.
867
+
868
+ Raises:
869
+ RuntimeError: QrackSimulator raised an exception.
870
+ """
871
+ Qrack.qrack_lib.MCR(
872
+ self.sid,
873
+ ctypes.c_ulonglong(b),
874
+ ctypes.c_double(ph),
875
+ len(c),
876
+ self._ulonglong_byref(c),
877
+ q,
878
+ )
879
+ self._throw_if_error()
880
+
881
+ def mcexp(self, b, ph, cs, q):
882
+ """Multi-controlled arbitrary exponentiation
883
+
884
+ If all controlled qubits are `|1>` then the target qubit is
885
+ exponentiated an pauli basis basis with coefficient.
886
+
887
+ Args:
888
+ b: Pauli basis
889
+ ph: coefficient of exponentiation.
890
+ q: the qubit number on which the gate is applied to.
891
+
892
+ Raises:
893
+ RuntimeError: QrackSimulator raised an exception.
894
+ """
895
+ if len(b) != len(q):
896
+ raise RuntimeError("Lengths of list parameters are mismatched.")
897
+ Qrack.qrack_lib.MCExp(
898
+ self.sid,
899
+ len(b),
900
+ self._ulonglong_byref(b),
901
+ ctypes.c_double(ph),
902
+ len(cs),
903
+ self._ulonglong_byref(cs),
904
+ self._ulonglong_byref(q),
905
+ )
906
+ self._throw_if_error()
907
+
908
+ def swap(self, qi1, qi2):
909
+ """Swap Gate
910
+
911
+ Swaps the qubits at two given positions.
912
+
913
+ Args:
914
+ qi1: First position of qubit.
915
+ qi2: Second position of qubit.
916
+
917
+ Raises:
918
+ RuntimeError: QrackSimulator raised an exception.
919
+ """
920
+ Qrack.qrack_lib.SWAP(self.sid, qi1, qi2)
921
+ self._throw_if_error()
922
+
923
+ def iswap(self, qi1, qi2):
924
+ """Swap Gate with phase.
925
+
926
+ Swaps the qubits at two given positions.
927
+ If the bits are different then there is additional phase of `i`.
928
+
929
+ Args:
930
+ qi1: First position of qubit.
931
+ qi2: Second position of qubit.
932
+
933
+ Raises:
934
+ RuntimeError: QrackSimulator raised an exception.
935
+ """
936
+ Qrack.qrack_lib.ISWAP(self.sid, qi1, qi2)
937
+ self._throw_if_error()
938
+
939
+ def adjiswap(self, qi1, qi2):
940
+ """Swap Gate with phase.
941
+
942
+ Swaps the qubits at two given positions.
943
+ If the bits are different then there is additional phase of `-i`.
944
+
945
+ Args:
946
+ qi1: First position of qubit.
947
+ qi2: Second position of qubit.
948
+
949
+ Raises:
950
+ RuntimeError: QrackSimulator raised an exception.
951
+ """
952
+ Qrack.qrack_lib.AdjISWAP(self.sid, qi1, qi2)
953
+ self._throw_if_error()
954
+
955
+ def fsim(self, th, ph, qi1, qi2):
956
+ """Fsim gate.
957
+
958
+ The 2-qubit “fSim” gate
959
+ Useful in the simulation of particles with fermionic statistics
960
+
961
+ Args:
962
+ qi1: First position of qubit.
963
+ qi2: Second position of qubit.
964
+
965
+ Raises:
966
+ RuntimeError: QrackSimulator raised an exception.
967
+ """
968
+ Qrack.qrack_lib.FSim(
969
+ self.sid, ctypes.c_double(th), ctypes.c_double(ph), qi1, qi2
970
+ )
971
+ self._throw_if_error()
972
+
973
+ def cswap(self, c, qi1, qi2):
974
+ """Controlled-swap Gate
975
+
976
+ Swaps the qubits at two given positions if the control qubits are `|1>`
977
+
978
+ Args:
979
+ c: list of controlled qubits.
980
+ qi1: First position of qubit.
981
+ qi2: Second position of qubit.
982
+
983
+ Raises:
984
+ RuntimeError: QrackSimulator raised an exception.
985
+ """
986
+ Qrack.qrack_lib.CSWAP(self.sid, len(c), self._ulonglong_byref(c), qi1, qi2)
987
+ self._throw_if_error()
988
+
989
+ def acswap(self, c, qi1, qi2):
990
+ """Anti controlled-swap Gate
991
+
992
+ Swaps the qubits at two given positions if the control qubits are `|0>`
993
+
994
+ Args:
995
+ c: list of controlled qubits.
996
+ qi1: First position of qubit.
997
+ qi2: Second position of qubit.
998
+
999
+ Raises:
1000
+ RuntimeError: QrackSimulator raised an exception.
1001
+ """
1002
+ Qrack.qrack_lib.ACSWAP(self.sid, len(c), self._ulonglong_byref(c), qi1, qi2)
1003
+ self._throw_if_error()
1004
+
1005
+ # standard operations
1006
+ def m(self, q):
1007
+ """Measurement gate
1008
+
1009
+ Measures the qubit at "q" and returns Boolean value.
1010
+ This operator is not unitary & is probabilistic in nature.
1011
+
1012
+ Args:
1013
+ q: qubit to measure
1014
+
1015
+ Raises:
1016
+ RuntimeError: QrackSimulator raised an exception.
1017
+
1018
+ Returns:
1019
+ Measurement result.
1020
+ """
1021
+ result = Qrack.qrack_lib.M(self.sid, q)
1022
+ self._throw_if_error()
1023
+ return result
1024
+
1025
+ def force_m(self, q, r):
1026
+ """Force-Measurement gate
1027
+
1028
+ Acts as if the measurement is applied and the result obtained is `r`
1029
+
1030
+ Args:
1031
+ q: qubit to measure
1032
+ r: the required result
1033
+
1034
+ Raises:
1035
+ RuntimeError: QrackSimulator raised an exception.
1036
+
1037
+ Returns:
1038
+ Measurement result.
1039
+ """
1040
+ result = Qrack.qrack_lib.ForceM(self.sid, q, r)
1041
+ self._throw_if_error()
1042
+ return result
1043
+
1044
+ def m_all(self):
1045
+ """Measure-all gate
1046
+
1047
+ Measures measures all qubits.
1048
+ This operator is not unitary & is probabilistic in nature.
1049
+
1050
+ Raises:
1051
+ RuntimeError: QrackSimulator raised an exception.
1052
+
1053
+ Returns:
1054
+ Measurement result of all qubits.
1055
+ """
1056
+ result = Qrack.qrack_lib.MAll(self.sid)
1057
+ self._throw_if_error()
1058
+ return result
1059
+
1060
+ def measure_pauli(self, b, q):
1061
+ """Pauli Measurement gate
1062
+
1063
+ Measures the qubit at "q" with the given pauli basis.
1064
+ This operator is not unitary & is probabilistic in nature.
1065
+
1066
+ Args:
1067
+ b: Pauli basis
1068
+ q: qubit to measure
1069
+
1070
+ Raises:
1071
+ RuntimeError: QrackSimulator raised an exception.
1072
+
1073
+ Returns:
1074
+ Measurement result.
1075
+ """
1076
+ if len(b) != len(q):
1077
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1078
+ result = Qrack.qrack_lib.Measure(
1079
+ self.sid, len(b), self._int_byref(b), self._ulonglong_byref(q)
1080
+ )
1081
+ self._throw_if_error()
1082
+ return result
1083
+
1084
+ def measure_shots(self, q, s):
1085
+ """Multi-shot measurement operator
1086
+
1087
+ Measures the qubit at "q" with the given pauli basis.
1088
+ This operator is not unitary & is probabilistic in nature.
1089
+
1090
+ Args:
1091
+ q: list of qubits to measure
1092
+ s: number of shots
1093
+
1094
+ Raises:
1095
+ RuntimeError: QrackSimulator raised an exception.
1096
+
1097
+ Returns:
1098
+ list of measurement result.
1099
+ """
1100
+ m = self._ulonglong_byref([0] * s)
1101
+ Qrack.qrack_lib.MeasureShots(self.sid, len(q), self._ulonglong_byref(q), s, m)
1102
+ self._throw_if_error()
1103
+ return [m[i] for i in range(s)]
1104
+
1105
+ def reset_all(self):
1106
+ """Reset gate
1107
+
1108
+ Resets all qubits to `|0>`
1109
+
1110
+ Raises:
1111
+ RuntimeError: QrackSimulator raised an exception.
1112
+ """
1113
+ Qrack.qrack_lib.ResetAll(self.sid)
1114
+ self._throw_if_error()
1115
+
1116
+ # arithmetic-logic-unit (ALU)
1117
+ def _split_longs(self, a):
1118
+ """Split operation
1119
+
1120
+ Splits the given integer into 64 bit numbers.
1121
+
1122
+
1123
+ Args:
1124
+ a: number to split
1125
+
1126
+ Raises:
1127
+ RuntimeError: QrackSimulator raised an exception.
1128
+
1129
+ Returns:
1130
+ list of split numbers.
1131
+ """
1132
+ aParts = []
1133
+ if a == 0:
1134
+ aParts.append(0)
1135
+ while a > 0:
1136
+ aParts.append(a & 0xFFFFFFFFFFFFFFFF)
1137
+ a = a >> 64
1138
+ return aParts
1139
+
1140
+ def _split_longs_2(self, a, m):
1141
+ """Split simultanoues operation
1142
+
1143
+ Splits 2 integers into same number of 64 bit numbers.
1144
+
1145
+ Args:
1146
+ a: first number to split
1147
+ m: second number to split
1148
+
1149
+ Raises:
1150
+ RuntimeError: QrackSimulator raised an exception.
1151
+
1152
+ Returns:
1153
+ pair of lists of split numbers.
1154
+ """
1155
+ aParts = []
1156
+ mParts = []
1157
+ if a == 0 and m == 0:
1158
+ aParts.append(0)
1159
+ mParts.append(0)
1160
+ while a > 0 or m > 0:
1161
+ aParts.append(a & 0xFFFFFFFFFFFFFFFF)
1162
+ a = a >> 64
1163
+ mParts.append(m & 0xFFFFFFFFFFFFFFFF)
1164
+ m = m >> 64
1165
+ return aParts, mParts
1166
+
1167
+ def add(self, a, q):
1168
+ """Add integer to qubit
1169
+
1170
+ Adds the given integer to the given set of qubits.
1171
+
1172
+ Args:
1173
+ a: first number to split
1174
+ q: list of qubits to add the number
1175
+
1176
+ Raises:
1177
+ RuntimeError: QrackSimulator raised an exception.
1178
+ """
1179
+ aParts = self._split_longs(a)
1180
+ Qrack.qrack_lib.ADD(
1181
+ self.sid,
1182
+ len(aParts),
1183
+ self._ulonglong_byref(aParts),
1184
+ len(q),
1185
+ self._ulonglong_byref(q),
1186
+ )
1187
+ self._throw_if_error()
1188
+
1189
+ def sub(self, a, q):
1190
+ """Subtract integer to qubit
1191
+
1192
+ Subtracts the given integer to the given set of qubits.
1193
+
1194
+ Args:
1195
+ a: first number to split
1196
+ q: list of qubits to subtract the number
1197
+
1198
+ Raises:
1199
+ RuntimeError: QrackSimulator raised an exception.
1200
+ """
1201
+ aParts = self._split_longs(a)
1202
+ Qrack.qrack_lib.SUB(
1203
+ self.sid,
1204
+ len(aParts),
1205
+ self._ulonglong_byref(aParts),
1206
+ len(q),
1207
+ self._ulonglong_byref(q),
1208
+ )
1209
+ self._throw_if_error()
1210
+
1211
+ def adds(self, a, s, q):
1212
+ """Signed Addition integer to qubit
1213
+
1214
+ Signed Addition of the given integer to the given set of qubits,
1215
+ if there is an overflow the resultant will become negative.
1216
+
1217
+ Args:
1218
+ a: number to add
1219
+ s: qubit to store overflow
1220
+ q: list of qubits to add the number
1221
+
1222
+ Raises:
1223
+ RuntimeError: QrackSimulator raised an exception.
1224
+ """
1225
+ aParts = self._split_longs(a)
1226
+ Qrack.qrack_lib.ADDS(
1227
+ self.sid,
1228
+ len(aParts),
1229
+ self._ulonglong_byref(aParts),
1230
+ s,
1231
+ len(q),
1232
+ self._ulonglong_byref(q),
1233
+ )
1234
+ self._throw_if_error()
1235
+
1236
+ def subs(self, a, s, q):
1237
+ """Subtract integer to qubit
1238
+
1239
+ Subtracts the given integer to the given set of qubits,
1240
+ if there is an overflow the resultant will become negative.
1241
+
1242
+ Args:
1243
+ a: number to subtract
1244
+ s: qubit to store overflow
1245
+ q: list of qubits to subtract the number
1246
+
1247
+ Raises:
1248
+ RuntimeError: QrackSimulator raised an exception.
1249
+ """
1250
+ aParts = self._split_longs(a)
1251
+ Qrack.qrack_lib.SUBS(
1252
+ self.sid,
1253
+ len(aParts),
1254
+ self._ulonglong_byref(aParts),
1255
+ s,
1256
+ len(q),
1257
+ self._ulonglong_byref(q),
1258
+ )
1259
+ self._throw_if_error()
1260
+
1261
+ def mul(self, a, q, o):
1262
+ """Multiplies integer to qubit
1263
+
1264
+ Multiplies the given integer to the given set of qubits.
1265
+ Carry register is required for maintaining the unitary nature of
1266
+ operation and must be as long as the input qubit register.
1267
+
1268
+ Args:
1269
+ a: number to multiply
1270
+ q: list of qubits to multiply the number
1271
+ o: carry register
1272
+
1273
+ Raises:
1274
+ RuntimeError: QrackSimulator raised an exception.
1275
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot mul()! (Turn off just this option, in the constructor.)
1276
+ """
1277
+ if self.is_tensor_network:
1278
+ raise RuntimeError(
1279
+ "QrackSimulator with isTensorNetwork=True option cannot mul()! (Turn off just this option, in the constructor.)"
1280
+ )
1281
+ if self.is_pure_stabilizer:
1282
+ raise RuntimeError(
1283
+ "QrackStabilizer cannot mul()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1284
+ )
1285
+
1286
+ if len(q) != len(o):
1287
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1288
+ aParts = self._split_longs(a)
1289
+ Qrack.qrack_lib.MUL(
1290
+ self.sid,
1291
+ len(aParts),
1292
+ self._ulonglong_byref(aParts),
1293
+ len(q),
1294
+ self._ulonglong_byref(q),
1295
+ self._ulonglong_byref(o),
1296
+ )
1297
+ self._throw_if_error()
1298
+
1299
+ def div(self, a, q, o):
1300
+ """Divides qubit by integer
1301
+
1302
+ 'Divides' the given qubits by the integer.
1303
+ (This is rather the adjoint of mul().)
1304
+ Carry register is required for maintaining the unitary nature of
1305
+ operation.
1306
+
1307
+ Args:
1308
+ a: integer to divide by
1309
+ q: qubits to divide
1310
+ o: carry register
1311
+
1312
+ Raises:
1313
+ RuntimeError: QrackSimulator raised an exception.
1314
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot div()! (Turn off just this option, in the constructor.)
1315
+ """
1316
+ if self.is_tensor_network:
1317
+ raise RuntimeError(
1318
+ "QrackSimulator with isTensorNetwork=True option cannot div()! (Turn off just this option, in the constructor.)"
1319
+ )
1320
+ if self.is_pure_stabilizer:
1321
+ raise RuntimeError(
1322
+ "QrackStabilizer cannot div()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1323
+ )
1324
+
1325
+ if len(q) != len(o):
1326
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1327
+ aParts = self._split_longs(a)
1328
+ Qrack.qrack_lib.DIV(
1329
+ self.sid,
1330
+ len(aParts),
1331
+ self._ulonglong_byref(aParts),
1332
+ len(q),
1333
+ self._ulonglong_byref(q),
1334
+ self._ulonglong_byref(o),
1335
+ )
1336
+ self._throw_if_error()
1337
+
1338
+ def muln(self, a, m, q, o):
1339
+ """Modulo Multiplication
1340
+
1341
+ Modulo Multiplication of the given integer to the given set of qubits
1342
+ Out-of-place register is required to store the resultant.
1343
+
1344
+ Args:
1345
+ a: number to multiply
1346
+ m: modulo number
1347
+ q: list of qubits to multiply the number
1348
+ o: carry register
1349
+
1350
+ Raises:
1351
+ RuntimeError: QrackSimulator raised an exception.
1352
+ """
1353
+ if len(q) != len(o):
1354
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1355
+ aParts, mParts = self._split_longs_2(a, m)
1356
+ Qrack.qrack_lib.MULN(
1357
+ self.sid,
1358
+ len(aParts),
1359
+ self._ulonglong_byref(aParts),
1360
+ self._ulonglong_byref(mParts),
1361
+ len(q),
1362
+ self._ulonglong_byref(q),
1363
+ self._ulonglong_byref(o),
1364
+ )
1365
+ self._throw_if_error()
1366
+
1367
+ def divn(self, a, m, q, o):
1368
+ """Modulo Division
1369
+
1370
+ 'Modulo Division' of the given set of qubits by the given integer
1371
+ (This is rather the adjoint of muln().)
1372
+ Out-of-place register is required to retrieve the resultant.
1373
+
1374
+ Args:
1375
+ a: integer by which qubit will be divided
1376
+ m: modulo integer
1377
+ q: qubits to divide
1378
+ o: carry register
1379
+
1380
+ Raises:
1381
+ RuntimeError: QrackSimulator raised an exception.
1382
+ """
1383
+ if len(q) != len(o):
1384
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1385
+ aParts, mParts = self._split_longs_2(a, m)
1386
+ Qrack.qrack_lib.DIVN(
1387
+ self.sid,
1388
+ len(aParts),
1389
+ self._ulonglong_byref(aParts),
1390
+ self._ulonglong_byref(mParts),
1391
+ len(q),
1392
+ self._ulonglong_byref(q),
1393
+ self._ulonglong_byref(o),
1394
+ )
1395
+ self._throw_if_error()
1396
+
1397
+ def pown(self, a, m, q, o):
1398
+ """Modulo Power
1399
+
1400
+ Raises the qubit to the power `a` to which `mod m` is applied to.
1401
+ Out-of-place register is required to store the resultant.
1402
+
1403
+ Args:
1404
+ a: number in power
1405
+ m: modulo number
1406
+ q: list of qubits to exponentiate
1407
+ o: out-of-place register
1408
+
1409
+ Raises:
1410
+ RuntimeError: QrackSimulator raised an exception.
1411
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot pown()! (Turn off just this option, in the constructor.)
1412
+ """
1413
+ if self.is_tensor_network:
1414
+ raise RuntimeError(
1415
+ "QrackSimulator with isTensorNetwork=True option cannot pown()! (Turn off just this option, in the constructor.)"
1416
+ )
1417
+ if self.is_pure_stabilizer:
1418
+ raise RuntimeError(
1419
+ "QrackStabilizer cannot pown()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1420
+ )
1421
+
1422
+ if len(q) != len(o):
1423
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1424
+ aParts, mParts = self._split_longs_2(a, m)
1425
+ Qrack.qrack_lib.POWN(
1426
+ self.sid,
1427
+ len(aParts),
1428
+ self._ulonglong_byref(aParts),
1429
+ self._ulonglong_byref(mParts),
1430
+ len(q),
1431
+ self._ulonglong_byref(q),
1432
+ self._ulonglong_byref(o),
1433
+ )
1434
+ self._throw_if_error()
1435
+
1436
+ def mcadd(self, a, c, q):
1437
+ """Controlled-add
1438
+
1439
+ Adds the given integer to the given set of qubits if all controlled
1440
+ qubits are `|1>`.
1441
+
1442
+ Args:
1443
+ a: number to add.
1444
+ c: list of controlled qubits.
1445
+ q: list of qubits to add the number
1446
+
1447
+ Raises:
1448
+ RuntimeError: QrackSimulator raised an exception.
1449
+ """
1450
+ aParts = self._split_longs(a)
1451
+ Qrack.qrack_lib.MCADD(
1452
+ self.sid,
1453
+ len(aParts),
1454
+ self._ulonglong_byref(aParts),
1455
+ len(c),
1456
+ self._ulonglong_byref(c),
1457
+ len(q),
1458
+ self._ulonglong_byref(q),
1459
+ )
1460
+ self._throw_if_error()
1461
+
1462
+ def mcsub(self, a, c, q):
1463
+ """Controlled-subtract
1464
+
1465
+ Subtracts the given integer to the given set of qubits if all controlled
1466
+ qubits are `|1>`.
1467
+
1468
+ Args:
1469
+ a: number to subtract.
1470
+ c: list of controlled qubits.
1471
+ q: list of qubits to add the number
1472
+
1473
+ Raises:
1474
+ RuntimeError: QrackSimulator raised an exception.
1475
+ """
1476
+ aParts = self._split_longs(a)
1477
+ Qrack.qrack_lib.MCSUB(
1478
+ self.sid,
1479
+ len(aParts),
1480
+ self._ulonglong_byref(aParts),
1481
+ len(c),
1482
+ self._ulonglong_byref(c),
1483
+ len(q),
1484
+ self._ulonglong_byref(q),
1485
+ )
1486
+ self._throw_if_error()
1487
+
1488
+ def mcmul(self, a, c, q, o):
1489
+ """Controlled-multiply
1490
+
1491
+ Multiplies the given integer to the given set of qubits if all controlled
1492
+ qubits are `|1>`.
1493
+ Carry register is required for maintaining the unitary nature of
1494
+ operation.
1495
+
1496
+ Args:
1497
+ a: number to multiply
1498
+ c: list of controlled qubits.
1499
+ q: list of qubits to add the number
1500
+ o: carry register
1501
+
1502
+ Raises:
1503
+ RuntimeError: QrackSimulator raised an exception.
1504
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot mcmul()! (Turn off just this option, in the constructor.)
1505
+ """
1506
+ if self.is_tensor_network:
1507
+ raise RuntimeError(
1508
+ "QrackSimulator with isTensorNetwork=True option cannot mcmul()! (Turn off just this option, in the constructor.)"
1509
+ )
1510
+ if self.is_pure_stabilizer:
1511
+ raise RuntimeError(
1512
+ "QrackStabilizer cannot mcmul()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1513
+ )
1514
+
1515
+ if len(q) != len(o):
1516
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1517
+ aParts = self._split_longs(a)
1518
+ Qrack.qrack_lib.MCMUL(
1519
+ self.sid,
1520
+ len(aParts),
1521
+ self._ulonglong_byref(aParts),
1522
+ len(c),
1523
+ self._ulonglong_byref(c),
1524
+ len(q),
1525
+ self._ulonglong_byref(q),
1526
+ )
1527
+ self._throw_if_error()
1528
+
1529
+ def mcdiv(self, a, c, q, o):
1530
+ """Controlled-divide.
1531
+
1532
+ 'Divides' the given qubits by the integer if all controlled
1533
+ qubits are `|1>`.
1534
+ (This is rather the adjoint of mcmul().)
1535
+ Carry register is required for maintaining the unitary nature of
1536
+ operation.
1537
+
1538
+ Args:
1539
+ a: number to divide by
1540
+ c: list of controlled qubits.
1541
+ q: qubits to divide
1542
+ o: carry register
1543
+
1544
+ Raises:
1545
+ RuntimeError: QrackSimulator raised an exception.
1546
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot mcdiv()! (Turn off just this option, in the constructor.)
1547
+ """
1548
+ if self.is_tensor_network:
1549
+ raise RuntimeError(
1550
+ "QrackSimulator with isTensorNetwork=True option cannot mcdiv()! (Turn off just this option, in the constructor.)"
1551
+ )
1552
+ if self.is_pure_stabilizer:
1553
+ raise RuntimeError(
1554
+ "QrackStabilizer cannot mcdiv()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1555
+ )
1556
+
1557
+ if len(q) != len(o):
1558
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1559
+ aParts = self._split_longs(a)
1560
+ Qrack.qrack_lib.MCDIV(
1561
+ self.sid,
1562
+ len(aParts),
1563
+ self._ulonglong_byref(aParts),
1564
+ len(c),
1565
+ self._ulonglong_byref(c),
1566
+ len(q),
1567
+ self._ulonglong_byref(q),
1568
+ )
1569
+ self._throw_if_error()
1570
+
1571
+ def mcmuln(self, a, c, m, q, o):
1572
+ """Controlled-modulo multiplication
1573
+
1574
+ Modulo multiplication of the given integer to the given set of qubits
1575
+ if all controlled qubits are `|1>`.
1576
+ Out-of-place register is required to store the resultant.
1577
+
1578
+ Args:
1579
+ a: number to multiply
1580
+ c: list of controlled qubits.
1581
+ m: modulo number
1582
+ q: list of qubits to add the number
1583
+ o: out-of-place output register
1584
+
1585
+ Raises:
1586
+ RuntimeError: QrackSimulator raised an exception.
1587
+ """
1588
+ if len(q) != len(o):
1589
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1590
+ aParts, mParts = self._split_longs_2(a, m)
1591
+ Qrack.qrack_lib.MCMULN(
1592
+ self.sid,
1593
+ len(aParts),
1594
+ self._ulonglong_byref(aParts),
1595
+ len(c),
1596
+ self._ulonglong_byref(c),
1597
+ self._ulonglong_byref(mParts),
1598
+ len(q),
1599
+ self._ulonglong_byref(q),
1600
+ self._ulonglong_byref(o),
1601
+ )
1602
+ self._throw_if_error()
1603
+
1604
+ def mcdivn(self, a, c, m, q, o):
1605
+ """Controlled-divide.
1606
+
1607
+ Modulo division of the given qubits by the given number if all
1608
+ controlled qubits are `|1>`.
1609
+ (This is rather the adjoint of mcmuln().)
1610
+ Out-of-place register is required to retrieve the resultant.
1611
+
1612
+ Args:
1613
+ a: number to divide by
1614
+ c: list of controlled qubits.
1615
+ m: modulo number
1616
+ q: qubits to divide
1617
+ o: carry register
1618
+
1619
+ Raises:
1620
+ RuntimeError: QrackSimulator raised an exception.
1621
+ """
1622
+ if len(q) != len(o):
1623
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1624
+ aParts, mParts = self._split_longs_2(a, m)
1625
+ Qrack.qrack_lib.MCDIVN(
1626
+ self.sid,
1627
+ len(aParts),
1628
+ self._ulonglong_byref(aParts),
1629
+ len(c),
1630
+ self._ulonglong_byref(c),
1631
+ self._ulonglong_byref(mParts),
1632
+ len(q),
1633
+ self._ulonglong_byref(q),
1634
+ self._ulonglong_byref(o),
1635
+ )
1636
+ self._throw_if_error()
1637
+
1638
+ def mcpown(self, a, c, m, q, o):
1639
+ """Controlled-modulo Power
1640
+
1641
+ Raises the qubit to the power `a` to which `mod m` is applied to if
1642
+ all the controlled qubits are set to `|1>`.
1643
+ Out-of-place register is required to store the resultant.
1644
+
1645
+ Args:
1646
+ a: number in power
1647
+ c: control qubits
1648
+ m: modulo number
1649
+ q: list of qubits to exponentiate
1650
+ o: out-of-place register
1651
+
1652
+ Raises:
1653
+ RuntimeError: QrackSimulator raised an exception.
1654
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot mcpown()! (Turn off just this option, in the constructor.)
1655
+ """
1656
+ if self.is_tensor_network:
1657
+ raise RuntimeError(
1658
+ "QrackSimulator with isTensorNetwork=True option cannot mcpown()! (Turn off just this option, in the constructor.)"
1659
+ )
1660
+ if self.is_pure_stabilizer:
1661
+ raise RuntimeError(
1662
+ "QrackStabilizer cannot mcpown()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1663
+ )
1664
+
1665
+ if len(q) != len(o):
1666
+ raise RuntimeError("Lengths of list parameters are mismatched.")
1667
+ aParts, mParts = self._split_longs_2(a, m)
1668
+ Qrack.qrack_lib.MCPOWN(
1669
+ self.sid,
1670
+ len(aParts),
1671
+ self._ulonglong_byref(aParts),
1672
+ len(c),
1673
+ self._ulonglong_byref(c),
1674
+ self._ulonglong_byref(mParts),
1675
+ len(q),
1676
+ self._ulonglong_byref(q),
1677
+ self._ulonglong_byref(o),
1678
+ )
1679
+ self._throw_if_error()
1680
+
1681
+ def lda(self, qi, qv, t):
1682
+ """Load Accumalator
1683
+
1684
+ Quantum counterpart for LDA from MOS-6502 assembly. `t` must be of
1685
+ the length `2 ** len(qi)`. It loads each list entry index of t into
1686
+ the qi register and each list entry value into the qv register.
1687
+
1688
+ Args:
1689
+ qi: qubit register for index
1690
+ qv: qubit register for value
1691
+ t: list of values
1692
+
1693
+ Raises:
1694
+ RuntimeError: QrackSimulator raised an exception.
1695
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot lda()! (Turn off just this option, in the constructor.)
1696
+ """
1697
+ if self.is_tensor_network:
1698
+ raise RuntimeError(
1699
+ "QrackSimulator with isTensorNetwork=True option cannot lda()! (Turn off just this option, in the constructor.)"
1700
+ )
1701
+ if self.is_pure_stabilizer:
1702
+ raise RuntimeError(
1703
+ "QrackStabilizer cannot lda()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1704
+ )
1705
+
1706
+ Qrack.qrack_lib.LDA(
1707
+ self.sid,
1708
+ len(qi),
1709
+ self._ulonglong_byref(qi),
1710
+ len(qv),
1711
+ self._ulonglong_byref(qv),
1712
+ self._to_ubyte(len(qv), t),
1713
+ )
1714
+ self._throw_if_error()
1715
+
1716
+ def adc(self, s, qi, qv, t):
1717
+ """Add with Carry
1718
+
1719
+ Quantum counterpart for ADC from MOS-6502 assembly. `t` must be of
1720
+ the length `2 ** len(qi)`.
1721
+
1722
+ Args:
1723
+ qi: qubit register for index
1724
+ qv: qubit register for value
1725
+ t: list of values
1726
+
1727
+ Raises:
1728
+ RuntimeError: QrackSimulator raised an exception.
1729
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot adc()! (Turn off just this option, in the constructor.)
1730
+ """
1731
+ if self.is_tensor_network:
1732
+ raise RuntimeError(
1733
+ "QrackSimulator with isTensorNetwork=True option cannot adc()! (Turn off just this option, in the constructor.)"
1734
+ )
1735
+ if self.is_pure_stabilizer:
1736
+ raise RuntimeError(
1737
+ "QrackStabilizer cannot adc()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1738
+ )
1739
+
1740
+ Qrack.qrack_lib.ADC(
1741
+ self.sid,
1742
+ s,
1743
+ len(qi),
1744
+ self._ulonglong_byref(qi),
1745
+ len(qv),
1746
+ self._ulonglong_byref(qv),
1747
+ self._to_ubyte(len(qv), t),
1748
+ )
1749
+ self._throw_if_error()
1750
+
1751
+ def sbc(self, s, qi, qv, t):
1752
+ """Subtract with Carry
1753
+
1754
+ Quantum counterpart for SBC from MOS-6502 assembly. `t` must be of
1755
+ the length `2 ** len(qi)`
1756
+
1757
+ Args:
1758
+ qi: qubit register for index
1759
+ qv: qubit register for value
1760
+ t: list of values
1761
+
1762
+ Raises:
1763
+ RuntimeError: QrackSimulator raised an exception.
1764
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot sbc()! (Turn off just this option, in the constructor.)
1765
+ """
1766
+ if self.is_tensor_network:
1767
+ raise RuntimeError(
1768
+ "QrackSimulator with isTensorNetwork=True option cannot sbc()! (Turn off just this option, in the constructor.)"
1769
+ )
1770
+ if self.is_pure_stabilizer:
1771
+ raise RuntimeError(
1772
+ "QrackStabilizer cannot sbc()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1773
+ )
1774
+
1775
+ Qrack.qrack_lib.SBC(
1776
+ self.sid,
1777
+ s,
1778
+ len(qi),
1779
+ self._ulonglong_byref(qi),
1780
+ len(qv),
1781
+ self._ulonglong_byref(qv),
1782
+ self._to_ubyte(len(qv), t),
1783
+ )
1784
+ self._throw_if_error()
1785
+
1786
+ def hash(self, q, t):
1787
+ """Hash function
1788
+
1789
+ Replicates the behaviour of LDA without the index register.
1790
+ For the operation to be unitary, the entries present in `t` must be
1791
+ unique, and the length of `t` must be `2 ** len(qi)`.
1792
+
1793
+
1794
+ Args:
1795
+ q: qubit register for value
1796
+ t: list of values
1797
+
1798
+ Raises:
1799
+ RuntimeError: QrackSimulator raised an exception.
1800
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot hash()! (Turn off just this option, in the constructor.)
1801
+ """
1802
+ if self.is_tensor_network:
1803
+ raise RuntimeError(
1804
+ "QrackSimulator with isTensorNetwork=True option cannot hash()! (Turn off just this option, in the constructor.)"
1805
+ )
1806
+ if self.is_pure_stabilizer:
1807
+ raise RuntimeError(
1808
+ "QrackStabilizer cannot hash()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
1809
+ )
1810
+
1811
+ Qrack.qrack_lib.Hash(
1812
+ self.sid, len(q), self._ulonglong_byref(q), self._to_ubyte(len(q), t)
1813
+ )
1814
+ self._throw_if_error()
1815
+
1816
+ # boolean logic gates
1817
+ def qand(self, qi1, qi2, qo):
1818
+ """Logical AND
1819
+
1820
+ Logical AND of 2 qubits whose result is stored in the target qubit.
1821
+
1822
+ Args:
1823
+ qi1: qubit 1
1824
+ qi2: qubit 2
1825
+ qo: target qubit
1826
+
1827
+ Raises:
1828
+ RuntimeError: QrackSimulator raised an exception.
1829
+ """
1830
+ Qrack.qrack_lib.AND(self.sid, qi1, qi2, qo)
1831
+ self._throw_if_error()
1832
+
1833
+ def qor(self, qi1, qi2, qo):
1834
+ """Logical OR
1835
+
1836
+ Logical OR of 2 qubits whose result is stored in the target qubit.
1837
+
1838
+ Args:
1839
+ qi1: qubit 1
1840
+ qi2: qubit 2
1841
+ qo: target qubit
1842
+
1843
+ Raises:
1844
+ RuntimeError: QrackSimulator raised an exception.
1845
+ """
1846
+ Qrack.qrack_lib.OR(self.sid, qi1, qi2, qo)
1847
+ self._throw_if_error()
1848
+
1849
+ def qxor(self, qi1, qi2, qo):
1850
+ """Logical XOR
1851
+
1852
+ Logical exlusive-OR of 2 qubits whose result is stored in the target
1853
+ qubit.
1854
+
1855
+ Args:
1856
+ qi1: qubit 1
1857
+ qi2: qubit 2
1858
+ qo: target qubit
1859
+
1860
+ Raises:
1861
+ RuntimeError: QrackSimulator raised an exception.
1862
+ """
1863
+ Qrack.qrack_lib.XOR(self.sid, qi1, qi2, qo)
1864
+ self._throw_if_error()
1865
+
1866
+ def qnand(self, qi1, qi2, qo):
1867
+ """Logical NAND
1868
+
1869
+ Logical NAND of 2 qubits whose result is stored in the target
1870
+ qubit.
1871
+
1872
+ Args:
1873
+ qi1: qubit 1
1874
+ qi2: qubit 2
1875
+ qo: target qubit
1876
+
1877
+ Raises:
1878
+ RuntimeError: QrackSimulator raised an exception.
1879
+ """
1880
+ Qrack.qrack_lib.NAND(self.sid, qi1, qi2, qo)
1881
+ self._throw_if_error()
1882
+
1883
+ def qnor(self, qi1, qi2, qo):
1884
+ """Logical NOR
1885
+
1886
+ Logical NOR of 2 qubits whose result is stored in the target
1887
+ qubit.
1888
+
1889
+ Args:
1890
+ qi1: qubit 1
1891
+ qi2: qubit 2
1892
+ qo: target qubit
1893
+
1894
+ Raises:
1895
+ RuntimeError: QrackSimulator raised an exception.
1896
+ """
1897
+ Qrack.qrack_lib.NOR(self.sid, qi1, qi2, qo)
1898
+ self._throw_if_error()
1899
+
1900
+ def qxnor(self, qi1, qi2, qo):
1901
+ """Logical XOR
1902
+
1903
+ Logical exlusive-NOR of 2 qubits whose result is stored in the target
1904
+ qubit.
1905
+
1906
+ Args:
1907
+ qi1: qubit 1
1908
+ qi2: qubit 2
1909
+ qo: target qubit
1910
+
1911
+ Raises:
1912
+ RuntimeError: QrackSimulator raised an exception.
1913
+ """
1914
+ Qrack.qrack_lib.XNOR(self.sid, qi1, qi2, qo)
1915
+ self._throw_if_error()
1916
+
1917
+ def cland(self, ci, qi, qo):
1918
+ """Classical AND
1919
+
1920
+ Logical AND with one qubit and one classical bit whose result is
1921
+ stored in target qubit.
1922
+
1923
+ Args:
1924
+ qi1: qubit 1
1925
+ qi2: qubit 2
1926
+ qo: target qubit
1927
+
1928
+ Raises:
1929
+ RuntimeError: QrackSimulator raised an exception.
1930
+ """
1931
+ Qrack.qrack_lib.CLAND(self.sid, ci, qi, qo)
1932
+ self._throw_if_error()
1933
+
1934
+ def clor(self, ci, qi, qo):
1935
+ """Classical OR
1936
+
1937
+ Logical OR with one qubit and one classical bit whose result is
1938
+ stored in target qubit.
1939
+
1940
+ Args:
1941
+ qi1: qubit 1
1942
+ qi2: qubit 2
1943
+ qo: target qubit
1944
+
1945
+ Raises:
1946
+ RuntimeError: QrackSimulator raised an exception.
1947
+ """
1948
+ Qrack.qrack_lib.CLOR(self.sid, ci, qi, qo)
1949
+ self._throw_if_error()
1950
+
1951
+ def clxor(self, ci, qi, qo):
1952
+ """Classical XOR
1953
+
1954
+ Logical exlusive-OR with one qubit and one classical bit whose result is
1955
+ stored in target qubit.
1956
+
1957
+ Args:
1958
+ qi1: qubit 1
1959
+ qi2: qubit 2
1960
+ qo: target qubit
1961
+
1962
+ Raises:
1963
+ RuntimeError: QrackSimulator raised an exception.
1964
+ """
1965
+ Qrack.qrack_lib.CLXOR(self.sid, ci, qi, qo)
1966
+ self._throw_if_error()
1967
+
1968
+ def clnand(self, ci, qi, qo):
1969
+ """Classical NAND
1970
+
1971
+ Logical NAND with one qubit and one classical bit whose result is
1972
+ stored in target qubit.
1973
+
1974
+ Args:
1975
+ qi1: qubit 1
1976
+ qi2: qubit 2
1977
+ qo: target qubit
1978
+
1979
+ Raises:
1980
+ RuntimeError: QrackSimulator raised an exception.
1981
+ """
1982
+ Qrack.qrack_lib.CLNAND(self.sid, ci, qi, qo)
1983
+ self._throw_if_error()
1984
+
1985
+ def clnor(self, ci, qi, qo):
1986
+ """Classical NOR
1987
+
1988
+ Logical NOR with one qubit and one classical bit whose result is
1989
+ stored in target qubit.
1990
+
1991
+ Args:
1992
+ qi1: qubit 1
1993
+ qi2: qubit 2
1994
+ qo: target qubit
1995
+
1996
+ Raises:
1997
+ RuntimeError: QrackSimulator raised an exception.
1998
+ """
1999
+ Qrack.qrack_lib.CLNOR(self.sid, ci, qi, qo)
2000
+ self._throw_if_error()
2001
+
2002
+ def clxnor(self, ci, qi, qo):
2003
+ """Classical XNOR
2004
+
2005
+ Logical exlusive-NOR with one qubit and one classical bit whose result is
2006
+ stored in target qubit.
2007
+
2008
+ Args:
2009
+ qi1: qubit 1
2010
+ qi2: qubit 2
2011
+ qo: target qubit
2012
+
2013
+ Raises:
2014
+ RuntimeError: QrackSimulator raised an exception.
2015
+ """
2016
+ Qrack.qrack_lib.CLXNOR(self.sid, ci, qi, qo)
2017
+ self._throw_if_error()
2018
+
2019
+ # Particular Quantum Circuits
2020
+
2021
+ ## fourier transform
2022
+ def qft(self, qs):
2023
+ """Quantum Fourier Transform
2024
+
2025
+ Applies Quantum Fourier Transform on the list of qubits provided.
2026
+
2027
+ Args:
2028
+ qs: list of qubits
2029
+
2030
+ Raises:
2031
+ RuntimeError: QrackSimulator raised an exception.
2032
+ """
2033
+ Qrack.qrack_lib.QFT(self.sid, len(qs), self._ulonglong_byref(qs))
2034
+ self._throw_if_error()
2035
+
2036
+ def iqft(self, qs):
2037
+ """Inverse-quantum Fourier Transform
2038
+
2039
+ Applies Inverse-quantum Fourier Transform on the list of qubits
2040
+ provided.
2041
+
2042
+ Args:
2043
+ qs: list of qubits
2044
+
2045
+ Raises:
2046
+ RuntimeError: QrackSimulator raised an exception.
2047
+ """
2048
+ Qrack.qrack_lib.IQFT(self.sid, len(qs), self._ulonglong_byref(qs))
2049
+ self._throw_if_error()
2050
+
2051
+ # pseudo-quantum
2052
+
2053
+ ## allocate and release
2054
+ def allocate_qubit(self, qid):
2055
+ """Allocate Qubit
2056
+
2057
+ Allocate 1 new qubit with the given qubit ID.
2058
+
2059
+ Args:
2060
+ qid: qubit id
2061
+
2062
+ Raises:
2063
+ RuntimeError: QrackSimulator raised an exception.
2064
+ """
2065
+ Qrack.qrack_lib.allocateQubit(self.sid, qid)
2066
+ self._throw_if_error()
2067
+
2068
+ def release(self, q):
2069
+ """Release Qubit
2070
+
2071
+ Release qubit given by the given qubit ID.
2072
+
2073
+ Args:
2074
+ q: qubit id
2075
+
2076
+ Raises:
2077
+ RuntimeError: QrackSimulator raised an exception.
2078
+
2079
+ Returns:
2080
+ If the qubit was in `|0>` state with small tolerance.
2081
+ """
2082
+ result = Qrack.qrack_lib.release(self.sid, q)
2083
+ self._throw_if_error()
2084
+ return result
2085
+
2086
+ def num_qubits(self):
2087
+ """Get Qubit count
2088
+
2089
+ Returns the qubit count of the simulator.
2090
+
2091
+ Args:
2092
+ q: qubit id
2093
+
2094
+ Raises:
2095
+ RuntimeError: QrackSimulator raised an exception.
2096
+
2097
+ Returns:
2098
+ Qubit count of the simulator
2099
+ """
2100
+ result = Qrack.qrack_lib.num_qubits(self.sid)
2101
+ self._throw_if_error()
2102
+ return result
2103
+
2104
+ ## schmidt decomposition
2105
+ def compose(self, other, q):
2106
+ """Compose qubits
2107
+
2108
+ Compose quantum description of given qubit with the current system.
2109
+
2110
+ Args:
2111
+ q: qubit id
2112
+
2113
+ Raises:
2114
+ RuntimeError: QrackSimulator raised an exception.
2115
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot compose()! (Turn off just this option, in the constructor.)
2116
+ """
2117
+ if self.is_tensor_network:
2118
+ raise RuntimeError(
2119
+ "QrackSimulator with isTensorNetwork=True option cannot compose()! (Turn off just this option, in the constructor.)"
2120
+ )
2121
+
2122
+ Qrack.qrack_lib.Compose(self.sid, other.sid, self._ulonglong_byref(q))
2123
+ self._throw_if_error()
2124
+
2125
+ def decompose(self, q):
2126
+ """Decompose system
2127
+
2128
+ Decompose the given qubit out of the system.
2129
+ Warning: The qubit subsystem state must be separable, or the behavior
2130
+ of this method is undefined.
2131
+
2132
+ Args:
2133
+ q: qubit id
2134
+
2135
+ Raises:
2136
+ RuntimeError: QrackSimulator raised an exception.
2137
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot decompose()! (Turn off just this option, in the constructor.)
2138
+
2139
+ Returns:
2140
+ State of the systems.
2141
+ """
2142
+ if self.is_tensor_network:
2143
+ raise RuntimeError(
2144
+ "QrackSimulator with isTensorNetwork=True option cannot decompose()! (Turn off just this option, in the constructor.)"
2145
+ )
2146
+
2147
+ other = QrackSimulator()
2148
+ Qrack.qrack_lib.destroy(other.sid)
2149
+ l = len(q)
2150
+ other.sid = Qrack.qrack_lib.Decompose(self.sid, l, self._ulonglong_byref(q))
2151
+ self._throw_if_error()
2152
+ return other
2153
+
2154
+ def dispose(self, q):
2155
+ """Dispose qubits
2156
+
2157
+ Minimally decompose a set of contiguous bits from the separably
2158
+ composed unit, and discard the separable bits.
2159
+ Warning: The qubit subsystem state must be separable, or the behavior
2160
+ of this method is undefined.
2161
+
2162
+ Args:
2163
+ q: qubit
2164
+
2165
+ Raises:
2166
+ RuntimeError: QrackSimulator raised an exception.
2167
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot dispose()! (Turn off just this option, in the constructor.)
2168
+
2169
+ Returns:
2170
+ State of the systems.
2171
+ """
2172
+ if self.is_tensor_network:
2173
+ raise RuntimeError(
2174
+ "QrackSimulator with isTensorNetwork=True option cannot dispose()! (Turn off just this option, in the constructor.)"
2175
+ )
2176
+
2177
+ l = len(q)
2178
+ Qrack.qrack_lib.Dispose(self.sid, l, self._ulonglong_byref(q))
2179
+ self._throw_if_error()
2180
+
2181
+ ## miscellaneous
2182
+ def dump_ids(self):
2183
+ """Dump all IDs
2184
+
2185
+ Dump all IDs from the selected simulator ID into the callback.
2186
+
2187
+ Returns:
2188
+ List of ids
2189
+ """
2190
+ global ids_list
2191
+ global ids_list_index
2192
+ ids_list = [0] * self.num_qubits()
2193
+ ids_list_index = 0
2194
+ Qrack.qrack_lib.DumpIds(self.sid, self.dump_ids_callback)
2195
+ return ids_list
2196
+
2197
+ @ctypes.CFUNCTYPE(None, ctypes.c_ulonglong)
2198
+ def dump_ids_callback(i):
2199
+ """C callback function"""
2200
+ global ids_list
2201
+ global ids_list_index
2202
+ ids_list[ids_list_index] = i
2203
+ ids_list_index = ids_list_index + 1
2204
+
2205
+ def dump(self):
2206
+ """Dump state vector
2207
+
2208
+ Dump state vector from the selected simulator ID into the callback.
2209
+
2210
+ Returns:
2211
+ State vector list
2212
+ """
2213
+ global state_vec_list
2214
+ global state_vec_list_index
2215
+ global state_vec_probability
2216
+ state_vec_list = [complex(0, 0)] * (1 << self.num_qubits())
2217
+ state_vec_list_index = 0
2218
+ state_vec_probability = 0
2219
+ Qrack.qrack_lib.Dump(self.sid, self.dump_callback)
2220
+ return state_vec_list
2221
+
2222
+ @ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_double, ctypes.c_double)
2223
+ def dump_callback(r, i):
2224
+ """C callback function"""
2225
+ global state_vec_list
2226
+ global state_vec_list_index
2227
+ global state_vec_probability
2228
+ state_vec_list[state_vec_list_index] = complex(r, i)
2229
+ state_vec_list_index = state_vec_list_index + 1
2230
+ state_vec_probability = state_vec_probability + (r * r) + (i * i)
2231
+ if (1.0 - state_vec_probability) <= (7.0 / 3 - 4.0 / 3 - 1):
2232
+ return False
2233
+ return True
2234
+
2235
+ def in_ket(self, ket):
2236
+ """Set state vector
2237
+
2238
+ Set state vector for the selected simulator ID.
2239
+ Warning: State vector is not always the internal representation leading
2240
+ to sub-optimal performance of the method.
2241
+
2242
+ Args:
2243
+ ket: the state vector to which simulator will be set
2244
+
2245
+ Raises:
2246
+ RuntimeError: QrackSimulator raised an exception.
2247
+ """
2248
+ Qrack.qrack_lib.InKet(self.sid, self._qrack_complex_byref(ket))
2249
+ self._throw_if_error()
2250
+
2251
+ def out_ket(self):
2252
+ """Get state vector
2253
+
2254
+ Returns the raw state vector of the simulator.
2255
+ Warning: State vector is not always the internal representation leading
2256
+ to sub-optimal performance of the method.
2257
+
2258
+ Raises:
2259
+ RuntimeError: QrackSimulator raised an exception.
2260
+
2261
+ Returns:
2262
+ list representing the state vector.
2263
+ """
2264
+ amp_count = 1 << self.num_qubits()
2265
+ ket = self._qrack_complex_byref([complex(0, 0)] * amp_count)
2266
+ Qrack.qrack_lib.OutKet(self.sid, ket)
2267
+ self._throw_if_error()
2268
+ return [complex(r, i) for r, i in self._pairwise(ket)]
2269
+
2270
+ def out_probs(self):
2271
+ """Get basis dimension probabilities
2272
+
2273
+ Returns the probabilities of each basis dimension in the state vector
2274
+ of the simulator.
2275
+
2276
+ Raises:
2277
+ RuntimeError: QrackSimulator raised an exception.
2278
+
2279
+ Returns:
2280
+ list representing the basis dimension probabilities.
2281
+ """
2282
+ prob_count = 1 << self.num_qubits()
2283
+ probs = self._real1_byref([0.0] * prob_count)
2284
+ Qrack.qrack_lib.OutProbs(self.sid, probs)
2285
+ self._throw_if_error()
2286
+ return list(probs)
2287
+
2288
+ def prob_all(self, q):
2289
+ """Probabilities of all subset permutations
2290
+
2291
+ Get the probabilities of all permutations of the subset.
2292
+
2293
+ Args:
2294
+ q: list of qubit ids
2295
+
2296
+ Raises:
2297
+ RuntimeError: QrackSimulator raised an exception.
2298
+
2299
+ Returns:
2300
+ list representing the state vector.
2301
+ """
2302
+ probs = self._real1_byref([0.0] * (1 << len(q)))
2303
+ Qrack.qrack_lib.ProbAll(self.sid, len(q), self._ulonglong_byref(q), probs)
2304
+ self._throw_if_error()
2305
+ return list(probs)
2306
+
2307
+ def prob(self, q):
2308
+ """Probability of `|1>`
2309
+
2310
+ Get the probability that a qubit is in the `|1>` state.
2311
+
2312
+ Args:
2313
+ q: qubit id
2314
+
2315
+ Raises:
2316
+ RuntimeError: QrackSimulator raised an exception.
2317
+
2318
+ Returns:
2319
+ probability of qubit being in `|1>`
2320
+ """
2321
+ result = Qrack.qrack_lib.Prob(self.sid, q)
2322
+ self._throw_if_error()
2323
+ return result
2324
+
2325
+ def prob_rdm(self, q):
2326
+ """Probability of `|1>`, (tracing out the reduced
2327
+ density matrix without stabilizer ancillary qubits)
2328
+
2329
+ Get the probability that a qubit is in the `|1>` state.
2330
+
2331
+ Args:
2332
+ q: qubit id
2333
+
2334
+ Raises:
2335
+ RuntimeError: QrackSimulator raised an exception.
2336
+
2337
+ Returns:
2338
+ probability of qubit being in `|1>`
2339
+ """
2340
+ result = Qrack.qrack_lib.ProbRdm(self.sid, q)
2341
+ self._throw_if_error()
2342
+ return result
2343
+
2344
+ def prob_perm(self, q, c):
2345
+ """Probability of permutation
2346
+
2347
+ Get the probability that the qubit IDs in "q" have the truth values
2348
+ in "c", directly corresponding by list index.
2349
+
2350
+ Args:
2351
+ q: list of qubit ids
2352
+ c: list of qubit truth values bools
2353
+
2354
+ Raises:
2355
+ RuntimeError: QrackSimulator raised an exception.
2356
+
2357
+ Returns:
2358
+ probability that each qubit in "q[i]" has corresponding truth
2359
+ value in "c[i]", at once
2360
+ """
2361
+
2362
+ if len(q) != len(c):
2363
+ raise RuntimeError("prob_perm argument lengths do not match.")
2364
+ result = Qrack.qrack_lib.PermutationProb(
2365
+ self.sid, len(q), self._ulonglong_byref(q), self._bool_byref(c)
2366
+ )
2367
+ self._throw_if_error()
2368
+ return result
2369
+
2370
+ def prob_perm_rdm(self, q, c, r=True):
2371
+ """Probability of permutation, (tracing out the reduced
2372
+ density matrix without stabilizer ancillary qubits)
2373
+
2374
+ Get the probability that the qubit IDs in "q" have the truth
2375
+ values in "c", directly corresponding by list index.
2376
+
2377
+ Args:
2378
+ q: list of qubit ids
2379
+ c: list of qubit truth values bools
2380
+ r: round Rz gates down from T^(1/2)
2381
+
2382
+ Raises:
2383
+ RuntimeError: QrackSimulator raised an exception.
2384
+
2385
+ Returns:
2386
+ probability that each qubit in "q[i]" has corresponding truth
2387
+ value in "c[i]", at once
2388
+ """
2389
+
2390
+ if len(q) != len(c):
2391
+ raise RuntimeError("prob_perm argument lengths do not match.")
2392
+ result = Qrack.qrack_lib.PermutationProbRdm(
2393
+ self.sid, len(q), self._ulonglong_byref(q), self._bool_byref(c), r
2394
+ )
2395
+ self._throw_if_error()
2396
+ return result
2397
+
2398
+ def permutation_expectation(self, q):
2399
+ """Permutation expectation value
2400
+
2401
+ Get the permutation expectation value, based upon the order of
2402
+ input qubits.
2403
+
2404
+ Args:
2405
+ q: qubits, from low to high
2406
+
2407
+ Raises:
2408
+ RuntimeError: QrackSimulator raised an exception.
2409
+
2410
+ Returns:
2411
+ Expectation value
2412
+ """
2413
+ result = Qrack.qrack_lib.PermutationExpectation(
2414
+ self.sid, len(q), self._ulonglong_byref(q)
2415
+ )
2416
+ self._throw_if_error()
2417
+ return result
2418
+
2419
+ def permutation_expectation_rdm(self, q, r=True):
2420
+ """Permutation expectation value, (tracing out the reduced
2421
+ density matrix without stabilizer ancillary qubits)
2422
+
2423
+ Get the permutation expectation value, based upon the order of
2424
+ input qubits.
2425
+
2426
+ Args:
2427
+ q: qubits, from low to high
2428
+ r: round Rz gates down from T^(1/2)
2429
+
2430
+ Raises:
2431
+ RuntimeError: QrackSimulator raised an exception.
2432
+
2433
+ Returns:
2434
+ Expectation value
2435
+ """
2436
+ result = Qrack.qrack_lib.PermutationExpectationRdm(
2437
+ self.sid, len(q), self._ulonglong_byref(q), r
2438
+ )
2439
+ self._throw_if_error()
2440
+ return result
2441
+
2442
+ def factorized_expectation(self, q, c):
2443
+ """Factorized expectation value
2444
+
2445
+ Get the factorized expectation value, where each entry
2446
+ in "c" is an expectation value for corresponding "q"
2447
+ being false, then true, repeated for each in "q".
2448
+
2449
+ Args:
2450
+ q: qubits, from low to high
2451
+ c: qubit falsey/truthy values, from low to high
2452
+
2453
+ Raises:
2454
+ RuntimeError: QrackSimulator raised an exception.
2455
+
2456
+ Returns:
2457
+ Expectation value
2458
+ """
2459
+ if (len(q) << 1) != len(c):
2460
+ raise RuntimeError("factorized_expectation argument lengths do not match.")
2461
+ m = max([(x.bit_length() + 63) // 64 for x in c])
2462
+ result = Qrack.qrack_lib.FactorizedExpectation(
2463
+ self.sid, len(q), self._ulonglong_byref(q), m, self._to_ulonglong(m, c)
2464
+ )
2465
+ self._throw_if_error()
2466
+ return result
2467
+
2468
+ def factorized_expectation_rdm(self, q, c, r=True):
2469
+ """Factorized expectation value, (tracing out the reduced
2470
+ density matrix without stabilizer ancillary qubits)
2471
+
2472
+ Get the factorized expectation value, where each entry
2473
+ in "c" is an expectation value for corresponding "q"
2474
+ being false, then true, repeated for each in "q".
2475
+
2476
+ Args:
2477
+ q: qubits, from low to high
2478
+ c: qubit falsey/truthy values, from low to high
2479
+ r: round Rz gates down from T^(1/2)
2480
+
2481
+ Raises:
2482
+ RuntimeError: QrackSimulator raised an exception.
2483
+
2484
+ Returns:
2485
+ Expectation value
2486
+ """
2487
+ if (len(q) << 1) != len(c):
2488
+ raise RuntimeError(
2489
+ "factorized_expectation_rdm argument lengths do not match."
2490
+ )
2491
+ m = max([(x.bit_length() + 63) // 64 for x in c])
2492
+ result = Qrack.qrack_lib.FactorizedExpectationRdm(
2493
+ self.sid, len(q), self._ulonglong_byref(q), m, self._to_ulonglong(m, c), r
2494
+ )
2495
+ self._throw_if_error()
2496
+ return result
2497
+
2498
+ def factorized_expectation_fp(self, q, c):
2499
+ """Factorized expectation value (floating-point)
2500
+
2501
+ Get the factorized expectation value, where each entry
2502
+ in "c" is an expectation value for corresponding "q"
2503
+ being false, then true, repeated for each in "q".
2504
+
2505
+ Args:
2506
+ q: qubits, from low to high
2507
+ c: qubit falsey/truthy values, from low to high
2508
+
2509
+ Raises:
2510
+ RuntimeError: QrackSimulator raised an exception.
2511
+
2512
+ Returns:
2513
+ Expectation value
2514
+ """
2515
+ if (len(q) << 1) != len(c):
2516
+ raise RuntimeError(
2517
+ "factorized_expectation_rdm argument lengths do not match."
2518
+ )
2519
+ result = Qrack.qrack_lib.FactorizedExpectationFp(
2520
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(c)
2521
+ )
2522
+ self._throw_if_error()
2523
+ return result
2524
+
2525
+ def factorized_expectation_fp_rdm(self, q, c, r=True):
2526
+ """Factorized expectation value, (tracing out the reduced
2527
+ density matrix without stabilizer ancillary qubits)
2528
+
2529
+ Get the factorized expectation value, where each entry
2530
+ in "c" is an expectation value for corresponding "q"
2531
+ being false, then true, repeated for each in "q".
2532
+
2533
+ Args:
2534
+ q: qubits, from low to high
2535
+ c: qubit falsey/truthy values, from low to high
2536
+ r: round Rz gates down from T^(1/2)
2537
+
2538
+ Raises:
2539
+ RuntimeError: QrackSimulator raised an exception.
2540
+
2541
+ Returns:
2542
+ Expectation value
2543
+ """
2544
+ if (len(q) << 1) != len(c):
2545
+ raise RuntimeError(
2546
+ "factorized_expectation_fp_rdm argument lengths do not match."
2547
+ )
2548
+ result = Qrack.qrack_lib.FactorizedExpectationFpRdm(
2549
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(c), r
2550
+ )
2551
+ self._throw_if_error()
2552
+ return result
2553
+
2554
+ def unitary_expectation(self, q, b):
2555
+ """3-parameter unitary tensor product expectation value
2556
+
2557
+ Get the single-qubit (3-parameter) operator
2558
+ expectation value for the array of qubits and bases.
2559
+
2560
+ Args:
2561
+ q: qubits, from low to high
2562
+ b: 3-parameter, single-qubit, unitary bases (flat over wires)
2563
+
2564
+ Raises:
2565
+ RuntimeError: QrackSimulator raised an exception.
2566
+
2567
+ Returns:
2568
+ Expectation value
2569
+ """
2570
+ if (3 * len(q)) != len(b):
2571
+ raise RuntimeError("unitary_expectation argument lengths do not match.")
2572
+ result = Qrack.qrack_lib.UnitaryExpectation(
2573
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(b)
2574
+ )
2575
+ self._throw_if_error()
2576
+ return result
2577
+
2578
+ def matrix_expectation(self, q, b):
2579
+ """Single-qubit operator tensor product expectation value
2580
+
2581
+ Get the single-qubit (3-parameter) operator
2582
+ expectation value for the array of qubits and bases.
2583
+
2584
+ Args:
2585
+ q: qubits, from low to high
2586
+ b: single-qubit (2x2) operator unitary bases (flat over wires)
2587
+
2588
+ Raises:
2589
+ RuntimeError: QrackSimulator raised an exception.
2590
+
2591
+ Returns:
2592
+ Expectation value
2593
+ """
2594
+ if (len(q) << 2) != len(b):
2595
+ raise RuntimeError("matrix_expectation argument lengths do not match.")
2596
+ result = Qrack.qrack_lib.MatrixExpectation(
2597
+ self.sid, len(q), self._ulonglong_byref(q), self._complex_byref(b)
2598
+ )
2599
+ self._throw_if_error()
2600
+ return result
2601
+
2602
+ def unitary_expectation_eigenval(self, q, b, e):
2603
+ """3-parameter unitary tensor product expectation value
2604
+
2605
+ Get the single-qubit (3-parameter) operator
2606
+ expectation value for the array of qubits and bases.
2607
+
2608
+ Args:
2609
+ q: qubits, from low to high
2610
+ b: 3-parameter, single-qubit, unitary bases (flat over wires)
2611
+
2612
+ Raises:
2613
+ RuntimeError: QrackSimulator raised an exception.
2614
+
2615
+ Returns:
2616
+ Expectation value
2617
+ """
2618
+ if (3 * len(q)) != len(b):
2619
+ raise RuntimeError(
2620
+ "unitary_expectation_eigenval qubit and basis argument lengths do not match."
2621
+ )
2622
+ if (len(q) << 1) != len(e):
2623
+ raise RuntimeError(
2624
+ "unitary_expectation_eigenval qubit and eigenvalue argument lengths do not match."
2625
+ )
2626
+ result = Qrack.qrack_lib.UnitaryExpectationEigenVal(
2627
+ self.sid,
2628
+ len(q),
2629
+ self._ulonglong_byref(q),
2630
+ self._real1_byref(b),
2631
+ self._real1_byref(e),
2632
+ )
2633
+ self._throw_if_error()
2634
+ return result
2635
+
2636
+ def matrix_expectation_eigenval(self, q, b, e):
2637
+ """Single-qubit operator tensor product expectation value
2638
+
2639
+ Get the single-qubit (3-parameter) operator
2640
+ expectation value for the array of qubits and bases.
2641
+
2642
+ Args:
2643
+ q: qubits, from low to high
2644
+ b: single-qubit (2x2) operator unitary bases (flat over wires)
2645
+
2646
+ Raises:
2647
+ RuntimeError: QrackSimulator raised an exception.
2648
+
2649
+ Returns:
2650
+ Expectation value
2651
+ """
2652
+ if (len(q) << 2) != len(b):
2653
+ raise RuntimeError(
2654
+ "matrix_expectation_eigenval qubit and basis argument lengths do not match."
2655
+ )
2656
+ if (len(q) << 1) != len(e):
2657
+ raise RuntimeError(
2658
+ "matrix_expectation_eigenval qubit and eigenvalue argument lengths do not match."
2659
+ )
2660
+ result = Qrack.qrack_lib.MatrixExpectationEigenVal(
2661
+ self.sid,
2662
+ len(q),
2663
+ self._ulonglong_byref(q),
2664
+ self._complex_byref(b),
2665
+ self._real1_byref(e),
2666
+ )
2667
+ self._throw_if_error()
2668
+ return result
2669
+
2670
+ def pauli_expectation(self, q, b):
2671
+ """Pauli tensor product expectation value
2672
+
2673
+ Get the Pauli tensor product expectation value,
2674
+ where each entry in "b" is a Pauli observable for
2675
+ corresponding "q", as the product for each in "q".
2676
+
2677
+ Args:
2678
+ q: qubits, from low to high
2679
+ b: qubit Pauli bases
2680
+
2681
+ Raises:
2682
+ RuntimeError: QrackSimulator raised an exception.
2683
+
2684
+ Returns:
2685
+ Expectation value
2686
+ """
2687
+ if len(q) != len(b):
2688
+ raise RuntimeError("pauli_expectation argument lengths do not match.")
2689
+ result = Qrack.qrack_lib.PauliExpectation(
2690
+ self.sid, len(q), self._ulonglong_byref(q), self._ulonglong_byref(b)
2691
+ )
2692
+ self._throw_if_error()
2693
+ return result
2694
+
2695
+ def variance(self, q):
2696
+ """Variance of probabilities of all subset permutations
2697
+
2698
+ Get the overall variance of probabilities of all
2699
+ permutations of the subset.
2700
+
2701
+ Args:
2702
+ q: list of qubit ids
2703
+
2704
+ Raises:
2705
+ RuntimeError: QrackSimulator raised an exception.
2706
+
2707
+ Returns:
2708
+ float variance
2709
+ """
2710
+ result = Qrack.qrack_lib.Variance(self.sid, len(q), self._ulonglong_byref(q))
2711
+ self._throw_if_error()
2712
+ return result
2713
+
2714
+ def variance_rdm(self, q, r=True):
2715
+ """Permutation variance, (tracing out the reduced
2716
+ density matrix without stabilizer ancillary qubits)
2717
+
2718
+ Get the permutation variance, based upon the order of
2719
+ input qubits.
2720
+
2721
+ Args:
2722
+ q: qubits, from low to high
2723
+ r: round Rz gates down from T^(1/2)
2724
+
2725
+ Raises:
2726
+ RuntimeError: QrackSimulator raised an exception.
2727
+
2728
+ Returns:
2729
+ variance
2730
+ """
2731
+ result = Qrack.qrack_lib.VarianceRdm(
2732
+ self.sid, len(q), self._ulonglong_byref(q), r
2733
+ )
2734
+ self._throw_if_error()
2735
+ return result
2736
+
2737
+ def factorized_variance(self, q, c):
2738
+ """Factorized variance
2739
+
2740
+ Get the factorized variance, where each entry
2741
+ in "c" is an variance for corresponding "q"
2742
+ being false, then true, repeated for each in "q".
2743
+
2744
+ Args:
2745
+ q: qubits, from low to high
2746
+ c: qubit falsey/truthy values, from low to high
2747
+
2748
+ Raises:
2749
+ RuntimeError: QrackSimulator raised an exception.
2750
+
2751
+ Returns:
2752
+ variance
2753
+ """
2754
+ if (len(q) << 1) != len(c):
2755
+ raise RuntimeError("factorized_variance argument lengths do not match.")
2756
+ m = max([(x.bit_length() + 63) // 64 for x in c])
2757
+ result = Qrack.qrack_lib.FactorizedVariance(
2758
+ self.sid, len(q), self._ulonglong_byref(q), m, self._to_ulonglong(m, c)
2759
+ )
2760
+ self._throw_if_error()
2761
+ return result
2762
+
2763
+ def factorized_variance_rdm(self, q, c, r=True):
2764
+ """Factorized variance, (tracing out the reduced
2765
+ density matrix without stabilizer ancillary qubits)
2766
+
2767
+ Get the factorized variance, where each entry
2768
+ in "c" is an variance for corresponding "q"
2769
+ being false, then true, repeated for each in "q".
2770
+
2771
+ Args:
2772
+ q: qubits, from low to high
2773
+ c: qubit falsey/truthy values, from low to high
2774
+ r: round Rz gates down from T^(1/2)
2775
+
2776
+ Raises:
2777
+ RuntimeError: QrackSimulator raised an exception.
2778
+
2779
+ Returns:
2780
+ variance
2781
+ """
2782
+ if (len(q) << 1) != len(c):
2783
+ raise RuntimeError("factorized_variance_rdm argument lengths do not match.")
2784
+ m = max([(x.bit_length() + 63) // 64 for x in c])
2785
+ result = Qrack.qrack_lib.FactorizedVarianceRdm(
2786
+ self.sid, len(q), self._ulonglong_byref(q), m, self._to_ulonglong(m, c), r
2787
+ )
2788
+ self._throw_if_error()
2789
+ return result
2790
+
2791
+ def factorized_variance_fp(self, q, c):
2792
+ """Factorized variance (floating-point)
2793
+
2794
+ Get the factorized variance, where each entry
2795
+ in "c" is an variance for corresponding "q"
2796
+ being false, then true, repeated for each in "q".
2797
+
2798
+ Args:
2799
+ q: qubits, from low to high
2800
+ c: qubit falsey/truthy values, from low to high
2801
+
2802
+ Raises:
2803
+ RuntimeError: QrackSimulator raised an exception.
2804
+
2805
+ Returns:
2806
+ variance
2807
+ """
2808
+ if (len(q) << 1) != len(c):
2809
+ raise RuntimeError("factorized_variance_rdm argument lengths do not match.")
2810
+ result = Qrack.qrack_lib.FactorizedVarianceFp(
2811
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(c)
2812
+ )
2813
+ self._throw_if_error()
2814
+ return result
2815
+
2816
+ def factorized_variance_fp_rdm(self, q, c, r=True):
2817
+ """Factorized variance, (tracing out the reduced
2818
+ density matrix without stabilizer ancillary qubits)
2819
+
2820
+ Get the factorized variance, where each entry
2821
+ in "c" is an variance for corresponding "q"
2822
+ being false, then true, repeated for each in "q".
2823
+
2824
+ Args:
2825
+ q: qubits, from low to high
2826
+ c: qubit falsey/truthy values, from low to high
2827
+ r: round Rz gates down from T^(1/2)
2828
+
2829
+ Raises:
2830
+ RuntimeError: QrackSimulator raised an exception.
2831
+
2832
+ Returns:
2833
+ variance
2834
+ """
2835
+ if (len(q) << 1) != len(c):
2836
+ raise RuntimeError(
2837
+ "factorized_variance_fp_rdm argument lengths do not match."
2838
+ )
2839
+ result = Qrack.qrack_lib.FactorizedVarianceFpRdm(
2840
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(c), r
2841
+ )
2842
+ self._throw_if_error()
2843
+ return result
2844
+
2845
+ def unitary_variance(self, q, b):
2846
+ """3-parameter unitary tensor product variance
2847
+
2848
+ Get the single-qubit (3-parameter) operator
2849
+ variance for the array of qubits and bases.
2850
+
2851
+ Args:
2852
+ q: qubits, from low to high
2853
+ b: 3-parameter, single-qubit, unitary bases (flat over wires)
2854
+
2855
+ Raises:
2856
+ RuntimeError: QrackSimulator raised an exception.
2857
+
2858
+ Returns:
2859
+ variance
2860
+ """
2861
+ if (3 * len(q)) != len(b):
2862
+ raise RuntimeError("unitary_variance argument lengths do not match.")
2863
+ result = Qrack.qrack_lib.UnitaryVariance(
2864
+ self.sid, len(q), self._ulonglong_byref(q), self._real1_byref(b)
2865
+ )
2866
+ self._throw_if_error()
2867
+ return result
2868
+
2869
+ def matrix_variance(self, q, b):
2870
+ """Single-qubit operator tensor product variance
2871
+
2872
+ Get the single-qubit (3-parameter) operator
2873
+ variance for the array of qubits and bases.
2874
+
2875
+ Args:
2876
+ q: qubits, from low to high
2877
+ b: single-qubit (2x2) operator unitary bases (flat over wires)
2878
+
2879
+ Raises:
2880
+ RuntimeError: QrackSimulator raised an exception.
2881
+
2882
+ Returns:
2883
+ variance
2884
+ """
2885
+ if (len(q) << 2) != len(b):
2886
+ raise RuntimeError("matrix_variance argument lengths do not match.")
2887
+ result = Qrack.qrack_lib.MatrixVariance(
2888
+ self.sid, len(q), self._ulonglong_byref(q), self._complex_byref(b)
2889
+ )
2890
+ self._throw_if_error()
2891
+ return result
2892
+
2893
+ def unitary_variance_eigenval(self, q, b, e):
2894
+ """3-parameter unitary tensor product variance
2895
+
2896
+ Get the single-qubit (3-parameter) operator
2897
+ variance for the array of qubits and bases.
2898
+
2899
+ Args:
2900
+ q: qubits, from low to high
2901
+ b: 3-parameter, single-qubit, unitary bases (flat over wires)
2902
+
2903
+ Raises:
2904
+ RuntimeError: QrackSimulator raised an exception.
2905
+
2906
+ Returns:
2907
+ variance
2908
+ """
2909
+ if (3 * len(q)) != len(b):
2910
+ raise RuntimeError(
2911
+ "unitary_variance_eigenval qubit and basis argument lengths do not match."
2912
+ )
2913
+ if (len(q) << 1) != len(e):
2914
+ raise RuntimeError(
2915
+ "unitary_variance_eigenval qubit and eigenvalue argument lengths do not match."
2916
+ )
2917
+ result = Qrack.qrack_lib.UnitaryVarianceEigenVal(
2918
+ self.sid,
2919
+ len(q),
2920
+ self._ulonglong_byref(q),
2921
+ self._real1_byref(b),
2922
+ self._real1_byref(e),
2923
+ )
2924
+ self._throw_if_error()
2925
+ return result
2926
+
2927
+ def matrix_variance_eigenval(self, q, b, e):
2928
+ """Single-qubit operator tensor product variance
2929
+
2930
+ Get the single-qubit (3-parameter) operator
2931
+ variance for the array of qubits and bases.
2932
+
2933
+ Args:
2934
+ q: qubits, from low to high
2935
+ b: single-qubit (2x2) operator unitary bases (flat over wires)
2936
+
2937
+ Raises:
2938
+ RuntimeError: QrackSimulator raised an exception.
2939
+
2940
+ Returns:
2941
+ variance
2942
+ """
2943
+ if (len(q) << 2) != len(b):
2944
+ raise RuntimeError(
2945
+ "matrix_variance_eigenval qubit and basis argument lengths do not match."
2946
+ )
2947
+ if (len(q) << 1) != len(e):
2948
+ raise RuntimeError(
2949
+ "matrix_variance_eigenval qubit and eigenvalue argument lengths do not match."
2950
+ )
2951
+ result = Qrack.qrack_lib.MatrixVarianceEigenVal(
2952
+ self.sid,
2953
+ len(q),
2954
+ self._ulonglong_byref(q),
2955
+ self._complex_byref(b),
2956
+ self._real1_byref(e),
2957
+ )
2958
+ self._throw_if_error()
2959
+ return result
2960
+
2961
+ def pauli_variance(self, q, b):
2962
+ """Pauli tensor product variance
2963
+
2964
+ Get the Pauli tensor product variance,
2965
+ where each entry in "b" is a Pauli observable for
2966
+ corresponding "q", as the product for each in "q".
2967
+
2968
+ Args:
2969
+ q: qubits, from low to high
2970
+ b: qubit Pauli bases
2971
+
2972
+ Raises:
2973
+ RuntimeError: QrackSimulator raised an exception.
2974
+
2975
+ Returns:
2976
+ variance
2977
+ """
2978
+ if len(q) != len(b):
2979
+ raise RuntimeError("pauli_variance argument lengths do not match.")
2980
+ result = Qrack.qrack_lib.PauliVariance(
2981
+ self.sid, len(q), self._ulonglong_byref(q), self._ulonglong_byref(b)
2982
+ )
2983
+ self._throw_if_error()
2984
+ return result
2985
+
2986
+ def joint_ensemble_probability(self, b, q):
2987
+ """Ensemble probability
2988
+
2989
+ Find the joint probability for all specified qubits under the
2990
+ respective Pauli basis transformations.
2991
+
2992
+ Args:
2993
+ b: pauli basis
2994
+ q: specified qubits
2995
+
2996
+ Raises:
2997
+ RuntimeError: QrackSimulator raised an exception.
2998
+
2999
+ Returns:
3000
+ Variance
3001
+ """
3002
+ if len(b) != len(q):
3003
+ raise RuntimeError("Lengths of list parameters are mismatched.")
3004
+ result = Qrack.qrack_lib.JointEnsembleProbability(
3005
+ self.sid, len(b), self._ulonglong_byref(b), q
3006
+ )
3007
+ self._throw_if_error()
3008
+ return result
3009
+
3010
+ def phase_parity(self, la, q):
3011
+ """Phase to odd parity
3012
+
3013
+ Applies `e^(i*la)` phase factor to all combinations of bits with
3014
+ odd parity, based upon permutations of qubits.
3015
+
3016
+ Args:
3017
+ la: phase
3018
+ q: specified qubits
3019
+
3020
+ Raises:
3021
+ RuntimeError: QrackSimulator raised an exception.
3022
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot phase_parity()! (Turn off just this option, in the constructor.)
3023
+ """
3024
+ if self.is_tensor_network:
3025
+ raise RuntimeError(
3026
+ "QrackSimulator with isTensorNetwork=True option cannot phase_parity()! (Turn off just this option, in the constructor.)"
3027
+ )
3028
+ if self.is_pure_stabilizer:
3029
+ raise RuntimeError(
3030
+ "QrackStabilizer cannot phase_parity()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
3031
+ )
3032
+
3033
+ Qrack.qrack_lib.PhaseParity(
3034
+ self.sid, ctypes.c_double(la), len(q), self._ulonglong_byref(q)
3035
+ )
3036
+ self._throw_if_error()
3037
+
3038
+ def phase_root_n(self, n, q):
3039
+ """Phase to root n
3040
+
3041
+ Applies `-2 * math.pi / (2**N)` phase rotation to each qubit.
3042
+
3043
+ Args:
3044
+ n: Phase root
3045
+ q: specified qubits
3046
+
3047
+ Raises:
3048
+ RuntimeError: QrackSimulator raised an exception.
3049
+ RuntimeError: QrackSimulator with isTensorNetwork=True option cannot phase_root_n()! (Turn off just this option, in the constructor.)
3050
+ """
3051
+ if self.is_tensor_network:
3052
+ raise RuntimeError(
3053
+ "QrackSimulator with isTensorNetwork=True option cannot phase_root_n()! (Turn off just this option, in the constructor.)"
3054
+ )
3055
+ if self.is_pure_stabilizer:
3056
+ raise RuntimeError(
3057
+ "QrackStabilizer cannot phase_root_n()! (Create a QrackSimulator instead, also with isTensorNetwork=False.)"
3058
+ )
3059
+
3060
+ Qrack.qrack_lib.PhaseRootN(self.sid, n, len(q), self._ulonglong_byref(q))
3061
+ self._throw_if_error()
3062
+
3063
+ def try_separate_1qb(self, qi1):
3064
+ """Manual seperation
3065
+
3066
+ Exposes manual control for schmidt decomposition which attempts to
3067
+ decompose the qubit with possible performance improvement
3068
+
3069
+ Args:
3070
+ qi1: qubit to be decomposed
3071
+
3072
+ Raises:
3073
+ RuntimeError: QrackSimulator raised an exception.
3074
+
3075
+ Returns:
3076
+ State of the qubit.
3077
+ """
3078
+ result = Qrack.qrack_lib.TrySeparate1Qb(self.sid, qi1)
3079
+ self._throw_if_error()
3080
+ return result
3081
+
3082
+ def try_separate_2qb(self, qi1, qi2):
3083
+ """Manual two-qubits seperation
3084
+
3085
+ two-qubits counterpart of `try_separate_1qb`.
3086
+
3087
+ Args:
3088
+ qi1: first qubit to be decomposed
3089
+ qi2: second qubit to be decomposed
3090
+
3091
+ Raises:
3092
+ Runtimeerror: QrackSimulator raised an exception.
3093
+
3094
+ Returns:
3095
+ State of both the qubits.
3096
+ """
3097
+ result = Qrack.qrack_lib.TrySeparate2Qb(self.sid, qi1, qi2)
3098
+ self._throw_if_error()
3099
+ return result
3100
+
3101
+ def try_separate_tolerance(self, qs, t):
3102
+ """Manual multi-qubits seperation
3103
+
3104
+ Multi-qubits counterpart of `try_separate_1qb`.
3105
+
3106
+ Args:
3107
+ qs: list of qubits to be decomposed
3108
+ t: allowed tolerance
3109
+
3110
+ Raises:
3111
+ Runtimeerror: QrackSimulator raised an exception.
3112
+
3113
+ Returns:
3114
+ State of all the qubits.
3115
+ """
3116
+ result = Qrack.qrack_lib.TrySeparateTol(
3117
+ self.sid, len(qs), self._ulonglong_byref(qs), t
3118
+ )
3119
+ self._throw_if_error()
3120
+ return result
3121
+
3122
+ def separate(self, qs):
3123
+ """Force manual multi-qubits seperation
3124
+
3125
+ Force separation as per `try_separate_tolerance`.
3126
+
3127
+ Args:
3128
+ qs: list of qubits to be decomposed
3129
+
3130
+ Raises:
3131
+ Runtimeerror: QrackSimulator raised an exception.
3132
+ """
3133
+ result = Qrack.qrack_lib.Separate(self.sid, len(qs), self._ulonglong_byref(qs))
3134
+ self._throw_if_error()
3135
+
3136
+ def get_unitary_fidelity(self):
3137
+ """Get fidelity estimate
3138
+
3139
+ When using "Schmidt decomposition rounding parameter" ("SDRP")
3140
+ approximate simulation, QrackSimulator() can make an excellent
3141
+ estimate of its overall fidelity at any time, tested against a
3142
+ nearest-neighbor variant of quantum volume circuits.
3143
+
3144
+ Resetting the fidelity calculation to 1.0 happens automatically
3145
+ when calling `mall` are can be done manually with
3146
+ `reset_unitary_fidelity()`.
3147
+
3148
+ Raises:
3149
+ RuntimeError: QrackSimulator raised an exception.
3150
+
3151
+ Returns:
3152
+ Fidelity estimate
3153
+ """
3154
+ result = Qrack.qrack_lib.GetUnitaryFidelity(self.sid)
3155
+ self._throw_if_error()
3156
+ return result
3157
+
3158
+ def reset_unitary_fidelity(self):
3159
+ """Reset fidelity estimate
3160
+
3161
+ When using "Schmidt decomposition rounding parameter" ("SDRP")
3162
+ approximate simulation, QrackSimulator() can make an excellent
3163
+ estimate of its overall fidelity at any time, tested against a
3164
+ nearest-neighbor variant of quantum volume circuits.
3165
+
3166
+ Resetting the fidelity calculation to 1.0 happens automatically
3167
+ when calling `m_all` or can be done manually with
3168
+ `reset_unitary_fidelity()`.
3169
+
3170
+ Raises:
3171
+ RuntimeError: QrackSimulator raised an exception.
3172
+ """
3173
+ Qrack.qrack_lib.ResetUnitaryFidelity(self.sid)
3174
+ self._throw_if_error()
3175
+
3176
+ def set_sdrp(self, sdrp):
3177
+ """Set "Schmidt decomposition rounding parameter"
3178
+
3179
+ When using "Schmidt decomposition rounding parameter" ("SDRP")
3180
+ approximate simulation, QrackSimulator() can make an excellent
3181
+ estimate of its overall fidelity at any time, tested against a
3182
+ nearest-neighbor variant of quantum volume circuits.
3183
+
3184
+ Resetting the fidelity calculation to 1.0 happens automatically
3185
+ when calling `m_all` or can be done manually with
3186
+ `reset_unitary_fidelity()`.
3187
+
3188
+ Raises:
3189
+ RuntimeError: QrackSimulator raised an exception.
3190
+ """
3191
+ Qrack.qrack_lib.SetSdrp(self.sid, sdrp)
3192
+ self._throw_if_error()
3193
+
3194
+ def set_ncrp(self, ncrp):
3195
+ """Set "Near-Clifford rounding parameter"
3196
+
3197
+ When using "near-Clifford rounding parameter" ("NCRP")
3198
+ approximate simulation, QrackSimulator() can make an excellent
3199
+ estimate of its overall fidelity after measurement, tested against
3200
+ a nearest-neighbor variant of quantum volume circuits.
3201
+
3202
+ Resetting the fidelity calculation to 1.0 happens automatically
3203
+ when calling `m_all` or can be done manually with
3204
+ `reset_unitary_fidelity()`.
3205
+
3206
+ Raises:
3207
+ RuntimeError: QrackSimulator raised an exception.
3208
+ """
3209
+ Qrack.qrack_lib.SetNcrp(self.sid, ncrp)
3210
+ self._throw_if_error()
3211
+
3212
+ def set_reactive_separate(self, irs):
3213
+ """Set reactive separation option
3214
+
3215
+ If reactive separation is available, then this method turns it off/on.
3216
+ Note that reactive separation is on by default.
3217
+
3218
+ Args:
3219
+ irs: is aggresively separable
3220
+
3221
+ Raises:
3222
+ RuntimeError: QrackSimulator raised an exception.
3223
+ """
3224
+ Qrack.qrack_lib.SetReactiveSeparate(self.sid, irs)
3225
+ self._throw_if_error()
3226
+
3227
+ def set_t_injection(self, iti):
3228
+ """Set t-injection option
3229
+
3230
+ If t-injection is available, then this method turns it off/on.
3231
+ Note that t-injection is on by default.
3232
+
3233
+ Args:
3234
+ iti: use "reverse t-injection gadget"
3235
+
3236
+ Raises:
3237
+ RuntimeError: QrackSimulator raised an exception.
3238
+ """
3239
+ Qrack.qrack_lib.SetTInjection(self.sid, iti)
3240
+ self._throw_if_error()
3241
+
3242
+ def set_noise_parameter(self, np):
3243
+ """Set noise parameter option
3244
+
3245
+ If noisy simulation is on, then this set the depolarization
3246
+ parameter per qubit per gate. (Default is 0.01.)
3247
+
3248
+ Args:
3249
+ np: depolarizing noise parameter
3250
+
3251
+ Raises:
3252
+ RuntimeError: QrackSimulator raised an exception.
3253
+ """
3254
+ Qrack.qrack_lib.SetNoiseParameter(self.sid, np)
3255
+ self._throw_if_error()
3256
+
3257
+ def normalize(self):
3258
+ """Normalize the state
3259
+
3260
+ This should never be necessary to use unless
3261
+ decompose() is "abused." ("Abusing" decompose()
3262
+ might lead to efficient entanglement-breaking
3263
+ channels, though.)
3264
+
3265
+ Raises:
3266
+ RuntimeError: QrackSimulator raised an exception.
3267
+ """
3268
+ Qrack.qrack_lib.Normalize(self.sid)
3269
+ self._throw_if_error()
3270
+
3271
+ def out_to_file(self, filename):
3272
+ """Output state to file (stabilizer only!)
3273
+
3274
+ Outputs the hybrid stabilizer state to file.
3275
+
3276
+ Args:
3277
+ filename: Name of file
3278
+ """
3279
+ Qrack.qrack_lib.qstabilizer_out_to_file(self.sid, filename.encode("utf-8"))
3280
+ self._throw_if_error()
3281
+
3282
+ def in_from_file(
3283
+ filename,
3284
+ is_binary_decision_tree=False,
3285
+ is_paged=True,
3286
+ is_cpu_gpu_hybrid=False,
3287
+ is_opencl=True,
3288
+ is_host_pointer=False,
3289
+ is_noisy=False,
3290
+ ):
3291
+ """Input state from file (stabilizer only!)
3292
+
3293
+ Reads in a hybrid stabilizer state from file.
3294
+
3295
+ Args:
3296
+ filename: Name of file
3297
+ """
3298
+ qb_count = 1
3299
+ with open(filename) as f:
3300
+ qb_count = int(f.readline())
3301
+ out = QrackSimulator(
3302
+ qubitCount=qb_count,
3303
+ isTensorNetwork=False,
3304
+ isSchmidtDecomposeMulti=False,
3305
+ isSchmidtDecompose=False,
3306
+ isStabilizerHybrid=True,
3307
+ isBinaryDecisionTree=is_binary_decision_tree,
3308
+ isPaged=is_paged,
3309
+ isCpuGpuHybrid=is_cpu_gpu_hybrid,
3310
+ isOpenCL=is_opencl,
3311
+ isHostPointer=is_host_pointer,
3312
+ isNoisy=is_noisy,
3313
+ )
3314
+ Qrack.qrack_lib.qstabilizer_in_from_file(out.sid, filename.encode("utf-8"))
3315
+ out._throw_if_error()
3316
+
3317
+ return out
3318
+
3319
+ def file_to_qiskit_circuit(filename, is_hardware_encoded=False):
3320
+ """Convert an output state file to a Qiskit circuit
3321
+
3322
+ Reads in an (optimized) circuit from a file named
3323
+ according to the "filename" parameter and outputs
3324
+ a Qiskit circuit.
3325
+
3326
+ Args:
3327
+ filename: Name of file
3328
+
3329
+ Raises:
3330
+ RuntimeErorr: Before trying to file_to_qiskit_circuit() with
3331
+ QrackCircuit, you must install Qiskit, numpy, and math!
3332
+ """
3333
+ if not (_IS_QISKIT_AVAILABLE and _IS_NUMPY_AVAILABLE):
3334
+ raise RuntimeError(
3335
+ "Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!"
3336
+ )
3337
+
3338
+ lines = []
3339
+ with open(filename, "r") as file:
3340
+ lines = file.readlines()
3341
+
3342
+ logical_qubits = int(lines[0])
3343
+ stabilizer_qubits = int(lines[1])
3344
+
3345
+ stabilizer_count = int(lines[2])
3346
+
3347
+ clifford_circ = None
3348
+ line_number = 3
3349
+ for i in range(stabilizer_count):
3350
+ shard_map_size = int(lines[line_number])
3351
+ line_number += 1
3352
+
3353
+ shard_map = {}
3354
+ for j in range(shard_map_size):
3355
+ line = lines[line_number].split()
3356
+ line_number += 1
3357
+ shard_map[int(line[0])] = int(line[1])
3358
+
3359
+ line_number += 1
3360
+ tableau = []
3361
+ row_count = shard_map_size << 1
3362
+ for line in lines[line_number : (line_number + row_count)]:
3363
+ bits = line.split()
3364
+ if len(bits) != (row_count + 1):
3365
+ raise QrackException("Invalid Qrack hybrid stabilizer file!")
3366
+ row = []
3367
+ for b in range(row_count):
3368
+ row.append(bool(int(bits[b])))
3369
+ row.append(bool((int(bits[-1]) >> 1) & 1))
3370
+ tableau.append(row)
3371
+ line_number += shard_map_size << 1
3372
+ tableau = np.array(tableau, bool)
3373
+
3374
+ clifford = Clifford(tableau, validate=False, copy=False)
3375
+ clifford_circ = clifford.to_circuit()
3376
+ clifford_circ = QrackSimulator._reorder_qubits(clifford_circ, shard_map)
3377
+
3378
+ non_clifford_gates = []
3379
+ g = 0
3380
+ for line in lines[line_number:]:
3381
+ i = 0
3382
+ tokens = line.split()
3383
+ op = np.zeros((2, 2), dtype=complex)
3384
+ row = []
3385
+ for _ in range(2):
3386
+ amp = tokens[i].replace("(", "").replace(")", "").split(",")
3387
+ row.append(float(amp[0]) + float(amp[1]) * 1j)
3388
+ i = i + 1
3389
+ l = math.sqrt(np.real(row[0] * np.conj(row[0]) + row[1] * np.conj(row[1])))
3390
+ op[0][0] = row[0] / l
3391
+ op[0][1] = row[1] / l
3392
+
3393
+ if np.abs(op[0][0] - row[0]) > 1e-5:
3394
+ print("Warning: gate ", str(g), " might not be unitary!")
3395
+ if np.abs(op[0][1] - row[1]) > 1e-5:
3396
+ print("Warning: gate ", str(g), " might not be unitary!")
3397
+
3398
+ row = []
3399
+ for _ in range(2):
3400
+ amp = tokens[i].replace("(", "").replace(")", "").split(",")
3401
+ row.append(float(amp[0]) + float(amp[1]) * 1j)
3402
+ i = i + 1
3403
+ l = math.sqrt(np.real(row[0] * np.conj(row[0]) + row[1] * np.conj(row[1])))
3404
+ op[1][0] = row[0] / l
3405
+ op[1][1] = row[1] / l
3406
+
3407
+ ph = np.real(np.log(np.linalg.det(op)) / 1j)
3408
+
3409
+ op[1][0] = -np.exp(1j * ph) * np.conj(op[0][1])
3410
+ op[1][1] = np.exp(1j * ph) * np.conj(op[0][0])
3411
+
3412
+ if np.abs(op[1][0] - row[0]) > 1e-5:
3413
+ print("Warning: gate ", str(g), " might not be unitary!")
3414
+ if np.abs(op[1][1] - row[1]) > 1e-5:
3415
+ print("Warning: gate ", str(g), " might not be unitary!")
3416
+
3417
+ non_clifford_gates.append(op)
3418
+ g = g + 1
3419
+
3420
+ basis_gates = [
3421
+ "rz",
3422
+ "h",
3423
+ "x",
3424
+ "y",
3425
+ "z",
3426
+ "sx",
3427
+ "sxdg",
3428
+ "s",
3429
+ "sdg",
3430
+ "t",
3431
+ "tdg",
3432
+ "cx",
3433
+ "cy",
3434
+ "cz",
3435
+ "swap",
3436
+ ]
3437
+ try:
3438
+ circ = transpile(
3439
+ clifford_circ, basis_gates=basis_gates, optimization_level=2
3440
+ )
3441
+ except:
3442
+ circ = clifford_circ
3443
+
3444
+ for i in range(len(non_clifford_gates)):
3445
+ circ.unitary(non_clifford_gates[i], [i])
3446
+
3447
+ if is_hardware_encoded:
3448
+ for i in range(logical_qubits, stabilizer_qubits, 2):
3449
+ circ.h(i + 1)
3450
+ circ.cz(i, i + 1)
3451
+ circ.h(i + 1)
3452
+
3453
+ return circ
3454
+
3455
+ def _reorder_qubits(circuit, mapping):
3456
+ """
3457
+ Reorders qubits in the circuit according to the given mapping using SWAP gates.
3458
+ (Thanks to "Elara," an OpenAI GPT, for this implementation)
3459
+
3460
+ Parameters:
3461
+ - circuit (QuantumCircuit): The circuit to modify.
3462
+ - mapping (dict): Dictionary mapping internal qubit indices to logical qubit indices.
3463
+
3464
+ Returns:
3465
+ - QuantumCircuit: The modified circuit with qubits reordered.
3466
+ """
3467
+ swaps = []
3468
+
3469
+ # Determine swaps to fix the order
3470
+ for logical_index in sorted(mapping):
3471
+ internal_index = mapping[logical_index]
3472
+ if logical_index != internal_index:
3473
+ swaps.append((logical_index, internal_index))
3474
+ # Update the reverse mapping for subsequent swaps
3475
+ mapping[logical_index] = logical_index
3476
+ mapping[internal_index] = internal_index
3477
+
3478
+ # Apply the swaps to the circuit
3479
+ for qubit1, qubit2 in swaps:
3480
+ circuit.swap(qubit1, qubit2)
3481
+
3482
+ return circuit
3483
+
3484
+ def file_to_optimized_qiskit_circuit(filename):
3485
+ """Convert an output state file to a Qiskit circuit
3486
+
3487
+ Reads in a circuit from a file named according to the "filename"
3488
+ parameter and outputs a 'hyper-optimized' Qiskit circuit that
3489
+ favors maximum reduction in gate count and depth at the potential
3490
+ expense of additional non-Clifford gates. (Ancilla qubits are
3491
+ left included in the output, though they probably have no gates.)
3492
+
3493
+ Args:
3494
+ filename: Name of file
3495
+
3496
+ Raises:
3497
+ RuntimeErorr: Before trying to file_to_qiskit_circuit() with
3498
+ QrackCircuit, you must install Qiskit, numpy, and math!
3499
+ """
3500
+ circ = QrackSimulator.file_to_qiskit_circuit(filename)
3501
+
3502
+ width = 0
3503
+ with open(filename, "r", encoding="utf-8") as file:
3504
+ width = int(file.readline())
3505
+
3506
+ sqrt_pi = np.sqrt(1j)
3507
+ sqrt_ni = np.sqrt(-1j)
3508
+ sqrt1_2 = 1 / math.sqrt(2)
3509
+ ident = np.eye(2, dtype=np.complex128)
3510
+ # passable_gates = ["unitary", "rz", "h", "x", "y", "z", "sx", "sxdg", "s", "sdg", "t", "tdg"]
3511
+
3512
+ passed_swaps = []
3513
+ for i in range(0, circ.width()):
3514
+ # We might trace out swap, but we want to maintain the iteration order of qubit channels.
3515
+ non_clifford = np.copy(ident)
3516
+ j = 0
3517
+ while j < len(circ.data):
3518
+ op = circ.data[j].operation
3519
+ qubits = circ.data[j].qubits
3520
+ if len(qubits) > 2:
3521
+ raise RuntimeError(
3522
+ "Something went wrong while optimizing circuit! (Found a gate with 3 or more qubits)"
3523
+ )
3524
+ q1 = circ.find_bit(qubits[0])[0]
3525
+ if (len(qubits) < 2) and (q1 == i):
3526
+ if op.name == "unitary":
3527
+ non_clifford = np.matmul(op.params[0], non_clifford)
3528
+ elif op.name == "rz":
3529
+ lm = float(op.params[0])
3530
+ non_clifford = np.matmul(
3531
+ [[np.exp(-1j * lm / 2), 0], [0, np.exp(1j * lm / 2)]],
3532
+ non_clifford,
3533
+ )
3534
+ elif op.name == "h":
3535
+ non_clifford = np.matmul(
3536
+ np.array(
3537
+ [[sqrt1_2, sqrt1_2], [sqrt1_2, -sqrt1_2]], np.complex128
3538
+ ),
3539
+ non_clifford,
3540
+ )
3541
+ elif op.name == "x":
3542
+ non_clifford = np.matmul(
3543
+ np.array([[0, 1], [1, 0]], np.complex128), non_clifford
3544
+ )
3545
+ elif op.name == "y":
3546
+ non_clifford = np.matmul(
3547
+ np.array([[0, -1j], [1j, 0]], np.complex128), non_clifford
3548
+ )
3549
+ elif op.name == "z":
3550
+ non_clifford = np.matmul(
3551
+ np.array([[1, 0], [0, -1]], np.complex128), non_clifford
3552
+ )
3553
+ elif op.name == "sx":
3554
+ non_clifford = np.matmul(
3555
+ np.array(
3556
+ [
3557
+ [(1 + 1j) / 2, (1 - 1j) / 2],
3558
+ [(1 - 1j) / 2, (1 + 1j) / 2],
3559
+ ],
3560
+ np.complex128,
3561
+ ),
3562
+ non_clifford,
3563
+ )
3564
+ elif op.name == "sxdg":
3565
+ non_clifford = np.matmul(
3566
+ np.array(
3567
+ [
3568
+ [(1 - 1j) / 2, (1 + 1j) / 2],
3569
+ [(1 + 1j) / 2, (1 - 1j) / 2],
3570
+ ],
3571
+ np.complex128,
3572
+ ),
3573
+ non_clifford,
3574
+ )
3575
+ elif op.name == "sy":
3576
+ non_clifford = np.matmul(
3577
+ np.array(
3578
+ [
3579
+ [(1 + 1j) / 2, -(1 + 1j) / 2],
3580
+ [(1 + 1j) / 2, (1 + 1j) / 2],
3581
+ ],
3582
+ np.complex128,
3583
+ ),
3584
+ non_clifford,
3585
+ )
3586
+ elif op.name == "sydg":
3587
+ non_clifford = np.matmul(
3588
+ np.array(
3589
+ [
3590
+ [(1 - 1j) / 2, (1 - 1j) / 2],
3591
+ [(-1 + 1j) / 2, (1 - 1j) / 2],
3592
+ ],
3593
+ np.complex128,
3594
+ ),
3595
+ non_clifford,
3596
+ )
3597
+ elif op.name == "s":
3598
+ non_clifford = np.matmul(
3599
+ np.array([[1, 0], [0, 1j]], np.complex128), non_clifford
3600
+ )
3601
+ elif op.name == "sdg":
3602
+ non_clifford = np.matmul(
3603
+ np.array([[1, 0], [0, -1j]], np.complex128), non_clifford
3604
+ )
3605
+ elif op.name == "t":
3606
+ non_clifford = np.matmul(
3607
+ np.array([[1, 0], [0, sqrt_pi]], np.complex128),
3608
+ non_clifford,
3609
+ )
3610
+ elif op.name == "tdg":
3611
+ non_clifford = np.matmul(
3612
+ np.array([[1, 0], [0, sqrt_ni]], np.complex128),
3613
+ non_clifford,
3614
+ )
3615
+ else:
3616
+ raise RuntimeError(
3617
+ "Something went wrong while optimizing circuit! (Dropped a single-qubit gate.)"
3618
+ )
3619
+
3620
+ del circ.data[j]
3621
+ continue
3622
+
3623
+ if len(qubits) < 2:
3624
+ j += 1
3625
+ continue
3626
+
3627
+ q2 = circ.find_bit(qubits[1])[0]
3628
+
3629
+ if (i != q1) and (i != q2):
3630
+ j += 1
3631
+ continue
3632
+
3633
+ if op.name == "swap":
3634
+ i = q2 if i == q1 else q1
3635
+
3636
+ if circ.data[j] in passed_swaps:
3637
+ passed_swaps.remove(circ.data[j])
3638
+ del circ.data[j]
3639
+ continue
3640
+
3641
+ passed_swaps.append(circ.data[j])
3642
+
3643
+ j += 1
3644
+ continue
3645
+
3646
+ if (q1 == i) and (
3647
+ (op.name == "cx") or (op.name == "cy") or (op.name == "cz")
3648
+ ):
3649
+ if np.isclose(np.abs(non_clifford[0][1]), 0) and np.isclose(
3650
+ np.abs(non_clifford[1][0]), 0
3651
+ ):
3652
+ # If we're not buffering anything but phase, the blocking gate has no effect, and we're safe to continue.
3653
+ del circ.data[j]
3654
+ continue
3655
+
3656
+ if np.isclose(np.abs(non_clifford[0][0]), 0) and np.isclose(
3657
+ np.abs(non_clifford[1][1]), 0
3658
+ ):
3659
+ # If we're buffering full negation (plus phase), the control qubit can be dropped.
3660
+ c = QuantumCircuit(circ.qubits)
3661
+ if op.name == "cx":
3662
+ c.x(qubits[1])
3663
+ elif op.name == "cy":
3664
+ c.y(qubits[1])
3665
+ else:
3666
+ c.z(qubits[1])
3667
+ circ.data[j] = copy.deepcopy(c.data[0])
3668
+
3669
+ j += 1
3670
+ continue
3671
+
3672
+ if np.allclose(non_clifford, ident):
3673
+ # No buffer content to write to circuit definition
3674
+ non_clifford = np.copy(ident)
3675
+ break
3676
+
3677
+ # We're blocked, so we insert our buffer at this place in the circuit definition.
3678
+ c = QuantumCircuit(circ.qubits)
3679
+ c.unitary(non_clifford, qubits[0])
3680
+ circ.data.insert(j, copy.deepcopy(c.data[0]))
3681
+
3682
+ non_clifford = np.copy(ident)
3683
+ break
3684
+
3685
+ if (j == len(circ.data)) and not np.allclose(non_clifford, ident):
3686
+ # We're at the end of the wire, so add the buffer gate.
3687
+ circ.unitary(non_clifford, i)
3688
+
3689
+ passed_swaps.clear()
3690
+ for i in range(width, circ.width()):
3691
+ # We might trace out swap, but we want to maintain the iteration order of qubit channels.
3692
+ non_clifford = np.copy(ident)
3693
+ j = len(circ.data) - 1
3694
+ while j >= 0:
3695
+ op = circ.data[j].operation
3696
+ qubits = circ.data[j].qubits
3697
+ if len(qubits) > 2:
3698
+ raise RuntimeError(
3699
+ "Something went wrong while optimizing circuit! (Found a gate with 3 or more qubits.)"
3700
+ )
3701
+ q1 = circ.find_bit(qubits[0])[0]
3702
+ if (len(qubits) < 2) and (q1 == i):
3703
+ if op.name == "unitary":
3704
+ non_clifford = np.matmul(non_clifford, op.params[0])
3705
+ elif op.name == "rz":
3706
+ lm = float(op.params[0])
3707
+ non_clifford = np.matmul(
3708
+ non_clifford,
3709
+ [[np.exp(-1j * lm / 2), 0], [0, np.exp(1j * lm / 2)]],
3710
+ )
3711
+ elif op.name == "h":
3712
+ non_clifford = np.matmul(
3713
+ non_clifford,
3714
+ np.array(
3715
+ [[sqrt1_2, sqrt1_2], [sqrt1_2, -sqrt1_2]], np.complex128
3716
+ ),
3717
+ )
3718
+ elif op.name == "x":
3719
+ non_clifford = np.matmul(
3720
+ non_clifford, np.array([[0, 1], [1, 0]], np.complex128)
3721
+ )
3722
+ elif op.name == "y":
3723
+ non_clifford = np.matmul(
3724
+ non_clifford, np.array([[0, -1j], [1j, 0]], np.complex128)
3725
+ )
3726
+ elif op.name == "z":
3727
+ non_clifford = np.matmul(
3728
+ non_clifford, np.array([[1, 0], [0, -1]], np.complex128)
3729
+ )
3730
+ elif op.name == "sx":
3731
+ non_clifford = np.matmul(
3732
+ non_clifford,
3733
+ np.array(
3734
+ [
3735
+ [(1 + 1j) / 2, (1 - 1j) / 2],
3736
+ [(1 - 1j) / 2, (1 + 1j) / 2],
3737
+ ],
3738
+ np.complex128,
3739
+ ),
3740
+ )
3741
+ elif op.name == "sxdg":
3742
+ non_clifford = np.matmul(
3743
+ non_clifford,
3744
+ np.array(
3745
+ [
3746
+ [(1 - 1j) / 2, (1 + 1j) / 2],
3747
+ [(1 + 1j) / 2, (1 - 1j) / 2],
3748
+ ],
3749
+ np.complex128,
3750
+ ),
3751
+ )
3752
+ elif op.name == "sy":
3753
+ non_clifford = np.matmul(
3754
+ non_clifford,
3755
+ np.array(
3756
+ [
3757
+ [(1 + 1j) / 2, -(1 + 1j) / 2],
3758
+ [(1 + 1j) / 2, (1 + 1j) / 2],
3759
+ ],
3760
+ np.complex128,
3761
+ ),
3762
+ )
3763
+ elif op.name == "sydg":
3764
+ non_clifford = np.matmul(
3765
+ non_clifford,
3766
+ np.array(
3767
+ [
3768
+ [(1 - 1j) / 2, (1 - 1j) / 2],
3769
+ [(-1 + 1j) / 2, (1 - 1j) / 2],
3770
+ ],
3771
+ np.complex128,
3772
+ ),
3773
+ )
3774
+ elif op.name == "s":
3775
+ non_clifford = np.matmul(
3776
+ non_clifford, np.array([[1, 0], [0, 1j]], np.complex128)
3777
+ )
3778
+ elif op.name == "sdg":
3779
+ non_clifford = np.matmul(
3780
+ non_clifford, np.array([[1, 0], [0, -1j]], np.complex128)
3781
+ )
3782
+ elif op.name == "t":
3783
+ non_clifford = np.matmul(
3784
+ non_clifford,
3785
+ np.array([[1, 0], [0, sqrt_pi]], np.complex128),
3786
+ )
3787
+ elif op.name == "tdg":
3788
+ non_clifford = np.matmul(
3789
+ non_clifford,
3790
+ np.array([[1, 0], [0, sqrt_ni]], np.complex128),
3791
+ )
3792
+ else:
3793
+ raise RuntimeError(
3794
+ "Something went wrong while optimizing circuit! (Dropped a single-qubit gate.)"
3795
+ )
3796
+
3797
+ del circ.data[j]
3798
+ j -= 1
3799
+ continue
3800
+
3801
+ if len(qubits) < 2:
3802
+ j -= 1
3803
+ continue
3804
+
3805
+ q2 = circ.find_bit(qubits[1])[0]
3806
+
3807
+ if (i != q1) and (i != q2):
3808
+ j -= 1
3809
+ continue
3810
+
3811
+ if (op.name == "swap") and (q1 >= width) and (q2 >= width):
3812
+ i = q2 if i == q1 else q1
3813
+ if circ.data[j] in passed_swaps:
3814
+ passed_swaps.remove(circ.data[j])
3815
+ del circ.data[j]
3816
+ else:
3817
+ passed_swaps.append(circ.data[j])
3818
+
3819
+ j -= 1
3820
+ continue
3821
+
3822
+ if (
3823
+ (q1 == i)
3824
+ and ((op.name == "cx") or (op.name == "cy") or (op.name == "cz"))
3825
+ and (
3826
+ np.isclose(np.abs(non_clifford[0][1]), 0)
3827
+ and np.isclose(np.abs(non_clifford[1][0]), 0)
3828
+ )
3829
+ ):
3830
+ # If we're not buffering anything but phase, this commutes with control, and we're safe to continue.
3831
+ j -= 1
3832
+ continue
3833
+
3834
+ if (q1 == i) and (op.name == "cx"):
3835
+ orig_instr = circ.data[j]
3836
+ del circ.data[j]
3837
+
3838
+ # We're replacing CNOT with CNOT in the opposite direction plus four H gates
3839
+ rep = QuantumCircuit(circ.qubits)
3840
+ rep.h(qubits[0])
3841
+ circ.data.insert(j, copy.deepcopy(rep.data[0]))
3842
+ rep.h(qubits[1])
3843
+ circ.data.insert(j, copy.deepcopy(rep.data[1]))
3844
+ rep.cx(qubits[1], qubits[0])
3845
+ circ.data.insert(j, copy.deepcopy(rep.data[2]))
3846
+ rep.h(qubits[0])
3847
+ circ.data.insert(j, copy.deepcopy(rep.data[3]))
3848
+ rep.h(qubits[1])
3849
+ circ.data.insert(j, copy.deepcopy(rep.data[4]))
3850
+
3851
+ j += 4
3852
+ continue
3853
+
3854
+ if (q1 == i) or (op.name != "cx"):
3855
+ if np.allclose(non_clifford, ident):
3856
+ # No buffer content to write to circuit definition
3857
+ break
3858
+
3859
+ # We're blocked, so we insert our buffer at this place in the circuit definition.
3860
+ c = QuantumCircuit(circ.qubits)
3861
+ c.unitary(non_clifford, qubits[0])
3862
+ circ.data.insert(j + 1, copy.deepcopy(c.data[0]))
3863
+
3864
+ break
3865
+
3866
+ # Re-injection branch (apply gadget to target)
3867
+ to_inject = np.matmul(
3868
+ non_clifford, np.array([[sqrt1_2, sqrt1_2], [sqrt1_2, -sqrt1_2]])
3869
+ )
3870
+ if np.allclose(to_inject, ident):
3871
+ # No buffer content to write to circuit definition
3872
+ del circ.data[j]
3873
+ j -= 1
3874
+ continue
3875
+
3876
+ c = QuantumCircuit(circ.qubits)
3877
+ c.unitary(to_inject, qubits[0])
3878
+ circ.data.insert(j, copy.deepcopy(c.data[0]))
3879
+ j -= 1
3880
+
3881
+ basis_gates = [
3882
+ "u",
3883
+ "rz",
3884
+ "h",
3885
+ "x",
3886
+ "y",
3887
+ "z",
3888
+ "sx",
3889
+ "sxdg",
3890
+ "s",
3891
+ "sdg",
3892
+ "t",
3893
+ "tdg",
3894
+ "cx",
3895
+ "cy",
3896
+ "cz",
3897
+ "swap",
3898
+ ]
3899
+ circ = transpile(circ, basis_gates=basis_gates, optimization_level=2)
3900
+
3901
+ # Eliminate unused ancillae
3902
+ try:
3903
+ qasm = qasm3.dumps(circ)
3904
+ except:
3905
+ qasm = circ.qasm()
3906
+ qasm = qasm.replace(
3907
+ "qreg q[" + str(circ.width()) + "];", "qreg q[" + str(width) + "];"
3908
+ )
3909
+ highest_index = max(
3910
+ [int(x) for x in re.findall(r"\[(.*?)\]", qasm) if x.isdigit()]
3911
+ )
3912
+ if highest_index != width:
3913
+ qasm = qasm.replace(
3914
+ "qreg q[" + str(width) + "];", "qreg q[" + str(highest_index) + "];"
3915
+ )
3916
+
3917
+ orig_circ = circ
3918
+ try:
3919
+ circ = QuantumCircuit.from_qasm_str(qasm)
3920
+ except:
3921
+ circ = orig_circ
3922
+
3923
+ return circ
3924
+
3925
+ def _apply_pyzx_op(self, gate):
3926
+ if gate.name == "XPhase":
3927
+ self.r(Pauli.PauliX, math.pi * gate.phase, gate.target)
3928
+ elif gate.name == "ZPhase":
3929
+ self.r(Pauli.PauliZ, math.pi * gate.phase, gate.target)
3930
+ elif gate.name == "Z":
3931
+ self.z(gate.target)
3932
+ elif gate.name == "S":
3933
+ self.s(gate.target)
3934
+ elif gate.name == "T":
3935
+ self.t(gate.target)
3936
+ elif gate.name == "NOT":
3937
+ self.x(gate.target)
3938
+ elif gate.name == "HAD":
3939
+ self.h(gate.target)
3940
+ elif gate.name == "CNOT":
3941
+ self.mcx([gate.control], gate.target)
3942
+ elif gate.name == "CZ":
3943
+ self.mcz([gate.control], gate.target)
3944
+ elif gate.name == "CX":
3945
+ self.h(gate.control)
3946
+ self.mcx([gate.control], gate.target)
3947
+ self.h(gate.control)
3948
+ elif gate.name == "SWAP":
3949
+ self.swap(gate.control, gate.target)
3950
+ elif gate.name == "CRZ":
3951
+ self.mcr(Pauli.PauliZ, math.pi * gate.phase, [gate.control], gate.target)
3952
+ elif gate.name == "CHAD":
3953
+ self.mch([gate.control], gate.target)
3954
+ elif gate.name == "ParityPhase":
3955
+ self.phase_parity(math.pi * gate.phase, gate.targets)
3956
+ elif gate.name == "FSim":
3957
+ self.fsim(gate.theta, gate.phi, gate.control, gate.target)
3958
+ elif gate.name == "CCZ":
3959
+ self.mcz([gate.ctrl1, gate.ctrl2], gate.target)
3960
+ elif gate.name == "Tof":
3961
+ self.mcx([gate.ctrl1, gate.ctrl2], gate.target)
3962
+ self._throw_if_error()
3963
+
3964
+ def run_pyzx_gates(self, gates):
3965
+ """PYZX Gates
3966
+
3967
+ Converts PYZX gates to `QRackSimulator` and immediately executes them.
3968
+
3969
+ Args:
3970
+ gates: list of PYZX gates
3971
+
3972
+ Raises:
3973
+ RuntimeError: QrackSimulator raised an exception.
3974
+ """
3975
+ for gate in gates:
3976
+ self._apply_pyzx_op(gate)
3977
+
3978
+ def _apply_op(self, operation):
3979
+ name = operation.name
3980
+
3981
+ if (name == "id") or (name == "barrier"):
3982
+ # Skip measurement logic
3983
+ return
3984
+
3985
+ conditional = getattr(operation, "conditional", None)
3986
+ if isinstance(conditional, int):
3987
+ conditional_bit_set = (self._classical_register >> conditional) & 1
3988
+ if not conditional_bit_set:
3989
+ return
3990
+ elif conditional is not None:
3991
+ mask = int(conditional.mask, 16)
3992
+ if mask > 0:
3993
+ value = self._classical_memory & mask
3994
+ while (mask & 0x1) == 0:
3995
+ mask >>= 1
3996
+ value >>= 1
3997
+ if value != int(conditional.val, 16):
3998
+ return
3999
+
4000
+ if (name == "u1") or (name == "p"):
4001
+ self._sim.u(operation.qubits[0]._index, 0, 0, float(operation.params[0]))
4002
+ elif name == "u2":
4003
+ self._sim.u(
4004
+ operation.qubits[0]._index,
4005
+ math.pi / 2,
4006
+ float(operation.params[0]),
4007
+ float(operation.params[1]),
4008
+ )
4009
+ elif (name == "u3") or (name == "u"):
4010
+ self._sim.u(
4011
+ operation.qubits[0]._index,
4012
+ float(operation.params[0]),
4013
+ float(operation.params[1]),
4014
+ float(operation.params[2]),
4015
+ )
4016
+ elif (name == "unitary") and (len(operation.qubits) == 1):
4017
+ self._sim.mtrx(operation.params[0].flatten(), operation.qubits[0]._index)
4018
+ elif name == "r":
4019
+ self._sim.u(
4020
+ operation.qubits[0]._index,
4021
+ float(operation.params[0]),
4022
+ float(operation.params[1]) - math.pi / 2,
4023
+ (-1 * float(operation.params[1])) + math.pi / 2,
4024
+ )
4025
+ elif name == "rx":
4026
+ self._sim.r(
4027
+ Pauli.PauliX, float(operation.params[0]), operation.qubits[0]._index
4028
+ )
4029
+ elif name == "ry":
4030
+ self._sim.r(
4031
+ Pauli.PauliY, float(operation.params[0]), operation.qubits[0]._index
4032
+ )
4033
+ elif name == "rz":
4034
+ self._sim.r(
4035
+ Pauli.PauliZ, float(operation.params[0]), operation.qubits[0]._index
4036
+ )
4037
+ elif name == "h":
4038
+ self._sim.h(operation.qubits[0]._index)
4039
+ elif name == "x":
4040
+ self._sim.x(operation.qubits[0]._index)
4041
+ elif name == "y":
4042
+ self._sim.y(operation.qubits[0]._index)
4043
+ elif name == "z":
4044
+ self._sim.z(operation.qubits[0]._index)
4045
+ elif name == "s":
4046
+ self._sim.s(operation.qubits[0]._index)
4047
+ elif name == "sdg":
4048
+ self._sim.adjs(operation.qubits[0]._index)
4049
+ elif name == "sx":
4050
+ self._sim.mtrx(
4051
+ [(1 + 1j) / 2, (1 - 1j) / 2, (1 - 1j) / 2, (1 + 1j) / 2],
4052
+ operation.qubits[0]._index,
4053
+ )
4054
+ elif name == "sxdg":
4055
+ self._sim.mtrx(
4056
+ [(1 - 1j) / 2, (1 + 1j) / 2, (1 + 1j) / 2, (1 - 1j) / 2],
4057
+ operation.qubits[0]._index,
4058
+ )
4059
+ elif name == "t":
4060
+ self._sim.t(operation.qubits[0]._index)
4061
+ elif name == "tdg":
4062
+ self._sim.adjt(operation.qubits[0]._index)
4063
+ elif name == "cu1":
4064
+ self._sim.mcu(
4065
+ [q._index for q in operation.qubits[0:1]],
4066
+ operation.qubits[1]._index,
4067
+ 0,
4068
+ 0,
4069
+ float(operation.params[0]),
4070
+ )
4071
+ elif name == "cu2":
4072
+ self._sim.mcu(
4073
+ [q._index for q in operation.qubits[0:1]],
4074
+ operation.qubits[1]._index,
4075
+ math.pi / 2,
4076
+ float(operation.params[0]),
4077
+ float(operation.params[1]),
4078
+ )
4079
+ elif (name == "cu3") or (name == "cu"):
4080
+ self._sim.mcu(
4081
+ [q._index for q in operation.qubits[0:1]],
4082
+ operation.qubits[1]._index,
4083
+ float(operation.params[0]),
4084
+ float(operation.params[1]),
4085
+ float(operation.params[2]),
4086
+ )
4087
+ elif name == "cx":
4088
+ self._sim.mcx(
4089
+ [q._index for q in operation.qubits[0:1]], operation.qubits[1]._index
4090
+ )
4091
+ elif name == "cy":
4092
+ self._sim.mcy(
4093
+ [q._index for q in operation.qubits[0:1]], operation.qubits[1]._index
4094
+ )
4095
+ elif name == "cz":
4096
+ self._sim.mcz(
4097
+ [q._index for q in operation.qubits[0:1]], operation.qubits[1]._index
4098
+ )
4099
+ elif name == "ch":
4100
+ self._sim.mch(
4101
+ [q._index for q in operation.qubits[0:1]], operation.qubits[1]._index
4102
+ )
4103
+ elif name == "cp":
4104
+ self._sim.mcmtrx(
4105
+ [q._index for q in operation.qubits[0:1]],
4106
+ [
4107
+ 1,
4108
+ 0,
4109
+ 0,
4110
+ math.cos(float(operation.params[0]))
4111
+ + 1j * math.sin(float(operation.params[0])),
4112
+ ],
4113
+ operation.qubits[1]._index,
4114
+ )
4115
+ elif name == "csx":
4116
+ self._sim.mcmtrx(
4117
+ [q._index for q in operation.qubits[0:1]],
4118
+ [(1 + 1j) / 2, (1 - 1j) / 2, (1 - 1j) / 2, (1 + 1j) / 2],
4119
+ operation.qubits[1]._index,
4120
+ )
4121
+ elif name == "csxdg":
4122
+ self._sim.mcmtrx(
4123
+ [q._index for q in operation.qubits[0:1]],
4124
+ [(1 - 1j) / 2, (1 + 1j) / 2, (1 + 1j) / 2, (1 - 1j) / 2],
4125
+ operation.qubits[1]._index,
4126
+ )
4127
+ elif name == "dcx":
4128
+ self._sim.mcx(
4129
+ [q._index for q in operation.qubits[0:1]], operation.qubits[1]._index
4130
+ )
4131
+ self._sim.mcx(operation.qubits[1:2]._index, operation.qubits[0]._index)
4132
+ elif name == "ccx":
4133
+ self._sim.mcx(
4134
+ [q._index for q in operation.qubits[0:2]], operation.qubits[2]._index
4135
+ )
4136
+ elif name == "ccy":
4137
+ self._sim.mcy(
4138
+ [q._index for q in operation.qubits[0:2]], operation.qubits[2]._index
4139
+ )
4140
+ elif name == "ccz":
4141
+ self._sim.mcz(
4142
+ [q._index for q in operation.qubits[0:2]], operation.qubits[2]._index
4143
+ )
4144
+ elif name == "mcx":
4145
+ self._sim.mcx(
4146
+ [q._index for q in operation.qubits[0:-1]], operation.qubits[-1]._index
4147
+ )
4148
+ elif name == "mcy":
4149
+ self._sim.mcy(
4150
+ [q._index for q in operation.qubits[0:-1]], operation.qubits[-1]._index
4151
+ )
4152
+ elif name == "mcz":
4153
+ self._sim.mcz(
4154
+ [q._index for q in operation.qubits[0:-1]], operation.qubits[-1]._index
4155
+ )
4156
+ elif name == "swap":
4157
+ self._sim.swap(operation.qubits[0]._index, operation.qubits[1]._index)
4158
+ elif name == "iswap":
4159
+ self._sim.iswap(operation.qubits[0]._index, operation.qubits[1]._index)
4160
+ elif name == "iswap_dg":
4161
+ self._sim.adjiswap(operation.qubits[0]._index, operation.qubits[1]._index)
4162
+ elif name == "cswap":
4163
+ self._sim.cswap(
4164
+ [q._index for q in operation.qubits[0:1]],
4165
+ operation.qubits[1]._index,
4166
+ operation.qubits[2]._index,
4167
+ )
4168
+ elif name == "mcswap":
4169
+ self._sim.cswap(
4170
+ [q._index for q in operation.qubits[:-2]],
4171
+ operation.qubits[-2]._index,
4172
+ operation.qubits[-1]._index,
4173
+ )
4174
+ elif name == "reset":
4175
+ qubits = operation.qubits
4176
+ for qubit in qubits:
4177
+ if self._sim.m(qubit._index):
4178
+ self._sim.x(qubit._index)
4179
+ elif name == "measure":
4180
+ qubits = operation.qubits
4181
+ clbits = operation.clbits
4182
+ cregbits = (
4183
+ operation.register
4184
+ if hasattr(operation, "register")
4185
+ else len(operation.qubits) * [-1]
4186
+ )
4187
+
4188
+ self._sample_qubits += qubits
4189
+ self._sample_clbits += clbits
4190
+ self._sample_cregbits += cregbits
4191
+
4192
+ if not self._sample_measure:
4193
+ for index in range(len(qubits)):
4194
+ qubit_outcome = self._sim.m(qubits[index]._index)
4195
+
4196
+ clbit = clbits[index]
4197
+ clmask = 1 << clbit
4198
+ self._classical_memory = (self._classical_memory & (~clmask)) | (
4199
+ qubit_outcome << clbit
4200
+ )
4201
+
4202
+ cregbit = cregbits[index]
4203
+ if cregbit < 0:
4204
+ cregbit = clbit
4205
+
4206
+ regbit = 1 << cregbit
4207
+ self._classical_register = (
4208
+ self._classical_register & (~regbit)
4209
+ ) | (qubit_outcome << cregbit)
4210
+
4211
+ elif name == "bfunc":
4212
+ mask = int(operation.mask, 16)
4213
+ relation = operation.relation
4214
+ val = int(operation.val, 16)
4215
+
4216
+ cregbit = operation.register
4217
+ cmembit = operation.memory if hasattr(operation, "memory") else None
4218
+
4219
+ compared = (self._classical_register & mask) - val
4220
+
4221
+ if relation == "==":
4222
+ outcome = compared == 0
4223
+ elif relation == "!=":
4224
+ outcome = compared != 0
4225
+ elif relation == "<":
4226
+ outcome = compared < 0
4227
+ elif relation == "<=":
4228
+ outcome = compared <= 0
4229
+ elif relation == ">":
4230
+ outcome = compared > 0
4231
+ elif relation == ">=":
4232
+ outcome = compared >= 0
4233
+ else:
4234
+ raise QrackError("Invalid boolean function relation.")
4235
+
4236
+ # Store outcome in register and optionally memory slot
4237
+ regbit = 1 << cregbit
4238
+ self._classical_register = (self._classical_register & (~regbit)) | (
4239
+ int(outcome) << cregbit
4240
+ )
4241
+ if cmembit is not None:
4242
+ membit = 1 << cmembit
4243
+ self._classical_memory = (self._classical_memory & (~membit)) | (
4244
+ int(outcome) << cmembit
4245
+ )
4246
+ else:
4247
+ err_msg = 'QrackSimulator encountered unrecognized operation "{0}"'
4248
+ raise RuntimeError(err_msg.format(operation))
4249
+
4250
+ def _add_sample_measure(self, sample_qubits, sample_clbits, num_samples):
4251
+ """Generate data samples from current statevector.
4252
+
4253
+ Taken almost straight from the terra source code.
4254
+
4255
+ Args:
4256
+ measure_params (list): List of (qubit, clbit) values for
4257
+ measure instructions to sample.
4258
+ num_samples (int): The number of data samples to generate.
4259
+
4260
+ Returns:
4261
+ list: A list of data values in hex format.
4262
+ """
4263
+ # Get unique qubits that are actually measured
4264
+ measure_qubit = [qubit for qubit in sample_qubits]
4265
+ measure_clbit = [clbit for clbit in sample_clbits]
4266
+
4267
+ # Sample and convert to bit-strings
4268
+ if num_samples == 1:
4269
+ sample = self._sim.m_all()
4270
+ result = 0
4271
+ for index in range(len(measure_qubit)):
4272
+ qubit = measure_qubit[index]._index
4273
+ qubit_outcome = (sample >> qubit) & 1
4274
+ result |= qubit_outcome << index
4275
+ measure_results = [result]
4276
+ else:
4277
+ measure_results = self._sim.measure_shots(
4278
+ [q._index for q in measure_qubit], num_samples
4279
+ )
4280
+
4281
+ data = []
4282
+ for sample in measure_results:
4283
+ for index in range(len(measure_qubit)):
4284
+ qubit_outcome = (sample >> index) & 1
4285
+ clbit = measure_clbit[index]._index
4286
+ clmask = 1 << clbit
4287
+ self._classical_memory = (self._classical_memory & (~clmask)) | (
4288
+ qubit_outcome << clbit
4289
+ )
4290
+
4291
+ data.append(bin(self._classical_memory)[2:].zfill(self.num_qubits()))
4292
+
4293
+ return data
4294
+
4295
+ def run_qiskit_circuit(self, experiment, shots=1):
4296
+ if not _IS_QISKIT_AVAILABLE:
4297
+ raise RuntimeError(
4298
+ "Before trying to run_qiskit_circuit() with QrackSimulator, you must install Qiskit!"
4299
+ )
4300
+
4301
+ instructions = []
4302
+ if isinstance(experiment, QuantumCircuit):
4303
+ instructions = experiment.data
4304
+ else:
4305
+ raise RuntimeError('Unrecognized "run_input" argument specified for run().')
4306
+
4307
+ self._shots = shots
4308
+ self._sample_qubits = []
4309
+ self._sample_clbits = []
4310
+ self._sample_cregbits = []
4311
+ self._sample_measure = True
4312
+ _data = []
4313
+ shotLoopMax = 1
4314
+
4315
+ is_initializing = True
4316
+ boundary_start = -1
4317
+
4318
+ for opcount in range(len(instructions)):
4319
+ operation = instructions[opcount]
4320
+
4321
+ if operation.name == "id" or operation.name == "barrier":
4322
+ continue
4323
+
4324
+ if is_initializing and (
4325
+ (operation.name == "measure") or (operation.name == "reset")
4326
+ ):
4327
+ continue
4328
+
4329
+ is_initializing = False
4330
+
4331
+ if (operation.name == "measure") or (operation.name == "reset"):
4332
+ if boundary_start == -1:
4333
+ boundary_start = opcount
4334
+
4335
+ if (boundary_start != -1) and (operation.name != "measure"):
4336
+ shotsPerLoop = 1
4337
+ shotLoopMax = self._shots
4338
+ self._sample_measure = False
4339
+ break
4340
+
4341
+ preamble_memory = 0
4342
+ preamble_register = 0
4343
+ preamble_sim = None
4344
+
4345
+ if self._sample_measure or boundary_start <= 0:
4346
+ boundary_start = 0
4347
+ self._sample_measure = True
4348
+ shotsPerLoop = self._shots
4349
+ shotLoopMax = 1
4350
+ else:
4351
+ boundary_start -= 1
4352
+ if boundary_start > 0:
4353
+ self._sim = self
4354
+ self._classical_memory = 0
4355
+ self._classical_register = 0
4356
+
4357
+ for operation in instructions[:boundary_start]:
4358
+ self._apply_op(operation)
4359
+
4360
+ preamble_memory = self._classical_memory
4361
+ preamble_register = self._classical_register
4362
+ preamble_sim = self._sim
4363
+
4364
+ for shot in range(shotLoopMax):
4365
+ if preamble_sim is None:
4366
+ self._sim = self
4367
+ self._classical_memory = 0
4368
+ self._classical_register = 0
4369
+ else:
4370
+ self._sim = QrackSimulator(cloneSid=preamble_sim.sid)
4371
+ self._classical_memory = preamble_memory
4372
+ self._classical_register = preamble_register
4373
+
4374
+ for operation in instructions[boundary_start:]:
4375
+ self._apply_op(operation)
4376
+
4377
+ if not self._sample_measure and (len(self._sample_qubits) > 0):
4378
+ _data += [bin(self._classical_memory)[2:].zfill(self.num_qubits())]
4379
+ self._sample_qubits = []
4380
+ self._sample_clbits = []
4381
+ self._sample_cregbits = []
4382
+
4383
+ if self._sample_measure and (len(self._sample_qubits) > 0):
4384
+ _data = self._add_sample_measure(
4385
+ self._sample_qubits, self._sample_clbits, self._shots
4386
+ )
4387
+
4388
+ del self._sim
4389
+
4390
+ return _data
4391
+
4392
+ def get_qiskit_basis_gates():
4393
+ return [
4394
+ "id",
4395
+ "u",
4396
+ "u1",
4397
+ "u2",
4398
+ "u3",
4399
+ "r",
4400
+ "rx",
4401
+ "ry",
4402
+ "rz",
4403
+ "h",
4404
+ "x",
4405
+ "y",
4406
+ "z",
4407
+ "s",
4408
+ "sdg",
4409
+ "sx",
4410
+ "sxdg",
4411
+ "p",
4412
+ "t",
4413
+ "tdg",
4414
+ "cu",
4415
+ "cu1",
4416
+ "cu3",
4417
+ "cx",
4418
+ "cy",
4419
+ "cz",
4420
+ "ch",
4421
+ "cp",
4422
+ "csx",
4423
+ "ccx",
4424
+ "ccz",
4425
+ "swap",
4426
+ "iswap",
4427
+ "cswap",
4428
+ "reset",
4429
+ "measure",
4430
+ ]