Exemplo n.º 1
0
iaf1.add(lems.Parameter('reset', 'voltage'))
iaf1.add(lems.Parameter('refractoryPeriod', 'time'))
iaf1.add(lems.Parameter('capacitance', 'capacitance'))
iaf1.add(lems.Exposure('vexp', 'voltage'))
dp = lems.DerivedParameter('range', 'threshold - reset', 'voltage')
iaf1.add(dp)

iaf1.dynamics.add(lems.StateVariable('v','voltage', 'vexp')) 
iaf1.dynamics.add(lems.DerivedVariable('v2',dimension='voltage', value='v*2'))
cdv = lems.ConditionalDerivedVariable('v_abs','voltage')
cdv.add(lems.Case('v .geq. 0','v'))
cdv.add(lems.Case('v .lt. 0','-1*v'))
iaf1.dynamics.add(cdv)


model.add(lems.Component('celltype_a', iaf1.name))
model.add(lems.Component('celltype_b', iaf1.name, threshold="20mV"))

fn = '/tmp/model.xml'
model.export_to_file(fn)

print("----------------------------------------------")
print(open(fn,'r').read())
print("----------------------------------------------")

print("Written generated LEMS to %s"%fn)

from lems.base.util import validate_lems

validate_lems(fn)
Exemplo n.º 2
0
    def add_neurongroup(self, neurongrp, index_neurongrp, initializers):
        """
        Add NeuronGroup to self._model
    
        If number of elements is 1 it adds component of that type, if
        it's bigger, the network is created by calling:
        `make_multiinstantiate`.

        Parameters
        ----------
        neurongrp : dict
            Standard dictionary representation of NeuronGroup object
        index_neurongrp : int
            Index of neurongroup in the network
        initializers : list
            List of initializers defined in the network
        """
        # get name of the neurongrp
        component_name = neurongrp['name']
        self._model_namespace["neuronname"] = component_name
        # add BASE_CELL component
        self._component_type = lems.ComponentType(component_name,
                                                  extends=BASE_CELL)
        # get identifiers attached to neurongrp and create special_properties dict
        identifiers = []
        special_properties = {}

        if 'identifiers' in neurongrp:
            identifiers = neurongrp['identifiers']

        for initializer in initializers:
            if 'identifiers' in initializer:
                identifiers.update(initializer['identifiers'])

        for identifier in identifiers.keys():
            special_properties.update({identifier: None})

        # add the identifers as properties of the component
        for param in self._determine_properties(identifiers):
            self._component_type.add(param)
        # common things for every neuron definition
        # TODO: Is this same for custom events too?
        self._component_type.add(lems.EventPort(name='spike', direction='out'))

        # dynamics of the network
        dynamics = lems.Dynamics()
        # get neurongrp equations
        equations = neurongrp['equations']
        # loop over the variables
        initializer_vars = []
        for initializer in initializers:
            if initializer['source'] == neurongrp['name']:
                initializer_vars.append(initializer['variable'])

        for var in equations.keys():

            # determine the dimension
            dimension = _determine_dimension(equations[var]['unit'])
            # add to all_params_unit
            self._all_params_unit[var] = dimension
            # identify diff eqns to add Exposure
            if equations[var]['type'] == 'differential equation':
                state_var = lems.StateVariable(var,
                                               dimension=dimension,
                                               exposure=var)
                self._component_type.add(
                    lems.Exposure(var, dimension=dimension))
                dynamics.add_state_variable(state_var)
            else:
                if var in initializer_vars and 'i' in initializer['value']:
                    self._component_type.add(lems.Property(var, dimension))
                    special_properties[var] = initializer['value']
                    continue
                state_var = lems.StateVariable(var, dimension=dimension)
                dynamics.add_state_variable(state_var)

        # what happens at initialization
        onstart = lems.OnStart()
        # loop over the initializers
        for var in equations.keys():
            if var in (NOT_REFRACTORY, LAST_SPIKE):
                continue
            # check the initializer is connected to this neurongrp
            if var not in initializer_vars:
                continue
            if var in special_properties:
                continue
            for initializer in initializers:
                if initializer['variable'] == var and initializer[
                        'source'] == neurongrp['name']:
                    init_value = initializer['value']
            if type(init_value) != str:
                value = brian_unit_to_lems(init_value)
            else:
                value = renderer.render_expr(str(init_value))
            # add to onstart
            onstart.add(lems.StateAssignment(var, value))
        dynamics.add(onstart)

        # check whether refractoriness is defined
        if ('events' in neurongrp and 'spike' in neurongrp['events']
                and 'refractory' in neurongrp['events']['spike']):
            # if refractoriness, we create separate regimes for integrating
            integr_regime = lems.Regime(INTEGRATING, dynamics,
                                        True)  # True -> initial regime
            # check spike event
            # NOTE: isn't refractory only for spike events?
            for spike_flag, on_cond in self._event_builder(
                    neurongrp['events']):
                if spike_flag:
                    # if spike occured we make transition to refractory regime
                    on_cond.add_action(lems.Transition(REFRACTORY))
                integr_regime.add_event_handler(on_cond)
            # add refractory regime
            refrac_regime = lems.Regime(REFRACTORY, dynamics)
            # make lastspike variable and initialize it
            refrac_regime.add_state_variable(
                lems.StateVariable(LAST_SPIKE, dimension='time'))
            oe = lems.OnEntry()
            oe.add(lems.StateAssignment(LAST_SPIKE, 't'))
            refrac_regime.add(oe)
            # after refractory time we make transition to integrating regime
            refractory_code = neurongrp['events']['spike']['refractory']
            if not _equation_separator(str(refractory_code)):
                # if there is no specific variable given, we assume
                # that this is time condition
                ref_oc = lems.OnCondition('t .gt. ( {0} + {1} )'.format(
                    LAST_SPIKE, brian_unit_to_lems(refractory_code)))
            else:
                ref_oc = lems.OnCondition(
                    renderer.render_expr(refractory_code))
            ref_trans = lems.Transition(INTEGRATING)
            ref_oc.add_action(ref_trans)
            refrac_regime.add_event_handler(ref_oc)
            # identify variables with differential equation
            for var in neurongrp['equations']:
                if neurongrp['equations'][var][
                        'type'] == 'differential equation':
                    diff_var = neurongrp['equations'][var]
                    # get the expression
                    td = lems.TimeDerivative(
                        var, renderer.render_expr(diff_var['expr']))
                    # check flags for UNLESS_REFRACTORY TODO: is this available in 'flags' key?
                    if 'flags' in diff_var:
                        # if unless refratory we add only do integration regime
                        if UNLESS_REFRACTORY in diff_var['flags']:
                            integr_regime.add_time_derivative(td)
                            continue
                    # add time derivative to both regimes
                    integr_regime.add_time_derivative(td)
                    refrac_regime.add_time_derivative(td)
            # add the regimes to dynamics
            dynamics.add_regime(integr_regime)
            dynamics.add_regime(refrac_regime)

        else:
            # adding events directly to dynamics
            for spike_flag, on_cond in self._event_builder(
                    neurongrp['events']):
                dynamics.add_event_handler(on_cond)
            # get variables with diff eqns
            for var in neurongrp['equations']:
                if neurongrp['equations'][var][
                        'type'] == 'differential equation':
                    diff_var = neurongrp['equations'][var]
                    td = lems.TimeDerivative(
                        var, renderer.render_expr(diff_var['expr']))
                    # add to dynamics
                    dynamics.add_time_derivative(td)
        # add dynamics to _component_type
        self._component_type.dynamics = dynamics
        # add _component_type to _model
        self._model.add_component_type(self._component_type)
        # get identifiers
        paramdict = dict()
        for ident_name, ident_value in neurongrp['identifiers'].items():
            paramdict[ident_name] = self._unit_lems_validator(ident_value)
        # if more than one neuron use multiinstantiate
        if neurongrp['N'] == 1:
            self._model.add(
                lems.Component("n{}".format(index_neurongrp), component_name,
                               **paramdict))
        else:
            self.make_multiinstantiate(special_properties, component_name,
                                       paramdict, neurongrp['N'])
