Harald Schilly edited this page Feb 8, 2019 · 34 revisions

Sage Worksheet (and User Interface) Help

This page is for help when using worksheets in CoCalc. There is a highly related page for the mathematical syntax, in CoCalc and in Sage generally.

Remember: if you don't find what you need, or if you'd like to ask a question, then please email help@sagemath.com at any time. We'd love to hear from you! Please include a link (the address in your browser) to any relevant project or document.

Note: A 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, R, and so forth.

Question: How do I create a Sage worksheet in CoCalc?

You can one create by clicking the "+New" icon from any project, and then "Sage worksheet" (or by making a file whose name ends in .sagews).

Question: I think I've made a major mistake! How do I revert/undo changes?

One of the most amazing 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, and this can be a life-safer in the event of a catastrophic mistake.

From any worksheet, click on Timetravel. There is a sliding bar, but it can be very hard to see. Look under the orange button marked "Revert live version to this", and you'll see the slider.

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

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

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

In almost all cases, when something incorrect is inputted into Sage, an extremely long error message appears. This many-lined report can be extremely intimidating, and even moderately experienced Sage users might not know what to make of it.

This is actually called a "stack trace" and it is very useful to experienced programmers, who can use it to locate a bug very rapidly. However (for new users) it can be very intimidating. The key is to realize that the last line of the error message is usually the most useful.

Whenever you have a huge error message, start with the very last line. That's often all you need. Alternatively, some users find it easier to ignore the error message entirely, read their own code, and figure out what is wrong themselves.

Question: Hitting shift+enter does not evaluate the cell. Nothing works!

Furthermore, the shift key does capitalize letters, but it just behaves like the enter button when I hit shift+enter.

Answer: Make sure that the file you have open ends in .sagews exactly. If not, close the editor tab, rename the file to end in .sagews and open it again. The file acts as a Sage Worksheet only if it ends in .sagews exactly.

Question: How can I get help for a command, if I've remembered the name of that command?

To get help on a Sage command, you can type the name of the command, followed by a question mark. For example, to get help on plot, just type plot? and press shift-enter.

This even works if the command is a property of an object, like a matrix or a vector. For example, if you type

A = matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print A

and evaluate that, then Sage knows that $A$ is a matrix. Then if you type A.right_kernel?, you'll get help for the right_kernel command, even though that command is inside the object $A$. (The technical way of saying this is that right_kernel is a method of the object $A$, which is of class matrix.)

Help is also available on an object-by-object basis. Try this example:

A = matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])

help(A)

The above code will display so much information about matrices in Sage that CoCalc will have trouble displaying it all. For this reason, most users prefer the ? operator.

In the next question, we'll explain what to do if you've forgotten the name of a command.

Question: How can I get help for a command, if I've forgotten the name of that command?

If you remember the name of a command, such as A.right_kernal(), then you can use the question mark operator to get help for it, as we discussed in the previous question above. However, if you've forgotten the command to compute a null space, then you have several options.

  • Search in Google for: null space "sage reference manual"
  • Search in Google for: null space site:sagemath.org
  • Download a copy of the book Sage for Undergraduates, by Gregory Bard, published by the American Mathematical Society in 2015. The electronic version is a 100% free pdf file.

Note: That middle option deserves some further information. The term site:sagemath.org, with no spaces on either side of the colon, will restrict Google to search on webpages whose URL ends in sagemath.org and therefore your search is far more focused. Of course, you can use this with any URL that you like. Sometimes it is useful to search with site:edu.

There used to be a command called search_doc, but in many cases it has been rendered inoperative, for technical reasons.

Question: How can I get the source code for a command?

One of the advantages of open-source software is that you can see the source code actually being used to calculate your computations.

As you might recall from the question "How can I get help for a command, if I've remembered the name of that command?" somewhere above, you can put a question mark at the end of a command, to get help on that command. To get the source code, you merely put two question marks instead.

Here's an example:

A = matrix( 3,3, [1,2,3,4,5,6,7,8,9])
A.rref??

Question: How long are definitions saved in a .sagews file?

Definitions 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 .sagews file. 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, determined by the "Idle timeout" on project Settings and configuration (wrench icon). 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. For more information, see What is an "idle timeout?

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

