scitools.PrmDictBase

Module for managing parameters.

class scitools.PrmDictBase.PrmDictBase[source]

Bases: object

Base class for managing parameters stored in dictionaries. Typical use includes data or solver classes for solving physical problems numerically. One may then choose to hold all physical parameters in a dictionary physical_prm, containing (parameter name, value) pairs, and all numerical parameters in a dictionary numerical_prm. The physical_prm and numerical_prm dictionaries can then be defined in a subclass of PrmDictBase and managed by PrmDictBase. The management includes several convenient features:

  • keeping all input data in one place
  • setting of one or more parameters where the type of the value must match the type of the previous (initial) value
  • pretty print of all defined parameters
  • copying parameters from dictionaries to, e.g., local variables and back again, or to local namespaces and back again
  • easy transition from parameter dictionaries to more sophisticated handling of input data, e.g., class scitools.ParameterInterface (GUI, CGI, command-line args)

The subclass typically defines the dictionaries, say self.physical_prm and self.numerical_prm. Then these are appended to the inherited self._prm_list list to be registered. All members of this list are dictionaries that will not accept new keys (i.e., all parameters must be defined prior to registering them in self._prm_list). With this list one has a collection of all parameter dictionaries in the application.

self._type_check[prm] is defined if we want to type check a parameter prm. if self._type_check[prm] is True (or False), prm must either be None, of the same type as the previously registered value of prm, or any number (float, int, complex) if the previous value prm was any number. Instead of a boolean value, self._type_check[prm] may hold a tuple of class types (to be used in isinstance checks), or a function which takes the value as argument and returns True if the that value is of the right type (otherwise False).

In addition to the parameter dictionaries with fixed keys, class PrmDictBase also holds a self.user_prm, which is a dictionary of “meta data”, i.e., an arbitrary set of keys and values that can arbitrarily extended anywhere. If self.user_prm is None, no such meta data can exists (implying that only parameters registered in the dictionaries in self._prm_list are allowed - the programmer of subclasses can of course extend these parameter sets whenever desired; disallowing a parameter name is only a feature of the set function for setting the value of a (registered) parameter).

Here is an example:

from scitools.PrmDictBase import PrmDictBase

class SomeSolver(PrmDictBase):
    def __init__(self, **kwargs):
        PrmDictBase.__init__(self)
        # register parameters in dictionaries:
        self.physical_prm = {'density': 1.0, 'Cp': 1.0,
                                   'k': 1.0, 'L': 1.0}
        self.numerical_prm =  {'n': 10, 'dt': 0.1, 'tstop': 3}

        # attach dictionaries to base class list (required):
        self._prm_list = [self.physical_prm, self.numerical_prm]

        # specify parameters to be type checked when set:
        self._type_check.update({'n': True, 'dt': (float,),
              'k': lambda k: isinstance(int,float) and k>0})

        # disallow arbitrary meta data
        self.user_prm = None # set to {} if meta data are allowed

        # initialize parameters according to keyword arguments:
        self.set(**kwargs)

    def _update(self):
        # dt depends on n, L, k; update dt in case the three
        # others parameters have been changed
        # (in general this method is used to check consistency
        # between parameters and perform updates if necessary)
        n = self.numerical_prm['n']
        L = self.physical_prm['L']
        k = self.physical_prm['k']

        self.u = zeros(n+1, Float)
        h = L/float(n)
        dt_limit = h**2/(2*k)
        if self.numerical_prm['dt'] > dt_limit:
            self.numerical_prm['dt'] = dt_limit

    def compute1(self):
        # compute something
        return self.physical_prm['k']/self.physical_prm['Cp']

    def compute2(self):
        # turn numerical parameters into local variables:
        exec self.dicts2variables(self._prm_list)
        # or exec self.dicts2variables(self.numerical_prm)  # selected prms

        # now we have local variables n, dt, tstop, density, Cp, k, L
        # that we can compute with, say

        Q = k/Cp
        dt = 0.9*dt

        # if some of the local variables are changed, say dt, they must
        # be inserted back into the parameter dictionaries:
        self.variables2dicts(self.numerical_prm, dt=dt)    

Methods

