# Interface to Magma#

Sage provides an interface to the Magma computational algebra system. This system provides extensive functionality for number theory, group theory, combinatorics and algebra.

Note

You must have Magma installed on your computer for this interface to work. Magma is not free, so it is not included with Sage, but you can obtain it from http://magma.maths.usyd.edu.au/.

The Magma interface offers three pieces of functionality:

1. `magma_console()` - A function that dumps you into an interactive command-line Magma session.

2. `magma.new(obj)` and alternatively `magma(obj)` - Creation of a Magma object from a Sage object `obj`. This provides a Pythonic interface to Magma. For example, if `f=magma.new(10)`, then `f.Factors()` returns the prime factorization of 10 computed using Magma. If obj is a string containing an arbitrary Magma expression, then the expression is evaluated in Magma to create a Magma object. An example is `magma.new('10 div 3')`, which returns Magma integer 3.

3. `magma.eval(expr)` - Evaluation of the Magma expression `expr`, with the result returned as a string.

Type `magma.[tab]` for a list of all functions available from your Magma. Type `magma.Function?` for Magma’s help about the Magma `Function`.

## Parameters#

Some Magma functions have optional “parameters”, which are arguments that in Magma go after a colon. In Sage, you pass these using named function arguments. For example,

```sage: E = magma('EllipticCurve([0,1,1,-1,0])')                 # optional - magma
sage: E.Rank(Bound = 5)                                        # optional - magma
0
```

## Multiple Return Values#

Some Magma functions return more than one value. You can control how many you get using the `nvals` named parameter to a function call:

```sage: n = magma(100)                                           # optional - magma
sage: n.IsSquare(nvals = 1)                                    # optional - magma
true
sage: n.IsSquare(nvals = 2)                                    # optional - magma
(true, 10)
sage: n = magma(-2006)                                         # optional - magma
sage: n.Factorization()                                        # optional - magma
[ <2, 1>, <17, 1>, <59, 1> ]
sage: n.Factorization(nvals=2)                                 # optional - magma
([ <2, 1>, <17, 1>, <59, 1> ], -1)
```

We verify that an obviously principal ideal is principal:

```sage: _ = magma.eval('R<x> := PolynomialRing(RationalField())')    # optional - magma
sage: O = magma.NumberField('x^2+23').MaximalOrder()               # optional - magma
sage: I = magma('ideal<%s|%s.1>'%(O.name(),O.name()))              # optional - magma
sage: I.IsPrincipal(nvals=2)                                       # optional - magma
(true, [1, 0])
```

## Long Input#

The Magma interface reads in even very long input (using files) in a robust manner.

```sage: t = '"%s"'%10^10000   # ten thousand character string.       # optional - magma
sage: a = magma.eval(t)                                            # optional - magma
sage: a = magma(t)                                                 # optional - magma
```

## Garbage Collection#

There is a subtle point with the Magma interface, which arises from how garbage collection works. Consider the following session:

First, create a matrix m in Sage:

```sage: m=matrix(ZZ,2,[1,2,3,4])                                     # optional - magma
```

Then I create a corresponding matrix A in Magma:

```sage: A = magma(m)                                                 # optional - magma
```

It is called _sage_[…] in Magma:

```sage: s = A.name(); s                                              # optional - magma
'_sage_[...]'
```

It’s there:

```sage: magma.eval(s)                                                # optional - magma
'[1 2]\n[3 4]'
```

Now I delete the reference to that matrix:

```sage: del A                                                        # optional - magma
```

Now _sage_[…] is “zeroed out” in the Magma session:

```sage: magma.eval(s)                                                # optional - magma
'0'
```

If Sage did not do this garbage collection, then every single time you ever create any magma object from a sage object, e.g., by doing magma(m), you would use up a lot of memory in that Magma session. This would lead to a horrible memory leak situation, which would make the Magma interface nearly useless for serious work.

## Other Examples#

We compute a space of modular forms with character.

```sage: N = 20
sage: D = 20
sage: eps_top = fundamental_discriminant(D)
sage: eps = magma.KroneckerCharacter(eps_top, RationalField())        # optional - magma
sage: M2 = magma.ModularForms(eps)                                    # optional - magma
sage: print(M2)                                                       # optional - magma
Space of modular forms on Gamma_1(5) ...
sage: print(M2.Basis())                                               # optional - magma
[
1 + 10*q^2 + 20*q^3 + 20*q^5 + 60*q^7 + ...
q + q^2 + 2*q^3 + 3*q^4 + 5*q^5 + 2*q^6 + ...
]
```

