def get_component():

    component = hierachical_iaf_2coba.get_component()
    comp = flattening.flatten(component)

    # Remap some ports:
    RenameSymbol(comp, 'iaf_vthresh', 'V_th')
    RenameSymbol(comp, 'iaf_vreset', 'V_reset')
    RenameSymbol(comp, 'iaf_taurefrac', 't_ref')
    RenameSymbol(comp, 'iaf_vrest', 'E_L')
    RenameSymbol(comp, 'iaf_cm', 'C_m')
    RenameSymbol(comp, 'iaf_gl', 'g_L')
    RenameSymbol(comp, 'cobaExcit_vrev', 'E_ex')
    RenameSymbol(comp, 'cobaInhib_vrev', 'E_in')
    RenameSymbol(comp, 'cobaInhib_q', 'q_in')
    RenameSymbol(comp, 'cobaExcit_q', 'q_ex')
    RenameSymbol(comp, 'cobaExcit_tau', 'tau_syn_ex')
    RenameSymbol(comp, 'cobaInhib_tau', 'tau_syn_in')
    RenameSymbol(comp, 'iaf_V', 'V_m')
    RenameSymbol(comp, 'iaf_tspike', 'tspike')
    RenameSymbol(comp, 'cobaInhib_g', 'g_in')
    RenameSymbol(comp, 'cobaExcit_g', 'g_ex')
    RenameSymbol(comp, 'cobaInhib_spikeinput', 'spike_in')
    RenameSymbol(comp, 'cobaExcit_spikeinput', 'spike_ex')

    return comp
    def test(cls, testable_component, build_dir):
        component = testable_component()
        print "  -- Testing One and a half trips..."

        if not component.is_flat():
            component = flattening.flatten(component)

        xmlfile1 = build_dir + component.name + "1.xml"
        xmlfile2 = build_dir + component.name + "2.xml"

        print "    -- Saving Component To XML:", xmlfile1
        writers.XMLWriter.write(component, xmlfile1)

        print "    -- Loading Component To XML."
        reloaded_comp = readers.XMLReader.read(xmlfile1)

        print "    -- Checking Components are identical"
        validators.ComponentEqualityChecker.check_equal(component, reloaded_comp)

        print "    -- Saving Reloaded Component to XML", xmlfile2
        writers.XMLWriter.write(reloaded_comp, xmlfile2)

        print "    -- Checking the SHA1 Checksum of the two xml files:"
        hash1 = file_sha1_hexdigest(xmlfile1)
        hash2 = file_sha1_hexdigest(xmlfile2)
        print "      -->", hash1
        print "      -->", hash2

        if hash1 != hash2:
            raise ValueError("XML files are different. This may not be an error but please report it to the developers")
