quantrs2-core 0.1.3

Core types and traits for the QuantRS2 quantum computing framework
Documentation
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// ADAPT-VQE: Adaptive Derivative-Assembled Pseudo-Trotter VQE
//
// A state-of-the-art quantum chemistry algorithm that adaptively constructs
// the ansatz circuit during optimization, avoiding the barren plateau problem
// and reducing circuit depth.
//
// Reference: Grimsley, H. R., et al. (2019). "An adaptive variational algorithm for exact molecular simulations on a quantum computer"
// Nature Communications 10, 3007

use crate::error::QuantRS2Error;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::{Complex64};
use scirs2_core::random::prelude::*;
use scirs2_core::ndarray::ndarray_linalg::Solve;
use scirs2_optimize::{Optimizer, OptimizerConfig, OptimizerMethod};
use std::collections::HashMap;

/// Fermionic operator pool for quantum chemistry
///
/// Contains the complete set of single and double excitation operators
/// that can be used to construct the ADAPT-VQE ansatz.
#[derive(Debug, Clone)]
pub struct FermionicOperatorPool {
    /// Single excitation operators (a†_p a_q)
    pub single_excitations: Vec<FermionicOperator>,
    /// Double excitation operators (a†_p a†_q a_r a_s)
    pub double_excitations: Vec<FermionicOperator>,
    /// Number of spin orbitals
    pub num_orbitals: usize,
}

impl FermionicOperatorPool {
    /// Create a new operator pool for a given number of spin orbitals
    pub fn new(num_orbitals: usize) -> Self {
        let mut single_excitations = Vec::new();
        let mut double_excitations = Vec::new();

        // Generate all single excitations
        for p in 0..num_orbitals {
            for q in 0..num_orbitals {
                if p != q {
                    single_excitations.push(FermionicOperator::single_excitation(p, q));
                }
            }
        }

        // Generate all double excitations
        for p in 0..num_orbitals {
            for q in p + 1..num_orbitals {
                for r in 0..num_orbitals {
                    for s in r + 1..num_orbitals {
                        if (p, q) != (r, s) {
                            double_excitations.push(
                                FermionicOperator::double_excitation(p, q, r, s)
                            );
                        }
                    }
                }
            }
        }

        Self {
            single_excitations,
            double_excitations,
            num_orbitals,
        }
    }

    /// Get all operators in the pool
    pub fn all_operators(&self) -> Vec<FermionicOperator> {
        let mut operators = Vec::new();
        operators.extend(self.single_excitations.clone());
        operators.extend(self.double_excitations.clone());
        operators
    }

    /// Get operator count
    pub fn size(&self) -> usize {
        self.single_excitations.len() + self.double_excitations.len()
    }
}

/// Fermionic operator representation
#[derive(Debug, Clone, PartialEq)]
pub struct FermionicOperator {
    /// Creation operator indices
    pub creation_ops: Vec<usize>,
    /// Annihilation operator indices
    pub annihilation_ops: Vec<usize>,
    /// Operator label for identification
    pub label: String,
}

impl FermionicOperator {
    /// Create a single excitation operator a†_p a_q
    pub fn single_excitation(p: usize, q: usize) -> Self {
        Self {
            creation_ops: vec![p],
            annihilation_ops: vec![q],
            label: format!("E_{{{},{}}}", p, q),
        }
    }

    /// Create a double excitation operator a†_p a†_q a_r a_s
    pub fn double_excitation(p: usize, q: usize, r: usize, s: usize) -> Self {
        Self {
            creation_ops: vec![p, q],
            annihilation_ops: vec![r, s],
            label: format!("E_{{{},{},{},{}}}", p, q, r, s),
        }
    }

