Ejemplo n.º 1
0
    def __init__(self, name, dimension=None):
        """StateVariable Constructor

        :param name:  The name of the state variable.
        """
        super(StateVariable, self).__init__()
        self._name = validate_identifier(name)
        self._dimension = dimension if dimension is not None else dimensionless
        assert isinstance(self._dimension, Dimension)
        validate_identifier(self._name)
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        BaseALObject.__init__(self)
        ContainerObject.__init__(self)
        valid_kwargs = ('name', 'transitions', 'on_events', 'on_conditions',
                        'time_derivatives', 'aliases')
        for arg in kwargs:
            if arg not in valid_kwargs:
                err = 'Unexpected Arg: %s' % arg
                raise NineMLUsageError(err)

        name = kwargs.get('name', None)
        if name is None:
            self._name = 'default'
        else:
            self._name = validate_identifier(name)
            validate_identifier(self._name)

        # Get Time derivatives from args or kwargs
        kw_tds = normalise_parameter_as_list(
            kwargs.get('time_derivatives', None))
        time_derivatives = list(args) + kw_tds
        # 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 = [TimeDerivative.from_str(o)
                       for o in td_type_dict[basestring]]
        time_derivatives = td_type_dict[TimeDerivative] + td_from_str
        # Check for double definitions:
        td_dep_vars = [td.variable for td in time_derivatives]
        assert_no_duplicates(
            td_dep_vars,
            ("Multiple time derivatives found for the same state variable "
                 "in regime '{}' (found '{}')".format(
                     self.name,
                     "', '".join(td.variable for td in time_derivatives))))
        self.add(*time_derivatives)

        # We support passing in 'transitions', which is a list of both OnEvents
        # and OnConditions as well as separate on_conditions and on_events.
        transitions = normalise_parameter_as_list(
            kwargs.get('transitions', None))
        self.add(*transitions)
        on_conditions = normalise_parameter_as_list(
            kwargs.get('on_conditions', None))
        self.add(*on_conditions)
        on_events = normalise_parameter_as_list(
            kwargs.get('on_events', None))
        self.add(*on_events)

        # Add regime specific aliases
        aliases = normalise_parameter_as_list(kwargs.get('aliases', None))
        self.add(*aliases)
Ejemplo n.º 3
0
 def __init__(self, name, definition, properties={}):
     """
     Create a new component_class with the given name, definition and
     properties, or create a prototype to another component_class that will
     be resolved later.
     """
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     ContainerObject.__init__(self)
     if isinstance(definition, basestring):
         if "#" in definition:
             defn_url, name = definition.split("#")
         else:
             raise NineMLUsageError(
                 "Must provide name of class using '#' syntax when "
                 "providing definition as url string ('{}')".format(
                     definition))
         definition = Definition(name=name, document=None, url=defn_url)
     elif (isinstance(definition, ComponentClass)
           or definition.nineml_type in ('Dynamics', 'MultiDynamics')):
         definition = Definition(definition)
     elif (isinstance(definition, Component) or definition.nineml_type
           in ('DynamicsProperties', 'MultiDynamicsProperties')):
         definition = Prototype(definition)
     elif definition.nineml_type not in ('Definition', 'Prototype'):
         raise ValueError("'definition' must be either a 'Definition', "
                          "'Prototype' element or url pointing to a "
                          "dynamics class")
     self._definition = definition
     if isinstance(properties, dict):
         properties = (Property(name, qty)
                       for name, qty in properties.items())
     self.add(*properties)
     self.check_properties()
Ejemplo n.º 4
0
    def __init__(self, name, parameters=(), aliases=(), constants=()):
        self._name = validate_identifier(name)
        BaseALObject.__init__(self)
        DocumentLevelObject.__init__(self)
        ContainerObject.__init__(self)

        # Caches the dimension resolver so that it can be reused in subsequent
        # calls
        self._dimension_resolver = None

        # Turn any strings in the parameter list into Parameters:
        param_types = (basestring, Parameter)
        param_td = filter_discrete_types(parameters, param_types)
        params_from_strings = [Parameter(s) for s in param_td[basestring]]
        parameters = param_td[Parameter] + params_from_strings

        # Load the aliases as objects or strings:
        aliases = normalise_parameter_as_list(aliases)
        alias_td = filter_discrete_types(aliases, (basestring, Alias))
        aliases_from_strs = [Alias.from_str(o) for o in alias_td[basestring]]
        aliases = alias_td[Alias] + aliases_from_strs

        constants = normalise_parameter_as_list(constants)

        self.add(*parameters)
        self.add(*aliases)
        self.add(*constants)
Ejemplo n.º 5
0
    def __init__(self, name):
        """ Port Constructor.

        `name` -- The name of the port, as a `string`
        """
        super(Port, self).__init__()
        self._name = validate_identifier(name)
