Sage Worksheets

Introduction

Sage Worksheets were developed for collaborative, notebook-style computing with SageMath on the CoCalc platform. Like Jupyter Notebooks, Sage Worksheets support many programming environments. More than one language environment can be used in the same Sage Worksheet.

Note: in the CoCalc User Manual, we will generally use the term SageMath to refer to the open source mathematical system that runs on CoCalc and in many other environments. Elsewhere, you may see it referred to simply as Sage.

In CoCalc, there are at least three ways to run SageMath:

  • in a Sage Worksheet
  • in a Jupyter Notebook
  • from the command line in a terminal

What’s a Sage Worksheet?

A Sage Worksheet is a file ending in .sagews and is subdivided into cells. Each cell has an input region and an output region, which might be 0, 1, 2, or many lines long. The input can be mathematical, in the Sage syntax, or it could be in many other formats, including Markdown, HTML, Python 2 or 3, and R.

When you run a cell, by clicking Run or typing Shift-Enter, the input is executed (or formatted, for text processing). The result appears in the output after the calculation is done.

To begin work on a Sage Worksheet, create a file ending with .sagews.

_images/sagews-example.png

example of a Sage Worksheet

How to Revert/Undo Changes in a Sage Worksheet

For tiny changes, control+Z (or command+Z on a mac) will give you an instantaneous undo.

When it comes to undoing larger changes, one of the most useful things about CoCalc is that it will keep all versions of all of your files. This means that you can revert back to previous versions easily.

TimeTravel

From any worksheet, click on TimeTravel.

_images/sagews-example-tt.png

Using the slider, look at all the versions. Find the revision that you want and then click “Revert live version to this.”

_images/sagews-timetravel-a.png

looking at a Sage Worksheet with TimeTravel

Backups (snapshots)

For a list of snapshots taken by CoCalc, use the Backups button from the TimeTravel view or the Files list. Note that these backups are read-only. If you want to continue working on a file from a snapshot in Backups, you will need to copy it into a writable folder in your project.

Understanding Error Messages

Question: I did xyz and now I have this huge error message! Why?

Often when SageMath encounters an error, a long error message appears. This output is called a “stack trace” and it can be very useful to experienced programmers. However, often it is enough to look at the last line of the error message to understand what has gone wrong.

_images/sagews-stacktrace.png

making sense of error messages

Help for Programmers

Extended Documentation

To see verbose documentation for language features, including commands, methods, and attributes, use the help() function.

_images/sagews-help.png

Concise Documentation

To see concise documentation (docstrings) for language features, attributes, append a single question mark and run the cell. This information is similar to what you get with help().

_images/sagews-1q.png

Source Code

To see source code for language features, append two question marks and run the cell.

_images/sagews-2q.png

Tab Completion

To get a hint for possible completions of a function name, method argument, etc., type the beginning of what you are looking for then press the [tab] key. This is a quick way to browse through the methods for an object.

_images/sagews-tabc.jpg

How Long are Definitions Stored in a Sage Worksheet?

Definitions (of variables, functions, etc.) are stored in the worksheet process and are retained until that process terminates. The worksheet process may end by itself, for example when Restart is clicked at the top of the worksheet. It is also terminated when the sage worksheet server terminates or is restarted, when the project is stopped or restarted, and when the host virtual machine restarts.

Projects are stopped after some number of hours of non-interactive use (see Idle Timeout). If your project is on a free server, it will be stopped whenever the Google pre-emptible server instance restarts, typically once per 24 hours.

SageMath built-in functions save, load, save_session and load_session are useful for saving and restoring state. See Loading and saving sessions and listing all variables.

Wiki resources

Conversion utilities

  • There are buttons in the UI to convert to PDF, a print-button or a Jupyter Notebook
  • SageWS to HTML (including a utility to extract the sagews file from a generated HTML file)
  • Run smc-sagews2pdf --help in a Linux Terminal for more information about converting to PDF
  • Similarly, smc-sagews2ipynb is a command-line utility to convert to *.ipynb.

SageMath specific

Items relating strictly to SageMath, whether or not you are using CoCalc.

Howto

Attach Sage files to Sage Worksheets

Is there a way to write functions in one worksheet, and then import them to another and use them there?

Not exactly, but you can write code in a .sage file and then load it into another Sage Worksheet as illustrated at https://cocalc.com/share/4a5f0542-5873-4eed-a85c-a18c706e8bcd/support/2018-06-12-sage-code/?viewer=share

  1. Put code in a new file with extension .sage, e.g. code.sage
  2. In a Sage worksheet or the terminal, run this: %attach code.sage or attach("code.sage")
  3. Now all code in code.sage is available in your worksheet, and whenever it changes, it will get reloaded automatically.
  4. If you’re using Jupyter, this is all broken (see https://github.com/sagemathinc/cocalc/issues/2916), but at least you can use load("code.sage") instead.

How can I connect an HTML form with my Python code?

Note

The following explanation might be outdated!

To create a connection between your HTML form in a .sagews file created using HTML, CSS and JS, you need to use the worksheet.execute_code() function in your JS code.

Because worksheet.execute_code` isn't a standard JS function, but special CoCalc function, you need to load your JS code with ``worksheet.execute_code(). In particular do NOT use

load('path/to/js/code.js')

but instead use

salvus.javascript(open('path/to/js/code.js').read())

For example in a .sagews file suppose you created a div with id='myApp' as follows:

%html
<div id='myApp'>
....
    <div id="msgLog"></div>
    <div id="msgErr"></div>
</div>

Let’s say your Python function will double x:

def myfunc(x):
    print(x*2)

In your JS code type:

worksheet.execute_code({
    code: 'myfunc(n)',
    data: {n: 2},
    preparse: true,
    cb: function(msg){
            if(msg.stdout){$('#myApp #msgLog').html(msg.stdout);}
            if(msg.stderr){$('#myApp #msgErr').html(msg.stderr);}
    }
});

Please note that myfunc() doesn’t return anything. On the contrary, it uses print() to send output. This is because JS and python are different languages, and you can’t just use return in your Python function to return some answer. stdout in JS code means standard output stream. That is, the print function in your Python code places the result of myfunc() in the output stream. That’s why you need to use print() but not return() in your Python code.

Also, if your Python code will raise some exception, then it will result in output to stderr the standard error stream. If you JS code (as in the example above) catches stderr, you can get any error message from your Python code.