    /// Convert to Pauli string representation using Jordan-Wigner transformation
    pub fn to_pauli_string(&self, num_qubits: usize) -> PauliString {
        // Simplified Jordan-Wigner transformation
        // Full implementation would require more sophisticated mapping
        let mut pauli_ops = vec![PauliOp::I; num_qubits];

        // Apply creation operators
        for &idx in &self.creation_ops {
            if idx < num_qubits {
                pauli_ops[idx] = PauliOp::X;
            }
        }

        // Apply annihilation operators
        for &idx in &self.annihilation_ops {
            if idx < num_qubits {
                pauli_ops[idx] = PauliOp::Y;
            }
        }

        PauliString {
            operators: pauli_ops,
            coefficient: Complex64::new(1.0, 0.0),
        }
    }
}

/// Pauli operator types
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PauliOp {
    I, // Identity
    X, // Pauli-X
    Y, // Pauli-Y
    Z, // Pauli-Z
}

/// Pauli string representation of a quantum operator
#[derive(Debug, Clone)]
pub struct PauliString {
    /// Pauli operators for each qubit
    pub operators: Vec<PauliOp>,
    /// Overall coefficient
    pub coefficient: Complex64,
}

impl PauliString {
    /// Compute expectation value <ψ|P|ψ> for this Pauli string
    pub fn expectation_value(&self, state: &Array1<Complex64>) -> Complex64 {
        // Apply Pauli operator to state and compute overlap
        let transformed = self.apply_to_state(state);
        state.iter()
            .zip(transformed.iter())
            .map(|(a, b)| a.conj() * b)
            .sum::<Complex64>()
            * self.coefficient
    }

    /// Apply Pauli string to a quantum state
    pub fn apply_to_state(&self, state: &Array1<Complex64>) -> Array1<Complex64> {
        let n = self.operators.len();
        let dim = 1 << n;
        let mut result = Array1::<Complex64>::zeros(dim);

        for i in 0..dim {
            let mut new_index = i;
            let mut phase = Complex64::new(1.0, 0.0);

            for (qubit, &op) in self.operators.iter().enumerate() {
                let bit = (i >> qubit) & 1;
                match op {
                    PauliOp::I => {},
                    PauliOp::X => {
                        new_index ^= 1 << qubit; // Flip bit
                    },
                    PauliOp::Y => {
                        new_index ^= 1 << qubit;
                        phase *= if bit == 0 {
                            Complex64::new(0.0, 1.0)
                        } else {
                            Complex64::new(0.0, -1.0)
                        };
                    },
                    PauliOp::Z => {
                        if bit == 1 {
                            phase *= Complex64::new(-1.0, 0.0);
                        }
                    },
                }
            }

            result[new_index] += phase * state[i];
        }

        result
    }

    /// Compute commutator [H, P] where H is the Hamiltonian
    pub fn commutator_with_hamiltonian(
        &self,
        hamiltonian: &MolecularHamiltonian,
        state: &Array1<Complex64>,
    ) -> Complex64 {
        // [H, P] = HP - PH
        let hp_state = hamiltonian.apply_to_state(&self.apply_to_state(state));
        let ph_state = self.apply_to_state(&hamiltonian.apply_to_state(state));

        state.iter()
            .zip(hp_state.iter().zip(ph_state.iter()))
            .map(|(psi, (hp, ph))| psi.conj() * (hp - ph))
            .sum()
    }
}

/// Molecular Hamiltonian in second-quantized form
#[derive(Debug, Clone)]
pub struct MolecularHamiltonian {
    /// One-electron integrals
    pub one_electron_integrals: Array2<f64>,
    /// Two-electron integrals (4D tensor flattened)
    pub two_electron_integrals: HashMap<(usize, usize, usize, usize), f64>,
    /// Nuclear repulsion energy
    pub nuclear_repulsion: f64,
    /// Number of spin orbitals
    pub num_orbitals: usize,
}

impl MolecularHamiltonian {
    /// Create a new molecular Hamiltonian
    pub fn new(
        one_electron: Array2<f64>,
        two_electron: HashMap<(usize, usize, usize, usize), f64>,
        nuclear_repulsion: f64,
    ) -> Self {
        let num_orbitals = one_electron.nrows();
        Self {
            one_electron_integrals: one_electron,
            two_electron_integrals: two_electron,
            nuclear_repulsion,
            num_orbitals,
        }
    }