In Sage/Python (and sort of C++) coercion of an element x into a structure S is denoted by S(x). This also works for the Magma interface:

```sage: G = magma.DirichletGroup(20)                                    # optional - magma
sage: G.AssignNames(['a', 'b'])                                       # optional - magma
sage: (G.1).Modulus()                                                 # optional - magma
20
sage: e = magma.DirichletGroup(40)(G.1)                               # optional - magma
sage: print(e)                                                        # optional - magma
Kronecker character -4 in modulus 40
sage: print(e.Modulus())                                              # optional - magma
40
```

We coerce some polynomial rings into Magma:

```sage: R.<y> = PolynomialRing(QQ)
sage: S = magma(R)                                                    # optional - magma
sage: print(S)                                                        # optional - magma
Univariate Polynomial Ring in y over Rational Field
sage: S.1                                                             # optional - magma
y
```

This example illustrates that Sage doesn’t magically extend how Magma implicit coercion (what there is, at least) works. The errors below are the result of Magma having a rather limited automatic coercion system compared to Sage’s:

```sage: R.<x> = ZZ[]
sage: x * 5
5*x
sage: x * 1.0
x
sage: x * (2/3)
2/3*x
sage: y = magma(x)                                                    # optional - magma
sage: y * 5                                                           # optional - magma
5*x
sage: y * 1.0                                                         # optional - magma
\$.1
sage: y * (2/3)                                                       # optional - magma
Traceback (most recent call last):
...
TypeError: Error evaluating Magma code.
...
Argument types given: RngUPolElt[RngInt], FldRatElt
```

AUTHORS:

• William Stein (2005): initial version

• William Stein (2006-02-28): added extensive tab completion and interactive IPython documentation support.

• William Stein (2006-03-09): added nvals argument for magma.functions…

class sage.interfaces.magma.Magma(script_subdirectory=None, logfile=None, server=None, server_tmpdir=None, user_config=False, seed=None, command=None)#

Bases: `ExtraTabCompletion`, `Expect`

Interface to the Magma interpreter.

Type `magma.[tab]` for a list of all the functions available from your Magma install. Type `magma.Function?` for Magma’s help about a given `Function` Type `magma(...)` to create a new Magma object, and `magma.eval(...)` to run a string using Magma (and get the result back as a string).

Note

If you do not own a local copy of Magma, try using the `magma_free` command instead, which uses the free demo web interface to Magma.

If you have ssh access to a remote installation of Magma, you can also set the `server` parameter to use it.

EXAMPLES:

You must use nvals = 0 to call a function that doesn’t return anything, otherwise you’ll get an error. (nvals is the number of return values.)

```sage: magma.SetDefaultRealFieldPrecision(200, nvals=0)  # magma >= v2.12; optional - magma
sage: magma.eval('1.1')   # optional - magma
'1.1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
sage: magma.SetDefaultRealFieldPrecision(30, nvals=0)  # optional - magma
```
Attach(filename)#

Attach the given file to the running instance of Magma.

Attaching a file in Magma makes all intrinsics defined in the file available to the shell. Moreover, if the file doesn’t start with the `freeze;` command, then the file is reloaded whenever it is changed. Note that functions and procedures defined in the file are not available. For only those, use `magma.load(filename)`.

INPUT:

• `filename` - a string

EXAMPLES: Attaching a file that exists is fine:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']               # optional - magma
sage: magma.attach('%s/magma/sage/basic.m'%SAGE_EXTCODE)    # optional - magma
```

Attaching a file that doesn’t exist raises an exception:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']                 # optional - magma
sage: magma.attach('%s/magma/sage/basic2.m'%SAGE_EXTCODE)     # optional - magma
Traceback (most recent call last):
...
RuntimeError: Error evaluating Magma code...
```
AttachSpec(filename)#

Attach the given spec file to the running instance of Magma.

This can attach numerous other files to the running Magma (see the Magma documentation for more details).

INPUT:

• `filename` - a string

