Exemple #1
0
def expr_to_obj(s, name=None):
    """ Construct nineml objects from expressions """
    from util import StrToExpr

    # import re

    # Is our job already done?
    if isinstance(s, (RegimeElement)):
        return s

    # strip surrounding whitespace
    s = s.strip()

    # Do we have a alias?
    if StrToExpr.is_alias(s):
        return StrToExpr.alias(s)

    # re for an expression -> groups into lhs, op, rhs
    p_eqn = re.compile(
        r"(?P<lhs>[a-zA-Z_]+[a-zA-Z_0-9]*(/?[a-zA-Z_]+[a-zA-Z_0-9]*)?)\s*(?P<op>[+\-*/:]?=)\s*(?P<rhs>.*)")
    m = p_eqn.match(s)
    if not m:
        raise ValueError, "Not a valid nineml expression: %s" % s

    # get lhs, op, rhs
    lhs, op, rhs = [m.group(x) for x in ['lhs', 'op', 'rhs']]

    # do we have an TimeDerivative?
    # re for lhs for TimeDerivative
    p_ode_lhs = re.compile(r"(?:d)([a-zA-Z_]+[a-zA-Z_0-9]*)/(?:d)([a-zA-Z_]+[a-zA-Z_0-9]*)")
    m = p_ode_lhs.match(lhs)
    if m:
        if op != "=":
            raise ValueError, "TimeDerivative lhs, but op not '=' in %s" % s

        dep_var = m.group(1)
        indep_var = m.group(2)
        return TimeDerivative(dep_var, indep_var, rhs, name=name)

    # Do we have an Inplace op?
    # if op in Inplace.op_name_map.keys():
    #    return Inplace(lhs,op,rhs, name = name)

    # Do we have an assignment?
    if op == "=":
        return StateAssignment(lhs, rhs, name=name)

    # If we get here, what do we have?
    raise ValueError, "Cannot map expr '%s' to a nineml Expression" % s
Exemple #2
0
    def __init__(self, regimes=None, aliases=None, state_variables=None):
        """Dynamics object constructor

           :param aliases: A list of aliases, which must be either |Alias|
               objects or ``string``s.
           :param regimes: A list containing at least one |Regime| object.
           :param state_variables: An optional list of the state variables,
                which can either be |StateVariable| objects or `string` s. If
                provided, it must match the inferred state-variables from the
                regimes; if it is not provided it will be inferred
                automatically.
        """

        aliases = nineml.utility.normalise_parameter_as_list(aliases)
        regimes = nineml.utility.normalise_parameter_as_list(regimes)
        state_variables = nineml.utility.normalise_parameter_as_list(state_variables)

        # Load the aliases as objects or strings:
        from nineml.utility import filter_discrete_types
        alias_td = filter_discrete_types(aliases, (basestring, Alias))
        aliases_from_strs = [StrToExpr.alias(o) for o in alias_td[basestring]]
        aliases = alias_td[Alias] + aliases_from_strs

        # Load the state variables as objects or strings:
        sv_types = (basestring, StateVariable)
        sv_td = filter_discrete_types(state_variables, sv_types)
        sv_from_strings = [StateVariable(o) for o in sv_td[basestring]]
        state_variables = sv_td[StateVariable] + sv_from_strings

        self._regimes = regimes
        self._aliases = aliases
        self._state_variables = state_variables