    /// Apply Hamiltonian to a quantum state
    pub fn apply_to_state(&self, state: &Array1<Complex64>) -> Array1<Complex64> {
        // Simplified: In practice, would convert to Pauli decomposition
        // and apply each term. For now, returns a placeholder.
        state.clone()
    }

    /// Compute energy expectation value <ψ|H|ψ>
    pub fn expectation_value(&self, state: &Array1<Complex64>) -> f64 {
        let h_psi = self.apply_to_state(state);
        let energy: Complex64 = state.iter()
            .zip(h_psi.iter())
            .map(|(a, b)| a.conj() * b)
            .sum();

        energy.re + self.nuclear_repulsion
    }
}

/// ADAPT-VQE algorithm configuration
#[derive(Debug, Clone)]
pub struct AdaptVQEConfig {
    /// Gradient threshold for operator selection
    pub gradient_threshold: f64,
    /// Maximum number of ADAPT iterations
    pub max_iterations: usize,
    /// Energy convergence threshold
    pub energy_threshold: f64,
    /// Maximum VQE optimization steps per iteration
    pub max_vqe_steps: usize,
    /// Optimizer for parameter optimization
    pub optimizer_method: OptimizerMethod,
}

impl Default for AdaptVQEConfig {
    fn default() -> Self {
        Self {
            gradient_threshold: 1e-3,
            max_iterations: 50,
            energy_threshold: 1e-6,
            max_vqe_steps: 100,
            optimizer_method: OptimizerMethod::LBFGS,
        }
    }
}

/// ADAPT-VQE ansatz built adaptively
#[derive(Debug, Clone)]
pub struct AdaptAnsatz {
    /// Selected operators in order
    pub operators: Vec<FermionicOperator>,
    /// Optimized parameters for each operator
    pub parameters: Vec<f64>,
    /// Energy at each iteration
    pub energy_history: Vec<f64>,
}

impl AdaptAnsatz {
    /// Create an empty ansatz
    pub const fn new() -> Self {
        Self {
            operators: Vec::new(),
            parameters: Vec::new(),
            energy_history: Vec::new(),
        }
    }

    /// Add a new operator to the ansatz
    pub fn add_operator(&mut self, operator: FermionicOperator, parameter: f64) {
        self.operators.push(operator);
        self.parameters.push(parameter);
    }

    /// Get current circuit depth (number of operators)
    pub fn depth(&self) -> usize {
        self.operators.len()
    }

    /// Apply ansatz to a reference state
    pub fn apply_to_state(&self, reference_state: &Array1<Complex64>, num_qubits: usize) -> Array1<Complex64> {
        let mut state = reference_state.clone();

        for (operator, &theta) in self.operators.iter().zip(self.parameters.iter()) {
            let pauli_string = operator.to_pauli_string(num_qubits);

            // Apply exp(-iθP) using Pauli rotation
            // In practice, would use Trotter decomposition or other methods
            let rotation = self.apply_pauli_rotation(&pauli_string, theta);
            state = rotation.dot(&state);
        }

        state
    }

    /// Apply Pauli rotation exp(-iθP)
    fn apply_pauli_rotation(&self, pauli: &PauliString, theta: f64) -> Array2<Complex64> {
        let n = pauli.operators.len();
        let dim = 1 << n;

        // Simplified: construct rotation matrix
        // Full implementation would use efficient Pauli rotation circuits
        let mut rotation = Array2::<Complex64>::zeros((dim, dim));

        for i in 0..dim {
            for j in 0..dim {
                if i == j {
                    rotation[[i, j]] = Complex64::new((theta / 2.0).cos(), 0.0);
                }
            }
        }

        rotation
    }
}

impl Default for AdaptAnsatz {
    fn default() -> Self {
        Self::new()
    }
}