Ejemplo n.º 6
0
    def __init__(self, name, parameters=(), aliases=(), constants=()):
        self._name = validate_identifier(name)
        BaseALObject.__init__(self)
        DocumentLevelObject.__init__(self)
        ContainerObject.__init__(self)

        # Caches the dimension resolver so that it can be reused in subsequent
        # calls
        self._dimension_resolver = None

        # Turn any strings in the parameter list into Parameters:
        param_types = (basestring, Parameter)
        param_td = filter_discrete_types(parameters, param_types)
        params_from_strings = [Parameter(s) for s in param_td[basestring]]
        parameters = param_td[Parameter] + params_from_strings

        # Load the aliases as objects or strings:
        aliases = normalise_parameter_as_list(aliases)
        alias_td = filter_discrete_types(aliases, (basestring, Alias))
        aliases_from_strs = [Alias.from_str(o) for o in alias_td[basestring]]
        aliases = alias_td[Alias] + aliases_from_strs

        constants = normalise_parameter_as_list(constants)

        self.add(*parameters)
        self.add(*aliases)
        self.add(*constants)
Ejemplo n.º 7
0
 def __init__(self, name, source, destination, source_port,
              destination_port, delay, connectivity=None,
              connection_rule_properties=None,
              connectivity_class=Connectivity):
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     self._source = source
     self._destination = destination
     self._source_port = source_port
     self._destination_port = destination_port
     if connectivity is not None:
         assert isinstance(connectivity, BaseConnectivity)
         if connection_rule_properties is not None:
             raise NineMLUsageError(
                 "Cannot provide both connectivty and "
                 "connection_rule_properties as kwargs to projection class")
         self._connectivity = connectivity
     else:
         connectivity = connectivity_class(
             connection_rule_properties, source.size, destination.size)
     self._connectivity = connectivity
     self._delay = delay
     if isinstance(source_port, Port):
         self._check_ports(source_port, destination_port)
Ejemplo n.º 8
0
 def __init__(self, name, dimension, power, offset=0.0):
     self._name = validate_identifier(name)
     AnnotatedNineMLObject.__init__(self)
     DocumentLevelObject.__init__(self)
     assert isinstance(dimension, Dimension)
     self._dimension = dimension
     self._power = power
     self._offset = offset
Ejemplo n.º 9
0
 def __init__(self, name, dimension, power, offset=0.0):
     self._name = validate_identifier(name)
     AnnotatedNineMLObject.__init__(self)
     DocumentLevelObject.__init__(self)
     assert isinstance(dimension, Dimension)
     self._dimension = dimension
     self._power = power
     self._offset = offset
Ejemplo n.º 10
0
 def __init__(self, name, size, dynamics_properties):
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     self.size = size
     if not dynamics_properties.component_class.is_flat:
         dynamics_properties = dynamics_properties.flatten(name +
                                                           '_flat_dyn')
     self._dynamics_properties = dynamics_properties
Ejemplo n.º 11
0
 def __init__(self, lhs, rhs, assign_to_reserved=False):
     ExpressionWithLHS.__init__(self, rhs)
     if not is_single_symbol(lhs):
         err = 'Expecting a single symbol on the LHS; got: %s' % lhs
         raise NineMLUsageError(err)
     if not assign_to_reserved and not is_valid_lhs_target(lhs):
         err = 'Invalid LHS target: %s' % lhs
         raise NineMLUsageError(err)
     self._name = validate_identifier(lhs)
Ejemplo n.º 12
0
 def __init__(self, lhs, rhs, assign_to_reserved=False):
     ExpressionWithLHS.__init__(self, rhs)
     if not is_single_symbol(lhs):
         err = 'Expecting a single symbol on the LHS; got: %s' % lhs
         raise NineMLUsageError(err)
     if not assign_to_reserved and not is_valid_lhs_target(lhs):
         err = 'Invalid LHS target: %s' % lhs
         raise NineMLUsageError(err)
     self._name = validate_identifier(lhs)
Ejemplo n.º 13
0
 def __init__(self, name, size, dynamics_properties):
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     self.size = size
     if not dynamics_properties.component_class.is_flat:
         dynamics_properties = dynamics_properties.flatten(
             name + '_flat_dyn')
     self._dynamics_properties = dynamics_properties