Exemplo n.º 3
0
    def handle_population(self,
                          population_id,
                          component,
                          size=-1,
                          component_obj=None,
                          properties={}):

        sizeInfo = " as yet unspecified size"
        if size >= 0:
            sizeInfo = ", size: " + str(size) + " cells"
        if component_obj:
            compInfo = " (%s)" % component_obj.__class__.__name__
        else:
            compInfo = ""

        print_v("Population: " + population_id + ", component: " + component +
                compInfo + sizeInfo + ", properties: %s" % properties)

        if size >= 0:
            for i in range(size):
                node_id = "%s_%i" % (population_id, i)
                node = {}

                comp = self.nl_network.get_child(component, "cells")
                base_dir = "./"  # for now...

                if properties:
                    node["metadata"] = properties

                node["parameters"] = {}
                node["input_ports"] = {}
                node["output_ports"] = {}
                if comp is not None:
                    if comp.lems_source_file:
                        fname = locate_file(comp.lems_source_file, base_dir)
                        model = MDFHandler._load_lems_file_with_neuroml2_types(
                            fname)
                        lems_comp = model.components.get(component)

                    if comp.neuroml2_cell:
                        model = MDFHandler._get_lems_model_with_neuroml2_types(
                        )
                        lems_comp = lems.Component(id_=comp.id,
                                                   type_=comp.neuroml2_cell)
                        for p in comp.parameters:
                            lems_comp.set_parameter(
                                p,
                                evaluate(comp.parameters[p],
                                         self.nl_network.parameters),
                            )

                    print_v("All LEMS comps in model: %s" %
                            model.components.keys())
                    print_v("This comp: %s" % lems_comp)
                    comp_type_name = lems_comp.type
                    lems_comp_type = model.component_types.get(comp_type_name)
                    notes = "Cell: [%s] is defined in %s and in Lems is: %s" % (
                        comp,
                        comp.lems_source_file,
                        lems_comp,
                    )

                    node["notes"] = notes

                    for p in lems_comp.parameters:
                        node["parameters"][p] = {
                            "value":
                            get_value_in_si(evaluate(lems_comp.parameters[p]))
                        }

                    for c in lems_comp_type.constants:
                        node["parameters"][c.name] = {
                            "value": get_value_in_si(c.value)
                        }

                    for sv in lems_comp_type.dynamics.state_variables:
                        node["parameters"][sv.name] = {}
                        if sv.exposure:
                            node["output_ports"][sv.exposure] = {
                                "value": sv.name
                            }

                    for dv in lems_comp_type.dynamics.derived_variables:

                        print_v("Converting: %s (exp: %s) = [%s] or [%s]" %
                                (dv.name, dv.exposure, dv.value, dv.select))
                        if dv.name == "INPUT":
                            node["input_ports"][dv.name] = {}
                        else:
                            if dv.value is not None:
                                node["parameters"][dv.name] = {
                                    "value": self._convert_value(dv.value)
                                }
                                if dv.exposure:
                                    node["output_ports"][dv.exposure] = {
                                        "value": dv.name
                                    }
                            if dv.select is not None:
                                in_port = dv.select.replace("[*]/", "_")
                                node["input_ports"][in_port] = {}
                                node["parameters"][dv.name] = {
                                    "value": in_port
                                }

                    conditions = 0
                    for eh in lems_comp_type.dynamics.event_handlers:

                        print_v("Converting: %s (type: %s)" % (eh, type(eh)))
                        if type(eh) == lems.OnStart:
                            for a in eh.actions:
                                if type(a) == lems.StateAssignment:
                                    node["parameters"][a.variable][
                                        "default_initial_value"] = a.value
                        if type(eh) == lems.OnCondition:
                            test = (eh.test.replace(".gt.", ">").replace(
                                ".geq.", ">=").replace(".lt.", "<").replace(
                                    ".leq.", "<=").replace(".eq.", "=="))
                            for a in eh.actions:
                                if type(a) == lems.StateAssignment:
                                    if (not "conditions"
                                            in node["parameters"][a.variable]):
                                        node["parameters"][
                                            a.variable]["conditions"] = {}

                                    node["parameters"][
                                        a.variable]["conditions"][
                                            "condition_%i" % conditions] = {
                                                "test": test,
                                                "value": a.value
                                            }
                            conditions += 1

                    for td in lems_comp_type.dynamics.time_derivatives:
                        node["parameters"][td.variable][
                            "time_derivative"] = self._convert_value(td.value)

                self.mdf_graph["nodes"][node_id] = node
