def finalise_projection(self, id, prePop, postPop, synapse=None, type="projection"): ''' Check whether handle_projection was not called, e.g. due to no connections present ''' self.log.debug("Projection: %s from %s to %s completed" % (id, prePop, postPop)) if type == "projection": present = False for p in self.network.projections: if p.id == id: present = True if not present: proj = neuroml.Projection(id=id, presynaptic_population=prePop, postsynaptic_population=postPop, synapse=synapse) self.network.projections.append(proj) elif type == "electricalProjection": present = False for p in self.network.electrical_projections: if p.id == id: present = True if not present: proj = neuroml.ElectricalProjection( id=id, presynaptic_population=prePop, postsynaptic_population=postPop) self.network.electrical_projections.append(proj)
def handle_projection(self, id, prePop, postPop, synapse, hasWeights=False, hasDelays=False, type="projection", synapse_obj=None, pre_synapse_obj=None): if synapse_obj: self.nml_doc.append(synapse_obj) if pre_synapse_obj: self.nml_doc.append(pre_synapse_obj) proj = None if type == "projection": proj = neuroml.Projection(id=id, presynaptic_population=prePop, postsynaptic_population=postPop, synapse=synapse) self.network.projections.append(proj) elif type == "electricalProjection": proj = neuroml.ElectricalProjection( id=id, presynaptic_population=prePop, postsynaptic_population=postPop) self.network.electrical_projections.append(proj) self.projection_syns[id] = synapse elif type == "continuousProjection": proj = neuroml.ContinuousProjection( id=id, presynaptic_population=prePop, postsynaptic_population=postPop) self.network.continuous_projections.append(proj) if synapse_obj != None: self.projection_syns[id] = synapse_obj.id else: self.projection_syns[id] = synapse if pre_synapse_obj == None: pre_synapse_obj = neuroml.SilentSynapse(id="silentSyn_%s" % id) self.nml_doc.silent_synapses.append(pre_synapse_obj) self.projection_syns_pre[id] = pre_synapse_obj.id self.projections[id] = proj self.weightDelays[id] = hasWeights or hasDelays self.log.debug( "Projection: %s (%s) from %s to %s with syn: %s, weights: %s, delays: %s" % (id, type, prePop, postPop, synapse, hasWeights, hasDelays))
def __init__(self, presynaptic_population, postsynaptic_population, connector, synapse_type, source=None, receptor_type=None, space=Space(), label=None): common.Projection.__init__(self, presynaptic_population, postsynaptic_population, connector, synapse_type, source, receptor_type, space, label) nml_doc = simulator._get_nml_doc() net = nml_doc.networks[0] nml_proj_id = self.label.replace(u'\u2192','__TO__') syn_id = 'syn__%s'%nml_proj_id logger.debug("Creating Synapse: %s; %s; %s" % (receptor_type, synapse_type.parameter_space, connector)) celltype = postsynaptic_population.celltype.__class__.__name__ logger.debug("Post cell: %s" % (celltype)) syn = None if receptor_type == 'inhibitory': tau_key = 'tau_syn_I' erev_key = 'e_rev_I' else: tau_key = 'tau_syn_E' erev_key = 'e_rev_E' if 'cond_exp' in celltype: syn = neuroml.ExpCondSynapse(id=syn_id) syn.__setattr__('e_rev', postsynaptic_population.celltype.parameter_space[erev_key].base_value) nml_doc.exp_cond_synapses.append(syn) if 'cond_alpha' in celltype: syn = neuroml.AlphaCondSynapse(id=syn_id) syn.__setattr__('e_rev', postsynaptic_population.celltype.parameter_space[erev_key].base_value) nml_doc.alpha_cond_synapses.append(syn) if 'curr_exp' in celltype: syn = neuroml.ExpCurrSynapse(id=syn_id) nml_doc.exp_curr_synapses.append(syn) if 'curr_alpha' in celltype: syn = neuroml.AlphaCurrSynapse(id=syn_id) nml_doc.alpha_curr_synapses.append(syn) syn.tau_syn = postsynaptic_population.celltype.parameter_space[tau_key].base_value self.pre_pop_comp = '%s_%s'%(presynaptic_population.celltype.__class__.__name__, presynaptic_population.label) self.post_pop_comp = '%s_%s'%(postsynaptic_population.celltype.__class__.__name__, postsynaptic_population.label) logger.debug("Creating Projection: %s" % (nml_proj_id)) self.projection = neuroml.Projection(id=nml_proj_id, presynaptic_population=presynaptic_population.label, postsynaptic_population=postsynaptic_population.label, synapse=syn_id) net.projections.append(self.projection) ## Create connections self.connections = [] connector.connect(self)
def handleProjection(self, id, prePop, postPop, synapse, hasWeights=False, hasDelays=False): proj = neuroml.Projection(id=id, presynaptic_population=prePop, postsynaptic_population=postPop, synapse=synapse) self.projections[id] = proj self.network.projections.append(proj) self.weightDelays[id] = hasWeights or hasDelays self.log.info( "Projection: %s from %s to %s with syn: %s, weights: %s, delays: %s" % (id, prePop, postPop, synapse, hasWeights, hasDelays))
def add_synapses(net, conndata, nrn_runname, dCellIDs, dNumCells, write_synapse_file=False): ''' Reads original data files: conndata_x.dat, connections.dat and synlist.dat (created by launch_synapse_printer.hoc) create synapse files (only .txt files TODO: automate to make .nml-files) calculates the place of synapses and connects the cells :param net: neuroml.Network() - to which the projections will be added :param conndata: string(int) - original connection data file (only for setting the weights of the synapses, other parameters are loaded from other files) :param nrn_runname: string - name of the directory where the saved data files are stored (synlist.dat, connections.dat) ! nrn_runname depends on conndata ! :param dCellIDs - dictionary created by create_populations, which stroes the gid's :param dNumCells - dictionary created by create_populations, quick and dirty way to handle pyramidalcell -> [poolosyncell, cutsuridiscell] in conndata_x.dat and synlist.dat ''' # read in synaptic weight (if weight is 0 don't create synapses) fConndata = "../../datasets/conndata_%s.dat" % conndata dSWeights = {} with open(fConndata) as file: next(file) # skip header/first row: "99" for line in file: # handle pyramidalcell preCell = helper_pyramidalcell(line.split()[0], dNumCells) postCell = helper_pyramidalcell(line.split()[1], dNumCells) weight = float(line.split()[2]) * 1000 # nS if weight != 0.: id = "%s_to_%s" % (preCell, postCell) dSWeights[id] = weight file.close() # read in synapse types and IDs fSynapses = "../../results/%s/synlist.dat" % nrn_runname dSynapseIDs = {} # for automated synapse file generation ... # there will be a unique synapse for every poosible connection where the weight is not 0 (not all of them will be used in the network) exp2Synapses = '' customGABASynapses = '' synapse_types = [] with open(fSynapses) as file: for line in file: # handle pyramidalcell preCell = helper_pyramidalcell(line.split()[1], dNumCells) postCell = helper_pyramidalcell(line.split()[0], dNumCells) tmp = "%s_to_%s" % (preCell, postCell) if tmp in dSWeights: # only handle synapse if weight is != 0 id = "syn_%s_to_%s" % (preCell, postCell) synapseID = "%s_%s" % (id, int(line.split()[2])) weight = dSWeights[tmp] tmp = line.split()[3] # is like: cell_type[0].foo[x] postSegID = tmp[tmp.rfind('.') + 1:tmp.rfind('[')] + '_' + tmp[ tmp.rfind('[') + 1:tmp.rfind(']')] # converts it to: foo_x if synapseID not in dSynapseIDs: dSynapseIDs[synapseID] = postSegID # write out synapses tauRise = float(line.split()[5]) tauDecay = float(line.split()[6]) erev = float(line.split()[7]) syn = '\t<expTwoSynapse id="%s" gbase="%gnS" erev="%gmV" tauDecay="%gms" tauRise="%gms"/>\n\n' % ( id, weight, erev, tauDecay, tauRise) if id not in synapse_types and line.split( )[4] != "ExpGABAab": exp2Synapses += syn synapse_types.append(id) else: tauRiseB = float(line.split()[5]) tauDecayB = float(line.split()[6]) erevB = float(line.split()[7]) synA = '\t<expTwoSynapse id="%s_A" gbase="%gnS" erev="%gmV" tauDecay="%gms" tauRise="%gms"/>\n' % ( id, weight, erev, tauDecay, tauRise) synB = '\t<expTwoSynapse id="%s_B" gbase="%gnS" erev="%gmV" tauDecay="%gms" tauRise="%gms"/>\n\n' % ( id, weight / 3.37, erevB, tauDecayB, tauRiseB) if id not in synapse_types: customGABASynapses += (synA + synB) synapse_types.append(id) if write_synapse_file: fExp2Synapses = open("../synapses/exp2Synapses.txt", 'w') fExp2Synapses.write(exp2Synapses) fExp2Synapses.close() fCustomGABASynapses = open("../synapses/customGABASynapses.txt", 'w') fCustomGABASynapses.write(customGABASynapses) fCustomGABASynapses.close() file.close() # read in connections """ Note: if you run the model (the NEURON one) on multiple processors with CatFlag==0, then the connections will be dispersed in one file per processor, named subconns_[processorID].dat. SimTracker can then merge the files together, but if you don't use SimTracker and are using multiple processors, try setting CatFlag==1 to have NEURON concatenate all the data into one connections.dat file) This code was based on test runs wth a single processor, so we are using subconns_0.dat """ fConnections = "../../results/%s/subconns_0.dat" % nrn_runname # TODO: fix this...(see above in docstring) dProjections = {} with open(fConnections) as file: # next(file) # skip header: "source, target, synapse" <- only if useing connections.dat, created by SimTracker for line in file: preCellID = int(line.split()[0]) preCell_type = dCellIDs[preCellID][0] preCellIDPop = dCellIDs[preCellID][1] postCellID = int(line.split()[1]) postCell_type = dCellIDs[postCellID][0] postCellIDPop = dCellIDs[postCellID][1] synapseID = int(line.split()[2]) postSegID = dSynapseIDs["syn_%s_to_%s_%g" % (preCell_type, postCell_type, synapseID)] connection = [preCellIDPop, postCellIDPop, postSegID] projID = "proj_%spop_to_%spop" % (preCell_type, postCell_type) if projID not in dProjections: dProjections[projID] = [] dProjections[projID].append(connection) else: dProjections[projID].append(connection) file.close() # load cell morphologies (for segment and fractionAlong calculation for neuroml.Connections) - see morphology_helper.py cell_types = dNumCells.keys() dMorphs = {} for cell in cell_types: dMorphs[cell] = helper_morphology( "../cells/%s.cell.nml" % cell ) # will be a dictionary of dictionaries d[cell][segGroupID] = [[segIDs], [lSegs]] ##### add projections and connections to nml file ##### for projID, connection_list in dProjections.iteritems(): presynaptic = projID.split('_')[1][:-3] postsynaptic = projID.split('_')[-1][:-3] if presynaptic != "ngf": # ngf cells are useing the boundled GABA_A, GABA_B syapse (ExpGABAab.mod)... proj = neuroml.Projection( id=projID, presynaptic_population="pop_%s" % presynaptic, postsynaptic_population="pop_%s" % postsynaptic, synapse="syn_%s_to_%s" % (presynaptic, postsynaptic)) for i, sublist in enumerate(connection_list): preCellID = sublist[0] postCellID = sublist[1] postSegmentGroupID = sublist[2] if presynaptic not in ["ca3", "ec"]: presynapticComp = "%scell" % presynaptic preSegID, preFracAlong = calc_seg_fracalong( dMorphs[presynaptic], "soma_0", 0.5) # see morphology_helper. else: presynapticComp = "spikeGenPoisson" # TODO: implement other stimulations ... preSegID = 0 preFracAlong = 0.5 postSegID, postFracAlong = calc_seg_fracalong( dMorphs[postsynaptic], postSegmentGroupID, 0.5) # see morphology_helper.py conn = neuroml.ConnectionWD( id=i, pre_cell_id="../pop_%s/%g/%s" % (presynaptic, preCellID, presynapticComp), pre_segment_id=preSegID, pre_fraction_along=preFracAlong, post_cell_id="../pop_%s/%g/%scell" % (postsynaptic, postCellID, postsynaptic), post_segment_id=postSegID, post_fraction_along=postFracAlong, weight= 1, # synaptic weights are specified at the synapse component level and are not scaled in the network delay="3ms") proj.connection_wds.append(conn) net.projections.append(proj) else: # TODO: check if only ngf is using ExpGABAab (with other ConnDat, SynData spec.) for sType in ['A', 'B']: proj = neuroml.Projection( id="%s_%s" % (projID, sType), presynaptic_population="pop_%s" % presynaptic, postsynaptic_population="pop_%s" % postsynaptic, synapse="syn_%s_to_%s_%s" % (presynaptic, postsynaptic, sType)) for i, sublist in enumerate(connection_list): preCellID = sublist[0] postCellID = sublist[1] postSegmentGroupID = sublist[2] presynapticComp = "ngfcell" preSegID, preFracAlong = calc_seg_fracalong( dMorphs["ngf"], "soma_0", 0.5) # see morphology_helper. postSegID, postFracAlong = calc_seg_fracalong( dMorphs[postsynaptic], postSegmentGroupID, 0.5) # see morphology_helper.py conn = neuroml.ConnectionWD( id=i, pre_cell_id="../pop_ngf/%g/%s" % (preCellID, presynapticComp), pre_segment_id=preSegID, pre_fraction_along=preFracAlong, post_cell_id="../pop_%s/%g/%scell" % (postsynaptic, postCellID, postsynaptic), post_segment_id=postSegID, post_fraction_along=postFracAlong, weight= 1, # synaptic weights are specified at the synapse component level and are not scaled in the network delay="3ms") proj.connection_wds.append(conn) net.projections.append(proj)
def create_GoC_network( duration, dt, seed, runid, run=False): ### ---------- Load Params noPar = True pfile = Path('params_file.pkl') if pfile.exists(): print('Reading parameters from file:') file = open('params_file.pkl','rb') params_list = pkl.load(file) if len(params_list)>runid: p = params_list[runid] file.close() if noPar: p = inp.get_simulation_params( runid ) ### ---------- Component types goc_filename = 'GoC.cell.nml' # Golgi cell with channels goc_file = pynml.read_neuroml2_file( goc_filename ) goc_type = goc_file.cells[0] goc_ref = nml.IncludeType( href=goc_filename ) MFSyn_filename = 'MF_GoC_Syn.nml' # small conductance synapse for background inputs mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename ) MFSyn_type = mfsyn_file.exp_three_synapses[0] mfsyn_ref = nml.IncludeType( href=MFSyn_filename ) MF20Syn_filename = 'MF_GoC_SynMult.nml' # multi-syn conductance for strong/coincident transient input mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename ) MF20Syn_type = mf20syn_file.exp_three_synapses[0] mf20syn_ref = nml.IncludeType( href=MF20Syn_filename ) mf_type2 = 'spikeGeneratorPoisson' # Spike source for background inputs mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" ) # Not tuned to any data - qqq ! mf_bursttype = 'transientPoissonFiringSynapse' # Burst of MF input (as explicit input) mf_burst = nml.TransientPoissonFiringSynapse( id="MF_Burst", average_rate="100 Hz", delay="2000 ms", duration="500 ms", synapse=MF20Syn_type.id, spike_target='./{}'.format(MF20Syn_type.id) ) gj = nml.GapJunction( id="GJ_0", conductance="426pS" ) # GoC synapse ### --------- Populations # Build network to specify cells and connectivity net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" ) # Create GoC population goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=p["nGoC"] ) for goc in range( p["nGoC"] ): inst = nml.Instance( id=goc ) goc_pop.instances.append( inst ) inst.location = nml.Location( x=p["GoC_pos"][goc,0], y=p["GoC_pos"][goc,1], z=p["GoC_pos"][goc,2] ) net.populations.append( goc_pop ) ### MF population MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=p["nMF"]) for mf in range( p["nMF"] ): inst = nml.Instance(id=mf) MF_Poisson_pop.instances.append( inst ) inst.location = nml.Location( x=p["MF_pos"][mf,0], y=p["MF_pos"][mf,1], z=p["MF_pos"][mf,2] ) net.populations.append( MF_Poisson_pop ) # Create NML document for network specification net_doc = nml.NeuroMLDocument( id=net.id ) net_doc.networks.append( net ) net_doc.includes.append( goc_ref ) net_doc.includes.append( mfsyn_ref ) net_doc.includes.append( mf20syn_ref ) net_doc.spike_generator_poissons.append( mf_poisson ) net_doc.transient_poisson_firing_synapses.append( mf_burst ) net_doc.gap_junctions.append(gj) ### ------------ Connectivity ### 1. Background excitatory inputs: MF to GoC populations MFProjection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id) net.projections.append(MFProjection) # MF_> GoC synapses (with syn_count equivalent to integer scaling of Mf synapse strength) nMFSyn = p["MF_GoC_pairs"].shape[1] ctr=0 for syn in range( nMFSyn ): mf, goc = p["MF_GoC_pairs"][:, syn] for syn_count in range(p["MF_GoC_wt"][ctr]): conn2 = nml.Connection(id=ctr, 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") #on soma MFProjection.connections.append(conn2) ctr+=1 ### 2. Perturbation as High Freq MF Inputs ctr=0 for goc in p["Burst_GoC"]: for jj in range( p["nBurst"] ): # Each Perturbed GoC gets nBurst random Burst sources 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 ### 3. Electrical coupling between GoCs GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id ) net.electrical_projections.append( GoCCoupling ) dend_id = [1,2,5] for jj in range( p["GJ_pairs"].shape[0] ): conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,0], goc_type.id), pre_segment=dend_id[p["GJ_loc"][jj,0]], pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,1], goc_type.id), post_segment=dend_id[p["GJ_loc"][jj,1]], post_fraction_along='0.5', synapse=gj.id, weight=p["GJ_wt"][jj] ) GoCCoupling.electrical_connection_instance_ws.append( conn ) ### -------------- Write files net_filename = 'gocNetwork.nml' pynml.write_neuroml2_file( net_doc, net_filename ) simid = 'sim_gocnet_'+goc_type.id+'_run_{}'.format(runid) ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed ) ls.assign_simulation_target( net.id ) ls.include_neuroml2_file( net_filename) ls.include_neuroml2_file( goc_filename) ls.include_neuroml2_file( MFSyn_filename) ls.include_neuroml2_file( MF20Syn_filename) # 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() if run: res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", nogui=True, plot=False) else: res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False) return res
def add_targeted_projection(net, prefix, presynaptic_population, postsynaptic_population, targeting_mode, synapse_list, number_conns_per_cell, pre_segment_group=None, post_segment_group=None, delays_dict=None, weights_dict=None): ''' Adds (chemical, event based) projection from `presynaptic_population` to `postsynaptic_population`, specifically limiting connections presynaptically to `pre_segment_group` and postsynaptically to `post_segment_group`. `net` reference to the network object previously created `prefix` prefix to use in the id of the projection `presynaptic_population` presynaptic population e.g. added via add_population_in_rectangular_region() `postsynaptic_population` postsynaptic population e.g. added via add_population_in_rectangular_region() `targeting_mode` a string that specifies the targeting mode: 'convergent' or 'divergent' `synapse_list` the list of synapse ids that correspond to the individual receptor components on the physical synapse, e.g. the first element is the id of the AMPA synapse and the second element is the id of the NMDA synapse; these synapse components will be mapped onto the same location of the target segment `number_conns_per_cell` number of connections to make on each cell in the postsynaptic population (when targeting_mode='convergent') or from each cell in the presynaptic population (when targeting_mode='divergent') `pre_segment_group` which segment_group to target connennections from on the presynaptic population, e.g. axon_group. This can be left out or set to None if the presynaptic component has no morphology `post_segment_group` which segment_group to target connennections from on the postsynaptic population, e.g. dendrite_group. This can be left out or set to None if the postsynaptic component has no morphology `delays_dict` optional dictionary that specifies the delays (in ms) for individual synapse components, e.g. {'NMDA':5.0} or {'AMPA':3.0,'NMDA':5} `weights_dict` optional dictionary that specifies the weights (in ms) for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2} ''' if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None projections = [] if presynaptic_population.component in oc_build.cell_ids_vs_nml_docs: pre_cell = oc_build.cell_ids_vs_nml_docs[ presynaptic_population.component].get_by_id( presynaptic_population.component) else: pre_cell = "Undetermined" if postsynaptic_population.component in oc_build.cell_ids_vs_nml_docs: post_cell = oc_build.cell_ids_vs_nml_docs[ postsynaptic_population.component].get_by_id( postsynaptic_population.component) else: post_cell = "Undetermined" if pre_segment_group: pre_segs = oc_build.extract_seg_ids(pre_cell, [pre_segment_group], "segGroups") pre_seg_target_dict = oc_build.make_target_dict(pre_cell, pre_segs) else: pre_segs = None pre_seg_target_dict = None if post_segment_group: post_segs = oc_build.extract_seg_ids(post_cell, [post_segment_group], "segGroups") post_seg_target_dict = oc_build.make_target_dict(post_cell, post_segs) else: post_segs = None post_seg_target_dict = None #print pre_seg_target_dict, post_seg_target_dict for synapse in synapse_list: proj_id = "%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id) if len(synapse_list) == 1 else \ "%s_%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id, synapse) opencortex.print_comment_v( "Adding projection: %s: %s#%s, %s (%s) -> %s#%s, %s (%s)" % (proj_id, presynaptic_population.id, presynaptic_population.size, pre_cell, pre_segs, postsynaptic_population.id, postsynaptic_population.size, post_cell, post_segs)) proj = neuroml.Projection( id=proj_id, presynaptic_population=presynaptic_population.id, postsynaptic_population=postsynaptic_population.id, synapse=synapse) projections.append(proj) subset_dict = {} #{'dendrite_group':number_conns_per_cell} subset_dict[post_segment_group] = number_conns_per_cell oc_build.add_targeted_projection_by_dicts( net, projections, presynaptic_population, postsynaptic_population, targeting_mode, synapse_list, pre_seg_target_dict, post_seg_target_dict, subset_dict, delays_dict, weights_dict) return projections
def add_probabilistic_projection(net, prefix, presynaptic_population, postsynaptic_population, synapse_id, connection_probability, delay=0, weight=1): """ Add a projection between `presynaptic_population` and `postsynaptic_population` with probability of connection between each pre & post pair of cells given by `connection_probability`. Attributes: `net` reference to the network object previously created `prefix` prefix to use in the id of the projection `presynaptic_population` presynaptic population e.g. added via add_population_in_rectangular_region() `postsynaptic_population` postsynaptic population e.g. added via add_population_in_rectangular_region() `synapse_id` id of synapse previously added, e.g. added with add_exp_two_syn() `connection_probability` For each pre syn cell i and post syn cell j, where i!=j, the chance they will be connected is given by this `delay` optional delay for each connection, default 0 ms `weight` optional weight for each connection, default 1 """ if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None proj = neuroml.Projection( id="%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id), presynaptic_population=presynaptic_population.id, postsynaptic_population=postsynaptic_population.id, synapse=synapse_id) count = 0 for i in range(0, presynaptic_population.size): for j in range(0, postsynaptic_population.size): if i != j or presynaptic_population.id != postsynaptic_population.id: if connection_probability >= 1 or random.random( ) < connection_probability: oc_build._add_connection(proj, count, presynaptic_population, i, 0, postsynaptic_population, j, 0, delay=delay, weight=weight) count += 1 net.projections.append(proj) return proj
# Create network net = neuroml.Network(id="simplenet") nml_doc.networks.append(net) # Create 2 populations size0 = 5 size1 = 5 pop0 = neuroml.Population(id="Pop0", size=size0, component=iaf0.id) pop1 = neuroml.Population(id="Pop1", size=size1, component=iaf0.id) net.populations.append(pop0) net.populations.append(pop1) # Create a projection between them proj1 = neuroml.Projection(id="Proj0", synapse=syn0.id, presynaptic_population=pop0.id, postsynaptic_population=pop1.id) net.projections.append(proj1) conn_count = 0 for pre in range(0, size0): # Create a number of random amplitude current pulses pg = neuroml.PulseGenerator(id="input%i" % pre, delay="0ms", duration="500ms", amplitude="%fnA" % (0.5 + random.random())) nml_doc.pulse_generators.append(pg) # Add these to cells input_list = neuroml.InputList(id="il%i" % pre, component=pg.id,
def create_GoC_network(duration, dt, seed, N_goc=0, N_mf=15, run=False, prob_type='Boltzmann', GJw_type='Vervaeke2010'): ### ---------- Component types goc_filename = 'GoC.cell.nml' # Golgi cell with channels goc_file = pynml.read_neuroml2_file(goc_filename) goc_type = goc_file.cells[0] goc_ref = nml.IncludeType(href=goc_filename) MFSyn_filename = 'MF_GoC_Syn.nml' # small conductance synapse for background inputs mfsyn_file = pynml.read_neuroml2_file(MFSyn_filename) MFSyn_type = mfsyn_file.exp_three_synapses[0] mfsyn_ref = nml.IncludeType(href=MFSyn_filename) MF20Syn_filename = 'MF_GoC_SynMult.nml' # multi-syn conductance for strong/coincident transient input mf20syn_file = pynml.read_neuroml2_file(MF20Syn_filename) MF20Syn_type = mf20syn_file.exp_three_synapses[0] mf20syn_ref = nml.IncludeType(href=MF20Syn_filename) mf_type2 = 'spikeGeneratorPoisson' # Spike source for background inputs mf_poisson = nml.SpikeGeneratorPoisson( id="MF_Poisson", average_rate="5 Hz") # Not tuned to any data - qqq ! mf_bursttype = 'transientPoissonFiringSynapse' # Burst of MF input (as explicit input) mf_burst = nml.TransientPoissonFiringSynapse(id="MF_Burst", average_rate="100 Hz", delay="2000 ms", duration="500 ms", synapse=MF20Syn_type.id, spike_target='./{}'.format( MF20Syn_type.id)) gj = nml.GapJunction(id="GJ_0", conductance="426pS") # GoC synapse ### --------- Populations # Build network to specify cells and connectivity net = nml.Network(id="gocNetwork", type="networkWithTemperature", temperature="23 degC") ### Golgi cells if N_goc > 0: GoC_pos = nu.GoC_locate(N_goc) else: GoC_pos = nu.GoC_density_locate() N_goc = GoC_pos.shape[0] # Create GoC population goc_pop = nml.Population(id=goc_type.id + "Pop", component=goc_type.id, type="populationList", size=N_goc) 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]) net.populations.append(goc_pop) ### MF population MF_Poisson_pop = nml.Population(id=mf_poisson.id + "_pop", component=mf_poisson.id, type="populationList", size=N_mf) 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]) net.populations.append(MF_Poisson_pop) # Create NML document for network specification net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(goc_ref) net_doc.includes.append(mfsyn_ref) net_doc.includes.append(mf20syn_ref) net_doc.spike_generator_poissons.append(mf_poisson) net_doc.transient_poisson_firing_synapses.append(mf_burst) net_doc.gap_junctions.append(gj) ### ------------ Connectivity ### background excitatory inputs: MF to GoC populations MFProjection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id) net.projections.append(MFProjection) #Get list of MF->GoC synapse mf_synlist = nu.randdist_MF_syn(N_mf, N_goc, pConn=0.3) # Not tuned to any data - qqq! 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") #on soma MFProjection.connections.append(conn2) ### Add few burst inputs n_bursts = 4 gocPerm = np.random.permutation( N_goc) # change to central neurons later -qqq !!! 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 ### Electrical coupling between GoCs # 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) # Add electrical synapses GoCCoupling = nml.ElectricalProjection(id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id) nGJ = GJ_pairs.shape[0] for jj in range(nGJ): 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]) GoCCoupling.electrical_connection_instance_ws.append(conn) net.electrical_projections.append(GoCCoupling) ### -------------- Write files 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_neuroml2_file(net_filename) ls.include_neuroml2_file(goc_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() if run: res = pynml.run_lems_with_jneuroml_neuron(lems_simfile, max_memory="2G", nogui=True, plot=False) else: res = pynml.run_lems_with_jneuroml_neuron(lems_simfile, max_memory="2G", only_generate_scripts=True, compile_mods=False, nogui=True, plot=False) return res
def XF_input_models_3D_region_specific_import(popID, cellType, cellNML2Type, input_group_parameters, cell_positions, seed_number, sim_params): random.seed(seed_number) parentDir = None simID = sim_params['simID'] expID = sim_params['experimentID'] libID = sim_params['libraryID'] saveCellID = sim_params['saveCellID'] lib_params = sim_params['libraryParams'] input_receiving_cells = [] if 'currentDir' in sim_params: currDir = sim_params['currentDir'] if 'parentDir' in sim_params: parentDir = sim_params['parentDir'] if parentDir != None: cellTypeFile = parentDir + "/NeuroML2" + "/" + cellType else: cellTypeFile = cellType fraction_to_target_per_pop = input_group_parameters['fractionToTarget'] dim_array = np.shape(cell_positions) region_specific_targets_per_cell_group = [] for region in range(0, len(input_group_parameters['regionList'])): for cell in range(0, dim_array[0]): if input_group_parameters['regionList'][region]['xVector'][0] < cell_positions[cell,0] \ and cell_positions[cell,0] < input_group_parameters['regionList'][region]['xVector'][1]: if input_group_parameters['regionList'][region]['yVector'][0] < cell_positions[cell,1] \ and cell_positions[cell,1] < input_group_parameters['regionList'][region]['yVector'][1] : if input_group_parameters['regionList'][region]['zVector'][0] < cell_positions[cell,2] \ and cell_positions[cell,2] < input_group_parameters['regionList'][region]['zVector'][1]: region_specific_targets_per_cell_group.append(cell) target_cells = random.sample( region_specific_targets_per_cell_group, int( round(fraction_to_target_per_pop * len(region_specific_targets_per_cell_group)))) synapse_list = input_group_parameters['synapseList'] label = input_group_parameters['inputLabel'] input_pop_array = [] spike_arrays = [] proj_arrays = [] synapse_name_array = [] if input_group_parameters['colocalizeSynapses']: print("will add block for localizing synapses") if input_group_parameters[ 'targetingModel'] == "segments and subsegments": segment_target_array = extract_morphology_information( [cellTypeFile], {cellTypeFile: cellNML2Type}, ["segments", input_group_parameters['segmentList']]) if input_group_parameters[ 'targetingModel'] == "segment groups and segments": segment_target_array = extract_morphology_information( [cellTypeFile], {cellTypeFile: cellNML2Type}, ["segment groups", input_group_parameters['segmentGroupList']]) cell_counter = 0 for target_cell in target_cells: if saveCellID: input_receiving_cells.append(target_cell) if input_group_parameters[ 'numberModel'] == "constant number of inputs per cell": no_of_inputs = input_group_parameters['noInputs'] if input_group_parameters[ 'numberModel'] == "variable number of inputs per cell": if input_group_parameters['distribution'] == "binomial": no_of_inputs=np.random.binomial(input_group_parameters['maxNoInputs'],\ input_group_parameters['averageNoInputs']/input_group_parameters['maxNoInputs']) ### other options can be added if input_group_parameters[ 'targetingModel'] == "segment groups and segments": target_points=get_unique_target_points(segment_target_array,"segment groups and segments",\ [input_group_parameters['segmentGroupList'],input_group_parameters['segmentGroupProbabilities']],no_of_inputs) if input_group_parameters[ 'targetingModel'] == "segments and subsegments": target_points=get_unique_target_points(segment_target_array,"segments and subsegments",\ [input_group_parameters['segmentList'],input_group_parameters['segmentProbabilities'],\ input_group_parameters['fractionAlongANDsubsegProbabilities']],no_of_inputs) target_point_counter = 0 for target_point in range(0, len(target_points)): train_libID = cell_counter + target_point_counter if libID == 'newlyGenerated': file_string = currDir + "/simulations/%s/sim%d/%s_%s_syn0_PoissonTrain_%d.dat" % ( expID, simID, label, popID, train_libID) else: file_string = currDir + "/simulations/%s/sim%d/%s_PoissonTrain_%d.dat" % ( libID, simID, input_group_parameters['inputIdLibrary'], train_libID) if os.path.getsize(file_string) > 0: target_point_counter += 1 spike_times = np.loadtxt(file_string) spike_times = np.transpose(spike_times) spike_times = spike_times[1] spike_array = neuroml.SpikeArray( id="%s_%s_cell%d_%d" % (label, popID, target_cell, target_point)) if 'units' in input_group_parameters: units = input_group_parameters['units'] else: units = "ms" for spike in range(0, len(spike_times)): spike_object = neuroml.Spike( id="%d" % spike, time="%f%s" % (spike_times[spike], units)) spike_array.spikes.append(spike_object) spike_arrays.append(spike_array) Input_pop = neuroml.Population( id="InputPop_%s_%s_cell%d_%d" % (label, popID, target_cell, target_point), size=1, component=spike_array.id) input_pop_array.append(Input_pop) for synapse_index in range(0, len(synapse_list)): synapse_array = synapse_list[synapse_index] synapse_name = synapse_array['synapseType'] synapse_name_array.append(synapse_name) proj = neuroml.Projection(id="InputProj_%s_%s_cell%d_syn%d_%d"%(label,popID,target_cell,synapse_index,target_point),presynaptic_population=Input_pop.id,\ postsynaptic_population=popID,synapse=synapse_name) conn = neuroml.Connection(id="0", \ pre_cell_id="../%s[0]"%(Input_pop.id), \ pre_segment_id=0, \ pre_fraction_along=0.5,\ post_cell_id="../%s/%i/%s"%(popID,target_cell,cellType), \ post_segment_id="%d"%target_points[target_point,0], post_fraction_along="%f"%target_points[target_point,1]) proj.connections.append(conn) proj_arrays.append(proj) cell_counter += 1 else: for synapse_index in range(0, len(synapse_list)): synapse_array = synapse_list[synapse_index] synapse_name = synapse_array['synapseType'] synapse_name_array.append(synapse_name) if synapse_array['targetingModel'] == "segments and subsegments": segment_target_array = extract_morphology_information( [cellTypeFile], {cellTypeFile: cellNML2Type}, ["segments", synapse_array['segmentList']]) if synapse_array[ 'targetingModel'] == "segment groups and segments": segment_target_array = extract_morphology_information( [cellTypeFile], {cellTypeFile: cellNML2Type}, ["segment groups", synapse_array['segmentGroupList']]) cell_counter = 0 for target_cell in target_cells: if saveCellID: input_receiving_cells.append(target_cell) if synapse_array[ 'numberModel'] == "constant number of inputs per cell": no_of_inputs = synapse_array['noInputs'] if synapse_array[ 'numberModel'] == "variable number of inputs per cell": if synapse_array['distribution'] == "binomial": no_of_inputs=np.random.binomial(synapse_array['maxNoInputs'],\ synapse_array['averageNoInputs']/synapse_array['maxNoInputs']) ### other options can be added if synapse_array[ 'targetingModel'] == "segment groups and segments": target_points=get_unique_target_points(segment_target_array,"segment groups and segments",\ [synapse_array['segmentGroupList'],synapse_array['segmentGroupProbabilities']],no_of_inputs) if synapse_array[ 'targetingModel'] == "segments and subsegments": target_points=get_unique_target_points(segment_target_array,"segments and subsegments",\ [synapse_array['segmentList'],synapse_array['segmentProbabilities'],\ synapse_array['fractionAlongANDsubsegProbabilities']],no_of_inputs) target_point_counter = 0 for target_point in range(0, len(target_points)): train_libID = cell_counter + target_point_counter if libID == 'newlyGenerated': file_string = currDir + "/simulations/%s/sim%d/%s_%s_syn%d_PoissonTrain_%d.dat" % ( expID, simID, label, popID, synapse_index, train_libID) else: file_string = currDir + "/simulations/%s/sim%d/%s_PoissonTrain_%d.dat" % ( libID, simID, synapse_array['inputIdLibrary'], train_libID) if os.path.getsize(file_string) > 0: target_point_counter += 1 spike_times = np.loadtxt(file_string) spike_times = np.transpose(spike_times) spike_times = spike_times[1] spike_array = neuroml.SpikeArray( id="%s_%s_cell%d_syn%d_%d" % (label, popID, target_cell, synapse_index, target_point)) if 'units' in input_group_parameters: units = synapse_array['units'] else: units = "ms" for spike in range(0, len(spike_times)): spike_object = neuroml.Spike( id="%d" % spike, time="%f%s" % (spike_times[spike], units)) spike_array.spikes.append(spike_object) spike_arrays.append(spike_array) Input_pop = neuroml.Population( id="InputPop_%s_%s_syn%d_%d" % (label, popID, synapse_index, target_point), size=1, component=spike_array.id) input_pop_array.append(Input_pop) proj = neuroml.Projection(id="InputProj_%s_%s_syn%d_%d"%(label,popID,synapse_index,target_point),presynaptic_population=Input_pop.id,\ postsynaptic_population=popID,synapse=synapse_name) conn = neuroml.Connection(id="0", \ pre_cell_id="../%s[0]"%(Input_pop.id), \ pre_segment_id=0, \ pre_fraction_along=0.5,\ post_cell_id="../%s/%i/%s"%(popID,target_cell,cellType), \ post_segment_id="%d"%target_points[target_point,0], post_fraction_along="%f"%target_points[target_point,1]) proj.connections.append(conn) proj_arrays.append(proj) cell_counter += 1 return input_pop_array, spike_arrays, proj_arrays, synapse_name_array, input_receiving_cells
def chemical_connection_model(pair_id,projection_id,prePop,prePop_listIndex,prePopSize,preCellType,preNML2Type,pre_cell_positions,\ postPop,postPop_listIndex,postPopSize,postCellType,postNML2Type,post_cell_positions,\ connectivity_parameters,seed_number,parentDir=None): random.seed(seed_number) if parentDir != None: preCellTypeFile=parentDir+"/NeuroML2"+"/"+preCellType postCellTypeFile=parentDir+"/NeuroML2"+"/"+postCellType else: preCellTypeFile=preCellType postCellTypeFile=postCellType nonempty_projection=False gapJ_object_array=[] gap_counter=0 ####### one_population=False if prePop==postPop: one_population=True if connectivity_parameters['targetingModelprePop']['model']=="segment groups and segments": pre_pop_target_segment_array=extract_morphology_information([preCellTypeFile],{preCellTypeFile:preNML2Type},\ ["segment groups", \ connectivity_parameters['targetingModelprePop']['segmentGroupList']]) if connectivity_parameters['targetingModelprePop']['model']=="segments and subsegments": pre_pop_target_segment_array=extract_morphology_information([preCellTypeFile],{preCellTypeFile:preNML2Type},\ ["segments",connectivity_parameters['targetingModelprePop']['segmentList']]) if connectivity_parameters['targetingModelpostPop']['model']=="segment groups and segments": post_pop_target_segment_array=extract_morphology_information([postCellTypeFile],{postCellTypeFile:postNML2Type},\ ["segment groups",connectivity_parameters['targetingModelpostPop']['segmentGroupList'] ] ) if connectivity_parameters['targetingModelpostPop']['model']=="segments and subsegments": post_pop_target_segment_array=extract_morphology_information([postCellTypeFile],{postCellTypeFile:postNML2Type},\ ["segments",connectivity_parameters['targetingModelpostPop']['segmentGroupList']]) proj = neuroml.Projection(id="proj%d"%projection_id,presynaptic_population=prePop,postsynaptic_population=postPop,synapse=connectivity_parameters['synapse']) synapse_name=connectivity_parameters['synapse'] conn_count = 0 #### for now, no_of_Synapses_Onto_TargetCell is fixed for each presynaptic cell of a given population no_of_Synapses_Onto_TargetCell=connectivity_parameters['number_of_PostCellSynapses_per_PreCell'] ######## connect pre and post populations according to a given probability and a number of synapses made by a single presynaptic cell onto a single postsynaptic cell if connectivity_parameters['chemicalConnModel']=="explicit_connection_probabilities": connection_probability=connectivity_parameters['connProb_from_PreCell_to_PostCell'] for Pre_cell in range(0,prePopSize): if one_population: post_index_array=range(0,postPopSize) post_index_array.remove(Pre_cell) else: post_index_array=range(0,postPopSize) if connectivity_parameters['targetingModelprePop']['model']=="segment groups and segments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segment groups and segments",\ [connectivity_parameters['targetingModelprePop']['segmentGroupList'],\ connectivity_parameters['targetingModelprePop']['segmentGroupProbabilities']],no_of_Synapses_Onto_TargetCell) if connectivity_parameters['targetingModelprePop']['model']=="segments and subsegments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segments and subsegments",\ [connectivity_parameters['targetingModelprePop']['segmentList'],\ connectivity_parameters['targetingModelprePop']['segmentProbabilities'],connectivity_parameters['targetingModelprePop']['fractionAlongANDsubsegProbabilities']],\ no_of_Synapses_Onto_TargetCell) for Post_cell in post_index_array: if random.random() < connection_probability: if connectivity_parameters['targetingModelpostPop']['model']=="segment groups and segments": post_targeting_mode="segment groups and segments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentGroupList'],\ connectivity_parameters['targetingModelpostPop']['segmentGroupProbabilities']] if connectivity_parameters['targetingModelpostPop']['model']=="segments and subsegments": post_targeting_mode="segments and subsegments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentList'],\ connectivity_parameters['targetingModelpostPop']['segmentProbabilities'],connectivity_parameters['targetingModelpostPop']['fractionAlongANDsubsegProbabilities']] for pre_target_point in range(0,no_of_Synapses_Onto_TargetCell): if 'maximalConnDistance' in connectivity_parameters: x=0 while x==0: post_target_points=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,post_targeting_parameters,1) if get_3D_connection_length(preCellTypeFile,postCellTypeFile,preNML2Type,postNML2Type,pre_cell_positions,post_cell_positions,Pre_cell,\ Post_cell,pre_target_points[pre_target_point,0],post_target_point[0,0],\ pre_target_points[pre_target_point,1],post_target_point[0,1]) <=connectivity_parameters['maximalConnDistance']: x=1 else: post_target_point=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,\ post_targeting_parameters,1) Pre_segment_id=pre_target_points[pre_target_point,0] Post_segment_id=post_target_point[0,0] Pre_fraction=pre_target_points[pre_target_point,1] Post_fraction=post_target_point[0,1] conn =neuroml.Connection(id=conn_count,pre_cell="../%s/%d/%s"%(prePop,Pre_cell,preCellType),\ post_cell="../%s/%d/%s"%(postPop,Post_cell,postCellType),\ pre_segment="%d"%Pre_segment_id,post_segment="%d"%Post_segment_id,\ pre_fraction_along="%f"%Pre_fraction,post_fraction_along="%f"%Post_fraction) nonempty_projection=True proj.connections.append(conn) conn_count+=1 ##### projection in which each presynaptic cell contacts a fixed number of postsynaptic cells if connectivity_parameters['chemicalConnModel']=="fixedNo_of_PostTargetCells": for Pre_cell in range(0,prePopSize): if one_population: post_index_array=range(0,postPopSize) post_index_array.remove(Pre_cell) else: post_index_array=range(0,postPopSize) if connectivity_parameters['chooseTargetMode']=='random': randomly_selected_target_cells=random.sample(range(post_index_array),int(round(connectivity_parameters['number_of_PostTargetCells_per_PreCell']))) ###### other chooseTargetModes can be added in the future if connectivity_parameters['targetingModelprePop']['model']=="segment groups and segments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segment groups and segments",\ [connectivity_parameters['targetingModelprePop']['segmentGroupList'],\ connectivity_parameters['targetingModelprePop']['segmentGroupProbabilities']],no_of_Synapses_Onto_TargetCell) if connectivity_parameters['targetingModelprePop']['model']=="segments and subsegments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segments and subsegments",\ [connectivity_parameters['targetingModelprePop']['segmentList'],\ connectivity_parameters['targetingModelprePop']['segmentProbabilities'],connectivity_parameters['targetingModelprePop']['fractionAlongANDsubsegProbabilities']],\ no_of_Synapses_Onto_TargetCell) for Post_cell in randomly_selected_target_cells: if connectivity_parameters['targetingModelpostPop']['model']=="segment groups and segments": post_targeting_mode="segment groups and segments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentGroupList'],\ connectivity_parameters['targetingModelpostPop']['segmentGroupProbabilities']] if connectivity_parameters['targetingModelpostPop']['model']=="segments and subsegments": post_targeting_mode="segments and subsegments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentList'],\ connectivity_parameters['targetingModelpostPop']['segmentProbabilities'],connectivity_parameters['targetingModelpostPop']['fractionAlongANDsubsegProbabilities']] for pre_target_point in range(0,no_of_Synapses_Onto_TargetCell): if 'maximalConnDistance' in connectivity_parameters: x=0 while x==0: post_target_points=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,post_targeting_parameters,1) if get_3D_connection_length(preCellTypeFile,postCellTypeFile,preNML2Type,postNML2Type,pre_cell_positions,post_cell_positions,Pre_cell,\ Post_cell,pre_target_points[pre_target_point,0],post_target_point[0,0],\ pre_target_points[pre_target_point,1],post_target_point[0,1]) <=connectivity_parameters['maximalConnDistance']: x=1 else: post_target_point=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,\ post_targeting_parameters,1) Pre_segment_id=pre_target_points[pre_target_point,0] Post_segment_id=post_target_point[0,0] Pre_fraction=pre_target_points[pre_target_point,1] Post_fraction=post_target_point[0,1] conn =neuroml.Connection(id=conn_count,pre_cell="../%s/%d/%s"%(prePop,Pre_cell,preCellType),\ post_cell="../%s/%d/%s"%(postPop,Post_cell,postCellType),\ pre_segment="%d"%Pre_segment_id,post_segment="%d"%Post_segment_id,\ pre_fraction_along="%f"%Pre_fraction,post_fraction_along="%f"%Post_fraction) nonempty_projection=True proj.connections.append(conn) conn_count+=1 ############ projection in which each presynaptic cell of a given presynaptic population has a variable number of postsynaptic targets according to a given statistical distribution if connectivity_parameters['chemicalConnModel']=="variableNo_of_PostTargetCells": for Pre_cell in range(0,prePopSize): if one_population: post_index_array=range(0,postPopSize) post_index_array.remove(Pre_cell) else: post_index_array=range(0,postPopSize) if connectivity_parameters['targetNoModel']['modelType']=='binomial': no_of_targets=np.random.binomial(connectivity_parameters['targetNoModel']['maxTargetNo'],\ connectivity_parameters['targetNoModel']['average']/connectivity_parameters['targetNoModel']['maxTargetNo']) ####### other distributions can be added in the future if connectivity_parameters['chooseTargetMode']=='random': randomly_selected_target_cells=random.sample(post_index_array,int(round(no_of_targets))) ###### other chooseTargetModes can be added in the future if connectivity_parameters['targetingModelprePop']['model']=="segment groups and segments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segment groups and segments",\ [connectivity_parameters['targetingModelprePop']['segmentGroupList'],\ connectivity_parameters['targetingModelprePop']['segmentGroupProbabilities']],no_of_Synapses_Onto_TargetCell) if connectivity_parameters['targetingModelprePop']['model']=="segments and subsegments": pre_target_points=get_unique_target_points(pre_pop_target_segment_array,"segments and subsegments",\ [connectivity_parameters['targetingModelprePop']['segmentList'],\ connectivity_parameters['targetingModelprePop']['segmentProbabilities'],connectivity_parameters['targetingModelprePop']['fractionAlongANDsubsegProbabilities']],\ no_of_Synapses_Onto_TargetCell) for Post_cell in randomly_selected_target_cells: if connectivity_parameters['targetingModelpostPop']['model']=="segment groups and segments": post_targeting_mode="segment groups and segments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentGroupList'],\ connectivity_parameters['targetingModelpostPop']['segmentGroupProbabilities']] if connectivity_parameters['targetingModelpostPop']['model']=="segments and subsegments": post_targeting_mode="segments and subsegments" post_targeting_parameters=[connectivity_parameters['targetingModelpostPop']['segmentList'],\ connectivity_parameters['targetingModelpostPop']['segmentProbabilities'],connectivity_parameters['targetingModelpostPop']['fractionAlongANDsubsegProbabilities']] for pre_target_point in range(0,no_of_Synapses_Onto_TargetCell): if 'maximalConnDistance' in connectivity_parameters: x=0 while x==0: post_target_points=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,post_targeting_parameters,1) if get_3D_connection_length(preCellTypeFile,postCellTypeFile,preNML2Type,postNML2Type,pre_cell_positions,post_cell_positions,Pre_cell,\ Post_cell,pre_target_points[pre_target_point,0],post_target_point[0,0],\ pre_target_points[pre_target_point,1],post_target_point[0,1]) <=connectivity_parameters['maximalConnDistance']: x=1 else: post_target_point=get_unique_target_points(post_pop_target_segment_array,post_targeting_mode,\ post_targeting_parameters,1) Pre_segment_id=pre_target_points[pre_target_point,0] Post_segment_id=post_target_point[0,0] Pre_fraction=pre_target_points[pre_target_point,1] Post_fraction=post_target_point[0,1] conn =neuroml.Connection(id=conn_count,pre_cell="../%s/%d/%s"%(prePop,Pre_cell,preCellType),\ post_cell="../%s/%d/%s"%(postPop,Post_cell,postCellType),\ pre_segment="%d"%Pre_segment_id,post_segment="%d"%Post_segment_id,\ pre_fraction_along="%f"%Pre_fraction,post_fraction_along="%f"%Post_fraction) nonempty_projection=True proj.connections.append(conn) conn_count+=1 return proj, nonempty_projection,gapJ_object_array,synapse_name
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
tsi_input_list.input.append( neuroml.Input(id=1, target='../%s/1/%s' % (pyr_cells_pop3.id, cell_id), segment_id="2", destination="synapses")) tsi_input_list.input.append( neuroml.Input(id=2, target='../%s/2/%s' % (pyr_cells_pop3.id, cell_id), segment_id="4", destination="synapses")) net.input_lists.append(tsi_input_list) # Create a projection proj_sa = neuroml.Projection(id="Proj_sa", synapse=syn1.id, presynaptic_population=sa_pop.id, postsynaptic_population=pyr_cells_pop1.id) net.projections.append(proj_sa) proj_sa.connections.append(neuroml.Connection(id=0, \ pre_cell_id="../%s[0]"%(sa_pop.id), post_cell_id="../%s/%i/%s"%(pyr_cells_pop1.id,0,cell_id))) proj_sa.connections.append(neuroml.Connection(id=1, \ pre_cell_id="../%s[0]"%(sa_pop.id), post_cell_id="../%s/%i/%s"%(pyr_cells_pop1.id,1,cell_id), post_segment_id = "2",)) proj_sa.connections.append(neuroml.Connection(id=2, \ pre_cell_id="../%s[0]"%(sa_pop.id),
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