/
schema.py
612 lines (541 loc) · 19 KB
/
schema.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
from collections import defaultdict
from marshmallow import (
Schema,
fields,
validate,
validates_schema,
ValidationError as MarshmallowValidationError,
)
from paramtools import contrib
from paramtools import utils
class RangeSchema(Schema):
"""
Schema for range object
{
"range": {"min": field, "max": field}
}
"""
_min = fields.Field(attribute="min", data_key="min")
_max = fields.Field(attribute="max", data_key="max")
level = fields.String(validate=[validate.OneOf(["warn", "error"])])
class ChoiceSchema(Schema):
choices = fields.List(fields.Field)
level = fields.String(validate=[validate.OneOf(["warn", "error"])])
class ValueValidatorSchema(Schema):
"""
Schema for validation specification for each parameter value
"""
_range = fields.Nested(
RangeSchema(), attribute="range", data_key="range", required=False
)
date_range = fields.Nested(RangeSchema(), required=False)
choice = fields.Nested(ChoiceSchema(), required=False)
when = fields.Nested("WhenSchema", required=False)
class IsSchema(Schema):
equal_to = fields.Field(required=False)
greater_than = fields.Field(required=False)
less_than = fields.Field(required=False)
@validates_schema
def just_one(self, data, **kwargs):
if len(data.keys()) > 1:
raise MarshmallowValidationError(
f"Only one condition may be specified for the 'is' field. "
f"You specified {len(data.keys())}."
)
def _deserialize(self, data, **kwargs):
if data is not None and not isinstance(data, dict):
data = {"equal_to": data}
return super()._deserialize(data, **kwargs)
class WhenSchema(Schema):
param = fields.Str()
_is = fields.Nested(
IsSchema(), attribute="is", data_key="is", required=False
)
then = fields.Nested(ValueValidatorSchema())
otherwise = fields.Nested(ValueValidatorSchema())
class BaseParamSchema(Schema):
"""
Defines a base parameter schema. This specifies the required fields and
their types.
{
"title": str,
"description": str,
"notes": str,
"type": str (limited to 'int', 'float', 'bool', 'str'),
"value": `BaseValidatorSchema`, "value" type depends on "type" key,
"range": range schema ({"min": ..., "max": ..., "other ops": ...}),
}
This class is defined further by a JSON file indicating extra fields that
are required by the implementer of the schema.
"""
title = fields.Str(required=True)
description = fields.Str(required=True)
notes = fields.Str(required=False)
_type = fields.Str(
required=True,
validate=validate.OneOf(
choices=["str", "float", "int", "bool", "date"]
),
attribute="type",
data_key="type",
)
number_dims = fields.Integer(required=False, missing=0)
value = fields.Field(required=True) # will be specified later
validators = fields.Nested(
ValueValidatorSchema(), required=False, missing={}
)
indexed = fields.Boolean(required=False)
class EmptySchema(Schema):
"""
An empty schema that is used as a base class for creating other classes via
the `type` function
"""
pass
class OrderedSchema(Schema):
"""
Same as `EmptySchema`, but preserves the order of its fields.
"""
class Meta:
ordered = True
class ValueObject(fields.Nested):
"""
Schema for value objects
"""
def _deserialize(
self, value, attr, data, partial=None, many=False, **kwargs
):
if not isinstance(value, list) or (
isinstance(value, list)
and value
and not isinstance(value[0], dict)
):
value = [{"value": value}]
return super()._deserialize(
value, attr, data, partial=partial, many=many, **kwargs
)
class BaseValidatorSchema(Schema):
"""
Schema that validates parameter adjustments such as:
```
{
"STD": [{
"year": 2017,
"MARS": "single",
"value": "3000"
}]
}
```
Information defined for each variable on the `BaseParamSchema` is utilized
to define this class and how it should validate its data. See
`build_schema.SchemaBuilder` for how parameters are defined onto this
class.
"""
class Meta:
ordered = True
WRAPPER_MAP = {
"range": "_get_range_validator",
"date_range": "_get_range_validator",
"choice": "_get_choice_validator",
"when": "_get_when_validator",
}
def load(self, data, ignore_warnings):
self.ignore_warnings = ignore_warnings
try:
return super().load(data)
finally:
self.ignore_warnings = False
@validates_schema
def validate_params(self, data, **kwargs):
"""
Loop over all parameters defined on this class. Validate them using
the `self.validate_param`. Errors are stored until all
parameters have been validated. Note that all data has been
type-validated. These methods only do range validation.
"""
warnings = defaultdict(dict)
errors = defaultdict(dict)
for name, specs in data.items():
for i, spec in enumerate(specs):
_warnings, _errors = self.validate_param(name, spec, data)
if _warnings:
warnings[name][i] = {"value": _warnings}
if _errors:
errors[name][i] = {"value": _errors}
if warnings and not self.ignore_warnings:
errors["warnings"] = warnings
if errors:
ve = MarshmallowValidationError(dict(errors))
raise ve
def validate_param(self, param_name, param_spec, raw_data):
"""
Do range validation for a parameter.
"""
param_info = self.context["spec"]._data[param_name]
# sort keys to guarantee order.
validator_spec = param_info["validators"]
validators = []
for vname, vdata in validator_spec.items():
validator = getattr(self, self.WRAPPER_MAP[vname])(
vname, vdata, param_name, param_spec, raw_data
)
validators.append(validator)
warnings = []
errors = []
for validator in validators:
try:
validator(param_spec, is_value_object=True)
except contrib.validate.ValidationError as ve:
if ve.level == "warn":
warnings += ve.messages
else:
errors += ve.messages
return warnings, errors
def _get_when_validator(
self,
vname,
when_dict,
param_name,
param_spec,
raw_data,
ndim_restriction=False,
):
when_param = when_dict["param"]
if (
when_param not in self.context["spec"]._data.keys()
and when_param != "default"
):
raise MarshmallowValidationError(
f"'{when_param}' is not a specified parameter."
)
oth_param, when_vos = self._resolve_op_value(
when_param, param_name, param_spec, raw_data
)
then_validators = []
for vname, vdata in when_dict["then"].items():
then_validators.append(
getattr(self, self.WRAPPER_MAP[vname])(
vname,
vdata,
param_name,
param_spec,
raw_data,
ndim_restriction=True,
)
)
otherwise_validators = []
for vname, vdata in when_dict["otherwise"].items():
otherwise_validators.append(
getattr(self, self.WRAPPER_MAP[vname])(
vname,
vdata,
param_name,
param_spec,
raw_data,
ndim_restriction=True,
)
)
_type = self.context["spec"]._data[oth_param]["type"]
number_dims = self.context["spec"]._data[oth_param]["number_dims"]
error_then = (
f"When {oth_param}{{when_labels}}{{ix}} is {{is_val}}, "
f"{param_name}{{labels}}{{ix}} value is invalid: {{submsg}}"
)
error_otherwise = (
f"When {oth_param}{{when_labels}}{{ix}} is not {{is_val}}, "
f"{param_name}{{labels}}{{ix}} value is invalid: {{submsg}}"
)
return contrib.validate.When(
when_dict["is"],
when_vos,
then_validators,
otherwise_validators,
error_then,
error_otherwise,
_type,
number_dims,
)
def _get_range_validator(
self,
vname,
range_dict,
param_name,
param_spec,
raw_data,
ndim_restriction=False,
):
if vname == "range":
range_class = contrib.validate.Range
elif vname == "date_range":
range_class = contrib.validate.DateRange
else:
raise MarshmallowValidationError(
f"{vname} is not an allowed validator."
)
min_value = range_dict.get("min", None)
if min_value is not None:
min_oth_param, min_vos = self._resolve_op_value(
min_value, param_name, param_spec, raw_data
)
else:
min_oth_param, min_vos = None, []
max_value = range_dict.get("max", None)
if max_value is not None:
max_oth_param, max_vos = self._resolve_op_value(
max_value, param_name, param_spec, raw_data
)
else:
max_oth_param, max_vos = None, []
self._check_ndim_restriction(
param_name,
min_oth_param,
max_oth_param,
ndim_restriction=ndim_restriction,
)
min_vos = self._sort_by_label_to_extend(min_vos)
max_vos = self._sort_by_label_to_extend(max_vos)
error_min = f"{param_name}{{labels}} {{input}} < min {{min}} {min_oth_param}{{oth_labels}}"
error_max = f"{param_name}{{labels}} {{input}} > max {{max}} {max_oth_param}{{oth_labels}}"
return range_class(
min_vo=min_vos,
max_vo=max_vos,
error_min=error_min,
error_max=error_max,
level=range_dict.get("level"),
)
def _sort_by_label_to_extend(self, vos):
label_to_extend = self.context["spec"].label_to_extend
if label_to_extend is not None:
label_grid = self.context["spec"]._stateless_label_grid
extend_vals = label_grid[label_to_extend]
return sorted(
vos,
key=lambda vo: (
extend_vals.index(vo[label_to_extend])
if label_to_extend in vo
and vo[label_to_extend] in extend_vals
else 9e99
),
)
else:
return vos
def _get_choice_validator(
self,
vname,
choice_dict,
param_name,
param_spec,
raw_data,
ndim_restriction=False,
):
choices = choice_dict["choices"]
labels = utils.make_label_str(param_spec)
label_suffix = f" for labels {labels}" if labels else ""
if len(choices) < 20:
error_template = (
'{param_name} "{input}" must be in list of choices '
"{choices}{label_suffix}."
)
else:
error_template = '{param_name} "{input}" must be in list of choices{label_suffix}.'
error = error_template.format(
param_name=param_name,
labels=labels,
input="{input}",
choices="{choices}",
label_suffix=label_suffix,
)
return contrib.validate.OneOf(
choices, error=error, level=choice_dict.get("level")
)
def _resolve_op_value(self, op_value, param_name, param_spec, raw_data):
"""
Operator values (`op_value`) are the values pointed to by the "min"
and "max" keys. These can be values to compare against, another
variable to compare against, or the default value of the adjusted
variable.
"""
if op_value in self.fields or op_value == "default":
return self._get_comparable_value(
op_value, param_name, param_spec, raw_data
)
return "", [{"value": op_value}]
def _get_comparable_value(
self, oth_param_name, param_name, param_spec, raw_data
):
"""
Get the value that the adjusted variable will be compared against.
Candidates are:
- the parameter's own default value if "default" is specified
- a reference variable's value
- first, look in the raw adjustment data
- second, look in the defaults data
"""
if oth_param_name in raw_data:
vals = raw_data[oth_param_name]
else:
# If comparing against the "default" value then get the current
# value of the parameter being updated.
if oth_param_name == "default":
oth_param = self.context["spec"]._data[param_name]
else:
oth_param = self.context["spec"]._data[oth_param_name]
vals = oth_param["value"]
labs_to_check = {k for k in param_spec if k != "value"}
if labs_to_check:
res = [
val
for val in vals
if all(val[k] == param_spec[k] for k in labs_to_check)
]
else:
res = vals
return oth_param_name, res
def _check_ndim_restriction(
self, param_name, *other_params, ndim_restriction=False
):
"""
Test restriction on validator's concerning references to other
parameters with number of dimensions >= 1.
"""
if ndim_restriction and any(other_params):
for other_param in other_params:
if other_param is None:
continue
if other_param == "default":
ndims = self.context["spec"]._data[param_name][
"number_dims"
]
else:
ndims = self.context["spec"]._data[other_param][
"number_dims"
]
if ndims > 0:
raise contrib.validate.ValidationError(
f"{param_name} is validated against {other_param} in an invalid context."
)
class LabelSchema(Schema):
_type = fields.Str(
required=True,
validate=validate.OneOf(
choices=["str", "float", "int", "bool", "date"]
),
attribute="type",
data_key="type",
)
number_dims = fields.Integer(required=False, missing=0)
validators = fields.Nested(
ValueValidatorSchema(), required=False, missing={}
)
class AdditionalMembersSchema(Schema):
_type = fields.Str(
required=True,
validate=validate.OneOf(
choices=["str", "float", "int", "bool", "date"]
),
attribute="type",
data_key="type",
)
number_dims = fields.Integer(required=False, missing=0)
class OperatorsSchema(Schema):
array_first = fields.Bool(required=False)
label_to_extend = fields.Str(required=False, allow_none=True)
uses_extend_func = fields.Bool(required=False)
class ParamToolsSchema(Schema):
labels = fields.Dict(
keys=fields.Str(),
values=fields.Nested(LabelSchema()),
required=False,
missing={},
)
additional_members = fields.Dict(
keys=fields.Str(),
values=fields.Nested(AdditionalMembersSchema()),
required=False,
missing={},
)
operators = fields.Nested(OperatorsSchema, required=False)
# A few fields that have not been instantiated yet
CLASS_FIELD_MAP = {
"str": contrib.fields.Str,
"int": contrib.fields.Integer,
"float": contrib.fields.Float,
"bool": contrib.fields.Boolean,
"date": contrib.fields.Date,
}
INVALID_NUMBER = {"invalid": "Not a valid number: {input}."}
INVALID_BOOLEAN = {"invalid": "Not a valid boolean: {input}."}
INVALID_DATE = {"invalid": "Not a valid date: {input}."}
# A few fields that have been instantiated
FIELD_MAP = {
"str": contrib.fields.Str(allow_none=True),
"int": contrib.fields.Integer(
allow_none=True, error_messages=INVALID_NUMBER
),
"float": contrib.fields.Float(
allow_none=True, error_messages=INVALID_NUMBER
),
"bool": contrib.fields.Boolean(
allow_none=True, error_messages=INVALID_BOOLEAN
),
"date": contrib.fields.Date(allow_none=True, error_messages=INVALID_DATE),
}
VALIDATOR_MAP = {
"range": contrib.validate.Range,
"date_range": contrib.validate.DateRange,
"choice": contrib.validate.OneOf,
}
def get_type(data):
numeric_types = {
"int": contrib.fields.Int64(
allow_none=True, error_messages=INVALID_NUMBER
),
"bool": contrib.fields.Bool_(
allow_none=True, error_messages=INVALID_BOOLEAN
),
"float": contrib.fields.Float64(
allow_none=True, error_messages=INVALID_NUMBER
),
}
types = dict(FIELD_MAP, **numeric_types)
fieldtype = types[data["type"]]
dim = data.get("number_dims", 0)
while dim > 0:
np_type = getattr(fieldtype, "np_type", object)
fieldtype = fields.List(fieldtype, allow_none=True)
fieldtype.np_type = np_type
dim -= 1
return fieldtype
def get_param_schema(base_spec, field_map=None):
"""
Read in data from the initializing schema. This will be used to fill in the
optional properties on classes derived from the `BaseParamSchema` class.
This data is also used to build validators for schema for each parameter
that will be set on the `BaseValidatorSchema` class
"""
if field_map is not None:
field_map = dict(FIELD_MAP, **field_map)
else:
field_map = FIELD_MAP.copy()
optional_fields = {}
for k, v in base_spec["additional_members"].items():
fieldtype = field_map[v["type"]]
if v.get("number_dims", 0) > 0:
d = v["number_dims"]
while d > 0:
fieldtype = fields.List(fieldtype)
d -= 1
optional_fields[k] = fieldtype
ParamSchema = type(
"ParamSchema",
(BaseParamSchema,),
{k: v for k, v in optional_fields.items()},
)
label_validators = {}
for name, label in base_spec["labels"].items():
validators = []
for vname, kwargs in label["validators"].items():
validator_class = VALIDATOR_MAP[vname]
validators.append(validator_class(**kwargs))
fieldtype = CLASS_FIELD_MAP[label["type"]]
label_validators[name] = fieldtype(validate=validators)
return ParamSchema, label_validators