-
Notifications
You must be signed in to change notification settings - Fork 240
/
options_dictionary.py
475 lines (402 loc) · 16.1 KB
/
options_dictionary.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
"""Define the OptionsDictionary class."""
from openmdao.warnings import warn_deprecation
from openmdao.core.constants import _UNDEFINED
#
# Template for `check_valid` function
#
def check_valid(name, value):
"""
Check the validity of value for the option with name.
Parameters
----------
name : str
name of the option
value : any
value for the option
Raises
------
ValueError
if value is not valid for option
"""
raise ValueError(f"Option '{name}' with value {value} is not valid.")
class OptionsDictionary(object):
"""
Dictionary with pre-declaration of keys for value-checking and default values.
This class is instantiated for:
1. the options attribute in solvers, drivers, and processor allocators
2. the supports attribute in drivers
3. the options attribute in systems
Attributes
----------
_dict : dict of dict
Dictionary of entries. Each entry is a dictionary consisting of value, values,
types, desc, lower, and upper.
_parent_name : str or None
If defined, prepend this name to beginning of all exceptions.
_read_only : bool
If True, no options can be set after declaration.
_all_recordable : bool
Flag to determine if all options in UserOptions are recordable.
_deprecation_warning_issued : list
Option names that are deprecated and a warning has been issued for their use.
"""
def __init__(self, parent_name=None, read_only=False):
"""
Initialize all attributes.
Parameters
----------
parent_name : str
Name or class name of System that owns this OptionsDictionary
read_only : bool
If True, setting (via __setitem__ or update) is not permitted.
"""
self._dict = {}
self._parent_name = parent_name
self._read_only = read_only
self._all_recordable = True
self._deprecation_warning_issued = []
def __getstate__(self):
"""
Return state as a dict.
Returns
-------
dict
State to get.
"""
if self._all_recordable:
return self.__dict__
else:
state = self.__dict__.copy()
state['_dict'] = {key: val for key, val in state['_dict'].items() if val['recordable']}
return state
def __repr__(self):
"""
Return a dictionary representation of the options.
Returns
-------
dict
The options dictionary.
"""
return self._dict.__repr__()
def __rst__(self):
"""
Generate reStructuredText view of the options table.
Returns
-------
list of str
A rendition of the options as an rST table.
"""
lines = self.to_table(fmt='rst').split('\n')
return lines
def to_table(self, fmt='github', missingval='N/A'):
"""
Get a table representation of this OptionsDictionary as a table in the requested format.
Parameters
----------
fmt : str
The formatting of the requested table. Options are the same as those available
to the tabulate package. See tabulate.tabulate_formats for a complete list.
Default value of 'github' produces a table in GitHub-flavored markdown.
missingval : str
The value to be displayed in place of None.
Returns
-------
str
A string representation of the table in the requested format.
"""
try:
from tabulate import tabulate
except ImportError as e:
msg = "'to_table' requires the tabulate package but it is not currently installed." \
" Use `pip install tablulate` or install openmdao with" \
" `pip install openmdao[notebooks]`."
raise ImportError(msg)
tlist = [['Option', 'Default', 'Acceptable Values', 'Acceptable Types', 'Description']]
for key in sorted(self._dict.keys()):
options = self._dict[key]
default = options['value'] if options['value'] is not _UNDEFINED else '**Required**'
# if the default is an object instance, replace with the (unqualified) object type
default_str = str(default)
idx = default_str.find(' object at ')
if idx >= 0 and default_str[0] == '<':
parts = default_str[:idx].split('.')
default = parts[-1]
acceptable_values = options['values']
if acceptable_values is not None:
if not isinstance(acceptable_values, (set, tuple, list)):
acceptable_values = (acceptable_values,)
acceptable_values = [value for value in acceptable_values]
acceptable_types = options['types']
if acceptable_types is not None:
if not isinstance(acceptable_types, (set, tuple, list)):
acceptable_types = (acceptable_types,)
acceptable_types = [type_.__name__ for type_ in acceptable_types]
desc = options['desc']
tlist.append([key, default, acceptable_values, acceptable_types, desc])
return tabulate(tlist, headers='firstrow', tablefmt=fmt, missingval=missingval)
def __str__(self, width=100):
"""
Generate text string representation of the options table.
Parameters
----------
width : int
The maximum width of the text.
Returns
-------
str
A text representation of the options table.
"""
rst = self.to_table(fmt='rst').split('\n')
cols = [len(header) for header in rst[0].split()]
desc_col = sum(cols[:-1]) + 2 * (len(cols) - 1)
desc_len = width - desc_col
# if it won't fit in allowed width, just return the rST
if desc_len < 10:
return '\n'.join(rst)
text = []
for row in rst:
if len(row) > width:
text.append(row[:width])
if not row.startswith('==='):
row = row[width:].rstrip()
while(len(row) > 0):
text.append(' ' * desc_col + row[:desc_len])
row = row[desc_len:]
else:
text.append(row)
return '\n'.join(text)
def _raise(self, msg, exc_type=RuntimeError):
"""
Raise the given exception type, with parent's name prepended to the message.
Parameters
----------
msg : str
The error message.
exc_type : class
The type of the exception to be raised.
"""
if self._parent_name is None:
full_msg = msg
else:
full_msg = '{}: {}'.format(self._parent_name, msg)
raise exc_type(full_msg)
def _assert_valid(self, name, value):
"""
Check whether the given value is valid, where the key has already been declared.
The optional checks consist of ensuring: the value is one of a list of acceptable values,
the type of value is one of a list of acceptable types, value is not less than lower,
value is not greater than upper, and value satisfies check_valid.
Parameters
----------
name : str
The key for the declared option.
value : object
The default or user-set value to check for value, type, lower, and upper.
"""
meta = self._dict[name]
values = meta['values']
types = meta['types']
lower = meta['lower']
upper = meta['upper']
if not (value is None and meta['allow_none']):
# If only values is declared
if values is not None:
if value not in values:
if isinstance(value, str):
value = "'{}'".format(value)
self._raise("Value ({}) of option '{}' is not one of {}.".format(value, name,
values),
ValueError)
# If only types is declared
elif types is not None:
if not isinstance(value, types):
vtype = type(value).__name__
if isinstance(value, str):
value = "'{}'".format(value)
if isinstance(types, (set, tuple, list)):
typs = tuple([type_.__name__ for type_ in types])
self._raise("Value ({}) of option '{}' has type '{}', but one of "
"types {} was expected.".format(value, name, vtype, typs),
exc_type=TypeError)
else:
self._raise("Value ({}) of option '{}' has type '{}', but type '{}' "
"was expected.".format(value, name, vtype, types.__name__),
exc_type=TypeError)
if upper is not None:
if value > upper:
self._raise("Value ({}) of option '{}' "
"exceeds maximum allowed value of {}.".format(value, name, upper),
exc_type=ValueError)
if lower is not None:
if value < lower:
self._raise("Value ({}) of option '{}' "
"is less than minimum allowed value of {}.".format(value, name,
lower),
exc_type=ValueError)
# General function test
if meta['check_valid'] is not None:
meta['check_valid'](name, value)
def declare(self, name, default=_UNDEFINED, values=None, types=None, desc='',
upper=None, lower=None, check_valid=None, allow_none=False, recordable=True,
deprecation=None):
r"""
Declare an option.
The value of the option must satisfy the following:
1. If values only was given when declaring, value must be in values.
2. If types only was given when declaring, value must satisfy isinstance(value, types).
3. It is an error if both values and types are given.
Parameters
----------
name : str
Name of the option.
default : object or Null
Optional default value that must be valid under the above 3 conditions.
values : set or list or tuple or None
Optional list of acceptable option values.
types : type or tuple of types or None
Optional type or list of acceptable option types.
desc : str
Optional description of the option.
upper : float or None
Maximum allowable value.
lower : float or None
Minimum allowable value.
check_valid : function or None
User-supplied function with arguments (name, value) that raises an exception
if the value is not valid.
allow_none : bool
If True, allow None as a value regardless of values or types.
recordable : bool
If True, add to recorder
deprecation : str or None
If None, it is not deprecated. If a str, use as a DeprecationWarning
during __setitem__ and __getitem__
"""
if values is not None and not isinstance(values, (set, list, tuple)):
self._raise("In declaration of option '%s', the 'values' arg must be of type None,"
" list, or tuple - not %s." % (name, values), exc_type=TypeError)
if types is not None and not isinstance(types, (type, set, list, tuple)):
self._raise("In declaration of option '%s', the 'types' arg must be None, a type "
"or a tuple - not %s." % (name, types), exc_type=TypeError)
if types is not None and values is not None:
self._raise("'types' and 'values' were both specified for option '%s'." % name)
if types is bool:
values = (True, False)
if not recordable:
self._all_recordable = False
default_provided = default is not _UNDEFINED
if default_provided and default is None:
# specifying default=None implies allow_none
allow_none = True
self._dict[name] = {
'value': default,
'values': values,
'types': types,
'desc': desc,
'upper': upper,
'lower': lower,
'check_valid': check_valid,
'has_been_set': default_provided,
'allow_none': allow_none,
'recordable': recordable,
'deprecation': deprecation,
}
# If a default is given, check for validity
if default_provided:
self._assert_valid(name, default)
def undeclare(self, name):
"""
Remove entry from the OptionsDictionary, for classes that don't use that option.
Parameters
----------
name : str
The name of a key, the entry of which will be removed from the internal dictionary.
"""
if name in self._dict:
del self._dict[name]
def update(self, in_dict):
"""
Update the internal dictionary with the given one.
Parameters
----------
in_dict : dict
The incoming dictionary to add to the internal one.
"""
for name in in_dict:
self[name] = in_dict[name]
def __iter__(self):
"""
Provide an iterator.
Returns
-------
iterable
iterator over the keys in the dictionary.
"""
return iter(self._dict)
def __contains__(self, key):
"""
Check if the key is in the local dictionary.
Parameters
----------
key : str
name of the option.
Returns
-------
boolean
whether key is in the local dict.
"""
return key in self._dict
def __setitem__(self, name, value):
"""
Set an option in the local dictionary.
Parameters
----------
name : str
name of the option.
value : -
value of the option to be value- and type-checked if declared.
"""
try:
meta = self._dict[name]
except KeyError:
# The key must have been declared.
msg = "Option '{}' cannot be set because it has not been declared."
self._raise(msg.format(name), exc_type=KeyError)
if meta['deprecation'] is not None and name not in self._deprecation_warning_issued:
warn_deprecation(meta['deprecation'])
self._deprecation_warning_issued.append(name)
if self._read_only:
self._raise("Tried to set read-only option '{}'.".format(name), exc_type=KeyError)
self._assert_valid(name, value)
meta['value'] = value
meta['has_been_set'] = True
def __getitem__(self, name):
"""
Get an option from the dict or declared default.
Parameters
----------
name : str
name of the option.
Returns
-------
value : -
value of the option.
"""
# If the option has been set in this system, return the set value
try:
meta = self._dict[name]
if meta['deprecation'] is not None and name not in self._deprecation_warning_issued:
warn_deprecation(meta['deprecation'])
self._deprecation_warning_issued.append(name)
if meta['has_been_set']:
return meta['value']
else:
self._raise("Option '{}' is required but has not been set.".format(name))
except KeyError:
self._raise("Option '{}' cannot be found".format(name), exc_type=KeyError)
def items(self):
"""
Yield name and value of options.
"""
for key, val in self._dict.items():
yield key, val['value']