Skip to main content

vqe_h2/
vqe_h2.rs

1//! Variational Quantum Eigensolver (VQE) for H2 Molecule
2//!
3//! This example demonstrates a complete VQE implementation for finding the ground state
4//! energy of the hydrogen molecule (H2) using various components from the optimization module.
5//!
6//! The example showcases:
7//! - Multiple ansatz architectures (Hardware-Efficient, Real Amplitudes, Efficient SU(2), Custom)
8//! - Different gradient methods (Parameter-Shift Rule, Finite Difference)
9//! - Various optimizers (Adam, Gradient Descent)
10//! - Quantum Natural Gradient
11//! - Custom H2 Hamiltonian construction
12//! - Comparison of different approaches
13
14use logosq::circuits::Circuit;
15use logosq::optimization::ansatz::{
16    Ansatz, EfficientSU2Ansatz, EntanglingGate, EntanglingPattern, HardwareEfficientAnsatz,
17    ParameterizedCircuit, RealAmplitudesAnsatz,
18};
19use logosq::optimization::gradient::{FiniteDifference, GradientMethod, ParameterShift};
20use logosq::optimization::observable::{Observable, Pauli, PauliObservable, PauliTerm};
21use logosq::optimization::optimizer::{Adam, GradientDescent};
22use logosq::optimization::qng::QuantumNaturalGradient;
23use logosq::optimization::vqe::{VQEResult, VQE};
24use logosq::states::State;
25use ndarray::Array2;
26use num_complex::Complex64;
27use std::f64::consts::PI;
28
29/// Creates the H2 molecular Hamiltonian in minimal STO-3G basis (4 qubits)
30///
31/// The Hamiltonian is represented as a sum of Pauli terms:
32/// H = Σᵢ cᵢ Pᵢ
33///
34/// ## How Coefficients Are Determined
35///
36/// The coefficients come from quantum chemistry calculations:
37///
38/// 1. **Molecular Geometry**: H2 at equilibrium (R = 0.74 Å)
39/// 2. **Basis Set**: STO-3G (4 spin-orbitals → 4 qubits)
40/// 3. **Compute Integrals**: One-electron (hᵢⱼ) and two-electron (hᵢⱼₖₗ) integrals
41/// 4. **Hartree-Fock**: Solve for molecular orbitals
42/// 5. **Second Quantization**: H = Σ hᵢⱼ aᵢ†aⱼ + ½ Σ hᵢⱼₖₗ aᵢ†aⱼ†aₖaₗ
43/// 6. **Jordan-Wigner**: Map fermionic operators → Pauli operators
44///
45/// Each coefficient cᵢ is a linear combination of molecular integrals transformed
46/// through the JW mapping. See `examples/HAMILTONIAN_COEFFICIENTS.md` for details.
47///
48/// ## Coefficient Values
49///
50/// These coefficients are based on standard H2 STO-3G calculations at equilibrium
51/// geometry (R = 0.74 Å) using Jordan-Wigner transformation. The values come from
52/// quantum chemistry integrals computed via Hartree-Fock method.
53///
54/// **Note**: The ground state energy from these coefficients may differ from
55/// the literature value of -1.137 Ha depending on the specific basis set
56/// implementation and integral calculation method used. This is normal and
57/// reflects the approximations inherent in minimal basis sets.
58fn create_h2_hamiltonian() -> PauliObservable {
59    let num_qubits = 4;
60    let mut hamiltonian = PauliObservable::new(num_qubits);
61
62    // Identity term (nuclear repulsion + constant offset from JW transformation)
63    // This includes: nuclear repulsion energy (1/R) + constant terms from
64    // transforming fermionic operators to Pauli operators
65    hamiltonian.add_term(PauliTerm::new(
66        -0.8097,
67        vec![Pauli::I, Pauli::I, Pauli::I, Pauli::I],
68    ));
69
70    // Single-qubit Z terms (one-electron integrals)
71    hamiltonian.add_term(PauliTerm::new(
72        0.1712,
73        vec![Pauli::Z, Pauli::I, Pauli::I, Pauli::I],
74    ));
75    hamiltonian.add_term(PauliTerm::new(
76        0.1712,
77        vec![Pauli::I, Pauli::Z, Pauli::I, Pauli::I],
78    ));
79    hamiltonian.add_term(PauliTerm::new(
80        0.1712,
81        vec![Pauli::I, Pauli::I, Pauli::Z, Pauli::I],
82    ));
83    hamiltonian.add_term(PauliTerm::new(
84        0.1712,
85        vec![Pauli::I, Pauli::I, Pauli::I, Pauli::Z],
86    ));
87
88    // Two-qubit ZZ interactions (electron-electron repulsion)
89    hamiltonian.add_term(PauliTerm::new(
90        -0.2228,
91        vec![Pauli::Z, Pauli::Z, Pauli::I, Pauli::I],
92    ));
93    hamiltonian.add_term(PauliTerm::new(
94        -0.2228,
95        vec![Pauli::I, Pauli::I, Pauli::Z, Pauli::Z],
96    ));
97    hamiltonian.add_term(PauliTerm::new(
98        0.1656,
99        vec![Pauli::Z, Pauli::I, Pauli::Z, Pauli::I],
100    ));
101    hamiltonian.add_term(PauliTerm::new(
102        0.1656,
103        vec![Pauli::I, Pauli::Z, Pauli::I, Pauli::Z],
104    ));
105    hamiltonian.add_term(PauliTerm::new(
106        0.1656,
107        vec![Pauli::Z, Pauli::I, Pauli::I, Pauli::Z],
108    ));
109    hamiltonian.add_term(PauliTerm::new(
110        0.1656,
111        vec![Pauli::I, Pauli::Z, Pauli::Z, Pauli::I],
112    ));
113
114    // XX and YY terms (hopping/exchange terms)
115    hamiltonian.add_term(PauliTerm::new(
116        0.1712,
117        vec![Pauli::X, Pauli::X, Pauli::I, Pauli::I],
118    ));
119    hamiltonian.add_term(PauliTerm::new(
120        0.1712,
121        vec![Pauli::I, Pauli::I, Pauli::X, Pauli::X],
122    ));
123    hamiltonian.add_term(PauliTerm::new(
124        0.1206,
125        vec![Pauli::Y, Pauli::Y, Pauli::I, Pauli::I],
126    ));
127    hamiltonian.add_term(PauliTerm::new(
128        0.1206,
129        vec![Pauli::I, Pauli::I, Pauli::Y, Pauli::Y],
130    ));
131
132    // Cross terms
133    hamiltonian.add_term(PauliTerm::new(
134        0.0453,
135        vec![Pauli::X, Pauli::X, Pauli::Z, Pauli::Z],
136    ));
137    hamiltonian.add_term(PauliTerm::new(
138        0.0453,
139        vec![Pauli::Y, Pauli::Y, Pauli::Z, Pauli::Z],
140    ));
141
142    hamiltonian
143}
144
145/// Compute the exact ground state energy by diagonalizing the Hamiltonian
146/// This builds the full 2^n × 2^n matrix and finds its minimum eigenvalue
147fn compute_exact_ground_state_energy(hamiltonian: &PauliObservable) -> f64 {
148    let n = hamiltonian.num_qubits;
149    let dim = 1 << n;
150
151    // Build the full matrix representation
152    let mut matrix = Array2::<Complex64>::zeros((dim, dim));
153
154    // Iterate over each Pauli term and add its contribution
155    for term in &hamiltonian.terms {
156        let pauli_matrices: Vec<Array2<Complex64>> =
157            term.paulis.iter().map(|p| p.matrix()).collect();
158
159        // Build the tensor product of all Pauli matrices
160        let mut term_matrix = Array2::<Complex64>::ones((1, 1));
161        for pauli_mat in &pauli_matrices {
162            // Compute Kronecker product: term_matrix ⊗ pauli_mat
163            let (rows1, cols1) = (term_matrix.shape()[0], term_matrix.shape()[1]);
164            let (rows2, cols2) = (pauli_mat.shape()[0], pauli_mat.shape()[1]);
165
166            let mut new_matrix = Array2::<Complex64>::zeros((rows1 * rows2, cols1 * cols2));
167            for i in 0..rows1 {
168                for j in 0..cols1 {
169                    for k in 0..rows2 {
170                        for l in 0..cols2 {
171                            new_matrix[[i * rows2 + k, j * cols2 + l]] =
172                                term_matrix[[i, j]] * pauli_mat[[k, l]];
173                        }
174                    }
175                }
176            }
177            term_matrix = new_matrix;
178        }
179
180        // Add this term to the full Hamiltonian (scaled by coefficient)
181        for i in 0..dim {
182            for j in 0..dim {
183                matrix[[i, j]] += Complex64::new(term.coefficient, 0.0) * term_matrix[[i, j]];
184            }
185        }
186    }
187
188    // For a 16x16 matrix, we can compute eigenvalues more directly
189    // Use inverse power iteration with shift to find minimum eigenvalue
190    // First, find an upper bound for eigenvalues
191    let mut max_eigenvalue = f64::NEG_INFINITY;
192    for i in 0..dim {
193        max_eigenvalue = max_eigenvalue.max(matrix[[i, i]].re);
194    }
195
196    // Use shift so that (H - shift*I) has negative eigenvalues
197    // Then apply inverse power iteration to find the eigenvalue closest to shift
198    let shift = max_eigenvalue + 10.0; // Shift to ensure all eigenvalues are negative
199    let mut shifted_matrix = matrix.clone();
200    for i in 0..dim {
201        shifted_matrix[[i, i]] -= Complex64::new(shift, 0.0);
202    }
203
204    // Initialize random state
205    use rand::Rng;
206    let mut rng = rand::thread_rng();
207    let mut state_vec = Array2::<Complex64>::zeros((dim, 1));
208    for i in 0..dim {
209        state_vec[[i, 0]] = Complex64::new(rng.gen::<f64>(), rng.gen::<f64>());
210    }
211
212    // Normalize (unused for now, but kept for future inverse power iteration)
213    let _norm: f64 = state_vec.iter().map(|x| x.norm_sqr()).sum::<f64>().sqrt();
214
215    // Inverse power iteration: solve (H - shift*I) * x = state_vec
216    // Since we don't have a direct solver, use iterative refinement
217    // Actually, for small matrices, we can use a simple approach:
218    // Try many random states and minimize Rayleigh quotient
219
220    let mut min_energy = f64::INFINITY;
221
222    // Try all computational basis states
223    for i in 0..dim {
224        let mut state = State::zero_state(n);
225        state.vector_mut()[i] = Complex64::new(1.0, 0.0);
226        let energy = hamiltonian.expectation(&state);
227        min_energy = min_energy.min(energy);
228    }
229
230    // Use power iteration with Rayleigh quotient to find minimum eigenvalue
231    // Start from the best computational basis state
232    let mut best_state_idx = 0;
233    let mut best_basis_energy = f64::INFINITY;
234    for i in 0..dim {
235        let mut state = State::zero_state(n);
236        state.vector_mut()[i] = Complex64::new(1.0, 0.0);
237        let energy = hamiltonian.expectation(&state);
238        if energy < best_basis_energy {
239            best_basis_energy = energy;
240            best_state_idx = i;
241        }
242    }
243    min_energy = best_basis_energy;
244
245    // Initialize state vector from best computational basis state
246    let mut state_vec = Array2::<Complex64>::zeros((dim, 1));
247    state_vec[[best_state_idx, 0]] = Complex64::new(1.0, 0.0);
248
249    // Power iteration to find ground state (minimum eigenvalue)
250    // For minimum eigenvalue, we use: (H - λ_max*I) has negative eigenvalues
251    // The minimum eigenvalue of H corresponds to maximum eigenvalue of (λ_max*I - H)
252    let lambda_max = max_eigenvalue + 10.0;
253    let mut transformed_matrix = Array2::<Complex64>::zeros((dim, dim));
254    for i in 0..dim {
255        for j in 0..dim {
256            transformed_matrix[[i, j]] = if i == j {
257                Complex64::new(lambda_max, 0.0) - matrix[[i, j]]
258            } else {
259                -matrix[[i, j]]
260            };
261        }
262    }
263
264    // Power iteration on transformed matrix to find maximum eigenvalue
265    for iteration in 0..200 {
266        let new_state = transformed_matrix.dot(&state_vec);
267        let norm: f64 = new_state.iter().map(|x| x.norm_sqr()).sum::<f64>().sqrt();
268        state_vec = &new_state / norm;
269
270        // Compute Rayleigh quotient for transformed matrix
271        let numerator = (state_vec.t().dot(&transformed_matrix.dot(&state_vec)))[[0, 0]];
272        let transformed_max_eigenval = numerator.re;
273
274        // Convert back to minimum eigenvalue of original matrix
275        let current_min_energy = lambda_max - transformed_max_eigenval;
276        min_energy = min_energy.min(current_min_energy);
277
278        // Check convergence
279        if iteration > 10 && (current_min_energy - min_energy).abs() < 1e-8 {
280            break;
281        }
282    }
283
284    min_energy
285}
286
287/// Creates a chemistry-inspired ansatz for H2
288///
289/// This custom ansatz is inspired by the structure of quantum chemistry ansatzes,
290/// using a Hartree-Fock preparation followed by parameterized excitations.
291fn create_chemistry_ansatz() -> ParameterizedCircuit<impl Fn(&[f64]) -> Circuit> {
292    ParameterizedCircuit::new(
293        4, // 4 qubits for H2
294        8, // 8 parameters
295        move |params| {
296            let mut circuit = Circuit::new(4);
297
298            // Hartree-Fock preparation (|1100⟩ state - two electrons in bonding orbital)
299            circuit.x(0);
300            circuit.x(1);
301
302            // Parameterized single excitations (UCCSD-inspired)
303            // Rotation around X for single excitations
304            circuit.rx(0, params[0]);
305            circuit.rx(1, params[1]);
306            circuit.rx(2, params[2]);
307            circuit.rx(3, params[3]);
308
309            // Entangling layer for correlations
310            circuit.cnot(0, 2);
311            circuit.cnot(1, 3);
312            circuit.cnot(0, 1);
313            circuit.cnot(2, 3);
314
315            // Final rotations
316            circuit.ry(0, params[4]);
317            circuit.ry(1, params[5]);
318            circuit.ry(2, params[6]);
319            circuit.ry(3, params[7]);
320
321            circuit
322        },
323    )
324}
325
326/// Run VQE with Hardware-Efficient Ansatz using Adam optimizer
327fn run_vqe_hardware_efficient_adam(hamiltonian: &PauliObservable, depth: usize) -> VQEResult {
328    println!("\n{}", "=".repeat(70));
329    println!("Hardware-Efficient Ansatz (depth={}) with Adam", depth);
330    println!("{}", "=".repeat(70));
331
332    let ansatz =
333        HardwareEfficientAnsatz::new(4, depth, EntanglingGate::CNOT, EntanglingPattern::Linear);
334
335    let gradient_method = ParameterShift::new();
336    let optimizer = Adam::new(0.01, 200).with_tolerance(1e-6);
337
338    let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
339    vqe.verbose = true;
340    vqe.run_random()
341}
342
343/// Run VQE with Hardware-Efficient Ansatz using Gradient Descent optimizer
344fn run_vqe_hardware_efficient_gd(hamiltonian: &PauliObservable, depth: usize) -> VQEResult {
345    println!("\n{}", "=".repeat(70));
346    println!(
347        "Hardware-Efficient Ansatz (depth={}) with Gradient Descent",
348        depth
349    );
350    println!("{}", "=".repeat(70));
351
352    let ansatz =
353        HardwareEfficientAnsatz::new(4, depth, EntanglingGate::CNOT, EntanglingPattern::Linear);
354
355    let gradient_method = ParameterShift::new();
356    let optimizer = GradientDescent::new(0.01, 200).with_tolerance(1e-6);
357
358    let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
359    vqe.verbose = true;
360    vqe.run_random()
361}
362
363/// Run VQE with Real Amplitudes Ansatz
364fn run_vqe_real_amplitudes(hamiltonian: &PauliObservable, depth: usize) -> VQEResult {
365    println!("\n{}", "=".repeat(70));
366    println!("Real Amplitudes Ansatz (depth={})", depth);
367    println!("{}", "=".repeat(70));
368
369    let ansatz = RealAmplitudesAnsatz::new(4, depth);
370    let gradient_method = ParameterShift::new();
371    let optimizer = Adam::new(0.01, 200).with_tolerance(1e-6);
372
373    let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
374    vqe.verbose = true;
375    vqe.run_random()
376}
377
378/// Run VQE with Efficient SU(2) Ansatz
379fn run_vqe_efficient_su2(hamiltonian: &PauliObservable, depth: usize) -> VQEResult {
380    println!("\n{}", "=".repeat(70));
381    println!("Efficient SU(2) Ansatz (depth={})", depth);
382    println!("{}", "=".repeat(70));
383
384    let ansatz = EfficientSU2Ansatz::new(4, depth);
385    let gradient_method = ParameterShift::new();
386    let optimizer = Adam::new(0.01, 200).with_tolerance(1e-6);
387
388    let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
389    vqe.verbose = true;
390    vqe.run_random()
391}
392
393/// Run VQE with custom chemistry-inspired ansatz
394fn run_vqe_chemistry_ansatz(hamiltonian: &PauliObservable) -> VQEResult {
395    println!("\n{}", "=".repeat(70));
396    println!("Chemistry-Inspired Custom Ansatz");
397    println!("{}", "=".repeat(70));
398
399    let ansatz = create_chemistry_ansatz();
400    let gradient_method = ParameterShift::new();
401    let optimizer = Adam::new(0.01, 200).with_tolerance(1e-6);
402
403    let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
404    vqe.verbose = true;
405    vqe.run_random()
406}
407
408/// Compare Parameter-Shift Rule vs Finite Difference gradients
409fn compare_gradient_methods(hamiltonian: &PauliObservable) {
410    println!("\n{}", "=".repeat(70));
411    println!("Gradient Method Comparison");
412    println!("{}", "=".repeat(70));
413
414    let ansatz =
415        HardwareEfficientAnsatz::new(4, 2, EntanglingGate::CNOT, EntanglingPattern::Linear);
416
417    let parameters: Vec<f64> = (0..ansatz.num_parameters())
418        .map(|i| (i as f64) * 0.1)
419        .collect();
420
421    let ps_method = ParameterShift::new();
422    let fd_method = FiniteDifference::new(1e-7);
423
424    println!(
425        "Computing gradients with {} parameters...",
426        parameters.len()
427    );
428
429    let ps_gradient = ps_method.compute_gradient(&ansatz, hamiltonian, &parameters);
430    let fd_gradient = fd_method.compute_gradient(&ansatz, hamiltonian, &parameters);
431
432    println!("\nParameter-Shift Rule gradient:");
433    for (i, g) in ps_gradient.iter().enumerate() {
434        println!("  ∂E/∂θ[{}] = {:.6}", i, g);
435    }
436
437    println!("\nFinite Difference gradient:");
438    for (i, g) in fd_gradient.iter().enumerate() {
439        println!("  ∂E/∂θ[{}] = {:.6}", i, g);
440    }
441
442    // Compare gradients
443    let max_diff = ps_gradient
444        .iter()
445        .zip(fd_gradient.iter())
446        .map(|(ps, fd)| (ps - fd).abs())
447        .fold(0.0, f64::max);
448
449    println!("\nMaximum difference: {:.6}", max_diff);
450
451    if max_diff < 1e-4 {
452        println!("✓ Gradients match within tolerance!");
453    } else {
454        println!("⚠ Warning: Significant difference between methods");
455    }
456}
457
458/// Demonstrate Quantum Natural Gradient
459fn demonstrate_qng(hamiltonian: &PauliObservable) {
460    println!("\n{}", "=".repeat(70));
461    println!("Quantum Natural Gradient Demonstration");
462    println!("{}", "=".repeat(70));
463
464    let ansatz =
465        HardwareEfficientAnsatz::new(4, 2, EntanglingGate::CNOT, EntanglingPattern::Linear);
466
467    let parameters: Vec<f64> = (0..ansatz.num_parameters())
468        .map(|i| (i as f64) * 0.1)
469        .collect();
470
471    let gradient_method = ParameterShift::new();
472    let qng = QuantumNaturalGradient::new();
473
474    println!("Computing standard gradient...");
475    let standard_grad = gradient_method.compute_gradient(&ansatz, hamiltonian, &parameters);
476
477    println!("Computing quantum natural gradient...");
478    let nat_grad =
479        qng.compute_natural_gradient(&ansatz, hamiltonian, &gradient_method, &parameters);
480
481    println!(
482        "\nStandard gradient norm: {:.6}",
483        standard_grad.iter().map(|g| g * g).sum::<f64>().sqrt()
484    );
485    println!(
486        "Natural gradient norm: {:.6}",
487        nat_grad.iter().map(|g| g * g).sum::<f64>().sqrt()
488    );
489
490    println!("\nComputing metric tensor...");
491    let metric = qng.compute_metric_tensor(&ansatz, &parameters);
492    println!("Metric tensor shape: {:?}", metric.shape());
493    println!("Metric tensor diagonal (first 5):");
494    for i in 0..(parameters.len().min(5)) {
495        println!("  g[{}, {}] = {:.6}", i, i, metric[[i, i]]);
496    }
497}
498
499/// Test different entangling patterns
500fn test_entangling_patterns(hamiltonian: &PauliObservable) {
501    println!("\n{}", "=".repeat(70));
502    println!("Entangling Pattern Comparison");
503    println!("{}", "=".repeat(70));
504
505    let patterns = vec![
506        ("Linear", EntanglingPattern::Linear),
507        ("Circular", EntanglingPattern::Circular),
508        ("Full", EntanglingPattern::Full),
509    ];
510
511    for (name, pattern) in patterns {
512        println!("\nTesting {} pattern...", name);
513
514        let ansatz = HardwareEfficientAnsatz::new(4, 2, EntanglingGate::CNOT, pattern);
515
516        let gradient_method = ParameterShift::new();
517        let optimizer = Adam::new(0.01, 100).with_tolerance(1e-6);
518
519        let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
520        vqe.verbose = false;
521
522        let result = vqe.run_random();
523        println!("  Final energy: {:.6}", result.ground_state_energy);
524        println!("  Iterations: {}", result.num_iterations);
525    }
526}
527
528/// Test different entangling gates
529fn test_entangling_gates(hamiltonian: &PauliObservable) {
530    println!("\n{}", "=".repeat(70));
531    println!("Entangling Gate Comparison");
532    println!("{}", "=".repeat(70));
533
534    let gates = vec![
535        ("CNOT", EntanglingGate::CNOT),
536        ("CZ", EntanglingGate::CZ),
537        ("RZZ(π/2)", EntanglingGate::RZZ(PI / 2.0)),
538    ];
539
540    for (name, gate) in gates {
541        println!("\nTesting {} gate...", name);
542
543        let ansatz = HardwareEfficientAnsatz::new(4, 2, gate, EntanglingPattern::Linear);
544
545        let gradient_method = ParameterShift::new();
546        let optimizer = Adam::new(0.01, 100).with_tolerance(1e-6);
547
548        let mut vqe = VQE::new(ansatz, hamiltonian.clone(), gradient_method, optimizer);
549        vqe.verbose = false;
550
551        let result = vqe.run_random();
552        println!("  Final energy: {:.6}", result.ground_state_energy);
553        println!("  Iterations: {}", result.num_iterations);
554    }
555}
556
557/// Analyze convergence history
558fn analyze_convergence(result: &VQEResult, name: &str) {
559    println!("\n{} Convergence Analysis:", name);
560    println!("  Initial energy: {:.6}", result.convergence_history[0]);
561    println!("  Final energy: {:.6}", result.ground_state_energy);
562    println!(
563        "  Energy reduction: {:.6}",
564        result.convergence_history[0] - result.ground_state_energy
565    );
566    println!("  Iterations: {}", result.num_iterations);
567
568    // Check if energy is decreasing
569    let mut decreasing = true;
570    for i in 1..result.convergence_history.len() {
571        if result.convergence_history[i] > result.convergence_history[i - 1] + 1e-6 {
572            decreasing = false;
573            break;
574        }
575    }
576    println!("  Monotonically decreasing: {}", decreasing);
577}
578
579/// Main function demonstrating comprehensive VQE for H2
580fn main() {
581    println!("{}", "=".repeat(70));
582    println!("Variational Quantum Eigensolver for H2 Molecule");
583    println!("{}", "=".repeat(70));
584    println!("\nThis example demonstrates various optimization techniques");
585    println!("for finding the ground state energy of H2 using VQE.\n");
586
587    // Create H2 Hamiltonian
588    let hamiltonian = create_h2_hamiltonian();
589    println!(
590        "H2 Hamiltonian created with {} Pauli terms",
591        hamiltonian.terms.len()
592    );
593
594    // Test expectation value at initial state
595    let initial_state = State::zero_state(4);
596    let initial_energy = hamiltonian.expectation(&initial_state);
597    println!("Initial state energy (|0000⟩): {:.6}", initial_energy);
598
599    // Compute exact ground state energy by diagonalization
600    println!("Computing exact ground state energy by diagonalizing Hamiltonian...");
601    let exact_energy = compute_exact_ground_state_energy(&hamiltonian);
602    println!(
603        "Exact ground state energy (from this Hamiltonian): {:.6} Ha",
604        exact_energy
605    );
606
607    // Expected ground state energy for H2 at equilibrium
608    // Note: Different STO-3G implementations may give slightly different values
609    println!("Target ground state energy (literature, STO-3G): ~ -1.137 Ha (Hartree)");
610    println!("Note: The exact energy depends on the specific basis set implementation.");
611    println!("First-principles computed energy may differ from literature values.\n");
612
613    // ============================================================================
614    // Run VQE with different ansatzes
615    // ============================================================================
616
617    let result_he_adam = run_vqe_hardware_efficient_adam(&hamiltonian, 3);
618    analyze_convergence(&result_he_adam, "Hardware-Efficient (Adam)");
619
620    let result_he_gd = run_vqe_hardware_efficient_gd(&hamiltonian, 3);
621    analyze_convergence(&result_he_gd, "Hardware-Efficient (Gradient Descent)");
622
623    let result_ra = run_vqe_real_amplitudes(&hamiltonian, 3);
624    analyze_convergence(&result_ra, "Real Amplitudes");
625
626    let result_su2 = run_vqe_efficient_su2(&hamiltonian, 2);
627    analyze_convergence(&result_su2, "Efficient SU(2)");
628
629    let result_chem = run_vqe_chemistry_ansatz(&hamiltonian);
630    analyze_convergence(&result_chem, "Chemistry-Inspired");
631
632    // ============================================================================
633    // Gradient method comparison
634    // ============================================================================
635
636    compare_gradient_methods(&hamiltonian);
637
638    // ============================================================================
639    // Quantum Natural Gradient
640    // ============================================================================
641
642    demonstrate_qng(&hamiltonian);
643
644    // ============================================================================
645    // Ansatz architecture comparisons
646    // ============================================================================
647
648    test_entangling_patterns(&hamiltonian);
649    test_entangling_gates(&hamiltonian);
650
651    // ============================================================================
652    // Final summary
653    // ============================================================================
654
655    println!("\n{}", "=".repeat(70));
656    println!("Summary");
657    println!("{}", "=".repeat(70));
658    println!("\nBest results:");
659    println!(
660        "  Hardware-Efficient (Adam): {:.6} Ha",
661        result_he_adam.ground_state_energy
662    );
663    println!("  Real Amplitudes: {:.6} Ha", result_ra.ground_state_energy);
664    println!(
665        "  Efficient SU(2): {:.6} Ha",
666        result_su2.ground_state_energy
667    );
668    println!(
669        "  Chemistry-Inspired: {:.6} Ha",
670        result_chem.ground_state_energy
671    );
672
673    let best_energy = [
674        result_he_adam.ground_state_energy,
675        result_ra.ground_state_energy,
676        result_su2.ground_state_energy,
677        result_chem.ground_state_energy,
678    ]
679    .iter()
680    .fold(f64::INFINITY, |a, &b| a.min(b));
681
682    println!("\nBest energy found: {:.6} Ha", best_energy);
683    println!("Note: Compare this with the exact ground state energy shown at the start.");
684    println!("If VQE energy is close to the exact energy, VQE is working correctly.");
685    println!(
686        "If exact energy differs significantly from -1.137 Ha, verify Hamiltonian coefficients."
687    );
688
689    println!("\n{}", "=".repeat(70));
690    println!("Example completed successfully!");
691    println!("{}", "=".repeat(70));
692}