Exemple #3
0
    def __init__(self, *args, **kwargs):
        """Regime constructor

            :param name: The name of the constructor. If none, then a name will
                be automatically generated.
            :param time_derivatives: A list of time derivatives, as
                either ``string``s (e.g 'dg/dt = g/gtau') or as |TimeDerivative|
                objects.
            :param transitions: A list containing either |OnEvent| or
                |OnCondition| objects, which will automatically be sorted into
                the appropriate classes automatically.
            :param *args: Any non-keyword arguments will be treated as
                time_derivatives.


        """
        valid_kwargs = ('name', 'transitions', 'time_derivatives')
        for arg in kwargs:
            if not arg in valid_kwargs:
                err = 'Unexpected Arg: %s' % arg
                raise NineMLRuntimeError(err)

        transitions = kwargs.get('transitions', None)
        name = kwargs.get('name', None)
        kw_tds = nineml.utility.normalise_parameter_as_list(kwargs.get('time_derivatives', None))
        time_derivatives = list(args) + kw_tds

        # Generate a name for unnamed regions:
        self._name = name.strip() if name else Regime.get_next_name()
        nineml.utility.ensure_valid_c_variable_name(self._name)

        # Un-named arguments are time_derivatives:
        time_derivatives = nineml.utility.normalise_parameter_as_list(time_derivatives)
        # time_derivatives.extend( args )

        td_types = (basestring, TimeDerivative)
        td_type_dict = nineml.utility.filter_discrete_types(time_derivatives, td_types)
        td_from_str = [StrToExpr.time_derivative(o) for o in td_type_dict[basestring]]
        self._time_derivatives = td_type_dict[TimeDerivative] + td_from_str

        # Check for double definitions:
        td_dep_vars = [td.dependent_variable for td in self._time_derivatives]
        nineml.utility.assert_no_duplicates(td_dep_vars)

        # We support passing in 'transitions', which is a list of both OnEvents
        # and OnConditions. So, lets filter this by type and add them
        # appropriately:
        transitions = nineml.utility.normalise_parameter_as_list(transitions)
        f_dict = nineml.utility.filter_discrete_types(transitions, (OnEvent, OnCondition))
        self._on_events = []
        self._on_conditions = []

        # Add all the OnEvents and OnConditions:
        for event in f_dict[OnEvent]:
            self.add_on_event(event)
        for condition in f_dict[OnCondition]:
            self.add_on_condition(condition)
Exemple #4
0
def do_to_assignments_and_events(doList):
    if not doList:
        return [], []
    # 'doList' is a list of strings, OutputEvents, and StateAssignments.
    do_type_list = (OutputEvent, basestring, StateAssignment)
    do_types = nineml.utility.filter_discrete_types(doList, do_type_list)

    # Convert strings to StateAssignments:
    sa_from_strs = [StrToExpr.state_assignment(s) for s in do_types[basestring]]

    return do_types[StateAssignment] + sa_from_strs, do_types[OutputEvent]
Exemple #5
0
    def __init__(self, state_assignments=None, event_outputs=None,
                 target_regime_name=None):
        """Abstract class representing a transition from one |Regime| to
        another.

        |Transition| objects are not created directly, but via the subclasses
        |OnEvent| and |OnCondition|.

        :param state_assignments: A list of the state-assignments performed
            when this transition occurs. Objects in this list are either
            `string` (e.g A = A+13) or |StateAssignment| objects.
        :param event_outputs: A list of |OutputEvent| objects emitted when
            this transition occurs.
        :param target_regime_name: The name of the regime to go into after this
            transition.  ``None`` implies staying in the same regime. This has
            to be specified as a string, not the object, because in general the
            |Regime| object is not yet constructed. This is automatically
            resolved by the |ComponentClass| in
            ``_ResolveTransitionRegimeNames()`` during construction.


        .. todo::

            For more information about what happens at a regime transition, see
            here: XXXXXXX

        """
        if target_regime_name:
            assert isinstance(target_regime_name, basestring)

        # Load state-assignment objects as strings or StateAssignment objects
        from nineml.utility import filter_discrete_types
        state_assignments = state_assignments or []

        sa_types = (basestring, StateAssignment)
        sa_type_dict = filter_discrete_types(state_assignments, sa_types)
        sa_from_str = [StrToExpr.state_assignment(o) for o in sa_type_dict[basestring]]
        self._state_assignments = sa_type_dict[StateAssignment] + sa_from_str

        self._event_outputs = event_outputs or []

        self._target_regime_name = target_regime_name
        self._source_regime_name = None

        # Set later, once attached to a regime:
        self._target_regime = None
        self._source_regime = None