Exemplo n.º 4
0
def create_GoC_network( duration, dt, seed, N_goc=0, run=False, prob_type='Boltzmann', GJw_type='Vervaeke2010' ):


	goc_filename = 'GoC.cell.nml'
	goc_file = pynml.read_neuroml2_file( goc_filename )
	goc_type = goc_file.cells[0]
	
	GJ_filename = 'GapJuncCML.nml'
	GJ_file = pynml.read_neuroml2_file( GJ_filename )
	GJ_type = GJ_file.gap_junctions[0]

	MFSyn_filename = 'MF_GoC_Syn.nml'
	mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename )
	MFSyn_type = mfsyn_file.exp_three_synapses[0]
	
	MF20Syn_filename = 'MF_GoC_SynMult.nml'
	mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename )
	MF20Syn_type = mf20syn_file.exp_three_synapses[0]
	
	# Distribute cells in 3D
	if N_goc>0:
		GoC_pos = nu.GoC_locate(N_goc)
	else:
		GoC_pos = nu.GoC_density_locate()
		N_goc = GoC_pos.shape[0]
		
	# get GJ connectivity
	GJ_pairs, GJWt = nu.GJ_conn( GoC_pos, prob_type, GJw_type )
	tmp1, tmp2 = valnet.gapJuncAnalysis( GJ_pairs, GJWt )
	print("Number of gap junctions per cell: ", tmp1)
	print("Net GJ conductance per cell:", tmp2)
	
	# Create pop List
	goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=N_goc )
	
	# Create NML document for network specification
	net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" )
	net_doc = nml.NeuroMLDocument( id=net.id )
	net_doc.networks.append( net )
	net_doc.includes.append( goc_type )
	
	net.populations.append( goc_pop )
	
	#Add locations for GoC instances in the population:
	for goc in range(N_goc):
		inst = nml.Instance( id=goc )
		goc_pop.instances.append( inst )
		inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2] )
		
	# Define input spiketrains
	input_type = 'spikeGenerator'#'spikeGeneratorPoisson'
	lems_inst_doc = lems.Model()
	mf_inputs = lems.Component( "MF_Input", input_type)
	mf_inputs.set_parameter("period", "2000 ms" )
	#mf_inputs.set_parameter("averageRate", "50 Hz")
	lems_inst_doc.add( mf_inputs )
	
	#synapse_type = 'alphaCurrentSynapse'
	#alpha_syn = lems.Component( "AlphaSyn", synapse_type)
	#alpha_syn.set_parameter("tau", "30 ms" )
	#alpha_syn.set_parameter("ibase", "200 pA")
	#lems_inst_doc.add( alpha_syn )
	
	# Define MF input population
	
	N_mf = 15
	#MF_pop = nml.Population(id=mf_inputs.id+"_pop", component=mf_inputs.id, type="populationList", size=N_mf)
	#net.populations.append( MF_pop )

	mf_type2 = 'spikeGeneratorPoisson'
	#mf_poisson = lems.Component( "MF_Poisson", mf_type2)
	#mf_poisson.set_parameter("averageRate", "5 Hz")
	#lems_inst_doc.add( mf_poisson )
	# adding in neuroml document instead of mf_poisson
	mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" )
	net_doc.spike_generator_poissons.append( mf_poisson )
	
	net_doc.includes.append( goc_type )
	MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=N_mf)
	net.populations.append( MF_Poisson_pop )
	MF_pos = nu.GoC_locate( N_mf )
	for mf in range( N_mf ):
		inst = nml.Instance(id=mf)
		MF_Poisson_pop.instances.append( inst )
		inst.location = nml.Location( x=MF_pos[mf,0], y=MF_pos[mf,1], z=MF_pos[mf,2] )
		
	# Setup Mf->GoC synapses
	#MFprojection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_pop.id, postsynaptic_population=goc_pop.id, synapse=alpha_syn.id)
	#net.projections.append(MFprojection)

	MF2projection = nml.Projection(id="MF2toGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id)#alpha_syn.id
	net.projections.append(MF2projection)


	#Get list of MF->GoC synapse
	mf_synlist = nu.randdist_MF_syn( N_mf, N_goc, pConn=0.3)
	nMFSyn = mf_synlist.shape[1]
	for syn in range( nMFSyn ):
		mf, goc = mf_synlist[:, syn]
		conn2 = nml.Connection(id=syn, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)
		
		
	# Burst of MF input (as explicit input)
	mf_bursttype = 'transientPoissonFiringSynapse'
	mf_burst = lems.Component( "MF_Burst", mf_bursttype)
	mf_burst.set_parameter( "averageRate", "100 Hz" )
	mf_burst.set_parameter( "delay", "2000 ms" )
	mf_burst.set_parameter( "duration", "500 ms" )
	mf_burst.set_parameter( "synapse", MF20Syn_type.id )
	mf_burst.set_parameter( "spikeTarget", './{}'.format(MF20Syn_type.id) )
	lems_inst_doc.add( mf_burst )
	
	
	# Add few burst inputs
	n_bursts = 4
	gocPerm = np.random.permutation( N_goc )
	ctr = 0
	for gg in range(4):
		goc = gocPerm[gg]
		for jj in range( n_bursts ):
			inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id))
			net.explicit_inputs.append( inst )
			ctr += 1
		
	
	'''
	one-to-one pairing of MF and GoC -> no shared inputs
	for goc in range(N_mf):
		#inst = nml.Instance(id=goc)
		#MF_pop.instances.append( inst )
		#inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2]+100 )
		#conn = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_pop.id, goc, mf_inputs.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		#MFprojection.connections.append(conn)

		goc2 = N_goc-goc-1
		inst2 = nml.Instance(id=goc)
		MF_Poisson_pop.instances.append( inst2 )
		inst2.location = nml.Location( x=GoC_pos[goc2,0], y=GoC_pos[goc2,1], z=GoC_pos[goc2,2]+100 )
		conn2 = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, goc, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc2, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)

	'''
	
	# Add electrical synapses
	GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id )
	
	#print(GJ_pairs)
	gj = nml.GapJunction( id="GJ_0", conductance="426pS" )
	net_doc.gap_junctions.append(gj)
	nGJ = GJ_pairs.shape[0]
	for jj in range( nGJ ):
		#gj.append( lems.Component( "GJ_%d"%jj, 'gapJunction') )
		#gj[jj].set_parameter( "conductance", "%fnS"%(GJWt[jj]) )
		#gj = nml.GapJunction(id="GJ_%d"%jj, conductance="%fnS"%(GJWt[jj]))
		#net_doc.gap_junctions.append(gj)
		#lems_inst_doc.add( gj[jj] )
		#print("%fnS"%(GJWt[jj]*0.426))
		conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,0], goc_type.id), pre_segment='1', pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,1], goc_type.id), post_segment='1', post_fraction_along='0.5', synapse=gj.id, weight=GJWt[jj] )#synapse="GapJuncCML" synapse=gj.id , conductance="100E-9mS"
		# ------------ need to create GJ component
		GoCCoupling.electrical_connection_instance_ws.append( conn )
	
	net.electrical_projections.append( GoCCoupling )	
		
		
		
	net_filename = 'gocNetwork.nml'
	pynml.write_neuroml2_file( net_doc, net_filename )
	lems_filename = 'instances.xml'
	pynml.write_lems_file( lems_inst_doc, lems_filename, validate=False )

	simid = 'sim_gocnet'+goc_type.id
	ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed )
	ls.assign_simulation_target( net.id )
	
	#ls.include_lems_file( 'Synapses.xml', include_included=False)
	#ls.include_lems_file( 'Inputs.xml', include_included=False)
	ls.include_neuroml2_file( net_filename)
	ls.include_neuroml2_file( goc_filename)
	ls.include_neuroml2_file( GJ_filename)
	ls.include_neuroml2_file( MFSyn_filename)
	ls.include_neuroml2_file( MF20Syn_filename)
	ls.include_lems_file( lems_filename, include_included=False)
	
	
	# Specify outputs
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	for jj in range( goc_pop.size):
		ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' )
		
	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	for jj in range( goc_pop.size ):
		ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id))
		
	#Create Lems file to run
	lems_simfile = ls.save_to_file()

	#res = pynml.run_lems_with_jneuroml( lems_simfile, max_memory="1G",nogui=True, plot=False)
	#res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", compile_mods = False,nogui=True, plot=False)
	#res=True
	return res
