-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhamiltonian_time_evolution.py
More file actions
288 lines (223 loc) · 8.58 KB
/
hamiltonian_time_evolution.py
File metadata and controls
288 lines (223 loc) · 8.58 KB
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
"""Hamiltonian Time Evolution via Trotterization.
This example demonstrates:
1. Building Hamiltonians from Pauli strings
2. Trotterized time evolution circuits
3. Comparison between Trotter and exact evolution
4. Convergence analysis vs. number of Trotter steps
The Trotter-Suzuki decomposition approximates exp(-iHt) by breaking it into
small time steps: exp(-iHt) ≈ [exp(-iHδt)]^n where δt = t/n.
For H = Σⱼ wⱼ Pⱼ, each small step factorizes as:
exp(-iH δt) ≈ ∏ⱼ exp(-i wⱼ Pⱼ δt)
Author: TyxonQ Team
Date: 2025
"""
import numpy as np
import tyxonq as tq
from tyxonq.libs.circuits_library.trotter_circuit import build_trotter_circuit
def build_hamiltonian_pauli_strings(n_qubits, interaction_strength=1.0):
"""Build Hamiltonian as list of Pauli strings.
Example: 2-qubit Heisenberg model
H = J·(X₀X₁ + Y₀Y₁ + Z₀Z₁)
Pauli encoding: 0=I, 1=X, 2=Y, 3=Z
Args:
n_qubits: Number of qubits
interaction_strength: Coupling strength J
Returns:
(pauli_terms, weights) tuple
"""
if n_qubits == 2:
# H = J·(XX + YY + ZZ)
pauli_terms = [
[1, 1], # XX
[2, 2], # YY
[3, 3], # ZZ
]
weights = [interaction_strength] * 3
else:
# Nearest-neighbor Heisenberg chain
pauli_terms = []
weights = []
for i in range(n_qubits - 1):
# XX term
ps_xx = [0] * n_qubits
ps_xx[i] = 1
ps_xx[i+1] = 1
pauli_terms.append(ps_xx)
weights.append(interaction_strength)
# YY term
ps_yy = [0] * n_qubits
ps_yy[i] = 2
ps_yy[i+1] = 2
pauli_terms.append(ps_yy)
weights.append(interaction_strength)
# ZZ term
ps_zz = [0] * n_qubits
ps_zz[i] = 3
ps_zz[i+1] = 3
pauli_terms.append(ps_zz)
weights.append(interaction_strength)
return pauli_terms, weights
def build_dense_hamiltonian(pauli_terms, weights, n_qubits):
"""Build dense Hamiltonian matrix from Pauli strings.
Args:
pauli_terms: List of Pauli strings
weights: Coefficients
n_qubits: Number of qubits
Returns:
Dense Hamiltonian matrix (2^n × 2^n)
"""
from tyxonq.numerics.api import get_backend
K = get_backend(None)
dim = 2 ** n_qubits
H = K.zeros((dim, dim), dtype=K.complex128)
# Pauli matrices
I = K.array([[1, 0], [0, 1]], dtype=K.complex128)
X = K.array([[0, 1], [1, 0]], dtype=K.complex128)
Y = K.array([[0, -1j], [1j, 0]], dtype=K.complex128)
Z = K.array([[1, 0], [0, -1]], dtype=K.complex128)
pauli_map = [I, X, Y, Z]
# Build each term
for ps, w in zip(pauli_terms, weights):
term = pauli_map[ps[0]]
for p in ps[1:]:
term = K.kron(term, pauli_map[p])
H = H + w * term
return H
def exact_time_evolution(H, psi0, time):
"""Compute exact time evolution via matrix exponential.
|ψ(t)⟩ = exp(-iHt)|ψ₀⟩
"""
from tyxonq.numerics.api import get_backend
K = get_backend(None)
# Compute exp(-iHt)
U = K.expm(-1j * time * H)
# Apply to initial state
psi_t = U @ psi0.reshape((-1, 1))
return psi_t.reshape(-1)
def demonstrate_trotter_evolution():
"""Demonstrate Trotterized time evolution."""
print("\n" + "="*70)
print("HAMILTONIAN TIME EVOLUTION VIA TROTTERIZATION")
print("="*70)
# System parameters
n_qubits = 2
J = 1.0 # Coupling strength
time = 1.0 # Evolution time
print(f"\nSystem Configuration:")
print(f" Qubits: {n_qubits}")
print(f" Hamiltonian: H = J·(XX + YY + ZZ), J = {J}")
print(f" Evolution time: t = {time}")
# Build Hamiltonian
pauli_terms, weights = build_hamiltonian_pauli_strings(n_qubits, J)
print(f"\n Pauli terms: {len(pauli_terms)}")
for i, (ps, w) in enumerate(zip(pauli_terms, weights)):
pauli_str = ''.join(['I', 'X', 'Y', 'Z'][p] for p in ps)
print(f" Term {i+1}: {w:.1f} × {pauli_str}")
# Initial state: |10⟩ (qubit 0 in |1⟩, qubit 1 in |0⟩)
print(f"\n Initial state: |10⟩")
# Trotter evolution with varying steps
print(f"\nTrotter Evolution Results:")
print(f"{'Steps':<8} {'⟨Z₀⟩':<12} {'⟨Z₁⟩':<12}")
print("-" * 35)
for n_steps in [1, 2, 4, 8, 16, 32]:
# Prepare initial state |01⟩
c_init = tq.Circuit(n_qubits)
c_init.x(0)
# Build Trotter evolution
c_trot = build_trotter_circuit(
pauli_terms,
weights=weights,
time=time,
steps=n_steps,
num_qubits=n_qubits
)
# Combine circuits
c_init.ops.extend(c_trot.ops)
# Run simulation
result = c_init.device(provider="local", device="statevector", shots=0).run()
# Extract Z expectations
if isinstance(result, list):
result = result[0] if result else {}
exps = result.get("expectations", {})
z0 = exps.get("Z0", 0.0)
z1 = exps.get("Z1", 0.0)
print(f"{n_steps:<8} {z0:<12.6f} {z1:<12.6f}")
print("\n" + "-" * 35)
print("Observation: Converges with increasing Trotter steps")
def demonstrate_trotter_accuracy():
"""Compare Trotter approximation with exact evolution."""
print("\n" + "="*70)
print("TROTTER APPROXIMATION ACCURACY")
print("="*70)
n_qubits = 2
J = 1.0
time = 1.0
# Build Hamiltonian
pauli_terms, weights = build_hamiltonian_pauli_strings(n_qubits, J)
H = build_dense_hamiltonian(pauli_terms, weights, n_qubits)
# Initial state |10⟩ (qubit 0 = 1, qubit 1 = 0)
psi0 = np.zeros(4, dtype=np.complex128)
psi0[2] = 1.0 # Binary: 10 = index 2
# Exact evolution
psi_exact = exact_time_evolution(H, psi0, time)
print(f"\nAccuracy Analysis (Fidelity with exact evolution):")
print(f"{'Steps':<8} {'Fidelity':<12} {'Error':<12}")
print("-" * 35)
for n_steps in [1, 2, 4, 8, 16, 32, 64]:
# Trotter evolution
c = tq.Circuit(n_qubits)
c.x(0) # Prepare |01⟩
# Build Trotter circuit (without measurements)
c_trotter = build_trotter_circuit(
pauli_terms,
weights=weights,
time=time,
steps=n_steps,
num_qubits=n_qubits
)
# Remove measurement ops
c_trotter.ops = [op for op in c_trotter.ops if op[0] != 'measure_z']
# Combine circuits
c.ops.extend(c_trotter.ops)
# Get final state
psi_trotter = c.state()
# Compute fidelity
fidelity = float(np.abs(np.vdot(psi_exact, psi_trotter))**2)
error = 1.0 - fidelity
print(f"{n_steps:<8} {fidelity:<12.9f} {error:<12.2e}")
print("\n" + "-" * 35)
print("Key insight: Error decreases exponentially with more steps")
print("Rule of thumb: Use n_steps ≥ 10 × evolution_time for accuracy ~1e-4")
def main():
"""Run all demonstrations."""
print("\n" + "="*70)
print("HAMILTONIAN TIME EVOLUTION")
print("="*70)
print("\nThis example demonstrates:")
print(" • Building Hamiltonians from Pauli strings")
print(" • Trotterized time evolution circuits")
print(" • Convergence with increasing Trotter steps")
print(" • Accuracy comparison with exact evolution")
demonstrate_trotter_evolution()
demonstrate_trotter_accuracy()
print("\n" + "="*70)
print("KEY CONCEPTS")
print("="*70)
print("\n1. Trotter-Suzuki Decomposition:")
print(" exp(-iHt) ≈ [∏ⱼ exp(-iwⱼPⱼδt)]^n")
print(" where δt = t/n and n = number of steps")
print("\n2. Error Scaling:")
print(" • First-order Trotter: Error ∝ O(t²/n)")
print(" • Higher-order methods: Better scaling but more gates")
print("\n3. Practical Guidelines:")
print(" • Small systems (<5 qubits): Use exact evolution")
print(" • Large systems: Trotterization essential")
print(" • Choose n_steps to balance accuracy vs. circuit depth")
print("\n4. Supported Pauli Patterns:")
print(" ✓ Single-qubit Z: RZ gate")
print(" ✓ Single-qubit X: H-RZ-H")
print(" ✓ Two-qubit ZZ: CX-RZ-CX")
print(" ⚠️ Other patterns: Requires gate decomposition")
print("="*70 + "\n")
if __name__ == "__main__":
main()