Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168744
Image: ubuntu2004

MTH213/MH2400 - Experimental Mathematics

Lesson 1: Introduction to Sage

 

Introductory Sage Tutorial - Welcome!

Sage and Python. What are they, and what is the difference between them?

Python is a general programming language. It is higher level than C and Java, which means it makes things easier for you, at the price of speed.

Sage extends Python to do mathematics. That includes a Python library with mathematical objects and a preparser. A preparser is a translator that makes you use Sage objects instead of Python ones, like when you type '3'. Sage is used to work on mathematical subjects as varied as

  • Numerical Linear Algebra
  • Calculus
  • Number Theory
  • Statistics
  • Combinatorics and Graph Theory
  • Cryptography
  • and many more.

Sage has a graphical user interface that runs in the browser and is called the Sage Notebook, or the Sage Worksheet. You are using the Sage Notebook right now.

This tutorial has the following sections:

Evaluating Sage Commands

(How do I get Sage to do some math?)

The little boxes below are called input cells or code cells. To evaluate the content of an input cell, 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.

Exercise: Evaluate the following cell

2+2

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

You can also evaluate a cell using a keyboard shortcut. The keyboard shortcut is "Shift-Enter": hold down the Shift key while you press the Enter key. You can also edit a cell and evaluate it again.

Exercises:

  • If the following cell isn't active, click in it. Then evaluate it by pressing "Shift-Enter".
  • Change the number "2010" to your favorite number and evaluate the cell to find its factorization.
factor(2010)

To create a new input cell, move your cursor over the space above or below another cell.  A blue horizontal line as wide as the browser appears. Click on the line to insert a new cell.  To delete an input cell, just delete all the text inside of it, and then press backspace in the now-empty cell. 

Exercise: Create a few new input cells below, do some arithmetic, and delete one of the input cells.

Different (evaluated) cells depend upon each other. This can be best explained by an example.

Exercise: There are three input cells below.

  • Evaluate the second input cell first. Do you get any error?
  • Now, evaluate the first input cell, and follow it by evaluating the second input cell below. Do you still get an error?
  • Now, evaluate the third input cell.
a=30
b=a^2
factor(b)

Clearly, the variable b above is not defined until we define a first. Hence the second input cell depends on the first input cell. Similarly, the third input depends on both the first and the second input cell. That is, unless both the first and the second input cells have been evaluated, the third input cell will also produce an error.

 


Finally, something less trivial, just to whet your appetite: 

batman logo

Let's draw this figure in Sage!

var('x y') f1(x,y)=((x/7)^2*sqrt(abs(abs(x)-3)/(abs(x)-3))+(y/3)^2*sqrt(abs(y+(3*sqrt(33))/7)/(y+(3*sqrt(33))/7))-1) f2(x,y)=(abs(x/2)-((3*sqrt(33)-7)/112)*x^2-3+sqrt(1- (abs(abs(x)-2)-1)^2)- y) f3(x,y)=(9*sqrt(abs((abs(x)-1)*(abs(x)-3/4))/((1- abs(x))*(abs(x)-3/4)))-8*abs(x)-y) f4(x,y)=(3*abs(x)+.75*sqrt(abs((abs(x)-3/4)*(abs(x)-1/2))/((3/4- abs(x))*(abs(x)-1/2)))- y) f5(x,y)=(9/4*sqrt(abs((x-1/2)*(x+1/2))/((1/2-x)*(1/2+x)))-y) f6(x,y)=((6*sqrt(10))/ 7+(3/2-abs(x)/2)*sqrt(abs(abs(x)-1)/(abs(x)-1))-(6*sqrt(10))/14*sqrt(4- (abs(x)-1)^2)-y) p1=implicit_plot(f1==0,(-8,8),(-3,3),plot_points=200) p2=implicit_plot(f2==0,(-8,8),(-3,3),plot_points=200) p3=implicit_plot(f3==0,(-8,8),(-3,3),plot_points=200) p4=implicit_plot(f4==0,(-8,8),(-3,3),plot_points=200) p5=implicit_plot(f5==0,(-8,8),(-3,3),plot_points=200) p6=implicit_plot(f6==0,(-8,8),(-3,3),plot_points=200) show(p1+p2+p3+p4+p5+p6)

Exercise: fix the plot! (You might need to use a bit of guessing to figure out the way it works)




Objects in Sage

Everything in Sage and in Python is an object. Each object has a type (e.g. number, vector, matrice, set, etc). You can inspect its type by typing

type
type(4)
type([1,2,3])

Notice that list does not have sage in its name. Lists are basic Python types.

You can build an object in various ways. The most used one is calling the type name as a function with certain parameters.

v = vector([1,2,3,5]) type(v)

The letter xx is treated in a special manner in sage. By default, it is considered as a symbolic variable. This means that the variable can be used in a program just as one does mathematics. Let us define a function f(x)f(x) below in terms of the symbolic variable xx.

type(x)
f(x)=x^2

Exercises:

  • What is the type of the function f(x)f(x)?
  • Create a new cell and evaluate the function f(x)f(x) at some number, say at 9.

 

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 guidance.  To access these, just click the "Help" link at the top right of any worksheet.  Also, the Quick Reference cards are useful.

Tab completion

To see what you can do to an expression, usually you can just give the expression a name, type a period after it, and then press Tab.  You will see a list pop up of all the things you can do to the expression.

Exercise: Just in case you didn't define the function f(x)f(x) before, evaluate this cell to (re-)define f(x)f(x).

f(x)=x^2

Exercise: After evaluating the above cell, put your cursor after the period in the cell below and press your Tab key.

