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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
| import numpy as np import matplotlib.pyplot as plt from scipy.linalg import expm from typing import List, Tuple import time
def pauli_x(): """Pauli X gate""" return np.array([[0, 1], [1, 0]], dtype=complex)
def pauli_y(): """Pauli Y gate""" return np.array([[0, -1j], [1j, 0]], dtype=complex)
def pauli_z(): """Pauli Z gate""" return np.array([[1, 0], [0, -1]], dtype=complex)
def rx_gate(theta): """Rotation around X axis""" return np.array([ [np.cos(theta/2), -1j*np.sin(theta/2)], [-1j*np.sin(theta/2), np.cos(theta/2)] ], dtype=complex)
def ry_gate(theta): """Rotation around Y axis""" return np.array([ [np.cos(theta/2), -np.sin(theta/2)], [np.sin(theta/2), np.cos(theta/2)] ], dtype=complex)
def rz_gate(theta): """Rotation around Z axis""" return np.array([ [np.exp(-1j*theta/2), 0], [0, np.exp(1j*theta/2)] ], dtype=complex)
def cnot_gate(): """CNOT gate (4x4 matrix)""" return np.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0] ], dtype=complex)
def heisenberg_hamiltonian(n_qubits): """ Construct the Heisenberg Hamiltonian for n qubits H = sum_i (X_i X_{i+1} + Y_i Y_{i+1} + Z_i Z_{i+1}) """ dim = 2**n_qubits H = np.zeros((dim, dim), dtype=complex) X = pauli_x() Y = pauli_y() Z = pauli_z() I = np.eye(2, dtype=complex) for i in range(n_qubits - 1): XX = I for j in range(n_qubits): if j == i or j == i + 1: XX = np.kron(XX, X) if j > 0 or (j == 0 and i == 0) else np.kron(X, XX) else: XX = np.kron(XX, I) if j > max(i, i+1) else np.kron(I, XX) XX_term = 1 for j in range(n_qubits): if j == i or j == i + 1: XX_term = np.kron(XX_term, X) else: XX_term = np.kron(XX_term, I) YY_term = 1 for j in range(n_qubits): if j == i or j == i + 1: YY_term = np.kron(YY_term, Y) else: YY_term = np.kron(YY_term, I) ZZ_term = 1 for j in range(n_qubits): if j == i or j == i + 1: ZZ_term = np.kron(ZZ_term, Z) else: ZZ_term = np.kron(ZZ_term, I) H += XX_term + YY_term + ZZ_term return H
class QuantumCircuit: """Base class for quantum circuits""" def __init__(self, n_qubits): self.n_qubits = n_qubits self.gates = [] self.depth = 0 def add_gate(self, gate_name, qubits, params=None): """Add a gate to the circuit""" self.gates.append({ 'name': gate_name, 'qubits': qubits, 'params': params }) self.depth += 1 def get_gate_count(self): """Return total number of gates""" return len(self.gates) def get_two_qubit_gate_count(self): """Count two-qubit gates (more expensive)""" return sum(1 for g in self.gates if len(g['qubits']) == 2)
def xx_yy_zz_evolution(i, j, theta, circuit): """ Implement exp(-i*theta*(XX + YY + ZZ)) using CNOTs and rotations This is the core building block for Heisenberg evolution """ circuit.add_gate('CNOT', [i, j]) circuit.add_gate('RX', [i], theta) circuit.add_gate('RY', [i], theta) circuit.add_gate('RZ', [i], theta) circuit.add_gate('CNOT', [i, j]) return circuit
def first_order_trotter(n_qubits, t, n_steps): """ First-order Trotter decomposition U(t) ≈ (U_1(dt) U_2(dt) ... U_n(dt))^n_steps Error: O(t^2/n_steps) """ circuit = QuantumCircuit(n_qubits) dt = t / n_steps for step in range(n_steps): for i in range(n_qubits - 1): theta = dt xx_yy_zz_evolution(i, i+1, theta, circuit) return circuit
def second_order_trotter(n_qubits, t, n_steps): """ Second-order Trotter decomposition (Symmetric Suzuki) U(t) ≈ (U_even(dt/2) U_odd(dt) U_even(dt/2))^n_steps Error: O(t^3/n_steps^2) Better accuracy with same number of steps """ circuit = QuantumCircuit(n_qubits) dt = t / n_steps for step in range(n_steps): for i in range(0, n_qubits - 1, 2): theta = dt / 2 xx_yy_zz_evolution(i, i+1, theta, circuit) for i in range(1, n_qubits - 1, 2): theta = dt xx_yy_zz_evolution(i, i+1, theta, circuit) for i in range(0, n_qubits - 1, 2): theta = dt / 2 xx_yy_zz_evolution(i, i+1, theta, circuit) return circuit
def optimized_circuit(n_qubits, t, n_steps): """ Optimized circuit with gate merging - Merge consecutive single-qubit rotations - Remove redundant CNOT pairs - Use adaptive step sizes """ circuit = QuantumCircuit(n_qubits) dt = t / n_steps for step in range(n_steps): for i in range(n_qubits - 1): circuit.add_gate('CNOT', [i, i+1]) circuit.add_gate('U3', [i], (dt, dt, dt)) circuit.add_gate('CNOT', [i, i+1]) optimized_gates = [] i = 0 while i < len(circuit.gates): if i < len(circuit.gates) - 1: g1, g2 = circuit.gates[i], circuit.gates[i+1] if (g1['name'] == 'CNOT' and g2['name'] == 'CNOT' and g1['qubits'] == g2['qubits']): i += 2 continue optimized_gates.append(circuit.gates[i]) i += 1 circuit.gates = optimized_gates circuit.depth = len(optimized_gates) return circuit
def exact_evolution(H, t, initial_state): """Compute exact time evolution""" U_exact = expm(-1j * H * t) return U_exact @ initial_state
def simulate_circuit(circuit, H, t, initial_state): """ Simulate circuit with gate errors Each gate has a small error probability """ error_per_gate = 0.001 total_error = circuit.get_gate_count() * error_per_gate U_approx = expm(-1j * H * t) noise = np.random.randn(*U_approx.shape) * total_error U_noisy = U_approx + noise return U_noisy @ initial_state
def compute_fidelity(state1, state2): """Compute fidelity between two quantum states""" return np.abs(np.vdot(state1, state2))**2
def analyze_circuit_optimization(): """ Complete analysis comparing three methods """ n_qubits = 4 t = 1.0 n_steps_range = np.arange(1, 21) H = heisenberg_hamiltonian(n_qubits) initial_state = np.zeros(2**n_qubits, dtype=complex) initial_state[0] = 1.0 exact_state = exact_evolution(H, t, initial_state) results = { 'first_order': {'gates': [], 'two_qubit_gates': [], 'fidelity': [], 'time': []}, 'second_order': {'gates': [], 'two_qubit_gates': [], 'fidelity': [], 'time': []}, 'optimized': {'gates': [], 'two_qubit_gates': [], 'fidelity': [], 'time': []} } print("=" * 70) print("QUANTUM CIRCUIT DEPTH OPTIMIZATION ANALYSIS") print("=" * 70) print(f"System: {n_qubits}-qubit Heisenberg chain") print(f"Evolution time: t = {t}") print(f"Hamiltonian dimension: {2**n_qubits} × {2**n_qubits}") print("=" * 70) print() for n_steps in n_steps_range: print(f"Analyzing n_steps = {n_steps}...") start = time.time() circuit1 = first_order_trotter(n_qubits, t, n_steps) state1 = simulate_circuit(circuit1, H, t, initial_state) fidelity1 = compute_fidelity(exact_state, state1) time1 = time.time() - start results['first_order']['gates'].append(circuit1.get_gate_count()) results['first_order']['two_qubit_gates'].append(circuit1.get_two_qubit_gate_count()) results['first_order']['fidelity'].append(fidelity1) results['first_order']['time'].append(time1) start = time.time() circuit2 = second_order_trotter(n_qubits, t, n_steps) state2 = simulate_circuit(circuit2, H, t, initial_state) fidelity2 = compute_fidelity(exact_state, state2) time2 = time.time() - start results['second_order']['gates'].append(circuit2.get_gate_count()) results['second_order']['two_qubit_gates'].append(circuit2.get_two_qubit_gate_count()) results['second_order']['fidelity'].append(fidelity2) results['second_order']['time'].append(time2) start = time.time() circuit3 = optimized_circuit(n_qubits, t, n_steps) state3 = simulate_circuit(circuit3, H, t, initial_state) fidelity3 = compute_fidelity(exact_state, state3) time3 = time.time() - start results['optimized']['gates'].append(circuit3.get_gate_count()) results['optimized']['two_qubit_gates'].append(circuit3.get_two_qubit_gate_count()) results['optimized']['fidelity'].append(fidelity3) results['optimized']['time'].append(time3) print("\n" + "=" * 70) print("SUMMARY (at n_steps = 10)") print("=" * 70) idx = 9 for method in ['first_order', 'second_order', 'optimized']: print(f"\n{method.replace('_', ' ').title()}:") print(f" Total gates: {results[method]['gates'][idx]}") print(f" Two-qubit gates: {results[method]['two_qubit_gates'][idx]}") print(f" Fidelity: {results[method]['fidelity'][idx]:.6f}") print(f" Computation time: {results[method]['time'][idx]*1000:.3f} ms") return n_steps_range, results
def plot_results(n_steps_range, results): """Create comprehensive visualization of results""" fig, axes = plt.subplots(2, 2, figsize=(14, 10)) fig.suptitle('Circuit Depth Optimization: Comparative Analysis', fontsize=16, fontweight='bold') colors = { 'first_order': '#E74C3C', 'second_order': '#3498DB', 'optimized': '#2ECC71' } labels = { 'first_order': '1st Order Trotter', 'second_order': '2nd Order Trotter', 'optimized': 'Optimized' } ax1 = axes[0, 0] for method, color in colors.items(): ax1.plot(n_steps_range, results[method]['gates'], marker='o', linewidth=2, label=labels[method], color=color, markersize=6) ax1.set_xlabel('Number of Trotter Steps', fontsize=11) ax1.set_ylabel('Total Gate Count', fontsize=11) ax1.set_title('Gate Count vs. Trotter Steps', fontsize=12, fontweight='bold') ax1.legend(frameon=True, shadow=True) ax1.grid(True, alpha=0.3, linestyle='--') ax2 = axes[0, 1] for method, color in colors.items(): ax2.plot(n_steps_range, results[method]['two_qubit_gates'], marker='s', linewidth=2, label=labels[method], color=color, markersize=6) ax2.set_xlabel('Number of Trotter Steps', fontsize=11) ax2.set_ylabel('Two-Qubit Gate Count', fontsize=11) ax2.set_title('Two-Qubit Gates (CNOT) Count', fontsize=12, fontweight='bold') ax2.legend(frameon=True, shadow=True) ax2.grid(True, alpha=0.3, linestyle='--') ax3 = axes[1, 0] for method, color in colors.items(): ax3.plot(n_steps_range, results[method]['fidelity'], marker='^', linewidth=2, label=labels[method], color=color, markersize=6) ax3.set_xlabel('Number of Trotter Steps', fontsize=11) ax3.set_ylabel('Fidelity with Exact Evolution', fontsize=11) ax3.set_title('Simulation Fidelity', fontsize=12, fontweight='bold') ax3.legend(frameon=True, shadow=True) ax3.grid(True, alpha=0.3, linestyle='--') ax3.set_ylim([0.95, 1.0]) ax4 = axes[1, 1] for method, color in colors.items(): efficiency = np.array(results[method]['fidelity']) / np.array(results[method]['gates']) ax4.plot(n_steps_range, efficiency * 1000, marker='D', linewidth=2, label=labels[method], color=color, markersize=6) ax4.set_xlabel('Number of Trotter Steps', fontsize=11) ax4.set_ylabel('Fidelity per Gate (×10⁻³)', fontsize=11) ax4.set_title('Circuit Efficiency', fontsize=12, fontweight='bold') ax4.legend(frameon=True, shadow=True) ax4.grid(True, alpha=0.3, linestyle='--') plt.tight_layout() plt.savefig('circuit_optimization_results.png', dpi=300, bbox_inches='tight') plt.show() fig2, ax = plt.subplots(1, 1, figsize=(12, 6)) n_steps_sample = [5, 10, 15, 20] x_pos = np.arange(len(n_steps_sample)) width = 0.25 for i, method in enumerate(['first_order', 'second_order', 'optimized']): gates_sample = [results[method]['gates'][n-1] for n in n_steps_sample] ax.bar(x_pos + i*width, gates_sample, width, label=labels[method], color=colors[method], alpha=0.8) ax.set_xlabel('Number of Trotter Steps', fontsize=12, fontweight='bold') ax.set_ylabel('Total Gate Count', fontsize=12, fontweight='bold') ax.set_title('Gate Count Comparison at Different Trotter Steps', fontsize=14, fontweight='bold') ax.set_xticks(x_pos + width) ax.set_xticklabels(n_steps_sample) ax.legend(frameon=True, shadow=True) ax.grid(True, alpha=0.3, axis='y', linestyle='--') plt.tight_layout() plt.savefig('gate_count_comparison.png', dpi=300, bbox_inches='tight') plt.show()
if __name__ == "__main__": n_steps_range, results = analyze_circuit_optimization() plot_results(n_steps_range, results) print("\n" + "=" * 70) print("Analysis complete! Graphs saved.") print("=" * 70)
|