Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ Some searches are expensive, some bounds are heuristic, experimental APIs can ch
Fault-tolerant encoding is tracked in [issue #327](https://github.com/qLDPCOrg/qLDPC/issues/327).
- Exact distance calculations, fault-tolerance certificates, and transversal-gate searches can take exponential time.
When a method returns a bound rather than an exact distance, its docstring explains what kind of bound it is.
- Features that use GAP may start subprocesses, access online resources, or ask for manual input or permission to install a package.
- Features that use GAP or MAGMA may start subprocesses, access online resources, or ask for manual input or permission to install a package.
- Code lookups such as `QuditCode.from_qecdb_id` access online resources and cache results on disk; pass `refresh=True` to fetch the latest data.
- Everything under `qldpc.experimental` has an unstable public API and may change without deprecation.
- Lattice-surgery support in `qldpc.experimental.surgery` is experimental and unstable, and its implementation is still pending careful expert review.
Expand Down
11 changes: 11 additions & 0 deletions docs/source/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ Choose tools for the task
- :ref:`Additional decoders <installation-decoders>`.
* - Use algebra tools, named-code lookups, or distance estimates that require GAP
- :ref:`GAP integration <installation-gap>`.
* - Compute permutation automorphism groups or transversal gates with MAGMA
- :ref:`MAGMA integration <installation-magma>`.
* - Find symmetries of parity check matrices, as for some balanced product codes, or to speed up exact distances of symmetric codes
- :ref:`Matrix automorphisms <installation-bliss>`.
* - Estimate binary CSS code distances with the GPU-based ``sqetch`` backend
Expand Down Expand Up @@ -106,6 +108,15 @@ The installer's ``gap.bat`` does not meet these requirements, since it ignores i
Without such a command, use the manual fallback with the GAP console that the installer provides.
See `issue #294 <https://github.com/qLDPCOrg/qLDPC/issues/294>`_ for the status of Windows support.

.. _installation-magma:

MAGMA integration
-----------------

Permutation automorphism groups and transversal-gate searches can use `MAGMA <https://magma.maths.usyd.edu.au>`_, a commercial computer algebra system, instead of GAP when called with ``with_magma=True``.
qLDPC runs a licensed ``magma`` executable on ``PATH`` if it finds one, and otherwise offers a manual copy/paste workflow.
See the :doc:`library map <library_map>` for MAGMA calls, prompts, and caching.

.. _installation-bliss:

Matrix automorphisms
Expand Down
14 changes: 13 additions & 1 deletion docs/source/library_map.rst
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ Other limitations:

* Circuit and tableau tools work only with qubit codes, and memory experiments for non-CSS codes need ``basis=None``.
* :func:`~qldpc.circuits.encoding.get_encoding_circuit` builds a valid encoder that is not fault-tolerant.
* Transversal-gate searches enumerate code automorphisms, can take exponential time, and may run GAP or prompt on standard input.
* Transversal-gate searches enumerate code automorphisms, can take exponential time, and may run GAP or MAGMA, or prompt on standard input.
* Windowed decoders such as :class:`~qldpc.decoders.sinter.window.SlidingWindowDecoder` infer each detector's time from its coordinates by a heuristic; pass ``detector_to_time`` when a detector error model uses another convention.

What qLDPC computes exactly, bounds, and trusts
Expand Down Expand Up @@ -298,6 +298,18 @@ When qLDPC runs GAP as a separate program, it clones the package with Git into q

Functions that can use GAP include :meth:`ClassicalCode.from_name <qldpc.codes.common.ClassicalCode.from_name>`, :meth:`ClassicalCode.get_permutation_automorphism_group <qldpc.codes.common.ClassicalCode.get_permutation_automorphism_group>`, :meth:`abstract.Group.from_name <qldpc.abstract.groups.Group.from_name>`, distance bounds with the GAP backend, and transversal-gate searches such as :func:`~qldpc.circuits.transversal.get_transversal_ops`.

MAGMA
~~~~~

Permutation automorphism groups and transversal-gate searches use MAGMA instead of GAP when called with ``with_magma=True``, as does ``Group.from_name`` with ``from_magma=True``.
These calls never fall back to GAP, and calls without these arguments never run MAGMA, so the result of a call does not depend on which of GAP and MAGMA is installed.
If a ``magma`` executable is on ``PATH`` and a test run of it succeeds, qLDPC runs it in a subprocess, without the user's startup file.
If the test run fails, qLDPC warns.
Without a working ``magma``, qLDPC prints the MAGMA command, copies it to the system clipboard, and reads MAGMA's output from standard input.
The generators that MAGMA returns can depend on its random seed, so both the subprocess and the manual workflow start the command by fixing the seed.
An error that MAGMA reports raises a ``ValueError``; if MAGMA stops for another reason, such as a crash, qLDPC warns and falls back to the manual workflow.
qLDPC caches MAGMA's results on disk.

Code and group lookups
~~~~~~~~~~~~~~~~~~~~~~

Expand Down
27 changes: 19 additions & 8 deletions src/qldpc/abstract/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,14 +631,25 @@ def from_name(
If ``from_magma=True``, retrieve the group from the MAGMA CAS instead of GAP.

A GAP group is retrieved from a small local database if possible, else from GAP if GAP can
be called without user interaction, else from GroupNames.org (for a SmallGroup), and
finally by a manual workflow. Before falling back to the manual workflow, qLDPC asks on
standard input whether GAP is available for copy/paste. The manual workflow prints GAP
commands, copies them to the system clipboard, and reads the output that the user pastes
into standard input. It blocks, and raises EOFError if standard input is closed. Calling
GAP may install the GAP GUAVA package, after asking for consent on standard input, and
raises the warning warning_to_raise_if_calling_gap, if provided. A MAGMA group is always
retrieved by such a manual copy/paste workflow. Retrieved generators are cached to disk.
be called without user interaction, else from GroupNames.org (for a SmallGroup), and finally
by a manual workflow. Before falling back to the manual workflow, qLDPC asks on standard
input whether GAP is available for copy/paste. The manual workflow prints GAP commands,
copies them to the system clipboard, and reads the output that the user pastes into standard
input. It blocks, and raises EOFError if standard input is closed. Before calling GAP or
asking whether it is available, qLDPC raises the warning warning_to_raise_if_calling_gap, if
provided. Calling GAP may install the GAP GUAVA package, after asking for consent on
standard input.

A MAGMA group is retrieved from a local disk cache if possible, else from MAGMA if MAGMA can
be called from the command line, and otherwise by a manual copy/paste workflow like that for
GAP. qLDPC runs MAGMA without the user's startup file. If a ``magma`` executable on
``PATH`` fails a test run, qLDPC warns and uses the manual workflow. The generators that
MAGMA returns can depend on its random seed, so both the MAGMA subprocess and the manual
workflow start the command by fixing the seed. If MAGMA reports an error, qLDPC raises a
ValueError. If MAGMA stops for another reason, such as a crash, qLDPC warns and falls back
to the manual workflow.

Retrieved generators are cached to disk.
"""
from qldpc.external import _groups # avoid circular import

Expand Down
14 changes: 7 additions & 7 deletions src/qldpc/circuits/transversal.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ def get_transversal_ops(
gate, and (b) changing the code that encodes the logical state to
``code.deformed(physical_circuit, preserve_logicals=True)``.

This function constructs a transversal automorphism group, which may run GAP or prompt on
standard input; see help(get_transversal_automorphism_group).
This function constructs a transversal automorphism group, which may run GAP or MAGMA, or
prompt on standard input; see help(get_transversal_automorphism_group).

Uses the methods of https://arxiv.org/abs/2409.18175.
"""
Expand Down Expand Up @@ -159,7 +159,7 @@ def get_transversal_automorphism_group(
``code.deformed(physical_circuit, preserve_logicals=True)``.

Constructing this group computes the permutation automorphism group of a classical code, which
may run GAP or prompt on standard input; see
may run GAP or MAGMA, or prompt on standard input; see
help(qldpc.codes.ClassicalCode.get_permutation_automorphism_group).

Uses the methods of https://arxiv.org/abs/2409.18175.
Expand Down Expand Up @@ -285,8 +285,8 @@ def get_transversal_circuits(
gate, and (b) changing the code that encodes the logical state to
``code.deformed(physical_circuit, preserve_logicals=True)``.

This function constructs a transversal automorphism group, which may run GAP or prompt on
standard input; see help(get_transversal_automorphism_group).
This function constructs a transversal automorphism group, which may run GAP or MAGMA, or
prompt on standard input; see help(get_transversal_automorphism_group).

.. warning::
This method performs a brute-force search over the Clifford automorphisms of a code, and
Expand Down Expand Up @@ -373,8 +373,8 @@ def get_transversal_circuit(
gate, and (b) changing the code that encodes the logical state to
``code.deformed(physical_circuit, preserve_logicals=True)``.

This function constructs a transversal automorphism group, which may run GAP or prompt on
standard input; see help(get_transversal_automorphism_group).
This function constructs a transversal automorphism group, which may run GAP or MAGMA, or
prompt on standard input; see help(get_transversal_automorphism_group).

.. warning::
This method performs a brute-force search over the Clifford automorphisms of a code, and
Expand Down
12 changes: 9 additions & 3 deletions src/qldpc/codes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from qldpc._utils import format_docstring, get_external_caller_stacklevel
from qldpc.decoders._capabilities import is_prebuilt_decoder, is_prebuilt_observable_decoder
from qldpc.decoders._resolution import build_error_decoder, reject_prebuilt_decoder
from qldpc.external import _bliss, _codes
from qldpc.external import _bliss, _codes, _magma
from qldpc.math import IntegerArray, resolve_field
from qldpc.objects import (
PAULIS_XZ,
Expand Down Expand Up @@ -847,8 +847,9 @@ def get_permutation_automorphism_group(self, *, with_magma: bool = False) -> abs
contains maps that multiply bits by nonzero field elements.

This computation may run GAP, install GAP packages, access GroupNames.org, or prompt on
standard input, or with ``with_magma=True`` prompt for MAGMA output on standard input; see
help(qldpc.abstract.Group.from_name).
standard input. With ``with_magma=True``, it uses only MAGMA: it runs MAGMA if MAGMA can be
called from the command line, and otherwise prompts for MAGMA output on standard input. An
error that MAGMA reports raises a ValueError. See help(qldpc.abstract.Group.from_name).
"""
matrix = self.canonicalized.matrix.view(np.ndarray)

Expand All @@ -873,6 +874,11 @@ def get_matrix_str(elements: Sequence[str]) -> str:
" time. If this calculation takes too long, try computing the group with MAGMA by"
' passing the argument "with_magma=True" to the method that needs to compute the group.'
)
if _magma.is_on_path() and not external.gap.is_callable():
warning += (
" GAP cannot be called from the command line here, but a MAGMA executable is on"
" PATH, so MAGMA may compute the group without copying commands by hand."
)

gap_elements = (
[str(value) for value in range(self.field.order)]
Expand Down
43 changes: 38 additions & 5 deletions src/qldpc/codes/common_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,15 +359,22 @@ def test_permutation_automorphism_group(
code: codes.ClassicalCode = codes.HammingCode(2, field=2)
automorphisms = "\n(1,2)\n(2,3)\n"

# raise an error when GAP is not installed
# when GAP cannot be called but a magma executable is on PATH, warn with a hint to use MAGMA
# before asking whether GAP is available, and raise an error when the user declines
def decline_gap() -> bool:
assert any("MAGMA executable is on PATH" in str(record.message) for record in records)
return False

external.gap.require_package.cache_clear()
with (
unittest.mock.patch("qldpc.external.gap.is_callable", return_value=False),
unittest.mock.patch("qldpc.external.gap.is_installed", return_value=False),
unittest.mock.patch("qldpc.external.gap.is_installed", side_effect=decline_gap),
unittest.mock.patch(
"qldpc.external.gap.subprocess.run",
side_effect=AssertionError("GAP executable must not be called by this test"),
),
unittest.mock.patch("qldpc.external._magma.is_on_path", return_value=True),
pytest.warns(UserWarning, match="MAGMA executable is on PATH") as records,
pytest.raises(ValueError, match="Cannot build GAP group"),
):
codes.RepetitionCode(2).get_permutation_automorphism_group()
Expand All @@ -380,7 +387,8 @@ def test_permutation_automorphism_group(
"qldpc.external.gap.subprocess.run",
side_effect=AssertionError("GAP executable must not be called by this test"),
),
pytest.warns(UserWarning, match="with_magma=True"),
unittest.mock.patch("qldpc.external._magma.is_on_path", return_value=True),
pytest.warns(UserWarning, match="with_magma=True") as records,
):
for code, automorphisms in [
(codes.HammingCode(2, field=2), "\n(1,2)\n(2,3)\n"),
Expand Down Expand Up @@ -410,6 +418,28 @@ def get_output(*commands: str) -> str:
query = "".join("".join(get_output.call_args.args).split())
rows = "[Z(4)^0,0*Z(4),Z(4)^0,Z(4)^1,Z(4)^2],[0*Z(4),Z(4)^0,Z(4)^0,Z(4)^0,Z(4)^0]"
assert f"PermutationAutomorphismGroup(CheckMatCode([{rows}],GF(4)))" in query
# when GAP can be called from the command line, the warning does not say that it cannot
assert not any("MAGMA executable is on PATH" in str(record.message) for record in records)

# if GAP needs copying commands by hand, the warning says whether MAGMA is on PATH, and the
# default path still computes with GAP and never runs MAGMA
for magma_on_path in [True, False]:
with (
unittest.mock.patch("qldpc.external.gap.is_callable", return_value=False),
unittest.mock.patch("qldpc.external.gap.is_installed", return_value=True),
unittest.mock.patch("qldpc.external.gap.require_package", return_value=True),
unittest.mock.patch("qldpc.external.gap.get_output", return_value="\n(1,2)\n"),
unittest.mock.patch("qldpc.external._magma.is_on_path", return_value=magma_on_path),
unittest.mock.patch(
"qldpc.external._magma.get_output", side_effect=AssertionError("must not run MAGMA")
),
pytest.warns(UserWarning, match="with_magma=True") as records,
):
assert codes.RepetitionCode(2).get_permutation_automorphism_group().order == 2
messages = [str(record.message) for record in records]
assert (
any("MAGMA executable is on PATH" in message for message in messages) == magma_on_path
)

# compute a permutation automorphism group with MAGMA, asking it for the PermutationGroup of the
# code rather than its AutomorphismGroup, whose members also scale nonbinary coordinates
Expand All @@ -420,7 +450,8 @@ def get_output(*commands: str) -> str:
code = codes.RepetitionCode(2)
group = abstract.CyclicGroup(2)
assert code.get_permutation_automorphism_group(with_magma=True).equiv(group)
assert "\nPermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));\n" in capsys.readouterr().out
query = "\nSetSeed(1); PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));\n"
assert query in capsys.readouterr().out

# MAGMA maps integers into GF(8) through the prime field, so the query defines GF(8) by the
# irreducible polynomial x^3 + x^2 + 1 of the galois field, listing its coefficients constant
Expand All @@ -431,7 +462,9 @@ def get_output(*commands: str) -> str:
assert code.get_permutation_automorphism_group(with_magma=True).order == 1
field = "F<w>:=ext<GF(2)|Polynomial(GF(2),[1,0,1,1])>;"
matrix = "Matrix(F,1,3,[[1,w,w+w^2]])"
assert f"\n{field}PermutationGroup(LinearCode({matrix}));\n" in capsys.readouterr().out
assert (
f"\nSetSeed(1); {field}PermutationGroup(LinearCode({matrix}));\n" in capsys.readouterr().out
)


def test_matrix_automorphism_group() -> None:
Expand Down
15 changes: 15 additions & 0 deletions src/qldpc/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import pytest

from qldpc import _compilation, abstract, external
from qldpc.external import _magma

# A comment that lets an import break the layering rule of check_import_layering.
_LAYERING_EXCEPTION = re.compile(r"#\s*layering-exception:\s*\S")
Expand Down Expand Up @@ -106,6 +107,20 @@ def block_clipboard(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("pyperclip.copy", lambda text: None)


@pytest.fixture(autouse=True)
def block_local_magma(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""Keep tests from running a MAGMA executable that is installed on the machine.

Tests that need MAGMA mock it, since CI has no MAGMA. The availability probe is cached for the
process, so this fixture clears it around every test.
"""
monkeypatch.setattr(_magma, "is_on_path", lambda: False)
is_callable = _magma.is_callable # tests may replace this function
is_callable.cache_clear()
yield
is_callable.cache_clear()


@pytest.fixture(autouse=True, scope="session")
def vary_default_transformer_seed(pytestconfig: pytest.Config) -> Iterator[None]:
"""Build seedless Wedderburn-Artin decompositions from the seed of the test run.
Expand Down
Loading