pymatching 0.1.0

Safe Rust bindings for the PyMatching quantum error-correction decoder
Documentation
use std::{fs, path::Path};

use pymatching_cxx::RawMatchingHandle;

use crate::{Matching, MatchingError, Result};

fn stim_error_to_matching_error(error: stim::StimError) -> MatchingError {
    MatchingError::Upstream(error.to_string())
}

fn from_detector_error_model_text(
    detector_error_model_text: &str,
    enable_correlations: bool,
) -> Result<Matching> {
    let raw = RawMatchingHandle::from_detector_error_model_text(
        detector_error_model_text,
        enable_correlations,
    )
    .map_err(|error| MatchingError::Upstream(error.to_string()))?;
    Ok(Matching::from_raw_handle(raw))
}

fn detector_error_model_from_circuit(
    circuit: &stim::Circuit,
) -> std::result::Result<stim::DetectorErrorModel, stim::StimError> {
    circuit.detector_error_model_with_options(true, true, false, 0.0, false, false)
}

impl Matching {
    /// Constructs a matching graph from a Stim detector error model.
    ///
    /// Each detector becomes a graph node. Graphlike error mechanisms that
    /// flip one or two detectors become boundary or ordinary edges, and their
    /// logical-observable indices become edge fault ids. Larger errors are used
    /// only when the model supplies a decomposition into graphlike components;
    /// undecomposed non-graphlike errors are ignored. Parallel mechanisms are
    /// merged as independent errors.
    ///
    /// Set `enable_correlations` at construction time to retain decomposition
    /// data for native two-pass correlated matching. It may then be selected by
    /// [`DecodeOptions::with_enable_correlations`](crate::DecodeOptions::with_enable_correlations).
    /// GAP decoding automatically follows this construction setting.
    ///
    /// ```
    /// use pymatching::Matching;
    ///
    /// let dem: stim::DetectorErrorModel = "\
    ///     error(0.1) D0 L0\n\
    ///     error(0.2) D0 D1\n\
    ///     error(0.1) D1\n".parse()?;
    /// let matching = Matching::from_detector_error_model_with_options(&dem, true)?;
    /// assert_eq!(matching.num_detectors(), 2);
    /// assert_eq!(matching.num_fault_ids(), 1);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_detector_error_model_with_options(
        detector_error_model: &stim::DetectorErrorModel,
        enable_correlations: bool,
    ) -> Result<Self> {
        from_detector_error_model_text(&detector_error_model.to_string(), enable_correlations)
    }

    /// Constructs a matching graph from a Stim circuit.
    ///
    /// The circuit is converted to a detector error model with errors
    /// decomposed into graphlike components. Set `enable_correlations` to retain
    /// the decomposition data required by native correlated matching. See
    /// [`Matching::from_detector_error_model_with_options`] for graph semantics.
    pub fn from_stim_circuit_with_options(
        circuit: &stim::Circuit,
        enable_correlations: bool,
    ) -> Result<Self> {
        let detector_error_model =
            detector_error_model_from_circuit(circuit).map_err(stim_error_to_matching_error)?;
        Self::from_detector_error_model_with_options(&detector_error_model, enable_correlations)
    }

    /// Loads a detector error model file for raw matching.
    ///
    /// This convenience constructor does not retain correlation data. For
    /// correlated matching, parse a [`stim::DetectorErrorModel`] and call
    /// [`Matching::from_detector_error_model_with_options`].
    pub fn from_detector_error_model_file(path: impl AsRef<Path>) -> Result<Self> {
        let detector_error_model_text =
            fs::read_to_string(path).map_err(|error| MatchingError::Upstream(error.to_string()))?;
        from_detector_error_model_text(&detector_error_model_text, false)
    }

    /// Loads a Stim circuit file for raw matching.
    ///
    /// The circuit is converted to a decomposed detector error model. For
    /// correlated matching, parse a [`stim::Circuit`] and call
    /// [`Matching::from_stim_circuit_with_options`].
    pub fn from_stim_circuit_file(path: impl AsRef<Path>) -> Result<Self> {
        let circuit = stim::Circuit::from_file(path).map_err(stim_error_to_matching_error)?;
        Self::from_stim_circuit_with_options(&circuit, false)
    }
}

impl TryFrom<&stim::DetectorErrorModel> for Matching {
    type Error = MatchingError;

    fn try_from(value: &stim::DetectorErrorModel) -> Result<Self> {
        Self::from_detector_error_model_with_options(value, false)
    }
}

impl TryFrom<stim::DetectorErrorModel> for Matching {
    type Error = MatchingError;

    fn try_from(value: stim::DetectorErrorModel) -> Result<Self> {
        Self::try_from(&value)
    }
}

impl TryFrom<&stim::Circuit> for Matching {
    type Error = MatchingError;

    fn try_from(value: &stim::Circuit) -> Result<Self> {
        Self::from_stim_circuit_with_options(value, false)
    }
}

impl TryFrom<stim::Circuit> for Matching {
    type Error = MatchingError;

    fn try_from(value: stim::Circuit) -> Result<Self> {
        Self::try_from(&value)
    }
}