pymatching 0.1.0

Safe Rust bindings for the PyMatching quantum error-correction decoder
Documentation
use std::collections::HashSet;

use pymatching_cxx::RawMatchingHandle;
use rustworkx_core::petgraph::graph::UnGraph;
use rustworkx_core::petgraph::visit::EdgeRef;

use crate::export::is_virtual_boundary_marker;
use crate::{EdgeData, Matching, MatchingError, Result};

fn virtual_boundary_nodes(graph: &UnGraph<bool, EdgeData>) -> HashSet<usize> {
    graph
        .edge_references()
        .filter_map(|edge| {
            is_virtual_boundary_marker(edge.source().index(), edge.target().index(), edge.weight())
                .then_some(edge.source().index())
        })
        .collect()
}

impl Matching {
    /// Replaces this decoder with a `rustworkx-core` undirected graph.
    ///
    /// Node weights mark explicit boundary nodes. Edge weights are copied as
    /// [`EdgeData`]. The virtual-boundary sentinel emitted by
    /// [`Matching::to_rustworkx`] is recognized and converted back into virtual
    /// boundary edges. Loading is transactional: an error leaves this matching
    /// unchanged.
    ///
    /// This method is available with the `rustworkx` Cargo feature.
    pub fn load_rustworkx(&mut self, graph: &UnGraph<bool, EdgeData>) -> Result<()> {
        let virtual_boundary_nodes = virtual_boundary_nodes(graph);
        let mut node_map = vec![None; graph.node_count()];
        let mut next_node = 0;
        for node in graph.node_indices() {
            let node_index = node.index();
            if !virtual_boundary_nodes.contains(&node_index) {
                node_map[node_index] = Some(next_node);
                next_node += 1;
            }
        }

        let mut staged = Self::from_raw_handle(RawMatchingHandle::with_num_nodes(next_node));
        staged.set_boundary_nodes(
            graph
                .node_indices()
                .filter(|node| {
                    let node_index = node.index();
                    graph.node_weight(*node).copied().unwrap_or(false)
                        && !virtual_boundary_nodes.contains(&node_index)
                })
                .map(|node| {
                    node_map[node.index()]
                        .expect("real rustworkx nodes always map to matching nodes")
                }),
        );

        for edge in graph.edge_references() {
            let source = edge.source().index();
            let target = edge.target().index();
            if is_virtual_boundary_marker(source, target, edge.weight()) {
                continue;
            }

            let source_is_virtual = virtual_boundary_nodes.contains(&source);
            let target_is_virtual = virtual_boundary_nodes.contains(&target);
            match (source_is_virtual, target_is_virtual) {
                (false, false) => staged.add_edge(
                    node_map[source].expect("real rustworkx nodes always map to matching nodes"),
                    node_map[target].expect("real rustworkx nodes always map to matching nodes"),
                    edge.weight().clone(),
                )?,
                (true, false) => staged.add_boundary_edge(
                    node_map[target].expect("real rustworkx nodes always map to matching nodes"),
                    edge.weight().clone(),
                )?,
                (false, true) => staged.add_boundary_edge(
                    node_map[source].expect("real rustworkx nodes always map to matching nodes"),
                    edge.weight().clone(),
                )?,
                (true, true) => {
                    return Err(MatchingError::InvalidInput(
                        "rustworkx virtual-boundary sentinel nodes may not connect to each other",
                    ));
                }
            }
        }

        *self = staged;
        Ok(())
    }
}

impl TryFrom<&UnGraph<bool, EdgeData>> for Matching {
    type Error = MatchingError;

    fn try_from(value: &UnGraph<bool, EdgeData>) -> Result<Self> {
        let mut matching = Self::default();
        matching.load_rustworkx(value)?;
        Ok(matching)
    }
}

impl TryFrom<UnGraph<bool, EdgeData>> for Matching {
    type Error = MatchingError;

    fn try_from(value: UnGraph<bool, EdgeData>) -> Result<Self> {
        Self::try_from(&value)
    }
}