# Math Forum

## Intro to Sage

### November 12, 2015

Welcome to Math Forum!

So what is Sage?  Sage is comprehensive mathematics software that you can use from your computer, or even certain mobile devices.

The first thing we'll want to do is get people started up on Sage.   Nothing could be easier.

See this screenshot.

If you ever have trouble during the talk, you can always go and type commands here to your heart's content!

However, this can only handle one-off computations.  There are two options for doing lots of them online.

• Many of you may already be set up on the local Gordon server; it's easy to get a new account if you don't already have an account.  See http://sagemath.org/doc/prep/Logging-On.html for some nice screenshots.  I'll be using this for most of this talk.
• A somewhat more powerful, but also more intimidating, process is to create an account at https://cloud.sagemath.com/, which essentially provides a complete computer system online for you, including native Sage worksheets.
One great goal for the talk today would be to create an account on one of these and evaluate "2+2".  Our local server is mostly powered for a few people to use at a time, not a whole lab of students; the SageMath Cloud is set up for thousands of simultaneous users.  In both cases you
• Open a worksheet
• New Worksheet in the upper left in the local server
• New Project in the upper left first, then the New button with option SageMath worksheet in the SageMath Cloud
• Type in $2+2$ and evaluate it!

This last thing is done by clicking in the 'cell' like the one below, typing 2+2, and then either clicking "Evaluate" (or the "Run" button) or pressing Shift and Enter simultaneously (Shift-Enter).

2+2
 4 4

If you really want to, you can even "Edit a copy" of this worksheet, located at http://sage.math.gordon.edu/home/pub/86/; once you've logged in, click "Edit a copy", or follow the instructions at http://doc.sagemath.org/html/en/prep/Logging-On.html.

Once you've done this, the main goal for today is to give you an introduction to how to use Sage, whether or not you are required to use it in a class.

Sage can function as:

• a calculator
• a high-end scientific computation program
• an exploratory vehicle for mathematics research
• a homework aid

Of course, there are many programs which can do that!  There are some advantages to Sage, of course:

• Free
• Open Source (not the same as free)
• Mathematically Comprehensive

But those alone would not make it something I would necessarily ask students to use on a regular basis.  Here is why I use Sage, and why I often ask my classes to do so:

• Sage is the ONLY comprehensive program, free or not, which is freely available from any internet-accessible computer with a reasonably modern web browser.  There is nothing to download, no Java applet which needs to load, nothing like that.   It's all modern Web 2.0 technology like Google Docs/Drive.

Now let's get cracking!  First, let's recall the three examples on the advertising flyer for the Math Forum.  They were from:

• Calculus
• Linear Algebra
• Visualization
f(x) = x^2+5*x+1

As you can see, when you click on a "cell", there is a little 'evaluate' link right below it on the left.  You may click on this to ask Sage to do something, or you can press Shift and Enter at the same time.  In the case above, I have asked it to define a function of a variable $x$.  Notice that exponentiation is denoted with the carat (Shift-6) and multiplication with the asterisk (Shift-8).  Other than this, Sage 'knows' about most math expressions via something called a preparser, but you must do these correctly (especially multiplication!).

You should also notice that nothing appeared to happen when I clicked 'evaluate'.  That is because I did not ask Sage to show any output.  The last thing I type is the thing that gets displayed, if it is an actual calculation.  Here, I just defined something, but didn't calculate it.  On the other hand:

 \newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ x^{2} + 5 \, x + 1

Notice that if I check the "Typeset" button at the top, it is nicely typeset, using MathJax, the standard for web mathematics.  Surrounding something with "pretty_print()" also will do this.

Now, if I wanted to do everything above all at once, I could have typed the following:

f(x) = x^2 + 5*x + 1 f
 \newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ x^{2} + 5 \, x + 1

If I want more than one thing to show up at the same time, I put it all on the last line and separate by semicolons, like so:

f ; f(2) ; sqrt(f)

And now it is a simple matter to do some calculus homework checking.  What was the integral of the square root of $x^2+5x+1$ again?

integrate(sqrt(f),x)
 \newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \frac{1}{2} \, \sqrt{x^{2} + 5 \, x + 1} x + \frac{5}{4} \, \sqrt{x^{2} + 5 \, x + 1} - \frac{21}{8} \, \log\left(2 \, x + 2 \, \sqrt{x^{2} + 5 \, x + 1} + 5\right)

Notice I included the variable; otherwise, how does Sage know I didn't mean an integral with respect to some other variable?

If I want the definite integral, the syntax is similar, and intuitive:

