Skip to content
Open
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
83 changes: 83 additions & 0 deletions crates/pecos-qec/src/fault_tolerance/propagator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,52 @@ pub fn is_supported_noop_or_metadata_gate(gate_type: GateType) -> bool {
)
}

/// Gate classification for compiling gate-triggered quantum noise.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateNoiseKind {
/// Preparation or allocation receiving preparation noise.
Prep,
/// Single-qubit operation receiving single-qubit noise.
Single,
/// Two-qubit operation receiving one noise channel per pair.
Two,
/// Measurement receiving no post-gate quantum noise.
Measurement,
/// Operation left unchanged by the noise callback.
Transparent,
/// Unsupported operation that must be rejected when noise is active.
Error,
}

/// Classify a gate for preparation, single-qubit, or two-qubit quantum noise.
///
/// Identity and idle gates retain single-qubit noise even though they are
/// transparent to Pauli propagation. Custom gates have no known arity.
#[inline]
#[must_use]
pub fn gate_noise_kind(gate_type: GateType) -> GateNoiseKind {
match gate_type {
// Custom has placeholder arity 1, not a known single-qubit operation.
GateType::Custom => GateNoiseKind::Error,
gate if is_supported_prep_gate(gate) => GateNoiseKind::Prep,
// consumes_measurement_record excludes MeasureLeaked, which still collapses
// the qubit. A complete measurement predicate belongs in pecos_core::GateType,
// alongside consumes_measurement_record (see also Gate::validate).
gate if gate.consumes_measurement_record() || gate == GateType::MeasureLeaked => {
GateNoiseKind::Measurement
}
// Identity and idle operations retain their physical single-qubit noise.
GateType::I | GateType::Idle => GateNoiseKind::Single,
// The core rejects Channel upstream of the noise callback.
gate if is_supported_noop_or_metadata_gate(gate) || gate == GateType::Channel => {
GateNoiseKind::Transparent
}
gate if gate.is_single_qubit() => GateNoiseKind::Single,
gate if gate.is_two_qubit() => GateNoiseKind::Two,
_ => GateNoiseKind::Error,
}
}