EXAMPLES:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']            # optional - magma
sage: magma.attach_spec('%s/magma/spec'%SAGE_EXTCODE)    # optional - magma
sage: magma.attach_spec('%s/magma/spec2'%SAGE_EXTCODE)   # optional - magma
Traceback (most recent call last):
...
RuntimeError: Can't open package spec file .../magma/spec2 for reading (No such file or directory)
```

Get the number of threads used in Magma.

EXAMPLES:

```sage: magma.set_nthreads(2)                #optional - magma
2
```
GetVerbose(type)#

Get the verbosity level of a given algorithm class etc. in Magma.

INPUT:

• `type` - string (e.g. ‘Groebner’), see Magma documentation

EXAMPLES:

```sage: magma.set_verbose("Groebner", 2)        # optional - magma
sage: magma.get_verbose("Groebner")           # optional - magma
2
```

Set the number of threads used for parallelized algorithms in Magma.

INPUT:

• `n` - number of threads

EXAMPLES:

```sage: magma.set_nthreads(2)                #optional - magma
2
```
SetVerbose(type, level)#

Set the verbosity level for a given algorithm, class, etc. in Magma.

INPUT:

• `type` – string (e.g. ‘Groebner’)

• `level` – integer >= 0

EXAMPLES:

```sage: magma.set_verbose("Groebner", 2)      # optional - magma
sage: magma.get_verbose("Groebner")         # optional - magma
2
```
attach(filename)#

Attach the given file to the running instance of Magma.

Attaching a file in Magma makes all intrinsics defined in the file available to the shell. Moreover, if the file doesn’t start with the `freeze;` command, then the file is reloaded whenever it is changed. Note that functions and procedures defined in the file are not available. For only those, use `magma.load(filename)`.

INPUT:

• `filename` - a string

EXAMPLES: Attaching a file that exists is fine:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']               # optional - magma
sage: magma.attach('%s/magma/sage/basic.m'%SAGE_EXTCODE)    # optional - magma
```

