# Sage Essentials

Sage Colors

At times you'll find it's useful to refer to colors by name. The list of colors that can be referred to by name can be found here.

Specifying the height of 2D plots

A 2d looks something like this: plot(f,(x,-10,20)) where $latex -10\leq x\leq20$ and Sage figures out the range of y-values in the plot. In some cases, such as a function like tangent, you may find the need to adjust the range of y-values yourself. You can do that by defining a graphics object, say G, as G=plot(f,(x,-10,20)) and then show(G,ymin=-5,ymax=5) sets the range of y-values.

Formatting numbers

Chances are you'll find Sage gives you a number in a format that doesn't look very nice. You can change the formatting by converting the number to a string and then using the formatting options for string to clean up the representation. Run the following code:

print("The square root of 2: "+str(sqrt(2)))#Print sqrt(2) symbolically
a=float(sqrt(2))#force sqrt(2) to a floating point number
print("The square root of 2 is "+str(a)+"but now you might not like the format of the number.")#Print the number
print("To control the format of the number, try: The square root of 2 is {0:.3f}".format(a))#print 3 digits after decimal
b=float(sqrt(3))
c=float(a+b)
print("Multiple arguments can also be handled: the sqrt(2)+sqrt(3) is just {0:.5f} + {1:.5f} = {2:.5f}".format(a,b,c))

and you'll get this output:

$latex \sqrt{2}$ is represented symbolically as sqrt(2) until it is converted to a floating a point number with:

a=float(sqrt(2))#force sqrt(2) to a floating point number

at which point now you have Sage deciding for you how the decimal is represented. You can tell Sage how you want your numbers displayed using the format method of Python as explained in detail here. The key line in our code above is

print("Multiple arguments can also be handled: the sqrt(2)+sqrt(3) is just {0:.5f} + {1:.5f} = {2:.5f}".format(a,b,c))print("Multiple arguments can also be handled: the sqrt(2)+sqrt(3) is just {0:.5f} + {1:.5f} = {2:.5f}".format(a,b,c))

There are 3 numbers used in the print statement, referred to as 0, 1, and 2. When it's time to print a number we give instruction as to how the number should be formatted. The argument {0:.5f} instructs that the 0th number should show 5 digits after the decimal. After instructing what the format will be for each number you finish it off with the format(a,b,c) to define a as the 0th number, b as the first number, and c as the 2nd number. As the Python documentation tells us, decimals can be represented as fixed point (f), exponential (e), general format (g), n as number and % as percents.

Older methods of string format still work but are being deprecated so use the format method.

Text fields

If you want other people to look at your Sage notebooks then there'll be times when you want to put in some instructions/explanations so others can understand what you're doing. Sage gives you 2 ways to include text. The first option is to use a Sage cell (field), type %latex on the first line and then include the rest of your text. The second option is to create a text field and put your text in there.

Now I love  $latex \LaTeX$, but there are plenty of times when you'll find that creating a text field helps your notebook look even better. To create a text cell, move your mouse above a Sage cell until a purple line appears--like the one shown below:

While you've got that purple line, press Shift and (while holding it down) left click your mouse. That will create a text field like the one immediately above it. (Note: you can click on the image above to get a larger view). The text field gives you a lot of options: changing the font, highlighting, inserting images, inserting hyperlinks, and so on. When you finish typing in your text, click the "Save Changes" button.

Compare that with the Sage cell above that: you'll see I started the line with %latex, typed in some text, and then got $latex \LaTeX$ output. Here's a better picture:

The $latex \LaTeX$ output is followed by the text field output. You can see the text field gives you more choices in working with text. Being able to insert images and clickable hyperlinks (in purple) is convenient.

One final point worth mentioning: there's a drawback to using $latex \LaTeX$ in Sage that isn't so apparent. If you print your notebook as a PDF, the $latex \LaTeX$ output is likely to get cut off unless you keep it really short. Here's the PDF output from the notebook: TextFields. See that annoying scrollbar? Although the notebook looked fine, the PDF output doesn't. Text fields don't have these problems.

