All published worksheets from http://sagenb.org
Image: ubuntu2004
Sage Interact Quickstart
This Sage worksheet was developed for the MAA PREP Workshop "Sage: Using Open-Source Mathematics Software with Undergraduates" (funding provided by NSF DUE 0817071).
Invaluable resources are the Sage wiki http://wiki.sagemath.org/interact (type "sage interact" into Google) and the interact documentation.
Start by getting the commands for what you want the output to look like. Here we just want a simple plot.
Then abstract out the parts you want to change. We'll be letting the user change the function, so let's make that a variable .
Now make this a "def" function. The "show" or "print" is needed since the output is not automatically printed from within a function. Note also that we give the variable a default value of x^2. This is what is if the user does not specify a value for .
Let's test the def function myplot by just calling it.
If we call it with a different value for f, we should get a different plot.
Now to make a control to enter the function, we just preface the function with @interact.
Tech tip: Technically what the @interact does is wrap the function, so the above is equivalent to:
def myplot(..): ...
myplot=interact(myplot)
Note that we can still call our function, even when we've used @interact. This is often useful in debugging it.
We can go ahead and replace other parts of the expression with variables. Note the "_" is the function name now. That is a convention for throw-away names that we don't care about.
If we pass ('label', default_value) in for a control, then the control gets the label when printed.
We can specify the type of control explicitly, along with options.
Here's another type of control: a color picker.
Here are a bunch of options. Notice the new controls:
- range slider, which passes in two values, zoom[0] and zoom[1]
- True/False get converted to checkboxes
That was a bit ugly because all of the controls were stacked on top of each other. We can layout the controls in a grid in the top, bottom, left, or right using the 'layout' parameter.
Control Types
Sage has:
- boxes
- sliders
- range sliders
- checkboxes
- selectors (dropdown lists or buttons)
- grid of boxes
- color selectors
- plain text
We illustrate some of these.
By default, ranges are sliders that divide the range into 500 steps (I think that's the right number...)
You can set the step size to get, for example, just integer values.
Or you can explicitly specify the slider values.
And the slider values don't even have to be numbers!
Matrices are automatically converted to a grid of input boxes.
Here's how to get vectors from a grid of boxes.
Sometimes we don't want any updates until we specifically say so. We can use the auto_update=False option for that.