analog-ecc-heights 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- analog_ecc_heights/__init__.py +33 -0
- analog_ecc_heights/_dispatch.py +55 -0
- analog_ecc_heights/_validation.py +64 -0
- analog_ecc_heights/combinatorial.py +59 -0
- analog_ecc_heights/cpp_backend/__init__.py +1 -0
- analog_ecc_heights/cpp_backend/adapter.py +55 -0
- analog_ecc_heights/lp.py +63 -0
- analog_ecc_heights/py_backend/__init__.py +1 -0
- analog_ecc_heights/py_backend/_linalg.py +174 -0
- analog_ecc_heights/py_backend/_lp_solver.py +62 -0
- analog_ecc_heights/py_backend/_utils.py +29 -0
- analog_ecc_heights/py_backend/jiang_lp.py +92 -0
- analog_ecc_heights/py_backend/roth_comb.py +176 -0
- analog_ecc_heights/py_backend/roth_lp.py +57 -0
- analog_ecc_heights/py_backend/roth_mds_comb.py +51 -0
- analog_ecc_heights-0.1.0.dist-info/METADATA +111 -0
- analog_ecc_heights-0.1.0.dist-info/RECORD +20 -0
- analog_ecc_heights-0.1.0.dist-info/WHEEL +5 -0
- analog_ecc_heights-0.1.0.dist-info/licenses/LICENSE +21 -0
- solve_m_height_cpp.py +40 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""LP and combinatorial heights of analog error-correcting codes."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from ._dispatch import available_backends
|
|
6
|
+
from .combinatorial import (
|
|
7
|
+
h_m_roth_dual_combinatorial_generator,
|
|
8
|
+
h_m_roth_dual_combinatorial_parity,
|
|
9
|
+
h_m_roth_mds_combinatorial,
|
|
10
|
+
h_m_roth_mds_combinatorial_parity,
|
|
11
|
+
h_m_roth_primal_combinatorial,
|
|
12
|
+
h_m_roth_primal_combinatorial_pruning,
|
|
13
|
+
)
|
|
14
|
+
from .lp import (
|
|
15
|
+
h_m_jiang_original_lp,
|
|
16
|
+
h_m_jiang_simplified_lp,
|
|
17
|
+
h_m_roth_dual_lp,
|
|
18
|
+
h_m_roth_primal_lp,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
__version__ = version("analog-ecc-heights")
|
|
23
|
+
except PackageNotFoundError:
|
|
24
|
+
__version__ = "0+unknown"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"available_backends", "__version__",
|
|
28
|
+
"h_m_jiang_original_lp", "h_m_jiang_simplified_lp",
|
|
29
|
+
"h_m_roth_primal_lp", "h_m_roth_dual_lp",
|
|
30
|
+
"h_m_roth_primal_combinatorial", "h_m_roth_primal_combinatorial_pruning",
|
|
31
|
+
"h_m_roth_dual_combinatorial_generator", "h_m_roth_dual_combinatorial_parity",
|
|
32
|
+
"h_m_roth_mds_combinatorial", "h_m_roth_mds_combinatorial_parity",
|
|
33
|
+
]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Explicit backend selection; native imports happen only on request."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
|
|
5
|
+
from ._validation import thread_count
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
_METHOD_MODULES = {
|
|
9
|
+
"h_m_jiang_original_lp": "jiang_lp",
|
|
10
|
+
"h_m_jiang_simplified_lp": "jiang_lp",
|
|
11
|
+
"h_m_roth_primal_lp": "roth_lp",
|
|
12
|
+
"h_m_roth_dual_lp": "roth_lp",
|
|
13
|
+
"h_m_roth_primal_combinatorial": "roth_comb",
|
|
14
|
+
"h_m_roth_primal_combinatorial_pruning": "roth_comb",
|
|
15
|
+
"h_m_roth_dual_combinatorial_generator": "roth_comb",
|
|
16
|
+
"h_m_roth_dual_combinatorial_parity": "roth_comb",
|
|
17
|
+
"h_m_roth_mds_combinatorial": "roth_mds_comb",
|
|
18
|
+
"h_m_roth_mds_combinatorial_parity": "roth_mds_comb",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def run(method, matrix, m, *, backend, num_threads, **options):
|
|
23
|
+
family = "combinatorial" if "combinatorial" in method else "lp"
|
|
24
|
+
accepted = ("python", "cpp") if family == "combinatorial" else (
|
|
25
|
+
"python", "cpp-glpk", "cpp-highs"
|
|
26
|
+
)
|
|
27
|
+
if not isinstance(backend, str) or backend not in accepted:
|
|
28
|
+
raise ValueError(f"Unsupported backend {backend!r} for {family}; choose from {accepted}.")
|
|
29
|
+
threads = thread_count(num_threads)
|
|
30
|
+
if backend == "python":
|
|
31
|
+
if threads not in (None, 1):
|
|
32
|
+
raise ValueError("The python backend supports num_threads=None or 1 only.")
|
|
33
|
+
module = import_module(f".py_backend.{_METHOD_MODULES[method]}", __package__)
|
|
34
|
+
return getattr(module, method)(matrix, m, **options)
|
|
35
|
+
from .cpp_backend.adapter import call
|
|
36
|
+
|
|
37
|
+
return call(method, matrix, m, backend=backend, num_threads=threads, **options)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def available_backends():
|
|
41
|
+
"""Return usable backend names; this explicit check may load native code.
|
|
42
|
+
|
|
43
|
+
``python`` supports both method families, ``cpp`` supports combinatorial
|
|
44
|
+
methods, and ``cpp-glpk``/``cpp-highs`` support LP methods.
|
|
45
|
+
"""
|
|
46
|
+
from .cpp_backend.adapter import load_native
|
|
47
|
+
|
|
48
|
+
result = ["python"]
|
|
49
|
+
for backend in ("cpp", "cpp-glpk", "cpp-highs"):
|
|
50
|
+
try:
|
|
51
|
+
load_native(backend)
|
|
52
|
+
except ImportError:
|
|
53
|
+
continue
|
|
54
|
+
result.append(backend)
|
|
55
|
+
return result
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Argument checks shared by the public Python and native interfaces."""
|
|
2
|
+
|
|
3
|
+
from numbers import Integral, Real
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def matrix(value, name="G", *, parity=False):
|
|
9
|
+
"""Normalize real, finite matrix input without changing caller data."""
|
|
10
|
+
try:
|
|
11
|
+
raw = np.asarray(value)
|
|
12
|
+
if np.iscomplexobj(raw):
|
|
13
|
+
raise ValueError(f"{name} must be a real matrix.")
|
|
14
|
+
result = np.asarray(raw, dtype=np.float64)
|
|
15
|
+
except (TypeError, ValueError) as exc:
|
|
16
|
+
raise ValueError(f"{name} must be a real numeric matrix.") from exc
|
|
17
|
+
if result.ndim != 2:
|
|
18
|
+
raise ValueError(f"{name} must be two-dimensional.")
|
|
19
|
+
rows, cols = result.shape
|
|
20
|
+
if cols == 0 or (rows == 0 and not parity):
|
|
21
|
+
raise ValueError(f"{name} must be nonempty.")
|
|
22
|
+
if not np.isfinite(result).all():
|
|
23
|
+
raise ValueError(f"{name} must contain only finite values.")
|
|
24
|
+
return result
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def height_index(value, n, *, allow_none=False, jiang=False):
|
|
28
|
+
if value is None and allow_none:
|
|
29
|
+
return None
|
|
30
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral):
|
|
31
|
+
raise TypeError("m must be an integer" + (" or None." if allow_none else "."))
|
|
32
|
+
value = int(value)
|
|
33
|
+
lower, upper = (1, min(30, n - 1)) if jiang else (0, n - 1)
|
|
34
|
+
if not lower <= value <= upper:
|
|
35
|
+
raise ValueError(f"m must satisfy {lower} <= m <= {upper}.")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def threshold(value):
|
|
40
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
|
|
41
|
+
raise TypeError("early_quit_threshold must be a real number.")
|
|
42
|
+
value = float(value)
|
|
43
|
+
if np.isnan(value):
|
|
44
|
+
raise ValueError("early_quit_threshold must not be NaN.")
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def tolerance(value):
|
|
49
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
|
|
50
|
+
raise TypeError("tol must be a real number.")
|
|
51
|
+
value = float(value)
|
|
52
|
+
if not np.isfinite(value) or value < 0:
|
|
53
|
+
raise ValueError("tol must be finite and nonnegative.")
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def thread_count(value):
|
|
58
|
+
if value is None:
|
|
59
|
+
return None
|
|
60
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral):
|
|
61
|
+
raise TypeError("num_threads must be a positive integer or None.")
|
|
62
|
+
if value < 1:
|
|
63
|
+
raise ValueError("num_threads must be a positive integer or None.")
|
|
64
|
+
return int(value)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Combinatorial methods using generator or parity-check matrices."""
|
|
2
|
+
|
|
3
|
+
from . import _validation as validate
|
|
4
|
+
from ._dispatch import run
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _solve(method, matrix, m, backend, tol, num_threads):
|
|
8
|
+
parity = method.endswith("_parity")
|
|
9
|
+
matrix = validate.matrix(matrix, "H" if parity else "G", parity=parity)
|
|
10
|
+
rows, n = matrix.shape
|
|
11
|
+
if rows > n or (parity and rows == n):
|
|
12
|
+
raise ValueError("H must have rows < columns." if parity else "G must have rows <= columns.")
|
|
13
|
+
profile = method == "h_m_roth_primal_combinatorial"
|
|
14
|
+
m = validate.height_index(m, n, allow_none=profile)
|
|
15
|
+
tol = validate.tolerance(tol)
|
|
16
|
+
if "_mds_" in method and m != (rows if parity else n - rows):
|
|
17
|
+
raise ValueError("MDS methods require m equal to the code redundancy.")
|
|
18
|
+
result = run(method, matrix, m, backend=backend, num_threads=num_threads, tol=tol)
|
|
19
|
+
return [float(x) for x in result] if m is None else float(result)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def h_m_roth_primal_combinatorial(G, m=None, *, backend="python", tol=1e-10, num_threads=None):
|
|
23
|
+
"""Return scalar h_m, or [h_1, ..., h_(n-k)] when m is None.
|
|
24
|
+
|
|
25
|
+
G must have full row rank. Scalar indices satisfy 0 <= m < n.
|
|
26
|
+
The profile shares work across heights. Backends: python, cpp.
|
|
27
|
+
"""
|
|
28
|
+
return _solve("h_m_roth_primal_combinatorial", G, m, backend, tol, num_threads)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def h_m_roth_primal_combinatorial_pruning(G, m, *, backend="python", tol=1e-10, num_threads=None):
|
|
32
|
+
"""Compute a scalar primal combinatorial height with pruning."""
|
|
33
|
+
return _solve("h_m_roth_primal_combinatorial_pruning", G, m, backend, tol, num_threads)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def h_m_roth_dual_combinatorial_generator(G, m, *, backend="python", tol=1e-10, num_threads=None):
|
|
37
|
+
"""Compute a dual combinatorial height from a full-row-rank generator G."""
|
|
38
|
+
return _solve("h_m_roth_dual_combinatorial_generator", G, m, backend, tol, num_threads)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def h_m_roth_dual_combinatorial_parity(H, m, *, backend="python", tol=1e-10, num_threads=None):
|
|
42
|
+
"""Compute a dual combinatorial height from a full-row-rank parity matrix H."""
|
|
43
|
+
return _solve("h_m_roth_dual_combinatorial_parity", H, m, backend, tol, num_threads)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def h_m_roth_mds_combinatorial(G, m, *, backend="python", tol=1e-10, num_threads=None):
|
|
47
|
+
"""Compute the MDS specialization with m = n-k; reject non-MDS codes.
|
|
48
|
+
|
|
49
|
+
For zero redundancy, preserves the native specialization's return of 0.0.
|
|
50
|
+
"""
|
|
51
|
+
return _solve("h_m_roth_mds_combinatorial", G, m, backend, tol, num_threads)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def h_m_roth_mds_combinatorial_parity(H, m, *, backend="python", tol=1e-10, num_threads=None):
|
|
55
|
+
"""Compute the MDS specialization with m = H.shape[0]; reject non-MDS codes.
|
|
56
|
+
|
|
57
|
+
For zero redundancy, preserves the native specialization's return of 0.0.
|
|
58
|
+
"""
|
|
59
|
+
return _solve("h_m_roth_mds_combinatorial_parity", H, m, backend, tol, num_threads)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional C++ backend, imported lazily by the public API."""
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Adapt the stable public API to the original pybind11 function names."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
_MODULES = {"cpp": "_comb", "cpp-glpk": "_glpk", "cpp-highs": "_highs"}
|
|
7
|
+
_REQUIREMENTS = {
|
|
8
|
+
"cpp": "Eigen headers and OpenMP; build with -Cwheel.cmake=true",
|
|
9
|
+
"cpp-glpk": "Eigen headers and system GLPK; build with -Cwheel.cmake=true "
|
|
10
|
+
"-Ccmake.define.BUILD_CPP_COMB=OFF -Ccmake.define.USE_GLPK=ON",
|
|
11
|
+
"cpp-highs": "Eigen headers, OpenMP, and system HiGHS; build with -Cwheel.cmake=true "
|
|
12
|
+
"-Ccmake.define.BUILD_CPP_COMB=OFF -Ccmake.define.USE_HIGHS=ON",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_native(backend):
|
|
17
|
+
"""Load only the extension for the requested backend."""
|
|
18
|
+
try:
|
|
19
|
+
return import_module(f".{_MODULES[backend]}", __package__)
|
|
20
|
+
except (ImportError, OSError) as exc:
|
|
21
|
+
raise ImportError(
|
|
22
|
+
f"Backend {backend!r} could not be loaded. Requires {_REQUIREMENTS[backend]}. "
|
|
23
|
+
"Keep the native shared libraries available after installation. "
|
|
24
|
+
f"Original error: {exc}"
|
|
25
|
+
) from exc
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _threads(backend, requested):
|
|
29
|
+
if backend == "cpp-glpk":
|
|
30
|
+
if requested not in (None, 1):
|
|
31
|
+
raise ValueError("The cpp-glpk backend supports num_threads=None or 1 only.")
|
|
32
|
+
return 1
|
|
33
|
+
# OpenMP is required when building either parallel extension.
|
|
34
|
+
return 16 if requested is None else requested
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def call(method, matrix, m, *, backend, num_threads, **options):
|
|
38
|
+
native = load_native(backend)
|
|
39
|
+
if backend == "cpp":
|
|
40
|
+
symbol = method
|
|
41
|
+
else:
|
|
42
|
+
solver = backend.removeprefix("cpp-")
|
|
43
|
+
symbol = f"{method}_{solver}"
|
|
44
|
+
if method == "h_m_jiang_simplified_lp":
|
|
45
|
+
symbol += "_early_quit"
|
|
46
|
+
try:
|
|
47
|
+
function = getattr(native, symbol)
|
|
48
|
+
except AttributeError as exc:
|
|
49
|
+
raise ImportError(
|
|
50
|
+
f"Backend {backend!r} is missing symbol {symbol!r}; rebuild analog-ecc-heights."
|
|
51
|
+
) from exc
|
|
52
|
+
threads = _threads(backend, num_threads)
|
|
53
|
+
if backend != "cpp-glpk":
|
|
54
|
+
options["num_threads"] = threads
|
|
55
|
+
return function(matrix, m, **options)
|
analog_ecc_heights/lp.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Linear-programming methods for analog error-correcting code heights."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from . import _validation as validate
|
|
6
|
+
from ._dispatch import run
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _solve(method, G, m, backend, num_threads, **options):
|
|
10
|
+
G = validate.matrix(G)
|
|
11
|
+
jiang = "jiang" in method
|
|
12
|
+
m = validate.height_index(m, G.shape[1], jiang=jiang)
|
|
13
|
+
if method == "h_m_jiang_original_lp" and np.any(np.all(G == 0, axis=0)):
|
|
14
|
+
raise ValueError("Jiang original LP assumes no zero column in G.")
|
|
15
|
+
if "early_quit_threshold" in options:
|
|
16
|
+
options["early_quit_threshold"] = validate.threshold(options["early_quit_threshold"])
|
|
17
|
+
return float(run(method, G, m, backend=backend, num_threads=num_threads, **options))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def h_m_jiang_original_lp(G, m, *, backend="python", num_threads=None):
|
|
21
|
+
"""Compute Jiang's original LP formulation.
|
|
22
|
+
|
|
23
|
+
G must be real, finite and have no zero columns. Requires
|
|
24
|
+
1 <= m <= min(30, n-1). No early-quit threshold is supported.
|
|
25
|
+
Backends: python (default), cpp-glpk, cpp-highs.
|
|
26
|
+
"""
|
|
27
|
+
return _solve("h_m_jiang_original_lp", G, m, backend, num_threads)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def h_m_jiang_simplified_lp(
|
|
31
|
+
G, m, *, backend="python", early_quit_threshold=float("inf"), num_threads=None
|
|
32
|
+
):
|
|
33
|
+
"""Compute Jiang's simplified LP, returning min(height, threshold).
|
|
34
|
+
|
|
35
|
+
Requires 1 <= m <= min(30, n-1). An infinite threshold computes the
|
|
36
|
+
complete height. Backends: python (default), cpp-glpk, cpp-highs.
|
|
37
|
+
"""
|
|
38
|
+
return _solve("h_m_jiang_simplified_lp", G, m, backend, num_threads,
|
|
39
|
+
early_quit_threshold=early_quit_threshold)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def h_m_roth_primal_lp(
|
|
43
|
+
G, m, *, backend="python", early_quit_threshold=float("inf"), num_threads=None
|
|
44
|
+
):
|
|
45
|
+
"""Compute Roth's primal LP, returning min(height, threshold).
|
|
46
|
+
|
|
47
|
+
Requires 0 <= m < n. At m=0, returns min(1, threshold).
|
|
48
|
+
Backends: python (default), cpp-glpk, cpp-highs.
|
|
49
|
+
"""
|
|
50
|
+
return _solve("h_m_roth_primal_lp", G, m, backend, num_threads,
|
|
51
|
+
early_quit_threshold=early_quit_threshold)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def h_m_roth_dual_lp(
|
|
55
|
+
G, m, *, backend="python", early_quit_threshold=float("inf"), num_threads=None
|
|
56
|
+
):
|
|
57
|
+
"""Compute Roth's dual LP, returning min(height, threshold).
|
|
58
|
+
|
|
59
|
+
Requires 0 <= m < n. At m=0, returns min(1, threshold).
|
|
60
|
+
Backends: python (default), cpp-glpk, cpp-highs.
|
|
61
|
+
"""
|
|
62
|
+
return _solve("h_m_roth_dual_lp", G, m, backend, num_threads,
|
|
63
|
+
early_quit_threshold=early_quit_threshold)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Reference implementations using NumPy, SciPy, and the standard library."""
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Linear algebra using the native methods' full-pivot rank convention.
|
|
2
|
+
|
|
3
|
+
Rank is determined by complete-pivot LU with an absolute cutoff of
|
|
4
|
+
``tol * reference_scale``. Submatrices use the *parent matrix's* largest
|
|
5
|
+
absolute entry as their reference scale. An SVD's default rank threshold
|
|
6
|
+
would change minimum-distance decisions for small or nearly singular bases.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import operator
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ._utils import complement_indices, subsets
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def matrix_scale(matrix):
|
|
17
|
+
"""Largest absolute entry, including the empty-matrix convention."""
|
|
18
|
+
return float(np.max(np.abs(matrix), initial=0.0))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FullPivotLU:
|
|
22
|
+
"""Complete-pivot LU with one factorization for rank checks and solves."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, matrix, tol, reference_scale=None):
|
|
25
|
+
self.lu = np.array(matrix, dtype=float, copy=True)
|
|
26
|
+
rows, cols = self.lu.shape
|
|
27
|
+
self.row_order = np.arange(rows)
|
|
28
|
+
self.col_order = np.arange(cols)
|
|
29
|
+
if reference_scale is None:
|
|
30
|
+
reference_scale = matrix_scale(self.lu)
|
|
31
|
+
diagonal_size = min(rows, cols)
|
|
32
|
+
max_pivot = 0.0
|
|
33
|
+
nonzero = 0
|
|
34
|
+
for step in range(diagonal_size):
|
|
35
|
+
corner = np.abs(self.lu[step:, step:])
|
|
36
|
+
# Eigen stores MatrixXd in column-major order. Preserve its tie order.
|
|
37
|
+
pivot_index = int(np.argmax(corner.ravel(order="F")))
|
|
38
|
+
row = step + pivot_index % corner.shape[0]
|
|
39
|
+
col = step + pivot_index // corner.shape[0]
|
|
40
|
+
pivot_size = abs(self.lu[row, col])
|
|
41
|
+
if pivot_size == 0.0:
|
|
42
|
+
break
|
|
43
|
+
max_pivot = max(max_pivot, pivot_size)
|
|
44
|
+
nonzero += 1
|
|
45
|
+
if row != step:
|
|
46
|
+
self.lu[[step, row], :] = self.lu[[row, step], :]
|
|
47
|
+
self.row_order[[step, row]] = self.row_order[[row, step]]
|
|
48
|
+
if col != step:
|
|
49
|
+
self.lu[:, [step, col]] = self.lu[:, [col, step]]
|
|
50
|
+
self.col_order[[step, col]] = self.col_order[[col, step]]
|
|
51
|
+
if step + 1 < rows:
|
|
52
|
+
self.lu[step + 1:, step] /= self.lu[step, step]
|
|
53
|
+
if step + 1 < diagonal_size:
|
|
54
|
+
self.lu[step + 1:, step + 1:] -= np.outer(
|
|
55
|
+
self.lu[step + 1:, step], self.lu[step, step + 1:]
|
|
56
|
+
)
|
|
57
|
+
# Retain the multiplication order of FullPivLU::rank(), including
|
|
58
|
+
# rounding exactly at the tolerance boundary.
|
|
59
|
+
threshold = max_pivot * (tol * reference_scale / max_pivot) if max_pivot else 0.0
|
|
60
|
+
self.rank = int(np.count_nonzero(np.abs(self.lu.diagonal()[:nonzero]) > threshold))
|
|
61
|
+
|
|
62
|
+
def solve(self, targets):
|
|
63
|
+
"""Solve square nonsingular systems, retaining the rank factorization."""
|
|
64
|
+
rows, cols = self.lu.shape
|
|
65
|
+
if rows != cols or self.rank != rows:
|
|
66
|
+
raise np.linalg.LinAlgError("A square, numerically invertible basis is required.")
|
|
67
|
+
targets = np.asarray(targets, dtype=float)
|
|
68
|
+
vector = targets.ndim == 1
|
|
69
|
+
if vector:
|
|
70
|
+
targets = targets[:, None]
|
|
71
|
+
if targets.ndim != 2 or targets.shape[0] != rows:
|
|
72
|
+
raise ValueError("The right-hand side must have one row per basis row.")
|
|
73
|
+
result = targets[self.row_order].copy()
|
|
74
|
+
# Column-oriented substitutions mirror Eigen's triangular solves.
|
|
75
|
+
for col in range(rows):
|
|
76
|
+
result[col + 1:] -= self.lu[col + 1:, col, None] * result[col]
|
|
77
|
+
for col in range(rows - 1, -1, -1):
|
|
78
|
+
result[col] /= self.lu[col, col]
|
|
79
|
+
result[:col] -= self.lu[:col, col, None] * result[col]
|
|
80
|
+
unpermuted = np.empty_like(result)
|
|
81
|
+
unpermuted[self.col_order] = result
|
|
82
|
+
return unpermuted[:, 0] if vector else unpermuted
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def numerical_rank(matrix, tol, reference_scale=None):
|
|
86
|
+
return FullPivotLU(matrix, tol, reference_scale).rank
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def factor_columns(matrix, columns, tol, reference_scale):
|
|
90
|
+
return FullPivotLU(matrix[:, list(columns)], tol, reference_scale)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def validate_rank_tolerance(tol):
|
|
94
|
+
if not np.isfinite(tol) or tol < 0.0:
|
|
95
|
+
raise ValueError("tol must be a finite nonnegative value.")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _as_real_matrix(matrix, name):
|
|
99
|
+
raw = np.asarray(matrix)
|
|
100
|
+
if np.iscomplexobj(raw):
|
|
101
|
+
raise ValueError(f"{name} must contain real values.")
|
|
102
|
+
matrix = np.asarray(raw, dtype=float)
|
|
103
|
+
if matrix.ndim != 2:
|
|
104
|
+
raise ValueError(f"{name} must be a two-dimensional matrix.")
|
|
105
|
+
if not np.all(np.isfinite(matrix)):
|
|
106
|
+
raise ValueError(f"{name} must contain only finite values.")
|
|
107
|
+
return matrix
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def validate_generator_matrix(G, tol=1e-10):
|
|
111
|
+
validate_rank_tolerance(tol)
|
|
112
|
+
G = _as_real_matrix(G, "G")
|
|
113
|
+
k, n = G.shape
|
|
114
|
+
if k == 0 or n == 0:
|
|
115
|
+
raise ValueError("G must be a non-empty generator matrix.")
|
|
116
|
+
if k > n:
|
|
117
|
+
raise ValueError(f"G must satisfy rows <= cols, got rows={k}, cols={n}.")
|
|
118
|
+
if numerical_rank(G, tol) != k:
|
|
119
|
+
raise ValueError("G must have full row rank.")
|
|
120
|
+
return G
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def validate_parity_check_matrix(H, tol=1e-10):
|
|
124
|
+
validate_rank_tolerance(tol)
|
|
125
|
+
H = _as_real_matrix(H, "H")
|
|
126
|
+
r, n = H.shape
|
|
127
|
+
if n == 0:
|
|
128
|
+
raise ValueError("H must have at least one column.")
|
|
129
|
+
if r >= n:
|
|
130
|
+
raise ValueError(f"H must satisfy rows < cols, got rows={r}, cols={n}.")
|
|
131
|
+
if numerical_rank(H, tol) != r:
|
|
132
|
+
raise ValueError("H must have full row rank.")
|
|
133
|
+
return H
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def validate_m_for_columns(m, n):
|
|
137
|
+
if isinstance(m, (bool, np.bool_)):
|
|
138
|
+
raise TypeError("m must be an integer.")
|
|
139
|
+
try:
|
|
140
|
+
m = operator.index(m)
|
|
141
|
+
except TypeError:
|
|
142
|
+
raise TypeError("m must be an integer.") from None
|
|
143
|
+
if m < 0 or m >= n:
|
|
144
|
+
raise ValueError("m must satisfy 0 <= m <= n-1.")
|
|
145
|
+
return m
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def generator_minimum_distance_exceeds_validated(G, m, tol):
|
|
149
|
+
k, n = G.shape
|
|
150
|
+
if n - m < k:
|
|
151
|
+
return False
|
|
152
|
+
scale = matrix_scale(G)
|
|
153
|
+
return all(
|
|
154
|
+
numerical_rank(G[:, complement_indices(n, S)], tol, scale) == k
|
|
155
|
+
for S in subsets(n, m)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def parity_check_minimum_distance_exceeds_validated(H, m, tol):
|
|
160
|
+
if m > H.shape[0]:
|
|
161
|
+
return False
|
|
162
|
+
scale = matrix_scale(H)
|
|
163
|
+
return all(
|
|
164
|
+
numerical_rank(H[:, list(S)], tol, scale) == m
|
|
165
|
+
for S in subsets(H.shape[1], m)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def generator_minimum_distance_validated(G, tol):
|
|
170
|
+
redundancy = G.shape[1] - G.shape[0]
|
|
171
|
+
for m in range(1, redundancy + 1):
|
|
172
|
+
if not generator_minimum_distance_exceeds_validated(G, m, tol):
|
|
173
|
+
return m
|
|
174
|
+
return redundancy + 1
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Small SciPy LP adapter shared by the Python height algorithms."""
|
|
2
|
+
|
|
3
|
+
from typing import NamedTuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.optimize import linprog
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LpResult(NamedTuple):
|
|
10
|
+
status: str
|
|
11
|
+
value: float = float("nan")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def solve_lp(
|
|
15
|
+
cost,
|
|
16
|
+
*,
|
|
17
|
+
A_ub=None,
|
|
18
|
+
b_ub=None,
|
|
19
|
+
A_eq=None,
|
|
20
|
+
b_eq=None,
|
|
21
|
+
maximize=False,
|
|
22
|
+
nonnegative=False,
|
|
23
|
+
):
|
|
24
|
+
"""Solve an LP, separating infeasibility/unboundedness from solver errors.
|
|
25
|
+
|
|
26
|
+
The default variable bounds are free, as required by generator-coordinate
|
|
27
|
+
LPs. Dual LPs opt into nonnegative variables explicitly. A failed solve
|
|
28
|
+
never supplies an objective value to an outer height maximization.
|
|
29
|
+
"""
|
|
30
|
+
if A_eq is not None and b_eq is not None:
|
|
31
|
+
# An exactly zero equality row cannot equal a nonzero right-hand
|
|
32
|
+
# side. Older HiGHS versions can report an unknown status for this
|
|
33
|
+
# contradiction with presolve off; certify it directly, without a
|
|
34
|
+
# numerical rank tolerance or a solver fallback.
|
|
35
|
+
zero_rows = np.all(np.asarray(A_eq) == 0, axis=1)
|
|
36
|
+
if np.any(zero_rows & (np.asarray(b_eq) != 0)):
|
|
37
|
+
return LpResult("infeasible")
|
|
38
|
+
result = linprog(
|
|
39
|
+
-cost if maximize else cost,
|
|
40
|
+
A_ub=A_ub,
|
|
41
|
+
b_ub=b_ub,
|
|
42
|
+
A_eq=A_eq,
|
|
43
|
+
b_eq=b_eq,
|
|
44
|
+
bounds=(0, None) if nonnegative else (None, None),
|
|
45
|
+
method="highs",
|
|
46
|
+
# Presolve can misclassify feasible, unbounded homogeneous LPs as
|
|
47
|
+
# infeasible. The native HiGHS implementation disables it as well.
|
|
48
|
+
options={"presolve": False},
|
|
49
|
+
)
|
|
50
|
+
if result.status == 0:
|
|
51
|
+
if result.fun is None or not np.isfinite(result.fun):
|
|
52
|
+
raise RuntimeError("SciPy LP returned a nonfinite optimal objective.")
|
|
53
|
+
return LpResult("optimal", float(-result.fun if maximize else result.fun))
|
|
54
|
+
if result.status == 2:
|
|
55
|
+
# Some SciPy releases map HiGHS model errors to status 2 as well.
|
|
56
|
+
# Only an explicitly identified infeasible model has mathematical
|
|
57
|
+
# meaning for the caller; rejected models must raise an error.
|
|
58
|
+
if "infeasible" in str(result.message).lower():
|
|
59
|
+
return LpResult("infeasible")
|
|
60
|
+
elif result.status == 3:
|
|
61
|
+
return LpResult("unbounded")
|
|
62
|
+
raise RuntimeError(f"SciPy LP failed (status {result.status}): {result.message}")
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Small, deterministic enumeration helpers shared by Python methods."""
|
|
2
|
+
|
|
3
|
+
from itertools import combinations, product
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def complement_indices(n, subset):
|
|
9
|
+
"""Return the sorted complement of a coordinate subset."""
|
|
10
|
+
excluded = set(subset)
|
|
11
|
+
return [i for i in range(n) if i not in excluded]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def subsets(pool, size):
|
|
15
|
+
"""Yield lexicographic subsets; impossible sizes have no subsets."""
|
|
16
|
+
if isinstance(pool, int):
|
|
17
|
+
pool = range(pool)
|
|
18
|
+
if size < 0 or size > len(pool):
|
|
19
|
+
return iter(())
|
|
20
|
+
return combinations(pool, size)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sign_vectors(k):
|
|
24
|
+
"""Enumerate signs once modulo global sign symmetry, as native code does."""
|
|
25
|
+
if k == 0:
|
|
26
|
+
yield np.empty(0, dtype=float)
|
|
27
|
+
elif k > 0:
|
|
28
|
+
for tail in product((-1.0, 1.0), repeat=k - 1):
|
|
29
|
+
yield np.asarray((1.0, *tail))
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Jiang's original and simplified enumerations using SciPy linear programs."""
|
|
2
|
+
|
|
3
|
+
from itertools import combinations
|
|
4
|
+
from math import inf
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from ._lp_solver import solve_lp
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def h_m_jiang_original_lp(G, m):
|
|
12
|
+
"""Evaluate the original sign/order LP enumeration for a validated G, m."""
|
|
13
|
+
k, n = G.shape
|
|
14
|
+
rows = 2 * (m - 1) + 2 * (n - m - 1)
|
|
15
|
+
A = np.empty((rows, k))
|
|
16
|
+
upper = np.empty(rows)
|
|
17
|
+
best = 0.0
|
|
18
|
+
|
|
19
|
+
for a in range(n):
|
|
20
|
+
for b in range(n):
|
|
21
|
+
if a == b:
|
|
22
|
+
continue
|
|
23
|
+
remaining = tuple(j for j in range(n) if j != a and j != b)
|
|
24
|
+
for X in combinations(remaining, m - 1):
|
|
25
|
+
selected = set(X)
|
|
26
|
+
Y = tuple(j for j in remaining if j not in selected)
|
|
27
|
+
for mask in range(1 << m):
|
|
28
|
+
sa = 1.0 if mask & 1 else -1.0
|
|
29
|
+
cost = sa * G[:, a]
|
|
30
|
+
row = 0
|
|
31
|
+
for t, x in enumerate(X):
|
|
32
|
+
sx = 1.0 if mask & (1 << (t + 1)) else -1.0
|
|
33
|
+
# 1 <= sx*c_x <= sa*c_a.
|
|
34
|
+
A[row] = sx * G[:, x] - cost
|
|
35
|
+
upper[row] = 0.0
|
|
36
|
+
A[row + 1] = -sx * G[:, x]
|
|
37
|
+
upper[row + 1] = -1.0
|
|
38
|
+
row += 2
|
|
39
|
+
for y in Y:
|
|
40
|
+
A[row] = G[:, y]
|
|
41
|
+
A[row + 1] = -G[:, y]
|
|
42
|
+
upper[row : row + 2] = 1.0
|
|
43
|
+
row += 2
|
|
44
|
+
result = solve_lp(
|
|
45
|
+
cost,
|
|
46
|
+
A_ub=A if rows else None,
|
|
47
|
+
b_ub=upper if rows else None,
|
|
48
|
+
A_eq=G[:, b].reshape(1, k),
|
|
49
|
+
b_eq=np.ones(1),
|
|
50
|
+
maximize=True,
|
|
51
|
+
)
|
|
52
|
+
if result.status == "optimal":
|
|
53
|
+
best = max(best, result.value)
|
|
54
|
+
elif result.status == "unbounded":
|
|
55
|
+
return inf
|
|
56
|
+
# Infeasible sign/order cases make no contribution.
|
|
57
|
+
return float(best)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def h_m_jiang_simplified_lp(G, m, early_quit_threshold=inf):
|
|
61
|
+
"""Evaluate the simplified enumeration, capped at early_quit_threshold."""
|
|
62
|
+
k, n = G.shape
|
|
63
|
+
A = np.empty((m - 1 + 2 * (n - m), k))
|
|
64
|
+
upper = np.ones(A.shape[0])
|
|
65
|
+
upper[: m - 1] = 0.0
|
|
66
|
+
best = -inf
|
|
67
|
+
|
|
68
|
+
for a in range(n):
|
|
69
|
+
cost = G[:, a]
|
|
70
|
+
remaining = tuple(j for j in range(n) if j != a)
|
|
71
|
+
for X in combinations(remaining, m - 1):
|
|
72
|
+
selected = set(X)
|
|
73
|
+
row = 0
|
|
74
|
+
for x in X:
|
|
75
|
+
A[row] = G[:, x] - cost
|
|
76
|
+
row += 1
|
|
77
|
+
for y in remaining:
|
|
78
|
+
if y in selected:
|
|
79
|
+
continue
|
|
80
|
+
A[row] = G[:, y]
|
|
81
|
+
A[row + 1] = -G[:, y]
|
|
82
|
+
row += 2
|
|
83
|
+
result = solve_lp(cost, A_ub=A, b_ub=upper, maximize=True)
|
|
84
|
+
if result.status == "optimal":
|
|
85
|
+
best = max(best, result.value)
|
|
86
|
+
elif result.status == "unbounded":
|
|
87
|
+
return float(early_quit_threshold)
|
|
88
|
+
else:
|
|
89
|
+
raise RuntimeError("Simplified Jiang LP is infeasible although u=0 is feasible.")
|
|
90
|
+
if best > early_quit_threshold:
|
|
91
|
+
return float(early_quit_threshold)
|
|
92
|
+
return float(min(best, early_quit_threshold))
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Roth's primal and dual combinatorial height formulas."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from ._linalg import (
|
|
6
|
+
factor_columns,
|
|
7
|
+
generator_minimum_distance_exceeds_validated,
|
|
8
|
+
generator_minimum_distance_validated,
|
|
9
|
+
matrix_scale,
|
|
10
|
+
parity_check_minimum_distance_exceeds_validated,
|
|
11
|
+
validate_generator_matrix,
|
|
12
|
+
validate_m_for_columns,
|
|
13
|
+
validate_parity_check_matrix,
|
|
14
|
+
)
|
|
15
|
+
from ._utils import complement_indices, sign_vectors, subsets
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _candidate_stats(values):
|
|
19
|
+
magnitudes = np.abs(values)
|
|
20
|
+
return (
|
|
21
|
+
float(np.max(magnitudes, initial=0.0)),
|
|
22
|
+
int(np.count_nonzero(magnitudes > 1.0)),
|
|
23
|
+
int(np.count_nonzero(magnitudes < 1.0)),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _candidate_value(values, m, n):
|
|
28
|
+
value, greater, less = _candidate_stats(values)
|
|
29
|
+
# These are strict comparisons, as in Roth Theorem 5, equation (15).
|
|
30
|
+
if greater > m or less > n - m - 1:
|
|
31
|
+
return -float("inf")
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _primal_transforms(G, tol):
|
|
36
|
+
k, n = G.shape
|
|
37
|
+
scale = matrix_scale(G)
|
|
38
|
+
for I in subsets(n, k):
|
|
39
|
+
lu = factor_columns(G, I, tol, scale)
|
|
40
|
+
if lu.rank == k:
|
|
41
|
+
yield lu.solve(G[:, complement_indices(n, I)]).T
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def h_m_roth_primal_combinatorial(G, m=None, tol=1e-10):
|
|
45
|
+
"""Return one height, or the shared-computation profile h_1,...,h_(n-k)."""
|
|
46
|
+
G = validate_generator_matrix(G, tol)
|
|
47
|
+
k, n = G.shape
|
|
48
|
+
if m is not None:
|
|
49
|
+
m = validate_m_for_columns(m, n)
|
|
50
|
+
if m == 0:
|
|
51
|
+
return 1.0
|
|
52
|
+
if not generator_minimum_distance_exceeds_validated(G, m, tol):
|
|
53
|
+
return float("inf")
|
|
54
|
+
best = -float("inf")
|
|
55
|
+
for R in _primal_transforms(G, tol):
|
|
56
|
+
for signs in sign_vectors(k):
|
|
57
|
+
best = max(best, _candidate_value(R @ signs, m, n))
|
|
58
|
+
return best
|
|
59
|
+
|
|
60
|
+
max_m = n - k
|
|
61
|
+
if max_m == 0:
|
|
62
|
+
return []
|
|
63
|
+
finite_m_count = min(max_m, generator_minimum_distance_validated(G, tol) - 1)
|
|
64
|
+
result = [float("inf")] * max_m
|
|
65
|
+
if finite_m_count == 0:
|
|
66
|
+
return result
|
|
67
|
+
result[:finite_m_count] = [-float("inf")] * finite_m_count
|
|
68
|
+
# Each basis solve and sign-vector product is shared across the profile.
|
|
69
|
+
for R in _primal_transforms(G, tol):
|
|
70
|
+
for signs in sign_vectors(k):
|
|
71
|
+
value, greater, less = _candidate_stats(R @ signs)
|
|
72
|
+
first = max(1, greater)
|
|
73
|
+
last = min(finite_m_count, n - less - 1)
|
|
74
|
+
for current_m in range(first, last + 1):
|
|
75
|
+
result[current_m - 1] = max(result[current_m - 1], value)
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _pruned_sign_maximum(R, m, n):
|
|
80
|
+
# Explore the most influential coordinates first; sign reversal allows
|
|
81
|
+
# fixing the first sign after this permutation as well.
|
|
82
|
+
order = np.argsort(-np.sum(np.abs(R), axis=0), kind="stable")
|
|
83
|
+
R = R[:, order]
|
|
84
|
+
k = R.shape[1]
|
|
85
|
+
suffix_abs = np.zeros((R.shape[0], k + 1))
|
|
86
|
+
for col in range(k - 1, -1, -1):
|
|
87
|
+
suffix_abs[:, col] = suffix_abs[:, col + 1] + np.abs(R[:, col])
|
|
88
|
+
partial = R[:, 0].copy()
|
|
89
|
+
best = -float("inf")
|
|
90
|
+
|
|
91
|
+
def visit(depth):
|
|
92
|
+
nonlocal best
|
|
93
|
+
upper_bound = float(np.max(np.abs(partial) + suffix_abs[:, depth], initial=0.0))
|
|
94
|
+
if upper_bound <= best:
|
|
95
|
+
return
|
|
96
|
+
if depth == k:
|
|
97
|
+
best = max(best, _candidate_value(partial, m, n))
|
|
98
|
+
return
|
|
99
|
+
partial[:] += R[:, depth]
|
|
100
|
+
visit(depth + 1)
|
|
101
|
+
partial[:] -= 2.0 * R[:, depth]
|
|
102
|
+
visit(depth + 1)
|
|
103
|
+
partial[:] += R[:, depth]
|
|
104
|
+
|
|
105
|
+
visit(1)
|
|
106
|
+
return best
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def h_m_roth_primal_combinatorial_pruning(G, m, tol=1e-10):
|
|
110
|
+
"""Evaluate the primal formula with an exact sign-search upper bound."""
|
|
111
|
+
G = validate_generator_matrix(G, tol)
|
|
112
|
+
m = validate_m_for_columns(m, G.shape[1])
|
|
113
|
+
if m == 0:
|
|
114
|
+
return 1.0
|
|
115
|
+
if not generator_minimum_distance_exceeds_validated(G, m, tol):
|
|
116
|
+
return float("inf")
|
|
117
|
+
return max(_pruned_sign_maximum(R, m, G.shape[1]) for R in _primal_transforms(G, tol))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def h_m_roth_dual_combinatorial_generator(G, m, tol=1e-10):
|
|
121
|
+
"""Evaluate the dual formula from a generator matrix."""
|
|
122
|
+
G = validate_generator_matrix(G, tol)
|
|
123
|
+
k, n = G.shape
|
|
124
|
+
m = validate_m_for_columns(m, n)
|
|
125
|
+
if m == 0:
|
|
126
|
+
return 1.0
|
|
127
|
+
if not generator_minimum_distance_exceeds_validated(G, m, tol):
|
|
128
|
+
return float("inf")
|
|
129
|
+
scale = matrix_scale(G)
|
|
130
|
+
best = -float("inf")
|
|
131
|
+
for S in subsets(n, m):
|
|
132
|
+
targets = G[:, list(S)]
|
|
133
|
+
minima = np.full(m, np.inf)
|
|
134
|
+
found = False
|
|
135
|
+
for I in subsets(complement_indices(n, S), k):
|
|
136
|
+
lu = factor_columns(G, I, tol, scale)
|
|
137
|
+
if lu.rank != k:
|
|
138
|
+
continue
|
|
139
|
+
coefficients = lu.solve(targets)
|
|
140
|
+
minima = np.minimum(minima, np.sum(np.abs(coefficients), axis=0))
|
|
141
|
+
found = True
|
|
142
|
+
if not found:
|
|
143
|
+
raise RuntimeError("No invertible I subset of S^c was found.")
|
|
144
|
+
# Each target has its own minimum: max_i min_I, not min_I max_i.
|
|
145
|
+
best = max(best, float(np.max(minima)))
|
|
146
|
+
return best
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def h_m_roth_dual_combinatorial_parity(H, m, tol=1e-10):
|
|
150
|
+
"""Evaluate the dual formula from a parity-check matrix."""
|
|
151
|
+
H = validate_parity_check_matrix(H, tol)
|
|
152
|
+
r, n = H.shape
|
|
153
|
+
m = validate_m_for_columns(m, n)
|
|
154
|
+
if m == 0:
|
|
155
|
+
return 1.0
|
|
156
|
+
if not parity_check_minimum_distance_exceeds_validated(H, m, tol):
|
|
157
|
+
return float("inf")
|
|
158
|
+
scale = matrix_scale(H)
|
|
159
|
+
best = -float("inf")
|
|
160
|
+
for S in subsets(n, m):
|
|
161
|
+
minima = np.full(m, np.inf)
|
|
162
|
+
found = False
|
|
163
|
+
for extra in subsets(complement_indices(n, S), r - m):
|
|
164
|
+
J = sorted((*S, *extra))
|
|
165
|
+
lu = factor_columns(H, J, tol, scale)
|
|
166
|
+
if lu.rank != r:
|
|
167
|
+
continue
|
|
168
|
+
coefficients = lu.solve(H[:, complement_indices(n, J)])
|
|
169
|
+
positions = np.searchsorted(J, S)
|
|
170
|
+
row_norms = np.sum(np.abs(coefficients[positions]), axis=1)
|
|
171
|
+
minima = np.minimum(minima, row_norms)
|
|
172
|
+
found = True
|
|
173
|
+
if not found:
|
|
174
|
+
raise RuntimeError("No invertible J superset of S was found.")
|
|
175
|
+
best = max(best, float(np.max(minima)))
|
|
176
|
+
return best
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Roth's primal and dual LP enumerations using SciPy."""
|
|
2
|
+
|
|
3
|
+
from itertools import combinations
|
|
4
|
+
from math import inf
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from ._lp_solver import solve_lp
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _roth_lp(G, m, early_quit_threshold, *, primal):
|
|
12
|
+
if m == 0:
|
|
13
|
+
return float(min(1.0, early_quit_threshold))
|
|
14
|
+
k, n = G.shape
|
|
15
|
+
q = n - m
|
|
16
|
+
A = np.empty((2 * q, k) if primal else (k, 2 * q))
|
|
17
|
+
ones = np.ones(2 * q)
|
|
18
|
+
best = -inf
|
|
19
|
+
|
|
20
|
+
for S in combinations(range(n), m):
|
|
21
|
+
selected = set(S)
|
|
22
|
+
complement = [j for j in range(n) if j not in selected]
|
|
23
|
+
if primal:
|
|
24
|
+
# -1 <= u*g_j <= 1 for every j outside S.
|
|
25
|
+
A[::2] = G[:, complement].T
|
|
26
|
+
A[1::2] = -A[::2]
|
|
27
|
+
else:
|
|
28
|
+
# G_complement * (y-z) = g_i, with y,z >= 0.
|
|
29
|
+
A[:, :q] = G[:, complement]
|
|
30
|
+
A[:, q:] = -A[:, :q]
|
|
31
|
+
for i in S:
|
|
32
|
+
if primal:
|
|
33
|
+
result = solve_lp(G[:, i], A_ub=A, b_ub=ones, maximize=True)
|
|
34
|
+
else:
|
|
35
|
+
result = solve_lp(ones, A_eq=A, b_eq=G[:, i], nonnegative=True)
|
|
36
|
+
if result.status == "optimal":
|
|
37
|
+
best = max(best, result.value)
|
|
38
|
+
elif (primal and result.status == "unbounded") or (
|
|
39
|
+
not primal and result.status == "infeasible"
|
|
40
|
+
):
|
|
41
|
+
return float(early_quit_threshold)
|
|
42
|
+
else:
|
|
43
|
+
raise RuntimeError(f"Unexpected {result.status} Roth {'primal' if primal else 'dual'} LP.")
|
|
44
|
+
# Only a completed inner minimization certifies a dual value.
|
|
45
|
+
if best > early_quit_threshold:
|
|
46
|
+
return float(early_quit_threshold)
|
|
47
|
+
return float(min(best, early_quit_threshold))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def h_m_roth_primal_lp(G, m, early_quit_threshold=inf):
|
|
51
|
+
"""Evaluate Roth's primal LP enumeration, with an optional height cap."""
|
|
52
|
+
return _roth_lp(G, m, early_quit_threshold, primal=True)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def h_m_roth_dual_lp(G, m, early_quit_threshold=inf):
|
|
56
|
+
"""Evaluate Roth's dual LP enumeration, with an optional height cap."""
|
|
57
|
+
return _roth_lp(G, m, early_quit_threshold, primal=False)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Roth's MDS specialization for generator and parity-check matrices."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from ._linalg import (
|
|
6
|
+
factor_columns,
|
|
7
|
+
generator_minimum_distance_exceeds_validated,
|
|
8
|
+
matrix_scale,
|
|
9
|
+
parity_check_minimum_distance_exceeds_validated,
|
|
10
|
+
validate_generator_matrix,
|
|
11
|
+
validate_m_for_columns,
|
|
12
|
+
validate_parity_check_matrix,
|
|
13
|
+
)
|
|
14
|
+
from ._utils import complement_indices, subsets
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _mds_height(matrix, m, tol, parity):
|
|
18
|
+
matrix = (validate_parity_check_matrix if parity else validate_generator_matrix)(matrix, tol)
|
|
19
|
+
n = matrix.shape[1]
|
|
20
|
+
m = validate_m_for_columns(m, n)
|
|
21
|
+
redundancy = matrix.shape[0] if parity else n - matrix.shape[0]
|
|
22
|
+
if m != redundancy:
|
|
23
|
+
raise ValueError("MDS form requires m equal to the code redundancy.")
|
|
24
|
+
# Preserve the historical native MDS convention. General methods return
|
|
25
|
+
# h_0 = 1; the specialized MDS routine returns 0 for zero redundancy.
|
|
26
|
+
if redundancy == 0:
|
|
27
|
+
return 0.0
|
|
28
|
+
distance_exceeds = (parity_check_minimum_distance_exceeds_validated if parity
|
|
29
|
+
else generator_minimum_distance_exceeds_validated)
|
|
30
|
+
if not distance_exceeds(matrix, redundancy, tol):
|
|
31
|
+
raise ValueError("The matrix must define an MDS code.")
|
|
32
|
+
scale = matrix_scale(matrix)
|
|
33
|
+
best = -float("inf")
|
|
34
|
+
for S in subsets(n, redundancy):
|
|
35
|
+
Sc = complement_indices(n, S)
|
|
36
|
+
basis, targets = (S, Sc) if parity else (Sc, S)
|
|
37
|
+
lu = factor_columns(matrix, basis, tol, scale)
|
|
38
|
+
coefficients = lu.solve(matrix[:, list(targets)])
|
|
39
|
+
value = float(np.max(np.sum(np.abs(coefficients), axis=1 if parity else 0)))
|
|
40
|
+
best = max(best, value)
|
|
41
|
+
return best
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def h_m_roth_mds_combinatorial(G, m, tol=1e-10):
|
|
45
|
+
"""Return the redundancy-height of an MDS generator matrix."""
|
|
46
|
+
return _mds_height(G, m, tol, False)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def h_m_roth_mds_combinatorial_parity(H, m, tol=1e-10):
|
|
50
|
+
"""Return the redundancy-height of an MDS parity-check matrix."""
|
|
51
|
+
return _mds_height(H, m, tol, True)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: analog-ecc-heights
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Height calculations for analog error-correcting codes
|
|
5
|
+
Author-Email: Changcheng Yuan <eric.yuan.cc@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: C++
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
12
|
+
Project-URL: Repository, https://github.com/EricYJA/Analog-ECC-height-profile-methods
|
|
13
|
+
Project-URL: Issues, https://github.com/EricYJA/Analog-ECC-height-profile-methods/issues
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: numpy>=1.23
|
|
16
|
+
Requires-Dist: scipy>=1.9
|
|
17
|
+
Provides-Extra: test
|
|
18
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
21
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
22
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# analog-ecc-heights
|
|
26
|
+
|
|
27
|
+
Python and C++ methods for computing the height profile of analog error-correcting codes, including Jiang's LP formulations and Roth's LP and combinatorial formulations. The distribution is **`analog-ecc-heights`**; the Python import is **`analog_ecc_heights`**.
|
|
28
|
+
|
|
29
|
+
One package provides a NumPy/SciPy implementation by default and optional native backends. Installing native support does not change the default backend.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
Requires Python 3.10 or later. Pip installs NumPy >=1.23 and SciPy >=1.9 automatically. With Python and Git installed, start from a fresh checkout:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
git clone https://github.com/EricYJA/Analog-ECC-height-profile-methods.git
|
|
37
|
+
cd Analog-ECC-height-profile-methods
|
|
38
|
+
python -m venv .venv
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
If your Python command is `python3` or `py`, use it to create the environment. Activate it using the command for your shell:
|
|
42
|
+
|
|
43
|
+
| Platform / shell | Activation command |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| Linux or macOS / Bash or Zsh | `source .venv/bin/activate` |
|
|
46
|
+
| Windows / PowerShell | `.\.venv\Scripts\Activate.ps1` |
|
|
47
|
+
| Windows / Command Prompt | `.venv\Scripts\activate.bat` |
|
|
48
|
+
|
|
49
|
+
Then install into the active environment:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
python -m pip install .
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
An existing Python environment also works. See [environment setup](docs/installation.md#choose-a-python-environment) for details and the optional Conda workflow.
|
|
56
|
+
|
|
57
|
+
The default installation does not invoke CMake or require a compiler, Eigen, GLPK, or a separately installed HiGHS library. Native support is an optional source build of this same distribution; see [installation](docs/installation.md).
|
|
58
|
+
|
|
59
|
+
## Use
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import numpy as np
|
|
63
|
+
from analog_ecc_heights import (
|
|
64
|
+
available_backends,
|
|
65
|
+
h_m_roth_primal_lp,
|
|
66
|
+
h_m_roth_primal_combinatorial,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
G = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]])
|
|
70
|
+
|
|
71
|
+
print(h_m_roth_primal_lp(G, 1)) # 2.0
|
|
72
|
+
print(h_m_roth_primal_lp(G, 1, early_quit_threshold=1.5)) # 1.5
|
|
73
|
+
print(h_m_roth_primal_combinatorial(G)) # [2.0]
|
|
74
|
+
print(available_backends()) # ["python"] in a default install
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
For a native-enabled installation, select the implementation explicitly:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
h_m_roth_primal_lp(G, 1, backend="cpp-glpk")
|
|
81
|
+
h_m_roth_primal_lp(G, 1, backend="cpp-highs", num_threads=1)
|
|
82
|
+
h_m_roth_primal_combinatorial(G, 1, backend="cpp", num_threads=1)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
| Backend | Methods | Separately installed native dependencies |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `python` | LP and combinatorial | None; LP uses the HiGHS solver included with SciPy |
|
|
88
|
+
| `cpp` | Combinatorial | Eigen headers at build time; OpenMP |
|
|
89
|
+
| `cpp-glpk` | LP | Eigen headers at build time; GLPK headers and library |
|
|
90
|
+
| `cpp-highs` | LP | Eigen headers at build time; HiGHS headers and library; OpenMP |
|
|
91
|
+
|
|
92
|
+
An unavailable backend raises an installation error. Unsupported combinations raise an argument error. Calls never switch to another backend automatically.
|
|
93
|
+
|
|
94
|
+
## Documentation and examples
|
|
95
|
+
|
|
96
|
+
- [Installation and native builds](docs/installation.md)
|
|
97
|
+
- [API, backend selection, and numerical behavior](docs/api.md)
|
|
98
|
+
- Runnable examples: [basic usage](examples/basic_usage.py), [height profiles](examples/height_profile.py), and [backend comparison](examples/compare_backends.py)
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
Licensed under the [MIT License](https://github.com/EricYJA/Analog-ECC-height-profile-methods/blob/main/LICENSE).
|
|
103
|
+
Copyright (c) 2026 Changcheng Yuan.
|
|
104
|
+
|
|
105
|
+
## References
|
|
106
|
+
|
|
107
|
+
All implementations are based on the methods and theorems developed in these papers:
|
|
108
|
+
|
|
109
|
+
1. Ron M. Roth, “[Analog Error-Correcting Codes](https://doi.org/10.1109/TIT.2020.2977918),” *IEEE Transactions on Information Theory*, 66(7), 4075–4088, 2020.
|
|
110
|
+
2. Anxiao Jiang, “[Analog Error-Correcting Codes: Designs and Analysis](https://doi.org/10.1109/TIT.2024.3454059),” *IEEE Transactions on Information Theory*, 70(11), 7740–7756, 2024.
|
|
111
|
+
3. Ron M. Roth, Ziyuan Zhu, Changcheng Yuan, Paul H. Siegel, and Anxiao Jiang, “[On the Height Profile of Analog Error-Correcting Codes](https://arxiv.org/abs/2602.20366),” *2026 IEEE International Symposium on Information Theory (ISIT)*, also available as arXiv:2602.20366.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
analog_ecc_heights/__init__.py,sha256=Grh74dRUY3apk_li5XMJ4ZatTPYFo4age6Stv0oeCeg,1062
|
|
2
|
+
analog_ecc_heights/_dispatch.py,sha256=kJ3H926LHFaa-ysKy6QJ3VJ26-487ejox_PJ9uOPNgE,2067
|
|
3
|
+
analog_ecc_heights/_validation.py,sha256=LepND3sy9KcRC9GUT5rfgGQOLjL6N-amIx7lzr3EcQo,2343
|
|
4
|
+
analog_ecc_heights/combinatorial.py,sha256=K8fauWzqDRGufZlT_EyIupBrRHObopq2YUvm0Afmfb4,2813
|
|
5
|
+
analog_ecc_heights/cpp_backend/__init__.py,sha256=52mYQiR8ULULeMu32zWl3BeM2Vi3g2svZTz5OWLsa3c,63
|
|
6
|
+
analog_ecc_heights/cpp_backend/adapter.py,sha256=X5eqQmMugeAXhhfyYgjrI9_L9n9TV7W9wBlmutA6lLQ,2108
|
|
7
|
+
analog_ecc_heights/lp.py,sha256=YNr_Qupvhbj-zzdfPV8FBQjjbYHnCTWl_c-fV42Cd4I,2425
|
|
8
|
+
analog_ecc_heights/py_backend/__init__.py,sha256=Pz6I-j18U9XtrksidgcBcLC-jiJLkyPadsgdTCc7t0c,78
|
|
9
|
+
analog_ecc_heights/py_backend/_linalg.py,sha256=0g_pOxaUtJeVSR3_tLTymy_RBmmvr5SJvXCBi5q1Wg4,6453
|
|
10
|
+
analog_ecc_heights/py_backend/_lp_solver.py,sha256=yfHbfKJxzdAAktyW7MLt3KH-4lumqyDf3f3ReOzM1qs,2327
|
|
11
|
+
analog_ecc_heights/py_backend/_utils.py,sha256=hST2ytRt-1vTuWrTF2-JLXg5_Cf2gksfpSJ5So6xd9s,846
|
|
12
|
+
analog_ecc_heights/py_backend/jiang_lp.py,sha256=p_ryoUApLJpDeimzzcAApu4Wim1JmcxCBDViDmA_5L4,3413
|
|
13
|
+
analog_ecc_heights/py_backend/roth_comb.py,sha256=Qh0VpMLR8UxG7hDdiYvHUg0XujWTCgQx8U7n6VNlmt8,6114
|
|
14
|
+
analog_ecc_heights/py_backend/roth_lp.py,sha256=myE4_L7k6XmfPkh6i_ZFFR5cNK58zf-XimQHULfpM48,2075
|
|
15
|
+
analog_ecc_heights/py_backend/roth_mds_comb.py,sha256=KQC9qzvG_tza_2bwP7ztPhQFt1AikPFlB00A9LSp8L8,2003
|
|
16
|
+
solve_m_height_cpp.py,sha256=VSgAJG9NOsrKY-4K6EC0u9NSf6HC3lDBlKRNbNq_i68,1379
|
|
17
|
+
analog_ecc_heights-0.1.0.dist-info/METADATA,sha256=YAEjPipFm9THKVLp-Z0YSLGrhlSGJbKa1tcb-gq8CnU,5030
|
|
18
|
+
analog_ecc_heights-0.1.0.dist-info/WHEEL,sha256=DJBbB-IMWy7eyPvSdm5L2t-BbrULtweJWf0YC-blkl0,95
|
|
19
|
+
analog_ecc_heights-0.1.0.dist-info/licenses/LICENSE,sha256=oOMt3OGm9P0fEWk8I-iyLkkyAiYciAfH5Osh5u-YzUs,1072
|
|
20
|
+
analog_ecc_heights-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Changcheng Yuan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
solve_m_height_cpp.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Lazy compatibility access to the original native function names."""
|
|
2
|
+
|
|
3
|
+
from analog_ecc_heights.cpp_backend.adapter import load_native as _load_native
|
|
4
|
+
|
|
5
|
+
_SYMBOLS = {
|
|
6
|
+
"cpp": (
|
|
7
|
+
"h_m_roth_primal_combinatorial", "h_m_roth_primal_combinatorial_pruning",
|
|
8
|
+
"h_m_roth_dual_combinatorial_generator", "h_m_roth_dual_combinatorial_parity",
|
|
9
|
+
"h_m_roth_mds_combinatorial", "h_m_roth_mds_combinatorial_parity",
|
|
10
|
+
),
|
|
11
|
+
}
|
|
12
|
+
for _solver in ("glpk", "highs"):
|
|
13
|
+
_SYMBOLS[f"cpp-{_solver}"] = (
|
|
14
|
+
f"h_m_jiang_original_lp_{_solver}",
|
|
15
|
+
f"h_m_jiang_simplified_lp_{_solver}_early_quit",
|
|
16
|
+
f"h_m_roth_primal_lp_{_solver}", f"h_m_roth_dual_lp_{_solver}",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def __getattr__(name):
|
|
21
|
+
if name == "__all__":
|
|
22
|
+
return __dir__()
|
|
23
|
+
for backend, symbols in _SYMBOLS.items():
|
|
24
|
+
if name in symbols:
|
|
25
|
+
try:
|
|
26
|
+
return getattr(_load_native(backend), name)
|
|
27
|
+
except ImportError as exc:
|
|
28
|
+
raise AttributeError(f"{name} is unavailable: {exc}") from exc
|
|
29
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def __dir__():
|
|
33
|
+
names = []
|
|
34
|
+
for backend, symbols in _SYMBOLS.items():
|
|
35
|
+
try:
|
|
36
|
+
native = _load_native(backend)
|
|
37
|
+
except ImportError:
|
|
38
|
+
continue
|
|
39
|
+
names.extend(name for name in symbols if hasattr(native, name))
|
|
40
|
+
return sorted(names)
|