Text fields are a convenient way to annotate your Sage notebooks and make them look presentable. As much as I love $latex \LaTeX$, you're better off using text fields in a Sage notebook. I've posted the PDF output from TextFields on the Python/Sage page as well, so it can always be found easily.

Formatting program output

The Sage notebook lets you format the output from your programs in multiple ways depending on how much time and effort you want to spend on making it look nice.

• The print statement is the simplest it gives you basic output but equations aren't so easy on the eyes. At times the background of a print statement will look gray.
• A plain html statement won't result in a gray background and it has the same simplistic representation for math output.
• html statements can be adjusted to give $latex \LaTeX$ output for numbers by enclosing the numerical output it $signs (thereby entering math mode). The fonts become a little nicer and exponentiation is easier on the eyes. • html statements can be adjusted to give$latex \LaTeX$fonts for text and math by putting the output string into math mode and then using the \mbox command to get into text mode. I've cleaned up the math output a little more using \\frac{%s}{%s}$<p>'% (v.numerator(), v.denominator())) to create a ratio with 2 lines. However, the multiplication symbol gets printed out which doesn't look the way it should.
• To get around the problem of the * sign showing up, use the latex() command to convert the statement to latex code. This strips out the * sign. Converting that to a string via str(latex(v)) finally gives the cleanest output of all.
• Another way of getting $latex \LaTeX$ uses the view() command. In some ways, it's simpler but I've had problems with it when you combine text and math into a view command: in the second cell below, view(p+q+r+s) causes problems.

Here's a comparison of the approaches:

The code for each cell is here: SageFormat1 (.txt) and SageFormat2 (.txt)

Plotting graphs with asymptotes

Graphs with asymptotes are plotted as if they were one connected graph.

To plot tangent accurately we need to turn on an option to detect_poles. So, for example,  plot(f,(x,-10,20),detect_poles=True,color='green') will give us the desired plot.

Saving Pictures as Anaglyphs

Although creating anaglyphs in Sage is easy, saving the output is not as straightforward as you'd expect. Type G = dodecahedron(color='darkseagreen',opacity=0.2)
G.show() into a Sage.

Press "Enter" to get

Right-click on the image to Style -> Stereographic -> Red + Cyan glasses

which will give you an anaglyph.

Saving the anaglyph output is not as straightforward as it should be. Adding code like G.show(stereo='redcyan')and other similar attempts won't result in the image being an anaglyph. If, however, you're using a Sage Notebook (and not a Sage Cell Server) then there will be an option "Get Image" at the bottom (See the picture below). Note this is missing from the Sage Cell Server picture above. Left click on "Get Image" and another picture pops up. Right click on that picture, choose "Save Image As..." and select where you want the picture to be saved. Notice that

If you've got Sage installed on your computer you can use it to process files that you have. There's a good example at AskSage which we can modify to something a little more useful. Start with a simple file: SageFile (.csv) which has this student data.

Name,Test 1,Test 2
Art,64,88
Betty,45,99
Corey,87,67
Darnell,79,84

Save SageFile.csv in some folder on your computer; suppose the path is:     /home/SageFile.csv

Now paste the following code into a Sage Cell SageProcessFile (.txt) and press evaluate. The output is shown below. The code prints the average score for each student and then gets the average of all those scores.

Writing to a file

If you've got Sage installed on your computer you can save output to a file. First you'll need to write a line like:

f = open(r"/home/<rest of path>/MyFile.tex",'w')

where you fill in the path appropriate for your computer. If the file MyFile.tex doesn't exist then it will be created. After that you generate the text you want in the .tex file:

f.write(r"\documentclass[11pt]{article}")
f.write("\n")
f.write(r"\begin{document}")
f.write("\n")
f.write(r"The first sentence.")
f.write("\n")
f.write(r"$\int_0^1 e^x dx$")
f.write("\n")
f.write(r"\end{document}")
f.close()

My output resulted in what appears to be an error; but there was no problem with the output. It was compiled by LaTeX without any problems.

Turning off warnings