Question: Is there a way for me to search the entire Help/FAQ/Wiki System of CoCalc?

Certainly. Click here to search the entire Help/FAQ/Wiki System.

Alternatively, the Index Page is like a table of contents.

Question: Is there an online or printed book where I can find some nice examples of doing math in Sage?

Yes! There is Sage for Undergraduates, a book written by Gregory V. Bard and published by The American Mathematical Society in 2015. (The pdf-file of that book is available for free, and the print version has an extremely low price.)

Question: All the input to one of the cells has suddenly vanished! How do I make it visible again?

You can hide and show input by clicking the triangle to the left of the input divider, or by clicking the "In" button at the top while selecting the input.

Question: How do I insert a new cell between two existing cells in a Sage worksheet?

Click the boundary between the output of the first cell and the input of the second cell.

Question: Can I configure one or more cells to run automatically when I open a worksheet?

Yes, you can! If you type %auto in the top of the cell (as the first line of input to a cell), then it will automatically run whenever the worksheet is first opened.

Question: How do I execute all the code cells in the entire worksheet?

Control+A (or command+A on Mac), then click run or hit "control+enter".

Question: How do I execute code from a set of consecutive cells?

Just highlight those cells, then click run or hit "control+enter".

Question: The output of one of my cells is getting cut off because there is too much output. How do I raise the limit on the number of output messages per cell in a Sage worksheet?

    import sage_server
    sage_server.MAX_OUTPUT_MESSAGES=100000

See this published worksheet for more details.

Also, type sage_server.[tab key] to see information about other limitations.

Question: How do I adjust the output cut-offs, for example, to protect against infinite loops?

It is an extremely common programming mistake to write an infinite loop, particularly when first learning about loops. Because CoCalc assumes an experienced programmer, the "cutoff limits" are set rather high. Users new to programming might want to set that limit lower, so that their screen isn't overflowing with repeated lines in the event that they inadvertently code up an infinite loop. (By the way, this works in all languages, not just Sage, e.g. R, C, FORTRAN, whatever you'd like.)

You can type

print sage_server.MAX_STDOUT_SIZE

at any time to find out the current limit. By default, it is 40,000.

Then, you can change it by typing something like this:

sage_server.MAX_STDOUT_SIZE = 500

Note, this is 500 characters. Take care to ensure that the setting of this variable will be executed before your code starts. If you type

sage_server.MAX_STDOUT_SIZE = 500

for i in range(0,1000):
    print i

then it will be cut off somewhere in the middle of printing 152, because you need to count each digit, as well as the invisible "end of line" symbol. At the 501st character, the computation is stopped, and there is no more output.

By the way, it isn't just the case that the output is truncated at this point. The computation is halted as well. (The technical term for this is that "the process is killed.")

Question: How do I delete a cell?

It's like a text document. You can delete delimiters and lines using any editor delete commands, for example "ctrl+d" or backspace/delete if you're using Standard keyboard bindings, or "dd" or "x" in command mode if you're using Vim keyboard bindings. You can also highlight a range of several cells and delete them all at once, just as with a text file.

Question: How do I split a cell into two cells?

Just put your cursor in the input region of the cell, at the spot where you want the split to go. Then press control+; (or command+; on a Mac).

Question: How do I jump to a specific line?

Just press control+L (or command+L on a Mac).

Question: How can I insert HTML, LaTeX, or simple text between two cells in a Sage worksheet?

This is a great way to annotate your worksheet, whether for others to be able to read it and understand it, for students, or just for yourself.

To do this, first insert a cell between those two cells. (To do that, click the boundary between the output of the first cell and the input of the second cell.) Then put

%md

at the top of this newly created cell to use markdown formatting (which fully supports LaTeX formulas).

When you press shift-enter, the output is displayed. Type md(hide=True) or use the triangle to the left of the input if you would like to hide the input for display purposes.

See http://daringfireball.net/projects/markdown/ about markdown.

You can also use %html in a similar way to the above, to use HTML instead of markdown. The %html mode also supports LaTeX.

More details on HTML and markdown follow in the next three questions.

Question: I want to annotate my worksheet with some HTML. How do I make an HTML cell inside of a worksheet?

Just type %html as the first line of input to that cell.

