diff --git a/README.md b/README.md index 8a7bb2a64..7fd963c5a 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/source/installation.rst b/docs/source/installation.rst index 60d2af606..655f0ac99 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -38,6 +38,8 @@ Choose tools for the task - :ref:`Additional decoders `. * - Use algebra tools, named-code lookups, or distance estimates that require GAP - :ref:`GAP integration `. + * - Compute permutation automorphism groups or transversal gates with MAGMA + - :ref:`MAGMA integration `. * - Find symmetries of parity check matrices, as for some balanced product codes, or to speed up exact distances of symmetric codes - :ref:`Matrix automorphisms `. * - Estimate binary CSS code distances with the GPU-based ``sqetch`` backend @@ -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 `_ for the status of Windows support. +.. _installation-magma: + +MAGMA integration +----------------- + +Permutation automorphism groups and transversal-gate searches can use `MAGMA `_, 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 ` for MAGMA calls, prompts, and caching. + .. _installation-bliss: Matrix automorphisms diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index 7af9f8d1f..9f1f64087 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -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 @@ -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 `, :meth:`ClassicalCode.get_permutation_automorphism_group `, :meth:`abstract.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 ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index a74c5af70..472168491 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -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 diff --git a/src/qldpc/circuits/transversal.py b/src/qldpc/circuits/transversal.py index 5e91302d9..311e84c86 100644 --- a/src/qldpc/circuits/transversal.py +++ b/src/qldpc/circuits/transversal.py @@ -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. """ @@ -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. @@ -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 @@ -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 diff --git a/src/qldpc/codes/common.py b/src/qldpc/codes/common.py index ecb30a178..d95b8713c 100644 --- a/src/qldpc/codes/common.py +++ b/src/qldpc/codes/common.py @@ -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, @@ -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) @@ -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)] diff --git a/src/qldpc/codes/common_test.py b/src/qldpc/codes/common_test.py index 4091eadbf..6e1877f97 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -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() @@ -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"), @@ -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 @@ -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 @@ -431,7 +462,9 @@ def get_output(*commands: str) -> str: assert code.get_permutation_automorphism_group(with_magma=True).order == 1 field = "F:=ext;" 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: diff --git a/src/qldpc/conftest.py b/src/qldpc/conftest.py index f8acd0af6..c22ba18ef 100644 --- a/src/qldpc/conftest.py +++ b/src/qldpc/conftest.py @@ -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") @@ -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. diff --git a/src/qldpc/external/_groups.py b/src/qldpc/external/_groups.py index 64a1435a7..0c807abf1 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -20,12 +20,17 @@ import qldpc.external.gap from qldpc import _deprecations from qldpc._utils import get_external_caller_stacklevel +from qldpc.external import _magma _GeneratorsList = list[list[tuple[int, ...]]] _Idempotents = tuple[tuple[tuple[int, tuple[tuple[int, ...], ...]], ...], ...] _GROUPNAMES_URL = "https://people.maths.bris.ac.uk/~matyd/GroupNames/" +# MAGMA's generators of a group can depend on its random seed, so both the MAGMA subprocess and the +# manual workflow fix the seed +_MAGMA_SEED = 1 + #################################################################################################### # group generators @@ -80,20 +85,28 @@ def get_generators( def get_generators_from_magma(group: str) -> _GeneratorsList: """Retrieve group generators from MAGMA. - This function uses a manual copy/paste workflow that prints the command, copies it to the system - clipboard, and reads the pasted output from standard input (blocking, and raising ``EOFError`` - if standard input is closed). + This function tries a local disk cache, then MAGMA if it can be called from the command line, + and finally a manual copy/paste workflow. The manual workflow prints the command, copies it to + the system clipboard, and reads the pasted output from standard input (blocking, and raising + ``EOFError`` if standard input is closed). 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, this function raises it. If MAGMA stops for another + reason, such as a crash, this function warns and falls back to the manual workflow. + + Raises: + ValueError: If MAGMA reports an error, such as an error in the command, or its output does + not describe a permutation group. """ - print("Run the following command in MAGMA:") - print() - print(group) - print() - + command = f"SetSeed({_MAGMA_SEED}); {group}" cache_name = "magma_groups" cache = qldpc.cache.get_disk_cache(cache_name) - key = "".join(group.split()) # strip whitespace + key = "".join(command.split()) # strip whitespace if generators := cache.get(key, None): + print("MAGMA command:") + print() + print(command) + print() print( "NOTICE: group found in the local MAGMA group cache." " Retrieved group generators (in cycle notation):" @@ -110,10 +123,28 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: ) return generators + # run MAGMA, if it can be called from the command line + if _magma.is_callable(): + try: + output = _magma.get_output(command) + except _magma.MAGMARunError as error: + warnings.warn( + f"{error}\n\nFalling back to copying commands into MAGMA by hand.", + stacklevel=get_external_caller_stacklevel(), + ) + else: + generators = _parse_magma_generators(output) + cache[key] = generators + return generators + + print("Run the following command in MAGMA:") + print() + print(command) + print() print("===============================================================================") print("NOTE:") try: - pyperclip.copy(group) + pyperclip.copy(command) print("The above command has been copied to your system clipboard.") print("You can paste the command into MAGMA with ctrl+v or cmd+v.") except pyperclip.PyperclipException: # pragma: no cover @@ -131,21 +162,7 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: while line := input(): lines.append(line) - # identify permutations in the output; MAGMA lists no generators of a trivial group - output = "\n".join(lines) - one_cycle_pattern = r"\((?:\d|,\s+)+\)" - permutation_pattern = rf"(?:{one_cycle_pattern})+" - permutations = re.findall(permutation_pattern, output, re.DOTALL) - if not permutations and re.search(r"^\s*Order = 1\s*$", output, re.MULTILINE): - permutations = ["()"] - if not permutations: - raise ValueError("Invalid MAGMA output") - - # remove whitespace (and, in particular, newlines) from every permutation - permutations = [re.sub(r"\s+", "", permutation) for permutation in permutations] - - # compute generators - generators = _parse_gap_permutations("\n".join(permutations)) + generators = _parse_magma_generators("\n".join(lines)) cache[key] = generators return generators @@ -156,16 +173,17 @@ def _maybe_get_generators_from_gap( """Retrieve group generators from GAP, or return None if GAP is not available. Checking whether GAP is available may prompt on standard input; see - help(qldpc.external.gap.is_installed). + help(qldpc.external.gap.is_installed). The given warning, if any, is raised before that check, + so that a user sees it before answering a prompt. """ - if not qldpc.external.gap.is_installed(): - return None - qldpc.external.gap.require_package("GUAVA") - # if provided a warning to raise before calling GAP, raise it now if warning is not None: warnings.warn(warning, stacklevel=get_external_caller_stacklevel()) + if not qldpc.external.gap.is_installed(): + return None + qldpc.external.gap.require_package("GUAVA") + # run GAP commands commands = [ 'LoadPackage("guava", false);;', @@ -216,6 +234,25 @@ def _maybe_get_generators_from_groupnames(group: str) -> _GeneratorsList | None: return _parse_gap_permutations(permutations, cycle_sep=" ") +def _parse_magma_generators(output: str) -> _GeneratorsList: + """Parse the generators of a permutation group from MAGMA's description of the group. + + MAGMA prints each generator in cycle notation, starting on a new line, and lists no generators + of a trivial group, for which this function returns the identity. + """ + # identify the lines that hold only cycles, allowing pasted output to wrap lines after commas + cycle_pattern = r"\(\d+(?:,\s+\d+)*\)" + permutations = re.findall(rf"^[ \t]*((?:{cycle_pattern})+)[ \t]*$", output, re.MULTILINE) + if not permutations and re.search(r"^\s*Order = 1\s*$", output, re.MULTILINE): + permutations = ["()"] + if not permutations: + raise ValueError(f"Invalid MAGMA output:\n{output}") + + # remove whitespace (and, in particular, newlines) from every permutation + permutations = [re.sub(r"\s+", "", permutation) for permutation in permutations] + return _parse_gap_permutations("\n".join(permutations)) + + def _parse_gap_permutations(permutations: str, cycle_sep: str = ",") -> _GeneratorsList: """Parse newline-separated GAP permutations. diff --git a/src/qldpc/external/_groups_test.py b/src/qldpc/external/_groups_test.py index 209a2b2b5..67810845c 100644 --- a/src/qldpc/external/_groups_test.py +++ b/src/qldpc/external/_groups_test.py @@ -10,7 +10,7 @@ import pytest from qldpc import external -from qldpc.external import _groups +from qldpc.external import _groups, _magma # define global testing variables ORDER, INDEX = 2, 1 @@ -231,7 +231,6 @@ def test_get_generators_from_magma( assert _groups.get_generators_from_magma(group) == generators terminal_output, error_message = capsys.readouterr() assert not error_message - assert terminal_output.startswith("Run the following command in MAGMA:") assert "NOTICE: group found in the local MAGMA group cache" in terminal_output # MAGMA lists no generators of a trivial group, for which this function returns the identity @@ -247,6 +246,59 @@ def test_get_generators_from_magma( _groups.get_generators_from_magma(group) capsys.readouterr() # intercept print statements + # parentheses that hold numbers in output that describes no permutation group are not cycles, + # as in this output of the command GL(2,3), recorded from MAGMA V2.29-10 + with pytest.raises(ValueError, match="Invalid MAGMA output"): + _groups._parse_magma_generators("GL(2, GF(3))\n") + + # MAGMA may wrap lines after the commas of a cycle + output = "Order = 80 = 2^4 * 5\n (1, 40)(2, 39)(3,\n 38)\n (1, 2)\n" + assert _groups._parse_magma_generators(output) == [[(0, 39), (1, 38), (2, 37)], [(0, 1)]] + + +def test_get_generators_from_local_magma( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Retrieve generators for a MAGMA group from a MAGMA executable.""" + group = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));" + # MAGMA's description of the group, recorded from MAGMA V2.29-10 + output = "Permutation group acting on a set of cardinality 2\nOrder = 2\n(1, 2)\n" + monkeypatch.setattr(_magma, "is_callable", lambda: True) + + # MAGMA runs without prompting, with a fixed random seed, and the result is cached + cache: dict[str, str] = {} + monkeypatch.setattr("builtins.input", unittest.mock.Mock(side_effect=AssertionError)) + with ( + unittest.mock.patch("qldpc.cache.get_disk_cache", return_value=cache), + unittest.mock.patch.object(_magma, "get_output", return_value=output) as get_output, + ): + assert _groups.get_generators_from_magma(group) == [[(0, 1)]] + get_output.assert_called_once_with(f"SetSeed(1); {group}") + assert _groups.get_generators_from_magma(group) == [[(0, 1)]] + get_output.assert_called_once() + assert "Run the following command in MAGMA" not in capsys.readouterr().out + + # an error that MAGMA reports is raised + with ( + unittest.mock.patch.object(_magma, "get_output", side_effect=_magma.MAGMAError("_TEST_")), + pytest.raises(ValueError, match="_TEST_"), + ): + _groups.get_generators_from_magma(group) + + # if MAGMA fails to finish the command for another reason, fall back to the manual workflow + inputs = iter(output.splitlines() + [""]) + monkeypatch.setattr("builtins.input", lambda: next(inputs)) + with ( + unittest.mock.patch.object( + _magma, "get_output", side_effect=_magma.MAGMARunError("_TEST_") + ), + pytest.warns(UserWarning, match="_TEST_"), + ): + assert _groups.get_generators_from_magma(group) == [[(0, 1)]] + assert ( + f"Run the following command in MAGMA:\n\nSetSeed(1); {group}\n" in capsys.readouterr().out + ) + def test_get_small_group_number() -> None: """Retrieve the number of groups of some order.""" diff --git a/src/qldpc/external/_magma.py b/src/qldpc/external/_magma.py new file mode 100644 index 000000000..84baa7d77 --- /dev/null +++ b/src/qldpc/external/_magma.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Running the MAGMA computer algebra system from the command line. + +See https://magma.maths.usyd.edu.au. The command-line options that this module uses are documented +in the "Command Line Options" section of the MAGMA handbook. +""" + +from __future__ import annotations + +import functools +import os +import re +import shutil +import subprocess +import tempfile +import warnings + +from qldpc._utils import get_external_caller_stacklevel + +# MAGMA prints these markers around the output of a command. The script builds each marker from +# two strings, so that the script's own text never contains a marker. +_BEGIN_MARKER = "__qldpc_begin__" +_END_MARKER = "__qldpc_end__" + +# MAGMA reports errors on lines such as "User error: ...", "Runtime error in ...", or "System error" +_ERROR_PATTERN = re.compile(r"^\w+ error\b", flags=re.MULTILINE) + + +class MAGMAError(ValueError): + """MAGMA reported an error while running a command.""" + + +class MAGMARunError(RuntimeError): + """MAGMA stopped before finishing a command, without reporting an error.""" + + +#################################################################################################### +# calling MAGMA + + +def is_on_path() -> bool: + """Is there a ``magma`` executable on ``PATH``? Unlike :func:`is_callable`, never runs it.""" + return shutil.which("magma") is not None + + +@functools.cache +def is_callable() -> bool: + """Can MAGMA be called from the command line (with ``magma``)? + + This check runs MAGMA once, so it also fails if MAGMA cannot start, such as for lack of a + licence. If ``magma`` is on ``PATH`` but fails the check, this function warns with the reason. + It never prompts for input. + """ + if not is_on_path(): + return False + try: + output = get_output("1 + 1;", timeout=60) + except (subprocess.TimeoutExpired, MAGMAError, MAGMARunError) as error: + reason = str(error) + else: + if output.split() == ["2"]: + return True + reason = f"MAGMA printed {output!r} for 1 + 1" + warnings.warn( + "A magma executable is on PATH, but a test run of it failed, so qLDPC does not run MAGMA" + f" automatically.\n\n{reason}", + stacklevel=get_external_caller_stacklevel(), + ) + return False + + +def get_output(command: str, *, timeout: float | None = None) -> str: + """Get the output that MAGMA prints when it runs the given command. + + This function writes the command to a temporary script file and runs ``magma`` on that file in + a subprocess, without the user's startup file, and with output lines of unlimited length. + + Raises: + MAGMAError: If MAGMA reports an error, such as an error in the command. + MAGMARunError: If MAGMA cannot start, or stops before finishing the command without + reporting an error. + """ + command = command.strip() + if not command.endswith(";"): + command += ";" + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "command.m") + with open(path, "w") as file: + file.write(_get_script(command)) + try: + result = subprocess.run( + [*_get_arguments(), path], + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + except OSError as error: + raise MAGMARunError( + f"Cannot run MAGMA: {error}\n\nMAGMA command:\n{command}" + ) from error + return _parse_output(command, result.returncode, result.stdout, result.stderr) + + +#################################################################################################### +# helper functions + + +def _get_arguments() -> list[str]: + """The command line that runs MAGMA, without the script file. + + The option -b suppresses MAGMA's banner and exit summary, and -n skips the user's startup file. + """ + return ["magma", "-b", "-n"] + + +def _get_script(command: str) -> str: + """A MAGMA script that runs a command, prints markers around its output, and quits. + + The script stops at the first error, does not echo itself, and neither wraps nor pages output. + """ + lines = [ + "SetQuitOnError(true);", + "SetEchoInput(false);", + "SetAutoColumns(false);", + "SetColumns(0);", + "SetRows(0);", + _get_print_marker_statement(_BEGIN_MARKER), + command, + _get_print_marker_statement(_END_MARKER), + "quit;", + ] + return "\n".join(lines) + "\n" + + +def _get_print_marker_statement(marker: str) -> str: + """A MAGMA statement that prints a marker, without the marker appearing in its own text.""" + middle = len(marker) // 2 + return f'print "{marker[:middle]}" cat "{marker[middle:]}";' + + +def _parse_output(command: str, returncode: int, stdout: str, stderr: str) -> str: + """Extract the output of a command from the output of a MAGMA script that runs it. + + The markers show that MAGMA ran the command to the end, so the output of a finished command is + returned whatever MAGMA's exit status, which the MAGMA handbook does not document. + """ + details = f"MAGMA output:\n{stdout}" + if stderr: + details += f"\n\nMAGMA standard error:\n{stderr}" + details += f"\n\nMAGMA command:\n{command}" + + match = re.search( + rf"^{_BEGIN_MARKER}$\n(.*?)^{_END_MARKER}$", stdout, flags=re.MULTILINE | re.DOTALL + ) + if match and not _ERROR_PATTERN.search(match.group(1)): + return match.group(1) + if _ERROR_PATTERN.search(stdout): + raise MAGMAError(f"MAGMA reported an error\n\n{details}") + raise MAGMARunError( + f"MAGMA stopped before finishing a command (exit code {returncode})\n\n{details}" + ) diff --git a/src/qldpc/external/_magma_test.py b/src/qldpc/external/_magma_test.py new file mode 100644 index 000000000..3054f2969 --- /dev/null +++ b/src/qldpc/external/_magma_test.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for _magma.py.""" + +from __future__ import annotations + +import subprocess +import unittest.mock +from collections.abc import Iterator + +import pytest + +from qldpc.external import _magma + +# The scripts that qLDPC runs for a command, and their output from MAGMA V2.29-10, recorded on the +# online MAGMA calculator, https://magma.maths.usyd.edu.au/calc +SCRIPT = ( + "SetQuitOnError(true);\n" + "SetEchoInput(false);\n" + "SetAutoColumns(false);\n" + "SetColumns(0);\n" + "SetRows(0);\n" + 'print "__qldpc" cat "_begin__";\n' + "{command}\n" + 'print "__qldp" cat "c_end__";\n' + "quit;\n" +) +COMMAND_SUM = "1 + 1;" +OUTPUT_SUM = "__qldpc_begin__\n2\n__qldpc_end__\n" +COMMAND_GROUP = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));" +OUTPUT_GROUP = ( + "__qldpc_begin__\n" + "Permutation group acting on a set of cardinality 2\n" + "Order = 2\n" + "(1, 2)\n" + "__qldpc_end__\n" +) +COMMAND_ERROR = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[1])));" +OUTPUT_ERROR = ( + "__qldpc_begin__\n\n" + ">> PermutationGroup(LinearCode(Matrix(GF(2),1,2,[1])));\n" + " ^\n" + "Runtime error in 'Matrix': Sequence has length 1 but should have length 1 * 2 = 2\n\n\n" +) + + +@pytest.fixture(autouse=True) +def block_local_magma() -> Iterator[None]: + """Test the real MAGMA probes, mocking the executable in each test instead. + + This fixture overrides the fixture of conftest.py that hides any MAGMA executable. + """ + _magma.is_callable.cache_clear() + yield + _magma.is_callable.cache_clear() + + +def mock_magma(stdout: str, returncode: int = 0, stderr: str = "") -> unittest.mock.MagicMock: + """Mock subprocess.run for a MAGMA run, recording the script that each call runs.""" + scripts = [] + + def run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: + with open(args[-1]) as file: + scripts.append(file.read()) + return subprocess.CompletedProcess(args, returncode, stdout, stderr) + + mock = unittest.mock.MagicMock(side_effect=run) + mock.scripts = scripts + return mock + + +def test_get_output() -> None: + """Run commands in MAGMA and extract their output.""" + # MAGMA runs the recorded script without the user's startup file or access to standard input + run = mock_magma(OUTPUT_GROUP) + with unittest.mock.patch("subprocess.run", run): + output = _magma.get_output(COMMAND_GROUP) + assert output.splitlines() == [ + "Permutation group acting on a set of cardinality 2", + "Order = 2", + "(1, 2)", + ] + assert run.scripts == [SCRIPT.format(command=COMMAND_GROUP)] + args = run.call_args.args[0] + assert args[:-1] == ["magma", "-b", "-n"] + assert run.call_args.kwargs["stdin"] is subprocess.DEVNULL + + # the output of a finished command is returned whatever MAGMA's exit status, which the MAGMA + # handbook does not document + with unittest.mock.patch("subprocess.run", mock_magma(OUTPUT_SUM, returncode=1)): + assert _magma.get_output(COMMAND_SUM) == "2\n" + + # a command without a final semicolon is completed, so that it ends before the next statement + run = mock_magma(OUTPUT_SUM) + with unittest.mock.patch("subprocess.run", run): + assert _magma.get_output("1 + 1") == "2\n" + assert run.scripts == [SCRIPT.format(command=COMMAND_SUM)] + + # MAGMA reports an error, which stops the script before the end marker + with ( + unittest.mock.patch("subprocess.run", mock_magma(OUTPUT_ERROR, returncode=1)), + pytest.raises(_magma.MAGMAError, match="Runtime error in 'Matrix'"), + ): + _magma.get_output(COMMAND_ERROR) + + # an error between the markers is reported even if MAGMA went on to print the end marker + with ( + unittest.mock.patch("subprocess.run", mock_magma(OUTPUT_ERROR + "__qldpc_end__\n")), + pytest.raises(_magma.MAGMAError, match="Runtime error in 'Matrix'"), + ): + _magma.get_output(COMMAND_ERROR) + + # MAGMA stops without finishing the command or reporting an error, or cannot start + with ( + unittest.mock.patch( + "subprocess.run", mock_magma("", returncode=1, stderr="no valid licence") + ), + pytest.raises(_magma.MAGMARunError, match=r"(?s)exit code 1.*no valid licence"), + ): + _magma.get_output(COMMAND_SUM) + with ( + unittest.mock.patch("subprocess.run", side_effect=PermissionError("_TEST_")), + pytest.raises(_magma.MAGMARunError, match="_TEST_"), + ): + _magma.get_output(COMMAND_SUM) + + +def test_is_callable() -> None: + """Check whether MAGMA can be called from the command line.""" + # no MAGMA executable + with ( + unittest.mock.patch("shutil.which", return_value=None), + unittest.mock.patch("subprocess.run", side_effect=AssertionError("must not run MAGMA")), + ): + assert not _magma.is_on_path() + assert not _magma.is_callable() + + # MAGMA runs a probe + _magma.is_callable.cache_clear() + with ( + unittest.mock.patch("shutil.which", return_value="/usr/local/bin/magma"), + unittest.mock.patch("subprocess.run", mock_magma(OUTPUT_SUM)), + ): + assert _magma.is_on_path() + assert _magma.is_callable() + + # MAGMA is on PATH but fails the probe, which warns with the reason + for run, reason in [ + (mock_magma("", returncode=1, stderr="no valid licence"), "no valid licence"), + (mock_magma(OUTPUT_ERROR), "Runtime error"), + (mock_magma(OUTPUT_SUM.replace("2", "3")), "MAGMA printed '3\\\\n'"), + (unittest.mock.MagicMock(side_effect=subprocess.TimeoutExpired("magma", 60)), "timed out"), + ]: + _magma.is_callable.cache_clear() + with ( + unittest.mock.patch("shutil.which", return_value="/usr/local/bin/magma"), + unittest.mock.patch("subprocess.run", run), + pytest.warns(UserWarning, match=reason), + ): + assert not _magma.is_callable()