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