Exemplo n.º 1
0
    def test_assert_no_duplicates(self):
        # Signature: name(lst, error_func=None)
                # Check for duplicates in a sequence.
                #
                # This function checks that a list contains no duplicates, by casting the list
                # to a set and comparing the lengths.
                #
                # It raises an `NineMLRuntimeError` if the lengths are not equal.

        from nineml.utility import assert_no_duplicates
        from nineml.exceptions import NineMLRuntimeError

        # Duplication
        self.assertRaises(
            NineMLRuntimeError,
            assert_no_duplicates, [1, 2, 3, 4, 4],
        )

        self.assertRaises(
            NineMLRuntimeError,
            assert_no_duplicates, ['1', '2', '3', '4', '4'],
        )

        assert_no_duplicates([1, 2, 3, 4])
        assert_no_duplicates(['1', '2', '3', '4'])

        assert_no_duplicates([None])
        assert_no_duplicates([True])
        assert_no_duplicates([()])
Exemplo n.º 2
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 = 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()
        ensure_valid_c_variable_name(self._name)

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

        td_types = (basestring, TimeDerivative)
        td_type_dict = 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]
        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 = normalise_parameter_as_list(transitions)
        f_dict = 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)
Exemplo n.º 3
0
    def _resolve_transition_regime_names(self):
        # Check that the names of the regimes are unique:
        names = [r.name for r in self.regimes]
        assert_no_duplicates(names)

        # Create a map of regime names to regimes:
        regime_map = dict([(r.name, r) for r in self.regimes])

        # We only worry about 'target' regimes, since source regimes are taken
        # care of for us by the Regime objects they are attached to.
        for trans in self.transitions:
            if not trans.target_regime_name in regime_map:
                errmsg = "Can't find regime: %s" % trans.target_regime_name
                raise NineMLRuntimeError(errmsg)
            trans.set_target_regime(regime_map[trans.target_regime_name])
Exemplo n.º 4
0
 def action_componentclass(self, componentclass, namespace):  # @UnusedVariable @IgnorePep8
     regime_names = [r.name for r in componentclass.regimes]
     assert_no_duplicates(regime_names)
Exemplo n.º 5
0
 def action_regime(self, regime, namespace, **kwargs):  # @UnusedVariable
     event_triggers = [on_event.src_port_name
                       for on_event in regime.on_events]
     assert_no_duplicates(event_triggers)
Exemplo n.º 6
0
 def __init__(self, component):
     ComponentValidatorPerNamespace.__init__(self,
                                   explicitly_require_action_overrides=True)
     self.all_objects = list()
     self.visit(component)
     assert_no_duplicates(self.all_objects)
