Introduction to SageMath

Aurore Guillevic (Inria Nancy Grand-Est)

February 3, 2022

Introduction to SageMath

SageMath library: a mathematical software suite based on Python, open-source.

Installation

Install SageMath from

Note: you cannot move SageMath somewhere else on your disk once it is installed.

If the installation is successful, the sage command should give a prompt:

sage:

You can test it with a simple command:

sage: 42.factor()
2 * 3 * 7

On Linux, to run sage from everywhere: add the SageMath directory into your PATH, or in your .bash_aliases, create an alias to your installation:

alias sage='~/Libs/SageMath/sage'

SageMath Tutorial

https://doc.sagemath.org/html/en/tutorial/index.html

https://doc.sagemath.org/html/en/tutorial/introduction.html

Quick presentation of SageMath

(From Cyril Bouvier’s tutorial)

Sage

Sage is an open-source computer algebra software.

It is based on Python 3 (from 2020).

It combines lots of open-source libraries (GMP, Pari, FLINT, NTL, MPFR, FFLAS-FFPACK, GMP-ECM, …)

Four ways to use it:

Running Sage

Interactive Shell

sage

It opens an interactive prompt (using IPython). You can write commands and press Enter to run them; the result is printed below.

sage:~59-17
42

Script files

Write commands in a file and run it with

sage scriptname.sage

Sage translates the file scriptname.sage into a Python file and executes it.

echo "print(59-17)" > example.sage
sage example.sage

Prints on the terminal:

42

Notebook

Similar to the interactive shell but you can use it in your browser.

sage --notebook

Python module

Follow the instructions at https://wiki.sagemath.org/SpyderInstructions to configure Spyder.

You can import Sage as a Python library into a Python code with

from sage.all_cmdline import *   # import sage library

or alternatively

from sage.all import *   # import sage library

Then run it with the Python of Sage (without the extension .py):

sage -python myfile

If this is a module file in a directory myproject/test/mytest.py:

sage -python -m myproject.test.mytest
sage -python -m myproject.test.mytest <customized command-line options>

Python

Dynamically type: types of variables are verified at runtime.
Variable name: can contains letters, numbers and underscore _; cannot start with a number; case sensitive. Blocks: whitespace indentation (or tabulations) are used to delimit code blocks. Scope of variables: a block. Comments: Everything after a # is a comment.

Python - types

Built-in types

Python - conditionals

if condition1:
    ... # do something if condition1 is true
elif condition2:
    ... # do something else if condition 1 is false but condition2 is true
elif condition3:
    ... # do something else if condition3 is true but others are false
else:
    ... # do something if no condition is true

The else and elif clauses are optional. The elif clause can be repeated as many times as necessary.

One can use and, or and not to combine conditions.

if myvariable is None:
    ... # do something if the variable is None (not defined)
if p.is_prime():
    Fp = GF(p) # define a prime finite field if p is a prime

Python - for loop, while loop

for i in range(10):
    print(i**2)

i = 0
while i < 10:
    print(i**2)
    i = i+1

Functions, methods

One defines a function with def, with input variables, and a return statement. If there is no return, then by default the function returns the special type None.

def sum_up_to(n):
    s = 0
    for i in range(0, n):
        s = s + i
    return s

A method is attached to an instance of a class. This is a function defined inside a class, whose 1st argument is self. To use it on Sage predefined classes:

s = "Hello world"
print(s.capitalize())
print(s.split(" "))

gives

Hello world
['Hello', 'world']

Sage - Differences with Python

Syntactic sugar available:

QQx.<x> = QQ[] # defines a polynomial ring in the variable x over the rationals QQ
f = x^3
3^3  # in Sage ^ is powering
3**3 # python powering is still defined in Sage

Check at https://doc.sagemath.org/html/en/tutorial/tour_assignment.html for a longer list of arithmetic with SageMath.

The division operation 42/17 gives

From Python to SageMath and vice-versa

Important features of the interactive shell of Sage.

A list of methods attached to a variable can be printed by pressing the Tab key:

E = EllipticCurve([0,-2])
E. # here press tab right after the dot

The documentation can be printed by appending a `?’ to variables, functions and methods.

The code can be printed by appending a double question mark ?? to functions and methods.

Remove the syntactic sugar from SageMath interpreter

preparse("QQx.<x> = QQ[]")

Ask which packages to import in a python file

import_statements(QQ)

answers

# ** Warning **: several names for that object: Q, QQ
from sage.rings.rational_field import Q

History

Print the history of all commands you typed in the interpreter:

%hist

Then you can copy-paste in a file to save your work.

Files .sage and .py

For small SageMath scripts: files myfile.sage with .sage extension, no import needed, the interactive shell (like ipython) imports everything.

Run this file:

load("myfile.sage")

within SageMath interactive shell.
This creates a file myfile.sage.py which is a translation into Python of the SageMath script. It removes the syntactic sugar, and add all the needed import statements.

To directly write Python-like code: create a file with .py extension such as myfile.py.

Run SageMath within Spyder

Launch Spyder, then open your file with Spider.

Alternatively, uses a Text Editor