forked from sagemath/cloud
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsage_salvus.py
2866 lines (2310 loc) · 96.4 KB
/
sage_salvus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################################################################################
# #
# Extra code that the Salvus server makes available in the running Sage session. #
# #
##################################################################################
#########################################################################################
# Copyright (C) 2013 William Stein <[email protected]> #
# #
# Distributed under the terms of the GNU General Public License (GPL), version 2+ #
# #
# http://www.gnu.org/licenses/ #
#########################################################################################
import copy, os, sys
salvus = None
import json
from uuid import uuid4
def uuid():
return str(uuid4())
##########################################################################
# New function interact implementation
##########################################################################
import inspect
interacts = {}
def jsonable(x):
"""
Given any object x, make a JSON-able version of x, doing as best we can.
For some objects, sage as Sage integers, this works well. For other
objects which make no sense in Javascript, we get a string.
"""
import sage.all
try:
json.dumps(x)
return x
except:
if isinstance(x, (sage.all.Integer)):
return int(x)
else:
return str(x)
class InteractCell(object):
def __init__(self, f, layout=None, width=None, style=None,
update_args=None, auto_update=True,
flicker=False, output=True):
"""
Given a function f, create an object that describes an interact
for working with f interactively.
INPUT:
- `f` -- Python function
- ``width`` -- (default: None) overall width of the interact canvas
- ``style`` -- (default: None) extra CSS style to apply to canvas
- ``update_args`` -- (default: None) only call f if one of the args in
this list of strings changes.
- ``auto_update`` -- (default: True) call f every time an input changes
(or one of the argus in update_args).
- ``flicker`` -- (default: False) if False, the output part of the cell
never shrinks; it can only grow, which aleviates flicker.
- ``output`` -- (default: True) if False, do not automatically
provide any area to display output.
"""
self._flicker = flicker
self._output = output
self._uuid = uuid()
# Prevent garbage collection until client specifically requests it,
# since we want to be able to store state.
interacts[self._uuid] = self
self._f = f
self._width = jsonable(width)
self._style = str(style)
(args, varargs, varkw, defaults) = inspect.getargspec(f)
if defaults is None:
defaults = []
n = len(args) - len(defaults)
self._controls = dict([(arg, interact_control(arg, defaults[i-n] if i >= n else None))
for i, arg in enumerate(args)])
self._last_vals = {}
for arg in args:
self._last_vals[arg] = self._controls[arg].default()
self._ordered_args = args
self._args = set(args)
if isinstance(layout, dict):
# Implement the layout = {'top':, 'bottom':, 'left':,
# 'right':} dictionary option that is in the Sage
# notebook. I personally think it is really awkward and
# unsuable, but there may be many interacts out there that
# use it.
# Example layout={'top': [['a', 'b'], ['x', 'y']], 'left': [['c']], 'bottom': [['d']]}
top = layout.get('top', [])
bottom = layout.get('bottom', [])
left = layout.get('left', [])
right = layout.get('right', [])
new_layout = []
for row in top:
new_layout.append(row)
if len(left) > 0 and len(right) > 0:
new_layout.append(left[0] + [''] + right[0])
del left[0]
del right[0]
elif len(left) > 0 and len(right) == 0:
new_layout.append(left[0] + [''])
del left[0]
elif len(left) == 0 and len(right) > 0:
new_layout.append([''] + right[0])
del right[0]
i = 0
while len(left) > 0 and len(right) > 0:
new_layout.append(left[0] + ['_salvus_'] + right[0])
del left[0]
del right[0]
while len(left) > 0:
new_layout.append(left[0])
del left[0]
while len(right) > 0:
new_layout.append(right[0])
del right[0]
for row in bottom:
new_layout.append(row)
layout = new_layout
if layout is None:
layout = [[(str(arg), 12, None)] for arg in self._ordered_args]
else:
try:
v = []
for row in layout:
new_row = []
for x in row:
if isinstance(x, str):
x = (x,)
if len(x) == 1:
new_row.append((str(x[0]), 12//len(row), None))
elif len(x) == 2:
new_row.append((str(x[0]), int(x[1]), None))
elif len(x) == 3:
new_row.append((str(x[0]), int(x[1]), str(x[2])))
v.append(new_row)
layout = v
except:
raise ValueError, "layout must be None or a list of tuples (variable_name, width, [optional label]), with width is an integer between 1 and 12, variable_name is a string, and label is a string. The widths in each row must add up to at most 12. The empty string '' denotes the output area."
# Append a row for any remaining controls:
layout_vars = set(sum([[x[0] for x in row] for row in layout],[]))
for v in args:
if v not in layout_vars:
layout.append([(v, 12, None)])
if self._output:
if '' not in layout_vars:
layout.append([('', 12, None)])
self._layout = layout
# TODO -- this is UGLY
if not auto_update:
c = button('Update')
c._opts['var'] = 'auto_update'
self._controls['auto_update'] = c
self._ordered_args.append("auto_update")
layout.append([('auto_update',2)])
update_args = ['auto_update']
self._update_args = update_args
def jsonable(self):
"""
Return a JSON-able description of this interact, which the client
can use for laying out controls.
"""
X = {'controls':[self._controls[arg].jsonable() for arg in self._ordered_args], 'id':self._uuid}
if self._width is not None:
X['width'] = self._width
if self._layout is not None:
X['layout'] = self._layout
X['style'] = self._style
X['flicker'] = self._flicker
return X
def __call__(self, vals):
"""
Call self._f with inputs specified by vals. Any input variables not
specified in vals will have the value they had last time.
"""
self.changed = [str(x) for x in vals.keys()]
for k, v in vals.iteritems():
x = self._controls[k](v)
self._last_vals[k] = x
if self._update_args is not None:
do_it = False
for v in self._update_args:
if v in self.changed:
do_it = True
if not do_it:
return
interact_exec_stack.append(self)
try:
self._f(**dict([(k,self._last_vals[k]) for k in self._args]))
finally:
interact_exec_stack.pop()
class InteractFunction(object):
def __init__(self, interact_cell):
self.__dict__['interact_cell'] = interact_cell
def __call__(self, **kwds):
salvus.clear()
for arg, value in kwds.iteritems():
self.__setattr__(arg, value)
return self.interact_cell(kwds)
def __setattr__(self, arg, value):
I = self.__dict__['interact_cell']
if arg in I._controls and not isinstance(value, control):
# setting value of existing control
v = I._controls[arg].convert_to_client(value)
desc = {'var':arg, 'default':v}
I._last_vals[arg] = value
else:
# create a new control
new_control = interact_control(arg, value)
I._controls[arg] = new_control
desc = new_control.jsonable()
# set the id of the containing interact
desc['id'] = I._uuid
salvus.javascript("worksheet.set_interact_var(obj)", obj=jsonable(desc))
def __getattr__(self, arg):
I = self.__dict__['interact_cell']
try:
return I._last_vals[arg]
except Exception, err:
print err
raise AttributeError("no interact control corresponding to input variable '%s'"%arg)
def __delattr__(self, arg):
I = self.__dict__['interact_cell']
try:
del I._controls[arg]
except KeyError:
pass
desc = {'id':I._uuid, 'name':arg}
salvus.javascript("worksheet.del_interact_var(obj)", obj=jsonable(desc))
def changed(self):
"""
Return the variables that changed since last evaluation of the interact function
body. [SALVUS only]
For example::
@interact
def f(n=True, m=False, xyz=[1,2,3]):
print n, m, xyz, interact.changed()
"""
return self.__dict__['interact_cell'].changed
class _interact_layout:
def __init__(self, *args):
self._args = args
def __call__(self, f):
return interact(f, *self._args)
class Interact(object):
"""
Use interact to create interactive worksheet cells with sliders,
text boxes, radio buttons, check boxes, color selectors, and more.
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). You
may also put ``@interact(layout=...)`` to control the layout of
controls. Within the function, you may explicitly set the value
of the control corresponding to a variable foo to bar by typing
interact.foo = bar.
Type "interact.controls.[tab]" to get access to all of the controls.
INPUT:
- ``f`` -- function
- ``width`` -- number, or string such as '80%', '300px', '20em'.
- ``style`` -- CSS style string, which allows you to change the border,
background color, etc., of the interact.
- ``update_args`` -- (default: None); list of strings, so that
only changing the corresponding controls causes the function to
be re-evaluated; changing other controls will not cause an update.
- ``auto_update`` -- (default: True); if False, a button labeled
'Update' will appear which you can click on to re-evalute.
- ``layout`` -- (default: one control per row) a list [row0,
row1, ...] of lists of tuples row0 = [(var_name, width,
label), ...], where the var_name's are strings, the widths
must add up to at most 12, and the label is optional. This
will layout all of the controls and output using Twitter
Bootstraps "Fluid layout", with spans corresponding
to the widths. Use var_name='' to specify where the output
goes, if you don't want it to last. You may specify entries for
controls that you will create later using interact.var_name = foo.
NOTES: The flicker and layout options above are only in SALVUS.
For backwards compatibility with the Sage notebook, if layout
is a dictionary (with keys 'top', 'bottom', 'left', 'right'),
then the appropriate layout will be rendered as it used to be
in the Sage notebook.
OUTPUT:
- creates an interactive control.
AUTOMATIC CONTROL RULES
-----------------------
There are also some 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 between ``u`` and
``v`` by just writing ``x=(u,v)`` in the argument list.
- ``u`` - blank input_box
- ``u=elt`` - input_box with ``default=element``, unless other rule below
- ``u=(umin,umax)`` - continuous slider (really `100` steps)
- ``u=(umin,umax,du)`` - slider with step size ``du``
- ``u=list`` - buttons if ``len(list)`` at most `5`; otherwise, drop down
- ``u=generator`` - a slider (up to `10000` steps)
- ``u=bool`` - a checkbox
- ``u=Color('blue')`` - a color selector; returns ``Color`` object
- ``u=matrix`` - an ``input_grid`` with ``to_value`` set to
``matrix.parent()`` and default values given by the matrix
- ``u=(default, v)`` - ``v`` anything as above, with given ``default`` value
- ``u=(label, v)`` - ``v`` anything as above, with given ``label`` (a string)
EXAMPLES:
The layout option::
@interact(layout={'top': [['a', 'b']], 'left': [['c']],
'bottom': [['d']], 'right':[['e']]})
def _(a=x^2, b=(0..20), c=100, d=x+1, e=sin(2)):
print a+b+c+d+e
We illustrate some features that are only in Salvus, not in the
Sage cell server or Sage notebook.
You can set the value of a control called foo to 100 using
interact.foo=100. For example::
@interact
def f(n=20, twice=None):
interact.twice = int(n)*2
In this example, we create and delete multiple controls depending
on properties of the input::
@interact
def f(n=20, **kwds):
print kwds
n = Integer(n)
if n % 2 == 1:
del interact.half
else:
interact.half = input_box(n/2, readonly=True)
if n.is_prime():
interact.is_prime = input_box('True', readonly=True)
else:
del interact.is_prime
You can access the value of a control associated to a variable foo
that you create using interact.foo, and check whether there is a
control associated to a given variable name using hasattr::
@interact
def f():
if not hasattr(interact, 'foo'):
interact.foo = 'hello'
else:
print interact.foo
An indecisive interact::
@interact
def f(n=selector(['yes', 'no'])):
for i in range(5):
interact.n = i%2
sleep(.2)
We use the style option to make a holiday interact::
@interact(width=25,
style="background-color:lightgreen; border:5px dashed red;")
def f(x=button('Merry ...',width=20)):
pass
We make a little box that can be dragged around, resized, and is
updated via a computation (in this case, counting primes)::
@interact(width=30,
style="background-color:lightorange; position:absolute; z-index:1000; box-shadow : 8px 8px 4px #888;")
def f(prime=text_control(label="Counting primes: ")):
salvus.javascript("cell.element.closest('.salvus-cell-output-interact').draggable().resizable()")
p = 2
c = 1
while True:
interact.prime = '%s, %.2f'%(p, float(c)/p)
p = next_prime(p)
c += 1
sleep(.25)
"""
def __call__(self, f=None, layout=None, width=None, style=None, update_args=None, auto_update=True, flicker=False, output=True):
if f is None:
return _interact_layout(layout, width, style, update_args, auto_update, flicker)
else:
return salvus.interact(f, layout=layout, width=width, style=style,
update_args=update_args, auto_update=auto_update, flicker=flicker, output=output)
def __setattr__(self, arg, value):
I = interact_exec_stack[-1]
if arg in I._controls and not isinstance(value, control):
# setting value of existing control
v = I._controls[arg].convert_to_client(value)
desc = {'var':arg, 'default':v}
I._last_vals[arg] = value
else:
# create a new control
new_control = interact_control(arg, value)
I._controls[arg] = new_control
desc = new_control.jsonable()
desc['id'] = I._uuid
salvus.javascript("worksheet.set_interact_var(obj)", obj=desc)
def __delattr__(self, arg):
try:
del interact_exec_stack[-1]._controls[arg]
except KeyError:
pass
desc['id'] = I._uuid
salvus.javascript("worksheet.del_interact_var(obj)", obj=jsonable(arg))
def __getattr__(self, arg):
try:
return interact_exec_stack[-1]._last_vals[arg]
except Exception, err:
raise AttributeError("no interact control corresponding to input variable '%s'"%arg)
def changed(self):
"""
Return the variables that changed since last evaluation of the interact function
body. [SALVUS only]
For example::
@interact
def f(n=True, m=False, xyz=[1,2,3]):
print n, m, xyz, interact.changed()
"""
return interact_exec_stack[-1].changed
interact = Interact()
interact_exec_stack = []
class control:
def __init__(self, control_type, opts, repr, convert_from_client=None, convert_to_client=jsonable):
# The type of the control -- a string, used for CSS selectors, switches, etc.
self._control_type = control_type
# The options that define the control -- passed to client
self._opts = dict(opts)
# Used to print the control to a string.
self._repr = repr
# Callable that the control may use in converting from JSON
self._convert_from_client = convert_from_client
self._convert_to_client = convert_to_client
self._last_value = self._opts['default']
def convert_to_client(self, value):
try:
return self._convert_to_client(value)
except Exception, err:
sys.stderr.write("%s -- %s\n"%(err, self))
sys.stderr.flush()
return jsonable(value)
def __call__(self, obj):
"""
Convert JSON-able object returned from client to describe
value of this control.
"""
if self._convert_from_client is not None:
try:
x = self._convert_from_client(obj)
except Exception, err:
sys.stderr.write("%s -- %s\n"%(err, self))
sys.stderr.flush()
x = self._last_value
else:
x = obj
self._last_value = x
return x
def __repr__(self):
return self._repr
def label(self):
"""Return the label of this control."""
return self._opts['label']
def default(self):
"""Return default value of this control."""
return self(self._opts['default'])
def type(self):
"""Return type that values of this control are coerced to."""
return self._opts['type']
def jsonable(self):
"""Return JSON-able object the client browser uses to render the control."""
X = {'control_type':self._control_type}
for k, v in self._opts.iteritems():
X[k] = jsonable(v)
return X
import types
def list_of_first_n(v, n):
"""Given an iterator v, return first n elements it produces as a list."""
if not hasattr(v, 'next'):
v = v.__iter__()
w = []
while n > 0:
try:
w.append(v.next())
except StopIteration:
return w
n -= 1
return w
def automatic_control(default):
from sage.all import Color
from sage.structure.element import is_Matrix
label = None
default_value = None
for _ in range(2):
if isinstance(default, tuple) and len(default) == 2 and isinstance(default[0], str):
label, default = default
if isinstance(default, tuple) and len(default) == 2 and isinstance(default[1], (tuple, list, types.GeneratorType)):
default_value, default = default
if isinstance(default, control):
if label:
default._opts['label'] = label
return default
elif isinstance(default, str):
return input_box(default, label=label, type=str)
elif isinstance(default, bool):
return checkbox(default, label=label)
elif isinstance(default, list):
return selector(default, default=default_value, label=label, buttons=len(default) <= 5)
elif isinstance(default, types.GeneratorType):
return slider(list_of_first_n(default, 10000), default=default_value, label=label)
elif isinstance(default, Color):
return color_selector(default=default, label=label)
elif isinstance(default, tuple):
if len(default) == 2:
return slider(default[0], default[1], default=default_value, label=label)
elif len(default) == 3:
return slider(default[0], default[1], default[2], default=default_value, label=label)
else:
return slider(list(default), default=default_value, label=label)
elif is_Matrix(default):
return input_grid(default.nrows(), default.ncols(), default=default.list(), to_value=default.parent(), label=label)
else:
return input_box(default, label=label)
def interact_control(arg, value):
if isinstance(value, control):
if value._opts['label'] is None:
value._opts['label'] = arg
c = value
else:
c = automatic_control(value)
if c._opts['label'] is None:
c._opts['label'] = arg
c._opts['var'] = arg
return c
def sage_eval(x):
x = str(x).strip()
if x.isspace():
return None
from sage.all import sage_eval
return sage_eval(x, salvus.namespace)
class ParseValue:
def __init__(self, type):
self._type = type
def _eval(self, value):
return sage_eval(value)
def __call__(self, value):
from sage.all import Color
if self._type is None:
return self._eval(value)
elif self._type is str:
return str(value)
elif self._type is Color:
try:
return Color(value)
except ValueError:
try:
return Color("#"+value)
except ValueError:
raise TypeError("invalid color '%s'"%value)
else:
return self._type(self._eval(value))
def input_box(default=None, label=None, type=None, nrows=1, width=None, readonly=False, submit_button=None):
"""
An input box interactive control for use with the :func:`interact` command.
INPUT:
- default -- default value
- label -- label test
- type -- the type that the input is coerced to (from string)
- nrows -- (default: 1) the number of rows of the box
- width -- width; how wide the box is
- readonly -- is it read-only?
- submit_button -- defaults to true if nrows > 1 and false otherwise.
"""
return control(
control_type = 'input-box',
opts = locals(),
repr = "Input box",
convert_from_client = ParseValue(type)
)
def checkbox(default=True, label=None, readonly=False):
"""
A checkbox interactive control for use with the :func:`interact` command.
"""
return control(
control_type = 'checkbox',
opts = locals(),
repr = "Checkbox"
)
def color_selector(default='blue', label=None, readonly=False, widget=None, hide_box=False):
"""
A color selector.
SALVUS only: the widget option is ignored -- SALVUS only provides
bootstrap-colorpicker.
EXAMPLES::
@interact
def f(c=color_selector()):
print c
"""
from sage.all import Color
default = Color(default).html_color()
return control(
control_type = 'color-selector',
opts = locals(),
repr = "Color selector",
convert_from_client = lambda x : Color(str(x)),
convert_to_client = lambda x : Color(x).html_color()
)
def text_control(default='', label=None, classes=None):
"""
A read-only control that displays arbitrary HTML amongst the other
interact controls. This is very powerful, since it can display
any HTML.
INPUT::
- ``default`` -- actual HTML to display
- ``label`` -- string or None
- ``classes`` -- space separated string of CSS classes
EXAMPLES::
We output the factorization of a number in a text_control::
@interact
def f(n=2013, fact=text_control("")):
interact.fact = factor(n)
We use a CSS class to make the text_control look like a button:
@interact
def f(n=text_control("foo <b>bar</b>", classes='btn')):
pass
We animate a picture into view:
@interact
def f(size=[10,15,..,30], speed=[1,2,3,4]):
for k in range(size):
interact.g = text_control("<img src='http://sagemath.org/pix/sage_logo_new.png' width=%s>"%(20*k))
sleep(speed/50.0)
"""
return control(
control_type = 'text',
opts = locals(),
repr = "Text %r"%(default)
)
def button(default=None, label=None, classes=None, width=None, icon=None):
"""
Create a button. [SALVUS only]
You can tell that pressing this button triggered the interact
evaluation because interact.changed() will include the variable
name tied to the button.
INPUT:
- ``default`` -- value variable is set to
- ``label`` -- string (default: None)
- ``classes`` -- string if None; if given, space separated
list of CSS classes. e.g., Bootstrap CSS classes such as:
btn-primary, btn-info, btn-success, btn-warning, btn-danger,
btn-link, btn-large, btn-small, btn-mini.
See http://twitter.github.com/bootstrap/base-css.html#buttons
If button_classes a single string, that class is applied to all buttons.
- ``width`` - an integer or string (default: None); if given,
all buttons are this width. If an integer, the default units
are 'ex'. A string that specifies any valid HTML units (e.g., '100px', '3em')
is also allowed [SALVUS only].
- ``icon`` -- None or string name of any icon listed at the font
awesome website (http://fortawesome.github.com/Font-Awesome/), e.g., 'fa-repeat'
EXAMPLES::
@interact
def f(hi=button('Hello', label='', classes="btn-primary btn-large"),
by=button("By")):
if 'hi' in interact.changed():
print "Hello to you, good sir."
if 'by' in interact.changed():
print "See you."
Some buttons with icons::
@interact
def f(n=button('repeat', icon='fa-repeat'),
m=button('see?', icon="fa-eye", classes="btn-large")):
print interact.changed()
"""
return control(
control_type = "button",
opts = locals(),
repr = "Button",
convert_from_client = lambda x : default,
convert_to_client = lambda x : str(x)
)
class Slider:
def __init__(self, start, stop, step_size, max_steps):
if isinstance(start, (list, tuple)):
self.vals = start
else:
if step_size is None:
if stop is None:
step_size = start/float(max_steps)
else:
step_size = (stop-start)/float(max_steps)
from sage.all import srange # sage range is much better/more flexible.
self.vals = srange(start, stop, step_size, include_endpoint=True)
# Now check to see if any of thee above constructed a list of
# values that exceeds max_steps -- if so, linearly interpolate:
if len(self.vals) > max_steps:
n = len(self.vals)//max_steps
self.vals = [self.vals[n*i] for i in range(len(self.vals)//n)]
def to_client(self, val):
if val is None:
return 0
if isinstance(val, (list, tuple)):
return [self.to_client(v) for v in val]
else:
# Find index into self.vals of closest match.
try:
return self.vals.index(val) # exact match
except ValueError:
pass
z = [(abs(val-x),i) for i, x in enumerate(self.vals)]
z.sort()
return z[0][1]
def from_client(self, val):
if val is None:
return self.vals[0]
# val can be a n-tuple or an integer
if isinstance(val, (list, tuple)):
return tuple([self.vals[v] for v in val])
else:
return self.vals[int(val)]
class InputGrid:
def __init__(self, nrows, ncols, default, to_value):
self.nrows = nrows
self.ncols = ncols
self.to_value = to_value
self.value = copy.deepcopy(self.adapt(default))
def adapt(self, x):
if not isinstance(x, list):
return [[x for _ in range(self.ncols)] for _ in range(self.nrows)]
elif not all(isinstance(elt, list) for elt in x):
return [[x[i * self.ncols + j] for j in xrange(self.ncols)] for i in xrange(self.nrows)]
else:
return x
def from_client(self, x):
if len(x) == 0:
self.value = []
elif isinstance(x[0], list):
self.value = [[sage_eval(t) for t in z] for z in x]
else:
# x is a list of (unicode) strings -- we sage eval them all at once (instead of individually).
s = '[' + ','.join([str(t) for t in x]) + ']'
v = sage_eval(s)
self.value = [v[n:n+self.ncols] for n in range(0, self.nrows*self.ncols, self.ncols)]
return self.to_value(self.value) if self.to_value is not None else self.value
def to_client(self, x=None):
if x is None:
v = self.value
else:
v = self.adapt(x)
self.value = v # save value in our local cache
return [[repr(x) for x in y] for y in v]
def input_grid(nrows, ncols, default=0, label=None, to_value=None, width=5):
r"""
A grid of input boxes, for use with the :func:`interact` command.
INPUT:
- ``nrows`` - an integer
- ``ncols`` - an integer
- ``default`` - an object; the default put in this input box
- ``label`` - 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
EXAMPLES:
Solving a system::
@interact
def _(m = input_grid(2,2, default = [[1,7],[3,4]],
label=r'$M\qquad =$', to_value=matrix, width=8),
v = input_grid(2,1, default=[1,2],
label=r'$v\qquad =$', to_value=matrix)):
try:
x = m.solve_right(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)))
Squaring an editable and randomizable matrix::
@interact
def f(reset = button('Randomize', classes="btn-primary", icon="fa-th"),
square = button("Square", icon="fa-external-link"),
m = input_grid(4,4,default=0, width=5, label="m =", to_value=matrix)):
if 'reset' in interact.changed():
print "randomize"
interact.m = [[random() for _ in range(4)] for _ in range(4)]
if 'square' in interact.changed():
salvus.tex(m^2)
"""
ig = InputGrid(nrows, ncols, default, to_value)
return control(
control_type = 'input-grid',
opts = {'default' : ig.to_client(),
'label' : label,
'width' : width,
'nrows' : nrows,
'ncols' : ncols},
repr = "Input Grid",
convert_from_client = ig.from_client,
convert_to_client = ig.to_client
)
def slider(start, stop=None, step=None, default=None, label=None,
display_value=True, max_steps=500, step_size=None, range=False,
width=None, animate=True):
"""
An interactive slider control for use with :func:`interact`.
There are several ways to call the slider function, but they all
take several named arguments:
- ``default`` - an object (default: None); default value is closest
value. If range=True, default can also be a 2-tuple (low, high).
- ``label`` -- string
- ``display_value`` -- bool (default: True); whether to display the
current value to the right of the slider.
- ``max_steps`` -- integer, default: 500; this is the maximum
number of values that the slider can take on. Do not make
it too large, since it could overwhelm the client. [SALVUS only]
- ``range`` -- bool (default: False); instead, you can select
a range of values (lower, higher), which are returned as a
2-tuple. You may also set the value of the slider or
specify a default value using a 2-tuple.
- ``width`` -- how wide the slider appears to the user [SALVUS only]
- ``animate`` -- True (default), False,"fast", "slow", or the
duration of the animation in milliseconds. [SALVUS only]
You may call the slider function as follows:
- slider([list of objects], ...) -- slider taking values the objects in the list
- slider([start,] stop[, step]) -- slider over numbers from start
to stop. When step is given it specifies the increment (or
decrement); if it is not given, then the number of steps equals
the width of the control in pixels. In all cases, the number of
values will be shrunk to be at most the pixel_width, since it is
not possible to select more than this many values using a slider.
EXAMPLES::
Use one slider to modify the animation speed of another::
@interact
def f(speed=(50,100,..,2000), x=slider([1..50], animate=1000)):
if 'speed' in interact.triggers():
print "change x to have speed", speed
del interact.x
interact.x = slider([1..50], default=interact.x, animate=speed)
return
"""
if step_size is not None: # for compat with sage
step = step_size
slider = Slider(start, stop, step, max_steps)
vals = [str(x) for x in slider.vals] # for display by the client
if range and default is None:
default = [0, len(vals)-1]
return control(
control_type = 'range-slider' if range else 'slider',
opts = {'default' : slider.to_client(default),
'label' : label,
'animate' : animate,
'vals' : vals,
'display_value' : display_value,
'width' : width},
repr = "Slider",
convert_from_client = slider.from_client,
convert_to_client = slider.to_client
)
def range_slider(*args, **kwds):
"""
range_slider is the same as :func:`slider`, except with range=True.
EXAMPLES:
A range slider with a constraint::
@interact
def _(t = range_slider([1..1000], default=(100,200), label=r'Choose a range for $\alpha$')):
print t
"""
kwds['range'] = True
return slider(*args, **kwds)
def selector(values, label=None, default=None,
nrows=None, ncols=None, width=None, buttons=False,
button_classes=None):
"""