integrate(sqrt(f),x,0,5)
 \newcommand{\Bold}[1]{\mathbf{#1}}\frac{15}{4} \, \sqrt{51} + \frac{21}{8} \, \log\left(7\right) - \frac{21}{8} \, \log\left(2 \, \sqrt{51} + 15\right) - \frac{5}{4}

You can numerically approximate things, of course:

numerical_approx(integrate(sqrt(f),x,0,5),digits=100)
 \newcommand{\Bold}[1]{\mathbf{#1}}7.434227410250764360242969907609241409761476483161967301410481014636985634733048623022573014833219802

Here is what happens if you try to use any variable or constant other than $x$, $e$, or $pi$ without "declaring" it first:

integrate(sqrt(f),y)
 Traceback (click to the left of this block for traceback) ... NameError: name 'y' is not defined Traceback (most recent call last): File "", line 1, in File "_sage_input_13.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aW50ZWdyYXRlKHNxcnQoZikseSk="),globals())+"\\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in File "/tmp/tmp9p7VIr/___code___.py", line 2, in exec compile(u'integrate(sqrt(f),y) File "", line 1, in NameError: name 'y' is not defined

But if you do declare it (the syntax is always the same), neat things can happen!

var('y') integrate(sqrt(f),y)
 \newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \sqrt{x^{2} + 5 \, x + 1} y

And of course other calculus stuff works, too.

diff(sqrt(f),x)
 \newcommand{\Bold}[1]{\mathbf{#1}}x \ {\mapsto}\ \frac{2 \, x + 5}{2 \, \sqrt{x^{2} + 5 \, x + 1}}

Before we see what else Sage can do, I should point out that you should feel free to just type whatever you can and see what works.

You should especially try to make mistakes and find new commands.  How might one do that?  There are a few ways to do it:

• If you don't remember a name of a command, but suspect it starts with a certain letter or combination of letters, you can type them and then [tab].  This tab-completion is very handy.
• If you find the name but don't remember the syntax or what it does, you can type the command and ?, then evaluate or tab and it will give you that information.
• If you already have an object defined (like the function $f$ above), you can type a period/dot after its name, and then [tab].  This will give you everything you can do to this object.
I'll demonstrate these below.

deriv
derivative?
f.

Before we move on to linear algebra, I wanted to show you some eye candy.  Just in case you thought Sage wasn't up to applications.

import pylab A=pylab.imread(DATA + 'gordon_college_medium.png') graphics_array([matrix_plot(A^(-1)),matrix_plot(1-A[0:,0:,2])]).show(figsize=[8,3])
 __main__:1: RuntimeWarning: divide by zero encountered in reciprocal __main__:1: RuntimeWarning: divide by zero encountered in reciprocal
import pylab A_image = pylab.mean(pylab.imread(DATA + 'gordon_college_medium.png'), 2) @interact def svd_image(i=(20,(1..100)),display_axes=True): u,s,v = pylab.linalg.svd(A_image) A = sum(s[j]*pylab.outer(u[0:,j],v[j,0:]) for j in range(i)) g = graphics_array([matrix_plot(A),matrix_plot(A_image)]) show(g,axes=display_axes, figsize=[8,3]) pretty_print(html('<h2>Compressed using %s eigenvalues</h2>'%i))

display_axes

## Click to the left again to hide and once more to show the dynamic interactive window

Now, those of you in the know noticed that the specific commands I used seem to indicate doing things like matrix inversion and other matrix operations - that is to say, it involves linear algebra!  So let's see what Sage can do with linear algebra.

A = Matrix([[1,2,3],[3,2,1],[1,1,1]]) A
 \newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rrr} 1 & 2 & 3 \\ 3 & 2 & 1 \\ 1 & 1 & 1 \end{array}\right)
w = vector([1,1,-4]) w
 \newcommand{\Bold}[1]{\mathbf{#1}}\left(1,\,1,\,-4\right)
w*A; A*w

So Sage can pretty easily create matrices and vectors and do things with them.  One interesting point here is that vectors are not regarded as $1\times n$ or $n\times 1$ matrices, but as their own entities.  Even w*w makes sense, and gives the dot product (the only reasonable interpretation of the product of two vectors).

We can also use it to solve systems of linear equations in this context, for instance

• $x+2y+3z=0$
• $3x+2y+z=-4$
• $x+y+z=-1$
Y = vector([0,-4,-1]) X = A.solve_right(Y) A \ Y; X; A*X

It also tells me if there is not a solution, which certainly can happen!

A.solve_right(w)
 Traceback (click to the left of this block for traceback) ... ValueError: matrix equation has no solutions Traceback (most recent call last): File "", line 1, in File "_sage_input_31.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("QS5zb2x2ZV9yaWdodCh3KQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in File "/tmp/tmpwU4PZu/___code___.py", line 2, in exec compile(u'A.solve_right(w) File "", line 1, in File "sage/matrix/matrix2.pyx", line 398, in sage.matrix.matrix2.Matrix.solve_right (/usr/local/sage-6.9/src/build/cythonized/sage/matrix/matrix2.c:6765) File "sage/matrix/matrix2.pyx", line 516, in sage.matrix.matrix2.Matrix._solve_right_general (/usr/local/sage-6.9/src/build/cythonized/sage/matrix/matrix2.c:7924) ValueError: matrix equation has no solutions

I can also get other things I might want.  Remember, type the dot/period and then [tab] to see what options I have:

A.
A.echelon_form();A.determinant();A.rank()

Notice that most commands are accessed by dot/period and function_name().  This allows Sage to only try to do math on things that deserve it; for instance, you don't want the determinant of a polynomial to be possible!  What would that even mean?

We can do more complicated things if we tell Sage that we are allowing non-integer values:

B = Matrix(RDF,[[1,2,3],[3,2,1],[1,1,1]]) B;B.LU()

Or to the end of your spring course!

A.eigenvalues()
 \newcommand{\Bold}[1]{\mathbf{#1}}\left[5, 0, -1\right]
A.eigenvectors_left()
 \newcommand{\Bold}[1]{\mathbf{#1}}\left[\left(5, \left[\left(1,\,1,\,1\right)\right], 1\right), \left(0, \left[\left(1,\,1,\,-4\right)\right], 1\right), \left(-1, \left[\left(1,\,-\frac{1}{5},\,-\frac{7}{5}\right)\right], 1\right)\right]

Differential equations can be nicely modeled too.  Here is a slope field, just for you!

var('x,y') plot_slope_field(sin(x+y)+cos(x+y), (x,-3,3), (y,-3,3)).show(figsize=5)

It is possible to even plot solutions, solve numerically, get exact answer, etc., depending on how hard they are:

y = var('y') P=plot_slope_field(1-y,(x,0,3),(y,0,20)) x = var('x') y = function('y',x) f = desolve(diff(y,x) + y - 1, y, ics=[2,2]) Q=plot(f,0,3) show(P+Q,figsize=5)
 \newcommand{\Bold}[1]{\mathbf{#1}}{\left(e^{2} + e^{x}\right)} e^{\left(-x\right)}

If you know how to ask a little more of Sage, you can define your own interactive demos.  This is not too hard, but does require you to be able to follow the examples given in interact? fairly closely.

@interact def _(initial_y=([2..5]),initial_x=([2..5])): x,y = var('x,y') P=plot_slope_field(1-y,(x,0,initial_x),(y,0,(initial_y-1)*e^initial_x)) x = var('x') y = function('y',x) f = desolve(diff(y,x) + y - 1, y, ics=[initial_x,initial_y]) Q=plot(f,0,initial_x) show(f.expand()) show(P+Q,figsize=5)

initial_y
initial_x

## Click to the left again to hide and once more to show the dynamic interactive window

Of course there is a lot more to math than just this!  In fact, Sage's greatest strong suit is in things like high-precision numerical computing, number theory and abstract algebra, because that is the roots of its founders.  But the examples I've shown you are all the basic ones in freshman and sophomore courses.

Interlude: What kind of program is Sage?  What language does it use?

• It is based on the Python language we use for our intro course at Gordon.
• So all the same stuff that works there, works here!
[i^2 if i%4 == 2 else 'hi' for i in range(20) ]
 \newcommand{\Bold}[1]{\mathbf{#1}}\left[\verb|hi|, \verb|hi|, 4, \verb|hi|, \verb|hi|, \verb|hi|, 36, \verb|hi|, \verb|hi|, \verb|hi|, 100, \verb|hi|, \verb|hi|, \verb|hi|, 196, \verb|hi|, \verb|hi|, \verb|hi|, 324, \verb|hi|\right]

Sage also contains the best of open-source mathematical programs.  As an example, the program R is actually a component of Sage, which we can use directly from the notebook.

%r M <- rnorm(100) summary(M)
  Min. 1st Qu. Median Mean 3rd Qu. Max. -2.70500 -0.83980 -0.05069 -0.05685 0.68200 2.56700   Min. 1st Qu. Median Mean 3rd Qu. Max. -2.70500 -0.83980 -0.05069 -0.05685 0.68200 2.56700 

There is one last thing I haven't shown too much of, namely plotting.  But we should certainly return to that as our final set of examples before I set us all loose.

plot(x^2,0,1,figsize=5)

You'll notice the "figsize=5"; that's just there because the projector I use probably won't project this worksheet at full size so we make graphics a bit smaller.

P=Graphics() for i in [1..10]: P += plot(x^i,0,1,hue=i*0.1) show(P,figsize=5)
plot([x^i for i in [1..10]],(x,0,1),fill = dict((i,[i+1]) for i in [0..9]),figsize=5)
x, y = var('x,y') plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))

There are MANY MANY resources for Sage online.  A few:

Sage is also so much more than this. As one example, for those familiar with LaTeX, you can combine the power of Sage and LaTeX in SageTeX!  I use this to prepare many of my lecture notes and handouts for students.

Remember, for once-off computations you have some nice options with the Sage cell servers; for more in-depth ones, use the notebook server or the SageMath Cloud.  Let's check that out for a little bit.

Do you have any questions about other things you might want to try?