Exemplo n.º 5
0
lorenz.dynamics.add(
    lems.StateVariable(name="z", dimension="none", exposure="z"))

lorenz.dynamics.add(
    lems.TimeDerivative(variable="x", value="( sigma * (y - x)) / sec"))
lorenz.dynamics.add(
    lems.TimeDerivative(variable="y", value="( rho * x - y - x * z ) / sec"))
lorenz.dynamics.add(
    lems.TimeDerivative(variable="z", value="( x * y - beta * z) / sec"))

onstart = lems.OnStart()
onstart.add(lems.StateAssignment(variable="x", value="x0"))
onstart.add(lems.StateAssignment(variable="y", value="y0"))
onstart.add(lems.StateAssignment(variable="z", value="z0"))
lorenz.dynamics.add(onstart)

model.add(
    lems.Component(id_="lorenzCell",
                   type_=lorenz.name,
                   sigma="10",
                   beta="2.67",
                   rho="28",
                   x0="1.0",
                   y0="1.0",
                   z0="1.0"))

file_name = "LEMS_lorenz.xml"
model.export_to_file(file_name)

validate_lems(file_name)
def generate_grc_layer_network(
        runID,
        correlationRadius,
        NADT,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz
        OFFRate,  # Hz
        run=False):
    ########################################
    # Load parameters for this run
    file = open('../params_file.pkl', 'r')
    p = pkl.load(file)
    N_syn = p['N_syn'][int(runID) - 1]
    f_mf = p['f_mf'][int(runID) - 1]
    run_num = p['run_num'][int(runID) - 1]
    file.close()
    #################################################################################
    # Get connectivity matrix between cells
    file = open('../../network_structures/GCLconnectivity_' + str(N_syn) +
                '.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == N_syn)), 'Connectivity matrix is incorrect.'
    # Get MF activity pattern
    if correlationRadius == 0:  # Activate MFs randomly
        N_mf_ON = int(N_mf * f_mf)
        mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
        mf_indices_ON.sort()
    elif correlationRadius > 0:  # Spatially correlated MFs
        f_mf_range = np.linspace(.05, .95, 19)
        f_mf_ix = np.where(f_mf_range == f_mf)[0][0]
        p = io.loadmat('../../input_statistics/mf_patterns_r' +
                       str(correlationRadius) + '.mat')
        R = p['Rs'][:, :, f_mf_ix]
        g = p['gs'][f_mf_ix]
        t = np.dot(R.transpose(), np.random.randn(N_mf))
        S = (t > -g * np.ones(N_mf))
        mf_indices_ON = np.where(S)[0]
        N_mf_ON = len(mf_indices_ON)
    #
    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()
    #################################################################################
    # load NeuroML components, LEMS components and LEMS componentTypes from external files
    # Spike generator (for Poisson MF spiking)
    spike_generator_file_name = "../../grc_lemsDefinitions/spikeGenerators.xml"
    spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)
    # Integrate-and-fire GC model
    # if NADT = 1, loads model GC
    iaf_nml2_file_name = "../../grc_lemsDefinitions/IaF_GrC.nml" if NADT == 0 else "../../grc_lemsDefinitions/IaF_GrC_" + '{:.2f}'.format(
        f_mf) + ".nml"
    iaF_GrC_doc = pynml.read_neuroml2_file(iaf_nml2_file_name)
    iaF_GrC = iaF_GrC_doc.iaf_ref_cells[0]
    # AMPAR and NMDAR mediated synapses
    ampa_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCAMPA_" + str(
        N_syn) + ".xml"
    nmda_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCNMDA_" + str(
        N_syn) + ".xml"
    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)
    #
    # Define components from the componentTypes we just loaded
    # Refractory poisson input -- representing active MF
    spike_generator_ref_poisson_type = spike_generator_doc.component_types[
        'spikeGeneratorRefPoisson']
    lems_instances_doc = lems.Model()
    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type.name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)
    # Refractory poisson input -- representing silent MF
    spike_generator_off = lems.Component("mossySpikerOFF",
                                         spike_generator_ref_poisson_type.name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)
    # Synapses
    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id
    #
    # Create ON MF, OFF MF, and GC populations
    GrCPop = nml.Population(id="GrCPop", component=iaF_GrC.id, size=N_grc)
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       size=N_mf_ON)
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    #
    # Create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)
    #
    # MF-GC connectivity
    # First connect ON MFs to GCs
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopON.id, mf_ix_ON),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Now connect OFF MFs to GCs
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopOFF.id, mf_ix_OFF),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Write network to file
    net_file_name = 'generated_network_' + runID + '.net.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)
    # Write LEMS instances to file
    lems_instances_file_name = 'instances_' + runID + '.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)
    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation('sim_' + runID,
                        duration,
                        dt,
                        lems_seed=int(np.round(1000 * random.random())))
    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)
    # Include generated/existing NeuroML2 files
    ls.include_neuroml2_file(iaf_nml2_file_name)
    ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)
    # Specify Displays and Output Files
    # Details for saving output files
    basedir = '../data_r' + str(
        correlationRadius) + '/' if NADT == 0 else '../data_r' + str(
            correlationRadius) + '_NADT/'
    end_filename = str(N_syn) + '_{:.2f}'.format(f_mf) + '_' + str(
        run_num)  # Add parameter values to spike time filename
    # Save MF spike times under basedir + MF_spikes_ + end_filename
    eof0 = 'MFspikes_file'
    ls.create_event_output_file(eof0,
                                basedir + "MF_spikes_" + end_filename + ".dat")
    # ON MFs
    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], "%s[%i]" % (mossySpikersPopON.id, i),
            'spike')
    # OFF MFs
    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i], "%s[%i]" % (mossySpikersPopOFF.id, i),
            'spike')
    # Save GC spike times under basedir + GrC_spikes_ + end_filename
    eof1 = 'GrCspikes_file'
    ls.create_event_output_file(
        eof1, basedir + "GrC_spikes_" + end_filename + ".dat")
    #
    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(eof1, i,
                                              "%s[%i]" % (GrCPop.id, i),
                                              'spike')
    #
    lems_file_name = ls.save_to_file()
    #
    if run:
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results
Exemplo n.º 7
0
model.add(lems.Dimension('voltage', m=1, l=3, t=-3, i=-1))
model.add(lems.Dimension('time', t=1))
model.add(lems.Dimension('capacitance', m=-1, l=-2, t=4, i=2))

