- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Start Sage
- •Installing Sage
- •Starting Sage
- •Prerequisites
- •Installation
- •Summary
- •Command history
- •Working with code
- •Arithmetic operators
- •Strings
- •Functions
- •Functions with keyword arguments
- •Objects
- •Summary
- •Python 2 and Python 3
- •Running scripts
- •Strings
- •List comprehensions
- •Storing data in a dictionary
- •Summary
- •Vectors and vector spaces
- •Creating a vector space
- •Vector operators and methods
- •Decomposing matrices
- •Summary
- •Using graphics primitives
- •Summary
- •Substitutions
- •Finding roots
- •Derivatives
- •Integrals
- •Series and summations
- •Summary
- •Computing gradients
- •Constrained optimization
- •Probability
- •Summary
- •Making our tanks move
- •Unit testing
- •Summary
- •Introducing Python decorators
- •Making interactive graphics
- •Summary
- •Index
Getting Started with Sage
When you use any of the help commands, the normal contents of the terminal will be replaced by a help screen, which looks like this:
Use the arrows to scroll up and down. Use the Spacebar to page down, and the b key to page up. Press q to leave the help screen and return to the command line. If you want to see the documentation and the source code for the function (if the code is available), type two question marks after the function name:
sage: exp??
Finally, to see the complete class documentation, use the help function:
sage: help(exp)
Command history
The Sage command line has a number of built-in shortcuts that help you work more efficiently. Most of these will be familiar to people who have worked with UNIX-like command line interfaces. We have already seen that you can use the Up arrow on your keyboard to scroll through commands that you have previously entered. To see a list of everything you have typed in this session, type %hist at the command prompt.
[ 46 ]
Chapter 3
We can use the %macro command, in conjunction with the %hist command, to define macros. Let's say we frequently need to define some physical constants, so we want to save those commands as a macro. First, enter the following commands and then display them with the %hist command:
sage: epsilon_zero = 8.85418782e-12 sage: mu_zero = 1.25663706e-6 sage: NA = 6.0221415e23
sage: %hist
1:epsilon_zero = RealNumber('8.85418782e-12')
2:NA = RealNumber('6.0221415e23')
3:mu_zero = RealNumber('1.25663706e-6')
4:_ip.magic("hist ")
Note that the results of the %hist command will be different on your screen, because the command history for your session is not the same as the history for the session used to create this example. Look at the output from %hist and note the number to the left of each command. Now, use the %macro command to define a macro called constants using commands 1-3. You will have to replace the numbers 1 and 3 with the appropriate numbers from your command line history.
sage: %macro constants 1-3
Macro `constants` created. To execute, type its name (without quotes). Macro contents:
epsilon_zero = RealNumber('8.85418782e-12') NA = RealNumber('6.0221415e23')
mu_zero = RealNumber('1.25663706e-6')
We can now use the command constants to quickly define some variables that contain physical constants. For more information about the %macro command, type the following:
sage: %macro?
Tabcompletion
Tab completion can also make your life easier. Type the first letter (or first few letters) of a command at the prompt, and press Tab to see a list of possible completions. For example, type pl and press Tab:
sage: pl |
|
|
|
|
plot |
plot_step_function |
plotkin_bound_asymp |
||
plot3d |
plot_vector_field |
plotkin_upper_bound |
||
plot_slope_field |
plot_vector_field3d |
|
||
|
|
|
|
|
|
|
[ 47 ] |
|
|
|
|
|
|
|
Getting Started with Sage
Interactivelytracingexecution
Only the interactive shell allows you to trace the execution of a command interactively. Use the trace function, which accepts a string that contains a Sage command. For example, to trace the execution of the following exp function:
sage: trace("exp(1.0)")
This command starts the Python debugger, which gives you the ipdb> prompt. To step through execution of the function, type step (or just s) at the prompt and press Enter. Type ? to get help on other commands you can use in the debugger. Type quit (or just q) to quit the debugger and return to the Sage command line. A typical session looks like this:
Usingthenotebookinterface
The notebook interface is a more flexible way to work with Sage. Your calculations and the resulting numbers and plots can be saved together in a worksheet. You can add headings and text to document what you've done. In Chapter 10, we'll learn how to use LaTeX to typeset mathematical expressions right in a worksheet.
[ 48 ]
Chapter 3
Startingthenotebookinterface
There are several ways to start the notebook interface. If you are running Sage in a virtual machine on Windows, double-click on the icon labelled Sage Notebook. If you are starting Sage from the command line, you can use the –notebook option to start Sage and launch the notebook interface. If you already have the Sage interactive shell running, use the notebook() function to start the notebook interface:
sage: notebook()
If a web browser doesn't open automatically, manually start the web browser and go to http://localhost:8000.
If this is your first time running the notebook interface, follow the prompts in the terminal to enter a password for the administrative account.
[ 49 ]
Getting Started with Sage
When you have entered a password, you will see a screen that allows you to log in. Log in using the name and password you just created.
Once you have logged in, you will see the home page for the notebook interface:
[ 50 ]
Chapter 3
You can create a new worksheet by clicking the New Worksheet link. When prompted, enter a name in the dialog box. The blank worksheet should look like this:
You can access many powerful features of the notebook interface from this page:
The File menu allows you to perform operations such as saving, renaming, and deleting worksheets
The Action menu allows you to control the evaluation of cells, such as interrupting a calculation that is taking too long
The Data menu allows you to attach a data file to a worksheet
The sage menu allows you to choose which tool evaluates the code in a cell
The six tabs towards the right side of the screen allow you to perform other operations:
The Worksheet tab shows the default view of the worksheet
The Edit tab allows you to edit a text representation of the worksheet The Text tab shows you a read-only text representation of the worksheet
The Undo tab shows a revision history of the worksheet, and allows you to go back to a previous version
The Share tab allows you to give other Sage users the ability to edit your worksheets
The Publish tab allows you to make your worksheet available on the Web, where it can be viewed by anyone who can access the web server on your computer
[ 51 ]
Getting Started with Sage
Timeforaction–doingcalculationswiththenotebookinterface
Now, we will use the Notebook interface to repeat the calculations that we did with the interactive shell. We will add some text to document what we've done.
1. Define variables.
The empty white box in the middle of the worksheet is an input cell. Click in the input cell and type in the following text:
R |
= |
250e3 |
# |
ohms |
C |
= |
4e-6 |
# |
Farads |
tau |
= R * C |
|
|
|
tau |
|
|
|
|
To evaluate the cell, press Shift-Enter or click the evaluate link, which is found just below the bottom-left corner of the input cell. As soon as the code executes, an empty input cell appears on the screen below the previous cell. The screen will look like this:
2. Perform a calculation.
You can also insert an empty input cell by moving the cursor into the blank space above or below an existing cell. When a thin, solid bar appears in the blank space, click to insert a new input cell. Enter the following code in the next input cell:
v0 = 20.0 |
# |
Volts |
t = 1.0 |
# |
seconds |
v0 * exp(-t / tau)
Click the evaluate link or press Shift-Enter to execute the code. The result will appear below the input box.
[ 52 ]
Chapter 3
3.Add documentation.
Let's add a text field to document what we've done. Move the mouse cursor to the empty space just above the first input box. As your mouse enters this area, a thin, solid bar will appear. Hold down the Shift key and click on this rectangle to insert a new text cell. The text cell will include a graphical editor that allows you to enter text and apply HTML formatting. Choose Heading 1 from the menu at the upper left corner of the editor, and type RC Circuit Analysis into the box. Click the Save Changes button to exit the editor.
[ 53 ]
Getting Started with Sage
4.Save your work.
Click the Save button at the top-right corner of the worksheet. If you are done with this notebook, click Save & quit.
What just happened?
We repeated the calculation that we performed earlier. This time, we were able to create a single document that contains calculations, results, and documentation. We made use of comments in the input cells to note the units for each value (you can also use comments on the command line). A # sign indicates the beginning of a comment. Sage ignores anything on the line after the #. Get in the habit of using comments to remind yourself how the code works. As in the interactive shell, no output is displayed when a value is assigned to a variable. Only the last line of an input cell will produce output on the screen. We'll see how to produce more output in the next section.
Gettinghelpinthenotebookinterface
To get help with the notebook interface, click the Help link in the upper-right corner of the notebook window. To get help on a command or function, type the command name in an empty input cell, followed by a ?. Press Tab, or evaluate the cell, to see the documentation. You can also type the command name followed by ?? to see the source code. Another option is to type help(command), which will result in a link that you can click to open the documentation in a new tab or window. To search the documentation, type search_ doc("my query") in an empty input cell and evaluate the cell. You can also search the source code by using search_src("my query").
Workingwithcells
The example showed some of the basic commands that can be used to edit worksheets.
The following shortcuts are useful for working with cells:
Evaluate cell |
With cursor in cell, hold Shift and press Enter |
Insert new input cell |
Move cursor between cells and click when solid bar appears |
Insert new text cell |
Move cursor between cells and Shift-click when solid bar appears |
Delete cell |
Delete cell contents, and then press Backspace |
Split cell at cursor |
Press Ctrl-; |
Join two cells |
Click in the lower cell and press Ctrl-backspace |
[ 54 ]
