pymatching 0.1.0

Safe Rust bindings for the PyMatching quantum error-correction decoder
Documentation
use sprs::{CompressedStorage, CsMat};

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

fn column_supports(matrix: &CsMat<u8>) -> Result<Vec<Vec<usize>>> {
    let (_, cols) = matrix.shape();
    let mut supports = vec![Vec::with_capacity(2); cols];
    let is_csc = matrix.storage() == CompressedStorage::CSC;

    for (outer, vector) in matrix.outer_iterator().enumerate() {
        for (inner, &value) in vector.iter() {
            let (row, col) = if is_csc {
                (inner, outer)
            } else {
                (outer, inner)
            };
            match value {
                0 => {}
                1 => {
                    let column = &mut supports[col];
                    if !column.contains(&row) {
                        column.push(row);
                        if column.len() > 2 {
                            return Err(MatchingError::Upstream(format!(
                                "check_matrix column {col} contains more than two ones"
                            )));
                        }
                    }
                }
                _ => {
                    return Err(MatchingError::Upstream(
                        "check_matrix must contain only binary values".to_string(),
                    ));
                }
            }
        }
    }

    Ok(supports)
}

impl TryFrom<&CsMat<u8>> for Matching {
    type Error = MatchingError;

    fn try_from(value: &CsMat<u8>) -> Result<Self> {
        let (rows, cols) = value.shape();
        let supports = column_supports(value)?;

        let mut matching = Self::default();
        matching.load_check_matrix_from_column_supports(
            rows,
            cols,
            supports,
            CheckMatrixOptions::new(),
        )?;
        Ok(matching)
    }
}

impl TryFrom<CsMat<u8>> for Matching {
    type Error = MatchingError;

    fn try_from(value: CsMat<u8>) -> Result<Self> {
        Self::try_from(&value)
    }
}