Skip to main content

faultscope_core/
model.rs

1use std::collections::{HashMap, HashSet};
2use std::error::Error;
3use std::fmt;
4use std::sync::Arc;
5
6use crate::Mask;
7
8pub type NpResult<T> = Result<T, NpError>;
9
10/// Error type returned by the Rust core APIs.
11///
12/// The core crate is still pre-1.0, so error messages are intended to be
13/// readable diagnostics rather than a stable machine-readable taxonomy.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct NpError {
16    message: String,
17}
18
19impl NpError {
20    pub fn new(message: impl Into<String>) -> Self {
21        Self {
22            message: message.into(),
23        }
24    }
25
26    pub fn message(&self) -> &str {
27        &self.message
28    }
29}
30
31impl fmt::Display for NpError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        self.message.fmt(f)
34    }
35}
36
37impl Error for NpError {}
38
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub enum TagValue {
41    None,
42    Bool(bool),
43    Int(i64),
44    Float(u64),
45    String(String),
46}
47
48impl TagValue {
49    pub fn float(value: f64) -> NpResult<Self> {
50        if value.is_nan() {
51            return Err(NpError::new("tags do not support NaN"));
52        }
53        Ok(Self::Float(value.to_bits()))
54    }
55
56    pub fn as_f64(&self) -> Option<f64> {
57        match self {
58            Self::Float(bits) => Some(f64::from_bits(*bits)),
59            _ => None,
60        }
61    }
62}
63
64#[derive(Debug, Clone, PartialEq)]
65pub enum NoiseModel {
66    BernoulliPauli(String),
67    MeasurementBitFlip,
68    SingleQubitDepolarizing,
69    TwoQubitDepolarizing,
70    PauliChannel(Vec<(String, f64)>),
71}
72
73impl NoiseModel {
74    /// Validate configuration that is intrinsic to this noise model.
75    pub fn validate(&self) -> NpResult<()> {
76        validate_noise_model(self, "noise model").map(|_| ())
77    }
78}
79
80/// A named stochastic noise source attached to a circuit operation.
81///
82/// Noise location ids must be unique within runtime compilation and DEM
83/// generation. Tags are optional metadata used by hotspot aggregation.
84#[derive(Debug, Clone, PartialEq)]
85pub struct NoiseLocation {
86    pub id: String,
87    pub model: NoiseModel,
88    pub rate: f64,
89    pub qubits: Vec<usize>,
90    pub tags: HashMap<String, TagValue>,
91}
92
93impl NoiseLocation {
94    pub fn validate(&self) -> NpResult<()> {
95        validate_noise_rate(self.rate)?;
96        let context = format!("noise location {:?}", self.id);
97        validate_unique_qubits(&self.qubits, &context)?;
98        validate_noise_shape(&self.model, &self.qubits, &context)
99    }
100
101    pub(crate) fn validate_for_n_qubits<C>(&self, n_qubits: usize, context: &C) -> NpResult<()>
102    where
103        C: fmt::Display + ?Sized,
104    {
105        validate_noise_parts(n_qubits, &self.model, self.rate, &self.qubits, context)
106    }
107}
108
109/// Typed circuit operation understood by the Rust core.
110#[derive(Debug, Clone, PartialEq)]
111pub enum Operation {
112    /// A semantic no-op used to preserve Stim scheduling boundaries.
113    Tick,
114    /// Add an offset to subsequent detector coordinates.
115    ShiftCoords(Vec<f64>),
116    /// Repeat a nested operation body `count` times.
117    Repeat {
118        count: usize,
119        body: Vec<Operation>,
120    },
121    H(usize),
122    S(usize),
123    SDag(usize),
124    Cx(usize, usize),
125    Cz(usize, usize),
126    Swap(usize, usize),
127    Pauli {
128        qubits: Vec<usize>,
129        pauli: String,
130    },
131    Noise(NoiseLocation),
132    Measure {
133        qubit: usize,
134        key: Option<String>,
135        basis: String,
136        noise: Option<NoiseLocation>,
137    },
138    MeasurePauli {
139        qubits: Vec<usize>,
140        pauli: String,
141        key: Option<String>,
142        noise: Option<NoiseLocation>,
143    },
144    /// Combined measurement and reset with an automatically assigned record key.
145    MeasureReset {
146        qubit: usize,
147        basis: String,
148    },
149    Reset {
150        qubit: usize,
151        key: Option<String>,
152        basis: String,
153    },
154    Detector {
155        detector_id: Option<i64>,
156        measurement_keys: Vec<String>,
157        coords: Vec<f64>,
158    },
159    /// Detector declaration using positive measurement-record lookbacks.
160    DetectorRec {
161        detector_id: Option<i64>,
162        lookbacks: Vec<usize>,
163        coords: Vec<f64>,
164    },
165    ObservableInclude {
166        observable_id: i64,
167        measurement_keys: Vec<String>,
168    },
169    /// Observable declaration using positive measurement-record lookbacks.
170    ObservableIncludeRec {
171        observable_id: i64,
172        lookbacks: Vec<usize>,
173    },
174}
175
176impl Operation {
177    pub fn noise_locations(&self) -> Vec<&NoiseLocation> {
178        match self {
179            Self::Noise(location) => vec![location],
180            Self::Measure {
181                noise: Some(location),
182                ..
183            }
184            | Self::MeasurePauli {
185                noise: Some(location),
186                ..
187            } => vec![location],
188            Self::Repeat { body, .. } => body.iter().flat_map(Operation::noise_locations).collect(),
189            _ => Vec::new(),
190        }
191    }
192}
193
194/// A stabilizer-compatible circuit for forward sampling and DEM generation.
195///
196/// The Rust API is intentionally typed and Python-independent. It is currently
197/// pre-1.0 and may change as the core package stabilizes.
198#[derive(Debug, Clone, PartialEq)]
199pub struct Circuit {
200    pub n_qubits: usize,
201    pub operations: Vec<Operation>,
202}
203
204impl Circuit {
205    /// Validate all qubit-bearing operations without expanding repeat blocks.
206    pub fn validate(&self) -> NpResult<()> {
207        validate_operations(self.n_qubits, &self.operations)
208    }
209
210    pub fn noise_locations(&self) -> HashMap<String, NoiseLocation> {
211        let mut locations = HashMap::new();
212        for operation in &self.operations {
213            for location in operation.noise_locations() {
214                locations.insert(location.id.clone(), location.clone());
215            }
216        }
217        locations
218    }
219}
220
221/// Detector declaration used by detector error models.
222#[derive(Debug, Clone, PartialEq)]
223pub struct Detector {
224    pub id: i64,
225    pub measurement_keys: Vec<String>,
226    pub coords: Vec<f64>,
227}
228
229/// Logical observable declaration.
230///
231/// Observables can be defined from measurement keys, from a final Pauli frame
232/// projection, or from both.
233#[derive(Debug, Clone, PartialEq)]
234pub struct LogicalObservable {
235    pub id: i64,
236    pub measurement_keys: Vec<String>,
237    pub pauli_qubits: Vec<usize>,
238    pub pauli: String,
239}
240
241impl LogicalObservable {
242    pub fn validate(&self) -> NpResult<()> {
243        if self.pauli_qubits.is_empty() != self.pauli.is_empty() {
244            return Err(NpError::new(
245                "pauli_qubits and pauli must be supplied together",
246            ));
247        }
248        if !self.pauli.is_empty() && self.pauli_qubits.len() != pauli_len(&self.pauli) {
249            return Err(NpError::new(
250                "pauli_qubits and pauli must have the same length",
251            ));
252        }
253        let context = ObservableContext { id: self.id };
254        validate_pauli_string(&self.pauli, &context)?;
255        validate_unique_qubits(&self.pauli_qubits, &context)?;
256        Ok(())
257    }
258
259    pub fn validate_for_n_qubits(&self, n_qubits: usize) -> NpResult<()> {
260        self.validate()?;
261        let context = ObservableContext { id: self.id };
262        for qubit in &self.pauli_qubits {
263            validate_qubit_index(n_qubits, *qubit, &context)?;
264        }
265        Ok(())
266    }
267}
268
269#[derive(Clone, Copy)]
270struct ObservableContext {
271    id: i64,
272}
273
274impl fmt::Display for ObservableContext {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(f, "logical observable {}", self.id)
277    }
278}
279
280#[derive(Clone, Copy)]
281struct OperationContext<'a> {
282    kind: &'static str,
283    path: &'a [usize],
284}
285
286impl fmt::Display for OperationContext<'_> {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        write!(f, "{} at operation path ", self.kind)?;
289        for (index, component) in self.path.iter().enumerate() {
290            if index != 0 {
291                f.write_str(".")?;
292            }
293            component.fmt(f)?;
294        }
295        Ok(())
296    }
297}
298
299struct OperationNoiseContext<'a> {
300    operation: OperationContext<'a>,
301    location_id: &'a str,
302}
303
304impl fmt::Display for OperationNoiseContext<'_> {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        write!(
307            f,
308            "{} noise location {:?}",
309            self.operation, self.location_id
310        )
311    }
312}
313
314pub(crate) fn validate_operations(n_qubits: usize, operations: &[Operation]) -> NpResult<()> {
315    validate_operation_sequence(n_qubits, operations, &mut Vec::new())
316}
317
318fn validate_operation_sequence(
319    n_qubits: usize,
320    operations: &[Operation],
321    path: &mut Vec<usize>,
322) -> NpResult<()> {
323    for (index, operation) in operations.iter().enumerate() {
324        path.push(index);
325        validate_operation(n_qubits, operation, path)?;
326        path.pop();
327    }
328    Ok(())
329}
330
331fn validate_operation(
332    n_qubits: usize,
333    operation: &Operation,
334    path: &mut Vec<usize>,
335) -> NpResult<()> {
336    match operation {
337        Operation::Tick
338        | Operation::ShiftCoords(_)
339        | Operation::Detector { .. }
340        | Operation::DetectorRec { .. }
341        | Operation::ObservableInclude { .. }
342        | Operation::ObservableIncludeRec { .. } => return Ok(()),
343        Operation::Repeat { count, body } => {
344            if *count == 0 {
345                return Err(NpError::new("repeat count must be positive"));
346            }
347            return validate_operation_sequence(n_qubits, body, path);
348        }
349        _ => {}
350    }
351
352    let context = OperationContext {
353        kind: operation_kind(operation),
354        path,
355    };
356    match operation {
357        Operation::H(qubit) | Operation::S(qubit) | Operation::SDag(qubit) => {
358            validate_qubit_index(n_qubits, *qubit, &context)?;
359        }
360        Operation::Cx(control, target)
361        | Operation::Cz(control, target)
362        | Operation::Swap(control, target) => {
363            validate_qubit_pair(n_qubits, *control, *target, &context)?;
364        }
365        Operation::Pauli { qubits, pauli } | Operation::MeasurePauli { qubits, pauli, .. } => {
366            validate_pauli_targets(n_qubits, qubits, pauli, &context)?;
367            if let Operation::MeasurePauli {
368                noise: Some(location),
369                ..
370            } = operation
371            {
372                let noise_context = OperationNoiseContext {
373                    operation: context,
374                    location_id: &location.id,
375                };
376                location.validate_for_n_qubits(n_qubits, &noise_context)?;
377            }
378        }
379        Operation::Noise(location) => {
380            let noise_context = OperationNoiseContext {
381                operation: context,
382                location_id: &location.id,
383            };
384            location.validate_for_n_qubits(n_qubits, &noise_context)?;
385        }
386        Operation::Measure { qubit, noise, .. } => {
387            validate_qubit_index(n_qubits, *qubit, &context)?;
388            if let Some(location) = noise {
389                let noise_context = OperationNoiseContext {
390                    operation: context,
391                    location_id: &location.id,
392                };
393                location.validate_for_n_qubits(n_qubits, &noise_context)?;
394            }
395        }
396        Operation::MeasureReset { qubit, .. } | Operation::Reset { qubit, .. } => {
397            validate_qubit_index(n_qubits, *qubit, &context)?;
398        }
399        Operation::Tick
400        | Operation::ShiftCoords(_)
401        | Operation::Repeat { .. }
402        | Operation::Detector { .. }
403        | Operation::DetectorRec { .. }
404        | Operation::ObservableInclude { .. }
405        | Operation::ObservableIncludeRec { .. } => unreachable!("handled above"),
406    }
407    Ok(())
408}
409
410fn operation_kind(operation: &Operation) -> &'static str {
411    match operation {
412        Operation::Tick => "Tick",
413        Operation::ShiftCoords(_) => "ShiftCoords",
414        Operation::Repeat { .. } => "Repeat",
415        Operation::H(_) => "H",
416        Operation::S(_) => "S",
417        Operation::SDag(_) => "SDag",
418        Operation::Cx(_, _) => "CX",
419        Operation::Cz(_, _) => "CZ",
420        Operation::Swap(_, _) => "SWAP",
421        Operation::Pauli { .. } => "Pauli",
422        Operation::Noise(_) => "Noise",
423        Operation::Measure { .. } => "Measure",
424        Operation::MeasurePauli { .. } => "MeasurePauli",
425        Operation::MeasureReset { .. } => "MeasureReset",
426        Operation::Reset { .. } => "Reset",
427        Operation::Detector { .. } => "Detector",
428        Operation::DetectorRec { .. } => "DetectorRec",
429        Operation::ObservableInclude { .. } => "ObservableInclude",
430        Operation::ObservableIncludeRec { .. } => "ObservableIncludeRec",
431    }
432}
433
434pub(crate) fn validate_qubit_index<C>(n_qubits: usize, qubit: usize, context: &C) -> NpResult<()>
435where
436    C: fmt::Display + ?Sized,
437{
438    if qubit >= n_qubits {
439        return Err(NpError::new(format!(
440            "{context} targets qubit {qubit}, but only {n_qubits} qubits are available"
441        )));
442    }
443    Ok(())
444}
445
446pub(crate) fn validate_unique_qubits<C>(qubits: &[usize], context: &C) -> NpResult<()>
447where
448    C: fmt::Display + ?Sized,
449{
450    // Most gates and noise events touch very few qubits. A short linear scan
451    // avoids allocating a hash table in that overwhelmingly common case.
452    const LINEAR_SCAN_LIMIT: usize = 8;
453    if qubits.len() <= LINEAR_SCAN_LIMIT {
454        for (index, qubit) in qubits.iter().enumerate() {
455            if qubits[..index].contains(qubit) {
456                return Err(NpError::new(format!(
457                    "{context} requires unique qubit targets; duplicate qubit {qubit}"
458                )));
459            }
460        }
461        return Ok(());
462    }
463
464    let mut seen = HashSet::with_capacity(qubits.len());
465    for qubit in qubits {
466        if !seen.insert(*qubit) {
467            return Err(NpError::new(format!(
468                "{context} requires unique qubit targets; duplicate qubit {qubit}"
469            )));
470        }
471    }
472    Ok(())
473}
474
475pub(crate) fn validate_qubit_targets<C>(
476    n_qubits: usize,
477    qubits: &[usize],
478    context: &C,
479) -> NpResult<()>
480where
481    C: fmt::Display + ?Sized,
482{
483    for qubit in qubits {
484        validate_qubit_index(n_qubits, *qubit, context)?;
485    }
486    validate_unique_qubits(qubits, context)
487}
488
489pub(crate) fn validate_qubit_pair<C>(
490    n_qubits: usize,
491    left: usize,
492    right: usize,
493    context: &C,
494) -> NpResult<()>
495where
496    C: fmt::Display + ?Sized,
497{
498    validate_qubit_index(n_qubits, left, context)?;
499    validate_qubit_index(n_qubits, right, context)?;
500    if left == right {
501        return Err(NpError::new(format!(
502            "{context} requires distinct qubit targets; duplicate qubit {left}"
503        )));
504    }
505    Ok(())
506}
507
508pub(crate) fn validate_pauli_string<C>(pauli: &str, context: &C) -> NpResult<()>
509where
510    C: fmt::Display + ?Sized,
511{
512    if let Some(local) = pauli
513        .chars()
514        .find(|local| !matches!(local, 'I' | 'X' | 'Y' | 'Z'))
515    {
516        return Err(NpError::new(format!(
517            "{context} contains unsupported Pauli {local:?}"
518        )));
519    }
520    Ok(())
521}
522
523pub(crate) fn validate_pauli_targets<C>(
524    n_qubits: usize,
525    qubits: &[usize],
526    pauli: &str,
527    context: &C,
528) -> NpResult<()>
529where
530    C: fmt::Display + ?Sized,
531{
532    if qubits.len() != pauli_len(pauli) {
533        return Err(NpError::new(format!(
534            "{context} qubit targets and Pauli must have the same length"
535        )));
536    }
537    validate_pauli_string(pauli, context)?;
538    validate_qubit_targets(n_qubits, qubits, context)
539}
540
541pub(crate) fn validate_noise_parts<C>(
542    n_qubits: usize,
543    model: &NoiseModel,
544    rate: f64,
545    qubits: &[usize],
546    context: &C,
547) -> NpResult<()>
548where
549    C: fmt::Display + ?Sized,
550{
551    validate_noise_rate(rate)?;
552    validate_qubit_targets(n_qubits, qubits, context)?;
553    validate_noise_shape(model, qubits, context)
554}
555
556fn validate_noise_rate(rate: f64) -> NpResult<()> {
557    if !(0.0..=1.0).contains(&rate) {
558        return Err(NpError::new(format!(
559            "noise rate must be in [0, 1], got {rate}"
560        )));
561    }
562    Ok(())
563}
564
565fn validate_noise_shape<C>(model: &NoiseModel, qubits: &[usize], context: &C) -> NpResult<()>
566where
567    C: fmt::Display + ?Sized,
568{
569    let event_length = validate_noise_model(model, context)?;
570    match model {
571        NoiseModel::MeasurementBitFlip | NoiseModel::SingleQubitDepolarizing => {
572            if qubits.len() != 1 {
573                return Err(NpError::new(format!(
574                    "{context} requires exactly one qubit target, got {}",
575                    qubits.len()
576                )));
577            }
578        }
579        NoiseModel::TwoQubitDepolarizing => {
580            if qubits.len() != 2 {
581                return Err(NpError::new(format!(
582                    "{context} requires exactly two qubit targets, got {}",
583                    qubits.len()
584                )));
585            }
586        }
587        NoiseModel::BernoulliPauli(_) => {
588            if qubits.len() != event_length {
589                return Err(NpError::new(format!(
590                    "{context} qubit targets and Pauli event must have the same length"
591                )));
592            }
593        }
594        NoiseModel::PauliChannel(_) => {
595            if qubits.len() != event_length {
596                return Err(NpError::new(format!(
597                    "{context} qubit targets and PauliChannel events must have the same length"
598                )));
599            }
600        }
601    }
602    Ok(())
603}
604
605fn validate_noise_model<C>(model: &NoiseModel, context: &C) -> NpResult<usize>
606where
607    C: fmt::Display + ?Sized,
608{
609    match model {
610        NoiseModel::MeasurementBitFlip | NoiseModel::SingleQubitDepolarizing => Ok(1),
611        NoiseModel::TwoQubitDepolarizing => Ok(2),
612        NoiseModel::BernoulliPauli(pauli) => {
613            validate_non_identity_pauli_event(pauli, context)?;
614            Ok(pauli_len(pauli))
615        }
616        NoiseModel::PauliChannel(weights) => validate_pauli_channel_weights(weights, context),
617    }
618}
619
620fn validate_non_identity_pauli_event<C>(pauli: &str, context: &C) -> NpResult<()>
621where
622    C: fmt::Display + ?Sized,
623{
624    if pauli.is_empty() {
625        return Err(NpError::new(format!(
626            "{context} Pauli event must not be empty"
627        )));
628    }
629    validate_pauli_string(pauli, context)?;
630    if pauli.chars().all(|local| local == 'I') {
631        return Err(NpError::new(format!(
632            "{context} Pauli event must be non-identity"
633        )));
634    }
635    Ok(())
636}
637
638pub(crate) fn validate_pauli_channel_weights<C>(
639    weights: &[(String, f64)],
640    context: &C,
641) -> NpResult<usize>
642where
643    C: fmt::Display + ?Sized,
644{
645    if weights.is_empty() {
646        return Err(NpError::new(format!(
647            "{context} PauliChannel requires at least one non-identity event"
648        )));
649    }
650
651    let mut total = 0.0;
652    let mut event_length = None;
653    for (event, weight) in weights {
654        validate_non_identity_pauli_event(event, context)?;
655        if !weight.is_finite() {
656            return Err(NpError::new(format!(
657                "{context} PauliChannel weights must be finite"
658            )));
659        }
660        if *weight < 0.0 {
661            return Err(NpError::new(format!(
662                "{context} PauliChannel weights must be non-negative"
663            )));
664        }
665        match event_length {
666            None => event_length = Some(pauli_len(event)),
667            Some(length) if pauli_len(event) != length => {
668                return Err(NpError::new(format!(
669                    "{context} PauliChannel events must have the same length"
670                )));
671            }
672            _ => {}
673        }
674        total += *weight;
675        if !total.is_finite() {
676            return Err(NpError::new(format!(
677                "{context} PauliChannel total weight must be finite"
678            )));
679        }
680    }
681
682    if total <= 0.0 {
683        return Err(NpError::new(format!(
684            "{context} PauliChannel weights must have positive total weight"
685        )));
686    }
687    Ok(event_length.expect("non-empty PauliChannel has an event length"))
688}
689
690#[inline]
691fn pauli_len(pauli: &str) -> usize {
692    if pauli.is_ascii() {
693        pauli.len()
694    } else {
695        pauli.chars().count()
696    }
697}
698
699/// Event label carried by a detector error edge.
700#[derive(Debug, Clone, PartialEq)]
701pub enum DemEvent {
702    Pauli(String),
703    Bool(bool),
704}
705
706/// One detector error model instruction.
707#[derive(Debug, Clone, PartialEq)]
708pub struct DetectorErrorEdge {
709    pub probability: f64,
710    pub detectors: Vec<i64>,
711    pub observables: Vec<i64>,
712    pub location_id: String,
713    pub event: DemEvent,
714    pub tags: HashMap<String, TagValue>,
715}
716
717impl DetectorErrorEdge {
718    pub fn validate(&self) -> NpResult<()> {
719        if !(0.0..=1.0).contains(&self.probability) {
720            return Err(NpError::new(format!(
721                "DEM edge probability must be in [0, 1], got {}",
722                self.probability
723            )));
724        }
725        Ok(())
726    }
727}
728
729/// Typed detector error model.
730///
731/// This model can be produced by [`crate::DetectorErrorModelGenerator`] or
732/// supplied directly to [`crate::DemHotspotEstimator`].
733#[derive(Debug, Clone, PartialEq)]
734pub struct DetectorErrorModel {
735    pub detectors: Vec<Detector>,
736    pub observables: Vec<LogicalObservable>,
737    pub edges: Vec<DetectorErrorEdge>,
738}
739
740#[derive(Debug, Clone, PartialEq)]
741pub struct DemLocationGroup {
742    pub location_id: String,
743    pub edge_indices: Vec<usize>,
744    pub total_probability: f64,
745}
746
747#[derive(Debug, Clone, PartialEq)]
748pub struct DemBatch {
749    shots: usize,
750    all_mask: Mask,
751    pub detectors: HashMap<i64, Mask>,
752    pub observables: HashMap<i64, Mask>,
753    edge_event_masks: Vec<Mask>,
754    pub loss_mask: Mask,
755    edge_events_recorded: bool,
756    hotspot_layout_identity: Arc<()>,
757}
758
759impl DemBatch {
760    pub(crate) fn new(
761        shots: usize,
762        all_mask: Mask,
763        detectors: HashMap<i64, Mask>,
764        observables: HashMap<i64, Mask>,
765        edge_event_masks: Option<Vec<Mask>>,
766        loss_mask: Mask,
767        hotspot_layout_identity: Arc<()>,
768    ) -> Self {
769        let edge_events_recorded = edge_event_masks.is_some();
770        Self {
771            shots,
772            all_mask,
773            detectors,
774            observables,
775            edge_event_masks: edge_event_masks.unwrap_or_default(),
776            loss_mask,
777            edge_events_recorded,
778            hotspot_layout_identity,
779        }
780    }
781
782    pub fn shots(&self) -> usize {
783        self.shots
784    }
785
786    pub fn all_mask(&self) -> &Mask {
787        &self.all_mask
788    }
789
790    pub fn edge_event_masks(&self) -> &[Mask] {
791        &self.edge_event_masks
792    }
793
794    pub fn records_edge_events(&self) -> bool {
795        self.edge_events_recorded
796    }
797
798    pub(crate) fn matches_hotspot_layout(&self, identity: &Arc<()>) -> bool {
799        Arc::ptr_eq(&self.hotspot_layout_identity, identity)
800    }
801}
802
803#[derive(Debug, Clone, PartialEq, Eq, Hash)]
804pub struct DetectorGraphKey {
805    pub detectors: Vec<i64>,
806    pub observables: Vec<i64>,
807}
808
809#[derive(Debug, Clone, PartialEq)]
810pub struct DetectorGraphEstimate {
811    pub by_detector_edge: HashMap<DetectorGraphKey, f64>,
812    pub signed_by_detector_edge: HashMap<DetectorGraphKey, f64>,
813    pub by_detector: HashMap<i64, f64>,
814    pub signed_by_detector: HashMap<i64, f64>,
815    pub by_observable: HashMap<i64, f64>,
816    pub signed_by_observable: HashMap<i64, f64>,
817    pub by_location: HashMap<String, f64>,
818    pub signed_by_location: HashMap<String, f64>,
819}
820
821#[derive(Debug, Clone, PartialEq)]
822pub struct HotspotEstimate {
823    pub shots: usize,
824    pub mean_loss: f64,
825    pub baseline: f64,
826    pub sensitivities: HashMap<String, f64>,
827    pub hotspots: HashMap<String, f64>,
828    pub by_qubit: HashMap<usize, f64>,
829    pub by_round: HashMap<TagValue, f64>,
830    pub by_gate: HashMap<TagValue, f64>,
831    pub by_operation: HashMap<TagValue, f64>,
832    pub top_locations: Vec<String>,
833}
834
835#[derive(Debug, Clone, PartialEq)]
836pub struct DemHotspotEstimate {
837    pub shots: usize,
838    pub mean_loss: f64,
839    pub baseline: f64,
840    pub edge_sensitivities: Vec<f64>,
841    pub edge_hotspots: Vec<f64>,
842    pub location_sensitivities: HashMap<String, f64>,
843    pub location_hotspots: HashMap<String, f64>,
844    pub by_detector: HashMap<i64, f64>,
845    pub by_round: HashMap<TagValue, f64>,
846    pub by_gate: HashMap<TagValue, f64>,
847    pub by_operation: HashMap<TagValue, f64>,
848    pub detector_graph: DetectorGraphEstimate,
849    pub top_edges: Vec<usize>,
850    pub top_locations: Vec<String>,
851}
852
853#[cfg(test)]
854mod tests {
855    use super::*;
856
857    fn noise_location(id: &str, rate: f64) -> NoiseLocation {
858        NoiseLocation {
859            id: id.to_string(),
860            model: NoiseModel::BernoulliPauli("X".to_string()),
861            rate,
862            qubits: vec![0],
863            tags: HashMap::new(),
864        }
865    }
866
867    #[test]
868    fn noise_models_reject_invalid_pauli_configurations() {
869        let invalid_models = vec![
870            NoiseModel::BernoulliPauli(String::new()),
871            NoiseModel::BernoulliPauli("II".to_string()),
872            NoiseModel::BernoulliPauli("A".to_string()),
873            NoiseModel::PauliChannel(Vec::new()),
874            NoiseModel::PauliChannel(vec![(String::new(), 1.0)]),
875            NoiseModel::PauliChannel(vec![("I".to_string(), 1.0)]),
876            NoiseModel::PauliChannel(vec![("X".to_string(), f64::NAN)]),
877            NoiseModel::PauliChannel(vec![("X".to_string(), f64::INFINITY)]),
878            NoiseModel::PauliChannel(vec![("X".to_string(), f64::NEG_INFINITY)]),
879            NoiseModel::PauliChannel(vec![
880                ("X".to_string(), f64::MAX),
881                ("Z".to_string(), f64::MAX),
882            ]),
883            NoiseModel::PauliChannel(vec![("X".to_string(), -1.0)]),
884            NoiseModel::PauliChannel(vec![("X".to_string(), 0.0)]),
885            NoiseModel::PauliChannel(vec![("X".to_string(), 1.0), ("ZZ".to_string(), 1.0)]),
886        ];
887
888        for model in invalid_models {
889            assert!(
890                model.validate().is_err(),
891                "accepted invalid model {model:?}"
892            );
893        }
894
895        NoiseModel::BernoulliPauli("XI".to_string())
896            .validate()
897            .unwrap();
898        NoiseModel::PauliChannel(vec![("IX".to_string(), 0.0), ("XI".to_string(), 2.0)])
899            .validate()
900            .unwrap();
901    }
902
903    #[test]
904    fn noise_location_rejects_invalid_model_at_zero_rate() {
905        let location = NoiseLocation {
906            id: "bad".to_string(),
907            model: NoiseModel::BernoulliPauli("A".to_string()),
908            rate: 0.0,
909            qubits: vec![0],
910            tags: HashMap::new(),
911        };
912
913        assert!(location.validate().is_err());
914        let circuit = Circuit {
915            n_qubits: 1,
916            operations: vec![Operation::Noise(location)],
917        };
918        assert!(circuit.validate().is_err());
919    }
920
921    #[test]
922    fn circuit_collects_explicit_and_measurement_noise_locations() {
923        let explicit = noise_location("after_h", 0.01);
924        let measurement = noise_location("m0_noise", 0.02);
925        let circuit = Circuit {
926            n_qubits: 1,
927            operations: vec![
928                Operation::H(0),
929                Operation::Noise(explicit.clone()),
930                Operation::Measure {
931                    qubit: 0,
932                    key: Some("m0".to_string()),
933                    basis: "Z".to_string(),
934                    noise: Some(measurement.clone()),
935                },
936            ],
937        };
938
939        let locations = circuit.noise_locations();
940
941        assert_eq!(locations.len(), 2);
942        assert_eq!(locations.get("after_h"), Some(&explicit));
943        assert_eq!(locations.get("m0_noise"), Some(&measurement));
944    }
945
946    #[test]
947    fn circuit_recursively_rejects_out_of_range_operation_targets() {
948        let mut invalid_noise = noise_location("bad_target", 0.1);
949        invalid_noise.qubits = vec![1];
950        let cases = vec![
951            Operation::H(1),
952            Operation::S(1),
953            Operation::SDag(1),
954            Operation::Cx(0, 1),
955            Operation::Cz(0, 1),
956            Operation::Swap(0, 1),
957            Operation::Pauli {
958                qubits: vec![1],
959                pauli: "X".to_string(),
960            },
961            Operation::Noise(invalid_noise.clone()),
962            Operation::Measure {
963                qubit: 1,
964                key: None,
965                basis: "Z".to_string(),
966                noise: None,
967            },
968            Operation::Measure {
969                qubit: 0,
970                key: None,
971                basis: "Z".to_string(),
972                noise: Some(invalid_noise.clone()),
973            },
974            Operation::MeasurePauli {
975                qubits: vec![1],
976                pauli: "Z".to_string(),
977                key: None,
978                noise: None,
979            },
980            Operation::MeasurePauli {
981                qubits: vec![0],
982                pauli: "Z".to_string(),
983                key: None,
984                noise: Some(invalid_noise),
985            },
986            Operation::MeasureReset {
987                qubit: 1,
988                basis: "Z".to_string(),
989            },
990            Operation::Reset {
991                qubit: 1,
992                key: None,
993                basis: "Z".to_string(),
994            },
995        ];
996
997        for operation in cases {
998            let circuit = Circuit {
999                n_qubits: 1,
1000                operations: vec![Operation::Repeat {
1001                    count: 2,
1002                    body: vec![operation],
1003                }],
1004            };
1005            let err = circuit.validate().unwrap_err();
1006            assert!(err.message().contains("targets qubit 1"), "{err}");
1007            assert!(err.message().contains("operation path 0.0"), "{err}");
1008        }
1009    }
1010
1011    #[test]
1012    fn circuit_rejects_duplicate_targets_for_every_multi_target_shape() {
1013        let duplicate_noise = NoiseLocation {
1014            id: "two".to_string(),
1015            model: NoiseModel::TwoQubitDepolarizing,
1016            rate: 0.1,
1017            qubits: vec![0, 0],
1018            tags: HashMap::new(),
1019        };
1020        let cases = vec![
1021            Operation::Cx(0, 0),
1022            Operation::Cz(0, 0),
1023            Operation::Swap(0, 0),
1024            Operation::Pauli {
1025                qubits: vec![0, 0],
1026                pauli: "XZ".to_string(),
1027            },
1028            Operation::MeasurePauli {
1029                qubits: vec![0, 0],
1030                pauli: "ZZ".to_string(),
1031                key: None,
1032                noise: None,
1033            },
1034            Operation::Noise(duplicate_noise),
1035        ];
1036
1037        for operation in cases {
1038            let err = Circuit {
1039                n_qubits: 1,
1040                operations: vec![operation],
1041            }
1042            .validate()
1043            .unwrap_err();
1044            assert!(err.message().contains("duplicate qubit 0"), "{err}");
1045        }
1046    }
1047
1048    #[test]
1049    fn circuit_validates_pauli_width_characters_and_noise_target_arity() {
1050        let invalid_operations = vec![
1051            Operation::Pauli {
1052                qubits: vec![0],
1053                pauli: "XX".to_string(),
1054            },
1055            Operation::MeasurePauli {
1056                qubits: vec![0],
1057                pauli: "Q".to_string(),
1058                key: None,
1059                noise: None,
1060            },
1061            Operation::Noise(NoiseLocation {
1062                id: "single".to_string(),
1063                model: NoiseModel::SingleQubitDepolarizing,
1064                rate: 0.1,
1065                qubits: vec![0, 1],
1066                tags: HashMap::new(),
1067            }),
1068            Operation::Noise(NoiseLocation {
1069                id: "two".to_string(),
1070                model: NoiseModel::TwoQubitDepolarizing,
1071                rate: 0.1,
1072                qubits: vec![0],
1073                tags: HashMap::new(),
1074            }),
1075            Operation::Noise(NoiseLocation {
1076                id: "channel".to_string(),
1077                model: NoiseModel::PauliChannel(vec![("XX".to_string(), 1.0)]),
1078                rate: 0.1,
1079                qubits: vec![0],
1080                tags: HashMap::new(),
1081            }),
1082        ];
1083
1084        for operation in invalid_operations {
1085            assert!(Circuit {
1086                n_qubits: 2,
1087                operations: vec![operation],
1088            }
1089            .validate()
1090            .is_err());
1091        }
1092    }
1093
1094    #[test]
1095    fn circuit_accepts_valid_targets_at_the_upper_boundary() {
1096        let circuit = Circuit {
1097            n_qubits: 2,
1098            operations: vec![
1099                Operation::H(1),
1100                Operation::Cx(0, 1),
1101                Operation::Cz(1, 0),
1102                Operation::Swap(0, 1),
1103                Operation::Pauli {
1104                    qubits: vec![0, 1],
1105                    pauli: "IY".to_string(),
1106                },
1107                Operation::Noise(NoiseLocation {
1108                    id: "two".to_string(),
1109                    model: NoiseModel::TwoQubitDepolarizing,
1110                    rate: 0.1,
1111                    qubits: vec![0, 1],
1112                    tags: HashMap::new(),
1113                }),
1114            ],
1115        };
1116
1117        circuit.validate().unwrap();
1118        Circuit {
1119            n_qubits: 0,
1120            operations: Vec::new(),
1121        }
1122        .validate()
1123        .unwrap();
1124    }
1125
1126    #[test]
1127    fn noise_location_rejects_invalid_rates() {
1128        let invalid = noise_location("bad", 1.5);
1129
1130        let err = invalid.validate().unwrap_err();
1131
1132        assert!(err.message().contains("noise rate must be in [0, 1]"));
1133    }
1134
1135    #[test]
1136    fn detector_error_edge_rejects_invalid_probabilities() {
1137        let edge = DetectorErrorEdge {
1138            probability: -0.1,
1139            detectors: vec![0],
1140            observables: Vec::new(),
1141            location_id: "loc".to_string(),
1142            event: DemEvent::Bool(true),
1143            tags: HashMap::new(),
1144        };
1145
1146        let err = edge.validate().unwrap_err();
1147
1148        assert!(err
1149            .message()
1150            .contains("DEM edge probability must be in [0, 1]"));
1151    }
1152
1153    #[test]
1154    fn logical_observable_requires_matching_pauli_support() {
1155        let observable = LogicalObservable {
1156            id: 0,
1157            measurement_keys: Vec::new(),
1158            pauli_qubits: vec![0, 1],
1159            pauli: "X".to_string(),
1160        };
1161
1162        let err = observable.validate().unwrap_err();
1163
1164        assert!(err
1165            .message()
1166            .contains("pauli_qubits and pauli must have the same length"));
1167    }
1168
1169    #[test]
1170    fn logical_observable_rejects_out_of_range_and_duplicate_targets() {
1171        let out_of_range = LogicalObservable {
1172            id: 4,
1173            measurement_keys: Vec::new(),
1174            pauli_qubits: vec![1],
1175            pauli: "Z".to_string(),
1176        };
1177        let err = out_of_range.validate_for_n_qubits(1).unwrap_err();
1178        assert!(err.message().contains("logical observable 4"));
1179        assert!(err.message().contains("targets qubit 1"));
1180
1181        let duplicate = LogicalObservable {
1182            id: 5,
1183            measurement_keys: Vec::new(),
1184            pauli_qubits: vec![0, 0],
1185            pauli: "XZ".to_string(),
1186        };
1187        let err = duplicate.validate_for_n_qubits(1).unwrap_err();
1188        assert!(err.message().contains("duplicate qubit 0"));
1189    }
1190}