Ejemplo n.º 14
0
 def __init__(self,
              name,
              pre,
              post,
              response,
              delay,
              connectivity=None,
              connection_rule_properties=None,
              plasticity=None,
              port_connections=None,
              analog_port_connections=None,
              event_port_connections=None,
              connectivity_class=Connectivity,
              **kwargs):
     """
     Create a new projection.
     """
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     ContainerObject.__init__(self)
     DocumentLevelObject.__init__(self)
     assert isinstance(name, basestring)
     assert isinstance(delay, Quantity)
     assert isinstance(pre, (Population, Selection))
     assert isinstance(post, (Population, Selection))
     assert isinstance(response, DynamicsProperties)
     assert isinstance(plasticity, (DynamicsProperties, type(None)))
     self._pre = pre
     self._post = post
     self._response = response
     self._plasticity = plasticity
     if connectivity is not None:
         assert isinstance(connectivity, Connectivity)
         if connection_rule_properties is not None:
             raise NineMLUsageError(
                 "Cannot provide both connectivty and "
                 "connection_rule_properties as kwargs to projection class")
         self._connectivity = connectivity
     else:
         self._connectivity = connectivity_class(connection_rule_properties,
                                                 pre.size, post.size,
                                                 **kwargs)
     self._delay = delay
     if port_connections is None:
         port_connections = []
     if analog_port_connections is None:
         analog_port_connections = []
     if event_port_connections is None:
         event_port_connections = []
     for port_connection in chain(port_connections, event_port_connections,
                                  analog_port_connections):
         if isinstance(port_connection, tuple):
             port_connection = BasePortConnection.from_tuple(
                 port_connection, self)
         port_connection.bind(self, to_roles=True)
         self.add(port_connection)
Ejemplo n.º 15
0
 def __init__(self, sub_component_name, port_name, name=None):
     super(BasePortExposure, self).__init__()
     assert isinstance(sub_component_name, basestring)
     self._sub_component_name = sub_component_name
     assert isinstance(port_name, basestring)
     self._port_name = port_name
     self._parent = None
     if name is None:
         name = self._default_name()
     self._name = validate_identifier(name)
Ejemplo n.º 16
0
 def __init__(self, sub_component_name, port_name, name=None):
     super(BasePortExposure, self).__init__()
     assert isinstance(sub_component_name, basestring)
     self._sub_component_name = sub_component_name
     assert isinstance(port_name, basestring)
     self._port_name = port_name
     self._parent = None
     if name is None:
         name = self._default_name()
     self._name = validate_identifier(name)
Ejemplo n.º 17
0
 def __init__(self, name, populations=[], projections=[], selections=[]):
     # better would be *items, then sort by type, taking the name from the
     # item
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     ContainerObject.__init__(self)
     self.add(*populations)
     self.add(*projections)
     self.add(*selections)
Ejemplo n.º 18
0
    def __init__(self, name, dimension=None):
        """Parameter Constructor

        `name` -- The name of the parameter.
        """
        super(Parameter, self).__init__()
        self._name = validate_identifier(name)
        self._dimension = dimension if dimension is not None else dimensionless
        assert isinstance(self._dimension, Dimension), (
            "dimension must be None or a nineml.Dimension instance")
Ejemplo n.º 19
0
 def __init__(self, name, ns, rel_index=None, abs_index=None, attr=None,
              branches=None, body=None):
     super(_AnnotationsBranch, self).__init__(branches)
     if attr is None:
         attr = {}
     self._name = validate_identifier(name)
     self._ns = ns
     self._abs_index = abs_index
     self._rel_index = rel_index
     self._attr = attr
     self._body = body
Ejemplo n.º 20
0
 def __init__(self, name, dimensions=None, **kwargs):
     self._name = validate_identifier(name)
     AnnotatedNineMLObject.__init__(self)
     DocumentLevelObject.__init__(self)
     if dimensions is not None:
         assert len(dimensions) == 7, "Incorrect dimension length"
         self._dims = tuple(dimensions)
     else:
         self._dims = tuple(kwargs.pop(d, 0)
                            for d in self.dimension_symbols)
     assert not len(kwargs), "Unrecognised kwargs ({})".format(kwargs)
Ejemplo n.º 21
0
 def __init__(self, name, dimensions=None, **kwargs):
     self._name = validate_identifier(name)
     AnnotatedNineMLObject.__init__(self)
     DocumentLevelObject.__init__(self)
     if dimensions is not None:
         assert len(dimensions) == 7, "Incorrect dimension length"
         self._dims = tuple(dimensions)
     else:
         self._dims = tuple(
             kwargs.pop(d, 0) for d in self.dimension_symbols)
     assert not len(kwargs), "Unrecognised kwargs ({})".format(kwargs)
Ejemplo n.º 22
0
    def __init__(self, port_name):
        """
        Parameters
        ----------
        port_name: str
            The name of the output EventPort that should
            transmit an event. An `EventPort` with a mode of 'send' must exist
            with a corresponding name in the component_class, otherwise a
            ``NineMLRuntimeException`` will be raised.

        """
        super(OutputEvent, self).__init__()
        self._port_name = validate_identifier(port_name)
        self._port = None
