use oxilean_kernel::{BinderInfo, Declaration, Environment, Expr, Level, Name};
use super::types::{
CSSCode, ConcatenatedCode, FaultToleranceThreshold, GKPCodeSimulator, MagicStateDistillation,
MagicStateProtocol, PauliOp, PauliOperator, PauliString, QECNormChecker, QuantumLDPC, ShorCode,
StabCode, StabilizerCode, StabilizerSimulator, SurfaceCode, SurfaceCodeDecoder,
SyndromeDecoder2, ThresholdEstimator,
};
pub fn app(f: Expr, a: Expr) -> Expr {
Expr::App(Box::new(f), Box::new(a))
}
pub fn app2(f: Expr, a: Expr, b: Expr) -> Expr {
app(app(f, a), b)
}
pub fn app3(f: Expr, a: Expr, b: Expr, c: Expr) -> Expr {
app(app2(f, a, b), c)
}
pub fn cst(s: &str) -> Expr {
Expr::Const(Name::str(s), vec![])
}
pub fn prop() -> Expr {
Expr::Sort(Level::zero())
}
pub fn type0() -> Expr {
Expr::Sort(Level::succ(Level::zero()))
}
pub fn pi(bi: BinderInfo, name: &str, dom: Expr, body: Expr) -> Expr {
Expr::Pi(bi, Name::str(name), Box::new(dom), Box::new(body))
}
pub fn arrow(a: Expr, b: Expr) -> Expr {
pi(BinderInfo::Default, "_", a, b)
}
pub fn bvar(n: u32) -> Expr {
Expr::BVar(n)
}
pub fn nat_ty() -> Expr {
cst("Nat")
}
pub fn real_ty() -> Expr {
cst("Real")
}
pub fn bool_ty() -> Expr {
cst("Bool")
}
pub fn list_ty(elem: Expr) -> Expr {
app(cst("List"), elem)
}
pub fn pauli_op_ty() -> Expr {
type0()
}
pub fn pauli_group_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn pauli_phase_ty() -> Expr {
type0()
}
pub fn symplectic_representation_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn commutator_pauli_ty() -> Expr {
arrow(
app(cst("PauliGroup"), nat_ty()),
arrow(app(cst("PauliGroup"), nat_ty()), bool_ty()),
)
}
pub fn weight_pauli_ty() -> Expr {
arrow(app(cst("PauliGroup"), nat_ty()), nat_ty())
}
pub fn pauli_group_non_abelian_ty() -> Expr {
prop()
}
pub fn pauli_square_identity_ty() -> Expr {
prop()
}
pub fn pauli_anti_commute_ty() -> Expr {
prop()
}
pub fn stabilizer_group_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn stabilizer_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn error_syndrome_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn logical_operator_ty() -> Expr {
arrow(
app3(cst("StabilizerCode"), nat_ty(), nat_ty(), nat_ty()),
arrow(app(cst("PauliGroup"), nat_ty()), type0()),
)
}
pub fn decoder_map_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn code_distance_ty() -> Expr {
arrow(
app3(cst("StabilizerCode"), nat_ty(), nat_ty(), nat_ty()),
nat_ty(),
)
}
pub fn knill_laflamme_conditions_ty() -> Expr {
prop()
}
pub fn quantum_singleton_bound_ty() -> Expr {
prop()
}
pub fn quantum_hamming_bound_ty() -> Expr {
prop()
}
pub fn gottesman_knill_theorem_ty() -> Expr {
prop()
}
pub fn classical_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn css_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn css_x_stabilizer_ty() -> Expr {
arrow(app3(cst("CSSCode"), nat_ty(), nat_ty(), nat_ty()), type0())
}
pub fn css_z_stabilizer_ty() -> Expr {
arrow(app3(cst("CSSCode"), nat_ty(), nat_ty(), nat_ty()), type0())
}
pub fn css_construction_ty() -> Expr {
prop()
}
pub fn css_transversal_cnot_ty() -> Expr {
prop()
}
pub fn shor_code_ty() -> Expr {
type0()
}
pub fn shor_logical_zero_ty() -> Expr {
arrow(cst("ShorCode"), type0())
}
pub fn shor_logical_one_ty() -> Expr {
arrow(cst("ShorCode"), type0())
}
pub fn shor_bit_flip_code_ty() -> Expr {
type0()
}
pub fn shor_phase_flip_code_ty() -> Expr {
type0()
}
pub fn shor_corrects_single_errors_ty() -> Expr {
prop()
}
pub fn shor_is_css_ty() -> Expr {
prop()
}
pub fn steane_code_ty() -> Expr {
type0()
}
pub fn steane_h_matrix_ty() -> Expr {
type0()
}
pub fn steane_stabilizer_ty() -> Expr {
arrow(cst("SteaneCode"), arrow(nat_ty(), type0()))
}
pub fn steane_corrects_single_errors_ty() -> Expr {
prop()
}
pub fn steane_transversal_clifford_ty() -> Expr {
prop()
}
pub fn steane_is_css_ty() -> Expr {
prop()
}
pub fn fault_tolerant_gate_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn transversal_gate_ty() -> Expr {
type0()
}
pub fn magic_state_injection_ty() -> Expr {
type0()
}
pub fn teleported_gate_ty() -> Expr {
type0()
}
pub fn easttin_knill_theorem_ty() -> Expr {
prop()
}
pub fn transversal_clifford_css_ty() -> Expr {
prop()
}
pub fn magic_state_distillation_works_ty() -> Expr {
prop()
}
pub fn error_threshold_ty() -> Expr {
real_ty()
}
pub fn concatenated_code_ty() -> Expr {
arrow(
nat_ty(),
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0()))),
)
}
pub fn fault_tolerance_overhead_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), real_ty()))
}
pub fn pseudo_threshold_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), real_ty())))
}
pub fn threshold_theorem_ty() -> Expr {
prop()
}
pub fn concatenated_code_distance_ty() -> Expr {
prop()
}
pub fn polytope_bound_ty() -> Expr {
prop()
}
pub fn color_code_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn color_code_lattice_ty() -> Expr {
type0()
}
pub fn color_code_syndrome_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn color_code_transversal_t_ty() -> Expr {
prop()
}
pub fn color_code_equivalent_ty() -> Expr {
prop()
}
pub fn quantum_capacity_ty() -> Expr {
arrow(type0(), real_ty())
}
pub fn coherent_information_ty() -> Expr {
arrow(type0(), arrow(type0(), real_ty()))
}
pub fn hashing_bound_ty() -> Expr {
arrow(real_ty(), real_ty())
}
pub fn quantum_erasure_capacity_ty() -> Expr {
arrow(real_ty(), real_ty())
}
pub fn quantum_noise_threshold_ty() -> Expr {
prop()
}
pub fn quantum_shannon_theorem_ty() -> Expr {
prop()
}
pub fn no_cloning_capacity_ty() -> Expr {
prop()
}
pub fn kl_matrix_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn kl_error_set_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn kl_correctable_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn kl_necessary_condition_ty() -> Expr {
arrow(
app(cst("KLErrorSet"), nat_ty()),
arrow(
app3(cst("StabilizerCode"), nat_ty(), nat_ty(), nat_ty()),
prop(),
),
)
}
pub fn kl_sufficient_condition_ty() -> Expr {
arrow(
app(cst("KLErrorSet"), nat_ty()),
arrow(
app3(cst("StabilizerCode"), nat_ty(), nat_ty(), nat_ty()),
prop(),
),
)
}
pub fn kl_equivalence_ty() -> Expr {
prop()
}
pub fn kl_degenerate_code_ty() -> Expr {
prop()
}
pub fn reed_muller_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn quantum_reed_muller_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn rm_transversal_t_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), prop()))
}
pub fn rm_code_concatenation_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn rm_transversal_universal_ty() -> Expr {
prop()
}
pub fn rm_code_distance_ty() -> Expr {
prop()
}
pub fn surface_code_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn toric_code_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn surface_code_vertex_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn surface_code_plaquette_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn surface_code_logical_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn surface_code_distance_ty() -> Expr {
prop()
}
pub fn toric_code_anyons_ty() -> Expr {
prop()
}
pub fn surface_code_threshold_ty() -> Expr {
prop()
}
pub fn qldpc_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn fiber_bundle_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn good_qldpc_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), prop())))
}
pub fn qldpc_tanner_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn qldpc_good_codes_ty() -> Expr {
prop()
}
pub fn fiber_bundle_distance_ty() -> Expr {
prop()
}
pub fn bosonic_code_ty() -> Expr {
type0()
}
pub fn cat_code_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn gkp_code_ty() -> Expr {
arrow(real_ty(), type0())
}
pub fn binomial_code_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), type0()))
}
pub fn gkp_displacement_error_ty() -> Expr {
arrow(real_ty(), arrow(real_ty(), type0()))
}
pub fn gkp_corrects_bounded_displacement_ty() -> Expr {
prop()
}
pub fn cat_code_loss_tolerance_ty() -> Expr {
prop()
}
pub fn noise_model_ty() -> Expr {
type0()
}
pub fn depolarizing_noise_ty() -> Expr {
arrow(real_ty(), type0())
}
pub fn circuit_noise_threshold_ty() -> Expr {
arrow(cst("NoiseModel"), real_ty())
}
pub fn fault_tolerance_gadget_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn circuit_threshold_theorem_ty() -> Expr {
prop()
}
pub fn threshold_upper_bound_ty() -> Expr {
prop()
}
pub fn magic_state_ty() -> Expr {
type0()
}
pub fn t_state_ty() -> Expr {
type0()
}
pub fn distillation_protocol_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(real_ty(), type0())))
}
pub fn magic_state_robustness_ty() -> Expr {
real_ty()
}
pub fn bravyi_kitaev_distillation_ty() -> Expr {
prop()
}
pub fn magic_state_non_stabilizer_ty() -> Expr {
prop()
}
pub fn mwpm_decoder_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn belief_prop_decoder_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn union_find_decoder_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn ml_decoder_ty() -> Expr {
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0())))
}
pub fn decoding_threshold_ty() -> Expr {
arrow(type0(), real_ty())
}
pub fn mwpm_optimal_surface_ty() -> Expr {
prop()
}
pub fn bp_convergence_ldpc_ty() -> Expr {
prop()
}
pub fn subsystem_code_ty() -> Expr {
arrow(
nat_ty(),
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0()))),
)
}
pub fn gauge_group_ty() -> Expr {
arrow(
nat_ty(),
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0()))),
)
}
pub fn bacon_shor_code_ty() -> Expr {
arrow(nat_ty(), type0())
}
pub fn operator_qec_ty() -> Expr {
arrow(
nat_ty(),
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), prop()))),
)
}
pub fn subsystem_code_correction_ty() -> Expr {
prop()
}
pub fn bacon_shor_single_fault_tolerant_ty() -> Expr {
prop()
}
pub fn code_switching_ty() -> Expr {
arrow(
nat_ty(),
arrow(
nat_ty(),
arrow(
nat_ty(),
arrow(nat_ty(), arrow(nat_ty(), arrow(nat_ty(), type0()))),
),
),
)
}
pub fn gate_synthesis_ty() -> Expr {
arrow(nat_ty(), arrow(real_ty(), type0()))
}
pub fn solovay_kitaev_approx_ty() -> Expr {
arrow(real_ty(), nat_ty())
}
pub fn solovay_kitaev_theorem_ty() -> Expr {
prop()
}
pub fn t_count_optimality_ty() -> Expr {
prop()
}
#[allow(clippy::too_many_arguments)]
pub fn build_quantum_error_correction_env(env: &mut Environment) -> Result<(), String> {
let axioms: &[(&str, Expr)] = &[
("PauliOp", pauli_op_ty()),
("PauliGroup", pauli_group_ty()),
("PauliPhase", pauli_phase_ty()),
("SymplecticRepresentation", symplectic_representation_ty()),
("CommutatorPauli", commutator_pauli_ty()),
("WeightPauli", weight_pauli_ty()),
("PauliGroupNonAbelian", pauli_group_non_abelian_ty()),
("PauliSquareIdentity", pauli_square_identity_ty()),
("PauliAntiCommute", pauli_anti_commute_ty()),
("StabilizerGroup", stabilizer_group_ty()),
("StabilizerCode", stabilizer_code_ty()),
("ErrorSyndrome", error_syndrome_ty()),
("LogicalOperator", logical_operator_ty()),
("DecoderMap", decoder_map_ty()),
("CodeDistance", code_distance_ty()),
("KnillLaflammeConditions", knill_laflamme_conditions_ty()),
("QuantumSingletonBound", quantum_singleton_bound_ty()),
("QuantumHammingBound", quantum_hamming_bound_ty()),
("GottesmanKnillTheorem", gottesman_knill_theorem_ty()),
("ClassicalCode", classical_code_ty()),
("CSSCode", css_code_ty()),
("CSSXStabilizer", css_x_stabilizer_ty()),
("CSSZStabilizer", css_z_stabilizer_ty()),
("CSSConstruction", css_construction_ty()),
("CSSTransversalCNOT", css_transversal_cnot_ty()),
("ShorCode", shor_code_ty()),
("ShorLogicalZero", shor_logical_zero_ty()),
("ShorLogicalOne", shor_logical_one_ty()),
("ShorBitFlipCode", shor_bit_flip_code_ty()),
("ShorPhaseFlipCode", shor_phase_flip_code_ty()),
("ShorCorrectsSingleErrors", shor_corrects_single_errors_ty()),
("ShorIsCSS", shor_is_css_ty()),
("SteaneCode", steane_code_ty()),
("SteaneHMatrix", steane_h_matrix_ty()),
("SteaneStabilizer", steane_stabilizer_ty()),
(
"SteaneCorrectsSingleErrors",
steane_corrects_single_errors_ty(),
),
(
"SteaneTransversalClifford",
steane_transversal_clifford_ty(),
),
("SteaneIsCSS", steane_is_css_ty()),
("FaultTolerantGate", fault_tolerant_gate_ty()),
("TransversalGate", transversal_gate_ty()),
("MagicStateInjection", magic_state_injection_ty()),
("TeleportedGate", teleported_gate_ty()),
("EasttinKnillTheorem", easttin_knill_theorem_ty()),
("TransversalCliffordCSS", transversal_clifford_css_ty()),
(
"MagicStateDistillationWorks",
magic_state_distillation_works_ty(),
),
("ErrorThreshold", error_threshold_ty()),
("ConcatenatedCode", concatenated_code_ty()),
("FaultToleranceOverhead", fault_tolerance_overhead_ty()),
("PseudoThreshold", pseudo_threshold_ty()),
("ThresholdTheorem", threshold_theorem_ty()),
("ConcatenatedCodeDistance", concatenated_code_distance_ty()),
("PolytopeBound", polytope_bound_ty()),
("ColorCode", color_code_ty()),
("ColorCodeLattice", color_code_lattice_ty()),
("ColorCodeSyndrome", color_code_syndrome_ty()),
("ColorCodeTransversalT", color_code_transversal_t_ty()),
("ColorCodeEquivalent", color_code_equivalent_ty()),
("QuantumCapacity", quantum_capacity_ty()),
("CoherentInformation", coherent_information_ty()),
("HashingBound", hashing_bound_ty()),
("QuantumErasureCapacity", quantum_erasure_capacity_ty()),
("QuantumNoiseThreshold", quantum_noise_threshold_ty()),
("QuantumShannonTheorem", quantum_shannon_theorem_ty()),
("NoCloning", no_cloning_capacity_ty()),
("KLMatrix", kl_matrix_ty()),
("KLErrorSet", kl_error_set_ty()),
("KLCorrectableCode", kl_correctable_code_ty()),
("KLNecessaryCondition", kl_necessary_condition_ty()),
("KLSufficientCondition", kl_sufficient_condition_ty()),
("KLEquivalence", kl_equivalence_ty()),
("KLDegenerateCode", kl_degenerate_code_ty()),
("ReedMullerCode", reed_muller_code_ty()),
("QuantumReedMullerCode", quantum_reed_muller_code_ty()),
("RMTransversalT", rm_transversal_t_ty()),
("RMCodeConcatenation", rm_code_concatenation_ty()),
("RMTransversalUniversal", rm_transversal_universal_ty()),
("RMCodeDistance", rm_code_distance_ty()),
("SurfaceCode", surface_code_ty()),
("ToricCode", toric_code_ty()),
("SurfaceCodeVertex", surface_code_vertex_ty()),
("SurfaceCodePlaquette", surface_code_plaquette_ty()),
("SurfaceCodeLogical", surface_code_logical_ty()),
("SurfaceCodeDistance", surface_code_distance_ty()),
("ToricCodeAnyons", toric_code_anyons_ty()),
("SurfaceCodeThreshold", surface_code_threshold_ty()),
("QLDPCCode", qldpc_code_ty()),
("FiberBundleCode", fiber_bundle_code_ty()),
("GoodQLDPCCode", good_qldpc_code_ty()),
("QLDPCTanner", qldpc_tanner_ty()),
("QLDPCGoodCodes", qldpc_good_codes_ty()),
("FiberBundleDistance", fiber_bundle_distance_ty()),
("BosonicCode", bosonic_code_ty()),
("CatCode", cat_code_ty()),
("GKPCode", gkp_code_ty()),
("BinomialCode", binomial_code_ty()),
("GKPDisplacementError", gkp_displacement_error_ty()),
(
"GKPCorrectsBoundedDisplacement",
gkp_corrects_bounded_displacement_ty(),
),
("CatCodeLossTolerance", cat_code_loss_tolerance_ty()),
("NoiseModel", noise_model_ty()),
("DepolarizingNoise", depolarizing_noise_ty()),
("CircuitNoiseThreshold", circuit_noise_threshold_ty()),
("FaultToleranceGadget", fault_tolerance_gadget_ty()),
("CircuitThresholdTheorem", circuit_threshold_theorem_ty()),
("ThresholdUpperBound", threshold_upper_bound_ty()),
("MagicState", magic_state_ty()),
("TState", t_state_ty()),
("DistillationProtocol", distillation_protocol_ty()),
("MagicStateRobustness", magic_state_robustness_ty()),
("BravyiKitaevDistillation", bravyi_kitaev_distillation_ty()),
("MagicStateNonStabilizer", magic_state_non_stabilizer_ty()),
("MWPMDecoder", mwpm_decoder_ty()),
("BeliefPropDecoder", belief_prop_decoder_ty()),
("UnionFindDecoder", union_find_decoder_ty()),
("MLDecoder", ml_decoder_ty()),
("DecodingThreshold", decoding_threshold_ty()),
("MWPMOptimalSurface", mwpm_optimal_surface_ty()),
("BPConvergenceLDPC", bp_convergence_ldpc_ty()),
("SubsystemCode", subsystem_code_ty()),
("GaugeGroup", gauge_group_ty()),
("BaconShorCode", bacon_shor_code_ty()),
("OperatorQEC", operator_qec_ty()),
("SubsystemCodeCorrection", subsystem_code_correction_ty()),
(
"BaconShorSingleFaultTolerant",
bacon_shor_single_fault_tolerant_ty(),
),
("CodeSwitching", code_switching_ty()),
("GateSynthesis", gate_synthesis_ty()),
("SolovayKitaevApprox", solovay_kitaev_approx_ty()),
("SolovayKitaevTheorem", solovay_kitaev_theorem_ty()),
("TCountOptimality", t_count_optimality_ty()),
];
for (name, ty) in axioms {
env.add(Declaration::Axiom {
name: Name::str(*name),
univ_params: vec![],
ty: ty.clone(),
})
.map_err(|e| format!("Failed to add '{}': {:?}", name, e))?;
}
Ok(())
}
pub fn binary_entropy(p: f64) -> f64 {
if p <= 0.0 || p >= 1.0 {
return 0.0;
}
-p * p.log2() - (1.0 - p) * (1.0 - p).log2()
}
pub fn hashing_bound(p: f64) -> f64 {
let q = 1.0 - binary_entropy(p) - p * 3.0_f64.log2();
q.max(0.0)
}
pub fn erasure_channel_capacity(epsilon: f64) -> f64 {
(1.0 - 2.0 * epsilon).max(0.0)
}
pub fn amplitude_damping_capacity(gamma: f64) -> f64 {
(1.0 - binary_entropy(gamma)).max(0.0)
}
pub fn distill_t_state_fidelity(f_in: f64) -> f64 {
let eps = 1.0 - f_in;
let f_out = 1.0 - 35.0 * eps.powi(3);
f_out.min(1.0).max(0.0)
}
pub fn distillation_rounds(f_init: f64, f_target: f64) -> usize {
let mut f = f_init;
let mut rounds = 0;
while f < f_target && rounds < 100 {
f = distill_t_state_fidelity(f);
rounds += 1;
}
rounds
}
pub fn distillation_overhead(rounds: usize) -> u64 {
15u64.pow(rounds as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pauli_commutation() {
assert!(!PauliOp::X.commutes_with(PauliOp::Z));
assert!(!PauliOp::X.commutes_with(PauliOp::Y));
assert!(PauliOp::X.commutes_with(PauliOp::X));
for &p in &[PauliOp::I, PauliOp::X, PauliOp::Y, PauliOp::Z] {
assert!(PauliOp::I.commutes_with(p));
}
}
#[test]
fn test_pauli_string_commutation() {
let a = PauliString::new(vec![PauliOp::Z, PauliOp::Z, PauliOp::I]);
let b = PauliString::new(vec![PauliOp::I, PauliOp::Z, PauliOp::Z]);
assert!(a.commutes_with(&b));
let c = PauliString::new(vec![PauliOp::X, PauliOp::X, PauliOp::I]);
assert!(!c.commutes_with(&b));
}
#[test]
fn test_stabilizer_code_3qubit() {
let code = StabilizerCode::bit_flip_3();
assert_eq!(code.n, 3);
assert_eq!(code.k, 1);
let x_err = vec![0u8; 3];
let z_err = vec![0u8; 3];
let synd = code.syndrome(&x_err, &z_err);
assert!(synd.iter().all(|&s| s == 0));
let x_err1 = vec![1u8, 0, 0];
assert!(code.detects_error(&x_err1, &z_err));
}
#[test]
fn test_steane_7_code() {
let code = StabilizerCode::steane_7();
assert_eq!(code.n, 7);
assert_eq!(code.k, 1);
assert_eq!(code.d, 3);
let x_err = vec![0u8; 7];
let z_err = vec![0u8; 7];
let synd = code.syndrome(&x_err, &z_err);
assert!(
synd.iter().all(|&s| s == 0),
"No-error syndrome should be zero"
);
assert!(code.satisfies_singleton_bound());
assert!(code.satisfies_hamming_bound());
}
#[test]
fn test_shor_code() {
let shor = ShorCode::new();
assert_eq!(shor.n(), 9);
assert_eq!(shor.k(), 1);
assert_eq!(shor.d(), 3);
assert!(shor.corrects_single_qubit_error());
assert!(shor.satisfies_singleton_bound());
let x_err = vec![0u8; 9];
let z_err = vec![0u8; 9];
let synd = shor.syndrome(&x_err, &z_err);
assert!(synd.iter().all(|&s| s == 0));
}
#[test]
fn test_css_steane_syndrome() {
let css = CSSCode::steane();
let no_err = vec![0u8; 7];
assert!(!css.detects_x_error(&no_err));
assert!(!css.detects_z_error(&no_err));
let mut x_err = vec![0u8; 7];
x_err[0] = 1;
assert!(css.detects_x_error(&x_err));
}
#[test]
fn test_hashing_bound() {
assert!((hashing_bound(0.0) - 1.0).abs() < 1e-9);
let q = hashing_bound(0.25);
assert!(q >= 0.0);
assert!((erasure_channel_capacity(0.0) - 1.0).abs() < 1e-9);
assert!((erasure_channel_capacity(0.5)).abs() < 1e-9);
assert!(erasure_channel_capacity(0.3) > 0.0);
}
#[test]
fn test_magic_state_distillation() {
let f_init = 0.95;
let f_out = distill_t_state_fidelity(f_init);
assert!(f_out > f_init, "Distillation should improve fidelity");
let rounds = distillation_rounds(f_init, 0.9999);
assert!(rounds >= 1);
assert_eq!(distillation_overhead(1), 15);
assert_eq!(distillation_overhead(2), 225);
}
#[test]
fn test_concatenated_code() {
let cc = ConcatenatedCode::new(7, 3, 2);
assert_eq!(cc.num_physical_qubits(), 49);
assert_eq!(cc.distance(), 9);
let cc1 = ConcatenatedCode::new(7, 3, 1);
let cc2 = ConcatenatedCode::new(7, 3, 2);
let p = 0.001;
let th = 0.01;
assert!(cc2.logical_error_rate(p, th) < cc1.logical_error_rate(p, th));
}
#[test]
fn test_build_quantum_error_correction_env() {
let mut env = oxilean_kernel::Environment::new();
let result = build_quantum_error_correction_env(&mut env);
assert!(
result.is_ok(),
"build_quantum_error_correction_env failed: {:?}",
result.err()
);
}
#[test]
fn test_surface_code_decoder() {
let decoder = SurfaceCodeDecoder::new(3);
let corrections = decoder.decode(&[]);
assert!(corrections.is_empty());
let d3 = SurfaceCodeDecoder::new(3);
let d5 = SurfaceCodeDecoder::new(5);
let p = 0.001;
assert!(d5.logical_error_rate(p) < d3.logical_error_rate(p));
assert!(d3.logical_error_rate(0.005) < 0.5);
}
#[test]
fn test_surface_code_decoder_syndrome_matching() {
let decoder = SurfaceCodeDecoder::new(5);
let syndrome = vec![(1, 1), (1, 2)];
let corrections = decoder.decode(&syndrome);
assert!(!corrections.is_empty());
}
#[test]
fn test_stabilizer_simulator_init() {
let sim = StabilizerSimulator::new(3);
assert_eq!(sim.measure_z(0), 0);
assert_eq!(sim.measure_z(1), 0);
assert_eq!(sim.measure_z(2), 0);
}
#[test]
fn test_stabilizer_simulator_hadamard() {
let mut sim = StabilizerSimulator::new(2);
sim.hadamard(0);
assert_eq!(sim.stab_x[0][0], 1);
assert_eq!(sim.stab_z[0][0], 0);
}
#[test]
fn test_stabilizer_simulator_phase_gate() {
let mut sim = StabilizerSimulator::new(1);
sim.phase_gate(0);
assert_eq!(sim.stab_z[0][0], 1);
assert_eq!(sim.stab_x[0][0], 0);
}
#[test]
fn test_fault_tolerance_threshold() {
let ft = FaultToleranceThreshold::new(7, 1, 3);
let p_th = ft.estimate_threshold();
assert!(p_th > 0.0);
assert!((ft.logical_error_rate(p_th, 1) - 0.5).abs() < 1e-10);
let p = p_th * 0.5;
assert!(ft.logical_error_rate(p, 2) < ft.logical_error_rate(p, 1));
let level = ft.min_level(p, 1e-6);
assert!(level < u32::MAX);
}
#[test]
fn test_qec_norm_checker_steane() {
let code = StabilizerCode::steane_7();
let checker = QECNormChecker::new(code);
assert!(
checker.all_single_qubit_errors_correctable(),
"Steane code should correct all single-qubit errors"
);
}
#[test]
fn test_qec_norm_checker_kl_condition() {
let code = StabilizerCode::steane_7();
let checker = QECNormChecker::new(code);
assert!(checker.satisfies_kl_conditions(&[0u8; 7], &[0u8; 7]));
let mut x_err = vec![0u8; 7];
x_err[0] = 1;
assert!(checker.satisfies_kl_conditions(&x_err, &[0u8; 7]));
}
#[test]
fn test_gkp_code_simulator_correction() {
let gkp = GKPCodeSimulator::new();
let delta = gkp.lattice_spacing;
assert!(gkp.is_correctable(delta * 0.1, delta * 0.1));
assert!(!gkp.is_correctable(delta * 0.6, 0.0));
let (rq, rp) = gkp.correct_displacement(0.1, 0.05);
assert!(rq.abs() < delta / 2.0);
assert!(rp.abs() < delta / 2.0);
}
#[test]
fn test_gkp_code_simulator_logical_error_rate() {
let gkp = GKPCodeSimulator::new();
let rate_small = gkp.logical_error_rate_gaussian(0.1);
let rate_large = gkp.logical_error_rate_gaussian(0.5);
assert!(
rate_small < rate_large,
"Larger noise should give larger error rate"
);
assert_eq!(gkp.logical_error_rate_gaussian(0.0), 0.0);
}
#[test]
fn test_gkp_simulate_errors() {
let gkp = GKPCodeSimulator::new();
let delta = gkp.lattice_spacing;
let displacements = vec![
(delta * 0.1, delta * 0.1),
(delta * 0.4, delta * 0.4),
(delta * 0.6, 0.0),
];
let uncorrected = gkp.simulate_errors(&displacements);
assert_eq!(
uncorrected, 1,
"Only one displacement should be uncorrectable"
);
}
}
#[cfg(test)]
mod tests_qec_extra {
use super::*;
#[test]
fn test_pauli_commutation() {
let x = PauliOperator::single_x(2, 0);
let z = PauliOperator::single_z(2, 0);
assert!(!x.commutes_with(&z), "X and Z anticommute");
let x1 = PauliOperator::single_x(2, 0);
let x2 = PauliOperator::single_x(2, 1);
assert!(x1.commutes_with(&x2), "X on different qubits commute");
}
#[test]
fn test_five_qubit_code() {
let code = StabCode::five_qubit_code();
assert_eq!(code.n_physical, 5);
assert_eq!(code.k_logical, 1);
assert_eq!(code.generators.len(), 4);
for i in 0..4 {
for j in (i + 1)..4 {
assert!(
code.generators[i].commutes_with(&code.generators[j]),
"Generator {} must commute with {}",
i,
j
);
}
}
}
#[test]
fn test_steane_code_structure() {
let code = StabCode::steane_code();
assert_eq!(code.n_physical, 7);
assert_eq!(code.k_logical, 1);
assert_eq!(code.generators.len(), 6);
}
#[test]
fn test_syndrome_decoder_weight1() {
let code = StabCode::five_qubit_code();
let mut decoder = SyndromeDecoder2::new(code);
decoder.build_weight1_table();
assert!(decoder.lookup_table.len() <= 15);
}
#[test]
fn test_threshold_estimator() {
let est = ThresholdEstimator::new(0.001, 3, 10);
let threshold = 0.01;
assert!(est.is_below_threshold(threshold));
let logical_rate = est.logical_error_rate(threshold);
assert!(
logical_rate < est.physical_error_rate,
"Logical rate should improve below threshold"
);
}
#[test]
fn test_surface_code() {
let sc = SurfaceCode::new(5);
assert_eq!(sc.code_distance(), 5);
assert_eq!(sc.n_data_qubits, 25);
assert!(sc.total_qubits() > 25);
assert!(SurfaceCode::depolarizing_threshold() > 0.0);
}
#[test]
fn test_magic_state_distillation() {
let msd = MagicStateDistillation::new(0.01, 1e-10, MagicStateProtocol::FifteenToOne);
let out = msd.output_error_rate();
assert!(
out < msd.input_error_rate,
"Distillation should reduce error"
);
let rounds = msd.n_rounds_needed();
assert!(rounds > 0);
}
#[test]
fn test_quantum_ldpc() {
let code = QuantumLDPC::new(100, 10, 10, 6, 6);
assert!(code.rate() > 0.0);
let hp = QuantumLDPC::hypergraph_product(4, 8, 4, 8);
assert!(hp.n > 0);
}
}