Skip to content

Run a local MAGMA executable for with_magma=True, and let QLDPC_AUTOMORPHISM_BACKEND choose it by default - #1063

Open
perlinm wants to merge 7 commits into
mainfrom
feat/local-magma
Open

perlinm wants to merge 7 commits into
mainfrom
feat/local-magma

Conversation

@perlinm

@perlinm perlinm commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Closes #389. qLDPC could use MAGMA only through a manual workflow, in which it printed a command and the user pasted MAGMA's output back. This pull request runs a local MAGMA automatically when one is available, and lets users make MAGMA the default for permutation automorphism groups.

Changes

  • Running MAGMA: with_magma=True (in get_permutation_automorphism_group and the transversal-gate functions) and Group.from_name(..., from_magma=True) try the disk cache, then a magma on PATH that passes a test run, then the manual workflow. They never fall back to GAP. The new private module qldpc/external/_magma.py runs magma -b -n <script> with standard input closed. The script turns off echoing, wrapping, and paging, stops at the first error, and prints markers around the output, which qLDPC checks instead of the exit status. An error that MAGMA reports raises a ValueError. Any other failure warns and falls back to the manual workflow.
  • Default: with_magma now defaults to None, which follows the environment variable QLDPC_AUTOMORPHISM_BACKEND: magma selects MAGMA, unset or gap selects GAP, and any other value raises. An explicit with_magma always wins. With the variable unset, behavior is unchanged. The variable does not affect Group.from_name, whose from_magma says which language the caller's command is in: GAP's DihedralGroup(4) has order 4, but MAGMA's has order 8.
  • Seed: MAGMA's generators can depend on its random seed, so both MAGMA workflows start the command with SetSeed(1);. The disk-cache key includes this prefix, so MAGMA results cached before this change are not reused.
  • Parser: the MAGMA output parser now accepts only lines made entirely of cycles. Before, it read any digits in parentheses as a cycle, so output such as GL(2, GF(3)) became a wrong group that was then cached.
  • Warning: the GAP warning mentions QLDPC_AUTOMORPHISM_BACKEND, and says when a magma is on PATH but GAP needs copy/paste. It is now raised before GAP's availability prompt.

Validation

CI has no MAGMA, so tests mock it. The MAGMA output that the tests use was recorded by running qLDPC's exact scripts on MAGMA's online calculator (V2.29-10), and the tests pin those scripts and the command-line options. On the calculator, generators of a 48-point code's group differed between runs without SetSeed(1), and agreed with it. Long output wrapped only after commas, at every width from 16 to 100 columns.

Before merging: check with a local MAGMA

The calculator cannot show what only a local magma does: its exit status, banner, echoing, and behavior without a licence. Someone with a licensed MAGMA should check out this branch, merge main into it, and install it with python -m pip install -e '.[dev]'. They should then save the script below as check_local_magma.py in the repository root, run PYTHONPATH=src python check_local_magma.py, and paste the output here. Every check should print PASS. The script bypasses qLDPC's disk cache. If a merge renames a private name that the script uses, update the script.

check_local_magma.py
"""Check qLDPC's automatic MAGMA workflow against a local MAGMA installation."""

import itertools
import os
import shutil
import subprocess
import tempfile

import galois
import numpy as np

import qldpc.cache
from qldpc import codes
from qldpc.external import _groups, _magma

qldpc.cache.get_disk_cache = lambda *args, **kwargs: {}  # always run MAGMA, and cache nothing
failures = []


def check(name: str, passed: bool, details: object = "") -> None:
    """Report one check."""
    print(f"{'PASS' if passed else 'FAIL'}: {name}")
    if not passed and details:
        print(f"    {details!r}")
    if not passed:
        failures.append(name)


def run_script(command: str) -> subprocess.CompletedProcess[str]:
    """Run qLDPC's MAGMA script for a command, and return the raw result."""
    with tempfile.TemporaryDirectory() as directory:
        path = os.path.join(directory, "command.m")
        with open(path, "w") as file:
            file.write(_magma._get_script(command))
        return subprocess.run(
            [*_magma._get_arguments(), path],
            stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False,
        )


def brute_force_order(code: codes.ClassicalCode) -> int:
    """Count the bit permutations that preserve a small code."""
    generator = code.generator.view(np.ndarray)
    count = 0
    for permutation in itertools.permutations(range(len(code))):
        stacked = code.field(np.vstack([generator, generator[:, permutation]]))
        count += int(stacked.row_space().shape[0] == code.dimension)
    return count