Ejemplo n.º 23
0
    def __init__(self, port_name):
        """
        Parameters
        ----------
        port_name: str
            The name of the output EventPort that should
            transmit an event. An `EventPort` with a mode of 'send' must exist
            with a corresponding name in the component_class, otherwise a
            ``NineMLRuntimeException`` will be raised.

        """
        super(OutputEvent, self).__init__()
        self._port_name = validate_identifier(port_name)
        self._port = None
Ejemplo n.º 24
0
 def __init__(self, name, dynamics_properties, port_connections=None,
              analog_port_connections=None, event_port_connections=None):
     super(SynapseProperties, self).__init__()
     ContainerObject.__init__(self)
     self._name = validate_identifier(name)
     self._dynamics_properties = dynamics_properties.clone()
     if port_connections is None:
         port_connections = []
     if analog_port_connections is None:
         analog_port_connections = []
     if event_port_connections is None:
         event_port_connections = []
     for port_conn in chain(port_connections, analog_port_connections,
                            event_port_connections):
         self.add(port_conn.clone())
Ejemplo n.º 25
0
    def __init__(self, src_port_name, state_assignments=None,
                 output_events=None, target_regime_name=None):
        """
        Constructor for ``OnEvent``

        Parameters
        ----------
        src_port_name: str
            The name of the |EventPort| that triggers this transition
        """
        Transition.__init__(self, state_assignments=state_assignments,
                            output_events=output_events,
                            target_regime_name=target_regime_name)
        self._src_port_name = validate_identifier(src_port_name)
        self._port = None
Ejemplo n.º 26
0
 def __init__(self, name, pre, post, response, delay, connectivity=None,
              connection_rule_properties=None,
              plasticity=None, port_connections=None,
              analog_port_connections=None, event_port_connections=None,
              connectivity_class=Connectivity, **kwargs):
     """
     Create a new projection.
     """
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     ContainerObject.__init__(self)
     DocumentLevelObject.__init__(self)
     assert isinstance(name, basestring)
     assert isinstance(delay, Quantity)
     assert isinstance(pre, (Population, Selection))
     assert isinstance(post, (Population, Selection))
     assert isinstance(response, DynamicsProperties)
     assert isinstance(plasticity, (DynamicsProperties, type(None)))
     self._pre = pre
     self._post = post
     self._response = response
     self._plasticity = plasticity
     if connectivity is not None:
         assert isinstance(connectivity, Connectivity)
         if connection_rule_properties is not None:
             raise NineMLUsageError(
                 "Cannot provide both connectivty and "
                 "connection_rule_properties as kwargs to projection class")
         self._connectivity = connectivity
     else:
         self._connectivity = connectivity_class(
             connection_rule_properties, pre.size, post.size, **kwargs)
     self._delay = delay
     if port_connections is None:
         port_connections = []
     if analog_port_connections is None:
         analog_port_connections = []
     if event_port_connections is None:
         event_port_connections = []
     for port_connection in chain(port_connections,
                                  event_port_connections,
                                  analog_port_connections):
         if isinstance(port_connection, tuple):
             port_connection = BasePortConnection.from_tuple(
                 port_connection, self)
         port_connection.bind(self, to_roles=True)
         self.add(port_connection)