Esempio n. 3
0
    def test_Flattening1(self):

        c = ComponentClass(
            name='C',
            aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/cp2',
                    transitions=[On('SV1>cp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('c_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[RecvPort('cIn1'), RecvPort('cIn2'), SendPort('C1'), SendPort('C2')],
            parameters=['cp1', 'cp2']
        )

        d = ComponentClass(
            name='D',
            aliases=['D1:=dp1', 'D2 := dIn1', 'D3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/dp2',
                    transitions=[On('SV1>dp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('d_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[RecvPort('dIn1'), RecvPort('dIn2'), SendPort('D1'), SendPort('D2')],
            parameters=['dp1', 'dp2']
        )

        # Flatten a flat component
        # Everything should be as before:
        c_flat = flattening.flatten(c)

        assert c_flat is not c

        self.assertEqual(c_flat.name, 'C')
        self.assertEqual(set(c_flat.aliases_map.keys()), set(['C1', 'C2', 'C3']))

        # - Regimes and Transitions:
        self.assertEqual(set(c_flat.regimes_map.keys()), set(['r1', 'r2']))
        self.assertEqual(len(list(c_flat.regimes_map['r1'].on_events)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r1'].on_conditions)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_events)), 0)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_conditions)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_conditions)), 1)

        #  - Ports & Parameters:
        self.assertEqual(
            set(c_flat.query.analog_ports_map.keys()),  set(['cIn2', 'cIn1', 'C1', 'C2']))
        self.assertEqual(
            set(c_flat.query.event_ports_map.keys()),   set(['spikein', 'c_emit', 'emit']))
        self.assertEqual(set(c_flat.query.parameters_map.keys()),    set(['cp1', 'cp2']))
        self.assertEqual(set(c_flat.state_variables_map.keys()),     set(['SV1']))
Esempio n. 4
0
def write_and_compile_nmodl(component):
    build_dir = os.path.join(BUILD_DIR, component.name.replace('-', '_'))
    clear_and_recreate_dir(build_dir)
    if not component.is_flat():
        component = flatten(component)
    ComponentModifier.close_all_reduce_ports(component=component)
    print '  -- Writing Component to .mod'
    modfilename = os.path.join(build_dir, component.name + '.mod').replace('-', '_')
    write_nmodldirect(component=component, mod_filename=modfilename, weight_variables={})
    compile_nmodl(build_dir)
Esempio n. 5
0
    def __new__(cls, name, bases, dct):
        
        import nineml.abstraction_layer as al
        from nineml.abstraction_layer import flattening, writers, component_modifiers

        #Extract Parameters Back out from Dict:
        combined_model = dct['nineml_model']
        synapse_components = dct['synapse_components']

        # Flatten the model:
        assert isinstance(combined_model, al.ComponentClass)
        if combined_model.is_flat():
            flat_component = combined_model
        else:
            flat_component = flattening.flatten( combined_model,name )
        
        # Make the substitutions:
        flat_component.backsub_all()
        #flat_component.backsub_aliases()
        #flat_component.backsub_equations()

        # Close any open reduce ports:
        component_modifiers.ComponentModifier.close_all_reduce_ports(component = flat_component)
         
        # New:
        dct["combined_model"] = flat_component
        dct["default_parameters"] = dict( (param.name, 1.0) for param in flat_component.parameters )
        dct["default_initial_values"] = dict((statevar.name, 0.0) for statevar in chain(flat_component.state_variables) )
        dct["synapse_types"] = [syn.namespace for syn in synapse_components] 
        dct["standard_receptor_type"] = (dct["synapse_types"] == ('excitatory', 'inhibitory'))
        dct["injectable"] = True # need to determine this. How??
        dct["conductance_based"] = True # how to determine this??
        dct["model_name"] = name
        
        
        # Recording from bindings:
        dct["recordable"] = [port.name for port in flat_component.analog_ports] + ['spikes', 'regime'] + [alias.lhs for alias in flat_component.aliases] + [statevar.name for statevar in flat_component.state_variables]
        
        dct["weight_variables"] = dict([ (syn.namespace,syn.namespace+'_'+syn.weight_connector )
                                         for syn in synapse_components ])
        
        
        logger.debug("Creating class '%s' with bases %s and dictionary %s" % (name, bases, dct))
        # generate and compile NMODL code, then load the mechanism into NEUORN
        dct["builder"](flat_component, dct["weight_variables"], hierarchical_mode=True)
        
        return type.__new__(cls, name, bases, dct)
Esempio n. 6
0
    def func_test(self):

        emitter = ComponentClass(
            name="EventEmitter",
            parameters=["cyclelength"],
            regimes=[Regime(transitions=On("t > tchange + cyclelength", do=[OutputEvent("emit"), "tchange=t"]))],
        )

        ev_based_cc = ComponentClass(
            name="EventBasedCurrentClass",
            parameters=["dur", "i"],
            analog_ports=[SendPort("I")],
            regimes=[
                Regime(
                    transitions=[
                        On("inputevent", do=["I=i", "tchange = t"]),
                        On("t>tchange + dur", do=["I=0", "tchange=t"]),
                    ]
                )
            ],
        )

        pulsing_emitter = ComponentClass(
            name="pulsing_cc",
            subnodes={"evs": emitter, "cc": ev_based_cc},
            portconnections=[("evs.emit", "cc.inputevent")],
        )

        nrn = ComponentClass(
            name="LeakyNeuron",
            parameters=["Cm", "gL", "E"],
            regimes=[Regime("dV/dt = (iInj + (E-V)*gL )/Cm")],
            aliases=["iIn := iInj"],
            analog_ports=[SendPort("V"), ReducePort("iInj", reduce_op="+")],
        )

        combined_comp = ComponentClass(
            name="Comp1",
            subnodes={"nrn": nrn, "cc1": pulsing_emitter, "cc2": pulsing_emitter},
            portconnections=[("cc1.cc.I", "nrn.iInj"), ("cc2.cc.I", "nrn.iInj")],
        )

        combined_comp = flattening.flatten(combined_comp)

        records = [
            RecordValue(what="cc1_cc_I", tag="Current", label="Current Clamp 1"),
            RecordValue(what="cc2_cc_I", tag="Current", label="Current Clamp 2"),
            RecordValue(what="nrn_iIn", tag="Current", label="Total Input Current"),
            RecordValue(what="nrn_V", tag="Voltage", label="Neuron Voltage"),
            RecordValue(what="cc1_cc_tchange", tag="Tchange", label="tChange CC1"),
            RecordValue(what="cc2_cc_tchange", tag="Tchange", label="tChange CC2"),
            RecordValue(what="regime", tag="Regime", label="Regime"),
        ]

        parameters = flattening.ComponentFlattener.flatten_namespace_dict(
            {
                "cc1.cc.i": 13.8,
                "cc1.cc.dur": 10,
                "cc1.evs.cyclelength": 30,
                "cc2.cc.i": 20.8,
                "cc2.cc.dur": 5.0,
                "cc2.evs.cyclelength": 20,
                "nrn.gL": 4.3,
                "nrn.E": -70,
            }
        )

        res = std_pynn_simulation(
            test_component=combined_comp,
            parameters=parameters,
            initial_values={},
            synapse_components=[],
            records=records,
            # plot = False,
        )
        return
        t, records = res

        def check_trace(trace_name, time_period, exp_mean, exp_std=0):
            t_indices = (t > time_period[0] + 1) & (t < time_period[1] - 1)
            self.assertAlmostEqual(records[trace_name][t_indices].mean(), exp_mean, places=3)
            self.assertAlmostEqual(records[trace_name][t_indices].std(), exp_std, places=3)

        check_trace("cc1_cc_I", (00, 30), exp_mean=0.0)
        check_trace("cc1_cc_I", (30, 40), exp_mean=13.8)
        check_trace("cc1_cc_I", (40, 60), exp_mean=0.0)
        check_trace("cc1_cc_I", (60, 70), exp_mean=13.8)
        check_trace("cc1_cc_I", (70, 90), exp_mean=0.0)
        check_trace("cc1_cc_I", (90, 100), exp_mean=13.8)

        check_trace("cc2_cc_I", (00, 20), exp_mean=0.0)
        check_trace("cc2_cc_I", (20, 25), exp_mean=20.8)
        check_trace("cc2_cc_I", (25, 40), exp_mean=0.0)
        check_trace("cc2_cc_I", (40, 45), exp_mean=20.8)
        check_trace("cc2_cc_I", (45, 60), exp_mean=0.0)
        check_trace("cc2_cc_I", (60, 65), exp_mean=20.8)
        check_trace("cc2_cc_I", (65, 80), exp_mean=0.0)
        check_trace("cc2_cc_I", (80, 85), exp_mean=20.8)
        check_trace("cc2_cc_I", (85, 100), exp_mean=0.0)

        check_trace("nrn_iIn", (00, 20), exp_mean=0.0)
        check_trace("nrn_iIn", (20, 25), exp_mean=20.8)
        check_trace("nrn_iIn", (25, 30), exp_mean=0.0)
        check_trace("nrn_iIn", (30, 40), exp_mean=13.8)
        check_trace("nrn_iIn", (40, 45), exp_mean=20.8)
        check_trace("nrn_iIn", (45, 60), exp_mean=0.0)
        check_trace("nrn_iIn", (60, 65), exp_mean=34.6)
        check_trace("nrn_iIn", (65, 70), exp_mean=13.8)
        check_trace("nrn_iIn", (70, 80), exp_mean=0.0)
        check_trace("nrn_iIn", (80, 85), exp_mean=20.8)
        check_trace("nrn_iIn", (85, 90), exp_mean=0.0)
        check_trace("nrn_iIn", (90, 100), exp_mean=13.8)

        check_trace("nrn_V", (00 + 2, 20), exp_mean=(0.0 / 4.3) - 70)
        check_trace("nrn_V", (20 + 2, 25), exp_mean=(20.8 / 4.3) - 70)
        check_trace("nrn_V", (25 + 2, 30), exp_mean=(0.0 / 4.3) - 70)
        check_trace("nrn_V", (30 + 2, 40), exp_mean=(13.8 / 4.3) - 70)
        check_trace("nrn_V", (40 + 2, 45), exp_mean=(20.8 / 4.3) - 70)
        check_trace("nrn_V", (45 + 2, 60), exp_mean=(0.0 / 4.3) - 70)
        check_trace("nrn_V", (60 + 2, 65), exp_mean=(34.6 / 4.3) - 70)
        check_trace("nrn_V", (65 + 2, 70), exp_mean=(13.8 / 4.3) - 70)
        check_trace("nrn_V", (70 + 2, 80), exp_mean=(0.0 / 4.3) - 70)
        check_trace("nrn_V", (80 + 2, 85), exp_mean=(20.8 / 4.3) - 70)
        check_trace("nrn_V", (85 + 2, 90), exp_mean=(0.0 / 4.3) - 70)
        check_trace("nrn_V", (90 + 2, 100), exp_mean=(13.8 / 4.3) - 70)
Esempio n. 7
0
    def func_test(self):

        emitter = ComponentClass(
            name='EventEmitter',
            parameters=['cyclelength'],
            regimes=[
                Regime(transitions=On('t > tchange + random_offset + cyclelength',
                                      do=[OutputEvent(
                                          'emit'), 'tchange=t', 'random_offset=random.uniform(5,10) '])),
            ])

        ev_based_cc = ComponentClass(
            name='EventBasedCurrentClass',
            parameters=['dur', 'i'],
            analog_ports=[SendPort('I')],
            regimes=[
                Regime(
                    transitions=[
                        On('inputevent', do=['I=i', 'tchange = t', ]),
                        On('t>tchange + dur  ', do=['I=0', 'tchange=t'])
                    ]
                )
            ]
        )

        pulsing_emitter = ComponentClass(name='pulsing_cc',
                                         subnodes={'evs': emitter, 'cc': ev_based_cc},
                                         portconnections=[('evs.emit', 'cc.inputevent')]
                                         )

        nrn = ComponentClass(
            name='LeakyNeuron',
            parameters=['Cm', 'gL', 'E'],
            regimes=[Regime('dV/dt = (iInj + (E-V)*gL )/Cm'), ],
            aliases=['iIn := iInj'],
            analog_ports=[SendPort('V'),
                          ReducePort('iInj', reduce_op='+')],
        )

        combined_comp = ComponentClass(name='Comp1',
                                       subnodes={'nrn': nrn,
                                                 'cc1': pulsing_emitter,
                                                 'cc2': pulsing_emitter},
                                       portconnections=[('cc1.cc.I', 'nrn.iInj'),
                                                        ('cc2.cc.I', 'nrn.iInj')]
                                       )

        combined_comp = flattening.flatten(combined_comp)

        records = [
            RecordValue(what='cc1_cc_I', tag='Current', label='Current Clamp 1'),
            RecordValue(what='cc2_cc_I', tag='Current', label='Current Clamp 2'),
            RecordValue(what='nrn_iIn',  tag='Current', label='Total Input Current'),
            RecordValue(what='nrn_V',    tag='Voltage', label='Neuron Voltage'),
            RecordValue(what='cc1_cc_tchange', tag='Tchange', label='tChange CC1'),
            RecordValue(what='cc2_cc_tchange', tag='Tchange', label='tChange CC2'),
            RecordValue(what='regime',     tag='Regime',  label='Regime'),
        ]

        parameters = flattening.ComponentFlattener.flatten_namespace_dict({
                                                                                    'cc1.cc.i': 13.8,
                                                                                    'cc1.cc.dur': 5,
                                                                                    'cc1.evs.cyclelength': 15,

                                                                                    'cc2.cc.i': 20.8,
                                                                                    'cc2.cc.dur': 5,
                                                                                    'cc2.evs.cyclelength': 15,

                                                                                    'nrn.gL': 4.3,
                                                                                    'nrn.E': -70})

        res = std_pynn_simulation(test_component=combined_comp,
                                  parameters=parameters,
                                  initial_values={},
                                  synapse_components=[],
                                  records=records,
                                  # plot = False,
                                  )
        return
        t, records = res

        def check_trace(trace_name, time_period, exp_mean, exp_std=0):
            t_indices = (t > time_period[0] + 1) & (t < time_period[1] - 1)
            self.assertAlmostEqual(records[trace_name][t_indices].mean(), exp_mean, places=3)
            self.assertAlmostEqual(records[trace_name][t_indices].std(),  exp_std, places=3)
Esempio n. 8
0
#import os
from nineml.abstraction_layer.testing_utils import TestableComponent
from nineml.abstraction_layer.flattening import flatten
#from nineml.abstraction_layer.flattening import ComponentFlattener
from nineml.abstraction_layer.component_modifiers import ComponentModifier
from nineml.utility import LocationMgr
#from nineml.abstraction_layer.visitors import RenameSymbol

LocationMgr.StdAppendToPath()


comp_data = TestableComponent('nestequivalent_iaf_cond_exp')

# Build the component:
component = comp_data()
component = flatten( component )
component.backsub_all()
ComponentModifier.close_all_reduce_ports(component=component)


# Copy the descriptive strings:
component.short_description = comp_data.metadata.short_description 
component.long_description = comp_data.metadata.long_description 



# Get the initial regime. If this component comes from an flattened component, 
# then we should look up the new regime from the locations in the old
# components, hence the nedd for this code:
initial_regime = comp_data.metadata.initial_regime
if component.was_flattened():
Esempio n. 9
0
    def test_Flattening2(self):

        c = ComponentClass(
            name='C',
            aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/cp2',
                    transitions=[On('SV1>cp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('c_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[AnalogReceivePort('cIn1'), AnalogReceivePort('cIn2'),
                          AnalogSendPort('C1'), AnalogSendPort('C2')],
            parameters=['cp1', 'cp2']
        )

        d = ComponentClass(
            name='D',
            aliases=['D1:=dp1', 'D2 := dIn1', 'D3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/dp2',
                    transitions=[On('SV1>dp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('d_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[AnalogReceivePort('dIn1'), AnalogReceivePort('dIn2'),
                          AnalogSendPort('D1'), AnalogSendPort('D2')],
            parameters=['dp1', 'dp2']
        )

        # Test Cloner, 1 level of hierachy
        # ------------------------------ #

        # Everything should be as before:
        b = ComponentClass(name='B',
                           subnodes={'c1': c, 'c2': c, 'd': d},
                           # portconnections= [('c1.C1','c2.cIn1'),('c2.emit','c1.spikein'), ]
                           )

        b_flat = flattening.flatten(b)

        # Name
        self.assertEqual(b_flat.name, 'B')

        # Aliases
        self.assertEqual(
            set(b_flat.aliases_map.keys()),
            set(['c1_C1', 'c1_C2', 'c1_C3', 'c2_C1', 'c2_C2', 'c2_C3', 'd_D1', 'd_D2', 'd_D3']))

        # - Regimes and Transitions:
        self.assertEqual(len(b_flat.regimes_map), 8)
        r_c1_1_c2_1_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r1 c2:r1 ')
        r_c1_1_c2_2_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r1 c2:r2 ')
        r_c1_2_c2_1_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r2 c2:r1')
        r_c1_2_c2_2_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r2 c2:r2')
        r_c1_1_c2_1_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r1 c2:r1 ')
        r_c1_1_c2_2_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r1 c2:r2 ')
        r_c1_2_c2_1_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r2 c2:r1')
        r_c1_2_c2_2_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r2 c2:r2')

        # Do we have the right number of on_events and on_conditions:
        self.assertEqual(len(list(r_c1_1_c2_1_d_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1.on_conditions)), 3)

        self.assertEqual(len(list(r_c1_1_c2_1_d_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2.on_events)), 0)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2.on_conditions)), 3)

        # All on_events return to thier same transition:
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[0].target_regime, r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[1].target_regime, r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[2].target_regime, r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_2_d_1.on_events))[0].target_regime, r_c1_1_c2_2_d_1)
        self.assertEqual((list(r_c1_1_c2_2_d_1.on_events))[1].target_regime, r_c1_1_c2_2_d_1)
        self.assertEqual((list(r_c1_2_c2_1_d_1.on_events))[0].target_regime, r_c1_2_c2_1_d_1)
        self.assertEqual((list(r_c1_2_c2_1_d_1.on_events))[1].target_regime, r_c1_2_c2_1_d_1)
        self.assertEqual((list(r_c1_2_c2_2_d_1.on_events))[0].target_regime, r_c1_2_c2_2_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_2.on_events))[0].target_regime, r_c1_1_c2_1_d_2)
        self.assertEqual((list(r_c1_1_c2_1_d_2.on_events))[1].target_regime, r_c1_1_c2_1_d_2)
        self.assertEqual((list(r_c1_1_c2_2_d_2.on_events))[0].target_regime, r_c1_1_c2_2_d_2)
        self.assertEqual((list(r_c1_2_c2_1_d_2.on_events))[0].target_regime, r_c1_2_c2_1_d_2)

        # Check On-Event port names are remapped properly:
        self.assertEqual(set([ev.src_port_name for ev in r_c1_1_c2_1_d_1.on_events]), set(
            ['c1_spikein', 'c2_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_1.on_events]), set(['c1_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_1.on_events]), set(['c2_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1.on_events]), set(['d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_2.on_events]), set(['c1_spikein', 'c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2.on_events]), set(['c1_spikein', ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2.on_events]), set(['c2_spikein', ]))
        self.assertEqual(set([ev.src_port_name for ev in r_c1_2_c2_2_d_2.on_events]), set([]))

        # ToDo: Check the OnConditions:
        #  - Ports & Parameters:
        self.assertEqual(
            set(b_flat.query.analog_ports_map.keys()),
            set(['c1_cIn1', 'c1_cIn2', 'c1_C1', 'c1_C2', 'c2_cIn1', 'c2_cIn2', 'c2_C1', 'c2_C2', 'd_dIn1', 'd_dIn2', 'd_D1', 'd_D2']))

        self.assertEqual(
            set(b_flat.query.event_ports_map.keys()),
            set(['c1_spikein', 'c1_emit', 'c1_c_emit', 'c2_spikein', 'c2_emit', 'c2_c_emit', 'd_spikein', 'd_emit', 'd_d_emit']))

        self.assertEqual(
            set(b_flat.query.parameters_map.keys()),
            set(['c1_cp1', 'c1_cp2', 'c2_cp1', 'c2_cp2', 'd_dp1', 'd_dp2', ]))

        self.assertEqual(
            set(b_flat.state_variables_map.keys()),
            set(['c1_SV1', 'c2_SV1', 'd_SV1']))
Esempio n. 10
0
    def func_test(self):

        emitter = ComponentClass(
            name='EventEmitter',
            parameters=['rate'],
            regimes=[
                Regime(
                    transitions=On(
                        't > tchange', do=[OutputEvent('emit'), 'tchange=t + random.exponential(1/rate) '])),
            ])

        ev_based_cc = ComponentClass(
            name='EventBasedCurrentClass',
            parameters=['dur', 'i'],
            analog_ports=[SendPort('I')],
            regimes=[
                Regime(
                    transitions=[
                        On('inputevent', do=['I=i', 'tchange = t']),
                        On('t>tchange + dur', do=['I=0', 'tchange=t'])
                    ]
                )
            ]
        )

        pulsing_emitter = ComponentClass(name='pulsing_cc',
                                         subnodes={'evs': emitter, 'cc': ev_based_cc},
                                         portconnections=[('evs.emit', 'cc.inputevent')]
                                         )

        nrn = ComponentClass(
            name='LeakyNeuron',
            parameters=['Cm', 'gL', 'E'],
            regimes=[Regime('dV/dt = (iInj + (E-V)*gL )/Cm'), ],
            aliases=['iIn := iInj'],
            analog_ports=[SendPort('V'),
                          ReducePort('iInj', reduce_op='+')],
        )

        combined_comp = ComponentClass(name='Comp1',
                                       subnodes={
                                       'nrn': nrn,  'cc1': pulsing_emitter, 'cc2': pulsing_emitter},
                                       portconnections=[('cc1.cc.I', 'nrn.iInj'),
                                                        ('cc2.cc.I', 'nrn.iInj')]
                                       )

        combined_comp = flattening.flatten(combined_comp)

        records = [
            RecordValue(what='cc1_cc_I', tag='Current', label='Current Clamp 1'),
            RecordValue(what='cc2_cc_I', tag='Current', label='Current Clamp 2'),
            # RecordValue(what='nrn_iIn', tag='Current', label='Total Input Current'),
            RecordValue(what='nrn_V', tag='Voltage', label='Neuron Voltage'),
            RecordValue(what='cc1_cc_tchange', tag='Tchange', label='tChange CC1'),
            RecordValue(what='cc2_cc_tchange', tag='Tchange', label='tChange CC2'),
            RecordValue(what='regime',     tag='Regime',  label='Regime'),
        ]

        parameters = flattening.ComponentFlattener.flatten_namespace_dict({
                                                                                    'cc1.cc.i': 13.8,
                                                                                    'cc1.cc.dur': 1,
                                                                                    'cc1.evs.rate': 110. / 1000.,

                                                                                    'cc2.cc.i': 20.8,
                                                                                    'cc2.cc.dur': 1.,
                                                                                    'cc2.evs.rate': 20. / 1000.,

                                                                                    'nrn.gL': 4.3,
                                                                                    'nrn.E': -70})

        res = std_pynn_simulation(test_component=combined_comp,
                                  parameters=parameters,
                                  initial_values={},
                                  synapse_components=[],
                                  records=records,
                                  sim_time=1000
                                  # plot = False,
                                  )
        return
        t, records = res

        def check_trace(trace_name, time_period, exp_mean, exp_std=0):
            t_indices = (t > time_period[0] + 1) & (t < time_period[1] - 1)
            self.assertAlmostEqual(records[trace_name][t_indices].mean(), exp_mean, places=3)
            self.assertAlmostEqual(records[trace_name][t_indices].std(),  exp_std, places=3)

        check_trace('cc1_cc_I', (00, 30),  exp_mean=0.0)
        check_trace('cc1_cc_I', (30, 40), exp_mean=13.8)
        check_trace('cc1_cc_I', (40, 60), exp_mean=0.0)
        check_trace('cc1_cc_I', (60, 70), exp_mean=13.8)
        check_trace('cc1_cc_I', (70, 90), exp_mean=0.0)
        check_trace('cc1_cc_I', (90, 100), exp_mean=13.8)

        check_trace('cc2_cc_I', (00, 20),  exp_mean=0.0)
        check_trace('cc2_cc_I', (20, 25),  exp_mean=20.8)
        check_trace('cc2_cc_I', (25, 40),  exp_mean=0.0)
        check_trace('cc2_cc_I', (40, 45),  exp_mean=20.8)
        check_trace('cc2_cc_I', (45, 60),  exp_mean=0.0)
        check_trace('cc2_cc_I', (60, 65),  exp_mean=20.8)
        check_trace('cc2_cc_I', (65, 80),  exp_mean=0.0)
        check_trace('cc2_cc_I', (80, 85),  exp_mean=20.8)
        check_trace('cc2_cc_I', (85, 100), exp_mean=0.0)

        check_trace('nrn_iIn', (00, 20),  exp_mean=0.0)
        check_trace('nrn_iIn', (20, 25),  exp_mean=20.8)
        check_trace('nrn_iIn', (25, 30),  exp_mean=0.0)
        check_trace('nrn_iIn', (30, 40),  exp_mean=13.8)
        check_trace('nrn_iIn', (40, 45),  exp_mean=20.8)
        check_trace('nrn_iIn', (45, 60),  exp_mean=0.0)
        check_trace('nrn_iIn', (60, 65),  exp_mean=34.6)
        check_trace('nrn_iIn', (65, 70),  exp_mean=13.8)
        check_trace('nrn_iIn', (70, 80),  exp_mean=0.0)
        check_trace('nrn_iIn', (80, 85),  exp_mean=20.8)
        check_trace('nrn_iIn', (85, 90),  exp_mean=0.0)
        check_trace('nrn_iIn', (90, 100),  exp_mean=13.8)

        check_trace('nrn_V', (00 + 2, 20),  exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (20 + 2, 25),  exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (25 + 2, 30),  exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (30 + 2, 40),  exp_mean=(13.8 / 4.3) - 70)
        check_trace('nrn_V', (40 + 2, 45),  exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (45 + 2, 60),  exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (60 + 2, 65),  exp_mean=(34.6 / 4.3) - 70)
        check_trace('nrn_V', (65 + 2, 70),  exp_mean=(13.8 / 4.3) - 70)
        check_trace('nrn_V', (70 + 2, 80),  exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (80 + 2, 85),  exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (85 + 2, 90),  exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (90 + 2, 100),  exp_mean=(13.8 / 4.3) - 70)
Esempio n. 11
0
    def test_Flattening2(self):

        c = ComponentClass(name='C',
                           aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1'],
                           regimes=[
                               Regime(
                                   'dSV1/dt = -SV1/cp2',
                                   transitions=[
                                       On('SV1>cp1', do=[OutputEvent('emit')]),
                                       On('spikein',
                                          do=[OutputEvent('c_emit')])
                                   ],
                                   name='r1',
                               ),
                               Regime(name='r2',
                                      transitions=On('SV1>1', to='r1'))
                           ],
                           analog_ports=[
                               AnalogReceivePort('cIn1'),
                               AnalogReceivePort('cIn2'),
                               AnalogSendPort('C1'),
                               AnalogSendPort('C2')
                           ],
                           parameters=['cp1', 'cp2'])

        d = ComponentClass(name='D',
                           aliases=['D1:=dp1', 'D2 := dIn1', 'D3 := SV1'],
                           regimes=[
                               Regime(
                                   'dSV1/dt = -SV1/dp2',
                                   transitions=[
                                       On('SV1>dp1', do=[OutputEvent('emit')]),
                                       On('spikein',
                                          do=[OutputEvent('d_emit')])
                                   ],
                                   name='r1',
                               ),
                               Regime(name='r2',
                                      transitions=On('SV1>1', to='r1'))
                           ],
                           analog_ports=[
                               AnalogReceivePort('dIn1'),
                               AnalogReceivePort('dIn2'),
                               AnalogSendPort('D1'),
                               AnalogSendPort('D2')
                           ],
                           parameters=['dp1', 'dp2'])

        # Test Cloner, 1 level of hierachy
        # ------------------------------ #

        # Everything should be as before:
        b = ComponentClass(
            name='B',
            subnodes={
                'c1': c,
                'c2': c,
                'd': d
            },
            # portconnections= [('c1.C1','c2.cIn1'),('c2.emit','c1.spikein'), ]
        )

        b_flat = flattening.flatten(b)

        # Name
        self.assertEqual(b_flat.name, 'B')

        # Aliases
        self.assertEqual(
            set(b_flat.aliases_map.keys()),
            set([
                'c1_C1', 'c1_C2', 'c1_C3', 'c2_C1', 'c2_C2', 'c2_C3', 'd_D1',
                'd_D2', 'd_D3'
            ]))

        # - Regimes and Transitions:
        self.assertEqual(len(b_flat.regimes_map), 8)
        r_c1_1_c2_1_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r1 c2:r1 ')
        r_c1_1_c2_2_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r1 c2:r2 ')
        r_c1_2_c2_1_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r2 c2:r1')
        r_c1_2_c2_2_d_1 = b_flat.flattener.get_new_regime('d:r1 c1:r2 c2:r2')
        r_c1_1_c2_1_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r1 c2:r1 ')
        r_c1_1_c2_2_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r1 c2:r2 ')
        r_c1_2_c2_1_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r2 c2:r1')
        r_c1_2_c2_2_d_2 = b_flat.flattener.get_new_regime('d:r2 c1:r2 c2:r2')

        # Do we have the right number of on_events and on_conditions:
        self.assertEqual(len(list(r_c1_1_c2_1_d_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1.on_conditions)), 3)

        self.assertEqual(len(list(r_c1_1_c2_1_d_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2.on_conditions)), 3)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2.on_events)), 0)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2.on_conditions)), 3)

        # All on_events return to thier same transition:
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[0].target_regime,
                         r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[1].target_regime,
                         r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_1.on_events))[2].target_regime,
                         r_c1_1_c2_1_d_1)
        self.assertEqual((list(r_c1_1_c2_2_d_1.on_events))[0].target_regime,
                         r_c1_1_c2_2_d_1)
        self.assertEqual((list(r_c1_1_c2_2_d_1.on_events))[1].target_regime,
                         r_c1_1_c2_2_d_1)
        self.assertEqual((list(r_c1_2_c2_1_d_1.on_events))[0].target_regime,
                         r_c1_2_c2_1_d_1)
        self.assertEqual((list(r_c1_2_c2_1_d_1.on_events))[1].target_regime,
                         r_c1_2_c2_1_d_1)
        self.assertEqual((list(r_c1_2_c2_2_d_1.on_events))[0].target_regime,
                         r_c1_2_c2_2_d_1)
        self.assertEqual((list(r_c1_1_c2_1_d_2.on_events))[0].target_regime,
                         r_c1_1_c2_1_d_2)
        self.assertEqual((list(r_c1_1_c2_1_d_2.on_events))[1].target_regime,
                         r_c1_1_c2_1_d_2)
        self.assertEqual((list(r_c1_1_c2_2_d_2.on_events))[0].target_regime,
                         r_c1_1_c2_2_d_2)
        self.assertEqual((list(r_c1_2_c2_1_d_2.on_events))[0].target_regime,
                         r_c1_2_c2_1_d_2)

        # Check On-Event port names are remapped properly:
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_1.on_events]),
            set(['c1_spikein', 'c2_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_1.on_events]),
            set(['c1_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_1.on_events]),
            set(['c2_spikein', 'd_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1.on_events]),
            set(['d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_2.on_events]),
            set(['c1_spikein', 'c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2.on_events]),
            set([
                'c1_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2.on_events]),
            set([
                'c2_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_2.on_events]),
            set([]))

        # ToDo: Check the OnConditions:
        #  - Ports & Parameters:
        self.assertEqual(
            set(b_flat.query.analog_ports_map.keys()),
            set([
                'c1_cIn1', 'c1_cIn2', 'c1_C1', 'c1_C2', 'c2_cIn1', 'c2_cIn2',
                'c2_C1', 'c2_C2', 'd_dIn1', 'd_dIn2', 'd_D1', 'd_D2'
            ]))

        self.assertEqual(
            set(b_flat.query.event_ports_map.keys()),
            set([
                'c1_spikein', 'c1_emit', 'c1_c_emit', 'c2_spikein', 'c2_emit',
                'c2_c_emit', 'd_spikein', 'd_emit', 'd_d_emit'
            ]))

        self.assertEqual(
            set(b_flat.query.parameters_map.keys()),
            set([
                'c1_cp1',
                'c1_cp2',
                'c2_cp1',
                'c2_cp2',
                'd_dp1',
                'd_dp2',
            ]))

        self.assertEqual(set(b_flat.state_variables_map.keys()),
                         set(['c1_SV1', 'c2_SV1', 'd_SV1']))
Esempio n. 12
0
    def test_Flattening1(self):

        c = ComponentClass(name='C',
                           aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1'],
                           regimes=[
                               Regime(
                                   'dSV1/dt = -SV1/cp2',
                                   transitions=[
                                       On('SV1>cp1', do=[OutputEvent('emit')]),
                                       On('spikein',
                                          do=[OutputEvent('c_emit')])
                                   ],
                                   name='r1',
                               ),
                               Regime(name='r2',
                                      transitions=On('SV1>1', to='r1'))
                           ],
                           analog_ports=[
                               AnalogReceivePort('cIn1'),
                               AnalogReceivePort('cIn2'),
                               AnalogSendPort('C1'),
                               AnalogSendPort('C2')
                           ],
                           parameters=['cp1', 'cp2'])

        d = ComponentClass(name='D',
                           aliases=['D1:=dp1', 'D2 := dIn1', 'D3 := SV1'],
                           regimes=[
                               Regime(
                                   'dSV1/dt = -SV1/dp2',
                                   transitions=[
                                       On('SV1>dp1', do=[OutputEvent('emit')]),
                                       On('spikein',
                                          do=[OutputEvent('d_emit')])
                                   ],
                                   name='r1',
                               ),
                               Regime(name='r2',
                                      transitions=On('SV1>1', to='r1'))
                           ],
                           analog_ports=[
                               AnalogReceivePort('dIn1'),
                               AnalogReceivePort('dIn2'),
                               AnalogSendPort('D1'),
                               AnalogSendPort('D2')
                           ],
                           parameters=['dp1', 'dp2'])

        # Flatten a flat component
        # Everything should be as before:
        c_flat = flattening.flatten(c)

        assert c_flat is not c

        self.assertEqual(c_flat.name, 'C')
        self.assertEqual(set(c_flat.aliases_map.keys()),
                         set(['C1', 'C2', 'C3']))

        # - Regimes and Transitions:
        self.assertEqual(set(c_flat.regimes_map.keys()), set(['r1', 'r2']))
        self.assertEqual(len(list(c_flat.regimes_map['r1'].on_events)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r1'].on_conditions)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_events)), 0)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_conditions)), 1)
        self.assertEqual(len(list(c_flat.regimes_map['r2'].on_conditions)), 1)

        #  - Ports & Parameters:
        self.assertEqual(set(c_flat.query.analog_ports_map.keys()),
                         set(['cIn2', 'cIn1', 'C1', 'C2']))
        self.assertEqual(set(c_flat.query.event_ports_map.keys()),
                         set(['spikein', 'c_emit', 'emit']))
        self.assertEqual(set(c_flat.query.parameters_map.keys()),
                         set(['cp1', 'cp2']))
        self.assertEqual(set(c_flat.state_variables_map.keys()), set(['SV1']))
Esempio n. 13
0
    def test_Flattening4(self):

        c = ComponentClass(
            name='C',
            aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1', 'C4:=cIn2'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/cp2',
                    transitions=[
                        On('SV1>cp1', do=[OutputEvent('emit')]),
                        On('spikein', do=[OutputEvent('c_emit')])
                    ],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[
                AnalogReceivePort('cIn1'),
                AnalogReceivePort('cIn2'),
                AnalogSendPort('C1'),
                AnalogSendPort('C2')
            ],
            parameters=['cp1', 'cp2'])

        d = ComponentClass(
            name='D',
            aliases=['D1:=dp1', 'D2 := dIn1 + dp2', 'D3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/dp2',
                    transitions=[
                        On('SV1>dp1', do=[OutputEvent('emit')]),
                        On('spikein', do=[OutputEvent('d_emit')])
                    ],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[
                AnalogReceivePort('dIn1'),
                AnalogReceivePort('dIn2'),
                AnalogSendPort('D1'),
                AnalogSendPort('D2')
            ],
            parameters=['dp1', 'dp2'])

        # Test Cloner, 2 levels of hierachy
        # ------------------------------ #

        # Everything should be as before:
        b = ComponentClass(
            name='B',
            subnodes={
                'c1': c,
                'c2': c,
                'd': d
            },
            portconnections=[('c1.C1', 'c2.cIn2'), ('c2.C1', 'c1.cIn1')],
        )

        a = ComponentClass(name='A',
                           subnodes={
                               'b': b,
                               'c': c
                           },
                           portconnections=[('b.c1.C1', 'b.c1.cIn2'),
                                            ('b.c1.C1', 'b.c2.cIn1'),
                                            ('b.c1.C2', 'b.d.dIn1')])

        a_flat = flattening.flatten(a)

        # Name
        self.assertEqual(a_flat.name, 'A')

        # Aliases
        self.assertEqual(
            set(a_flat.aliases_map.keys()),
            set([
                'b_c1_C1', 'b_c1_C2', 'b_c1_C3', 'b_c1_C4', 'b_c2_C1',
                'b_c2_C2', 'b_c2_C3', 'b_c2_C4', 'b_d_D1', 'b_d_D2', 'b_d_D3',
                'c_C1', 'c_C2', 'c_C3', 'c_C4'
            ]))

        # - Regimes and Transitions:
        self.assertEqual(len(a_flat.regimes_map), 16)
        r_c1_1_c2_1_d_1_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r1 b.c2:r1 c:r1')
        r_c1_1_c2_2_d_1_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r1 b.c2:r2 c:r1')
        r_c1_2_c2_1_d_1_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r2 b.c2:r1 c:r1')
        r_c1_2_c2_2_d_1_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r2 b.c2:r2 c:r1')
        r_c1_1_c2_1_d_2_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r1 b.c2:r1 c:r1')
        r_c1_1_c2_2_d_2_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r1 b.c2:r2 c:r1')
        r_c1_2_c2_1_d_2_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r2 b.c2:r1 c:r1')
        r_c1_2_c2_2_d_2_c_1 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r2 b.c2:r2 c:r1')
        r_c1_1_c2_1_d_1_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r1 b.c2:r1 c:r2')
        r_c1_1_c2_2_d_1_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r1 b.c2:r2 c:r2')
        r_c1_2_c2_1_d_1_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r2 b.c2:r1 c:r2')
        r_c1_2_c2_2_d_1_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r1 b.c1:r2 b.c2:r2 c:r2')
        r_c1_1_c2_1_d_2_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r1 b.c2:r1 c:r2')
        r_c1_1_c2_2_d_2_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r1 b.c2:r2 c:r2')
        r_c1_2_c2_1_d_2_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r2 b.c2:r1 c:r2')
        r_c1_2_c2_2_d_2_c_2 = a_flat.flattener.get_new_regime(
            'b.d:r2 b.c1:r2 b.c2:r2 c:r2')

        regimes = [
            r_c1_1_c2_1_d_1_c_1, r_c1_1_c2_2_d_1_c_1, r_c1_2_c2_1_d_1_c_1,
            r_c1_2_c2_2_d_1_c_1, r_c1_1_c2_1_d_2_c_1, r_c1_1_c2_2_d_2_c_1,
            r_c1_2_c2_1_d_2_c_1, r_c1_2_c2_2_d_2_c_1, r_c1_1_c2_1_d_1_c_2,
            r_c1_1_c2_2_d_1_c_2, r_c1_2_c2_1_d_1_c_2, r_c1_2_c2_2_d_1_c_2,
            r_c1_1_c2_1_d_2_c_2, r_c1_1_c2_2_d_2_c_2, r_c1_2_c2_1_d_2_c_2,
            r_c1_2_c2_2_d_2_c_2
        ]
        self.assertEqual(len(set(regimes)), 16)

        # Do we have the right number of on_events and on_conditions:
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_1.on_events)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_1.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_1.on_conditions)), 4)

        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_2.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_2.on_events)), 0)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_2.on_conditions)), 4)

        # All on_events return to thier same transition:
        for r in a_flat.regimes:
            for on_ev in r.on_events:
                self.assertEquals(on_ev.target_regime, r)

        # Check On-Event port names are remapped properly:
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_1_c_1.on_events]),
            set(['c_spikein', 'b_c1_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_1_c_1.on_events]),
            set(['c_spikein', 'b_c1_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_1_c_1.on_events]),
            set(['c_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1_c_1.on_events]),
            set(['c_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_2_c_1.on_events]),
            set(['c_spikein', 'b_c1_spikein', 'b_c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2_c_1.on_events]),
            set([
                'c_spikein',
                'b_c1_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2_c_1.on_events]),
            set([
                'c_spikein',
                'b_c2_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_2_c_1.on_events]),
            set(['c_spikein']))

        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_1_c_2.on_events]),
            set(['b_c1_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_1_c_2.on_events]),
            set(['b_c1_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_1_c_2.on_events]),
            set(['b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1_c_2.on_events]),
            set(['b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_2_c_2.on_events]),
            set(['b_c1_spikein', 'b_c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2_c_2.on_events]),
            set([
                'b_c1_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2_c_2.on_events]),
            set([
                'b_c2_spikein',
            ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_2_c_2.on_events]),
            set([]))

        # ToDo: Check the OnConditions:

        #  - Ports & Parameters:
        self.assertEqual(
            set(a_flat.query.analog_ports_map.keys()),
            set([
                'b_c1_C1', 'b_c1_C2', 'b_c2_C1', 'b_c2_C2', 'b_d_dIn2',
                'b_d_D1', 'b_d_D2', 'c_cIn1', 'c_cIn2', 'c_C1', 'c_C2'
            ]))

        self.assertEqual(
            set(a_flat.query.event_ports_map.keys()),
            set([
                'b_c1_spikein',
                'b_c1_emit',
                'b_c1_c_emit',
                'b_c2_spikein',
                'b_c2_emit',
                'b_c2_c_emit',
                'b_d_spikein',
                'b_d_emit',
                'b_d_d_emit',
                'c_spikein',
                'c_emit',
                'c_c_emit',
            ]))

        self.assertEqual(
            set(a_flat.query.parameters_map.keys()),
            set([
                'c_cp1',
                'c_cp2',
                'b_c1_cp1',
                'b_c1_cp2',
                'b_c2_cp1',
                'b_c2_cp2',
                'b_d_dp1',
                'b_d_dp2',
            ]))

        self.assertEqual(set(a_flat.state_variables_map.keys()),
                         set(['b_c1_SV1', 'b_c2_SV1', 'b_d_SV1', 'c_SV1']))

        # Back-sub everything - then do we get the correct port mappings:
        a_flat.backsub_all()

        self.assertEqual(set(a_flat.aliases_map['b_c2_C4'].rhs_atoms),
                         set(['b_c1_cp1']))

        self.assertEqual(set(a_flat.aliases_map['b_c1_C2'].rhs_atoms),
                         set(['b_c2_cp1']))

        self.assertEqual(set(a_flat.aliases_map['b_c1_C4'].rhs_atoms),
                         set(['b_c1_cp1']))

        self.assertEqual(set(a_flat.aliases_map['b_c2_C2'].rhs_atoms),
                         set(['b_c1_cp1']))

        self.assertEqual(set(a_flat.aliases_map['b_d_D2'].rhs_atoms),
                         set(['b_c2_cp1', 'b_d_dp2']))
Esempio n. 14
0
    def func_test(self):

        emitter = ComponentClass(
            name='EventEmitter',
            parameters=['rate'],
            regimes=[
                Regime(transitions=On(
                    't > tchange',
                    do=[
                        OutputEvent('emit'),
                        'tchange=t + random.exponential(1/rate) '
                    ])),
            ])

        ev_based_cc = ComponentClass(
            name='EventBasedCurrentClass',
            parameters=['dur', 'i'],
            analog_ports=[SendPort('I')],
            regimes=[
                Regime(transitions=[
                    On('inputevent', do=['I=i', 'tchange = t']),
                    On('t>tchange + dur', do=['I=0', 'tchange=t'])
                ])
            ])

        pulsing_emitter = ComponentClass(name='pulsing_cc',
                                         subnodes={
                                             'evs': emitter,
                                             'cc': ev_based_cc
                                         },
                                         portconnections=[('evs.emit',
                                                           'cc.inputevent')])

        nrn = ComponentClass(
            name='LeakyNeuron',
            parameters=['Cm', 'gL', 'E'],
            regimes=[
                Regime('dV/dt = (iInj + (E-V)*gL )/Cm'),
            ],
            aliases=['iIn := iInj'],
            analog_ports=[SendPort('V'),
                          ReducePort('iInj', reduce_op='+')],
        )

        combined_comp = ComponentClass(name='Comp1',
                                       subnodes={
                                           'nrn': nrn,
                                           'cc1': pulsing_emitter,
                                           'cc2': pulsing_emitter
                                       },
                                       portconnections=[
                                           ('cc1.cc.I', 'nrn.iInj'),
                                           ('cc2.cc.I', 'nrn.iInj')
                                       ])

        combined_comp = flattening.flatten(combined_comp)

        records = [
            RecordValue(what='cc1_cc_I',
                        tag='Current',
                        label='Current Clamp 1'),
            RecordValue(what='cc2_cc_I',
                        tag='Current',
                        label='Current Clamp 2'),
            # RecordValue(what='nrn_iIn', tag='Current', label='Total Input Current'),
            RecordValue(what='nrn_V', tag='Voltage', label='Neuron Voltage'),
            RecordValue(what='cc1_cc_tchange',
                        tag='Tchange',
                        label='tChange CC1'),
            RecordValue(what='cc2_cc_tchange',
                        tag='Tchange',
                        label='tChange CC2'),
            RecordValue(what='regime', tag='Regime', label='Regime'),
        ]

        parameters = flattening.ComponentFlattener.flatten_namespace_dict({
            'cc1.cc.i':
            13.8,
            'cc1.cc.dur':
            1,
            'cc1.evs.rate':
            110. / 1000.,
            'cc2.cc.i':
            20.8,
            'cc2.cc.dur':
            1.,
            'cc2.evs.rate':
            20. / 1000.,
            'nrn.gL':
            4.3,
            'nrn.E':
            -70
        })

        res = std_pynn_simulation(test_component=combined_comp,
                                  parameters=parameters,
                                  initial_values={},
                                  synapse_components=[],
                                  records=records,
                                  sim_time=1000
                                  # plot = False,
                                  )
        return
        t, records = res

        def check_trace(trace_name, time_period, exp_mean, exp_std=0):
            t_indices = (t > time_period[0] + 1) & (t < time_period[1] - 1)
            self.assertAlmostEqual(records[trace_name][t_indices].mean(),
                                   exp_mean,
                                   places=3)
            self.assertAlmostEqual(records[trace_name][t_indices].std(),
                                   exp_std,
                                   places=3)

        check_trace('cc1_cc_I', (00, 30), exp_mean=0.0)
        check_trace('cc1_cc_I', (30, 40), exp_mean=13.8)
        check_trace('cc1_cc_I', (40, 60), exp_mean=0.0)
        check_trace('cc1_cc_I', (60, 70), exp_mean=13.8)
        check_trace('cc1_cc_I', (70, 90), exp_mean=0.0)
        check_trace('cc1_cc_I', (90, 100), exp_mean=13.8)

        check_trace('cc2_cc_I', (00, 20), exp_mean=0.0)
        check_trace('cc2_cc_I', (20, 25), exp_mean=20.8)
        check_trace('cc2_cc_I', (25, 40), exp_mean=0.0)
        check_trace('cc2_cc_I', (40, 45), exp_mean=20.8)
        check_trace('cc2_cc_I', (45, 60), exp_mean=0.0)
        check_trace('cc2_cc_I', (60, 65), exp_mean=20.8)
        check_trace('cc2_cc_I', (65, 80), exp_mean=0.0)
        check_trace('cc2_cc_I', (80, 85), exp_mean=20.8)
        check_trace('cc2_cc_I', (85, 100), exp_mean=0.0)

        check_trace('nrn_iIn', (00, 20), exp_mean=0.0)
        check_trace('nrn_iIn', (20, 25), exp_mean=20.8)
        check_trace('nrn_iIn', (25, 30), exp_mean=0.0)
        check_trace('nrn_iIn', (30, 40), exp_mean=13.8)
        check_trace('nrn_iIn', (40, 45), exp_mean=20.8)
        check_trace('nrn_iIn', (45, 60), exp_mean=0.0)
        check_trace('nrn_iIn', (60, 65), exp_mean=34.6)
        check_trace('nrn_iIn', (65, 70), exp_mean=13.8)
        check_trace('nrn_iIn', (70, 80), exp_mean=0.0)
        check_trace('nrn_iIn', (80, 85), exp_mean=20.8)
        check_trace('nrn_iIn', (85, 90), exp_mean=0.0)
        check_trace('nrn_iIn', (90, 100), exp_mean=13.8)

        check_trace('nrn_V', (00 + 2, 20), exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (20 + 2, 25), exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (25 + 2, 30), exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (30 + 2, 40), exp_mean=(13.8 / 4.3) - 70)
        check_trace('nrn_V', (40 + 2, 45), exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (45 + 2, 60), exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (60 + 2, 65), exp_mean=(34.6 / 4.3) - 70)
        check_trace('nrn_V', (65 + 2, 70), exp_mean=(13.8 / 4.3) - 70)
        check_trace('nrn_V', (70 + 2, 80), exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (80 + 2, 85), exp_mean=(20.8 / 4.3) - 70)
        check_trace('nrn_V', (85 + 2, 90), exp_mean=(0.0 / 4.3) - 70)
        check_trace('nrn_V', (90 + 2, 100), exp_mean=(13.8 / 4.3) - 70)
Esempio n. 15
0
    def __new__(cls, name, bases, dct):
        
        import nineml.abstraction_layer as al
        from nineml.abstraction_layer import flattening, writers, component_modifiers
        import nest

        #Extract Parameters Back out from Dict:
        nineml_model = dct['nineml_model']
        synapse_components = dct['synapse_components']

        # Flatten the model:
        assert isinstance(nineml_model, al.ComponentClass)
        if nineml_model.is_flat():
            flat_component = nineml_model
        else:
            flat_component = flattening.flatten( nineml_model,name )
        
        # Make the substitutions:
        flat_component.backsub_all()
        #flat_component.backsub_aliases()
        #flat_component.backsub_equations()

        # Close any open reduce ports:
        component_modifiers.ComponentModifier.close_all_reduce_ports(component = flat_component)


        flat_component.short_description = "Auto-generated 9ML neuron model for PyNN.nest"
        flat_component.long_description = "Auto-generated 9ML neuron model for PyNN.nest"

        # Close any open reduce ports:
        component_modifiers.ComponentModifier.close_all_reduce_ports(component = flat_component)

        # synapse ports:
        synapse_ports = []
        for syn in synapse_components:
            # get recv event ports
            # TODO: model namespace look
            #syn_component = nineml_model[syn.namespace]
            syn_component = nineml_model.subnodes[syn.namespace]
            recv_event_ports = list(syn_component.query.event_recv_ports)
            # check there's only one
            if len(recv_event_ports)!=1:
                raise ValueError("A synapse component has multiple recv ports.  Cannot dis-ambiguate")
            synapse_ports.append(syn.namespace+'_'+recv_event_ports[0].name)

        
        # New:
        dct["combined_model"] = flat_component
        # TODO: Override this with user layer
        #default_values = ModelToSingleComponentReducer.flatten_namespace_dict( parameters )
        dct["default_parameters"] = dict( (p.name, 1.0) for p in flat_component.parameters )
        dct["default_initial_values"] = dict((s.name, 0.0) for s in flat_component.state_variables)
        dct["synapse_types"] = [syn.namespace for syn in synapse_components] 
        dct["standard_receptor_type"] = (dct["synapse_types"] == ('excitatory', 'inhibitory'))
        dct["injectable"] = True # need to determine this. How??
        dct["conductance_based"] = True # how to determine this??
        dct["model_name"] = name
        dct["nest_model"] = name

        
        # Recording from bindings:
        dct["recordable"] = [port.name for port in flat_component.analog_ports] + ['spikes', 'regime']
        # TODO bindings -> alias and support recording of them in nest template
        #+ [binding.name for binding in flat_component.bindings]
        
        dct["weight_variables"] = dict([ (syn.namespace,syn.namespace+'_'+syn.weight_connector )
                                         for syn in synapse_components ])
        
        logger.debug("Creating class '%s' with bases %s and dictionary %s" % (name, bases, dct))

        # TODO: UL configuration of initial regime.
        initial_regime = flat_component.regimes_map.keys()[0]

        from nestbuilder import NestFileBuilder
        nfb = NestFileBuilder(  nest_classname = name, 
                                component = flat_component, 
                                synapse_ports = synapse_ports,
                                initial_regime =  initial_regime,
                                initial_values = dct["default_initial_values"],
                                default_values = dct["default_parameters"],
                                )
        nfb.compile_files()
        nest.Install('mymodule')
        
        return type.__new__(cls, name, bases, dct)
def t4():
    print 'Loading Forth XML File (iaf-2coba-Model)'
    print '----------------------------------------'
    component = readers.XMLReader.read_component(
        Join(tenml_dir, 'iaf_2coba.10ml'), component_name='iaf')
    writers.XMLWriter.write(component, '/tmp/nineml_toxml4.xml', )
    model = readers.XMLReader.read_component(Join(tenml_dir, 'iaf_2coba.10ml'))

    from nineml.abstraction_layer.flattening import flatten
    from nineml.abstraction_layer.component_modifiers import ComponentModifier

    flatcomponent = flatten(model, componentname='iaf_2coba')
    ComponentModifier.close_analog_port(component=flatcomponent, port_name='iaf_iSyn', value='0')

    writers.XMLWriter.write(flatcomponent, '/tmp/nineml_out_iaf_2coba.9ml')

    import pyNN.neuron as sim
    from pyNN.utility import init_logging

    init_logging(None, debug=True)
    sim.setup(timestep=0.1, min_delay=0.1)
    print 'Attempting to simulate From Model:'
    print '----------------------------------'
    celltype_cls = pyNNml.nineml_celltype_from_model(
        name="iaf_2coba",
        nineml_model=flatcomponent,
        synapse_components=[
            pyNNml.CoBaSyn(namespace='cobaExcit',  weight_connector='q'),
            pyNNml.CoBaSyn(namespace='cobaInhib',  weight_connector='q'),
        ]
    )

    parameters = {
        'iaf.cm': 1.0,
        'iaf.gl': 50.0,
        'iaf.taurefrac': 5.0,
        'iaf.vrest': -65.0,
        'iaf.vreset': -65.0,
        'iaf.vthresh': -50.0,
        'cobaExcit.tau': 2.0,
        'cobaInhib.tau': 5.0,
        'cobaExcit.vrev': 0.0,
        'cobaInhib.vrev': -70.0,
    }

    parameters = ComponentFlattener.flatten_namespace_dict(parameters)

    cells = sim.Population(1, celltype_cls, parameters)
    cells.initialize('iaf_V', parameters['iaf_vrest'])
    cells.initialize('tspike', -1e99)  # neuron not refractory at start
    cells.initialize('regime', 1002)  # temporary hack

    input = sim.Population(2, sim.SpikeSourcePoisson, {'rate': 100})

    connector = sim.OneToOneConnector(weights=1.0, delays=0.5)

    conn = [sim.Projection(input[0:1], cells, connector, target='cobaExcit'),
            sim.Projection(input[1:2], cells, connector, target='cobaInhib')]

    cells._record('iaf_V')
    cells._record('cobaExcit_g')
    cells._record('cobaInhib_g')
    cells._record('cobaExcit_I')
    cells._record('cobaInhib_I')
    cells.record()

    sim.run(100.0)

    cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]])
    cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]])
    cells.recorders['cobaInhib_g'].write("Results/nineml_neuron.g_inh", filter=[cells[0]])
    cells.recorders['cobaExcit_I'].write("Results/nineml_neuron.g_exc", filter=[cells[0]])
    cells.recorders['cobaInhib_I'].write("Results/nineml_neuron.g_inh", filter=[cells[0]])

    t = cells.recorders['iaf_V'].get()[:, 1]
    v = cells.recorders['iaf_V'].get()[:, 2]
    gInh = cells.recorders['cobaInhib_g'].get()[:, 2]
    gExc = cells.recorders['cobaExcit_g'].get()[:, 2]
    IInh = cells.recorders['cobaInhib_I'].get()[:, 2]
    IExc = cells.recorders['cobaExcit_I'].get()[:, 2]

    import pylab
    pylab.subplot(311)
    pylab.ylabel('Voltage')
    pylab.plot(t, v)

    pylab.subplot(312)
    pylab.ylabel('Conductance')
    pylab.plot(t, gInh)
    pylab.plot(t, gExc)

    pylab.subplot(313)
    pylab.ylabel('Current')
    pylab.plot(t, IInh)
    pylab.plot(t, IExc)

    pylab.suptitle("From Tree-Model Pathway")
    pylab.show()

    sim.end()
Esempio n. 17
0
import nineml.abstraction_layer as nineml
import os
#import nineml.models
from nineml.abstraction_layer.example_models import get_hierachical_iaf_2coba
#from nineml.abstraction_layer.models import reduce_to_single_component, ModelToSingleComponentReducer
from nineml.abstraction_layer.flattening import flatten, ComponentFlattener
from nineml.abstraction_layer.writers import dump_reduced
from nineml.abstraction_layer.componentmodifiers import ComponentModifier



nest_classname = "iaf_cond_exp_9ml"



iaf_cond_exp_9ML_reduced = flatten( get_hierachical_iaf_2coba(), componentname=nest_classname )
iaf_cond_exp_9ML_reduced.backsub_aliases()
iaf_cond_exp_9ML_reduced.backsub_equations()
ComponentModifier.close_all_reduce_ports(component=iaf_cond_exp_9ML_reduced)

dump_reduced(iaf_cond_exp_9ML_reduced,'reduced.txt')



iaf_cond_exp_9ML_reduced.long_description = """
Long description of the iaf_cond_exp ...
Author: Eilif Muller, Ecublens, 2011
"""


iaf_cond_exp_9ML_reduced.short_description = "Standard integrate and fire with exponential conductance based synapses"
Esempio n. 18
0
    def test_Flattening4(self):

        c = ComponentClass(
            name='C',
            aliases=['C1:=cp1', 'C2 := cIn1', 'C3 := SV1', 'C4:=cIn2'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/cp2',
                    transitions=[On('SV1>cp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('c_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[AnalogReceivePort('cIn1'), AnalogReceivePort('cIn2'),
                          AnalogSendPort('C1'), AnalogSendPort('C2')],
            parameters=['cp1', 'cp2']
        )

        d = ComponentClass(
            name='D',
            aliases=['D1:=dp1', 'D2 := dIn1 + dp2', 'D3 := SV1'],
            regimes=[
                Regime(
                    'dSV1/dt = -SV1/dp2',
                    transitions=[On('SV1>dp1', do=[OutputEvent('emit')]),
                                 On('spikein', do=[OutputEvent('d_emit')])],
                    name='r1',
                ),
                Regime(name='r2', transitions=On('SV1>1', to='r1'))
            ],
            analog_ports=[AnalogReceivePort('dIn1'), AnalogReceivePort('dIn2'),
                          AnalogSendPort('D1'), AnalogSendPort('D2')],
            parameters=['dp1', 'dp2']
        )

        # Test Cloner, 2 levels of hierachy
        # ------------------------------ #

        # Everything should be as before:
        b = ComponentClass(name='B',
                           subnodes={'c1': c, 'c2': c, 'd': d},
                           portconnections=[('c1.C1', 'c2.cIn2'),
                                            ('c2.C1', 'c1.cIn1')],
                           )

        a = ComponentClass(name='A',
                           subnodes={'b': b, 'c': c},
                           portconnections=[('b.c1.C1', 'b.c1.cIn2'),
                                            ('b.c1.C1', 'b.c2.cIn1'),
                                            ('b.c1.C2', 'b.d.dIn1')]
                           )

        a_flat = flattening.flatten(a)

        # Name
        self.assertEqual(a_flat.name, 'A')

        # Aliases
        self.assertEqual(
            set(a_flat.aliases_map.keys()),
            set(['b_c1_C1', 'b_c1_C2', 'b_c1_C3', 'b_c1_C4',
                 'b_c2_C1', 'b_c2_C2', 'b_c2_C3', 'b_c2_C4',
                 'b_d_D1', 'b_d_D2', 'b_d_D3',
                 'c_C1', 'c_C2', 'c_C3', 'c_C4']))

        # - Regimes and Transitions:
        self.assertEqual(len(a_flat.regimes_map), 16)
        r_c1_1_c2_1_d_1_c_1 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r1 b.c2:r1 c:r1')
        r_c1_1_c2_2_d_1_c_1 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r1 b.c2:r2 c:r1')
        r_c1_2_c2_1_d_1_c_1 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r2 b.c2:r1 c:r1')
        r_c1_2_c2_2_d_1_c_1 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r2 b.c2:r2 c:r1')
        r_c1_1_c2_1_d_2_c_1 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r1 b.c2:r1 c:r1')
        r_c1_1_c2_2_d_2_c_1 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r1 b.c2:r2 c:r1')
        r_c1_2_c2_1_d_2_c_1 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r2 b.c2:r1 c:r1')
        r_c1_2_c2_2_d_2_c_1 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r2 b.c2:r2 c:r1')
        r_c1_1_c2_1_d_1_c_2 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r1 b.c2:r1 c:r2')
        r_c1_1_c2_2_d_1_c_2 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r1 b.c2:r2 c:r2')
        r_c1_2_c2_1_d_1_c_2 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r2 b.c2:r1 c:r2')
        r_c1_2_c2_2_d_1_c_2 = a_flat.flattener.get_new_regime('b.d:r1 b.c1:r2 b.c2:r2 c:r2')
        r_c1_1_c2_1_d_2_c_2 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r1 b.c2:r1 c:r2')
        r_c1_1_c2_2_d_2_c_2 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r1 b.c2:r2 c:r2')
        r_c1_2_c2_1_d_2_c_2 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r2 b.c2:r1 c:r2')
        r_c1_2_c2_2_d_2_c_2 = a_flat.flattener.get_new_regime('b.d:r2 b.c1:r2 b.c2:r2 c:r2')

        regimes = [
            r_c1_1_c2_1_d_1_c_1,
            r_c1_1_c2_2_d_1_c_1,
            r_c1_2_c2_1_d_1_c_1,
            r_c1_2_c2_2_d_1_c_1,
            r_c1_1_c2_1_d_2_c_1,
            r_c1_1_c2_2_d_2_c_1,
            r_c1_2_c2_1_d_2_c_1,
            r_c1_2_c2_2_d_2_c_1,
            r_c1_1_c2_1_d_1_c_2,
            r_c1_1_c2_2_d_1_c_2,
            r_c1_2_c2_1_d_1_c_2,
            r_c1_2_c2_2_d_1_c_2,
            r_c1_1_c2_1_d_2_c_2,
            r_c1_1_c2_2_d_2_c_2,
            r_c1_2_c2_1_d_2_c_2,
            r_c1_2_c2_2_d_2_c_2]
        self.assertEqual(len(set(regimes)), 16)

        # Do we have the right number of on_events and on_conditions:
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_1.on_events)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_1.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_1.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_1.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_1.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_1.on_conditions)), 4)

        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_2.on_events)), 3)
        self.assertEqual(len(list(r_c1_1_c2_1_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_2_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_2_c2_1_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_2_d_1_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_2.on_events)), 2)
        self.assertEqual(len(list(r_c1_1_c2_1_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_1_c2_2_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_2.on_events)), 1)
        self.assertEqual(len(list(r_c1_2_c2_1_d_2_c_2.on_conditions)), 4)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_2.on_events)), 0)
        self.assertEqual(len(list(r_c1_2_c2_2_d_2_c_2.on_conditions)), 4)

# All on_events return to thier same transition:
        for r in a_flat.regimes:
            for on_ev in r.on_events:
                self.assertEquals(on_ev.target_regime, r)

        # Check On-Event port names are remapped properly:
        self.assertEqual(set([ev.src_port_name for ev in r_c1_1_c2_1_d_1_c_1.on_events]), set(
            ['c_spikein', 'b_c1_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(set([ev.src_port_name for ev in r_c1_1_c2_2_d_1_c_1.on_events]), set(
            ['c_spikein', 'b_c1_spikein', 'b_d_spikein']))
        self.assertEqual(set([ev.src_port_name for ev in r_c1_2_c2_1_d_1_c_1.on_events]), set(
            ['c_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1_c_1.on_events]), set(['c_spikein', 'b_d_spikein']))
        self.assertEqual(set([ev.src_port_name for ev in r_c1_1_c2_1_d_2_c_1.on_events]), set(
            ['c_spikein', 'b_c1_spikein', 'b_c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2_c_1.on_events]), set(['c_spikein', 'b_c1_spikein', ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2_c_1.on_events]), set(['c_spikein', 'b_c2_spikein', ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_2_c_1.on_events]), set(['c_spikein']))

        self.assertEqual(set([ev.src_port_name for ev in r_c1_1_c2_1_d_1_c_2.on_events]), set(
            ['b_c1_spikein', 'b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_1_c_2.on_events]), set(['b_c1_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_1_c_2.on_events]), set(['b_c2_spikein', 'b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_2_d_1_c_2.on_events]), set(['b_d_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_1_d_2_c_2.on_events]), set(['b_c1_spikein', 'b_c2_spikein']))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_1_c2_2_d_2_c_2.on_events]), set(['b_c1_spikein', ]))
        self.assertEqual(
            set([ev.src_port_name for ev in r_c1_2_c2_1_d_2_c_2.on_events]), set(['b_c2_spikein', ]))
        self.assertEqual(set([ev.src_port_name for ev in r_c1_2_c2_2_d_2_c_2.on_events]), set([]))

        # ToDo: Check the OnConditions:

        #  - Ports & Parameters:
        self.assertEqual(
            set(a_flat.query.analog_ports_map.keys()),
            set(['b_c1_C1', 'b_c1_C2',
                 'b_c2_C1', 'b_c2_C2',
                 'b_d_dIn2', 'b_d_D1', 'b_d_D2',
                 'c_cIn1', 'c_cIn2', 'c_C1', 'c_C2']))

        self.assertEqual(
            set(a_flat.query.event_ports_map.keys()),
            set(['b_c1_spikein', 'b_c1_emit', 'b_c1_c_emit',
                 'b_c2_spikein', 'b_c2_emit', 'b_c2_c_emit',
                 'b_d_spikein', 'b_d_emit', 'b_d_d_emit',
                 'c_spikein', 'c_emit', 'c_c_emit', ]))

        self.assertEqual(
            set(a_flat.query.parameters_map.keys()),
            set(['c_cp1', 'c_cp2',
                 'b_c1_cp1', 'b_c1_cp2',
                 'b_c2_cp1', 'b_c2_cp2',
                 'b_d_dp1', 'b_d_dp2', ]))

        self.assertEqual(
            set(a_flat.state_variables_map.keys()),
            set(['b_c1_SV1', 'b_c2_SV1', 'b_d_SV1', 'c_SV1']))

        # Back-sub everything - then do we get the correct port mappings:
        a_flat.backsub_all()

        self.assertEqual(
            set(a_flat.aliases_map['b_c2_C4'].rhs_atoms),
            set(['b_c1_cp1']))

        self.assertEqual(
            set(a_flat.aliases_map['b_c1_C2'].rhs_atoms),
            set(['b_c2_cp1']))

        self.assertEqual(
            set(a_flat.aliases_map['b_c1_C4'].rhs_atoms),
            set(['b_c1_cp1']))

        self.assertEqual(
            set(a_flat.aliases_map['b_c2_C2'].rhs_atoms),
            set(['b_c1_cp1']))

        self.assertEqual(
            set(a_flat.aliases_map['b_d_D2'].rhs_atoms),
            set(['b_c2_cp1', 'b_d_dp2']))
Esempio n. 19
0
    def __new__(cls, name, bases, dct):

        import nineml.abstraction_layer as al
        from nineml.abstraction_layer import flattening, writers, component_modifiers
        import nest

        # Extract Parameters Back out from Dict:
        nineml_model = dct["nineml_model"]
        synapse_components = dct["synapse_components"]

        # Flatten the model:
        assert isinstance(nineml_model, al.ComponentClass)
        if nineml_model.is_flat():
            flat_component = nineml_model
        else:
            flat_component = flattening.flatten(nineml_model, name)

        # Make the substitutions:
        flat_component.backsub_all()
        # flat_component.backsub_aliases()
        # flat_component.backsub_equations()

        # Close any open reduce ports:
        component_modifiers.ComponentModifier.close_all_reduce_ports(component=flat_component)

        flat_component.short_description = "Auto-generated 9ML neuron model for PyNN.nest"
        flat_component.long_description = "Auto-generated 9ML neuron model for PyNN.nest"

        # Close any open reduce ports:
        component_modifiers.ComponentModifier.close_all_reduce_ports(component=flat_component)

        # synapse ports:
        synapse_ports = []
        for syn in synapse_components:
            # get recv event ports
            # TODO: model namespace look
            # syn_component = nineml_model[syn.namespace]
            syn_component = nineml_model.subnodes[syn.namespace]
            recv_event_ports = list(syn_component.query.event_recv_ports)
            # check there's only one
            if len(recv_event_ports) != 1:
                raise ValueError, "A synapse component has multiple recv ports.  Cannot dis-ambiguate"
            synapse_ports.append(syn.namespace + "_" + recv_event_ports[0].name)

        # New:
        dct["combined_model"] = flat_component
        # TODO: Override this with user layer
        # default_values = ModelToSingleComponentReducer.flatten_namespace_dict( parameters )
        dct["default_parameters"] = dict((p.name, 1.0) for p in flat_component.parameters)
        dct["default_initial_values"] = dict((s.name, 0.0) for s in flat_component.state_variables)
        dct["synapse_types"] = [syn.namespace for syn in synapse_components]
        dct["standard_receptor_type"] = dct["synapse_types"] == ("excitatory", "inhibitory")
        dct["injectable"] = True  # need to determine this. How??
        dct["conductance_based"] = True  # how to determine this??
        dct["model_name"] = name
        dct["nest_model"] = name

        # Recording from bindings:
        dct["recordable"] = [port.name for port in flat_component.analog_ports] + ["spikes", "regime"]
        # TODO bindings -> alias and support recording of them in nest template
        # + [binding.name for binding in flat_component.bindings]

        dct["weight_variables"] = dict(
            [(syn.namespace, syn.namespace + "_" + syn.weight_connector) for syn in synapse_components]
        )

        logger.debug("Creating class '%s' with bases %s and dictionary %s" % (name, bases, dct))

        # TODO: UL configuration of initial regime.
        initial_regime = flat_component.regimes_map.keys()[0]

        from nestbuilder import NestFileBuilder

        nfb = NestFileBuilder(
            nest_classname=name,
            component=flat_component,
            synapse_ports=synapse_ports,
            initial_regime=initial_regime,
            initial_values=dct["default_initial_values"],
            default_values=dct["default_parameters"],
        )
        nfb.compile_files()
        nest.Install("mymodule")

        return type.__new__(cls, name, bases, dct)
Esempio n. 20
0

"""

import nineml.abstraction_layer as nineml
import os
#import nineml.models
from nineml.abstraction_layer.example_models import get_hierachical_iaf_2coba
#from nineml.abstraction_layer.models import reduce_to_single_component, ModelToSingleComponentReducer
from nineml.abstraction_layer.flattening import flatten, ComponentFlattener
from nineml.abstraction_layer.writers import dump_reduced
from nineml.abstraction_layer.componentmodifiers import ComponentModifier

nest_classname = "iaf_cond_exp_9ml"

iaf_cond_exp_9ML_reduced = flatten(get_hierachical_iaf_2coba(),
                                   componentname=nest_classname)
iaf_cond_exp_9ML_reduced.backsub_aliases()
iaf_cond_exp_9ML_reduced.backsub_equations()
ComponentModifier.close_all_reduce_ports(component=iaf_cond_exp_9ML_reduced)

dump_reduced(iaf_cond_exp_9ML_reduced, 'reduced.txt')

iaf_cond_exp_9ML_reduced.long_description = """
Long description of the iaf_cond_exp ...
Author: Eilif Muller, Ecublens, 2011
"""

iaf_cond_exp_9ML_reduced.short_description = "Standard integrate and fire with exponential conductance based synapses"

# Things we need to know which should come from the user layer
synapse_ports = ['cobaExcit_spikeinput', 'cobaInhib_spikeinput']