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