Subsections

2. Using SAGE

2.1 Installation

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.

2.2 Input and Output

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:

  1. Type quit.
  2. Ctrl-D (or EOF)
  3. Use the IPython magic command %Exit or %Quit.
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)
You can also use _in to refer to the $n$th input line, and _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
...
returns the listing of the current directory. To read in a python file, type
sage: execfile("filename")
However, this file must contain pure Python, not SAGE commands (e.g., use ** for exponentiation and must explicitly import the SAGE library). To input a file of commands exactly as if you were typing them into the interpreter, type
sage: load filename.py
or
sage: run -i filename.py

For much more about the extensive features of the interactive interpreter see the IPython documentation.

2.3 Copy and Paste

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.

2.4 Timing Commands

If you place the time comand at the beginning of an input line, the time the command takes will be displayed after the output. For example, we can compare the running time for a certain exponentiation operation using three large integer arithmetic packages: First, native Python:
sage: time a = int(1938)^int(99484)
Time: 0.41 seconds
Next the SAGE Integer type, which is implemented using the GMP C library:
sage: time a = 1938^99484
Time: 0.04 seconds
sage: time len(str(a))    # how many digits?
      327040
Time: 0.5 seconds
Finally using the PARI C-library interface:
sage: time a = pari(1938)^pari(99484)
Time: 0.19 seconds
GMP wins this one.

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

2.5 Errors and Exceptions

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
Note that the first error (3_2) wasn't so bad--SAGE returned a prompt--thus giving us an opportunity to try to define the ``elliptic curve'' $y^2=x^3+\infty$:
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.

2.6 The Interactive Debugger

SAGE includes an interactive debugger (which is inherited from IPython). If you type %pdb at a SAGE prompt, it turns on (or off) the interactive debugger.

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:
For a list of commands in the debugger, type ? at the (Pdb) prompt:
(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.

2.7 Rings: Rational Numbers

We illustrate using rings in SAGE with the field $\mathbf{Q}$ of rational numbers.

sage: QQ = RationalField()
In fact, both Q and QQ are already known to SAGE to be the field of rationals. But don't worry, if you use both names as variables, you can still fetch the rational numbers using the command RationalField().

To enter a rational number, just do the ``obvious'':

sage: 4/3
      4/3
This gets passed to Python, which (as mentioned in Section 1.3) thinks you want an integer back and so returns to you the integer quotient of $4$ divided by $3$. If you want the rational number quotient, you must say so this way:

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'>


2.8 Tab Completion

First create the three dimensional vector space $V=\mathbf{Q}^3$.

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 $V$ 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
If you type the first few letters of a function, then [tab key], you get only functions that begin as indicated.

sage: V.i[tab key]
V.is_ambient  V.is_dense    V.is_full     V.is_sparse
sage: V.is_

2.9 Integrated Help System

SAGE contains an integrated help facility, which is actually a feature implemented by IPython. Type a function name followed by ? for the documentation for that function. The documentation contains (or will contain!) the file in which the function is defined, a description of each input argument, a description of each output argument, and examples illustrating usage. The examples assume only that the file in which the command is defined has been included. This means that if you import that file in your own Python programs, then the examples will work; in particular, no special SAGE syntax conversions (e.g., ^ $\to$ **) 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]
You may also type help(command_name) or help(class) for a man page like help file about a given class. This documentation is automatically extracted from the source code.
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
 :
When you type q to exit the help system, your session appears just as it was. The help listing does not clutter up your session, unlike the output of function_name?.
sage: help(VectorSpace)

sage:

2.10 Data Types

The vector space $V$ is an object of type 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 $V$. In most other math software systems, these would be called using the notation foo(V,...). In SAGE, the functions belong to the class of $V$, 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()
which transform the usual functional notation into the object oriented notation in some cases. For example
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 $V$, 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.



Footnotes

... library2.1
Currently not working on 64-bit SUSE Linux.
See About this document... for information on suggesting changes.