Ejemplo n.º 27
0
    def __init__(self,
                 state_assignments=None,
                 output_events=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.

        Parameters
        ----------
        state_assignments: list(StateAssignment)
            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.
        output_events: list(OutputEvent)
            A list of OutputEvent objects emitted when
            this transition occurs.
        target_regime_name: str | None
            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 Dynamics during construction.
        """
        BaseALObject.__init__(self)
        ContainerObject.__init__(self)

        # Load state-assignment objects as strings or StateAssignment objects
        state_assignments = state_assignments or []

        sa_types = (basestring, StateAssignment)
        sa_type_dict = filter_discrete_types(state_assignments, sa_types)
        sa_from_str = [
            StateAssignment.from_str(o) for o in sa_type_dict[basestring]
        ]

        self.add(*(sa_type_dict[StateAssignment] + sa_from_str))
        self.add(*normalise_parameter_as_list(output_events))

        self._target_regime_name = (validate_identifier(target_regime_name) if
                                    target_regime_name is not None else None)
        self._target_regime = None
        self._source_regime = None
Ejemplo n.º 28
0
 def __init__(self, name, dynamics_properties, synapse_propertiess=[],
              connection_property_sets=[]):
     self._name = validate_identifier(name)
     self._dynamics_properties = dynamics_properties
     self.add(*synapse_propertiess)
     self.add(*connection_property_sets)
     # Extract the AL objects for the definition
     synapses = (Synapse(s.name, s.dynamics_properties.component_class,
                         s.port_connections)
                 for s in synapse_propertiess)
     connection_parameter_sets = (
         ConnectionParameterSet(
             cp.port,
             [Parameter(p.name, p.units.dimension) for p in cp.properties])
         for cp in connection_property_sets)
     self._definition = Definition(
         WithSynapses.wrap(dynamics_properties.component_class,
                           synapses, connection_parameter_sets))
Ejemplo n.º 29
0
 def __init__(self,
              name,
              dynamics_properties,
              port_connections=None,
              analog_port_connections=None,
              event_port_connections=None):
     super(SynapseProperties, self).__init__()
     ContainerObject.__init__(self)
     self._name = validate_identifier(name)
     self._dynamics_properties = dynamics_properties.clone()
     if port_connections is None:
         port_connections = []
     if analog_port_connections is None:
         analog_port_connections = []
     if event_port_connections is None:
         event_port_connections = []
     for port_conn in chain(port_connections, analog_port_connections,
                            event_port_connections):
         self.add(port_conn.clone())
Ejemplo n.º 30
0
 def __init__(self,
              name,
              dynamics_properties,
              synapse_propertiess=[],
              connection_property_sets=[]):
     self._name = validate_identifier(name)
     self._dynamics_properties = dynamics_properties
     self.add(*synapse_propertiess)
     self.add(*connection_property_sets)
     # Extract the AL objects for the definition
     synapses = (Synapse(s.name, s.dynamics_properties.component_class,
                         s.port_connections) for s in synapse_propertiess)
     connection_parameter_sets = (ConnectionParameterSet(
         cp.port,
         [Parameter(p.name, p.units.dimension) for p in cp.properties])
                                  for cp in connection_property_sets)
     self._definition = Definition(
         WithSynapses.wrap(dynamics_properties.component_class, synapses,
                           connection_parameter_sets))
Ejemplo n.º 31
0
    def __init__(self,
                 src_port_name,
                 state_assignments=None,
                 output_events=None,
                 target_regime_name=None):
        """
        Constructor for ``OnEvent``

        Parameters
        ----------
        src_port_name: str
            The name of the |EventPort| that triggers this transition
        """
        Transition.__init__(self,
                            state_assignments=state_assignments,
                            output_events=output_events,
                            target_regime_name=target_regime_name)
        self._src_port_name = validate_identifier(src_port_name)
        self._port = None
Ejemplo n.º 32
0
    def __init__(self, state_assignments=None, output_events=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.

        Parameters
        ----------
        state_assignments: list(StateAssignment)
            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.
        output_events: list(OutputEvent)
            A list of OutputEvent objects emitted when
            this transition occurs.
        target_regime_name: str | None
            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 Dynamics during construction.
        """
        BaseALObject.__init__(self)
        ContainerObject.__init__(self)

        # Load state-assignment objects as strings or StateAssignment objects
        state_assignments = state_assignments or []

        sa_types = (basestring, StateAssignment)
        sa_type_dict = filter_discrete_types(state_assignments, sa_types)
        sa_from_str = [StateAssignment.from_str(o)
                       for o in sa_type_dict[basestring]]

        self.add(*(sa_type_dict[StateAssignment] + sa_from_str))
        self.add(*normalise_parameter_as_list(output_events))

        self._target_regime_name = (
            validate_identifier(target_regime_name)
            if target_regime_name is not None else None)
        self._target_regime = None
        self._source_regime = None
Ejemplo n.º 33
0
 def __init__(self, visitor, serial_elem, name, check_unprocessed=True,
              **options):
     super(NodeToUnserialize, self).__init__(visitor, serial_elem)
     self._name = validate_identifier(name)
     if check_unprocessed:
         self.unprocessed_attr = set(
             a for a in self.visitor.get_attr_keys(serial_elem, **options)
             if not a.startswith('@'))  # Special attributes start with '@'
         self.unprocessed_children = set(
             n for n, _ in self.visitor.get_all_children(
                 serial_elem, **options))
         self.unprocessed_children.discard(
             self.visitor.node_name(Annotations))
         self.unprocessed_body = (
             self.visitor.get_body(serial_elem, **options) is not None)
     else:
         self.unprocessed_attr = set([])
         self.unprocessed_children = set([])
         self.unprocessed_body = False
Ejemplo n.º 34
0
 def __init__(self, name, definition, properties={}):
     """
     Create a new component_class with the given name, definition and
     properties, or create a prototype to another component_class that will
     be resolved later.
     """
     self._name = validate_identifier(name)
     BaseULObject.__init__(self)
     DocumentLevelObject.__init__(self)
     ContainerObject.__init__(self)
     if isinstance(definition, basestring):
         if "#" in definition:
             defn_url, name = definition.split("#")
         else:
             raise NineMLUsageError(
                 "Must provide name of class using '#' syntax when "
                 "providing definition as url string ('{}')"
                 .format(definition))
         definition = Definition(
             name=name,
             document=None,
             url=defn_url)
     elif (isinstance(definition, ComponentClass) or
           definition.nineml_type in ('Dynamics', 'MultiDynamics')):
         definition = Definition(definition)
     elif (isinstance(definition, Component) or
           definition.nineml_type in ('DynamicsProperties',
                                      'MultiDynamicsProperties')):
         definition = Prototype(definition)
     elif definition.nineml_type not in ('Definition', 'Prototype'):
         raise ValueError("'definition' must be either a 'Definition', "
                          "'Prototype' element or url pointing to a "
                          "dynamics class")
     self._definition = definition
     if isinstance(properties, dict):
         properties = (Property(name, qty)
                       for name, qty in properties.items())
     self.add(*properties)
     self.check_properties()
Ejemplo n.º 35
0
 def __init__(self,
              visitor,
              serial_elem,
              name,
              check_unprocessed=True,
              **options):
     super(NodeToUnserialize, self).__init__(visitor, serial_elem)
     self._name = validate_identifier(name)
     if check_unprocessed:
         self.unprocessed_attr = set(
             a for a in self.visitor.get_attr_keys(serial_elem, **options)
             if not a.startswith('@'))  # Special attributes start with '@'
         self.unprocessed_children = set(
             n for n, _ in self.visitor.get_all_children(
                 serial_elem, **options))
         self.unprocessed_children.discard(
             self.visitor.node_name(Annotations))
         self.unprocessed_body = (self.visitor.get_body(
             serial_elem, **options) is not None)
     else:
         self.unprocessed_attr = set([])
         self.unprocessed_children = set([])
         self.unprocessed_body = False
Ejemplo n.º 36
0
 def __init__(self, name, dynamics, synapses, connection_parameter_sets):
     assert isinstance(dynamics, (Dynamics, MultiDynamics))
     # Initialise Dynamics/MultiDynamics base classes
     self._name = validate_identifier(name)
     self._dynamics = dynamics
     self.add(*synapses)
     self.add(*connection_parameter_sets)
     for conn_param in self.all_connection_parameters():
         try:
             dyn_param = self._dynamics.parameter(conn_param.name)
             if conn_param.dimension != dyn_param.dimension:
                 raise Pype9RuntimeError(
                     "Inconsistent dimensions between connection parameter"
                     " '{}' ({}) and parameter of the same name ({})"
                     .format(conn_param.name, conn_param.dimension,
                             dyn_param.dimension))
         except NineMLNameError:
             raise Pype9RuntimeError(
                 "Connection parameter '{}' does not refer to a parameter "
                 "in the base MultiDynamics class ('{}')"
                 .format(conn_param, "', '".join(
                     sp.name for sp in self._dynamics.parameters)))
     self._dimension_resolver = None
Ejemplo n.º 37
0
 def __init__(self, name, value, units=None):
     BaseALObject.__init__(self)
     self._name = validate_identifier(name)
     if isinstance(value, Quantity):
         if units is None:
             self._value = float(value._value)
             self._units = value.units
         elif units.dimension == value.units.dimension:
             self._value = float(value._value * 10 ** (units.power -
                                                       value.units.power))
             self._units = units
         else:
             raise NineMLDimensionError(
                 "Dimensions do not match between provided quantity ({}) "
                 "and units ({})".format(value.units.dimension,
                                         units.dimension))
     else:
         self._value = float(value)
         self._units = units if units is not None else unitless
     if not isinstance(self._units, Unit):
         raise NineMLUsageError(
             "'units' in '{}' constant needs to be a Unit obj ({}). "
             "Supplied arguments were ({}, {}, {}).".format(
                 self.name, self._units, name, value, units))
Ejemplo n.º 38
0
 def __init__(self, name, value, units=None):
     BaseALObject.__init__(self)
     self._name = validate_identifier(name)
     if isinstance(value, Quantity):
         if units is None:
             self._value = float(value._value)
             self._units = value.units
         elif units.dimension == value.units.dimension:
             self._value = float(value._value *
                                 10**(units.power - value.units.power))
             self._units = units
         else:
             raise NineMLDimensionError(
                 "Dimensions do not match between provided quantity ({}) "
                 "and units ({})".format(value.units.dimension,
                                         units.dimension))
     else:
         self._value = float(value)
         self._units = units if units is not None else unitless
     if not isinstance(self._units, Unit):
         raise NineMLUsageError(
             "'units' in '{}' constant needs to be a Unit obj ({}). "
             "Supplied arguments were ({}, {}, {}).".format(
                 self.name, self._units, name, value, units))
Ejemplo n.º 39
0
 def __init__(self, name, dynamics, synapses, connection_parameter_sets):
     assert isinstance(dynamics, (Dynamics, MultiDynamics))
     # Initialise Dynamics/MultiDynamics base classes
     self._name = validate_identifier(name)
     self._dynamics = dynamics
     self.add(*synapses)
     self.add(*connection_parameter_sets)
     for conn_param in self.all_connection_parameters():
         try:
             dyn_param = self._dynamics.parameter(conn_param.name)
             if conn_param.dimension != dyn_param.dimension:
                 raise Pype9RuntimeError(
                     "Inconsistent dimensions between connection parameter"
                     " '{}' ({}) and parameter of the same name ({})".
                     format(conn_param.name, conn_param.dimension,
                            dyn_param.dimension))
         except NineMLNameError:
             raise Pype9RuntimeError(
                 "Connection parameter '{}' does not refer to a parameter "
                 "in the base MultiDynamics class ('{}')".format(
                     conn_param,
                     "', '".join(sp.name
                                 for sp in self._dynamics.parameters)))
     self._dimension_resolver = None
Ejemplo n.º 40
0
 def __init__(self, send_port_name, receive_port_name,
              sender_role=None, receiver_role=None,
              sender_name=None, receiver_name=None):
     """
     `send_port`     -- The name of the sending port
     `receiver_port` -- The name of the receiving port
     `sender_role`   -- A reference to the sending object via the role it
                        plays in the container
     `receiver_role` -- A reference to the receiving object via the role it
                        plays in the container
     `sender_name`   -- A reference to the sending object via its name,
                        which uniquely identifies it within the container
     `receiver_name` -- A reference to the receiving object via its name,
                        which uniquely identifies it within the container
     """
     BaseULObject.__init__(self)
     assert isinstance(send_port_name, basestring)
     assert isinstance(receive_port_name, basestring)
     self._send_port_name = validate_identifier(send_port_name)
     self._send_port = None
     self._receive_port_name = validate_identifier(receive_port_name)
     self._receive_port = None
     if sender_role is not None:
         if sender_name is not None:
             raise NineMLUsageError(
                 "Both 'sender_role' ({}) and 'sender_name' ({}) cannot"
                 " be provided to PortConnection __init__"
                 .format(sender_role, sender_name))
         assert isinstance(sender_role, basestring)
         sender_role = str(sender_role)
     elif sender_name is not None:
         sender_name = validate_identifier(sender_name)
     else:
         raise NineMLUsageError(
             "Either 'sender_role' or 'sender_name' must be "
             "provided to PortConnection __init__")
     if receiver_role is not None:
         if receiver_name is not None:
             raise NineMLUsageError(
                 "Both 'receiver_role' ({}) and 'receiver_name' ({}) cannot"
                 " be provided to PortConnection __init__"
                 .format(receiver_role, receiver_name))
         assert isinstance(receiver_role, basestring)
         receiver_role = str(receiver_role)
     elif receiver_name is not None:
         receiver_name = validate_identifier(receiver_name)
     else:
         raise NineMLUsageError(
             "Either 'receiver_role' or 'receiver_name' must be "
             "provided to PortConnection __init__")
     self._sender_role = sender_role
     self._sender_name = sender_name
     self._receiver_name = receiver_name
     self._receiver_role = receiver_role
     # Initialise members that will hold the connected objects once they are
     # bound
     self._sender = None
     self._receiver = None
     # check to see if the ports are either all bound or all not bound,
     # raising an error if they are inconsistent
     self.is_bound()
Ejemplo n.º 41
0
    def __init__(self, dependent_variable, independent_variable, rhs):
        ExpressionWithLHS.__init__(self, rhs)

        self._dependent_variable = validate_identifier(dependent_variable)
        self._independent_variable = validate_identifier(independent_variable)
Ejemplo n.º 42
0
 def __init__(self, name, quantity):
     super(Property, self).__init__()
     assert isinstance(name, basestring)
     quantity = Quantity.parse(quantity)
     self._name = validate_identifier(name)
     self._quantity = quantity
Ejemplo n.º 43
0
 def name(self, name):
     self._name = validate_identifier(name)
Ejemplo n.º 44
0
 def __init__(self,
              send_port_name,
              receive_port_name,
              sender_role=None,
              receiver_role=None,
              sender_name=None,
              receiver_name=None):
     """
     `send_port`     -- The name of the sending port
     `receiver_port` -- The name of the receiving port
     `sender_role`   -- A reference to the sending object via the role it
                        plays in the container
     `receiver_role` -- A reference to the receiving object via the role it
                        plays in the container
     `sender_name`   -- A reference to the sending object via its name,
                        which uniquely identifies it within the container
     `receiver_name` -- A reference to the receiving object via its name,
                        which uniquely identifies it within the container
     """
     BaseULObject.__init__(self)
     assert isinstance(send_port_name, basestring)
     assert isinstance(receive_port_name, basestring)
     self._send_port_name = validate_identifier(send_port_name)
     self._send_port = None
     self._receive_port_name = validate_identifier(receive_port_name)
     self._receive_port = None
     if sender_role is not None:
         if sender_name is not None:
             raise NineMLUsageError(
                 "Both 'sender_role' ({}) and 'sender_name' ({}) cannot"
                 " be provided to PortConnection __init__".format(
                     sender_role, sender_name))
         assert isinstance(sender_role, basestring)
         sender_role = str(sender_role)
     elif sender_name is not None:
         sender_name = validate_identifier(sender_name)
     else:
         raise NineMLUsageError(
             "Either 'sender_role' or 'sender_name' must be "
             "provided to PortConnection __init__")
     if receiver_role is not None:
         if receiver_name is not None:
             raise NineMLUsageError(
                 "Both 'receiver_role' ({}) and 'receiver_name' ({}) cannot"
                 " be provided to PortConnection __init__".format(
                     receiver_role, receiver_name))
         assert isinstance(receiver_role, basestring)
         receiver_role = str(receiver_role)
     elif receiver_name is not None:
         receiver_name = validate_identifier(receiver_name)
     else:
         raise NineMLUsageError(
             "Either 'receiver_role' or 'receiver_name' must be "
             "provided to PortConnection __init__")
     self._sender_role = sender_role
     self._sender_name = sender_name
     self._receiver_name = receiver_name
     self._receiver_role = receiver_role
     # Initialise members that will hold the connected objects once they are
     # bound
     self._sender = None
     self._receiver = None
     # check to see if the ports are either all bound or all not bound,
     # raising an error if they are inconsistent
     self.is_bound()
Ejemplo n.º 45
0
 def __init__(self, port, properties):
     super(ConnectionPropertySet, self).__init__()
     ContainerObject.__init__(self)
     self._port = validate_identifier(port)
     for prop in properties:
         self.add(prop.clone(as_class=Property))
Ejemplo n.º 46
0
 def name(self, name):
     self._name = validate_identifier(name)
Ejemplo n.º 47
0
 def __init__(self, name, z):
     super(B, self).__init__()
     self._name = validate_identifier(name)
     self.z = z
Ejemplo n.º 48
0
 def __init__(self, name, u, v):
     AnnotatedNineMLObject.__init__(self)
     self._name = validate_identifier(name)
     DocumentLevelObject.__init__(self)
     self.u = u
     self.v = v
Ejemplo n.º 49
0
 def __init__(self, port, parameters):
     super(ConnectionParameterSet, self).__init__()
     ContainerObject.__init__(self)
     self._port = validate_identifier(port)
     for param in parameters:
         self.add(param.clone(as_class=Parameter))
Ejemplo n.º 50
0
 def __init__(self, port, properties):
     super(ConnectionPropertySet, self).__init__()
     ContainerObject.__init__(self)
     self._port = validate_identifier(port)
     for prop in properties:
         self.add(prop.clone(as_class=Property))
Ejemplo n.º 51
0
 def __init__(self, port, parameters):
     super(ConnectionParameterSet, self).__init__()
     ContainerObject.__init__(self)
     self._port = validate_identifier(port)
     for param in parameters:
         self.add(param.clone(as_class=Parameter))
Ejemplo n.º 52
0
 def __init__(self, name, operation, **kwargs):
     self._name = validate_identifier(name)
     BaseULObject.__init__(self, **kwargs)
     DocumentLevelObject.__init__(self)
     self._operation = operation
Ejemplo n.º 53
0
 def __init__(self, name, x, y):
     AnnotatedNineMLObject.__init__(self)
     self._name = validate_identifier(name)
     DocumentLevelObject.__init__(self)
     self.x = x
     self.y = y
Ejemplo n.º 54
0
 def __init__(self, name, x, y):
     AnnotatedNineMLObject.__init__(self)
     self._name = validate_identifier(name)
     DocumentLevelObject.__init__(self)
     self.x = x
     self.y = y
Ejemplo n.º 55
0
 def __init__(self, name, u, v):
     AnnotatedNineMLObject.__init__(self)
     self._name = validate_identifier(name)
     DocumentLevelObject.__init__(self)
     self.u = u
     self.v = v
Ejemplo n.º 56
0
 def __init__(self, name, z):
     super(B, self).__init__()
     self._name = validate_identifier(name)
     self.z = z