-
Notifications
You must be signed in to change notification settings - Fork 32
/
settings.py
440 lines (385 loc) · 13.9 KB
/
settings.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
"""Settings to yield control to the user."""
import os
import six
from six import iteritems
import yaml
from serpentTools import ROOT_DIR
from serpentTools import messages
__all__ = ['defaultSettings', 'rc']
SETTING_HEADER_CHAR = '-'
SETTING_DOC_FMTR = """.. _{tag}:
{header}
``{name}``
{header}
{desc}
::
Default: {default}
Type: {vtype}
{options}
"""
SETTING_OPTIONS_FMTR = "Options: [{}]"
defaultSettings = {
'branching.areUncsPresent': {
'default': False,
'type': bool,
'description': "True if the values in the .coe file contain "
"uncertainties"
},
'branching.intVariables': {
'default': [],
'description': 'Name of state data variables to convert to integers '
'for each branch',
'type': list
},
'branching.floatVariables': {
'default': [],
'description': 'Names of state data variables to convert to floats '
'for each branch',
'type': list
},
'depletion.metadataKeys': {
'default': ['ZAI', 'NAMES', 'DAYS', 'BU'],
'options': 'default',
'description': 'Non-material data to store, i.e. zai, isotope names, '
'burnup schedule, etc.',
'type': list
},
'depletion.materialVariables': {
'default': [],
'description': 'Names of variables to store. '
'Empty list -> all variables.',
'type': list
},
'depletion.materials': {
'default': [],
'description': 'Names of materials to store. '
'Empty list -> all materials.',
'type': list
},
'depletion.processTotal': {
'default': True,
'description': 'Option to store the depletion data from the TOT block',
'type': bool
},
'detector.names': {
'default': [],
'description': 'List of detectors to store. Empty list -> store all '
'detectors',
'type': list
},
'verbosity': {
'default': 'warning',
'options': messages.LOG_OPTS,
'type': str,
'description': 'Set the level of errors to be shown.',
'updater': messages.updateLevel
},
'sampler.allExist': {
'default': True,
'description': 'True if all the files should exist. Suppresses '
'errors if a file does not exist',
'type': bool
},
'sampler.freeAll': {
'default': False,
'description': 'If true, do not retain data from parsers after '
'reading. Limits memory usage after reading',
'type': bool,
},
'sampler.raiseErrors': {
'default': True,
'description': 'If True, stop at the first error. Otherwise, '
'continue reading but make a note about the error',
'type': bool
},
'sampler.skipPrecheck': {
'default': False,
'description': 'If True, no checks are performed prior to preparing '
'data. Set this to be True only if you know all files '
'contain the same data as errors may arise',
'type': bool
},
'serpentVersion': {
'default': '2.1.29',
'options': ['2.1.29'],
'description': 'Version of SERPENT',
'type': str
},
'xs.getInfXS': {
'default': True,
'description': 'If true, store the infinite medium cross sections.',
'type': bool
},
'xs.getB1XS': {
'default': True,
'description': 'If true, store the critical leakage cross sections.',
'type': bool
},
'xs.variableGroups': {
'default': [],
'description': ('Name of variable groups from variables.yaml to be '
'expanded into SERPENT variable to be stored'),
'type': list
},
'xs.variableExtras': {
'default': [],
'description': 'Full SERPENT name of variables to be read',
'type': list
}
}
class DefaultSetting(object):
"""Store a single setting."""
def __init__(self, name, default, varType, description, options, updater):
self.name = name
self.description = description
self.default = default
self.type = varType
self.options = options
self.updater = updater
def __repr__(self):
return '<DefaultSetting {}: value: {}>'.format(self.name, self.default)
def validate(self, value):
"""Return True if the value matches the default scheme.
Parameters
----------
value:
value to be tested
Returns
-------
bool
if the value can be used
Raises
------
TypeError
If the value is of an incorrect type
KeyError
If the value does not correspond to one of the acceptable options
"""
if not isinstance(value, self.type):
raise TypeError('Setting {} should be of type {}, not {}'
.format(self.name, self.type, type(value)))
if self.options:
listVals = [value] if not isinstance(value, list) else value
inOptions = any([val in self.options for val in listVals])
if not inOptions:
opts = ', '.join([str(option) for option in self.options])
raise KeyError('Setting {} is {} and not one of the allowed '
'options: {}'
.format(self.name, value, opts))
return True
class DefaultSettingsLoader(dict):
"""Base class for loading all the default settings."""
def __init__(self):
self.__locked = False
dict.__init__(self, self._load())
self.__locked = True
@staticmethod
def _load():
"""Load the default setting objects."""
defaults = {}
for name, value in iteritems(defaultSettings):
if 'options' in value:
options = (value['default'] if value['options'] == 'default'
else value['options'])
else:
options = None
settingsOptions = {'name': name,
'default': value['default'],
'varType': value['type'],
'options': options,
'description': value['description'],
'updater': value.get('updater', None)
}
defaults[name] = DefaultSetting(**settingsOptions)
return defaults
def __setitem__(self, key, value):
if self.__locked:
raise KeyError('Default settings cannot be updated once set.')
self[key] = value
def retrieveDefaults(self):
"""Return a dictionary with the default settings."""
return {key: setting.default for key, setting in iteritems(self)}
def validateSetting(self, name, value):
"""Validate the setting.
Parameters
----------
name: str
Full name of the setting
value: value to be set
Raises
------
KeyError
If the value is not one of the allowable options or if the
setting does not match an existing setting
TypeError
If the value is not of the correct type
"""
if name not in self:
raise KeyError('Setting {} does not exist'.format(name))
self[name].validate(value)
class UserSettingsLoader(dict):
"""Class that stores the active user settings."""
def __init__(self):
self._defaultLoader = DefaultSettingsLoader()
self.__inside = False
self.__originals = {}
dict.__init__(self, self._defaultLoader.retrieveDefaults())
def __setitem__(self, key, value):
self._checkStoreOriginal(key)
self.setValue(key, value)
def __enter__(self):
self.__inside= True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.__inside__ = False
for key, originalValue in iteritems(self.__originals):
self[key] = originalValue
self.__originals= {}
def _checkStoreOriginal(self, key):
if self.__inside:
self.__originals[key] = self[key]
def setValue(self, name, value):
"""Set the value of a specific setting.
Parameters
----------
name: str
Full name of the setting
value: value to be set
Raises
------
KeyError
If the value is not one of the allowable options or if the
setting does not match an existing setting
TypeError
If the value is not of the correct type
"""
if name not in self:
raise KeyError('Setting {} does not exist'.format(name))
self._defaultLoader[name].validate(value)
# if we've made it here, then the value is valid
if self._defaultLoader[name].updater is not None:
value = self._defaultLoader[name].updater(value)
dict.__setitem__(self, name, value)
messages.debug('Updated setting {} to {}'.format(name, value))
def getReaderSettings(self, settingsPreffix):
"""Get all module-wide and reader-specific settings.
Parameters
----------
settingsPreffix: str or list
Name of the specific reader.
Will look for settings that lead with ``readerName``, e.g.
``depletion.metadataKeys`` or ``xs.variables``
Returns
-------
dict
Single level dictionary with ``settingName: settingValue`` pairs
Raises
------
KeyError
If the reader name is not located in the ``readers`` settings
dictionary
"""
settings = {}
settingsPreffix = (
[settingsPreffix] if isinstance(settingsPreffix, str)
else settingsPreffix)
for setting, value in iteritems(self):
settingPath = setting.split('.')
if settingPath[0] in settingsPreffix:
name = settingPath[1]
else:
continue
settings[name] = value
if not settings:
messages.warning('Could not obtain settings for the following '
'reader names: {}'
.format(', '.join(settingsPreffix)))
return settings
def expandVariables(self):
"""Extend the keyword groups into lists of serpent variables.
Returns
-------
set
Names of all variables to be scraped
"""
keywords = self['xs.variableGroups']
extras = self['xs.variableExtras']
serpentVersion = self['serpentVersion']
if not (keywords or extras): # return empty set and don't read
return set()
variables = set(extras) if extras else set()
if not keywords:
return variables
varFile = os.path.join(ROOT_DIR, 'variables.yaml')
with open(varFile) as fObj:
groups = yaml.load(fObj)
thisVersion = groups[serpentVersion]
baseGroups = groups['base']
for key in keywords:
if key in thisVersion:
variables.update(thisVersion[key])
elif key in baseGroups:
variables.update(baseGroups[key])
return variables
def loadYaml(self, filePath, strict=True):
"""
Update the settings based on the contents of the yaml file
.. versionadded:: 0.2.0
Parameters
----------
filePath: str, or FileType
Path to config file
strict: bool
Fail at the first incorrect setting. If false, failed settings
will not be loaded and alerts will be raised
Raises
------
KeyError or TypeError
If settings found in the config file are not
valid
FileNotFound or OSError
If the file does not exist
"""
messages.debug('Attempting to read from {}'.format(filePath))
with open(filePath) as yFile:
configSettings = yaml.safe_load(yFile)
messages.debug('Loading settings onto object with strict:{}'
.format(strict))
for key, value in iteritems(configSettings):
if isinstance(value, dict):
self.__recursiveLoad(value, strict, key)
else:
self.__safeLoad(key, value, strict)
messages.info('Done')
def __recursiveLoad(self, curLevel, strict, preset):
for nextLevelKey, nextLevel in iteritems(curLevel):
newSettingName = preset + '.' + nextLevelKey
if isinstance(nextLevel, dict):
self.__recursiveLoad(nextLevel, strict, newSettingName)
else:
self.__safeLoad(newSettingName, nextLevel, strict)
def __safeLoad(self, key, value, strict):
messages.debug('Attempting to set setting {} to {}'
.format(key, value))
try:
self.setValue(key, value)
except (KeyError, TypeError) as error:
if strict:
raise error
else:
messages.error(str(error))
def prettyPrint(self):
out = ''
for key in sorted(self._defaultLoader.keys()):
setting = self._defaultLoader[key]
tag = '-'.join(setting.name.split('.'))
header = SETTING_HEADER_CHAR * (4 + len(setting.name))
optStr = (SETTING_OPTIONS_FMTR.format(', '.join(setting.options))
if setting.options else '')
desc = setting.description
out += SETTING_DOC_FMTR.format(
header=header, name=setting.name,
vtype=setting.type.__name__, default=setting.default,
desc=desc, options=optStr, tag=tag)
return out
rc = UserSettingsLoader()