faultscope-core 0.2.12

Python-independent circuit, DEM, sampling, and decoder primitives for FaultScope
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};

mod assembly;
mod bitset;
mod event_plan;
mod fallback_path;
mod indexed_parity;
mod measurement_plan;
mod product_path;

use assembly::{
    assemble_dem_edge_refs, coalesce_sibling_dem_edge_refs, materialize_generated_dem_edges,
    DemFlipMasks,
};
use event_plan::collect_dem_event_plan_from_program_with_options;
pub use event_plan::{
    collect_dem_event_plan, collect_dem_event_plan_with_options, DemEventPlan, DemGenerationOptions,
};
use fallback_path::generate_fallback_dem_flip_masks_from_plan;
use measurement_plan::{
    compile_dem_measurement_plan, compile_dem_measurement_plan_with_optional_declarations,
    DemMeasurementPlan,
};
use product_path::{
    generate_indexed_product_dem_flip_masks_from_plan, supports_product_reference_fast_path,
};

use crate::dem_canonical::parity_support_len;
use crate::dem_problem::{compile_graphlike_problem_from_edge_views, GraphlikeSourceEdge};
use crate::dem_sampling::{DemHotspotEstimator, DemProgramEdge, DemProgramEdgeMetadata};
use crate::program::{ExpandedOperation, ExpandedProgram, ExpansionMode};
use crate::{
    Circuit, Detector, DetectorErrorEdge, DetectorErrorModel, GraphlikeDecodingProblem,
    LogicalObservable, NpError, NpResult, Operation,
};

/// Detector error model generator based on single-error propagation.
///
/// The generator is pure Rust core logic. It can infer detector and observable
/// declarations from circuit operations or use declarations supplied by the
/// caller.
#[derive(Debug, Clone, PartialEq)]
pub struct DetectorErrorModelGenerator {
    pub circuit: Arc<Circuit>,
    pub detectors: Vec<Detector>,
    pub observables: Vec<LogicalObservable>,
    event_plan: Arc<DemEventPlan>,
    measurement_plan: DemMeasurementPlan,
}

/// A circuit whose targets have been validated and whose DEM event plan is
/// guaranteed to be derived from that exact circuit.
///
/// This type is intentionally opaque.  It lets trusted adapters carry the
/// validation result across API boundaries without allowing callers to pair a
/// circuit with an unrelated event plan.
#[doc(hidden)]
#[derive(Debug)]
pub struct ValidatedDemCircuit {
    circuit: Arc<Circuit>,
    event_plan: OnceLock<Arc<DemEventPlan>>,
}

impl ValidatedDemCircuit {
    /// Validate a circuit once and retain it for DEM compilation.
    #[doc(hidden)]
    pub fn new(circuit: Circuit) -> NpResult<Self> {
        circuit.validate()?;
        Ok(Self {
            circuit: Arc::new(circuit),
            event_plan: OnceLock::new(),
        })
    }

    /// Borrow the validated circuit.
    #[doc(hidden)]
    pub fn circuit(&self) -> &Circuit {
        &self.circuit
    }

    /// Return shared ownership of the validated circuit.
    fn shared_circuit(&self) -> Arc<Circuit> {
        Arc::clone(&self.circuit)
    }

    /// Return the event plan derived from this circuit, compiling it once.
    #[doc(hidden)]
    pub fn event_plan(&self) -> NpResult<Arc<DemEventPlan>> {
        if let Some(event_plan) = self.event_plan.get() {
            return Ok(Arc::clone(event_plan));
        }

        let event_plan = Arc::new(collect_dem_event_plan(&self.circuit.operations)?);
        let _ = self.event_plan.set(event_plan);
        Ok(Arc::clone(
            self.event_plan
                .get()
                .expect("DEM event plan must be initialized after set"),
        ))
    }

    /// Return an event plan compiled with explicit disjoint-channel options.
    #[doc(hidden)]
    pub fn event_plan_with_options(
        &self,
        options: DemGenerationOptions,
    ) -> NpResult<Arc<DemEventPlan>> {
        if options == DemGenerationOptions::default() {
            return self.event_plan();
        }
        Ok(Arc::new(collect_dem_event_plan_with_options(
            &self.circuit.operations,
            options,
        )?))
    }
}

impl DemEventPlan {
    /// Materialize public detector declarations from the indexed IR.
    #[doc(hidden)]
    pub fn inferred_detectors(&self) -> Vec<Detector> {
        detectors_from_program(&self.program)
    }

    /// Materialize public observable declarations from the indexed IR.
    #[doc(hidden)]
    pub fn inferred_observables(&self) -> Vec<LogicalObservable> {
        observables_from_program(&self.program)
    }
}

