-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathbasevalidators.py
1405 lines (1127 loc) · 48.5 KB
/
basevalidators.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
import base64
import numbers
import textwrap
import uuid
from importlib import import_module
import io
from copy import deepcopy
import numpy as np
import pandas as pd
import re
# Utility functions
# -----------------
def copy_to_contiguous_readonly_numpy_array(v, dtype=None, force_numeric=False):
# Copy to numpy array and handle dtype param
# ------------------------------------------
# If dtype was not specified then it will be passed to the numpy array constructor as None and the data type
# will be inferred automatically
# TODO: support datetime dtype here and in widget serialization
numeric_kinds = ['u', 'i', 'f']
if not isinstance(v, np.ndarray):
new_v = np.array(v, order='C', dtype=dtype)
elif v.dtype.kind in numeric_kinds:
new_v = np.ascontiguousarray(v.astype(dtype))
else:
new_v = v.copy()
# Handle force numeric param
# --------------------------
if force_numeric and new_v.dtype.kind not in numeric_kinds: # (un)signed int, or float
raise ValueError('Input value is not numeric and force_numeric parameter set to True')
if dtype != 'unicode':
# Force non-numeric arrays to have object type
# --------------------------------------------
# Here we make sure that non-numeric arrays have the object datatype. This works around cases like
# np.array([1, 2, '3']) where numpy converts the integers to strings and returns array of dtype '<U21'
if new_v.dtype.kind not in ['u', 'i', 'f', 'O']: # (un)signed int, float, or object
new_v = np.array(v, dtype='object')
# Convert int64 arrays to int32
# -----------------------------
# JavaScript doesn't support int64 typed arrays
if new_v.dtype == 'int64':
new_v = new_v.astype('int32')
# Set new array to be read-only
# -----------------------------
new_v.flags['WRITEABLE'] = False
return new_v
def is_array(v):
return (isinstance(v, (list, tuple)) or
(isinstance(v, np.ndarray) and v.ndim == 1) or
isinstance(v, pd.Series))
def type_str(v):
if isinstance(v, str) and v.startswith('<class '):
return repr(v[7:-1])
if not isinstance(v, type):
v = type(v)
return "'{module}.{name}'".format(module=v.__module__, name=v.__name__)
# Validators
# ----------
class BaseValidator:
def __init__(self, plotly_name, parent_name, role=None, **_):
self.parent_name = parent_name
self.plotly_name = plotly_name
self.role = role
def validate_coerce(self, v):
raise NotImplementedError()
def description(self):
"""Returns a string that describes the values that are acceptable to the validator.
Should start with:
The '{plotly_name}' property is a...
For consistancy, string should have leading 4-space indent
"""
raise NotImplementedError()
def raise_invalid_val(self, v):
raise ValueError(
("\n"
" Invalid value of type {typ} received for the '{plotly_name}' property of {parent_name}\n"
" Received value: {v}\n\n"
"{vald_clr_desc}\n"
).format(plotly_name=self.plotly_name,
parent_name=self.parent_name,
typ=type_str(v),
v=repr(v),
vald_clr_desc=self.description()))
def raise_invalid_elements(self, invalid_els):
if invalid_els:
raise ValueError(
("\n"
" Invalid element(s) received for the '{plotly_name}' property of {parent_name}\n"
" Invalid elements include: {invalid}\n\n"
"{vald_clr_desc}\n"
).format(plotly_name=self.plotly_name,
parent_name=self.parent_name,
invalid=invalid_els[:10],
vald_clr_desc=self.description()))
class DataArrayValidator(BaseValidator):
"""
"data_array": {
"description": "An {array} of data. The value MUST be an {array}, or we ignore it.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
},
"""
def __init__(self, plotly_name, parent_name, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
def description(self):
return ("""\
The '{plotly_name}' property is an array that may be specified as a tuple, list, or one-dimensional numpy array"""
.format(plotly_name=self.plotly_name))
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif is_array(v):
v = copy_to_contiguous_readonly_numpy_array(v)
else:
self.raise_invalid_val(v)
return v
class EnumeratedValidator(BaseValidator):
"""
"enumerated": {
"description": "Enumerated value type. The available values are listed in `values`.",
"requiredOpts": [
"values"
],
"otherOpts": [
"dflt",
"coerceNumber",
"arrayOk"
]
},
"""
def __init__(self, plotly_name, parent_name, values,
array_ok=False,
coerce_number=False,
**kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
# coerce_number is rarely used and not implemented
self.coerce_number = coerce_number
self.values = values
# compile regexes
self.val_regexs = []
# regex replacement that runs before the matching regex
# So far, this is only used to cast x1 -> x for anchor-style
# enumeration properties
self.regex_replacements = []
for v in self.values:
if v and isinstance(v, str) and v[0] == '/' and v[-1] == '/':
# String is regex with leading and trailing '/' character
regex_str = v[1:-1]
self.val_regexs.append(re.compile(regex_str))
self.regex_replacements.append(
EnumeratedValidator.build_regex_replacement(regex_str))
else:
self.val_regexs.append(None)
self.regex_replacements.append(None)
self.array_ok = array_ok
@staticmethod
def build_regex_replacement(regex_str):
# regex_str = r"^y([2-9]|[1-9][0-9]+)?$"
# Remove id of 1 from subplotid-style anchors. The regular
# expressions forbid a suffix of 1. But we want just want to convert
# to by removing the 1 (e.g. turn x1 -> x).
#
# To be cautious, we only perform this conversion for enumerated
# values that match the anchor-style regex
match = re.match(r"\^(\w)\(\[2\-9\]\|\[1\-9\]\[0\-9\]\+\)\?\$",
regex_str)
if match:
anchor_char = match.group(1)
return '^' + anchor_char + '1$', anchor_char
else:
return None
def perform_replacemenet(self, v):
for repl_args in self.regex_replacements:
if repl_args:
v = re.sub(repl_args[0], repl_args[1], v)
return v
def description(self):
# Separate regular values from regular expressions
enum_vals = []
enum_regexs = []
for v, regex in zip(self.values, self.val_regexs):
if regex is not None:
enum_regexs.append(regex.pattern)
else:
enum_vals.append(v)
desc = """\
The '{plotly_name}' property is an enumeration that may be specified as:""".format(plotly_name=self.plotly_name)
if enum_vals:
enum_vals_str = '\n'.join(textwrap.wrap(repr(enum_vals),
subsequent_indent=' ' * 12,
break_on_hyphens=False))
desc = desc + """
- One of the following enumeration values:
{enum_vals_str}""".format(enum_vals_str=enum_vals_str)
if enum_regexs:
enum_regexs_str = '\n'.join(textwrap.wrap(repr(enum_regexs),
subsequent_indent=' ' * 12,
break_on_hyphens=False))
desc = desc + """
- A string that matches one of the following regular expressions:
{enum_vals_str}""".format(enum_vals_str=enum_regexs_str)
if self.array_ok:
desc = desc + """
- A tuple, list, or one-dimensional numpy array of the above"""
return desc
def in_values(self, e):
is_str = isinstance(e, str)
for v, regex in zip(self.values, self.val_regexs):
if is_str and regex:
in_values = regex.fullmatch(e) is not None
else:
in_values = e == v
if in_values:
return True
return False
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
v = [self.perform_replacemenet(v_el) for v_el in v]
invalid_els = [e for e in v if (not self.in_values(e))]
if invalid_els:
self.raise_invalid_elements(invalid_els)
v = copy_to_contiguous_readonly_numpy_array(v)
else:
v = self.perform_replacemenet(v)
if not self.in_values(v):
self.raise_invalid_val(v)
return v
class BooleanValidator(BaseValidator):
"""
"boolean": {
"description": "A boolean (true/false) value.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
},
"""
def __init__(self, plotly_name, parent_name, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
def description(self):
return ("""\
The '{plotly_name}' property must be specified as a bool (either True, or False)"""
.format(plotly_name=self.plotly_name))
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif not isinstance(v, bool):
self.raise_invalid_val(v)
return v
class NumberValidator(BaseValidator):
"""
"number": {
"description": "A number or a numeric value (e.g. a number inside a string). When applicable, values greater (less) than `max` (`min`) are coerced to the `dflt`.",
"requiredOpts": [],
"otherOpts": [
"dflt",
"min",
"max",
"arrayOk"
]
},
"""
def __init__(self, plotly_name, parent_name,
min=None, max=None, array_ok=False, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
# Handle min
if min is None and max is not None:
# Max was specified, so make min -inf
self.min_val = -np.inf
else:
self.min_val = min
# Handle max
if max is None and min is not None:
# Min was specified, so make min inf
self.max_val = np.inf
else:
self.max_val = max
self.array_ok = array_ok
def description(self):
desc = """\
The '{plotly_name}' property is a number and may be specified as:""".format(plotly_name=self.plotly_name)
if self.min_val is None and self.max_val is None:
desc = desc + """
- An int or float"""
else:
desc = desc + """
- An int or float in the interval [{min_val}, {max_val}]""".format(
min_val=self.min_val,
max_val=self.max_val)
if self.array_ok:
desc = desc + """
- A tuple, list, or one-dimensional numpy array of the above"""
return desc
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
try:
v_array = copy_to_contiguous_readonly_numpy_array(v, force_numeric=True)
except ValueError as ve:
self.raise_invalid_val(v)
v_valid = np.ones(v_array.shape, dtype='bool')
if self.min_val is not None:
v_valid = np.logical_and(v_valid, v_array >= self.min_val)
if self.max_val is not None:
v_valid = np.logical_and(v_valid, v_array <= self.max_val)
if not np.all(v_valid):
# Grab up to the first 10 invalid values
some_invalid_els = np.array(v, dtype='object')[np.logical_not(v_valid)][:10].tolist()
self.raise_invalid_elements(some_invalid_els)
v = v_array # Always numpy array of float64
else:
if not isinstance(v, numbers.Number):
self.raise_invalid_val(v)
if (self.min_val is not None and not v >= self.min_val) or \
(self.max_val is not None and not v <= self.max_val):
self.raise_invalid_val(v)
return v
class IntegerValidator(BaseValidator):
"""
"integer": {
"description": "An integer or an integer inside a string. When applicable, values greater (less) than `max` (`min`) are coerced to the `dflt`.",
"requiredOpts": [],
"otherOpts": [
"dflt",
"min",
"max",
"arrayOk"
]
},
"""
def __init__(self, plotly_name, parent_name,
min=None, max=None, array_ok=False, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
# Handle min
if min is None and max is not None:
# Max was specified, so make min -inf
self.min_val = np.iinfo(np.int32).min
else:
self.min_val = min
# Handle max
if max is None and min is not None:
# Min was specified, so make min inf
self.max_val = np.iinfo(np.int32).max
else:
self.max_val = max
self.array_ok = array_ok
def description(self):
desc = """\
The '{plotly_name}' property is a integer and may be specified as:""".format(plotly_name=self.plotly_name)
if self.min_val is None and self.max_val is None:
desc = desc + """
- An int (or float that will be cast to an int)"""
else:
desc = desc + """
- An int (or float that will be cast to an int) in the interval [{min_val}, {max_val}]""".format(
min_val=self.min_val,
max_val=self.max_val)
if self.array_ok:
desc = desc + """
- A tuple, list, or one-dimensional numpy array of the above"""
return desc
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
try:
v_array = copy_to_contiguous_readonly_numpy_array(v, dtype='int32')
except (ValueError, TypeError, OverflowError) as ve:
self.raise_invalid_val(v)
v_valid = np.ones(v_array.shape, dtype='bool')
if self.min_val is not None:
v_valid = np.logical_and(v_valid, v_array >= self.min_val)
if self.max_val is not None:
v_valid = np.logical_and(v_valid, v_array <= self.max_val)
if not np.all(v_valid):
invalid_els = np.array(v, dtype='object')[np.logical_not(v_valid)][:10].tolist()
self.raise_invalid_elements(invalid_els)
v = v_array
else:
try:
if not isinstance(v, numbers.Number):
# don't let int() cast strings to ints
self.raise_invalid_val(v)
v_int = int(v)
except (ValueError, TypeError, OverflowError) as ve:
self.raise_invalid_val(v)
if (self.min_val is not None and not v >= self.min_val) or \
(self.max_val is not None and not v <= self.max_val):
self.raise_invalid_val(v)
v = v_int
return v
class StringValidator(BaseValidator):
"""
"string": {
"description": "A string value. Numbers are converted to strings except for attributes with `strict` set to true.",
"requiredOpts": [],
"otherOpts": [
"dflt",
"noBlank",
"strict",
"arrayOk",
"values"
]
},
"""
def __init__(self, plotly_name, parent_name,
no_blank=False, strict=False, array_ok=False, values=None,
**kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
self.no_blank = no_blank
self.strict = strict # Not implemented. We're always strict
self.array_ok = array_ok
self.values = values
def description(self):
desc = """\
The '{plotly_name}' property is a string and must be specified as:""".format(plotly_name=self.plotly_name)
if self.no_blank:
desc = desc + """
- A non-empty string"""
elif self.values:
valid_str = '\n'.join(textwrap.wrap(repr(self.values),
subsequent_indent=' ' * 12,
break_on_hyphens=False))
desc = desc + """
- One of the following strings:
{valid_str}""".format(valid_str=valid_str)
else:
desc = desc + """
- A string"""
if self.array_ok:
desc = desc + """
- A tuple, list, or one-dimensional numpy array of the above"""
return desc
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
# Make sure all elements are strings. Is there a more efficient way to do this in numpy?
invalid_els = [e for e in v if not isinstance(e, str)]
if invalid_els:
self.raise_invalid_elements(invalid_els)
v = copy_to_contiguous_readonly_numpy_array(v, dtype='unicode')
if self.no_blank:
invalid_els = v[v == ''][:10].tolist()
if invalid_els:
self.raise_invalid_elements(invalid_els)
if self.values:
invalid_els = v[np.logical_not(np.isin(v, self.values))][:10].tolist()
if invalid_els:
self.raise_invalid_elements(invalid_els)
else:
if not isinstance(v, str):
self.raise_invalid_val(v)
if self.no_blank and len(v) == 0:
self.raise_invalid_val(v)
if self.values and v not in self.values:
self.raise_invalid_val(v)
return v
class ColorValidator(BaseValidator):
"""
"color": {
"description": "A string describing color. Supported formats: - hex (e.g. '#d3d3d3') - rgb (e.g. 'rgb(255, 0, 0)') - rgba (e.g. 'rgb(255, 0, 0, 0.5)') - hsl (e.g. 'hsl(0, 100%, 50%)') - hsv (e.g. 'hsv(0, 100%, 100%)') - named colors (full list: http://www.w3.org/TR/css3-color/#svg-color)",
"requiredOpts": [],
"otherOpts": [
"dflt",
"arrayOk"
]
},
"""
re_hex = re.compile('#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})')
re_rgb_etc = re.compile('(rgb|hsl|hsv)a?\([\d.]+%?(,[\d.]+%?){2,3}\)')
named_colors = [
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond",
"blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
"cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgrey", "darkgreen",
"darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon",
"darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink",
"deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia",
"gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink",
"indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue",
"lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgrey", "lightgreen", "lightpink",
"lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue",
"lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue",
"mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
"mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace",
"olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise",
"palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown",
"royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
"slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato",
"turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen"]
def __init__(self, plotly_name, parent_name,
array_ok=False, colorscale_path=None, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
self.colorscale_path = colorscale_path
self.array_ok = array_ok
def numbers_allowed(self):
return self.colorscale_path is not None
def description(self):
named_clrs_str = '\n'.join(textwrap.wrap(', '.join(
self.named_colors), width=79, subsequent_indent=' ' * 12))
valid_color_description = """\
The '{plotly_name}' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
{clrs}""".format(
plotly_name=self.plotly_name,
clrs=named_clrs_str)
if self.colorscale_path:
valid_color_description = valid_color_description + """
- A number that will be interpreted as a color according to {colorscale_path}""".format(
colorscale_path=self.colorscale_path)
if self.array_ok:
valid_color_description = valid_color_description + """
- A list or array of any of the above"""
return valid_color_description
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
v_array = copy_to_contiguous_readonly_numpy_array(v)
if self.numbers_allowed() and v_array.dtype.kind in ['u', 'i', 'f']: # (un)signed int or float
# All good
v = v_array
else:
validated_v = [ColorValidator.perform_validate_coerce(e, allow_number=self.numbers_allowed())
for e in v]
invalid_els = [el for el, validated_el in zip(v, validated_v) if validated_el is None]
if invalid_els:
self.raise_invalid_elements(invalid_els)
# ### Check that elements have valid colors types ###
if self.numbers_allowed():
v = copy_to_contiguous_readonly_numpy_array(validated_v, dtype='object')
else:
v = copy_to_contiguous_readonly_numpy_array(validated_v, dtype='unicode')
else:
# Validate scalar color
validated_v = ColorValidator.perform_validate_coerce(v, allow_number=self.numbers_allowed())
if validated_v is None:
self.raise_invalid_val(v)
v = validated_v
return v
@staticmethod
def perform_validate_coerce(v, allow_number=None):
if isinstance(v, numbers.Number) and allow_number:
# If allow_numbers then any number is ok
return v
elif not isinstance(v, str):
return None
else:
# Remove spaces so regexes don't need to bother with them.
v = v.replace(' ', '')
v = v.lower()
if ColorValidator.re_hex.fullmatch(v):
# valid hex color (e.g. #f34ab3)
return v
elif ColorValidator.re_rgb_etc.fullmatch(v):
# Valid rgb(a), hsl(a), hsv(a) color (e.g. rgba(10, 234, 200, 50%)
return v
elif v in ColorValidator.named_colors:
# Valid named color (e.g. 'coral')
return v
else:
# Not a valid color
return None
class ColorlistValidator(BaseValidator):
"""
"colorlist": {
"description": "A list of colors. Must be an {array} containing valid colors.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
}
"""
def __init__(self, plotly_name, parent_name, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
def description(self):
return ("""\
The '{plotly_name}' property is a colorlist that may be specified as a tuple, list,
or one-dimensional numpy array of valid color strings""".format(plotly_name=self.plotly_name))
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif is_array(v):
validated_v = [ColorValidator.perform_validate_coerce(e, allow_number=False) for e in v]
invalid_els = [el for el, validated_el in zip(v, validated_v) if validated_el is None]
if invalid_els:
self.raise_invalid_elements(invalid_els)
v = copy_to_contiguous_readonly_numpy_array(validated_v, dtype='unicode')
else:
self.raise_invalid_val(v)
return v
class ColorscaleValidator(BaseValidator):
"""
"colorscale": {
"description": "A Plotly colorscale either picked by a name: (any of Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis ) customized as an {array} of 2-element {arrays} where the first element is the normalized color level value (starting at *0* and ending at *1*), and the second item is a valid color string.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
},
"""
named_colorscales = ['Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds', 'Blues', 'Picnic',
'Rainbow', 'Portland', 'Jet', 'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis']
def __init__(self, plotly_name, parent_name, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
def description(self):
desc = """\
The '{plotly_name}' property is a colorscale and may be specified as:
- A list of 2-element lists where the first element is the normalized color level value
(starting at 0 and ending at 1), and the second item is a valid color string.
(e.g. [[0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds', 'Blues', 'Picnic',
'Rainbow', 'Portland', 'Jet', 'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis']
""".format(plotly_name=self.plotly_name)
return desc
def validate_coerce(self, v):
v_valid = False
if v is None:
# Pass None through
pass
if v is None:
v_valid = True
elif isinstance(v, str):
v_match = [el for el in ColorscaleValidator.named_colorscales if el.lower() == v.lower()]
if v_match:
v_valid = True
v = v_match[0]
elif is_array(v) and len(v) > 0:
invalid_els = [e for e in v
if not is_array(e) or
len(e) != 2 or
not isinstance(e[0], numbers.Number) or
not (0 <= e[0] <= 1) or
not isinstance(e[1], str) or
ColorValidator.perform_validate_coerce(e[1]) is None]
if len(invalid_els) == 0:
v_valid = True
# Convert to tuple of tuples so colorscale is immutable
v = tuple([tuple([e[0], ColorValidator.perform_validate_coerce(e[1])]) for e in v])
if not v_valid:
self.raise_invalid_val(v)
return v
class AngleValidator(BaseValidator):
"""
"angle": {
"description": "A number (in degree) between -180 and 180.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
},
"""
def __init__(self, plotly_name, parent_name, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
def description(self):
desc = """\
The '{plotly_name}' property is a angle (in degrees) that may be specified as a number between -180 and 180.
Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90).
""".format(plotly_name=self.plotly_name)
return desc
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif not isinstance(v, numbers.Number):
self.raise_invalid_val(v)
else:
# Normalize v onto the interval [-180, 180)
v = (v + 180) % 360 - 180
return v
class SubplotidValidator(BaseValidator):
"""
"subplotid": {
"description": "An id string of a subplot type (given by dflt), optionally followed by an integer >1. e.g. if dflt='geo', we can have 'geo', 'geo2', 'geo3', ...",
"requiredOpts": [
"dflt"
],
"otherOpts": []
},
"""
def __init__(self, plotly_name, parent_name, dflt, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
self.base = dflt
self.regex = dflt + "(\d*)"
def description(self):
desc = """\
The '{plotly_name}' property is an identifier of a particular subplot, of type '{base}', that
may be specified as the string '{base}' optionally followed by an integer >= 1
(e.g. '{base}', '{base}1', '{base}2', '{base}3', etc.)
""".format(plotly_name=self.plotly_name, base=self.base)
return desc
def validate_coerce(self, v):
if v is None:
pass
elif not isinstance(v, str):
self.raise_invalid_val(v)
else:
match = re.fullmatch(self.regex, v)
if not match:
is_valid = False
else:
digit_str = match.group(1)
if len(digit_str) > 0 and int(digit_str) == 0:
is_valid = False
elif len(digit_str) > 0 and int(digit_str) == 1:
# Remove 1 suffix (e.g. x1 -> x)
v = self.base
is_valid = True
else:
is_valid = True
if not is_valid:
self.raise_invalid_val(v)
return v
class FlaglistValidator(BaseValidator):
"""
"flaglist": {
"description": "A string representing a combination of flags (order does not matter here). Combine any of the available `flags` with *+*. (e.g. ('lines+markers')). Values in `extras` cannot be combined.",
"requiredOpts": [
"flags"
],
"otherOpts": [
"dflt",
"extras",
"arrayOk"
]
},
"""
def __init__(self, plotly_name, parent_name, flags,
extras=None, array_ok=False, **kwargs):
super().__init__(plotly_name=plotly_name,
parent_name=parent_name, **kwargs)
self.flags = flags
self.extras = extras if extras is not None else []
self.array_ok = array_ok
self.all_flags = self.flags + self.extras
def description(self):
desc = ("""\
The '{plotly_name}' property is a flaglist and may be specified as a string containing:"""
).format(plotly_name=self.plotly_name)
# Flags
desc = desc + ("""
- Any combination of {flags} joined with '+' characters (e.g. '{eg_flag}')"""
).format(flags=self.flags,
eg_flag='+'.join(self.flags[:2]))
# Extras
if self.extras:
desc = desc + ("""
OR exactly one of {extras} (e.g. '{eg_extra}')"""
).format(extras=self.extras,
eg_extra=self.extras[-1])
if self.array_ok:
desc = desc + """
- A list or array of the above"""
return desc
def perform_validate_coerce(self, v):
if not isinstance(v, str):
return None
split_vals = [e.strip() for e in re.split('[,+]', v)]
all_flags_valid = [f for f in split_vals if f not in self.all_flags] == []
has_extras = [f for f in split_vals if f in self.extras] != []
is_valid = all_flags_valid and (not has_extras or len(split_vals) == 1)
if is_valid:
return '+'.join(split_vals)
else:
return None
def validate_coerce(self, v):
if v is None:
# Pass None through
pass
elif self.array_ok and is_array(v):
validated_v = [self.perform_validate_coerce(e) for e in v] # Coerce individual strings
invalid_els = [el for el, validated_el in zip(v, validated_v) if validated_el is None]
if invalid_els:
self.raise_invalid_elements(invalid_els)
v = copy_to_contiguous_readonly_numpy_array(validated_v, dtype='unicode')
else:
validated_v = self.perform_validate_coerce(v)
if validated_v is None:
self.raise_invalid_val(v)
v = validated_v
return v