def _get_lems_model_with_neuroml2_types(cls): from pyneuroml.pynml import get_path_to_jnml_jar from pyneuroml.pynml import read_lems_file from lems.parser.LEMS import LEMSFileParser import zipfile lems_model = lems.Model(include_includes=False) parser = LEMSFileParser(lems_model) jar_path = get_path_to_jnml_jar() # print_comment_v("Loading standard NeuroML2 dimension/unit definitions from %s"%jar_path) jar = zipfile.ZipFile(jar_path, "r") new_lems = jar.read("NeuroML2CoreTypes/NeuroMLCoreDimensions.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/NeuroMLCoreCompTypes.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/Cells.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/Networks.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/Simulation.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/Synapses.xml") parser.parse(new_lems) new_lems = jar.read("NeuroML2CoreTypes/PyNN.xml") parser.parse(new_lems) return lems_model
def read_lems_file(fname): """Import LEMS model from file fname or builtin model name. """ here = os.path.dirname(os.path.abspath(__file__)) builtin_fname = os.path.join(here, fname + '.lems.xml') if os.path.exists(builtin_fname): fname = builtin_fname model = lems.Model() model.import_from_file(fname) return model
def __init__(self): self._model = lems.Model() self._all_params_unit = {} self._population = None self._model_namespace = {'neuronname': None, 'ct_populationname': None, 'populationname': None, 'networkname': None, 'targetname': None, 'simulname': None, 'poiss_generator': "poiss"}
def _load_lems_file_with_neuroml2_types(cls, lems_filename): from pyneuroml.pynml import get_path_to_jnml_jar from pyneuroml.pynml import read_lems_file from lems.parser.LEMS import LEMSFileParser import zipfile lems_model = lems.Model(include_includes=False) parser = LEMSFileParser(lems_model) jar_path = get_path_to_jnml_jar() # print_comment_v("Loading standard NeuroML2 dimension/unit definitions from %s"%jar_path) jar = zipfile.ZipFile(jar_path, 'r') new_lems = jar.read('NeuroML2CoreTypes/NeuroMLCoreDimensions.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/NeuroMLCoreCompTypes.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/Cells.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/Networks.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/Simulation.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/Synapses.xml') parser.parse(new_lems) new_lems = jar.read('NeuroML2CoreTypes/PyNN.xml') parser.parse(new_lems) model = read_lems_file(lems_filename, include_includes=False, fail_on_missing_includes=True, debug=True) for cid, c in model.components.items(): lems_model.components[cid] = c for ctid, ct in model.component_types.items(): lems_model.component_types[ctid] = ct return lems_model
def build_lems_for_model(src): model = lems.Model() model.add(lems.Dimension('time', t=1)) # model.add(lems.Dimension('au')) # primary element of the model is a mass model component mass = lems.ComponentType(src.name, extends="baseCellMembPot") model.add(mass) ######### Adding v is required to ease mapping to NEURON... mass.dynamics.add(lems.StateVariable(name="v", dimension="voltage", exposure="v")) mass.add(lems.Attachments(name="synapses",type_="basePointCurrentDL")) for input in src.input: mass.dynamics.add(lems.DerivedVariable(name=input, dimension='none', exposure=input, select='synapses[*]/I', reduce='add')) mass.add(lems.Exposure(input, 'none')) for key, val in src.const.items(): mass.add(lems.Parameter(key, 'none')) # TODO units mass.add(lems.Constant(name="MSEC", dimension="time", value="1ms")) mass.add(lems.Constant(name="PI", dimension="none", value="3.14159265359")) states = [] der_vars = [] # for key in src.param: # mass.add(lems.Parameter(key, 'au')) # TODO units for key, val in src.auxex: val = val.replace('**', '^') mass.dynamics.add(lems.DerivedVariable(key, value=val)) for key in src.obsrv: name_dv = key.replace('(','_').replace(')','').replace(' - ','_min_') mass.dynamics.add(lems.DerivedVariable(name_dv, value=key, exposure=name_dv)) mass.add(lems.Exposure(name_dv, 'none')) for src_svar in src.state_space: name = src_svar.name ddt = src_svar.drift.replace('**', '^') mass.dynamics.add(lems.StateVariable(name, 'none', name)) mass.dynamics.add(lems.TimeDerivative(name, '(%s)/MSEC'%ddt)) mass.add(lems.Exposure(name, 'none')) ''' On condition is not need on the model but NeuroML requires its definition --> <OnCondition test="r .lt. 0"> <EventOut port="spike"/> </OnCondition>''' oc = lems.OnCondition(test='v .gt. 0') oc.actions.append(lems.EventOut(port='spike')) mass.dynamics.add(oc) return model
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) if size>=0: for i in range(size): node_id = '%s_%i'%(population_id, i) node = {} node['type'] = {} node['name'] = node_id #node['type']['NeuroML'] = component comp = self.nl_network.get_child(component, 'cells') base_dir = './' # for now... fname = locate_file(comp.lems_source_file, base_dir) model = lems.Model() model.import_from_file(fname) lems_comp = model.components.get(component) print('Cell: [%s] comes from %s and in Lems is: %s'%(comp,fname, lems_comp)) comp_type = lems_comp.type type = "The type of %s"%comp_type function = "The function of %s"%comp_type if comp_type == 'pnlLinearFunctionTM': function = 'Linear' type = "TransferMechanism" elif comp_type == 'inputNode': function = 'Linear' type = "TransferMechanism" elif comp_type == 'pnlLogisticFunctionTM': function = 'Logistic' type = "TransferMechanism" elif comp_type == 'pnlExponentialFunctionTM': function = 'Exponential' type = "TransferMechanism" elif comp_type == 'pnlSimpleIntegratorMechanism': function = 'SimpleIntegrator' type = "IntegratorMechanism" node['type']["PNL"] = type node['type']["generic"] = None node['parameters'] = {} node['parameters']['PNL'] = {} node['functions'] = [] func_info = {} func_info['type']={} func_info['type']['generic']=function func_info['name']='Function_%s'%function func_info['args']={} for p in lems_comp.parameters: func_info['args'][p] = {} func_info['args'][p]['type'] = 'float' func_info['args'][p]['source'] = '%s.input_ports.%s'%(node_id,p) if comp.parameters is not None and p in comp.parameters: func_info['args'][p]['value'] = evaluate(comp.parameters[p], self.nl_network.parameters) else: func_info['args'][p]['value'] = evaluate(lems_comp.parameters[p]) # evaluate to ensure strings -> ints/floats etc node['functions'].append(func_info) self.bids_mdf_graph['nodes'][node_id] = node pop_node_id = '%s'%(population_id) pop_node = {} pop_node['type'] = {} pop_node['name'] = pop_node_id pop_node['type']['NeuroML'] = component pop_node['parameters'] = {} pop_node['parameters']['size'] = size pop_node['functions'] = {} self.bids_mdf_graph_hl['nodes'][pop_node_id] = pop_node
#! /usr/bin/python import lems.api as lems model = lems.Model() 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('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)
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
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
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
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
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) if size >= 0: for i in range(size): node_id = "%s_%i" % (population_id, i) node = {} node["type"] = {} node["name"] = node_id # node['type']['NeuroML'] = component comp = self.nl_network.get_child(component, "cells") base_dir = "./" # for now... fname = locate_file(comp.lems_source_file, base_dir) model = lems.Model() model.import_from_file(fname) lems_comp = model.components.get(component) print("Cell: [%s] comes from %s and in Lems is: %s" % (comp, fname, lems_comp)) comp_type = lems_comp.type type = "The type of %s" % comp_type function = "The function of %s" % comp_type if comp_type == "pnlLinearFunctionTM": function = "Linear" type = "TransferMechanism" elif comp_type == "inputNode": function = "Linear" type = "TransferMechanism" elif comp_type == "pnlLogisticFunctionTM": function = "Logistic" type = "TransferMechanism" elif comp_type == "pnlExponentialFunctionTM": function = "Exponential" type = "TransferMechanism" elif comp_type == "pnlSimpleIntegratorMechanism": function = "SimpleIntegrator" type = "IntegratorMechanism" elif comp_type == "fnCell": function = "FitzHughNagumoIntegrator" type = "IntegratorMechanism" node["type"]["PNL"] = type node["type"]["generic"] = None node["parameters"] = {} node["parameters"]["PNL"] = {} node["functions"] = [] func_info = {} func_info["type"] = {} func_info["type"]["generic"] = function func_info["name"] = "Function_%s" % function func_info["args"] = {} for p in lems_comp.parameters: func_info["args"][p] = {} func_info["args"][p]["type"] = "float" func_info["args"][p]["source"] = "%s.input_ports.%s" % ( node_id, p) if comp.parameters is not None and p in comp.parameters: func_info["args"][p]["value"] = evaluate( comp.parameters[p], self.nl_network.parameters) else: func_info["args"][p]["value"] = evaluate( lems_comp.parameters[p] ) # evaluate to ensure strings -> ints/floats etc node["functions"].append(func_info) self.bids_mdf_graph["nodes"][node_id] = node pop_node_id = "%s" % (population_id) pop_node = {} pop_node["type"] = {} pop_node["name"] = pop_node_id pop_node["type"]["NeuroML"] = component pop_node["parameters"] = {} pop_node["parameters"]["size"] = size pop_node["functions"] = {} self.bids_mdf_graph_hl["nodes"][pop_node_id] = pop_node