Dist m4ri 0.16.1
Computing distance of a classical or quantum CSS code
Loading...
Searching...
No Matches
dist_m4ri Namespace Reference

Classes

class  DistanceResult
class  _StartList

Functions

int parse_debug_value (Union[str, int] val)
 _get_codedistance ()
 _get_stim ()
 _get_qec_cert ()
bool _has_qec_cert ()
Any __getattr__ (str name)
None set_distance_cache_file (Optional[Union[str, Path]] filepath=None)
Dict[str, Any] load_distance_cache (Optional[Union[str, Path]] filepath=None)
None save_distance_cache (Optional[Union[str, Path]] filepath=None)
None clear_distance_cache (Optional[Union[str, Path]] cache_file=None, bool clear_file=False)
None enable_distance_cache ()
None disable_distance_cache ()
Dict[str, Any] get_distance_cache ()
List[int] format_bounds_list (int dmin, int dmax, int num_rw)
str format_bounds_str (List[int] bounds)
float rw_infoset_find_prob (int n, int rank, int w, int pairs_l=0)
Optional[Dict[str, Any]] rw_infoset_estimate (int n, int rank, int steps, int d, int dmin=1, float step_time=0.0, float target=0.01, int steps_total=0, int pairs_l=0)
str _format_duration (float t)
Dict[str, Any] _parse_stderr_stats (str stderr)
str explain_bounds (List[int] bounds, Optional[int] method=None, str label="", Optional[Dict[str, Any]] stats=None, int dstop=0)
Optional[Dict[str, Any]] get_cached_distance (Optional[Any] H=None, Optional[Any] G=None, Optional[Any] L=None, Optional[Any] Hx=None, Optional[Any] Hz=None, Optional[Any] Lx=None, Optional[Any] Lz=None, Optional[Any] dem=None, Optional[Any] circuit=None, float pmin=0.0, Optional[Union[str, Path]] cache_file=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[bool] simple=None, Optional[bool] full=None, Optional[str] basis=None, Optional[int] rounds=None, float p_noise=0.001, bool force_noise=False, bool start_scan=False)
str get_sparse_array_state (A)
str create_unique_file (Union[str, Path] directory="tmp", str extension=".tmp")
None _remove_temp_files (Sequence[Optional[str]] files, int debug=0)
List[List[int]] read_sparse_vectors (str filepath)
str find_dist_m4ri_binary (Optional[str] custom_path=None)
Tuple[int,...] _parse_version (str v_str)
Tuple[Optional[str], Optional[str], Optional[str]] _binary_version (Optional[str] binary_path=None)
Optional[str] check_binary_compatibility (Optional[str] binary_path=None)
Tuple[int, int, int] parse_dist_m4ri_output (str stdout)
Optional[str] check_finc_outc (Optional[str] finC, Optional[str] outC, bool verbose=False)
Optional[List[int]] _normalize_start_list (Any start)
Optional[List[int]] _scan_start_list (Optional[List[int]] start_list, bool start_scan)
str _start_key_suffix (Optional[List[int]] start_list)
str _format_start_list (List[int] start_list, int max_show=8)
None set_silent (bool silent=True)
None _warn_ignored (str msg)
None _warn_codedistance_ignored (Dict[str, Any] values)
None _warn_disabled_options (Any noscan=0, Any cbeg=None, Any cend=None)
str _start_warning_text (List[int] start_list)
str _ksub_warning_text (int ksub)
None _warn_experimental_ksub (Any ksub, int method, str solver="dist_m4ri")
str _ortho_warning_text ()
None _warn_ortho (Any ortho, bool has_g, str solver="dist_m4ri")
None _check_kwargs (Callable[..., Any] func, Dict[str, Any] kwargs, Sequence[str] aliases=("win",))
Optional[List[int]] _prepare_start_option (Any start, bool trust_start=False, Any noscan=0, Any cbeg=None, Any cend=None, str solver="dist_m4ri", bool start_scan=False)
Tuple[int, int] _seed_bounds_from_entry (int eff_dmin, int eff_dmax, Optional[Dict[str, Any]] entry)
List[List[int]] _union_cws (Optional[List[List[int]]] base, Optional[List[List[int]]] extra)
int _dist_from_bounds (int dmin, int dmax)
bool _single_entry_is_exact (Dict[str, Any] entry, bool need_cws=False, int dstop=0)
str _resolve_cert_engine (str solver="dist_m4ri", Optional[str] engine=None)
bool _can_delegate_to_cert (str mode, *, int method=3, bool do_cws=False, Optional[str] outC=None, Optional[str] finC=None, Optional[int] smax=None, int dW=-1, int maxC=0, Optional[List[int]] start_list=None, Optional[Any] outD=None, Optional[Any] out_reduced=None, float pmin=0.0)
Any _cert_to_csr (Any M, Any qec_io)
bool _cert_is_conditional (Any cert)
Tuple[int, int] _cert_extract_bounds (Any cert, int certified_dmin=1)
bool _cert_wmin_discharged (Any cert, int certified_dmin)
Dict[str, Any] _cert_code_distance (Callable[[], str] key_fn, Callable[[int, int], Any] run_cert_fn, *, str label="code", int dmin=0, int dmax=0, int dstop=0, int wmax=0, Optional[str] eff_cache_file=None, int debug=0, bool verbose=False)
bool _merge_start_into_plain (str plain_key, Dict[str, Any] src, bool trust=False, Optional[Dict[str, int]] rw_delta=None)
Tuple[str, Optional[Dict[str, Any]], Optional[Dict[str, Any]]] _resolve_start_cache (str plain_key, Optional[List[int]] start_list, Callable[[Dict[str, Any]], bool] is_hit, bool trust_start, Callable[[Dict[str, Any]], bool] merge_copy, Optional[str] eff_cache_file, bool verbose=False)
Tuple[int, int, int] run_dist_m4ri (Optional[str] dist_m4ri_path=None, int method=3, Optional[str] finH=None, Optional[str] finG=None, Optional[str] finL=None, Optional[str] fin=None, Optional[str] finC=None, Optional[str] fdem=None, int dmin=0, int dmax=0, int wmax=0, int wmin=1, int dexp=0, int dest=0, int dstop=0, Optional[int] steps=None, Optional[int] threads=None, float timeout=60.0, Optional[int] smax=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[int] cbeg=None, Optional[int] cend=None, Optional[int] css=None, int noscan=0, int classical=-1, int dW=-1, int maxC=0, float pmin=0.0, bool merge=True, Optional[str] drop=None, Optional[str] outD=None, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, Optional[str] outC=None, int seed=0, int debug=0, bool nothrottle=False, int chunk_size=0, int ksub=0, int kwin=0, int win_mode=0, int win_hyb=0, int pairs=-1, Optional[int] min_hits=None, int cov_cws=100, Optional[int] refresh=None, bool verbose=False, Optional[threading.Event] stop_event=None, bool warn_start=True, bool warn_ksub=True, bool start_scan=False, bool ortho=True, bool warn_ortho=True)
Tuple[int, int, Any, Any] _gf2_entries (Any matrix)
None _write_mtx_gf2 (str path, Any matrix)
str _matrix_to_file (matrix, str extension=".mtx", str temp_dir="tmp")
bool has_noise (Any circuit)
Any strip_noise (Any circuit)
Any _add_noise_recursive (Any circuit, float p, int num_qubits, Set[int] active_qubits)
Any add_noise (Any circuit, float p=0.001, bool force=False)
Tuple[Any, int] remove_empty_detectors (Any circuit)
bool has_repeat_block (Any circuit)
Any set_circuit_rounds (Any circuit, int rounds)
int count_circuit_rounds (Any circuit)
str detect_basis (Any circuit, Optional[Union[str, Path]] filepath=None, Optional[str] basis_arg=None)
List[List[int]] track_circuit_carriers (Any circuit)
Any _rewrite_circuit_internal (Any circ, Dict[int, int] phys_to_log, Dict[int, int] active_gates_count)
Dict[str, Any] classify_qubits_thorough (Any circuit, bool verbose=False, Optional[str] basis_arg=None, Optional[Union[str, Path]] filepath=None)
Dict[str, Any] verify_qubit_metadata (Any circuit, bool verbose=False, Optional[str] basis_arg=None, Optional[Union[str, Path]] filepath=None)
Tuple[Any, int, int] strip_minority_detectors (Any circuit, str basis, bool verbose=False, bool thorough=True, Optional[Dict[str, Any]] thorough_res=None, Optional[List[bool]] mask_out=None)
str _matrix_cache_key (Any H, Optional[Any] G=None, Optional[Any] L=None, bool classical=False)
str _dem_cache_key (Any dem, float pmin=0.0)
None _write_dem_file (Any dem, str path)
List[Tuple[Any,...]] _dem_error_columns (Any dem, float pmin=0.0, bool with_prob=False)
str _drop_mode (Any drop)
str _reduced_out_prefix (Union[bool, str, Path] spec, str src, Optional[Union[str, Path]] out_dir=None)
Tuple[List[int], Optional[int]] read_drop_file (Union[str, Path] path)
Tuple[str, str] write_reduced_dem (Any dem, Sequence[int] dropped, Union[str, Path] prefix, float pmin=0.0, Optional[int] num_detectors=None, Optional[Dict[str, Any]] meta=None)
List[List[int]] _expand_equal_columns (List[List[int]] cws, Any dem, float pmin=0.0, int maxC=0, bool verbose=False)
Dict[str, Tuple[Any, Any, Any]] _css_sector_codes (Any Hx, Any Hz, Optional[Any] Lx, Optional[Any] Lz)
Tuple[int, int, int, int] _css_combine (Tuple[int, int, int] x, Tuple[int, int, int] z, int dmax=0)
Dict[str, Any] _sector_record (int dmin, int dmax, int rw_steps, List[List[int]] cws)
bool _migrate_css_records (Any Hx, Any Hz, Optional[Any] Lx=None, Optional[Any] Lz=None, Optional[str] eff_cache_file=None)
Dict[str, Any] _cached_code_distance (Any H, Optional[Any] G, Optional[Any] L, bool classical, str kind, Optional[str] dist_m4ri, int method, Optional[int] threads, float timeout, Optional[int] num_steps, int d_exp, int dmin, int dmax, int dstop, int wmin, int wmax, Optional[int] smax, Optional[List[int]] start_list, int dW, int maxC, Optional[str] finC, Optional[str] outC, bool need_cws, Optional[str] eff_cache_file, int seed, int debug, bool verbose, bool nothrottle, int chunk_size, int ksub, int kwin, int win_mode, Optional[int] min_hits, int cov_cws, Optional[int] refresh, bool trust_start, Optional[Any] fdem=None, float pmin=0.0, bool merge=True, Optional[Callable[[], str]] key_fn=None, Optional[Callable[[List[List[int]]], List[List[int]]]] cws_out_fn=None, Optional[Union[str, Path, List[int]]] fdrop=None, Optional[str] outD=None, Optional[bool] sort_rows=None, int win_hyb=0, int pairs=-1, Optional[int] cc_prune=None, bool ortho=True)
Any compute_classical_distance (Any H, Optional[str] dist_m4ri=None, int method=3, Optional[int] threads=None, float timeout=60.0, Optional[int] num_steps=None, int d_exp=0, int d_min=0, int d_max=0, int dmin=0, int dmax=0, int dstop=0, int wmin=1, int wmax=0, Optional[int] smax=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[int] cbeg=None, Optional[int] cend=None, int noscan=0, int dW=-1, int maxC=0, Optional[str] finC=None, Optional[str] outC=None, bool do_cws=False, bool return_info=False, Optional[Union[str, Path]] cache_file=None, str solver="dist_m4ri", str codedistance_method="QDistEvol", Optional[Dict[str, Any]] codedistance_params=None, int seed=0, int debug=0, bool verbose=False, bool nothrottle=False, int chunk_size=0, int ksub=0, int kwin=0, int win_mode=0, int win_hyb=0, int pairs=-1, Optional[int] min_hits=None, int cov_cws=100, Optional[int] refresh=None, bool trust_start=False, bool start_scan=False, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, Optional[str] engine=None, **kwargs)
Any compute_quantum_distance (Any H, Optional[Any] G=None, Optional[Any] L=None, Optional[str] dist_m4ri=None, int method=3, Optional[int] threads=None, float timeout=60.0, Optional[int] num_steps=None, int d_exp=0, int d_min=0, int d_max=0, int dmin=0, int dmax=0, int dstop=0, int wmin=1, int wmax=0, Optional[int] smax=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[int] cbeg=None, Optional[int] cend=None, int noscan=0, int dW=-1, int maxC=0, Optional[str] finC=None, Optional[str] outC=None, bool do_cws=False, bool return_info=False, Optional[Union[str, Path]] cache_file=None, str solver="dist_m4ri", str codedistance_method="QDistEvol", Optional[Dict[str, Any]] codedistance_params=None, int seed=0, int debug=0, bool verbose=False, bool nothrottle=False, int chunk_size=0, int ksub=0, int kwin=0, int win_mode=0, int win_hyb=0, int pairs=-1, Optional[int] min_hits=None, int cov_cws=100, Optional[int] refresh=None, bool trust_start=False, bool start_scan=False, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, bool ortho=True, Optional[str] engine=None, **kwargs)
Optional[str] _split_css_filename (Optional[str] filepath, str sector)
Tuple[Optional[str], Optional[str]] _css_sector_finc (Optional[str] finC, Optional[str] outC)
Tuple[Any,...] compute_css_distance (Any Hx, Any Hz, Optional[Any] Lx=None, Optional[Any] Lz=None, Optional[str] dist_m4ri=None, int method=3, Optional[int] threads=None, float timeout=60.0, Optional[int] num_steps=None, int d_exp=0, int d_min=0, int d_max=0, int dmin=0, int dmax=0, int dstop=0, int wmin=1, int wmax=0, Optional[int] smax=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[int] cbeg=None, Optional[int] cend=None, int noscan=0, int dW=-1, int maxC=0, Optional[str] finC=None, Optional[str] outC=None, bool do_cws=False, Optional[Union[str, Path]] cache_file=None, str solver="dist_m4ri", str codedistance_method="QDistEvol", Optional[Dict[str, Any]] codedistance_params=None, int seed=0, int debug=0, bool verbose=False, bool nothrottle=False, int chunk_size=0, int ksub=0, int kwin=0, int win_mode=0, int win_hyb=0, int pairs=-1, Optional[int] min_hits=None, int cov_cws=100, Optional[int] refresh=None, bool trust_start=False, bool start_scan=False, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, bool ortho=True, Optional[str] engine=None, **kwargs)
Optional[str] _resolve_stim_dem_out_path (Optional[Union[bool, str, Path]] out_spec, str circuit_src, str mode_tag, str ext, Optional[Union[str, Path]] out_dir=None)
Tuple[Any, bool, bool] _circuit_dem (Any circuit)
None _warn_disabled_simple_full (Optional[bool] simple=None, Optional[bool] full=None, bool cli=False)
Tuple[Any, Optional[Any], Optional[str]] _dem_from_input (Optional[Any] dem, Optional[Any] circuit, Optional[str] basis=None, Optional[int] rounds=None, float p_noise=0.001, Optional[Union[str, Path]] out_dir=None, Optional[Union[bool, str, Path]] out_dem=None, Optional[Union[bool, str, Path]] out_stim=None, bool circ_verbose=False, Optional[List[int]] drop_out=None, bool force_noise=False)
Tuple[Any,...] compute_dem_distance (Optional[Any] dem=None, Optional[Any] circuit=None, Optional[str] dist_m4ri=None, int method=3, Optional[int] threads=None, float timeout=60.0, Optional[int] num_steps=None, int d_exp=0, int d_min=0, int d_max=0, int dmin=0, int dmax=0, int dstop=0, int wmin=1, int wmax=0, Optional[int] smax=None, Optional[Union[int, str, Sequence[int]]] start=None, Optional[int] cbeg=None, Optional[int] cend=None, int noscan=0, int dW=-1, int maxC=0, float pmin=0.0, bool merge=True, bool expand=False, Optional[Union[bool, int, str, Path]] drop=None, Optional[Union[str, Path]] outD=None, Optional[Union[bool, str, Path]] out_reduced=None, Optional[str] finC=None, Optional[str] outC=None, bool do_cws=False, Optional[Union[str, Path]] cache_file=None, str solver="dist_m4ri", str codedistance_method="UndetectableErrorStim", Optional[Dict[str, Any]] codedistance_params=None, int seed=0, int debug=0, bool verbose=False, bool nothrottle=False, int chunk_size=0, int ksub=0, int kwin=0, int win_mode=0, int win_hyb=0, int pairs=-1, Optional[int] min_hits=None, int cov_cws=100, Optional[int] refresh=None, Optional[bool] simple=None, Optional[bool] full=None, Optional[str] basis=None, Optional[int] rounds=None, Optional[Union[str, Path]] out_dir=None, Optional[Union[bool, str, Path]] out_dem=None, Optional[Union[bool, str, Path]] out_stim=None, float p_noise=0.001, bool force_noise=False, bool trust_start=False, bool start_scan=False, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, Optional[str] engine=None, **kwargs)
Tuple[List[int], List[bool], int] _model_detector_groups (Any circuit)
Tuple[List[int], List[bool], int, int, int] _dem_detector_groups (Any dem, float pmin=0.0)
Dict[str, Any] _model_matrices (List[Tuple[Any,...]] cols, List[int] group, List[bool] use, int num_observables)
Any compute_model_lower_bound (Any circuit=None, Optional[str] dist_m4ri=None, int method=3, Optional[int] threads=None, float timeout=60.0, Optional[int] num_steps=None, int dstop=0, int wmax=0, bool minority=False, float pmin=0.0, Optional[int] rounds=None, float p_noise=0.001, bool force_noise=False, Optional[Union[str, Path]] out_model=None, Optional[Union[str, Path]] cache_file=None, int seed=0, int debug=0, bool verbose=False, bool nothrottle=False, int pairs=-1, Optional[bool] sort_rows=None, Optional[int] cc_prune=None, bool return_info=False, Optional[Any] dem=None, **kwargs)
None _write_nzlist_file (str filepath, List[List[int]] cws)
Dict[str, Any] parse_cli_args (List[str] argv)
None print_cli_short_help (Optional[Any] file=None)
None print_cli_help (Optional[Any] file=None)
str _cli_morehelp_text ()
List[Tuple[str, List[str], Dict[str, str]]] _help_entries (str text)
str _help_name_key (str name)
Optional[Set[str]] _help_group_members (Tuple[str, List[str], Dict[str, str]] entry)
bool _help_group_key_match (str gkey, str key)
int print_cli_morehelp (Optional[Any] file=None, Optional[str] topic=None)
None _warn_cli_conflicts (Dict[str, Any] args)
int main (Optional[List[str]] argv=None)
int _main (Optional[List[str]] argv=None)

Variables

 _codedistance_mod = None
 _stim_mod = None
 _qec_cert_mod = None
int PY_DBG_COMMANDS = 1 << 16
int PY_DBG_CACHE = 1 << 17
int PY_DBG_CIRCUITS = 1 << 18
int PY_DBG_KEEP_FILES = 1 << 19
int BIN_DBG_MASK = 0xFFFF
int VERBOSE_DEBUG = 3 | PY_DBG_COMMANDS | PY_DBG_CACHE
dict _distance_cache = {}
bool _use_distance_cache = True
Optional _distance_cache_file = None
Set _newer_cache_files = set()
dict _last_run_stats = {}
dict _last_css_stats = {"X": {}, "Z": {}}
dict _css_distance_cache = _distance_cache
bool _use_css_distance_cache = _use_distance_cache
None clear_css_distance_cache = clear_distance_cache
None enable_css_distance_cache = enable_distance_cache
None disable_css_distance_cache = disable_distance_cache
bool _report_ignored = True
dict _CODEDISTANCE_UNUSED
int _MTX_PY_MAX_NNZ = 1 << 16

Detailed Description

dist_m4ri.py: Python wrapper for the multithreaded dist_m4ri distance calculator.

