diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dd3a2363..13d4fa0ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -94,6 +94,7 @@ set(PERF_FILES set(PYTHON_API_FILES src/pymatching/sparse_blossom/driver/user_graph.pybind.cc + src/pymatching/sparse_blossom/driver/persistent.pybind.cc src/pymatching/rand/rand_gen.pybind.cc src/pymatching/pymatching.pybind.cc ) diff --git a/src/pymatching/__init__.py b/src/pymatching/__init__.py index f0c9d753a..860c4b926 100644 --- a/src/pymatching/__init__.py +++ b/src/pymatching/__init__.py @@ -15,6 +15,7 @@ from pymatching._cpp_pymatching import (randomize, set_seed, rand_float) # noqa from pymatching._cpp_pymatching import main as cli # noqa from pymatching.matching import Matching # noqa +from pymatching.persistent_matcher import PersistentMatcher # noqa from pymatching._version import __version__ randomize() # Set random seed using std::random_device diff --git a/src/pymatching/persistent_matcher.py b/src/pymatching/persistent_matcher.py new file mode 100644 index 000000000..b85d3b406 --- /dev/null +++ b/src/pymatching/persistent_matcher.py @@ -0,0 +1,139 @@ +# Copyright 2022 PyMatching Contributors + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Optional, Union + +import numpy as np +from scipy.sparse import csc_matrix, identity, spmatrix + +from pymatching._cpp_pymatching import PersistentMatcher as _CppPersistentMatcher + + +def _to_binary_csc(matrix: Union[csc_matrix, spmatrix, np.ndarray, List[List[int]]], name: str) -> csc_matrix: + m = csc_matrix(matrix) + m.eliminate_zeros() + if m.nnz and not np.all(m.data == 1): + raise ValueError(f"{name} must be a binary matrix") + m = m.astype(np.uint8) + m.sort_indices() + return m + + +class PersistentMatcher: + """A matching graph built once from a check matrix, whose edge weights are updated in place. + + Decoding many syndromes of the same check matrix with different weights normally means building a new + :py:class:`pymatching.Matching` for every weight vector, and building the graph can cost far more than the + decode itself. A `PersistentMatcher` builds the graph once; :py:meth:`set_weights` then rewrites the edge + weights in place, and :py:meth:`decode` gives the same result as:: + + pymatching.Matching.from_check_matrix(check_matrix, weights=weights, + faults_matrix=faults_matrix).decode(syndrome) + + that is, with the default ``merge_strategy="smallest-weight"``, no virtual boundary node and a single + repetition. Weights may be negative, as for `Matching`. + + Parameters + ---------- + check_matrix : scipy.sparse.csc_matrix or numpy.ndarray + A binary check matrix with at most two non-zero elements per column. + weights : float or numpy.ndarray, optional + The initial weight of each column (fault). A float sets every column to that weight. By default 1. + faults_matrix : scipy.sparse.csc_matrix or numpy.ndarray, optional + A binary matrix with one column per column of `check_matrix`: ``faults_matrix[i, j] == 1`` if fault ``j`` + flips logical observable ``i``. :py:meth:`decode` then returns the predicted observables. By default the + identity, so :py:meth:`decode` returns the correction, as `Matching.decode` does. + """ + + def __init__( + self, + check_matrix: Union[csc_matrix, spmatrix, np.ndarray, List[List[int]]], + weights: Optional[Union[float, np.ndarray, List[float]]] = None, + *, + faults_matrix: Optional[Union[csc_matrix, spmatrix, np.ndarray, List[List[int]]]] = None, + ) -> None: + h = _to_binary_csc(check_matrix, "check_matrix") + num_rows, num_cols = h.shape + if faults_matrix is None: + f = identity(num_cols, dtype=np.uint8, format="csc") + else: + f = _to_binary_csc(faults_matrix, "faults_matrix") + if f.shape[1] != num_cols: + raise ValueError( + f"faults_matrix has {f.shape[1]} columns but check_matrix has {num_cols}; they must be equal" + ) + self._num_rows = num_rows + self._num_cols = num_cols + self._num_observables = f.shape[0] + self._matcher = _CppPersistentMatcher( + h.indptr.astype(np.int64), + h.indices.astype(np.int64), + num_rows, + num_cols, + f.indptr.astype(np.int64), + f.indices.astype(np.int64), + f.shape[0], + self._weight_array(1.0 if weights is None else weights), + ) + + def _weight_array(self, weights: Union[float, np.ndarray, List[float]]) -> np.ndarray: + if np.isscalar(weights): + w = np.full(self._num_cols, float(weights)) + else: + w = np.ascontiguousarray(weights, dtype=np.float64) + if w.shape != (self._num_cols,): + raise ValueError(f"weights must have shape ({self._num_cols},), not {w.shape}") + if not np.all(np.isfinite(w)): + raise ValueError("weights must be finite") + return w + + def set_weights(self, weights: Union[float, np.ndarray, List[float]]) -> None: + """Set the weight of every column (fault). + + Parameters + ---------- + weights : float or numpy.ndarray + One weight per column of the check matrix, or a float for all of them. + """ + self._matcher.set_weights(self._weight_array(weights)) + + def decode(self, syndrome: Union[np.ndarray, List[int]]) -> np.ndarray: + """Decode a syndrome with the current weights. + + Parameters + ---------- + syndrome : numpy.ndarray + A binary vector with one element per row of the check matrix. + + Returns + ------- + numpy.ndarray + The predicted observables (one per row of `faults_matrix`); the correction if no `faults_matrix` was + given. + """ + z = np.asarray(syndrome) + if z.shape != (self._num_rows,): + raise ValueError(f"syndrome must have shape ({self._num_rows},), not {z.shape}") + return self._matcher.decode(np.flatnonzero(z).astype(np.uint64)) + + @property + def num_detectors(self) -> int: + """The number of detectors (rows of the check matrix).""" + return self._num_rows + + @property + def num_fault_ids(self) -> int: + """The number of fault IDs (observables): the rows of `faults_matrix`, or the columns of the check matrix + if no `faults_matrix` was given.""" + return self._num_observables diff --git a/src/pymatching/pymatching.pybind.cc b/src/pymatching/pymatching.pybind.cc index fa398c1d4..0fa0a691b 100644 --- a/src/pymatching/pymatching.pybind.cc +++ b/src/pymatching/pymatching.pybind.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "pybind11/pybind11.h" +#include "pymatching/sparse_blossom/driver/persistent.pybind.h" #include "pymatching/rand/rand_gen.pybind.h" #include "pymatching/sparse_blossom/driver/namespaced_main.h" #include "pymatching/sparse_blossom/driver/user_graph.pybind.h" @@ -33,6 +34,7 @@ PYBIND11_MODULE(_cpp_pymatching, m) { auto matching_graph = pm_pybind::pybind_user_graph(m); pm_pybind::pybind_user_graph_methods(m, matching_graph); pm_pybind::pybind_rand_gen_methods(m); + pm_pybind::pybind_persistent_matcher(m); m.def("main", &pymatching_main, pybind11::kw_only(), pybind11::arg("command_line_args"), R"pbdoc( Runs the command line tool version of pymatching with the given arguments. )pbdoc"); diff --git a/src/pymatching/sparse_blossom/driver/persistent.pybind.cc b/src/pymatching/sparse_blossom/driver/persistent.pybind.cc new file mode 100644 index 000000000..02da2f859 --- /dev/null +++ b/src/pymatching/sparse_blossom/driver/persistent.pybind.cc @@ -0,0 +1,284 @@ +// Copyright 2022 PyMatching Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// PersistentMatcher: a matching graph built once from a check matrix (exactly as +// sparse_column_check_matrix_to_matching_graph builds it, merge strategy "smallest-weight", no virtual boundary node, +// one repetition), whose edge weights are then rewritten in place for every decode instead of +// rebuilding the graph and its flooder. +// +// Rewriting reproduces what a rebuild would produce: the graph's structure (nodes, neighbour order) does not depend on +// the weights; per user edge the kept column is the first column with the strictly smallest weight (the smallest-weight +// merge rule applied in column order); the discretisation is UserGraph::iter_discretized_edges with the normalising +// constant of UserGraph::get_edge_weight_normalising_constant; negative weights update the same sets as +// MatchingGraph::add_edge / add_boundary_edge, and the flooder's copies are refreshed with +// sync_negative_weight_observables_and_detection_events, as UserGraph::to_mwpm does. +// +// More than 64 observables (e.g. the identity faults matrix, so that decode returns the full correction as +// Matching.decode does): the Mwpm then carries a search graph, built as UserGraph::to_mwpm(..., true) builds it, whose +// weights, observable lists and sign markers are rewritten in place too; the matching graph's observable masks stay 0 +// as MatchingGraph::add_edge leaves them. +#include "pymatching/sparse_blossom/driver/persistent.pybind.h" + +#include +#include +#include +#include +#include +#include + +#include "pybind11/numpy.h" +#include "pymatching/sparse_blossom/driver/mwpm_decoding.h" +#include "pymatching/sparse_blossom/driver/user_graph.h" + +namespace py = pybind11; +using namespace py::literals; + +namespace { + +struct Slot { + size_t node; + size_t index; +}; + +class PersistentMatcher { + public: + PersistentMatcher( + const py::array_t &h_indptr, + const py::array_t &h_indices, + size_t num_rows, + size_t num_cols, + const py::array_t &f_indptr, + const py::array_t &f_indices, + size_t num_observables, + const py::array_t &weights) + : num_detectors(num_rows), num_cols(num_cols), big_obs(num_observables > sizeof(pm::obs_int) * 8) { + auto hp = h_indptr.unchecked<1>(); + auto hi = h_indices.unchecked<1>(); + auto fp = f_indptr.unchecked<1>(); + auto fi = f_indices.unchecked<1>(); + auto w = weights.unchecked<1>(); + if ((size_t)w.size() != num_cols) + throw std::invalid_argument("weights must have one entry per column"); + + pm::UserGraph graph(num_detectors, num_observables); + col_obs.resize(num_cols); + col_obs_mask.assign(num_cols, 0); + col_nodes.resize(num_cols); + for (size_t c = 0; c < num_cols; c++) { + for (auto q = fp(c); q < fp(c + 1); q++) { + col_obs[c].push_back((size_t)fi(q)); + if (!big_obs) + col_obs_mask[c] ^= (pm::obs_int)1 << fi(q); + } + auto n = hp(c + 1) - hp(c); + if (n == 2) { + col_nodes[c] = {(size_t)hi(hp(c)), (size_t)hi(hp(c) + 1)}; + } else if (n == 1) { + col_nodes[c] = {(size_t)hi(hp(c)), num_detectors}; + } else if (n != 0) { + throw std::invalid_argument("check matrix must contain at most two ones per column"); + } else { + col_nodes[c] = {SIZE_MAX, SIZE_MAX}; + continue; + } + graph.add_or_merge_edge( + col_nodes[c].first, col_nodes[c].second, col_obs[c], w(c), -1, pm::SMALLEST_WEIGHT); + } + if (graph.nodes.size() == num_detectors + 1) + graph.set_boundary({num_detectors}); + has_boundary = graph.nodes.size() == num_detectors + 1; + + // user edges in graph order, and the columns of each (in column order) + std::map, size_t> edge_of_pair; + for (auto &e : graph.edges) { + edge_of_pair[{e.node1, e.node2}] = edge_nodes.size(); + edge_nodes.push_back({e.node1, e.node2}); + } + edge_cols.resize(edge_nodes.size()); + for (size_t c = 0; c < num_cols; c++) { + if (col_nodes[c].first == SIZE_MAX) + continue; + auto it = edge_of_pair.find(col_nodes[c]); + if (it == edge_of_pair.end()) + it = edge_of_pair.find({col_nodes[c].second, col_nodes[c].first}); + edge_cols[it->second].push_back(c); + } + + mwpm = graph.to_mwpm(pm::NUM_DISTINCT_WEIGHTS, false); + auto &g = mwpm.flooder.graph; + auto &sg = mwpm.search_flooder.graph; + // locate each edge's weight slots in the matching graph (and in the search graph) + for (auto &uv : edge_nodes) { + bool b1 = is_boundary(uv.first), b2 = is_boundary(uv.second); + std::vector slots, sslots; + if (b1 || b2) { + size_t u = b1 ? uv.second : uv.first; + slots.push_back({u, find_neighbor(g, u, nullptr)}); + if (big_obs) + sslots.push_back({u, find_neighbor(sg, u, nullptr)}); + } else { + slots.push_back({uv.first, find_neighbor(g, uv.first, &g.nodes[uv.second])}); + slots.push_back({uv.second, find_neighbor(g, uv.second, &g.nodes[uv.first])}); + if (big_obs) { + sslots.push_back({uv.first, find_neighbor(sg, uv.first, &sg.nodes[uv.second])}); + sslots.push_back({uv.second, find_neighbor(sg, uv.second, &sg.nodes[uv.first])}); + } + } + edge_slots.push_back(slots); + edge_sslots.push_back(sslots); + } + edge_weight.assign(edge_nodes.size(), 0.0); + edge_kept.assign(edge_nodes.size(), 0); + set_weights(weights); + } + + void set_weights(const py::array_t &weights) { + auto w = weights.unchecked<1>(); + if ((size_t)w.size() != num_cols) + throw std::invalid_argument("weights must have one entry per column"); + // smallest-weight merge, in column order + double max_abs = 0; + bool all_integral = true; + for (size_t e = 0; e < edge_nodes.size(); e++) { + auto &cols = edge_cols[e]; + size_t kept = cols[0]; + double we = w(kept); + for (size_t k = 1; k < cols.size(); k++) { + if (w(cols[k]) < we) { + we = w(cols[k]); + kept = cols[k]; + } + } + edge_weight[e] = we; + edge_kept[e] = kept; + if (std::abs(we) > max_abs) + max_abs = std::abs(we); + if (round(we) != we) + all_integral = false; + } + if (max_abs > pm::MAX_USER_EDGE_WEIGHT) + throw std::invalid_argument("maximum absolute edge weight exceeded"); + double nc = all_integral ? 1.0 : (double)(pm::NUM_DISTINCT_WEIGHTS - 1) / max_abs; + + auto &g = mwpm.flooder.graph; + g.negative_weight_detection_events_set.clear(); + g.negative_weight_observables_set.clear(); + g.negative_weight_sum = 0; + for (size_t e = 0; e < edge_nodes.size(); e++) { + pm::signed_weight_int wi = (pm::signed_weight_int)round(edge_weight[e] * nc); + wi *= 2; + size_t c = edge_kept[e]; + auto &slots = edge_slots[e]; + if (wi < 0) { + g.update_negative_weight_observables(col_obs[c]); + for (auto &s : slots) + g.update_negative_weight_detection_events(s.node); + g.negative_weight_sum += wi; + } + for (auto &s : slots) { + g.nodes[s.node].neighbor_weights[s.index] = std::abs(wi); + g.nodes[s.node].neighbor_observables[s.index] = col_obs_mask[c]; + } + } + g.normalising_constant = nc; + if (big_obs) { + auto &sg = mwpm.search_flooder.graph; + sg.negative_weight_edges.clear(); + for (size_t e = 0; e < edge_nodes.size(); e++) { + pm::signed_weight_int wi = 2 * (pm::signed_weight_int)round(edge_weight[e] * nc); + size_t c = edge_kept[e]; + auto &ss = edge_sslots[e]; + if (wi < 0) + sg.negative_weight_edges.push_back( + {ss[0].node, ss.size() == 2 ? ss[1].node : SIZE_MAX}); + for (auto &s : ss) { + sg.nodes[s.node].neighbor_weights[s.index] = std::abs(wi); + sg.nodes[s.node].neighbor_observable_indices[s.index] = col_obs[c]; + sg.nodes[s.node].neighbor_markers[s.index] = wi < 0 ? pm::WEIGHT_SIGN : 0; + } + } + } + mwpm.flooder.sync_negative_weight_observables_and_detection_events(); + } + + // same call as UserGraph.decode (enable_correlations = false); returns the observables crossed + py::array_t decode(const py::array_t &detection_events) { + std::vector ev(detection_events.data(), detection_events.data() + detection_events.size()); + size_t num_obs = mwpm.flooder.graph.num_observables; + py::array_t out(num_obs); + std::fill(out.mutable_data(), out.mutable_data() + num_obs, 0); + pm::total_weight_int weight = 0; + pm::decode_detection_events(mwpm, ev, out.mutable_data(), weight, false); + return out; + } + + size_t get_num_detectors() const { + return num_detectors; + } + + private: + bool is_boundary(size_t node) const { + return node == SIZE_MAX || (has_boundary && node == num_detectors); + } + + template + static size_t find_neighbor(Graph &g, size_t u, const void *v) { + auto &nb = g.nodes[u].neighbors; + for (size_t j = 0; j < nb.size(); j++) + if ((const void *)nb[j] == v) + return j; + throw std::logic_error("edge slot not found"); + } + + size_t num_detectors, num_cols; + bool big_obs; + bool has_boundary = false; + pm::Mwpm mwpm; + std::vector> col_obs; + std::vector col_obs_mask; + std::vector> col_nodes; + std::vector> edge_nodes; + std::vector> edge_cols; + std::vector> edge_slots; + std::vector> edge_sslots; + std::vector edge_weight; + std::vector edge_kept; +}; + +} // namespace + +void pm_pybind::pybind_persistent_matcher(py::module &m) { + py::class_(m, "PersistentMatcher") + .def( + py::init< + const py::array_t &, + const py::array_t &, + size_t, + size_t, + const py::array_t &, + const py::array_t &, + size_t, + const py::array_t &>(), + "h_indptr"_a, + "h_indices"_a, + "num_rows"_a, + "num_cols"_a, + "f_indptr"_a, + "f_indices"_a, + "num_observables"_a, + "weights"_a) + .def("set_weights", &PersistentMatcher::set_weights, "weights"_a) + .def("decode", &PersistentMatcher::decode, "detection_events"_a) + .def("get_num_detectors", &PersistentMatcher::get_num_detectors); +} diff --git a/src/pymatching/sparse_blossom/driver/persistent.pybind.h b/src/pymatching/sparse_blossom/driver/persistent.pybind.h new file mode 100644 index 000000000..318bbd07c --- /dev/null +++ b/src/pymatching/sparse_blossom/driver/persistent.pybind.h @@ -0,0 +1,24 @@ +// Copyright 2022 PyMatching Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef PYMATCHING2_PERSISTENT_PYBIND_H +#define PYMATCHING2_PERSISTENT_PYBIND_H + +#include + +namespace pm_pybind { +void pybind_persistent_matcher(pybind11::module &m); +} + +#endif diff --git a/tests/matching/persistent_matcher_test.py b/tests/matching/persistent_matcher_test.py new file mode 100644 index 000000000..d9a8d87bb --- /dev/null +++ b/tests/matching/persistent_matcher_test.py @@ -0,0 +1,147 @@ +# Copyright 2022 PyMatching Contributors + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import pytest +from scipy.sparse import csc_matrix, hstack, kron, eye + +from pymatching import Matching, PersistentMatcher + + +def repetition_code(n): + return csc_matrix(np.eye(n - 1, n, dtype=np.uint8) + np.eye(n - 1, n, 1, dtype=np.uint8)) + + +def toric_code_x_checks(L): + h = csc_matrix(np.eye(L, dtype=np.uint8) + np.roll(np.eye(L, dtype=np.uint8), 1, axis=1)) + return csc_matrix(hstack([kron(h, eye(L)), kron(eye(L), h.T)]), dtype=np.uint8) + + +def surface_code_x_checks(d): + h = repetition_code(d) + m, n = h.shape + return csc_matrix(hstack([kron(h, eye(n)), kron(eye(m), h.T)]), dtype=np.uint8) + + +def with_parallel_edges(h, rng): + """Duplicate some columns, so that several faults share an edge (merged by smallest weight).""" + cols = rng.choice(h.shape[1], size=h.shape[1] // 3, replace=False) + return csc_matrix(hstack([h, h[:, cols]]), dtype=np.uint8) + + +def random_faults_matrix(rng, num_observables, num_cols): + return csc_matrix((rng.random((num_observables, num_cols)) < 0.2).astype(np.uint8)) + + +def assert_matches_fresh_matching(h, faults_matrix, rng, num_weight_sets=8, shots=15, negative=False): + pm = PersistentMatcher(h, faults_matrix=faults_matrix) + for _ in range(num_weight_sets): + w = rng.uniform(0.1, 10.0, h.shape[1]) + if negative: + w[rng.random(h.shape[1]) < 0.1] *= -1 + pm.set_weights(w) + m = Matching.from_check_matrix(h, weights=w, faults_matrix=faults_matrix) + for _ in range(shots): + errors = (rng.random(h.shape[1]) < 0.1).astype(np.uint8) + syndrome = (h @ errors) % 2 + assert np.array_equal(pm.decode(syndrome), m.decode(syndrome)) + + +@pytest.mark.parametrize("negative", [False, True]) +@pytest.mark.parametrize( + "make_h", + [ + lambda rng: repetition_code(9), + lambda rng: surface_code_x_checks(5), + lambda rng: toric_code_x_checks(4), + lambda rng: with_parallel_edges(surface_code_x_checks(4), rng), + ], +) +def test_persistent_matcher_returns_the_correction_of_a_fresh_matching(make_h, negative): + rng = np.random.default_rng(0) + assert_matches_fresh_matching(make_h(rng), None, rng, negative=negative) + + +@pytest.mark.parametrize("num_observables", [1, 3, 64, 70]) +def test_persistent_matcher_with_faults_matrix(num_observables): + rng = np.random.default_rng(1) + h = with_parallel_edges(surface_code_x_checks(5), rng) + f = random_faults_matrix(rng, num_observables, h.shape[1]) + assert_matches_fresh_matching(h, f, rng, negative=True) + + +def test_persistent_matcher_integral_weights(): + # integral weights are not rescaled before discretisation, as in Matching + rng = np.random.default_rng(2) + h = surface_code_x_checks(5) + pm = PersistentMatcher(h) + for _ in range(5): + w = rng.integers(1, 20, h.shape[1]).astype(float) + pm.set_weights(w) + m = Matching.from_check_matrix(h, weights=w) + for _ in range(10): + syndrome = (h @ (rng.random(h.shape[1]) < 0.1).astype(np.uint8)) % 2 + assert np.array_equal(pm.decode(syndrome), m.decode(syndrome)) + + +def test_persistent_matcher_scalar_and_default_weights(): + h = repetition_code(7) + syndrome = np.array([0, 1, 0, 0, 1, 0]) + expected = Matching.from_check_matrix(h).decode(syndrome) + assert np.array_equal(PersistentMatcher(h).decode(syndrome), expected) + pm = PersistentMatcher(h, weights=2.5) + assert np.array_equal(pm.decode(syndrome), expected) + assert pm.num_detectors == 6 + assert pm.num_fault_ids == 7 + + +def test_persistent_matcher_input_validation(): + h = repetition_code(5) + pm = PersistentMatcher(h) + with pytest.raises(ValueError): + pm.set_weights(np.ones(4)) + with pytest.raises(ValueError): + pm.decode(np.zeros(5)) + with pytest.raises(ValueError): + PersistentMatcher(h, faults_matrix=np.ones((1, 4))) + with pytest.raises(ValueError): + PersistentMatcher(2 * h) + with pytest.raises(ValueError): + PersistentMatcher(np.ones((3, 2), dtype=np.uint8)) # a column with three non-zero elements + + +@pytest.mark.parametrize("bad", [np.nan, np.inf, -np.inf]) +def test_persistent_matcher_rejects_non_finite_weights(bad): + h = repetition_code(5) + w = np.ones(h.shape[1]) + w[2] = bad + with pytest.raises(ValueError, match="finite"): + PersistentMatcher(h, weights=w) + with pytest.raises(ValueError, match="finite"): + PersistentMatcher(h, weights=bad) + pm = PersistentMatcher(h) + with pytest.raises(ValueError, match="finite"): + pm.set_weights(w) + with pytest.raises(ValueError, match="finite"): + pm.set_weights(bad) + + +@pytest.mark.parametrize("num_observables", [None, 1, 3]) +def test_persistent_matcher_num_fault_ids_counts_observables(num_observables): + h = repetition_code(5) + f = None if num_observables is None else np.ones((num_observables, h.shape[1]), dtype=np.uint8) + pm = PersistentMatcher(h, faults_matrix=f) + m = Matching.from_check_matrix(h, faults_matrix=f) + assert pm.num_fault_ids == m.num_fault_ids + assert pm.decode(np.zeros(h.shape[0], dtype=np.uint8)).shape == (pm.num_fault_ids,)