impl DetectorErrorModelGenerator {
    /// Create a generator for `circuit`.
    ///
    /// If `detectors` or `observables` are `None`, declarations are inferred
    /// from `Operation::Detector` and `Operation::ObservableInclude` entries in
    /// the circuit.
    pub fn new(
        circuit: Circuit,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
    ) -> NpResult<Self> {
        Self::new_with_options(
            circuit,
            detectors,
            observables,
            DemGenerationOptions::default(),
        )
    }

    /// Create a generator with explicit disjoint-channel handling options.
    pub fn new_with_options(
        circuit: Circuit,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
        options: DemGenerationOptions,
    ) -> NpResult<Self> {
        circuit.validate()?;
        let (circuit, program) = crate::program::expand_circuit(&circuit)?;
        let measurement_plan = compile_dem_measurement_plan_with_optional_declarations(
            &program,
            detectors.as_deref(),
            observables.as_deref(),
        )?;
        let detectors = detectors.unwrap_or_else(|| detectors_from_program(&program));
        let observables = observables.unwrap_or_else(|| observables_from_program(&program));
        validate_detector_ids(&detectors)?;
        validate_observable_ids(&observables)?;
        validate_observables_for_n_qubits(circuit.n_qubits, &observables)?;
        let event_plan = collect_dem_event_plan_from_program_with_options(program, options)?;
        Ok(Self {
            circuit: Arc::new(circuit),
            detectors,
            observables,
            event_plan: Arc::new(event_plan),
            measurement_plan,
        })
    }

    /// Create a generator using a precompiled event plan for this circuit.
    pub fn new_with_event_plan(
        circuit: Circuit,
        detectors: Vec<Detector>,
        observables: Vec<LogicalObservable>,
        event_plan: DemEventPlan,
    ) -> NpResult<Self> {
        Self::new_with_shared_event_plan(
            Arc::new(circuit),
            detectors,
            observables,
            Arc::new(event_plan),
        )
    }

    /// Create a generator using shared circuit and event-plan ownership.
    pub fn new_with_shared_event_plan(
        circuit: Arc<Circuit>,
        detectors: Vec<Detector>,
        observables: Vec<LogicalObservable>,
        event_plan: Arc<DemEventPlan>,
    ) -> NpResult<Self> {
        Self::new_with_shared_event_plan_options(
            circuit,
            Some(detectors),
            Some(observables),
            event_plan,
        )
    }

    /// Create a generator from a shared integer event plan, inferring omitted
    /// declarations directly from that plan without a string round trip.
    #[doc(hidden)]
    pub fn new_with_shared_event_plan_options(
        circuit: Arc<Circuit>,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
        event_plan: Arc<DemEventPlan>,
    ) -> NpResult<Self> {
        circuit.validate()?;
        crate::program::validate_expanded_program_targets(circuit.n_qubits, &event_plan.program)?;
        Self::new_with_prevalidated_shared_event_plan_options(
            circuit,
            detectors,
            observables,
            event_plan,
        )
    }

    /// Create a generator from a circuit carrying proof that validation and
    /// event-plan binding have already been performed.
    #[doc(hidden)]
    pub fn new_with_validated_dem_circuit_options(
        circuit: &ValidatedDemCircuit,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
    ) -> NpResult<Self> {
        Self::new_with_validated_dem_circuit_generation_options(
            circuit,
            detectors,
            observables,
            DemGenerationOptions::default(),
        )
    }

    /// Create a generator from a validated circuit with explicit
    /// disjoint-channel handling options.
    #[doc(hidden)]
    pub fn new_with_validated_dem_circuit_generation_options(
        circuit: &ValidatedDemCircuit,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
        options: DemGenerationOptions,
    ) -> NpResult<Self> {
        let event_plan = circuit.event_plan_with_options(options)?;
        Self::new_with_prevalidated_shared_event_plan_options(
            circuit.shared_circuit(),
            detectors,
            observables,
            event_plan,
        )
    }

    fn new_with_prevalidated_shared_event_plan_options(
        circuit: Arc<Circuit>,
        detectors: Option<Vec<Detector>>,
        observables: Option<Vec<LogicalObservable>>,
        event_plan: Arc<DemEventPlan>,
    ) -> NpResult<Self> {
        let measurement_plan = compile_dem_measurement_plan_with_optional_declarations(
            &event_plan.program,
            detectors.as_deref(),
            observables.as_deref(),
        )?;
        let detectors = detectors.unwrap_or_else(|| detectors_from_program(&event_plan.program));
        let observables =
            observables.unwrap_or_else(|| observables_from_program(&event_plan.program));
        validate_detector_ids(&detectors)?;
        validate_observable_ids(&observables)?;
        validate_observables_for_n_qubits(circuit.n_qubits, &observables)?;
        Ok(Self {
            circuit,
            detectors,
            observables,
            event_plan,
            measurement_plan,
        })
    }