Attaching a file that doesn’t exist raises an exception:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']                 # optional - magma
sage: magma.attach('%s/magma/sage/basic2.m'%SAGE_EXTCODE)     # optional - magma
Traceback (most recent call last):
...
RuntimeError: Error evaluating Magma code...
```
attach_spec(filename)#

Attach the given spec file to the running instance of Magma.

This can attach numerous other files to the running Magma (see the Magma documentation for more details).

INPUT:

• `filename` - a string

EXAMPLES:

```sage: SAGE_EXTCODE = SAGE_ENV['SAGE_EXTCODE']            # optional - magma
sage: magma.attach_spec('%s/magma/spec'%SAGE_EXTCODE)    # optional - magma
sage: magma.attach_spec('%s/magma/spec2'%SAGE_EXTCODE)   # optional - magma
Traceback (most recent call last):
...
RuntimeError: Can't open package spec file .../magma/spec2 for reading (No such file or directory)
```
bar_call(left, name, gens, nvals=1)#

This is a wrapper around the Magma constructor

nameleft gens

returning nvals.

INPUT:

• `left` - something coerceable to a magma object

• `name` - name of the constructor, e.g., sub, quo, ideal, etc.

• `gens` - if a list/tuple, each item is coerced to magma; otherwise gens itself is converted to magma

• `nvals` - positive integer; number of return values

OUTPUT: a single magma object if nvals == 1; otherwise a tuple of nvals magma objects.

EXAMPLES: The bar_call function is used by the sub, quo, and ideal methods of Magma elements. Here we illustrate directly using bar_call to create quotients:

```sage: V = magma.RModule(ZZ,3)    # optional - magma
sage: V                          # optional - magma
RModule(IntegerRing(), 3)
sage: magma.bar_call(V, 'quo', [[1,2,3]], nvals=1)  # optional - magma
RModule(IntegerRing(), 2)
sage: magma.bar_call(V, 'quo', [[1,2,3]], nvals=2)  # optional - magma
(RModule(IntegerRing(), 2),
Mapping from: RModule(IntegerRing(), 3) to RModule(IntegerRing(), 2))
sage: magma.bar_call(V, 'quo', V, nvals=2)          # optional - magma
(RModule(IntegerRing(), 0),
Mapping from: RModule(IntegerRing(), 3) to RModule(IntegerRing(), 0))
```
chdir(dir)#

Change the Magma interpreter’s current working directory.

INPUT:

• `dir` – a string

EXAMPLES:

```sage: magma.chdir('/')                 # optional - magma
sage: magma.eval('System("pwd")')      # optional - magma
'/'
```
clear(var)#

Clear the variable named var and make it available to be used again.

INPUT:

• `var` - a string

EXAMPLES:

```sage: magma = Magma()      # optional - magma
sage: magma.clear('foo')   # sets foo to 0 in magma; optional - magma
sage: magma.eval('foo')    # optional - magma
'0'
```

Because we cleared foo, it is set to be used as a variable name in the future:

```sage: a = magma('10')      # optional - magma
sage: a.name()             # optional - magma
'foo'
```

The following tests that the whole variable clearing and freeing system is working correctly.

```sage: magma = Magma()      # optional - magma
sage: a = magma('100')     # optional - magma
sage: a.name()             # optional - magma
'_sage_'
sage: del a                # optional - magma
sage: b = magma('257')     # optional - magma
sage: b.name()             # optional - magma
'_sage_'
sage: del b                # optional - magma
sage: magma('_sage_')   # optional - magma
0
```
console()#

Run a command line Magma session. This session is completely separate from this Magma interface.

EXAMPLES:

```sage: magma.console()             # not tested
Magma V2.14-9     Sat Oct 11 2008 06:36:41 on one      [Seed = 1157408761]
Type ? for help.  Type <Ctrl>-D to quit.
>
Total time: 2.820 seconds, Total memory usage: 3.95MB
```
cputime(t=None)#

Return the CPU time in seconds that has elapsed since this Magma session started. This is a floating point number, computed by Magma.

If t is given, then instead return the floating point time from when t seconds had elapsed. This is useful for computing elapsed times between two points in a running program.

INPUT:

• `t` - float (default: None); if not None, return cputime since t

OUTPUT:

• `float` - seconds

EXAMPLES:

```sage: type(magma.cputime())         # optional - magma
<... 'float'>
sage: magma.cputime()                # random, optional - magma
1.9399999999999999
sage: t = magma.cputime()            # optional - magma
sage: magma.cputime(t)               # random, optional - magma
0.02
```
eval(x, strip=True, **kwds)#

Evaluate the given block x of code in Magma and return the output as a string.

INPUT:

• `x` - string of code

• `strip` - ignored

OUTPUT: string

EXAMPLES:

We evaluate a string that involves assigning to a variable and printing.

```sage: magma.eval("a := 10;print 2+a;")      # optional - magma
'12'
```

We evaluate a large input line (note that no weird output appears and that this works quickly).

```sage: magma.eval("a := %s;"%(10^10000))    # optional - magma
''
```

Verify that github issue #9705 is fixed:

```sage: nl=chr(10) # newline character
sage: magma.eval(  # optional - magma
....: "_<x>:=PolynomialRing(Rationals());"+nl+
....: "repeat"+nl+
....: "  g:=3*b*x^4+18*c*x^3-6*b^2*x^2-6*b*c*x-b^3-9*c^2 where b:=Random([-10..10]) where c:=Random([-10..10]);"+nl+
....: "until g ne 0 and Roots(g) ne [];"+nl+
....: "print "success";")
'success'
```

Verify that github issue #11401 is fixed:

```sage: nl=chr(10) # newline character
sage: magma.eval("a:=3;"+nl+"b:=5;") == nl  # optional - magma
True
sage: magma.eval("[a,b];")                  # optional - magma
'[ 3, 5 ]'
```
function_call(function, args=[], params={}, nvals=1)#

Return result of evaluating a Magma function with given input, parameters, and asking for nvals as output.

INPUT:

• `function` - string, a Magma function name

• `args` - list of objects coercible into this magma interface

• `params` - Magma parameters, passed in after a colon

• `nvals` - number of return values from the function to ask Magma for

OUTPUT: MagmaElement or tuple of nvals MagmaElement’s

EXAMPLES:

```sage: magma.function_call('Factorization', 100)    # optional - magma
[ <2, 2>, <5, 2> ]
sage: magma.function_call('NextPrime', 100, {'Proof':False})    # optional - magma
101
sage: magma.function_call('PolynomialRing', [QQ,2])      # optional - magma
Polynomial ring of rank 2 over Rational Field
Order: Lexicographical
Variables: \$.1, \$.2
```

Next, we illustrate multiple return values:

```sage: magma.function_call('IsSquare', 100)         # optional - magma
true
sage: magma.function_call('IsSquare', 100, nvals=2)     # optional - magma
(true, 10)
sage: magma.function_call('IsSquare', 100, nvals=3)     # optional - magma
Traceback (most recent call last):
...
RuntimeError: Error evaluating Magma code...
Runtime error in :=: Expected to assign 3 value(s) but only computed 2 value(s)
```
get(var)#

Get the value of the variable var.

INPUT:

• `var` - string; name of a variable defined in the Magma session

OUTPUT:

• `string` - string representation of the value of the variable.

EXAMPLES:

```sage: magma.set('abc', '2 + 3/5')     # optional - magma
sage: magma.get('abc')                # optional - magma
'13/5'
```

Get the number of threads used in Magma.

EXAMPLES:

```sage: magma.set_nthreads(2)                #optional - magma
2
```
get_verbose(type)#

Get the verbosity level of a given algorithm class etc. in Magma.

INPUT:

• `type` - string (e.g. ‘Groebner’), see Magma documentation

EXAMPLES:

```sage: magma.set_verbose("Groebner", 2)        # optional - magma
sage: magma.get_verbose("Groebner")           # optional - magma
2
```
help(s)#

Return Magma help on string s.

This returns what typing ?s would return in Magma.

INPUT:

• `s` - string

OUTPUT: string

EXAMPLES:

```sage: magma.help("NextPrime")       # optional - magma
===============================================================================
PATH: /magma/ring-field-algebra/integer/prime/next-previous/NextPrime
KIND: Intrinsic
===============================================================================
NextPrime(n) : RngIntElt -> RngIntElt
NextPrime(n: parameter) : RngIntElt -> RngIntElt
...
```
ideal(L)#

Return the Magma ideal defined by L.

INPUT:

• `L` - a list of elements of a Sage multivariate polynomial ring.

OUTPUT: The magma ideal generated by the elements of L.

EXAMPLES:

```sage: R.<x,y> = QQ[]
sage: magma.ideal([x^2, y^3*x])         # optional - magma
Ideal of Polynomial ring of rank 2 over Rational Field
Variables: x, y
Homogeneous
Basis:
[
x^2,
x*y^3
]
```

Load the file with given filename using the ‘load’ command in the Magma shell.

Loading a file in Magma makes all the functions and procedures in the file available. The file should not contain any intrinsics (or you’ll get errors). It also runs code in the file, which can produce output.

INPUT:

• `filename` - string

EXAMPLES:

```sage: from tempfile import NamedTemporaryFile as NTF
sage: with NTF(mode="w+t", suffix=".m") as f:  # optional - magma
....:     _ = f.write('function f(n) return n^2; end function;\nprint "hi";')
hi
sage: magma('f(12)')  # optional - magma
144
```
objgens(value, gens)#

Create a new object with given value and gens.

INPUT:

• `value` - something coercible to an element of this Magma

interface

• `gens` - string; comma separated list of variable names

OUTPUT: new Magma element that is equal to value with given gens

EXAMPLES:

```sage: R = magma.objgens('PolynomialRing(Rationals(),2)', 'alpha,beta')    # optional - magma
sage: R.gens()          # optional - magma
[alpha, beta]
```

Because of how Magma works you can use this to change the variable names of the generators of an object:

```sage: S = magma.objgens(R, 'X,Y')          # optional - magma
sage: R                                    # optional - magma
Polynomial ring of rank 2 over Rational Field
Order: Lexicographical
Variables: X, Y
sage: S                                    # optional - magma
Polynomial ring of rank 2 over Rational Field
Order: Lexicographical
Variables: X, Y
```
set(var, value)#

Set the variable var to the given value in the Magma interpreter.

INPUT:

• `var` - string; a variable name

• `value` - string; what to set var equal to

EXAMPLES:

```sage: magma.set('abc', '2 + 3/5')       # optional - magma
sage: magma('abc')                      # optional - magma
13/5
```

Set the number of threads used for parallelized algorithms in Magma.

INPUT:

• `n` - number of threads

EXAMPLES:

```sage: magma.set_nthreads(2)                #optional - magma
2
```
set_seed(seed=None)#

Set the seed for the Magma interpreter.

The seed should be an integer.

EXAMPLES:

```sage: m = Magma() # optional - magma
sage: m.set_seed(1) # optional - magma
1
sage: [m.Random(100) for i in range(5)] # optional - magma
[14, 81, 45, 75, 67]
```
set_verbose(type, level)#

Set the verbosity level for a given algorithm, class, etc. in Magma.

INPUT:

• `type` – string (e.g. ‘Groebner’)

• `level` – integer >= 0

EXAMPLES:

```sage: magma.set_verbose("Groebner", 2)      # optional - magma
sage: magma.get_verbose("Groebner")         # optional - magma
2
```
version()#

Return the version of Magma that you have in your PATH on your computer.

OUTPUT:

• `numbers` - 3-tuple: major, minor, etc.

• `string` - version as a string

EXAMPLES:

```sage: magma.version()       # random, optional - magma
((2, 14, 9), 'V2.14-9')
```
class sage.interfaces.magma.MagmaElement(parent, value, is_name=False, name=None)#

Bases: `ExtraTabCompletion`, `ExpectElement`, `MagmaElement`

AssignNames(names)#

EXAMPLES:

```sage: S = magma.PolynomialRing(magma.Integers(), 2)   # optional - magma
sage: S.AssignNames(['a', 'b'])       # optional - magma
sage: S.1                             # optional - magma
a
sage: S.1^2 + S.2 # optional - magma
a^2 + b
```
assign_names(names)#

EXAMPLES:

```sage: S = magma.PolynomialRing(magma.Integers(), 2)   # optional - magma
sage: S.AssignNames(['a', 'b'])       # optional - magma
sage: S.1                             # optional - magma
a
sage: S.1^2 + S.2 # optional - magma
a^2 + b
```
eval(*args)#

Evaluate self at the inputs.

INPUT:

• `*args` – import arguments

OUTPUT: self(*args)

EXAMPLES:

```sage: f = magma('Factorization')            # optional - magma
sage: f.evaluate(15)                        # optional - magma
[ <3, 1>, <5, 1> ]
sage: f(15)                                 # optional - magma
[ <3, 1>, <5, 1> ]
sage: f = magma('GCD')                      # optional - magma
sage: f.evaluate(15,20)                     # optional - magma
5

