def from_xml(cls, element, document): if element.find(NINEML + 'SingleValue') is not None: value = SingleValue.from_xml( expect_single(element.findall(NINEML + 'SingleValue')), document) elif element.find(NINEML + 'ArrayValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) elif element.find(NINEML + 'ExternalArrayValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) elif element.find(NINEML + 'ComponentValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) else: raise Exception( "Did not find recognised value tag in property (found {})". format(', '.join(c.tag for c in element.getchildren()))) units_str = element.attrib.get('units', None) try: units = document[units_str] if units_str else None except KeyError: raise Exception("Did not find definition of '{}' units in the " "current document.".format(units_str)) return cls(value=value, units=units)
def from_xml(cls, element, document): if element.find(NINEML + 'SingleValue') is not None: value = SingleValue.from_xml( expect_single(element.findall(NINEML + 'SingleValue')), document) elif element.find(NINEML + 'ArrayValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) elif element.find(NINEML + 'ExternalArrayValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) elif element.find(NINEML + 'ComponentValue') is not None: value = ArrayValue.from_xml( expect_single(element.findall(NINEML + 'ArrayValue')), document) else: raise Exception( "Did not find recognised value tag in property (found {})" .format(', '.join(c.tag for c in element.getchildren()))) units_str = element.attrib.get('units', None) try: units = document[units_str] if units_str else None except KeyError: raise Exception("Did not find definition of '{}' units in the " "current document.".format(units_str)) return cls(value=value, units=units)
def load_single_internmaths_block(self, element, checkOnlyBlock=True): if checkOnlyBlock: elements = list(element.iterchildren(tag=etree.Element)) if len(elements) != 1: print elements assert 0, "Unexpected tags found" assert (len(element.findall(MATHML + "MathML")) + len(element.findall(NINEML + "MathInline"))) == 1 if element.find(NINEML + "MathInline") is not None: mblock = expect_single(element.findall(NINEML + "MathInline")).text.strip() elif element.find(MATHML + "MathML") is not None: mblock = self.load_mathml(expect_single(element.find(MATHML + "MathML"))) return mblock
def load_single_internmaths_block(self, element, checkOnlyBlock=True): if checkOnlyBlock: elements = list(element.iterchildren(tag=etree.Element)) if len(elements) != 1: print elements assert 0, 'Unexpected tags found' assert (len(element.findall(MATHML + "MathML")) + len(element.findall(NINEML + "MathInline"))) == 1 if element.find(NINEML + "MathInline") is not None: mblock = expect_single( element.findall(NINEML + 'MathInline')).text.strip() elif element.find(MATHML + "MathML") is not None: mblock = self.load_mathml( expect_single(element.find(MATHML + "MathML"))) return mblock
def load_componentclass(self, element): subblocks = ('Parameter', 'RandomDistribution') children = self._load_blocks(element, blocks=subblocks) distributionblock = expect_single(children["RandomDistribution"]) return DistributionClass(name=element.get('name'), parameters=children["Parameter"], distributionblock=distributionblock)
def load_componentclass(self, element): subblocks = ('Parameter', 'ConnectionRule') children = self._load_blocks(element, blocks=subblocks) connectionruleblock = expect_single(children["ConnectionRule"]) return ConnectionRuleClass(name=element.get('name'), parameters=children["Parameter"], connectionruleblock=connectionruleblock)
def ode_for(regime, variable): """ Yields the TimeDerivative for the given variable in the regime """ odes = [eq for eq in regime.time_derivatives if eq.dependent_variable == variable.name] if len(odes) == 0: odes.append(al.TimeDerivative(dependent_variable = variable, rhs = "0.0")) return expect_single(odes)
def load_oncondition(self, element): subblocks = ('Trigger', 'StateAssignment', 'OutputEvent') subnodes = self._load_blocks(element, blocks=subblocks) target_regime = element.get('target_regime') trigger = expect_single(subnodes["Trigger"]) return OnCondition(trigger=trigger, state_assignments=subnodes["StateAssignment"], event_outputs=subnodes["OutputEvent"], target_regime_name=target_regime)
def read_class_type(cls, element): """ Returns the name of the tag that defines the type of the ComponentClass """ assert element.tag == NINEML + "ComponentClass", "Not a component class ('{}')".format(element.tag) class_type = expect_single(chain(*(element.findall(NINEML + t) for t in cls.class_types))).tag if class_type.startswith(NINEML): class_type = class_type[len(NINEML) :] # TGC 1/15 Temporary fix until name is reverted (pending approval) if class_type == "RandomDistribution": class_type = "Distribution" return class_type
def from_xml(cls, element, document): check_tag(element, cls) layout_elem = element.find(NINEML + 'Layout') kwargs = {} if layout_elem: kwargs['positions'] = Component.from_xml(layout_elem, document) cell = expect_single(element.findall(NINEML + 'Cell')) cell_component = cell.find(NINEML + 'Component') if cell_component is None: cell_component = cell.find(NINEML + 'Reference') return cls(name=element.attrib['name'], number=int(element.find(NINEML + 'Number').text), cell=Component.from_xml(cell_component, document), **kwargs)
def read_class_type(cls, element): """ Returns the name of the tag that defines the type of the ComponentClass """ assert element.tag == NINEML + 'ComponentClass', \ "Not a component class ('{}')".format(element.tag) class_type = expect_single(chain(*(element.findall(NINEML + t) for t in cls.class_types))).tag if class_type.startswith(NINEML): class_type = class_type[len(NINEML):] # TGC 1/15 Temporary fix until name is reverted (pending approval) if class_type == "RandomDistribution": class_type = "Distribution" return class_type
def load_componentclass(self, element): blocks = ('Parameter', 'AnalogSendPort', 'AnalogReceivePort', 'EventSendPort', 'EventReceivePort', 'AnalogReducePort', 'Dynamics', 'Subnode', 'ConnectPorts', 'Component') subnodes = self._load_blocks(element, blocks=blocks) dynamicsblock = expect_single(subnodes["Dynamics"]) return DynamicsClass( name=element.get('name'), parameters=subnodes["Parameter"], analog_ports=chain(subnodes["AnalogSendPort"], subnodes["AnalogReceivePort"], subnodes["AnalogReducePort"]), event_ports=chain(subnodes["EventSendPort"], subnodes["EventReceivePort"]), dynamicsblock=dynamicsblock, subnodes=dict(subnodes['Subnode']), portconnections=subnodes["ConnectPorts"])
def from_xml(cls, element, document): check_tag(element, cls) # Get Name name = element.get('name') # Get Source e = expect_single(element.findall(NINEML + 'Source')) e = expect_single(e.findall(NINEML + 'Reference')) source = nineml.user_layer.Reference.from_xml( e, document).user_layer_object # Get Destination e = expect_single(element.findall(NINEML + 'Destination')) e = expect_single(e.findall(NINEML + 'Reference')) destination = nineml.user_layer.Reference.from_xml( e, document).user_layer_object # Get Response e = element.find(NINEML + 'Response') component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') response = Component.from_xml(component, document) # Get Plasticity e = expect_none_or_single(element.findall(NINEML + 'Plasticity')) if e is not None: component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') plasticity = Component.from_xml(component, document) else: plasticity = None # Get Connectivity e = element.find(NINEML + 'Connectivity') component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') connectivity = Component.from_xml(component, document) # Get Delay delay = Delay.from_xml( expect_single(element.findall(NINEML + 'Delay')), document) # Get port connections by Loop through 'source', 'destination', # 'response', 'plasticity' tags and extracting the "From*" elements port_connections = [] for receive_role in cls._component_roles: # Get element for component name e = element.find(NINEML + receive_role.capitalize()) if e is not None: # Plasticity is not required # Loop through all incoming port connections and add them to # list for sender_role in cls._component_roles: pc_elems = e.findall(NINEML + 'From' + sender_role.capitalize()) if sender_role == receive_role and pc_elems: msg = ("{} port connection receives from itself in " "Projection '{}'".format(name, name)) raise NineMLRuntimeError(msg) if (sender_role is 'plasticity' and plasticity is None and len(pc_elems)): msg = ( "{} port connection receives from plasticity, " "which wasn't provided for Projection '{}'".format( receive_role, name)) raise NineMLRuntimeError(msg) for pc in pc_elems: port_connections.append( PortConnection(sender_role, receive_role, pc.get('send_port'), pc.get('receive_port'))) return cls(name=element.attrib["name"], source=source, destination=destination, response=response, plasticity=plasticity, connectivity=connectivity, delay=delay, port_connections=port_connections)
def from_xml(cls, element, document): check_tag(element, cls) # The only supported op at this stage op = Concatenate.from_xml( expect_single(element.findall(NINEML + 'Concatenate')), document) return cls(element.attrib['name'], op)
def from_xml(cls, element, document): check_tag(element, cls) # Get Name name = element.get('name') # Get Source e = expect_single(element.findall(NINEML + 'Source')) e = expect_single(e.findall(NINEML + 'Reference')) source = nineml.user_layer.Reference.from_xml( e, document).user_layer_object # Get Destination e = expect_single(element.findall(NINEML + 'Destination')) e = expect_single(e.findall(NINEML + 'Reference')) destination = nineml.user_layer.Reference.from_xml( e, document).user_layer_object # Get Response e = element.find(NINEML + 'Response') component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') response = Component.from_xml(component, document) # Get Plasticity e = expect_none_or_single(element.findall(NINEML + 'Plasticity')) if e is not None: component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') plasticity = Component.from_xml(component, document) else: plasticity = None # Get Connectivity e = element.find(NINEML + 'Connectivity') component = e.find(NINEML + 'Component') if component is None: component = e.find(NINEML + 'Reference') connectivity = Component.from_xml(component, document) # Get Delay delay = Delay.from_xml( expect_single(element.findall(NINEML + 'Delay')), document) # Get port connections by Loop through 'source', 'destination', # 'response', 'plasticity' tags and extracting the "From*" elements port_connections = [] for receive_role in cls._component_roles: # Get element for component name e = element.find(NINEML + receive_role.capitalize()) if e is not None: # Plasticity is not required # Loop through all incoming port connections and add them to # list for sender_role in cls._component_roles: pc_elems = e.findall(NINEML + 'From' + sender_role.capitalize()) if sender_role == receive_role and pc_elems: msg = ("{} port connection receives from itself in " "Projection '{}'".format(name, name)) raise NineMLRuntimeError(msg) if (sender_role is 'plasticity' and plasticity is None and len(pc_elems)): msg = ("{} port connection receives from plasticity, " "which wasn't provided for Projection '{}'" .format(receive_role, name)) raise NineMLRuntimeError(msg) for pc in pc_elems: port_connections.append( PortConnection(sender_role, receive_role, pc.get('send_port'), pc.get('receive_port'))) return cls(name=element.attrib["name"], source=source, destination=destination, response=response, plasticity=plasticity, connectivity=connectivity, delay=delay, port_connections=port_connections)
def test_expect_single(self): # Signature: name(lst, error_func=None) # Retrieve a single element from an iterable. # # This function tests whether an iterable contains just a single element and # if so returns that element. Otherwise it raises an Exception. # # :param lst: An iterable # # :param error_func: An exception object or a callable. ``error_func`` will be # raised or called in case there is not exactly one element in ``lst``. If # ``error_func`` is ``None``, a ``NineMLRuntimeError`` exception will be # raised. # # # :rtype: the element in the list, ``lst[0]``, provided ``len(lst)==1`` # # # # >>> expect_single( ['hello'] ) # 'hello' # # >>> expect_single( [1] ) # 1 # # >>> expect_single( [] ) #doctest: +SKIP # NineMLRuntimeError: expect_single() recieved an iterable of length: 0 # # >>> expect_single( [None,None] ) #doctest: +SKIP # NineMLRuntimeError: expect_single() recieved an iterable of length: 2 # # >>> expect_single( [], lambda: raise_exception( RuntimeError('Aggh') ) #doctest: +SKIP # RuntimeError: Aggh # # >>> #Slightly more tersly: # >>> expect_single( [], RuntimeError('Aggh') ) #doctest: +SKIP # RuntimeError: Aggh # Empty Objects should raise: self.assertRaises(NineMLRuntimeError, expect_single, []) self.assertRaises(NineMLRuntimeError, expect_single, tuple()) self.assertRaises(NineMLRuntimeError, expect_single, set()) # Dictionaries should raise: self.assertRaises(NineMLRuntimeError, expect_single, {}) self.assertRaises(NineMLRuntimeError, expect_single, {1: None}) self.assertRaises(NineMLRuntimeError, expect_single, {1: None, 2: True}) # Strings should raise: self.assertRaises(NineMLRuntimeError, expect_single, "") self.assertRaises(NineMLRuntimeError, expect_single, "A") self.assertRaises(NineMLRuntimeError, expect_single, "AA") # Two items should raise: self.assertRaises(NineMLRuntimeError, expect_single, [None, None]) self.assertRaises(NineMLRuntimeError, expect_single, [True, False]) self.assertRaises(NineMLRuntimeError, expect_single, [True, True]) self.assertRaises(NineMLRuntimeError, expect_single, ["Hello", "World"]) # Some good cases: self.assertEqual(expect_single([None]), None) self.assertEqual(expect_single([1]), 1) self.assertEqual(expect_single([2]), 2) self.assertEqual(expect_single(['2']), '2') self.assertEqual(expect_single(['hello']), 'hello')
def test_expect_single(self): # Signature: name(lst, error_func=None) # Retrieve a single element from an iterable. # # This function tests whether an iterable contains just a single element and # if so returns that element. Otherwise it raises an Exception. # # :param lst: An iterable # # :param error_func: An exception object or a callable. ``error_func`` will be # raised or called in case there is not exactly one element in ``lst``. If # ``error_func`` is ``None``, a ``NineMLRuntimeError`` exception will be # raised. # # # :rtype: the element in the list, ``lst[0]``, provided ``len(lst)==1`` # # # # >>> expect_single( ['hello'] ) # 'hello' # # >>> expect_single( [1] ) # 1 # # >>> expect_single( [] ) #doctest: +SKIP # NineMLRuntimeError: expect_single() recieved an iterable of length: 0 # # >>> expect_single( [None,None] ) #doctest: +SKIP # NineMLRuntimeError: expect_single() recieved an iterable of length: 2 # # >>> expect_single( [], lambda: raise_exception( RuntimeError('Aggh') ) #doctest: +SKIP # RuntimeError: Aggh # # >>> #Slightly more tersly: # >>> expect_single( [], RuntimeError('Aggh') ) #doctest: +SKIP # RuntimeError: Aggh # Empty Objects should raise: self.assertRaises(NineMLRuntimeError, expect_single, []) self.assertRaises(NineMLRuntimeError, expect_single, tuple()) self.assertRaises(NineMLRuntimeError, expect_single, set()) # Dictionaries should raise: self.assertRaises(NineMLRuntimeError, expect_single, {}) self.assertRaises(NineMLRuntimeError, expect_single, {1: None}) self.assertRaises(NineMLRuntimeError, expect_single, { 1: None, 2: True }) # Strings should raise: self.assertRaises(NineMLRuntimeError, expect_single, "") self.assertRaises(NineMLRuntimeError, expect_single, "A") self.assertRaises(NineMLRuntimeError, expect_single, "AA") # Two items should raise: self.assertRaises(NineMLRuntimeError, expect_single, [None, None]) self.assertRaises(NineMLRuntimeError, expect_single, [True, False]) self.assertRaises(NineMLRuntimeError, expect_single, [True, True]) self.assertRaises(NineMLRuntimeError, expect_single, ["Hello", "World"]) # Some good cases: self.assertEqual(expect_single([None]), None) self.assertEqual(expect_single([1]), 1) self.assertEqual(expect_single([2]), 2) self.assertEqual(expect_single(['2']), '2') self.assertEqual(expect_single(['hello']), 'hello')