-
Notifications
You must be signed in to change notification settings - Fork 6
/
Executor.py
55 lines (46 loc) · 1.82 KB
/
Executor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from QuantumCircuit import QuantumCircuit, QGate
import numpy as np
from consts import gate2matrix, cnots
import random
DEFAULT_SHOTS = 8192
class Executor:
def __init__(self, qc: QuantumCircuit):
self.state_vector = np.zeros(2**qc.no_qubits)
self.state_vector[0] = 1
skip = False
max_len = max([len(e) for e in qc.circ])
for i in range(max_len):
layer_matrix = np.array([[1]])
for j in range(qc.no_qubits):
if skip:
skip = False
continue
if i<len(qc.circ[j]):
gate = qc.circ[j][i][0]
else:
gate = QGate.IDENTITY
g_matrix = gate2matrix[gate]
# print(f"layer: {i}, qubit: {j}, gate: {gate}")
layer_matrix = np.kron(layer_matrix, g_matrix)
# print(layer_matrix)
if gate in cnots:
skip = True
self.state_vector = [email protected]_vector
def get_statevector(self):
return self.state_vector
def get_probs(self) -> list:
probabilities = [np.round(abs(e)**2, 4) for e in self.state_vector]
return probabilities
def measure_all(self, shots=DEFAULT_SHOTS):
values = [i for i in range(len(self.state_vector))]
probabilities = [np.round(abs(e)**2, 4) for e in self.state_vector]
# cum_probs = [probabilities[0]]
# for i in range(1, len(probabilities)):
# cum_probs.append(cum_probs[i-1]+probabilities[i])
# # print(probabilities)
# # print(cum_probs)
counts = [0 for _ in self.state_vector]
for _ in range(shots):
choice = random.choices(values, weights=probabilities, k=1)[0]
counts[choice]+=1
return counts