If you use Sage for graphing you've almost certainly encountered some not so welcome warnings when you plot:

Notice also that Sage didn't plot from -1 to 4 like you asked. To turn of the warnings, you can use the set_verbose command. To fix the values of x that it is plotted over, store the plot in a variable and specify the xmin and xmax with show. Here's the code:

set_verbose(-1)
p=plot(sqrt(x),(x,-1,4))
p.show(xmin=-1)

Which results in this output:

The warnings are off and the plotting parameters are as you specified. You can turn the warnings back on with set_verbose(0).

Plotting the Floor function: exclude, closed circle, open circle

If you try and plot the floor function in Sage, you'll get unwanted output. Here's the result of plot(floor(x), (x, -2.5, 2.5), color='red', thickness=2). Note there are no warnings.

There's no asymptote here but the problem of the connecting one point to the next for a discontinuous graph results in a plot which is no longer a function. To get rid of this there is a plot option called exclude. Since we know the problem points are the integers between -2.5 to 2.5 we make sure that Sage knows there is a gap there.

plot(floor(x), (x, -2.5, 2.5), exclude = [-2..2],color='red', thickness=2)

In this case Sage throws out -2, -1, 0, 1, 2 and the graph is more like we'd expect.

The documentation on exclude can be found on this page of the Sagemath site. Now we're missing the detail as to what happens on the ends of each piece.

P=plot(floor(x), (x, -2.5, 2.5), exclude = [-2..2],color='red', thickness=2)
H = point([(t, t) for t in range(-2, 3)], color='red',size=20)
P += H
P.show()

To get the open circles at the end we need the circles command.

P=plot(floor(x), (x, -2.5, 2.5), exclude = [-2..2],color='red', thickness=2)
H = point([(t, t) for t in range(-2, 3)], color='red',size=20)
P += H
disk((1,0), .2, (0,2*pi), color='red', fill=False, thickness=2)
for i in range(-2,3):
P+=circle((i,i-1),.02,facecolor='white',edgecolor='red',thickness=1,fill=True)
P.show()

Plotting cube roots and other rational functions

Plotting a simple function like $latex f(x)=x^{1/3}$ is annoyingly convoluted

Sage is complaining about raising a negative number to a rational power.  So how do we get the entire graph? Take a look at the code for the animated GIF:

c = var('c')
p1 = plot(sign(x)*abs(x)^(1/3),-2,2)
a = animate([p1+point((0,0),rgbcolor='black',size=20)+ point((c,c^(1/3)),rgbcolor='black',size=20)+plot(c^(-2/3)*x,(x,-2,2),rgbcolor=(1,1/4,1/2)) for c in srange(1,0,-.05)],xmin=-2, xmax=2, ymin=-2,ymax=2)
a.show(delay=100)

The plot of $latex f(x)=x^{1/3}$ is created by: sign(x)*abs(x)^(1/3) and you've got an  example why Sage is a tool for the teacher but not appropriate for the student. First, to get around x being negative (and then raised to rational power) we take the absolute value of it--but now that the answer is positive. The sign(x) is 1 if x is positive, 0 if x is 0, and -1 if x is negative.

Getting Sage's points used in implicit plotting

If you like to combine Sage with LaTeX you'll find the need to get the points that were created by implicit plotting for something, like $latex f(x,y)= x^3-x-y^2$ which is not a function. Sage creates a grid of points, think of discrete pixels on a screen, and turns on (colors) the points where $latex f(x,y)=0$. The code

f(x,y)= x^3-x-y^2
P1=implicit_plot(f,(x,-2,1.5),(y,-1,1),plot_points=250)
C1 = P1._objects[0]

sets up the grid of (250)X(250) points. Most will not make the equation $latex f(x,y)=0$ true. But we're dealing with computers, so the equation is "true" when the $latex f(x,y) \approx 0$. Through testing I've found .02 does a decent job. In code a statement like

if abs(C1.xy_data_array[i][j])<.02:

will be used to determine the points in the grid which are close to 0. These points can then be stored and plotted. See the Plotting with Sagetex page.