Spring 2011 MAA Northeastern Sectional Sage Workshop

349 days ago by kcrisman

Sage Introductory Workshop

MAA Northeastern Section Spring 2011 Conference

 

Welcome to the Sage workshop!  Special thanks to Rob P. for inviting me.  We should have a lot of fun and learn a lot.

Click here to go straight to the main content.  Some of this content was originally developed for the MAA PREP Workshop "Sage: Using Open-Source Mathematics Software with Undergraduates" (funding provided by NSF DUE 0817071).

Getting a Live Copy of a Worksheet

The first part of this workshop is to learn how to open a Sage worksheet.   You'll need your own copy of the worksheet on the server.  It should look like this at the top:

Except, of course, your username will appear!  If you already have a live copy, please skip below.

If you don't see this, take another look at the top of the screen.  Does it look like this?    

If so, you need to log in!  Click the link at the upper left and follow usual website login creation/login procedures.  Then return to this worksheet page.

Otherwise, it should look like this:

It should also look like this once you log in.   In that case, just click 'Edit this'.

Then the worksheet should look like this!  

Then you can continue with the worksheet.

 

Our Goals

Because you self-selected into this workshop, we're going to assume that you know some of the point of mathematics software in the classroom.  So we are going to have two goals.

  1. Giving you enough information that you can start to find answers to your own questions.
  2. Showing off a little of the variety of topics that can be addressed in Sage.

The first goal will be addressed through some brief introduction to how Sage works, how to find help interactively, and how to annotate in Sage.

The second goal will be addressed after this.

Let's get started!

Evaluating Sage Commands

(i.e., How do I get Sage to do some math?)

Below, and throughout this worksheet, are little boxes called input cells or code cells.   They should be about the width of your browser.  

Evaluating the content of an input cell is very easy.

  • First, click inside the cell so that the cell is active (i.e., has a bright blue border).  
  • Then, just below the cell on the left, an "evaluate" link appears; clicking this link evaluates the cell.  

Try evaluating the following cell.

2+2 
       
4
4

