From d265122bb2ef2981fdd5465bb90ac1cae73f6ad7 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Mon, 16 Nov 2026 13:29:14 -0500 Subject: [PATCH 1/3] Name the inputs of the stepped distance searches sectors, and the searches in the singular A joint search of the X and Z sectors of a CSS code is one problem with two sectors, so the stepped searches take `sectors` and their classes have singular names: `BrouwerZimmermannSearch`, `ConnectedClusterSearch`, and `_SectorSearch` for the BZ search of one sector. The BZ entry point loses its `_many` suffix. Behavior is unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/exact_search_tuning.rst | 2 +- experiments/distance_tuning/trace.py | 78 +++--- src/qldpc/codes/distance/README.md | 3 +- .../distance/_brouwer_zimmermann/distance.py | 104 +++---- .../_brouwer_zimmermann/distance_test.py | 254 +++++++++--------- .../distance/_connected_cluster/search.py | 72 ++--- .../_connected_cluster/search_test.py | 36 +-- .../codes/distance/_counting/scan_test.py | 4 +- .../automorphism_families_test.py | 8 +- src/qldpc/codes/distance/_tuning.py | 4 +- src/qldpc/codes/distance/_tuning_test.py | 6 +- .../codes/distance/brouwer_zimmermann.md | 22 +- src/qldpc/codes/distance/conftest.py | 2 +- src/qldpc/codes/distance/connected_cluster.md | 24 +- src/qldpc/codes/distance/core.py | 20 +- src/qldpc/codes/distance/core_test.py | 12 +- src/qldpc/codes/distance/logical_counts.py | 4 +- .../codes/distance/logical_counts_test.py | 4 +- 18 files changed, 324 insertions(+), 335 deletions(-) diff --git a/docs/source/exact_search_tuning.rst b/docs/source/exact_search_tuning.rst index 876360d3d..3483176ff 100644 --- a/docs/source/exact_search_tuning.rst +++ b/docs/source/exact_search_tuning.rst @@ -33,7 +33,7 @@ Start from a symptom * - The costliest queries of :class:`~qldpc.codes.distance.CosetLeaderSearch` by the Brouwer-Zimmermann method spend their time building completion tables - Lower :attr:`~SearchTuning.coset_completion_block_bits`, or set :attr:`~SearchTuning.completion_bound_max_table_bytes` to zero to build none. * - A search or count uses too much memory - - For distance searches and counts, lower :attr:`~SearchTuning.completion_bound_max_table_bytes`, which applies to each problem of a search, such as each sector of a CSS code, and to each sector of a count, besides the tables that it is building. + - For distance searches and counts, lower :attr:`~SearchTuning.completion_bound_max_table_bytes`, which applies to each sector of a search, such as the X-type logical operators of a CSS code, and to each sector of a count, besides the tables that it is building. For exhaustive enumeration, lower :attr:`~SearchTuning.enumeration_batch_exponent`. For the Brouwer-Zimmermann method of :class:`~qldpc.codes.distance.CosetLeaderSearch`, lower :attr:`~SearchTuning.max_css_single_pairs`. For its completion tables, lower :attr:`~SearchTuning.coset_completion_block_bits`, or :attr:`~SearchTuning.completion_bound_max_table_bytes`, which applies to each set of a family, or raise :attr:`~SearchTuning.coset_route_minimum_work`, so that fewer queries build extra families and tables. diff --git a/experiments/distance_tuning/trace.py b/experiments/distance_tuning/trace.py index 6a02c0939..c0786ec0e 100644 --- a/experiments/distance_tuning/trace.py +++ b/experiments/distance_tuning/trace.py @@ -11,18 +11,18 @@ ``completion_bound_max_cost_percent``, and layer, and the first test of each number of rows and weight for tables. For a connected-cluster search, it records each weight limit, and for a count by the MacWilliams method, each walk and test. The wrapper of each event says what it records. Each -layer and weight limit numbers its problem, such as a sector of a CSS code, in a ``problem`` field -(see ``wrap_problems``). The script prints the events, and with ``--output`` saves them as JSON -with the tuning and a fingerprint of the qLDPC source. With ``--setup-only``, it ends the workload -before the first layer of a BZ distance search, after its setup; workloads of other kinds run in -full. +layer and weight limit numbers its sector, such as the X-type logical operators of a CSS code, in a +``sector`` field (see ``wrap_sectors``). The script prints the events, and with ``--output`` saves +them as JSON with the tuning and a fingerprint of the qLDPC source. With ``--setup-only``, it ends +the workload before the first layer of a BZ distance search, after its setup; workloads of other +kinds run in full. With ``--compare``, the script instead says whether two saved traces of one workload, such as traces under two tunings or of two checkouts, make the same decisions, and prints the first that differs, unless one trace ends before it. If the tunings differ only in thresholds and every decision is the same, so is the search, apart from the time of the decisions themselves. The comparison sees the number of sets of each family but not the sets, not the states that a connected-cluster search -visits within a weight limit, and not the problems of layers and weight limits. +visits within a weight limit, and not the sectors of layers and weight limits. The script refuses to run if this process imports qLDPC from elsewhere; to trace another checkout, run the script of that checkout with its own Python. @@ -87,12 +87,12 @@ # The seconds of asking for automorphisms in the current weight limit of a connected-cluster search. CURRENT_ASK: dict[str, Any] = {} -# The index of the problem of each search, by the id of the search (see wrap_problems). -PROBLEM_INDICES: dict[int, int | None] = {} +# The index of the sector of each search, by the id of the search (see wrap_sectors). +SECTOR_INDICES: dict[int, int | None] = {} -# The index of the problem whose search is prepared next, within a call that wrap_problems wraps, or +# The index of the sector whose search is prepared next, within a call that wrap_sectors wraps, or # None outside such calls. -NEXT_PROBLEM_INDEX: int | None = None +NEXT_SECTOR_INDEX: int | None = None # The coverages that matroid partitioning tries within a call of get_partitioned_family, or None # outside such calls. @@ -183,7 +183,7 @@ def parse_args() -> argparse.Namespace: def install_wrappers() -> None: """Wrap the stages of the exact searches, in this process, to record events.""" - search_class = distance._BrouwerZimmermannSearch + search_class = distance._SectorSearch tables_class = completion_bounds.CompletionTables patches: list[tuple[object, str, Callable[[Any], Any]]] = [ (basis_families, f"get_{kind}_family", functools.partial(wrap_family, kind)) @@ -202,9 +202,9 @@ def install_wrappers() -> None: (completion_bounds, "considers_tables", wrap_considers), (completion_bounds, "is_within_cost_limit", wrap_limit), (certificates, "get_lp_lower_bound", wrap_linear_program), - (core, "get_distance_brouwer_zimmermann_many", wrap_problems), - (core, "get_distance_connected_cluster", wrap_problems), - (logical_counts, "get_distance_brouwer_zimmermann_many", wrap_problems), + (core, "get_distance_brouwer_zimmermann", wrap_sectors), + (core, "get_distance_connected_cluster", wrap_sectors), + (logical_counts, "get_distance_brouwer_zimmermann", wrap_sectors), (distance, "_prepare_brouwer_zimmermann_search", wrap_prepare), (support_search.SupportSearch, "__init__", wrap_support_search), (support_search.SupportSearch, "find_witness", wrap_find_witness), @@ -216,53 +216,53 @@ def install_wrappers() -> None: setattr(owner, name, wrap(getattr(owner, name))) -def wrap_problems(function: Callable[..., Any]) -> Callable[..., Any]: - """Number the problems of each call of the wrapped distance search from zero. +def wrap_sectors(function: Callable[..., Any]) -> Callable[..., Any]: + """Number the sectors of each call of the wrapped distance search from zero. - The wrapped function, ``get_distance_brouwer_zimmermann_many`` or - ``get_distance_connected_cluster``, prepares a search of each of its problems in the order in + The wrapped function, ``get_distance_brouwer_zimmermann`` or + ``get_distance_connected_cluster``, prepares a search of each of its sectors in the order in which it receives them, and ``wrap_prepare`` and ``wrap_support_search`` record the index of the - problem of each search. So a call with one problem has only problem 0. ``core._search_css`` + sector of each search. So a call with one sector has only sector 0. ``core._search_css`` puts the X sector, of the X-type logical operators, before the Z sector, and so does the distance search of a count. """ @functools.wraps(function) def wrapper(*args: Any, **kwargs: Any) -> Any: - global NEXT_PROBLEM_INDEX - NEXT_PROBLEM_INDEX = 0 + global NEXT_SECTOR_INDEX + NEXT_SECTOR_INDEX = 0 try: return function(*args, **kwargs) finally: - NEXT_PROBLEM_INDEX = None + NEXT_SECTOR_INDEX = None return wrapper -def take_problem_index() -> int | None: - """The index of the problem whose search is being prepared, or None outside a wrapped call. +def take_sector_index() -> int | None: + """The index of the sector whose search is being prepared, or None outside a wrapped call. Within a wrapped call, it also advances the index for the next search. """ - global NEXT_PROBLEM_INDEX - index = NEXT_PROBLEM_INDEX + global NEXT_SECTOR_INDEX + index = NEXT_SECTOR_INDEX if index is not None: - NEXT_PROBLEM_INDEX = index + 1 + NEXT_SECTOR_INDEX = index + 1 return index def wrap_prepare(function: Callable[..., Any]) -> Callable[..., Any]: - """Record, for each BZ distance search that a call prepares, the index of its problem. + """Record, for each BZ distance search that a call prepares, the index of its sector. - A problem that setup settles takes its index but has no search, and so no layers. + A sector that setup settles takes its index but has no search, and so no layers. """ @functools.wraps(function) def wrapper(*args: Any, **kwargs: Any) -> Any: - index = take_problem_index() + index = take_sector_index() prepared = function(*args, **kwargs) - if isinstance(prepared, distance._BrouwerZimmermannSearch): - PROBLEM_INDICES[id(prepared)] = index + if isinstance(prepared, distance._SectorSearch): + SECTOR_INDICES[id(prepared)] = index return prepared return wrapper @@ -531,7 +531,7 @@ def wrapper(search: Any) -> None: def wrap_advance(function: Callable[..., Any]) -> Callable[..., Any]: - """Record each layer that a search advances by, with the index of the problem of the search.""" + """Record each layer that a search advances by, with the index of the sector of the search.""" @functools.wraps(function) def wrapper(search: Any) -> int: @@ -547,7 +547,7 @@ def wrapper(search: Any) -> int: CURRENT_LAYER = { "event": "layer", "search": id(search), - "problem": PROBLEM_INDICES.get(id(search)), + "sector": SECTOR_INDICES.get(id(search)), "weight": weight, "dimension": dimension, "supports": math.comb(dimension, weight), @@ -694,14 +694,14 @@ def wrapper(*args: Any) -> Any: def wrap_support_search(function: Callable[..., Any]) -> Callable[..., Any]: - """Record the index of the problem of each connected-cluster search, as ``wrap_prepare`` does. + """Record the index of the sector of each connected-cluster search, as ``wrap_prepare`` does. Also time the function that the search calls to find automorphisms. """ @functools.wraps(function) def wrapper(search: Any, *args: Any, get_automorphisms: Any = None, **kwargs: Any) -> None: - PROBLEM_INDICES[id(search)] = take_problem_index() + SECTOR_INDICES[id(search)] = take_sector_index() if get_automorphisms is not None: get_automorphisms = functools.partial(time_finding, get_automorphisms) function(search, *args, get_automorphisms=get_automorphisms, **kwargs) @@ -733,7 +733,7 @@ def wrapper(search: Any, automorphisms: Any) -> None: def wrap_find_witness(function: Callable[..., Any]) -> Callable[..., Any]: """Record each weight limit of a connected-cluster search, and any request for automorphisms. - Each event names the problem of the search (see ``wrap_problems``). The predicted states are + Each event names the sector of the search (see ``wrap_sectors``). The predicted states are those that ``find_witness`` adds to the states visited so far, and compares with ``automorphism_minimum_states``, while the search has not yet asked. """ @@ -750,7 +750,7 @@ def wrapper(search: Any, max_weight: int) -> Any: event = { "event": "weight limit", "search": id(search), - "problem": PROBLEM_INDICES.get(id(search)), + "sector": SECTOR_INDICES.get(id(search)), "max_weight": max_weight, "states_before": states_before, "predicted_states": predicted, @@ -832,7 +832,7 @@ def print_trace(result: str, seconds: float) -> None: continue tables = "" if event["tables"] is None else f" tables={event['tables']}" print( - f" layer problem={event['problem']} w={event['weight']:<2d}" + f" layer sector={event['sector']} w={event['weight']:<2d}" f" rows={event['dimension']:<4d} sets={event['sets']:<2d}" f" scanned={event['scanned_sets']:<2d}" f" supports={event['supports']:.2e} evaluated={event['evaluated']:.2e}" diff --git a/src/qldpc/codes/distance/README.md b/src/qldpc/codes/distance/README.md index 2617e569b..5d41fca8e 100644 --- a/src/qldpc/codes/distance/README.md +++ b/src/qldpc/codes/distance/README.md @@ -19,6 +19,7 @@ The documentation cites the other names at `qldpc.codes.distance`. ## Terms - **Sector:** the words of one type that a search examines, such as the logical operators of one type of a CSS code. + A search of a classical code, of a qubit code that is not CSS, or of a circuit examines one sector. A Brouwer-Zimmermann search takes a basis of them, labeled to tell nontrivial words, such as logical operators, from trivial ones, such as stabilizers. A connected-cluster search takes checks whose kernel holds them and a matrix whose row space holds the trivial ones. - **Information set:** in most of the source, a basis of a sector, row reduced on `rank` pivot columns: its first `rank` rows are the identity there and its other rows zero. @@ -138,7 +139,7 @@ They are not arguments of public functions, whose arguments say what to compute - A search reads the active tuning once, when it starts, and passes the values that it needs down as arguments, including to compiled code, so that one search never mixes two tunings. The distance functions of `core.py` read it for a distance search, `CSSLogicalCounter.count_logical_ops` for a count, and `CosetLeaderSearch` when it is built. - `BrouwerZimmermannSearches` and `ConnectedClusterSearches`, which `get_distance_brouwer_zimmermann_many` and `get_distance_connected_cluster` build, read it only if their callers pass none. + `BrouwerZimmermannSearch` and `ConnectedClusterSearch`, which `get_distance_brouwer_zimmermann` and `get_distance_connected_cluster` build, read it only if their callers pass none. A cache that outlives a search is keyed by the values that it depends on, as the fields of `_CosetTuning` in `_brouwer_zimmermann/coset.py` key the cached searches of `CosetLeaderSearch`. - Only a value that qLDPC fixes before any search starts, such as the size of a cache, which `functools.lru_cache` fixes at import, is a constant in `_tuning.py`, read as `_tuning.NAME`. Constants fixed by the algorithm or by native integer widths, such as `WORK_CAP`, and the seeds of random generators, which make results reproducible rather than tune anything, stay in the modules that use them, except `MAX_VALUE`, the largest value of an integer field. diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py index a8046dab4..97d698065 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py @@ -31,19 +31,19 @@ from .._tuning import SearchTuning, get_tuning from . import affine_instance, affine_search -# The automorphism family of a problem: a basis family of the one set that a search scans, and the +# The automorphism family of a sector: a basis family of the one set that a search scans, and the # certificate of all of its images. _AutomorphismFamily = tuple[basis_families.BasisFamily, certificates.Certificate] -# A function that returns the automorphism family of a problem for a weight divisor, or None. +# A function that returns the automorphism family of a sector for a weight divisor, or None. _GetAutomorphismFamily = Callable[[int], _AutomorphismFamily | None] #################################################################################################### # search entry points -def get_distance_brouwer_zimmermann_many( - problems: Sequence[tuple[npt.NDArray[np.uint8], npt.NDArray[np.uint8]]], +def get_distance_brouwer_zimmermann( + sectors: Sequence[tuple[npt.NDArray[np.uint8], npt.NDArray[np.uint8]]], *, cutoff: int, weight_divisor: int = 1, @@ -52,41 +52,41 @@ def get_distance_brouwer_zimmermann_many( get_automorphisms: Callable[[], npt.NDArray[np.int_] | None] | None = None, tuning: SearchTuning | None = None, ) -> int: - """Compute the minimum distance across nested-code problems by BZ searches. + """Compute the minimum distance across nested-code sectors by a BZ search. The searches advance round-robin, and share their best upper bound, the weight of the lightest witness that any of them has found, but not their certificates (Section 3.3). Args: - problems: Nested-code bases and their quotient labels (see ``get_nested_code_basis``). The - distance of a problem is the least weight of a word of its basis with nonzero labels, or - of any nonzero word if its labels have no columns. Each problem must have such a word. + sectors: Nested-code bases and their quotient labels (see ``get_nested_code_basis``). The + distance of a sector is the least weight of a word of its basis with nonzero labels, or + of any nonzero word if its labels have no columns. Each sector must have such a word. cutoff: Return once the best upper bound is at most this cutoff. - weight_divisor: A proven divisor of the weights over which the problems minimize, to - whose multiples the certificates round up (Section 3.2). Default: 1. + weight_divisor: A proven divisor of the weights over which the sectors minimize, to whose + multiples the certificates round up (Section 3.2). Default: 1. upper_bound: A cap on the result, if any, such as the weight of a known witness outside - ``problems``, or ``max_weight + 1`` under a weight limit (Section 4.5). - get_disjoint_basis_families: If given, a function for each problem that returns a disjoint + ``sectors``, or ``max_weight + 1`` under a weight limit (Section 4.5). + get_disjoint_basis_families: If given, a function for each sector that returns a disjoint basis family of it, with its labels and certified with ``weight_divisor``, such as that of ``basis_families.get_disjoint_family``. A search calls it only if it needs the family. get_automorphisms: If given, returns None or an array whose rows ``g`` generate a group of column permutations, each mapping column ``j`` to column ``g[j]``. Each generator must - map the space and the excluded subspace of every problem onto themselves. A search + map the space and the excluded subspace of every sector onto themselves. A search calls the function at most once, and verifies the generators (Section 3.7). tuning: The tuning that every search uses throughout. Default: the active tuning. Returns: - The minimum of the distances of the problems and ``upper_bound``, or, after an early exit + The minimum of the distances of the sectors and ``upper_bound``, or, after an early exit at ``cutoff``, the weight of a witness or ``upper_bound``, whichever is at most ``cutoff``. Raises: - ValueError: If there are neither problems nor an upper bound, or if a generator from - ``get_automorphisms`` is not an automorphism of a problem whose search uses it. + ValueError: If there are neither sectors nor an upper bound, or if a generator from + ``get_automorphisms`` is not an automorphism of a sector whose search uses it. """ - searches = BrouwerZimmermannSearches( - problems, + search = BrouwerZimmermannSearch( + sectors, cutoff=cutoff, weight_divisor=weight_divisor, upper_bound=upper_bound, @@ -94,33 +94,33 @@ def get_distance_brouwer_zimmermann_many( get_automorphisms=get_automorphisms, tuning=tuning, ) - while not searches.finished: - searches.advance() - return searches.best + while not search.finished: + search.advance() + return search.best -class BrouwerZimmermannSearches: - """The BZ searches of several problems, which advance one layer at a time, round-robin. +class BrouwerZimmermannSearch: + """A BZ search of sectors, which advances one sector by one layer at a time, round-robin. - The arguments are those of ``get_distance_brouwer_zimmermann_many``, which advances the searches - until they finish. + The arguments are those of ``get_distance_brouwer_zimmermann``, which advances the search until + it finishes. Attributes: best: The shared upper bound: the least of ``upper_bound``, the weights of the lightest eligible rows, the results of setup, and the weights of the witnesses that the searches - have found as they advanced. A search can hold a lighter witness from its setup, which - lowers ``best`` once that search advances. Once the searches finish, ``best`` is the - result of ``get_distance_brouwer_zimmermann_many``. + of the sectors have found as they advanced. The search of a sector can hold a lighter + witness from its setup, which lowers ``best`` once that search advances. Once the + search finishes, ``best`` is the result of ``get_distance_brouwer_zimmermann``. Raises: - ValueError: As ``get_distance_brouwer_zimmermann_many`` says, when the searches are built. + ValueError: As ``get_distance_brouwer_zimmermann`` says, when the search is built. """ best: int def __init__( self, - problems: Sequence[tuple[npt.NDArray[np.uint8], npt.NDArray[np.uint8]]], + sectors: Sequence[tuple[npt.NDArray[np.uint8], npt.NDArray[np.uint8]]], *, cutoff: int, weight_divisor: int = 1, @@ -131,24 +131,24 @@ def __init__( tuning: SearchTuning | None = None, ) -> None: self._cutoff = cutoff - self._searches: list[_BrouwerZimmermannSearch] = [] + self._searches: list[_SectorSearch] = [] self._next = 0 - if not problems: + if not sectors: if upper_bound is None: - raise ValueError("Require at least one problem or an upper bound") + raise ValueError("Require at least one sector or an upper bound") self.best = upper_bound return - # Prepare a search of each problem, which setup may settle without searching. + # Prepare a search of each sector, which setup may settle without searching. tuning = get_tuning() if tuning is None else tuning initial_upper_bounds = [ - _get_lightest_eligible_row_weight(basis, labels) for basis, labels in problems + _get_lightest_eligible_row_weight(basis, labels) for basis, labels in sectors ] best = min(initial_upper_bounds) if upper_bound is not None: best = min(best, upper_bound) for index, ((basis, labels), initial_upper_bound) in enumerate( - zip(problems, initial_upper_bounds, strict=True) + zip(sectors, initial_upper_bounds, strict=True) ): prepared = _prepare_brouwer_zimmermann_search( basis, @@ -172,19 +172,19 @@ def __init__( @property def finished(self) -> bool: - """Whether the best upper bound is at most the cutoff, or every search has finished.""" + """Whether the best upper bound is at most the cutoff, or every sector's search finished.""" return self.best <= self._cutoff or all(search.finished for search in self._searches) def advance(self) -> None: - """Advance the next unfinished search, in round-robin order, by one layer, unless finished. + """Advance the next unfinished sector, in round-robin order, by one layer, unless finished. - Every search then takes the best upper bound, which shares witnesses between problems. If - this raises, as at a keyboard interrupt, the searches can be left inconsistent, so build new - ones to search again. + The search of every sector then takes the best upper bound, which shares witnesses between + sectors. If this raises, as at a keyboard interrupt, the search can be left inconsistent, + so build a new one to search again. Raises: ValueError: If a generator from ``get_automorphisms`` is not an automorphism of the - problem of the search that uses it. + sector whose search uses it. """ if self.finished: return @@ -196,7 +196,7 @@ def advance(self) -> None: self._share_best() def _share_best(self) -> None: - """Give every search the best upper bound; a search that this finishes frees its tables.""" + """Give each sector's search the best upper bound; one that finishes frees its tables.""" for search in self._searches: search.update_upper_bound(self.best) @@ -206,8 +206,8 @@ def _share_best(self) -> None: @dataclass -class _BrouwerZimmermannSearch: - """State for one resumable Brouwer-Zimmermann search. +class _SectorSearch: + """State for the resumable Brouwer-Zimmermann search of one sector. ``instance`` holds the packed sets that the search scans, and the certificate of its family: those sets, or, if ``uses_automorphism_family``, every image of the one packed set under @@ -215,7 +215,7 @@ class _BrouwerZimmermannSearch: the search has finished once ``lower_bound`` reaches ``best``. ``lower_bound`` bounds only the eligible words lighter than ``best`` (Section 3.9, "Certificates and contracts"). - ``get_automorphism_family``, if given, returns an automorphism family of the problem, or None. + ``get_automorphism_family``, if given, returns an automorphism family of the sector, or None. The search calls it at most once, and then sets it to None. A search that declines to switch keeps the family in ``automorphism_family``, and its best weight at that time in ``declined_best`` (Section 3.7, "When a search uses an automorphism family"). @@ -433,13 +433,13 @@ def _prepare_brouwer_zimmermann_search( get_disjoint_basis_family: Callable[[], basis_families.BasisFamily] | None = None, get_automorphisms: Callable[[], npt.NDArray[np.int_] | None] | None = None, tuning: SearchTuning, -) -> int | _BrouwerZimmermannSearch: +) -> int | _SectorSearch: """Prepare one BZ search, or return its result if setup already settles it. The stages of ``basis_families`` run in order, and between them setup returns if the rows of the family bring the best weight to the cutoff, or if its certificate proves the best weight (Section 4.2). ``get_disjoint_basis_family``, if given, returns the result of the first stage, - and ``get_automorphisms`` is as for ``get_distance_brouwer_zimmermann_many``. + and ``get_automorphisms`` is as for ``get_distance_brouwer_zimmermann``. """ dimension = len(basis) best = min( @@ -529,7 +529,7 @@ def _prepare_brouwer_zimmermann_search( if lower_bound >= best: return best - search = _BrouwerZimmermannSearch( + search = _SectorSearch( affine_instance.get_distance_instance( basis_family, basis_family.get_search_certificate( @@ -561,7 +561,7 @@ def _get_automorphism_family( get_automorphisms: Callable[[], npt.NDArray[np.int_] | None], weight_divisor: int, ) -> _AutomorphismFamily | None: - """Verify the automorphisms of a problem, and build the automorphism family of one set. + """Verify the automorphisms of a sector, and build the automorphism family of one set. ``basis`` is an independent basis of the searched space, with quotient labels ``labels``, and ``weight_divisor`` divides the Hamming weight of every eligible word. @@ -571,7 +571,7 @@ def _get_automorphism_family( ``get_automorphisms`` returns None. Raises: - ValueError: If a generator is not an automorphism of the problem. + ValueError: If a generator is not an automorphism of the sector. """ automorphisms = get_automorphisms() if automorphisms is None: @@ -589,7 +589,7 @@ def _get_automorphism_family_work( ) -> int: """The estimated work of the automorphism family that a search can switch to. - Returns ``WORK_CAP`` if the problem has no automorphism family. + Returns ``WORK_CAP`` if the sector has no automorphism family. """ automorphism_family = get_automorphism_family(weight_divisor) if automorphism_family is None: diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py index ffb6ad75b..f6bd9f2b2 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py @@ -31,7 +31,7 @@ CostlyStages, get_random_css_code, get_random_full_rank_matrix, - get_sector_problem, + get_sector, ) from . import affine_instance, affine_search from . import distance as bz @@ -48,7 +48,7 @@ def test_brouwer_zimmermann_search_state() -> None: """Only completed layers advance the certificate, not interrupted ones or ones cut off.""" # One set of rank zero, whose two eligible rows weigh two and one. - search = bz._BrouwerZimmermannSearch( + search = bz._SectorSearch( affine_instance.AffineInstance( generators=np.array([[[3], [2]]], dtype=np.uint64), labels=np.ones((1, 2, 1), dtype=np.uint64), @@ -90,7 +90,7 @@ def test_the_largest_layer_threshold_never_asks_for_automorphisms() -> None: assert math.comb(dimension, weight) > MAX_VALUE for minimum_layer_work, expected_calls in ((MAX_VALUE, 0), (2**61, 1)): get_automorphism_family = mock.Mock(return_value=None) - search = bz._BrouwerZimmermannSearch( + search = bz._SectorSearch( affine_instance.AffineInstance( generators=np.zeros((1, dimension, 2), dtype=np.uint64), labels=np.zeros((1, dimension, 1), dtype=np.uint64), @@ -236,7 +236,7 @@ def test_an_upper_bound_acts_as_a_known_witness() -> None: """A search returns the smaller of its upper bound and the distance.""" basis = get_independent_rows(np.asarray(qldpc.codes.HammingCode(3).generator, dtype=np.uint8)) for upper_bound, expected in ((2, 2), (3, 3), (5, 3)): - distance = bz.get_distance_brouwer_zimmermann_many( + distance = bz.get_distance_brouwer_zimmermann( [(basis, _no_labels(basis))], cutoff=0, upper_bound=upper_bound ) assert distance == expected @@ -265,7 +265,7 @@ def test_brouwer_zimmermann_shared_search() -> None: cutoff=0, method="brute_force", ) - actual = bz.get_distance_brouwer_zimmermann_many( + actual = bz.get_distance_brouwer_zimmermann( [(basis_a, _no_labels(basis_a)), (basis_b, labels_b)], cutoff=0, ) @@ -284,7 +284,7 @@ def test_labels_of_more_than_one_machine_word() -> None: expected = qldpc.codes.distance.get_distance_from_generators( basis, cutoff=0, method="brute_force" ) - assert bz.get_distance_brouwer_zimmermann_many([(basis, labels)], cutoff=0) == expected + assert bz.get_distance_brouwer_zimmermann([(basis, labels)], cutoff=0) == expected def test_a_given_disjoint_basis_family_replaces_the_first_stage() -> None: @@ -292,14 +292,14 @@ def test_a_given_disjoint_basis_family_replaces_the_first_stage() -> None: rng = np.random.default_rng(121) basis = get_random_full_rank_matrix(rng, 5, 9) labels = np.vstack([np.zeros((2, 3), dtype=np.uint8), np.eye(3, dtype=np.uint8)]) - expected = bz.get_distance_brouwer_zimmermann_many([(basis, labels)], cutoff=0) + expected = bz.get_distance_brouwer_zimmermann([(basis, labels)], cutoff=0) get_basis_family = mock.Mock( return_value=basis_families.get_disjoint_family( basis, labels, random_column_orders=DEFAULT_TUNING.disjoint_random_column_orders ) ) search = functools.partial( - bz.get_distance_brouwer_zimmermann_many, + bz.get_distance_brouwer_zimmermann, [(basis, labels)], get_disjoint_basis_families=[get_basis_family], ) @@ -337,27 +337,27 @@ def test_brouwer_zimmermann_sector_certificates() -> None: ] assert expected == [4, 2] - searches: list[bz._BrouwerZimmermannSearch] = [] + searches: list[bz._SectorSearch] = [] advanced: set[int] = set() original_prepare = bz._prepare_brouwer_zimmermann_search - original_advance = bz._BrouwerZimmermannSearch.advance + original_advance = bz._SectorSearch.advance - def prepare(*args: Any, **kwargs: Any) -> int | bz._BrouwerZimmermannSearch: + def prepare(*args: Any, **kwargs: Any) -> int | bz._SectorSearch: result = original_prepare(*args, **kwargs) - if isinstance(result, bz._BrouwerZimmermannSearch): + if isinstance(result, bz._SectorSearch): searches.append(result) return result - def advance(search: bz._BrouwerZimmermannSearch) -> int: + def advance(search: bz._SectorSearch) -> int: advanced.add(id(search)) return original_advance(search) # Exercise real layer advancement, rather than two results certified during setup. with ( mock.patch.object(bz, "_prepare_brouwer_zimmermann_search", side_effect=prepare), - mock.patch.object(bz._BrouwerZimmermannSearch, "advance", advance), + mock.patch.object(bz._SectorSearch, "advance", advance), ): - actual = bz.get_distance_brouwer_zimmermann_many( + actual = bz.get_distance_brouwer_zimmermann( [(basis_a, _no_labels(basis_a)), (basis_b, _no_labels(basis_b))], cutoff=0 ) assert actual == min(expected) @@ -627,11 +627,11 @@ def test_automorphism_family_searches_scan_every_layer_they_certify( # search finds sums four rows of that set. Completing layer four certifies weight ten, so a # search that certified that layer before scanning it would return ten. code = qldpc.codes.BBCode({x: 12, y: 3}, 1 + x + x**4 * y, 1 + y + x**2) - problem = get_sector_problem(code, Pauli.X) - expected = bz.get_distance_brouwer_zimmermann_many([problem], cutoff=0) + sector = get_sector(code, Pauli.X) + expected = bz.get_distance_brouwer_zimmermann([sector], cutoff=0) assert expected == 8 - distance = bz.get_distance_brouwer_zimmermann_many( - [problem], cutoff=0, get_automorphisms=code._get_qudit_automorphisms + distance = bz.get_distance_brouwer_zimmermann( + [sector], cutoff=0, get_automorphisms=code._get_qudit_automorphisms ) assert distance == expected @@ -643,14 +643,14 @@ def test_automorphism_family_searches_scan_every_layer_they_certify( @pytest.fixture -def prepared(monkeypatch: pytest.MonkeyPatch) -> list[bz._BrouwerZimmermannSearch]: - """The searches that setup prepares, rather than settles, in the order of their problems.""" - searches: list[bz._BrouwerZimmermannSearch] = [] +def prepared(monkeypatch: pytest.MonkeyPatch) -> list[bz._SectorSearch]: + """The searches that setup prepares, rather than settles, in the order of their sectors.""" + searches: list[bz._SectorSearch] = [] prepare = bz._prepare_brouwer_zimmermann_search def recording_prepare(*args: Any, **kwargs: Any) -> Any: result = prepare(*args, **kwargs) - if isinstance(result, bz._BrouwerZimmermannSearch): + if isinstance(result, bz._SectorSearch): searches.append(result) return result @@ -659,7 +659,7 @@ def recording_prepare(*args: Any, **kwargs: Any) -> Any: def test_stepped_searches_advance_one_unfinished_search_at_a_time_in_turn( - monkeypatch: pytest.MonkeyPatch, prepared: list[bz._BrouwerZimmermannSearch] + monkeypatch: pytest.MonkeyPatch, prepared: list[bz._SectorSearch] ) -> None: """Each advance scans one layer of the next unfinished search, in turn, until all finish. @@ -667,28 +667,28 @@ def test_stepped_searches_advance_one_unfinished_search_at_a_time_in_turn( """ # Record the index of each search that advances, and which searches had finished by then. visits: list[tuple[int, list[bool]]] = [] - advance = bz._BrouwerZimmermannSearch.advance + advance = bz._SectorSearch.advance - def recording_advance(search: bz._BrouwerZimmermannSearch) -> int: + def recording_advance(search: bz._SectorSearch) -> int: visits.append((prepared.index(search), [other.finished for other in prepared])) return advance(search) - monkeypatch.setattr(bz._BrouwerZimmermannSearch, "advance", recording_advance) + monkeypatch.setattr(bz._SectorSearch, "advance", recording_advance) # This code has distance 4, as the connected-cluster method finds. One sector's search finishes # while the other's goes on, so the turns skip it. code = get_random_css_code(np.random.default_rng(4), 60, 20, 25) - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] - searches = bz.BrouwerZimmermannSearches(problems, cutoff=0) + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] + search = bz.BrouwerZimmermannSearch(sectors, cutoff=0) num_searches = len(prepared) - assert num_searches == 2 and not searches.finished - lightest_rows = [basis[np.any(labels, axis=1)].sum(axis=1).min() for basis, labels in problems] - assert searches.best <= min(lightest_rows) - bests = [searches.best] - while not searches.finished: + assert num_searches == 2 and not search.finished + lightest_rows = [basis[np.any(labels, axis=1)].sum(axis=1).min() for basis, labels in sectors] + assert search.best <= min(lightest_rows) + bests = [search.best] + while not search.finished: num_visits = len(visits) - searches.advance() + search.advance() assert len(visits) == num_visits + 1 - bests.append(searches.best) + bests.append(search.best) assert bests == sorted(bests, reverse=True) and bests[-1] == 4 # Each search that advances is the first unfinished one after the last, in cyclic order. @@ -701,32 +701,32 @@ def recording_advance(search: bz._BrouwerZimmermannSearch) -> int: index == previous_index for (index, _), (previous_index, _) in zip(visits[1:], visits) ) - # Once finished, the searches do nothing. + # Once finished, the search does nothing. num_visits = len(visits) - searches.advance() + search.advance() assert len(visits) == num_visits def test_searches_that_setup_settles_are_finished_at_once( - prepared: list[bz._BrouwerZimmermannSearch], + prepared: list[bz._SectorSearch], ) -> None: - """Searches are finished when built if setup settles them, or with no problems. + """A search is finished when built if setup settles every sector, or with no sectors. - Setup settles the Hamming problem directly. In the random code, it settles one sector, whose - witness finishes the search of the other. + Setup settles the sector of the Hamming code directly. In the random code, it settles one + sector, whose witness finishes the search of the other. """ - searches = bz.BrouwerZimmermannSearches([], cutoff=0, upper_bound=3) - assert searches.finished and searches.best == 3 + search = bz.BrouwerZimmermannSearch([], cutoff=0, upper_bound=3) + assert search.finished and search.best == 3 hamming_code = qldpc.codes.HammingCode(3) - problem = (np.asarray(hamming_code.generator, dtype=np.uint8), np.zeros((4, 0), np.uint8)) - searches = bz.BrouwerZimmermannSearches([problem], cutoff=7) - assert searches.finished and searches.best == 3 and not prepared + sector = (np.asarray(hamming_code.generator, dtype=np.uint8), np.zeros((4, 0), np.uint8)) + search = bz.BrouwerZimmermannSearch([sector], cutoff=7) + assert search.finished and search.best == 3 and not prepared code = get_random_css_code(np.random.default_rng(153), 16, 5, 5) - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] - searches = bz.BrouwerZimmermannSearches(problems, cutoff=0) - assert len(prepared) == 1 and searches.finished - assert searches.best == code.get_distance(method="brute_force") == 2 + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] + search = bz.BrouwerZimmermannSearch(sectors, cutoff=0) + assert len(prepared) == 1 and search.finished + assert search.best == code.get_distance(method="brute_force") == 2 @pytest.mark.usefixtures("switch_before_any_layer", "completion_tables") @@ -734,8 +734,8 @@ def test_automorphism_family_searches_find_exact_distances() -> None: """Searches given automorphisms agree with brute force, alone or sharing witnesses.""" code = qldpc.codes.MBCode({x: 12}, x**10 + x**4 + x**2 + x, x**9 + x**8 + x**3 + x) identity = np.arange(len(code))[None] - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] - for problem, pauli in zip(problems, PAULIS_XZ): + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] + for sector, pauli in zip(sectors, PAULIS_XZ): expected = qldpc.codes.distance.get_distance_from_generators( code.get_logical_ops(pauli), code.get_stabilizer_ops(pauli), @@ -743,21 +743,21 @@ def test_automorphism_family_searches_find_exact_distances() -> None: method="brute_force", ) for get_automorphisms in (code._get_qudit_automorphisms, lambda: identity, lambda: None): - distance = bz.get_distance_brouwer_zimmermann_many( - [problem], cutoff=0, get_automorphisms=get_automorphisms + distance = bz.get_distance_brouwer_zimmermann( + [sector], cutoff=0, get_automorphisms=get_automorphisms ) assert distance == expected - assert bz.get_distance_brouwer_zimmermann_many( - problems, cutoff=0, get_automorphisms=code._get_qudit_automorphisms + assert bz.get_distance_brouwer_zimmermann( + sectors, cutoff=0, get_automorphisms=code._get_qudit_automorphisms ) == code.get_distance(method="brute_force") def test_stepped_searches_use_the_tuning_that_they_are_given( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Searches built with a tuning prepare every problem with it, whatever the active tuning. + """Searches built with a tuning prepare every sector with it, whatever the active tuning. - The function that builds the searches passes its tuning on, so calling it checks both. + The function that builds the search passes its tuning on, so calling it checks both. """ tunings: list[Any] = [] prepare = bz._prepare_brouwer_zimmermann_search @@ -769,9 +769,9 @@ def recording_prepare(*args: Any, **kwargs: Any) -> Any: monkeypatch.setattr(bz, "_prepare_brouwer_zimmermann_search", recording_prepare) code = get_random_css_code(np.random.default_rng(153), 16, 5, 5) tuning = dataclasses.replace(DEFAULT_TUNING, information_set_batch_exponent=5) - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] with use_tuning(information_set_batch_exponent=6): - bz.get_distance_brouwer_zimmermann_many(problems, cutoff=0, tuning=tuning) + bz.get_distance_brouwer_zimmermann(sectors, cutoff=0, tuning=tuning) assert tunings == [tuning, tuning] @@ -795,7 +795,7 @@ def test_automorphism_family_searches_scan_their_new_set_from_layer_two( 1, ) tune(automorphism_minimum_layer_work=math.comb(size, 3)) - distance = bz.get_distance_brouwer_zimmermann_many( + distance = bz.get_distance_brouwer_zimmermann( [(basis, labels)], cutoff=0, get_disjoint_basis_families=[lambda: first_family], @@ -817,12 +817,12 @@ def test_automorphism_family_searches_scan_their_new_set_from_layer_two( def test_searches_ask_for_automorphisms_only_before_costly_layers() -> None: """A search asks for automorphisms at most once, only before a costly layer or partitioning.""" code = qldpc.codes.MBCode({x: 12}, x**10 + x**4 + x**2 + x, x**9 + x**8 + x**3 + x) - problem = get_sector_problem(code, Pauli.X) + sector = get_sector(code, Pauli.X) for minimum_layer_work, expected_calls in ((10**9, 0), (0, 1)): get_automorphisms = mock.Mock(wraps=code._get_qudit_automorphisms) with use_tuning(automorphism_minimum_layer_work=minimum_layer_work): - bz.get_distance_brouwer_zimmermann_many( - [problem], cutoff=0, get_automorphisms=get_automorphisms + bz.get_distance_brouwer_zimmermann( + [sector], cutoff=0, get_automorphisms=get_automorphisms ) assert get_automorphisms.call_count == expected_calls @@ -831,15 +831,13 @@ def test_searches_ask_for_automorphisms_only_before_costly_layers() -> None: def switch_decisions(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, bool]]: """Record each consideration of a switch to automorphism images: the best weight and outcome.""" decisions: list[tuple[int, bool]] = [] - switch = bz._BrouwerZimmermannSearch._switch_to_automorphism_family + switch = bz._SectorSearch._switch_to_automorphism_family - def recording_switch(search: bz._BrouwerZimmermannSearch) -> None: + def recording_switch(search: bz._SectorSearch) -> None: switch(search) decisions.append((search.best, search.uses_automorphism_family)) - monkeypatch.setattr( - bz._BrouwerZimmermannSearch, "_switch_to_automorphism_family", recording_switch - ) + monkeypatch.setattr(bz._SectorSearch, "_switch_to_automorphism_family", recording_switch) return decisions @@ -870,15 +868,13 @@ def test_a_declined_switch_is_reconsidered_once_the_best_weight_drops( get_automorphisms=get_automorphisms, tuning=tuning, ) - assert isinstance(search, bz._BrouwerZimmermannSearch) + assert isinstance(search, bz._SectorSearch) get_family = search.get_automorphism_family = mock.Mock( wraps=search.get_automorphism_family ) while not search.finished: search.advance() - assert ( - search.best == bz.get_distance_brouwer_zimmermann_many([(basis, labels)], cutoff=0) == 8 - ) + assert search.best == bz.get_distance_brouwer_zimmermann([(basis, labels)], cutoff=0) == 8 assert switch_decisions == expected assert get_automorphisms.call_count == get_family.call_count == 1 @@ -924,7 +920,7 @@ def test_a_decline_at_the_end_of_setup_is_reconsidered_before_a_costly_layer( matroid_partition, "get_information_sets_with_coverage", wraps=get_information_sets ) as partition, ): - distance = bz.get_distance_brouwer_zimmermann_many( + distance = bz.get_distance_brouwer_zimmermann( [(basis, labels)], cutoff=0, get_automorphisms=lambda: identity ) assert distance == expected_distance == 9 @@ -947,10 +943,10 @@ def test_a_late_switch_weighs_the_layers_left_in_the_current_family( basis = _get_cyclic_basis("111100101101100010011", 35) labels = _no_labels(basis) automorphisms = np.roll(np.arange(35), -7)[None] - distance = bz.get_distance_brouwer_zimmermann_many( + distance = bz.get_distance_brouwer_zimmermann( [(basis, labels)], cutoff=0, get_automorphisms=lambda: automorphisms ) - assert distance == bz.get_distance_brouwer_zimmermann_many([(basis, labels)], cutoff=0) == 8 + assert distance == bz.get_distance_brouwer_zimmermann([(basis, labels)], cutoff=0) == 8 assert switch_decisions == [(8, False)] @@ -958,19 +954,19 @@ def test_searches_switch_to_automorphism_images_instead_of_partitioning(tune: Tu """A search skips partitioning, and switches at once, if automorphism images do no more work.""" tune(partition_work_ratio=0, max_information_sets=16) code = qldpc.codes.MBCode({x: 12}, x**10 + x**4 + x**2 + x, x**9 + x**8 + x**3 + x) - problem = get_sector_problem(code, Pauli.X) + sector = get_sector(code, Pauli.X) identity = np.arange(len(code))[None] expected = qldpc.codes.distance.get_distance_from_generators( code.get_logical_ops(Pauli.X), code.get_stabilizer_ops(Pauli.X), method="brute_force" ) get_information_sets = matroid_partition.get_information_sets_with_coverage - switch = bz._BrouwerZimmermannSearch._switch_to_automorphism_family + switch = bz._SectorSearch._switch_to_automorphism_family # The switch spy records whether each search that considers a switch makes it. A search that # partitions in setup may finish there, and consider none. switched: list[bool] = [] - def _spy_switch(search: bz._BrouwerZimmermannSearch) -> None: + def _spy_switch(search: bz._SectorSearch) -> None: switch(search) switched.append(search.uses_automorphism_family) @@ -989,12 +985,10 @@ def _spy_switch(search: bz._BrouwerZimmermannSearch) -> None: mock.patch.object( matroid_partition, "get_information_sets_with_coverage", wraps=get_information_sets ) as partition, - mock.patch.object( - bz._BrouwerZimmermannSearch, "_switch_to_automorphism_family", _spy_switch - ), + mock.patch.object(bz._SectorSearch, "_switch_to_automorphism_family", _spy_switch), ): - distance = bz.get_distance_brouwer_zimmermann_many( - [problem], cutoff=0, get_automorphisms=recorder + distance = bz.get_distance_brouwer_zimmermann( + [sector], cutoff=0, get_automorphisms=recorder ) assert distance == expected assert partition.called == partitions @@ -1009,9 +1003,7 @@ def _spy_switch(search: bz._BrouwerZimmermannSearch) -> None: mock.patch.object( matroid_partition, "get_information_sets_with_coverage", wraps=get_information_sets ) as partition, - mock.patch.object( - bz._BrouwerZimmermannSearch, "_switch_to_automorphism_family", _spy_switch - ), + mock.patch.object(bz._SectorSearch, "_switch_to_automorphism_family", _spy_switch), ): assert ( qldpc.codes.distance.get_distance_from_generators( @@ -1030,8 +1022,8 @@ def test_a_switch_at_the_end_of_setup_can_certify_the_distance(tune: Tune) -> No expected = qldpc.codes.distance.get_distance_from_generators( code.get_logical_ops(Pauli.X), code.get_stabilizer_ops(Pauli.X), method="brute_force" ) - distance = bz.get_distance_brouwer_zimmermann_many( - [get_sector_problem(code, Pauli.X)], + distance = bz.get_distance_brouwer_zimmermann( + [get_sector(code, Pauli.X)], cutoff=0, get_automorphisms=code._get_qudit_automorphisms, ) @@ -1049,10 +1041,10 @@ def test_rows_of_an_automorphism_family_can_reach_the_cutoff( # after asking for automorphisms to decide whether to partition. tune(overlapping_minimum_work=MAX_VALUE, partition_work_ratio=partition_work_ratio) code = qldpc.codes.BBCode({x: 6, y: 3}, 1 + x + x**3 * y, 1 + y + x) - problem = get_sector_problem(code, Pauli.Z) - assert bz.get_distance_brouwer_zimmermann_many([problem], cutoff=0) == 4 - distance = bz.get_distance_brouwer_zimmermann_many( - [problem], cutoff=6, get_automorphisms=code._get_qudit_automorphisms + sector = get_sector(code, Pauli.Z) + assert bz.get_distance_brouwer_zimmermann([sector], cutoff=0) == 4 + distance = bz.get_distance_brouwer_zimmermann( + [sector], cutoff=6, get_automorphisms=code._get_qudit_automorphisms ) assert distance == 6 @@ -1064,8 +1056,8 @@ def test_searches_reject_wrong_automorphisms() -> None: transposition = np.arange(len(code)) transposition[[0, 1]] = [1, 0] with pytest.raises(ValueError, match="not an automorphism"): - bz.get_distance_brouwer_zimmermann_many( - [get_sector_problem(code, Pauli.X)], + bz.get_distance_brouwer_zimmermann( + [get_sector(code, Pauli.X)], cutoff=0, get_automorphisms=lambda: transposition[None], ) @@ -1153,8 +1145,8 @@ def assert_skips(distance: int) -> int: # that is too high changes the distance. An overlapping family would hold a word of # weight four, and end the search before any layer. with use_tuning(completion_bound_block_bits=16, overlapping_minimum_work=MAX_VALUE): - distance = bz.get_distance_brouwer_zimmermann_many( - [get_sector_problem(code, pauli)], + distance = bz.get_distance_brouwer_zimmermann( + [get_sector(code, pauli)], cutoff=0, upper_bound=upper_bound, get_automorphisms=code._get_qudit_automorphisms, @@ -1162,17 +1154,17 @@ def assert_skips(distance: int) -> int: assert assert_skips(distance) == expected # Relabel the columns, and the automorphisms alike: column ``j`` is column ``columns[j]`` of - # the given problem, so a generator ``g`` maps it to ``inverse[g[columns[j]]]``, for the inverse - # permutation ``np.argsort(columns)``. The search of the given problem, without automorphisms + # the given sector, so a generator ``g`` maps it to ``inverse[g[columns[j]]]``, for the inverse + # permutation ``np.argsort(columns)``. The search of the given sector, without automorphisms # or tables, is the oracle. code = qldpc.codes.BBCode({x: 12, y: 3}, 1 + x + x**4 * y, 1 + y + x**2) - basis, labels = get_sector_problem(code, Pauli.X) + basis, labels = get_sector(code, Pauli.X) with use_tuning(completion_bound_max_table_bytes=0): - expected = bz.get_distance_brouwer_zimmermann_many([(basis, labels)], cutoff=0) + expected = bz.get_distance_brouwer_zimmermann([(basis, labels)], cutoff=0) columns = rng.permutation(len(code)) automorphisms = np.asarray(code._get_qudit_automorphisms()) skipped = completion_tables.skipped - distance = bz.get_distance_brouwer_zimmermann_many( + distance = bz.get_distance_brouwer_zimmermann( [(basis[:, columns], labels)], cutoff=0, get_automorphisms=functools.partial( @@ -1196,7 +1188,7 @@ def assert_skips(distance: int) -> int: def test_sets_that_are_not_information_sets_count_pivot_ones_only_below_their_rank() -> None: """A set of rank zero has no pivot ones, so its words weigh only their packed rows.""" - search = bz._BrouwerZimmermannSearch( + search = bz._SectorSearch( affine_instance.AffineInstance( generators=np.array([[[7], [6]]], dtype=np.uint64), labels=np.array([[[1], [2]]], dtype=np.uint64), @@ -1220,11 +1212,11 @@ def test_joint_searches_with_completion_tables( completion_tables: CompletionRecord, monkeypatch: pytest.MonkeyPatch ) -> None: """Joint searches that use tables in every layer are exact, and free their tables.""" - searches: list[bz._BrouwerZimmermannSearch] = [] + searches: list[bz._SectorSearch] = [] skipped: list[int] = [] - advance = bz._BrouwerZimmermannSearch.advance + advance = bz._SectorSearch.advance - def counting_advance(search: bz._BrouwerZimmermannSearch) -> int: + def counting_advance(search: bz._SectorSearch) -> int: if not any(known is search for known in searches): searches.append(search) skipped.append(0) @@ -1234,14 +1226,14 @@ def counting_advance(search: bz._BrouwerZimmermannSearch) -> int: skipped[index] += completion_tables.skipped - skipped_before return best - monkeypatch.setattr(bz._BrouwerZimmermannSearch, "advance", counting_advance) + monkeypatch.setattr(bz._SectorSearch, "advance", counting_advance) code = qldpc.codes.MBCode({x: 15}, x**10 + x**4 + x**2 + x, x**9 + x**8 + x**3 + x) - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] for upper_bound, expected in ((None, code.get_distance(method="brute_force")), (5, 5)): searches.clear() skipped.clear() - distance = bz.get_distance_brouwer_zimmermann_many( - problems, + distance = bz.get_distance_brouwer_zimmermann( + sectors, cutoff=0, upper_bound=upper_bound, get_automorphisms=code._get_qudit_automorphisms, @@ -1258,7 +1250,7 @@ def test_layers_of_several_sets_scan_each_set_with_its_tables( ) -> None: """Searches that scan several sets of a layer, each with its own tables or none, are exact.""" select = completion_bounds.select_completion_tables - scan_set_method = bz._BrouwerZimmermannSearch._scan_set + scan_set_method = bz._SectorSearch._scan_set scan_set = affine_search.scan_set num_choices, scanned_index, returned_to_first_set = 0, 0, False later_scans = {"with tables": 0, "without tables": 0} @@ -1270,7 +1262,7 @@ def mixing_select(*args: Any, **kwargs: Any) -> completion_bounds.CompletionTabl tables = select(*args, **kwargs) return None if mixed and num_choices % 2 else tables - def recording_scan_set(search: bz._BrouwerZimmermannSearch, index: int, weight: int) -> bool: + def recording_scan_set(search: bz._SectorSearch, index: int, weight: int) -> bool: nonlocal scanned_index, returned_to_first_set returned_to_first_set = index == 0 and scanned_index > 0 scanned_index = index @@ -1288,12 +1280,10 @@ def checking_scan(*args: Any) -> tuple[int, int, int, int, int]: return scan_set(*args) monkeypatch.setattr(completion_bounds, "select_completion_tables", mixing_select) - monkeypatch.setattr(bz._BrouwerZimmermannSearch, "_scan_set", recording_scan_set) + monkeypatch.setattr(bz._SectorSearch, "_scan_set", recording_scan_set) monkeypatch.setattr(affine_search, "scan_set", checking_scan) generators = get_random_full_rank_matrix(np.random.default_rng(4), 10, 36) - distance = bz.get_distance_brouwer_zimmermann_many( - [(generators, _no_labels(generators))], cutoff=0 - ) + distance = bz.get_distance_brouwer_zimmermann([(generators, _no_labels(generators))], cutoff=0) assert distance == qldpc.codes.distance.get_distance_from_generators( generators, cutoff=0, method="brute_force" ) @@ -1318,7 +1308,7 @@ def test_a_layer_of_several_sets_stops_once_its_sets_certify_the_best_weight(cut # completion of the layer certifies. A cutoff of five stops the scan at that word, before the # search certifies more than four. family, certificate = _get_family(generators, [[0, 1, 2], [3, 4, 5]]) - search = bz._BrouwerZimmermannSearch( + search = bz._SectorSearch( affine_instance.get_distance_instance(family, certificate), cutoff=cutoff, batch_size=1 << 20, @@ -1328,13 +1318,13 @@ def test_a_layer_of_several_sets_stops_once_its_sets_certify_the_best_weight(cut next_weight=2, ) scanned: list[int] = [] - scan_set_method = bz._BrouwerZimmermannSearch._scan_set + scan_set_method = bz._SectorSearch._scan_set - def recording_scan_set(search: bz._BrouwerZimmermannSearch, index: int, weight: int) -> bool: + def recording_scan_set(search: bz._SectorSearch, index: int, weight: int) -> bool: scanned.append(index) return scan_set_method(search, index, weight) - with mock.patch.object(bz._BrouwerZimmermannSearch, "_scan_set", recording_scan_set): + with mock.patch.object(bz._SectorSearch, "_scan_set", recording_scan_set): assert search.advance() == 5 assert search.finished and search.lower_bound == (4 if cutoff else 5) assert scanned == [0] @@ -1353,7 +1343,7 @@ def test_a_layer_with_a_set_that_is_not_an_information_set_is_exact() -> None: # The second set has rank two, and finds the lightest word, of weight four, in layer two. The # tuning forces tables, so the second set must scan without those of the first set. family, certificate = _get_family(generators, [[0, 1, 2], [3, 4, 5]]) - search = bz._BrouwerZimmermannSearch( + search = bz._SectorSearch( affine_instance.get_distance_instance(family, certificate), cutoff=0, batch_size=1 << 20, @@ -1401,9 +1391,7 @@ def checking_build( monkeypatch.setattr(completion_bounds.CompletionTables, "build", staticmethod(checking_build)) generators = get_random_full_rank_matrix(np.random.default_rng(4), 10, 36) - distance = bz.get_distance_brouwer_zimmermann_many( - [(generators, _no_labels(generators))], cutoff=0 - ) + distance = bz.get_distance_brouwer_zimmermann([(generators, _no_labels(generators))], cutoff=0) assert distance == qldpc.codes.distance.get_distance_from_generators( generators, cutoff=0, method="brute_force" ) @@ -1426,7 +1414,7 @@ def recording_select(*args: Any, **kwargs: Any) -> completion_bounds.CompletionT monkeypatch.setattr(completion_bounds, "select_completion_tables", recording_select) code = qldpc.codes.BBCode({x: 6, y: 3}, 1 + x + x**3 * y, 1 + y + x) - problems = [get_sector_problem(code, pauli) for pauli in PAULIS_XZ] + sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] # An overlapping family would hold a word of weight four, and end the searches before any layer. tune( overlapping_minimum_work=MAX_VALUE, @@ -1443,16 +1431,16 @@ def recording_select(*args: Any, **kwargs: Any) -> completion_bounds.CompletionT ): block_bits.clear() with use_tuning(**limits): - assert bz.get_distance_brouwer_zimmermann_many( - problems, + assert bz.get_distance_brouwer_zimmermann( + sectors, cutoff=0, get_automorphisms=code._get_qudit_automorphisms, ) == code.get_distance(method="brute_force") assert block_bits == expected_block_bits -def test_many_problems_need_a_problem_or_an_upper_bound() -> None: - """Without problems, the result is the known upper bound, which must then be given.""" - with pytest.raises(ValueError, match="at least one problem or an upper bound"): - bz.get_distance_brouwer_zimmermann_many([], cutoff=0) - assert bz.get_distance_brouwer_zimmermann_many([], cutoff=0, upper_bound=3) == 3 +def test_searches_need_a_sector_or_an_upper_bound() -> None: + """Without sectors, the result is the known upper bound, which must then be given.""" + with pytest.raises(ValueError, match="at least one sector or an upper bound"): + bz.get_distance_brouwer_zimmermann([], cutoff=0) + assert bz.get_distance_brouwer_zimmermann([], cutoff=0, upper_bound=3) == 3 diff --git a/src/qldpc/codes/distance/_connected_cluster/search.py b/src/qldpc/codes/distance/_connected_cluster/search.py index 8044d4a75..854648155 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search.py +++ b/src/qldpc/codes/distance/_connected_cluster/search.py @@ -39,7 +39,7 @@ def get_distance_connected_cluster( - problems: Sequence[tuple[npt.ArrayLike, npt.ArrayLike]], + sectors: Sequence[tuple[npt.ArrayLike, npt.ArrayLike]], *, cutoff: int, upper_bound: int | None = None, @@ -47,68 +47,68 @@ def get_distance_connected_cluster( get_automorphisms: Callable[[], npt.NDArray[np.int_] | None] | None = None, tuning: SearchTuning | None = None, ) -> int: - """Compute the minimum distance across problems by searching connected supports. + """Compute the minimum distance across sectors by searching connected supports. - Each problem is a pair ``(checks, excluded)``, whose distance is the least weight of a witness: + Each sector is a pair ``(checks, excluded)``, whose distance is the least weight of a witness: a vector that satisfies every check and is outside the row space of ``excluded``. The search of - each problem raises its weight limit one weight divisor at a time, and each limit within which + each sector raises its weight limit one weight divisor at a time, and each limit within which it finds no witness proves that every witness is heavier (Section 3.6 of ``connected_cluster.md``). Args: - problems: The problems, as ``SupportSearch`` takes them. + sectors: The pairs ``(checks, excluded)``, as ``SupportSearch`` takes them. cutoff: Return as soon as a witness, or ``upper_bound``, of weight at most ``cutoff`` is - known. The first weight limit of a problem is its divisor, or the largest multiple of + known. The first weight limit of a sector is its divisor, or the largest multiple of the divisor at most ``cutoff`` if that is larger. upper_bound: If not None, a cap on the result, such as the weight of a known witness outside - ``problems``, or one more than a weight limit of the caller. - symplectic: Whether the problems are symplectic (see ``SupportSearch``). + ``sectors``, or one more than a weight limit of the caller. + symplectic: Whether the sectors are symplectic (see ``SupportSearch``). get_automorphisms: A function that returns an array of generators of a group of permutations of the variables, or None. Each row ``p`` of the array maps variable ``j`` - to ``p[j]``, and must map the vectors that satisfy the checks of each problem, and the - row space of its excluded rows, onto themselves. The search of each problem calls the + to ``p[j]``, and must map the vectors that satisfy the checks of each sector, and the + row space of its excluded rows, onto themselves. The search of each sector calls the function at most once, as ``automorphism_minimum_states`` of ``tuning`` says (Section 3.5), and verifies the generators. tuning: The tuning of the search (see ``_tuning``), by default the active one. Returns: - The least of ``upper_bound`` and the distances of the problems, in which a problem without + The least of ``upper_bound`` and the distances of the sectors, in which a sector without witnesses counts as one more than its number of variables; or, after an early exit, a weight at most ``cutoff``, which can exceed the distance. Raises: - ValueError: If there are neither problems nor an upper bound, if a problem is not valid + ValueError: If there are neither sectors nor an upper bound, if a sector is not valid (see ``SupportSearch``), or if a generator fails its verification. - RuntimeError: If the searches take more weight limits than a correct search can. + RuntimeError: If the search takes more weight limits than a correct one can. """ - searches = ConnectedClusterSearches( - problems, + search = ConnectedClusterSearch( + sectors, cutoff=cutoff, upper_bound=upper_bound, symplectic=symplectic, get_automorphisms=get_automorphisms, tuning=tuning, ) - while not searches.finished: - searches.advance() - return searches.result + while not search.finished: + search.advance() + return search.result -class ConnectedClusterSearches: - """The connected-cluster searches of several problems, which advance one weight limit at a time. +class ConnectedClusterSearch: + """A connected-cluster search of sectors, which advances one weight limit at a time. - The arguments are those of ``get_distance_connected_cluster``, which advances the searches until - they finish. Each advance searches the problem with the lowest lower bound on its witnesses + The arguments are those of ``get_distance_connected_cluster``, which advances the search until + it finishes. Each advance searches the sector with the lowest lower bound on its witnesses through its next weight limit (Section 3.6 of ``connected_cluster.md``). Raises: - ValueError: If there are neither problems nor an upper bound, or if a problem is not valid + ValueError: If there are neither sectors nor an upper bound, or if a sector is not valid (see ``SupportSearch``). """ def __init__( self, - problems: Sequence[tuple[npt.ArrayLike, npt.ArrayLike]], + sectors: Sequence[tuple[npt.ArrayLike, npt.ArrayLike]], *, cutoff: int, upper_bound: int | None = None, @@ -116,17 +116,17 @@ def __init__( get_automorphisms: Callable[[], npt.NDArray[np.int_] | None] | None = None, tuning: SearchTuning | None = None, ) -> None: - if not problems and upper_bound is None: - raise ValueError("Require at least one problem or an upper bound") + if not sectors and upper_bound is None: + raise ValueError("Require at least one sector or an upper bound") - # Keep a search of each problem with witnesses; a problem without witnesses only bounds the + # Keep a search of each sector with witnesses; a sector without witnesses only bounds the # result. tuning = get_tuning() if tuning is None else tuning self._cutoff = cutoff self._best_weight = upper_bound self._no_distance_bounds: list[int] = [] self._searches: list[SupportSearch] = [] - for checks, excluded in problems: + for checks, excluded in sectors: search = SupportSearch( checks, excluded, @@ -141,7 +141,7 @@ def __init__( self._no_distance_bounds.append(search.num_variables + 1) # Start each lower bound at its divisor. A correct search takes at most n // d limits for a - # problem of n variables and divisor d (Section 3.6 of connected_cluster.md), so a broken + # sector of n variables and divisor d (Section 3.6 of connected_cluster.md), so a broken # one fails rather than loops. self._lower_bounds = [search.weight_divisor for search in self._searches] self._max_num_limits = sum( @@ -151,10 +151,10 @@ def __init__( @property def finished(self) -> bool: - """Whether no problem has witnesses, or the best weight is at most the cutoff or each bound. + """Whether no sector has witnesses, or the best weight is at most the cutoff or each bound. The best weight is that of the lightest witness found, or ``upper_bound`` if that is less, - and the bounds are the lower bounds of the problems on the weights of their witnesses. + and the bounds are the lower bounds of the sectors on the weights of their witnesses. """ if not self._searches: return True @@ -169,14 +169,14 @@ def result(self) -> int: return min(bound for bound in bounds if bound is not None) def advance(self) -> None: - """Search the problem with the lowest lower bound through its next limit, unless finished. + """Search the sector with the lowest lower bound through its next limit, unless finished. - If this raises, as at a keyboard interrupt, the searches can be left inconsistent, so build - new ones to search again. + If this raises, as at a keyboard interrupt, the search can be left inconsistent, so build a + new one to search again. Raises: ValueError: If a generator of automorphisms fails its verification. - RuntimeError: If the searches take more weight limits than a correct search can. + RuntimeError: If the search takes more weight limits than a correct one can. """ if self.finished: return @@ -186,7 +186,7 @@ def advance(self) -> None: " limits, which only a bug can cause" ) - # Search the problem with the lowest lower bound through its next limit, which the cutoff + # Search the sector with the lowest lower bound through its next limit, which the cutoff # can raise. index = self._lower_bounds.index(min(self._lower_bounds)) search = self._searches[index] diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index 2c100bdb7..9166d3b02 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -549,10 +549,10 @@ def record_limit(search: cs.SupportSearch, max_weight: int) -> npt.NDArray[np.in assert max(limits) == 3 -def test_stepped_searches_advance_the_problem_with_the_lowest_lower_bound( +def test_stepped_searches_advance_the_sector_with_the_lowest_lower_bound( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Each advance searches the problem with the lowest lower bound until the searches finish.""" + """Each advance searches the sector with the lowest lower bound until the search finishes.""" searches_made: list[cs.SupportSearch] = [] limits: list[tuple[int, int]] = [] init, find_witness = cs.SupportSearch.__init__, cs.SupportSearch.find_witness @@ -569,34 +569,34 @@ def recording_find_witness( monkeypatch.setattr(cs.SupportSearch, "__init__", recording_init) monkeypatch.setattr(cs.SupportSearch, "find_witness", recording_find_witness) - # The problems have the divisors 2 and 1, so advancing the problem with the lowest lower bound + # The sectors have the divisors 2 and 1, so advancing the sector with the lowest lower bound # gives a different order from round-robin. - problems = [PROBLEMS["toric-X"], PROBLEMS["steane-X"]] - searches = cs.ConnectedClusterSearches(problems, cutoff=0) - lower_bounds = [search.weight_divisor for search in searches_made] + sectors = [PROBLEMS["toric-X"], PROBLEMS["steane-X"]] + search = cs.ConnectedClusterSearch(sectors, cutoff=0) + lower_bounds = [made.weight_divisor for made in searches_made] assert lower_bounds == [2, 1] - while not searches.finished: + while not search.finished: num_limits = len(limits) - searches.advance() + search.advance() assert len(limits) == num_limits + 1 index, max_weight = limits[-1] assert max_weight == lower_bounds[index] == min(lower_bounds) lower_bounds[index] += searches_made[index].weight_divisor - assert searches.result == 3 and [max_weight for _, max_weight in limits] == [1, 2, 2, 3] + assert search.result == 3 and [max_weight for _, max_weight in limits] == [1, 2, 2, 3] - # Once finished, the searches do nothing. + # Once finished, the search does nothing. num_limits = len(limits) - searches.advance() + search.advance() assert len(limits) == num_limits - # Problems without witnesses, and a known bound within the cutoff, leave nothing to search. + # Sectors without witnesses, and a known bound within the cutoff, leave nothing to search. trivial = (np.array([[1, 1]], dtype=np.uint8), np.array([[1, 1]], dtype=np.uint8)) - for searches in ( - cs.ConnectedClusterSearches([trivial], cutoff=0), - cs.ConnectedClusterSearches(problems, cutoff=3, upper_bound=3), + for search in ( + cs.ConnectedClusterSearch([trivial], cutoff=0), + cs.ConnectedClusterSearch(sectors, cutoff=3, upper_bound=3), ): - assert searches.finished and searches.result == 3 - searches.advance() + assert search.finished and search.result == 3 + search.advance() assert len(limits) == num_limits @@ -952,7 +952,7 @@ def test_invalid_problems_are_rejected() -> None: get_search(np.zeros((0, 3), dtype=np.uint8), np.array([[1, 0.5, 0]])) with pytest.raises(ValueError, match="at least one"): get_search(*PROBLEMS["steane-X"]).find_witness(0) - with pytest.raises(ValueError, match="at least one problem or an upper bound"): + with pytest.raises(ValueError, match="at least one sector or an upper bound"): cs.get_distance_connected_cluster([], cutoff=0) with pytest.raises(ValueError, match="even number of columns"): get_search( diff --git a/src/qldpc/codes/distance/_counting/scan_test.py b/src/qldpc/codes/distance/_counting/scan_test.py index 559c8d795..9ddb98f87 100644 --- a/src/qldpc/codes/distance/_counting/scan_test.py +++ b/src/qldpc/codes/distance/_counting/scan_test.py @@ -26,7 +26,7 @@ CostlyStages, assert_counts_match_enumeration, get_random_css_code, - get_sector_problem, + get_sector, ) from ..core import DistanceMethod from . import scan @@ -239,7 +239,7 @@ def test_steps_run_in_order() -> None: def test_step_tables_choose_and_keep_tables(tune: Tune) -> None: """Steps get tables only for layers of two or more rows of full sets, within a memory limit.""" code = get_random_css_code(np.random.default_rng(1), 24, 8, 8) - basis, labels = get_sector_problem(code, Pauli.X) + basis, labels = get_sector(code, Pauli.X) disjoint = basis_families.get_disjoint_family(basis, labels, random_column_orders=0) deficient = len(disjoint.ranks) - 1 assert disjoint.ranks[0] == len(basis) and disjoint.ranks[deficient] < len(basis) diff --git a/src/qldpc/codes/distance/_information_sets/automorphism_families_test.py b/src/qldpc/codes/distance/_information_sets/automorphism_families_test.py index c69abe06c..6f83e48b1 100644 --- a/src/qldpc/codes/distance/_information_sets/automorphism_families_test.py +++ b/src/qldpc/codes/distance/_information_sets/automorphism_families_test.py @@ -16,14 +16,14 @@ from qldpc.objects import Pauli from .._binary import get_eligible_rows -from ..conftest import get_sector_problem +from ..conftest import get_sector from . import automorphism_families, certificates def test_automorphisms_must_map_both_spaces_onto_themselves() -> None: """Only permutations that preserve the searched space and its excluded subspace pass.""" code = codes.MBCode([7], 1 + x + x**3, 1 + x**2 + x**3 + x**4) - basis, labels = get_sector_problem(code, Pauli.X) + basis, labels = get_sector(code, Pauli.X) shift = np.concatenate([np.roll(np.arange(7), 1), np.roll(np.arange(7), 1) + 7]) automorphism_families.verify_automorphisms(basis, labels, shift[None]) automorphism_families.verify_automorphisms(basis, labels, np.empty((0, 14), dtype=int)) @@ -53,7 +53,7 @@ def test_automorphism_families_certify_like_the_family_of_all_images() -> None: for automorphisms in (translations, translations[:1]): elements = _get_group_elements(automorphisms) for pauli in (Pauli.X, Pauli.Z): - basis, labels = get_sector_problem(code, pauli) + basis, labels = get_sector(code, pauli) divisor = 2 if np.all(basis.sum(axis=1) % 2 == 0) else 1 family, certificate = automorphism_families.get_automorphism_family( basis, labels, automorphisms, divisor @@ -89,7 +89,7 @@ def test_scanned_sets_balance_two_orbits() -> None: rng = np.random.default_rng(1) for code in _get_random_mb_codes(rng, 12): for pauli in (Pauli.X, Pauli.Z): - basis, labels = get_sector_problem(code, pauli) + basis, labels = get_sector(code, pauli) dimension, num_columns = basis.shape family, _ = automorphism_families.get_automorphism_family( basis, labels, code._get_qudit_automorphisms(), 1 diff --git a/src/qldpc/codes/distance/_tuning.py b/src/qldpc/codes/distance/_tuning.py index effe91591..7ec6307d3 100644 --- a/src/qldpc/codes/distance/_tuning.py +++ b/src/qldpc/codes/distance/_tuning.py @@ -223,7 +223,7 @@ class SearchTuning: # Fields of connected-cluster searches. #: A connected-cluster search asks its caller for automorphisms before the first weight limit at - #: which it expects to have visited this many states over all limits of one problem, or before a + #: which it expects to have visited this many states over all limits of one sector, or before a #: first limit that ``cutoff`` sets; zero asks before the first limit, and ``MAX_VALUE`` never. #: Defaults to ``5 * 10**4``, a derived value: the cost of asking, for a large code, tens of #: thousands of states (Section 3.5 of ``connected_cluster.md``). @@ -271,7 +271,7 @@ class SearchTuning: #: ``brouwer_zimmermann.md``). completion_bound_max_cost_percent: int = 100 - #: The most bytes of completion tables kept by a distance search for each problem, by a count + #: The most bytes of completion tables kept by a distance search for each sector, by a count #: for each sector besides the tables that it is building, and by a ``CosetLeaderSearch`` for #: each set of a family; a basis whose tables do not fit gets none, and zero disables tables. #: Defaults to 256 MiB, a budget of memory, which fits blocks of 16 columns for bases of up to diff --git a/src/qldpc/codes/distance/_tuning_test.py b/src/qldpc/codes/distance/_tuning_test.py index b30988fab..94c191b60 100644 --- a/src/qldpc/codes/distance/_tuning_test.py +++ b/src/qldpc/codes/distance/_tuning_test.py @@ -36,7 +36,7 @@ CostlyStages, get_binary_matrix, get_random_css_code, - get_sector_problem, + get_sector, ) @@ -356,7 +356,7 @@ def recording(*args: Any, **kwargs: Any) -> Any: def prepare(*args: Any, **kwargs: Any) -> Any: result = original_prepare(*args, **kwargs) - if isinstance(result, bz._BrouwerZimmermannSearch): + if isinstance(result, bz._SectorSearch): seen["search"].append((result.batch_size, result.tuning)) return result @@ -411,5 +411,5 @@ def prepare(*args: Any, **kwargs: Any) -> Any: # tables. bb_code = codes.BBCode({x: 6, y: 6}, x**3 + y + y**2, y**3 + x + x**2) with _tuning.use_tuning(information_set_batch_exponent=5) as tuning: - bz.get_distance_brouwer_zimmermann_many([get_sector_problem(bb_code, Pauli.X)], cutoff=0) + bz.get_distance_brouwer_zimmermann([get_sector(bb_code, Pauli.X)], cutoff=0) assert seen["search"] and all(search == (1 << 5, tuning) for search in seen["search"]) diff --git a/src/qldpc/codes/distance/brouwer_zimmermann.md b/src/qldpc/codes/distance/brouwer_zimmermann.md index 019221af7..c87f5c06d 100644 --- a/src/qldpc/codes/distance/brouwer_zimmermann.md +++ b/src/qldpc/codes/distance/brouwer_zimmermann.md @@ -541,7 +541,7 @@ The thresholds, limits, and coefficients of the heuristics are fields of `Search [README.md](README.md) maps the modules of this directory and the levels in which they import each other; this section says how the searches use them. The distance functions of [core.py](core.py) run the BZ search of [_brouwer_zimmermann/distance.py](_brouwer_zimmermann/distance.py), the exhaustive enumeration of [_brute_force.py](_brute_force.py), or the connected-cluster search of [_connected_cluster/search.py](_connected_cluster/search.py). -For BZ, they build an adapted basis ([Section 3.4](#34-quotient-labels-for-the-stabilizer-test)) for each sector, and pass the problems, both sectors of a CSS code at once in `get_distance_css`, to `get_distance_brouwer_zimmermann_many`. +For BZ, they build an adapted basis ([Section 3.4](#34-quotient-labels-for-the-stabilizer-test)) for each sector, and pass the sectors, both of a CSS code at once in `get_distance_css`, to `get_distance_brouwer_zimmermann`. [_information_sets/automorphism_families.py](_information_sets/automorphism_families.py) verifies automorphisms and builds the families of [Section 3.7](#37-images-of-an-information-set-under-automorphisms), with the certificates of [_information_sets/certificates.py](_information_sets/certificates.py). [logical_counts.py](logical_counts.py) builds its families with the stages of [_information_sets/basis_families.py](_information_sets/basis_families.py) that distance searches use ([Section 4.4](#44-heuristics-and-cost-models)), in `_select_basis_family` and `count_words` of [_counting/scan.py](_counting/scan.py), under the stricter stopping rule of [Section 5](#5-correctness-requirements). @@ -600,9 +600,9 @@ The search of Pauli errors by CSS weight has no routes by tails, since the CSS w ### 4.2 Flow and exit points A public entry point validates inputs and chooses a method. -For BZ, `get_distance_brouwer_zimmermann_many` builds a `BrouwerZimmermannSearches`, which prepares each problem. -Each call of its `advance` method advances one remaining search by one layer, in round-robin order for a joint CSS search ([Section 3.3](#33-sharing-witnesses-between-css-sectors)). -Preparation returns a result, or a `_BrouwerZimmermannSearch` whose `advance` method searches one layer `t`, or only its first `j` search bases if step `(t, j)` certifies `U` ([Section 2.5](#25-the-stopping-certificate)). +For BZ, `get_distance_brouwer_zimmermann` builds a `BrouwerZimmermannSearch`, which prepares a search of each sector. +Each call of its `advance` method advances the search of one remaining sector by one layer, in round-robin order for a joint CSS search ([Section 3.3](#33-sharing-witnesses-between-css-sectors)). +Preparation returns a result, or a `_SectorSearch` whose `advance` method searches one layer `t`, or only its first `j` search bases if step `(t, j)` certifies `U` ([Section 2.5](#25-the-stopping-certificate)). A result of preparation can include a witness from another sector or the bound of a weight limit ([Section 4.5](#45-behavior-spanning-files)), so it need not be the distance of its sector. | Input or method in [core.py](core.py) | Outcome | @@ -621,13 +621,13 @@ The disjoint family, its pruning ([Section 4.4](#44-heuristics-and-cost-models)) | Rows of each replacement family, overlapping and then partitioned, if selected | Returns if `U ≤ cutoff` | | Certificate of each replacement family | Returns if `L(1) ≥ U` | | Switch at the end of setup | If setup asked for automorphisms before partitioning and found some, the search considers switching to their family ([Section 3.7](#37-images-of-an-information-set-under-automorphisms)); returns if then `U ≤ cutoff` or `L(1) ≥ U` | -| Ready search | Returns a `_BrouwerZimmermannSearch` that scans from layer two | +| Ready search | Returns a `_SectorSearch` that scans from layer two | | Search location | Outcome | | --- | --- | -| `_BrouwerZimmermannSearch.advance` | Returns after one layer, or after the leading search bases of a layer that certify `U`, or earlier if `U ≤ cutoff`; a search may first switch to an automorphism family ([Section 3.7](#37-images-of-an-information-set-under-automorphisms)); a finished search does no further work | -| `_BrouwerZimmermannSearch.finished` | Marks a search finished if `U ≤ cutoff`, `L ≥ U`, or every layer has been enumerated (`next_weight > dimension`) | -| `BrouwerZimmermannSearches.finished` | Marks the searches finished once the shared `U ≤ cutoff`, or every search has finished; `get_distance_brouwer_zimmermann_many` then returns `U` | +| `_SectorSearch.advance` | Returns after one layer, or after the leading search bases of a layer that certify `U`, or earlier if `U ≤ cutoff`; a search may first switch to an automorphism family ([Section 3.7](#37-images-of-an-information-set-under-automorphisms)); a finished search does no further work | +| `_SectorSearch.finished` | Marks a search finished if `U ≤ cutoff`, `L ≥ U`, or every layer has been enumerated (`next_weight > dimension`) | +| `BrouwerZimmermannSearch.finished` | Marks the search finished once the shared `U ≤ cutoff`, or the search of every sector has finished; `get_distance_brouwer_zimmermann` then returns `U` | The tests `test_brouwer_zimmermann_setup_exits`, `test_brouwer_zimmermann_setup_cutoffs`, `test_rows_of_an_automorphism_family_can_reach_the_cutoff`, and `test_searches_that_setup_settles_are_finished_at_once` in [_brouwer_zimmermann/distance_test.py](_brouwer_zimmermann/distance_test.py) exercise these exits. @@ -651,7 +651,7 @@ The tests `test_brouwer_zimmermann_setup_exits`, `test_brouwer_zimmermann_setup_ | Stored width `N_stored` | `basis.shape[1]` before pivot deletion, including any all-zero columns | | Labels `M` | `labels`, which has no columns for a classical problem | | Eligible rows | `get_eligible_rows` of [_binary.py](_binary.py): every row of a classical basis; rows with nonzero labels for a quantum problem | -| Support, prefix XORs | `support` and `prefixes` in `_BrouwerZimmermannSearch._scan_set` and in the scans of [_brouwer_zimmermann/affine_search.py](_brouwer_zimmermann/affine_search.py), which step through a layer with `advance_support` of [_information_sets/support_stepping.py](_information_sets/support_stepping.py) | +| Support, prefix XORs | `support` and `prefixes` in `_SectorSearch._scan_set` and in the scans of [_brouwer_zimmermann/affine_search.py](_brouwer_zimmermann/affine_search.py), which step through a layer with `advance_support` of [_information_sets/support_stepping.py](_information_sets/support_stepping.py) | | Packed generators | `generators` of the `AffineInstance` of a distance search: `uint64` words, after deleting pivot columns. `widths` counts the valid words for each search basis. | | Packed labels | `labels` of the `AffineInstance` of a distance search: `uint64` quotient-label words, without pivot-column deletion | | Batch of a compiled scan | `batch_size`, equal to `1 << information_set_batch_exponent` supports, or supports and lookups together in a scan with completion tables ([Section 4.5](#45-behavior-spanning-files)) | @@ -736,7 +736,7 @@ The Retuning section of [_tuning.py](_tuning.py) defines the other classes of fi The same docstring states the contract of `max_weight`. The functions pass `upper_bound=max_weight+1` to BZ, as though a witness of that weight were known, so that it stops once its certificate reaches that bound, and clamp the results of the other methods to `max_weight+1`. They also cap `cutoff` at `max_weight`, since a higher cutoff would end the search at once on the assumed witness. - Inside the searches, a problem without nontrivial words counts as `n+1`, which no word on `n` bits or qubits weighs, so that it never lowers the minimum over problems. + Inside the searches, a sector without nontrivial words counts as `n+1`, which no word on `n` bits or qubits weighs, so that it never lowers the minimum over sectors. - **Units.** Binary input (`symplectic=False`) is a classical problem, or a pure-X or pure-Z problem with one bit per qubit, and symplectic input (`symplectic=True`) has general Pauli rows. For symplectic input, BZ maps rows by `T` ([Section 2.7](#27-pauli-weight-as-hamming-weight)), doubles `cutoff` and the bound of a weight limit, passes `weight_divisor=2`, and halves the result, while `method="brute_force"` uses symplectic weights and the original `cutoff`. @@ -748,7 +748,7 @@ The Retuning section of [_tuning.py](_tuning.py) defines the other classes of fi Before a costly layer, `advance` may switch to an automorphism family ([Section 3.7](#37-images-of-an-information-set-under-automorphisms)), which sets `next_weight` to two and may raise `lower_bound`. If a scan stops at the cutoff or raises an exception, `advance` leaves `lower_bound` and `next_weight` as they were before that scan, but keeps any earlier switch. A later call restarts the layer from its first support, unless the search has finished, as it has after a stop at the cutoff. - If `BrouwerZimmermannSearches.advance` raises, a witness that the interrupted scan found can stay out of the shared `U`, so build new searches to search again. + If `BrouwerZimmermannSearch.advance` raises, a witness that the interrupted scan found can stay out of the shared `U`, so build a new search to search again. - **CSS sectors.** Each sector of a joint search keeps its `lower_bound` and the `certificate` of its `instance` ([Section 3.3](#33-sharing-witnesses-between-css-sectors)). - **Automorphisms.** diff --git a/src/qldpc/codes/distance/conftest.py b/src/qldpc/codes/distance/conftest.py index 1f0072750..c2c23d8e2 100644 --- a/src/qldpc/codes/distance/conftest.py +++ b/src/qldpc/codes/distance/conftest.py @@ -178,7 +178,7 @@ def get_random_css_code( return codes.CSSCode(checks_x.astype(int), checks_z.astype(int)) -def get_sector_problem( +def get_sector( code: codes.CSSCode, pauli: PauliXZ ) -> tuple[npt.NDArray[np.uint8], npt.NDArray[np.uint8]]: """The adapted basis and quotient labels of one sector of a binary CSS code.""" diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index 2288bc0f8..8335bf9a8 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -50,7 +50,7 @@ $$ Coordinates are **variables**, and the rows of `H` are **checks**. The **support** of a vector is the set of its nonzero variables, and its **syndrome** is the set of its **unsatisfied** checks, those with an odd number of variables in the support. -A CSS code with X-type checks `H_X` and Z-type checks `H_Z` has two **sectors**, which a search treats as separate problems: its X-type logical operators, of distance `d(H_Z, H_X)`, and its Z-type ones, of distance `d(H_X, H_Z)`. +A CSS code with X-type checks `H_X` and Z-type checks `H_Z` has two **sectors**, each an instance of this problem: its X-type logical operators, of distance `d(H_Z, H_X)`, and its Z-type ones, of distance `d(H_X, H_Z)`. Its distance is the smaller of the two. For a CSS subsystem code with gauge generators `G_X` and `G_Z` and stabilizers `S_X` and `S_Z`, the sectors are `(S_Z, G_X)` and `(S_X, G_Z)`, and a witness is a dressed logical operator. For a classical code, `H` is its parity-check matrix and `G` is empty. @@ -143,7 +143,7 @@ qLDPC takes the orbits of any group of automorphisms that it verifies. The generators of `Γ` are automorphisms that the caller of a distance function supplies on request, such as the `_found_qudit_automorphisms` of quantum codes; classical codes supply none. For a large code, finding the automorphisms, verifying them, and ordering their orbits can cost as much as visiting many states. -So the search of each problem asks for them at most once, before the first weight limit at which it expects to have visited `automorphism_minimum_states` states over all its limits. +So the search of each sector asks for them at most once, before the first weight limit at which it expects to have visited `automorphism_minimum_states` states over all its limits. That field of `SearchTuning` in `_tuning.py` defaults to a round number of states assumed to cost about as much to visit as asking. The search predicts the number of states of the next limit from the ratio between the numbers of the last two. The search predicts rather than counts because it can ask only between limits, each a single compiled call, and the limit in which it would reach `automorphism_minimum_states` can be a large part of the search. @@ -166,17 +166,17 @@ For example, each block row of the checks of a pair-partition code sums to the a `infer_weight_divisor` of `_information_sets/basis_families.py` finds `d` from a basis of `ker(H)`, as BZ does. **Exact distance.** -For each problem, such as a sector of a CSS code, the search keeps a lower bound `L` on the weights of its witnesses, starting at its divisor, and searches the problem with the lowest `L` at the weight limit `W = L`. -A witness found then is a lightest one over all problems; otherwise every witness of the problem weighs more than `W`, and its `L` rises to the next multiple of its divisor. +For each sector, the search keeps a lower bound `L` on the weights of its witnesses, starting at its divisor, and searches the sector with the lowest `L` at the weight limit `W = L`. +A witness found then is a lightest one over all sectors; otherwise every witness of the sector weighs more than `W`, and its `L` rises to the next multiple of its divisor. The search ends once the lightest witness found weighs at most every `L`, and so needs no initial upper bound. -The problems share the lightest witness found, as the sectors of a CSS code do in BZ, and an upper bound that the caller passes, such as a known distance of another sector, acts as a witness of that weight. -A `cutoff` above the `L` of a problem makes its first limit the largest multiple of its divisor at most `cutoff`, and a witness within that limit is returned at once, though it can be heavier than the distance. +The sectors share the lightest witness found, as they do in BZ, and an upper bound that the caller passes, such as a known distance of another sector, acts as a witness of that weight. +A `cutoff` above the `L` of a sector makes its first limit the largest multiple of its divisor at most `cutoff`, and a witness within that limit is returned at once, though it can be heavier than the distance. **Termination.** Each limit ends, since the search from a root is a finite tree of depth at most `W`. -A problem without witnesses is not searched. -The lightest witness of any other problem, with `n` variables and divisor `d`, weighs a multiple of `d` that is at most `n`, so the problem takes at most `n // d` limits. -A search that needs more limits than the sum of these over its problems has a bug, and raises a `RuntimeError` rather than looping forever. +A sector without witnesses is not searched. +The lightest witness of any other sector, with `n` variables and divisor `d`, weighs a multiple of `d` that is at most `n`, so the sector takes at most `n // d` limits. +A search that needs more limits than the sum of these over its sectors has a bug, and raises a `RuntimeError` rather than looping forever. **Interrupts.** Each weight limit runs in one compiled call, which a keyboard interrupt cannot stop. @@ -286,7 +286,7 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | Sectors of a CSS code | `_search_css` of `core.py`, which `get_distance_css` and `get_distance_pauli` call, and `get_css_stabilizers` of `_binary.py` | | Classical codes, and qubit codes that are not CSS | `get_distance_from_checks` and `get_distance_pauli` of `core.py` | | Problems of Section 3.7, values, and symbols | `symplectic` of `SupportSearch`, its `_get_symbol_columns`, and `_shift_other_values` | -| Distance of several problems | `get_distance_connected_cluster`, which advances `ConnectedClusterSearches` one weight limit at a time | +| Distance over several sectors | `get_distance_connected_cluster`, which advances `ConnectedClusterSearch` one weight limit at a time | | Distance of a vector `v` from a classical code with generator matrix `G_C` | `ClassicalCode.get_distance_exact(vector=v)` in `src/qldpc/codes/common.py`, which, by the connected-cluster method, searches `([H \| Hv], [G_C \| 0])` and subtracts one | | Search through a weight limit `W` | `SupportSearch.find_witness` | | Syndrome query | `SupportSearch.find_vector_with_syndrome`, which coset searches skip for `SupportSearch._find_vector_with_packed_syndrome`, and the sentinel root `-1` of `_search_supports` | @@ -302,8 +302,8 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | When a search asks for symmetries | `automorphism_minimum_states` of `SearchTuning` in `_tuning.py` | | Weight divisor | `infer_weight_divisor` of `_information_sets/basis_families.py` | -`get_distance_from_checks`, `get_distance_css`, and `get_distance_pauli` of `core.py` build the problems of the search and pass it the active tuning, the last two after they derive the stabilizers of subsystem codes and make them sparser ([Section 3.9](#39-sparser-stabilizers-of-subsystem-codes)). -`SupportSearch` validates every problem, and the `get_distance_exact` methods of the code classes in `src/qldpc/codes/common.py` call these functions. +`get_distance_from_checks`, `get_distance_css`, and `get_distance_pauli` of `core.py` build the sectors of the search and pass it the active tuning, the last two after they derive the stabilizers of subsystem codes and make them sparser ([Section 3.9](#39-sparser-stabilizers-of-subsystem-codes)). +`SupportSearch` validates every sector, and the `get_distance_exact` methods of the code classes in `src/qldpc/codes/common.py` call these functions. Nonbinary codes, `logical_counts.py`, and `get_distance_from_generators` reject `method="connected_cluster"`: counting needs every word of a weight rather than one witness, and generators are not checks. Hypergraph product codes get their closed-form distances by searching the classical seed codes with the given method. `_search_supports`, `_get_branches`, and `_is_outside_excluded` are compiled with `always_compiled`, and their small helpers with `always_compiled(inline=True)`, as [README.md](README.md) explains. diff --git a/src/qldpc/codes/distance/core.py b/src/qldpc/codes/distance/core.py index 184ad75c0..134a77665 100644 --- a/src/qldpc/codes/distance/core.py +++ b/src/qldpc/codes/distance/core.py @@ -27,7 +27,7 @@ swap_pauli_halves, symplectic_to_hamming, ) -from ._brouwer_zimmermann.distance import get_distance_brouwer_zimmermann_many +from ._brouwer_zimmermann.distance import get_distance_brouwer_zimmermann from ._brute_force import get_nested_distance_brute_force from ._connected_cluster.search import get_distance_connected_cluster from ._connected_cluster.sparse_checks import get_row_weights, get_sparser_rows @@ -491,8 +491,8 @@ def _search_css( # Each sector takes the stabilizers of the other type as checks, and excludes the gauge # generators of its own type. stabilizers_x, stabilizers_z = get_css_stabilizers(gauge_x, gauge_z) - sectors = {Pauli.X: (stabilizers_z, gauge_x), Pauli.Z: (stabilizers_x, gauge_z)} - problems = [sectors[sector_pauli] for sector_pauli in paulis] + sector_of_type = {Pauli.X: (stabilizers_z, gauge_x), Pauli.Z: (stabilizers_x, gauge_z)} + sectors = [sector_of_type[sector_pauli] for sector_pauli in paulis] # Each type has one independent nontrivial logical operator for each logical qubit, so the X # type alone shows whether the code encodes any. @@ -516,17 +516,17 @@ def _search_css( Pauli.X: gauge_z[~np.any(overlaps, axis=0)], Pauli.Z: gauge_x[~np.any(overlaps, axis=1)], } - problems = [ + sectors = [ ( _get_sparser_stabilizers( checks, kept_stabilizers[sector_pauli], symplectic=False, tuning=tuning ), excluded, ) - for sector_pauli, (checks, excluded) in zip(paulis, problems, strict=True) + for sector_pauli, (checks, excluded) in zip(paulis, sectors, strict=True) ] return get_distance_connected_cluster( - problems, + sectors, cutoff=cutoff, upper_bound=upper_bound, get_automorphisms=get_automorphisms, @@ -543,10 +543,10 @@ def _search_css( method=method, get_automorphisms=None, ) - for checks, excluded in problems + for checks, excluded in sectors ) - return get_distance_brouwer_zimmermann_many( - [get_nested_code_basis(get_kernel(checks), excluded) for checks, excluded in problems], + return get_distance_brouwer_zimmermann( + [get_nested_code_basis(get_kernel(checks), excluded) for checks, excluded in sectors], cutoff=cutoff, upper_bound=upper_bound, get_automorphisms=get_automorphisms, @@ -684,7 +684,7 @@ def _search_generators( get_automorphisms = functools.partial( _get_lifted_automorphisms, get_automorphisms, num_qubits ) - distance = get_distance_brouwer_zimmermann_many( + distance = get_distance_brouwer_zimmermann( [(basis, labels)], cutoff=cutoff * divisor, weight_divisor=divisor, diff --git a/src/qldpc/codes/distance/core_test.py b/src/qldpc/codes/distance/core_test.py index 43072bd46..97fcfa844 100644 --- a/src/qldpc/codes/distance/core_test.py +++ b/src/qldpc/codes/distance/core_test.py @@ -162,10 +162,10 @@ def test_pauli_checks_of_css_codes_are_searched_as_css_codes( searched: list[tuple[list[int], bool]] = [] - def record(problems: Any, **kwargs: Any) -> Any: - widths = [np.shape(sector_checks)[1] for sector_checks, _ in problems] + def record(sectors: Any, **kwargs: Any) -> Any: + widths = [np.shape(sector_checks)[1] for sector_checks, _ in sectors] searched.append((widths, kwargs.get("symplectic", False))) - return get_distance_connected_cluster(problems, **kwargs) + return get_distance_connected_cluster(sectors, **kwargs) get_distance_connected_cluster = core.get_distance_connected_cluster monkeypatch.setattr(core, "get_distance_connected_cluster", record) @@ -314,9 +314,9 @@ def get_stabilizers(checks: npt.NDArray[np.uint8]) -> npt.NDArray[np.uint8]: searched: list[npt.NDArray[np.uint8]] = [] - def record(problems: Any, **kwargs: Any) -> Any: - searched.extend(np.asarray(checks) for checks, _ in problems) - return get_distance_connected_cluster(problems, **kwargs) + def record(sectors: Any, **kwargs: Any) -> Any: + searched.extend(np.asarray(checks) for checks, _ in sectors) + return get_distance_connected_cluster(sectors, **kwargs) get_distance_connected_cluster = core.get_distance_connected_cluster monkeypatch.setattr(core, "get_distance_connected_cluster", record) diff --git a/src/qldpc/codes/distance/logical_counts.py b/src/qldpc/codes/distance/logical_counts.py index a83b4c16a..bfaf092b7 100644 --- a/src/qldpc/codes/distance/logical_counts.py +++ b/src/qldpc/codes/distance/logical_counts.py @@ -29,7 +29,7 @@ get_css_stabilizers, get_nested_code_basis, ) -from ._brouwer_zimmermann.distance import get_distance_brouwer_zimmermann_many +from ._brouwer_zimmermann.distance import get_distance_brouwer_zimmermann from ._brute_force import get_nested_distance_brute_force from ._counting import local_cliffords, macwilliams, scan from ._information_sets import basis_families @@ -809,7 +809,7 @@ def _get_distance( ) for basis, labels in sectors ) - return get_distance_brouwer_zimmermann_many( + return get_distance_brouwer_zimmermann( sectors, cutoff=0, get_disjoint_basis_families=get_disjoint_basis_families[: len(sectors)], diff --git a/src/qldpc/codes/distance/logical_counts_test.py b/src/qldpc/codes/distance/logical_counts_test.py index e0f26c8aa..4b6ba724a 100644 --- a/src/qldpc/codes/distance/logical_counts_test.py +++ b/src/qldpc/codes/distance/logical_counts_test.py @@ -262,13 +262,13 @@ def test_deprecated_max_information_sets_argument( counter.count_logical_ops(max_information_sets=-1) limits: list[int] = [] - original = lc.get_distance_brouwer_zimmermann_many + original = lc.get_distance_brouwer_zimmermann def search(*args: Any, **kwargs: Any) -> int: limits.append(kwargs["tuning"].max_information_sets) return original(*args, **kwargs) - monkeypatch.setattr(lc, "get_distance_brouwer_zimmermann_many", search) + monkeypatch.setattr(lc, "get_distance_brouwer_zimmermann", search) code = get_random_css_code(np.random.default_rng(2), 24, 8, 8) checks = code.matrix_x, code.matrix_z expected = lc.CSSLogicalCounter(*checks).count_logical_ops() From a74f3b85c319fe57547db7ae158d8da1b29159de Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Mon, 16 Nov 2026 13:42:18 -0500 Subject: [PATCH 2/3] Tighten the sector wording after review Define a sector without "of one type", say in the BZ docstrings that each sector has a search, call the sector in a test docstring by its name, and bring benchmark.py's description of non-CSS searches in line with the README. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- experiments/distance_tuning/benchmark.py | 5 +++-- src/qldpc/codes/distance/README.md | 2 +- src/qldpc/codes/distance/_brouwer_zimmermann/distance.py | 8 ++++---- .../codes/distance/_brouwer_zimmermann/distance_test.py | 2 +- .../codes/distance/_connected_cluster/search_test.py | 2 +- src/qldpc/codes/distance/brouwer_zimmermann.md | 2 +- 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/experiments/distance_tuning/benchmark.py b/experiments/distance_tuning/benchmark.py index b08a096c9..ada08cf37 100755 --- a/experiments/distance_tuning/benchmark.py +++ b/experiments/distance_tuning/benchmark.py @@ -104,7 +104,8 @@ def parse_args() -> argparse.Namespace: "--hadamards", action="store_true", help="apply Hadamards to the second half of the qubits, and search the resulting code," - " which is not CSS, as a QuditCode; this searches both sectors, and ignores --sectors", + " which is not CSS, as a QuditCode; this searches the whole code as one sector, and ignores" + " --sectors", ) return parser.parse_args() @@ -133,7 +134,7 @@ def time_distance( ) -> tuple[int | float, float, float]: """The distance of a code, and the wall and CPU seconds that it took. - A code that is not CSS has no sectors, and is searched whole. + A code that is not CSS is searched whole, as one sector. """ code.forget_distance() wall, cpu = time.perf_counter(), time.process_time() diff --git a/src/qldpc/codes/distance/README.md b/src/qldpc/codes/distance/README.md index 5d41fca8e..7902d9298 100644 --- a/src/qldpc/codes/distance/README.md +++ b/src/qldpc/codes/distance/README.md @@ -18,7 +18,7 @@ The documentation cites the other names at `qldpc.codes.distance`. ## Terms -- **Sector:** the words of one type that a search examines, such as the logical operators of one type of a CSS code. +- **Sector:** a set of words that a search examines, such as the logical operators of one type of a CSS code. A search of a classical code, of a qubit code that is not CSS, or of a circuit examines one sector. A Brouwer-Zimmermann search takes a basis of them, labeled to tell nontrivial words, such as logical operators, from trivial ones, such as stabilizers. A connected-cluster search takes checks whose kernel holds them and a matrix whose row space holds the trivial ones. diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py index 97d698065..81abe66fa 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py @@ -54,8 +54,8 @@ def get_distance_brouwer_zimmermann( ) -> int: """Compute the minimum distance across nested-code sectors by a BZ search. - The searches advance round-robin, and share their best upper bound, the weight of the lightest - witness that any of them has found, but not their certificates (Section 3.3). + The searches of the sectors advance round-robin, and share their best upper bound, the weight of + the lightest witness that any of them has found, but not their certificates (Section 3.3). Args: sectors: Nested-code bases and their quotient labels (see ``get_nested_code_basis``). The @@ -100,7 +100,7 @@ def get_distance_brouwer_zimmermann( class BrouwerZimmermannSearch: - """A BZ search of sectors, which advances one sector by one layer at a time, round-robin. + """A BZ search of sectors, which advances their searches one layer at a time, round-robin. The arguments are those of ``get_distance_brouwer_zimmermann``, which advances the search until it finishes. @@ -176,7 +176,7 @@ def finished(self) -> bool: return self.best <= self._cutoff or all(search.finished for search in self._searches) def advance(self) -> None: - """Advance the next unfinished sector, in round-robin order, by one layer, unless finished. + """Advance the next unfinished sector's search by one layer, round-robin, unless finished. The search of every sector then takes the best upper bound, which shares witnesses between sectors. If this raises, as at a keyboard interrupt, the search can be left inconsistent, diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py index f6bd9f2b2..bc30963e5 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py @@ -1051,7 +1051,7 @@ def test_rows_of_an_automorphism_family_can_reach_the_cutoff( @pytest.mark.usefixtures("switch_before_any_layer") def test_searches_reject_wrong_automorphisms() -> None: - """A permutation that does not preserve a problem fails loudly when a search would use it.""" + """A permutation that does not preserve a sector fails loudly when a search would use it.""" code = qldpc.codes.MBCode({x: 12}, x**10 + x**4 + x**2 + x, x**9 + x**8 + x**3 + x) transposition = np.arange(len(code)) transposition[[0, 1]] = [1, 0] diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index 9166d3b02..40634dbc6 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -573,7 +573,7 @@ def recording_find_witness( # gives a different order from round-robin. sectors = [PROBLEMS["toric-X"], PROBLEMS["steane-X"]] search = cs.ConnectedClusterSearch(sectors, cutoff=0) - lower_bounds = [made.weight_divisor for made in searches_made] + lower_bounds = [sector_search.weight_divisor for sector_search in searches_made] assert lower_bounds == [2, 1] while not search.finished: num_limits = len(limits) diff --git a/src/qldpc/codes/distance/brouwer_zimmermann.md b/src/qldpc/codes/distance/brouwer_zimmermann.md index c87f5c06d..3a5ba95e5 100644 --- a/src/qldpc/codes/distance/brouwer_zimmermann.md +++ b/src/qldpc/codes/distance/brouwer_zimmermann.md @@ -541,7 +541,7 @@ The thresholds, limits, and coefficients of the heuristics are fields of `Search [README.md](README.md) maps the modules of this directory and the levels in which they import each other; this section says how the searches use them. The distance functions of [core.py](core.py) run the BZ search of [_brouwer_zimmermann/distance.py](_brouwer_zimmermann/distance.py), the exhaustive enumeration of [_brute_force.py](_brute_force.py), or the connected-cluster search of [_connected_cluster/search.py](_connected_cluster/search.py). -For BZ, they build an adapted basis ([Section 3.4](#34-quotient-labels-for-the-stabilizer-test)) for each sector, and pass the sectors, both of a CSS code at once in `get_distance_css`, to `get_distance_brouwer_zimmermann`. +For BZ, they build an adapted basis ([Section 3.4](#34-quotient-labels-for-the-stabilizer-test)) for each sector, and pass the sectors to `get_distance_brouwer_zimmermann`, both sectors of a CSS code at once in `get_distance_css`. [_information_sets/automorphism_families.py](_information_sets/automorphism_families.py) verifies automorphisms and builds the families of [Section 3.7](#37-images-of-an-information-set-under-automorphisms), with the certificates of [_information_sets/certificates.py](_information_sets/certificates.py). [logical_counts.py](logical_counts.py) builds its families with the stages of [_information_sets/basis_families.py](_information_sets/basis_families.py) that distance searches use ([Section 4.4](#44-heuristics-and-cost-models)), in `_select_basis_family` and `count_words` of [_counting/scan.py](_counting/scan.py), under the stricter stopping rule of [Section 5](#5-correctness-requirements). From 8bb83d6ebe7615eeb4e4c5aa40ac6a1d1214bdc8 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Mon, 16 Nov 2026 14:37:00 -0500 Subject: [PATCH 3/3] Name the setup of one sector's BZ search for the sector, and finish the sector wording Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- experiments/distance_tuning/trace.py | 2 +- .../distance/_brouwer_zimmermann/distance.py | 6 +++--- .../_brouwer_zimmermann/distance_test.py | 20 +++++++++---------- .../_connected_cluster/search_test.py | 4 ++-- src/qldpc/codes/distance/_tuning_test.py | 4 ++-- .../codes/distance/brouwer_zimmermann.md | 2 +- src/qldpc/codes/distance/connected_cluster.md | 4 ++-- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/experiments/distance_tuning/trace.py b/experiments/distance_tuning/trace.py index c0786ec0e..7477dd125 100644 --- a/experiments/distance_tuning/trace.py +++ b/experiments/distance_tuning/trace.py @@ -205,7 +205,7 @@ def install_wrappers() -> None: (core, "get_distance_brouwer_zimmermann", wrap_sectors), (core, "get_distance_connected_cluster", wrap_sectors), (logical_counts, "get_distance_brouwer_zimmermann", wrap_sectors), - (distance, "_prepare_brouwer_zimmermann_search", wrap_prepare), + (distance, "_prepare_sector_search", wrap_prepare), (support_search.SupportSearch, "__init__", wrap_support_search), (support_search.SupportSearch, "find_witness", wrap_find_witness), (support_search.SupportSearch, "_use_automorphisms", wrap_use_automorphisms), diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py index 81abe66fa..8d532976c 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance.py @@ -150,7 +150,7 @@ def __init__( for index, ((basis, labels), initial_upper_bound) in enumerate( zip(sectors, initial_upper_bounds, strict=True) ): - prepared = _prepare_brouwer_zimmermann_search( + prepared = _prepare_sector_search( basis, labels, cutoff=cutoff, @@ -422,7 +422,7 @@ def _switch_to_automorphism_family(self) -> None: self.completion_tables = None -def _prepare_brouwer_zimmermann_search( +def _prepare_sector_search( basis: npt.NDArray[np.uint8], labels: npt.NDArray[np.uint8], *, @@ -434,7 +434,7 @@ def _prepare_brouwer_zimmermann_search( get_automorphisms: Callable[[], npt.NDArray[np.int_] | None] | None = None, tuning: SearchTuning, ) -> int | _SectorSearch: - """Prepare one BZ search, or return its result if setup already settles it. + """Prepare the BZ search of one sector, or return its result if setup already settles it. The stages of ``basis_families`` run in order, and between them setup returns if the rows of the family bring the best weight to the cutoff, or if its certificate proves the best weight diff --git a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py index bc30963e5..f0e50c814 100644 --- a/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py +++ b/src/qldpc/codes/distance/_brouwer_zimmermann/distance_test.py @@ -209,7 +209,7 @@ def test_brouwer_zimmermann_setup_cutoffs() -> None: """Setup can reach the cutoff from initial rows or a newly systematic row.""" basis = np.array([[1, 0, 1, 1], [0, 1, 1, 1]], dtype=np.uint8) assert ( - bz._prepare_brouwer_zimmermann_search( + bz._prepare_sector_search( basis, _no_labels(basis), cutoff=3, @@ -220,7 +220,7 @@ def test_brouwer_zimmermann_setup_cutoffs() -> None: == 3 ) assert ( - bz._prepare_brouwer_zimmermann_search( + bz._prepare_sector_search( basis, _no_labels(basis), cutoff=2, @@ -339,7 +339,7 @@ def test_brouwer_zimmermann_sector_certificates() -> None: searches: list[bz._SectorSearch] = [] advanced: set[int] = set() - original_prepare = bz._prepare_brouwer_zimmermann_search + original_prepare = bz._prepare_sector_search original_advance = bz._SectorSearch.advance def prepare(*args: Any, **kwargs: Any) -> int | bz._SectorSearch: @@ -354,7 +354,7 @@ def advance(search: bz._SectorSearch) -> int: # Exercise real layer advancement, rather than two results certified during setup. with ( - mock.patch.object(bz, "_prepare_brouwer_zimmermann_search", side_effect=prepare), + mock.patch.object(bz, "_prepare_sector_search", side_effect=prepare), mock.patch.object(bz._SectorSearch, "advance", advance), ): actual = bz.get_distance_brouwer_zimmermann( @@ -646,7 +646,7 @@ def test_automorphism_family_searches_scan_every_layer_they_certify( def prepared(monkeypatch: pytest.MonkeyPatch) -> list[bz._SectorSearch]: """The searches that setup prepares, rather than settles, in the order of their sectors.""" searches: list[bz._SectorSearch] = [] - prepare = bz._prepare_brouwer_zimmermann_search + prepare = bz._prepare_sector_search def recording_prepare(*args: Any, **kwargs: Any) -> Any: result = prepare(*args, **kwargs) @@ -654,7 +654,7 @@ def recording_prepare(*args: Any, **kwargs: Any) -> Any: searches.append(result) return result - monkeypatch.setattr(bz, "_prepare_brouwer_zimmermann_search", recording_prepare) + monkeypatch.setattr(bz, "_prepare_sector_search", recording_prepare) return searches @@ -710,7 +710,7 @@ def recording_advance(search: bz._SectorSearch) -> int: def test_searches_that_setup_settles_are_finished_at_once( prepared: list[bz._SectorSearch], ) -> None: - """A search is finished when built if setup settles every sector, or with no sectors. + """A search is finished when built if setup settles it, or with no sectors. Setup settles the sector of the Hamming code directly. In the random code, it settles one sector, whose witness finishes the search of the other. @@ -760,13 +760,13 @@ def test_stepped_searches_use_the_tuning_that_they_are_given( The function that builds the search passes its tuning on, so calling it checks both. """ tunings: list[Any] = [] - prepare = bz._prepare_brouwer_zimmermann_search + prepare = bz._prepare_sector_search def recording_prepare(*args: Any, **kwargs: Any) -> Any: tunings.append(kwargs["tuning"]) return prepare(*args, **kwargs) - monkeypatch.setattr(bz, "_prepare_brouwer_zimmermann_search", recording_prepare) + monkeypatch.setattr(bz, "_prepare_sector_search", recording_prepare) code = get_random_css_code(np.random.default_rng(153), 16, 5, 5) tuning = dataclasses.replace(DEFAULT_TUNING, information_set_batch_exponent=5) sectors = [get_sector(code, pauli) for pauli in PAULIS_XZ] @@ -859,7 +859,7 @@ def test_a_declined_switch_is_reconsidered_once_the_best_weight_drops( labels = _no_labels(basis) get_automorphisms = mock.Mock(return_value=np.roll(np.arange(num_columns), -step)[None]) switch_decisions.clear() - search = bz._prepare_brouwer_zimmermann_search( + search = bz._prepare_sector_search( basis, labels, cutoff=0, diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index 40634dbc6..89f53b877 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -733,7 +733,7 @@ def find_witness(search: cs.SupportSearch, max_weight: int) -> npt.NDArray[np.in with pytest.raises(RuntimeError, match="only a bug"): cs.get_distance_connected_cluster([PROBLEMS["toric-X"], PROBLEMS["toric-X"]], cutoff=0) - # Each of the two problems has 16 variables and weight divisor 2, so a correct search needs at + # Each of the two sectors has 16 variables and weight divisor 2, so a correct search needs at # most 8 limits for each. assert len(limits) == 2 * 16 // 2 @@ -768,7 +768,7 @@ def record_limit(search: cs.SupportSearch, max_weight: int) -> npt.NDArray[np.in def test_a_problem_without_logical_operators_has_no_distance() -> None: - """Without witnesses, a problem counts as one more than its number of variables.""" + """Without witnesses, a sector counts as one more than its number of variables.""" trivial = (np.array([[1, 1]], dtype=np.uint8), np.array([[1, 1]], dtype=np.uint8)) assert not get_search(*trivial).has_witnesses assert cs.get_distance_connected_cluster([trivial], cutoff=0) == 3 diff --git a/src/qldpc/codes/distance/_tuning_test.py b/src/qldpc/codes/distance/_tuning_test.py index 94c191b60..6a2c35b73 100644 --- a/src/qldpc/codes/distance/_tuning_test.py +++ b/src/qldpc/codes/distance/_tuning_test.py @@ -352,7 +352,7 @@ def recording(*args: Any, **kwargs: Any) -> Any: "restrict_viable_symbols", ) record(core, "get_sparser_rows", "max_rounds", "rounds_without_improvement") - original_prepare = bz._prepare_brouwer_zimmermann_search + original_prepare = bz._prepare_sector_search def prepare(*args: Any, **kwargs: Any) -> Any: result = original_prepare(*args, **kwargs) @@ -360,7 +360,7 @@ def prepare(*args: Any, **kwargs: Any) -> Any: seen["search"].append((result.batch_size, result.tuning)) return result - monkeypatch.setattr(bz, "_prepare_brouwer_zimmermann_search", prepare) + monkeypatch.setattr(bz, "_prepare_sector_search", prepare) code = get_random_css_code(np.random.default_rng(2), 24, 8, 8) with _tuning.use_tuning( diff --git a/src/qldpc/codes/distance/brouwer_zimmermann.md b/src/qldpc/codes/distance/brouwer_zimmermann.md index 3a5ba95e5..93a23c636 100644 --- a/src/qldpc/codes/distance/brouwer_zimmermann.md +++ b/src/qldpc/codes/distance/brouwer_zimmermann.md @@ -610,7 +610,7 @@ A result of preparation can include a witness from another sector or the bound o | Trivial input | Returns `NO_DISTANCE`, whatever `max_weight` is, for an empty classical code, a quantum problem with no logical rows, or `V = S` | | `method="brute_force"` | Runs exhaustive enumeration over an independent basis, adapted to `S ⊆ V` for a quantum problem | -`_prepare_brouwer_zimmermann_search` considers the following exits in order. +`_prepare_sector_search` considers the following exits in order. The disjoint family, its pruning ([Section 4.4](#44-heuristics-and-cost-models)), and any overlapping or partitioned replacement come from the stages of [_information_sets/basis_families.py](_information_sets/basis_families.py); the exits between those stages belong to the distance search. | Preparation stage | Outcome | diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index 8335bf9a8..e324d3062 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -53,8 +53,8 @@ The **support** of a vector is the set of its nonzero variables, and its **syndr A CSS code with X-type checks `H_X` and Z-type checks `H_Z` has two **sectors**, each an instance of this problem: its X-type logical operators, of distance `d(H_Z, H_X)`, and its Z-type ones, of distance `d(H_X, H_Z)`. Its distance is the smaller of the two. For a CSS subsystem code with gauge generators `G_X` and `G_Z` and stabilizers `S_X` and `S_Z`, the sectors are `(S_Z, G_X)` and `(S_X, G_Z)`, and a witness is a dressed logical operator. -For a classical code, `H` is its parity-check matrix and `G` is empty. -[Section 3.7](#37-qubit-codes-that-are-not-css) treats qubit codes that are not CSS. +For a classical code, `H` is its parity-check matrix and `G` is empty, and the search has one sector. +[Section 3.7](#37-qubit-codes-that-are-not-css) treats qubit codes that are not CSS, whose search also has one sector. ### 3.2 Light words are connected