/// Main ADAPT-VQE algorithm implementation
#[derive(Debug)]
pub struct AdaptVQE {
    /// Molecular Hamiltonian
    pub hamiltonian: MolecularHamiltonian,
    /// Operator pool
    pub operator_pool: FermionicOperatorPool,
    /// Configuration
    pub config: AdaptVQEConfig,
    /// Current ansatz
    pub ansatz: AdaptAnsatz,
    /// Number of qubits required
    pub num_qubits: usize,
}

impl AdaptVQE {
    /// Create a new ADAPT-VQE instance
    pub fn new(
        hamiltonian: MolecularHamiltonian,
        num_qubits: usize,
        config: AdaptVQEConfig,
    ) -> Self {
        let operator_pool = FermionicOperatorPool::new(hamiltonian.num_orbitals);
        let ansatz = AdaptAnsatz::new();

        Self {
            hamiltonian,
            operator_pool,
            config,
            ansatz,
            num_qubits,
        }
    }

    /// Run the ADAPT-VQE algorithm
    pub fn run(&mut self, initial_state: &Array1<Complex64>) -> Result<AdaptVQEResult, QuantRS2Error> {
        let mut current_state = initial_state.clone();
        let mut iteration = 0;
        let mut converged = false;

        while iteration < self.config.max_iterations && !converged {
            // Step 1: Compute gradients for all operators in the pool
            let gradients = self.compute_operator_gradients(&current_state)?;

            // Step 2: Select operator with largest gradient magnitude
            let (max_gradient_idx, max_gradient) = gradients.iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| a.abs().partial_cmp(&b.abs()).unwrap_or(std::cmp::Ordering::Equal))
                .ok_or_else(|| QuantRS2Error::InvalidState("No gradients computed".to_string()))?;

            // Check convergence: if max gradient is below threshold, we're done
            if max_gradient.abs() < self.config.gradient_threshold {
                converged = true;
                break;
            }

            // Step 3: Add selected operator to ansatz with initial parameter = 0
            let selected_operator = self.operator_pool.all_operators()[max_gradient_idx].clone();
            self.ansatz.add_operator(selected_operator, 0.0);

            // Step 4: Optimize all parameters in the current ansatz
            let optimized_params = self.optimize_parameters(&current_state)?;
            self.ansatz.parameters = optimized_params;

            // Step 5: Update state and energy
            current_state = self.ansatz.apply_to_state(initial_state, self.num_qubits);
            let energy = self.hamiltonian.expectation_value(&current_state);
            self.ansatz.energy_history.push(energy);

            // Check energy convergence
            if iteration > 0 {
                let energy_change = (self.ansatz.energy_history[iteration] -
                                    self.ansatz.energy_history[iteration - 1]).abs();
                if energy_change < self.config.energy_threshold {
                    converged = true;
                }
            }

            iteration += 1;
        }

        Ok(AdaptVQEResult {
            final_energy: self.ansatz.energy_history.last().copied().unwrap_or(0.0),
            final_state: current_state,
            ansatz: self.ansatz.clone(),
            num_iterations: iteration,
            converged,
        })
    }

    /// Compute gradients for all operators in the pool
    fn compute_operator_gradients(&self, state: &Array1<Complex64>) -> Result<Vec<f64>, QuantRS2Error> {
        let mut gradients = Vec::new();

        for operator in self.operator_pool.all_operators() {
            let pauli_string = operator.to_pauli_string(self.num_qubits);

            // Gradient = <ψ|[H, A]|ψ> where A is the operator
            let gradient = pauli_string.commutator_with_hamiltonian(&self.hamiltonian, state);
            gradients.push(gradient.re);
        }

        Ok(gradients)
    }

    /// Optimize all parameters in the ansatz
    fn optimize_parameters(&self, initial_state: &Array1<Complex64>) -> Result<Vec<f64>, QuantRS2Error> {
        // Use SciRS2 optimizer
        let mut optimizer = Optimizer::new(OptimizerConfig {
            method: self.config.optimizer_method.clone(),
            max_iterations: self.config.max_vqe_steps,
            tolerance: 1e-6,
            ..Default::default()
        });

        // Initial guess: current parameters
        let initial_params = Array1::from_vec(self.ansatz.parameters.clone());

        // Objective function: energy expectation value
        let objective = |params: &Array1<f64>| -> f64 {
            let mut ansatz_copy = self.ansatz.clone();
            ansatz_copy.parameters = params.to_vec();
            let state = ansatz_copy.apply_to_state(initial_state, self.num_qubits);
            self.hamiltonian.expectation_value(&state)
        };

        // Run optimization
        match optimizer.minimize(&objective, &initial_params) {
            Ok(result) => Ok(result.x.to_vec()),
            Err(_) => Err(QuantRS2Error::OptimizationFailed(
                "Parameter optimization failed".to_string()
            ))
        }
    }

    /// Get current circuit depth
    pub fn get_circuit_depth(&self) -> usize {
        self.ansatz.depth()
    }

    /// Get operator pool size
    pub fn get_pool_size(&self) -> usize {
        self.operator_pool.size()
    }
}

