diff --git a/.typos.toml b/.typos.toml index fd32352e..80d170cf 100644 --- a/.typos.toml +++ b/.typos.toml @@ -1,3 +1,7 @@ +[default] +# Unicode decimal-number category in regular expressions. +extend-ignore-re = ['\\p\{Nd\}'] + [default.extend-words] ket = "ket" bra = "bra" diff --git a/crates/binding-c/src/circuit/properties.rs b/crates/binding-c/src/circuit/properties.rs index 309c9fb8..992fd4a6 100644 --- a/crates/binding-c/src/circuit/properties.rs +++ b/crates/binding-c/src/circuit/properties.rs @@ -158,7 +158,9 @@ pub extern "C" fn circuit_to_matrix( } /// Compose another circuit into this one. `qubits_map` maps `other`'s qubits -/// to this circuit's qubits. NULL map uses identity mapping (merge by ID). +/// in insertion order to distinct qubits already in this circuit. +/// NULL or zero-length map uses identity mapping (merge by ID). +/// Errors leave this circuit unchanged. #[unsafe(no_mangle)] pub extern "C" fn circuit_compose( ptr: *mut CCircuit, diff --git a/crates/binding-c/tests/circuit_test.rs b/crates/binding-c/tests/circuit_test.rs index 1490794c..26b98384 100644 --- a/crates/binding-c/tests/circuit_test.rs +++ b/crates/binding-c/tests/circuit_test.rs @@ -289,6 +289,52 @@ fn compose_and_add_qubits() { circuit_free(circuit); } +#[test] +fn compose_rejects_duplicate_targets_without_mutation() { + for width in [1, 2] { + let circuit = circuit_new(width); + assert_eq!(circuit_h(circuit, 0), 0); + let len = circuit_to_matrix_len(circuit, std::ptr::null(), 0); + let mut before = vec![0.0; len * 2]; + assert_eq!( + circuit_to_matrix( + circuit, + std::ptr::null(), + 0, + before.as_mut_ptr(), + before.len() + ), + len + ); + let other = circuit_new(2); + assert_eq!(circuit_cx(other, 0, 1), 0); + let mapping = [0, 0]; + + assert_eq!( + circuit_compose(circuit, other, mapping.as_ptr(), mapping.len()), + -3 + ); + + assert_eq!(circuit_num_qubits(circuit), width); + assert_eq!(circuit_num_operations(circuit), 1); + assert_eq!(circuit_num_operations(other), 1); + let mut after = vec![0.0; len * 2]; + assert_eq!( + circuit_to_matrix( + circuit, + std::ptr::null(), + 0, + after.as_mut_ptr(), + after.len() + ), + len + ); + assert_eq!(after, before); + circuit_free(other); + circuit_free(circuit); + } +} + #[test] fn global_phase_operations() { let circuit = circuit_new(1); diff --git a/crates/binding-python/cqlib/circuit/circuit.pyi b/crates/binding-python/cqlib/circuit/circuit.pyi index 316e3338..94fab82b 100644 --- a/crates/binding-python/cqlib/circuit/circuit.pyi +++ b/crates/binding-python/cqlib/circuit/circuit.pyi @@ -638,7 +638,15 @@ class Circuit: """ ... def compose(self, other: Circuit, qubits: QubitList | None = ...) -> None: - """Append another circuit, optionally remapping its qubits.""" + """Append another circuit, optionally remapping its qubits in insertion order. + + Explicit targets must be distinct and already present in this circuit. + If ``qubits`` is None, merge qubits by ID, appending previously absent IDs. + Errors leave this circuit unchanged; existing classical handles remain valid. + + Raises: + CircuitError: If the mapping is invalid or stored references cannot be remapped. + """ ... def to_matrix(self, qubits_order: list[int] | None = ...) -> NDArray[np.complex128]: """Compute the dense numeric unitary matrix. diff --git a/crates/binding-python/src/circuit/circuit_impl.rs b/crates/binding-python/src/circuit/circuit_impl.rs index 678fa991..5e2f0f10 100644 --- a/crates/binding-python/src/circuit/circuit_impl.rs +++ b/crates/binding-python/src/circuit/circuit_impl.rs @@ -1007,7 +1007,9 @@ impl PyCircuit { .map_err(|error| PyCircuitError::new_err(error.to_string())) } - /// Appends another circuit, optionally remapping its qubits. + /// Appends another circuit, optionally remapping its qubits in source insertion order. + /// Explicit targets must be distinct and already present in this circuit. + /// Errors leave this circuit unchanged; existing classical handles remain valid. #[pyo3(signature = (other, qubits=None))] fn compose(&mut self, other: &PyCircuit, qubits: Option) -> PyResult<()> { let qubits = qubits.map(Vec::from); diff --git a/crates/binding-python/tests/circuit/test_edge_cases.py b/crates/binding-python/tests/circuit/test_edge_cases.py index 46c83ba1..b23fd02c 100644 --- a/crates/binding-python/tests/circuit/test_edge_cases.py +++ b/crates/binding-python/tests/circuit/test_edge_cases.py @@ -81,3 +81,20 @@ def test_compose_reports_incompatible_mapping(): with pytest.raises(CircuitError): main.compose(other, [0, 2]) + + +@pytest.mark.parametrize("width", [1, 2]) +def test_compose_rejects_duplicate_targets_without_mutation(width): + main = Circuit(width) + main.h(0) + before = main.to_matrix().copy() + other = Circuit(2) + other.cx(0, 1) + + with pytest.raises(CircuitError): + main.compose(other, [0, 0]) + + assert main.num_qubits == width + assert len(main.operations) == 1 + assert np.allclose(main.to_matrix(), before) + assert len(other.operations) == 1 diff --git a/crates/cqlib-core/src/circuit/circuit_classical.rs b/crates/cqlib-core/src/circuit/circuit_classical.rs index 7f51423c..8621fb23 100644 --- a/crates/cqlib-core/src/circuit/circuit_classical.rs +++ b/crates/cqlib-core/src/circuit/circuit_classical.rs @@ -411,7 +411,9 @@ use crate::circuit::control_flow::{ }; use crate::circuit::error::CircuitError; use crate::circuit::gate::instruction::Instruction; -use crate::circuit::{ClassicalDataOp, ClassicalType, ClassicalValue, ClassicalVar, Measurement}; +use crate::circuit::{ + CircuitParam, ClassicalDataOp, ClassicalType, ClassicalValue, ClassicalVar, Measurement, +}; use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -467,14 +469,17 @@ impl SwitchBuilder<'_> { } } -#[derive(Debug, Clone, Copy)] +/// Restores appended builder state and the previous phase, not edits to existing entries. +#[derive(Debug, Clone)] pub(super) struct CircuitCheckpoint { data_len: usize, + qubit_len: usize, parameter_len: usize, symbol_len: usize, classical_var_len: usize, classical_value_len: usize, control_scope_len: usize, + global_phase: CircuitParam, } /// Opaque rollback token for callback-driven control-flow construction. @@ -539,17 +544,21 @@ impl Circuit { pub(super) fn checkpoint(&self) -> CircuitCheckpoint { CircuitCheckpoint { data_len: self.data.len(), + qubit_len: self.qubits.len(), parameter_len: self.parameters.len(), symbol_len: self.symbols.len(), classical_var_len: self.classical_vars.len(), classical_value_len: self.classical_values.len(), control_scope_len: self.control_scope_stack.len(), + global_phase: self.global_phase.clone(), } } pub(super) fn rollback_to(&mut self, checkpoint: CircuitCheckpoint) { Arc::make_mut(&mut self.data).truncate(checkpoint.data_len); + self.qubits.truncate(checkpoint.qubit_len); self.parameters.truncate(checkpoint.parameter_len); + self.global_phase = checkpoint.global_phase; self.symbols.truncate(checkpoint.symbol_len); self.classical_vars.truncate(checkpoint.classical_var_len); self.classical_values diff --git a/crates/cqlib-core/src/circuit/circuit_impl.rs b/crates/cqlib-core/src/circuit/circuit_impl.rs index d670328f..15958783 100644 --- a/crates/cqlib-core/src/circuit/circuit_impl.rs +++ b/crates/cqlib-core/src/circuit/circuit_impl.rs @@ -2489,6 +2489,8 @@ impl Circuit { /// /// Parameters that remain symbolic are simplified and re-interned in the /// returned circuit. The original circuit is not modified. + /// Internal classical references are remapped to the returned circuit's + /// identity; handles from the original circuit remain owned by it. /// /// # Errors /// @@ -2513,6 +2515,29 @@ impl Circuit { new_circuit.classical_vars = self.classical_vars.clone(); new_circuit.classical_values = self.classical_values.clone(); + let var_map = self + .classical_vars + .iter() + .enumerate() + .map(|(index, ty)| { + ( + ClassicalVar::new(self.circuit_id, index as u32, *ty), + ClassicalVar::new(new_circuit.circuit_id, index as u32, *ty), + ) + }) + .collect(); + let value_map = self + .classical_values + .iter() + .enumerate() + .map(|(index, ty)| { + ( + ClassicalValue::new(self.circuit_id, index as u32, *ty), + ClassicalValue::new(new_circuit.circuit_id, index as u32, *ty), + ) + }) + .collect(); + // Map from old parameter index to new CircuitParam (either Fixed or Index) let mut index_map: Vec = Vec::with_capacity(self.parameters.len()); @@ -2547,20 +2572,23 @@ impl Circuit { } } - // Remap operations to use new parameter indices or fixed values + // Remap parameter indices and all classical references in the same pass. let new_data = Arc::make_mut(&mut new_circuit.data); new_data.reserve(self.data.len()); for op in self.data.iter() { - let mut new_op = op.clone(); - for p in &mut new_op.params { - if let CircuitParam::Index(old_idx) = p { - *p = index_map + new_data.push(Self::remap_operation( + op, + &|qubit| Ok(qubit), + &|param| match param { + CircuitParam::Index(old_idx) => index_map .get(*old_idx as usize) .cloned() - .ok_or(CircuitError::InvalidParameterIndex(*old_idx))?; - } - } - new_data.push(new_op); + .ok_or(CircuitError::InvalidParameterIndex(*old_idx)), + CircuitParam::Fixed(value) => Ok(CircuitParam::Fixed(*value)), + }, + &var_map, + &value_map, + )?); } // Remap global phase @@ -2781,21 +2809,25 @@ impl Circuit { /// [`Qubit`] IDs. /// Circuit-local classical variables and values from `other` are appended to `self`'s /// classical tables, and all classical data/control references inside copied operations are - /// remapped to those new local IDs. + /// remapped to those new local IDs. The identity of `self` and its existing classical + /// handles are preserved. If composition returns an error, `self` is unchanged. /// /// # Arguments /// /// * `other` - The circuit to compose into this circuit. /// * `qubits_map` - An optional slice mapping qubits from `other` to qubits in `self`. - /// - If `Some(mapping)` is provided, each qubit in `other` (in their natural iteration order) - /// is mapped to the corresponding qubit in `mapping`. + /// - If `Some(mapping)` is provided, each qubit in `other` (in insertion order) + /// is mapped to the corresponding qubit in `mapping`. Target qubits must be distinct, + /// including targets corresponding to idle source qubits. /// - If `None` is provided, qubits are mapped by ID. IDs not already present in `self` are /// appended, while matching IDs reuse the existing qubits. /// /// # Returns /// /// * `Ok(())` - If composition succeeds. - /// * `Err(CircuitError)` - If the mapping is invalid (wrong length or non-existent qubits). + /// * `Err(CircuitError)` - If the mapping has the wrong length, contains duplicate targets + /// ([`CircuitError::DuplicateQubits`]), references non-existent qubits, or stored circuit + /// references cannot be remapped. /// /// # Examples /// @@ -2834,6 +2866,9 @@ impl Circuit { actual: mapping.len(), }); } + if !Self::check_qubits_unique(mapping) { + return Err(CircuitError::DuplicateQubits); + } // Build map and validate target qubits exist in self let mut map = HashMap::with_capacity(mapping.len()); @@ -2848,8 +2883,6 @@ impl Circuit { // No explicit mapping: merge qubits by ID. let mut map = HashMap::with_capacity(other.qubits.len()); for other_qubit in other.qubits.iter() { - // Existing IDs are reused; new IDs preserve `other`'s insertion order. - self.qubits.insert(*other_qubit); map.insert(*other_qubit, *other_qubit); } map @@ -2875,10 +2908,20 @@ impl Circuit { ); } - // Merge parameters and build index mapping + // Stage only new parameters: remapping and phase resolution can still fail. + // Keep the existing registry read-only rather than copying it on each composition. + // Staged indices follow the existing entries and remain valid after the final append. + let parameter_base = self.parameters.len(); + let mut new_parameters = IndexSet::new(); + let mut new_symbols = IndexSet::new(); let mut param_index_map: Vec = Vec::with_capacity(other.parameters.len()); for param in other.parameters.iter() { - let (idx, _) = self.add_parameter(param.clone()); + let idx = if let Some(idx) = self.parameters.get_index_of(param) { + idx + } else { + new_symbols.extend(param.get_symbols()); + parameter_base + new_parameters.insert_full(param.clone()).0 + }; param_index_map.push(CircuitParam::Index(idx as u32)); } @@ -2896,56 +2939,32 @@ impl Circuit { }) .collect::, _>>()?; - // Merge global phase (if both have fixed values, add them; otherwise keep symbolic) - self.global_phase = match (self.global_phase.clone(), other.global_phase.clone()) { + // Resolve against the original registries. A new source parameter must not make an + // invalid pre-existing destination index appear valid in the merged registry. + let global_phase = match (&self.global_phase, &other.global_phase) { (CircuitParam::Fixed(a), CircuitParam::Fixed(b)) => CircuitParam::Fixed(a + b), - (CircuitParam::Fixed(a), CircuitParam::Index(idx)) => { - // Add fixed value to symbolic parameter - let sym_param = other - .parameters - .get_index(idx as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx))?; - let new_expr = Parameter::from(a) + sym_param; - let (new_idx, _) = self.parameters.insert_full(new_expr); - CircuitParam::Index(new_idx as u32) - } - (CircuitParam::Index(idx), CircuitParam::Fixed(b)) => { - // Add symbolic parameter to fixed value - let sym_param = self - .parameters - .get_index(idx as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx))?; - let new_expr = sym_param + Parameter::from(b); - let (new_idx, _) = self.parameters.insert_full(new_expr); - CircuitParam::Index(new_idx as u32) - } - (CircuitParam::Index(idx_a), CircuitParam::Index(idx_b)) => { - // Add two symbolic parameters - let param_a = self - .parameters - .get_index(idx_a as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx_a))?; - let param_b = other - .parameters - .get_index(idx_b as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx_b))?; - // param_b needs to be merged into self's parameter set first - let (merged_b_idx, _) = self.parameters.insert_full(param_b); - let merged_b = self + _ => { + let new_expr = self.resolve_parameter(&self.global_phase)? + + other.resolve_parameter(&other.global_phase)?; + // Every symbol in the sum already belongs to one of the merged registries. + let new_idx = self .parameters - .get_index(merged_b_idx) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(merged_b_idx as u32))?; - let new_expr = param_a + merged_b; - let (new_idx, _) = self.parameters.insert_full(new_expr); + .get_index_of(&new_expr) + .unwrap_or_else(|| parameter_base + new_parameters.insert_full(new_expr).0); CircuitParam::Index(new_idx as u32) } }; + // Commit only after all fallible preparation succeeds. Preserve insertion order and + // the active control-builder scope, as well as all existing classical handle IDs. + if qubits_map.is_none() { + self.qubits.extend(other.qubits.iter().copied()); + } + if !new_parameters.is_empty() { + self.parameters.extend(new_parameters); + } + self.symbols.extend(new_symbols); + self.global_phase = global_phase; self.classical_vars .extend(other.classical_vars.iter().copied()); self.classical_values diff --git a/crates/cqlib-core/src/circuit/circuit_test.rs b/crates/cqlib-core/src/circuit/circuit_test.rs index 373ef8dc..c42c81b5 100644 --- a/crates/cqlib-core/src/circuit/circuit_test.rs +++ b/crates/cqlib-core/src/circuit/circuit_test.rs @@ -20,13 +20,16 @@ use crate::circuit::gate::{ }; use crate::circuit::operation::ValueOperation; use crate::circuit::parameter::Parameter; +use crate::circuit::symbolic_matrix::{circuit_to_symbolic_matrix, evaluate_symbolic_matrix}; +use crate::circuit::test_utils::assert_matrix_approx_eq; use crate::circuit::{ ClassicalControlOp, ClassicalExpr, ClassicalType, ClassicalValue, ClassicalVar, ControlBody, - IfOp, Operation, SwitchCase, SwitchOp, ValueClassicalControlOp, ValueControlBody, - ValueInstruction, WhileOp, + ExternalControlScope, IfOp, Operation, SwitchCase, SwitchOp, ValueClassicalControlOp, + ValueControlBody, ValueInstruction, WhileOp, circuit_to_matrix, }; +use crate::qis::{RuntimeValue, StabilizerState, Statevector}; use smallvec::smallvec; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::f64::consts::PI; use std::sync::Arc; @@ -1239,8 +1242,6 @@ fn test_to_gate_and_circuit_gate() { #[test] fn test_assign_parameters() { - use std::collections::HashMap; - let mut circuit = Circuit::new(2); let q0 = Qubit::new(0); let a = Parameter::symbol("a"); @@ -1303,6 +1304,202 @@ fn test_assign_parameters() { } } +#[test] +fn test_assign_parameters_preserves_measurement_execution() { + for with_store in [false, true] { + let q0 = Qubit::new(0); + let mut source = Circuit::new(1); + source.rx(q0, "theta").unwrap(); + source.rz(q0, "phi").unwrap(); + source.set_global_phase(Parameter::symbol("theta")); + let measured = source.measure(q0).unwrap(); + if with_store { + let target = source.var(ClassicalType::Bit); + source.store(target, measured.expr()).unwrap(); + } + let before = format!("{source:?}"); + let full = Some(HashMap::from([("theta", 0.731), ("phi", 0.317)])); + + for bindings in [ + None, + Some(HashMap::new()), + Some(HashMap::from([("theta", 0.731)])), + full.clone(), + ] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_ne!(bound.id(), source.id()); + assert_eq!(bound.classical_values(), source.classical_values()); + assert!(matches!( + bound.validate_classical_expr(&measured.expr()), + Err(CircuitError::ForeignClassicalHandle { .. }) + )); + bound.clone().validate().unwrap(); + bound.decompose().unwrap().validate().unwrap(); + + if bindings.as_ref().is_some_and(|map| map.len() == 1) { + assert_eq!(bound.data[0].params[0], CircuitParam::Fixed(0.731)); + assert_eq!(bound.data[1].params[0], CircuitParam::Index(0)); + assert_eq!(bound.parameters.len(), 1); + assert!(bound.symbols.contains("phi")); + assert!(!bound.symbols.contains("theta")); + assert_eq!(*bound.global_phase_param(), CircuitParam::Fixed(0.731)); + } + + let complete = bound.assign_parameters(&full).unwrap(); + complete.validate().unwrap(); + assert_ne!(complete.id(), bound.id()); + let actual = Statevector::from_circuit(&complete).unwrap(); + let mut expected = Circuit::new(1); + expected.rx(q0, 0.731).unwrap(); + expected.rz(q0, 0.317).unwrap(); + expected.set_global_phase(Parameter::from(0.731)); + let expected = Statevector::from_circuit(&expected).unwrap(); + for (actual, expected) in actual.data().iter().zip(expected.data()) { + assert!((*actual - *expected).norm() < 1e-12); + } + assert_eq!(format!("{source:?}"), before); + } + } +} + +#[test] +fn test_assign_parameters_executes_classical_dataflow() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + for multibit in [false, true] { + let mut source = Circuit::new(2); + source.set_global_phase(Parameter::symbol("theta") + Parameter::symbol("phi")); + source.x(q0).unwrap(); + let measured = if multibit { + source.measure_bits([q1, q0]).unwrap() + } else { + source.measure(q0).unwrap() + }; + let first = source.var(measured.ty()); + let second = source.var(measured.ty()); + source.store(first, measured.expr()).unwrap(); + source.store(second, first.expr()).unwrap(); + let flag = source.var(ClassicalType::Bool); + // A nested expression must remap both immutable values and mutable vars. + source + .store( + flag, + !ClassicalExpr::eq(second.expr(), measured.expr()).unwrap(), + ) + .unwrap(); + let before = format!("{source:?}"); + + for bindings in [ + None, + Some(HashMap::new()), + Some(HashMap::from([("theta", 0.731)])), + Some(HashMap::from([("theta", 0.731), ("phi", 0.317)])), + ] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_eq!(bound.classical_vars(), source.classical_vars()); + assert_eq!(bound.classical_values(), source.classical_values()); + assert!(matches!( + bound.validate_classical_var(first), + Err(CircuitError::ForeignClassicalHandle { .. }) + )); + // Complete partial/absent bindings before runtime execution. + let mut complete = bound + .assign_parameters(&Some(HashMap::from([("theta", 0.731), ("phi", 0.317)]))) + .unwrap(); + complete.validate().unwrap(); + let execution = StabilizerState::run_circuit(&complete).unwrap(); + for operation in complete.operations() { + match &operation.instruction { + Instruction::ClassicalData(ClassicalDataOp::MeasureBit { result }) => { + assert_eq!( + execution.classical.value(*result), + Some(&RuntimeValue::Bit(true)) + ); + } + Instruction::ClassicalData(ClassicalDataOp::MeasureBits { result }) => { + assert_eq!( + execution + .classical + .value(*result) + .unwrap() + .to_bitstring() + .unwrap(), + "10" + ); + } + Instruction::ClassicalData(ClassicalDataOp::Store { target, .. }) => { + let actual = execution.classical.var(*target).unwrap(); + if target.ty() == ClassicalType::Bool { + assert_eq!(*actual, RuntimeValue::Bool(false)); + } else if multibit { + assert_eq!(actual.to_bitstring().unwrap(), "10"); + } else { + assert_eq!(*actual, RuntimeValue::Bit(true)); + } + } + _ => {} + } + } + assert!(execution.classical.value(measured.value()).is_none()); + assert!(execution.classical.var(first).is_none()); + complete.clone().validate().unwrap(); + complete.decompose().unwrap().validate().unwrap(); + let fresh = complete.var(ClassicalType::Bit); + complete + .store(fresh, ClassicalExpr::bit_literal(false)) + .unwrap(); + complete.validate().unwrap(); + assert_eq!(format!("{source:?}"), before); + } + } +} + +#[test] +fn test_assign_parameters_remaps_store_without_measurement() { + let mut source = Circuit::new(1); + let unused = source.var(ClassicalType::Bit); + let target = source.var(ClassicalType::Bit); + source + .store(target, ClassicalExpr::bit_literal(true)) + .unwrap(); + for bindings in [None, Some(HashMap::new())] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_ne!(bound.id(), source.id()); + assert_eq!(bound.classical_vars(), source.classical_vars()); + let execution = StabilizerState::run_circuit(&bound).unwrap(); + let Instruction::ClassicalData(ClassicalDataOp::Store { + target: bound_target, + .. + }) = bound.operations()[0].instruction + else { + panic!("expected Store"); + }; + assert_eq!( + execution.classical.var(bound_target), + Some(&RuntimeValue::Bit(true)) + ); + assert!(bound.validate_classical_var(unused).is_err()); + assert!(execution.classical.var(target).is_none()); + } +} + +#[test] +fn test_assign_parameters_still_rejects_classical_control() { + let mut source = Circuit::new(1); + source + .if_(ClassicalExpr::bool_literal(true), |body| { + body.rx(Qubit::new(0), "theta") + }) + .unwrap(); + assert!(matches!( + source.assign_parameters(&None), + Err(CircuitError::InvalidOperation(_)) + )); +} + #[test] fn test_parameterized_unitary_appends_fixed_and_symbolic_params() { let mut circuit = Circuit::new(1); @@ -1359,8 +1556,6 @@ fn test_parameterized_unitary_validates_param_count() { #[test] fn test_decompose() { - use std::collections::HashMap; - let mut inner = Circuit::new(2); let q0 = Qubit::new(0); let q1 = Qubit::new(1); @@ -1449,9 +1644,6 @@ fn test_decompose() { #[test] fn test_decompose_global_phase_constant_and_empty_definitions() { - use crate::circuit::circuit_to_matrix; - use crate::circuit::test_utils::assert_matrix_approx_eq; - for (width, has_operations) in [(0, false), (1, false), (1, true), (2, true)] { let mut inner = Circuit::new(width); inner.set_global_phase(Parameter::from(0.37)); @@ -1509,10 +1701,6 @@ fn test_decompose_global_phase_constant_and_empty_definitions() { #[test] fn test_decompose_global_phase_only_symbols_and_explicit_signature() { - use crate::circuit::circuit_to_matrix; - use crate::circuit::test_utils::assert_matrix_approx_eq; - use std::collections::HashMap; - let mut inner = Circuit::new(1); inner.set_global_phase(Parameter::symbol("theta") / 2.0); let gate = CircuitGate::with_signature( @@ -1567,11 +1755,6 @@ fn test_decompose_global_phase_only_symbols_and_explicit_signature() { #[test] fn test_decompose_global_phase_nested_symbolic_and_inverse() { - use crate::circuit::circuit_to_matrix; - use crate::circuit::symbolic_matrix::{circuit_to_symbolic_matrix, evaluate_symbolic_matrix}; - use crate::circuit::test_utils::assert_matrix_approx_eq; - use std::collections::HashMap; - let a = Parameter::symbol("a"); let b = Parameter::symbol("b"); let mut inner = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(2)]).unwrap(); @@ -2043,6 +2226,193 @@ fn test_control_op_constructor_error_rolls_back_captured_state() { assert!(circuit.classical_values().is_empty()); } +fn control_rollback_source() -> Circuit { + let mut source = Circuit::from_qubits(vec![Qubit::new(7)]).unwrap(); + source.rx(Qubit::new(7), "theta").unwrap(); + source.set_global_phase(Parameter::symbol("phase")); + let value = source.measure(Qubit::new(7)).unwrap(); + let var = source.var(ClassicalType::Bit); + source.store(var, value.expr()).unwrap(); + source +} + +fn control_rollback_error() -> Result<(), CircuitError> { + Err(CircuitError::InvalidOperation("stop".into())) +} + +fn assert_failed_control_build_restores_state( + circuit: &mut Circuit, + build: impl FnOnce(&mut Circuit) -> Result<(), CircuitError>, +) { + let id = circuit.id(); + let qubits = circuit.qubits(); + let parameters: Vec<_> = circuit.parameters().iter().cloned().collect(); + let symbols: Vec<_> = circuit.symbols().iter().cloned().collect(); + let data = circuit.data.clone(); + let vars = circuit.classical_vars.clone(); + let values = circuit.classical_values.clone(); + let scopes = circuit.control_scope_stack.clone(); + let phase = circuit.global_phase(); + let phase_param = circuit.global_phase_param().clone(); + + assert!(build(circuit).is_err()); + + // Exercise the accessor that panicked when rollback left a dangling index. + assert_eq!(circuit.global_phase(), phase); + assert_eq!(circuit.global_phase_param(), &phase_param); + assert_eq!(circuit.id(), id); + assert_eq!(circuit.qubits(), qubits); + assert_eq!( + circuit.parameters().iter().cloned().collect::>(), + parameters + ); + assert_eq!( + circuit.symbols().iter().cloned().collect::>(), + symbols + ); + assert_eq!(circuit.data, data); + assert_eq!(circuit.classical_vars, vars); + assert_eq!(circuit.classical_values, values); + assert_eq!(circuit.control_scope_stack, scopes); +} + +#[test] +fn test_control_rollback_callback_failure_restores_composed_state_and_existing_handles() { + let source = control_rollback_source(); + for phase in [ + Parameter::from(0.0), + Parameter::from(0.375), + Parameter::symbol("old_phase"), + ] { + let mut circuit = + Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(2), Qubit::new(5)]).unwrap(); + circuit.set_global_phase(phase); + circuit.rx(Qubit::new(2), "old_theta").unwrap(); + let measured = circuit.measure(Qubit::new(9)).unwrap(); + let var = circuit.var(ClassicalType::Bit); + circuit.store(var, measured.expr()).unwrap(); + + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.compose(&source, None).unwrap(); + control_rollback_error() + }) + }); + + circuit.validate_classical_var(var).unwrap(); + circuit.store(var, measured.expr()).unwrap(); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_callback_failure_restores_direct_qubit_and_phase_changes() { + let mut circuit = Circuit::new(1); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.add_qubits(vec![Qubit::new(7)]).unwrap(); + control_rollback_error() + }) + }); + for phase in [Parameter::from(0.75), Parameter::symbol("discarded")] { + circuit.set_global_phase(0.25.into()); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.set_global_phase(phase); + control_rollback_error() + }) + }); + } +} + +#[test] +fn test_control_rollback_outer_failure_restores_state_after_successful_bodies() { + let source = control_rollback_source(); + for failure in ["else", "switch-case", "constructor", "nested-loop"] { + let mut circuit = Circuit::new(1); + assert_failed_control_build_restores_state(&mut circuit, |circuit| match failure { + "else" => circuit.if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }, + |_| control_rollback_error(), + ), + "switch-case" => circuit.switch(ClassicalExpr::uint_literal(2, 0).unwrap(), |cases| { + cases + .value(0, |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }) + .unwrap(); + cases.value(1, |_| control_rollback_error()) + }), + "constructor" => circuit.if_(ClassicalExpr::bit_literal(true), |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }), + "nested-loop" => circuit.while_(ClassicalExpr::bool_literal(true), |body| { + body.if_(ClassicalExpr::bool_literal(true), |inner| { + inner.compose(&source, None).unwrap(); + Ok(()) + }) + .unwrap(); + control_rollback_error() + }), + _ => unreachable!(), + }); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_external_transaction_rollback_restores_state_before_and_after_capture() { + let source = control_rollback_source(); + for capture in [false, true] { + let mut circuit = Circuit::new(1); + circuit.set_global_phase(Parameter::symbol("old_phase")); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + let transaction = circuit.begin_control_body_transaction(); + circuit.enter_external_control_body(&transaction, ExternalControlScope::Loop); + circuit.compose(&source, None).unwrap(); + if capture { + let body = circuit.finish_external_control_body(&transaction); + assert_eq!(body.operations().len(), source.operations().len()); + } + circuit.rollback_control_body_transaction(transaction); + control_rollback_error() + }); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_nested_rollback_preserves_enclosing_loop_state() { + let source = control_rollback_source(); + let mut circuit = Circuit::new(1); + circuit + .while_(ClassicalExpr::bool_literal(true), |body| { + body.add_qubits(vec![Qubit::new(3)])?; + body.rx(Qubit::new(3), "outer_theta")?; + body.set_global_phase(Parameter::symbol("outer_phase")); + assert_failed_control_build_restores_state(body, |body| { + body.if_(ClassicalExpr::bool_literal(true), |inner| { + inner.compose(&source, None).unwrap(); + control_rollback_error() + }) + }); + body.continue_loop() + }) + .unwrap(); + + assert_eq!(circuit.qubits(), vec![Qubit::new(0), Qubit::new(3)]); + assert_eq!(circuit.global_phase(), Parameter::symbol("outer_phase")); + assert!(circuit.control_scope_stack.is_empty()); + assert!(circuit.continue_loop().is_err()); + circuit.validate().unwrap(); +} + #[test] fn test_decompose_rejects_classical_control() { let mut circuit = Circuit::new(2); @@ -2081,6 +2451,228 @@ fn test_decompose_remaps_classical_data_identity() { } } +#[test] +fn compose_rejects_duplicate_targets_without_changing_either_circuit() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + // The mapping is a wire embedding, even for idle or separately used wires. + for kind in 0..3 { + for width in [1, 2] { + let mut destination = Circuit::new(width); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(Parameter::symbol("phase")); + destination.var(ClassicalType::Bit); + destination.measure(q0).unwrap(); + let mut source = Circuit::new(2); + match kind { + 0 => source.cx(q0, q1).unwrap(), + 1 => { + source.x(q0).unwrap(); + source.h(q1).unwrap(); + } + _ => {} + } + source.rx(q0, "new_parameter").unwrap(); + source.var(ClassicalType::Bit); + if kind != 2 { + source.measure(q1).unwrap(); + } + let before = format!("{destination:?}"); + let source_before = format!("{source:?}"); + + assert!(matches!( + destination.compose(&source, Some(&[q0, q0])), + Err(CircuitError::DuplicateQubits) + )); + assert_eq!(format!("{destination:?}"), before); + assert_eq!(format!("{source:?}"), source_before); + } + } +} + +#[test] +fn compose_errors_leave_all_destination_state_unchanged() { + let q0 = Qubit::new(0); + let q7 = Qubit::new(7); + // Inject malformed storage IR to exercise errors after mapping/parameter preparation. + for failure in [ + "parameter", + "qubit", + "classical", + "phase", + "destination_phase", + ] { + for explicit in [false, true] { + let mut destination = Circuit::new(1); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(Parameter::from(0.25)); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::from_qubits(vec![q7]).unwrap(); + source.rx(q7, "new_parameter").unwrap(); + source.measure(q7).unwrap(); + match failure { + "parameter" => { + Arc::make_mut(&mut source.data)[0].params[0] = CircuitParam::Index(u32::MAX); + } + "qubit" => { + Arc::make_mut(&mut source.data)[0].qubits[0] = Qubit::new(99); + } + "classical" => { + Arc::make_mut(&mut source.data)[1].instruction = + Instruction::ClassicalData(ClassicalDataOp::MeasureBit { + result: ClassicalValue::new(destination.id(), 0, ClassicalType::Bit), + }); + } + "phase" => source.global_phase = CircuitParam::Index(u32::MAX), + "destination_phase" => { + // Merging the source parameter must not make a bad old index valid. + destination.global_phase = + CircuitParam::Index(destination.parameters.len() as u32); + } + _ => unreachable!(), + } + let before = format!("{destination:?}"); + let source_before = format!("{source:?}"); + let mapping = [q0]; + assert!( + destination + .compose(&source, explicit.then_some(&mapping[..])) + .is_err(), + "{failure}" + ); + assert_eq!(format!("{destination:?}"), before, "{failure}"); + assert_eq!(format!("{source:?}"), source_before); + destination.validate_classical_var(retained_var).unwrap(); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + } + } +} + +#[test] +fn compose_sparse_permutation_preserves_unitary_parameters_and_phase() { + let [q9, q2, q5] = [9, 2, 5].map(Qubit::new); + let [q8, q1] = [8, 1].map(Qubit::new); + for symbolic_left in [false, true] { + for symbolic_right in [false, true] { + let left = if symbolic_left { + Parameter::symbol("left") + } else { + Parameter::from(0.25) + }; + let right = if symbolic_right { + Parameter::symbol("right") + } else { + Parameter::from(-0.75) + }; + let mut destination = Circuit::from_qubits(vec![q9, q2, q5]).unwrap(); + destination.h(q9).unwrap(); + destination.cx(q9, q5).unwrap(); + destination.set_global_phase(left.clone()); + let id = destination.id(); + let mut definition = Circuit::new(2); + definition.ry(Qubit::new(0), "theta").unwrap(); + definition.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + let gate = definition.to_gate("rotation_pair").unwrap(); + let mut source = Circuit::from_qubits(vec![q8, q1]).unwrap(); + source + .append( + gate.clone(), + [q8, q1], + [Parameter::symbol("theta").into()], + Some("pair"), + ) + .unwrap(); + source.rz(q1, "theta").unwrap(); + source.set_global_phase(right.clone()); + let source_before = format!("{source:?}"); + + destination.compose(&source, Some(&[q5, q2])).unwrap(); + + let mut expected = Circuit::from_qubits(vec![q9, q2, q5]).unwrap(); + expected.h(q9).unwrap(); + expected.cx(q9, q5).unwrap(); + expected + .append( + gate, + [q5, q2], + [Parameter::symbol("theta").into()], + Some("pair"), + ) + .unwrap(); + expected.rz(q2, "theta").unwrap(); + expected.set_global_phase(left + right); + let bindings = Some(HashMap::from([ + ("theta", 0.731), + ("left", -0.4), + ("right", 1.2), + ])); + assert_matrix_approx_eq( + &destination + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &expected + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-12, + ); + assert_eq!(destination.id(), id); + assert_eq!(destination.qubits(), vec![q9, q2, q5]); + assert_eq!(destination.operations()[2].label.as_deref(), Some("pair")); + assert_eq!(format!("{source:?}"), source_before); + } + } +} + +#[test] +fn compose_preserves_existing_handles_inside_control_builder() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + let mut destination = Circuit::new(2); + let id = destination.id(); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::new(2); + let measured = source.measure(q0).unwrap(); + source + .if_( + ClassicalExpr::bit_to_bool(measured.expr()).unwrap(), + |body| body.cx(q0, q1), + ) + .unwrap(); + + destination + .while_(ClassicalExpr::bool_literal(true), |body| { + body.compose(&source, Some(&[q1, q0]))?; + body.store(retained_var, retained_value.expr())?; + body.break_loop() + }) + .unwrap(); + assert_eq!(destination.id(), id); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + destination.validate().unwrap(); + let Instruction::ClassicalControl(ClassicalControlOp::While(op)) = + &destination.operations()[1].instruction + else { + panic!("expected while") + }; + assert_eq!(op.body().operations()[0].qubits.as_slice(), &[q1]); + let Instruction::ClassicalControl(ClassicalControlOp::If(op)) = + &op.body().operations()[1].instruction + else { + panic!("expected if") + }; + assert_eq!(op.then_body().operations()[0].qubits.as_slice(), &[q1, q0]); +} + #[test] fn test_compose_basic_with_mapping() { // Create qc1 with qubits 1, 3, 5 @@ -2230,6 +2822,97 @@ fn test_compose_with_parameters() { assert!(qc1.symbols().contains("phi")); } +#[test] +fn compose_interns_phase_sum_in_existing_or_new_parameters() { + let q0 = Qubit::new(0); + for location in ["destination", "source", "phase_only"] { + let phi = Parameter::symbol("phi"); + let psi = Parameter::symbol("psi"); + let sum = phi.clone() + psi.clone(); + let mut destination = Circuit::new(1); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(phi); + if location == "destination" { + destination.rz(q0, sum.clone()).unwrap(); + } + let id = destination.id(); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::new(1); + source.rx(q0, "existing").unwrap(); + source.ry(q0, "new").unwrap(); + source.rz(q0, "new").unwrap(); + if location == "source" { + source.rx(q0, sum.clone()).unwrap(); + } + source.set_global_phase(psi); + let source_before = format!("{source:?}"); + let operation_base = destination.data.len(); + let mut expected_parameters = destination.parameters.clone(); + expected_parameters.extend(source.parameters.iter().cloned()); + expected_parameters.insert(sum.clone()); + + destination.compose(&source, None).unwrap(); + + assert_eq!( + destination.parameters.iter().collect::>(), + expected_parameters.iter().collect::>() + ); + assert_eq!(destination.global_phase(), sum); + assert_eq!( + destination.global_phase_param(), + &CircuitParam::Index(expected_parameters.get_index_of(&sum).unwrap() as u32) + ); + assert_eq!(destination.id(), id); + assert_eq!(format!("{source:?}"), source_before); + for (original, remapped) in source.data.iter().zip(&destination.data[operation_base..]) { + for (source_param, mapped_param) in original.params.iter().zip(&remapped.params) { + assert_eq!( + source.resolve_parameter(source_param).unwrap(), + destination.resolve_parameter(mapped_param).unwrap() + ); + } + } + assert_eq!( + destination.symbols.iter().cloned().collect::>(), + HashSet::from(["existing", "new", "phi", "psi"].map(String::from)) + ); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + destination.validate().unwrap(); + } +} + +#[test] +fn compose_repeated_parameters_preserve_indices_and_insertion_order() { + let q0 = Qubit::new(0); + let mut destination = Circuit::new(1); + let mut expected = Circuit::new(1); + for i in 0..128 { + let theta = Parameter::symbol(&format!("theta_{i}")); + let mut source = Circuit::new(1); + source.rx(q0, theta.clone()).unwrap(); + source.ry(q0, "shared").unwrap(); + destination.compose(&source, None).unwrap(); + expected.rx(q0, theta).unwrap(); + expected.ry(q0, "shared").unwrap(); + } + + assert_eq!(destination, expected); + assert_eq!( + destination.parameters.iter().collect::>(), + expected.parameters.iter().collect::>() + ); + assert_eq!( + destination.symbols.iter().collect::>(), + expected.symbols.iter().collect::>() + ); + for (actual, expected) in destination.operations().iter().zip(expected.operations()) { + assert_eq!(actual.params, expected.params); + } +} + #[test] fn test_compose_preserves_operation_order() { // qc1: Bell state preparation diff --git a/crates/cqlib-core/src/compile/device_planning/planner_test.rs b/crates/cqlib-core/src/compile/device_planning/planner_test.rs index 284a459b..3e8a8e3f 100644 --- a/crates/cqlib-core/src/compile/device_planning/planner_test.rs +++ b/crates/cqlib-core/src/compile/device_planning/planner_test.rs @@ -568,3 +568,82 @@ fn direction_template_preserves_exact_ordered_qargs() { &[PhysicalQubit::new(1)] ); } + +#[test] +fn single_qubit_rule_expansion_stays_bounded_with_heterogeneous_calibrations() { + use StandardGate::*; + let library = RuleLibrary::builtin_rules().unwrap(); + for basis in [ + vec![U, CZ], + vec![U, CX], + vec![RY, RZ, CX], + vec![RY, RZ, CZ], + vec![RXY, CX], + vec![RZ, X2P, CZ], + vec![RZ, X2M, CX], + vec![RZ, Y2P, CX], + vec![RZ, Y2M, CZ], + vec![RZ, XY2P, CZ], + vec![RZ, XY2M, CX], + ] { + for profile in 0..4 { + let mut device = Device::bidirectional_line("single-qubit-expansion-budget", 2) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (q, (error, duration)) in [(0, (0.001, 84.0)), (1, (0.006, 45.0))] { + let mut properties = QubitProp::new(0.0); + for &gate in basis.iter().filter(|gate| gate.num_qubits() == 1) { + let scale = 1.0 + profile as f64; + let mut native = + InstructionProp::new(Instruction::Standard(gate), error * scale); + if profile != 3 { + native = native.with_length(duration / scale); + } + properties = properties.with_native_instruction(native).unwrap(); + } + device + .add_qubit_properties(PhysicalQubit::new(q), properties) + .unwrap(); + } + for (a, b, error, duration) in [(0, 1, 0.019, 59.0), (1, 0, 0.016, 293.0)] { + let mut native = + InstructionProp::new(Instruction::Standard(*basis.last().unwrap()), error); + if profile != 2 { + native = native.with_length(duration * (1.0 + profile as f64)); + } + device + .add_edge_properties( + PhysicalQubit::new(a), + PhysicalQubit::new(b), + EdgeProp::new().with_native_instruction(native).unwrap(), + ) + .unwrap(); + } + let roots = [state(SWAP, &[0, 1]), state(SWAP, &[1, 0])]; + let planner = build_planner_with_budget( + &device, + library, + roots.clone(), + PlannerBudget { + max_frontier_size_per_state: 32, + max_total_plan_nodes: 5_000, + max_total_generated_candidates: 20_000, + }, + ) + .unwrap_or_else(|error| panic!("{basis:?}, profile={profile}: {error}")); + for root in roots { + assert!( + planner.selected_plan_for(&root).is_some(), + "{basis:?}: {root:?}" + ); + } + eprintln!( + "basis={basis:?}, profile={profile}, nodes={}, candidates={}, frontier={}", + planner.nodes.len(), + planner.generated_candidates, + planner.frontiers.iter().map(Vec::len).max().unwrap_or(0) + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs b/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs index 2f5e7333..ea4c748c 100644 --- a/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs +++ b/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs @@ -425,3 +425,74 @@ fn qcis_fsim_to_cz_verify_timing() { fn verify_all_builtin_rules_layered_equivalence_ignored() { verify_all_builtin_rules_layered_equivalence(); } + +/// Check registered DSL rules, including independent random parameters and all +/// scalar phases. A copied formula test would not catch an incorrect DSL edit. +#[test] +fn native_single_qubit_paths_preserve_full_unitary_for_parameters() { + use crate::circuit::circuit_to_matrix::circuit_to_matrix; + use rand::{Rng, SeedableRng, rngs::SmallRng}; + + let library = RuleLibrary::builtin_rules().unwrap(); + let mut rng = SmallRng::seed_from_u64(20261021); + for name in [ + "decompose_h_to_u", + "decompose_rx_to_u", + "decompose_ry_to_u", + "decompose_rxy_to_u", + "decompose_rx_to_rxy", + "decompose_ry_to_rxy", + "decompose_xy2p_to_xy2m", + "decompose_u_to_x2p_rz_same_sign", + "decompose_u_to_x2m_rz_same_sign", + "decompose_u_to_y2p_rz_same_sign", + "decompose_u_to_y2m_rz_same_sign", + ] { + let rule = library + .get_by_name(name) + .expect("native rule must be registered"); + let lhs = rule_items_to_circuit(&rule.operations, rule.num_qubits()).unwrap(); + let rhs = rule_items_to_circuit(&rule.target, rule.num_qubits()).unwrap(); + let mut symbols: Vec<_> = rule.collect_free_symbols().into_iter().collect(); + symbols.sort(); + for sample in 0..112 { + let bindings = Some( + symbols + .iter() + .enumerate() + .map(|(index, name)| { + let edge = [ + 0.0, + std::f64::consts::FRAC_PI_2, + -std::f64::consts::FRAC_PI_2, + std::f64::consts::PI, + -std::f64::consts::PI, + 2.0 * std::f64::consts::PI, + -2.0 * std::f64::consts::PI, + 4.0 * std::f64::consts::PI, + -4.0 * std::f64::consts::PI, + 1e-12, + -1e-12, + 0.173, + ]; + ( + name.as_str(), + if sample < edge.len() { + edge[(sample + index * 3) % edge.len()] + } else { + rng.random_range(-20.0..20.0) + }, + ) + }) + .collect(), + ); + let a = circuit_to_matrix(&lhs.assign_parameters(&bindings).unwrap(), None).unwrap(); + let b = circuit_to_matrix(&rhs.assign_parameters(&bindings).unwrap(), None).unwrap(); + let error = max_diff_strict(&a, &b); + assert!( + error < 1e-10, + "{name}: strict error {error}, bindings={bindings:?}" + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule index 0e48f5bf..32839b20 100644 --- a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule +++ b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule @@ -168,3 +168,8 @@ rule decompose_y2m_to_x2m { match { Y2M 0 } rewrite { RZ(-π/2) 0, X2M 0, RZ(π/2) 0 } } + +rule decompose_h_to_u { + match { H 0 } + rewrite { U(π/2, 0, π) 0 } +} diff --git a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule index a0a29325..8437c47b 100644 --- a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule +++ b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule @@ -168,3 +168,53 @@ rule decompose_u_to_xy_basis { match { U(theta, phi, lambda) 0 } rewrite { RZ(lambda) 0, XY2P(0) 0, RZ(theta) 0, XY2M(0) 0, RZ(phi) 0, GPhase((phi + lambda) / 2) } } + +rule decompose_rx_to_u { + match { RX(theta) 0 } + rewrite { U(theta, -π/2, π/2) 0 } +} + +rule decompose_ry_to_u { + match { RY(theta) 0 } + rewrite { U(theta, 0, 0) 0 } +} + +rule decompose_rxy_to_u { + match { RXY(theta, phi) 0 } + rewrite { U(theta, phi - π/2, π/2 - phi) 0 } +} + +rule decompose_rx_to_rxy { + match { RX(theta) 0 } + rewrite { RXY(theta, 0) 0 } +} + +rule decompose_ry_to_rxy { + match { RY(theta) 0 } + rewrite { RXY(theta, π/2) 0 } +} + +rule decompose_xy2p_to_xy2m { + match { XY2P(phi) 0 } + rewrite { XY2M(phi + π) 0 } +} + +rule decompose_u_to_x2p_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda) 0, X2P 0, RZ(theta + π) 0, X2P 0, RZ(phi + π) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_x2m_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda) 0, X2M 0, RZ(π - theta) 0, X2M 0, RZ(phi + π) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_y2p_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda + π/2) 0, Y2P 0, RZ(theta + π) 0, Y2P 0, RZ(phi + π/2) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_y2m_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda + π/2) 0, Y2M 0, RZ(π - theta) 0, Y2M 0, RZ(phi + π/2) 0, GPhase((phi + lambda) / 2 + π) } +} diff --git a/crates/cqlib-core/src/compile/transform/device_lowering_test.rs b/crates/cqlib-core/src/compile/transform/device_lowering_test.rs index 668db29a..236815aa 100644 --- a/crates/cqlib-core/src/compile/transform/device_lowering_test.rs +++ b/crates/cqlib-core/src/compile/transform/device_lowering_test.rs @@ -975,3 +975,103 @@ fn lowering_wide_sparse_circuit_only_plans_used_qubits() { assert!(result.circuit.operations().len() > circuit.operations().len()); device.validate_circuit(&result.circuit).unwrap(); } + +#[test] +fn universal_single_qubit_native_bases_preserve_symbolic_gates_and_phase() { + use crate::circuit::test_utils::assert_matrix_approx_eq; + use StandardGate::*; + + for basis in [ + vec![U], + vec![RXY], + vec![RZ, X2P], + vec![RZ, X2M], + vec![RZ, Y2P], + vec![RZ, Y2M], + vec![RZ, XY2P], + vec![RZ, XY2M], + ] { + let device = Device::line("single-qubit-basis", 1) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + let lowerer = DeviceLowerer::new(&device); + // Identity is removed by canonicalization before device lowering. + for &gate in StandardGate::all() + .iter() + .filter(|g| g.num_qubits() == 1 && **g != I) + { + let mut source = Circuit::new(1); + source + .append( + Instruction::Standard(gate), + [Qubit::new(0)], + ["theta", "phi", "lambda"] + .into_iter() + .take(gate.num_params()) + .map(|name| ParameterValue::Param(Parameter::symbol(name))), + None, + ) + .unwrap(); + source.set_global_phase(Parameter::symbol("phase")); + let lowered = lowerer + .transform_resolved(&source, None) + .unwrap_or_else(|e| panic!("{gate:?} -> {basis:?}: {e}")) + .circuit; + device.validate_circuit(&lowered).unwrap(); + if basis == [U] { + assert_eq!(lowered.operations().len(), 1, "{gate:?} must use one U"); + } + assert!(source.symbols().is_subset(lowered.symbols())); + for angle in [0.0, PI / 2.0, -PI, 2.0 * PI, -4.0 * PI, 0.173, -1.239] { + let bindings = Some(HashMap::from([ + ("theta", angle), + ("phi", 0.39 - angle), + ("lambda", -0.71 + 2.0 * angle), + ("phase", -0.37), + ])); + assert_matrix_approx_eq( + &source + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &lowered + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-9, + ); + } + } + } +} + +#[test] +fn native_u_lowering_respects_local_capability_override() { + let mut device = Device::line("local-capability", 2) + .unwrap() + .with_native_gates(vec![Instruction::Standard(StandardGate::U)]) + .unwrap(); + device + .add_qubit_properties( + PhysicalQubit::new(1), + QubitProp::new(0.0) + .with_native_instruction(InstructionProp::new( + Instruction::Standard(StandardGate::RZ), + 0.0, + )) + .unwrap(), + ) + .unwrap(); + let lowerer = DeviceLowerer::new(&device); + let mut allowed = Circuit::new(2); + allowed.h(Qubit::new(0)).unwrap(); + device + .validate_circuit(&lowerer.transform_resolved(&allowed, None).unwrap().circuit) + .unwrap(); + let mut blocked = Circuit::new(2); + blocked.h(Qubit::new(1)).unwrap(); + assert!(lowerer.transform_resolved(&blocked, None).is_err()); +} diff --git a/crates/cqlib-core/src/compile/transform/target_basis_test.rs b/crates/cqlib-core/src/compile/transform/target_basis_test.rs index bb940e9b..652bcf20 100644 --- a/crates/cqlib-core/src/compile/transform/target_basis_test.rs +++ b/crates/cqlib-core/src/compile/transform/target_basis_test.rs @@ -401,7 +401,7 @@ fn u_fails_for_basis_without_complete_euler_family() { assert_target_lowering_fails_with( &circuit, - &[StandardGate::RZ, StandardGate::X2M], + &[StandardGate::RZ, StandardGate::Z], &["cannot lower", "U"], ); } @@ -986,3 +986,54 @@ fn target_lowering_uses_compact_qcis_decompositions() { } } } + +#[test] +fn symbolic_u_lowers_to_each_single_polarity_half_rotation_basis() { + use StandardGate::*; + for half in [X2P, X2M, Y2P, Y2M] { + let mut source = Circuit::new(1); + source + .u( + Qubit::new(0), + Parameter::symbol("theta"), + Parameter::symbol("phi"), + Parameter::symbol("lambda"), + ) + .unwrap(); + source.set_global_phase((-0.37).into()); + let result = run_target_lowering(&source, &[RZ, half]); + assert_only_target_standard_gates(&result, &[RZ, half]); + assert!( + result.operations().len() <= 5, + "{half:?}: expected a compact Euler path" + ); + for (theta, phi, lambda) in [ + (0.0, 0.0, 0.0), + (0.173, -1.239, 0.71), + ( + std::f64::consts::PI, + -2.0 * std::f64::consts::PI, + 4.0 * std::f64::consts::PI, + ), + ] { + let bindings = Some(std::collections::HashMap::from([ + ("theta", theta), + ("phi", phi), + ("lambda", lambda), + ])); + assert_matrix_approx_eq( + &source + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &result + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-9, + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/workflow_test.rs b/crates/cqlib-core/src/compile/workflow_test.rs index 3b3e5d4f..26be6681 100644 --- a/crates/cqlib-core/src/compile/workflow_test.rs +++ b/crates/cqlib-core/src/compile/workflow_test.rs @@ -3853,3 +3853,195 @@ fn shared_device_workflow_supports_concurrent_mixed_runs() { handle.join().unwrap(); } } + +#[test] +fn heterogeneous_native_entanglers_remain_executable_without_fsim_detours() { + use crate::device::QubitProp; + use StandardGate::*; + + for (basis, singles, edges) in [ + ( + vec![U, CZ], + [(0.001, 84.0), (0.006, 45.0)], + [(0.019, 59.0), (0.016, 293.0)], + ), + ( + vec![RY, RZ, CX], + [(0.001, 10.0), (0.009, 80.0)], + [(0.01, 50.0), (0.03, 200.0)], + ), + ] { + let mut device = Device::bidirectional_line("heterogeneous-native-entangler", 2) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (q, (error, duration)) in singles.into_iter().enumerate() { + let mut prop = QubitProp::new(0.0); + for &gate in basis.iter().filter(|gate| gate.num_qubits() == 1) { + prop = prop + .with_native_instruction( + InstructionProp::new(Instruction::Standard(gate), error) + .with_length(duration), + ) + .unwrap(); + } + device + .add_qubit_properties(PhysicalQubit::new(q as u32), prop) + .unwrap(); + } + let entangler = *basis.last().unwrap(); + for ((a, b), (error, duration)) in [(0, 1), (1, 0)].into_iter().zip(edges) { + device + .add_edge_properties( + PhysicalQubit::new(a), + PhysicalQubit::new(b), + EdgeProp::new() + .with_native_instruction( + InstructionProp::new(Instruction::Standard(entangler), error) + .with_length(duration), + ) + .unwrap(), + ) + .unwrap(); + } + for (a, b) in [(0, 1), (1, 0)] { + let mut source = Circuit::new(2); + source + .append( + Instruction::Standard(entangler), + [Qubit::new(a), Qubit::new(b)], + [], + None, + ) + .unwrap(); + source.set_global_phase((-0.37).into()); + device.validate_circuit(&source).unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + let result = compile( + &source, + CompileConfig { + target: CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: Some(Layout::from_pairs(&[(0, 0), (1, 1)], 2).unwrap()), + seed: Some(7), + }), + ..compile_config(mode) + }, + ) + .unwrap_or_else(|e| panic!("{basis:?}/{a}->{b}/{mode:?}: {e}")); + device.validate_circuit(&result.circuit).unwrap(); + assert_eq!(result.circuit.operations().len(), 1); + crate::circuit::test_utils::assert_matrix_approx_eq( + &source.to_matrix(Some(&[0, 1])).unwrap(), + &result.circuit.to_matrix(Some(&[0, 1])).unwrap(), + 1e-9, + ); + } + } + } +} + +#[test] +fn universal_native_bases_route_on_directed_chain_with_exact_layout_isometry() { + use StandardGate::*; + + for native in [ + vec![U, CX], + vec![U, CZ], + vec![RY, RZ, CX], + vec![RY, RZ, CZ], + vec![U, H, CX], + vec![RXY, CX], + vec![RXY, CZ], + vec![RZ, X2P, CZ], + vec![RZ, X2M, CX], + vec![RZ, Y2P, CX], + vec![RZ, Y2M, CZ], + vec![RZ, XY2P, CZ], + vec![RZ, XY2M, CX], + ] { + let device = Device::from_edges("native-universality", 4, &[(0, 1), (1, 2), (2, 3)]) + .unwrap() + .with_native_gates(native.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (label, pairs) in [ + ("H", vec![]), + ("forward CX", vec![(0, 1)]), + ("both directions", vec![(0, 1), (1, 0)]), + ("triangle", vec![(0, 1), (1, 2), (2, 0)]), + ("mixed", vec![(0, 2), (2, 1), (1, 0)]), + ] { + let n = if matches!(label, "triangle" | "mixed") { + 3 + } else { + 2 + }; + let mut source = Circuit::new(n); + if pairs.is_empty() { + source.h(Qubit::new(0)).unwrap(); + } + for (a, b) in pairs { + source.cx(Qubit::new(a), Qubit::new(b)).unwrap(); + } + if label == "mixed" { + source.u(Qubit::new(0), 0.173, -1.239, 0.71).unwrap(); + source.crz(Qubit::new(0), Qubit::new(2), -0.43).unwrap(); + source + .fsim(Qubit::new(2), Qubit::new(1), 0.31, -0.27) + .unwrap(); + } + source.set_global_phase((-0.37).into()); + let expected = source.to_matrix(None).unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + let result = compile( + &source, + CompileConfig { + target: CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: None, + seed: Some(7), + }), + ..compile_config(mode) + }, + ) + .unwrap_or_else(|e| panic!("{native:?}/{label}/{mode:?}: {e}")); + device.validate_circuit(&result.circuit).unwrap(); + let metadata = result.device_metadata.unwrap(); + let order: Vec<_> = result.circuit.qubits().iter().map(|q| q.index()).collect(); + let actual = result.circuit.to_matrix(Some(&order)).unwrap(); + let encode = |state: usize, layout: &Layout| -> usize { + (0..n) + .map(|q| { + let physical = layout + .get_physical(LogicalQubit::new(q as u32)) + .unwrap() + .id() as usize; + ((state >> q) & 1) << order.iter().position(|&p| p == physical).unwrap() + }) + .sum() + }; + // Every computational input and every physical output, + // including outputs with a nonzero unused physical qubit. + for column in 0..1 << n { + let logical_rows: HashMap<_, _> = (0..1 << n) + .map(|row| (encode(row, &metadata.final_layout), row)) + .collect(); + for row in 0..actual.nrows() { + let value = logical_rows + .get(&row) + .map_or(Complex64::new(0.0, 0.0), |&logical| { + expected[[logical, column]] + }); + let error = (value + - actual[[row, encode(column, &metadata.initial_layout)]]) + .norm(); + assert!( + error < 1e-8, + "{native:?}/{label}/{mode:?}: matrix error {error}" + ); + } + } + } + } + } +} diff --git a/crates/cqlib-core/src/ir/qasm2/dump.rs b/crates/cqlib-core/src/ir/qasm2/dump.rs index a80aa55d..a1cffb15 100644 --- a/crates/cqlib-core/src/ir/qasm2/dump.rs +++ b/crates/cqlib-core/src/ir/qasm2/dump.rs @@ -987,6 +987,10 @@ fn resolve_param( Ok(param) } +fn format_parameter(param: &Parameter) -> String { + param.to_string().replace('π', "pi") +} + fn format_params( op: &Operation, circuit: &Circuit, @@ -997,8 +1001,7 @@ fn format_params( } let params = (0..op.params.len()) .map(|index| { - resolve_param(op, index, circuit, param_map) - .map(|param| param.to_string().replace("π", "pi")) + resolve_param(op, index, circuit, param_map).map(|param| format_parameter(¶m)) }) .collect::, _>>()?; Ok(format!("({})", params.join(","))) @@ -1062,22 +1065,22 @@ fn dump_standard_gate( match gate { StandardGate::X2P => { writeln!(output, "// x2p {}", mapped_qs[0])?; - writeln!(output, "rx(pi/2) {}", mapped_qs[0])?; + writeln!(output, "rx(pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::X2M => { writeln!(output, "// x2m {}", mapped_qs[0])?; - writeln!(output, "rx(-pi/2) {}", mapped_qs[0])?; + writeln!(output, "rx(-pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::Y2P => { writeln!(output, "// y2p {}", mapped_qs[0])?; - writeln!(output, "ry(pi/2) {}", mapped_qs[0])?; + writeln!(output, "ry(pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::Y2M => { writeln!(output, "// y2m {}", mapped_qs[0])?; - writeln!(output, "ry(-pi/2) {}", mapped_qs[0])?; + writeln!(output, "ry(-pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::XY2P => { @@ -1086,10 +1089,10 @@ fn dump_standard_gate( let p3 = theta.clone() - Parameter::pi() / 2.0; let q_str = &mapped_qs[0]; - writeln!(output, "// xy2p({}) {}", theta, q_str)?; - writeln!(output, "rz({}) {}", p1, q_str)?; - writeln!(output, "ry(pi/2) {}", q_str)?; - writeln!(output, "rz({}) {}", p3, q_str)?; + writeln!(output, "// xy2p({}) {}", format_parameter(&theta), q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&p1), q_str)?; + writeln!(output, "ry(pi/2) {};", q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&p3), q_str)?; return Ok(()); } StandardGate::XY2M => { @@ -1098,10 +1101,10 @@ fn dump_standard_gate( let m3 = theta.clone() + Parameter::pi() / 2.0; let q_str = &mapped_qs[0]; - writeln!(output, "// xy2m({}) {}", theta, q_str)?; - writeln!(output, "rz({}) {}", m1, q_str)?; - writeln!(output, "ry(pi/2) {}", q_str)?; - writeln!(output, "rz({}) {}", m3, q_str)?; + writeln!(output, "// xy2m({}) {}", format_parameter(&theta), q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&m1), q_str)?; + writeln!(output, "ry(pi/2) {};", q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&m3), q_str)?; return Ok(()); } StandardGate::XY => { @@ -1110,18 +1113,13 @@ fn dump_standard_gate( let lambda: Parameter = Parameter::pi() / 2.0 - theta.clone(); let q_str = &mapped_qs[0]; - writeln!( - output, - "// xy({}) {}", - theta.to_string().replace("π", "pi"), - q_str - )?; + writeln!(output, "// xy({}) {}", format_parameter(&theta), q_str)?; writeln!( output, "u3({},{},{}) {};", - Parameter::pi().to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&Parameter::pi()), + format_parameter(&phase), + format_parameter(&lambda), q_str )?; return Ok(()); @@ -1136,16 +1134,16 @@ fn dump_standard_gate( writeln!( output, "// rxy({},{}) {}", - theta.to_string().replace("π", "pi"), - phi.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phi), q_str )?; writeln!( output, "u3({},{},{}) {};", - theta.to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phase), + format_parameter(&lambda), q_str )?; return Ok(()); @@ -1475,9 +1473,9 @@ fn operation_to_qasm( let lambda: Parameter = Parameter::pi() / 2.0 - theta; return Ok(format!( "u3({},{},{}) {}", - Parameter::pi().to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&Parameter::pi()), + format_parameter(&phase), + format_parameter(&lambda), mapped_qs[0] )); } @@ -1488,9 +1486,9 @@ fn operation_to_qasm( let lambda: Parameter = Parameter::pi() / 2.0 - phi; return Ok(format!( "u3({},{},{}) {}", - theta.to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phase), + format_parameter(&lambda), mapped_qs[0] )); } diff --git a/crates/cqlib-core/src/ir/qasm2/dump_test.rs b/crates/cqlib-core/src/ir/qasm2/dump_test.rs index b2958e3e..088f9e25 100644 --- a/crates/cqlib-core/src/ir/qasm2/dump_test.rs +++ b/crates/cqlib-core/src/ir/qasm2/dump_test.rs @@ -14,7 +14,8 @@ use crate::circuit::gate::circuit_gate::FrozenCircuit; use crate::circuit::gate::{StandardGate, UnitaryGate}; use crate::circuit::parameter::Parameter; use crate::circuit::symbolic_matrix::standard_gate_symbolic_matrix; -use crate::circuit::{Circuit, ClassicalExpr, ClassicalType, Instruction, Qubit}; +use crate::circuit::test_utils::assert_matrix_approx_eq; +use crate::circuit::{Circuit, ClassicalExpr, ClassicalType, Instruction, ParameterValue, Qubit}; use crate::ir::qasm2::dump::{QasmDumpError, dump, dumps, to_path, to_string}; use crate::ir::qasm2::load::loads; use std::fs; @@ -69,6 +70,48 @@ fn verify_qasm_roundtrip(qasm: &str, expected_qubits: usize) { ); } +const HALF_ROTATION_GATES: [StandardGate; 6] = [ + StandardGate::X2P, + StandardGate::X2M, + StandardGate::Y2P, + StandardGate::Y2M, + StandardGate::XY2P, + StandardGate::XY2M, +]; + +fn half_rotation_circuit(gate: StandardGate, axis: Parameter) -> Circuit { + let mut circuit = Circuit::new(1); + let params: Vec = if gate.num_params() == 0 { + vec![] + } else { + vec![axis.into()] + }; + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], params, None) + .unwrap(); + circuit +} + +fn assert_qasm_unitary_matches(qasm: &str, circuit: &Circuit, allow_global_phase: bool) { + assert!(qasm.is_ascii(), "Expected ASCII QASM:\n{qasm}"); + let parsed = loads(qasm).unwrap_or_else(|error| panic!("{error}\n{qasm}")); + assert_eq!(parsed.num_qubits(), circuit.num_qubits()); + let mut expected = circuit.to_matrix(None).unwrap(); + let actual = parsed.to_matrix(None).unwrap(); + if allow_global_phase { + // QASM2 cannot preserve arbitrary global phase. Compare a single phase + // for the entire unitary, never a separate phase for each input column. + let (index, pivot) = expected + .indexed_iter() + .find(|(_, z)| z.norm() > 0.1) + .unwrap(); + let ratio = actual[index] / *pivot; + assert!((ratio.norm() - 1.0).abs() < 1e-10, "{qasm}"); + expected.mapv_inplace(|z| z * ratio); + } + assert_matrix_approx_eq(&actual, &expected, 1e-10); +} + /// Simple contains check (for backwards compatibility) fn assert_qasm_contains(qasm: &str, expected_lines: &[&str]) { for &line in expected_lines { @@ -1530,15 +1573,241 @@ fn test_dump_x2p_x2m_y2p_y2m() { &qasm, &[ "// x2p q[0]", - "rx(pi/2) q[0]", + "rx(pi/2) q[0];", "// x2m q[0]", - "rx(-pi/2) q[0]", + "rx(-pi/2) q[0];", "// y2p q[0]", - "ry(pi/2) q[0]", + "ry(pi/2) q[0];", "// y2m q[0]", - "ry(-pi/2) q[0]", + "ry(-pi/2) q[0];", ], ); + assert_qasm_unitary_matches(&qasm, &circuit, false); +} + +#[test] +fn half_rotations_roundtrip_individually_with_numeric_and_pi_axes() { + let axes = [ + Parameter::from(0.0), + Parameter::from(0.731), + Parameter::from(-1.219), + Parameter::pi() / 2.0, + -Parameter::pi() / 3.0, + Parameter::pi() * 4.0 + 0.25, + ]; + for gate in HALF_ROTATION_GATES { + for axis in &axes[..if gate.num_params() == 0 { + 1 + } else { + axes.len() + }] { + let circuit = half_rotation_circuit(gate, axis.clone()); + let qasm = dumps(&circuit).unwrap(); + assert_qasm_unitary_matches(&qasm, &circuit, false); + let statements: Vec<_> = qasm + .lines() + .filter(|line| { + line.starts_with("rx(") || line.starts_with("ry(") || line.starts_with("rz(") + }) + .collect(); + assert_eq!(statements.len(), if gate.num_params() == 0 { 1 } else { 3 }); + assert!( + statements.iter().all(|line| line.ends_with(';')), + "{gate:?}: {qasm}" + ); + } + } +} + +#[test] +fn half_rotations_roundtrip_in_entangled_circuit() { + let mut circuit = Circuit::new(3); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(2)).unwrap(); + for (index, gate) in HALF_ROTATION_GATES.into_iter().enumerate() { + let qubit = Qubit::new((index % 3) as u32); + circuit + .compose( + &half_rotation_circuit(gate, Parameter::pi() / 7.0), + Some(&[qubit]), + ) + .unwrap(); + circuit + .cx(qubit, Qubit::new(((index + 1) % 3) as u32)) + .unwrap(); + } + circuit.h(Qubit::new(1)).unwrap(); + circuit.rz(Qubit::new(2), -0.43).unwrap(); + assert_qasm_unitary_matches(&dumps(&circuit).unwrap(), &circuit, false); +} + +#[test] +fn half_rotations_roundtrip_in_parameterized_custom_and_unitary_gates() { + for gate in HALF_ROTATION_GATES { + let inner = half_rotation_circuit( + gate, + Parameter::symbol("theta") / 2.0 + Parameter::pi() / 3.0, + ); + let custom = inner.clone().to_gate("half_rotation").unwrap(); + let unitary = UnitaryGate::new("half_unitary", 1, gate.num_params() as u16) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + for value in [-1.219, 0.731, std::f64::consts::FRAC_PI_2] { + let params: Vec = if gate.num_params() == 0 { + vec![] + } else { + vec![value.into()] + }; + for instruction in [ + custom.clone(), + Instruction::UnitaryGate(Box::new(unitary.clone())), + ] { + let mut circuit = Circuit::new(2); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit + .append(instruction, [Qubit::new(1)], params.clone(), None) + .unwrap(); + circuit.h(Qubit::new(1)).unwrap(); + assert_qasm_unitary_matches(&dumps(&circuit).unwrap(), &circuit, false); + } + } + } +} + +#[test] +fn half_rotations_roundtrip_through_file_and_string_aliases() { + use crate::ir::qasm2::load::{from_path, load}; + + for gate in HALF_ROTATION_GATES { + let circuit = half_rotation_circuit(gate, Parameter::pi() / 3.0); + let qasm = dumps(&circuit).unwrap(); + assert_eq!(to_string(&circuit).unwrap(), qasm); + let path = unique_temp_path(&format!("half_rotation_{gate:?}")); + dump(&circuit, &path).unwrap(); + let saved = fs::read_to_string(&path).unwrap(); + assert_eq!(saved, qasm); + assert_qasm_unitary_matches(&saved, &circuit, false); + to_path(&circuit, &path).unwrap(); + for parsed in [load(&path).unwrap(), from_path(&path).unwrap()] { + assert_matrix_approx_eq( + &parsed.to_matrix(None).unwrap(), + &circuit.to_matrix(None).unwrap(), + 1e-10, + ); + } + fs::remove_file(path).unwrap(); + } +} + +#[test] +fn xy_half_rotations_resolve_parameters_and_report_invalid_values() { + use crate::circuit::CircuitParam; + use std::collections::HashMap; + + let qubit = Qubit::new(0); + let qubit_map = HashMap::from([(qubit, "q[0]".to_string())]); + let replacements = HashMap::from([("theta".to_string(), Parameter::pi() / 3.0)]); + for gate in [StandardGate::XY2P, StandardGate::XY2M] { + let circuit = half_rotation_circuit(gate, Parameter::symbol("theta")); + let operation = &circuit.operations()[0]; + let mut qasm = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[1];\n".to_string(); + super::dump_standard_gate( + &gate, + operation, + &circuit, + &mut qasm, + &qubit_map, + &replacements, + ) + .unwrap(); + assert_qasm_unitary_matches( + &qasm, + &half_rotation_circuit(gate, Parameter::pi() / 3.0), + false, + ); + + for invalid in [ + CircuitParam::Index(u32::MAX), + CircuitParam::Fixed(f64::NAN), + CircuitParam::Fixed(f64::INFINITY), + CircuitParam::Fixed(f64::NEG_INFINITY), + ] { + let mut operation = operation.clone(); + operation.params[0] = invalid; + let error = super::dump_standard_gate( + &gate, + &operation, + &circuit, + &mut String::new(), + &qubit_map, + &replacements, + ) + .unwrap_err(); + assert!(matches!(error, QasmDumpError::FormatError(message) + if message.contains("parameter 0") && message.contains(&format!("{gate:?}")))); + } + } +} + +#[test] +fn half_rotations_in_conditional_bodies_remain_explicitly_unsupported() { + for gate in HALF_ROTATION_GATES { + let mut circuit = Circuit::new(2); + let measured = circuit.measure(Qubit::new(0)).unwrap(); + let condition = ClassicalExpr::bit_to_bool(measured.expr()).unwrap(); + circuit + .if_(condition, |body| { + body.compose( + &half_rotation_circuit(gate, Parameter::pi() / 3.0), + Some(&[Qubit::new(1)]), + )?; + Ok(()) + }) + .unwrap(); + assert!( + matches!(dumps(&circuit), Err(QasmDumpError::UnsupportedClassicalControl(message)) + if message.contains(&format!("{gate:?}"))) + ); + } +} + +#[test] +fn every_standard_gate_qasm2_roundtrips_with_documented_phase_policy() { + let parameter_sets = [ + [0.0, 0.0, 0.0], + [0.731, -1.219, 2.031], + [-std::f64::consts::PI, std::f64::consts::FRAC_PI_2, -0.25], + ]; + for &gate in StandardGate::all() { + for values in parameter_sets { + let mut circuit = Circuit::new(3); + let params: Vec = values[..gate.num_params()] + .iter() + .copied() + .map(Into::into) + .collect(); + circuit + .append( + Instruction::Standard(gate), + (0..gate.num_qubits()).map(|index| Qubit::new(index as u32)), + params, + None, + ) + .unwrap(); + let qasm = dumps(&circuit).unwrap(); + if gate == StandardGate::GPhase { + // GPhase is deliberately emitted as a comment, not silently + // treated as a successful phase-preserving roundtrip. + assert!(qasm.contains("// gphase("), "{qasm}"); + let parsed = loads(&qasm).unwrap(); + assert!(parsed.operations().is_empty()); + assert_eq!(parsed.global_phase().evaluate(&None).unwrap(), 0.0); + } else { + assert_qasm_unitary_matches(&qasm, &circuit, !HALF_ROTATION_GATES.contains(&gate)); + } + } + } } #[test] diff --git a/crates/cqlib-core/src/ir/qasm3/load.rs b/crates/cqlib-core/src/ir/qasm3/load.rs index 9c60592c..41448e5d 100644 --- a/crates/cqlib-core/src/ir/qasm3/load.rs +++ b/crates/cqlib-core/src/ir/qasm3/load.rs @@ -147,6 +147,41 @@ fn frontend_panic_error(payload: Box) -> Qasm3ParseErr Qasm3ParseError::ParseError(format!("OpenQASM 3 front-end failed: {message}")) } +fn reject_end_statements(stmts: &[Stmt]) -> Result<(), Qasm3ParseError> { + // Check every scope before constant folding or loop expansion can discard + // statements. The circuit IR cannot preserve whole-program termination. + let mut pending = vec![stmts]; + while let Some(stmts) = pending.pop() { + for stmt in stmts { + match stmt { + Stmt::End => return Err(Qasm3ParseError::UnsupportedFeature("end".to_string())), + Stmt::Block(block) => pending.push(block.statements()), + Stmt::If(op) => { + pending.push(op.then_branch().statements()); + if let Some(block) = op.else_branch() { + pending.push(block.statements()); + } + } + Stmt::While(op) => pending.push(op.loop_body().statements()), + Stmt::ForStmt(op) => pending.push(op.loop_body().statements()), + Stmt::SwitchCaseStmt(op) => { + for case in op.cases() { + pending.push(case.statements()); + } + if let Some(stmts) = op.default_block() { + pending.push(stmts); + } + } + Stmt::GateDefinition(def) => pending.push(def.block().statements()), + Stmt::DefStmt(def) => pending.push(def.block().statements()), + Stmt::AnnotatedStmt(op) => pending.push(std::slice::from_ref(op.statement())), + _ => {} + } + } + } + Ok(()) +} + fn prepare_source(source: &str) -> Result { let layout = inspect_source(source)?; reject_empty_pragmas(&layout.code_mask)?; @@ -729,6 +764,7 @@ impl<'a> LoweringContext<'a> { ))); } + reject_end_statements(program.stmts())?; let total_qubits = self.discover_quantum(program.stmts())?; self.discover_gates(program.stmts())?; @@ -926,7 +962,8 @@ impl<'a> LoweringContext<'a> { "hardware qubit".to_string(), )), Stmt::Box => Err(Qasm3ParseError::UnsupportedFeature("box".to_string())), - Stmt::End | Stmt::NullStmt => Ok(()), + Stmt::End => Err(Qasm3ParseError::UnsupportedFeature("end".to_string())), + Stmt::NullStmt => Ok(()), Stmt::OldStyleDeclaration => Err(Qasm3ParseError::UnsupportedFeature( "old-style declaration".to_string(), )), diff --git a/crates/cqlib-core/src/ir/qasm3/load_test.rs b/crates/cqlib-core/src/ir/qasm3/load_test.rs index 9a9db6ef..b1ce4891 100644 --- a/crates/cqlib-core/src/ir/qasm3/load_test.rs +++ b/crates/cqlib-core/src/ir/qasm3/load_test.rs @@ -637,6 +637,120 @@ fn rejects_out_of_bounds_qubit_index() { ); } +#[test] +fn rejects_end_in_top_level_and_nested_scopes() { + for body in [ + "end;", + "x q; end; x q;", + "x q; end;", + "{ x q; end; } x q;", + "if (true) { x q; end; } x q;", + "bool flag = true; if (flag) { x q; end; } x q;", + "bool flag = false; if (flag) { x q; } else { end; } x q;", + "for uint i in [0:2] { x q; end; } x q;", + "while (true) { x q; end; } x q;", + "for uint i in [0:2] { if (true) { end; } } x q;", + "def stop() { end; } x q;", + "uint[2] c = 0; switch (c) { case 0 { end; } default { x q; } }", + "uint[2] c = 1; switch (c) { case 0 { x q; } default { end; } }", + ] { + let source = format!("OPENQASM 3.0; include \"stdgates.inc\"; qubit q; {body}"); + for loader in [loads, from_str] { + let result = loader(&source); + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection for {body:?}, got {result:?}" + ); + } + } +} + +#[test] +fn rejects_end_before_discarding_unreachable_statements() { + for body in [ + "if (false) { end; } x q;", + "if (true) { x q; } else { end; }", + "for uint i in [1:0] { end; } x q;", + "while (false) { end; } x q;", + "if (false) { for uint i in [1:0] { end; } } x q;", + ] { + let source = format!("OPENQASM 3.0; include \"stdgates.inc\"; qubit q; {body}"); + let result = loads(&source); + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection for {body:?}, got {result:?}" + ); + } +} + +#[test] +fn rejects_end_from_file() { + let path = unique_temp_path("end"); + fs::write( + &path, + "OPENQASM 3.0; include \"stdgates.inc\"; qubit q; x q; end; x q;", + ) + .unwrap(); + let loaded = load(&path); + let aliased = from_path(&path); + fs::remove_file(&path).unwrap(); + + for result in [loaded, aliased] { + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection, got {result:?}" + ); + } +} + +#[test] +fn rejects_end_from_included_file() { + let path = unique_temp_path("end_include"); + let included = path.with_extension("end"); + fs::write(&included, "if (false) { end; }").unwrap(); + fs::write( + &path, + format!( + "OPENQASM 3.0; include \"{}\";", + included.file_name().unwrap().to_str().unwrap() + ), + ) + .unwrap(); + let result = load(&path); + // An include path containing the keyword and comments are not statements. + fs::write(&included, "// end;\n/* end; */").unwrap(); + let without_end = load(&path); + fs::remove_file(&path).unwrap(); + fs::remove_file(&included).unwrap(); + + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection in include, got {result:?}" + ); + assert_eq!(without_end.unwrap().operations().len(), 0); +} + +#[test] +fn loads_null_statements_and_end_in_comments_and_identifiers() { + let circuit = loads( + r#" + OPENQASM 3.0; + include "stdgates.inc"; + qubit end_marker; + // end; + x end_marker; + /* if (true) { end; } */ + ; + h end_marker; + "#, + ) + .unwrap(); + + assert_eq!(circuit.operations().len(), 2); + assert_standard_gate(&circuit, 0, StandardGate::X, &[0]); + assert_standard_gate(&circuit, 1, StandardGate::H, &[0]); +} + #[test] fn rejects_unsupported_standard_gate() { assert_err( diff --git a/crates/cqlib-core/src/qis/state/stabilizer.rs b/crates/cqlib-core/src/qis/state/stabilizer.rs index 99d4640b..01cc7430 100644 --- a/crates/cqlib-core/src/qis/state/stabilizer.rs +++ b/crates/cqlib-core/src/qis/state/stabilizer.rs @@ -914,9 +914,9 @@ impl StabilizerState { /// Applies the √Y gate (Y2P, SY, Ry(π/2)) to qubit `qubit`. /// - /// Conjugation: X→Z, Y→Y, Z→−X. + /// Conjugation U P U†: X→−Z, Y→Y, Z→X. /// Rule per row `i`: - /// - `phase[i] ^= 2 * (!x[i][qubit] & z[i][qubit])` (flip for Z→−X) + /// - `phase[i] ^= 2 * (x[i][qubit] & !z[i][qubit])` (flip for X→−Z) /// - swap `x[i][qubit]` ↔ `z[i][qubit]` pub fn apply_y2p(&mut self, qubit: usize) -> Result<(), QisError> { self.validate_qubit(qubit)?; @@ -927,7 +927,7 @@ impl StabilizerState { let base = row * 2 * rl; let x = (self.tableau[base + word] & mask) != 0; let z = (self.tableau[base + rl + word] & mask) != 0; - if !x && z { + if x && !z { self.phases[row] ^= 2; } // swap x ↔ z @@ -947,9 +947,9 @@ impl StabilizerState { /// Applies the √Y† gate (Y2M, SYdg, Ry(−π/2)) to qubit `qubit`. /// - /// Conjugation: X→−Z, Y→Y, Z→X. + /// Conjugation U P U†: X→Z, Y→Y, Z→−X. /// Rule per row `i`: - /// - `phase[i] ^= 2 * (x[i][qubit] & !z[i][qubit])` (flip for X→−Z) + /// - `phase[i] ^= 2 * (!x[i][qubit] & z[i][qubit])` (flip for Z→−X) /// - swap `x[i][qubit]` ↔ `z[i][qubit]` pub fn apply_y2m(&mut self, qubit: usize) -> Result<(), QisError> { self.validate_qubit(qubit)?; @@ -960,7 +960,7 @@ impl StabilizerState { let base = row * 2 * rl; let x = (self.tableau[base + word] & mask) != 0; let z = (self.tableau[base + rl + word] & mask) != 0; - if x && !z { + if !x && z { self.phases[row] ^= 2; } // swap x ↔ z diff --git a/crates/cqlib-core/src/qis/state/stabilizer_test.rs b/crates/cqlib-core/src/qis/state/stabilizer_test.rs index 8876a098..8a3381a0 100644 --- a/crates/cqlib-core/src/qis/state/stabilizer_test.rs +++ b/crates/cqlib-core/src/qis/state/stabilizer_test.rs @@ -11,6 +11,228 @@ // that they have been altered from the originals. use super::*; +use crate::qis::{Hamiltonian, Statevector}; + +const CLIFFORD_GATES: [StandardGate; 15] = [ + StandardGate::I, + StandardGate::H, + StandardGate::X, + StandardGate::Y, + StandardGate::Z, + StandardGate::S, + StandardGate::SDG, + StandardGate::X2P, + StandardGate::X2M, + StandardGate::Y2P, + StandardGate::Y2M, + StandardGate::CX, + StandardGate::CY, + StandardGate::CZ, + StandardGate::SWAP, +]; + +#[test] +fn test_clifford_gates_on_complete_pauli_product_eigenstates() { + // These six states span the one-qubit operator space. Check every Pauli + // observable so opposite rotations cannot hide behind equal Z probabilities. + let preparations: [&[StandardGate]; 6] = [ + &[], + &[StandardGate::X], + &[StandardGate::H], + &[StandardGate::H, StandardGate::Z], + &[StandardGate::H, StandardGate::S], + &[StandardGate::H, StandardGate::Z, StandardGate::S], + ]; + for gate in CLIFFORD_GATES { + let n = gate.num_qubits(); + let qubits: Vec<_> = (0..n).collect(); + for input in 0..6usize.pow(n as u32) { + let mut state = StabilizerState::new(n); + let mut reference = Statevector::new(n); + let mut digits = input; + for q in 0..n { + for &prep in preparations[digits % 6] { + state.apply_standard_gate(prep, &[q], &[]).unwrap(); + reference + .apply_unitary_gate(&[q], &prep.matrix(&[]).unwrap()) + .unwrap(); + } + digits /= 6; + } + state.apply_standard_gate(gate, &qubits, &[]).unwrap(); + reference + .apply_unitary_gate(&qubits, &gate.matrix(&[]).unwrap()) + .unwrap(); + for mut index in 0..4usize.pow(n as u32) { + let mut pauli = PauliString::new(n); + for q in 0..n { + pauli.set_pauli(q, [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z][index % 4]); + index /= 4; + } + let expected = reference + .expectation(&Hamiltonian::from_pauli(pauli.clone())) + .unwrap(); + let actual = state.pauli_expectation(&pauli).unwrap(); + assert!( + (actual as f64 - expected).abs() < 1e-10, + "gate={gate:?}, input={input}, observable={pauli}: {actual} != {expected}" + ); + } + } + } +} + +#[test] +fn test_y2_rotations_match_h_z_decompositions_across_word_boundaries() { + // Compare both stabilizer and destabilizer rows, including untouched bits + // on either side of a packed-word boundary and rows containing Y. + let mut initial = StabilizerState::new(66); + initial.apply_h(0).unwrap(); + for q in 1..66 { + initial.apply_cx(q - 1, q).unwrap(); + initial.apply_s(q).unwrap(); + } + for q in [0, 63, 64, 65] { + for gate in [StandardGate::Y2P, StandardGate::Y2M] { + let mut actual = initial.clone(); + actual.apply_standard_gate(gate, &[q], &[]).unwrap(); + let mut expected = initial.clone(); + // In execution order: Y2P = Z;H, Y2M = H;Z. + if gate == StandardGate::Y2P { + expected.apply_z(q).unwrap(); + expected.apply_h(q).unwrap(); + } else { + expected.apply_h(q).unwrap(); + expected.apply_z(q).unwrap(); + } + assert_eq!(&*actual.tableau, &*expected.tableau, "{gate:?} on {q}"); + assert_eq!(&*actual.phases, &*expected.phases, "{gate:?} on {q}"); + } + } +} + +#[test] +fn test_y2_h_interference_probabilities_sampling_and_execution() { + use crate::qis::{RuntimeValue, Simulator, sample}; + + for (gate, bit) in [(StandardGate::Y2P, false), (StandardGate::Y2M, true)] { + let mut circuit = Circuit::new(1); + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], [], None) + .unwrap(); + circuit.h(Qubit::new(0)).unwrap(); + let measured = circuit.measure(Qubit::new(0)).unwrap(); + let state = StabilizerState::from_circuit(&circuit).unwrap(); + let expected = if bit { vec![0.0, 1.0] } else { vec![1.0, 0.0] }; + assert_eq!(state.probabilities().unwrap(), expected, "{gate:?};H"); + let outcome = Outcome::from_bitstring(if bit { "1" } else { "0" }).unwrap(); + for result in [ + state.sample(&measured, 8).unwrap(), + sample(&circuit, 8, Some(42), Simulator::Stabilizer, None).unwrap(), + ] { + assert_eq!(result.counts(), &HashMap::from([(outcome.clone(), 8)])); + } + let execution = StabilizerState::run_circuit(&circuit).unwrap(); + assert_eq!( + execution.classical.value(measured.value()), + Some(&RuntimeValue::Bit(bit)) + ); + } +} + +#[test] +fn test_y2_h_on_bell_state_preserves_expected_signed_correlations() { + for (gate, xx, zz, probabilities) in [ + (StandardGate::Y2P, -1, 1, vec![0.5, 0.0, 0.0, 0.5]), + (StandardGate::Y2M, 1, -1, vec![0.0, 0.5, 0.5, 0.0]), + ] { + let mut circuit = Circuit::new(2); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], [], None) + .unwrap(); + circuit.h(Qubit::new(0)).unwrap(); + let state = StabilizerState::from_circuit(&circuit).unwrap(); + // Y2P;H applies Z to |Phi+>, yielding |Phi->; Y2M;H applies X, + // yielding |Psi+>. Their Z distributions and XX/ZZ signs differ. + assert_eq!(state.probabilities().unwrap(), probabilities, "{gate:?}"); + for (name, expected) in [("XX", xx), ("ZZ", zz)] { + assert_eq!( + state.pauli_expectation(&name.parse().unwrap()).unwrap(), + expected + ); + } + for shot in state.sample_shots(16) { + assert_eq!(shot.is_one(0) == shot.is_one(1), zz == 1); + } + } +} + +#[test] +fn test_random_clifford_circuits_match_statevector_probabilities_and_observables() { + let mut rng = SmallRng::seed_from_u64(13); + for trial in 0..32 { + let mut circuit = Circuit::new(5); + // Guarantee that both rotations occur on an entangled input in every trial. + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit.y2p(Qubit::new(0)).unwrap(); + circuit.y2m(Qubit::new(1)).unwrap(); + for _ in 0..80 { + let gate = CLIFFORD_GATES[rng.random_range(0..CLIFFORD_GATES.len())]; + let a = rng.random_range(0..5); + let b = (a + rng.random_range(1..5)) % 5; + circuit + .append( + Instruction::Standard(gate), + [Qubit::new(a), Qubit::new(b)] + .into_iter() + .take(gate.num_qubits()), + [], + None, + ) + .unwrap(); + } + let state = StabilizerState::from_circuit(&circuit).unwrap(); + let reference = Statevector::from_circuit(&circuit).unwrap(); + for (basis, (actual, expected)) in state + .probabilities() + .unwrap() + .iter() + .zip(reference.probabilities()) + .enumerate() + { + assert!( + (actual - expected).abs() < 1e-10, + "trial={trial}, basis={basis}" + ); + } + // Generator checks always exercise nonzero expectations; uniformly random + // Paulis alone would mostly have zero expectation on five-qubit states. + let mut observables = state.get_stabilizers(); + for _ in 0..20 { + let mut pauli = PauliString::new(5); + for q in 0..5 { + pauli.set_pauli( + q, + [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z][rng.random_range(0..4)], + ); + } + observables.push(pauli); + } + for pauli in observables { + let actual = state.pauli_expectation(&pauli).unwrap(); + let expected = reference + .expectation(&Hamiltonian::from_pauli(pauli.clone())) + .unwrap(); + assert!( + (actual as f64 - expected).abs() < 1e-10, + "trial={trial}, observable={pauli}" + ); + } + } +} #[test] fn test_new_single_qubit() { @@ -674,7 +896,7 @@ fn test_x2m_four_is_identity() { assert_eq!(&*s.phases, &*original.phases); } -/// Y2P⁴ = Y2M⁴ = identity. +/// Y2P⁴ = Y2M⁴ = -I, equivalent to identity on the stabilizer tableau. #[test] fn test_y2p_four_is_identity() { let original = StabilizerState::new(2); @@ -733,7 +955,7 @@ fn test_x2p_squared_is_x() { assert_eq!(&*after_x2p2.phases, &*after_x.phases); } -/// Y2P² = Y (two √Y gates give Y gate). +/// Y2P² = -iY, equivalent to Y on the stabilizer tableau. #[test] fn test_y2p_squared_is_y() { let mut after_y2p2 = StabilizerState::new(2); diff --git a/docs/api/cn/c/1_ir/3_qasm3.md b/docs/api/cn/c/1_ir/3_qasm3.md index 58715594..5ba196e4 100644 --- a/docs/api/cn/c/1_ir/3_qasm3.md +++ b/docs/api/cn/c/1_ir/3_qasm3.md @@ -84,6 +84,7 @@ C 绑定提供 OpenQASM 3.0 文本与 `CCircuit` 之间的四个转换入口。 - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:运行时条件的 `while` 会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/cn/python/1_ir/3_qasm3.md b/docs/api/cn/python/1_ir/3_qasm3.md index fd53bcb8..e2ba59d8 100644 --- a/docs/api/cn/python/1_ir/3_qasm3.md +++ b/docs/api/cn/python/1_ir/3_qasm3.md @@ -143,6 +143,7 @@ circuit = qasm3.loads(code) - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:`while` 在实现中存在下降路径,但运行时条件的循环当前会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/cn/rust/1_ir/3_qasm3.md b/docs/api/cn/rust/1_ir/3_qasm3.md index 4e5d5779..ddda4dd8 100644 --- a/docs/api/cn/rust/1_ir/3_qasm3.md +++ b/docs/api/cn/rust/1_ir/3_qasm3.md @@ -99,6 +99,7 @@ use cqlib_core::ir::{qasm3_load, qasm3_loads, qasm3_dump, qasm3_dumps}; - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:`while` 在实现中存在下降路径,但运行时条件的循环当前会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/en/c/1_ir/3_qasm3.md b/docs/api/en/c/1_ir/3_qasm3.md index 26bd2a29..ddfcb2b2 100644 --- a/docs/api/en/c/1_ir/3_qasm3.md +++ b/docs/api/en/c/1_ir/3_qasm3.md @@ -84,6 +84,7 @@ The following features produce an explicit error rather than partial degradation - Subprograms and externals: `def` subprograms, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and float - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` only work when the target gate has a matching implementation - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: `while` over a runtime condition is rejected by semantic checks; `for` only supports static expansion of constant ranges diff --git a/docs/api/en/python/1_ir/3_qasm3.md b/docs/api/en/python/1_ir/3_qasm3.md index ae0e5c87..6b1982cb 100644 --- a/docs/api/en/python/1_ir/3_qasm3.md +++ b/docs/api/en/python/1_ir/3_qasm3.md @@ -143,6 +143,7 @@ The following OpenQASM 3.0 features are not supported in the current implementat - Subroutines and external calls: `def` subroutines, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and floating-point - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` are available only when a corresponding implementation exists for the target gate - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: a lowering path for `while` exists in the implementation, but loops with a runtime condition are currently rejected by the semantic check; `for` supports only the statically expanded form whose range is constant diff --git a/docs/api/en/rust/1_ir/3_qasm3.md b/docs/api/en/rust/1_ir/3_qasm3.md index 8bc15b95..858f89a5 100644 --- a/docs/api/en/rust/1_ir/3_qasm3.md +++ b/docs/api/en/rust/1_ir/3_qasm3.md @@ -99,6 +99,7 @@ The following OpenQASM 3.0 features are not supported in the current implementat - Subroutines and external calls: `def` subroutines, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and float - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` are available only when a corresponding implementation exists for the target gate - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: a lowering path for `while` exists in the implementation, but a loop with a runtime condition is currently rejected by the semantic check; `for` supports only the statically expanded form with a constant range diff --git a/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md b/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md index 320ab40a..f8b55275 100644 --- a/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md +++ b/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md @@ -261,6 +261,7 @@ Cqlib 的 QASM3 loader 支持部分可映射到当前 `Circuit` 的控制流: | `reset`、`barrier`、`gphase` | 支持 | | 自定义 gate | 支持可映射的 gate body | | calibration、pulse、extern、hardware qubit、alias | 当前不支持 | +| 程序终止 `end` | 任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 | | 任意复杂 classical arithmetic | 当前不支持无损 lowering | | 复杂 lvalue slicing、多维索引 | 当前不支持或仅支持必要子集 | diff --git a/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md b/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md index 2e700c56..2f3f11bf 100644 --- a/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md +++ b/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md @@ -261,6 +261,7 @@ Recommended principle: if a circuit is mainly used for cross-toolchain exchange, | `reset`, `barrier`, `gphase` | Supported | | Custom gate | Supported for a mappable gate body | | calibration, pulse, extern, hardware qubit, alias | Currently not supported | +| Program termination `end` | Explicitly rejected in every scope, including unreachable branches and zero-iteration loops | | Arbitrary complex classical arithmetic | Lossless lowering is currently not supported | | Complex lvalue slicing, multi-dimensional indexing | Currently not supported, or only the necessary subset is supported |