    /// Generate a typed detector error model.
    pub fn generate(&self) -> NpResult<DetectorErrorModel> {
        Ok(self.generate_lazy()?.materialize())
    }

    /// Generate detector/observable edge structure while deferring metadata clones.
    pub fn generate_lazy(&self) -> NpResult<LazyDetectorErrorModel> {
        let edges = self.generate_edge_refs()?;
        let (edges, edge_overrides) = coalesce_sibling_dem_edge_refs(&self.event_plan, edges);
        Ok(LazyDetectorErrorModel {
            detectors: self.detectors.clone(),
            observables: self.observables.clone(),
            event_plan: self.event_plan.clone(),
            edges,
            edge_overrides,
        })
    }

    fn generate_edge_refs(&self) -> NpResult<Vec<GeneratedDemEdgeRef>> {
        // Constructors validate the circuit, compiled plan, and observables.
        // Keep repeated generation scan-free so validation remains a boundary
        // cost instead of scaling with every generated model.
        generate_dem_edge_refs_from_compiled_plan(
            self.circuit.n_qubits,
            &self.event_plan.program,
            &self.measurement_plan,
            &self.event_plan,
        )
    }
}

pub fn generate_dem_edges(
    n_qubits: usize,
    operations: &[Operation],
    detectors: &[Detector],
    observables: &[LogicalObservable],
) -> NpResult<Vec<DetectorErrorEdge>> {
    generate_dem_edges_with_options(
        n_qubits,
        operations,
        detectors,
        observables,
        DemGenerationOptions::default(),
    )
}

/// Generate DEM edges with explicit disjoint-channel handling options.
pub fn generate_dem_edges_with_options(
    n_qubits: usize,
    operations: &[Operation],
    detectors: &[Detector],
    observables: &[LogicalObservable],
    options: DemGenerationOptions,
) -> NpResult<Vec<DetectorErrorEdge>> {
    crate::model::validate_operations(n_qubits, operations)?;
    validate_observables_for_n_qubits(n_qubits, observables)?;
    let program = crate::program::expand_operations(operations, ExpansionMode::Dem)?;
    let event_plan = collect_dem_event_plan_from_program_with_options(program, options)?;
    let measurement_plan =
        compile_dem_measurement_plan(&event_plan.program, detectors, observables)?;
    generate_dem_edges_from_compiled_plan(
        n_qubits,
        &event_plan.program,
        &measurement_plan,
        &event_plan,
    )
}

/// Generate DEM edges from a precompiled integer event plan.
pub fn generate_dem_edges_from_event_plan(
    n_qubits: usize,
    detectors: &[Detector],
    observables: &[LogicalObservable],
    event_plan: &DemEventPlan,
) -> NpResult<Vec<DetectorErrorEdge>> {
    crate::program::validate_expanded_program_targets(n_qubits, &event_plan.program)?;
    validate_observables_for_n_qubits(n_qubits, observables)?;
    let measurement_plan =
        compile_dem_measurement_plan(&event_plan.program, detectors, observables)?;
    generate_dem_edges_from_compiled_plan(
        n_qubits,
        &event_plan.program,
        &measurement_plan,
        event_plan,
    )
}

fn generate_dem_edges_from_compiled_plan(
    n_qubits: usize,
    program: &ExpandedProgram,
    measurement_plan: &DemMeasurementPlan,
    event_plan: &DemEventPlan,
) -> NpResult<Vec<DetectorErrorEdge>> {
    let edges =
        generate_dem_edge_refs_from_compiled_plan(n_qubits, program, measurement_plan, event_plan)?;
    let (edges, edge_overrides) = coalesce_sibling_dem_edge_refs(event_plan, edges);
    Ok(materialize_generated_dem_edges(
        event_plan,
        edges,
        &edge_overrides,
    ))
}

fn generate_dem_edge_refs_from_compiled_plan(
    n_qubits: usize,
    program: &ExpandedProgram,
    measurement_plan: &DemMeasurementPlan,
    event_plan: &DemEventPlan,
) -> NpResult<Vec<GeneratedDemEdgeRef>> {
    let flip_masks = generate_dem_flip_masks_from_compiled_plan(
        n_qubits,
        program,
        measurement_plan,
        event_plan,
    )?;
    Ok(assemble_dem_edge_refs(
        event_plan.fault_events.len(),
        flip_masks,
    ))
}

