forked from sagemath/sagecell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interact_sagecell.py
1244 lines (1051 loc) · 48.2 KB
/
interact_sagecell.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
"""
Interacts
The camelcase controls (like Selector or ButtonBar) have experimental APIs and may change. The stable API is still the backwards-compatible API.
Examples
--------
Radio button example::
@interact
def f(n = Selector(values=["Option1","Option2"], selector_type="radio", label=" ")):
print n
Push button example::
result = 0
@interact
def f(n = Button(text="Increment", default=0, value=1, width="10em", label=" ")):
global result
result = result + n
print "Result: ", result
Button bar example::
result = 0
@interact
def f(n = ButtonBar(values=[(1,"Increment"),(-1,"Decrement")], default=0, width="10em", label=" ")):
global result
result = result + n
print "Result: ", result
Multislider example::
sliders = 5
interval = [(0,10)]*sliders
default = [3]*sliders
@interact
def f(n = MultiSlider(sliders = sliders, interval = interval, default = default), c = (1,100)):
print "Sum of cn for all n: %s"%float(sum(c * i for i in n))
Nested interacts::
@interact
def f(n=(0,10,1)):
print n
@interact
def transformation(c=(0,n)):
print c
Nested interacts where the number of controls is changed::
@interact
def f(n=(0,10)):
@interact(controls=[('x%d'%i, (0,10)) for i in range(n)])
def s(multiplier=2, **kwargs):
print sum(kwargs.values())*multiplier
Recursively nested interact::
c=1
@interact
def f(n=(0,10)):
global c
c+=1
print 'f evaluated %d times'%c
for i in range(n):
interact(f)
"""
import sagecell_exec_config as CONFIG
_INTERACTS={}
__sage_cell_timeout__=0
from functools import wraps
def decorator_defaults(func):
"""
This function allows a decorator to have default arguments.
Normally, a decorator can be called with or without arguments.
However, the two cases call for different types of return values.
If a decorator is called with no parentheses, it should be run
directly on the function. However, if a decorator is called with
parentheses (i.e., arguments), then it should return a function
that is then in turn called with the defined function as an
argument.
This decorator allows us to have these default arguments without
worrying about the return type.
EXAMPLES::
sage: from sage.misc.decorators import decorator_defaults
sage: @decorator_defaults
... def my_decorator(f,*args,**kwds):
... print kwds
... print args
... print f.__name__
...
sage: @my_decorator
... def my_fun(a,b):
... return a,b
...
{}
()
my_fun
sage: @my_decorator(3,4,c=1,d=2)
... def my_fun(a,b):
... return a,b
...
{'c': 1, 'd': 2}
(3, 4)
my_fun
"""
from inspect import isfunction
@wraps(func)
def my_wrap(*args,**kwargs):
if len(kwargs)==0 and len(args)==1 and isfunction(args[0]):
# call without parentheses
return func(*args)
else:
def _(f):
return func(f, *args, **kwargs)
return _
return my_wrap
@decorator_defaults
def interact(f, controls=[], update=None, layout=None):
"""
A decorator that creates an interact.
Each control can be given as an :class:`.InteractControl` object
or a value, defined in :func:`.automatic_control`, that will be
interpreted as the parameters for some control.
The decorator can be used in several ways::
@interact([name1, (name2, control2), (name3, control3)])
def f(**kwargs):
...
@interact
def f(name1, name2=control2, name3=control3):
...
The two ways can also be combined::
@interact([name1, (name2, control2)])
def f(name3, name4=control4, name5=control5):
...
In each example, ``name1``, with no associated control,
will default to a text box.
:arg function f: the function to make into an interact
:arg list controls: a list of tuples of the form ``("name",control)``
:returns: the original function
:rtype: function
"""
if update is None: update = {}
if layout is None: layout = {}
global _INTERACTS
if isinstance(controls,(list,tuple)):
controls=list(controls)
for i,name in enumerate(controls):
if isinstance(name, str):
controls[i]=(name, None)
elif not isinstance(name[0], str):
raise ValueError("interact control must have a string name, but %s isn't a string"%(name[0],))
import inspect
(args, varargs, varkw, defaults) = inspect.getargspec(f)
if defaults is None:
defaults=[]
n=len(args)-len(defaults)
controls=zip(args,[None]*n+list(defaults))+controls
names=[n for n,_ in controls]
controls=[automatic_control(c, var=n) for n,c in controls]
nameset = set(names)
for n,c in zip(names, controls):
# Check for update button controls
if isinstance(c, UpdateButton):
update[n] = c.boundVars()
if update:
# sanitize input
for key,value in update.items():
# note: we are modifying the dictionary below, so we want
# to get all the items first
if key not in nameset:
# Test if the updating variable is defined
raise ValueError("%s is not an interacted variable."%repr(change))
# make the values unique, and make sure the control updates itself
value = set(value)
value.add(key)
if "*" in value:
# include all controls
value = nameset
elif value-nameset:
raise ValueError("Update variables %s are not interact variables."%repr(list(value-nameset)))
update[key]=list(value)
else:
update = dict((n,[n]) for n in names)
if isinstance(layout, (list, tuple)):
layout = {'top_center': layout}
if layout:
# sanitize input
layout_values = set(["top_left","top_right","top_center","right","left","bottom_left","bottom_right","bottom_center", "top", "bottom"])
sanitized_layout = {}
previous_vars = []
for key,value in layout.items():
error_vars = []
if key in layout_values:
if key in ("top", "bottom"):
oldkey=key
key+="_center"
if key in layout:
raise ValueError("Cannot have both %s and %s specified"%(oldkey,key))
else:
raise ValueError("%s is an incorrect layout key. Possible options are %s"%(repr(k), layout_values))
if isinstance(value[0], list):
if ["*"] in value:
value = [[n] for n in names]
elif set(flatten(value))-nameset:
raise ValueError("Layout variables %s are not interact variables."%repr(list(set(flatten(value))-nameset)))
for varlist in value:
for var in varlist:
if var in previous_vars:
error_vars.append(var);
if error_vars:
raise ValueError("Layout variables %s are repeated in '%s'."%(repr(error_vars),key))
previous_vars.extend(varlist)
sanitized_layout[key] = value
else:
if "*" in value:
value = [n for n in names]
elif set(value)-nameset:
raise ValueError("Layout variables %s are not interact variables."%repr(list(set(value)-nameset)))
for var in value:
if var in previous_vars:
error_vars.append(var);
if error_vars:
raise ValueError("Layout variables %s are repeated in '%s'."%(repr(error_vars),key))
previous_vars.extend(value)
sanitized_layout[key] = value
layout = sanitized_layout
else:
layout["top_center"] = [n for n in names]
# _sage_messages is monkey-patched onto sys by prepended user code
from sys import maxint, _sage_messages
from random import randrange
# UUID would be better, but we can't use it because of a
# bug in Python 2.6 on Mac OS X (http://bugs.python.org/issue8621)
function_id=str(randrange(maxint))
def adapted_f(control_vals):
_sage_messages.push_output_id(function_id)
returned=f(**control_vals)
_sage_messages.pop_output_id()
return returned
globs = f.func_globals
_INTERACTS[function_id] = {
"state": dict(zip(names,[c.adapter(c.default, globs) for c in controls])),
"function": adapted_f,
"controls": dict(zip(names, controls)),
"globals": globs,
}
_sage_messages.message_queue.message('interact_prepare',
{'interact_id':function_id,
'controls':dict(zip(names,[c.message() for c in controls])),
'update':update,
'layout':layout})
global __sage_cell_timeout__
__sage_cell_timeout__=60
adapted_f(control_vals=_INTERACTS[function_id]["state"].copy())
return f
class InteractControl:
"""
Base class for all interact controls.
"""
preserve_state = True
def __init__(self, *args, **kwargs):
self.args=args
self.kwargs=kwargs
def adapter(self, v, globs):
"""
Get the value of the interact in a form that can be passed to
the inner function
We pass in a global variable dictionary ``globs`` so that the
arguments can be evaluated in context of the current global
environment. This is necessary since the arguments are being evaluated
in a totally different context from the rest of the function.
:arg v: a value as passed from the client
:dict globs: the global variables in which to evaluate things
:returns: the interpretation of that value in the context of
this control (by default, the value is not changed)
"""
return v
def message(self):
"""
Get a control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
raise NotImplementedError
class Checkbox(InteractControl):
"""
A checkbox control
:arg bool default: ``True`` if the checkbox is checked by default
:arg bool raw: ``True`` if the value should be treated as "unquoted"
(raw), so it can be used in control structures. There are few
conceivable situations in which raw should be set to ``False``,
but it is available.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, default=True, label=None, raw=True):
self.default=default
self.raw=raw
self.label=label
def message(self):
"""
Get a checkbox control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type':'checkbox',
'default':self.default,
'raw':self.raw,
'label':self.label}
class InputBox(InteractControl):
"""
An input box control
:arg default: default value of the input box. If this is not a string, repr is
called on it to get a string, which is then the default input.
:arg int width: character width of the input box.
:arg int height: character height of the input box. If this is greater than
one, an HTML textarea will be rendered, while if it is less than one,
an input box form element will be rendered.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
:arg adapter: a callable which will be passed the input before
sending it into the function. This might ensure that the
input to the function is of a specific type, for example. The
function should take as input the value of the control and
should return something that is then passed into the interact
function as the value of the control.
:arg bool evaluate: If ``True`` (default), the user's string will first be evaluated
using ``sage_eval``, and then passed to the adapter function.
"""
def __init__(self, default="", label=None, width=0, height=1, adapter=None, evaluate=True):
if not isinstance(default, basestring):
default = repr(default)
self.default=default
self.width=int(width)
self.height=int(height)
self.raw=False
self.label=label
if evaluate:
from sage.all import sage_eval
if adapter is not None:
self.adapter = lambda x,globs: adapter(sage_eval(x,globs), globs)
else:
self.adapter = lambda x,globs: sage_eval(x,globs)
elif adapter is not None:
self.adapter = lambda x,globs: adapter(x,globs)
if self.height > 1:
self.subtype = "textarea"
self.raw = True
else:
self.subtype = "input"
def message(self):
"""
Get an input box control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type':'input_box',
'subtype':self.subtype,
'default':self.default,
'width':self.width,
'height':self.height,
'raw':self.raw,
'label':self.label}
class InputGrid(InteractControl):
"""
An input grid control
:arg int nrows: number of rows in the grid
:arg int ncols: number of columns in the grid
:arg default: default values of the control. A multi-dimensional
list specifies the values of individual inputs; a single value
sets the same value to all inputs
:arg adapter: a callable which will be passed the input before
sending it into the function. This might ensure that the
input to the function is of a specific type, for example. The
function should take as input a list of lists (the value
of the control), as well as the globals.
:arg int width: character width of each input box
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
:arg element_adapter: a callable which takes an element value and the globs
and returns an adapter element. A nested list of these adapted elements
is what is given to the adapter function.
:arg evaluate: whether or not the strings returned from the front end
are first sage_eval'd (default: ``True``).
"""
def __init__(self, nrows=1, ncols=1, default='0', adapter=None, width=0, label=None,
element_adapter=None, evaluate=True):
self.nrows = int(nrows)
self.ncols = int(ncols)
self.width = int(width)
self.label = label
if evaluate:
from sage.all import sage_eval
if element_adapter is not None:
self.element_adapter = lambda x,globs: element_adapter(sage_eval(x,globs), globs)
else:
self.element_adapter = lambda x,globs: sage_eval(x,globs)
else:
if element_adapter is not None:
self.element_adapter = lambda x,globs: element_adapter(x,globs)
else:
self.element_adapter = lambda x,globs: x
if adapter is None:
self.adapter = lambda x,globs: [[self.element_adapter(i,globs) for i in xi] for xi in x]
else:
self.adapter = lambda x,globs: adapter([[self.element_adapter(i,globs) for i in xi] for xi in x],globs)
def makestring(x):
if isinstance(x, basestring):
return x
else:
return repr(x)
if not isinstance(default, list):
self.default = [[makestring(default) for _ in range(self.ncols)] for _ in range(self.nrows)]
# Allows 1-row input grids to use non-nested lists for default values
elif not all(isinstance(entry, (list,tuple)) for entry in default):
# the above test will exhaust an iterator...
self.default = [[makestring(default[i * self.ncols + j]) for j in range(self.ncols)] for i in range(self.nrows)]
else:
self.default = [[makestring(default[r][c]) for c in range(self.ncols)] for r in range(self.nrows)]
def message(self):
"""
Get an input grid control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type': 'input_grid',
'nrows': self.nrows,
'ncols': self.ncols,
'default': self.default,
'width':self.width,
'raw': True,
'label': self.label}
class Selector(InteractControl):
"""
A selector interact control
:arg int default: initially selected item in the list of values
:arg list values: list of values from which the user can select. A value can
also be represented as a tuple of the form ``(value, label)``, where the
value is the name of the variable and the label is the text displayed to
the user.
:arg string selector_type: Type of selector. Currently supported options
are "button" (Buttons), "radio" (Radio buttons), and "list"
(Dropdown list), with "list" being the default. If "list" is used,
``ncols`` and ``nrows`` will be ignored. If "radio" is used, ``width``
will be ignored.
:arg int ncols: number of columns of selectable objects. If this is given,
it must cleanly divide the number of objects, else this value will be
set to the number of objects and ``nrows`` will be set to 1.
:arg int nrows: number of rows of selectable objects. If this is given, it
must cleanly divide the number of objects, else this value will be set
to 1 and ``ncols`` will be set to the number of objects. If both
``ncols`` and ``nrows`` are given, ``nrows * ncols`` must equal the
number of objects, else ``nrows`` will be set to 1 and ``ncols`` will
be set to the number of objects.
:arg string width: CSS width of each button. This should be specified in
px or em.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, values, default=None, selector_type="list", nrows=None, ncols=None, width="", label=None):
self.values=values[:]
self.selector_type=selector_type
self.nrows=nrows
self.ncols=ncols
self.width=str(width)
self.label=label
if self.selector_type != "button" and self.selector_type != "radio":
self.selector_type = "list"
# Assign selector labels and values.
self.value_labels=[str(v[1]) if isinstance(v,tuple) and
len(v)==2 else str(v) for v in values]
self.values = [v[0] if isinstance(v,tuple) and
len(v)==2 else v for v in values]
self.default = default_to_index(self.values, default)
# If not using a dropdown list,
# check/set rows and columns for layout.
if self.selector_type != "list":
if self.nrows is None and self.ncols is None:
self.nrows = 1
self.ncols = len(self.values)
elif self.nrows is None:
self.ncols = int(self.ncols)
if self.ncols <= 0:
self.ncols = len(values)
self.nrows = int(len(self.values) / self.ncols)
if self.ncols * self.nrows < len(self.values):
self.nrows = 1
self.ncols = len(self.values)
elif self.ncols is None:
self.nrows = int(self.nrows)
if self.nrows <= 0:
self.nrows = 1
self.ncols = int(len(self.values) / self.nrows)
if self.ncols * self.nrows < len(self.values):
self.nrows = 1
self.ncols = len(self.values)
else:
self.ncols = int(self.ncols)
self.nrows = int(self.nrows)
if self.ncols * self.nrows != len(self.values):
self.nrows = 1
self.ncols = len(self.values)
def message(self):
"""
Get a selector control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type': 'selector',
'subtype': self.selector_type,
'values': len(self.values),
'value_labels': self.value_labels,
'default': self.default,
'nrows': int(self.nrows) if self.nrows is not None else None,
'ncols': int(self.ncols) if self.ncols is not None else None,
'raw': True,
'width': self.width,
'label':self.label}
def adapter(self, v, globs):
return self.values[int(v)]
class DiscreteSlider(InteractControl):
"""
A discrete slider interact control.
The slider value correlates with the index of an array of values.
:arg int default: initial value (index) of the slider; if ``None``, the
slider defaults to the 0th index. The default will be the
closest values to this parameter.
:arg list values: list of values to which the slider position refers.
:arg bool range_slider: toggles whether the slider should select
one value (False, default) or a range of values (True).
:arg bool display_value: toggles whether the slider value sould be displayed (default = True)
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, values=[0,1], default=None, range_slider=False, display_value=True, label=None):
from types import GeneratorType
if isinstance(values, GeneratorType):
self.values = take(10000, values)
else:
self.values = values[:]
if len(self.values) < 2:
self.values = [0,1]
self.range_slider = range_slider
self.display_value = display_value
if self.range_slider:
self.subtype = "discrete_range"
if default is None:
self.default = (0,len(values)-1)
else:
self.default=tuple(default_to_index(self.values, d)
for d in default)
else:
self.subtype = "discrete"
self.default = default_to_index(self.values,
default)
self.label=label
def message(self):
"""
Get a discrete slider control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type':'slider',
'subtype':self.subtype,
'display_value':self.display_value,
'default':self.default,
'range':[0, len(self.values)-1],
'values':[repr(i) for i in self.values],
'step':1,
'raw':True,
'label':self.label}
def adapter(self,v, globs):
if self.range_slider:
return [self.values[int(i)] for i in v]
else:
return self.values[int(v)]
class ContinuousSlider(InteractControl):
"""
A continuous slider interact control.
The slider value moves between a range of numbers.
:arg int default: initial value of the slider; if ``None``, the
slider defaults to its minimum
:arg tuple interval: range of the slider, in the form ``(min, max)``
:arg int steps: number of steps the slider should have between min and max
:arg Number stepsize: size of step for the slider. If both step and stepsized are specified, stepsize takes precedence so long as it is valid.
:arg bool range_slider: toggles whether the slider should select one value (default = False) or a range of values (True).
:arg bool display_value: toggles whether the slider value sould be displayed (default = True)
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
Note that while "number of steps" and/or "stepsize" can be specified for the slider, this is to enable snapping, rather than a restriction on the slider's values. The only restrictions placed on the values of the slider are the endpoints of its range.
"""
def __init__(self, interval=(0,100), default=None, steps=250, stepsize=0, label=None, range_slider=False, display_value=True):
self.range_slider = range_slider
self.display_value = display_value
self.interval = interval if interval[0] < interval[1] and len(interval) == 2 else (0,100)
if self.range_slider:
self.subtype = "continuous_range"
self.default = default if default is not None and len(default) == 2 else [self.interval[0], self.interval[1]]
for i in range(2):
if not (self.interval[0] <= self.default[i] <= self.interval[1]):
self.default[i] = self.interval[i]
self.default_return = [float(i) for i in self.default]
else:
self.subtype = "continuous"
self.default = default if default is not None and self.interval[0] <= default <= self.interval[1] else self.interval[0]
self.default_return = float(self.default)
self.steps = int(steps) if steps > 0 else 250
self.stepsize = float(stepsize if stepsize > 0 and stepsize <= self.interval[1] - self.interval[0] else float(self.interval[1] - self.interval[0]) / self.steps)
self.label = label
def message(self):
"""
Get a continuous slider control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return {'control_type':'slider',
'subtype':self.subtype,
'display_value':self.display_value,
'default':self.default_return,
'range':[float(i) for i in self.interval],
'step':self.stepsize,
'raw':True,
'label':self.label}
class MultiSlider(InteractControl):
"""
A multiple-slider interact control.
Defines a bank of vertical sliders (either discrete or continuous sliders, but not both in the same control).
:arg string slider_type: type of sliders to generate. Currently, only "continuous" and "discrete" are valid, and other input defaults to "continuous."
:arg int sliders: Number of sliders to generate
:arg list default: Default value of each slider. The length of the list should be equivalent to the number of sliders, but if all sliders are to have the same default value, the list only needs to contain that one value.
:arg list values: Values for each value slider in a multi-dimensional list for the form [[slider_1_val_1..slider_1_val_n], ... ,[slider_n_val_1, .. ,slider_n_val_n]]. The length of the first dimension of the list should be equivalent to the number of sliders, but if all sliders are to iterate through the same values, the list only needs to contain that one list of values.
:arg list interval: Intervals for each continuous slider in a list of tuples of the form [(min_1, max_1), ... ,(min_n, max_n)]. This parameter cannot be set if value sliders are specified. The length of the first dimension of the list should be equivalent to the number of sliders, but if all sliders are to have the same interval, the list only needs to contain that one tuple.
:arg list stepsize: List of numbers representing the stepsize for each continuous slider. The length of the list should be equivalent to the number of sliders, but if all sliders are to have the same stepsize, the list only needs to contain that one value.
:arg list steps: List of numbers representing the number of steps for each continuous slider. Note that (as in the case of the regular continuous slider), specifying a valid stepsize will always take precedence over any specification of number of steps, valid or not. The length of this list should be equivalent to the number of sliders, but if all sliders are to have the same number of steps, the list only neesd to contain that one value.
:arg bool display_values: toggles whether the slider values sould be displayed (default = True)
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, sliders=1, values=[[0,1]], interval=[(0,1)], slider_type="continuous", default=[0], stepsize=[0], steps=[250], display_values=True, label=None):
from types import GeneratorType
self.slider_type = slider_type
self.display_values = display_values
self.sliders = int(sliders) if sliders > 0 else 1
self.slider_range = range(self.sliders)
if self.slider_type == "discrete":
self.stepsize = 1
if len(values) == self.sliders:
self.values = values[:]
elif len(values) == 1 and len(values[0]) >= 2:
self.values = [values[0]] * self.sliders
else:
self.values = [[0,1]] * self.sliders
self.values = [i if not isinstance(i, GeneratorType) else take(10000, i) for i in self.values]
self.interval = [(0, len(self.values[i])-1) for i in self.slider_range]
# TODO: make sure default specifies a value, not an index into self.values; use default_to_index
if len(default) == self.sliders:
self.default = [default_to_index(self.values, default[i]) for i in default]
elif len(default) == 1:
self.default = [default_to_index(self.values, default[0]) for i in self.slider_range]
else:
self.default = [0] * self.sliders
else:
self.slider_type = "continuous"
if len(interval) == self.sliders:
self.interval = interval[:]
elif len(interval) == 1 and len(interval[0]) == 2:
self.interval = [interval[0]] * self.sliders
else:
self.interval = [(0,1) for i in self.slider_range]
for i in self.slider_range:
if not len(self.interval[i]) == 2 or self.interval[i][0] > self.interval[i]:
self.interval[i] = (0,1)
else:
self.interval[i] = [float(j) for j in self.interval[i]]
if len(default) == self.sliders:
self.default = [default[i] if default[i] > self.interval[i][0] and default[i] < self.interval[i][1] else self.interval[i][0] for i in self.slider_range]
elif len(default) == 1:
self.default = [default[0] if default[0] > self.interval[i][0] and default[0] < self.interval[i][1] else self.interval[i][0] for i in self.slider_range]
else:
self.default = [self.interval[i][0] for i in self.slider_range]
self.default_return = [float(i) for i in self.default]
if len(steps) == 1:
self.steps = [steps[0]] * self.sliders if steps[0] > 0 else [250] * self.sliders
else:
self.steps = [int(i) if i > 0 else 250 for i in steps] if len(steps) == self.sliders else [250 for i in self.slider_range]
if len(stepsize) == self.sliders:
self.stepsize = [float(stepsize[i]) if stepsize[i] > 0 and stepsize[i] <= self.interval[i][1] - self.interval[i][0] else float(self.interval[i][1] - self.interval[i][0]) / self.steps[i] for i in self.slider_range]
elif len(stepsize) == 1:
self.stepsize = [float(stepsize[0]) if stepsize[0] > 0 and stepsize[0] <= self.interval[i][1] - self.interval[i][0] else float(self.interval[i][1] - self.interval[i][0]) / self.steps[i] for i in self.slider_range]
else:
self.stepsize = [float(self.interval[i][1] - self.interval[i][0]) / self.steps[i] for i in self.slider_range]
self.label = label
def message(self):
"""
Get a multi_slider control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
return_message = {'control_type':'multi_slider',
'subtype':self.slider_type,
'display_values':self.display_values,
'sliders':self.sliders,
'label':self.label,
'range':self.interval,
'step':self.stepsize,
'raw':True,
'label':self.label}
if self.slider_type == "discrete":
return_message["values"] = [[repr(j) for j in self.values[i]] for i in self.slider_range]
return_message["default"] = self.default
else:
return_message["default"] = self.default_return
return return_message
def adapter(self,v, globs):
if self.slider_type == "discrete":
return [self.values[i][v[i]] for i in self.slider_range]
else:
return v
class ColorSelector(InteractControl):
"""
A color selector interact control
:arg default: initial color (either as an html hex string or a Sage Color
object, if sage is installed.
:arg bool hide_input: Toggles whether the hex value of the color picker
should be displayed in an input box beside the control.
:arg bool sage_color: Toggles whether the return value should be a Sage
Color object (True) or html hex string (False). If Sage is unavailable
or if the user has deselected "sage mode" for the computation, this
value will always end up False, regardless of whether the user specified
otherwise in the interact.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, default="#000000", hide_input=False, sage_color=True, label=None):
self.sage_color = sage_color
self.sage_mode = CONFIG.EMBEDDED_MODE["sage_mode"]
self.enable_sage = CONFIG.EMBEDDED_MODE["enable_sage"]
if self.sage_mode and self.enable_sage and self.sage_color:
from sagenb.misc.misc import Color
if isinstance(default, Color):
self.default = default
elif isinstance(default, str):
self.default = Color(default)
else:
self.default = Color("#000000")
else:
self.default = default if isinstance(default,str) else "#000000"
self.hide_input = hide_input
self.label = label
def message(self):
"""
Get a color selector control configuration message for an
``interact_prepare`` message
:returns: configuration message
:rtype: dict
"""
self.return_value = {'control_type':'color_selector',
'hide_input': self.hide_input,
'raw':False,
'label':self.label}
if self.sage_mode and self.enable_sage and self.sage_color:
self.return_value["default"] = self.default.html_color()
else:
self.return_value["default"] = self.default
return self.return_value
def adapter(self, v, globs):
if self.sage_mode and self.enable_sage and self.sage_color:
from sagenb.misc.misc import Color
return Color(v)
else:
return v
class Button(InteractControl):
"""
A button interact control
:arg string text: button text
:arg value: value of the button, when pressed.
:arg default: default value that should be used if the button is not
pushed. This **must** be specified.
:arg string width: CSS width of the button. This should be specified in
px or em.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, default="", value = "", text="Button", width="", label=None):
self.text = text
self.width = width
self.value = value
self.default = False
self.default_value = default
self.label = label
self.preserve_state = False
def message(self):
return {'control_type':'button',
'width':self.width,
'text':self.text,
'raw': True,
'label': self.label}
def adapter(self, v, globs):
if v:
return self.value
else:
return self.default_value
class ButtonBar(InteractControl):
"""
A button bar interact control
:arg list values: list of values from which the user can select. A value can
also be represented as a tuple of the form ``(value, label)``, where the
value is the name of the variable and the label is the text displayed to
the user.
:arg default: default value that should be used if no button is pushed.
This **must** be specified.
:arg int ncols: number of columns of selectable buttons. If this is given,
it must cleanly divide the number of buttons, else this value will be
set to the number of buttons and ``nrows`` will be set to 1.
:arg int nrows: number of rows of buttons. If this is given, it must cleanly
divide the total number of objects, else this value will be set to 1 and
``ncols`` will be set to the number of buttosn. If both ``ncols`` and
``nrows`` are given, ``nrows * ncols`` must equal the number of buttons,
else ``nrows`` will be set to 1 and ``ncols`` will be set to the number
of objects.
:arg string width: CSS width of each button. This should be specified in
px or em.
:arg str label: the label of the control, ``""`` for no label, and
a default value (None) of the control's variable.
"""
def __init__(self, values=[0], default="", nrows=None, ncols=None, width="", label=None):
self.default = None
self.default_value = default
self.values = values[:]
self.nrows = nrows
self.ncols = ncols
self.width = str(width)
self.label = label
self.preserve_state=False
# Assign button labels and values.
self.value_labels=[str(v[1]) if isinstance(v,tuple) and
len(v)==2 else str(v) for v in values]
self.values = [v[0] if isinstance(v,tuple) and
len(v)==2 else v for v in values]
# Check/set rows and columns for layout
if self.nrows is None and self.ncols is None:
self.nrows = 1
self.ncols = len(self.values)
elif self.nrows is None:
self.ncols = int(self.ncols)
if self.ncols <= 0:
self.ncols = len(values)