Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/dynamic.py
447 views
1
# Modified from sage_salvus.py in the sagemath/cloud github project
2
# Original version licensed GPLv2+ by William Stein
3
4
#TODO: Need some way of having controls without output and without
5
#having a 'dirty' indicator. Just javascript controls. This should
6
#be an argument to interact, like @interact(output=False) or something
7
8
# also, need an easy way to make controls read-only (especially if
9
# they are just displaying a value)
10
11
import sys
12
from interact_sagecell import interact
13
def _dynamic(var, control=None):
14
if control is None:
15
control = sys._sage_.namespace.get(var,'')
16
17
# Workaround for not having the nonlocal statement in python 2.x
18
old_value = [sys._sage_.namespace.get(var,None)]
19
20
@interact(layout=[[(var,12)]], output=False)
21
def f(self, x=(var,control)):
22
if x is not old_value[0]:
23
# avoid infinite recursion: if control is already set,
24
# leave it alone
25
sys._sage_.namespace[var]=x
26
old_value[0] = x
27
28
def g(var,y):
29
f.x = y
30
sys._sage_.namespace.on(var,'change', g)
31
32
if var in sys._sage_.namespace:
33
g(var, sys._sage_.namespace[var])
34
35
def dynamic(*args, **kwds):
36
"""
37
Make variables in the global namespace dynamically linked to a control from the
38
interact label (see the documentation for interact).
39
40
EXAMPLES:
41
42
Make a control linked to a variable that doesn't yet exist::
43
44
dynamic('newname')
45
46
Make a slider and a selector, linked to t and x::
47
48
dynamic(t=(1..10), x=[1,2,3,4])
49
t = 5 # this changes the control
50
"""
51
for var in args:
52
if not isinstance(var, str):
53
i = id(var)
54
for k,v in sys._sage_.namespace.items():
55
if id(v) == i:
56
_dynamic(k)
57
return
58
else:
59
_dynamic(var)
60
61
for var, control in kwds.items():
62
_dynamic(var, control)
63
64
65
def dynamic_expression(v, vars):
66
"""
67
sage: t=5
68
sage: dynamic(t)
69
sage: dynamic_expression('2*t','t')
70
"""
71
# control
72
@interact(output=False, readonly=True)
73
def f(t=(0,2)):
74
pass
75
76
# update function
77
def g(var,val):
78
f.t = eval(v)
79
80
for vv in vars:
81
sys._sage_.namespace.on(vv,'change',g)
82
83
imports = {"dynamic": dynamic,
84
"dynamic_expression": dynamic_expression}
85
86