dicts2namespace(namespace, dicts[, overwrite]) Make namespace variables out of dict items.
dicts2namespace2(namespace, dicts) As dicts2namespace2, but use exec.
dicts2variables(dicts) Make Python code string that defines local variables from
dump() Dump all parameters and their values.
get(**kwargs)
namespace2dicts(namespace, dicts) Update dicts from variables in a namespace.
properties(global_namespace) Make properties out of local dictionaries.
set(**kwargs) Set kwargs data in parameter dictionaries.
set_in_dict(prm, value, d) Set d[prm]=value, but check if prm is registered in class
usage() Print the name of all parameters that can be set.
variables2dicts(dicts, **variables) Insert the name=value keyword arguments in variables into the dictionaries in dicts (list of dictionaries).
__class__

alias of type

__delattr__

x.__delattr__(‘name’) <==> del x.name

__dict__ = dict_proxy({'__module__': 'scitools.PrmDictBase', 'set': <function set at 0x861b8c0>, 'dump': <function dump at 0x861b848>, 'get': <function get at 0x861ba28>, 'dicts2namespace': <function dicts2namespace at 0x861bb18>, '__dict__': <attribute '__dict__' of 'PrmDictBase' objects>, '__weakref__': <attribute '__weakref__' of 'PrmDictBase' objects>, 'properties': <function properties at 0x861baa0>, '__init__': <function __init__ at 0x861b2a8>, 'set_in_dict': <function set_in_dict at 0x861b938>, '_prm_dict_names': <function _prm_dict_names at 0x861b758>, 'dicts2variables': <function dicts2variables at 0x861bc80>, 'dicts2namespace2': <function dicts2namespace2 at 0x861bb90>, 'usage': <function usage at 0x861b7d0>, 'variables2dicts': <function variables2dicts at 0x861bcf8>, 'namespace2dicts': <function namespace2dicts at 0x861bc08>, '_update': <function _update at 0x861b9b0>, '__doc__': '\nBase class for managing parameters stored in dictionaries.\nTypical use includes data or solver classes for solving physical\nproblems numerically. One may then choose to hold all physical\nparameters in a dictionary physical_prm, containing\n(parameter name, value) pairs, and all numerical parameters in\na dictionary numerical_prm. The physical_prm and numerical_prm\ndictionaries can then be defined in a subclass of PrmDictBase\nand managed by PrmDictBase. The management includes several\nconvenient features:\n\n - keeping all input data in one place\n - setting of one or more parameters where the type of the value\n must match the type of the previous (initial) value\n - pretty print of all defined parameters\n - copying parameters from dictionaries to, e.g., local variables\n and back again, or to local namespaces and back again\n - easy transition from parameter dictionaries to more sophisticated\n handling of input data, e.g., class scitools.ParameterInterface\n (GUI, CGI, command-line args)\n\nThe subclass typically defines the dictionaries, say\nself.physical_prm and self.numerical_prm. Then these are\nappended to the inherited self._prm_list list to be registered.\nAll members of this list are dictionaries that will not accept\nnew keys (i.e., all parameters must be defined prior to registering\nthem in self._prm_list). With this list one has a collection of all\nparameter dictionaries in the application.\n\nself._type_check[prm] is defined if we want to type check\na parameter prm.\nif self._type_check[prm] is True (or False), prm must either\nbe None, of the same type as the previously registered\nvalue of prm, or any number (float, int, complex) if\nthe previous value prm was any number. Instead of a boolean\nvalue, self._type_check[prm] may hold a tuple of class types\n(to be used in isinstance checks), or a function which takes\nthe value as argument and returns True if the that value is\nof the right type (otherwise False).\n\n\nIn addition to the parameter dictionaries with fixed keys, class\nPrmDictBase also holds a self.user_prm, which is a dictionary\nof "meta data", i.e., an arbitrary set of keys and values that\ncan arbitrarily extended anywhere. If self.user_prm is None,\nno such meta data can exists (implying that only parameters\nregistered in the dictionaries in self._prm_list are allowed - the\nprogrammer of subclasses can of course extend these parameter\nsets whenever desired; disallowing a parameter name is only a\nfeature of the set function for setting the value of a (registered)\nparameter).\n\nHere is an example::\n\n from scitools.PrmDictBase import PrmDictBase\n\n class SomeSolver(PrmDictBase):\n def __init__(self, **kwargs):\n PrmDictBase.__init__(self)\n # register parameters in dictionaries:\n self.physical_prm = {\'density\': 1.0, \'Cp\': 1.0,\n \'k\': 1.0, \'L\': 1.0}\n self.numerical_prm = {\'n\': 10, \'dt\': 0.1, \'tstop\': 3}\n\n # attach dictionaries to base class list (required):\n self._prm_list = [self.physical_prm, self.numerical_prm]\n\n # specify parameters to be type checked when set:\n self._type_check.update({\'n\': True, \'dt\': (float,),\n \'k\': lambda k: isinstance(int,float) and k>0})\n\n # disallow arbitrary meta data\n self.user_prm = None # set to {} if meta data are allowed\n\n # initialize parameters according to keyword arguments:\n self.set(**kwargs)\n\n\n def _update(self):\n # dt depends on n, L, k; update dt in case the three\n # others parameters have been changed\n # (in general this method is used to check consistency\n # between parameters and perform updates if necessary)\n n = self.numerical_prm[\'n\']\n L = self.physical_prm[\'L\']\n k = self.physical_prm[\'k\']\n\n self.u = zeros(n+1, Float)\n h = L/float(n)\n dt_limit = h**2/(2*k)\n if self.numerical_prm[\'dt\'] > dt_limit:\n self.numerical_prm[\'dt\'] = dt_limit\n\n def compute1(self):\n # compute something\n return self.physical_prm[\'k\']/self.physical_prm[\'Cp\']\n\n def compute2(self):\n # turn numerical parameters into local variables:\n exec self.dicts2variables(self._prm_list)\n # or exec self.dicts2variables(self.numerical_prm) # selected prms\n\n # now we have local variables n, dt, tstop, density, Cp, k, L\n # that we can compute with, say\n\n Q = k/Cp\n dt = 0.9*dt\n\n # if some of the local variables are changed, say dt, they must\n # be inserted back into the parameter dictionaries:\n self.variables2dicts(self.numerical_prm, dt=dt) \n\n '})
__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__hash__() <==> hash(x)
__init__()[source]
__module__ = 'scitools.PrmDictBase'
static __new__(S, ...) → a new object with type S, a subtype of T
__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__() <==> repr(x)
__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__sizeof__() → int

