forked from anastasiaangelo/ProjectAnastasia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ising_globalpenalty.py
303 lines (235 loc) · 10.7 KB
/
Ising_globalpenalty.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# Point 3 of constraint studies for paper, Ising model with global penalties
# Script to optimise the Hamiltonian, starting directly from the Ising Hamiltonian
# %%
import numpy as np
import pandas as pd
import time
from copy import deepcopy
num_rot = 2
########################### Configure the hamiltonian from the values calculated classically with pyrosetta ############################
df1 = pd.read_csv("energy_files/one_body_terms.csv")
q = df1['E_ii'].values
num = len(q)
N = int(num/num_rot)
num_qubits = num
print('Qii values: \n', q)
df = pd.read_csv("energy_files/two_body_terms.csv")
value = df['E_ij'].values
Q = np.zeros((num,num))
n = 0
for i in range(0, num-2):
if i%2 == 0:
Q[i][i+2] = deepcopy(value[n])
Q[i+2][i] = deepcopy(value[n])
Q[i][i+3] = deepcopy(value[n+1])
Q[i+3][i] = deepcopy(value[n+1])
n += 2
elif i%2 != 0:
Q[i][i+1] = deepcopy(value[n])
Q[i+1][i] = deepcopy(value[n])
Q[i][i+2] = deepcopy(value[n+1])
Q[i+2][i] = deepcopy(value[n+1])
n += 2
print('\nQij values: \n', Q)
H = np.zeros((num,num))
for i in range(num):
for j in range(num):
if i != j:
H[i][j] = np.multiply(0.25, Q[i][j])
for i in range(num):
H[i][i] = -(0.5 * q[i] + sum(0.25 * Q[i][j] for j in range(num) if j != i))
print('\nH: \n', H)
# %% ################################################ Classical optimisation ###########################################################
from scipy.sparse.linalg import eigsh
Z_matrix = np.array([[1, 0], [0, -1]])
identity = np.eye(2)
def construct_operator(qubit_indices, num_qubits):
operator = np.eye(1)
for qubit in range(num_qubits):
if qubit in qubit_indices:
operator = np.kron(operator, Z_matrix)
else:
operator = np.kron(operator, identity)
return operator
C = np.zeros((2**num_qubits, 2**num_qubits))
for i in range(num_qubits):
operator = construct_operator([i], num_qubits)
C += H[i][i] * operator
for i in range(num_qubits):
for j in range(i+1, num_qubits):
operator = construct_operator([i, j], num_qubits)
C += H[i][j] * operator
print('C :\n', C)
lambda_penalty = 1
Hamming_weight = 4
penalty_operator = np.zeros((2**num_qubits, 2**num_qubits))
for i in range(num_qubits):
Zi_operator = construct_operator([i], num_qubits)
penalty_operator += Zi_operator
penalty_operator = lambda_penalty * (np.dot(penalty_operator, penalty_operator) - 2 * Hamming_weight * penalty_operator + Hamming_weight**2 * np.eye(2**num_qubits))
C_with_penalty = C + penalty_operator
print('C_withpenalty: ', C_with_penalty)
# Extract the ground state energy and wavefunction
# using sparse representation so as to be able to generalise to larger systems
eigenvalues, eigenvectors = eigsh(C_with_penalty, k=num, which='SA')
print("\n\nClassical optimisation results. \n")
print("Ground energy eigsh: ", eigenvalues[0])
print("ground state wavefuncion eigsh: ", eigenvectors[:,0])
print('\n\n')
# %% ############################################ Quantum optimisation ########################################################################
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit.quantum_info.operators import Pauli, SparsePauliOp
from qiskit_algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
def X_op(i, num_qubits):
"""Return an X Pauli operator on the specified qubit in a num-qubit system."""
op_list = ['I'] * num_qubits
op_list[i] = 'X'
return SparsePauliOp(Pauli(''.join(op_list)))
def generate_pauli_zij(n, i, j):
if i<0 or i >= n or j<0 or j>=n:
raise ValueError(f"Indices out of bounds for n={n} qubits. ")
pauli_str = ['I']*n
if i == j:
pauli_str[i] = 'Z'
else:
pauli_str[i] = 'Z'
pauli_str[j] = 'Z'
return Pauli(''.join(pauli_str))
q_hamiltonian = SparsePauliOp(Pauli('I'*num_qubits), coeffs=[0])
for i in range(num_qubits):
for j in range(i+1, num_qubits):
if H[i][j] != 0:
pauli = generate_pauli_zij(num_qubits, i, j)
op = SparsePauliOp(pauli, coeffs=[H[i][j]])
q_hamiltonian += op
for i in range(num_qubits):
pauli = generate_pauli_zij(num_qubits, i, i)
Z_i = SparsePauliOp(pauli, coeffs=[H[i][i]])
q_hamiltonian += Z_i
def format_sparsepauliop(op):
terms = []
labels = [pauli.to_label() for pauli in op.paulis]
coeffs = op.coeffs
for label, coeff in zip(labels, coeffs):
terms.append(f"{coeff:.10f} * {label}")
return '\n'.join(terms)
# add global penalty term to the matrix so as to discourage the selection of two rotamers on the same residue - implementation of the Hammings constraint
def z_i(i, num_qubits):
pauli_str = ['I'] * num_qubits
pauli_str[i] = 'Z'
z_op = SparsePauliOp(Pauli(''.join(pauli_str)), coeffs=[1])
return z_op
def construct_hamming_penalty(num_qubits, desired_Hamming_weight, penalty):
total_z = sum(z_i(i, num_qubits) for i in range(num_qubits))
hamming_term = total_z - desired_Hamming_weight * SparsePauliOp('I' * num_qubits)
penalty_term = hamming_term @ hamming_term
penalty_term = penalty * penalty_term
return penalty_term
H_p = q_hamiltonian + construct_hamming_penalty(num_qubits, Hamming_weight, lambda_penalty)
print(f"\nThe hamiltonian constructed using Pauli operators is: \n", format_sparsepauliop(q_hamiltonian))
print(f"\nThe hamiltonian with the global penalty term is: \n", format_sparsepauliop(H_p))
#the mixer in QAOA should be a quantum operator representing transitions between configurations
mixer_op = sum(X_op(i,num_qubits) for i in range(num_qubits))
start_time = time.time()
p = 1 # Number of QAOA layers
initial_point = np.ones(2 * p)
qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA(), reps=p, mixer=mixer_op, initial_point=initial_point)
result = qaoa.compute_minimum_eigenvalue(q_hamiltonian)
end_time = time.time()
print("\n\nThe result of the quantum optimisation using QAOA is: \n")
print('best measurement', result.best_measurement)
print('adjusted energy: ', result.best_measurement['value'])
elapsed_time = end_time - start_time
print(f"Local Simulation run time: {elapsed_time} seconds")
print('\n\n')
# %% ############################################ Simulators ##########################################################################
from qiskit_aer import Aer
from qiskit_ibm_provider import IBMProvider
from qiskit_aer.noise import NoiseModel
from qiskit_aer.primitives import Sampler
from qiskit.primitives import Sampler, BackendSampler
from qiskit.transpiler import PassManager
simulator = Aer.get_backend('qasm_simulator')
provider = IBMProvider()
available_backends = provider.backends()
print("Available Backends:", available_backends)
device_backend = provider.get_backend('ibm_torino')
noise_model = NoiseModel.from_backend(device_backend)
options= {
"noise_model": noise_model,
"basis_gates": simulator.configuration().basis_gates,
"coupling_map": simulator.configuration().coupling_map,
"seed_simulator": 42,
"shots": 1000,
"optimization_level": 3,
"resilience_level": 0
}
noisy_sampler = BackendSampler(backend=simulator, options=options, bound_pass_manager=PassManager())
start_time1 = time.time()
qaoa1 = QAOA(sampler=noisy_sampler, optimizer=COBYLA(), reps=p, mixer=mixer_op, initial_point=initial_point)
result1 = qaoa1.compute_minimum_eigenvalue(q_hamiltonian)
end_time1 = time.time()
print("\n\nThe result of the noisy quantum optimisation using QAOA is: \n")
print('best measurement', result1.best_measurement)
print('Optimal parameters: ', result1.optimal_parameters)
print('The ground state energy with noisy QAOA is: ', np.real(result1.best_measurement['value']))
elapsed_time1 = end_time1 - start_time1
print(f"Aer Simulator run time: {elapsed_time1} seconds")
print('\n\n')
# %% ############################################# Hardware with QAOAAnastz ##################################################################
from qiskit.circuit.library import QAOAAnsatz
from qiskit_algorithms import SamplingVQE
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler
from qiskit import transpile, QuantumCircuit, QuantumRegister
from qiskit.transpiler import CouplingMap, Layout
service = QiskitRuntimeService()
backend = service.backend("ibm_torino")
print('Coupling Map of hardware: ', backend.configuration().coupling_map)
ansatz = QAOAAnsatz(q_hamiltonian, mixer_operator=mixer_op, reps=p)
print('\n\nQAOAAnsatz: ', ansatz)
target = backend.target
# %%
# real_coupling_map = backend.configuration().coupling_map
# coupling_map = CouplingMap(couplinglist=real_coupling_map)
def generate_linear_coupling_map(num_qubits):
coupling_list = [[i, i + 1] for i in range(num_qubits - 1)]
return CouplingMap(couplinglist=coupling_list)
# linear_coupling_map = generate_linear_coupling_map(num_qubits)
coupling_map = CouplingMap(couplinglist=[[0, 1],[0, 15], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14]])
qr = QuantumRegister(num_qubits, 'q')
circuit = QuantumCircuit(qr)
trivial_layout = Layout({qr[i]: i for i in range(num_qubits)})
ansatz_isa = transpile(ansatz, backend=backend, initial_layout=trivial_layout, coupling_map=coupling_map,
optimization_level=1, layout_method='trivial', routing_method='basic')
print("\n\nAnsatz layout after explicit transpilation:", ansatz_isa._layout)
hamiltonian_isa = q_hamiltonian.apply_layout(ansatz_isa.layout)
print("\n\nAnsatz layout after transpilation:", hamiltonian_isa)
# %%
session = Session(backend=backend)
print('\nhere 1')
sampler = Sampler(backend=backend, session=session)
print('here 2')
qaoa2 = SamplingVQE(sampler=sampler, ansatz=ansatz_isa, optimizer=COBYLA(), initial_point=initial_point)
print('here 3')
result2 = qaoa2.compute_minimum_eigenvalue(hamiltonian_isa)
print("\n\nThe result of the noisy quantum optimisation using QAOAAnsatz is: \n")
print('best measurement', result2.best_measurement)
print('Optimal parameters: ', result2.optimal_parameters)
print('The ground state energy with noisy QAOA is: ', np.real(result2.best_measurement['value']))
jobs = service.jobs(session_id='crmfh9d14ys00088aq6g')
total_usage_time = 0
for job in jobs:
job_result = job.usage_estimation['quantum_seconds']
total_usage_time += job_result
print(f"Total Usage Time Hardware
: {total_usage_time} seconds")
print('\n\n')
# %%
index = ansatz_isa.layout.final_index_layout() # Maps logical qubit index to its position in bitstring
measured_bitstring = result2.best_measurement['bitstring']
original_bitstring = ['']*num_qubits
for i, logical in enumerate(index):
original_bitstring[i] = measured_bitstring[logical]
original_bitstring = ''.join(original_bitstring)
print("Original bitstring:", original_bitstring)