fn generate_dem_flip_masks_from_compiled_plan(
    n_qubits: usize,
    program: &ExpandedProgram,
    measurement_plan: &DemMeasurementPlan,
    event_plan: &DemEventPlan,
) -> NpResult<DemFlipMasks> {
    if supports_product_reference_fast_path(n_qubits, &program.operations) {
        return generate_indexed_product_dem_flip_masks_from_plan(
            n_qubits,
            &program.operations,
            measurement_plan,
            event_plan,
        );
    }
    generate_fallback_dem_flip_masks_from_plan(
        n_qubits,
        &program.operations,
        measurement_plan,
        event_plan,
    )
}

/// Infer detector declarations from detector operations in a circuit.
pub fn detectors_from_circuit(circuit: &Circuit) -> Vec<Detector> {
    let program = match crate::program::expand_operations(&circuit.operations, ExpansionMode::Dem) {
        Ok(program) => program,
        Err(_) => return Vec::new(),
    };
    detectors_from_program(&program)
}

fn detectors_from_program(program: &ExpandedProgram) -> Vec<Detector> {
    let mut detectors = Vec::new();
    let mut detector_coords = program.detector_coords.iter();
    for operation in &program.operations {
        let ExpandedOperation::Detector {
            detector_id,
            measurement_ids,
        } = operation
        else {
            continue;
        };
        detectors.push(Detector {
            id: *detector_id,
            measurement_keys: measurement_ids
                .iter()
                .map(|measurement_id| program.measurement_keys[*measurement_id].clone())
                .collect(),
            coords: detector_coords.next().cloned().unwrap_or_default(),
        });
    }
    detectors
}

/// Infer logical observable declarations from observable include operations.
pub fn observables_from_circuit(circuit: &Circuit) -> Vec<LogicalObservable> {
    let program = match crate::program::expand_operations(&circuit.operations, ExpansionMode::Dem) {
        Ok(program) => program,
        Err(_) => return Vec::new(),
    };
    observables_from_program(&program)
}

fn observables_from_program(program: &ExpandedProgram) -> Vec<LogicalObservable> {
    let mut measurement_ids_by_observable = HashMap::<i64, Vec<usize>>::new();
    for operation in &program.operations {
        let ExpandedOperation::ObservableInclude {
            observable_id,
            measurement_ids,
        } = operation
        else {
            continue;
        };
        measurement_ids_by_observable
            .entry(*observable_id)
            .or_default()
            .extend(measurement_ids);
    }
    let mut observable_ids = measurement_ids_by_observable
        .keys()
        .copied()
        .collect::<Vec<_>>();
    observable_ids.sort_unstable();
    observable_ids
        .into_iter()
        .map(|observable_id| LogicalObservable {
            id: observable_id,
            measurement_keys: measurement_ids_by_observable
                .remove(&observable_id)
                .unwrap_or_default()
                .into_iter()
                .map(|measurement_id| program.measurement_keys[measurement_id].clone())
                .collect(),
            pauli_qubits: Vec::new(),
            pauli: String::new(),
        })
        .collect()
}

fn validate_detector_ids(detectors: &[Detector]) -> NpResult<()> {
    let mut seen = HashSet::new();
    for detector in detectors {
        if !seen.insert(detector.id) {
            return Err(NpError::new("detector ids must be unique"));
        }
    }
    Ok(())
}

fn validate_observable_ids(observables: &[LogicalObservable]) -> NpResult<()> {
    let mut seen = HashSet::new();
    for observable in observables {
        if !seen.insert(observable.id) {
            return Err(NpError::new("logical observable ids must be unique"));
        }
    }
    Ok(())
}

fn validate_observables_for_n_qubits(
    n_qubits: usize,
    observables: &[LogicalObservable],
) -> NpResult<()> {
    for observable in observables {
        observable.validate_for_n_qubits(n_qubits)?;
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq)]
struct GeneratedDemEdgeRef {
    event_index: usize,
    detectors: Vec<i64>,
    observables: Vec<i64>,
}

#[derive(Debug, Clone, PartialEq)]
struct GeneratedDemEdgeOverride {
    probability: f64,
    event: crate::DemEvent,
}

#[derive(Debug, Clone, PartialEq)]
pub struct LazyDetectorErrorModel {
    pub detectors: Vec<Detector>,
    pub observables: Vec<LogicalObservable>,
    pub event_plan: Arc<DemEventPlan>,
    edges: Vec<GeneratedDemEdgeRef>,
    edge_overrides: HashMap<usize, GeneratedDemEdgeOverride>,
}