Provides high-level APIs for computing:
- Classical code distance: compute_classical_distance(...)
- Single-sided quantum code distance: compute_quantum_distance(...)
- CSS quantum code distance: compute_css_distance(...)
- Detector Error Model (DEM) distance: compute_dem_distance(...)
- Certified lower bound on the distance of a Stim memory circuit from its code-sized model:
  compute_model_lower_bound(...)

Supports distance caching, codeword export, and fallback/option for the codedistance library.
Since dist_m4ri natively handles multithreading (via POSIX threads and dynamic bracketing),
no Python-level threading or subprocess-per-core logic is necessary.

Function Documentation

◆ __getattr__()

Any dist_m4ri.__getattr__ ( str name)
Lazily resolves module attributes without loading heavy dependencies at startup.

Definition at line 125 of file dist_m4ri.py.

References _has_qec_cert().

◆ _add_noise_recursive()

Any dist_m4ri._add_noise_recursive ( Any circuit,
float p,
int num_qubits,
Set[int] active_qubits )
protected
Recursively adds uniform circuit-level noise to a Stim circuit (see add_noise()).

Definition at line 2193 of file dist_m4ri.py.

References _add_noise_recursive(), and _get_stim().

Referenced by _add_noise_recursive(), and add_noise().

◆ _binary_version()

Tuple[Optional[str], Optional[str], Optional[str]] dist_m4ri._binary_version ( Optional[str] binary_path = None)
protected
The dist_m4ri binary and its version (from `dist_m4ri --version`).

Returns:
    (path, version, error): path is None if the binary is not found; version is None if it is unknown (then
    error is the reason, or None if the binary does not support --version).

Definition at line 926 of file dist_m4ri.py.

References find_dist_m4ri_binary().

Referenced by _main(), and check_binary_compatibility().

◆ _cached_code_distance()

Dict[str, Any] dist_m4ri._cached_code_distance ( Any H,
Optional[Any] G,
Optional[Any] L,
bool classical,
str kind,
Optional[str] dist_m4ri,
int method,
Optional[int] threads,
float timeout,
Optional[int] num_steps,
int d_exp,
int dmin,
int dmax,
int dstop,
int wmin,
int wmax,
Optional[int] smax,
Optional[List[int]] start_list,
int dW,
int maxC,
Optional[str] finC,
Optional[str] outC,
bool need_cws,
Optional[str] eff_cache_file,
int seed,
int debug,
bool verbose,
bool nothrottle,
int chunk_size,
int ksub,
int kwin,
int win_mode,
Optional[int] min_hits,
int cov_cws,
Optional[int] refresh,
bool trust_start,
Optional[Any] fdem = None,
float pmin = 0.0,
bool merge = True,
Optional[Callable[[], str]] key_fn = None,
Optional[Callable[[List[List[int]]], List[List[int]]]] cws_out_fn = None,
Optional[Union[str, Path, List[int]]] fdrop = None,
Optional[str] outD = None,
Optional[bool] sort_rows = None,
int win_hyb = 0,
int pairs = -1,
Optional[int] cc_prune = None,
bool ortho = True )
protected
Distance of a classical code (H), of a quantum code (H with G or L), or of a DEM (fdem: a stim DEM object or a .dem
file, with the probability cutoff pmin, merge, the detectors to drop fdrop ("auto", "0", a file, or a list), and
the file outD for the detectors dropped: see run_dist_m4ri()) with the dist_m4ri binary, using the distance cache
shared by compute_classical_distance(), compute_quantum_distance(), the two sectors of compute_css_distance(), and
compute_dem_distance() (the warnings for the expert options are issued by the callers).  The row order sort_rows
and the CC search cc_prune (see run_dist_m4ri()) do not change the result, nor the cache key; nor do the RW window
size win_hyb, the RW pairs (pairs), and the expert option ortho (False: the binary does not check H G^T = 0) change
the cache key.

A cache record (key: key_fn() if given, otherwise see _matrix_cache_key()) answers the request if it holds the
exact distance, or with the stop target dstop > 0 a lower bound dmin >= dstop (and the codewords, if needed).
Otherwise, the binary is run, starting from the cached bounds, and the merged bounds are stored.  The returned
codewords (those of the run merged with the cached ones, or the cached ones) are written to outC; with finC
identical to outC, the codewords already in the file are kept.  If given, cws_out_fn transforms the codewords
returned and written to outC (e.g., the expansion over equal DEM columns, see _expand_equal_columns()); the cache
keeps the codewords as found.

Returns:
    dict with the distance "dist" (see _dist_from_bounds()), the bounds "dmin", "dmax", "rw_steps", "d_info"
    (see format_bounds_list()), the codewords "cws" (empty unless need_cws), and "cached" (True if no binary run).

Definition at line 3983 of file dist_m4ri.py.

References _dist_from_bounds(), _matrix_cache_key(), _matrix_to_file(), _merge_start_into_plain(), _remove_temp_files(), _resolve_start_cache(), _sector_record(), _seed_bounds_from_entry(), _single_entry_is_exact(), _union_cws(), _write_dem_file(), _write_nzlist_file(), check_finc_outc(), create_unique_file(), format_bounds_list(), load_distance_cache(), read_sparse_vectors(), run_dist_m4ri(), and save_distance_cache().

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), compute_model_lower_bound(), and compute_quantum_distance().

◆ _can_delegate_to_cert()

bool dist_m4ri._can_delegate_to_cert ( str mode,
* ,
int method = 3,
bool do_cws = False,
Optional[str] outC = None,
Optional[str] finC = None,
Optional[int] smax = None,
int dW = -1,
int maxC = 0,
Optional[List[int]] start_list = None,
Optional[Any] outD = None,
Optional[Any] out_reduced = None,
float pmin = 0.0 )
protected
Whether a distance calculation should be delegated to `qec_cert`.
In 'auto' mode, delegates only when safe (no codeword enumeration, finC, smax, start list, outD, out_reduced,
pmin > 0, or single-sided method 1/2, and `qec_cert` is importable).

Definition at line 1463 of file dist_m4ri.py.

References _get_qec_cert(), _has_qec_cert(), and _warn_ignored().

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _cert_code_distance()

Dict[str, Any] dist_m4ri._cert_code_distance ( Callable[[], str] key_fn,
Callable[[int, int], Any] run_cert_fn,
* ,
str label = "code",
int dmin = 0,
int dmax = 0,
int dstop = 0,
int wmax = 0,
Optional[str] eff_cache_file = None,
int debug = 0,
bool verbose = False )
protected

◆ _cert_extract_bounds()

Tuple[int, int] dist_m4ri._cert_extract_bounds ( Any cert,
int certified_dmin = 1 )
protected
Extracts unconditional (dmin, dmax) from a qec_cert Certificate for dist_m4ri reporting and caching:
- An exact result (dmin = dmax = d) only if status == 'exact', witness_verified is True, and not conditional.
- For bounds, an upper bound dmax only if witness_verified is True, and a lower bound dmin only when
  status in ('exact', 'bounds', 'timeout') and not lb_conditional.

Definition at line 1525 of file dist_m4ri.py.

References _cert_is_conditional(), and _cert_wmin_discharged().

Referenced by _cert_code_distance().

◆ _cert_is_conditional()

bool dist_m4ri._cert_is_conditional ( Any cert)
protected
Whether a qec_cert Certificate (or dict) has a conditional lower bound (e.g., unverified symmetry).

Definition at line 1511 of file dist_m4ri.py.

Referenced by _cert_extract_bounds(), and _cert_wmin_discharged().

◆ _cert_to_csr()

Any dist_m4ri._cert_to_csr ( Any M,
Any qec_io )
protected
Converts a matrix (file path, numpy array, or scipy sparse matrix) to a binary CSR matrix for qec_cert.

Definition at line 1502 of file dist_m4ri.py.

Referenced by compute_classical_distance(), compute_css_distance(), and compute_quantum_distance().

◆ _cert_wmin_discharged()

bool dist_m4ri._cert_wmin_discharged ( Any cert,
int certified_dmin )
protected
True iff the certificate's conditionality is caused solely by an assumed lower bound
lb_assumed_wmin <= certified_dmin (already certified in _distance_cache), with no trust
flags, no precondition violation, and no other conditional stage or reduction.

Definition at line 1549 of file dist_m4ri.py.

References _cert_is_conditional(), and _cert_wmin_discharged().

Referenced by _cert_extract_bounds(), and _cert_wmin_discharged().

◆ _check_kwargs()

None dist_m4ri._check_kwargs ( Callable[..., Any] func,
Dict[str, Any] kwargs,
Sequence[str] aliases = ("win",) )
protected
Raises TypeError for the keyword arguments in kwargs (the **kwargs of func) other than the accepted aliases
(`win` for kwin), e.g., misspelled or unsupported options, with the closest parameter names as hints.

Definition at line 1331 of file dist_m4ri.py.

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), compute_model_lower_bound(), and compute_quantum_distance().

◆ _circuit_dem()

Tuple[Any, bool, bool] dist_m4ri._circuit_dem ( Any circuit)
protected
The DEM of a Stim circuit: with decompose_errors=True if stim can decompose its errors (otherwise without).  An
error channel with disjoint cases which stim cannot write as independent error mechanisms (e.g., a PAULI_CHANNEL_1
with X and Z but no Y errors, PAULI_CHANNEL_2, or ELSE_CORRELATED_ERROR) needs approximate_disjoint_errors=True,
which is used only if the conversion fails without it: it only changes the probabilities of the error mechanisms,
not which errors are possible (so neither the distance, unless pmin > 0, nor the codewords).

Returns:
    (dem, decompose_errors, approximate_disjoint_errors): the DEM, and the options used.

Definition at line 5058 of file dist_m4ri.py.

Referenced by _dem_from_input(), and test_dist_m4ri.test_stim_pauli_channel_circuit().

◆ _cli_morehelp_text()

str dist_m4ri._cli_morehelp_text ( )
protected
The full help text of the CLI (--morehelp).

Definition at line 6771 of file dist_m4ri.py.

Referenced by print_cli_morehelp().

◆ _css_combine()

Tuple[int, int, int, int] dist_m4ri._css_combine ( Tuple[int, int, int] x,
Tuple[int, int, int] z,
int dmax = 0 )
protected
Bounds of the CSS distance d = min(dX, dZ) from the sector bounds x, z = (dmin, dmax, rw_steps), and an upper
bound `dmax` on d supplied by the user (0: none).

Returns:
    (dist, dmin, dmax, rw_steps): dist is the smaller sector distance (see _dist_from_bounds(); the larger one if
    a sector distance is 0), at most the user's dmax; dmin = min(dmin_X, dmin_Z); dmax is the smallest of the
    positive upper bounds (0: none).

Definition at line 3888 of file dist_m4ri.py.

References _dist_from_bounds().

Referenced by _main(), compute_css_distance(), and get_cached_distance().

◆ _css_sector_codes()

Dict[str, Tuple[Any, Any, Any]] dist_m4ri._css_sector_codes ( Any Hx,
Any Hz,
Optional[Any] Lx,
Optional[Any] Lz )
protected
The quantum codes (H, G, L) of the two sectors of a CSS code: Z -> (Hx, Hz or Lx), X -> (Hz, Hx or Lz).

Definition at line 3880 of file dist_m4ri.py.

Referenced by _migrate_css_records(), compute_css_distance(), and get_cached_distance().

◆ _css_sector_finc()

Tuple[Optional[str], Optional[str]] dist_m4ri._css_sector_finc ( Optional[str] finC,
Optional[str] outC )
protected
Input codeword files (finC_X, finC_Z) of the two CSS sectors: the sector files (e.g. 'cws.nz' -> 'cws_X.nz' and
'cws_Z.nz') which exist and are not empty; if there are none, finC itself for both sectors (codewords which are
not valid in a sector are skipped by the binary), unless finC is identical to outC and does not exist or is
empty (see check_finc_outc()).

Definition at line 4705 of file dist_m4ri.py.

References _split_css_filename(), and check_finc_outc().

Referenced by compute_css_distance().

◆ _dem_cache_key()

str dist_m4ri._dem_cache_key ( Any dem,
float pmin = 0.0 )
protected
Cache key of a DEM (a stim.DetectorErrorModel or a .dem file) with the probability cutoff pmin.

Definition at line 3617 of file dist_m4ri.py.

References get_sparse_array_state().

Referenced by compute_dem_distance(), compute_model_lower_bound(), and get_cached_distance().

◆ _dem_detector_groups()

Tuple[List[int], List[bool], int, int, int] dist_m4ri._dem_detector_groups ( Any dem,
float pmin = 0.0 )
protected
Pure-DEM detector chains for compute_model_lower_bound() when no Stim circuit is available (or when the circuit
groups are trivial).  Uses detector coordinates (x, y, ..., t) when present in the DEM to group detectors with the
same spatial coordinates across rounds, and falls back to linking consecutive-round detectors via dominant weight-2
observable-free (ancilla measurement) error mechanisms when coordinates are absent.

Returns:
    (group, final, num_final, num_detectors, num_observables).

Definition at line 5703 of file dist_m4ri.py.

References _dem_error_columns().

Referenced by compute_model_lower_bound().

◆ _dem_error_columns()

List[Tuple[Any, ...]] dist_m4ri._dem_error_columns ( Any dem,
float pmin = 0.0,
bool with_prob = False )
protected
The columns of a DEM (a stim.DetectorErrorModel, or a .dem file) as read by the dist_m4ri binary: the detector and
observable sets of its error mechanisms, in their order in the flattened DEM (repeat blocks unrolled, with
shift_detectors), after the probability cutoff pmin (an error with probability < pmin is skipped).  The components
of a decomposed error (separated by '^') are summed mod 2, so that a target listed twice cancels.  With
with_prob=True, each column also has the probability of the error, as written: (detectors, observables, p).

Definition at line 3634 of file dist_m4ri.py.

Referenced by _dem_detector_groups(), _expand_equal_columns(), compute_model_lower_bound(), test_dist_m4ri.test_dem_drop_minority_detectors(), test_dist_m4ri.test_dem_error_columns_parser(), test_dist_m4ri.test_dem_out_reduced(), and write_reduced_dem().

◆ _dem_from_input()

Tuple[Any, Optional[Any], Optional[str]] dist_m4ri._dem_from_input ( Optional[Any] dem,
Optional[Any] circuit,
Optional[str] basis = None,
Optional[int] rounds = None,
float p_noise = 0.001,
Optional[Union[str, Path]] out_dir = None,
Optional[Union[bool, str, Path]] out_dem = None,
Optional[Union[bool, str, Path]] out_stim = None,
bool circ_verbose = False,
Optional[List[int]] drop_out = None,
bool force_noise = False )
protected
The DEM of compute_dem_distance() (also used by get_cached_distance() for the cache key).  A DEM
(stim.DetectorErrorModel or .dem file) is used as given.  A Stim circuit (stim.Circuit or .stim file, also when
given as `dem`) is processed: the empty detectors are removed, the qubits are classified, the REPEAT count is set
(rounds), and circuit-level noise of strength p_noise is added to a noiseless circuit (see add_noise(); none for
p_noise=0), or with force_noise=True replaces the noise of the circuit (see strip_noise(); with p_noise=0, all noise
is removed); then it is converted to a DEM (with all detectors).  The processed circuit and the DEM are saved if
requested (out_stim, out_dem, out_dir; see compute_dem_distance()).  For a CSS circuit, the list drop_out (if given)
is extended by the minority-basis detectors (0-based detectors of the DEM, see strip_minority_detectors()), which
the binary drops if this is exact (drop=css, passed as drop=FILE).  The qubits are only classified for drop_out and
circ_verbose.

Returns:
    (dem, circuit, saved_dem_path): the DEM (object or file name), the processed circuit (None for a DEM input),
    and the file to which the DEM was saved (None if it was not saved).

Definition at line 5096 of file dist_m4ri.py.

References _circuit_dem(), _get_stim(), _resolve_stim_dem_out_path(), _warn_ignored(), _write_dem_file(), add_noise(), classify_qubits_thorough(), count_circuit_rounds(), has_noise(), has_repeat_block(), remove_empty_detectors(), set_circuit_rounds(), and strip_minority_detectors().

Referenced by compute_dem_distance(), compute_model_lower_bound(), get_cached_distance(), and test_dist_m4ri.test_dem_drop_minority_detectors().

◆ _dist_from_bounds()

int dist_m4ri._dist_from_bounds ( int dmin,
int dmax )
protected
The distance reported for the bounds [dmin, dmax]: dmin if exact or without an upper bound, otherwise dmax.

Definition at line 1421 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _cert_code_distance(), _css_combine(), _merge_start_into_plain(), and _sector_record().

◆ _drop_mode()

str dist_m4ri._drop_mode ( Any drop)
protected
The drop option of compute_dem_distance(): "auto" (for None, True, 1, "1", or "auto"), "0" (False, 0, or "0"),
"css", or the name of an existing file (ValueError otherwise).

Definition at line 3691 of file dist_m4ri.py.

Referenced by compute_dem_distance().

◆ _expand_equal_columns()

List[List[int]] dist_m4ri._expand_equal_columns ( List[List[int]] cws,
Any dem,
float pmin = 0.0,
int maxC = 0,
bool verbose = False )
protected
The expanded list of the DEM codewords cws (0-based columns of the DEM, see _dem_error_columns()): every version
over the choices among equal columns (the same detectors and observables), which the binary merges (merge=1).
Each codeword is mapped to the first columns of its sets of equal columns (two equal columns cancel), and every
distinct result c is expanded into the prod_{j in c} |set(j)| codewords with one column from each set (sorted, in
the order of cws).  With maxC > 0, at most maxC codewords are returned, with a warning to stderr if some are
dropped.

Definition at line 3822 of file dist_m4ri.py.

References _dem_error_columns().

Referenced by compute_dem_distance().

◆ _format_duration()

str dist_m4ri._format_duration ( float t)
protected
Formats a duration in seconds (s, min, h, or days), as in the dist_m4ri binary.

Definition at line 381 of file dist_m4ri.py.

◆ _format_start_list()

str dist_m4ri._format_start_list ( List[int] start_list,
int max_show = 8 )
protected
Formats a start list for messages, showing at most `max_show` entries (as the dist_m4ri binary).

Definition at line 1201 of file dist_m4ri.py.

◆ _get_codedistance()

dist_m4ri._get_codedistance ( )
protected
Lazily imports the codedistance library only when requested.

Definition at line 79 of file dist_m4ri.py.

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _get_qec_cert()

dist_m4ri._get_qec_cert ( )
protected
Lazily imports qec_cert (io, pipeline) only when requested.

Definition at line 103 of file dist_m4ri.py.

Referenced by _can_delegate_to_cert(), _has_qec_cert(), compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _get_stim()

◆ _gf2_entries()

Tuple[int, int, Any, Any] dist_m4ri._gf2_entries ( Any matrix)
protected
The shape (m, n) and the nonzero entries (0-based row and column index arrays, in row-major order) of a binary
matrix given as a numpy array (or an array-like, e.g., a list of lists) or a scipy sparse matrix (or array): an
entry is nonzero iff its value is odd (floats are truncated to integers, and the duplicate entries of a sparse
matrix are summed first), as the dist_m4ri binary reads the integer entries of a MatrixMarket file.

Definition at line 2085 of file dist_m4ri.py.

Referenced by _write_mtx_gf2().

◆ _has_qec_cert()

bool dist_m4ri._has_qec_cert ( )
protected
Checks whether qec_cert is importable without raising ImportError.

Definition at line 116 of file dist_m4ri.py.

References _get_qec_cert().

Referenced by __getattr__(), and _can_delegate_to_cert().

◆ _help_entries()