Sage prints out its response just below the cell (that's the "4" above, so Sage confirms that 2+2=4).   Note also that Sage has automatically made the next cell active after you evaluated your first cell.

You can also evaluate a cell using a keyboard shortcut.  

  • If the following cell isn't active, click in it. 
  • Then hold down the Shift key while you press the Enter key.  
We call this "Shift-Enter".  Try doing Shift-Enter with this cell.
factor(2010) 
       
2 * 3 * 5 * 67
2 * 3 * 5 * 67

An input cell isn't much use if it can only do one thing, so you can edit a cell and evaluate it again.  Just click inside, and then make any changes you wish by typing as usual.  

Try changing the number "2010" above to "2011" and evaluate the cell to find its factorization (surprised?); then try your own favorite number.

To do more math, we'll need to be able to create new input cells.  This is also easy.

  • Move your cursor over the space above or below another cell.  
  • A blue horizontal line as wide as the browser should appear. 
  • Click on the line to insert a new cell.  

If for some reason you need to remove or delete an input cell, just delete all the text inside of it, and then press backspace in the now-empty cell.

Try creating a few new input cells below, doing some arithmetic in those cells, and then deleting one of the input cells.

 
       
 
       

There are lots of commands in Sage, but it wouldn't be productive to use all our time exploring them.  Instead, I want to illustrate an important fact about how to use Sage by creating some matrices and doing things to them.

matrix([[1,2,3],[3,2,1],[1,1,1]]) 
       
[1 2 3]
[3 2 1]
[1 1 1]
[1 2 3]
[3 2 1]
[1 1 1]

I can get the determinant of this matrix fairly easily.  Many Sage commands look like this.

det(matrix([[1,2,3],[3,2,1],[1,1,1]])) 
       
0
0

However, it might be tedious even to cut and paste this definition all the time.  So instead we assign the matrix to a new variable name.

A = matrix([[1,2,3],[3,2,1],[1,1,1]]) A 
       
[1 2 3]
[3 2 1]
[1 1 1]
[1 2 3]
[3 2 1]
[1 1 1]

This shows two things.  

  • First, we can give a matrix (or any other mathematical object) a name in Sage.
  • Second, if we put two commands on separate lines, they will both be evaluated (though only the last one will be visible).

Now let's do something to this matrix.

A.rref() 
       
[ 1  0 -1]
[ 0  1  2]
[ 0  0  0]
[ 1  0 -1]
[ 0  1  2]
[ 0  0  0]

This has given us the row-reduced echelon form of the matrix A.  The last row is all zeros because this matrix doesn't have full rank, as we saw from the determinant.

Question:  What's up with that syntax?

For now, we won't go in great depth explaining the reasons behind this syntax, which may be new to you.   For those who are interested, Sage often uses this type of syntax (known as "object-oriented") because...

  • Sage uses the Python programming language, which uses this syntax, 'under the hood', and 
  • Because it makes it easier to distinguish among
    • The mathematical object,
    • The thing you are doing to it, and
    • Any ancillary arguments.

For example, the following numerically evaluates ('n') the constant \pi ('pi') to twenty digits ('digits=20').

pi.n(digits=20) 
       
3.1415926535897932385
3.1415926535897932385

Help inside Sage

There are various ways to get help for doing things in Sage.  Here are several common ways to get help as you are working in a Sage worksheet.

Documentation

Sage includes extensive documentation covering thousands of functions, with many examples, tutorials, and other helps. 

Our main focus here, though, is help you can immediately access from within a worksheet, where you don't have to do any of those things.

Tab completion

The most useful help available in the notebook is "tab completion".   The idea is that even if you aren't one hundred percent sure of the name of a command, the first few letters should still be enough to help find it.  Here's an example.

  • Suppose you want to do a specific type of plot - maybe a slope field plot - but aren't quite sure what will do it.   
  • Still, it seems reasonable that the command might start with "pl".
  • Then one can type "pl" in an input cell, and then press the tab key to see all the commands that start with the letters "pl".

Try tabbing after the "pl" in the following cell to see all the commands that start with the letters "pl".     You should see that "plot_slope_field" is one of them.

pl 
       

And here is the slope field I wanted.

f(x,y) = 2*y+x plot_slope_field(f,(x,-5,5),(y,-5,5)) 
       

(Parenthetically, it's important that I defined my function with the usual mathematical notation f(x,y), but we won't delve into this now.)

 

You can also use tab-completion to see what you can do to an expression or mathematical object.

  • Assuming your expression has a name, type it;
  • Then type a period after it,
  • Then press tab.  

You will see a list pop up of all the things you can do to the expression.

To try this, evaluate the following cell, just to make sure our matrix A is defined.

A = matrix([[1,2,3],[3,2,1],[1,1,1]]) 
       

Now put your cursor after the period and press your tab key.  

A. 
       

Because Sage starts counting at zero (like many programming environments), it's the middle column that is rescaled.

Finding documentation (question marks)

In the previous example, because you have to pick a column and a scaling factor, it makes sense that there would be some extra things to input.  But how would you know what order they go in?  

To find out, there is another help tool one can use from right inside the notebook.  Almost all documentation in Sage has extensive examples that can illustrate how to use the function.

  • As with tab completion, type the expression, period, and the name of the function.
  • Then type a question mark.
  • Press tab or evaluate to see the documentation.

To see how this help works, evaluate the first cell, then move your cursor after the question mark in the second one and press tab.

A.rescale_col(1,5); A 
       
[ 1 10  3]
[ 3 10  1]
[ 1  5  1]
[ 1 10  3]
[ 3 10  1]
[ 1  5  1]

Finding documentation (question marks)

In the previous example, you might have wondered why I needed to put "f.integrate(x)" rather than just "f.integrate()", by analogy with "sqrt(2).n()".

To find out, there is another help tool one can use from right inside the notebook.  Almost all documentation in Sage has extensive examples that can illustrate how to use the function.

  • As with tab completion, type the expression, period, and the name of the function.
  • Then type a question mark.
  • Press tab or evaluate to see the documentation.

To see how this help works, move your cursor after the question mark below and press tab.

f(x)=x^3+1 
       
f.integrate? 
       

File: /home/sage/sage_install/sage-4.6/devel/sage/sage/symbolic/expression.pyx

Type: <type ‘builtin_function_or_method’>

Definition: f.integrate(*args, **kwds)

Docstring:

Compute the integral of f. Please see sage.symbolic.integration.integral.integrate for more details.

EXAMPLES:

sage: sin(x).integral(x,0,3)
-cos(3) + 1
sage: sin(x).integral(x)
-cos(x)

File: /home/sage/sage_install/sage-4.6/devel/sage/sage/symbolic/expression.pyx

Type: <type ‘builtin_function_or_method’>

Definition: f.integrate(*args, **kwds)

Docstring:

Compute the integral of f. Please see sage.symbolic.integration.integral.integrate for more details.

EXAMPLES:

sage: sin(x).integral(x,0,3)
-cos(3) + 1
sage: sin(x).integral(x)
-cos(x)

The examples illustrate that the syntax requires "f.integrate(x)" and not just "f.integrate()".   (After all, the latter could be ambiguous if several variables had already been defined).

To stop viewing the documentation after pressing tab, you can press the Escape key, just like with the completion of options.

 
       

 

Finding the source

There is one more source of help you may find useful in the long run, though perhaps not immediately.  

  • One can use two question marks after a function name to pull up the documentation and the source code for the function.  
  • Again, to see this help, you can either evaluate a cell like below, or just move your cursor after the question mark and press tab.

The ability to see the code (the underlying instructions to the computer) is one of Sage's great strengths.  You can see all the code to everything

This means:

  • You can see what Sage is doing.
  • Your curious students can see what is going on.
  • And if you find a better way to do something, then you can see how to change it!
binomial?? 
       

Annotating with Sage

Whether one uses Sage in the classroom or in research, it is usually helpful to describe to the reader what is being done, such as in the description you are now reading.   

Thanks to the mini-word processor TinyMCE and a TeX rendering engine called jsmath, you can type much more in Sage than just Sage commands.  This math-aware setup makes Sage perfect for annotating computations. 

To use the word processor, we create a text cell (as opposed to a input cell that contains Sage commands that Sage evaluates). 

To create a text cell, do the following.

  • First, move the cursor between two input cells, until the thin blue line appears.
  • Then hold the Shift key and click on the thin blue line. 
  • (So to create an input cell, one merely clicks, but one "Shift-Click"s to create a text cell.)

Try inserting a text cell between the input cells below.

 
       
 
       

TinyMCE makes it easy for format text in many ways.  Try experimenting with the usual bold button, underline button, different text fonts and colors, ordered and unordered lists, centering, and so on.  Some of the shortcut keys you are familiar with from other word processors may also work, depending on your system.

There are two other things you can do which take advantage of the worksheet being on the web.  

  • It is easy to link to other helpful websites for additional information.  
    • While in the editor, highlight a word or two, and then click on the little chain link toward the bottom right of the buttons.  
    • You can now type in a web address to link to.  
    • Be sure to prepend http:// to the address.  Normally, one should also select it to appear in a new window (so the Sage session isn't interrupted).
  • You may have already noticed that some of the descriptions above had typeset mathematics in them. In fact we can add nearly arbitrary LaTeX to our text cells!  
    • For instance, it isn't too hard to add things like
      \zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)\; .
       
    • One just types things like "$$\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right)$$" in the word processor.  
    • Whether this shows up as nicely as possible depends on what fonts you have in your browser, but it should be legible.  
    • More realistically, we might type "$f(x)=x^2$" so that we remember that f(x)=x^2 in this worksheet.