model.add(lems.Unit('milliVolt', 'mV', 'voltage', -3))
model.add(lems.Unit('milliSecond', 'ms', 'time', -3))
model.add(lems.Unit('microFarad', 'uF', 'capacitance', -12))

iaf1 = lems.ComponentType('iaf1')
model.add(iaf1)

iaf1.add(lems.Parameter('threshold', 'voltage'))
iaf1.add(lems.Parameter('refractoryPeriod', 'time'))
iaf1.add(lems.Parameter('capacitance', 'capacitance'))

model.add(lems.Component('celltype_a', 'iaf1'))

fn = '/tmp/model.xml'
model.export_to_file(fn)

print("----------------------------------------------")
print(open(fn, 'r').read())
print("----------------------------------------------")

print("Written generated LEMS to %s" % fn)

from lems.base.util import validate_lems

validate_lems(fn)
Exemplo n.º 8
0
def generate_grc_layer_network(
        p_mf_ON,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz 
        OFFRate,  # Hz
        run=False):

    # Load connectivity matrix

    file = open('GCLconnectivity.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == 4)), 'Connectivity matrix is incorrect.'

    # Load GrC and MF rosette positions

    grc_pos = p['grc_pos']
    glom_pos = p['glom_pos']

    # Choose which mossy fibers are on, which are off

    N_mf_ON = int(N_mf * p_mf_ON)
    mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
    mf_indices_ON.sort()

    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()

    # load NeuroML components, LEMS components and LEMS componentTypes from external files

    ##spikeGeneratorRefPoisson is now a standard nml type...
    ##spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)

    iaF_GrC = nml.IafRefCell(id="iaF_GrC",
                             refract="2ms",
                             C="3.22pF",
                             thresh="-40mV",
                             reset="-63mV",
                             leak_conductance="1.498nS",
                             leak_reversal="-79.67mV")

    ampa_syn_filename = "RothmanMFToGrCAMPA.xml"
    nmda_syn_filename = "RothmanMFToGrCNMDA.xml"

    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)

    # define some components from the componentTypes we just loaded
    ##spike_generator_ref_poisson_type = spike_generator_doc.component_types['spikeGeneratorRefPoisson']

    lems_instances_doc = lems.Model()
    spike_generator_ref_poisson_type_name = 'spikeGeneratorRefPoisson'

    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type_name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)

    spike_generator_off = lems.Component(
        "mossySpikerOFF", spike_generator_ref_poisson_type_name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)

    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id

    # create populations
    GrCPop = nml.Population(id=iaF_GrC.id + "Pop",
                            component=iaF_GrC.id,
                            type="populationList",
                            size=N_grc)
    GrCPop.properties.append(nml.Property(tag='color', value='0 0 0.8'))
    GrCPop.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       type="populationList",
                                       size=N_mf_ON)
    mossySpikersPopON.properties.append(
        nml.Property(tag='color', value='0.8 0 0'))
    mossySpikersPopON.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    mossySpikersPopOFF.properties.append(
        nml.Property(tag='color', value='0 0.8 0'))
    mossySpikersPopOFF.properties.append(nml.Property(tag='radius', value=2))

    # create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.iaf_ref_cells.append(iaF_GrC)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)

    #net_doc.includes.append(nml.IncludeType(href=iaf_nml2_file_name))

    # Add locations for GCs

    for grc in range(N_grc):
        inst = nml.Instance(id=grc)
        GrCPop.instances.append(inst)
        inst.location = nml.Location(x=grc_pos[grc, 0],
                                     y=grc_pos[grc, 1],
                                     z=grc_pos[grc, 2])

    # ON MFs: locations and connectivity

    ONprojectionAMPA = nml.Projection(
        id="ONProjAMPA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    ONprojectionNMDA = nml.Projection(
        id="ONProjNMDA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(ONprojectionAMPA)
    net.projections.append(ONprojectionNMDA)

    ix = 0
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        inst = nml.Instance(id=mf_ix_ON)
        mossySpikersPopON.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopON.id,
                                                     mf_ix_ON,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                ONprojectionAMPA.connections.append(connection)
                ONprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # OFF MFs: locations and connectivity

    OFFprojectionAMPA = nml.Projection(
        id="OFFProjAMPA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    OFFprojectionNMDA = nml.Projection(
        id="OFFProjNMDA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(OFFprojectionAMPA)
    net.projections.append(OFFprojectionNMDA)

    ix = 0
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        inst = nml.Instance(id=mf_ix_OFF)
        mossySpikersPopOFF.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopOFF.id,
                                                     mf_ix_OFF,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                OFFprojectionAMPA.connections.append(connection)
                OFFprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # Write network to file
    net_file_name = 'OSBnet.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)

    # Write LEMS instances to file
    lems_instances_file_name = 'instances.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)

    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation(
        'sim', duration, dt,
        simulation_seed=123)  # int(np.round(1000*random.random())))

    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)

    # Include generated/existing NeuroML2 files
    ###ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)

    # Specify Displays and Output Files

    basedir = ''

    eof0 = 'Volts_file'
    ls.create_event_output_file(eof0, basedir + "MF_spikes.dat")

    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], '{}/{}/{}'.format(mossySpikersPopON.id, i,
                                                      spike_generator_on.id),
            'spike')

    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i],
            '{}/{}/{}'.format(mossySpikersPopOFF.id, i,
                              spike_generator_on.id), 'spike')

    eof1 = 'GrCspike_file'
    ls.create_event_output_file(eof1, basedir + "GrC_spikes.dat")

    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(
            eof1, i, '{}/{}/{}'.format(GrCPop.id, i, iaF_GrC.id), 'spike')

    lems_file_name = ls.save_to_file()

    if run:
        print('Running the generated LEMS file: %s for simulation of %sms' %
              (lems_file_name, duration))
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results
Exemplo n.º 9
0
    def add_neurongroup(self, obj, idx_of_ng, namespace, initializers):
        """
        Adds NeuronGroup object *obj* to self._model.

        If number of elements is 1 it adds component of that type, if
        it's bigger, the network is created by calling:
        `make_multiinstantiate`.

        Parameters
        ----------
        obj : brian2.NeuronGroup
            NeuronGroup object to parse
        idx_of_ng : int
            index of neurongroup
        namespace : dict
            dictionary with all neccassary variables definition
        initializers : dict
            initial values for all model variables
        """
        if hasattr(obj, "namespace") and not obj.namespace:
            obj.namespace = namespace
        self._nr_of_neurons = obj.N  # maybe not the most robust solution
        ct_name = "neuron{}".format(idx_of_ng+1)
        self._model_namespace["neuronname"] = ct_name
        self._component_type = lems.ComponentType(ct_name, extends=BASE_CELL)
        # adding parameters
        special_properties = {}
        for key in obj.namespace.keys():
            special_properties[key] = None
        for param in self._determine_properties(obj.namespace):
            self._component_type.add(param)
        # common things for every neuron definition
        self._component_type.add(lems.EventPort(name='spike', direction='out'))
        # dynamics of the network
        dynamics = lems.Dynamics()
        ng_equations = obj.user_equations
        for var in ng_equations:
            if ng_equations[var].type == DIFFERENTIAL_EQUATION:
                dim_ = _determine_dimension(ng_equations[var].unit)
                sv_ = lems.StateVariable(var, dimension=dim_, exposure=var)
                self._all_params_unit[var] = dim_
                dynamics.add_state_variable(sv_)
                self._component_type.add(lems.Exposure(var, dimension=dim_))
            elif ng_equations[var].type in (PARAMETER, SUBEXPRESSION):
                if var == NOT_REFRACTORY:
                    continue
                dim_ = _determine_dimension(ng_equations[var].unit)
                self._all_params_unit[var] = dim_
                # all initializers contatining iterator need to be assigned
                # as a property
                # i is default iterator in Brian2
                if var in initializers and "i" in get_identifiers(str(initializers[var])):
                    self._component_type.add(lems.Property(var, dim_))
                    special_properties[var] = initializers[var]
                    continue
                sv_ = lems.StateVariable(var, dimension=dim_)
                dynamics.add_state_variable(sv_)
        # what happens at initialization
        onstart = lems.OnStart()
        for var in obj.equations.names:
            if var in (NOT_REFRACTORY, LAST_SPIKE):
                continue
            if var not in initializers:
                continue
            if var in special_properties:
                continue
            init_value = initializers[var]
            if type(init_value) != str:
                init_value = brian_unit_to_lems(init_value)
            else:
                init_value = renderer.render_expr(str(init_value))
            onstart.add(lems.StateAssignment(var, init_value))
        dynamics.add(onstart)

        if obj._refractory:
            # if refractoriness, we create separate regimes
            # - for integrating
            integr_regime = lems.Regime(INTEGRATING, dynamics, True)  # True -> initial regime
            for spike_flag, oc in self._event_builder(obj.events, obj.event_codes):
                if spike_flag:
                    # if spike occured we make transition to refractory regime
                    oc.add_action(lems.Transition(REFRACTORY))
                integr_regime.add_event_handler(oc)
            # - for refractory
            refrac_regime = lems.Regime(REFRACTORY, dynamics)
            # we make lastspike variable and initialize it
            refrac_regime.add_state_variable(lems.StateVariable(LAST_SPIKE, dimension='time'))
            oe = lems.OnEntry()
            oe.add(lems.StateAssignment(LAST_SPIKE, 't'))
            refrac_regime.add(oe)
            # after time spiecified in _refractory we make transition
            # to integrating regime
            if not _equation_separator(str(obj._refractory)):
                # if there is no specific variable given, we assume
                # that this is time condition
                ref_oc = lems.OnCondition('t .gt. ( {0} + {1} )'.format(LAST_SPIKE, brian_unit_to_lems(obj._refractory)))
            else:
                ref_oc = lems.OnCondition(renderer.render_expr(obj._refractory))
            ref_trans = lems.Transition(INTEGRATING)
            ref_oc.add_action(ref_trans)
            refrac_regime.add_event_handler(ref_oc)
            for var in obj.user_equations.diff_eq_names:
                td = lems.TimeDerivative(var, renderer.render_expr(str(ng_equations[var].expr)))
                # if unless refratory we add only do integration regime
                if UNLESS_REFRACTORY in ng_equations[var].flags:
                    integr_regime.add_time_derivative(td)
                    continue
                integr_regime.add_time_derivative(td)
                refrac_regime.add_time_derivative(td)
            dynamics.add_regime(integr_regime)
            dynamics.add_regime(refrac_regime)
        else:
            # here we add events directly to dynamics
            for spike_flag, oc in self._event_builder(obj.events, obj.event_codes):
                dynamics.add_event_handler(oc)
            for var in obj.user_equations.diff_eq_names:
                td = lems.TimeDerivative(var, renderer.render_expr(str(ng_equations[var].expr)))
                dynamics.add_time_derivative(td)

        self._component_type.dynamics = dynamics
        # making componenttype is done so we add it to the model
        self._model.add_component_type(self._component_type)
        obj.namespace.pop("init", None)                # kick out init
        # adding component to the model
        paramdict = dict()
        for param in obj.namespace:
            paramdict[param] = self._unit_lems_validator(obj.namespace[param])
        if obj.N == 1:
            self._model.add(lems.Component("n{}".format(idx_of_ng), ct_name, **paramdict))
        else:
            self.make_multiinstantiate(special_properties, ct_name, paramdict)
