Skip to content

Commit 50a4a86

Browse files
authoredApr 10, 2023
Update quantum_variation.py
1 parent 2f8194f commit 50a4a86

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed
 

‎examples/quantum_variation.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ def numdiff(i):
189189
for i in range(N - 1):
190190
h.append(J)
191191
h_door.append([5, i, i + 1])
192+
f = tf.constant(f, dtype="complex64")
193+
h = tf.constant(h, dtype="float32")
192194

193195
# initial state
194196
state = np.zeros(1 << N)
@@ -197,7 +199,6 @@ def numdiff(i):
197199
# numerical realize H
198200
ls = []
199201
weight = []
200-
H = np.zeros((1 << N, 1 << N)) * 1j
201202
for q in range(len(h_door)):
202203
if h_door[q][0] == 0:
203204
r = [0 for _ in range(N)]
@@ -227,7 +228,7 @@ def numdiff(i):
227228
H = tc.quantum.PauliStringSum2Dense(ls, weight, numpy=False)
228229

229230
# variation realize
230-
ODE_theta = np.zeros(len(door))
231+
ODE_theta = tf.zeros(len(door), dtype="float32")
231232
for T in range(int(t / dt)):
232233
# calculate coefficient in paper
233234
A = np.zeros((len(door), len(door)))
@@ -251,9 +252,9 @@ def numdiff(i):
251252
batch_is_k = tf.constant(batch_is_k)
252253
batch_is_q = tf.constant(batch_is_q)
253254
vmap_result = Calculation_A_vmap(batch_theta, batch_is_k, batch_is_q, ODE_theta)
254-
for k in range(len(door)):
255-
for q in range(len(door)):
256-
A[k, q] = abs(f[k] * f[q]) * vmap_result[k * len(door) + q]
255+
A = tf.cast(
256+
tf.tensordot(tf.abs(f), tf.abs(f), 0), dtype="float32"
257+
) * tf.reshape(tc.backend.real(vmap_result), [len(door), len(door)])
257258

258259
batch_theta = []
259260
batch_is_k = []
@@ -274,15 +275,16 @@ def numdiff(i):
274275
batch_is_k = tf.constant(batch_is_k)
275276
batch_is_q = tf.constant(batch_is_q)
276277
vmap_result = Calculation_C_vmap(batch_theta, batch_is_k, batch_is_q, ODE_theta)
277-
for k in range(len(door)):
278-
for q in range(len(h_door)):
279-
C[k] += abs(f[k] * h[q]) * vmap_result[k * len(h_door) + q]
278+
C = tf.reduce_sum(
279+
tf.cast(tf.tensordot(tf.abs(f), tf.abs(h), 0), dtype="float32")
280+
* tf.reshape(tc.backend.real(vmap_result), [len(door), len(h_door)]),
281+
1,
282+
)
280283

281284
# calculate parameter and its derivative
282285
A += np.eye(len(door)) * 1e-5
283286
ODE_dtheta = tc.backend.solve(A, C)
284-
for i in range(len(door)):
285-
ODE_theta[i] += ODE_dtheta[i] * dt
287+
ODE_theta += ODE_dtheta * dt
286288

287289
# numerical results
288290
ep = np.array(tc.backend.expm(-1j * H * (T + 1) * dt)) @ state

0 commit comments

Comments
 (0)
Please sign in to comment.