/// Result from ADAPT-VQE algorithm
#[derive(Debug, Clone)]
pub struct AdaptVQEResult {
    /// Final ground state energy
    pub final_energy: f64,
    /// Final quantum state
    pub final_state: Array1<Complex64>,
    /// Constructed ansatz
    pub ansatz: AdaptAnsatz,
    /// Number of ADAPT iterations performed
    pub num_iterations: usize,
    /// Whether the algorithm converged
    pub converged: bool,
}

impl AdaptVQEResult {
    /// Get circuit depth of the final ansatz
    pub fn circuit_depth(&self) -> usize {
        self.ansatz.depth()
    }

    /// Get energy lowering from initial to final
    pub fn energy_lowering(&self) -> Option<f64> {
        if self.ansatz.energy_history.len() >= 2 {
            Some(self.ansatz.energy_history[0] - self.final_energy)
        } else {
            None
        }
    }

    /// Get convergence rate (energy change per iteration)
    pub fn convergence_rate(&self) -> f64 {
        if self.num_iterations > 1 {
            let energy_change = (self.ansatz.energy_history.first().unwrap_or(&0.0) -
                               self.final_energy).abs();
            energy_change / self.num_iterations as f64
        } else {
            0.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fermionic_operator_pool() {
        let pool = FermionicOperatorPool::new(4);

        // For 4 orbitals: 4*3 = 12 single excitations
        assert_eq!(pool.single_excitations.len(), 12);

        // Double excitations: C(4,2) * C(4,2) - overlaps
        assert!(pool.double_excitations.len() > 0);

        assert_eq!(pool.size(), pool.single_excitations.len() + pool.double_excitations.len());
    }

    #[test]
    fn test_pauli_string_application() {
        let pauli = PauliString {
            operators: vec![PauliOp::X, PauliOp::I],
            coefficient: Complex64::new(1.0, 0.0),
        };

        let state = Array1::from_vec(vec![
            Complex64::new(1.0, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(0.0, 0.0),
        ]);

        let result = pauli.apply_to_state(&state);

        // X on qubit 0 should flip |00⟩ to |01⟩
        assert!((result[0].re - 0.0).abs() < 1e-10);
        assert!((result[1].re - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_adapt_ansatz() {
        let mut ansatz = AdaptAnsatz::new();

        assert_eq!(ansatz.depth(), 0);

        let op = FermionicOperator::single_excitation(0, 1);
        ansatz.add_operator(op, 0.1);

        assert_eq!(ansatz.depth(), 1);
        assert_eq!(ansatz.parameters.len(), 1);
    }

    #[test]
    fn test_molecular_hamiltonian() {
        let h_one = Array2::from_shape_fn((2, 2), |(i, j)| {
            if i == j { -1.0 } else { 0.0 }
        });

        let h_two = HashMap::new();
        let nuclear = 0.5;

        let hamiltonian = MolecularHamiltonian::new(h_one, h_two, nuclear);
        assert_eq!(hamiltonian.num_orbitals, 2);
        assert!((hamiltonian.nuclear_repulsion - 0.5).abs() < 1e-10);
    }
}