sage: m = matrix(QQ, 2, 2, [2,3,5,7])      # optional - magma
sage: f = magma('ElementaryDivisors')      # optional - magma
sage: f.evaluate(m)                        # optional - magma
[ 1, 1 ]
```
evaluate(*args)#

Evaluate self at the inputs.

INPUT:

• `*args` – import arguments

OUTPUT: self(*args)

EXAMPLES:

```sage: f = magma('Factorization')            # optional - magma
sage: f.evaluate(15)                        # optional - magma
[ <3, 1>, <5, 1> ]
sage: f(15)                                 # optional - magma
[ <3, 1>, <5, 1> ]
sage: f = magma('GCD')                      # optional - magma
sage: f.evaluate(15,20)                     # optional - magma
5

sage: m = matrix(QQ, 2, 2, [2,3,5,7])      # optional - magma
sage: f = magma('ElementaryDivisors')      # optional - magma
sage: f.evaluate(m)                        # optional - magma
[ 1, 1 ]
```
gen(n)#

Return the n-th generator of this Magma element. Note that generators are 1-based in Magma rather than 0 based!

INPUT:

• `n` - a positive integer

OUTPUT: MagmaElement

EXAMPLES:

```sage: k.<a> = GF(9)
sage: magma(k).gen(1)         # optional -- magma
a
sage: R.<s,t,w> = k[]
sage: m = magma(R)            # optional -- magma
sage: m.gen(1)                # optional -- magma
s
sage: m.gen(2)                # optional -- magma
t
sage: m.gen(3)                # optional -- magma
w
sage: m.gen(0)                # optional -- magma
Traceback (most recent call last):
...
IndexError: index must be positive since Magma indexes are 1-based
sage: m.gen(4)                # optional -- magma
Traceback (most recent call last):
...
IndexError: list index out of range
```
gen_names()#

Return list of Magma variable names of the generators of self.

Note

As illustrated below, these are not the print names of the the generators of the Magma object, but special variable names in the Magma session that reference the generators.

EXAMPLES:

```sage: R.<x,zw> = QQ[]
sage: S = magma(R)               # optional - magma
sage: S.gen_names()              # optional - magma
('_sage_[...]', '_sage_[...]')
sage: magma(S.gen_names())    # optional - magma
zw
```
gens()#

Return generators for `self`.

If self is named X in Magma, this function evaluates X.1, X.2, etc., in Magma until an error occurs. It then returns a Sage tuple of the resulting X.i. Note - I don’t think there is a Magma command that returns the list of valid X.i. There are numerous ad hoc functions for various classes but nothing systematic. This function gets around that problem. Again, this is something that should probably be reported to the Magma group and fixed there.

AUTHORS:

• William Stein (2006-07-02)

EXAMPLES:

```sage: magma("VectorSpace(RationalField(),3)").gens()         # optional - magma
((1 0 0), (0 1 0), (0 0 1))
sage: magma("AbelianGroup(EllipticCurve([1..5]))").gens()    # optional - magma
(\$.1,)
```
get_magma_attribute(attrname)#

Return value of a given Magma attribute. This is like selfattrname in Magma.

OUTPUT: MagmaElement

EXAMPLES:

```sage: V = magma("VectorSpace(RationalField(),10)")   # optional - magma
sage: V.set_magma_attribute('M','"hello"')           # optional - magma
sage: V.get_magma_attribute('M')                     # optional - magma
hello
sage: V.M                                            # optional - magma
hello
```
ideal(gens)#

Return the ideal of self with given list of generators.

INPUT:

• `gens` - object or list/tuple of generators

OUTPUT:

• `magma element` - a Magma ideal

EXAMPLES:

```sage: R = magma('PolynomialRing(RationalField())')        # optional - magma
sage: R.assign_names(['x'])                               # optional - magma
sage: x = R.1                                             # optional - magma
sage: R.ideal([x^2 - 1, x^3 - 1])                         # optional - magma
Ideal of Univariate Polynomial Ring in x over Rational Field generated by x - 1
```
list_attributes()#

Return the attributes of self, obtained by calling the ListAttributes function in Magma.

OUTPUT: list of strings

EXAMPLES: We observe that vector spaces in Magma have numerous funny and mysterious attributes.

```sage: V = magma("VectorSpace(RationalField(),2)")        # optional - magma
sage: v = V.list_attributes(); v.sort()               # optional - magma
sage: print(v)     # optional - magma
['Coroots', 'Involution', ..., 'p', 'ssbasis', 'weights']
```
methods(any=False)#

Return signatures of all Magma intrinsics that can take self as the first argument, as strings.

INPUT:

• `any` – (bool: default is False) if True, also include signatures with Any as first argument.

OUTPUT: list of strings

EXAMPLES:

```sage: v = magma('2/3').methods()          # optional - magma
sage: v                                # optional - magma
"'*'..."
```
quo(gens, **args)#

Return the quotient of self by the given object or list of generators.

INPUT:

• `gens` - object or list/tuple of generators

• further named arguments that are ignored

OUTPUT:

• `magma element` - the quotient object

• `magma element` - mapping from self to the quotient object

EXAMPLES:

```sage: V = magma('VectorSpace(RationalField(),3)')       # optional - magma
sage: V.quo([[1,2,3], [1,1,2]])                         # optional - magma
(Full Vector space of degree 1 over Rational Field, Mapping from: Full Vector space of degree 3 over Rational Field to Full Vector space of degree 1 over Rational Field)
```

We illustrate quotienting out by an object instead of a list of generators:

```sage: W = V.sub([ [1,2,3], [1,1,2] ])                   # optional - magma
sage: V.quo(W)                                          # optional - magma
(Full Vector space of degree 1 over Rational Field, Mapping from: Full Vector space of degree 3 over Rational Field to Full Vector space of degree 1 over Rational Field)
```

We quotient a ZZ module out by a submodule.

```sage: V = magma.RModule(ZZ,3); V # optional - magma
RModule(IntegerRing(), 3)
sage: W, phi = V.quo([[1,2,3]])  # optional - magma
sage: W                          # optional - magma
RModule(IntegerRing(), 2)
sage: phi                        # optional - magma
Mapping from: RModule(IntegerRing(), 3) to RModule(IntegerRing(), 2)
```
set_magma_attribute(attrname, value)#

INPUT: attrname - string value - something coercible to a MagmaElement

EXAMPLES:

```sage: V = magma("VectorSpace(RationalField(),2)")   # optional - magma
sage: V.set_magma_attribute('M',10)                 # optional - magma
sage: V.get_magma_attribute('M')                    # optional - magma
10
sage: V.M                                           # optional - magma
10
```
sub(gens)#

Return the sub-object of self with given gens.

INPUT:

• `gens` – object or list/tuple of generators

EXAMPLES:

```sage: V = magma('VectorSpace(RationalField(),3)')       # optional - magma
sage: W = V.sub([ [1,2,3], [1,1,2] ]); W                # optional - magma
Vector space of degree 3, dimension 2 over Rational Field
Generators:
(1 2 3)
(1 1 2)
Echelonized basis:
(1 0 1)
(0 1 1)
```
class sage.interfaces.magma.MagmaFunction(parent, name)#

Bases: `ExpectFunction`

class sage.interfaces.magma.MagmaFunctionElement(obj, name)#
class sage.interfaces.magma.MagmaGBDefaultContext(magma=None)#

Bases: `object`

Context to force preservation of verbosity options for Magma’s Groebner basis computation.

class sage.interfaces.magma.MagmaGBLogPrettyPrinter(verbosity=1, style='magma')#

Bases: `object`

A device which filters Magma Groebner basis computation logs.

app_inpt = re.compile('^Append\\(~_sage_, 0\\);\$')#
cmd_inpt = re.compile('^>>>\$')#
deg_curr = re.compile('^Basis length\\: (\\d+), queue length\\: (\\d+), step degree\\: (\\d+), num pairs\\: (\\d+)\$')#
flush()#

EXAMPLES:

```sage: from sage.interfaces.magma import MagmaGBLogPrettyPrinter
sage: logs = MagmaGBLogPrettyPrinter()
sage: logs.flush()
```
pol_curr = re.compile('^Number of pair polynomials\\: (\\d+), at (\\d+) column\\(s\\), .*')#
write(s)#

EXAMPLES:

```sage: P.<x,y,z> = GF(32003)[]
sage: I = sage.rings.ideal.Katsura(P)
sage: _ = I.groebner_basis('magma',prot=True) # indirect doctest, optional - magma
********************
FAUGERE F4 ALGORITHM
********************
...
Total Faugere F4 time: ..., real time: ...
```
sage.interfaces.magma.extcode_dir(iface=None)#

Return directory that contains all the Magma extcode. This is put in a writable directory owned by the user, since when attached, Magma has to write sig and lck files.

EXAMPLES:

```sage: sage.interfaces.magma.extcode_dir()
'...dir_.../data/'
```
sage.interfaces.magma.is_MagmaElement(x)#

Return True if `x` is of type `MagmaElement`, and False otherwise.

INPUT:

• `x` - any object

OUTPUT: bool

EXAMPLES:

```sage: from sage.interfaces.magma import is_MagmaElement
sage: is_MagmaElement(2)
doctest:...: DeprecationWarning: the function is_MagmaElement is deprecated; use isinstance(x, sage.interfaces.abc.MagmaElement) instead
See https://github.com/sagemath/sage/issues/34804 for details.
False
sage: is_MagmaElement(magma(2))                    # optional - magma
True
```
sage.interfaces.magma.magma_console()#

Run a command line Magma session.

EXAMPLES:

```sage: magma_console()             # not tested
Magma V2.14-9     Sat Oct 11 2008 06:36:41 on one      [Seed = 1157408761]
Type ? for help.  Type <Ctrl>-D to quit.
>
Total time: 2.820 seconds, Total memory usage: 3.95MB
```
sage.interfaces.magma.magma_gb_standard_options(func)#

Decorator to force default options for Magma.

EXAMPLES:

```sage: P.<a,b,c,d,e> = PolynomialRing(GF(127))
sage: J = sage.rings.ideal.Cyclic(P).homogenize()
sage: from sage.misc.sageinspect import sage_getsource
sage: "mself" in sage_getsource(J._groebner_basis_magma)
True
```
```sage: sage.interfaces.magma.reduce_load_Magma()