Exemplo n.º 10
0
def mdf_to_neuroml(graph, save_to=None, format=None, run_duration_sec=2):

    print("Converting graph: %s to NeuroML" % (graph.id))

    net = neuromllite.Network(id=graph.id)
    net.notes = "NeuroMLlite export of {} graph: {}".format(
        format if format else "MDF",
        graph.id,
    )

    model = lems.Model()
    lems_definitions = "%s_lems_definitions.xml" % graph.id

    for node in graph.nodes:
        print("    Node: %s" % node.id)

        node_comp_type = "%s__definition" % node.id
        node_comp = "%s__instance" % node.id

        # Create the ComponentType which defines behaviour of the general class
        ct = lems.ComponentType(node_comp_type, extends="baseCellMembPotDL")
        ct.add(lems.Attachments("only_input_port", "basePointCurrentDL"))
        ct.dynamics.add(
            lems.DerivedVariable(name="V",
                                 dimension="none",
                                 value="0",
                                 exposure="V"))
        model.add(ct)

        # Define the Component - an instance of the ComponentType
        comp = lems.Component(node_comp, node_comp_type)
        model.add(comp)

        cell = neuromllite.Cell(id=node_comp,
                                lems_source_file=lems_definitions)
        net.cells.append(cell)

        pop = neuromllite.Population(
            id=node.id,
            size=1,
            component=cell.id,
            properties={
                "color": "0.2 0.2 0.2",
                "radius": 3
            },
        )
        net.populations.append(pop)

        if len(node.input_ports) > 1:
            raise Exception(
                "Currently only max 1 input port supported in NeuroML...")

        for ip in node.input_ports:
            ct.add(lems.Exposure(ip.id, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(
                    name=ip.id,
                    dimension="none",
                    select="only_input_port[*]/I",
                    reduce="add",
                    exposure=ip.id,
                ))

        on_start = None

        for p in node.parameters:
            print("Converting %s" % p)
            if p.value is not None:
                try:
                    v_num = float(p.value)
                    ct.add(lems.Parameter(p.id, "none"))
                    comp.parameters[p.id] = v_num
                    print(comp.parameters[p.id])
                except Exception as e:

                    ct.add(lems.Exposure(p.id, "none"))
                    dv = lems.DerivedVariable(
                        name=p.id,
                        dimension="none",
                        value="%s" % (p.value),
                        exposure=p.id,
                    )
                    ct.dynamics.add(dv)

            elif p.function is not None:
                ct.add(lems.Exposure(p.id, "none"))
                func_info = mdf_functions[p.function]
                expr = func_info["expression_string"]
                expr2 = substitute_args(expr, p.args)
                for arg in p.args:
                    expr += ";{}={}".format(arg, p.args[arg])
                dv = lems.DerivedVariable(name=p.id,
                                          dimension="none",
                                          value="%s" % (expr2),
                                          exposure=p.id)
                ct.dynamics.add(dv)
            else:
                ct.add(lems.Exposure(p.id, "none"))
                ct.dynamics.add(
                    lems.StateVariable(name=p.id,
                                       dimension="none",
                                       exposure=p.id))
                if p.default_initial_value:
                    if on_start is None:
                        on_start = lems.OnStart()
                        ct.dynamics.add(on_start)
                    sa = lems.StateAssignment(
                        variable=p.id,
                        value=str(evaluate_expr(p.default_initial_value)))
                    on_start.actions.append(sa)

                if p.time_derivative:
                    td = lems.TimeDerivative(variable=p.id,
                                             value=p.time_derivative)
                    ct.dynamics.add(td)

        if len(node.output_ports) > 1:
            raise Exception(
                "Currently only max 1 output port supported in NeuroML...")

        for op in node.output_ports:
            ct.add(lems.Exposure(op.id, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(name=op.id,
                                     dimension="none",
                                     value=op.value,
                                     exposure=op.id))
            only_output_port = "only_output_port"
            ct.add(lems.Exposure(only_output_port, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(
                    name=only_output_port,
                    dimension="none",
                    value=op.id,
                    exposure=only_output_port,
                ))

    if len(graph.edges) > 0:

        model.add(
            lems.Include(
                os.path.join(os.path.dirname(__file__),
                             "syn_definitions.xml")))
        rsDL = neuromllite.Synapse(id="rsDL",
                                   lems_source_file=lems_definitions)
        net.synapses.append(rsDL)
        # syn_id = 'silentSyn'
        # silentSynDL = neuromllite.Synapse(id=syn_id, lems_source_file=lems_definitions)

    for edge in graph.edges:
        print(f"    Edge: {edge.id} connects {edge.sender} to {edge.receiver}")

        ssyn_id = "silentSyn_proj_%s" % edge.id
        ssyn_id = "silentSyn_proj_%s" % edge.id
        # ssyn_id = 'silentSynX'
        silentDLin = neuromllite.Synapse(id=ssyn_id,
                                         lems_source_file=lems_definitions)

        model.add(lems.Component(ssyn_id, "silentRateSynapseDL"))

        net.synapses.append(silentDLin)

        net.projections.append(
            neuromllite.Projection(
                id="proj_%s" % edge.id,
                presynaptic=edge.sender,
                postsynaptic=edge.receiver,
                synapse=rsDL.id,
                pre_synapse=silentDLin.id,
                type="continuousProjection",
                weight=1,
                random_connectivity=neuromllite.RandomConnectivity(
                    probability=1),
            ))

    # Much more todo...
    model.export_to_file(lems_definitions)

    print("Nml net: %s" % net)
    if save_to:
        new_file = net.to_json_file(save_to)
        print("Saved NML to: %s" % save_to)

    ################################################################################
    ###   Build Simulation object & save as JSON

    simtime = 1000 * run_duration_sec
    dt = 0.1
    sim = neuromllite.Simulation(
        id="Sim%s" % net.id,
        network=new_file,
        duration=simtime,
        dt=dt,
        seed=123,
        recordVariables={"OUTPUT": {
            "all": "*"
        }},
    )

    recordVariables = {}
    for node in graph.nodes:
        for ip in node.input_ports:
            if not ip.id in recordVariables:
                recordVariables[ip.id] = {}
            recordVariables[ip.id][node.id] = 0

        for p in node.parameters:
            if p.is_stateful():
                if not p.id in recordVariables:
                    recordVariables[p.id] = {}
                recordVariables[p.id][node.id] = 0

        for op in node.output_ports:
            if not op.id in recordVariables:
                recordVariables[op.id] = {}
            recordVariables[op.id][node.id] = 0

    sim.recordVariables = recordVariables
    if save_to:
        sf = sim.to_json_file()

        print("Saved Simulation to: %s" % sf)

    return net, sim