impl LazyDetectorErrorModel {
    /// Test whether parity-reduced lazy DEM edges satisfy graphlike constraints.
    pub fn is_graphlike(&self) -> bool {
        self.edges.iter().all(|edge| {
            let detector_count = parity_support_len(&edge.detectors);
            detector_count <= 2
                && (detector_count != 0 || parity_support_len(&edge.observables) == 0)
        })
    }

    /// Compile directly into the compact graphlike representation without
    /// materializing location labels, events, or tag dictionaries.
    pub fn compile_graphlike_problem(&self) -> NpResult<GraphlikeDecodingProblem> {
        compile_graphlike_problem_from_edge_views(
            &self.detectors,
            &self.observables,
            self.edges.len(),
            || {
                self.edges
                    .iter()
                    .enumerate()
                    .map(|(edge_index, edge)| GraphlikeSourceEdge {
                        probability: self
                            .edge_overrides
                            .get(&edge_index)
                            .map(|override_| override_.probability)
                            .unwrap_or(self.event_plan.fault_events[edge.event_index].probability),
                        detectors: &edge.detectors,
                        observables: &edge.observables,
                        original_edge_index: edge_index,
                    })
            },
        )
    }

    /// Consume a lazy DEM into the metadata-free sampling representation.
    #[doc(hidden)]
    pub fn into_sampling_estimator(self) -> DemHotspotEstimator {
        let Self {
            detectors,
            observables,
            event_plan,
            edges,
            edge_overrides,
        } = self;
        let program_edges = edges
            .into_iter()
            .enumerate()
            .map(|(edge_index, edge)| DemProgramEdge {
                probability: edge_overrides
                    .get(&edge_index)
                    .map(|override_| override_.probability)
                    .unwrap_or(event_plan.fault_events[edge.event_index].probability),
                detectors: edge.detectors,
                observables: edge.observables,
            })
            .collect();
        DemHotspotEstimator::from_compact_sampling_parts(
            detectors.into_iter().map(|detector| detector.id).collect(),
            observables
                .into_iter()
                .map(|observable| observable.id)
                .collect(),
            program_edges,
        )
    }

    /// Compile the lazy integer DEM directly into a sampler without
    /// materializing location labels or tag dictionaries.
    pub fn compile_hotspot_estimator(&self) -> DemHotspotEstimator {
        let mut edges = Vec::with_capacity(self.edges.len());
        let mut edge_metadata = Vec::with_capacity(self.edges.len());
        for (edge_index, edge) in self.edges.iter().enumerate() {
            let event = &self.event_plan.fault_events[edge.event_index];
            let location = &self.event_plan.program.noise_locations[event.noise_id];
            edges.push(DemProgramEdge {
                probability: self
                    .edge_overrides
                    .get(&edge_index)
                    .map(|override_| override_.probability)
                    .unwrap_or(event.probability),
                detectors: edge.detectors.clone(),
                observables: edge.observables.clone(),
            });
            edge_metadata.push(DemProgramEdgeMetadata {
                location_id: location.location_id,
                event: self
                    .edge_overrides
                    .get(&edge_index)
                    .map(|override_| override_.event.clone())
                    .unwrap_or_else(|| event.event.clone()),
            });
        }
        DemHotspotEstimator::from_program_parts(
            self.detectors.iter().map(|detector| detector.id).collect(),
            self.observables
                .iter()
                .map(|observable| observable.id)
                .collect(),
            edges,
            edge_metadata,
            self.event_plan.program.location_catalog.clone(),
        )
    }

    pub fn materialize(&self) -> DetectorErrorModel {
        DetectorErrorModel {
            detectors: self.detectors.clone(),
            observables: self.observables.clone(),
            edges: self
                .edges
                .iter()
                .enumerate()
                .map(|(edge_index, edge)| {
                    let event = &self.event_plan.fault_events[edge.event_index];
                    let location = &self.event_plan.program.noise_locations[event.noise_id];
                    let catalog = &self.event_plan.program.location_catalog;
                    DetectorErrorEdge {
                        probability: self
                            .edge_overrides
                            .get(&edge_index)
                            .map(|override_| override_.probability)
                            .unwrap_or(event.probability),
                        detectors: edge.detectors.clone(),
                        observables: edge.observables.clone(),
                        location_id: catalog.label(location.location_id).to_string(),
                        event: self
                            .edge_overrides
                            .get(&edge_index)
                            .map(|override_| override_.event.clone())
                            .unwrap_or_else(|| event.event.clone()),
                        tags: catalog.tags(location.location_id).clone(),
                    }
                })
                .collect(),
        }
    }
}

#[cfg(test)]
mod tests;