Skip to main content

pymatching_cxx/
lib.rs

1use stim_cxx as _;
2
3#[cxx::bridge]
4mod ffi {
5    #[repr(u8)]
6    enum MergeStrategy {
7        Disallow = 0,
8        Independent = 1,
9        SmallestWeight = 2,
10        KeepOriginal = 3,
11        Replace = 4,
12    }
13
14    struct EdgeInput {
15        fault_ids: Vec<u64>,
16        weight: f64,
17        error_probability: f64,
18    }
19
20    struct DecodeConfig {
21        return_weight: bool,
22        bit_packed_shots: bool,
23        bit_packed_predictions: bool,
24        enable_correlations: bool,
25    }
26
27    #[allow(dead_code)]
28    struct EdgeRecord {
29        node1: u64,
30        node2: u64,
31        fault_ids: Vec<u64>,
32        weight: f64,
33        error_probability: f64,
34        is_boundary: bool,
35    }
36
37    struct DecodeResult {
38        prediction: Vec<u8>,
39        weight: f64,
40        has_weight: bool,
41    }
42
43    struct GapDecodeResult {
44        prediction: Vec<u8>,
45        gaps: Vec<f64>,
46    }
47
48    struct GapBatchDecodeResult {
49        predictions: Vec<u8>,
50        gaps: Vec<f64>,
51        rows: u64,
52        cols: u64,
53    }
54
55    struct BatchDecodeResult {
56        predictions: Vec<u8>,
57        prediction_rows: u64,
58        prediction_cols: u64,
59        weights: Vec<f64>,
60        has_weights: bool,
61    }
62
63    struct Int64Matrix {
64        data: Vec<i64>,
65        rows: u64,
66        cols: u64,
67    }
68
69    struct NoiseResult {
70        errors: Vec<u8>,
71        syndrome: Vec<u8>,
72        has_noise: bool,
73    }
74
75    unsafe extern "C++" {
76        include!("pymatching-cxx/include/pymatching_rs_bridge.h");
77
78        #[namespace = "pymatching_rs"]
79        type SmokeProbe;
80        #[namespace = "pymatching_rs"]
81        type MatchingHandle;
82
83        #[namespace = "pymatching_rs"]
84        fn new_smoke_probe() -> UniquePtr<SmokeProbe>;
85        #[namespace = "pymatching_rs"]
86        fn describe(self: &SmokeProbe) -> String;
87        #[namespace = "pymatching_rs"]
88        fn weighted_checksum(self: &SmokeProbe, values: &[u32]) -> u64;
89        #[namespace = "pymatching_rs"]
90        fn set_global_rng_seed_for_tests(seed: u64);
91        #[namespace = "pymatching_rs"]
92        fn hold_noise_rng_lock_for_tests(duration_ms: u64);
93        #[namespace = "pymatching_rs"]
94        fn is_noise_rng_lock_held_for_tests() -> bool;
95
96        #[namespace = "pymatching_rs"]
97        fn new_matching_handle() -> UniquePtr<MatchingHandle>;
98        #[namespace = "pymatching_rs"]
99        fn new_matching_handle_with_num_nodes(num_nodes: u64) -> UniquePtr<MatchingHandle>;
100        #[namespace = "pymatching_rs"]
101        fn matching_from_detector_error_model_text(
102            dem_text: &str,
103            enable_correlations: bool,
104        ) -> Result<UniquePtr<MatchingHandle>>;
105        #[namespace = "pymatching_rs"]
106        fn matching_add_edge_with_merge_strategy(
107            matching: Pin<&mut MatchingHandle>,
108            node1: u64,
109            node2: u64,
110            edge: &EdgeInput,
111            merge_strategy: MergeStrategy,
112        ) -> Result<()>;
113        #[namespace = "pymatching_rs"]
114        fn matching_add_boundary_edge_with_merge_strategy(
115            matching: Pin<&mut MatchingHandle>,
116            node: u64,
117            edge: &EdgeInput,
118            merge_strategy: MergeStrategy,
119        ) -> Result<()>;
120        #[namespace = "pymatching_rs"]
121        fn matching_set_boundary_nodes(matching: Pin<&mut MatchingHandle>, nodes: &[u64]);
122        #[namespace = "pymatching_rs"]
123        fn matching_ensure_num_fault_ids(
124            matching: Pin<&mut MatchingHandle>,
125            min_num_fault_ids: u64,
126        );
127        #[namespace = "pymatching_rs"]
128        fn matching_has_edge(matching: &MatchingHandle, node1: u64, node2: u64) -> bool;
129        #[namespace = "pymatching_rs"]
130        fn matching_has_boundary_edge(matching: &MatchingHandle, node: u64) -> bool;
131        #[namespace = "pymatching_rs"]
132        fn matching_num_nodes(matching: &MatchingHandle) -> u64;
133        #[namespace = "pymatching_rs"]
134        fn matching_num_edges(matching: &MatchingHandle) -> u64;
135        #[namespace = "pymatching_rs"]
136        fn matching_num_fault_ids(matching: &MatchingHandle) -> u64;
137        #[namespace = "pymatching_rs"]
138        fn matching_num_detectors(matching: &MatchingHandle) -> u64;
139        #[namespace = "pymatching_rs"]
140        fn matching_boundary_nodes(matching: &MatchingHandle) -> Vec<u64>;
141        #[namespace = "pymatching_rs"]
142        fn matching_edges(matching: &MatchingHandle) -> Vec<EdgeRecord>;
143        #[namespace = "pymatching_rs"]
144        fn matching_edge_data(
145            matching: &MatchingHandle,
146            node1: u64,
147            node2: u64,
148        ) -> Result<EdgeRecord>;
149        #[namespace = "pymatching_rs"]
150        fn matching_boundary_edge_data(matching: &MatchingHandle, node: u64) -> Result<EdgeRecord>;
151        #[namespace = "pymatching_rs"]
152        fn matching_decode(matching: &MatchingHandle, syndrome: &[u8]) -> Result<Vec<u8>>;
153        #[namespace = "pymatching_rs"]
154        fn matching_decode_with_config(
155            matching: &MatchingHandle,
156            syndrome: &[u8],
157            config: &DecodeConfig,
158        ) -> Result<DecodeResult>;
159        #[namespace = "pymatching_rs"]
160        fn matching_decode_gap(
161            matching: &MatchingHandle,
162            syndrome: &[u8],
163        ) -> Result<GapDecodeResult>;
164        #[namespace = "pymatching_rs"]
165        fn matching_decode_gap_batch(
166            matching: &MatchingHandle,
167            shots: &[u8],
168            num_rows: u64,
169            num_cols: u64,
170        ) -> Result<GapBatchDecodeResult>;
171        #[namespace = "pymatching_rs"]
172        fn matching_decode_batch(
173            matching: &MatchingHandle,
174            shots: &[u8],
175            num_rows: u64,
176            num_cols: u64,
177            config: &DecodeConfig,
178        ) -> Result<BatchDecodeResult>;
179        #[namespace = "pymatching_rs"]
180        fn matching_decode_to_edges_array(
181            matching: &MatchingHandle,
182            syndrome: &[u8],
183            enable_correlations: bool,
184        ) -> Result<Int64Matrix>;
185        #[namespace = "pymatching_rs"]
186        fn matching_decode_to_matched_dets_array(
187            matching: &MatchingHandle,
188            syndrome: &[u8],
189        ) -> Result<Int64Matrix>;
190        #[namespace = "pymatching_rs"]
191        fn matching_add_noise(matching: &MatchingHandle) -> Result<NoiseResult>;
192        #[namespace = "pymatching_rs"]
193        fn matching_add_noise_with_seed(
194            matching: &MatchingHandle,
195            seed: u64,
196        ) -> Result<NoiseResult>;
197    }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub struct BuildMetadata {
202    pub crate_name: &'static str,
203    pub cxx_standard: &'static str,
204    pub target: &'static str,
205    pub vendor_pymatching_mode: &'static str,
206    pub vendor_pymatching_dir: &'static str,
207}
208
209#[must_use]
210pub fn build_metadata() -> BuildMetadata {
211    BuildMetadata {
212        crate_name: env!("CARGO_PKG_NAME"),
213        cxx_standard: env!("PYMATCHING_RS_CXX_STANDARD"),
214        target: env!("PYMATCHING_RS_TARGET"),
215        vendor_pymatching_mode: env!("PYMATCHING_RS_VENDOR_PYMATCHING_MODE"),
216        vendor_pymatching_dir: env!("PYMATCHING_RS_VENDOR_PYMATCHING_DIR"),
217    }
218}
219
220#[must_use]
221pub fn pinned_pymatching_commit() -> &'static str {
222    env!("PYMATCHING_RS_PINNED_PYMATCHING_COMMIT")
223}
224
225#[doc(hidden)]
226pub fn set_global_rng_seed_for_tests(seed: u64) {
227    ffi::set_global_rng_seed_for_tests(seed);
228}
229
230#[doc(hidden)]
231pub fn hold_noise_rng_lock_for_tests(duration_ms: u64) {
232    ffi::hold_noise_rng_lock_for_tests(duration_ms);
233}
234
235#[doc(hidden)]
236pub fn is_noise_rng_lock_held_for_tests() -> bool {
237    ffi::is_noise_rng_lock_held_for_tests()
238}
239
240#[derive(Debug, Clone, PartialEq)]
241pub struct EdgeInput {
242    pub fault_ids: Vec<u64>,
243    pub weight: f64,
244    pub error_probability: f64,
245}
246
247#[derive(Debug, Clone, PartialEq)]
248pub struct EdgeRecord {
249    pub node1: u64,
250    pub node2: u64,
251    pub fault_ids: Vec<u64>,
252    pub weight: f64,
253    pub error_probability: f64,
254    pub is_boundary: bool,
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct DecodeConfig {
259    pub return_weight: bool,
260    pub bit_packed_shots: bool,
261    pub bit_packed_predictions: bool,
262    pub enable_correlations: bool,
263}
264
265#[derive(Debug, Clone, PartialEq)]
266pub struct DecodeResult {
267    pub prediction: Vec<u8>,
268    pub weight: f64,
269    pub has_weight: bool,
270}
271
272#[derive(Debug, Clone, PartialEq)]
273pub struct GapDecodeResult {
274    pub prediction: Vec<u8>,
275    pub gaps: Vec<f64>,
276}
277
278#[derive(Debug, Clone, PartialEq)]
279pub struct GapBatchDecodeResult {
280    pub predictions: Vec<u8>,
281    pub gaps: Vec<f64>,
282    pub rows: u64,
283    pub cols: u64,
284}
285
286#[derive(Debug, Clone, PartialEq)]
287pub struct BatchDecodeResult {
288    pub predictions: Vec<u8>,
289    pub prediction_rows: u64,
290    pub prediction_cols: u64,
291    pub weights: Vec<f64>,
292    pub has_weights: bool,
293}
294
295#[derive(Debug, Clone, PartialEq)]
296pub struct Int64Matrix {
297    pub data: Vec<i64>,
298    pub rows: u64,
299    pub cols: u64,
300}
301
302#[derive(Debug, Clone, PartialEq)]
303pub struct NoiseResult {
304    pub errors: Vec<u8>,
305    pub syndrome: Vec<u8>,
306    pub has_noise: bool,
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub enum MergeStrategy {
311    Disallow,
312    Independent,
313    SmallestWeight,
314    KeepOriginal,
315    Replace,
316}
317
318pub struct RawMatchingHandle {
319    inner: cxx::UniquePtr<ffi::MatchingHandle>,
320}
321
322fn edge_record_from_ffi(record: ffi::EdgeRecord) -> EdgeRecord {
323    EdgeRecord {
324        node1: record.node1,
325        node2: record.node2,
326        fault_ids: record.fault_ids,
327        weight: record.weight,
328        error_probability: record.error_probability,
329        is_boundary: record.is_boundary,
330    }
331}
332
333fn int64_matrix_from_ffi(matrix: ffi::Int64Matrix) -> Int64Matrix {
334    Int64Matrix {
335        data: matrix.data,
336        rows: matrix.rows,
337        cols: matrix.cols,
338    }
339}
340
341impl DecodeConfig {
342    fn into_ffi(self) -> ffi::DecodeConfig {
343        ffi::DecodeConfig {
344            return_weight: self.return_weight,
345            bit_packed_shots: self.bit_packed_shots,
346            bit_packed_predictions: self.bit_packed_predictions,
347            enable_correlations: self.enable_correlations,
348        }
349    }
350}
351
352impl Default for RawMatchingHandle {
353    fn default() -> Self {
354        Self {
355            inner: ffi::new_matching_handle(),
356        }
357    }
358}
359
360impl RawMatchingHandle {
361    fn handle(&self) -> &ffi::MatchingHandle {
362        self.inner
363            .as_ref()
364            .expect("matching handle bridge should always construct")
365    }
366
367    #[must_use]
368    pub fn with_num_nodes(num_nodes: usize) -> Self {
369        Self {
370            inner: ffi::new_matching_handle_with_num_nodes(num_nodes as u64),
371        }
372    }
373
374    pub fn from_detector_error_model_text(
375        dem_text: &str,
376        enable_correlations: bool,
377    ) -> std::result::Result<Self, cxx::Exception> {
378        Ok(Self {
379            inner: ffi::matching_from_detector_error_model_text(dem_text, enable_correlations)?,
380        })
381    }
382
383    pub fn add_edge(
384        &mut self,
385        node1: usize,
386        node2: usize,
387        edge: &EdgeInput,
388    ) -> std::result::Result<(), cxx::Exception> {
389        self.add_edge_with_merge_strategy(node1, node2, edge, MergeStrategy::Disallow)
390    }
391
392    pub fn add_edge_with_merge_strategy(
393        &mut self,
394        node1: usize,
395        node2: usize,
396        edge: &EdgeInput,
397        merge_strategy: MergeStrategy,
398    ) -> std::result::Result<(), cxx::Exception> {
399        ffi::matching_add_edge_with_merge_strategy(
400            self.inner.pin_mut(),
401            node1 as u64,
402            node2 as u64,
403            &ffi::EdgeInput {
404                fault_ids: edge.fault_ids.clone(),
405                weight: edge.weight,
406                error_probability: edge.error_probability,
407            },
408            merge_strategy.into_ffi(),
409        )
410    }
411
412    pub fn add_boundary_edge(
413        &mut self,
414        node: usize,
415        edge: &EdgeInput,
416    ) -> std::result::Result<(), cxx::Exception> {
417        self.add_boundary_edge_with_merge_strategy(node, edge, MergeStrategy::Disallow)
418    }
419
420    pub fn add_boundary_edge_with_merge_strategy(
421        &mut self,
422        node: usize,
423        edge: &EdgeInput,
424        merge_strategy: MergeStrategy,
425    ) -> std::result::Result<(), cxx::Exception> {
426        ffi::matching_add_boundary_edge_with_merge_strategy(
427            self.inner.pin_mut(),
428            node as u64,
429            &ffi::EdgeInput {
430                fault_ids: edge.fault_ids.clone(),
431                weight: edge.weight,
432                error_probability: edge.error_probability,
433            },
434            merge_strategy.into_ffi(),
435        )
436    }
437
438    pub fn set_boundary_nodes(&mut self, nodes: &[usize]) {
439        let nodes: Vec<u64> = nodes.iter().map(|&node| node as u64).collect();
440        ffi::matching_set_boundary_nodes(self.inner.pin_mut(), &nodes);
441    }
442
443    pub fn ensure_num_fault_ids(&mut self, min_num_fault_ids: usize) {
444        ffi::matching_ensure_num_fault_ids(self.inner.pin_mut(), min_num_fault_ids as u64);
445    }
446
447    #[must_use]
448    pub fn has_edge(&self, node1: usize, node2: usize) -> bool {
449        ffi::matching_has_edge(self.handle(), node1 as u64, node2 as u64)
450    }
451
452    #[must_use]
453    pub fn has_boundary_edge(&self, node: usize) -> bool {
454        ffi::matching_has_boundary_edge(self.handle(), node as u64)
455    }
456
457    #[must_use]
458    pub fn num_nodes(&self) -> usize {
459        ffi::matching_num_nodes(self.handle()) as usize
460    }
461
462    #[must_use]
463    pub fn num_edges(&self) -> usize {
464        ffi::matching_num_edges(self.handle()) as usize
465    }
466
467    #[must_use]
468    pub fn num_fault_ids(&self) -> usize {
469        ffi::matching_num_fault_ids(self.handle()) as usize
470    }
471
472    #[must_use]
473    pub fn num_detectors(&self) -> usize {
474        ffi::matching_num_detectors(self.handle()) as usize
475    }
476
477    #[must_use]
478    pub fn boundary_nodes(&self) -> Vec<usize> {
479        ffi::matching_boundary_nodes(self.handle())
480            .into_iter()
481            .map(|node| node as usize)
482            .collect()
483    }
484
485    #[must_use]
486    pub fn edges(&self) -> Vec<EdgeRecord> {
487        ffi::matching_edges(self.handle())
488            .into_iter()
489            .map(edge_record_from_ffi)
490            .collect()
491    }
492
493    pub fn edge_data(
494        &self,
495        node1: usize,
496        node2: usize,
497    ) -> std::result::Result<EdgeRecord, cxx::Exception> {
498        ffi::matching_edge_data(self.handle(), node1 as u64, node2 as u64).map(edge_record_from_ffi)
499    }
500
501    pub fn boundary_edge_data(
502        &self,
503        node: usize,
504    ) -> std::result::Result<EdgeRecord, cxx::Exception> {
505        ffi::matching_boundary_edge_data(self.handle(), node as u64).map(edge_record_from_ffi)
506    }
507
508    pub fn decode(&self, syndrome: &[u8]) -> std::result::Result<Vec<u8>, cxx::Exception> {
509        ffi::matching_decode(self.handle(), syndrome)
510    }
511
512    pub fn decode_with_config(
513        &self,
514        syndrome: &[u8],
515        config: DecodeConfig,
516    ) -> std::result::Result<DecodeResult, cxx::Exception> {
517        ffi::matching_decode_with_config(self.handle(), syndrome, &config.into_ffi()).map(
518            |result| DecodeResult {
519                prediction: result.prediction,
520                weight: result.weight,
521                has_weight: result.has_weight,
522            },
523        )
524    }
525
526    pub fn decode_gap(
527        &self,
528        syndrome: &[u8],
529    ) -> std::result::Result<GapDecodeResult, cxx::Exception> {
530        ffi::matching_decode_gap(self.handle(), syndrome).map(|result| GapDecodeResult {
531            prediction: result.prediction,
532            gaps: result.gaps,
533        })
534    }
535
536    pub fn decode_gap_batch(
537        &self,
538        shots: &[u8],
539        num_rows: usize,
540        num_cols: usize,
541    ) -> std::result::Result<GapBatchDecodeResult, cxx::Exception> {
542        ffi::matching_decode_gap_batch(self.handle(), shots, num_rows as u64, num_cols as u64).map(
543            |result| GapBatchDecodeResult {
544                predictions: result.predictions,
545                gaps: result.gaps,
546                rows: result.rows,
547                cols: result.cols,
548            },
549        )
550    }
551
552    pub fn decode_batch(
553        &self,
554        shots: &[u8],
555        num_rows: usize,
556        num_cols: usize,
557        config: DecodeConfig,
558    ) -> std::result::Result<BatchDecodeResult, cxx::Exception> {
559        ffi::matching_decode_batch(
560            self.handle(),
561            shots,
562            num_rows as u64,
563            num_cols as u64,
564            &config.into_ffi(),
565        )
566        .map(|result| BatchDecodeResult {
567            predictions: result.predictions,
568            prediction_rows: result.prediction_rows,
569            prediction_cols: result.prediction_cols,
570            weights: result.weights,
571            has_weights: result.has_weights,
572        })
573    }
574
575    pub fn decode_to_edges_array(
576        &self,
577        syndrome: &[u8],
578        enable_correlations: bool,
579    ) -> std::result::Result<Int64Matrix, cxx::Exception> {
580        ffi::matching_decode_to_edges_array(self.handle(), syndrome, enable_correlations)
581            .map(int64_matrix_from_ffi)
582    }
583
584    pub fn decode_to_matched_dets_array(
585        &self,
586        syndrome: &[u8],
587    ) -> std::result::Result<Int64Matrix, cxx::Exception> {
588        ffi::matching_decode_to_matched_dets_array(self.handle(), syndrome)
589            .map(int64_matrix_from_ffi)
590    }
591
592    pub fn add_noise(&self, seed: Option<u64>) -> std::result::Result<NoiseResult, cxx::Exception> {
593        let result = match seed {
594            Some(seed) => ffi::matching_add_noise_with_seed(self.handle(), seed),
595            None => ffi::matching_add_noise(self.handle()),
596        }?;
597        Ok(NoiseResult {
598            errors: result.errors,
599            syndrome: result.syndrome,
600            has_noise: result.has_noise,
601        })
602    }
603}
604
605/// Bridge-backed probe used by the Linux smoke test.
606#[doc(hidden)]
607pub struct SmokeProbe {
608    inner: cxx::UniquePtr<ffi::SmokeProbe>,
609}
610
611impl SmokeProbe {
612    #[must_use]
613    pub fn new() -> Self {
614        Self {
615            inner: ffi::new_smoke_probe(),
616        }
617    }
618
619    #[must_use]
620    pub fn describe(&self) -> String {
621        self.inner
622            .as_ref()
623            .expect("smoke probe bridge should always construct")
624            .describe()
625    }
626
627    #[must_use]
628    pub fn weighted_checksum(&self, values: &[u32]) -> u64 {
629        self.inner
630            .as_ref()
631            .expect("smoke probe bridge should always construct")
632            .weighted_checksum(values)
633    }
634}
635
636impl Default for SmokeProbe {
637    fn default() -> Self {
638        Self::new()
639    }
640}
641
642impl MergeStrategy {
643    fn into_ffi(self) -> ffi::MergeStrategy {
644        match self {
645            Self::Disallow => ffi::MergeStrategy::Disallow,
646            Self::Independent => ffi::MergeStrategy::Independent,
647            Self::SmallestWeight => ffi::MergeStrategy::SmallestWeight,
648            Self::KeepOriginal => ffi::MergeStrategy::KeepOriginal,
649            Self::Replace => ffi::MergeStrategy::Replace,
650        }
651    }
652}