List[Tuple[str, List[str], Dict[str, str]]] dist_m4ri._help_entries ( str text)
protected
The entries of a help text (see _cli_morehelp_text()): (section header, the lines of the entry, its names).  An
entry starts with a line indented by 2 spaces (the names, then the description), and continues with the lines
indented by more; a section header is a line without indentation ending with ':'.  The names (a dict: normalized
name -> name as written) are those in the first column (e.g., 'Hx=FILE, Hz=FILE' -> Hx, Hz; '--no-cache /
nocache'), without the values (FILE, [N], ...; but all words of a note such as '(DEM codewords)'), and the aliases
in the description ('alias: dest', 'Alias: win=N', 'also --no-throttle', 'also rounds=N'); normalized: lowercase,
without '-' and '_'.

Definition at line 7220 of file dist_m4ri.py.

References _help_name_key().

Referenced by print_cli_morehelp().

◆ _help_group_key_match()

bool dist_m4ri._help_group_key_match ( str gkey,
str key )
protected
Whether the topic key matches the name gkey of a group, also as singular or plural (e.g., window, windows).

Definition at line 7275 of file dist_m4ri.py.

Referenced by print_cli_morehelp().

◆ _help_group_members()

Optional[Set[str]] dist_m4ri._help_group_members ( Tuple[str, List[str], Dict[str, str]] entry)
protected
The normalized names of the members of a group (an entry of the section 'Option groups' of the full help: the
names listed after its first column), or None for another entry.

Definition at line 7261 of file dist_m4ri.py.

References _help_name_key().

Referenced by print_cli_morehelp().

◆ _help_name_key()

str dist_m4ri._help_name_key ( str name)
protected
A name of a help entry normalized for matching (see _help_entries()): lowercase, without '-' and '_'.

Definition at line 7256 of file dist_m4ri.py.

Referenced by _help_entries(), _help_group_members(), and print_cli_morehelp().

◆ _ksub_warning_text()

str dist_m4ri._ksub_warning_text ( int ksub)
protected
Returns the stderr warning for the experimental RW option ksub (same wording as the dist_m4ri binary).

Definition at line 1285 of file dist_m4ri.py.

Referenced by _warn_experimental_ksub().

◆ _main()

◆ _matrix_cache_key()

str dist_m4ri._matrix_cache_key ( Any H,
Optional[Any] G = None,
Optional[Any] L = None,
bool classical = False )
protected
Cache key of a classical code (H), or of a quantum code given by H with G (or with L).  The two sectors of a CSS
code are stored as the quantum codes (H=Hx, G=Hz) -> dZ and (H=Hz, G=Hx) -> dX (with L=Lx / L=Lz if given), so
that compute_css_distance() and compute_quantum_distance() share their cache records.

Definition at line 3603 of file dist_m4ri.py.

References get_sparse_array_state().

Referenced by _cached_code_distance(), _migrate_css_records(), compute_classical_distance(), compute_css_distance(), compute_quantum_distance(), and get_cached_distance().

◆ _matrix_to_file()

str dist_m4ri._matrix_to_file ( matrix,
str extension = ".mtx",
str temp_dir = "tmp" )
protected
The MatrixMarket file of a matrix for the dist_m4ri binary: a file path is returned as is; a numpy array (or an
array-like) or a scipy sparse matrix is written to a new temporary file in temp_dir with _write_mtx_gf2() (its
nonzero entries over GF(2), i.e., those with an odd value; before version 0.15.2, scipy.io.mmwrite wrote the int8
entries, which took 10-13 ms per matrix with up to 1000 columns on a 128-core machine).

Definition at line 2147 of file dist_m4ri.py.

References _write_mtx_gf2(), and create_unique_file().

Referenced by _cached_code_distance(), and test_dist_m4ri.test_matrix_writer().

◆ _merge_start_into_plain()

bool dist_m4ri._merge_start_into_plain ( str plain_key,
Dict[str, Any] src,
bool trust = False,
Optional[Dict[str, int]] rw_delta = None )
protected
Merges the start-list cache record `src` (key plain_key + ':start=...') into the main record `plain_key`.

The upper bound dmax (minimum of the positive values) and the codewords (union) are always valid and
are always merged.  Only with `trust` (expert option trust_start) the lower bound dmin is merged as well
(maximum, capped at dmax), and rw_steps are either incremented by the steps of the run, `rw_delta`
(after a calculation), or set to the maximum of the two records (copy of a cached record, rw_delta=None).
(A CSS code is cached as the records of its two sectors, see _matrix_cache_key().)

Args:
    plain_key: Main cache key.
    src: Start-list cache record.
    trust: Accept the start-list lower bound as valid.
    rw_delta: RW steps of the run, {'': steps}.

Returns:
    True if the main record was created or modified.

Definition at line 1695 of file dist_m4ri.py.

References _dist_from_bounds(), _union_cws(), and format_bounds_list().

Referenced by _cached_code_distance().

◆ _migrate_css_records()

bool dist_m4ri._migrate_css_records ( Any Hx,
Any Hz,
Optional[Any] Lx = None,
Optional[Any] Lz = None,
Optional[str] eff_cache_file = None )
protected
Converts the CSS cache records written before version 0.12.0 (key 'css:X=<Hx>:Z=<Hz>[:Lx=<Lx>:Lz=<Lz>]', also
with a ':start=...' suffix) into the records of the two sectors (see _matrix_cache_key()), and removes them.

The lower bounds dmin_X and dmin_Z are kept.  An upper bound dmax_X or dmax_Z is kept only if a stored codeword
confirms it, or if it is smaller than the upper bound of the other sector: earlier versions passed an upper bound
dmax given to compute_css_distance() (a bound on min(dX, dZ)) to both sectors, where it was reported back as the
upper bound of the sector, which is not valid for the sector with the larger distance.  Otherwise, the weight of
the lightest stored codeword (if any) is used.

Returns:
    True if a record was converted (the cache file, if any, is then saved).

Definition at line 3928 of file dist_m4ri.py.

References _css_sector_codes(), _matrix_cache_key(), _sector_record(), _union_cws(), and save_distance_cache().

Referenced by compute_css_distance(), and get_cached_distance().

◆ _model_detector_groups()

Tuple[List[int], List[bool], int] dist_m4ri._model_detector_groups ( Any circuit)
protected
The groups of the detectors of a Stim circuit for its code-sized model (see compute_model_lower_bound()): two
detectors are in the same group if they share a measurement record other than a final data measurement.  The final
data measurements are the measurements in the final measurement block (after the last detector which precedes the
last measurement) of qubits not measured before it, or all measurements of the final block if there are none
(e.g., if every qubit is measured in each round).  In a memory circuit, the groups are the chains of the detectors
of the checks, linked by the measurements of their ancillas in consecutive rounds; the chain of a check of the
measured basis ends with its detector of the final data measurements.

Returns:
    (group, final, num_final): the group of each detector (numbered in the order of their first detectors), for
    each group whether one of its detectors has a final data measurement, and the number of final data
    measurements.

Definition at line 5634 of file dist_m4ri.py.

References _get_stim().

Referenced by compute_model_lower_bound(), and test_dist_m4ri.test_model_detector_groups_end_of_circuit_and_pure_dem().

◆ _model_matrices()

Dict[str, Any] dist_m4ri._model_matrices ( List[Tuple[Any, ...]] cols,
List[int] group,
List[bool] use,
int num_observables )
protected
The matrices of a code-sized model (see compute_model_lower_bound()): one row per group of detectors with use[g]
(the sum of the rows of its detectors), and one column per distinct pair (model column, observables) of the error
mechanisms `cols` (see _dem_error_columns()); the errors with no effect on the rows nor on the observables are
dropped.

Returns:
    dict with "H" and "L" (scipy.sparse.csr_matrix), "col_map" (the model column of each error mechanism, -1 if
    it is dropped), "groups" (the group of each row), and "trivial" (the error mechanisms which flip an observable
    but no row: then the model has a codeword of weight 1).

Definition at line 5861 of file dist_m4ri.py.

Referenced by compute_model_lower_bound().

◆ _normalize_start_list()

Optional[List[int]] dist_m4ri._normalize_start_list ( Any start)
protected
Normalizes the expert CC start-column specification `start` into a sorted list of distinct
non-negative (0-based) column indices, or None if unset.

Accepts None, an integer, a comma-separated string (e.g., "0,48"), or a sequence of integers.
A single negative value (e.g., -1, the default of the dist_m4ri binary) means unset (all columns).

Raises:
    ValueError: on malformed input or on negative entries in a list of several columns.

Definition at line 1132 of file dist_m4ri.py.

Referenced by _prepare_start_option(), get_cached_distance(), parse_cli_args(), and run_dist_m4ri().

◆ _ortho_warning_text()

str dist_m4ri._ortho_warning_text ( )
protected
Returns the stderr warning for the expert option ortho=0 (same wording as the dist_m4ri binary).

Definition at line 1307 of file dist_m4ri.py.

Referenced by _warn_ortho().

◆ _parse_stderr_stats()

Dict[str, Any] dist_m4ri._parse_stderr_stats ( str stderr)
protected
Parses codeword and hit statistics from dist_m4ri stderr output (debug & 1), and with debug & 8 the CC rounds:
"cc_rounds", a list with an entry for each completed CC round, {"w": weight, "work": the CC thread time in s,
"predicted": the predicted work (None if not known), "time": the wall time of the round in s, "threads": the CC
threads (at the end of the round in method=3), "nodes": the calls of the CC recursion (None from binaries before
0.15.0)}, and "cc_nodes", the total of the nodes of these rounds.

Definition at line 392 of file dist_m4ri.py.

Referenced by run_dist_m4ri(), test_dist_m4ri.test_cc_round_stats(), and test_dist_m4ri.test_rw_infoset_estimate().

◆ _parse_version()

Tuple[int, ...] dist_m4ri._parse_version ( str v_str)
protected

Definition at line 920 of file dist_m4ri.py.

Referenced by check_binary_compatibility(), and load_distance_cache().

◆ _prepare_start_option()

Optional[List[int]] dist_m4ri._prepare_start_option ( Any start,
bool trust_start = False,
Any noscan = 0,
Any cbeg = None,
Any cend = None,
str solver = "dist_m4ri",
bool start_scan = False )
protected
Validates the expert CC options of a compute_*_distance() call and issues the warnings to stderr.

Returns:
    The normalized start list (with the flag `scan` for start_scan, see _StartList), or None if unset (or not
    applicable to the selected solver).

Definition at line 1352 of file dist_m4ri.py.

References _normalize_start_list(), _scan_start_list(), _start_warning_text(), _warn_disabled_options(), and _warn_ignored().

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _reduced_out_prefix()

str dist_m4ri._reduced_out_prefix ( Union[bool, str, Path] spec,
str src,
Optional[Union[str, Path]] out_dir = None )
protected
The prefix PREFIX of the files PREFIX_red.dem and PREFIX_red.json of compute_dem_distance(out_reduced=spec) for the
input src (a file name, or e.g. 'stim.Circuit'): for True (also '', '1', 'true', 'yes', 'auto'), the basename of
the input file (without a suffix _full or _simp; 'dem' for an object); a bare name goes to out_dir (default: the
directory of the input file, as for --out-dem), and a path is used as given.

Definition at line 3716 of file dist_m4ri.py.

Referenced by compute_dem_distance().

◆ _remove_temp_files()

None dist_m4ri._remove_temp_files ( Sequence[Optional[str]] files,
int debug = 0 )
protected
Removes the temporary files `files` (None entries are skipped); with the debug bit PY_DBG_KEEP_FILES, the
files are kept and listed instead.

Definition at line 829 of file dist_m4ri.py.

Referenced by _cached_code_distance(), and compute_dem_distance().

◆ _resolve_cert_engine()

str dist_m4ri._resolve_cert_engine ( str solver = "dist_m4ri",
Optional[str] engine = None )
protected
Resolves the qec_cert delegation mode ('off', 'auto', or 'cert') from `solver` and `engine`.
Default ('dist_m4ri', engine=None) returns 'off'.

Definition at line 1437 of file dist_m4ri.py.

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _resolve_start_cache()

Tuple[str, Optional[Dict[str, Any]], Optional[Dict[str, Any]]] dist_m4ri._resolve_start_cache ( str plain_key,
Optional[List[int]] start_list,
Callable[[Dict[str, Any]], bool] is_hit,
bool trust_start,
Callable[[Dict[str, Any]], bool] merge_copy,
Optional[str] eff_cache_file,
bool verbose = False )
protected
Resolves the cache record of a run with an optional expert CC start list.

Without a start list, or if the main record already holds the requested exact result, the main record
is used.  Otherwise the separate start-list record (key plain_key + ':start=a,b,c') is used; with
trust_start, an existing exact start-list record is copied to the main record (via `merge_copy`), and
the cache file is saved, even though no calculation is needed.

Returns:
    (code_key, cached_entry, plain_entry): the key and the existing record (or None) for the results of
    this run, and the main record (or None) used to seed the bounds of a start-list run.

Definition at line 1748 of file dist_m4ri.py.

References _start_key_suffix(), and save_distance_cache().

Referenced by _cached_code_distance().

◆ _resolve_stim_dem_out_path()

Optional[str] dist_m4ri._resolve_stim_dem_out_path ( Optional[Union[bool, str, Path]] out_spec,
str circuit_src,
str mode_tag,
str ext,
Optional[Union[str, Path]] out_dir = None )
protected
Resolves output filepath for --out-dem or --out-stim.

Definition at line 5006 of file dist_m4ri.py.

Referenced by _dem_from_input().

◆ _rewrite_circuit_internal()

Any dist_m4ri._rewrite_circuit_internal ( Any circ,
Dict[int, int] phys_to_log,
Dict[int, int] active_gates_count )
protected
Rewrites a Stim circuit by tracking SWAPs virtually.

Definition at line 2651 of file dist_m4ri.py.

References _get_stim(), and _rewrite_circuit_internal().

Referenced by _rewrite_circuit_internal(), and classify_qubits_thorough().

◆ _scan_start_list()

Optional[List[int]] dist_m4ri._scan_start_list ( Optional[List[int]] start_list,
bool start_scan )
protected
The start list with the flag `scan` set if start_scan (None or the list itself otherwise).

Definition at line 1184 of file dist_m4ri.py.

Referenced by _prepare_start_option(), get_cached_distance(), and run_dist_m4ri().

◆ _sector_record()

Dict[str, Any] dist_m4ri._sector_record ( int dmin,
int dmax,
int rw_steps,
List[List[int]] cws )
protected
A cache record of a classical or quantum code (or of a CSS sector) with the bounds [dmin, dmax].

Definition at line 3914 of file dist_m4ri.py.

References _dist_from_bounds(), and format_bounds_list().

Referenced by _cached_code_distance(), _cert_code_distance(), _migrate_css_records(), and compute_model_lower_bound().

◆ _seed_bounds_from_entry()

Tuple[int, int] dist_m4ri._seed_bounds_from_entry ( int eff_dmin,
int eff_dmax,
Optional[Dict[str, Any]] entry )
protected
Tightens the bounds (eff_dmin, eff_dmax) with those stored in a cache entry (a CSS code is cached as the
records of its two sectors, see _matrix_cache_key()).

Definition at line 1392 of file dist_m4ri.py.

Referenced by _cached_code_distance(), and _cert_code_distance().

◆ _single_entry_is_exact()

bool dist_m4ri._single_entry_is_exact ( Dict[str, Any] entry,
bool need_cws = False,
int dstop = 0 )
protected
Cache hit test for a classical / quantum / DEM entry: the exact distance, or with the stop target dstop > 0 a
lower bound dmin >= dstop (and codewords if needed).

Definition at line 1426 of file dist_m4ri.py.

Referenced by _cached_code_distance(), and _cert_code_distance().

◆ _split_css_filename()

Optional[str] dist_m4ri._split_css_filename ( Optional[str] filepath,
str sector )
protected
Generates sector-suffixed filename for CSS codewords (e.g. 'cws.nz' -> 'cws_X.nz').

Definition at line 4691 of file dist_m4ri.py.

Referenced by _css_sector_finc(), and compute_css_distance().

◆ _start_key_suffix()

str dist_m4ri._start_key_suffix ( Optional[List[int]] start_list)
protected
Returns the cache key suffix ':start=a,b,c' for a normalized start list ('' if unset), with ':scan' for
start_scan.

Definition at line 1193 of file dist_m4ri.py.

Referenced by _resolve_start_cache(), get_cached_distance(), and test_dist_m4ri.test_normalize_start_list().

◆ _start_warning_text()

str dist_m4ri._start_warning_text ( List[int] start_list)
protected
Returns the stderr warning for a CC start list (same wording as the dist_m4ri binary).

Definition at line 1268 of file dist_m4ri.py.

Referenced by _prepare_start_option(), and run_dist_m4ri().

◆ _union_cws()

List[List[int]] dist_m4ri._union_cws ( Optional[List[List[int]]] base,
Optional[List[List[int]]] extra )
protected
Returns the union of two codeword lists (duplicates removed, sorted by weight).

Definition at line 1408 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _merge_start_into_plain(), and _migrate_css_records().

◆ _warn_cli_conflicts()

None dist_m4ri._warn_cli_conflicts ( Dict[str, Any] args)
protected
Writes warnings to stderr for the CLI inputs which are ignored.  The input is selected in the order fdem (a DEM or
a Stim circuit), Hx / Hz (a CSS code), and finH / finG / finL / fin (one sector of a quantum code, or a classical
code); fin=PREFIX supplies only the missing finH (PREFIX + 'X.mtx') and finG (PREFIX + 'Z.mtx', unless finL).  The
disabled options --simple and --full always give a warning (see _warn_disabled_simple_full()), and so does the
expert option irred of the dist_m4ri binary, unless irred=1 (the codewords recorded are always irreducible).  The
expert option ortho=0 gives a warning here for a DEM or a classical code (for a quantum code, see _warn_ortho()).

Definition at line 7333 of file dist_m4ri.py.

References _warn_disabled_simple_full(), and _warn_ignored().

Referenced by _main(), and test_dist_m4ri.test_ignored_inputs_warnings().

◆ _warn_codedistance_ignored()

None dist_m4ri._warn_codedistance_ignored ( Dict[str, Any] values)
protected
With solver="codedistance": a warning (see _warn_ignored()) on the options of the dist_m4ri binary in `values`
(the locals() of a compute_*() function) which are not at their defaults (see _CODEDISTANCE_UNUSED).

Definition at line 1239 of file dist_m4ri.py.

References _warn_ignored().

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), and compute_quantum_distance().

◆ _warn_disabled_options()

None dist_m4ri._warn_disabled_options ( Any noscan = 0,
Any cbeg = None,
Any cend = None )
protected
Issues a warning to stderr for each of the expert options noscan, cbeg, and cend that is set.
These options are disabled in the Python interface: they are accepted for backward compatibility
but ignored, since their results are not valid distance bounds on their own.

Definition at line 1249 of file dist_m4ri.py.

References _warn_ignored().

Referenced by _prepare_start_option(), and run_dist_m4ri().

◆ _warn_disabled_simple_full()

None dist_m4ri._warn_disabled_simple_full ( Optional[bool] simple = None,
Optional[bool] full = None,
bool cli = False )
protected
Writes a warning to stderr if the options simple or full (CLI: --simple, --full) are given: they are disabled since
version 0.13.0 (accepted for backward compatibility, but ignored).  The DEM of a Stim circuit always has all
detectors, and the binary drops detectors if this is exact (drop=auto, the default; e.g., the minority-basis
detectors of a CSS circuit, which the simple mode stripped): as fast, with the distance of the full DEM (the
simplified DEM only gives a lower bound when dropping them is not exact).

Definition at line 5081 of file dist_m4ri.py.

References _warn_ignored().

Referenced by _warn_cli_conflicts(), compute_dem_distance(), and get_cached_distance().

◆ _warn_experimental_ksub()

None dist_m4ri._warn_experimental_ksub ( Any ksub,
int method,
str solver = "dist_m4ri" )
protected
Issues the warning for the experimental RW option ksub > 0 to stderr (with or without min_hits), if RW runs
(method=1 or 3) with the dist_m4ri binary.

Definition at line 1294 of file dist_m4ri.py.

References _ksub_warning_text().

Referenced by compute_classical_distance(), compute_css_distance(), compute_dem_distance(), compute_quantum_distance(), and run_dist_m4ri().

◆ _warn_ignored()

None dist_m4ri._warn_ignored ( str msg)
protected
Writes the warning '# Warning: msg' on an input which is ignored to stderr, unless set_silent() is on.

Definition at line 1220 of file dist_m4ri.py.