print("MAGMA on PATH:", shutil.which("magma"))
print("magma -V:", subprocess.run(["magma", "-V"], capture_output=True, text=True).stdout.strip())

# 1. the test run, and MAGMA's raw output and exit status for a script that succeeds
check("1a. is_callable() is True", _magma.is_callable())
result = run_script("1 + 1;")
check(
    "1b. raw output is exactly the markers around 2 (no banner, no echo)",
    result.stdout == "__qldpc_begin__\n2\n__qldpc_end__\n",
    result,
)
print(f"INFO: exit status after a successful script: {result.returncode}")

# 2. groups computed with MAGMA through qLDPC's public interface, against independent orders
group = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[[1,1]])));"
check("2a. repetition code [2,1]", _groups.get_generators_from_magma(group) == [[(0, 1)]])
order = codes.HammingCode(3).get_permutation_automorphism_group(with_magma=True).order
check("2b. Hamming [7,4] group has order 168", order == 168, order)
field = galois.GF(8, irreducible_poly="x^3 + x^2 + 1")
code = codes.ClassicalCode(field([[1, 2, 6], [0, 1, 1]]))
order = code.get_permutation_automorphism_group(with_magma=True).order
check("2c. GF(8) code matches brute force", order == brute_force_order(code), order)

# 3. an error in a command
bad = "PermutationGroup(LinearCode(Matrix(GF(2),1,2,[1])));"
try:
    _magma.get_output(bad)
    check("3a. MAGMAError raised", False, "no error")
except _magma.MAGMAError:
    check("3a. MAGMAError raised", True)
result = run_script(bad)
check("3b. MAGMA quits before the end marker", "__qldpc_end__" not in result.stdout, result)
print(f"INFO: exit status after an error: {result.returncode}")

# 4. long output: one line per generator, no echo, and wrapped output parses alike
long_output = _magma.get_output("DihedralGroup(GrpPerm, 60);")
generators = _groups._parse_magma_generators(long_output)
check("4a. two generators of the dihedral group", len(generators) == 2, long_output)
check("4b. no echoed script text", "Set" not in long_output and "Dihedral" not in long_output)
wrapped = _magma.get_output("SetColumns(80); DihedralGroup(GrpPerm, 60);")
same = _groups._parse_magma_generators(wrapped) == generators
check("4c. output wrapped at 80 columns parses alike", same, wrapped)

# 5. the fixed seed: separate MAGMA processes give the same generators of a group with many
# generating sets (without SetSeed, these differ between runs)
row = lambda bits: ",".join(bits)  # noqa: E731
block = f"[[{row('1' * 24 + '0' * 24)}],[{row('0' * 24 + '1' * 24)}]]"
command = f"SetSeed({_groups._MAGMA_SEED}); "
command += f"PermutationGroup(LinearCode(Matrix(GF(2),2,48,{block})));"
runs = [_groups._parse_magma_generators(_magma.get_output(command)) for _ in range(2)]
check("5. seeded runs give the same generators", runs[0] == runs[1])

print("\nALL CHECKS PASSED" if not failures else f"\nFAILED: {failures}")

If a check fails, look here:

  • 1a or 1b: an option in _get_arguments, or a statement in _get_script, both in qldpc/external/_magma.py. Text outside the markers, such as a banner, is harmless.
  • 2a–2c and 4c: _parse_magma_generators in qldpc/external/_groups.py.
  • 3a or 3b: _ERROR_PATTERN or SetQuitOnError in _magma.py.
  • 4a or 4b: _get_script.
  • 5: _MAGMA_SEED in _groups.py.

After a fix, update the recorded scripts and outputs in qldpc/external/_magma_test.py.

perlinm and others added 7 commits November 25, 2026 18:05
…y/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>
…and warn when a magma on PATH fails its test run

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…GAP warning before GAP's availability prompt

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…at they return the same generators

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…e both MAGMA workflows in the docs

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
# Conflicts:
#	docs/source/installation.rst
@perlinm perlinm changed the title Run a local MAGMA executable for with_magma=True Run a local MAGMA executable for with_magma=True, and let QLDPC_AUTOMORPHISM_BACKEND choose it by default Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use a local installation of MAGMA, if available

1 participant