See the document Installing SAGE at [SA] for instructions on installing SAGE on your computer. We note that the SAGE download file comes with ``everything including batteries''. In other words, although SAGE uses Python, IPython, PARI, GMP, and so on, you do not need to install them separately as they are included with the SAGE distribution.
You can use SAGE either via an interactive shell, or you can write
Python programs that use the SAGE library.
To use sage as a Python module,
set the shell environmental variables LD_LIBRARY_PATH
,
SAGE_HOME
, PYTHONPATH
correctly (see bin/sage),
then run the Python 2.4 included with SAGE, and type
>>> from sage.all import *
In this tutorial we assume you start SAGE using the sage command located in the bin/sage subdirectory. This starts a customized version of IPython, and imports many functions and classes, so they are ready to use from the command prompt. Even further customization is possible by editing the conf/ipythonrc file to your taste. Upon starting SAGE you get output similar to the following:
was@form:~$ sage SAGE Version 0.2, Build Date: 2005-04-09-1550 Copyright (C) 2004 William Stein <was@math.harvard.edu> Distributed under the terms of the GNU General Public License (GPL)
To quit SAGE, do one of the following:
was@form:~$ sage SAGE Version 0.2, Export Date: 2005-04-09-1550 Copyright (C) 2004 William Stein <was@math.harvard.edu> Distributed under the terms of the GNU General Public License (GPL) sage: quit (or Ctrl-D or %Exit or %Quit) was@form:~$
SAGE (via IPython) logs all SAGE input (not the output). In fact, at
any point, you may type
%hist
to get a listing of all lines typed so far.
was@form:~$ sage SAGE Version 0.2, Export Date: 2005-04-09-1550 Copyright (C) 2004 William Stein <was@math.harvard.edu> Distributed under the terms of the GNU General Public License (GPL) sage: factor(100) [(2, 2), (5, 2)] sage: kronecker(3,5) -1 sage: %hist 1: factor(100) 2: kronecker(3,5)
_in
to refer to the
_ih
to list all
lines in the input buffer.
sage: _i1 'factor(100)\n' sage: eval(_i1) [(2, 2), (5, 2)] sage: %hist 1: factor(100) 2: kronecker(3,5) 3: %hist 4: _i1 5: eval(_i1) sage: _ih ['\n', 'factor(100)\n', 'kronecker(3,5)\n', '#%hist\n', '_i1\n', 'eval(_i1)\n', '#%hist\n', '_ih\n']
In UNIX, any shell command can be executed from SAGE by prefacing it by an exclamation point (!). For example,
sage: !ls ...
sage: execfile("filename")
sage: load filename.py
sage: run -i filename.py
For much more about the extensive features of the interactive interpreter see the IPython documentation.
Suppose you are reading a session of SAGE or Python computations and
want to copy them into SAGE. But there are these annoying >>>
or sage:
prompts to worry about. In fact, you can copy and
paste an example, including the prompts if you want, into SAGE. In
other words, by default the SAGE parser strips any leading
>>>
or sage:
prompt before passing it to Python. For example,
sage: 2^10 1024 sage: sage: 2^10 1024 sage: >>> 2^10 1024
Implementation Note: This is implemented in sage/misc/interpreter.py,
which contains code to remove >>>
or sage:
from the beginning
of a line.
sage: time a = int(1938)^int(99484) Time: 0.41 seconds
sage: time a = 1938^99484 Time: 0.04 seconds sage: time len(str(a)) # how many digits? 327040 Time: 0.5 seconds
sage: time a = pari(1938)^pari(99484) Time: 0.19 seconds
You can also time a block of commands using the cputime command, defined in sage.misc.misc, and available by default in the interpreter.
sage: t = cputime() sage: a = 1938^99484 sage: b = int(1938)^int(99484) sage: c = pari(1938)^99484 sage: print cputime(t) 0.64 sage: cputime? ... Return the time in CPU second since SAGE started, or with optional argument t, return the time since time t. INPUT: t -- (optional) float, time in CPU seconds OUTPUT: float -- time in CPU seconds
When you make a syntax error, you will see what Python calls an ``exception''. It even tries to suggest what it is that it that raised the exception. Often you see the name of the exception, e.g., NameError or ValueError (see the Python Reference Manual [Py] for more details). For example,
sage: 3_2 ------------------------------------------------------------ File "<console>", line 1 3_2 ^ SyntaxError: invalid syntax
3_2
) wasn't so bad--SAGE returned a
prompt--thus giving us an opportunity to try to define the ``elliptic
curve''
sage: EllipticCurve([1,infinity]) ------------------------------------------------------------ Traceback (most recent call last): File "<console>", line 1, in ? File "/home/was/sage/src/sage/ellcurve/ellcurve.py", line 83, in __init__ raise errors.MathError("Defining coefficients must lie in a field.") MathError: Defining coefficients must lie in a field.
With the debugger on, when an error occurs you get a new prompt (Pdb)
.
You can print the state of any local variable, and move up
and down the execution stack. For example,
sage: %pdb sage: EllipticCurve([1,infinity]) ... (Pdb) print ainvs [0, 0, 0, 1, Infinity] (Pdb) Ctrl-D sage:
(Pdb) ? Documented commands (type help <topic>): ======================================== EOF break condition disable help list q step w a bt cont down ignore n quit tbreak whatis alias c continue enable j next r u where args cl d exit jump p return unalias b clear debug h l pp s up
Type Ctrl-D
to return to SAGE.
Here's another example, in which we turn on printing of extra
context information:
sage: %pdb Automatic pdb calling has been turned ON sage: %xmode Context Exception reporting mode: Context sage: EllipticCurve([1,infinity]) --------------------------------------------------------------------------- sage.misc.errors.MathError Traceback (most recent call last) /home/was/sage/sage-doc/<console> /home/was/sage/src/sage/ellcurve/ellcurve.py in __init__(self, ainvs) 76 ainvs = [Q(a) for a in ainvs] 77 except: ---> 78 raise errors.MathError("Defining coefficients must lie in a field.") 79 self.__base_field = ainvs[0].parent() 80 self.__ainvs = [self.__base_field(x) for x in ainvs] MathError: Defining coefficients must lie in a field. sage:
As you can see, the output from the interactive debugger is much improved if you type %xmode Context or even %xmode Verbose. With Context, you'll see several lines before and after where the error occured in the Python source file. You can inspect the state of local variables, move up and down the execution stack, etc. To turn of extra context printing, type %xmode Plain.
sage: QQ = RationalField()
To enter a rational number, just do the ``obvious'':
sage: 4/3 4/3
sage: a = 4/3 sage: b = 2/3 # single quotes are also OK sage: a + b 2 sage: 2*b == a True sage: c = 2 sage: d = 3 sage: c/d 2/3 sage: c/d == 2/3 True sage: type(4/2) <type 'rational.Rational'>
First create the three dimensional vector space
.
sage: V = VectorSpace(QQ,3) sage: V Full Vector space of degree 3 over Rational Field
Using the readline library2.1, type the beginning of a line, then Ctrl-p to go back to each line you've ever entered that begins in that way. This even works if you completely exit SAGE and restart later (!) at least if you don't update to a new version in the mean time. You can also do a reverse search through the history using Ctrl-r.
Another feature of readline is that it is easy to list all member
functions for using tab completion. Just type V., then type
the [tab key] key on your keyboard:
sage: V.[tab key] V._VectorSpace_generic__base_field V.is_ambient V._VectorSpace_generic__degree V.is_dense V._VectorSpace_generic__is_sparse V.is_full V._VectorSpace_generic__set_vector_class V.is_sparse V._VectorSpace_generic__vector_class V.list V.ambient_space V.matrix V.base_field V.ngens V.base_ring V.random_element V.basis V.subspace V.coordinates V.subspace_with_basis V.degree V.vector V.dimension V.vector_space V.gen V.zero_vector V.gens
sage: V.i[tab key] V.is_ambient V.is_dense V.is_full V.is_sparse sage: V.is_
^
**
) are incorporated in these examples. These
examples are viewed by the authors of SAGE as being extremely
important, and are regularly automatically tested to make sure they
work exactly as claimed. No SAGE package will be considered
finished until every single function has examples of usage (this
is one of the goals for SAGE Version 1.0).
sage: V = VectorSpace(QQ,10) sage: V Full Vector space of degree 10 over Rational Field sage: V.subspace? Type: instancemethod Base Class: <type 'instancemethod'> String Form: <bound method VectorSpace_ambient.subspace of Full Vector space of degree 3 overRational Field> Namespace: Interactive File: /home/was/sage/src/sage/linalg/vector_space.py Definition: V.subspace(self, gens) Docstring: Create a subspace of self. INPUT: gens -- a list of vector in self OUTPUT: VectorSpace -- the subspace spanned by the vectors in the list gens. The basis for the subspace is always put in reduced row echelon form. EXAMPLES: >>> import sage.rings.rings as rings >>> V = VectorSpace(rings.RationalField(), 3) >>> B = V.basis() >>> W = V.subspace([B[0]+B[1], 2*B[1]-B[2]]) >>> W Vector space of degree 3, dimension 2 over Rational Field Basis matrix: [ 1 0 1/2] [ 0 1 -1/2]
sage: help(VectorSpace) Help on class VectorSpace in module sage.linalg.vector_space: class VectorSpace(__builtin__.object) | Create a Vector Space. | | Two create an ambient space over a field with given dimension | using the calling syntax | VectorSpace(field, dimension, sparse=True) | and to create a subspace use | VectorSpace(list_of_vectors), | where list_of_vectors is a list of vectors in a VectorSpace. | | EXAMPLES: | First we create some ambient spaces. | >>> from sage.rings.rings import RationalField, CyclotomicField | >>> V = VectorSpace(RationalField(), 389); V | Full Vector space of degree 389 over Rational Field | >>> V.dimension() | 389 :
sage: help(VectorSpace) sage:
VectorSpace_ambient
,
which is defined in the file sage/linalg/vector_space.py.
sage: V = VectorSpace(QQ,10) sage: type(V) <class 'sage.linalg.vector_space.VectorSpace_ambient'>
Only certain functions can be called on . In most other math
software systems, these would be called using the notation foo(V,...). In SAGE, the functions belong to the class of
, and
are called using an object-oriented syntax like in Java or C++, i.e.,
V.foo(...). This helps keep the global namespace from being
polluted with thousands of functions.
In many cases functional notation is still allowed, for convenience and because mathematical expressions often look funny using object oriented notation. The file sage/all.py contains function definitions such as
def basis(x): return x.basis()
sage: V = VectorSpace(Q,2) sage: V.basis() [(1 0), (0 1)] sage: basis(V) [(1 0), (0 1)] sage: M = MatrixSpace(Q, 2) sage: A = M([1,2,3,4]) sage: A.charpoly() x^2 - 5*x - 2 sage: charpoly(A) x^2 - 5*x - 2
It is easy to list all member functions for , using tab completion
from the readline library. Just type V., then type the [tab
key] key on your keyboard, as explained in
Section 2.8.