Referenced by _can_delegate_to_cert(), _dem_from_input(), _prepare_start_option(), _warn_cli_conflicts(), _warn_codedistance_ignored(), _warn_disabled_options(), _warn_disabled_simple_full(), _warn_ortho(), compute_dem_distance(), and run_dist_m4ri().

◆ _warn_ortho()

None dist_m4ri._warn_ortho ( Any ortho,
bool has_g,
str solver = "dist_m4ri" )
protected
Issues the warning for the expert option ortho=False to stderr: the dist_m4ri binary does not check that the rows
of H and G are orthogonal (if has_g: a matrix G is given), or the option has no effect (without G, or with the
codedistance solver).

Definition at line 1315 of file dist_m4ri.py.

References _ortho_warning_text(), and _warn_ignored().

Referenced by compute_css_distance(), compute_quantum_distance(), and run_dist_m4ri().

◆ _write_dem_file()

None dist_m4ri._write_dem_file ( Any dem,
str path )
protected
Writes a stim.DetectorErrorModel (flattened) or the text of a DEM to the file `path`.

Definition at line 3623 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _dem_from_input(), and compute_dem_distance().

◆ _write_mtx_gf2()

None dist_m4ri._write_mtx_gf2 ( str path,
Any matrix )
protected
Writes a binary matrix (numpy array, array-like, or scipy sparse matrix; see _gf2_entries()) to the file `path` in
the MatrixMarket coordinate pattern format (the 1-based indices of the nonzero entries, in row-major order), which
the dist_m4ri binary reads.  With up to _MTX_PY_MAX_NNZ nonzero entries, the file is formatted in Python (e.g.,
about 1 ms for 6000 entries); larger matrices are written by scipy.io.mmwrite, which is faster per entry, but has a
fixed cost of about 10 ms per call on a 128-core machine (the thread pool of its parallel writer).

Definition at line 2122 of file dist_m4ri.py.

References _gf2_entries().

Referenced by _matrix_to_file().

◆ _write_nzlist_file()

None dist_m4ri._write_nzlist_file ( str filepath,
List[List[int]] cws )
protected
Writes codewords to a text file in NZLIST format (1-based indices).
Skips creating the file if cws is empty.

Definition at line 6113 of file dist_m4ri.py.

Referenced by _cached_code_distance(), test_dist_m4ri.test_cached_outc_keeps_finc_codewords(), and test_dist_m4ri.test_cli_outc_keeps_finc_codewords().

◆ add_noise()

Any dist_m4ri.add_noise ( Any circuit,
float p = 0.001,
bool force = False )
Adds uniform circuit-level noise of strength p to a Stim circuit (the gates are classified by stim.gate_data()):
- DEPOLARIZE2(p) after two-qubit gates (CX, CY, CZ, XCX, XCY, XCZ, YCX, YCY, YCZ, SWAP, ISWAP, ISWAP_DAG, SQRT_XX,
  SQRT_YY, SQRT_ZZ and their _DAG versions, CXSWAP, SWAPCX, CZSWAP, II); a classically controlled gate (e.g.,
  CX rec[-1] 5 or CZ sweep[0] 5) gets DEPOLARIZE1(p/10) on its qubit;
- DEPOLARIZE1(p/10) after one-qubit gates (I, X, Y, Z, H, H_XY, H_YZ, S, S_DAG, SQRT_X, SQRT_Y and their _DAG
  versions, C_XYZ, C_ZYX, and the other variants), and on the qubits idle since the previous TICK (at each TICK,
  and at the end of the circuit);
- X (Z) flips with probability p after Z-basis or Y-basis (X-basis) resets and before measurements, both before and
  after a measurement with reset (MR, MRX, MRY);
- none for the multi-qubit measurements (MPP, MXX, MYY, MZZ) and the Pauli product gates (SPP, SPP_DAG).
The noise of a noisy circuit is kept and the uniform noise is added to it, unless force=True: then it is replaced
(see strip_noise()).

Args:
    circuit: stim.Circuit or path to a .stim file.
    p: Noise strength (for the distance, only which errors are possible matters); p=0: no noise is added.
    force: If True, all noise of the circuit is removed first (with p=0: only that).

Returns:
    The noisy stim.Circuit (a copy).

Definition at line 2261 of file dist_m4ri.py.

References _add_noise_recursive(), _get_stim(), and strip_noise().

Referenced by _dem_from_input(), make_yarn_mitten_circuits.main(), test_dist_m4ri.test_add_noise_and_noiseless_circuit(), test_dist_m4ri.test_add_noise_classically_controlled(), and test_dist_m4ri.test_add_noise_gate_classes_and_strip_noise().

◆ check_binary_compatibility()

Optional[str] dist_m4ri.check_binary_compatibility ( Optional[str] binary_path = None)
Checks if the backend dist_m4ri binary exists and is compatible (version >= __version__).
Returns a warning message string if missing or older, or None if compatible (silent).

Definition at line 948 of file dist_m4ri.py.

References _binary_version(), and _parse_version().

Referenced by _main(), and test_dist_m4ri.test_binary_compatibility_warning().

◆ check_finc_outc()

Optional[str] dist_m4ri.check_finc_outc ( Optional[str] finC,
Optional[str] outC,
bool verbose = False )
When finC and outC names are identical, an empty or non-existent file is silently ignored
(with a warning if verbose is True).

Returns:
    The effective finC filepath to use (or None if ignored).

Definition at line 1092 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _css_sector_finc(), run_dist_m4ri(), and test_dist_m4ri.test_check_finc_outc().

◆ classify_qubits_thorough()

Dict[str, Any] dist_m4ri.classify_qubits_thorough ( Any circuit,
bool verbose = False,
Optional[str] basis_arg = None,
Optional[Union[str, Path]] filepath = None )
Classifies qubits and checks via virtual SWAP rewriting and Pauli basis tracking.

Tracks both ancilla stabilizer evolution and data qubit initial basis
evolution through 1-qubit and 2-qubit Clifford gates. Supports standard
CSS codes as well as locally basis-rotated CSS codes (such as XZZX codes)
via 2-coloring of the check-data Pauli compatibility graph.

Returns:
    Dictionary with keys:
    - 'x_ancillas': Sorted list of X-type (or X-sector) ancilla qubit IDs.
    - 'z_ancillas': Sorted list of Z-type (or Z-sector) ancilla qubit IDs.
    - 'data_qubits': Sorted list of data qubit IDs.
    - 'routing_qubits': Sorted list of idle/routing qubit IDs.
    - 'rotated_data_qubits': Sorted list of data qubits with rotated local basis.
    - 'is_css': True if the circuit implements a (possibly locally rotated) CSS code.
    - 'is_rotated_css': True if CSS only after local data basis rotations (e.g. XZZX).
    - 'basis': Primary memory basis ('X' or 'Z').
    - 'rewritten_circuit': Circuit with SWAPs virtually eliminated.

Definition at line 2791 of file dist_m4ri.py.

References _get_stim(), _rewrite_circuit_internal(), and detect_basis().

Referenced by _dem_from_input(), test_dist_m4ri._make_xzzx_circuit(), strip_minority_detectors(), test_dist_m4ri.test_classify_qubits_checks_measured_in_hadamard_frame(), test_dist_m4ri.test_stim_simple_vs_full_and_basis_tracking(), test_dist_m4ri.test_stim_xzzx_rotated_css(), and verify_qubit_metadata().

◆ clear_distance_cache()

None dist_m4ri.clear_distance_cache ( Optional[Union[str, Path]] cache_file = None,
bool clear_file = False )
Clears all cached distance calculations from memory, and optionally deletes the persistent JSON file.

Definition at line 230 of file dist_m4ri.py.