/// Circuit position of a gate that cannot be faithfully Pauli-propagated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnsupportedGateLocation {
Expand Down Expand Up @@ -759,6 +805,43 @@ mod tests {
use super::*;
use pecos_quantum::TickCircuit;

#[test]
fn every_gate_has_an_explicit_noise_classification() {
for value in u8::MIN..=u8::MAX {
let Ok(gate) = GateType::try_from(value) else {
continue;
};
let prep = is_supported_prep_gate(gate);
let measurement = gate.consumes_measurement_record() || gate == GateType::MeasureLeaked;
let transparent = (is_supported_noop_or_metadata_gate(gate)
&& !matches!(gate, GateType::I | GateType::Idle))
|| gate == GateType::Channel;
let single = gate.is_single_qubit()
&& gate != GateType::Custom
&& !prep
&& !measurement
&& !transparent;
let two = gate.is_two_qubit();
// Intentionally enumerate errors: a future unclassified variant must fail.
let error = matches!(gate, GateType::CCX | GateType::Custom);
let buckets = [
(prep, GateNoiseKind::Prep),
(single, GateNoiseKind::Single),
(two, GateNoiseKind::Two),
(measurement, GateNoiseKind::Measurement),
(transparent, GateNoiseKind::Transparent),
(error, GateNoiseKind::Error),
];
assert_eq!(
buckets.iter().filter(|(member, _)| *member).count(),
1,
"{gate:?}"
);
let expected = buckets.iter().find(|(member, _)| *member).unwrap().1;
assert_eq!(gate_noise_kind(gate), expected, "{gate:?}");
}
}

fn simple_syndrome_circuit() -> TickCircuit {
// Simple Z-stabilizer measurement: Z0 Z1
// Ancilla qubit 2 measures the parity
Expand Down
4 changes: 4 additions & 0 deletions python/pecos-rslib/pecos_rslib.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1741,6 +1741,10 @@ class llvm:

PHYSICAL_DURATION_META_KEY: str

def is_supported_noop_or_metadata_gate(gate_type: GateType) -> bool:
"""Return whether the gate is transparent to Pauli propagation."""
...

class GateType:
"""Gate type marker."""

Expand Down
114 changes: 47 additions & 67 deletions python/pecos-rslib/src/dag_circuit_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
use crate::dtypes::AngleParam;
use crate::gate_registry_bindings::PyGateRegistry;
use pecos_core::{Angle64, ChannelExpr, GateQubits, GateSignature, Pauli, TimeUnits};
use pecos_qec::fault_tolerance::propagator::{
GateNoiseKind, gate_noise_kind, is_supported_noop_or_metadata_gate,
};
use pecos_quantum::{
Attribute, DagCircuit, Gate, GateType, PHYSICAL_DURATION_META_KEY, QubitId, Tick, TickCircuit,
TickGateError,
Expand Down Expand Up @@ -88,25 +91,6 @@ fn validate_probability(name: &str, p: f64) -> PyResult<()> {
}
}

fn receives_two_qubit_noise(gate_type: GateType) -> bool {
matches!(
gate_type,
GateType::CX
| GateType::CY
| GateType::CZ
| GateType::SZZ
| GateType::SZZdg
| GateType::SXX
| GateType::SXXdg
| GateType::SYY
| GateType::SYYdg
| GateType::SWAP
| GateType::RXX
| GateType::RYY
| GateType::RZZ
)
}

/// Convert a Rust Attribute to a Python object.
fn attribute_to_py(py: Python<'_>, attr: &Attribute) -> Py<PyAny> {
match attr {
Expand Down Expand Up @@ -647,6 +631,12 @@ impl PyGateType {
}
}

/// Whether a gate is transparent to Pauli propagation.
#[pyfunction(name = "is_supported_noop_or_metadata_gate")]
fn py_is_supported_noop_or_metadata_gate(gate_type: PyGateType) -> bool {
is_supported_noop_or_metadata_gate(gate_type.inner)
}

impl From<GateType> for PyGateType {
fn from(inner: GateType) -> Self {
Self { inner }
Expand Down Expand Up @@ -2895,9 +2885,22 @@ impl PyTickCircuit {
));
}

if p2 > 0.0 {
if p1 > 0.0 || p2 > 0.0 || p_prep > 0.0 {
for (tick_idx, gate) in self.inner.iter_gate_batches_with_tick() {
if receives_two_qubit_noise(gate.gate_type) && !gate.qubits.len().is_multiple_of(2)
match gate_noise_kind(gate.gate_type) {
GateNoiseKind::Prep
| GateNoiseKind::Single
| GateNoiseKind::Two
| GateNoiseKind::Measurement
| GateNoiseKind::Transparent => {}
GateNoiseKind::Error => {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"Unsupported gate type {:?} at tick {tick_idx} for with_noise",
gate.gate_type
)));
}
}
if p2 > 0.0 && gate.gate_type.is_two_qubit() && !gate.qubits.len().is_multiple_of(2)
{
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"{:?} at tick {tick_idx} has {} qubits; expected pairs",
Expand All @@ -2912,63 +2915,36 @@ impl PyTickCircuit {
.inner
.try_with_noise(&|gate: &Gate| -> Vec<ChannelExpr> {
let mut channels = Vec::new();
match gate.gate_type {
GateType::PZ | GateType::QAlloc if p_prep > 0.0 => {
channels.extend(
gate.qubits
.iter()
.map(|q| pecos_core::channel::BitFlip(p_prep, q.index())),
);
match gate_noise_kind(gate.gate_type) {
GateNoiseKind::Prep if p_prep > 0.0 => {
// Match pecos-qec's dem_builder/mem_builder.rs: PX errors are Z flips.
channels.extend(gate.qubits.iter().map(|q| {
if gate.gate_type == GateType::PX {
pecos_core::channel::Dephasing(p_prep, q.index())
} else {
pecos_core::channel::BitFlip(p_prep, q.index())
}
}));
}
GateType::I
| GateType::X
| GateType::Y
| GateType::Z
| GateType::H
| GateType::F
| GateType::Fdg
| GateType::SX
| GateType::SXdg
| GateType::SY
| GateType::SYdg
| GateType::SZ
| GateType::SZdg
| GateType::T
| GateType::Tdg
| GateType::RX
| GateType::RY
| GateType::RZ
| GateType::U
| GateType::RXY1Q
| GateType::Idle
if p1 > 0.0 =>
{
GateNoiseKind::Single if p1 > 0.0 => {
channels.extend(
gate.qubits
.iter()
.map(|q| pecos_core::channel::Depolarizing(p1, q.index())),
);
}
GateType::CX
| GateType::CY
| GateType::CZ
| GateType::SZZ
| GateType::SZZdg
| GateType::SXX
| GateType::SXXdg
| GateType::SYY
| GateType::SYYdg
| GateType::SWAP
| GateType::RXX
| GateType::RYY
| GateType::RZZ
if p2 > 0.0 =>
{
GateNoiseKind::Two if p2 > 0.0 => {
channels.extend(gate.qubits.as_chunks::<2>().0.iter().map(|pair| {
pecos_core::channel::Depolarizing2(p2, pair[0].index(), pair[1].index())
}));
}
_ => {}
// Unsupported gates were rejected above whenever noise is active.
GateNoiseKind::Prep
| GateNoiseKind::Single
| GateNoiseKind::Two
| GateNoiseKind::Measurement
| GateNoiseKind::Transparent
| GateNoiseKind::Error => {}
}
channels
})
Expand Down Expand Up @@ -4128,6 +4104,10 @@ pub fn register_quantum_circuit_types(parent_module: &Bound<'_, PyModule>) -> Py
// Add classes to parent module
parent_module.add_class::<PyQubitId>()?;
parent_module.add_class::<PyGateType>()?;
parent_module.add_function(wrap_pyfunction!(
py_is_supported_noop_or_metadata_gate,
parent_module
)?)?;
parent_module.add_class::<PyGate>()?;
parent_module.add_class::<PyDagCircuit>()?;
parent_module.add_class::<PyTick>()?;
Expand Down
29 changes: 28 additions & 1 deletion python/quantum-pecos/src/pecos/qec/surface/circuit_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3191,6 +3191,8 @@ def tick_circuit_to_stim(
import json
import math

from pecos_rslib import is_supported_noop_or_metadata_gate

lines = []

simple_gate_map = {
Expand Down Expand Up @@ -3302,7 +3304,32 @@ def _gate_to_stim(
msg = f"Unsupported traced Clifford RXY1Q angles: theta={theta!r}, phi={phi!r}"
raise ValueError(msg)

return [], None
if gate_name == "RXYXY2Q":
if len(gate.angles) < 2:
return [], None
theta = float(gate.angles[0])
phi = float(gate.angles[1])
if _is_close_turn(theta, 0.0):
return [], None
axis = None
if _is_close_turn(phi, 0.0) or _is_close_turn(phi, math.pi):
axis = "X"
elif _is_close_turn(phi, math.pi / 2) or _is_close_turn(phi, 3 * math.pi / 2):
axis = "Y"
if axis is not None:
if _is_close_turn(theta, math.pi / 2):
return [(f"SQRT_{axis}{axis}", qubits)], "two"
if _is_close_turn(theta, 3 * math.pi / 2):
return [(f"SQRT_{axis}{axis}_DAG", qubits)], "two"
if _is_close_turn(theta, math.pi):
return [(axis, qubits)], "two"
msg = f"Unsupported traced Clifford RXYXY2Q angles: theta={theta!r}, phi={phi!r}"
raise ValueError(msg)

if is_supported_noop_or_metadata_gate(gate.gate_type):
return [], None
msg = f"Unsupported gate for Stim export: {gate_name}"
raise ValueError(msg)

for tick_idx in range(tc.num_ticks()):
tick = tc.get_tick(tick_idx)
Expand Down
Loading
Loading