Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Tutorial made for the Virtual Global Sage Days 109
Introduction to Python and SageMath
We will introduce some of the fundamental concepts in Python and SageMath.
Learning outcomes
Introduction to SageMath
Learn how to run Sage command line or notebook
Basic expressions and variables in Python and SageMath
Introduce some basic packages for plotting etc.
For the full lessons see https://github.com/fredstro/sage-lesson-nt
What is SageMath?
SageMath was originally developed by William Stein and first released in 2005. It was initially called SAGE, then Sage, and now SageMath, or Sage for short. The intention behind SageMath is to provide a free, open source alternative to Magma, Maple, Mathematica, MATLAB etc. with an easy to use interface (both for end-users and developers) built on Python (Cython) and which can integrate with other free or commercial packages (installed separately).
The default installation guide (wiki) or official page: installation contains many (over 150) different free packages, including:
Pari/GP
GAP
Singular
R
Numpy
matplotlib
...
For a full list see: https://www.sagemath.org/links-components.html
It can be integrated with existing commercial packages like
Magma
Mathematica
Maple
Full documentation is included in the source of SageMath and is available online, together with a multitude of tutorials etc.
See for instance https://www.sagemath.org/tour.html
Optional packages
Some packages that are not shipped with SageMath are available to install afterwards.
In the terminal (on Windows, use the "SageMath Shell"):
sage -i <package_name>
- to install optional Sage packagesage --pip install <py_package_name>
- to install extra Python package usingpip
In a SageMath session (on Windows, use "SageMath" or "SageMath Notebook"):
sage: installed_packages()
- to list all installed packagessage: optional_packages()
- to list installed and available optional packages
Running SageMath
On your own machine
For the Sage REPL (read-eval-print loop) or command-line interactive use:
sage
to run Sagesage --help
to see all options, e.g.--python
,--pip
, etc.
For the Jupyter Notebook interface, run one of:
sage -n jupyter --notebook-dir=<dir>
sage --notebook=jupyter --notebook-dir=<dir>
sage --jupyter notebook --notebook-dir=<dir>
For the JupyterLab interface (if installed -- see above), run one of:
sage -n jupyterlab --notebook-dir=<dir>
sage --notebook=jupyterlab --notebook-dir=<dir>
sage --jupyter lab --notebook-dir=<dir>
Online
SageMathCell: https://sagecell.sagemath.org/ - write SageMath code directly in the browser
Cocalc: https://cocalc.com - full interactive notebook environment (compare with Google Colab)
Binder: https://opendreamkit.org/try/ - temporary instance
Getting help with SageMath
<function_name>?
- to read documentation (docstring)<function_name>??
- to read the source (if available)<object_name>.<tab>
- use tab completion to see available propertiesHelp button in the toolbar links to the online documentation
Example: Try using these features for yourself below. Run a code cell by first selecting it and then either
Press the
Run
button in the toolbar aboveUse the keyboard shortcut Ctrl+Enter or Shift+Enter
Programming in SageMath
Check that your kernel is set to SageMath (e.g. SageMath 9.0) in the top right of the toolbar.
You can change your kernel using the Kernel
button on the toolbar to set the default to Python (2.7 or 3.x depending on your version of SageMath).
Since version 9.0 released in January 2020, SageMath is using Python 3.
Since the main functionality of SageMath is written in Python it means that most of the programming can be done using Python. There are however some subtle differences.
Variable types in Python
Numerical types:
int
,float
,complex
Strings:
str
Lists:
list
Tuple:
tuple
Dictionary:
dict
Set:
set
Example: Run the cell below to explore basic data types in Python
Note that in Python 2, dividing two int
variables uses "integer division with floor floor function"
Variable types in SageMath
In SageMath defaults for many numeric types are overwritten. For example:
Integers are by default cast to SageMath's
Integer
type, which has different behaviour from Python'sint
Instead of
float
, SageMath usesRealLiteral
andRational
(where appropraite)
Sets
Sets are useful for making lists with unique elements, are order ambivalent, and can be defined using either braces {}
or the set()
constructor function.
The set
type features many useful methods such as unions and intersections. See the documentation here.
Sage has some additional useful builtin-functions:
Precision of variables in SageMath
SageMath stores variables to higher levels of precision than Python
The
RR
keyword denotes the Real Field with 53 bits of precision (double precision)The
CC
keyword denotes the Complex Field with 53 bits of precisionWe can construct fields with higher precision using
RealField(prec)
andComplexField(prec)
We can contruct high precision complex numbers as field elements as follows:
There are also builtin constants that can be given to arbitrary precision
Objects, Parents, Elements and categories
In Python and even more so in SageMath everything is an object and has properties and methods.
In SageMath most (every?) object is either an Element or a Parent
CC.coerce_map_from(RR)
String formatting
In previous versions of Python there were more types of strings but in current Python there are basically only strings str
and bytestrings bytes
(which we do not discuss here)
We can control how strings are formatted when printing by using either the format
method or by using formatted strings, which are strings with an f
character before the first quotation mark. Please see the examples below, and follow this link for a reference on string formatting.
Exercise 1. Print as a floating point number to 225 decimal places.
Python solution: Use the decimal
library (documentation)
The cell above shows that there is not enough precision in the stored values of pi
in the math
and numpy
libraries for our application, so we must use an algorithm to calculate it to a higher precision. We use the Gauss-Legendre algorithm for its fast convergence rate.
SageMath solution:
Note that this can be calculated using many fewer lines of code since there are builtin SageMath algorithms running behind the scenes.
Note also that we must convert from bit (binary) precision to precision in decimal places by multiplying by
Functions
Function names should be descriptive and use "snake_case" (this is a Python convention)
Variable names in Python should also be lower, snake_case
In SageMath we also use mathematical conventions even if they break this, e.g.
Ei
for the exponential integral functionFor full document about coding conventions see: http://doc.sagemath.org/html/en/developer/coding_basics.html
Sage has an alternative modulo reduction function
The issue is that we checked for type int
but in a SageMath environment the default type for integers is Integer
. Need to check for both types!
Docstrings
When writing our own functions we can help future users check the expected inputs in advance by writing a docstring (documentation string).
Variables in functions:
Type hints
In Python 3 it is also possible to add type hints (not enforced by Python).
Exercise Write a function is_square_residue
with the following specifications:
Takes as input an integer and a positive integer
Returns True if is congruent to a square modulo and otherwise False.
Handles errors in input with sensible error messages.
Includes a docstring which describes the function.
Functions and objects
Functions are also objects and can be introspected via their properties. Class methods and imports etc. can be modified at runtime (monkey-patching)
Example of monkey patching
Python Control Structures
Standard (used in most programming languages):
Iteration with
for
andwhile
loopsIf-then-else statements
More Python specific:
Generator expressions
List comprehensions
The output of the range
function is an example of a generator expression. It does not actually allocate all elements until needed.
We can cast a range to a list
to see all of its elements. Note that range
starts at the left endpoint and stops at the right endpoint without including it!
Calling list(range(10^(10^10)))
would run out of memory, but iterating over it is fine (although probably won't finish).
If evaluating the cell below, please call keyboard interrupt or select Kernel -> Interrupt from the toolbar above.
Example: for
loops and list comprehensions
We can evaluate , the zeta function at s=2
, using a loop, and compare to the known value .
We may also use a list comprehension, or directly use the generator expression to compute the partial sum
Plotting in Sagemath with the plot
function
The plot()
function in SageMath takes as its first argument a function or list of functions. In the case that the passed functions take a single argument, the next two arguments, start
and end
, can be used to define the range over which to evaluate and plot them.
Most objects have a latex
property which "pretty-prints" them in a format suitable for inclusion in a LaTeX document.
Symbolic expressions in SageMath
When starting Sage the name 'x' is defined as a symbolic variable and other variables have to be declared using the var('x, y, z, ...')
command. Symbolic expressions can be treated in various ways:
differentiation
simplifications
When the notebook is started we have as a variable:
We can define additional variables
Differentiation
Simplification
Substitution
Exercise Determine the value of for Is it
(a)
(b)
(c)
(d)
(e) None of the above?
We can now combine everything and compute the Bernoulli numbers. Recall that they can be defined by the generating series
Try to find the first Taylor coefficient:
Still of the form 0 /0. Need one more derivative!
So the first Bernoulli number . This method is a bit cumbersome but fortunately there is a builtin command in Sage for Taylor expansions
We can convert this to a polynomial over :
For a polynomial we can add a big-Oh
We can get coefficients of certain terms in Taylor expansions
We can now write a function that returns the j-th Bernoulli number
We can also work with polynomials in many variables
Linear algebra can be done using "native" Sage or numpy
Algebraic numbers
What is the "?" ?
Can be evaluated to arbitrary precision
Can use Numpy
Can work over finite fields
Can use Newton - Raphson to find the roots: