Interact Functions in the Notebook¶
This module implements an interact()
function decorator for the Sage
notebook.
AUTHORS:
- William Stein (2008-03-02): version 1.0 at Sage/Enthought Days 8 in Texas
- Jason Grout (2008-03): discussion and first few prototypes
- Jason Grout (2008-05):
input_grid
control
-
class
sagenb.notebook.interact.
ColorInput
(var, default_value, label=None, type=None, width=80, height=1, **kwargs)¶ Bases:
sagenb.notebook.interact.InputBox
An input box
interact()
control.INPUT:
var
- a string; name of variable that this control interactsdefault_value
- the default value of the variable corresponding to this controllabel
- a string (default: None); label for this controltype
- a type (default: None); the type of this control, e.g., the type ‘bool’height
- an integer (default: 1); the number of rows. If greater than 1 a value won’t be returned until something outside the textarea is clicked.width
- an integer (default: 80); the character width of this controlkwargs
- a dictionary; additional keyword options
EXAMPLES:
sage: sagenb.notebook.interact.InputBox('theta', 1, 'theta') An InputBox interactive control with theta=1 and label 'theta' sage: sagenb.notebook.interact.InputBox('theta', 1, 'theta', int) An InputBox interactive control with theta=1 and label 'theta'
-
render
()¶ Render this color input box to HTML.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.ColorInput('c', Color('red')).render() '...table...color...'
-
value_js
(n)¶ Return JavaScript that evaluates to value of this control. If
n
is 0, return code for evaluation by the actual color control. Ifn
is 1, return code for the text area that displays the current color.INPUT:
n
- integer, either 0 or 1.
OUTPUT:
- a string
EXAMPLES:
sage: C = sagenb.notebook.interact.ColorInput('c', Color('red')) sage: C.value_js(0) 'color' sage: C.value_js(1) 'this.value'
-
class
sagenb.notebook.interact.
InputBox
(var, default_value, label=None, type=None, width=80, height=1, **kwargs)¶ Bases:
sagenb.notebook.interact.InteractControl
An input box
interact()
control.INPUT:
var
- a string; name of variable that this control interactsdefault_value
- the default value of the variable corresponding to this controllabel
- a string (default: None); label for this controltype
- a type (default: None); the type of this control, e.g., the type ‘bool’height
- an integer (default: 1); the number of rows. If greater than 1 a value won’t be returned until something outside the textarea is clicked.width
- an integer (default: 80); the character width of this controlkwargs
- a dictionary; additional keyword options
EXAMPLES:
sage: sagenb.notebook.interact.InputBox('theta', 1, 'theta') An InputBox interactive control with theta=1 and label 'theta' sage: sagenb.notebook.interact.InputBox('theta', 1, 'theta', int) An InputBox interactive control with theta=1 and label 'theta'
-
render
()¶ Render this control as a string.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.InputBox('theta', 1).render() '...input...value="1"...theta...'
-
value_js
()¶ Return JavaScript string that will give the value of this control element.
OUTPUT:
- a string - JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.InputBox('theta', 1).value_js() 'this.value'
-
class
sagenb.notebook.interact.
InputGrid
(var, rows, columns, default_value=None, label=None, to_value=<function <lambda>>, width=4)¶ Bases:
sagenb.notebook.interact.InteractControl
A grid interact control.
INPUT:
var
- an object; the variablerows
- an integer; the number of rowscolumns
- an integer; the number of columnsdefault_value
- an object; if this is a scalar, it is put in every cell; if it is a list, it is filled into the cells row by row; if it is a nested list, then it is filled into the cells according to the nesting structure.label
- a string; the label for the controlto_value
- a function applied to the nested list from user input when assigning the variablewidth
- an integer; the width of the input boxes
EXAMPLES:
sage: sagenb.notebook.interact.InputGrid('M', 2,2, default_value = 0, label='M') A 2 x 2 InputGrid interactive control with M=[[0, 0], [0, 0]] and label 'M' sage: sagenb.notebook.interact.InputGrid('M', 2,2, default_value = [[1,2],[3,4]], label='M') A 2 x 2 InputGrid interactive control with M=[[1, 2], [3, 4]] and label 'M' sage: sagenb.notebook.interact.InputGrid('M', 2,2, default_value = [[1,2],[3,4]], label='M', to_value=MatrixSpace(ZZ,2,2)) A 2 x 2 InputGrid interactive control with M=[1 2] [3 4] and label 'M' sage: sagenb.notebook.interact.InputGrid('M', 1, 3, default_value=[1,2,3], to_value=lambda x: vector(flatten(x))) A 1 x 3 InputGrid interactive control with M=(1, 2, 3) and label 'M'
-
render
()¶ Render this control as a string.
OUTPUT:
- string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.InputGrid('M', 1,2).render() '...table...input...M...'
-
value_js
()¶ Return JavaScript string that will give the value of this control element.
OUTPUT:
- string - JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.InputGrid('M', 2,2).value_js() "...jQuery...table...map...val...join..."
-
class
sagenb.notebook.interact.
InteractCanvas
(controls, id, layout=None, width=None, **options)¶ Bases:
object
Base class for
interact()
canvases. This is where all the controls along with the output of the interacted function are laid out and rendered.INPUT:
controls
- a list ofInteractControl
instances.id
- an integer or a string; the ID of the cell that contains this InteractCanvas.layout
- a dictionary with keys ‘top’,’bottom’,’left’,’right’ and values lists of rows of control variable names. If a dictionary is not passed in, then the value of layout is set to the ‘top’ value. IfNone
, then all control names are put on separate rows in the ‘top’ value.width
- the width of the interact controloptions
- any additional keyword arguments (for example, auto_update=False)
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3) Interactive canvas in cell 3 with 1 controls
-
cell_id
()¶ Return the ID of the cell that contains this
interact()
control.OUTPUT:
- an integer or a string
EXAMPLES:
The output below should equal the ID of the current cell:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: C = sagenb.notebook.interact.InteractCanvas([B], 3); C Interactive canvas in cell 3 with 1 controls sage: C.cell_id() 3
-
controls
()¶ Return a list of controls in this canvas.
OUTPUT:
- list of controls
Note
Returns a reference to a mutable list.
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3).controls() [An InputBox interactive control with x=2 and label 'x']
-
is_auto_update
()¶ Returns True if any change of the values for the controls on this canvas should cause an update. If
auto_update=False
was not specified in the constructor for this canvas, then this will default to True.OUTPUT:
- a bool
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: canvas = sagenb.notebook.interact.InteractCanvas([B], 3) sage: canvas.is_auto_update() True sage: canvas = sagenb.notebook.interact.InteractCanvas([B], 3, auto_update=False) sage: canvas.is_auto_update() False
-
render
()¶ Render in text (HTML) the entire
interact()
canvas.OUTPUT:
- string - HTML format
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3).render() '...notruncate...div...interact...table...x...'
-
render_controls
(side='top')¶ Render in text (HTML) form all the input controls.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3).render_controls() '...table...x...input...2...'
-
render_output
()¶ Render in text (HTML) form the output portion of the
interact()
canvas.The output contains two special tags, <?TEXT> and <?HTML>, which get replaced at runtime by the text and HTML parts of the output of running the function.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3).render_output() '...div...interact...3...'
-
wrap_in_outside_frame
(inside)¶ Return the entire HTML for the interactive canvas, obtained by wrapping all the inside HTML of the canvas in a div and a table.
INPUT:
inside
- a string; HTML
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: B = sagenb.notebook.interact.InputBox('x',2) sage: sagenb.notebook.interact.InteractCanvas([B], 3).wrap_in_outside_frame('<!--inside-->') '...notruncate...div...interact...table...inside...'
-
class
sagenb.notebook.interact.
InteractControl
(var, default_value, label=None)¶ Bases:
sagenb.notebook.interact.InteractElement
Abstract base class for
interact()
controls. These are controls that are used in a specificinteract()
. They have internal state information about the specific function being interacted, etc.INPUT:
var
- a string; name of variable that this control interactsdefault_value
- the default value of the variable corresponding to this control.label
- a string (default: None); label for this control; if None then defaults tovar
.
EXAMPLES:
sage: from sagenb.notebook.interact import InteractControl sage: InteractControl('x', default_value=5) A InteractControl (abstract base class)
-
adapt_number
()¶ Return integer index into adapt dictionary of function that is called to adapt the values of this control to Python.
OUTPUT:
- an integer
EXAMPLES:
sage: from sagenb.notebook.interact import InteractControl sage: InteractControl('x', 19/3).adapt_number() # random -- depends on call order 2
-
cell_id
()¶ Return the ID of the cell that contains this
interact()
control.OUTPUT:
- an integer or a string
EXAMPLES:
The output below should equal the ID of the current cell:
sage: sagenb.notebook.interact.InteractControl('theta', 1).cell_id() 0
-
default_value
()¶ Return the default value of the variable corresponding to this
interact()
control.OUTPUT:
- an object
EXAMPLES:
sage: from sagenb.notebook.interact import InteractControl sage: InteractControl('x', 19/3).default_value() 19/3
-
html_escaped_default_value
()¶ Returns the HTML escaped default value of the variable corresponding to this
interact()
control. Note that any HTML that uses quotes around this should use double quotes and not single quotes.OUTPUT:
- a string
EXAMPLES:
sage: from sagenb.notebook.interact import InteractControl sage: InteractControl('x', '"cool"').html_escaped_default_value() '"cool"' sage: InteractControl('x',"'cool'").html_escaped_default_value() "'cool'" sage: x = var('x') sage: InteractControl('x', x^2).html_escaped_default_value() 'x^2'
-
interact
(*args)¶ Return a string that when evaluated in JavaScript calls the JavaScript
interact()
function with appropriate inputs for this control.This method will check to see if there is a canvas attached to this control and whether or not controls should automatically update the output when their values change. If no canvas is associated with this control, then the control will automatically update.
OUTPUT:
- a string - that is meant to be evaluated in JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.InteractControl('x', 1).interact() "...interact...x...1..."
-
label
()¶ Return the text label of this
interact()
control.OUTPUT:
- a string
EXAMPLES:
sage: from sagenb.notebook.interact import InteractControl sage: InteractControl('x', default_value=5, label='the x value').label() 'the x value'
-
value_js
()¶ JavaScript that when evaluated gives the current value of this control. This should be redefined in a derived class.
OUTPUT:
- a string - defaults to ‘NULL’ - this should be redefined.
EXAMPLES:
sage: sagenb.notebook.interact.InteractControl('x', default_value=5).value_js() 'NULL'
-
var
()¶ Return the name of the variable that this control interacts.
OUTPUT:
- a string - name of a variable as a string.
EXAMPLES:
sage: sagenb.notebook.interact.InteractControl('theta', 1).var() 'theta'
-
class
sagenb.notebook.interact.
InteractElement
¶ Bases:
object
-
canvas
()¶ Returns the
InteractCanvas
associated to this element. If no canvas has been set (via theset_canvas()
method), then raise a ValueError.EXAMPLES:
sage: from sagenb.notebook.interact import InputBox, InteractCanvas sage: B = InputBox('x',2) sage: canvas1 = InteractCanvas([B], 3) sage: canvas2 = InteractCanvas([B], 3) sage: B.canvas() is canvas2 True
-
label
()¶ Returns an empty label for this element. This should be overridden for subclasses that need a label.
OUTPUT:
- a string
EXAMPLES:
sage: from sagenb.notebook.interact import UpdateButton, InteractElement sage: b = UpdateButton(1, 'autoupdate') sage: isinstance(b, InteractElement) True sage: b.label() ''
-
set_canvas
(canvas)¶ Sets the
InteractCanvas
on which this element appears. This method is primarily called in the constructor forInteractCanvas
.EXAMPLES:
sage: from sagenb.notebook.interact import InputBox, InteractCanvas sage: B = InputBox('x',2) sage: canvas1 = InteractCanvas([B], 3) sage: canvas2 = InteractCanvas([B], 3) sage: B.canvas() is canvas2 True sage: B.set_canvas(canvas1) sage: B.canvas() is canvas1 True
-
-
class
sagenb.notebook.interact.
JavascriptCodeButton
(label, code)¶ Bases:
sagenb.notebook.interact.InteractElement
This
interact()
element displays a button which when clicked executes JavaScript code in the notebook.EXAMPLES:
sage: b = sagenb.notebook.interact.JavascriptCodeButton('Push me', 'alert("2")')
-
render
()¶ Returns the HTML to display this button.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: b = sagenb.notebook.interact.JavascriptCodeButton('Push me', 'alert("2")') sage: b.render() '...input...button...Push me...alert("2")...'
-
-
class
sagenb.notebook.interact.
RangeSlider
(var, values, default_position, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.SliderGeneric
A range slider
interact()
control that takes on the given list of values.INPUT:
var
- a string; name of variable being interactedvalues
- a list; a list of the values that the slider will take ondefault_position
- an integer 2-tuple; default location that the slider is set to.label
- a string; alternative label to the left of the slider, instead of the variable.display_value
- a bool, whether to display the current value below the slider
EXAMPLES:
sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha') Range Slider Interact Control: alpha [1--|3==4|---5]
-
default_position
()¶ Return the default position (as an integer) of the slider.
OUTPUT:
- an integer 2-tuple
EXAMPLES:
sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha').default_position() (2, 3)
-
render
()¶ Render this control as an HTML string.
OUTPUT:
- string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha').render() '...table...slider...["1","2","3","4","5"]...range...' sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha', display_value=False).render() '...table...slider...null...range...
-
value_js
()¶ Return JavaScript string that will give the value of this control element.
OUTPUT:
- a string - JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha').value_js() "pos[0]+' '+pos[1]"
-
class
sagenb.notebook.interact.
Selector
(var, values, label=None, default=0, nrows=None, ncols=None, width=None, buttons=False)¶ Bases:
sagenb.notebook.interact.InteractControl
A drop down menu or a button bar that when pressed sets a variable to a given value.
INPUT:
var
- a string; variable namevalues
- a list; button valueslabel
- a string (default: None); label off to the left for this button groupdefault
- an integer (default: 0); position of default value in values list.nrows
- an integer (default: None); number of rowsncols
- an integer (default: None); number of columnswidth
- an integer (default: None); width of all the buttonsbuttons
- a bool (default: False); if True use buttons- instead of dropdown
EXAMPLES:
sage: sagenb.notebook.interact.Selector('x', [1..5], 'alpha', default=2) Selector with 5 options for variable 'x' sage: sagenb.notebook.interact.Selector('x', [1..4], 'alpha', default=2, nrows=2, ncols=2, width=10, buttons=True) Selector with 4 options for variable 'x'
-
render
()¶ Render this control as a string.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.Selector('x', [1..5]).render() '...select...x...' sage: sagenb.notebook.interact.Selector('x', [1..5], buttons=True).render() '...table...button...x...'
Whether or not to use buttons instead of a drop down menu for this select list.
OUTPUT:
- a bool
EXAMPLES:
sage: sagenb.notebook.interact.Selector('x', [1..5]).use_buttons() False sage: sagenb.notebook.interact.Selector('x', [1..5], buttons=True).use_buttons() True
-
value_js
()¶ Return JavaScript string that will give the value of this control element.
OUTPUT:
- a string - JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.Selector('x', [1..5]).value_js() 'this.options[this.selectedIndex].value' sage: sagenb.notebook.interact.Selector('x', [1..5], buttons=True).value_js() 'this.value'
-
class
sagenb.notebook.interact.
Slider
(var, values, default_position, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.SliderGeneric
A slider
interact()
control that takes on the given list of values.INPUT:
var
- a string; name of variable being interactedvalues
- a list; a list of the values that the slider will take ondefault_position
- an integer; default location that the slider is set to.label
- a string; alternative label to the left of the slider, instead of the variable.display_value
- a bool, whether to display the current value right of the slider
EXAMPLES:
sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha') Slider Interact Control: alpha [1--|3|---5]
-
default_position
()¶ Return the default position (as an integer) of the slider.
OUTPUT:
- an integer
EXAMPLES:
sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').default_position() 2
-
render
()¶ Render this control as an HTML string.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').render() '...table...slider...["1","2","3","4","5"]...' sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha', display_value=False).render() '...table...slider...null...'
-
value_js
()¶ Return JavaScript string that will give the value of this control element.
OUTPUT:
- a string - JavaScript
EXAMPLES:
sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').value_js() 'position'
-
class
sagenb.notebook.interact.
SliderGeneric
(var, values, default_value, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.InteractControl
An abstract slider
interact()
control that takes on the given list of values.INPUT:
var
- a string; name of variable being interactedvalues
- a list; a list of the values that the slider- will take on
default_value
- an object; default value of the slider.label
- a string; alternative label to the left of the slider, instead of the variable.display_value
- a bool; whether to display the current value on the slider
EXAMPLES:
sage: sagenb.notebook.interact.SliderGeneric('x', [1..5], 2, 'alpha') Abstract Slider Interact Control: alpha [1--|2|---5]
-
display_value
()¶ Returns whether to display the value on the slider.
OUTPUT:
- a bool
EXAMPLES:
sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').display_value() True
-
values
()¶ Return list of values the slider acts on.
OUTPUT:
- a list
EXAMPLES:
sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').values() [1, 2, 3, 4, 5]
-
values_js
()¶ Returns JavaScript array representation of values or ‘null’ if display_value=False
OUTPUT:
- a string
EXAMPLES:
sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha').values_js() '["1","2","3","4","5"]' sage: sagenb.notebook.interact.Slider('x', [1..5], 2, 'alpha', False).values_js() 'null' sage: sagenb.notebook.interact.Slider('x', [pi..2*pi], 2, 'alpha').values_js() '["pi","pi + 1","pi + 2","pi + 3"]'
-
class
sagenb.notebook.interact.
TextControl
(var, data)¶ Bases:
sagenb.notebook.interact.InteractControl
A text field
interact()
controlINPUT:
data
- a string; the HTML value of the text field
EXAMPLES:
sage: sagenb.notebook.interact.TextControl('x', 'something') Text Interact Control: something
-
render
()¶ Render this control as an HTML string.
OUTPUT:
- a string - HTML format
EXAMPLES:
sage: sagenb.notebook.interact.TextControl('x', 'something').render() '...div...something...'
-
class
sagenb.notebook.interact.
UpdateButton
(cell_id, var)¶ Bases:
sagenb.notebook.interact.JavascriptCodeButton
Creates an
interact()
button element. A click on the button triggers recomputation of the cell with the current values of the variables.INPUT:
cell_id
- an integer or string; the ambient cell’s IDvar`
- a variable which is used in the layout
EXAMPLES:
sage: b = sagenb.notebook.interact.UpdateButton(0, 'auto_update') sage: b.render() '...input...button...Update...0...'
-
var
()¶ Return the name of the variable that this control interacts.
OUTPUT:
- a string - name of a variable as a string.
EXAMPLES:
sage: sagenb.notebook.interact.UpdateButton(1, 'auto_update').var() 'auto_update'
-
sagenb.notebook.interact.
automatic_control
(default)¶ Automagically determine the type of control from the default value of the variable.
INPUT:
default
- the default value forv
given by the function; see the documentation tointeract()
for details.
OUTPUT:
- an
interact()
control
EXAMPLES:
sage: sagenb.notebook.interact.automatic_control('') Interact input box labeled None with default value '' sage: sagenb.notebook.interact.automatic_control(15) Interact input box labeled None with default value 15 sage: sagenb.notebook.interact.automatic_control(('start', 15)) Interact input box labeled 'start' with default value 15 sage: sagenb.notebook.interact.automatic_control((1,250)) Slider: None [1.0--|1.0|---250.0] sage: sagenb.notebook.interact.automatic_control(('alpha', (1,250))) Slider: alpha [1.0--|1.0|---250.0] sage: sagenb.notebook.interact.automatic_control((2,(0,250))) Slider: None [0.0--|2.00400801603|---250.0] sage: sagenb.notebook.interact.automatic_control(('alpha label', (2,(0,250)))) Slider: alpha label [0.0--|2.00400801603|---250.0] sage: sagenb.notebook.interact.automatic_control((2, ('alpha label',(0,250)))) Slider: alpha label [0.0--|2.00400801603|---250.0] sage: C = sagenb.notebook.interact.automatic_control((1,52, 5)); C Slider: None [1--|1|---52] sage: C.values() [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 52] sage: sagenb.notebook.interact.automatic_control((17, (1,100,5))) Slider: None [1--|16|---100] sage: sagenb.notebook.interact.automatic_control([1..4]) Button bar with 4 buttons sage: sagenb.notebook.interact.automatic_control([1..100]) Drop down menu with 100 options sage: sagenb.notebook.interact.automatic_control((1..100)) Slider: None [1--|1|---100] sage: sagenb.notebook.interact.automatic_control((5, (1..100))) Slider: None [1--|5|---100] sage: sagenb.notebook.interact.automatic_control(matrix(2,2)) Interact 2 x 2 input grid control labeled None with default value [0, 0, 0, 0]
-
class
sagenb.notebook.interact.
checkbox
(default=True, label=None)¶ Bases:
sagenb.notebook.interact.input_box
A checkbox interactive control. Use this in conjunction with the
interact()
command.INPUT:
default
- a bool (default: True); whether box should be checked or notlabel
- a string (default: None) text label rendered to the left of the box
EXAMPLES:
sage: checkbox(False, "Points") Interact checkbox labeled 'Points' with default value False sage: checkbox(True, "Points") Interact checkbox labeled 'Points' with default value True sage: checkbox(True) Interact checkbox labeled None with default value True sage: checkbox() Interact checkbox labeled None with default value True
-
class
sagenb.notebook.interact.
color_selector
(default=(0, 0, 1), label=None, widget='colorpicker', hide_box=False)¶ Bases:
sagenb.notebook.interact.input_box
A color selector (also called a color chooser, picker, or tool) interactive control. Use this with the
interact()
command.INPUT:
default
- an instance of or valid constructor argument toColor
(default: (0,0,1)); the selector’s default color; a string argument must be a valid color name (e.g., ‘red’) or HTML hex color (e.g., ‘#abcdef’)label
- a string (default: None); the label rendered to the left of the selector.widget
- a string (default: ‘colorpicker’); the color selector widget to use; choices are ‘colorpicker’; in Debian other values are not supported.hide_box
- a boolean (default: False); whether to hide the input box associated with the color selector widget
EXAMPLES:
sage: color_selector() Interact color selector labeled None, with default RGB color (0.0, 0.0, 1.0), widget 'colorpicker', and visible input box sage: color_selector(default = Color(0, 0.5, 0.25)) Interact color selector labeled None, with default RGB color (0.0, 0.5, 0.25), widget 'colorpicker', and visible input box sage: color_selector('purple', widget = 'colorpicker') Interact color selector labeled None, with default RGB color (0.50..., 0.0, 0.50...), widget 'colorpicker', and visible input box sage: color_selector('crayon', widget = 'colorpicker') Traceback (most recent call last): ... ValueError: unknown color 'crayon'
-
hide_box
()¶ Return whether to hide the input box associated with this color selector.
OUTPUT:
- a boolean
EXAMPLES:
sage: color_selector().hide_box() False sage: color_selector((0.75,0.5,0.25)).hide_box() False
-
widget
()¶ Return the name of the HTML widget for this color selector.
OUTPUT:
- a string; the widget’s name
EXAMPLES:
sage: color_selector().widget() 'colorpicker' sage: color_selector(default=Color(0,0.5,0.25)).widget() 'colorpicker'
-
class
sagenb.notebook.interact.
control
(label=None)¶ An interactive control object used with the
interact()
command. This is the abstract base class.INPUTS:
label
- a string
EXAMPLES:
sage: sagenb.notebook.interact.control('a control') Interative control 'a control' (abstract base class)
-
label
()¶ Return the label of this control.
OUTPUT:
- a string
EXAMPLES:
sage: sagenb.notebook.interact.control('a control').label() 'a control' sage: selector([1,2,7], 'alpha').label() 'alpha'
-
set_label
(label)¶ Set the label of this control.
INPUT:
label
- a string
EXAMPLES:
sage: C = sagenb.notebook.interact.control('a control') sage: C.set_label('sage'); C Interative control 'sage' (abstract base class)
-
sagenb.notebook.interact.
html
(s)¶ Print the input string
s
in a form that tells the notebook to display it in the HTML portion of the output. This function has no return value.INPUT:
s
- a string
EXAMPLES:
sage: sagenb.notebook.interact.html('hello') <html>hello</html>
-
sagenb.notebook.interact.
html_color_selector
(id, change, input_change, default='000000', widget='colorpicker', hide_box=False)¶ Return HTML representation of a jQuery color selector.
INPUT:
id
- an integer or string; an identifier (e.g., cell ID) for this selectorchange
- a string; JavaScript code to execute when the color selector changes.default
- a string (default:'000000'
); default color as a 6-character HTML hexadecimal string.widget
- a string (default: ‘colorpicker’); the color selector widget to use; choices are ‘colorpicker’; in Debian other values are not supported.hide_box
- a boolean (default: False); whether to hide the input box associated with the color selector widget
OUTPUT:
- a string - HTML that creates the slider.
EXAMPLES:
sage: sagenb.notebook.interact.html_color_selector(0, 'alert("changed")', '', default='0afcac') '...<table>...colorpicker...'
-
sagenb.notebook.interact.
html_rangeslider
(id, values, callback, steps, default_l=0, default_r=1, margin=0)¶ Return the HTML representation of a jQuery range slider.
INPUT:
id
- a string; the DOM ID of the slider (better be unique)values
- a string; ‘null’ or JavaScript string containing array of values on slidercallback
- a string; JavaScript that is executed whenever the slider is done movingsteps
- an integer; number of steps from minimum to maximum valuedefault_l
- an integer (default: 0); the default position of the left edge of the sliderdefault_r
- an integer (default: 1); the default position of the right edge of the slidermargin
- an integer (default: 0); size of margin to insert around the slider
OUTPUT:
- a string - HTML format
EXAMPLES:
We create a jQuery range slider. If you do the following in the notebook you should obtain a slider that when moved pops up a window showing its current position:
sage: from sagenb.notebook.interact import html_rangeslider, html sage: html(html_rangeslider('slider-007', 'null', 'alert(pos[0]+", "+pos[1])', steps=5, default_l=2, default_r=3, margin=5)) <html>...slider...range...</html>
-
sagenb.notebook.interact.
html_slider
(id, values, callback, steps, default=0, margin=0)¶ Return the HTML representation of a jQuery slider.
INPUT:
id
- a string; the DOM ID of the slider (better be unique)values
- a string; ‘null’ or JavaScript string containing array of values on slidercallback
- a string; JavaScript that is executed whenever the slider is done movingsteps
- an integer; number of steps from minimum to maximum valuedefault
- an integer (default: 0); the default position of the slidermargin
- an integer (default: 0); size of margin to insert around the slider
OUTPUT:
- a string - HTML format
EXAMPLES:
We create a jQuery HTML slider. If you do the following in the notebook you should obtain a slider that when moved pops up a window showing its current position:
sage: from sagenb.notebook.interact import html_slider, html sage: html(html_slider('slider-007', 'null', 'alert(position)', steps=5, default=2, margin=5)) <html>...slider...</html>
-
class
sagenb.notebook.interact.
input_box
(default=None, label=None, type=None, width=80, height=1, **kwargs)¶ Bases:
sagenb.notebook.interact.control
An input box interactive control. Use this in conjunction with the
interact()
command.INPUT:
default
- an object; the default put in this input boxlabel
- a string; the label rendered to the left of the box.type
- a type; coerce inputs to this; this doesn’t have to be an actual type, since anything callable will do.height
- an integer (default: 1); the number of rows. If greater than 1 a value won’t be returned until something outside the textarea is clicked.width
- an integer; width of text box in characterskwargs
- a dictionary; additional keyword options
EXAMPLES:
sage: input_box("2+2", 'expression') Interact input box labeled 'expression' with default value '2+2' sage: input_box('sage', label="Enter your name", type=str) Interact input box labeled 'Enter your name' with default value 'sage' sage: input_box('Multiline\nInput',label='Click to change value',type=str,height=5) Interact input box labeled 'Click to change value' with default value 'Multiline\nInput'
-
default
()¶ Return the default value of this input box.
OUTPUT:
- an object
EXAMPLES:
sage: input_box('2+2', 'Expression').default() '2+2' sage: input_box(x^2 + 1, 'Expression').default() x^2 + 1 sage: checkbox(True, "Points").default() True
-
render
(var)¶ Return rendering of this input box as an
InputBox
to be used for aninteract()
canvas. Basically this specializes this input to be used for a specific function and variable.INPUT:
var
- a string (variable; one of the variable names input tof
)
OUTPUT:
- an
InputBox
instance
EXAMPLES:
sage: input_box("2+2", 'Exp').render('x') An InputBox interactive control with x='2+2' and label 'Exp'
-
type
()¶ Return the type that elements of this input box are coerced to or None if they are not coerced (they have whatever type they evaluate to).
OUTPUT:
- a type
EXAMPLES:
sage: input_box("2+2", 'expression', type=int).type() <type 'int'> sage: input_box("2+2", 'expression').type() is None True
-
class
sagenb.notebook.interact.
input_grid
(nrows, ncols, default=None, label=None, to_value=<function <lambda>>, width=4)¶ Bases:
sagenb.notebook.interact.control
An input grid interactive control. Use this in conjunction with the
interact()
command.INPUT:
nrows
- an integerncols
- an integerdefault
- an object; the default put in this input boxlabel
- a string; the label rendered to the left of the box.to_value
- a list; the grid output (list of rows) is sent through this function. This may reformat the data or coerce the type.width
- an integer; size of each input box in characters
NOTEBOOK EXAMPLE:
@interact def _(m = input_grid(2,2, default = [[1,7],[3,4]], label='M=', to_value=matrix), v = input_grid(2,1, default=[1,2], label='v=', to_value=matrix)): try: x = m\v html('$$%s %s = %s$$'%(latex(m), latex(x), latex(v))) except: html('There is no solution to $$%s x=%s$$'%(latex(m), latex(v)))
EXAMPLES:
sage: input_grid(2,2, default = 0, label='M') Interact 2 x 2 input grid control labeled M with default value 0 sage: input_grid(2,2, default = [[1,2],[3,4]], label='M') Interact 2 x 2 input grid control labeled M with default value [[1, 2], [3, 4]] sage: input_grid(2,2, default = [[1,2],[3,4]], label='M', to_value=MatrixSpace(ZZ,2,2)) Interact 2 x 2 input grid control labeled M with default value [[1, 2], [3, 4]] sage: input_grid(1, 3, default=[[1,2,3]], to_value=lambda x: vector(flatten(x))) Interact 1 x 3 input grid control labeled None with default value [[1, 2, 3]]
-
default
()¶ Return the default value of this input grid.
OUTPUT:
- an object
EXAMPLES:
sage: input_grid(2,2, default=1).default() 1
-
render
(var)¶ Return rendering of this input grid as an
InputGrid
to be used for aninteract()
canvas. Basically this specializes this input to be used for a specific function and variable.INPUT:
var
- a string (variable; one of the variable names input tof
)
OUTPUT:
- an
InputGrid
instance.
EXAMPLES:
sage: input_grid(2,2).render('x') A 2 x 2 InputGrid interactive control with x=[[None, None], [None, None]] and label 'x'
-
sagenb.notebook.interact.
interact
(f, layout=None, width='800px')¶ Use interact as a decorator to create interactive Sage notebook cells with sliders, text boxes, radio buttons, check boxes, and color selectors. Simply put
@interact
on the line before a function definition in a cell by itself, and choose appropriate defaults for the variable names to determine the types of controls (see tables below).INPUT:
f
- a Python functionlayout
(optional) - a dictionary with keys ‘top’, ‘bottom’, ‘left’, ‘right’ and values lists of rows of control variable names. Controls are laid out according to this pattern. Iflayout
is not a dictionary, it is assumed to be the ‘top’ value. Iflayout
is None, then all controls are assigned separate rows in thetop
value.
EXAMPLES:
In each example below we use a single underscore for the function name. You can use any name you want; it does not have to be an underscore.
We create an interact control with two inputs, a text input for the variable
a
and ay
slider that runs through the range of integers from \(0\) to \(19\).sage: @interact ....: def _(a=5, y=(0..20)): print(a + y) ....: <html>...
sage: @interact(layout=[['a','b'],['d']]) ....: def _(a=x^2, b=(0..20), c=100, d=x+1): print(a+b+c+d) ....: <html>...
sage: @interact(layout={'top': [['a', 'b']], 'left': [['c']], 'bottom': [['d']]}) ....: def _(a=x^2, b=(0..20), c=100, d=x+1): print(a+b+c+d) ....: <html>...
Draw a plot interacting with the “continuous” variable
a
. By default continuous variables have exactly 50 possibilities.sage: @interact ... def _(a=(0,2)): ... show(plot(sin(x*(1+a*x)), (x,0,6)), figsize=4) <html>...
Interact a variable in steps of 1 (we also use an unnamed function):
sage: @interact ... def _(n=(10,100,1)): ... show(factor(x^n - 1)) <html>...
Interact two variables:
sage: @interact ... def _(a=(1,4), b=(0,10)): ... show(plot(sin(a*x+b), (x,0,6)), figsize=3) <html>...
Place a block of text among the controls:
sage: @interact ....: def _(t1=text_control("Factors an integer."), n="1"): ....: print(factor(Integer(n))) <html>...
If your the time to evaluate your function takes awhile, you may not want to have it reevaluated every time the inputs change. In order to prevent this, you can add a keyword
auto_update=False
to your function to prevent it from updating whenever the values are changed. This will cause a button labeled ‘Update’ to appear which you can click on to re-evaluate your function.sage: @interact ... def _(n=(10,100,1), auto_update=False): ... show(factor(x^n - 1)) <html>...
DEFAULTS:
Defaults for the variables of the input function determine interactive controls. The standard controls are
input_box
,slider
,range_slider
,checkbox
,selector
,input_grid
, andcolor_selector
. There is also a text control (see the defaults below).u = input_box(default=None, label=None, type=None)
- input box with givendefault
; usetype=str
to get input as an arbitrary stringu = slider(vmin, vmax=None, step_size=1, default=None, label=None)
- slider with given list of possible values;vmin
can be a listu = range_slider(vmin, vmax=None, step_size=1, default=None, label=None)
- range slider with given list of possible values;vmin
can be a listu = checkbox(default=True, label=None)
- a checkboxu = selector(values, label=None, nrows=None, ncols=None, buttons=False)
- a dropdown menu or buttons (get buttons ifnrows
,ncols
, orbuttons
is set, otherwise a dropdown menu)u = input_grid(nrows, ncols, default=None, label=None, to_value=lambda x:x, width=4)
- an editable grid of objects (a matrix or array)u = color_selector(default=(0,0,1), label=None, widget='colorpicker', hide_box=False)
- a color selector with a possibly hidden input box; in Debian other values forwidget
are not supported.u = text_control(value='')
- a block of text
You can also create a color selector by setting the default value for an
input_box
toColor(...)
.There are also some convenient defaults that allow you to make controls automatically without having to explicitly specify them. E.g., you can make
x
a continuous slider of values betweenu
andv
by just writingx=(u,v)
in the argument list of your function. These are all just convenient shortcuts for creating the controls listed above.u
- blank input_box fieldu = element
- input_box withdefault=element
, if element not below.u = (umin,umax)
- continuous slider (really \(100\) steps)u = (umin,umax,du)
- slider with step sizedu
u = list
- buttons iflen(list)
at most \(5\); otherwise, drop downu = iterator
(e.g. a generator) - a slider (up to \(10000\) steps)u = bool
- a checkboxu = Color('blue')
- a color selector; returnsColor
objectu = (default, v)
-v
as above, with givendefault
valueu = (label, v)
-v
as above, with givenlabel
(a string)u = matrix
- aninput_grid
withto_value
set tomatrix.parent()
and default values given by the matrix
Note
Suppose you would like to make an interactive with a default RGB color of
(1,0,0)
, so the function would have signaturef(color=(1,0,0))
. Unfortunately, the above shortcuts reinterpret the(1,0,0)
as a discrete slider with step size 0 between 1 and 0. Instead you should do the following:sage: @interact ... def _(v = input_box((1,0,0))): ... show(plot(sin,color=v)) <html>...
An alternative:
sage: @interact ... def _(c = color_selector((1, 0, 0))): ... show(plot(sin, color = c)) <html>...
MORE EXAMPLES:
We give an input box that allows one to enter completely arbitrary strings:
sage: @interact ....: def _(a=input_box('sage', label="Enter your name", type=str)): ....: print("Hello there %s"%a.capitalize()) <html>...
The scope of variables that you control via
interact()
are local to the scope of the function being interacted with. However, by using theglobal
Python keyword, you can still modify global variables as follows:sage: xyz = 10 sage: @interact ... def _(a=('xyz',5)): ... global xyz ... xyz = a <html>...
If you enter the above you obtain an
interact()
canvas. Entering values in the box changes the global variablexyz
. Here’s a example with several controls:sage: @interact ....: def _(title=["A Plot Demo", "Something silly", "something tricky"], a=input_box(sin(x*sin(x*sin(x))), 'function'), ....: clr = Color('red'), thickness=[1..30], zoom=(1,0.95,..,0.1), plot_points=(200..2000)): ....: html('<h1 align=center>%s</h1>'%title) ....: print(plot_points) ....: show(plot(a, -zoom*pi,zoom*pi, color=clr, thickness=thickness, plot_points=plot_points)) <html>...
For a more compact color control, use an empty label and hide the input box:
sage: @interact ... def _(color=color_selector((1,0,1), label='', hide_box=True)): ... show(plot(x/(8/7+sin(x)), (x,-50,50), fill=True, fillcolor=color)) <html>...
We give defaults and name the variables:
sage: @interact ... def _(a=('first', (1,4)), b=(0,10)): ... show(plot(sin(a*x+sin(b*x)), (x,0,6)), figsize=3) <html>...
Another example involving labels, defaults, and the slider command:
sage: @interact ... def _(a = slider(1, 4, default=2, label='Multiplier'), ... b = slider(0, 10, default=0, label='Phase Variable')): ... show(plot(sin(a*x+b), (x,0,6)), figsize=4) <html>...
An example where the range slider control is useful:
sage: @interact ... def _(b = range_slider(-20, 20, 1, default=(-19,3), label='Range')): ... plot(sin(x)/x, b[0], b[1]).show(xmin=b[0],xmax=b[1]) <html>...
An example using checkboxes, obtained by making the default values bools:
sage: @interact ... def _(axes=('Show axes', True), square=False): ... show(plot(sin, -5,5), axes=axes, aspect_ratio = (1 if square else None)) <html>...
An example generating a random walk that uses a checkbox control to determine whether points are placed at each step:
sage: @interact ... def foo(pts = checkbox(True, "points"), n = (50,(10..100))): ... s = 0; v = [(0,0)] ... for i in range(n): ... s += random() - 0.5 ... v.append((i, s)) ... L = line(v, rgbcolor='#4a8de2') ... if pts: L += points(v, pointsize=20, rgbcolor='black') ... show(L) <html>...
You can rotate and zoom into 3-D graphics while interacting with a variable:
sage: @interact ... def _(a=(0,1)): ... x,y = var('x,y') ... show(plot3d(sin(x*cos(y*a)), (x,0,5), (y,0,5)), figsize=4) <html>...
A random polygon:
sage: pts = [(random(), random()) for _ in xrange(20)] sage: @interact ... def _(n = (4..len(pts)), c=Color('purple') ): ... G = points(pts[:n],pointsize=60) + polygon(pts[:n], rgbcolor=c) ... show(G, figsize=5, xmin=0, ymin=0) <html>...
Two “sinks” displayed simultaneously via a contour plot and a 3-D interactive plot:
sage: @interact ... def _(q1=(-1,(-3,3)), q2=(-2,(-3,3))): ... x,y = var('x,y') ... f = q1/sqrt((x+1)^2 + y^2) + q2/sqrt((x-1)^2+(y+0.5)^2) ... C = contour_plot(f, (-2,2), (-2,2), plot_points=30, contours=15, cmap='cool') ... show(C, figsize=3, aspect_ratio=1) ... show(plot3d(f, (x,-2,2), (y,-2,2)), figsize=4) <html>...
This is similar to above, but you can select the color map from a dropdown menu:
sage: @interact ... def _(q1=(-1,(-3,3)), q2=(-2,(-3,3)), ... cmap=['autumn', 'bone', 'cool', 'copper', 'gray', 'hot', 'hsv', ... 'jet', 'pink', 'prism', 'spring', 'summer', 'winter']): ... x,y = var('x,y') ... f = q1/sqrt((x+1)^2 + y^2) + q2/sqrt((x-1)^2+(y+0.5)^2) ... C = contour_plot(f, (x,-2,2), (y,-2,2), plot_points=30, contours=15, cmap=cmap) ... show(C, figsize=3, aspect_ratio=1) <html>...
A quadratic roots etch-a-sketch:
sage: v = [] sage: html('<h2>Quadratic Root Etch-a-sketch</h2>') <html>...<h2>Quadratic Root Etch-a-sketch</h2>...</html> sage: @interact ... def _(a=[-10..10], b=[-10..10], c=[-10..10]): ... f = a*x^2 + b*x + c == 0; show(f) ... soln = solve(a*x^2 + b*x + c == 0, x)[0].rhs() ... show(soln) ... P = tuple(CDF(soln)) ... v.append(P) ... show(line(v, rgbcolor='purple') + point(P, pointsize=200)) <html>...
In the following example, we only generate data for a given
n
once, so that as one variesp
the data does not randomly change. We do this by simply caching the results for eachn
in a dictionary.:sage: data = {} sage: @interact ... def _(n=(500,(100,5000,1)), p=(1,(0.1,10))): ... n = int(n) ... if not data.has_key(n): ... data[n] = [(random(), random()) for _ in xrange(n)] ... show(points([(x^p,y^p) for x,y in data[n]], rgbcolor='black'), xmin=0, ymin=0, axes=False) <html>...
A conchoid:
sage: @interact ... def _(k=(1.2,(1.1,2)), k_2=(1.2,(1.1,2)), a=(1.5,(1.1,2))): ... u, v = var('u,v') ... f = (k^u*(1+cos(v))*cos(u), k^u*(1+cos(v))*sin(u), k^u*sin(v)-a*k_2^u) ... show(parametric_plot3d(f, (u,0,6*pi), (v,0,2*pi), plot_points=[40,40], texture=(0,0.5,0))) <html>...
An input grid:
sage: @interact ... def _(A=matrix(QQ,3,3,range(9)), v=matrix(QQ,3,1,range(3))): ... try: ... x = A\v ... html('$$%s %s = %s$$'%(latex(A), latex(x), latex(v))) ... except: ... html('There is no solution to $$%s x=%s$$'%(latex(A), latex(v))) <html>...
-
sagenb.notebook.interact.
list_of_first_n
(v, n)¶ Given an iterator v, return first n elements it produces as a list.
INPUT:
v
- an iteratorn
- an integer
OUTPUT:
- a list
EXAMPLES:
sage: from itertools import takewhile sage: p100 = takewhile(lambda x: x < 100, Primes()) sage: sagenb.notebook.interact.list_of_first_n(p100, 10) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] sage: sagenb.notebook.interact.list_of_first_n((1..5), 10) [1, 2, 3, 4, 5] sage: sagenb.notebook.interact.list_of_first_n(QQ, 10) [0, 1, -1, 1/2, -1/2, 2, -2, 1/3, -1/3, 3]
-
sagenb.notebook.interact.
new_adapt_number
()¶ Return an integer, always counting up, and starting with 0. This is used for saving the adapt methods for controls. An adapt method is just a function that coerces data into some object, e.g., makes sure the control always produces int’s.
OUTPUT:
- an integer
EXAMPLES:
sage: sagenb.notebook.interact.new_adapt_number() # random output -- depends on when called 1
-
class
sagenb.notebook.interact.
range_slider
(vmin, vmax=None, step_size=None, default=None, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.slider_generic
An interactive range slider control, which can be used in conjunction with the
interact()
command.INPUT:
vmin
- an objectvmax
- object or None; if None thenvmin
must be a list, and the slider then varies over elements of the list.step_size
- integer (default: 1)default
- a 2-tuple of objects (default: None); default range is “closest” invmin
or range to this default.label
- a stringdisplay_value
- a bool, whether to display the current value below the slider
EXAMPLES:
We specify both
vmin
andvmax
. We make the default \((3,4)\) but since neither is one of \(3/17\)-th spaced values between \(2\) and \(5\), the closest values: \(52/17\) and \(67/17\), are instead chosen as the default:sage: range_slider(2, 5, 3/17, (3,4), 'alpha') Range Slider: alpha [2--|52/17==67/17|---5]
Here we give a list:
sage: range_slider([1..10], None, None, (3,7), 'alpha') Range Slider: alpha [1--|3==7|---10]
-
default_index
()¶ Return default index into the list of values.
OUTPUT:
- an integer 2-tuple
EXAMPLES:
sage: range_slider(2, 5, 1/2, (3,4), 'alpha').default_index() (2, 4)
-
render
(var)¶ Render the
interact()
control for the given function and variable.INPUT:
var
- string; variable name
OUTPUT:
- a
RangeSlider
instance
EXAMPLES:
sage: S = range_slider(0, 10, 1, default=(3,7), label='theta'); S Range Slider: theta [0--|3==7|---10] sage: S.render('x') Range Slider Interact Control: theta [0--|3==7|---10] sage: range_slider(2, 5, 2/7, (3,4), 'alpha').render('x') Range Slider Interact Control: alpha [2--|20/7==4|---5]
-
sagenb.notebook.interact.
recompute
(cell_id)¶ Evaluates the
interact()
function associated to the cellcell_id
. This typically gets called after a call toupdate()
.INPUT:
cell_id
- a string or an integer; the ID of aninteract()
cell
EXAMPLES:
The following outputs __SAGE_INTERACT_RESTART__ to indicate that not all the state of the
interact()
canvas has been set up yet (this setup happens when JavaScript calls certain functions):sage: sagenb.notebook.interact.recompute(10) __SAGE_INTERACT_RESTART__
-
sagenb.notebook.interact.
reset_state
()¶ Reset the
interact()
state of this sage process.EXAMPLES:
sage: sagenb.notebook.interact.state # random output {1: {'function': <function g at 0x72aaab0>, 'variables': {'m': 3, 'n': 5}, 'adapt': {1: <bound method Slider._adaptor of Slider Interact Control: n [1--|1|---10].>, 2: <bound method Slider._adaptor of Slider Interact Control: m [1--|1|---10].>}}} sage: from sagenb.notebook.interact import reset_state sage: reset_state() sage: sagenb.notebook.interact.state {}
-
class
sagenb.notebook.interact.
selector
(values, label=None, default=None, nrows=None, ncols=None, width=None, buttons=False)¶ Bases:
sagenb.notebook.interact.control
A drop down menu or a button bar that when pressed sets a variable to a given value. Use this in conjunction with the
interact()
command.We use the same command to create either a drop down menu or selector bar of buttons, since conceptually the two controls do exactly the same thing - they only look different. If either
nrows
orncols
is given, then you get a buttons instead of a drop down menu.INPUT:
values
- [val0, val1, val2, ...] or [(val0, lbl0), (val1,lbl1), ...] where all labels must be given or given as None.label
- a string (default: None); if given, this label is placed to the left of the entire button groupdefault
- an object (default: 0); default value in values listnrows
- an integer (default: None); if given determines the number of rows of buttons; if given buttons option below is set to Truencols
- an integer (default: None); if given determines the number of columns of buttons; if given buttons option below is set to Truewidth
- an integer (default: None); if given, all buttons are the same width, equal to this in HTML ex units’s.buttons
- a bool (default: False); if True, use buttons
EXAMPLES:
sage: selector([1..5]) Drop down menu with 5 options sage: selector([1,2,7], default=2) Drop down menu with 3 options sage: selector([1,2,7], nrows=2) Button bar with 3 buttons sage: selector([1,2,7], ncols=2) Button bar with 3 buttons sage: selector([1,2,7], width=10) Drop down menu with 3 options sage: selector([1,2,7], buttons=True) Button bar with 3 buttons
We create an
interact()
that involves computing charpolys of matrices over various rings:sage: @interact ....: def _(R=selector([ZZ,QQ,GF(17),RDF,RR]), n=(1..10)): ....: M = random_matrix(R, n) ....: show(M) ....: show(matrix_plot(M,cmap='Oranges')) ....: f = M.charpoly() ....: print(f) <html>...
Here we create a drop-down:
sage: @interact ....: def _(a=selector([(2,'second'), (3,'third')])): ....: print(a) <html>...
-
default
()¶ Return the default choice for this control.
OUTPUT:
- an integer, with 0 corresponding to the first choice.
EXAMPLES:
sage: selector([1,2,7], default=2).default() 1
-
render
(var)¶ Return rendering of this button as a
Selector
instance to be used for aninteract()
canvas.INPUT:
var
- a string (variable; one of the variable names input tof
)
OUTPUT:
- a
Selector
instance
EXAMPLES:
sage: selector([1..5]).render('alpha') Selector with 5 options for variable 'alpha'
-
values
()¶ Return the list of values or (val, lbl) pairs that this selector can take on.
OUTPUT:
- a list
EXAMPLES:
sage: selector([1..5]).values() [1, 2, 3, 4, 5] sage: selector([(5,'fifth'), (8,'eight')]).values() [(5, 'fifth'), (8, 'eight')]
-
class
sagenb.notebook.interact.
slider
(vmin, vmax=None, step_size=None, default=None, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.slider_generic
An interactive slider control, which can be used in conjunction with the
interact()
command.INPUT:
vmin
- an objectvmax
- an object (default: None); if None thenvmin
must be a list, and the slider then varies over elements of the list.step_size
- an integer (default: 1)default
- an object (default: None); default value is “closest” invmin
or range to this default.label
- a stringdisplay_value
- a bool, whether to display the current value to the right of the slider
EXAMPLES:
We specify both
vmin
andvmax
. We make the default \(3\), but since \(3\) isn’t one of \(3/17\)-th spaced values between \(2\) and \(5\), \(52/17\) is instead chosen as the default (it is closest):sage: slider(2, 5, 3/17, 3, 'alpha') Slider: alpha [2--|52/17|---5]
Here we give a list:
sage: slider([1..10], None, None, 3, 'alpha') Slider: alpha [1--|3|---10]
The elements of the list can be anything:
sage: slider([1, 'x', 'abc', 2/3], None, None, 'x', 'alpha') Slider: alpha [1--|x|---2/3]
-
default_index
()¶ Return default index into the list of values.
OUTPUT:
- an integer
EXAMPLES:
sage: slider(2, 5, 1/2, 3, 'alpha').default_index() 2
-
render
(var)¶ Render the
interact()
control for the given function and variable.INPUT:
var
- a string; variable name
OUTPUT:
- a
Slider
instance
EXAMPLES:
sage: S = slider(0, 10, 1, default=3, label='theta'); S Slider: theta [0--|3|---10] sage: S.render('x') Slider Interact Control: theta [0--|3|---10] sage: slider(2, 5, 2/7, 3, 'alpha').render('x') Slider Interact Control: alpha [2--|20/7|---5]
-
class
sagenb.notebook.interact.
slider_generic
(vmin, vmax=None, step_size=None, label=None, display_value=True)¶ Bases:
sagenb.notebook.interact.control
-
display_value
()¶ Returns whether to display the value on the slider.
OUTPUT:
- a bool
EXAMPLES:
sagenb.notebook.interact.slider_generic(1,10,1/2).display_value() True
-
values
()¶ Returns list of values that this slider takes on, in order.
OUTPUT:
- a list
Note
This is a reference to a mutable list.
EXAMPLES:
sage: sagenb.notebook.interact.slider(1,10,1/2).values() [1, 3/2, 2, 5/2, 3, 7/2, 4, 9/2, 5, 11/2, 6, 13/2, 7, 15/2, 8, 17/2, 9, 19/2, 10]
-
-
class
sagenb.notebook.interact.
text_control
(value='')¶ Bases:
sagenb.notebook.interact.control
Text that can be inserted among other
interact()
controls.INPUT:
value
- HTML for the control
EXAMPLES:
sage: text_control('something') Text field: something
-
render
(var)¶ Return rendering of the text field
INPUT:
var
- a string (variable; one of the variable names input tof
)
OUTPUT:
- a
TextControl
instance
-
sagenb.notebook.interact.
update
(cell_id, var, adapt, value, globs)¶ Called when updating the positions of an interactive control. Note that this just causes the values of the variables to be updated; it does not reevaluate the function with the new values.
INPUT:
cell_id
- an integer or string; the ID of aninteract()
cellvar
- an object; a variable associated to that celladapt
- in integer; the number of the adapt functionvalue
- an object; new value of the controlglobs
- global variables.
EXAMPLES:
The following outputs __SAGE_INTERACT_RESTART__ to indicate that not all the state of the
interact()
canvas has been set up yet (this setup happens when JavaScript calls certain functions):sage: sagenb.notebook.interact.update(0, 'a', 0, '5', globals()) __SAGE_INTERACT_RESTART__