Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .typos.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[default]
# Unicode decimal-number category in regular expressions.
extend-ignore-re = ['\\p\{Nd\}']

[default.extend-words]
ket = "ket"
bra = "bra"
Expand Down
4 changes: 3 additions & 1 deletion crates/binding-c/src/circuit/properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
46 changes: 46 additions & 0 deletions crates/binding-c/tests/circuit_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
10 changes: 9 additions & 1 deletion crates/binding-python/cqlib/circuit/circuit.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion crates/binding-python/src/circuit/circuit_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PyIntListOrQubitList>) -> PyResult<()> {
let qubits = qubits.map(Vec::from);
Expand Down
17 changes: 17 additions & 0 deletions crates/binding-python/tests/circuit/test_edge_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
13 changes: 11 additions & 2 deletions crates/cqlib-core/src/circuit/circuit_classical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
141 changes: 80 additions & 61 deletions crates/cqlib-core/src/circuit/circuit_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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<CircuitParam> = Vec::with_capacity(self.parameters.len());

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
///
Expand Down Expand Up @@ -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());
Expand All @@ -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
Expand All @@ -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<CircuitParam> = 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));
}

Expand All @@ -2896,56 +2939,32 @@ impl Circuit {
})
.collect::<Result<Vec<_>, _>>()?;

// 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
Expand Down
Loading
Loading