#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Scattering models (:mod:`hydrac.model.model`)
=============================================
.. autoclass:: Model
:members:
:private-members:
"""
from hydrac.util import constants
from hydrac.util.parameters import Parameters
from hydrac.util.paramcontainer import ParamContainer
import glob
[docs]class Model:
"""
Base class for model generation.
Contains methods to look up for preset models saved previously in xml files
(:func:`_set_model_presets`) or update the same xml file with new
model parameter definition dedicated to another application
(:func:`_update_model_presets`) given the user input model name of
interest.
"""
def __init__(self, name=None, default=None):
self.model_presets = self._set_model_presets()
self.param = Parameters({})
if name is None:
self.name = input('If you whish to use a model from library,' +
'choose among the present list :' +
str(list(self.model_presets.keys())))
else:
self.name = name
self.name_select(self.name)
self._default = default
if self.name in self.model_presets.keys():
self._descrip = self.name
self._default = 1
self.mtype = self.model_presets[self.name].mtype
self.nature = self.model_presets[self.name].nature
self.shape = self.model_presets[self.name].shape
self._preset = 1
else:
self._preset = 0
self._descrip = ''
[docs] def name_select(self, m):
"""
Prompts the user for a name if none is specified
"""
if not m:
self.name = input('Please name the model you want to generate : ')
if not self.name:
self.name_select(self.name)
else:
return
return
[docs] def _set_model_presets(self):
"""
If the model name is in the preset xml file along with the associated
parameters, those are loaded in the Model object
"""
rr = glob.glob(constants.dir_models_presets + '*.xml')
rr.sort()
try:
m = Parameters(ParamContainer(path_file=rr[-1]))
except(IndexError, AttributeError):
m = Parameters({})
return m
[docs] def _update_model_presets(self, a, b=None, remove_elem=False):
"""
Either saves the current parameters input by the user under the chosen
model name in the xml file, or deletes the parameters from a specific
model name in the xml file.
Parameters
----------
a : str
Nalme of the model to be saved in the xml
b = None : dict
Parameters to be saved under the name a in the xml
remove_elem=False : bool
Remove specified parameters saved under the name a in the xml file
"""
if remove_elem is False:
rr = glob.glob(constants.dir_models_presets + '*.xml')
rr.sort()
uiui = ParamContainer(path_file=rr[-1])
uiui._set_child(a, b)
uiui._save_as_xml(path_file=constants.dir_models_presets +
'models_presets.xml',
find_new_name=False, overwrite=True)
else:
rr = glob.glob(constants.dir_models_presets + '*.xml')
rr.sort()
uiui = Parameters(ParamContainer(path_file=rr[-1]))
del uiui[a]
yoyo = ParamContainer(tag='models_presets')
for a, b in uiui.items():
yoyo._set_child(a, b)
yoyo._save_as_xml(path_file=constants.dir_models_presets +
'models_presets.xml',
find_new_name=False, overwrite=True)