From 4f6c7d00c407964dd3aab1d7b786d27120b3bec3 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 16:12:48 -0500 Subject: [PATCH 1/6] Run a local MAGMA executable for with_magma=True, falling back to copy/paste MAGMA computations of permutation groups, requested with with_magma=True or Group.from_name(..., from_magma=True), now run a magma executable on PATH when a test run of it succeeds, and otherwise use the manual copy/paste workflow as before. MAGMA runs a script with a fixed random seed and without the user's startup file, and markers around the output of the command. An error that MAGMA reports in the command is raised; any other failure warns and falls back to the manual workflow. Calls without these arguments never run MAGMA, but the warning before a GAP computation of a permutation automorphism group notes when GAP needs copy/paste and a magma executable is on PATH. Closes #389. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/library_map.rst | 11 ++- src/qldpc/abstract/groups.py | 8 +- src/qldpc/circuits/transversal.py | 14 +-- src/qldpc/codes/common.py | 10 ++- src/qldpc/codes/common_test.py | 15 ++++ src/qldpc/conftest.py | 15 ++++ src/qldpc/external/_groups.py | 75 +++++++++++----- src/qldpc/external/_groups_test.py | 45 +++++++++- src/qldpc/external/_magma.py | 138 +++++++++++++++++++++++++++++ src/qldpc/external/_magma_test.py | 121 +++++++++++++++++++++++++ 10 files changed, 415 insertions(+), 37 deletions(-) create mode 100644 src/qldpc/external/_magma.py create mode 100644 src/qldpc/external/_magma_test.py diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index bcb5570ad..fbfdfe7c1 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 @@ -293,6 +293,15 @@ When a needed GAP package such as GUAVA or QDistRnd is missing, qLDPC asks on st 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 system that computes a group's generators is always the one that the caller chose. +qLDPC runs a ``magma`` executable on ``PATH`` in a subprocess, with a fixed random seed and without the user's startup file, if a test run of it succeeds. +Otherwise, it prints the MAGMA command, copies it to the system clipboard, and reads MAGMA's output from standard input. +Results of both workflows are cached on disk. + Code and group lookups ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index a74c5af70..56b232b78 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -637,8 +637,12 @@ def from_name( 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. + raises the warning warning_to_raise_if_calling_gap, if provided. 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 such a manual copy/paste workflow. If MAGMA fails to finish running + the command without reporting an error in it, qLDPC warns and falls back to the manual + workflow. qLDPC runs MAGMA with a fixed random seed and without the user's startup file. + 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 c6f0e4698..452b7afa5 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, @@ -846,7 +846,8 @@ 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 + 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. See help(qldpc.abstract.Group.from_name). """ matrix = self.canonicalized.matrix.view(np.ndarray) @@ -872,6 +873,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 not external.gap.is_callable() and _magma.is_on_path(): + 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..491a7f816 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -411,6 +411,21 @@ def get_output(*commands: str) -> str: 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 + # if GAP needs copying commands by hand but MAGMA is on PATH, the warning says so, but the + # default path still computes with GAP, the system that the caller chose + 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=True), + unittest.mock.patch( + "qldpc.external._magma.get_output", side_effect=AssertionError("must not run MAGMA") + ), + pytest.warns(UserWarning, match="MAGMA executable is on PATH"), + ): + assert codes.RepetitionCode(2).get_permutation_automorphism_group().order == 2 + # 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 user_inputs = iter( 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..782ae8534 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -20,6 +20,7 @@ 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, ...], ...]], ...], ...] @@ -80,20 +81,25 @@ 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). - """ - print("Run the following command in MAGMA:") - print() - print(group) - print() + 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). If MAGMA fails to finish running the command without + reporting an error in it, this function warns and falls back to the manual workflow. + Raises: + ValueError: If MAGMA reports an error in the command, or its output does not describe a + permutation group. + """ cache_name = "magma_groups" cache = qldpc.cache.get_disk_cache(cache_name) key = "".join(group.split()) # strip whitespace if generators := cache.get(key, None): + print("MAGMA command:") + print() + print(group) + print() print( "NOTICE: group found in the local MAGMA group cache." " Retrieved group generators (in cycle notation):" @@ -110,6 +116,24 @@ 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(group) + 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(group) + print() print("===============================================================================") print("NOTE:") try: @@ -131,21 +155,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 @@ -216,6 +226,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 lists no generators of a trivial group, for which this function returns the identity. + """ + # identify permutations in the output, which may wrap lines after commas + 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(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..0fd03bded 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 @@ -248,6 +247,48 @@ def test_get_generators_from_magma( capsys.readouterr() # intercept print statements +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, 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(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 in the command is raised, since a manual run would repeat it + 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 "Run the following command in MAGMA" in capsys.readouterr().out + + def test_get_small_group_number() -> None: """Retrieve the number of groups of some order.""" order, number = 16, 14 diff --git a/src/qldpc/external/_magma.py b/src/qldpc/external/_magma.py new file mode 100644 index 000000000..cedefaaf4 --- /dev/null +++ b/src/qldpc/external/_magma.py @@ -0,0 +1,138 @@ +# 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 + +# 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__" + +# The script fixes the random seed, so that runs of MAGMA's randomized algorithms are reproducible. +_SEED = 1 + + +class MAGMAError(ValueError): + """MAGMA reported an error in a command.""" + + +class MAGMARunError(RuntimeError): + """MAGMA did not finish running a command, without reporting an error in the command.""" + + +#################################################################################################### +# 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. It never prompts for input. + """ + if not is_on_path(): + return False + try: + return get_output("1 + 1;", timeout=60).split() == ["2"] + except (OSError, subprocess.TimeoutExpired, MAGMAError, MAGMARunError): + 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, with a fixed random seed, without the user's startup file, and with output lines + of unlimited length. + + Raises: + MAGMAError: If MAGMA reports an error in the command. + MAGMARunError: If MAGMA does not finish running the command for any other reason. + """ + 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)) + # -b suppresses MAGMA's banner and exit summary, -n skips the user's startup file, and -S + # sets the random seed + result = subprocess.run( + ["magma", "-b", "-n", "-S", str(_SEED), path], + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + return _parse_output(command, result.returncode, result.stdout, result.stderr) + + +#################################################################################################### +# helper functions + + +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 does not wrap output lines. + """ + lines = [ + "SetQuitOnError(true);", + "SetEchoInput(false);", + "SetColumns(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. + """ + match = re.search( + rf"^{_BEGIN_MARKER}$\n(.*?)^{_END_MARKER}$", stdout, flags=re.MULTILINE | re.DOTALL + ) + if match: + return match.group(1) + + # MAGMA reports errors in commands on lines such as "User error: ..." or "Runtime error ..." + details = f"MAGMA output:\n{stdout}" + if stderr: + details += f"\n\nMAGMA standard error:\n{stderr}" + details += f"\n\nMAGMA command:\n{command}" + if re.search(r"^\w+ error\b", stdout, flags=re.MULTILINE): + raise MAGMAError(f"MAGMA reported an error\n\n{details}") + raise MAGMARunError( + f"MAGMA did not finish running 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..f230acc12 --- /dev/null +++ b/src/qldpc/external/_magma_test.py @@ -0,0 +1,121 @@ +# 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 + +# Output of the scripts of _magma._get_script, recorded from MAGMA V2.29-10 on the online MAGMA +# calculator, https://magma.maths.usyd.edu.au/calc +OUTPUT_SUM = "__qldpc_begin__\n2\n__qldpc_end__\n" +OUTPUT_GROUP = ( + "__qldpc_begin__\n" + "Permutation group acting on a set of cardinality 2\n" + "Order = 2\n" + "(1, 2)\n" + "__qldpc_end__\n" +) +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 each script that it 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.""" + # a command runs in a script that does not contain the markers of its output, so that the + # markers cannot come from an echo of the script + run = mock_magma(OUTPUT_GROUP) + command = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));" + with unittest.mock.patch("subprocess.run", run): + output = _magma.get_output(command) + assert output.splitlines() == [ + "Permutation group acting on a set of cardinality 2", + "Order = 2", + "(1, 2)", + ] + (script,) = run.scripts + assert f"\n{command}\n" in script + assert _magma._BEGIN_MARKER not in script and _magma._END_MARKER not in script + + # 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 "\n1 + 1;\n" in run.scripts[0] + + # MAGMA reports an error in the command + with ( + unittest.mock.patch("subprocess.run", mock_magma(OUTPUT_ERROR, returncode=1)), + pytest.raises(_magma.MAGMAError, match="Runtime error in 'Matrix'"), + ): + _magma.get_output("PermutationGroup(LinearCode(Matrix(GF(2),1,2,[1])));") + + # MAGMA stops without finishing the command or reporting an error in it + 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("1 + 1;") + + +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, or fails to run, a probe + for run, callable_ in [ + (mock_magma(OUTPUT_SUM), True), + (mock_magma("", returncode=1), False), + (unittest.mock.MagicMock(side_effect=PermissionError), False), + (unittest.mock.MagicMock(side_effect=subprocess.TimeoutExpired("magma", 60)), False), + ]: + _magma.is_callable.cache_clear() + with ( + unittest.mock.patch("shutil.which", return_value="/usr/local/bin/magma"), + unittest.mock.patch("subprocess.run", run), + ): + assert _magma.is_on_path() + assert _magma.is_callable() == callable_ From 5a0fc1091df73b078c6a5b9237fbbfac8c7fe8d1 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 16:22:45 -0500 Subject: [PATCH 2/6] Pin MAGMA's script and options in tests, parse only lines of cycles, and warn when a magma on PATH fails its test run Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 2 +- docs/source/installation.rst | 11 ++++ docs/source/library_map.rst | 5 +- src/qldpc/abstract/groups.py | 9 +-- src/qldpc/codes/common.py | 6 +- src/qldpc/codes/common_test.py | 5 +- src/qldpc/external/_groups.py | 19 ++++--- src/qldpc/external/_groups_test.py | 11 +++- src/qldpc/external/_magma.py | 89 ++++++++++++++++++++---------- src/qldpc/external/_magma_test.py | 81 +++++++++++++++++++-------- 10 files changed, 165 insertions(+), 73 deletions(-) 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 b344830b4..779942a1c 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 @@ -87,6 +89,15 @@ Without that binding, qLDPC can call a GAP executable on ``PATH`` (possibly obta GAP integration on Windows remains limited; see `issue #294 `_. See the :doc:`library map ` for GAP calls, prompts, other side effects, and caching. +.. _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 fbfdfe7c1..81ccf127d 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -297,9 +297,10 @@ 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 system that computes a group's generators is always the one that the caller chose. -qLDPC runs a ``magma`` executable on ``PATH`` in a subprocess, with a fixed random seed and without the user's startup file, if a test run of it succeeds. +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. +qLDPC runs a ``magma`` executable on ``PATH`` in a subprocess, with a fixed random seed and without the user's startup file, if a test run of it succeeds, and warns if that test run fails. Otherwise, it prints the MAGMA command, copies it to the system clipboard, and reads MAGMA's output from standard input. +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. Results of both workflows are cached on disk. Code and group lookups diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index 56b232b78..6175f7017 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -639,10 +639,11 @@ def from_name( 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 retrieved from a local disk cache if possible, else from MAGMA if MAGMA can be called from the command - line, and otherwise by such a manual copy/paste workflow. If MAGMA fails to finish running - the command without reporting an error in it, qLDPC warns and falls back to the manual - workflow. qLDPC runs MAGMA with a fixed random seed and without the user's startup file. - Retrieved generators are cached to disk. + line, and otherwise by such a manual copy/paste workflow. qLDPC warns if a ``magma`` + executable on ``PATH`` fails a test run. qLDPC runs MAGMA with a fixed + random seed and without the user's startup file. 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/codes/common.py b/src/qldpc/codes/common.py index 452b7afa5..c85f6907a 100644 --- a/src/qldpc/codes/common.py +++ b/src/qldpc/codes/common.py @@ -847,8 +847,8 @@ def get_permutation_automorphism_group(self, *, with_magma: bool = False) -> abs This computation may run GAP, install GAP packages, access GroupNames.org, or prompt on 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. See - help(qldpc.abstract.Group.from_name). + 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,7 +873,7 @@ 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 not external.gap.is_callable() and _magma.is_on_path(): + 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." diff --git a/src/qldpc/codes/common_test.py b/src/qldpc/codes/common_test.py index 491a7f816..53feb03c6 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -380,7 +380,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 +411,8 @@ 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 but MAGMA is on PATH, the warning says so, but the # default path still computes with GAP, the system that the caller chose diff --git a/src/qldpc/external/_groups.py b/src/qldpc/external/_groups.py index 782ae8534..9a4025bca 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -84,12 +84,13 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: 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). If MAGMA fails to finish running the command without - reporting an error in it, this function warns and falls back to the manual workflow. + ``EOFError`` if standard input is closed). 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 in the command, or its output does not describe a - permutation group. + ValueError: If MAGMA reports an error, such as an error in the command, or its output does + not describe a permutation group. """ cache_name = "magma_groups" cache = qldpc.cache.get_disk_cache(cache_name) @@ -229,12 +230,12 @@ def _maybe_get_generators_from_groupnames(group: str) -> _GeneratorsList | None: def _parse_magma_generators(output: str) -> _GeneratorsList: """Parse the generators of a permutation group from MAGMA's description of the group. - MAGMA lists no generators of a trivial group, for which this function returns the identity. + 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 permutations in the output, which may wrap lines after commas - one_cycle_pattern = r"\((?:\d|,\s+)+\)" - permutation_pattern = rf"(?:{one_cycle_pattern})+" - permutations = re.findall(permutation_pattern, output, re.DOTALL) + # 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: diff --git a/src/qldpc/external/_groups_test.py b/src/qldpc/external/_groups_test.py index 0fd03bded..7d0a37b71 100644 --- a/src/qldpc/external/_groups_test.py +++ b/src/qldpc/external/_groups_test.py @@ -246,6 +246,15 @@ 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] @@ -269,7 +278,7 @@ def test_get_generators_from_local_magma( get_output.assert_called_once() assert "Run the following command in MAGMA" not in capsys.readouterr().out - # an error that MAGMA reports in the command is raised, since a manual run would repeat it + # 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_"), diff --git a/src/qldpc/external/_magma.py b/src/qldpc/external/_magma.py index cedefaaf4..73b87411f 100644 --- a/src/qldpc/external/_magma.py +++ b/src/qldpc/external/_magma.py @@ -14,22 +14,28 @@ 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__" -# The script fixes the random seed, so that runs of MAGMA's randomized algorithms are reproducible. +# MAGMA runs with this random seed, so that its randomized algorithms give reproducible results. _SEED = 1 +# 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 in a command.""" + """MAGMA reported an error while running a command.""" class MAGMARunError(RuntimeError): - """MAGMA did not finish running a command, without reporting an error in the command.""" + """MAGMA stopped before finishing a command, without reporting an error.""" #################################################################################################### @@ -46,14 +52,25 @@ 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. It never prompts for input. + 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: - return get_output("1 + 1;", timeout=60).split() == ["2"] - except (OSError, subprocess.TimeoutExpired, MAGMAError, MAGMARunError): - return False + 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: @@ -64,8 +81,9 @@ def get_output(command: str, *, timeout: float | None = None) -> str: of unlimited length. Raises: - MAGMAError: If MAGMA reports an error in the command. - MAGMARunError: If MAGMA does not finish running the command for any other reason. + 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(";"): @@ -74,16 +92,19 @@ def get_output(command: str, *, timeout: float | None = None) -> str: path = os.path.join(directory, "command.m") with open(path, "w") as file: file.write(_get_script(command)) - # -b suppresses MAGMA's banner and exit summary, -n skips the user's startup file, and -S - # sets the random seed - result = subprocess.run( - ["magma", "-b", "-n", "-S", str(_SEED), path], - stdin=subprocess.DEVNULL, - capture_output=True, - text=True, - check=False, - timeout=timeout, - ) + 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) @@ -91,15 +112,26 @@ def get_output(command: str, *, timeout: float | None = None) -> str: # 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, -n skips the user's startup file, and + -S sets the random seed. + """ + return ["magma", "-b", "-n", "-S", str(_SEED)] + + 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 does not wrap output lines. + 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), @@ -120,19 +152,18 @@ def _parse_output(command: str, returncode: int, stdout: str, stderr: str) -> st 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. """ - match = re.search( - rf"^{_BEGIN_MARKER}$\n(.*?)^{_END_MARKER}$", stdout, flags=re.MULTILINE | re.DOTALL - ) - if match: - return match.group(1) - - # MAGMA reports errors in commands on lines such as "User error: ..." or "Runtime error ..." details = f"MAGMA output:\n{stdout}" if stderr: details += f"\n\nMAGMA standard error:\n{stderr}" details += f"\n\nMAGMA command:\n{command}" - if re.search(r"^\w+ error\b", stdout, flags=re.MULTILINE): + + 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 did not finish running a command (exit code {returncode})\n\n{details}" + 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 index f230acc12..5205fe0f7 100644 --- a/src/qldpc/external/_magma_test.py +++ b/src/qldpc/external/_magma_test.py @@ -12,9 +12,22 @@ from qldpc.external import _magma -# Output of the scripts of _magma._get_script, recorded from MAGMA V2.29-10 on the online MAGMA -# calculator, https://magma.maths.usyd.edu.au/calc +# 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" @@ -22,6 +35,7 @@ "(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" @@ -42,7 +56,7 @@ def block_local_magma() -> Iterator[None]: def mock_magma(stdout: str, returncode: int = 0, stderr: str = "") -> unittest.mock.MagicMock: - """Mock subprocess.run for a MAGMA run, recording each script that it runs.""" + """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]: @@ -57,42 +71,54 @@ def run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: def test_get_output() -> None: """Run commands in MAGMA and extract their output.""" - # a command runs in a script that does not contain the markers of its output, so that the - # markers cannot come from an echo of the script + # MAGMA runs the recorded script, with a fixed random seed, without the user's startup file, and + # without access to standard input run = mock_magma(OUTPUT_GROUP) - command = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));" with unittest.mock.patch("subprocess.run", run): - output = _magma.get_output(command) + output = _magma.get_output(COMMAND_GROUP) assert output.splitlines() == [ "Permutation group acting on a set of cardinality 2", "Order = 2", "(1, 2)", ] - (script,) = run.scripts - assert f"\n{command}\n" in script - assert _magma._BEGIN_MARKER not in script and _magma._END_MARKER not in script + assert run.scripts == [SCRIPT.format(command=COMMAND_GROUP)] + args = run.call_args.args[0] + assert args[:-1] == ["magma", "-b", "-n", "-S", str(_magma._SEED)] + assert run.call_args.kwargs["stdin"] is subprocess.DEVNULL # 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 "\n1 + 1;\n" in run.scripts[0] + assert run.scripts == [SCRIPT.format(command=COMMAND_SUM)] - # MAGMA reports an error in the command + # 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("PermutationGroup(LinearCode(Matrix(GF(2),1,2,[1])));") + _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 in it + # 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("1 + 1;") + _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: @@ -105,17 +131,26 @@ def test_is_callable() -> None: assert not _magma.is_on_path() assert not _magma.is_callable() - # MAGMA runs, or fails to run, a probe - for run, callable_ in [ - (mock_magma(OUTPUT_SUM), True), - (mock_magma("", returncode=1), False), - (unittest.mock.MagicMock(side_effect=PermissionError), False), - (unittest.mock.MagicMock(side_effect=subprocess.TimeoutExpired("magma", 60)), False), + # 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 _magma.is_on_path() - assert _magma.is_callable() == callable_ + assert not _magma.is_callable() From 853e9601d0b2b99ac63f600671bcb64b4a505a47 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 17:52:44 -0500 Subject: [PATCH 3/6] Test the hint's PATH condition and nonzero exit codes, and raise the GAP warning before GAP's availability prompt Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/library_map.rst | 5 ++-- src/qldpc/abstract/groups.py | 27 +++++++++++----------- src/qldpc/codes/common_test.py | 38 +++++++++++++++++++------------ src/qldpc/external/_groups.py | 11 +++++---- src/qldpc/external/_magma_test.py | 5 ++++ 5 files changed, 51 insertions(+), 35 deletions(-) diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index 81ccf127d..245344c73 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -298,8 +298,9 @@ 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. -qLDPC runs a ``magma`` executable on ``PATH`` in a subprocess, with a fixed random seed and without the user's startup file, if a test run of it succeeds, and warns if that test run fails. -Otherwise, it prints the MAGMA command, copies it to the system clipboard, and reads MAGMA's output from standard input. +If a ``magma`` executable is on ``PATH`` and a test run of it succeeds, qLDPC runs it in a subprocess, with a fixed random seed and 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. 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. Results of both workflows are cached on disk. diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index 6175f7017..1a9f9a376 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -631,19 +631,20 @@ 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 retrieved - from a local disk cache if possible, else from MAGMA if MAGMA can be called from the command - line, and otherwise by such a manual copy/paste workflow. qLDPC warns if a ``magma`` - executable on ``PATH`` fails a test run. qLDPC runs MAGMA with a fixed - random seed and without the user's startup file. 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. + 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 such a manual + copy/paste workflow. qLDPC warns if a ``magma`` executable on ``PATH`` fails a test run. + qLDPC runs MAGMA with a fixed random seed and without the user's startup file. 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/codes/common_test.py b/src/qldpc/codes/common_test.py index 53feb03c6..28e9c1dad 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -359,7 +359,8 @@ 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 + # raise an error when GAP is not installed, after a warning that suggests MAGMA, which a user + # who declines to copy commands into GAP by hand sees too external.gap.require_package.cache_clear() with ( unittest.mock.patch("qldpc.external.gap.is_callable", return_value=False), @@ -368,6 +369,8 @@ def test_permutation_automorphism_group( "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"), pytest.raises(ValueError, match="Cannot build GAP group"), ): codes.RepetitionCode(2).get_permutation_automorphism_group() @@ -414,20 +417,25 @@ def get_output(*commands: str) -> str: # 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 but MAGMA is on PATH, the warning says so, but the - # default path still computes with GAP, the system that the caller chose - 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=True), - unittest.mock.patch( - "qldpc.external._magma.get_output", side_effect=AssertionError("must not run MAGMA") - ), - pytest.warns(UserWarning, match="MAGMA executable is on PATH"), - ): - assert codes.RepetitionCode(2).get_permutation_automorphism_group().order == 2 + # 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 diff --git a/src/qldpc/external/_groups.py b/src/qldpc/external/_groups.py index 9a4025bca..e69d48a53 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -167,16 +167,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);;', diff --git a/src/qldpc/external/_magma_test.py b/src/qldpc/external/_magma_test.py index 5205fe0f7..04b958ce2 100644 --- a/src/qldpc/external/_magma_test.py +++ b/src/qldpc/external/_magma_test.py @@ -86,6 +86,11 @@ def test_get_output() -> None: assert args[:-1] == ["magma", "-b", "-n", "-S", str(_magma._SEED)] 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): From 51cb45ca7cae4af9b07ab7a4caf491ddd3f4d80f Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 17:57:04 -0500 Subject: [PATCH 4/6] Fix MAGMA's random seed in the command of both MAGMA workflows, so that they return the same generators Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/library_map.rst | 3 ++- src/qldpc/abstract/groups.py | 8 ++++---- src/qldpc/codes/common_test.py | 7 +++++-- src/qldpc/external/_groups.py | 21 +++++++++++++-------- src/qldpc/external/_groups_test.py | 8 +++++--- src/qldpc/external/_magma.py | 11 +++-------- src/qldpc/external/_magma_test.py | 5 ++--- 7 files changed, 34 insertions(+), 29 deletions(-) diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index 245344c73..b2b50689f 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -298,9 +298,10 @@ 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, with a fixed random seed and without the user's startup file. +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 workflows 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. Results of both workflows are cached on disk. diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index 1a9f9a376..f9cbda93a 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -641,10 +641,10 @@ def from_name( 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 such a manual copy/paste workflow. qLDPC warns if a ``magma`` executable on ``PATH`` fails a test run. - qLDPC runs MAGMA with a fixed random seed and without the user's startup file. 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. + Both workflows fix MAGMA's random seed, on which the generators that MAGMA returns can + depend, and qLDPC runs MAGMA without the user's startup file. 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/codes/common_test.py b/src/qldpc/codes/common_test.py index 28e9c1dad..87add4a6f 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -446,7 +446,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 @@ -457,7 +458,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/external/_groups.py b/src/qldpc/external/_groups.py index e69d48a53..47b52a4a9 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -27,6 +27,9 @@ _GROUPNAMES_URL = "https://people.maths.bris.ac.uk/~matyd/GroupNames/" +# MAGMA's generators of a group can depend on its random seed, so both MAGMA workflows fix the seed +_MAGMA_SEED = 1 + #################################################################################################### # group generators @@ -84,22 +87,24 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: 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). 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. + ``EOFError`` if standard input is closed). Both workflows start the command by fixing MAGMA's + random seed, on which the generators that MAGMA returns can depend. 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. """ + 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(group) + print(command) print() print( "NOTICE: group found in the local MAGMA group cache." @@ -120,7 +125,7 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: # run MAGMA, if it can be called from the command line if _magma.is_callable(): try: - output = _magma.get_output(group) + output = _magma.get_output(command) except _magma.MAGMARunError as error: warnings.warn( f"{error}\n\nFalling back to copying commands into MAGMA by hand.", @@ -133,12 +138,12 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: print("Run the following command in MAGMA:") print() - print(group) + 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 diff --git a/src/qldpc/external/_groups_test.py b/src/qldpc/external/_groups_test.py index 7d0a37b71..67810845c 100644 --- a/src/qldpc/external/_groups_test.py +++ b/src/qldpc/external/_groups_test.py @@ -265,7 +265,7 @@ def test_get_generators_from_local_magma( 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, and the result is cached + # 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 ( @@ -273,7 +273,7 @@ def test_get_generators_from_local_magma( 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(group) + 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 @@ -295,7 +295,9 @@ def test_get_generators_from_local_magma( pytest.warns(UserWarning, match="_TEST_"), ): assert _groups.get_generators_from_magma(group) == [[(0, 1)]] - assert "Run the following command in MAGMA" in capsys.readouterr().out + assert ( + f"Run the following command in MAGMA:\n\nSetSeed(1); {group}\n" in capsys.readouterr().out + ) def test_get_small_group_number() -> None: diff --git a/src/qldpc/external/_magma.py b/src/qldpc/external/_magma.py index 73b87411f..84baa7d77 100644 --- a/src/qldpc/external/_magma.py +++ b/src/qldpc/external/_magma.py @@ -23,9 +23,6 @@ _BEGIN_MARKER = "__qldpc_begin__" _END_MARKER = "__qldpc_end__" -# MAGMA runs with this random seed, so that its randomized algorithms give reproducible results. -_SEED = 1 - # 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) @@ -77,8 +74,7 @@ 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, with a fixed random seed, without the user's startup file, and with output lines - of unlimited length. + 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. @@ -115,10 +111,9 @@ def get_output(command: str, *, timeout: float | None = None) -> str: 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, -n skips the user's startup file, and - -S sets the random seed. + The option -b suppresses MAGMA's banner and exit summary, and -n skips the user's startup file. """ - return ["magma", "-b", "-n", "-S", str(_SEED)] + return ["magma", "-b", "-n"] def _get_script(command: str) -> str: diff --git a/src/qldpc/external/_magma_test.py b/src/qldpc/external/_magma_test.py index 04b958ce2..3054f2969 100644 --- a/src/qldpc/external/_magma_test.py +++ b/src/qldpc/external/_magma_test.py @@ -71,8 +71,7 @@ def run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: def test_get_output() -> None: """Run commands in MAGMA and extract their output.""" - # MAGMA runs the recorded script, with a fixed random seed, without the user's startup file, and - # without access to standard input + # 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) @@ -83,7 +82,7 @@ def test_get_output() -> None: ] assert run.scripts == [SCRIPT.format(command=COMMAND_GROUP)] args = run.call_args.args[0] - assert args[:-1] == ["magma", "-b", "-n", "-S", str(_magma._SEED)] + 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 From 2c4081de5e0febe1f8cad2cc96298e97a1c7a735 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:01:50 -0500 Subject: [PATCH 5/6] Test that the GAP warning precedes GAP's availability prompt, and name both MAGMA workflows in the docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/library_map.rst | 4 ++-- src/qldpc/abstract/groups.py | 18 +++++++++++------- src/qldpc/codes/common_test.py | 12 ++++++++---- src/qldpc/external/_groups.py | 8 ++++---- 4 files changed, 25 insertions(+), 17 deletions(-) diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index b2b50689f..f246b3b80 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -301,9 +301,9 @@ These calls never fall back to GAP, and calls without these arguments never run 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 workflows start the command by fixing the seed. +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. -Results of both workflows are cached on disk. +Results of both are cached on disk. Code and group lookups ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/qldpc/abstract/groups.py b/src/qldpc/abstract/groups.py index f9cbda93a..0a1717e18 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -638,13 +638,17 @@ def from_name( 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 such a manual - copy/paste workflow. qLDPC warns if a ``magma`` executable on ``PATH`` fails a test run. - Both workflows fix MAGMA's random seed, on which the generators that MAGMA returns can - depend, and qLDPC runs MAGMA without the user's startup file. 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. + 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 warns if a ``magma`` executable on ``PATH`` fails a test run, and runs MAGMA + without the user's startup file. The generators that MAGMA returns can depend on its random + seed, so both the MAGMA subprocess and the manual workflow fix it. 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/codes/common_test.py b/src/qldpc/codes/common_test.py index 87add4a6f..11b48ff55 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -359,18 +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, after a warning that suggests MAGMA, which a user - # who declines to copy commands into GAP by hand sees too + # when GAP is not installed, or the user declines the manual GAP workflow, warn with the MAGMA + # hint before asking whether GAP is available, and then raise an error + 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"), + 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() diff --git a/src/qldpc/external/_groups.py b/src/qldpc/external/_groups.py index 47b52a4a9..021c1af73 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -87,10 +87,10 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: 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). Both workflows start the command by fixing MAGMA's - random seed, on which the generators that MAGMA returns can depend. 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. + ``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 fix it. 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 From f560aba73ac2f83774734f7cbf61c3c315d864d3 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:04:19 -0500 Subject: [PATCH 6/6] Clarify the wording of the MAGMA docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/source/library_map.rst | 2 +- src/qldpc/abstract/groups.py | 11 ++++++----- src/qldpc/codes/common_test.py | 4 ++-- src/qldpc/external/_groups.py | 9 +++++---- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/source/library_map.rst b/docs/source/library_map.rst index f246b3b80..7f46f8e4f 100644 --- a/docs/source/library_map.rst +++ b/docs/source/library_map.rst @@ -303,7 +303,7 @@ 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. -Results of both are cached on disk. +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 0a1717e18..472168491 100644 --- a/src/qldpc/abstract/groups.py +++ b/src/qldpc/abstract/groups.py @@ -642,11 +642,12 @@ def from_name( 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 warns if a ``magma`` executable on ``PATH`` fails a test run, and runs MAGMA - without the user's startup file. The generators that MAGMA returns can depend on its random - seed, so both the MAGMA subprocess and the manual workflow fix it. 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. + 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. """ diff --git a/src/qldpc/codes/common_test.py b/src/qldpc/codes/common_test.py index 11b48ff55..6e1877f97 100644 --- a/src/qldpc/codes/common_test.py +++ b/src/qldpc/codes/common_test.py @@ -359,8 +359,8 @@ def test_permutation_automorphism_group( code: codes.ClassicalCode = codes.HammingCode(2, field=2) automorphisms = "\n(1,2)\n(2,3)\n" - # when GAP is not installed, or the user declines the manual GAP workflow, warn with the MAGMA - # hint before asking whether GAP is available, and then raise an error + # 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 diff --git a/src/qldpc/external/_groups.py b/src/qldpc/external/_groups.py index 021c1af73..0c807abf1 100644 --- a/src/qldpc/external/_groups.py +++ b/src/qldpc/external/_groups.py @@ -27,7 +27,8 @@ _GROUPNAMES_URL = "https://people.maths.bris.ac.uk/~matyd/GroupNames/" -# MAGMA's generators of a group can depend on its random seed, so both MAGMA workflows fix the seed +# 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 @@ -88,9 +89,9 @@ def get_generators_from_magma(group: str) -> _GeneratorsList: 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 fix it. 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. + 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