Here is a simpler example.

f(x)=x^2 f(9) 
       
81
81

If f(x)=x^2, then f(9)=81.

It is simple to edit a text cell; simply double-click on the text. 

Try double-clicking on this text to edit this text cell (or any text cell) to see how we typed the mathematics!

html("Sage is <a style='text-decoration:line-through'>somewhat</a> <b>really</b> cool! <p style='color:red'>(It even does HTML.)</p>") 
       
Sage is somewhat really cool! 

(It even does HTML.)

Sage is somewhat really cool! 

(It even does HTML.)

We just have an hour together, so I would rather have you explore.  

So in the spirit of Grätzer's LaTeX book, here is a gallery of some of my favorite examples of Sage functionality.  

I particularly encourage you to take small pieces of these, make a new cell, and try to discover their use on their own.  

Calculus

integral(3*x^2/sqrt(25*x^2-3),x) 
       
3/50*sqrt(25*x^2 - 3)*x + 9/250*log(50*x + 10*sqrt(25*x^2 - 3))
3/50*sqrt(25*x^2 - 3)*x + 9/250*log(50*x + 10*sqrt(25*x^2 - 3))
find_root(cos(x)==sin(x),0,pi/2) 
       
f(x,y) = sin(x^2)*y+x*y^2 show(f(x,y).hessian()) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr} -4 \, x^{2} y \sin\left(x^{2}\right) + 2 \, y \cos\left(x^{2}\right) & 2 \, x \cos\left(x^{2}\right) + 2 \, y \\ 2 \, x \cos\left(x^{2}\right) + 2 \, y & 2 \, x \end{array}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr} -4 \, x^{2} y \sin\left(x^{2}\right) + 2 \, y \cos\left(x^{2}\right) & 2 \, x \cos\left(x^{2}\right) + 2 \, y \\ 2 \, x \cos\left(x^{2}\right) + 2 \, y & 2 \, x \end{array}\right)
y = var('y') P=plot_slope_field(1-y,(x,0,3),(y,0,20)) y = function('y',x) # declare y to be a function of x f = desolve(diff(y,x) + y - 1, y, ics=[2,2]) # solve the DE, with Initial ConditionS of 2,2 Q=plot(f,0,3) html('$f=%s$'%(latex(f),)); show(P+Q) # I can use HTML in my outcomes 
       

