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

pyqrack/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2021. 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
+ from .qrack_system import QrackSystem, Qrack
7
+ from .qrack_simulator import QrackSimulator
8
+ from .qrack_neuron import QrackNeuron
9
+ from .qrack_circuit import QrackCircuit
10
+ from .pauli import Pauli
11
+ from .neuron_activation_fn import NeuronActivationFn
12
+ from .quimb_circuit_type import QuimbCircuitType
13
+ from .util import convert_qiskit_circuit_to_qasm_experiment
@@ -0,0 +1,21 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2021. All rights reserved.
2
+ #
3
+ # Pauli operators are specified for "b" (or "basis") parameters.
4
+ #
5
+ # Use of this source code is governed by an MIT-style license that can be
6
+ # found in the LICENSE file or at https://opensource.org/licenses/MIT.
7
+
8
+ from enum import IntEnum
9
+
10
+
11
+ class NeuronActivationFn(IntEnum):
12
+ # Default
13
+ Sigmoid = 0
14
+ # Rectified linear
15
+ ReLU = 1
16
+ # Gaussian linear
17
+ GeLU = 2
18
+ # Version of (default) "Sigmoid" with tunable sharpness
19
+ Generalized_Logistic = 3
20
+ # Leaky rectified linear
21
+ LeakyReLU = 4
pyqrack/pauli.py ADDED
@@ -0,0 +1,19 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2021. All rights reserved.
2
+ #
3
+ # Pauli operators are specified for "b" (or "basis") parameters.
4
+ #
5
+ # Use of this source code is governed by an MIT-style license that can be
6
+ # found in the LICENSE file or at https://opensource.org/licenses/MIT.
7
+
8
+ from enum import IntEnum
9
+
10
+
11
+ class Pauli(IntEnum):
12
+ # Pauli Identity operator. Corresponds to Q# constant "PauliI."
13
+ PauliI = 0
14
+ # Pauli X operator. Corresponds to Q# constant "PauliX."
15
+ PauliX = 1
16
+ # Pauli Y operator. Corresponds to Q# constant "PauliY."
17
+ PauliY = 3
18
+ # Pauli Z operator. Corresponds to Q# constant "PauliZ."
19
+ PauliZ = 2
@@ -0,0 +1,473 @@
1
+ # (C) Daniel Strano and the Qrack contributors 2017-2023. 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 ctypes
7
+
8
+ from .qrack_system import Qrack
9
+ from .quimb_circuit_type import QuimbCircuitType
10
+
11
+ _IS_QISKIT_AVAILABLE = True
12
+ try:
13
+ from qiskit.circuit.quantumcircuit import QuantumCircuit
14
+ from qiskit.compiler.transpiler import transpile
15
+ from qiskit.circuit.library import UCGate
16
+ import numpy as np
17
+ import math
18
+ except ImportError:
19
+ _IS_QISKIT_AVAILABLE = False
20
+
21
+ _IS_QUIMB_AVAILABLE = True
22
+ try:
23
+ import quimb as qu
24
+ import quimb.tensor as qtn
25
+ except ImportError:
26
+ _IS_QUIMB_AVAILABLE = False
27
+
28
+ _IS_TENSORCIRCUIT_AVAILABLE = True
29
+ try:
30
+ import tensorcircuit as tc
31
+ except ImportError:
32
+ _IS_TENSORCIRCUIT_AVAILABLE = False
33
+
34
+ class QrackCircuit:
35
+ """Class that exposes the QCircuit class of Qrack
36
+
37
+ QrackCircuit allows the user to specify a unitary circuit, before running it.
38
+ Upon running the state, the result is a QrackSimulator state. Currently,
39
+ measurement is not supported, but measurement can be run on the resultant
40
+ QrackSimulator.
41
+
42
+ Attributes:
43
+ cid(int): Qrack ID of this circuit
44
+ """
45
+
46
+ def __init__(self, is_collapse = True, is_near_clifford = False, clone_cid = -1, is_inverse=False, past_light_cone = []):
47
+ if clone_cid < 0:
48
+ self.cid = Qrack.qrack_lib.init_qcircuit(is_collapse, is_near_clifford)
49
+ elif is_inverse:
50
+ self.cid = Qrack.qrack_lib.qcircuit_inverse(clone_cid)
51
+ elif len(past_light_cone) > 0:
52
+ self.cid = Qrack.qrack_lib.qcircuit_past_light_cone(clone_cid, len(past_light_cone), self._ulonglong_byref(past_light_cone))
53
+ else:
54
+ self.cid = Qrack.qrack_lib.init_qcircuit_clone(clone_cid)
55
+
56
+ def __del__(self):
57
+ if self.cid is not None:
58
+ Qrack.qrack_lib.destroy_qcircuit(self.cid)
59
+ self.cid = None
60
+
61
+ def _ulonglong_byref(self, a):
62
+ return (ctypes.c_ulonglong * len(a))(*a)
63
+
64
+ def _double_byref(self, a):
65
+ return (ctypes.c_double * len(a))(*a)
66
+
67
+ def _complex_byref(self, a):
68
+ t = [(c.real, c.imag) for c in a]
69
+ return self._double_byref([float(item) for sublist in t for item in sublist])
70
+
71
+ def clone(self):
72
+ """Make a new circuit that is an exact clone of this circuit
73
+
74
+ Raises:
75
+ RuntimeError: QrackCircuit C++ library raised an exception.
76
+ """
77
+ return QrackCircuit(clone_cid = self.cid, is_inverse = False)
78
+
79
+ def inverse(self):
80
+ """Make a new circuit that is the exact inverse of this circuit
81
+
82
+ Raises:
83
+ RuntimeError: QrackCircuit C++ library raised an exception.
84
+ """
85
+ return QrackCircuit(clone_cid = self.cid, is_inverse = True)
86
+
87
+ def past_light_cone(self, q):
88
+ """Make a new circuit with just this circuits' past light cone for certain qubits.
89
+
90
+ Args:
91
+ q: list of qubit indices to include at beginning of past light cone
92
+
93
+ Raises:
94
+ RuntimeError: QrackCircuit C++ library raised an exception.
95
+ """
96
+ return QrackCircuit(clone_cid = self.cid, is_inverse = False, past_light_cone = q)
97
+
98
+ def get_qubit_count(self):
99
+ """Get count of qubits in circuit
100
+
101
+ Raises:
102
+ RuntimeError: QrackCircuit C++ library raised an exception.
103
+ """
104
+ return Qrack.qrack_lib.get_qcircuit_qubit_count(self.cid)
105
+
106
+ def swap(self, q1, q2):
107
+ """Add a 'Swap' gate to the circuit
108
+
109
+ Args:
110
+ q1: qubit index #1
111
+ q2: qubit index #2
112
+
113
+ Raises:
114
+ RuntimeError: QrackCircuit C++ library raised an exception.
115
+ """
116
+ Qrack.qrack_lib.qcircuit_swap(self.cid, q1, q2)
117
+
118
+ def mtrx(self, m, q):
119
+ """Operation from matrix.
120
+
121
+ Applies arbitrary operation defined by the given matrix.
122
+
123
+ Args:
124
+ m: row-major complex list representing the operator.
125
+ q: the qubit number on which the gate is applied to.
126
+
127
+ Raises:
128
+ ValueError: 2x2 matrix 'm' in QrackCircuit.mtrx() must contain at least 4 elements.
129
+ RuntimeError: QrackSimulator raised an exception.
130
+ """
131
+ if len(m) < 4:
132
+ raise ValueError("2x2 matrix 'm' in QrackCircuit.mtrx() must contain at least 4 elements.")
133
+ Qrack.qrack_lib.qcircuit_append_1qb(self.cid, self._complex_byref(m), q)
134
+
135
+ def ucmtrx(self, c, m, q, p):
136
+ """Multi-controlled single-target-qubit gate
137
+
138
+ Specify a controlled gate by its control qubits, its single-qubit
139
+ matrix "payload," the target qubit, and the permutation of qubits
140
+ that activates the gate.
141
+
142
+ Args:
143
+ c: list of controlled qubits
144
+ m: row-major complex list representing the operator.
145
+ q: target qubit
146
+ p: permutation of target qubits
147
+
148
+ Raises:
149
+ ValueError: 2x2 matrix 'm' in QrackCircuit.ucmtrx() must contain at least 4 elements.
150
+ RuntimeError: QrackSimulator raised an exception.
151
+ """
152
+ if len(m) < 4:
153
+ raise ValueError("2x2 matrix 'm' in QrackCircuit.ucmtrx() must contain at least 4 elements.")
154
+ Qrack.qrack_lib.qcircuit_append_mc(
155
+ self.cid, self._complex_byref(m), len(c), self._ulonglong_byref(c), q, p
156
+ )
157
+
158
+ def run(self, qsim):
159
+ """Run circuit on simulator
160
+
161
+ Run the encoded circuit on a specific simulator. The
162
+ result will remain in this simulator.
163
+
164
+ Args:
165
+ qsim: QrackSimulator on which to run circuit
166
+
167
+ Raises:
168
+ RuntimeError: QrackCircuit raised an exception.
169
+ """
170
+ qb_count = self.get_qubit_count()
171
+ sim_qb_count = qsim.num_qubits()
172
+ if sim_qb_count < qb_count:
173
+ for i in range(sim_qb_count, qb_count):
174
+ qsim.allocate_qubit(i)
175
+ Qrack.qrack_lib.qcircuit_run(self.cid, qsim.sid)
176
+ qsim._throw_if_error()
177
+
178
+ def out_to_file(self, filename):
179
+ """Output optimized circuit to file
180
+
181
+ Outputs the (optimized) circuit to a file named
182
+ according to the "filename" parameter.
183
+
184
+ Args:
185
+ filename: Name of file
186
+ """
187
+ Qrack.qrack_lib.qcircuit_out_to_file(self.cid, filename.encode('utf-8'))
188
+
189
+ def in_from_file(filename):
190
+ """Read in optimized circuit from file
191
+
192
+ Reads in an (optimized) circuit from a file named
193
+ according to the "filename" parameter.
194
+
195
+ Args:
196
+ filename: Name of file
197
+ """
198
+ out = QrackCircuit()
199
+ Qrack.qrack_lib.qcircuit_in_from_file(out.cid, filename.encode('utf-8'))
200
+
201
+ return out
202
+
203
+ def file_to_qiskit_circuit(filename):
204
+ """Convert an output file to a Qiskit circuit
205
+
206
+ Reads in an (optimized) circuit from a file named
207
+ according to the "filename" parameter and outputs
208
+ a Qiskit circuit.
209
+
210
+ Args:
211
+ filename: Name of file
212
+
213
+ Raises:
214
+ RuntimeErorr: Before trying to file_to_qiskit_circuit() with
215
+ QrackCircuit, you must install Qiskit, numpy, and math!
216
+ """
217
+ if not _IS_QISKIT_AVAILABLE:
218
+ raise RuntimeError(
219
+ "Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!"
220
+ )
221
+
222
+ tokens = []
223
+ with open(filename, 'r') as file:
224
+ tokens = file.read().split()
225
+
226
+ i = 0
227
+ num_qubits = int(tokens[i])
228
+ i = i + 1
229
+ circ = QuantumCircuit(num_qubits)
230
+
231
+ num_gates = int(tokens[i])
232
+ i = i + 1
233
+
234
+ for g in range(num_gates):
235
+ target = int(tokens[i])
236
+ i = i + 1
237
+
238
+ control_count = int(tokens[i])
239
+ i = i + 1
240
+ controls = []
241
+ for j in range(control_count):
242
+ controls.append(int(tokens[i]))
243
+ i = i + 1
244
+
245
+ payload_count = int(tokens[i])
246
+ i = i + 1
247
+ payloads = {}
248
+ for j in range(payload_count):
249
+ key = int(tokens[i])
250
+ i = i + 1
251
+ op = np.zeros((2,2), dtype=complex)
252
+ row = []
253
+ for _ in range(2):
254
+ amp = tokens[i].replace("(","").replace(")","").split(',')
255
+ row.append(float(amp[0]) + float(amp[1])*1j)
256
+ i = i + 1
257
+ l = math.sqrt(np.real(row[0] * np.conj(row[0]) + row[1] * np.conj(row[1])))
258
+ op[0][0] = row[0] / l
259
+ op[0][1] = row[1] / l
260
+
261
+ if np.abs(op[0][0] - row[0]) > 1e-5:
262
+ print("Warning: gate ", str(g), ", payload ", str(j), " might not be unitary!")
263
+ if np.abs(op[0][1] - row[1]) > 1e-5:
264
+ print("Warning: gate ", str(g), ", payload ", str(j), " might not be unitary!")
265
+
266
+ row = []
267
+ for _ in range(2):
268
+ amp = tokens[i].replace("(","").replace(")","").split(',')
269
+ row.append(float(amp[0]) + float(amp[1])*1j)
270
+ i = i + 1
271
+ l = math.sqrt(np.real(row[0] * np.conj(row[0]) + row[1] * np.conj(row[1])))
272
+ op[1][0] = row[0] / l
273
+ op[1][1] = row[1] / l
274
+
275
+ ph = np.real(np.log(np.linalg.det(op)) / 1j)
276
+
277
+ op[1][0] = -np.exp(1j * ph) * np.conj(op[0][1])
278
+ op[1][1] = np.exp(1j * ph) * np.conj(op[0][0])
279
+
280
+ if np.abs(op[1][0] - row[0]) > 1e-5:
281
+ print("Warning: gate ", str(g), ", payload ", str(j), " might not be unitary!")
282
+ if np.abs(op[1][1] - row[1]) > 1e-5:
283
+ print("Warning: gate ", str(g), ", payload ", str(j), " might not be unitary!")
284
+
285
+ # Qiskit has a lower tolerance for deviation from numerically unitary.
286
+ payloads[key] = np.array(op)
287
+
288
+ gate_list = []
289
+ for j in range(1 << control_count):
290
+ if j in payloads:
291
+ gate_list.append(payloads[j])
292
+ else:
293
+ gate_list.append(np.array([[1, 0],[0, 1]]))
294
+
295
+ circ.append(UCGate(gate_list), controls + [target])
296
+
297
+ return circ
298
+
299
+ def in_from_qiskit_circuit(circ):
300
+ """Read a Qiskit circuit into a QrackCircuit
301
+
302
+ Reads in a circuit from a Qiskit `QuantumCircuit`
303
+
304
+ Args:
305
+ circ: Qiskit circuit
306
+
307
+ Raises:
308
+ RuntimeErorr: Before trying to file_to_qiskit_circuit() with
309
+ QrackCircuit, you must install Qiskit, numpy, and math!
310
+ """
311
+ if not _IS_QISKIT_AVAILABLE:
312
+ raise RuntimeError(
313
+ "Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!"
314
+ )
315
+
316
+ out = QrackCircuit()
317
+
318
+ basis_gates = ["u", "cx"]
319
+ circ = transpile(circ, basis_gates=basis_gates, optimization_level=3)
320
+ for gate in circ.data:
321
+ o = gate.operation
322
+ if o.name == "u":
323
+ th = float(o.params[0])
324
+ ph = float(o.params[1])
325
+ lm = float(o.params[2])
326
+
327
+ c = math.cos(th / 2)
328
+ s = math.sin(th / 2)
329
+
330
+ op = [
331
+ c + 0j,
332
+ -np.exp(1j * lm) * s,
333
+ np.exp(1j * ph) * s,
334
+ np.exp(1j * (ph + lm)) * c
335
+ ]
336
+ out.mtrx(op, circ.find_bit(gate.qubits[0])[0])
337
+ else:
338
+ ctrls = []
339
+ for c in gate.qubits[0:1]:
340
+ ctrls.append(circ.find_bit(c)[0])
341
+ out.ucmtrx(ctrls, [0, 1, 1, 0], circ.find_bit(gate.qubits[1])[0], 1)
342
+
343
+ return out
344
+
345
+ def file_to_quimb_circuit(
346
+ filename,
347
+ circuit_type=QuimbCircuitType.Circuit,
348
+ psi0=None,
349
+ gate_opts=None,
350
+ tags=None,
351
+ psi0_dtype='complex128',
352
+ psi0_tag='PSI0',
353
+ bra_site_ind_id='b{}'
354
+ ):
355
+ """Convert an output file to a Quimb circuit
356
+
357
+ Reads in an (optimized) circuit from a file named
358
+ according to the "filename" parameter and outputs
359
+ a Quimb circuit.
360
+
361
+ Args:
362
+ filename: Name of file
363
+ circuit_type: "QuimbCircuitType" enum value specifying type of Quimb circuit
364
+ psi0: The initial state, assumed to be |00000....0> if not given. The state is always copied and the tag PSI0 added
365
+ gate_opts: Default keyword arguments to supply to each gate_TN_1D() call during the circuit
366
+ tags: Tag(s) to add to the initial wavefunction tensors (whether these are propagated to the rest of the circuit’s tensors
367
+ psi0_dtype: Ensure the initial state has this dtype.
368
+ psi0_tag: Ensure the initial state has this tag.
369
+ bra_site_ind_id: Use this to label ‘bra’ site indices when creating certain (mostly internal) intermediate tensor networks.
370
+
371
+ Raises:
372
+ RuntimeErorr: Before trying to file_to_quimb_circuit() with
373
+ QrackCircuit, you must install quimb, Qiskit, numpy, and math!
374
+ """
375
+ if not _IS_QUIMB_AVAILABLE:
376
+ raise RuntimeError(
377
+ "Before trying to file_to_quimb_circuit() with QrackCircuit, you must install quimb, Qiskit, numpy, and math!"
378
+ )
379
+
380
+ qcirc = QrackCircuit.file_to_qiskit_circuit(filename)
381
+ basis_gates = ["u", "cx"]
382
+ qcirc = transpile(qcirc, basis_gates=basis_gates, optimization_level=3)
383
+
384
+ tcirc = qtn.Circuit(
385
+ N=qcirc.num_qubits,
386
+ psi0=psi0,
387
+ gate_opts=gate_opts,
388
+ tags=tags,
389
+ psi0_dtype=psi0_dtype,
390
+ psi0_tag=psi0_tag,
391
+ bra_site_ind_id=bra_site_ind_id
392
+ ) if circuit_type == QuimbCircuitType.Circuit else (
393
+ qtn.CircuitDense(N=qcirc.num_qubits, psi0=psi0, gate_opts=gate_opts, tags=tags) if circuit_type == QuimbCircuitType.CircuitDense else
394
+ qtn.CircuitMPS(
395
+ N=qcirc.num_qubits,
396
+ psi0=psi0,
397
+ gate_opts=gate_opts,
398
+ tags=tags,
399
+ psi0_dtype=psi0_dtype,
400
+ psi0_tag=psi0_tag,
401
+ bra_site_ind_id=bra_site_ind_id
402
+ )
403
+ )
404
+ for gate in qcirc.data:
405
+ o = gate.operation
406
+ if o.name == "u":
407
+ th = float(o.params[0])
408
+ ph = float(o.params[1])
409
+ lm = float(o.params[2])
410
+
411
+ tcirc.apply_gate('U3', th, ph, lm, qcirc.find_bit(gate.qubits[0])[0])
412
+ else:
413
+ tcirc.apply_gate('CNOT', qcirc.find_bit(gate.qubits[0])[0], qcirc.find_bit(gate.qubits[1])[0])
414
+
415
+ return tcirc
416
+
417
+ def file_to_tensorcircuit(
418
+ filename,
419
+ inputs=None,
420
+ circuit_params=None,
421
+ binding_params=None
422
+ ):
423
+ """Convert an output file to a TensorCircuit circuit
424
+
425
+ Reads in an (optimized) circuit from a file named
426
+ according to the "filename" parameter and outputs
427
+ a TensorCircuit circuit.
428
+
429
+ Args:
430
+ filename: Name of file
431
+ inputs: pass-through to tensorcircuit.Circuit.from_qiskit
432
+ circuit_params: pass-through to tensorcircuit.Circuit.from_qiskit
433
+ binding_params: pass-through to tensorcircuit.Circuit.from_qiskit
434
+
435
+ Raises:
436
+ RuntimeErorr: Before trying to file_to_quimb_circuit() with
437
+ QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!
438
+ """
439
+ if not _IS_TENSORCIRCUIT_AVAILABLE:
440
+ raise RuntimeError(
441
+ "Before trying to file_to_tensorcircuit() with QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!"
442
+ )
443
+
444
+ qcirc = QrackCircuit.file_to_qiskit_circuit(filename)
445
+ basis_gates = ["u", "cx"]
446
+ qcirc = transpile(qcirc, basis_gates=basis_gates, optimization_level=3)
447
+
448
+ return tc.Circuit.from_qiskit(qcirc, qcirc.num_qubits, inputs, circuit_params, binding_params)
449
+
450
+ def in_from_tensorcircuit(tcirc, enable_instruction = False, enable_inputs = False):
451
+ """Convert a TensorCircuit circuit to a QrackCircuit
452
+
453
+ Accepts a TensorCircuit circuit and outputs an equivalent QrackCircuit
454
+
455
+ Args:
456
+ tcirc: TensorCircuit circuit
457
+ enable_instruction: whether to also export measurement and reset instructions
458
+ enable_inputs: whether to also export the inputs
459
+
460
+ Raises:
461
+ RuntimeErorr: Before trying to in_from_tensorcircuit() with
462
+ QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!
463
+ """
464
+ if not _IS_TENSORCIRCUIT_AVAILABLE:
465
+ raise RuntimeError(
466
+ "Before trying to in_from_tensorcircuit() with QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!"
467
+ )
468
+
469
+ # Convert from TensorCircuit to Qiskit
470
+ qcirc = tcirc.to_qiskit(enable_instruction, enable_inputs)
471
+
472
+ # Convert to QrackCircuit
473
+ return QrackCircuit.in_from_qiskit_circuit(qcirc)