size of object in memory, in bytes

__str__() <==> str(x)
static __subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

dicts2namespace(namespace, dicts, overwrite=True)[source]

Make namespace variables out of dict items. That is, for all dicts, insert all (key,value) pairs in the namespace dict. namespace is a dictionary, dicts is a list of dictionaries.

dicts2namespace2(namespace, dicts)[source]

As dicts2namespace2, but use exec.

dicts2variables(dicts)[source]

Make Python code string that defines local variables from all parameters in dicts (list of dictionaries of parameters). For example, if dicts[1] has a key n with value 1.0, the statement ‘n=1.0’ will be included in the returned string. The calling code will typically exec this returned string to make local variables (short hands) from parameters stored in dictionaries. (Note that such local variables are read-only, changing their values will not be reflected in the dictionaries!).

dump()[source]

Dump all parameters and their values.

get(**kwargs)[source]
namespace2dicts(namespace, dicts)[source]

Update dicts from variables in a namespace. That is, for all keys in namespace, insert (key,value) pair in the dict in dicts that has the same key registered. namespace is a dictionary, dicts is a list of dictionaries.

properties(global_namespace)[source]

Make properties out of local dictionaries.

set(**kwargs)[source]

Set kwargs data in parameter dictionaries.

set_in_dict(prm, value, d)[source]

Set d[prm]=value, but check if prm is registered in class dictionaries, if the type is acceptable, etc.

usage()[source]

Print the name of all parameters that can be set.

variables2dicts(dicts, **variables)[source]

Insert the name=value keyword arguments in variables into the dictionaries in dicts (list of dictionaries). This is the inverse of the dicts2variables function.

Usage: exec self.dicts2variables(self.numerical_prm) # work with read-only n, dt, tstop ... # update (in case n, dt, tstop was changed): self.variables2dicts(self.numerical_prm, n=n, dt=dt, tstop=tstop)

scitools.PrmDictBase.message(m)[source]

This Page