use stim_cxx as _;
#[cxx::bridge]
mod ffi {
#[repr(u8)]
enum MergeStrategy {
Disallow = 0,
Independent = 1,
SmallestWeight = 2,
KeepOriginal = 3,
Replace = 4,
}
struct EdgeInput {
fault_ids: Vec<u64>,
weight: f64,
error_probability: f64,
}
struct DecodeConfig {
return_weight: bool,
bit_packed_shots: bool,
bit_packed_predictions: bool,
enable_correlations: bool,
}
#[allow(dead_code)]
struct EdgeRecord {
node1: u64,
node2: u64,
fault_ids: Vec<u64>,
weight: f64,
error_probability: f64,
is_boundary: bool,
}
struct DecodeResult {
prediction: Vec<u8>,
weight: f64,
has_weight: bool,
}
struct GapDecodeResult {
prediction: Vec<u8>,
gaps: Vec<f64>,
}
struct GapBatchDecodeResult {
predictions: Vec<u8>,
gaps: Vec<f64>,
rows: u64,
cols: u64,
}
struct BatchDecodeResult {
predictions: Vec<u8>,
prediction_rows: u64,
prediction_cols: u64,
weights: Vec<f64>,
has_weights: bool,
}
struct Int64Matrix {
data: Vec<i64>,
rows: u64,
cols: u64,
}
struct NoiseResult {
errors: Vec<u8>,
syndrome: Vec<u8>,
has_noise: bool,
}
unsafe extern "C++" {
include!("pymatching-cxx/include/pymatching_rs_bridge.h");
#[namespace = "pymatching_rs"]
type SmokeProbe;
#[namespace = "pymatching_rs"]
type MatchingHandle;
#[namespace = "pymatching_rs"]
fn new_smoke_probe() -> UniquePtr<SmokeProbe>;
#[namespace = "pymatching_rs"]
fn describe(self: &SmokeProbe) -> String;
#[namespace = "pymatching_rs"]
fn weighted_checksum(self: &SmokeProbe, values: &[u32]) -> u64;
#[namespace = "pymatching_rs"]
fn set_global_rng_seed_for_tests(seed: u64);
#[namespace = "pymatching_rs"]
fn hold_noise_rng_lock_for_tests(duration_ms: u64);
#[namespace = "pymatching_rs"]
fn is_noise_rng_lock_held_for_tests() -> bool;
#[namespace = "pymatching_rs"]
fn new_matching_handle() -> UniquePtr<MatchingHandle>;
#[namespace = "pymatching_rs"]
fn new_matching_handle_with_num_nodes(num_nodes: u64) -> UniquePtr<MatchingHandle>;
#[namespace = "pymatching_rs"]
fn matching_from_detector_error_model_text(
dem_text: &str,
enable_correlations: bool,
) -> Result<UniquePtr<MatchingHandle>>;
#[namespace = "pymatching_rs"]
fn matching_add_edge_with_merge_strategy(
matching: Pin<&mut MatchingHandle>,
node1: u64,
node2: u64,
edge: &EdgeInput,
merge_strategy: MergeStrategy,
) -> Result<()>;
#[namespace = "pymatching_rs"]
fn matching_add_boundary_edge_with_merge_strategy(
matching: Pin<&mut MatchingHandle>,
node: u64,
edge: &EdgeInput,
merge_strategy: MergeStrategy,
) -> Result<()>;
#[namespace = "pymatching_rs"]
fn matching_set_boundary_nodes(matching: Pin<&mut MatchingHandle>, nodes: &[u64]);
#[namespace = "pymatching_rs"]
fn matching_ensure_num_fault_ids(
matching: Pin<&mut MatchingHandle>,
min_num_fault_ids: u64,
);
#[namespace = "pymatching_rs"]
fn matching_has_edge(matching: &MatchingHandle, node1: u64, node2: u64) -> bool;
#[namespace = "pymatching_rs"]
fn matching_has_boundary_edge(matching: &MatchingHandle, node: u64) -> bool;
#[namespace = "pymatching_rs"]
fn matching_num_nodes(matching: &MatchingHandle) -> u64;
#[namespace = "pymatching_rs"]
fn matching_num_edges(matching: &MatchingHandle) -> u64;
#[namespace = "pymatching_rs"]
fn matching_num_fault_ids(matching: &MatchingHandle) -> u64;
#[namespace = "pymatching_rs"]
fn matching_num_detectors(matching: &MatchingHandle) -> u64;
#[namespace = "pymatching_rs"]
fn matching_boundary_nodes(matching: &MatchingHandle) -> Vec<u64>;
#[namespace = "pymatching_rs"]
fn matching_edges(matching: &MatchingHandle) -> Vec<EdgeRecord>;
#[namespace = "pymatching_rs"]
fn matching_edge_data(
matching: &MatchingHandle,
node1: u64,
node2: u64,
) -> Result<EdgeRecord>;
#[namespace = "pymatching_rs"]
fn matching_boundary_edge_data(matching: &MatchingHandle, node: u64) -> Result<EdgeRecord>;
#[namespace = "pymatching_rs"]
fn matching_decode(matching: &MatchingHandle, syndrome: &[u8]) -> Result<Vec<u8>>;
#[namespace = "pymatching_rs"]
fn matching_decode_with_config(
matching: &MatchingHandle,
syndrome: &[u8],
config: &DecodeConfig,
) -> Result<DecodeResult>;
#[namespace = "pymatching_rs"]
fn matching_decode_gap(
matching: &MatchingHandle,
syndrome: &[u8],
) -> Result<GapDecodeResult>;
#[namespace = "pymatching_rs"]
fn matching_decode_gap_batch(
matching: &MatchingHandle,
shots: &[u8],
num_rows: u64,
num_cols: u64,
) -> Result<GapBatchDecodeResult>;
#[namespace = "pymatching_rs"]
fn matching_decode_batch(
matching: &MatchingHandle,
shots: &[u8],
num_rows: u64,
num_cols: u64,
config: &DecodeConfig,
) -> Result<BatchDecodeResult>;
#[namespace = "pymatching_rs"]
fn matching_decode_to_edges_array(
matching: &MatchingHandle,
syndrome: &[u8],
enable_correlations: bool,
) -> Result<Int64Matrix>;
#[namespace = "pymatching_rs"]
fn matching_decode_to_matched_dets_array(
matching: &MatchingHandle,
syndrome: &[u8],
) -> Result<Int64Matrix>;
#[namespace = "pymatching_rs"]
fn matching_add_noise(matching: &MatchingHandle) -> Result<NoiseResult>;
#[namespace = "pymatching_rs"]
fn matching_add_noise_with_seed(
matching: &MatchingHandle,
seed: u64,
) -> Result<NoiseResult>;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuildMetadata {
pub crate_name: &'static str,
pub cxx_standard: &'static str,
pub target: &'static str,
pub vendor_pymatching_mode: &'static str,
pub vendor_pymatching_dir: &'static str,
}
#[must_use]
pub fn build_metadata() -> BuildMetadata {
BuildMetadata {
crate_name: env!("CARGO_PKG_NAME"),
cxx_standard: env!("PYMATCHING_RS_CXX_STANDARD"),
target: env!("PYMATCHING_RS_TARGET"),
vendor_pymatching_mode: env!("PYMATCHING_RS_VENDOR_PYMATCHING_MODE"),
vendor_pymatching_dir: env!("PYMATCHING_RS_VENDOR_PYMATCHING_DIR"),
}
}
#[must_use]
pub fn pinned_pymatching_commit() -> &'static str {
env!("PYMATCHING_RS_PINNED_PYMATCHING_COMMIT")
}
#[doc(hidden)]
pub fn set_global_rng_seed_for_tests(seed: u64) {
ffi::set_global_rng_seed_for_tests(seed);
}
#[doc(hidden)]
pub fn hold_noise_rng_lock_for_tests(duration_ms: u64) {
ffi::hold_noise_rng_lock_for_tests(duration_ms);
}
#[doc(hidden)]
pub fn is_noise_rng_lock_held_for_tests() -> bool {
ffi::is_noise_rng_lock_held_for_tests()
}
#[derive(Debug, Clone, PartialEq)]
pub struct EdgeInput {
pub fault_ids: Vec<u64>,
pub weight: f64,
pub error_probability: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EdgeRecord {
pub node1: u64,
pub node2: u64,
pub fault_ids: Vec<u64>,
pub weight: f64,
pub error_probability: f64,
pub is_boundary: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeConfig {
pub return_weight: bool,
pub bit_packed_shots: bool,
pub bit_packed_predictions: bool,
pub enable_correlations: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DecodeResult {
pub prediction: Vec<u8>,
pub weight: f64,
pub has_weight: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GapDecodeResult {
pub prediction: Vec<u8>,
pub gaps: Vec<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GapBatchDecodeResult {
pub predictions: Vec<u8>,
pub gaps: Vec<f64>,
pub rows: u64,
pub cols: u64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BatchDecodeResult {
pub predictions: Vec<u8>,
pub prediction_rows: u64,
pub prediction_cols: u64,
pub weights: Vec<f64>,
pub has_weights: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Int64Matrix {
pub data: Vec<i64>,
pub rows: u64,
pub cols: u64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NoiseResult {
pub errors: Vec<u8>,
pub syndrome: Vec<u8>,
pub has_noise: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeStrategy {
Disallow,
Independent,
SmallestWeight,
KeepOriginal,
Replace,
}
pub struct RawMatchingHandle {
inner: cxx::UniquePtr<ffi::MatchingHandle>,
}
fn edge_record_from_ffi(record: ffi::EdgeRecord) -> EdgeRecord {
EdgeRecord {
node1: record.node1,
node2: record.node2,
fault_ids: record.fault_ids,
weight: record.weight,
error_probability: record.error_probability,
is_boundary: record.is_boundary,
}
}
fn int64_matrix_from_ffi(matrix: ffi::Int64Matrix) -> Int64Matrix {
Int64Matrix {
data: matrix.data,
rows: matrix.rows,
cols: matrix.cols,
}
}
impl DecodeConfig {
fn into_ffi(self) -> ffi::DecodeConfig {
ffi::DecodeConfig {
return_weight: self.return_weight,
bit_packed_shots: self.bit_packed_shots,
bit_packed_predictions: self.bit_packed_predictions,
enable_correlations: self.enable_correlations,
}
}
}
impl Default for RawMatchingHandle {
fn default() -> Self {
Self {
inner: ffi::new_matching_handle(),
}
}
}
impl RawMatchingHandle {
fn handle(&self) -> &ffi::MatchingHandle {
self.inner
.as_ref()
.expect("matching handle bridge should always construct")
}
#[must_use]
pub fn with_num_nodes(num_nodes: usize) -> Self {
Self {
inner: ffi::new_matching_handle_with_num_nodes(num_nodes as u64),
}
}
pub fn from_detector_error_model_text(
dem_text: &str,
enable_correlations: bool,
) -> std::result::Result<Self, cxx::Exception> {
Ok(Self {
inner: ffi::matching_from_detector_error_model_text(dem_text, enable_correlations)?,
})
}
pub fn add_edge(
&mut self,
node1: usize,
node2: usize,
edge: &EdgeInput,
) -> std::result::Result<(), cxx::Exception> {
self.add_edge_with_merge_strategy(node1, node2, edge, MergeStrategy::Disallow)
}
pub fn add_edge_with_merge_strategy(
&mut self,
node1: usize,
node2: usize,
edge: &EdgeInput,
merge_strategy: MergeStrategy,
) -> std::result::Result<(), cxx::Exception> {
ffi::matching_add_edge_with_merge_strategy(
self.inner.pin_mut(),
node1 as u64,
node2 as u64,
&ffi::EdgeInput {
fault_ids: edge.fault_ids.clone(),
weight: edge.weight,
error_probability: edge.error_probability,
},
merge_strategy.into_ffi(),
)
}
pub fn add_boundary_edge(
&mut self,
node: usize,
edge: &EdgeInput,
) -> std::result::Result<(), cxx::Exception> {
self.add_boundary_edge_with_merge_strategy(node, edge, MergeStrategy::Disallow)
}
pub fn add_boundary_edge_with_merge_strategy(
&mut self,
node: usize,
edge: &EdgeInput,
merge_strategy: MergeStrategy,
) -> std::result::Result<(), cxx::Exception> {
ffi::matching_add_boundary_edge_with_merge_strategy(
self.inner.pin_mut(),
node as u64,
&ffi::EdgeInput {
fault_ids: edge.fault_ids.clone(),
weight: edge.weight,
error_probability: edge.error_probability,
},
merge_strategy.into_ffi(),
)
}
pub fn set_boundary_nodes(&mut self, nodes: &[usize]) {
let nodes: Vec<u64> = nodes.iter().map(|&node| node as u64).collect();
ffi::matching_set_boundary_nodes(self.inner.pin_mut(), &nodes);
}
pub fn ensure_num_fault_ids(&mut self, min_num_fault_ids: usize) {
ffi::matching_ensure_num_fault_ids(self.inner.pin_mut(), min_num_fault_ids as u64);
}
#[must_use]
pub fn has_edge(&self, node1: usize, node2: usize) -> bool {
ffi::matching_has_edge(self.handle(), node1 as u64, node2 as u64)
}
#[must_use]
pub fn has_boundary_edge(&self, node: usize) -> bool {
ffi::matching_has_boundary_edge(self.handle(), node as u64)
}
#[must_use]
pub fn num_nodes(&self) -> usize {
ffi::matching_num_nodes(self.handle()) as usize
}
#[must_use]
pub fn num_edges(&self) -> usize {
ffi::matching_num_edges(self.handle()) as usize
}
#[must_use]
pub fn num_fault_ids(&self) -> usize {
ffi::matching_num_fault_ids(self.handle()) as usize
}
#[must_use]
pub fn num_detectors(&self) -> usize {
ffi::matching_num_detectors(self.handle()) as usize
}
#[must_use]
pub fn boundary_nodes(&self) -> Vec<usize> {
ffi::matching_boundary_nodes(self.handle())
.into_iter()
.map(|node| node as usize)
.collect()
}
#[must_use]
pub fn edges(&self) -> Vec<EdgeRecord> {
ffi::matching_edges(self.handle())
.into_iter()
.map(edge_record_from_ffi)
.collect()
}
pub fn edge_data(
&self,
node1: usize,
node2: usize,
) -> std::result::Result<EdgeRecord, cxx::Exception> {
ffi::matching_edge_data(self.handle(), node1 as u64, node2 as u64).map(edge_record_from_ffi)
}
pub fn boundary_edge_data(
&self,
node: usize,
) -> std::result::Result<EdgeRecord, cxx::Exception> {
ffi::matching_boundary_edge_data(self.handle(), node as u64).map(edge_record_from_ffi)
}
pub fn decode(&self, syndrome: &[u8]) -> std::result::Result<Vec<u8>, cxx::Exception> {
ffi::matching_decode(self.handle(), syndrome)
}
pub fn decode_with_config(
&self,
syndrome: &[u8],
config: DecodeConfig,
) -> std::result::Result<DecodeResult, cxx::Exception> {
ffi::matching_decode_with_config(self.handle(), syndrome, &config.into_ffi()).map(
|result| DecodeResult {
prediction: result.prediction,
weight: result.weight,
has_weight: result.has_weight,
},
)
}
pub fn decode_gap(
&self,
syndrome: &[u8],
) -> std::result::Result<GapDecodeResult, cxx::Exception> {
ffi::matching_decode_gap(self.handle(), syndrome).map(|result| GapDecodeResult {
prediction: result.prediction,
gaps: result.gaps,
})
}
pub fn decode_gap_batch(
&self,
shots: &[u8],
num_rows: usize,
num_cols: usize,
) -> std::result::Result<GapBatchDecodeResult, cxx::Exception> {
ffi::matching_decode_gap_batch(self.handle(), shots, num_rows as u64, num_cols as u64).map(
|result| GapBatchDecodeResult {
predictions: result.predictions,
gaps: result.gaps,
rows: result.rows,
cols: result.cols,
},
)
}
pub fn decode_batch(
&self,
shots: &[u8],
num_rows: usize,
num_cols: usize,
config: DecodeConfig,
) -> std::result::Result<BatchDecodeResult, cxx::Exception> {
ffi::matching_decode_batch(
self.handle(),
shots,
num_rows as u64,
num_cols as u64,
&config.into_ffi(),
)
.map(|result| BatchDecodeResult {
predictions: result.predictions,
prediction_rows: result.prediction_rows,
prediction_cols: result.prediction_cols,
weights: result.weights,
has_weights: result.has_weights,
})
}
pub fn decode_to_edges_array(
&self,
syndrome: &[u8],
enable_correlations: bool,
) -> std::result::Result<Int64Matrix, cxx::Exception> {
ffi::matching_decode_to_edges_array(self.handle(), syndrome, enable_correlations)
.map(int64_matrix_from_ffi)
}
pub fn decode_to_matched_dets_array(
&self,
syndrome: &[u8],
) -> std::result::Result<Int64Matrix, cxx::Exception> {
ffi::matching_decode_to_matched_dets_array(self.handle(), syndrome)
.map(int64_matrix_from_ffi)
}
pub fn add_noise(&self, seed: Option<u64>) -> std::result::Result<NoiseResult, cxx::Exception> {
let result = match seed {
Some(seed) => ffi::matching_add_noise_with_seed(self.handle(), seed),
None => ffi::matching_add_noise(self.handle()),
}?;
Ok(NoiseResult {
errors: result.errors,
syndrome: result.syndrome,
has_noise: result.has_noise,
})
}
}
#[doc(hidden)]
pub struct SmokeProbe {
inner: cxx::UniquePtr<ffi::SmokeProbe>,
}
impl SmokeProbe {
#[must_use]
pub fn new() -> Self {
Self {
inner: ffi::new_smoke_probe(),
}
}
#[must_use]
pub fn describe(&self) -> String {
self.inner
.as_ref()
.expect("smoke probe bridge should always construct")
.describe()
}
#[must_use]
pub fn weighted_checksum(&self, values: &[u32]) -> u64 {
self.inner
.as_ref()
.expect("smoke probe bridge should always construct")
.weighted_checksum(values)
}
}
impl Default for SmokeProbe {
fn default() -> Self {
Self::new()
}
}
impl MergeStrategy {
fn into_ffi(self) -> ffi::MergeStrategy {
match self {
Self::Disallow => ffi::MergeStrategy::Disallow,
Self::Independent => ffi::MergeStrategy::Independent,
Self::SmallestWeight => ffi::MergeStrategy::SmallestWeight,
Self::KeepOriginal => ffi::MergeStrategy::KeepOriginal,
Self::Replace => ffi::MergeStrategy::Replace,
}
}
}