Note: To stop viewing the list, first ensure that the cell containing "f." is active and then press the Escape key on the keyboard.

f.

One of the things in that list above was "integrate".  Let's try it.

f.integrate(x)

This works with completing commands as well.

Exercise: Press Tab after the "plot" below to see all the commands that start with the letters "plot". Clicking on one of the options will use it for this cell.

plot

Remember, if you decide not to use any of the options, pressing Escape should make the list disappear.

Finding documentation: the question marks

Use a question mark after a function name to display the documentation for the function.  Almost all documentation in Sage has extensive examples that illustrates how to use the function. To see the help in this manner, one can either

  • Press "Shift-Enter" to evaluate the expression and show the documentation in the output below, or,
  • Press "Tab" after the "?" symbol to show the documentation on a dynamic popup.

For instance, the documentation for the integrate command has examples illustrating that the syntax requires "f.integrate(x)" and not just "f.integrate()". The latter would be ambiguous if ff was a function of several variables.

Exercise: Get the documentation for the integrate function by press "Tab".

f.integrate?

To stop viewing the documentation after pressing Tab, you can press the Escape key, just as you did with the completion of options.

Exercise: Evaluate the expression below to access its documentation.

binomial?

Exercise: Get the documentation for another function!

Finding the source

One can use two question marks after a function name to get both the documentation and the source code for the function.  Again, to see this help, you can either evaluate a cell, or just move your cursor after the question mark and press Tab.

The ability to see the code is one of Sage's great strengths.  You can see all the code to everything!  This means you can see what Sage is doing; if you are curious you can see how the function is implemented; and if you know a better way to implement it, then you can change it!

Exercise: Get the source code for the binomial function below.

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 mathematical Sage commands.  This math-aware word processor makes Sage perfect for annotating computations. 

To use the word processor, we create a text cell, as opposed to a input cell. Recall that an input cell contains Sage commands that Sage evaluates. To create a text cell, first move the cursor between two input cells.  Then hold the Shift key and then left click on the thin blue line that appears. Note that to create an input cell, one merely clicks, but one is required to "Shift-Click" to create a text cell.

Exercise: insert 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 ζ(s)=n=11ns=p(11ps)\zeta(s)=\sum_{n=1}^{\infty}\frac{1}{n^s}=\prod_p \left(\frac{1}{1-p^{-s}}\right) by just typing 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)=x2f(x)=x^2 in this worksheet.

To edit a text cell, simply double-click on the text.  Try double-clicking on this text to edit this text cell (and you can see how we typed the mathematics above!).

Exercise: Double click on the cell below (containing the description of f(x)=x2f(x)=x^2) and edit it and change it.

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

Of course, one can do much more, since Sage can execute arbitrary commands in the Python programming language, as well as output nicely formatted HTML, and so on.  If you have enough programming experience to do things like this, go for it!

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

The Sage Notebook interface

The input and text cells is usually how you interact with the Sage process. You will also need to save your work and to do that you need to understand the other elements of the notebook interface,- the many buttons and links at the very top of the notebook! Let us go over the most important ones.

    • Toggle: The Toggle link hides most of the controls at the top of the notebook.
    • Home: The Home link takes you back to the list of all the notebooks that you have on the list. Note: Make sure you save your notebook before using this link!
    • Help: The Help link opens up the extensive documentation of Sage in a new browser window.
    • Sign Out: The sign out link signs you out and takes you back to the login page. Note: Make sure you save your notebook before using this link!
    • File: The "File" drop down menu allows you to save this notebook, termed as worksheet in the menu, to a file in your hard disk. The file will have .sws extension. If you already have a .sws notebook file, then you can upload the file by using the "Load worksheet from a file" menu option.
    • Action: The most important option under the "Action" menu is the interrupt menu item. It allows you to interrupt a running calculation. This might be desirable if you find that the program is stuck, or if it is taking too long to finish. Note: Another way to interrupt a calculation is to click inside the cell that is being computed and press "Escape".
    • Typeset: The "Typeset" button can be used to print the evaluated output using LaTeX. This produces much nicer looking output.  Exercise: Set "Typeset" on and re-evaluate the input cells in this notebook.
    • Print: The "Print" button can be used to view a printable version of the notebook.
    • Worksheet View: This is the current view of the notebook, as you are viewing it now.
    • Plain View/Text: This is an advanced functionality. It displays the raw html text version of the notebook, as it is saved on the hard disk. You can perform raw html edits on the notebook in the "Plain View" mode. In this course, you would not be required to use either of these views.
    • Revisions: Revisions shows the previous versions of the notebook that were saved when you quit the notebook.

Saving your work

There are several ways you can save your work:

  • Every time you evaluate a cell, a temporary copy of the notebook gets saved to the hard disk.
  • Clicking on the "Save" button at the top of the notebook saves a temporary copy to the hard disk.
  • Clicking on the "Save and Quit" button at the top of the notebook saves the notebook to the hard disk and makes a backup revision of the notebook.
  • Go to "File" and then "Save worksheet to a file" to save this notebook to a file on your hard disk. Since the computers in the labs might erase the files you save to the hard disk, it is recommended that you save the files to your personal USB drive.

Note: It is highly recommended to use the "Save and Quit" button before you log out. It is also advised that you save your notebooks to a file and copy them to your personal USB drive.

That's the end of the 1st lesson.  Feel free to create more of your own worksheets!

This worksheet is based on a tutorial from MAA Prep Workshop found at http://wiki.sagemath.org/prep/2011/Tutorials.