Most of HTML, and even Javascript, should work. No graphical editor is available yet to edit %html cells, but we hope to change that soon.

Question: I want to annotate my worksheet with the markdown language. How do I make a markdown cell inside of a worksheet?

Just type %md as the first line of input for your cell.

By the way, markdown comes in several flavors. CoCalc uses Github-flavored Markdown.

(See https://guides.github.com/features/mastering-markdown/ )

You can add mathematical expressions. For example, create a cell with:

%md
# Cool Formulas:

My *absolute* favorite formula is
$e^{i \pi} = -1$
but some people write it as
$$ e^{i \pi} +1 = 0 $$
which is clearly the same thing.

That code produces the following output

Question: I want to annotate my worksheet with the LaTeX language. How do I make a LaTeX cell inside of a worksheet?

Just type %latex as the first line of input for your cell. Then you can write as much or as little LaTeX as you like. For example,

%latex

Sometimes it is \emph{much easier} to typeset mathematical formulas using LaTeX than {\bf any other tool}.

Consider, as an example, how easy it is to define a polynomial: $x^3 - 2x^2 - 7x - 6$.

Or better yet, an integral:
$$ \int_2^5 \left ( x^3 - 2x^2 - 7x - 6 \right )\sin 5x \; dx $$

That code produces the following output

How can I add additional definitions to the preamble of LaTeX cells?

Run a cell with %latex.add_to_preamble in the first line. It adds the given block of \LaTeX{} to the preamble. After that, it can be used in other cells.

Use %auto as a convenience to automatically run this cells each time the session starts. Also, if your definitions are faulty, you have to restart the worksheet to get rid of the already defined definitions!

Example:

%auto
%latex.add_to_preamble
\usepackage[parfill]{parskip}
\DeclareMathOperator{\Ext}{Ext}
\newcommand{\truth}[2]{if \texttt{#1} is true $\rightarrow$ \texttt{#2} is also true.}

Question: In the standard Sage notebook there is a checkbox to switch on the typesetting of math. How do I turn on typesetting of math output in CoCalc?

Turn it on with

typeset_mode(True)

and off with

typeset_mode(False)

Alternatively, you can add %typeset_mode True to the top of your cell, or %typeset_mode False as needed.

Note, that this works across multiple cells, so keep that in mind.

This means that if you execute your cells out of order, you might get different results each time. To avoid confusion, it is useful to make sure that one of these commands (setting typeset either to true or to false) appears at the top of each cell, if you intend to execute your cells out of order.

Question: How do I put the entire worksheet into "typeset" mode?

The previous question dealt with putting individual cells into "typeset" mode. To put all the cells into "typeset" mode, simply put

%auto
typeset_mode(True)

at the top of a worksheet. This will make typseting automatic.

Question: I would like nice typeset output from FriCAS mode in my Sage Worksheet. How do I do that?

A mode xxx specified by %xxx in the first line of a cell in CoCalc is just a Python function xxx that takes the cell input as a string and does something visible with it. We've written an entire FAQ page about this capability to make your own modes. You can find a very functional implementation for FriCAS mode as Example 7 of that FAQ page.

Note: The current version of Sage (6.6 and earlier) requires a patch to correct a bug in the fricas/axiom interface.

Question: I would like nice typeset output from non-Sage modes (other than FriCAS) in my Sage Worksheet. How do I do that?

A mode "xxx" specified by %xxx in the first line of a cell in CoCalc is just a Python function xxx that takes the cell input as a string and does something visible with it.

Therefore, you have to use the commands of "xxx" to do what you want, just like any other time you are using language "xxx."

We've written an entire FAQ page about this capability to make your own modes, with seven detailed examples.

Question: Is there a list of all currently supported % modes in CoCalc?

There are many built-in modes (e.g. Cython, GAP, Pari, R, Python, Markdown, HTML, etc...)

You can view available built-in modes by selecting Help > Mode commands in the Sage toolbar while cursor is in a sage cell. That will insert the line print('\n'.join(modes())) into the current cell.

Question: How do I create my own modes in a Sage worksheet, and what are they good for?

See Sage Custom Modes for an explanation, and seven detailed examples.

Question: How do I hide a cell's input?

There are three ways to do this.

  1. Click the triangle to the left of the input line to toggle display of the input

  2. You can type control+, both on a mac and on non-macs.

  3. Click the "In" toggle button at the top of screen with the cel selected.

Question: How do I keep HTML or markdown code blocks from being hidden?

For HTML Cells: Instead of using %html as the first line of the cell, simply use %html(hide=False) instead.

For markdown Cells: Instead of using %md as the first line of the cell, simply use %md(hide=False) instead.

Question: How do I delete/hide all output in a worksheet?

Delete: Press control+A (or command+A on a mac), then click the little circular x in the bar at the top.

Hide: Press control+A (or command+A on a mac), then click "out" to toggle the displaying of output. (Likewise you can click "in" to toggle the displaying of input).

Question: How do I delete/hide the output of a selected range of cells?

Delete: Highlight those cells with the mouse, then click the little circular x in the bar at the top.

Hide: Highlight those cells with the mouse, then click "out" to toggle the displaying of output. (Likewise you can click "in" to toggle the displaying of input).

Question: How do I hide the toolbar?

Under account settings, uncheck "Extra button bar."

Question: How do I hide the menu bar?

Click the full-screen toggle arrows in the far upper-right corner. The icon looks like two small diagonal arrows, pointing head to head.

Question: When outputting from a Sage Worksheet using show( ), print, and plot( ), the outputs are coming out of order; how do I fix this?!

Sometimes, if you have a mix of sources for output, e.g. the show() command, the print command, and the plot() command, the outputs can come out of order. This has to do with something called "flushing the output buffer."

Before giving the remedy, here is some sample code the illustrates the problem.

print ("Create a graph")
G = Graph(sparse=True)
G.allow_multiple_edges(True)
G.add_edge(1,2,"blue")
G.add_edge(2,3,"green")
G.add_edge(3,1,"red")
G.add_edge(1,4,"green")
G.add_edge(2,4,"red")
G.add_edge(3,4,"blue")

for i in range(5):
    print ("BEFORE SHOW ", i)
    show(G)
    print ("AFTER SHOW ", i)

    print ("BEFORE PLOT ", i)
    G.plot()
    print ("AFTER PLOT ", i)

Whenever you wish to output something, it goes into an output buffer. That buffer is periodically "flushed." By flushing, we mean that the information in the output buffer is actually outputted, and then removed from the buffer.

This is normal in many programming languages.

The issue is that the show command always immediately flushes the output buffer. So in the above example, the "Before Show" and the "After Show" print outputs might be sitting in the buffer for a while, whereas the show output essentially jumps the queue and gets displayed immediately. Therefore, the outputs appear out of order.

The fix to this complex problem is remarkably easy. Just put sys.stdout.flush() after each print statement to ensure that the output buffer is flushed to the output stream immediately, so you can see it at that instant.

Our previous example can be repaired as follows:

print ("Create a graph")
sys.stdout.flush()

G = Graph(sparse=True)
G.allow_multiple_edges(True)
G.add_edge(1,2,"blue")
G.add_edge(2,3,"green")
G.add_edge(3,1,"red")
G.add_edge(1,4,"green")
G.add_edge(2,4,"red")
G.add_edge(3,4,"blue")

for i in range(5):
    print ("BEFORE SHOW ", i)
    sys.stdout.flush()
    
    show(G)
    
    print ("AFTER SHOW ", i)
    sys.stdout.flush()

    print ("BEFORE PLOT ", i)
    sys.stdout.flush()
    
    G.plot()
    
    print ("AFTER PLOT ", i)
    sys.stdout.flush()

Question: Can I split the editor into two? So that I can look at one region while working on another region?

Sure, just press control+I (or command+I on a Mac).

If you do that, you'll get two editors, one above the editor.

Press that keyboard shortcut again, and you'll get two editors that are side by side.

Press that keyboard shortcut a third time, and you'll return to the normal situation of having one editor for the entire window.

Question: How do I use a Jupyter kernel from a Sage worksheet?

See Sage Jupyter

Question: What if my question isn't answered above?

Email help@sagemath.com in case of problems. Do not hesitate to email us at any time. We want to know if anything is broken! Please include a link (the address in your browser) to any relevant project or document.

Analytics

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.