Skip to main content

oxilean_std/quantum_computing/
functions.rs

1//! Auto-generated module
2//!
3//! πŸ€– Generated with [SplitRS](https://github.com/cool-japan/splitrs)
4
5use oxilean_kernel::Node;
6use oxilean_kernel::{BinderInfo, Declaration, Environment, Expr, Level, Name};
7use std::f64::consts::PI;
8
9use super::types::{
10    CliffordGroup, Complex, Gate2x2, GroverOracle, Pauli, PauliString, QFTSimulator,
11    QuantumChannel, QuantumCircuit, QuantumCircuitData, QuantumErrorCode, QuantumGate,
12    QuantumRegister, QuantumRegisterData, QuantumStatevector, Qubit, StabilizerState,
13};
14
15pub fn app(f: Expr, a: Expr) -> Expr {
16    Expr::App(Node::new(f), Node::new(a))
17}
18pub fn app2(f: Expr, a: Expr, b: Expr) -> Expr {
19    app(app(f, a), b)
20}
21pub fn app3(f: Expr, a: Expr, b: Expr, c: Expr) -> Expr {
22    app(app2(f, a, b), c)
23}
24pub fn cst(s: &str) -> Expr {
25    Expr::Const(Name::str(s), vec![])
26}
27pub fn prop() -> Expr {
28    Expr::Sort(Level::zero())
29}
30pub fn type0() -> Expr {
31    Expr::Sort(Level::succ(Level::zero()))
32}
33pub fn pi(bi: BinderInfo, name: &str, dom: Expr, body: Expr) -> Expr {
34    Expr::Pi(bi, Name::str(name), Node::new(dom), Node::new(body))
35}
36pub fn arrow(a: Expr, b: Expr) -> Expr {
37    pi(BinderInfo::Default, "_", a, b)
38}
39pub fn nat_ty() -> Expr {
40    cst("Nat")
41}
42pub fn real_ty() -> Expr {
43    cst("Real")
44}
45pub fn bool_ty() -> Expr {
46    cst("Bool")
47}
48/// `Qubit : Type` β€” qubit state Ξ±|0⟩ + Ξ²|1⟩ in β„‚Β².
49pub fn qubit_ty() -> Expr {
50    type0()
51}
52/// `QuantumGate : Nat β†’ Type` β€” unitary operator on n qubits.
53pub fn quantum_gate_ty() -> Expr {
54    arrow(nat_ty(), type0())
55}
56/// `QuantumCircuit : Type` β€” sequence of quantum gates applied to a register.
57pub fn quantum_circuit_ty() -> Expr {
58    type0()
59}
60/// `Measurement : Type` β€” quantum measurement (observable).
61pub fn measurement_ty() -> Expr {
62    type0()
63}
64/// `Entanglement : Type` β€” entangled quantum state (e.g., Bell state).
65pub fn entanglement_ty() -> Expr {
66    type0()
67}
68/// No-Cloning Theorem: it is impossible to create an identical copy of an
69/// arbitrary unknown quantum state.
70///
71/// `no_cloning : Prop`
72pub fn no_cloning_ty() -> Expr {
73    prop()
74}
75/// No-Deleting Theorem: it is impossible to delete a copy of an arbitrary
76/// unknown quantum state given two identical copies.
77///
78/// `no_deleting : Prop`
79pub fn no_deleting_ty() -> Expr {
80    prop()
81}
82/// Quantum Teleportation Theorem: the quantum teleportation protocol
83/// faithfully transmits an arbitrary unknown qubit state using one shared
84/// Bell pair and two classical bits.
85///
86/// `quantum_teleportation : Prop`
87pub fn quantum_teleportation_ty() -> Expr {
88    prop()
89}
90/// Grover's Quadratic Speedup: Grover's algorithm solves unstructured search
91/// on N items in O(√N) queries, a quadratic speedup over classical O(N).
92///
93/// `grover_speedup : βˆ€ n : Nat, GroverComplexity n ≀ Real.sqrt (Nat.pow 2 n)`
94pub fn grover_speedup_ty() -> Expr {
95    pi(
96        BinderInfo::Default,
97        "n",
98        nat_ty(),
99        app2(
100            cst("Real.le"),
101            app(cst("GroverComplexity"), cst("n")),
102            app(
103                cst("Real.sqrt"),
104                app2(cst("Nat.pow"), cst("Nat.two"), cst("n")),
105            ),
106        ),
107    )
108}
109/// Shor's Exponential Speedup: Shor's algorithm factors an n-bit integer in
110/// polynomial time O(nΒ³), an exponential speedup over the best classical algorithm.
111///
112/// `shor_exponential : Prop`
113pub fn shor_exponential_ty() -> Expr {
114    prop()
115}
116/// `GateSet : Type` β€” a finite set of quantum gates.
117pub fn gate_set_ty() -> Expr {
118    type0()
119}
120/// `UniversalGateSet : GateSet β†’ Prop`
121/// A gate set G is universal if any unitary can be approximated arbitrarily
122/// well by a circuit from G.
123pub fn universal_gate_set_ty() -> Expr {
124    arrow(cst("GateSet"), prop())
125}
126/// `SolovayKitaev : βˆ€ (g : GateSet), UniversalGateSet g β†’ Prop`
127/// The Solovay-Kitaev theorem: any universal gate set can approximate any
128/// single-qubit unitary to precision Ξ΅ in O(log^c(1/Ξ΅)) gates.
129pub fn solovay_kitaev_ty() -> Expr {
130    pi(
131        BinderInfo::Default,
132        "g",
133        cst("GateSet"),
134        arrow(app(cst("UniversalGateSet"), cst("g")), prop()),
135    )
136}
137/// `HTCliffordUniversal : Prop`
138/// The gate set {H, T, CNOT} is universal for quantum computation.
139pub fn ht_clifford_universal_ty() -> Expr {
140    prop()
141}
142/// `QFTState : Nat β†’ Type`
143/// The state produced by the quantum Fourier transform on n qubits.
144pub fn qft_state_ty() -> Expr {
145    arrow(nat_ty(), type0())
146}
147/// `QFTCorrectness : βˆ€ n : Nat, Prop`
148/// The quantum Fourier transform on n qubits correctly computes the DFT
149/// of the amplitude vector.
150pub fn qft_correctness_ty() -> Expr {
151    pi(BinderInfo::Default, "n", nat_ty(), prop())
152}
153/// `QFTComplexity : βˆ€ n : Nat, QFTGateCount n ≀ Nat.pow n 2`
154/// The QFT on n qubits requires O(nΒ²) gates.
155pub fn qft_complexity_ty() -> Expr {
156    pi(
157        BinderInfo::Default,
158        "n",
159        nat_ty(),
160        app2(
161            cst("Nat.le"),
162            app(cst("QFTGateCount"), cst("n")),
163            app2(cst("Nat.pow"), cst("n"), cst("Nat.two")),
164        ),
165    )
166}
167/// `PeriodFinding : βˆ€ (N a : Nat), Prop`
168/// Shor's period-finding subroutine: for coprime a, N, the quantum period
169/// finding algorithm finds the order r of a mod N in polynomial time.
170pub fn period_finding_ty() -> Expr {
171    pi(
172        BinderInfo::Default,
173        "N",
174        nat_ty(),
175        pi(BinderInfo::Default, "a", nat_ty(), prop()),
176    )
177}
178/// `ShorFactoring : βˆ€ N : Nat, Prop`
179/// Given access to the period-finding subroutine, Shor's algorithm factors N
180/// in O(logΒ³ N) quantum gate operations with high probability.
181pub fn shor_factoring_ty() -> Expr {
182    pi(BinderInfo::Default, "N", nat_ty(), prop())
183}
184/// `AmplitudeAmplification : βˆ€ n : Nat, βˆ€ k : Nat, Prop`
185/// General amplitude amplification: if a state has success probability p,
186/// then after O(1/√p) oracle calls the success probability is amplified to
187/// nearly 1.
188pub fn amplitude_amplification_ty() -> Expr {
189    pi(
190        BinderInfo::Default,
191        "n",
192        nat_ty(),
193        pi(BinderInfo::Default, "k", nat_ty(), prop()),
194    )
195}
196/// `GroverOptimality : Prop`
197/// Grover's algorithm is optimal: any quantum algorithm requires Ω(√N)
198/// oracle queries for unstructured search.
199pub fn grover_optimality_ty() -> Expr {
200    prop()
201}
202/// `PhaseEstimation : βˆ€ (n : Nat), Prop`
203/// Quantum phase estimation approximates the eigenvalue e^{2πiφ} of a
204/// unitary U to n bits of precision using n ancilla qubits and O(2^n)
205/// controlled-U applications.
206pub fn phase_estimation_ty() -> Expr {
207    pi(BinderInfo::Default, "n", nat_ty(), prop())
208}
209/// `PhaseEstimationPrecision : βˆ€ n : Nat, PhaseError n ≀ Real.pow 2 n`
210/// The phase estimation error is bounded by 2^{-n}.
211pub fn phase_estimation_precision_ty() -> Expr {
212    pi(
213        BinderInfo::Default,
214        "n",
215        nat_ty(),
216        app2(
217            cst("Real.le"),
218            app(cst("PhaseError"), cst("n")),
219            app2(cst("Real.pow"), cst("Real.two"), cst("n")),
220        ),
221    )
222}
223/// `VQEState : Type`
224/// The parameterized ansatz state used in the variational quantum eigensolver.
225pub fn vqe_state_ty() -> Expr {
226    type0()
227}
228/// `VQEVariationalPrinciple : Prop`
229/// The variational principle underlying VQE: the expectation value of any
230/// Hamiltonian H with any normalized state |ψ⟩ satisfies ⟨ψ|H|ψ⟩ β‰₯ E_0,
231/// where E_0 is the ground-state energy.
232pub fn vqe_variational_principle_ty() -> Expr {
233    prop()
234}
235/// `QAOAState : Nat β†’ Type`
236/// The variational state produced by the Quantum Approximate Optimization
237/// Algorithm (QAOA) at depth p.
238pub fn qaoa_state_ty() -> Expr {
239    arrow(nat_ty(), type0())
240}
241/// `QAOAApproximation : βˆ€ p : Nat, Prop`
242/// As the QAOA depth p β†’ ∞, the algorithm converges to the exact solution
243/// of the combinatorial optimization problem.
244pub fn qaoa_approximation_ty() -> Expr {
245    pi(BinderInfo::Default, "p", nat_ty(), prop())
246}
247/// `StabilizerCode : Nat β†’ Nat β†’ Type`
248/// An [\[n, k\]] stabilizer code encodes k logical qubits into n physical qubits.
249pub fn stabilizer_code_ty() -> Expr {
250    arrow(nat_ty(), arrow(nat_ty(), type0()))
251}
252/// `StabilizerCodeCorrectsErrors : βˆ€ (n k d : Nat), Prop`
253/// An [\[n, k, d\]] stabilizer code can correct ⌊(dβˆ’1)/2βŒ‹ arbitrary qubit errors.
254pub fn stabilizer_code_corrects_errors_ty() -> Expr {
255    pi(
256        BinderInfo::Default,
257        "n",
258        nat_ty(),
259        pi(
260            BinderInfo::Default,
261            "k",
262            nat_ty(),
263            pi(BinderInfo::Default, "d", nat_ty(), prop()),
264        ),
265    )
266}
267/// `QuantumHammingBound : βˆ€ (n k t : Nat), Prop`
268/// The quantum Hamming (Singleton) bound: n βˆ’ k β‰₯ 4t for a code correcting
269/// t errors.
270pub fn quantum_hamming_bound_ty() -> Expr {
271    pi(
272        BinderInfo::Default,
273        "n",
274        nat_ty(),
275        pi(
276            BinderInfo::Default,
277            "k",
278            nat_ty(),
279            pi(BinderInfo::Default, "t", nat_ty(), prop()),
280        ),
281    )
282}
283/// `SurfaceCode : Nat β†’ Type`
284/// A surface code of linear size d (code distance d, n β‰ˆ 2dΒ² physical qubits,
285/// 1 logical qubit).
286pub fn surface_code_ty() -> Expr {
287    arrow(nat_ty(), type0())
288}
289/// `SurfaceCodeDistance : βˆ€ d : Nat, Prop`
290/// The surface code with parameter d has code distance d, i.e., the minimum
291/// weight of any undetectable logical error is d.
292pub fn surface_code_distance_ty() -> Expr {
293    pi(BinderInfo::Default, "d", nat_ty(), prop())
294}
295/// `FaultTolerantThreshold : Prop`
296/// The threshold theorem: if the physical error rate p is below a constant
297/// threshold p_th β‰ˆ 10⁻², arbitrarily long quantum computations can be
298/// performed with exponentially suppressed logical error rates.
299pub fn fault_tolerant_threshold_ty() -> Expr {
300    prop()
301}
302/// `DenseCodingProtocol : Prop`
303/// Super-dense coding: using one shared Bell pair, Alice can send 2 classical
304/// bits to Bob using only a single qubit transmission.
305pub fn dense_coding_protocol_ty() -> Expr {
306    prop()
307}
308/// `BB84Security : Prop`
309/// Information-theoretic security of the BB84 protocol: any eavesdropper
310/// introduces detectable disturbance, and the secret key rate is positive
311/// below the QBER threshold β‰ˆ 11%.
312pub fn bb84_security_ty() -> Expr {
313    prop()
314}
315/// `BB84KeyRate : βˆ€ e : Real, Prop`
316/// The BB84 asymptotic key rate r(e) = 1 βˆ’ 2H(e), where H is the binary
317/// entropy function and e is the quantum bit-error rate.
318pub fn bb84_key_rate_ty() -> Expr {
319    pi(BinderInfo::Default, "e", real_ty(), prop())
320}
321/// `BQPContainsBPP : Prop`
322/// The complexity class BQP (bounded-error quantum polynomial time) contains
323/// BPP (bounded-error probabilistic polynomial time): BPP βŠ† BQP.
324pub fn bqp_contains_bpp_ty() -> Expr {
325    prop()
326}
327/// `BQPInPSHARPP : Prop`
328/// BQP is contained in P^#P (and hence in PSPACE): BQP βŠ† P^#P.
329pub fn bqp_in_psharp_p_ty() -> Expr {
330    prop()
331}
332/// `QMADefinition : Prop`
333/// QMA (Quantum Merlin-Arthur) is the quantum analogue of NP: a problem is
334/// in QMA if there exists a polynomial-time quantum verifier and a quantum
335/// witness state.
336pub fn qma_definition_ty() -> Expr {
337    prop()
338}
339/// `LocalHamiltonianQMAComplete : Prop`
340/// The k-local Hamiltonian problem is QMA-complete for k β‰₯ 2.
341pub fn local_hamiltonian_qma_complete_ty() -> Expr {
342    prop()
343}
344/// `HamiltonianSimulation : βˆ€ (t : Real), Prop`
345/// For any local Hamiltonian H, the time-evolution operator e^{βˆ’iHt} can be
346/// approximated to precision Ξ΅ in poly(n, t, 1/Ξ΅) gate complexity.
347pub fn hamiltonian_simulation_ty() -> Expr {
348    pi(BinderInfo::Default, "t", real_ty(), prop())
349}
350/// `TrotterSuzukiError : βˆ€ (t : Real) (r : Nat), Prop`
351/// The first-order Trotter-Suzuki product formula has error O(tΒ²/r) for r
352/// time steps.
353pub fn trotter_suzuki_error_ty() -> Expr {
354    pi(
355        BinderInfo::Default,
356        "t",
357        real_ty(),
358        pi(BinderInfo::Default, "r", nat_ty(), prop()),
359    )
360}
361/// `AdiabaticTheorem : βˆ€ (gap : Real), Prop`
362/// The adiabatic theorem: if a Hamiltonian is evolved slowly enough (relative
363/// to the inverse square of the spectral gap), the system remains in its
364/// instantaneous ground state.
365pub fn adiabatic_theorem_ty() -> Expr {
366    pi(BinderInfo::Default, "gap", real_ty(), prop())
367}
368/// `AdiabaticQCEquivalence : Prop`
369/// Adiabatic quantum computation is polynomially equivalent to the standard
370/// gate model of quantum computation.
371pub fn adiabatic_qc_equivalence_ty() -> Expr {
372    prop()
373}
374/// `Anyon : Type`
375/// An anyon: a quasi-particle in (2+1)D that obeys fractional (non-Abelian)
376/// statistics under exchange.
377pub fn anyon_ty() -> Expr {
378    type0()
379}
380/// `BraidingOperator : Anyon β†’ Anyon β†’ Type`
381/// The unitary braiding operator R_{ij} arising from exchanging two anyons.
382pub fn braiding_operator_ty() -> Expr {
383    arrow(cst("Anyon"), arrow(cst("Anyon"), type0()))
384}
385/// `NonAbelianStatistics : Prop`
386/// Non-Abelian anyons: the braiding operators do not commute in general,
387/// enabling topologically protected quantum gates.
388pub fn non_abelian_statistics_ty() -> Expr {
389    prop()
390}
391/// `TopologicalProtection : Prop`
392/// Topological quantum computation is inherently fault-tolerant: logical
393/// operations correspond to global topological properties immune to local
394/// perturbations.
395pub fn topological_protection_ty() -> Expr {
396    prop()
397}
398/// `FibonacciAnyon : Prop`
399/// Fibonacci anyons are universal for topological quantum computation: any
400/// unitary can be approximated by braiding Fibonacci anyons.
401pub fn fibonacci_anyon_ty() -> Expr {
402    prop()
403}
404/// `BosonSampling : Nat β†’ Type`
405/// The boson sampling problem on n photons: sample from the output
406/// distribution of a linear optical network acting on Fock states.
407pub fn boson_sampling_ty() -> Expr {
408    arrow(nat_ty(), type0())
409}
410/// `BosonSamplingHardness : Prop`
411/// Boson sampling is classically hard to simulate (under plausible complexity
412/// theoretic conjectures): efficient classical simulation would imply
413/// P^#P = BPP^NP.
414pub fn boson_sampling_hardness_ty() -> Expr {
415    prop()
416}
417/// `QuantumVolume : Nat β†’ Nat`
418/// The quantum volume V_Q = 2^n where n is the largest square quantum circuit
419/// that a device can implement with at-least-2/3 probability of success.
420pub fn quantum_volume_ty() -> Expr {
421    arrow(nat_ty(), nat_ty())
422}
423/// `QuantumVolumeMonotone : βˆ€ (n m : Nat), Prop`
424/// Quantum volume is monotone: improvements in gate fidelity and connectivity
425/// cannot decrease the quantum volume.
426pub fn quantum_volume_monotone_ty() -> Expr {
427    pi(
428        BinderInfo::Default,
429        "n",
430        nat_ty(),
431        pi(BinderInfo::Default, "m", nat_ty(), prop()),
432    )
433}
434pub fn build_quantum_computing_env(
435    env: &mut Environment,
436) -> Result<(), Box<dyn std::error::Error>> {
437    let axioms: &[(&str, Expr)] = &[
438        ("Qubit", qubit_ty()),
439        ("QuantumGate", quantum_gate_ty()),
440        ("QuantumCircuit", quantum_circuit_ty()),
441        ("Measurement", measurement_ty()),
442        ("Entanglement", entanglement_ty()),
443        ("GroverComplexity", arrow(nat_ty(), real_ty())),
444        ("Nat.two", nat_ty()),
445        ("Nat.pow", arrow(nat_ty(), arrow(nat_ty(), nat_ty()))),
446        ("no_cloning", no_cloning_ty()),
447        ("no_deleting", no_deleting_ty()),
448        ("quantum_teleportation", quantum_teleportation_ty()),
449        ("grover_speedup", grover_speedup_ty()),
450        ("shor_exponential", shor_exponential_ty()),
451        ("GateSet", gate_set_ty()),
452        ("UniversalGateSet", universal_gate_set_ty()),
453        ("solovay_kitaev", solovay_kitaev_ty()),
454        ("ht_clifford_universal", ht_clifford_universal_ty()),
455        ("QFTState", qft_state_ty()),
456        ("QFTGateCount", arrow(nat_ty(), nat_ty())),
457        ("qft_correctness", qft_correctness_ty()),
458        ("qft_complexity", qft_complexity_ty()),
459        ("period_finding", period_finding_ty()),
460        ("shor_factoring", shor_factoring_ty()),
461        ("amplitude_amplification", amplitude_amplification_ty()),
462        ("grover_optimality", grover_optimality_ty()),
463        ("phase_estimation", phase_estimation_ty()),
464        ("PhaseError", arrow(nat_ty(), real_ty())),
465        ("Real.two", real_ty()),
466        ("Real.pow", arrow(real_ty(), arrow(nat_ty(), real_ty()))),
467        (
468            "phase_estimation_precision",
469            phase_estimation_precision_ty(),
470        ),
471        ("VQEState", vqe_state_ty()),
472        ("vqe_variational_principle", vqe_variational_principle_ty()),
473        ("QAOAState", qaoa_state_ty()),
474        ("qaoa_approximation", qaoa_approximation_ty()),
475        ("StabilizerCode", stabilizer_code_ty()),
476        (
477            "stabilizer_code_corrects_errors",
478            stabilizer_code_corrects_errors_ty(),
479        ),
480        ("quantum_hamming_bound", quantum_hamming_bound_ty()),
481        ("SurfaceCode", surface_code_ty()),
482        ("surface_code_distance", surface_code_distance_ty()),
483        ("fault_tolerant_threshold", fault_tolerant_threshold_ty()),
484        ("dense_coding_protocol", dense_coding_protocol_ty()),
485        ("bb84_security", bb84_security_ty()),
486        ("bb84_key_rate", bb84_key_rate_ty()),
487        ("bqp_contains_bpp", bqp_contains_bpp_ty()),
488        ("bqp_in_psharp_p", bqp_in_psharp_p_ty()),
489        ("qma_definition", qma_definition_ty()),
490        (
491            "local_hamiltonian_qma_complete",
492            local_hamiltonian_qma_complete_ty(),
493        ),
494        ("hamiltonian_simulation", hamiltonian_simulation_ty()),
495        ("trotter_suzuki_error", trotter_suzuki_error_ty()),
496        ("adiabatic_theorem", adiabatic_theorem_ty()),
497        ("adiabatic_qc_equivalence", adiabatic_qc_equivalence_ty()),
498        ("Anyon", anyon_ty()),
499        ("BraidingOperator", braiding_operator_ty()),
500        ("non_abelian_statistics", non_abelian_statistics_ty()),
501        ("topological_protection", topological_protection_ty()),
502        ("fibonacci_anyon", fibonacci_anyon_ty()),
503        ("BosonSampling", boson_sampling_ty()),
504        ("boson_sampling_hardness", boson_sampling_hardness_ty()),
505        ("QuantumVolume", quantum_volume_ty()),
506        ("quantum_volume_monotone", quantum_volume_monotone_ty()),
507    ];
508    for (name, ty) in axioms {
509        env.add(Declaration::Axiom {
510            name: Name::str(*name),
511            univ_params: vec![],
512            ty: ty.clone(),
513        })
514        .ok();
515    }
516    Ok(())
517}
518/// Optimal number of Grover iterations for `n_qubits` qubits.
519///
520/// Approximately βŒŠΟ€/4 Β· √(2^n)βŒ‹.
521pub fn grover_iterations(n_qubits: u32) -> u32 {
522    let n = 1u64 << n_qubits;
523    let iters = (PI / 4.0 * (n as f64).sqrt()).floor() as u32;
524    iters.max(1)
525}
526/// Probability of success after `iterations` Grover iterations on `n_qubits` qubits.
527///
528/// P_success = sin²((2k + 1) · arcsin(1 / √N))  where N = 2^n, k = iterations.
529pub fn grover_success_prob(n_qubits: u32, iterations: u32) -> f64 {
530    let n = (1u64 << n_qubits) as f64;
531    let theta = (1.0 / n.sqrt()).asin();
532    let angle = (2 * iterations + 1) as f64 * theta;
533    angle.sin().powi(2)
534}
535#[cfg(test)]
536mod tests {
537    use super::*;
538    #[test]
539    fn test_complex_mul() {
540        let i = Complex::i();
541        let result = i.mul(&i);
542        assert!((result.re - (-1.0)).abs() < 1e-10);
543        assert!(result.im.abs() < 1e-10);
544        let a = Complex::new(1.0, 1.0);
545        let b = Complex::new(1.0, -1.0);
546        let r = a.mul(&b);
547        assert!((r.re - 2.0).abs() < 1e-10);
548        assert!(r.im.abs() < 1e-10);
549    }
550    #[test]
551    fn test_qubit_zero_normalized() {
552        let q = Qubit::zero();
553        assert!(q.is_normalized());
554        assert!((q.prob_zero() - 1.0).abs() < 1e-10);
555        assert!(q.prob_one().abs() < 1e-10);
556    }
557    #[test]
558    fn test_qubit_plus_equal_prob() {
559        let q = Qubit::plus();
560        assert!(q.is_normalized(), "|+⟩ must be normalized");
561        assert!((q.prob_zero() - 0.5).abs() < 1e-10, "prob_0 of |+⟩ = 0.5");
562        assert!((q.prob_one() - 0.5).abs() < 1e-10, "prob_1 of |+⟩ = 0.5");
563    }
564    #[test]
565    fn test_hadamard_maps_zero_to_plus() {
566        let h = Gate2x2::hadamard();
567        let zero = Qubit::zero();
568        let out = h.apply(&zero);
569        let inv_sqrt2 = 1.0 / 2.0f64.sqrt();
570        assert!((out.alpha.re - inv_sqrt2).abs() < 1e-10, "H|0⟩ α.re");
571        assert!((out.beta.re - inv_sqrt2).abs() < 1e-10, "H|0⟩ β.re");
572        assert!(out.is_normalized());
573    }
574    #[test]
575    fn test_pauli_x_maps_zero_to_one() {
576        let x = Gate2x2::pauli_x();
577        let zero = Qubit::zero();
578        let out = x.apply(&zero);
579        assert!(out.alpha.abs() < 1e-10, "X|0⟩ α should be 0");
580        assert!((out.beta.abs() - 1.0).abs() < 1e-10, "X|0⟩ β should be 1");
581    }
582    #[test]
583    fn test_hadamard_unitary() {
584        let h = Gate2x2::hadamard();
585        assert!(h.is_unitary(), "Hadamard should be unitary");
586        let hh = h.compose(&h);
587        let zero = Qubit::zero();
588        let out = hh.apply(&zero);
589        assert!(
590            (out.alpha.re - 1.0).abs() < 1e-9,
591            "HH|0⟩ should be |0⟩; got α={}",
592            out.alpha
593        );
594        assert!(
595            out.beta.abs() < 1e-9,
596            "HH|0⟩ should be |0⟩; got β={}",
597            out.beta
598        );
599    }
600    #[test]
601    fn test_statevector_new_normalized() {
602        for n in 1..=4 {
603            let sv = QuantumStatevector::new(n);
604            assert!(sv.is_normalized(), "{n}-qubit state should be normalized");
605            assert_eq!(sv.n_amplitudes(), 1 << n);
606            assert!((sv.prob(0) - 1.0).abs() < 1e-10);
607            for i in 1..(1 << n) {
608                assert!(sv.prob(i).abs() < 1e-10);
609            }
610        }
611    }
612    #[test]
613    fn test_grover_iterations_grows_sqrt() {
614        let k4 = grover_iterations(4);
615        let k8 = grover_iterations(8);
616        assert!(k8 > k4, "more qubits β†’ more iterations");
617        let p = grover_success_prob(4, k4);
618        assert!(p > 0.9, "Grover success prob should be > 90%; got {p:.3}");
619    }
620    #[test]
621    fn test_quantum_register_uniform_superposition() {
622        let mut reg = QuantumRegister::new(3);
623        reg.prepare_uniform_superposition();
624        assert!(
625            reg.is_normalized(),
626            "uniform superposition must be normalized"
627        );
628        for i in 0..8 {
629            let p = reg.prob(i);
630            assert!(
631                (p - 0.125).abs() < 1e-9,
632                "basis state {i} prob = {p}, expected 0.125"
633            );
634        }
635    }
636    #[test]
637    fn test_quantum_circuit_hadamard_chain() {
638        let mut circuit = QuantumCircuit::new(2);
639        circuit.add_gate(Gate2x2::hadamard(), 0);
640        circuit.add_gate(Gate2x2::hadamard(), 1);
641        let reg = circuit.run();
642        assert!(reg.is_normalized());
643        for i in 0..4 {
644            assert!((reg.prob(i) - 0.25).abs() < 1e-9);
645        }
646    }
647    #[test]
648    fn test_quantum_circuit_bell_state() {
649        let mut circuit = QuantumCircuit::new(2);
650        circuit.add_gate(Gate2x2::hadamard(), 0);
651        circuit.add_cnot(0, 1);
652        let reg = circuit.run();
653        assert!(reg.is_normalized(), "Bell state must be normalized");
654        let inv_sqrt2 = 1.0 / 2.0f64.sqrt();
655        assert!((reg.amplitude(0).re - inv_sqrt2).abs() < 1e-9);
656        assert!((reg.amplitude(3).re - inv_sqrt2).abs() < 1e-9);
657        assert!(reg.amplitude(1).abs() < 1e-9);
658        assert!(reg.amplitude(2).abs() < 1e-9);
659    }
660    #[test]
661    fn test_grover_oracle_amplifies_target() {
662        let n_qubits = 4;
663        let target = 5;
664        let oracle = GroverOracle::new(target);
665        let k = grover_iterations(n_qubits as u32);
666        let reg = oracle.run_grover(n_qubits, k);
667        assert!(reg.is_normalized(), "Grover register must be normalized");
668        let p_target = reg.prob(target);
669        let max_non_target = (0..reg.size())
670            .filter(|&i| i != target)
671            .map(|i| reg.prob(i))
672            .fold(0.0f64, f64::max);
673        assert!(
674            p_target > max_non_target,
675            "target prob {p_target:.4} should exceed max non-target {max_non_target:.4}"
676        );
677    }
678    #[test]
679    fn test_qft_preserves_norm() {
680        let n_qubits = 3;
681        let qft = QFTSimulator::new(n_qubits);
682        let mut reg = QuantumRegister::new(n_qubits);
683        reg.prepare_uniform_superposition();
684        qft.apply(&mut reg);
685        assert!(
686            reg.is_normalized(),
687            "QFT must preserve normalization; total prob = {}",
688            reg.amplitudes().iter().map(|a| a.abs_sq()).sum::<f64>()
689        );
690    }
691    #[test]
692    fn test_qft_transform_of_uniform() {
693        let n = 4;
694        let qft = QFTSimulator::new(n);
695        let uniform = vec![Complex::new(1.0 / (n as f64).sqrt(), 0.0); n];
696        let out = qft.transform(&uniform);
697        assert!(
698            (out[0].abs() - 1.0).abs() < 1e-9,
699            "DFT of uniform β†’ delta at 0"
700        );
701        for k in 1..n {
702            assert!(
703                out[k].abs() < 1e-9,
704                "DFT of uniform: output[{k}] = {} (expected ~0)",
705                out[k].abs()
706            );
707        }
708    }
709    #[test]
710    fn test_pauli_commutation() {
711        assert!(!Pauli::X.commutes_with(Pauli::Y));
712        assert!(!Pauli::Y.commutes_with(Pauli::Z));
713        assert!(!Pauli::Z.commutes_with(Pauli::X));
714        assert!(Pauli::X.commutes_with(Pauli::X));
715        assert!(Pauli::Y.commutes_with(Pauli::Y));
716        assert!(Pauli::Z.commutes_with(Pauli::Z));
717        assert!(Pauli::I.commutes_with(Pauli::X));
718        assert!(Pauli::I.commutes_with(Pauli::Y));
719        assert!(Pauli::I.commutes_with(Pauli::Z));
720    }
721    #[test]
722    fn test_pauli_string_commutation() {
723        let zz = PauliString::new(1, vec![Pauli::Z, Pauli::Z]);
724        let xx = PauliString::new(1, vec![Pauli::X, Pauli::X]);
725        assert!(zz.commutes_with(&xx), "ZZ and XX should commute");
726        let zi = PauliString::new(1, vec![Pauli::Z, Pauli::I]);
727        let ix = PauliString::new(1, vec![Pauli::I, Pauli::X]);
728        assert!(zi.commutes_with(&ix));
729    }
730    #[test]
731    fn test_stabilizer_state_zero_consistent() {
732        let stab = StabilizerState::computational_zero(4);
733        assert!(
734            stab.is_consistent(),
735            "|0000⟩ stabilizer generators must commute"
736        );
737    }
738    #[test]
739    fn test_stabilizer_state_plus_consistent() {
740        let stab = StabilizerState::plus_state(3);
741        assert!(
742            stab.is_consistent(),
743            "|+++⟩ stabilizer generators must commute"
744        );
745    }
746    #[test]
747    fn test_build_quantum_computing_env() {
748        let mut env = Environment::new();
749        build_quantum_computing_env(&mut env).expect("env build should succeed");
750        let names: &[&str] = &[
751            "GateSet",
752            "UniversalGateSet",
753            "solovay_kitaev",
754            "ht_clifford_universal",
755            "qft_correctness",
756            "qft_complexity",
757            "period_finding",
758            "shor_factoring",
759            "amplitude_amplification",
760            "grover_optimality",
761            "phase_estimation",
762            "phase_estimation_precision",
763            "VQEState",
764            "vqe_variational_principle",
765            "QAOAState",
766            "qaoa_approximation",
767            "StabilizerCode",
768            "stabilizer_code_corrects_errors",
769            "quantum_hamming_bound",
770            "SurfaceCode",
771            "surface_code_distance",
772            "fault_tolerant_threshold",
773            "dense_coding_protocol",
774            "bb84_security",
775            "bb84_key_rate",
776            "bqp_contains_bpp",
777            "bqp_in_psharp_p",
778            "qma_definition",
779            "local_hamiltonian_qma_complete",
780            "hamiltonian_simulation",
781            "trotter_suzuki_error",
782            "adiabatic_theorem",
783            "adiabatic_qc_equivalence",
784            "Anyon",
785            "BraidingOperator",
786            "non_abelian_statistics",
787            "topological_protection",
788            "fibonacci_anyon",
789            "BosonSampling",
790            "boson_sampling_hardness",
791            "QuantumVolume",
792            "quantum_volume_monotone",
793        ];
794        for name in names {
795            assert!(
796                env.get(&Name::str(*name)).is_some(),
797                "axiom '{name}' not found in env"
798            );
799        }
800    }
801}
802/// Standard quantum algorithms summary.
803#[allow(dead_code)]
804pub fn standard_quantum_algorithms() -> Vec<(&'static str, &'static str, &'static str)> {
805    vec![
806        ("Shor", "Integer factorization", "O((log N)^3)"),
807        ("Grover", "Unstructured search", "O(sqrt(N))"),
808        ("HHL", "Linear systems", "O(log(N) kappa^2 / epsilon)"),
809        ("QFT", "Quantum Fourier transform", "O(n^2)"),
810        ("QPE", "Phase estimation", "O(n / epsilon)"),
811        ("QAOA", "Combinatorial optimization", "variational"),
812        ("VQE", "Ground state energy", "variational"),
813        ("QRAM", "Quantum random access", "O(log N)"),
814        (
815            "Amplitude Amplification",
816            "Generalized Grover",
817            "O(1/sqrt(p))",
818        ),
819        ("Quantum Walk", "Graph problems", "quadratic speedup"),
820    ]
821}
822#[cfg(test)]
823mod qc_ext_tests {
824    use super::*;
825    #[test]
826    fn test_quantum_register() {
827        let r = QuantumRegisterData::new(3, "q");
828        assert_eq!(r.hilbert_space_dim(), 8);
829    }
830    #[test]
831    fn test_quantum_circuit() {
832        let mut c = QuantumCircuitData::new(2);
833        c.apply(QuantumGate::hadamard(), vec![0]);
834        c.apply(QuantumGate::cnot(), vec![0, 1]);
835        assert_eq!(c.gate_count(), 2);
836        assert!(c.is_clifford());
837    }
838    #[test]
839    fn test_error_code() {
840        let steane = QuantumErrorCode::steane_7();
841        assert_eq!(steane.n, 7);
842        assert_eq!(steane.corrects_errors_up_to(), 1);
843        let sc = QuantumErrorCode::surface_code(3);
844        assert_eq!(sc.d, 3);
845    }
846    #[test]
847    fn test_clifford_gottesman_knill() {
848        let c = CliffordGroup::new(5);
849        assert!(c.is_efficiently_simulable());
850        assert!(c.universal_with_t_gate());
851    }
852    #[test]
853    fn test_quantum_channel() {
854        let ch = QuantumChannel::depolarizing(2, 0.1);
855        assert!(ch.is_unital());
856        let ad = QuantumChannel::amplitude_damping(0.3);
857        assert!(ad.is_degradable());
858    }
859    #[test]
860    fn test_algorithms_nonempty() {
861        let algs = standard_quantum_algorithms();
862        assert!(!algs.is_empty());
863    }
864}