pymatching 0.1.0

Safe Rust bindings for the PyMatching quantum error-correction decoder
Documentation
#[cfg(feature = "rustworkx")]
use std::collections::HashSet;

#[cfg(feature = "rustworkx")]
use rustworkx_core::petgraph::graph::UnGraph;

#[cfg(feature = "rustworkx")]
use crate::{EdgeData, Matching, Result};

#[cfg(feature = "rustworkx")]
pub(crate) fn virtual_boundary_marker() -> EdgeData {
    EdgeData {
        fault_ids: vec![usize::MAX],
        weight: f64::INFINITY,
        error_probability: Some(0.0),
    }
}

#[cfg(feature = "rustworkx")]
pub(crate) fn is_virtual_boundary_marker(node1: usize, node2: usize, edge: &EdgeData) -> bool {
    node1 == node2
        && edge.fault_ids.as_slice() == [usize::MAX]
        && edge.weight.is_infinite()
        && edge.weight.is_sign_positive()
        && edge.error_probability == Some(0.0)
}

#[cfg(feature = "rustworkx")]
impl Matching {
    /// Exports the decoding graph as a `rustworkx-core` undirected graph.
    ///
    /// Node weights are `true` for explicit boundary nodes. If virtual-boundary
    /// edges exist, the exported graph includes a marked sentinel node so that
    /// [`Matching::load_rustworkx`] can round-trip them losslessly.
    ///
    /// This method is available with the `rustworkx` Cargo feature.
    pub fn to_rustworkx(&self) -> Result<UnGraph<bool, EdgeData>> {
        let boundary: HashSet<_> = self.boundary().collect();
        let edges = self.edges();
        let has_virtual_boundary = edges.iter().any(|edge| edge.node2.is_none());

        let mut graph = UnGraph::default();
        let nodes: Vec<_> = (0..self.num_nodes())
            .map(|node| graph.add_node(boundary.contains(&node)))
            .collect();
        let virtual_boundary = has_virtual_boundary.then(|| graph.add_node(true));

        if let Some(node) = virtual_boundary {
            graph.add_edge(node, node, virtual_boundary_marker());
        }

        for edge in edges {
            let source = nodes[edge.node1];
            let target = match edge.node2 {
                Some(node2) => nodes[node2],
                None => {
                    virtual_boundary.expect("virtual boundary exists when boundary edges exist")
                }
            };
            graph.add_edge(source, target, edge.data);
        }

        Ok(graph)
    }
}