Skip to main content

oxicuda_quantum/
lib.rs

1//! Quantum simulation primitives for OxiCUDA.
2//!
3//! Provides state-vector simulation, Pauli expectation values, VQE/QAOA,
4//! density matrices, Trotter-Suzuki time evolution, quantum kernels, and
5//! PTX kernel code generation for GPU execution.
6
7pub mod algorithm;
8pub mod algorithms;
9pub mod channel;
10pub mod circuit;
11pub mod density;
12pub mod embedding;
13pub mod error;
14pub mod error_correction;
15pub mod fourier;
16pub mod gates;
17pub mod handle;
18pub mod kernel;
19pub mod linear_systems;
20pub mod midcircuit;
21pub mod mps;
22pub mod pauli;
23pub mod ptx_kernels;
24pub mod qaoa;
25pub mod stabilizer;
26pub mod statevec;
27pub mod trotter;
28pub mod vqe;
29
30pub use algorithm::{
31    BernsteinVaziraniResult, DeutschJozsaResult, FunctionKind, GroverResult, OrderFindingResult,
32    ShorResult, SimonResult, SuperdenseResult, TeleportResult, bernstein_vazirani,
33    bit_flip_correct, bit_flip_encode, classical_order, continued_fraction_convergents,
34    deutsch_jozsa, factor_from_order, gcd, grover_search, hadamard_test, marked_probability,
35    mod_exp, optimal_iterations, order_finding, phase_flip_correct, phase_flip_encode, prepare_ghz,
36    prepare_w, recover_period_from_constraints, shor_factor, simon, superdense_decode, swap_test,
37    teleport,
38};
39pub use algorithms::{
40    AmplitudeEstimationResult, CoinInit, CoinedWalk, IterativeQpeResult, LcuOperator, Mat2, Pauli,
41    PauliTerm, StatePreparation, VqlsResult, VqlsSolver, amplitude_estimation,
42    chebyshev_qsp_angles, chebyshev_t, iterative_phase_estimation, position_std_about,
43    qsp_top_left, qsp_unitary, signal_operator,
44};
45pub use channel::pauli_channel::{
46    bit_flip_channel, bit_phase_flip_channel, pauli_channel, pauli_twirl, phase_flip_channel,
47};
48pub use error::{QuantumError, QuantumResult};
49pub use error_correction::{
50    PauliError, StabKind, Stabilizer, SurfaceCode, SurfaceCodeConfig, Syndrome,
51};
52pub use fourier::{PhaseEstimationResult, phase_estimation, qft_inplace, qft_inverse_inplace};
53pub use linear_systems::{HermitianMatrix, HhlConfig, HhlResult, hhl_solve};
54pub use midcircuit::{
55    ClassicalRegister, MidCircuitOp, apply_if, measure_and_collapse, measure_deterministic,
56    run as run_midcircuit,
57};
58pub use mps::{MatrixProductState, MpsConfig};
59
60#[cfg(test)]
61mod e2e_tests {
62    use crate::channel::noise::{amplitude_damping_channel, depolarizing_channel};
63    use crate::circuit::circuit::{GateOp, QuantumCircuit};
64    use crate::density::density::DensityMatrix;
65    use crate::density::metrics::purity;
66    use crate::fourier::{phase_estimation, qft_inplace, qft_inverse_inplace};
67    use crate::gates::controlled::apply_cnot;
68    use crate::gates::hadamard::gate_h;
69    use crate::gates::hadamard::gate_s;
70    use crate::gates::pauli::gate_x;
71    use crate::handle::LcgRng;
72    use crate::pauli::expval::expectation_value;
73    use crate::pauli::hamiltonian::Hamiltonian;
74    use crate::pauli::pauli_string::PauliOp;
75    use crate::ptx_kernels::{
76        expval_pauli_ptx, measure_prob_ptx, partial_trace_ptx, qft_butterfly_ptx,
77        statevec_apply_1q_ptx, statevec_apply_2q_ptx, statevec_apply_cnot_ptx, trotter_step_ptx,
78    };
79    use crate::qaoa::qaoa::QaoaCircuit;
80    use crate::statevec::apply_1q::apply_1q_inplace;
81    use crate::statevec::state::StateVector;
82    use crate::vqe::ansatz::HardwareEfficientAnsatz;
83    use crate::vqe::vqe::VqeOptimizer;
84
85    // Test 1: |0⟩ state has norm 1
86    #[test]
87    fn e2e_01_zero_state_norm_is_one() {
88        let sv = StateVector::new_zero_state(3).expect("valid 3-qubit zero state");
89        let norm = sv.norm_sq();
90        assert!((norm - 1.0).abs() < 1e-6, "norm={norm}");
91    }
92
93    // Test 2: H gate on |0⟩ gives equal superposition
94    #[test]
95    fn e2e_02_hadamard_creates_superposition() {
96        let mut sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
97        apply_1q_inplace(&mut sv, 0, &gate_h()).expect("valid qubit index for H gate");
98        let inv_sqrt2 = std::f32::consts::FRAC_1_SQRT_2;
99        assert!(
100            (sv.amps[0].re - inv_sqrt2).abs() < 1e-5,
101            "amp0={:?}",
102            sv.amps[0]
103        );
104        assert!(
105            (sv.amps[1].re - inv_sqrt2).abs() < 1e-5,
106            "amp1={:?}",
107            sv.amps[1]
108        );
109    }
110
111    // Test 3: H·H = I (round-trip)
112    #[test]
113    fn e2e_03_hadamard_round_trip() {
114        let mut sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
115        apply_1q_inplace(&mut sv, 0, &gate_h()).expect("valid qubit index for first H gate");
116        apply_1q_inplace(&mut sv, 0, &gate_h()).expect("valid qubit index for second H gate");
117        assert!((sv.amps[0].re - 1.0).abs() < 1e-5, "amp0={:?}", sv.amps[0]);
118        assert!(sv.amps[1].norm() < 1e-5, "amp1={:?}", sv.amps[1]);
119    }
120
121    // Test 4: CNOT creates Bell state |00⟩+|11⟩/√2
122    #[test]
123    fn e2e_04_cnot_creates_bell_state() {
124        let mut sv = StateVector::new_zero_state(2).expect("valid 2-qubit zero state");
125        apply_1q_inplace(&mut sv, 0, &gate_h()).expect("valid qubit index for H gate");
126        apply_cnot(&mut sv, 0, 1).expect("valid CNOT qubit indices");
127        let inv_sqrt2 = std::f32::consts::FRAC_1_SQRT_2;
128        // |00⟩ at index 0, |11⟩ at index 3
129        assert!((sv.amps[0].re - inv_sqrt2).abs() < 1e-5);
130        assert!((sv.amps[3].re - inv_sqrt2).abs() < 1e-5);
131        assert!(sv.amps[1].norm() < 1e-5);
132        assert!(sv.amps[2].norm() < 1e-5);
133    }
134
135    // Test 5: Pauli-Z expectation of |0⟩ = +1
136    #[test]
137    fn e2e_05_pauli_z_expval_zero_state() {
138        let sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
139        let mut ham = Hamiltonian::new();
140        ham.add_term(1.0, vec![PauliOp::Z]);
141        let ev = expectation_value(&sv, &ham).expect("valid Hamiltonian expectation value");
142        assert!((ev - 1.0).abs() < 1e-5, "ev={ev}");
143    }
144
145    // Test 6: Pauli-Z expectation of |1⟩ = -1
146    #[test]
147    fn e2e_06_pauli_z_expval_one_state() {
148        let mut sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
149        apply_1q_inplace(&mut sv, 0, &gate_x()).expect("valid qubit index for X gate"); // flip to |1⟩
150        let mut ham = Hamiltonian::new();
151        ham.add_term(1.0, vec![PauliOp::Z]);
152        let ev = expectation_value(&sv, &ham).expect("valid Hamiltonian expectation value");
153        assert!((ev - (-1.0)).abs() < 1e-5, "ev={ev}");
154    }
155
156    // Test 7: Mixed Hamiltonian expectation value is finite
157    #[test]
158    fn e2e_07_mixed_hamiltonian_expval_finite() {
159        let mut sv = StateVector::new_zero_state(2).expect("valid 2-qubit zero state");
160        apply_1q_inplace(&mut sv, 0, &gate_h()).expect("valid qubit index for H gate");
161        apply_cnot(&mut sv, 0, 1).expect("valid CNOT qubit indices");
162        let mut ham = Hamiltonian::new();
163        ham.add_term(0.5, vec![PauliOp::Z, PauliOp::Z]);
164        ham.add_term(0.3, vec![PauliOp::X, PauliOp::I]);
165        ham.add_term(0.2, vec![PauliOp::I, PauliOp::Y]);
166        let ev = expectation_value(&sv, &ham).expect("valid Hamiltonian expectation value");
167        assert!(ev.is_finite(), "ev={ev}");
168    }
169
170    // Test 8: VQE energy decreases over iterations
171    #[test]
172    fn e2e_08_vqe_energy_decreases() {
173        let ans = HardwareEfficientAnsatz::new(2, 1);
174        let mut ham = Hamiltonian::new();
175        ham.add_term(1.0, vec![PauliOp::Z, PauliOp::Z]);
176        ham.add_term(-0.5, vec![PauliOp::X, PauliOp::I]);
177        let mut rng = LcgRng::new(42);
178        let mut opt = VqeOptimizer::new(ans, ham, &mut rng);
179        let e_initial = opt
180            .energy(&opt.params.clone())
181            .expect("valid energy computation");
182        let (e_final, _) = opt.optimize(5, 0.1).expect("valid VQE optimization run");
183        assert!(
184            e_final <= e_initial + 1e-3,
185            "e_initial={e_initial}, e_final={e_final}"
186        );
187    }
188
189    // Test 9: QAOA circuit runs without error
190    #[test]
191    fn e2e_09_qaoa_runs_without_error() {
192        let circuit = QaoaCircuit::new(4, 2, vec![0.3, 0.5], vec![0.7, 0.2])
193            .expect("valid QAOA circuit parameters");
194        let graph = vec![(0, 1), (1, 2), (2, 3), (3, 0)];
195        let sv = circuit.run(&graph).expect("valid QAOA circuit run");
196        let norm = sv.norm_sq();
197        assert!((norm - 1.0).abs() < 1e-4, "norm={norm}");
198    }
199
200    // Test 10: Density matrix from pure state has purity 1
201    #[test]
202    fn e2e_10_pure_state_purity_is_one() {
203        let sv = StateVector::new_zero_state(2).expect("valid 2-qubit zero state");
204        let dm = DensityMatrix::from_pure_state(&sv);
205        let p = purity(&dm);
206        assert!((p - 1.0).abs() < 1e-5, "purity={p}");
207    }
208
209    // Test 11: Depolarizing channel reduces purity
210    #[test]
211    fn e2e_11_depolarizing_channel_reduces_purity() {
212        let sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
213        let dm = DensityMatrix::from_pure_state(&sv);
214        let p_initial = purity(&dm);
215
216        let ch = depolarizing_channel(0.5, 2).expect("valid depolarizing channel");
217        let dm_out = ch.apply(&dm).expect("valid channel application");
218        let p_final = purity(&dm_out);
219
220        assert!(
221            p_final < p_initial,
222            "purity did not decrease: {p_initial} → {p_final}"
223        );
224    }
225
226    // Test 12: PTX kernels generate non-empty strings for all 6 SM versions
227    #[test]
228    fn e2e_12_ptx_kernels_non_empty_all_sm() {
229        for sm in [75u32, 80, 86, 89, 90, 100] {
230            let s1 = statevec_apply_1q_ptx(sm);
231            let s2 = statevec_apply_2q_ptx(sm);
232            let s3 = statevec_apply_cnot_ptx(sm);
233            let s4 = expval_pauli_ptx(sm);
234            let s5 = partial_trace_ptx(sm);
235            let s6 = trotter_step_ptx(sm);
236            let s7 = measure_prob_ptx(sm);
237            let s8 = qft_butterfly_ptx(sm);
238            assert!(!s1.is_empty(), "statevec_apply_1q sm={sm}");
239            assert!(!s2.is_empty(), "statevec_apply_2q sm={sm}");
240            assert!(!s3.is_empty(), "statevec_apply_cnot sm={sm}");
241            assert!(!s4.is_empty(), "expval_pauli sm={sm}");
242            assert!(!s5.is_empty(), "partial_trace sm={sm}");
243            assert!(!s6.is_empty(), "trotter_step sm={sm}");
244            assert!(!s7.is_empty(), "measure_prob sm={sm}");
245            assert!(!s8.is_empty(), "qft_butterfly sm={sm}");
246        }
247    }
248
249    // Supplementary: amplitude damping channel test
250    #[test]
251    fn e2e_13_amplitude_damping_channel() {
252        let sv = StateVector::new_zero_state(1).expect("valid 1-qubit zero state");
253        let dm = DensityMatrix::from_pure_state(&sv);
254        let ch = amplitude_damping_channel(0.3).expect("valid amplitude damping channel");
255        let dm_out = ch.apply(&dm).expect("valid channel application");
256        let tr = dm_out.trace();
257        assert!((tr.re - 1.0).abs() < 1e-5, "trace={}", tr.re);
258    }
259
260    // Supplementary: circuit with explicit CNOTs
261    #[test]
262    fn e2e_14_circuit_bell_state() {
263        let mut circ = QuantumCircuit::new(2);
264        circ.add_gate(GateOp::H);
265        circ.add_gate(GateOp::Cnot { ctrl: 0, tgt: 1 });
266        let sv = StateVector::new_zero_state(2).expect("valid 2-qubit zero state");
267        let mut rng = LcgRng::new(7);
268        let out = circ
269            .exec_on_state(&sv, &mut rng)
270            .expect("valid circuit execution");
271        let inv_sqrt2 = std::f32::consts::FRAC_1_SQRT_2;
272        assert!((out.amps[0].re - inv_sqrt2).abs() < 1e-5);
273        assert!((out.amps[3].re - inv_sqrt2).abs() < 1e-5);
274    }
275
276    // Test 15: QFT on |0…0⟩ yields the uniform superposition
277    #[test]
278    fn e2e_15_qft_uniform_from_zero_state() {
279        let mut sv = StateVector::new_zero_state(3).expect("valid 3-qubit zero state");
280        qft_inplace(&mut sv, &[0, 1, 2]).expect("valid QFT qubit indices");
281        let expected = 1.0 / (8.0_f32).sqrt();
282        for a in &sv.amps {
283            assert!((a.re - expected).abs() < 1e-5, "re={}", a.re);
284            assert!(a.im.abs() < 1e-5, "im={}", a.im);
285        }
286    }
287
288    // Test 16: QFT followed by inverse QFT is the identity
289    #[test]
290    fn e2e_16_qft_roundtrip_identity() {
291        let mut rng = LcgRng::new(2024);
292        let mut amps = Vec::with_capacity(8);
293        for _ in 0..8 {
294            amps.push(num_complex::Complex::new(
295                rng.next_normal(),
296                rng.next_normal(),
297            ));
298        }
299        let mut sv = StateVector { amps, n_qubits: 3 };
300        sv.normalize_inplace();
301        let original = sv.amps.clone();
302        qft_inplace(&mut sv, &[0, 1, 2]).expect("valid QFT qubit indices");
303        qft_inverse_inplace(&mut sv, &[0, 1, 2]).expect("valid inverse QFT qubit indices");
304        for (a, b) in sv.amps.iter().zip(original.iter()) {
305            assert!((a.re - b.re).abs() < 1e-5, "re {a:?} vs {b:?}");
306            assert!((a.im - b.im).abs() < 1e-5, "im {a:?} vs {b:?}");
307        }
308    }
309
310    // Test 17: QPE recovers φ = 1/4 (integer 1) for U = S on eigenstate |1⟩
311    #[test]
312    fn e2e_17_qpe_recovers_quarter_phase() {
313        let mut sv = StateVector::new_zero_state(3).expect("valid 3-qubit zero state");
314        apply_1q_inplace(&mut sv, 2, &gate_x())
315            .expect("valid qubit index for X gate on target qubit"); // target qubit → |1⟩
316        let res =
317            phase_estimation(&mut sv, &[0, 1], 2, &gate_s()).expect("valid QPE configuration");
318        assert_eq!(res.integer, 1, "integer={}", res.integer);
319        assert!((res.phase - 0.25).abs() < 1e-6, "phase={}", res.phase);
320        assert!(res.probability > 0.999, "prob={}", res.probability);
321    }
322}