Referenced by test_dist_m4ri.test_add_noise_and_noiseless_circuit(), test_dist_m4ri.test_cache_newer_version_not_overwritten(), test_dist_m4ri.test_cache_versioning(), test_dist_m4ri.test_cached_outc_keeps_finc_codewords(), test_dist_m4ri.test_caching(), test_dist_m4ri.test_caching_cumulative_rw_steps(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cert_engine_delegation_and_cache_rules(), test_dist_m4ri.test_cli_outc_keeps_finc_codewords(), test_dist_m4ri.test_css_cache_migration(), test_dist_m4ri.test_css_outc_sector_files_and_finc(), test_dist_m4ri.test_css_user_dmax_and_sector_records(), test_dist_m4ri.test_debug_bits(), test_dist_m4ri.test_dem_cache_merged_bounds_and_circuit_key(), test_dist_m4ri.test_dem_distance_file(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_force_noise_and_p_noise(), test_dist_m4ri.test_dem_out_reduced(), test_dist_m4ri.test_dstop_stop_target(), test_dist_m4ri.test_model_lower_bound(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_persistent_json_cache(), test_dist_m4ri.test_quantum_cache_separation(), test_dist_m4ri.test_rw_ksub_kwin_min_hits(), test_dist_m4ri.test_sort_rows_option(), test_dist_m4ri.test_start_list_cache_records(), test_dist_m4ri.test_start_list_trust_after_calculation_css(), test_dist_m4ri.test_start_scan_option(), test_dist_m4ri.test_stim_out_dem_out_stim_out_dir(), test_dist_m4ri.test_stim_rounds_option(), test_dist_m4ri.test_stim_simple_vs_full_and_basis_tracking(), test_dist_m4ri.test_stim_xzzx_rotated_css(), test_dist_m4ri.test_win_hyb_option(), and test_dist_m4ri.test_zero_rank_g_and_css_sectors().

◆ compute_classical_distance()

Any dist_m4ri.compute_classical_distance ( Any H,
Optional[str] dist_m4ri = None,
int method = 3,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] num_steps = None,
int d_exp = 0,
int d_min = 0,
int d_max = 0,
int dmin = 0,
int dmax = 0,
int dstop = 0,
int wmin = 1,
int wmax = 0,
Optional[int] smax = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[int] cbeg = None,
Optional[int] cend = None,
int noscan = 0,
int dW = -1,
int maxC = 0,
Optional[str] finC = None,
Optional[str] outC = None,
bool do_cws = False,
bool return_info = False,
Optional[Union[str, Path]] cache_file = None,
str solver = "dist_m4ri",
str codedistance_method = "QDistEvol",
Optional[Dict[str, Any]] codedistance_params = None,
int seed = 0,
int debug = 0,
bool verbose = False,
bool nothrottle = False,
int chunk_size = 0,
int ksub = 0,
int kwin = 0,
int win_mode = 0,
int win_hyb = 0,
int pairs = -1,
Optional[int] min_hits = None,
int cov_cws = 100,
Optional[int] refresh = None,
bool trust_start = False,
bool start_scan = False,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
Optional[str] engine = None,
** kwargs )
Computes the minimum distance of a classical linear code given parity check matrix H.

Args:
    H: Parity check matrix (numpy array, scipy sparse matrix, or file path).
    dist_m4ri: Path to dist_m4ri executable (optional).
    method: Solver method (1=RW, 2=CC, 3=Bracketing default).
    threads: Maximum number of worker threads (default: all logical CPUs available; subject to throttling).
    timeout: Execution timeout in seconds (default: 60.0; 0: no limit).
    nothrottle: If True, the automatic thread throttling of the binary is disabled (default: False).
    chunk_size: Maximum RW batch claimed at once by a thread (default: 0: adaptive, 25-500 steps).
    num_steps: Maximum RW steps.
    min_hits: RW stops once the average number of hits per codeword reaches min_hits, both for the codewords of
        the minimum weight found and for a representative set of cov_cws lowest-weight codewords (see
        run_dist_m4ri()); passed if not None and >= 0 (None, the default: the binary's 5; 0: off, and then the
        repeated hits are not counted, unless codewords are collected with do_cws, outC, or maxC).
    cov_cws: Size of the representative set of lowest-weight codewords for min_hits (default: 100; 0: only the
        minimum weight).
    kwin / win_mode: A window of kwin columns in every RW step (alias: win; win_mode=0, the default: a Tanner
        graph ball, 1: an index window); kwin=0 (default): the automatic hybrid windows for n >= 500, see
        win_hyb and run_dist_m4ri(); kwin=-1: no windows (uniform random permutations in every step).
    refresh: RW steps between the basis refreshes of the experimental ksub RW (passed if not None; None,
        the default: the binary's 5000 with ksub > 0; 0: no refresh).
    d_exp: Expected distance estimate.
    d_min / dmin: Known lower bound on distance.
    d_max / dmax: Known upper bound on distance.
    dstop: Stop target for the lower bound (default: 0 = off): the search ends once CC has certified
        dmin >= dstop (method=2 or 3), unless a lighter codeword is found.  Unlike dmax, dstop is not an upper
        bound, and it is not reported as dmax: d_info = [dmin, w, rw_steps] with dmin >= dstop and the weight w
        of the lightest codeword found (0: none).  A cached lower bound dmin >= dstop answers the request without
        a calculation.
    wmin: Minimum distance of interest (terminate early if cw of weight <= wmin is found in RW or CC, default: 1).
    wmax: Maximum weight to search in CC.
    smax: Maximum syndrome weight for CC confinement profile.
    start: Expert option: list of CC start columns (int, comma-separated string "a,b,c", or
        sequence of ints; None or -1: all columns).  CC clusters are grown only from the listed
        columns, and they are not limited to larger column indices.  WARNING: the lower bound
        (and an exact result) is valid only if a code symmetry maps every minimum-weight codeword
        to one containing a listed column (e.g., one column per block of a quasi-cyclic code);
        the upper bound is always valid.  Results are cached under the separate key
        '<key>:start=a,b,c'; only dmax and codewords update the main cache record.
    trust_start: Expert option: accept the start-list results as valid, i.e., also merge dmin and
        rw_steps into the main cache record, and copy an existing exact start-list record to the
        main record even if no calculation is needed (default: False).
    start_scan: Expert option, with start (default: False): a cluster grown from a listed column c only
        uses the columns > c (see run_dist_m4ri()), e.g., start=[0, l] for the two blocks of a two-block
        group-algebra code over an abelian group; cached under the key suffix ':start=a,b,c:scan' (not for a
        DEM: ignored with a warning).
    cbeg / cend / noscan: Disabled in the Python interface: accepted for backward compatibility,
        but ignored with a warning to stderr (use the dist_m4ri binary directly).
    sort_rows: Row order of H in the binary (see run_dist_m4ri()): True sorts the rows by increasing weight
        (faster CC for very different row weights with cc_prune=0), False keeps their order, and None (default)
        leaves the binary's default (sorted for matrices; the detectors of a DEM are kept in time order).  The
        result and the cache key do not depend on it.
    cc_prune: The CC search of the binary (see run_dist_m4ri()): 0, the walk of the versions before 0.15.0; 1,
        the branch and bound (each codeword found once); 2, also the coverage and fractional cover bounds; None
        (default): the binary's default 1.  The result and the cache key do not depend on it.
    win_hyb: Window size of the automatic hybrid RW steps (kwin=0, n >= 500: a window on every other step; see
        run_dist_m4ri()); 0 (default): 256 columns for a DEM, 512 for matrices.  The cache key does not depend on
        it.
    pairs: The RW pairs of non-pivot columns (p=2, see run_dist_m4ri()): the number of random pivot rows of
        their buckets (0: off; -1, the default: auto).  The cache key does not depend on it.
    ksub: Experimental, should not be used (a warning is printed to stderr for ksub > 0 with method=1 or 3):
        subspace dimension sampled from ker(H) in RW (default: 0, full-matrix RW).
    dW: Extra weight window above dmin to collect codewords (only irreducible ones: not the union of a
        codeword and a disjoint nonzero vector with zero syndrome; the binary's default irred=1).
    maxC: Maximum number of codewords to collect.
    finC: Input file with initial codewords.
    outC: Output file to save codewords (NZLIST format).
    do_cws: Whether to return extracted codewords.
    return_info: If True, return (dist, d_info) or (dist, d_info, cws) where d_info is [dmin, dmax, num_rw].
    cache_file: Optional JSON file path for persistent distance caching.
    solver: "dist_m4ri" or "codedistance".
    codedistance_method: Method if using codedistance library.
    codedistance_params: Extra parameters for codedistance library.
    seed: Random seed.
    debug: Debug bitmap: the bits in BIN_DBG_MASK for the dist_m4ri binary, and the PY_DBG_* bits.
    verbose: Verbose reporting flag.

Returns:
    dist or (dist, cws) if do_cws is True (or (dist, d_info) / (dist, d_info, cws) if return_info=True)

Raises:
    TypeError: for an unknown keyword argument (e.g., a misspelled option).
    ValueError: for an invalid option value (e.g., start, or cc_prune other than 0, 1, or 2), for method=2 with
        timeout <= 0 but without wmax, dmax, or dstop, or for do_cws / outC with solver="codedistance".
    FileNotFoundError: if the dist_m4ri binary is not found (see find_dist_m4ri_binary()).
    RuntimeError: if the binary exits with an error (e.g., for a missing input file).
    ImportError: if solver="codedistance" but the codedistance package is not installed.

Definition at line 4241 of file dist_m4ri.py.

References _cached_code_distance(), _can_delegate_to_cert(), _cert_code_distance(), _cert_to_csr(), _check_kwargs(), _get_codedistance(), _get_qec_cert(), _matrix_cache_key(), _prepare_start_option(), _resolve_cert_engine(), _warn_codedistance_ignored(), _warn_experimental_ksub(), and format_bounds_list().

Referenced by _main(), test_dist_m4ri.test_cache_newer_version_not_overwritten(), test_dist_m4ri.test_caching(), test_dist_m4ri.test_caching_cumulative_rw_steps(), test_dist_m4ri.test_cc_zero_col_strip_and_even_weight_parity(), test_dist_m4ri.test_cert_engine_delegation_and_cache_rules(), test_dist_m4ri.test_classical_distance_file(), test_dist_m4ri.test_classical_distance_numpy(), test_dist_m4ri.test_debug_bits(), test_dist_m4ri.test_dmin_dmax_parameters(), test_dist_m4ri.test_ignored_inputs_warnings(), test_dist_m4ri.test_kwin_negative_turns_windows_off(), test_dist_m4ri.test_persistent_json_cache(), test_dist_m4ri.test_quantum_cache_separation(), test_dist_m4ri.test_unknown_keyword_arguments(), and test_dist_m4ri.test_zero_rank_g_and_css_sectors().

◆ compute_css_distance()

Tuple[Any, ...] dist_m4ri.compute_css_distance ( Any Hx,
Any Hz,
Optional[Any] Lx = None,
Optional[Any] Lz = None,
Optional[str] dist_m4ri = None,
int method = 3,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] num_steps = None,
int d_exp = 0,
int d_min = 0,
int d_max = 0,
int dmin = 0,
int dmax = 0,
int dstop = 0,
int wmin = 1,
int wmax = 0,
Optional[int] smax = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[int] cbeg = None,
Optional[int] cend = None,
int noscan = 0,
int dW = -1,
int maxC = 0,
Optional[str] finC = None,
Optional[str] outC = None,
bool do_cws = False,
Optional[Union[str, Path]] cache_file = None,
str solver = "dist_m4ri",
str codedistance_method = "QDistEvol",
Optional[Dict[str, Any]] codedistance_params = None,
int seed = 0,
int debug = 0,
bool verbose = False,
bool nothrottle = False,
int chunk_size = 0,
int ksub = 0,
int kwin = 0,
int win_mode = 0,
int win_hyb = 0,
int pairs = -1,
Optional[int] min_hits = None,
int cov_cws = 100,
Optional[int] refresh = None,
bool trust_start = False,
bool start_scan = False,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
bool ortho = True,
Optional[str] engine = None,
** kwargs )
Computes CSS quantum code distance d = min(d_X, d_Z).

Args:
    Hx: X-stabilizer parity check matrix (required, at least one row).
    Hz: Z-stabilizer parity check matrix (required, at least one row).
    Lx: Optional X-logical operator matrix (alternative to Hz as finG).
    Lz: Optional Z-logical operator matrix (alternative to Hx as finG).
    ortho: Expert option (default: True; since version 0.15.2): False skips the checks of the binary that the
        rows of Hx and Hz are orthogonal (Hx Hz^T = 0, in each sector with G; True: an error otherwise), e.g., to
        screen many codes which are orthogonal by construction; a warning is printed to stderr, and the result is
        valid only if Hx Hz^T = 0.  No effect with both Lx and Lz.  The cache key does not depend on it.
    dist_m4ri: Path to dist_m4ri executable (optional).
    method: Solver method (1=RW, 2=CC, 3=Bracketing default).
    threads: Maximum number of worker threads (default: all logical CPUs available; subject to throttling).
    timeout: Execution timeout in seconds (default: 60.0; 0: no limit).
    nothrottle: If True, the automatic thread throttling of the binary is disabled (default: False).
    chunk_size: Maximum RW batch claimed at once by a thread (default: 0: adaptive, 25-500 steps).
    num_steps: Maximum RW steps.
    min_hits: RW stops once the average number of hits per codeword reaches min_hits, both for the codewords of
        the minimum weight found and for a representative set of cov_cws lowest-weight codewords (see
        run_dist_m4ri()); passed if not None and >= 0 (None, the default: the binary's 5; 0: off, and then the
        repeated hits are not counted, unless codewords are collected with do_cws, outC, or maxC).
    cov_cws: Size of the representative set of lowest-weight codewords for min_hits (default: 100; 0: only the
        minimum weight).
    kwin / win_mode: A window of kwin columns in every RW step (alias: win; win_mode=0, the default: a Tanner
        graph ball, 1: an index window); kwin=0 (default): the automatic hybrid windows for n >= 500, see
        win_hyb and run_dist_m4ri(); kwin=-1: no windows (uniform random permutations in every step).
    refresh: RW steps between the basis refreshes of the experimental ksub RW (passed if not None; None,
        the default: the binary's 5000 with ksub > 0; 0: no refresh).
    d_exp: Expected distance estimate.
    d_min / dmin: Known lower bound on d = min(dX, dZ), inclusive (a lower bound of both sectors).
    d_max / dmax: Known upper bound on d = min(dX, dZ), inclusive.  As it is not an upper bound of either
        sector, it is passed to both sector runs as the stop target dstop (each sector is needed only up to this
        weight), and it is not stored in the sector cache records; the returned d is at most dmax.
    dstop: Stop target for the lower bound of d (default: 0 = off): both sector runs end once CC has certified
        dmin >= dstop, unless a lighter codeword is found (see compute_classical_distance()).
    wmin: Minimum distance of interest (terminate early if cw of weight <= wmin is found in RW or CC, default: 1).
    wmax: Maximum weight to search in CC.
    smax: Maximum syndrome weight for CC confinement profile.
    start: Expert option: list of CC start columns (int, comma-separated string "a,b,c", or
        sequence of ints; None or -1: all columns).  CC clusters are grown only from the listed
        columns, and they are not limited to larger column indices.  WARNING: the lower bound
        (and an exact result) is valid only if a code symmetry maps every minimum-weight codeword
        to one containing a listed column (e.g., one column per block of a quasi-cyclic code);
        the upper bound is always valid.  Results are cached under the separate key
        '<key>:start=a,b,c'; only dmax and codewords update the main cache record.
    trust_start: Expert option: accept the start-list results as valid, i.e., also merge dmin and
        rw_steps into the main cache record, and copy an existing exact start-list record to the
        main record even if no calculation is needed (default: False).
    start_scan: Expert option, with start (default: False): a cluster grown from a listed column c only
        uses the columns > c (see run_dist_m4ri()), e.g., start=[0, l] for the two blocks of a two-block
        group-algebra code over an abelian group; cached under the key suffix ':start=a,b,c:scan' (not for a
        DEM: ignored with a warning).
    cbeg / cend / noscan: Disabled in the Python interface: accepted for backward compatibility,
        but ignored with a warning to stderr (use the dist_m4ri binary directly).
    sort_rows: Row order of H in the binary (see run_dist_m4ri()): True sorts the rows by increasing weight
        (faster CC for very different row weights with cc_prune=0), False keeps their order, and None (default)
        leaves the binary's default (sorted for matrices; the detectors of a DEM are kept in time order).  The
        result and the cache key do not depend on it.
    cc_prune: The CC search of the binary (see run_dist_m4ri()): 0, the walk of the versions before 0.15.0; 1,
        the branch and bound (each codeword found once); 2, also the coverage and fractional cover bounds; None
        (default): the binary's default 1.  The result and the cache key do not depend on it.
    win_hyb: Window size of the automatic hybrid RW steps (kwin=0, n >= 500: a window on every other step; see
        run_dist_m4ri()); 0 (default): 256 columns for a DEM, 512 for matrices.  The cache key does not depend on
        it.
    pairs: The RW pairs of non-pivot columns (p=2, see run_dist_m4ri()): the number of random pivot rows of
        their buckets (0: off; -1, the default: auto).  The cache key does not depend on it.
    ksub: Experimental, should not be used (a warning is printed to stderr for ksub > 0 with method=1 or 3):
        subspace dimension sampled from ker(H) in RW (default: 0, full-matrix RW).
    dW: Extra weight window above dmin to collect codewords (only irreducible ones: not the union of a
        codeword and a disjoint nonzero vector with zero syndrome; the binary's default irred=1).
    maxC: Maximum number of codewords to collect.
    finC: Input file with initial codewords.
    outC: Output file to save codewords (NZLIST format).
    do_cws: Whether to return extracted X and Z codewords.
    cache_file: Optional JSON file path for persistent distance caching.  The two sectors are cached as the
        quantum codes (H=Hx, G=Hz) -> dZ and (H=Hz, G=Hx) -> dX (with L=Lx / L=Lz if given), i.e., they share
        the records of compute_quantum_distance(); CSS records written before version 0.12.0 are converted.
    solver: "dist_m4ri" or "codedistance".
    codedistance_method: Method if using codedistance library.
    codedistance_params: Extra parameters for codedistance library.
    seed: Random seed.
    debug: Debug bitmap: the bits in BIN_DBG_MASK for the dist_m4ri binary, and the PY_DBG_* bits.
    verbose: Verbose reporting flag.

Returns:
    tuple (dist, dX_info, dZ_info, cws_X, cws_Z) if do_cws
    else (dist, dX_info, dZ_info)

Raises:
    ValueError: if Hx or Hz is missing or empty (use compute_quantum_distance() for one sector, or
        compute_classical_distance() for a classical code), for an invalid option value (e.g., start, or
        cc_prune other than 0, 1, or 2), for method=2 with timeout <= 0 but without wmax, dmax, or dstop, or
        for do_cws / outC with solver="codedistance".
    TypeError: for an unknown keyword argument (e.g., a misspelled option).
    FileNotFoundError: if the dist_m4ri binary is not found (see find_dist_m4ri_binary()).
    RuntimeError: if the binary exits with an error (e.g., for a missing input file, or with ortho=True for
        rows of Hx and Hz which are not orthogonal).
    ImportError: if solver="codedistance" but the codedistance package is not installed.

Definition at line 4722 of file dist_m4ri.py.

References _cached_code_distance(), _can_delegate_to_cert(), _cert_code_distance(), _cert_to_csr(), _check_kwargs(), _css_combine(), _css_sector_codes(), _css_sector_finc(), _get_codedistance(), _get_qec_cert(), _matrix_cache_key(), _migrate_css_records(), _prepare_start_option(), _resolve_cert_engine(), _split_css_filename(), _warn_codedistance_ignored(), _warn_experimental_ksub(), _warn_ortho(), format_bounds_list(), and load_distance_cache().

Referenced by _main(), test_dist_m4ri.test_css_and_quantum_distance_inputs(), test_dist_m4ri.test_css_cache_migration(), test_dist_m4ri.test_css_distance_files(), test_dist_m4ri.test_css_distance_requires_both_matrices(), test_dist_m4ri.test_css_distance_sparse(), test_dist_m4ri.test_css_outc_sector_files_and_finc(), test_dist_m4ri.test_css_user_dmax_and_sector_records(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_persistent_json_cache(), test_dist_m4ri.test_start_list_trust_after_calculation_css(), test_dist_m4ri.test_unknown_keyword_arguments(), and test_dist_m4ri.test_zero_rank_g_and_css_sectors().

◆ compute_dem_distance()

Tuple[Any, ...] dist_m4ri.compute_dem_distance ( Optional[Any] dem = None,
Optional[Any] circuit = None,
Optional[str] dist_m4ri = None,
int method = 3,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] num_steps = None,
int d_exp = 0,
int d_min = 0,
int d_max = 0,
int dmin = 0,
int dmax = 0,
int dstop = 0,
int wmin = 1,
int wmax = 0,
Optional[int] smax = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[int] cbeg = None,
Optional[int] cend = None,
int noscan = 0,
int dW = -1,
int maxC = 0,
float pmin = 0.0,
bool merge = True,
bool expand = False,
Optional[Union[bool, int, str, Path]] drop = None,
Optional[Union[str, Path]] outD = None,
Optional[Union[bool, str, Path]] out_reduced = None,
Optional[str] finC = None,
Optional[str] outC = None,
bool do_cws = False,
Optional[Union[str, Path]] cache_file = None,
str solver = "dist_m4ri",
str codedistance_method = "UndetectableErrorStim",
Optional[Dict[str, Any]] codedistance_params = None,
int seed = 0,
int debug = 0,
bool verbose = False,
bool nothrottle = False,
int chunk_size = 0,
int ksub = 0,
int kwin = 0,
int win_mode = 0,
int win_hyb = 0,
int pairs = -1,
Optional[int] min_hits = None,
int cov_cws = 100,
Optional[int] refresh = None,
Optional[bool] simple = None,
Optional[bool] full = None,
Optional[str] basis = None,
Optional[int] rounds = None,
Optional[Union[str, Path]] out_dir = None,
Optional[Union[bool, str, Path]] out_dem = None,
Optional[Union[bool, str, Path]] out_stim = None,
float p_noise = 0.001,
bool force_noise = False,
bool trust_start = False,
bool start_scan = False,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
Optional[str] engine = None,
** kwargs )
Computes minimum graph/hypergraph distance of a Stim Detector Error Model (DEM).

Args:
    dem: stim.DetectorErrorModel object or path to .dem / .stim file.
    circuit: stim.Circuit object or path to .stim file (converted to DEM; if stim cannot write an error channel with
        disjoint cases, e.g., a PAULI_CHANNEL_1 without Y errors, as independent error mechanisms, with
        approximate_disjoint_errors=True, which only changes the probabilities of the error mechanisms).
    dist_m4ri: Path to dist_m4ri executable (optional).
    method: Solver method (1=RW, 2=CC, 3=Bracketing default).
    threads: Maximum number of worker threads (default: all logical CPUs available; subject to throttling).
    timeout: Execution timeout in seconds (default: 60.0; 0: no limit).
    nothrottle: If True, the automatic thread throttling of the binary is disabled (default: False).
    chunk_size: Maximum RW batch claimed at once by a thread (default: 0: adaptive, 25-500 steps).
    num_steps: Maximum RW steps.
    min_hits: RW stops once the average number of hits per codeword reaches min_hits, both for the codewords of
        the minimum weight found and for a representative set of cov_cws lowest-weight codewords (see
        run_dist_m4ri()); passed if not None and >= 0 (None, the default: the binary's 5; 0: off, and then the
        repeated hits are not counted, unless codewords are collected with do_cws, outC, or maxC).
    cov_cws: Size of the representative set of lowest-weight codewords for min_hits (default: 100; 0: only the
        minimum weight).
    kwin / win_mode: A window of kwin columns in every RW step (alias: win; win_mode=0, the default: a Tanner
        graph ball, 1: an index window); kwin=0 (default): the automatic hybrid windows for n >= 500, see
        win_hyb and run_dist_m4ri(); kwin=-1: no windows (uniform random permutations in every step).
    refresh: RW steps between the basis refreshes of the experimental ksub RW (passed if not None; None,
        the default: the binary's 5000 with ksub > 0; 0: no refresh).
    d_exp: Expected distance estimate.
    d_min / dmin: Known lower bound on distance, inclusive.
    d_max / dmax: Known upper bound on distance, inclusive.
    dstop: Stop target for the lower bound (see compute_classical_distance(); default: 0 = off).
    wmin: Minimum distance of interest (terminate early if cw of weight <= wmin is found in RW or CC, default: 1).
    wmax: Maximum weight to search in CC.
    smax: Maximum syndrome weight for CC confinement profile.
    start: Expert option: list of CC start columns (int, comma-separated string "a,b,c", or
        sequence of ints; None or -1: all columns).  CC clusters are grown only from the listed
        columns, and they are not limited to larger column indices.  WARNING: the lower bound
        (and an exact result) is valid only if a code symmetry maps every minimum-weight codeword
        to one containing a listed column (e.g., one column per block of a quasi-cyclic code);
        the upper bound is always valid.  Results are cached under the separate key
        '<key>:start=a,b,c'; only dmax and codewords update the main cache record.
    trust_start: Expert option: accept the start-list results as valid, i.e., also merge dmin and
        rw_steps into the main cache record, and copy an existing exact start-list record to the
        main record even if no calculation is needed (default: False).
    start_scan: Expert option, with start (default: False): a cluster grown from a listed column c only
        uses the columns > c (see run_dist_m4ri()), e.g., start=[0, l] for the two blocks of a two-block
        group-algebra code over an abelian group; cached under the key suffix ':start=a,b,c:scan' (not for a
        DEM: ignored with a warning).
    cbeg / cend / noscan: Disabled in the Python interface: accepted for backward compatibility,
        but ignored with a warning to stderr (use the dist_m4ri binary directly).
    sort_rows: Row order of H in the binary (see run_dist_m4ri()): True sorts the rows by increasing weight
        (faster CC for very different row weights with cc_prune=0), False keeps their order, and None (default)
        leaves the binary's default (sorted for matrices; the detectors of a DEM are kept in time order).  The
        result and the cache key do not depend on it.
    cc_prune: The CC search of the binary (see run_dist_m4ri()): 0, the walk of the versions before 0.15.0; 1,
        the branch and bound (each codeword found once); 2, also the coverage and fractional cover bounds; None
        (default): the binary's default 1.  The result and the cache key do not depend on it.
    win_hyb: Window size of the automatic hybrid RW steps (kwin=0, n >= 500: a window on every other step; see
        run_dist_m4ri()); 0 (default): 256 columns for a DEM, 512 for matrices.  The cache key does not depend on
        it.
    pairs: The RW pairs of non-pivot columns (p=2, see run_dist_m4ri()): the number of random pivot rows of
        their buckets (0: off; -1, the default: auto).  The cache key does not depend on it.
    ksub: Experimental, should not be used (a warning is printed to stderr for ksub > 0 with method=1 or 3):
        subspace dimension sampled from ker(H) in RW (default: 0, full-matrix RW).
    dW: Extra weight window above dmin to collect codewords (only irreducible ones: not the union of a
        codeword and a disjoint nonzero vector with zero syndrome; the binary's default irred=1).
    maxC: Maximum number of codewords to collect (with expand=True, also the maximum number of codewords of the
        expanded list returned and written to outC; a warning is printed to stderr if some are dropped).
    pmin: Probability cutoff for error mechanisms in DEM.
        Note: CC start columns (start) and the codewords (finC, outC, do_cws) index the error mechanisms in
        their order of appearance in the (flattened) DEM, after the pmin cutoff: with another pmin, the columns
        (and the codewords) change.
    merge: Merge the equal columns of the DEM (error mechanisms with the same detectors and observables) in the
        binary (default: True).  Exact: dropping two equal columns of a codeword gives a lighter one, so the
        distance does not change (and the cache key does not depend on merge).  Column indices (finC, outC,
        start, the returned codewords) are those of the DEM; the codewords found use the first one of each set
        of equal columns (merge=False: all columns are kept, e.g., to enumerate the codewords with each of them;
        or expand=True to expand the list found).
    expand: If True, the codewords returned and written to outC are expanded in Python: each codeword is listed
        once for every choice among equal columns (default: False; see _expand_equal_columns()).  The binary
        and the cache keep the merged list.  With dW <= 1, the expanded list is that of merge=False (with
        dW >= 2, merge=False also lists lighter codewords with two equal columns added).  The expanded list can
        be much longer (it grows quickly with the weight); with maxC > 0, it is cut at maxC codewords.
    drop: The detectors which the binary drops if this is verified to be exact, so that the distance (and every
        codeword found) is that of the DEM, found from the DEM without these detectors and the errors touching
        them (fewer detectors and errors: as fast as the DEM with only the primary-basis detectors of a CSS
        circuit).  None, True, 1, or "auto" (default): the binary searches for the largest such set in the DEM alone
        (drop=auto, see the README), e.g., the minority-basis detectors of a CSS circuit (with the usual noise).
        "css": for a Stim circuit classified as CSS, its minority-basis detectors (see strip_minority_detectors()),
        passed as a file (otherwise, e.g., for a DEM, drop=auto is used, with a warning).  False or 0: no detectors
        are dropped.  A file name: the file with the detectors to drop (0-based, k for Dk; see read_drop_file()),
        for any DEM.  With "css" or a file, if dropping the detectors is not exact, a note is printed to stderr and
        the full DEM is used.  The codewords found use only the errors touching no dropped detector.
    outD: File to which the binary writes the detectors dropped (0-based, see read_drop_file()); with a cached
        result, the binary is run only to find them (with dmin = dmax: no search).
    out_reduced: True or a prefix PREFIX: writes the DEM without the detectors dropped (see outD) to
        PREFIX_red.dem, and the maps to the original DEM (its detectors and errors) to PREFIX_red.json, see
        write_reduced_dem() (True: PREFIX = <basename>, in out_dir or the directory of the input file).
    finC: Input file with initial codewords.
    outC: Output file to save codewords (NZLIST format).
    do_cws: Whether to return extracted error mechanisms / codewords.
    cache_file: Optional JSON file path for persistent distance caching.
    solver: "dist_m4ri" or "codedistance".
    codedistance_method: Method if using codedistance library.
    codedistance_params: Extra parameters for codedistance library.
    seed: Random seed.
    debug: Debug bitmap: the bits in BIN_DBG_MASK for the dist_m4ri binary, and the PY_DBG_* bits.
    verbose: Verbose reporting flag.
    simple / full: Disabled since version 0.13.0 (accepted for backward compatibility, but ignored with a warning
        to stderr): the DEM of a Stim circuit always has all detectors, and the minority-basis detectors of a CSS
        circuit (which simple=True stripped) are dropped by the binary if this is exact (see drop).  The distance
        of the simplified circuit (a lower bound) can still be found by passing the circuit stripped with
        strip_minority_detectors().
    basis: Optional primary memory basis override ('X' or 'Z') for .stim circuits, only used with drop="css" (the
        other basis is that of the minority-basis detectors) and for the verbose report of the classification.
    rounds: Optional number of REPEAT rounds for .stim circuits (warns if no REPEAT block).
    out_dir: Optional output directory for saved DEM and/or Stim circuit files.
    out_dem: Optional bool or filename to save the constructed DEM (True = auto-named <basename>_full.dem).  The
        codewords (outC, do_cws) index its error lines (in the order of the flattened DEM): save the DEM in the
        same run, since a DEM generated again from the circuit may differ (e.g., with another stim version); with
        outC but without out_dem, a warning is printed to stderr for a Stim circuit.
    out_stim: Optional bool or filename to save the processed (noisy, rounds-adjusted) Stim circuit
        (True = auto-named <basename>_full.stim).
    p_noise: Strength of the uniform circuit-level noise added to a noiseless Stim circuit (see add_noise();
        default: 0.001; 0: no noise is added, and a noiseless circuit gives no distance, with a note).  The
        distance does not depend on it (unless pmin > 0), only on which faults are possible.  A circuit with noise
        (a noise channel or a noisy measurement such as M(0.001), see has_noise()) is used as is, unless
        force_noise=True.
    force_noise: If True, the noise of a Stim circuit is replaced by the uniform noise of strength p_noise (see
        strip_noise(); with p_noise=0, all noise is removed, e.g., to save the noiseless circuit with out_stim),
        e.g., to compare circuits with the same noise model (default: False).

Returns:
    tuple (dist, d_info, cws) if do_cws else (dist, d_info)

Raises:
    TypeError: for an unknown keyword argument (e.g., a misspelled option).
    ValueError: if neither dem nor circuit is given, for rounds without a Stim circuit (or rounds < 0), for
        p_noise outside [0, 0.5], for an invalid drop (e.g., a file which does not exist) or another invalid
        option value (e.g., start, or cc_prune other than 0, 1, or 2), for method=2 with timeout <= 0 but
        without wmax, dmax, or dstop, or for do_cws / outC with solver="codedistance".
    FileNotFoundError: if the dist_m4ri binary is not found (see find_dist_m4ri_binary()).
    RuntimeError: if the binary exits with an error.
    ImportError: if stim is needed (e.g., for a Stim circuit) or solver="codedistance", but the package is not
        installed.

Definition at line 5253 of file dist_m4ri.py.

References _cached_code_distance(), _can_delegate_to_cert(), _cert_code_distance(), _check_kwargs(), _dem_cache_key(), _dem_from_input(), _drop_mode(), _expand_equal_columns(), _get_codedistance(), _get_qec_cert(), _prepare_start_option(), _reduced_out_prefix(), _remove_temp_files(), _resolve_cert_engine(), _warn_codedistance_ignored(), _warn_disabled_simple_full(), _warn_experimental_ksub(), _warn_ignored(), _write_dem_file(), create_unique_file(), format_bounds_list(), read_drop_file(), run_dist_m4ri(), and write_reduced_dem().

Referenced by _main(), test_dist_m4ri.test_add_noise_and_noiseless_circuit(), test_dist_m4ri.test_cc_zero_col_strip_and_even_weight_parity(), test_dist_m4ri.test_dem_cache_merged_bounds_and_circuit_key(), test_dist_m4ri.test_dem_circuit_outc_without_out_dem_warning(), test_dist_m4ri.test_dem_distance_file(), test_dist_m4ri.test_dem_distance_stim(), test_dist_m4ri.test_dem_drop_minority_detectors(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_force_noise_and_p_noise(), test_dist_m4ri.test_dem_merge_equal_columns(), test_dist_m4ri.test_dem_out_reduced(), test_dist_m4ri.test_dmin_dmax_parameters(), test_dist_m4ri.test_model_lower_bound(), test_dist_m4ri.test_persistent_json_cache(), test_dist_m4ri.test_rw_ksub_kwin_min_hits(), test_dist_m4ri.test_start_scan_option(), test_dist_m4ri.test_stim_pauli_channel_circuit(), test_dist_m4ri.test_stim_rounds_option(), and test_dist_m4ri.test_stim_xzzx_rotated_css().

◆ compute_model_lower_bound()

Any dist_m4ri.compute_model_lower_bound ( Any circuit = None,
Optional[str] dist_m4ri = None,
int method = 3,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] num_steps = None,
int dstop = 0,
int wmax = 0,
bool minority = False,
float pmin = 0.0,
Optional[int] rounds = None,
float p_noise = 0.001,
bool force_noise = False,
Optional[Union[str, Path]] out_model = None,
Optional[Union[str, Path]] cache_file = None,
int seed = 0,
int debug = 0,
bool verbose = False,
bool nothrottle = False,
int pairs = -1,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
bool return_info = False,
Optional[Any] dem = None,
** kwargs )
Certified lower bound on the circuit-level distance of a Stim memory circuit from its code-sized model.

The model is a row reduction of the DEM (H, L) of the circuit (processed as in compute_dem_distance(), with the
options rounds, p_noise, force_noise, and pmin): two detectors are linked if they share a measurement record other
than a final data measurement, and each group of linked detectors gives one row, the sum of the rows of its
detectors (see _model_detector_groups()).  In a memory circuit, the groups are the chains of the detectors of the
checks over the rounds: the chain of a check h of the measured basis telescopes to the parity of the final data
measurements on its support, so that the column of an error mechanism is the syndrome of its net data error (a
data error or a hook error), and the chains of the minority-basis checks (with minority=True) add the net change
of their values between their first and last measurements.  Equal columns are merged, and the errors with no effect
on the rows nor on the observables (e.g., ancilla measurement errors) are dropped; the model has a few columns per
data qubit.  Since every row is a sum of detector rows, every codeword x of the DEM (Hx = 0, Lx != 0) gives a model
codeword of weight at most |x|: the distance of the model, as certified by CC (its dmin), is a lower bound on the
distance of the DEM.  It ignores the timing within the rounds, so it is not tight in general (e.g., 5 for the
bb_72 circuit of distance 6).  Any circuit gives a valid bound, but a useful one needs this structure; if an error
flips an observable but no row, the bound is 1 (with a note to stderr).

The binary runs on the model with the rows of the measured-basis chains first, and then (with minority=True) on
the model with all rows, starting from that bound (the extra rows can only raise it): RW first, which ends as soon
as it finds a model codeword of that weight (then the bound is not raised), and only otherwise with `method` (CC
from dmin).  The minority-basis rows are off by default: with depolarizing-type noise, every net data error which
flips the measured-basis observable also occurs without a component of the other basis, so that a lightest model
codeword has a version which the minority-basis rows do not detect (they never raised the bound of the benchmark
circuits or of the surface-code circuits of stim, and cost up to 9 s for the mitten_270 circuits); they may raise
it for other noise models (e.g., biased noise).  The certified bound is stored as dmin in the cache record of the
DEM (the same key as compute_dem_distance(); "dmin_model": the bound), so that a later compute_dem_distance()
starts CC from it; the distances of the models are cached under their own keys.

Args:
    circuit: Stim memory circuit (stim.Circuit or .stim file).
    dist_m4ri: Path to dist_m4ri executable (optional).
    method: Solver method for the model (1=RW, 2=CC, 3=Bracketing default); only CC certifies a bound.
    threads / timeout / num_steps / seed / nothrottle / pairs: As for compute_dem_distance(), for each run of the
        binary (at most three).
    sort_rows / cc_prune: The row order and the CC search of the binary (see run_dist_m4ri(); None, the default:
        the binary's defaults, i.e., the rows of the model sorted by weight, and the branch and bound), for each
        run.  The bound and the cache keys do not depend on them.
    dstop: Stop target (see compute_dem_distance()): the runs end once CC has certified dmin >= dstop.
    wmax: Maximum weight of the CC rounds on the model (0: until the bounds meet or the timeout).
    minority: If True, the groups without a final data measurement (e.g., the chains of the minority-basis
        checks of a CSS circuit) are rows of the model as well (default: False; CLI: --model-minority).
    pmin: Probability cutoff for the error mechanisms of the DEM.
    rounds / p_noise / force_noise: The processing of the circuit, as in compute_dem_distance().
    out_model: If given, the model (with all rows used) is written to PREFIX_HR.mtx and PREFIX_LR.mtx.
    cache_file: Optional JSON file path for persistent distance caching.
    debug / verbose: As for compute_dem_distance().
    return_info: If True, return (bound, info).

Returns:
    The certified lower bound, or (bound, info) with return_info=True, where info has "d_info" (the bounds
    [dmin, dmax, rw_steps] of the circuit's DEM from the cache record, with dmin including the bound; [bound, 0, 0]
    without the cache), "model_d_info" and "measured_d_info" (the bounds of the model and of its measured-basis
    part, [] if not run), the sizes "rows", "cols", "rows_measured", "cols_measured", "groups", "groups_final",
    "detectors", "final_data", "dem_cols", "trivial" (the error mechanisms which flip an observable but no row),
    the model "H", "L", and "col_map" (the model column of each error mechanism of the DEM, -1 if dropped), and
    "files" (the files written with out_model).

Raises:
    TypeError: for an unknown keyword argument (e.g., a misspelled option).
    ValueError: if the input is not a Stim circuit.

Definition at line 5907 of file dist_m4ri.py.

References _cached_code_distance(), _check_kwargs(), _dem_cache_key(), _dem_detector_groups(), _dem_error_columns(), _dem_from_input(), _model_detector_groups(), _model_matrices(), _sector_record(), format_bounds_list(), load_distance_cache(), and save_distance_cache().

Referenced by _main(), test_dist_m4ri.test_model_detector_groups_end_of_circuit_and_pure_dem(), and test_dist_m4ri.test_model_lower_bound().

◆ compute_quantum_distance()

Any dist_m4ri.compute_quantum_distance ( Any H,
Optional[Any] G = None,
Optional[Any] L = None,
Optional[str] dist_m4ri = None,
int method = 3,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] num_steps = None,
int d_exp = 0,
int d_min = 0,
int d_max = 0,
int dmin = 0,
int dmax = 0,
int dstop = 0,
int wmin = 1,
int wmax = 0,
Optional[int] smax = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[int] cbeg = None,
Optional[int] cend = None,
int noscan = 0,
int dW = -1,
int maxC = 0,
Optional[str] finC = None,
Optional[str] outC = None,
bool do_cws = False,
bool return_info = False,
Optional[Union[str, Path]] cache_file = None,
str solver = "dist_m4ri",
str codedistance_method = "QDistEvol",
Optional[Dict[str, Any]] codedistance_params = None,
int seed = 0,
int debug = 0,
bool verbose = False,
bool nothrottle = False,
int chunk_size = 0,
int ksub = 0,
int kwin = 0,
int win_mode = 0,
int win_hyb = 0,
int pairs = -1,
Optional[int] min_hits = None,
int cov_cws = 100,
Optional[int] refresh = None,
bool trust_start = False,
bool start_scan = False,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
bool ortho = True,
Optional[str] engine = None,
** kwargs )
Computes the minimum distance of a single-sided quantum code given parity check matrix H
and degeneracy generator G (or logical operator matrix L).

Args:
    H: Parity check matrix (numpy array, scipy sparse matrix, or file path).
    G: Degeneracy generator matrix (numpy array, scipy sparse matrix, or file path); the binary constructs the
        logical operators from H and G.  Either G or L is required, not both (ValueError).
    L: Logical operator matrix (numpy array, scipy sparse matrix, or file path), instead of G.
    ortho: Expert option (default: True; since version 0.15.2): False skips the check of the binary that the rows
        of H and G are orthogonal (H G^T = 0; True: an error otherwise), e.g., to screen many codes which are
        orthogonal by construction; a warning is printed to stderr, and the result is valid only if H G^T = 0.  No
        effect without G.  The cache key does not depend on it.
    dist_m4ri: Path to dist_m4ri executable (optional).
    method: Solver method (1=RW, 2=CC, 3=Bracketing default).
    threads: Maximum number of worker threads (default: all logical CPUs available; subject to throttling).
    timeout: Execution timeout in seconds (default: 60.0; 0: no limit).
    nothrottle: If True, the automatic thread throttling of the binary is disabled (default: False).
    chunk_size: Maximum RW batch claimed at once by a thread (default: 0: adaptive, 25-500 steps).
    num_steps: Maximum RW steps.
    min_hits: RW stops once the average number of hits per codeword reaches min_hits, both for the codewords of
        the minimum weight found and for a representative set of cov_cws lowest-weight codewords (see
        run_dist_m4ri()); passed if not None and >= 0 (None, the default: the binary's 5; 0: off, and then the
        repeated hits are not counted, unless codewords are collected with do_cws, outC, or maxC).
    cov_cws: Size of the representative set of lowest-weight codewords for min_hits (default: 100; 0: only the
        minimum weight).
    kwin / win_mode: A window of kwin columns in every RW step (alias: win; win_mode=0, the default: a Tanner
        graph ball, 1: an index window); kwin=0 (default): the automatic hybrid windows for n >= 500, see
        win_hyb and run_dist_m4ri(); kwin=-1: no windows (uniform random permutations in every step).
    refresh: RW steps between the basis refreshes of the experimental ksub RW (passed if not None; None,
        the default: the binary's 5000 with ksub > 0; 0: no refresh).
    d_exp: Expected distance estimate.
    d_min / dmin: Known lower bound on distance.
    d_max / dmax: Known upper bound on distance.
    dstop: Stop target for the lower bound (default: 0 = off): the search ends once CC has certified
        dmin >= dstop (method=2 or 3), unless a lighter codeword is found.  Unlike dmax, dstop is not an upper
        bound, and it is not reported as dmax: d_info = [dmin, w, rw_steps] with dmin >= dstop and the weight w
        of the lightest codeword found (0: none).  A cached lower bound dmin >= dstop answers the request without
        a calculation.
    wmin: Minimum distance of interest (terminate early if cw of weight <= wmin is found in RW or CC, default: 1).
    wmax: Maximum weight to search in CC.
    smax: Maximum syndrome weight for CC confinement profile.
    start: Expert option: list of CC start columns (int, comma-separated string "a,b,c", or
        sequence of ints; None or -1: all columns).  CC clusters are grown only from the listed
        columns, and they are not limited to larger column indices.  WARNING: the lower bound
        (and an exact result) is valid only if a code symmetry maps every minimum-weight codeword
        to one containing a listed column (e.g., one column per block of a quasi-cyclic code);
        the upper bound is always valid.  Results are cached under the separate key
        '<key>:start=a,b,c'; only dmax and codewords update the main cache record.
    trust_start: Expert option: accept the start-list results as valid, i.e., also merge dmin and
        rw_steps into the main cache record, and copy an existing exact start-list record to the
        main record even if no calculation is needed (default: False).
    start_scan: Expert option, with start (default: False): a cluster grown from a listed column c only
        uses the columns > c (see run_dist_m4ri()), e.g., start=[0, l] for the two blocks of a two-block
        group-algebra code over an abelian group; cached under the key suffix ':start=a,b,c:scan' (not for a
        DEM: ignored with a warning).
    cbeg / cend / noscan: Disabled in the Python interface: accepted for backward compatibility,
        but ignored with a warning to stderr (use the dist_m4ri binary directly).
    sort_rows: Row order of H in the binary (see run_dist_m4ri()): True sorts the rows by increasing weight
        (faster CC for very different row weights with cc_prune=0), False keeps their order, and None (default)
        leaves the binary's default (sorted for matrices; the detectors of a DEM are kept in time order).  The
        result and the cache key do not depend on it.
    cc_prune: The CC search of the binary (see run_dist_m4ri()): 0, the walk of the versions before 0.15.0; 1,
        the branch and bound (each codeword found once); 2, also the coverage and fractional cover bounds; None
        (default): the binary's default 1.  The result and the cache key do not depend on it.
    win_hyb: Window size of the automatic hybrid RW steps (kwin=0, n >= 500: a window on every other step; see
        run_dist_m4ri()); 0 (default): 256 columns for a DEM, 512 for matrices.  The cache key does not depend on
        it.
    pairs: The RW pairs of non-pivot columns (p=2, see run_dist_m4ri()): the number of random pivot rows of
        their buckets (0: off; -1, the default: auto).  The cache key does not depend on it.
    ksub: Experimental, should not be used (a warning is printed to stderr for ksub > 0 with method=1 or 3):
        subspace dimension sampled from ker(H) in RW (default: 0, full-matrix RW).
    dW: Extra weight window above dmin to collect codewords (only irreducible ones: not the union of a
        codeword and a disjoint nonzero vector with zero syndrome; the binary's default irred=1).
    maxC: Maximum number of codewords to collect.
    finC: Input file with initial codewords.
    outC: Output file to save codewords (NZLIST format).
    do_cws: Whether to return extracted codewords.
    return_info: If True, return (dist, d_info) or (dist, d_info, cws) where d_info is [dmin, dmax, num_rw].
    cache_file: Optional JSON file path for persistent distance caching.
    solver: "dist_m4ri" or "codedistance".
    codedistance_method: Method if using codedistance library.
    codedistance_params: Extra parameters for codedistance library.
    seed: Random seed.
    debug: Debug bitmap: the bits in BIN_DBG_MASK for the dist_m4ri binary, and the PY_DBG_* bits.
    verbose: Verbose reporting flag.

Returns:
    dist or (dist, cws) if do_cws is True (or (dist, d_info) / (dist, d_info, cws) if return_info=True)

Raises:
    TypeError: for an unknown keyword argument (e.g., a misspelled option).
    ValueError: if neither or both of G and L are given (or G is not given, with solver="codedistance"), for an
        invalid option value (e.g., start, or cc_prune other than 0, 1, or 2), for method=2 with timeout <= 0
        but without wmax, dmax, or dstop, or for do_cws / outC with solver="codedistance".
    FileNotFoundError: if the dist_m4ri binary is not found (see find_dist_m4ri_binary()).
    RuntimeError: if the binary exits with an error (e.g., for a missing input file, or with ortho=True for rows
        of H and G which are not orthogonal).
    ImportError: if solver="codedistance" but the codedistance package is not installed.

Definition at line 4449 of file dist_m4ri.py.

References _cached_code_distance(), _can_delegate_to_cert(), _cert_code_distance(), _cert_to_csr(), _check_kwargs(), _get_codedistance(), _get_qec_cert(), _matrix_cache_key(), _prepare_start_option(), _resolve_cert_engine(), _warn_codedistance_ignored(), _warn_experimental_ksub(), _warn_ortho(), and format_bounds_list().

Referenced by _main(), test_dist_m4ri.test_cached_outc_keeps_finc_codewords(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cc_zero_col_strip_and_even_weight_parity(), test_dist_m4ri.test_cert_engine_delegation_and_cache_rules(), test_dist_m4ri.test_css_and_quantum_distance_inputs(), test_dist_m4ri.test_css_user_dmax_and_sector_records(), test_dist_m4ri.test_dstop_stop_target(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_quantum_cache_separation(), test_dist_m4ri.test_quantum_distance_single_sided(), test_dist_m4ri.test_sort_rows_option(), test_dist_m4ri.test_start_list_cache_records(), test_dist_m4ri.test_start_scan_option(), test_dist_m4ri.test_unknown_keyword_arguments(), test_dist_m4ri.test_win_hyb_option(), and test_dist_m4ri.test_zero_rank_g_and_css_sectors().

◆ count_circuit_rounds()

int dist_m4ri.count_circuit_rounds ( Any circuit)
Returns total repeat count of all repeat blocks in circuit, or 1 if unrolled.

Definition at line 2400 of file dist_m4ri.py.

References _get_stim().

Referenced by _dem_from_input().

◆ create_unique_file()

str dist_m4ri.create_unique_file ( Union[str, Path] directory = "tmp",
str extension = ".tmp" )
Creates a unique temporary file path and ensures the parent directory exists.

Definition at line 818 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _matrix_to_file(), and compute_dem_distance().

◆ detect_basis()

str dist_m4ri.detect_basis ( Any circuit,
Optional[Union[str, Path]] filepath = None,
Optional[str] basis_arg = None )
Determines the primary memory basis ('X' or 'Z') of a Stim circuit.

Definition at line 2420 of file dist_m4ri.py.

References _get_stim().

Referenced by classify_qubits_thorough().

◆ disable_distance_cache()

◆ enable_distance_cache()

None dist_m4ri.enable_distance_cache ( )
Enables distance caching.

Definition at line 245 of file dist_m4ri.py.

Referenced by test_dist_m4ri.test_cache_newer_version_not_overwritten(), test_dist_m4ri.test_cached_outc_keeps_finc_codewords(), test_dist_m4ri.test_caching(), test_dist_m4ri.test_caching_cumulative_rw_steps(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cc_zero_col_strip_and_even_weight_parity(), test_dist_m4ri.test_cert_engine_delegation_and_cache_rules(), test_dist_m4ri.test_cli_conflict_warnings(), test_dist_m4ri.test_cli_dstop(), test_dist_m4ri.test_cli_start_trust_start_and_disabled_options(), test_dist_m4ri.test_css_cache_migration(), test_dist_m4ri.test_css_distance_requires_both_matrices(), test_dist_m4ri.test_css_outc_sector_files_and_finc(), test_dist_m4ri.test_css_user_dmax_and_sector_records(), test_dist_m4ri.test_debug_bits(), test_dist_m4ri.test_dem_cache_merged_bounds_and_circuit_key(), test_dist_m4ri.test_dem_circuit_outc_without_out_dem_warning(), test_dist_m4ri.test_dem_drop_minority_detectors(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_force_noise_and_p_noise(), test_dist_m4ri.test_dem_merge_equal_columns(), test_dist_m4ri.test_dem_out_reduced(), test_dist_m4ri.test_dstop_stop_target(), test_dist_m4ri.test_ignored_inputs_warnings(), test_dist_m4ri.test_kwin_negative_turns_windows_off(), test_dist_m4ri.test_model_detector_groups_end_of_circuit_and_pure_dem(), test_dist_m4ri.test_model_lower_bound(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_quantum_cache_separation(), test_dist_m4ri.test_rw_ksub_kwin_min_hits(), test_dist_m4ri.test_sort_rows_option(), test_dist_m4ri.test_start_list_cache_records(), test_dist_m4ri.test_start_list_trust_after_calculation_css(), test_dist_m4ri.test_start_scan_option(), test_dist_m4ri.test_stim_out_dem_out_stim_out_dir(), test_dist_m4ri.test_stim_pauli_channel_circuit(), test_dist_m4ri.test_stim_rounds_option(), test_dist_m4ri.test_stim_simple_vs_full_and_basis_tracking(), test_dist_m4ri.test_win_hyb_option(), and test_dist_m4ri.test_zero_rank_g_and_css_sectors().

◆ explain_bounds()

str dist_m4ri.explain_bounds ( List[int] bounds,
Optional[int] method = None,
str label = "",
Optional[Dict[str, Any]] stats = None,
int dstop = 0 )
Returns a human-readable explanation of [dmin, dmax, num_rw] following README.md.

Args:
    bounds: [dmin, dmax, rw_steps] list.
    method: Optional solver method (1=RW, 2=CC, 3=Bracketing).
    label: Optional prefix/label (e.g. "dX", "dZ", "").
    stats: Optional dictionary of codeword and hit statistics parsed from dist_m4ri.
    dstop: Stop target of the search (0: none); once dmin >= dstop, the upper bound is not needed, and the
        estimates of the probability that RW missed a lighter codeword are skipped.

Returns:
    Multi-line formatted explanation string.

Definition at line 537 of file dist_m4ri.py.

References rw_infoset_estimate(), and rw_infoset_find_prob().

Referenced by _main(), test_dist_m4ri.test_dstop_stop_target(), test_dist_m4ri.test_explain_bounds(), test_dist_m4ri.test_explain_bounds_model_check_needs_hit_counts(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_rw_infoset_estimate(), and test_dist_m4ri.test_win_hyb_option().

◆ find_dist_m4ri_binary()

str dist_m4ri.find_dist_m4ri_binary ( Optional[str] custom_path = None)
Finds the dist_m4ri executable.

Definition at line 887 of file dist_m4ri.py.

Referenced by _binary_version(), run_dist_m4ri(), and test_dist_m4ri.test_find_binary().

◆ format_bounds_list()

List[int] dist_m4ri.format_bounds_list ( int dmin,
int dmax,
int num_rw )
Returns [dmin, dmax, num_rw] according to:
- [d, d, 0] if known exactly
- [dmin, 0, 0] if there is no upper bound (dmax == 0)
- [0, dmax, num_rw] if there is no lower bound (dmin <= 1)
- [dmin, dmax, num_rw] otherwise

Definition at line 263 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _cert_code_distance(), _merge_start_into_plain(), _sector_record(), compute_classical_distance(), compute_css_distance(), compute_dem_distance(), compute_model_lower_bound(), compute_quantum_distance(), get_cached_distance(), and test_dist_m4ri.test_format_bounds_list_and_str().

◆ format_bounds_str()

str dist_m4ri.format_bounds_str ( List[int] bounds)
Formats a bounds list [dmin, dmax, num_rw] as a string, stating '(exact)' if bounds coincide.

Definition at line 284 of file dist_m4ri.py.

Referenced by _main(), and test_dist_m4ri.test_format_bounds_list_and_str().

◆ get_cached_distance()

Optional[Dict[str, Any]] dist_m4ri.get_cached_distance ( Optional[Any] H = None,
Optional[Any] G = None,
Optional[Any] L = None,
Optional[Any] Hx = None,
Optional[Any] Hz = None,
Optional[Any] Lx = None,
Optional[Any] Lz = None,
Optional[Any] dem = None,
Optional[Any] circuit = None,
float pmin = 0.0,
Optional[Union[str, Path]] cache_file = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[bool] simple = None,
Optional[bool] full = None,
Optional[str] basis = None,
Optional[int] rounds = None,
float p_noise = 0.001,
bool force_noise = False,
bool start_scan = False )
Retrieves the cached distance entry (including bounds and cumulative rw_steps)
for a given code matrix, CSS code, or DEM.

If the expert CC start-column list `start` is given (see compute_classical_distance), the
separate start-list record (cache key suffix ':start=a,b,c', or ':start=a,b,c:scan' with start_scan=True) is
returned instead of the main record.

For a CSS code (Hx and Hz, optionally Lx / Lz), the entry is assembled from the records of its two sectors,
the quantum codes (H=Hx, G=Hz) -> dZ and (H=Hz, G=Hx) -> dX (shared with compute_quantum_distance()): the fields
dmin_X, dmax_X, rw_steps_X, dX, cws_X (the same for Z), and dist, dmin, dmax, rw_steps of d = min(dX, dZ).

For a Stim circuit (circuit, or dem with a .stim file), the cache key is that of the DEM processed as in
compute_dem_distance(), with the same options rounds, p_noise, and force_noise (simple and full are disabled since
version 0.13.0: ignored with a warning to stderr; basis does not change the DEM).

Returns:
    dict with keys {"dist", "dmin", "dmax", "rw_steps", ...} or None if not cached.

Definition at line 697 of file dist_m4ri.py.

References _css_combine(), _css_sector_codes(), _dem_cache_key(), _dem_from_input(), _matrix_cache_key(), _migrate_css_records(), _normalize_start_list(), _scan_start_list(), _start_key_suffix(), _warn_disabled_simple_full(), format_bounds_list(), and load_distance_cache().

Referenced by test_dist_m4ri.test_caching_cumulative_rw_steps(), test_dist_m4ri.test_cert_engine_delegation_and_cache_rules(), test_dist_m4ri.test_css_cache_migration(), test_dist_m4ri.test_css_user_dmax_and_sector_records(), test_dist_m4ri.test_dem_cache_merged_bounds_and_circuit_key(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_force_noise_and_p_noise(), test_dist_m4ri.test_model_lower_bound(), test_dist_m4ri.test_persistent_json_cache(), test_dist_m4ri.test_start_list_cache_records(), test_dist_m4ri.test_start_list_trust_after_calculation_css(), and test_dist_m4ri.test_start_scan_option().

◆ get_distance_cache()

Dict[str, Any] dist_m4ri.get_distance_cache ( )
Returns the global distance cache dictionary.

Definition at line 257 of file dist_m4ri.py.

Referenced by test_dist_m4ri.test_quantum_cache_separation().

◆ get_sparse_array_state()

str dist_m4ri.get_sparse_array_state ( A)
Returns a deterministic string representation for JSON-compatible cache keys.

Definition at line 789 of file dist_m4ri.py.

Referenced by _dem_cache_key(), and _matrix_cache_key().

◆ has_noise()

bool dist_m4ri.has_noise ( Any circuit)
Checks if a Stim circuit has noise: a noise channel (e.g., DEPOLARIZE1, X_ERROR, PAULI_CHANNEL_2, E, or
HERALDED_ERASE), or a measurement with a flip probability (e.g., M(0.001) or MPP(0.01)), i.e., if strip_noise()
changes it.

Definition at line 2161 of file dist_m4ri.py.

References _get_stim().

Referenced by _dem_from_input(), test_dist_m4ri.test_add_noise_and_noiseless_circuit(), test_dist_m4ri.test_add_noise_gate_classes_and_strip_noise(), test_dist_m4ri.test_stim_out_dem_out_stim_out_dir(), and test_dist_m4ri.test_stim_pauli_channel_circuit().

◆ has_repeat_block()

bool dist_m4ri.has_repeat_block ( Any circuit)
Checks if a Stim circuit contains at least one REPEAT block.

Definition at line 2325 of file dist_m4ri.py.

References _get_stim().

Referenced by _dem_from_input().

◆ load_distance_cache()

Dict[str, Any] dist_m4ri.load_distance_cache ( Optional[Union[str, Path]] filepath = None)
Loads distance cache from a JSON file into memory.
Inspects cache version silently; a cache file written by a newer version is ignored with a warning, and it is
never overwritten by save_distance_cache().

Definition at line 169 of file dist_m4ri.py.

References _parse_version().

Referenced by _cached_code_distance(), _cert_code_distance(), compute_css_distance(), compute_model_lower_bound(), get_cached_distance(), set_distance_cache_file(), test_dist_m4ri.test_cache_newer_version_not_overwritten(), and test_dist_m4ri.test_cache_versioning().

◆ main()

int dist_m4ri.main ( Optional[List[str]] argv = None)
The CLI (see print_cli_help()); with --silent, set_silent() is on during the run, and restored at its end.

Definition at line 7443 of file dist_m4ri.py.

References _main(), and set_silent().

Referenced by _main(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cli_binary_compatibility_silent(), test_dist_m4ri.test_cli_conflict_warnings(), test_dist_m4ri.test_cli_css_dx_dz_bounds(), test_dist_m4ri.test_cli_dstop(), test_dist_m4ri.test_cli_help(), test_dist_m4ri.test_cli_identical_finc_outc_nonexistent(), test_dist_m4ri.test_cli_morehelp(), test_dist_m4ri.test_cli_morehelp_topic(), test_dist_m4ri.test_cli_no_args_error(), test_dist_m4ri.test_cli_outc_keeps_finc_codewords(), test_dist_m4ri.test_cli_start_trust_start_and_disabled_options(), test_dist_m4ri.test_cli_verbose_mode(), test_dist_m4ri.test_cli_version(), test_dist_m4ri.test_css_distance_requires_both_matrices(), test_dist_m4ri.test_dem_drop_minority_detectors(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_force_noise_and_p_noise(), test_dist_m4ri.test_dem_merge_equal_columns(), test_dist_m4ri.test_dem_out_reduced(), test_dist_m4ri.test_ignored_inputs_warnings(), test_dist_m4ri.test_model_lower_bound(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_sort_rows_option(), test_dist_m4ri.test_start_scan_option(), test_dist_m4ri.test_stim_out_dem_out_stim_out_dir(), test_dist_m4ri.test_stim_pauli_channel_circuit(), test_dist_m4ri.test_stim_rounds_option(), test_dist_m4ri.test_stim_simple_vs_full_and_basis_tracking(), and test_dist_m4ri.test_win_hyb_option().

◆ parse_cli_args()

◆ parse_debug_value()

int dist_m4ri.parse_debug_value ( Union[str, int] val)
Parses a debug bitmap value: a non-negative decimal or hexadecimal (0x...) integer, as in the dist_m4ri binary
(no octal: leading zeros are ignored).

Args:
    val: The value, e.g., "3" or "0x10004", or an int.

Returns:
    The debug bitmap.

Raises:
    ValueError: If the value is not a non-negative integer.

Definition at line 49 of file dist_m4ri.py.

Referenced by parse_cli_args(), and test_dist_m4ri.test_debug_bits().

◆ parse_dist_m4ri_output()

Tuple[int, int, int] dist_m4ri.parse_dist_m4ri_output ( str stdout)
Parses the standard output of dist_m4ri.
Expected format on stdout: "dmin dmax rw_steps", "dmin dmax", or a single integer.

Returns:
    tuple (dmin, dmax, rw_steps)

Definition at line 971 of file dist_m4ri.py.

Referenced by run_dist_m4ri().

◆ print_cli_help()

None dist_m4ri.print_cli_help ( Optional[Any] file = None)

Definition at line 6686 of file dist_m4ri.py.

Referenced by _main().

◆ print_cli_morehelp()

int dist_m4ri.print_cli_morehelp ( Optional[Any] file = None,
Optional[str] topic = None )
Prints the full help of the CLI (--morehelp), or with `topic` (one or more names separated by commas, see
_help_entries()) only the entries of these parameters, in the order of the full help under their section headers.
A topic may also be a group of the section 'Option groups' (also as singular or plural, e.g., window): then all
its members are printed; and an entry of a group also gives the other members of its groups and these groups
(one level: 'see also').  Returns 0, or 1 if some topic has no entry (then the closest names are suggested on
stderr).

Definition at line 7280 of file dist_m4ri.py.

References _cli_morehelp_text(), _help_entries(), _help_group_key_match(), _help_group_members(), and _help_name_key().

Referenced by _main().

◆ print_cli_short_help()

None dist_m4ri.print_cli_short_help ( Optional[Any] file = None)

Definition at line 6663 of file dist_m4ri.py.

Referenced by _main().

◆ read_drop_file()

Tuple[List[int], Optional[int]] dist_m4ri.read_drop_file ( Union[str, Path] path)
Reads a drop file: the 0-based detector indices (k for Dk) separated by white space or commas, where lines starting
with '#' or '%' are comments, e.g., the detectors dropped from a DEM written by the binary (outD=FILE).

Returns:
    (detectors, num_detectors): the sorted distinct detectors, and the number of detectors of the DEM from the
    comment line '# N of M detectors dropped ...' written by the binary (None if there is none).

Definition at line 3734 of file dist_m4ri.py.

Referenced by compute_dem_distance(), test_dist_m4ri.test_dem_drop_minority_detectors(), and test_dist_m4ri.test_dem_out_reduced().

◆ read_sparse_vectors()

List[List[int]] dist_m4ri.read_sparse_vectors ( str filepath)
Reads a list of sparse vectors from a text file in NZLIST format,
converting from 1-based indexing (in the file) to 0-based indexing (in Python).

Args:
    filepath (str): The path to the text file.

Returns:
    list of list of int: A list where each element is a 0-based sparse vector.

Definition at line 844 of file dist_m4ri.py.

Referenced by _cached_code_distance(), test_dist_m4ri.test_cached_outc_keeps_finc_codewords(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cli_outc_keeps_finc_codewords(), test_dist_m4ri.test_css_outc_sector_files_and_finc(), test_dist_m4ri.test_dem_expand_equal_columns(), test_dist_m4ri.test_dem_merge_equal_columns(), test_dist_m4ri.test_sort_rows_option(), and test_dist_m4ri.test_start_scan_option().

◆ remove_empty_detectors()

Tuple[Any, int] dist_m4ri.remove_empty_detectors ( Any circuit)
Removes DETECTOR instructions that have no measurement record targets.

Definition at line 2301 of file dist_m4ri.py.

References _get_stim(), and remove_empty_detectors().

Referenced by _dem_from_input(), and remove_empty_detectors().

◆ run_dist_m4ri()

Tuple[int, int, int] dist_m4ri.run_dist_m4ri ( Optional[str] dist_m4ri_path = None,
int method = 3,
Optional[str] finH = None,
Optional[str] finG = None,
Optional[str] finL = None,
Optional[str] fin = None,
Optional[str] finC = None,
Optional[str] fdem = None,
int dmin = 0,
int dmax = 0,
int wmax = 0,
int wmin = 1,
int dexp = 0,
int dest = 0,
int dstop = 0,
Optional[int] steps = None,
Optional[int] threads = None,
float timeout = 60.0,
Optional[int] smax = None,
Optional[Union[int, str, Sequence[int]]] start = None,
Optional[int] cbeg = None,
Optional[int] cend = None,
Optional[int] css = None,
int noscan = 0,
int classical = -1,
int dW = -1,
int maxC = 0,
float pmin = 0.0,
bool merge = True,
Optional[str] drop = None,
Optional[str] outD = None,
Optional[bool] sort_rows = None,
Optional[int] cc_prune = None,
Optional[str] outC = None,
int seed = 0,
int debug = 0,
bool nothrottle = False,
int chunk_size = 0,
int ksub = 0,
int kwin = 0,
int win_mode = 0,
int win_hyb = 0,
int pairs = -1,
Optional[int] min_hits = None,
int cov_cws = 100,
Optional[int] refresh = None,
bool verbose = False,
Optional[threading.Event] stop_event = None,
bool warn_start = True,
bool warn_ksub = True,
bool start_scan = False,
bool ortho = True,
bool warn_ortho = True )
Low-level invocation of the multithreaded dist_m4ri binary.

DEM input:
    merge: If True (default), the binary merges the equal columns of the DEM fdem (error mechanisms with the
        same detectors and observables).  Exact: dropping two equal columns of a codeword gives a lighter one,
        so the distance does not change.  Column indices (finC, outC, start) are those of the DEM; the codewords
        found use the first one of each set of equal columns.  merge=False passes merge=0 (all columns are
        kept, e.g., to enumerate the codewords with each of them).  Ignored without fdem.
    drop: The detectors of the DEM fdem to drop if this is verified to be exact, passed as drop=...: None (the
        binary's default, drop=auto: a search for the largest such set in the DEM), "auto" or "1" (the same), "0"
        (keep all detectors), or a file with the detectors to drop (0-based; otherwise, the binary uses the full DEM
        and prints a note, see _parse_stderr_stats()).  Ignored without fdem.
    outD: File to which the binary writes the detectors dropped from the DEM fdem (0-based; only the comment line
        '# N of M detectors dropped ...' if none, see read_drop_file()).  Ignored without fdem.

Orthogonality check:
    ortho: If True (default), the binary checks that the rows of H and G (finG, or fin without finL) are
        orthogonal (H G^T = 0) and stops with an error otherwise.  False (expert option, since version 0.15.2)
        passes ortho=0: the check is skipped, e.g., to screen many codes which are orthogonal by construction; the
        result is then valid only if H G^T = 0.  No effect without G.  The cache key does not depend on it.
    warn_ortho: If True (default), issue the warning for ortho=False to stderr (see _warn_ortho()).

Row order:
    sort_rows: Passed as sort_rows=1 (True) or sort_rows=0 (False); None (default): the binary's default, i.e.,
        1 for matrices and 0 for a DEM.  With sort_rows=1, the binary sorts the rows of H by increasing weight
        (stable).  With cc_prune=0, this reduces the CC work for matrices with very different row weights (e.g.,
        1.7-4x with the hook columns of an extended CSS distance), while the detectors of a DEM are in time
        order, which is better for CC (use sort_rows=False also for matrices exported from a DEM); with the
        default cc_prune=1, the order of the rows only breaks ties.  The distance and RW do not depend on the
        order of the rows; CC enumerates the same codewords, possibly in another order (with cc_prune=0, also with
        other hit counts).

CC search:
    cc_prune: Passed as cc_prune=N if not None (0, 1, or 2; None, the default: the binary's default 1).  The CC
        search with smax=0: 0, the walk of the versions before 0.15.0 (a cluster is extended by the columns of the
        first unsatisfied row of its syndrome); 1, the branch and bound (the unsatisfied row with the fewest
        available columns, the columns of the earlier branches forbidden in the later ones, so that each codeword
        is found once, and pruning by lower bounds on the number of columns needed: an unsatisfied row without
        available columns, a packing of unsatisfied rows with disjoint sets of available columns); 2, also the
        coverage and fractional cover bounds.  The same codewords and distances (doc/cc_completeness.tex); with
        the expert start list (and start_scan=False), cc_prune=1 and 2 forbid the columns listed before the start
        column.  The cache key does not depend on it.

RW windows:
    kwin / win_mode: A window of kwin columns in every RW step (win_mode=0: a Tanner graph ball, 1: an index
        window).  kwin=0 (default): the automatic hybrid for n >= 500, an index window of win_hyb columns in every
        other step and uniform random permutations in the others.  kwin=-1 (any negative value): no windows,
        uniform random permutations in every step.
    win_hyb: Window size of the hybrid RW steps, passed as win_hyb=N if nonzero; 0 (default): 256 columns for a
        DEM, 512 for matrices (at most 3n/4).  The windows of 192-256 columns find the minimum-weight codewords of
        circuit DEMs 2-10 times faster than 512, and windows of one round of columns are much slower.  With
        debug & 1 (or verbose=True), the binary prints the rounds of a DEM (estimated from the time translation of
        its errors: D detectors and L columns per round, also in _last_run_stats["rounds"]) and the codewords found
        by the uniform and by the window steps (see _parse_stderr_stats()).

RW pairs:
    pairs: The RW pairs of non-pivot columns (p=2, as in Lee-Brickell and Stern), passed as pairs=N if not -1: a
        RW step also finds the codewords with two non-pivot columns, checking only the pairs which agree on N
        random pivot rows (0: off).  -1 (default): auto, about one non-pivot column per bucket, with fewer rows
        while a codeword of the weight of the upper bound would be kept with probability below 0.8, but enough
        rows to keep the pairs of a step within about the work of its elimination (e.g., at least 6 for large
        circuit DEMs while the upper bound is far above the distance).  The pairs find the minimum-weight
        codewords of circuit DEMs 7-26 times faster (per wall time) and lighter codewords of codes with a large
        distance.  With debug & 1, the binary prints the pairs checked per step and the codewords found by pairs
        and by single columns (also in _last_run_stats).  The pairs of disjoint codewords are skipped (their sum
        is reducible: the binary records only irreducible codewords, its default irred=1).

RW stopping criterion:
    min_hits: Passed as min_hits=N if not None and >= 0 (None, the default, or a negative value: the binary's
        default 5): RW ends once the average number of hits <n> per codeword reaches N, both for the codewords
        of the minimum weight found and for a representative set of cov_cws lowest-weight codewords (the hits of
        all RW steps, with or without windows, and those of CC and finC count).  0: off; then, unless the
        codewords are collected (outC or maxC), RW records only the codewords lighter than the upper bound, so
        that the repeated hits are not counted.
    cov_cws: Size of the representative set of lowest-weight codewords for min_hits, passed as cov_cws=N if not
        100 (the default, as in the binary; 0: only the minimum weight).

Stop target:
    dstop: The run (method=2 or 3) ends once CC has certified dmin >= dstop, i.e., that there is no codeword of
        weight < dstop, unless a lighter codeword is found (default: 0 = off).  Unlike dmax, dstop is not an
        upper bound and is not reported as dmax: the result is (dmin, w, rw_steps), where w is the weight of the
        lightest codeword found (0: none).

Expert CC options:
    start: List of CC start columns (int, comma-separated string "a,b,c", or sequence of ints;
        None or a single negative value: all columns), passed as start=a,b,c (sorted, distinct).
        CC clusters are grown only from the listed columns, and they are not limited to larger
        column indices.  WARNING: the returned dmin (and an exact result) is valid only if a code
        symmetry maps every minimum-weight codeword to one containing a listed column (e.g., one
        column per block of a quasi-cyclic code); dmax is always valid.
    start_scan: With start (expert option, since version 0.15.1): passed as start_scan=1, so that a cluster
        grown from a listed column c only uses the columns > c, as in the scan of all columns (not with fdem).
        WARNING: dmin is then valid only if a code symmetry maps every minimum-weight codeword to one whose
        smallest column is listed, e.g., if the listed columns are the smallest columns of the orbits of a
        group of code automorphisms, one per orbit (start=[0, l] for the two blocks of a two-block
        group-algebra code of length 2l over an abelian group).  The later start columns then need much less
        work, the least if each orbit is a range of consecutive columns.
    warn_start: If True (default), issue the start-list warning to stderr.
    noscan / cbeg / cend: Disabled in the Python interface: accepted for backward compatibility,
        but ignored with a warning to stderr (use the dist_m4ri binary directly).

Experimental RW options:
    ksub: Experimental, should not be used: subspace dimension sampled from ker(H) in RW (0: full-matrix RW).
        A RW step reduces the span of ksub rows of a fixed basis of ker(H), so that a few codewords are found
        much more often than others (min_hits may end RW early).
    refresh: RW steps between the basis refreshes of the experimental ksub RW (passed if not None; None, the
        default: the binary's 5000 with ksub > 0; 0: no refresh).
    warn_ksub: If True (default), issue the warning for ksub > 0 to stderr (with method=1 or 3).

Debug output:
    debug: Debug bitmap; the bits in BIN_DBG_MASK are passed to the binary (its diagnostic output on stderr
        is printed), and PY_DBG_COMMANDS echoes the command line and the run time.  verbose=True implies
        the bits VERBOSE_DEBUG.

Cancellation:
    stop_event: Optional threading.Event; once it is set, the binary is terminated and RuntimeError is raised
        (the binary is also terminated on any other exception, e.g., KeyboardInterrupt).

Returns:
    tuple (dmin, dmax, rw_steps)

Definition at line 1786 of file dist_m4ri.py.

References _normalize_start_list(), _parse_stderr_stats(), _scan_start_list(), _start_warning_text(), _warn_disabled_options(), _warn_experimental_ksub(), _warn_ignored(), _warn_ortho(), check_finc_outc(), find_dist_m4ri_binary(), and parse_dist_m4ri_output().

Referenced by _cached_code_distance(), compute_dem_distance(), test_dist_m4ri.test_cc_prune_option(), test_dist_m4ri.test_cc_round_stats(), test_dist_m4ri.test_debug_bits(), test_dist_m4ri.test_dmin_dmax_parameters(), test_dist_m4ri.test_dstop_stop_target(), test_dist_m4ri.test_kwin_negative_turns_windows_off(), test_dist_m4ri.test_matrix_writer(), test_dist_m4ri.test_ortho_option(), test_dist_m4ri.test_pairs_option(), test_dist_m4ri.test_refresh_passed_to_binary(), test_dist_m4ri.test_run_dist_m4ri_start_list_and_disabled_options(), test_dist_m4ri.test_run_dist_m4ri_stop_event(), test_dist_m4ri.test_run_dist_m4ri_three_numbers(), test_dist_m4ri.test_sort_rows_option(), test_dist_m4ri.test_start_scan_option(), and test_dist_m4ri.test_win_hyb_option().

◆ rw_infoset_estimate()

Optional[Dict[str, Any]] dist_m4ri.rw_infoset_estimate ( int n,
int rank,
int steps,
int d,
int dmin = 1,
float step_time = 0.0,
float target = 0.01,
int steps_total = 0,
int pairs_l = 0 )
Information-set estimate of the probability that RW missed a codeword lighter than the upper bound d found.

Among the weights max(dmin, 1) <= w < d (not excluded by CC), the weight hardest to find (the smallest P(w),
see rw_infoset_find_prob()) is used: a single codeword of this weight is missed in `steps` RW steps with uniform
random permutations with probability (1 - P)^steps.  The number of RW steps for the target miss probability is
given in total, with the fraction steps / steps_total of uniform steps as in the run (localized windows, used in
about half of the steps for n >= 500, are not counted).  Same as print_rw_infoset_estimate() in the binary.

Args:
    n: Block length (number of columns of H).
    rank: Rank of H.
    steps: Number of completed RW steps with uniform random permutations.
    d: Smallest weight found (the upper bound dmax).
    dmin: Certified lower bound (smaller weights are excluded).
    step_time: Wall time per RW step in seconds (0: unknown).
    target: Target miss probability (default: 0.01).
    steps_total: Number of all completed RW steps (0: the same as `steps`).
    pairs_l: The number l of pivot rows of the buckets of the RW pairs (0: no pairs), see rw_infoset_find_prob().

Returns:
    Dictionary with the weight `w`, the probability `p_find` = P(w) per step, the miss probability `p_miss`,
    the total number of RW steps `steps_target` for the target miss probability (None if the codeword cannot be
    found), and the corresponding wall time `time_target` (None if unknown); or None if there are no weights to
    check.

Definition at line 327 of file dist_m4ri.py.

References rw_infoset_find_prob().

Referenced by explain_bounds(), and test_dist_m4ri.test_rw_infoset_estimate().

◆ rw_infoset_find_prob()

float dist_m4ri.rw_infoset_find_prob ( int n,
int rank,
int w,
int pairs_l = 0 )
Information-set estimate of the probability that a RW step finds a given codeword of weight w.

Model: uniform random information sets (as in the dist_m4ri binary, rw_infoset_find_prob()).  A RW step
reduces H (rank r) with a random column order; a codeword is found if exactly one of its w positions is among
the k = n - r non-pivot columns: P1(w) = w C(n-w, k-1) / C(n, k).  Codewords of weight w > r + 1 are never
found (P1 = 0).  With the RW pairs (pairs_l > 0, the binary's option pairs), also if exactly two of its positions
are non-pivot columns and its other w - 2 positions avoid the l pivot rows of the buckets:
P2(w) = C(w, 2) C(n-w, k-2) / C(n, k) * C(r - w + 2, l) / C(r, l), and the probability is P1 + P2.

Args:
    n: Block length (number of columns of H).
    rank: Rank r of H.
    w: Codeword weight.
    pairs_l: The number l of pivot rows of the buckets of the RW pairs (0: no pairs).

Returns:
    P1(w) + P2(w).

Definition at line 292 of file dist_m4ri.py.

Referenced by explain_bounds(), rw_infoset_estimate(), and test_dist_m4ri.test_rw_infoset_estimate().

◆ save_distance_cache()

None dist_m4ri.save_distance_cache ( Optional[Union[str, Path]] filepath = None)
Saves the in-memory distance cache to a JSON file.
Silently writes "__version__": __version__ into the file.
Uses atomic write via a temporary file to prevent corruption.
A cache file written by a newer version (see load_distance_cache()) is not overwritten.

Definition at line 202 of file dist_m4ri.py.

Referenced by _cached_code_distance(), _cert_code_distance(), _migrate_css_records(), _resolve_start_cache(), compute_model_lower_bound(), test_dist_m4ri.test_cache_newer_version_not_overwritten(), and test_dist_m4ri.test_cache_versioning().

◆ set_circuit_rounds()

Any dist_m4ri.set_circuit_rounds ( Any circuit,
int rounds )
Sets the repeat_count of CircuitRepeatBlocks in a Stim circuit.

For circuits with a single repeat block, sets its repeat_count to rounds.
For circuits with two repeat blocks (e.g. preamble + periodic body),
adjusts them to achieve total requested rounds.

Args:
    circuit: A stim.Circuit instance.
    rounds: The new repetition count to set for repeat blocks. If <= 0,
        repeat blocks are omitted.

Returns:
    A new stim.Circuit instance with modified repeat counts.

Definition at line 2338 of file dist_m4ri.py.

References _get_stim(), and set_circuit_rounds().

Referenced by _dem_from_input(), and set_circuit_rounds().

◆ set_distance_cache_file()

None dist_m4ri.set_distance_cache_file ( Optional[Union[str, Path]] filepath = None)
Sets the default JSON file for persistent distance caching.
If the file exists, its contents are loaded into memory.

Definition at line 156 of file dist_m4ri.py.

References load_distance_cache().

◆ set_silent()

None dist_m4ri.set_silent ( bool silent = True)
Turns off (silent=True) or on again (silent=False) the warnings written to stderr for the inputs which are
ignored (the CLI option --silent).  The warnings on the validity of a result (e.g., for ksub, ortho=0, or start)
are always written.

Definition at line 1210 of file dist_m4ri.py.

Referenced by _main(), main(), and test_dist_m4ri.test_ignored_inputs_warnings().

◆ strip_minority_detectors()

Tuple[Any, int, int] dist_m4ri.strip_minority_detectors ( Any circuit,
str basis,
bool verbose = False,
bool thorough = True,
Optional[Dict[str, Any]] thorough_res = None,
Optional[List[bool]] mask_out = None )
Strips detectors corresponding to the minority basis from a Stim circuit.

Always uses ancilla and data basis tracking (and dynamic carrier tracking
across SWAPs and syndrome handoffs) to identify each detector's basis.

Args:
    circuit: A stim.Circuit object or path to a .stim file.
    basis: Primary memory basis ('X' or 'Z'). Detectors of the opposite
        basis are removed.
    verbose: Whether to print warnings/statistics.
    thorough: Kept for API compatibility (basis tracking is always enabled).
    thorough_res: Optional precomputed result from classify_qubits_thorough.
    mask_out: Optional list, extended by one entry per detector of the circuit (in the order of the detectors of
        its DEM, REPEAT blocks unrolled): True if the detector is stripped, False if it is kept.

Returns:
    Tuple of (simplified_circuit, stripped_count, kept_count).

Definition at line 3388 of file dist_m4ri.py.

References _get_stim(), classify_qubits_thorough(), and track_circuit_carriers().

Referenced by _dem_from_input(), test_dist_m4ri.test_classify_qubits_checks_measured_in_hadamard_frame(), test_dist_m4ri.test_stim_simple_vs_full_and_basis_tracking(), and test_dist_m4ri.test_stim_xzzx_rotated_css().

◆ strip_noise()

Any dist_m4ri.strip_noise ( Any circuit)
Removes all noise from a Stim circuit (stim.Circuit or a .stim file), see stim.Circuit.without_noise(): the noise
channels (e.g., DEPOLARIZE1, X_ERROR, PAULI_CHANNEL_2, E) are removed, the measurements lose their flip
probabilities (M(0.001) becomes M), and heralded noise (e.g., HERALDED_ERASE) is replaced by MPAD, so that the
measurement record does not change.  E.g., add_noise(strip_noise(circuit), p) (or add_noise(circuit, p,
force=True); CLI: --force-noise) gives circuits with the same noise model.

Returns:
    The noiseless stim.Circuit.

Definition at line 2176 of file dist_m4ri.py.

References _get_stim().

Referenced by add_noise(), and test_dist_m4ri.test_add_noise_gate_classes_and_strip_noise().

◆ track_circuit_carriers()

List[List[int]] dist_m4ri.track_circuit_carriers ( Any circuit)
Dynamically tracks logical syndrome carriers across the circuit to measurements.

Accounts for physical qubit permutations via SWAP, CXSWAP, CZSWAP, ISWAP,
and ISWAP_DAG gates, as well as CNOT/CZ syndrome handoffs onto fresh ancilla
or routing qubits.

Returns:
    meas_carriers: List mapping each measurement index to a list of initial
        logical qubit IDs whose syndrome or state is carried into that
        measurement.

Definition at line 2471 of file dist_m4ri.py.

References _get_stim().

Referenced by strip_minority_detectors().

◆ verify_qubit_metadata()

Dict[str, Any] dist_m4ri.verify_qubit_metadata ( Any circuit,
bool verbose = False,
Optional[str] basis_arg = None,
Optional[Union[str, Path]] filepath = None )
Verifies qubit classification and returns basis tracking metadata.

Definition at line 3376 of file dist_m4ri.py.

References classify_qubits_thorough().

◆ write_reduced_dem()

Tuple[str, str] dist_m4ri.write_reduced_dem ( Any dem,
Sequence[int] dropped,
Union[str, Path] prefix,
float pmin = 0.0,
Optional[int] num_detectors = None,
Optional[Dict[str, Any]] meta = None )
Writes the DEM (a stim.DetectorErrorModel or a .dem file) without the detectors `dropped` (0-based, e.g., those
dropped by the binary, see compute_dem_distance(outD=..., out_reduced=...)) to PREFIX_red.dem: the errors which
touch none of them (after the cutoff pmin, in the order of the flattened DEM; a decomposed error as the sum of its
components), with the other detectors numbered consecutively, and the observables unchanged.  The maps go to
PREFIX_red.json: "detectors" (the original index of each detector of the reduced DEM, i.e., the complement of
"dropped"), "errors" (the original index of each error of the reduced DEM, 0-based in the order of the flattened DEM
after the cutoff pmin, as the columns of the codewords in outC), "dropped", "num_detectors", "num_errors", "pmin",
and the entries of meta.  If dropping the detectors is exact (as verified by the binary), the reduced DEM has the
same distance, and its codewords map to codewords of the DEM with "errors".

Returns:
    (dem_path, json_path): the files written.

Definition at line 3758 of file dist_m4ri.py.

References _dem_error_columns().

Referenced by compute_dem_distance(), and test_dist_m4ri.test_dem_out_reduced().

Variable Documentation

◆ _codedistance_mod

dist_m4ri._codedistance_mod = None
protected

Definition at line 32 of file dist_m4ri.py.

◆ _CODEDISTANCE_UNUSED

dict dist_m4ri._CODEDISTANCE_UNUSED
protected
Initial value:
1= {
2 "method": 3, "threads": None, "timeout": 60.0, "d_exp": 0, "dmin": 0, "dmax": 0, "d_min": 0, "d_max": 0,
3 "dstop": 0, "wmin": 1, "wmax": 0, "smax": None, "dW": -1, "maxC": 0, "finC": None, "nothrottle": False,
4 "chunk_size": 0, "ksub": 0, "kwin": 0, "win_mode": 0, "win_hyb": 0, "pairs": -1, "sort_rows": None,
5 "cc_prune": None, "min_hits": None, "cov_cws": 100, "refresh": None, "dist_m4ri": None, "pmin": 0.0,
6 "merge": True, "drop": None, "expand": False,
7}

Definition at line 1230 of file dist_m4ri.py.

◆ _css_distance_cache

dict dist_m4ri._css_distance_cache = _distance_cache
protected

Definition at line 152 of file dist_m4ri.py.

◆ _distance_cache

dict dist_m4ri._distance_cache = {}
protected

Definition at line 144 of file dist_m4ri.py.

◆ _distance_cache_file

Optional dist_m4ri._distance_cache_file = None
protected

Definition at line 146 of file dist_m4ri.py.

◆ _last_css_stats

dict dist_m4ri._last_css_stats = {"X": {}, "Z": {}}
protected

Definition at line 149 of file dist_m4ri.py.

◆ _last_run_stats

dict dist_m4ri._last_run_stats = {}
protected

Definition at line 148 of file dist_m4ri.py.

◆ _MTX_PY_MAX_NNZ

int dist_m4ri._MTX_PY_MAX_NNZ = 1 << 16
protected

Definition at line 2082 of file dist_m4ri.py.

◆ _newer_cache_files

Set dist_m4ri._newer_cache_files = set()
protected

Definition at line 147 of file dist_m4ri.py.

◆ _qec_cert_mod

dist_m4ri._qec_cert_mod = None
protected

Definition at line 34 of file dist_m4ri.py.

◆ _report_ignored

bool dist_m4ri._report_ignored = True
protected

Definition at line 1207 of file dist_m4ri.py.

◆ _stim_mod

dist_m4ri._stim_mod = None
protected

Definition at line 33 of file dist_m4ri.py.

◆ _use_css_distance_cache

bool dist_m4ri._use_css_distance_cache = _use_distance_cache
protected

Definition at line 153 of file dist_m4ri.py.

◆ _use_distance_cache

bool dist_m4ri._use_distance_cache = True
protected

Definition at line 145 of file dist_m4ri.py.

◆ BIN_DBG_MASK

int dist_m4ri.BIN_DBG_MASK = 0xFFFF

Definition at line 45 of file dist_m4ri.py.

◆ clear_css_distance_cache

None dist_m4ri.clear_css_distance_cache = clear_distance_cache

Definition at line 784 of file dist_m4ri.py.

◆ disable_css_distance_cache

None dist_m4ri.disable_css_distance_cache = disable_distance_cache

Definition at line 786 of file dist_m4ri.py.

◆ enable_css_distance_cache

None dist_m4ri.enable_css_distance_cache = enable_distance_cache

Definition at line 785 of file dist_m4ri.py.

◆ PY_DBG_CACHE

int dist_m4ri.PY_DBG_CACHE = 1 << 17

Definition at line 42 of file dist_m4ri.py.

◆ PY_DBG_CIRCUITS

int dist_m4ri.PY_DBG_CIRCUITS = 1 << 18

Definition at line 43 of file dist_m4ri.py.

◆ PY_DBG_COMMANDS

int dist_m4ri.PY_DBG_COMMANDS = 1 << 16

Definition at line 41 of file dist_m4ri.py.

◆ PY_DBG_KEEP_FILES

int dist_m4ri.PY_DBG_KEEP_FILES = 1 << 19

Definition at line 44 of file dist_m4ri.py.

◆ VERBOSE_DEBUG

int dist_m4ri.VERBOSE_DEBUG = 3 | PY_DBG_COMMANDS | PY_DBG_CACHE

Definition at line 46 of file dist_m4ri.py.