Number theory and algebra

factorial(2011) 
       
2
2
primitive_root(991) 
       
6
6
var('z') M.<a>=NumberField(z^2-2) M ; M.is_galois() 
       
Number Field in a with defining polynomial z^2 - 2
True
Number Field in a with defining polynomial z^2 - 2
True
G = graphs.PetersenGraph() H = G.automorphism_group() H.is_simple() 
       
False
False

Graphs and discrete math

graph_editor() 
       
Permutations(5) 
       
list(IntegerVectors(4,3)) 
       
[[4, 0, 0], [3, 1, 0], [3, 0, 1], [2, 2, 0], [2, 1, 1], [2, 0, 2], [1,
3, 0], [1, 2, 1], [1, 1, 2], [1, 0, 3], [0, 4, 0], [0, 3, 1], [0, 2, 2],
[0, 1, 3], [0, 0, 4]]
[[4, 0, 0], [3, 1, 0], [3, 0, 1], [2, 2, 0], [2, 1, 1], [2, 0, 2], [1, 3, 0], [1, 2, 1], [1, 1, 2], [1, 0, 3], [0, 4, 0], [0, 3, 1], [0, 2, 2], [0, 1, 3], [0, 0, 4]]

"Applied" Math

R = [[1,2],[3.45,4],[6,5],[4,3],[1.5,2.3]] var('a,b') model(x) = a*x+b find_fit(R,model) points(R)+plot(model(a=find_fit(R,model)[0].rhs(),b=find_fit(R,model)[1].rhs()),(x,0,10),color='red') 
       

The following cell finds a maximal stable set of a graph using linear programming.

g = graphs.PetersenGraph() p = MixedIntegerLinearProgram(maximization=True) b = p.new_variable() p.set_objective(sum([b[v] for v in g])) for (u,v) in g.edges(labels=None): p.add_constraint(b[u] + b[v], max=1) p.set_binary(b) p.solve(objective_only=True) 
       

There are many ways to do statistics in Sage.  Here we use the very powerful program R, which is part of Sage.

x=r([2.9, 3.0, 2.5, 2.6, 3.2]) # normal subjects y=r([3.8, 2.7, 4.0, 2.4]) # with obstructive airway disease z=r([2.8, 3.4, 3.7, 2.2, 2.0]) # with asbestosis a = r([x,y,z]) # make a long R vector of all the data b = r.factor(5*[1]+4*[2]+5*[3]) # create something for R to tell which subjects are which a; b # show them 
       
 [1] 2.9 3.0 2.5 2.6 3.2 3.8 2.7 4.0 2.4 2.8 3.4 3.7 2.2 2.0
 [1] 1 1 1 1 1 2 2 2 2 3 3 3 3 3
Levels: 1 2 3
 [1] 2.9 3.0 2.5 2.6 3.2 3.8 2.7 4.0 2.4 2.8 3.4 3.7 2.2 2.0
 [1] 1 1 1 1 1 2 2 2 2 3 3 3 3 3
Levels: 1 2 3
r.kruskal_test(a,b) # do the KW test! 
       
	Kruskal-Wallis rank sum test

data:  sage17 and sage33 
Kruskal-Wallis chi-squared = 0.7714, df = 2, p-value = 0.68
	Kruskal-Wallis rank sum test

data:  sage17 and sage33 
Kruskal-Wallis chi-squared = 0.7714, df = 2, p-value = 0.68

Eye Candy

plot([x^i for i in [1..10]],(x,0,1),fill = dict((i,[i+1]) for i in [0..9])) 
       
import pylab A_image = pylab.mean(pylab.imread(DATA + 'NorwichBand.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)) html('<h2>Compressed using %s eigenvalues</h2>'%i) 
       

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

var('x,y') plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1)) 
       

Final Pedagogical Notes

Part of our gallery of functionality is pedagogical.  Here are many things one can do with Sage (or any other such software) - but in Sage's case, from the convenience of students' own rooms.  For instance:

  • Use interactive "mathlets" or "Sagelets" like the one with the image of the Norwich band to create lab experiments which don't require remembering syntax or commands - even completely GUI-driven. 
  • Fully featured lecture notes. 
  • Sage's power only increases as you go up the mathematical food chain, as it were, so it can be incredibly useful for undergraduate (or your own!) research. 
  • Create a "cheat sheet" of commands which students can use to check homework or try things out. 
  • Allow students to share worksheets collaboratively for a project, with you or without you.  This is very easy (see the "Share" button above), but I haven't found the need for it yet; if you do a lot of that, you may want to try it.
  • For more ideas, join the sage-edu list at Google groups.

And of course, for everything else, please go to 

www.sagemath.org

for all things Sage.  Thanks for participating!