Exemplo n.º 7
0
    def __init__(self, name, parameters=None, analog_ports=[],
                 event_ports=[],
                 dynamics=None, subnodes=None,
                 portconnections=None, regimes=None,
                 aliases=None, state_variables=None):
        """Constructs a ComponentClass

        :param name: The name of the component.
        :param parameters: A list containing either |Parameter| objects
            or strings representing the parameter names. If ``None``, then the
            parameters are automatically inferred from the |Dynamics| block.
        :param analog_ports: A list of |AnalogPorts|, which will be the
            local |AnalogPorts| for this object.
        :param event_ports: A list of |EventPorts| objects, which will be the
            local event-ports for this object. If this is ``None``, then they
            will be automatically inferred from the dynamics block.
        :param dynamics: A |Dynamics| object, defining the local dynamics of
                         the component.
        :param subnodes: A dictionary mapping namespace-names to sub-component.
            [Type: ``{string:|ComponentClass|, string:|ComponentClass|,
            string:|ComponentClass|}`` ] describing the namespace of
            subcomponents for this component.
        :param portconnections: A list of pairs, specifying the connections
            between the ports of the subcomponents in this component. These can
            be `(|NamespaceAddress|, |NamespaceAddress|)' or ``(string,
            string)``.
        :param interface: A shorthand way of specifying the **interface** for
            this component; |Parameters|, |AnalogPorts| and |EventPorts|.
            ``interface`` takes a list of these objects, and automatically
            resolves them by type into the correct types.

        Examples:

        >>> a = ComponentClass(name='MyComponent1')

        .. todo::

            Point this towards and example of constructing ComponentClasses.
            This can't be here, because we also need to know about dynamics.
            For examples

        """
        BaseComponentClass.__init__(self, name, parameters)
        # We can specify in the componentclass, and they will get forwarded to
        # the dynamics class. We check that we do not specify half-and-half:
        if dynamics is not None:
            if regimes or aliases or state_variables:
                err = "Either specify a 'dynamics' parameter, or "
                err += "state_variables /regimes/aliases, but not both!"
                raise NineMLRuntimeError(err)

        else:
            # We should always create a dynamics object, even is it is empty. FIXME: TGC 11/11/14, Why? @IgnorePep8
            dynamics = dyn.Dynamics(regimes=regimes,
                                    aliases=aliases,
                                    state_variables=state_variables)
        self._query = componentqueryer.ComponentQueryer(self)

        # Ensure analog_ports is a list not an iterator
        analog_ports = list(analog_ports)
        event_ports = list(event_ports)

        # Check there aren't any duplicates in the port and parameter names
        assert_no_duplicates(p if isinstance(p, basestring) else p.name
                             for p in chain(parameters if parameters else [],
                                            analog_ports,
                                            event_ports))

        analog_receive_ports = [port for port in analog_ports
                                if isinstance(port, AnalogReceivePort)]
        analog_reduce_ports = [port for port in analog_ports
                               if isinstance(port, AnalogReducePort)]
        incoming_port_names = [p.name for p in chain(analog_receive_ports,
                                                     analog_reduce_ports)]
        # EventPort, StateVariable and Parameter Inference:
        inferred_struct = InterfaceInferer(dynamics, incoming_port_names)
        inf_check = lambda l1, l2, desc: check_list_contain_same_items(
            l1, l2, desc1='Declared', desc2='Inferred', ignore=['t'],
            desc=desc)

        # Check any supplied parameters match:
        if parameters is not None:
            inf_check(self._parameters.keys(),
                      inferred_struct.parameter_names,
                      'Parameters')
        else:
            self._parameters = dict((n, Parameter(n))
                                    for n in inferred_struct.parameter_names)

        # Check any supplied state_variables match:
        if dynamics._state_variables:
            state_var_names = [p.name for p in dynamics.state_variables]
            inf_check(state_var_names,
                      inferred_struct.state_variable_names,
                      'StateVariables')
        else:
            state_vars = dict((n, StateVariable(n)) for n in
                              inferred_struct.state_variable_names)
            dynamics._state_variables = state_vars

        # Check Event Receive Ports Match:
        event_receive_ports = [port for port in event_ports
                               if isinstance(port, EventReceivePort)]
        event_send_ports = [port for port in event_ports
                            if isinstance(port, EventSendPort)]
        if event_receive_ports:
            # FIXME: not all OutputEvents are necessarily exposed as Ports,
            # so really we should just check that all declared output event
            # ports are in the list of inferred ports, not that the declared
            # list is identical to the inferred one.
            inf_check([p.name for p in event_receive_ports],
                      inferred_struct.input_event_port_names,
                      'Event Ports In')

        # Check Event Send Ports Match:
        if event_send_ports:
            inf_check([p.name for p in event_send_ports],
                      inferred_struct.output_event_port_names,
                      'Event Ports Out')
        else:
            event_ports = []
            # Event ports not supplied, so lets use the inferred ones.
            for evt_port_name in inferred_struct.input_event_port_names:
                event_ports.append(EventReceivePort(name=evt_port_name))
            for evt_port_name in inferred_struct.output_event_port_names:
                event_ports.append(EventSendPort(name=evt_port_name))

        # Construct super-classes:
        ComponentClassMixinFlatStructure.__init__(
            self, analog_ports=analog_ports, event_ports=event_ports,
            dynamics=dynamics)
        ComponentClassMixinNamespaceStructure.__init__(
            self, subnodes=subnodes, portconnections=portconnections)

        # Finalise initiation:
        self._resolve_transition_regime_names()

        # Store flattening Information:
        self._flattener = None

        # Is the finished component valid?:
        self._validate_self()
Exemplo n.º 8
0
 def action_componentclass(self, componentclass, namespace):
     regime_names = [r.name for r in componentclass.regimes]
     assert_no_duplicates(regime_names)