def create_olm_network(): """Create the network :returns: name of network nml file """ net_doc = NeuroMLDocument(id="network", notes="OLM cell network") net_doc_fn = "olm_example_net.nml" net_doc.includes.append(IncludeType(href=create_olm_cell())) # Create a population: convenient to create many cells of the same type pop = Population(id="pop0", notes="A population for our cell", component="olm", size=1, type="populationList") pop.instances.append(Instance(id=1, location=Location(0., 0., 0.))) # Input pulsegen = PulseGenerator(id="pg_olm", notes="Simple pulse generator", delay="100ms", duration="100ms", amplitude="0.08nA") exp_input = ExplicitInput(target="pop0[0]", input="pg_olm") net = Network(id="single_olm_cell_network", note="A network with a single population") net_doc.pulse_generators.append(pulsegen) net.explicit_inputs.append(exp_input) net.populations.append(pop) net_doc.networks.append(net) pynml.write_neuroml2_file(nml2_doc=net_doc, nml2_file_name=net_doc_fn, validate=True) return net_doc_fn
def run(): ######################## Build the network #################################### nml_doc = NeuroMLDocument(id="IafNet") IaFCell0 = IaFCell(id="iaf0", C="1.0 nF", thresh = "-50mV", reset="-65mV", leak_conductance="10 nS", leak_reversal="-65mV") nml_doc.iaf_cells.append(IaFCell0) IaFCell1 = IaFCell(id="iaf1", C="1.0 nF", thresh = "-50mV", reset="-65mV", leak_conductance="20 nS", leak_reversal="-65mV") nml_doc.iaf_cells.append(IaFCell1) syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms") nml_doc.exp_one_synapses.append(syn0) net = Network(id="IafNet") nml_doc.networks.append(net) size0 = 5 pop0 = Population(id="IafPop0", component=IaFCell0.id, size=size0) net.populations.append(pop0) size1 = 5 pop1 = Population(id="IafPop1", component=IaFCell0.id, size=size1) net.populations.append(pop1) prob_connection = 0.5 for pre in range(0,size0): pg = PulseGenerator(id="pulseGen_%i"%pre, delay="0ms", duration="100ms", amplitude="%f nA"%(0.1*random())) nml_doc.pulse_generators.append(pg) net.explicit_inputs.append(ExplicitInput(target="%s[%i]"%(pop0.id,pre), input=pg.id)) for post in range(0,size1): # fromxx is used since from is Python keyword if random() <= prob_connection: net.synaptic_connections.append(SynapticConnection(from_="%s[%i]"%(pop0.id,pre), synapse=syn0.id, to="%s[%i]"%(pop1.id,post))) nml_file = 'tmp/testnet.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) ###### Validate the NeuroML ###### from utils import validateNeuroML2 validateNeuroML2(nml_file)
def add_new_input(nml_doc, cell, delay, duration, amplitude, params): stim = PulseGenerator(id="stim_" + cell, delay=delay, duration=duration, amplitude=amplitude) nml_doc.pulse_generators.append(stim) populations_without_location = isinstance(params.elec_syn, GapJunction) target = "%s/0/%s" % (cell, params.generic_cell.id) if populations_without_location: target = "%s[0]" % (cell) exp_input = ExplicitInput(target=target, input=stim.id) nml_doc.networks[0].explicit_inputs.append(exp_input)
def generate(net_id, params, cells = None, cells_to_plot=None, cells_to_stimulate=None, duration=500, dt=0.01, vmin=-75, vmax=20): nml_doc = NeuroMLDocument(id=net_id) nml_doc.iaf_cells.append(params.generic_cell) net = Network(id=net_id) nml_doc.networks.append(net) nml_doc.pulse_generators.append(params.offset_current) # Use the spreadsheet reader to give a list of all cells and a list of all connections # This could be replaced with a call to "DatabaseReader" or "OpenWormNeuroLexReader" in future... cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet("../../../") cell_names.sort() # To hold all Cell NeuroML objects vs. names all_cells = {} # lems_file = "" lems_info = {"reference": net_id, "duration": duration, "dt": dt, "vmin": vmin, "vmax": vmax, "cell_component": params.generic_cell.id} lems_info["plots"] = [] lems_info["cells"] = [] for cell in cell_names: if cells is None or cell in cells: # build a Population data structure out of the cell name pop0 = Population(id=cell, component=params.generic_cell.id, type="populationList") inst = Instance(id="0") pop0.instances.append(inst) # put that Population into the Network data structure from above net.populations.append(pop0) # also use the cell name to grab the morphology file, as a NeuroML data structure # into the 'all_cells' dict cell_file = '../../generatedNeuroML2/%s.nml'%cell doc = loaders.NeuroMLLoader.load(cell_file) all_cells[cell] = doc.cells[0] location = doc.cells[0].morphology.segments[0].proximal print("Loaded morphology file from: %s, with id: %s, location: (%s, %s, %s)"%(cell_file, all_cells[cell].id, location.x, location.y, location.z)) inst.location = Location(float(location.x), float(location.y), float(location.z)) exp_input = ExplicitInput(target="%s/0/%s"%(pop0.id, params.generic_cell.id), input=params.offset_current.id) if cells_to_stimulate is None or cell in cells_to_stimulate: net.explicit_inputs.append(exp_input) if cells_to_plot is None or cell in cells_to_plot: plot = {} plot["cell"] = cell plot["colour"] = get_random_colour_hex() lems_info["plots"].append(plot) lems_info["cells"].append(cell) for conn in conns: if conn.pre_cell in lems_info["cells"] and conn.post_cell in lems_info["cells"]: # take information about each connection and package it into a # NeuroML Projection data structure proj_id = get_projection_id(conn.pre_cell, conn.post_cell, conn.synclass, conn.syntype) syn0 = params.exc_syn if 'GABA' in conn.synclass: syn0 = params.inh_syn syn_new = create_n_connection_synapse(syn0, conn.number, nml_doc) proj0 = Projection(id=proj_id, \ presynaptic_population=conn.pre_cell, postsynaptic_population=conn.post_cell, synapse=syn_new.id) # Get the corresponding Cell for each # pre_cell = all_cells[conn.pre_cell] # post_cell = all_cells[conn.post_cell] net.projections.append(proj0) # Add a Connection with the closest locations conn0 = Connection(id="0", \ pre_cell_id="../%s/0/%s"%(conn.pre_cell, params.generic_cell.id), post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_cell.id)) proj0.connections.append(conn0) write_to_file(nml_doc, lems_info, net_id)
pop1 = Population(id="IafPop1", component=IafCell0.id, size=size1) net.populations.append(pop1) prob_connection = 0.5 for pre in range(0, size0): pg = PulseGenerator(id="pulseGen_%i" % pre, delay="0ms", duration="100ms", amplitude="%f nA" % (0.1 * random())) nml_doc.pulse_generators.append(pg) exp_input = ExplicitInput(target="%s[%i]" % (pop0.id, pre), input=pg.id) net.explicit_inputs.append(exp_input) for post in range(0, size1): # fromxx is used since from is Python keyword if random() <= prob_connection: syn = SynapticConnection(from_="%s[%i]" % (pop0.id, pre), synapse=syn0.id, to="%s[%i]" % (pop1.id, post)) net.synaptic_connections.append(syn) nml_file = 'tmp/testnet.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: " + nml_file)
size=n_pops[pop_idx], type='populationList') net.populations.append(population) population.properties.append(Property(tag='color', value=colours[pop_idx])) population.properties.append(Property(tag='radius', value='10')) for n_pop in range(n_pops[pop_idx]): inst = Instance(id=n_pop) population.instances.append(inst) inst.location = Location(x=-20 if 'E' in pop else 20, y=0, z=0) for from_idx, from_pop in enumerate(pops): for to_idx, to_pop in enumerate(pops): generatePopulationProjection(pops[from_idx], pops[to_idx], n_pops[from_idx], n_pops[to_idx], w_to_from_pops[to_idx, from_idx], net) # Add inputs for pop_idx, pop in enumerate(pops): for n_idx in range(n_pops[pop_idx]): exp_input = ExplicitInput(target='%sPop/%i/%s' % (pop, n_idx, pop), input='mod_%s' % pops[pop_idx], destination='synapses') net.explicit_inputs.append(exp_input) nml_file = 'WC_%s%s.net.nml' % (baseline, dl_str) writers.NeuroMLWriter.write(nml_doc, nml_file) print('Written NeuroML file: %s' % nml_file) generatePopulationSimulationLEMS(n_pops, baseline, pops, duration, dt, dl)
def generate(net_id, params, cells = None, cells_to_plot = None, cells_to_stimulate = None, include_muscles=False, conn_number_override = None, conn_number_scaling = None, duration = 500, dt = 0.01, vmin = -75, vmax = 20, seed = 1234, validate=True, test=False): random.seed(seed) info = "\n\nParameters and setting used to generate this network:\n\n"+\ " Cells: %s\n" % (cells if cells is not None else "All cells")+\ " Cell stimulated: %s\n" % (cells_to_stimulate if cells_to_stimulate is not None else "All cells")+\ " Connection numbers overridden: %s\n" % (conn_number_override if conn_number_override is not None else "None")+\ " Connection numbers scaled: %s\n" % (conn_number_scaling if conn_number_scaling is not None else "None")+\ " Include muscles: %s\n" % include_muscles info += "\n%s\n"%(bioparameter_info(" ")) nml_doc = NeuroMLDocument(id=net_id, notes=info) nml_doc.iaf_cells.append(params.generic_cell) net = Network(id=net_id) nml_doc.networks.append(net) nml_doc.pulse_generators.append(params.offset_current) # Use the spreadsheet reader to give a list of all cells and a list of all connections # This could be replaced with a call to "DatabaseReader" or "OpenWormNeuroLexReader" in future... # If called from unittest folder ammend path to "../../../../" spreadsheet_location = "../../../../" if test else "../../../" cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet(spreadsheet_location, include_nonconnected_cells=True) cell_names.sort() # To hold all Cell NeuroML objects vs. names all_cells = {} # lems_file = "" lems_info = {"comment": info, "reference": net_id, "duration": duration, "dt": dt, "vmin": vmin, "vmax": vmax, "cell_component": params.generic_cell.id} lems_info["plots"] = [] lems_info["activity_plots"] = [] lems_info["muscle_plots"] = [] lems_info["muscle_activity_plots"] = [] lems_info["to_save"] = [] lems_info["activity_to_save"] = [] lems_info["muscles_to_save"] = [] lems_info["muscles_activity_to_save"] = [] lems_info["cells"] = [] lems_info["muscles"] = [] lems_info["includes"] = [] if hasattr(params.generic_cell, 'custom_component_type_definition'): lems_info["includes"].append(params.generic_cell.custom_component_type_definition) backers_dir = "../../../../OpenWormBackers/" if test else "../../../OpenWormBackers/" sys.path.append(backers_dir) import backers cells_vs_name = backers.get_adopted_cell_names(backers_dir) populations_without_location = isinstance(params.elec_syn, GapJunction) count = 0 for cell in cell_names: if cells is None or cell in cells: inst = Instance(id="0") if not populations_without_location: # build a Population data structure out of the cell name pop0 = Population(id=cell, component=params.generic_cell.id, type="populationList") pop0.instances.append(inst) else: # build a Population data structure out of the cell name pop0 = Population(id=cell, component=params.generic_cell.id, size="1") # put that Population into the Network data structure from above net.populations.append(pop0) if cells_vs_name.has_key(cell): p = Property(tag="OpenWormBackerAssignedName", value=cells_vs_name[cell]) pop0.properties.append(p) # also use the cell name to grab the morphology file, as a NeuroML data structure # into the 'all_cells' dict cell_file_path = "../../../" if test else "../../" #if running test cell_file = cell_file_path+'generatedNeuroML2/%s.nml'%cell doc = loaders.NeuroMLLoader.load(cell_file) all_cells[cell] = doc.cells[0] location = doc.cells[0].morphology.segments[0].proximal print("Loaded morphology file from: %s, with id: %s, location: (%s, %s, %s)"%(cell_file, all_cells[cell].id, location.x, location.y, location.z)) inst.location = Location(float(location.x), float(location.y), float(location.z)) target = "%s/0/%s"%(pop0.id, params.generic_cell.id) if populations_without_location: target = "%s[0]" % (cell) exp_input = ExplicitInput(target=target, input=params.offset_current.id) if cells_to_stimulate is None or cell in cells_to_stimulate: net.explicit_inputs.append(exp_input) if cells_to_plot is None or cell in cells_to_plot: plot = {} plot["cell"] = cell plot["colour"] = get_random_colour_hex() plot["quantity"] = "%s/0/%s/v" % (cell, params.generic_cell.id) if populations_without_location: plot["quantity"] = "%s[0]/v" % (cell) lems_info["plots"].append(plot) if hasattr(params.generic_cell, 'custom_component_type_definition'): plot = {} plot["cell"] = cell plot["colour"] = get_random_colour_hex() plot["quantity"] = "%s/0/%s/activity" % (cell, params.generic_cell.id) if populations_without_location: plot["quantity"] = "%s[0]/activity" % (cell) lems_info["activity_plots"].append(plot) save = {} save["cell"] = cell save["quantity"] = "%s/0/%s/v" % (cell, params.generic_cell.id) if populations_without_location: save["quantity"] = "%s[0]/v" % (cell) lems_info["to_save"].append(save) if hasattr(params.generic_cell, 'custom_component_type_definition'): save = {} save["cell"] = cell save["quantity"] = "%s/0/%s/activity" % (cell, params.generic_cell.id) if populations_without_location: save["quantity"] = "%s[0]/activity" % (cell) lems_info["activity_to_save"].append(save) lems_info["cells"].append(cell) count+=1 print("Finished loading %i cells"%count) mneurons, all_muscles, muscle_conns = SpreadsheetDataReader.readMuscleDataFromSpreadsheet(spreadsheet_location) muscles = get_muscle_names() if include_muscles: muscle_count = 0 for muscle in muscles: inst = Instance(id="0") if not populations_without_location: # build a Population data structure out of the cell name pop0 = Population(id=muscle, component=params.generic_cell.id, type="populationList") pop0.instances.append(inst) else: # build a Population data structure out of the cell name pop0 = Population(id=muscle, component=params.generic_cell.id, size="1") # put that Population into the Network data structure from above net.populations.append(pop0) if cells_vs_name.has_key(muscle): # No muscles adopted yet, but just in case they are in future... p = Property(tag="OpenWormBackerAssignedName", value=cells_vs_name[muscle]) pop0.properties.append(p) inst.location = Location(100, 10*muscle_count, 100) target = "%s/0/%s"%(pop0.id, params.generic_cell.id) if populations_without_location: target = "%s[0]" % (muscle) plot = {} plot["cell"] = muscle plot["colour"] = get_random_colour_hex() plot["quantity"] = "%s/0/%s/v" % (muscle, params.generic_cell.id) if populations_without_location: plot["quantity"] = "%s[0]/v" % (muscle) lems_info["muscle_plots"].append(plot) if hasattr(params.generic_cell, 'custom_component_type_definition'): plot = {} plot["cell"] = muscle plot["colour"] = get_random_colour_hex() plot["quantity"] = "%s/0/%s/activity" % (muscle, params.generic_cell.id) if populations_without_location: plot["quantity"] = "%s[0]/activity" % (muscle) lems_info["muscle_activity_plots"].append(plot) save = {} save["cell"] = muscle save["quantity"] = "%s/0/%s/v" % (muscle, params.generic_cell.id) if populations_without_location: save["quantity"] = "%s[0]/v" % (muscle) lems_info["muscles_to_save"].append(save) if hasattr(params.generic_cell, 'custom_component_type_definition'): save = {} save["cell"] = muscle save["quantity"] = "%s/0/%s/activity" % (muscle, params.generic_cell.id) if populations_without_location: save["quantity"] = "%s[0]/activity" % (muscle) lems_info["muscles_activity_to_save"].append(save) lems_info["muscles"].append(muscle) muscle_count+=1 print("Finished creating %i muscles"%muscle_count) for conn in conns: if conn.pre_cell in lems_info["cells"] and conn.post_cell in lems_info["cells"]: # take information about each connection and package it into a # NeuroML Projection data structure proj_id = get_projection_id(conn.pre_cell, conn.post_cell, conn.synclass, conn.syntype) elect_conn = False syn0 = params.exc_syn if 'GABA' in conn.synclass: syn0 = params.inh_syn if '_GJ' in conn.synclass: syn0 = params.elec_syn elect_conn = isinstance(params.elec_syn, GapJunction) number_syns = conn.number conn_shorthand = "%s-%s"%(conn.pre_cell, conn.post_cell) if conn_number_override is not None and (conn_number_override.has_key(conn_shorthand)): number_syns = conn_number_override[conn_shorthand] elif conn_number_scaling is not None and (conn_number_scaling.has_key(conn_shorthand)): number_syns = conn.number*conn_number_scaling[conn_shorthand] ''' else: print conn_shorthand print conn_number_override print conn_number_scaling''' if number_syns != conn.number: magnitude, unit = split_neuroml_quantity(syn0.gbase) cond0 = "%s%s"%(magnitude*conn.number, unit) cond1 = "%s%s"%(magnitude*number_syns, unit) print(">> Changing number of effective synapses connection %s -> %s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \ (conn.pre_cell, conn.post_cell, conn.number, cond0, number_syns, cond1)) syn_new = create_n_connection_synapse(syn0, number_syns, nml_doc) if not elect_conn: if not populations_without_location: proj0 = Projection(id=proj_id, \ presynaptic_population=conn.pre_cell, postsynaptic_population=conn.post_cell, synapse=syn_new.id) net.projections.append(proj0) # Add a Connection with the closest locations pre_cell_id="../%s/0/%s"%(conn.pre_cell, params.generic_cell.id) post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_cell.id) conn0 = Connection(id="0", \ pre_cell_id=pre_cell_id, post_cell_id=post_cell_id) proj0.connections.append(conn0) if populations_without_location: # <synapticConnection from="hh1pop[0]" to="hh2pop[0]" synapse="syn1exp" destination="synapses"/> pre_cell_id="%s[0]"%(conn.pre_cell) post_cell_id="%s[0]"%(conn.post_cell) conn0 = SynapticConnection(from_=pre_cell_id, to=post_cell_id, synapse=syn_new.id, destination="synapses") net.synaptic_connections.append(conn0) else: proj0 = ElectricalProjection(id=proj_id, \ presynaptic_population=conn.pre_cell, postsynaptic_population=conn.post_cell) net.electrical_projections.append(proj0) # Add a Connection with the closest locations conn0 = ElectricalConnection(id="0", \ pre_cell="0", post_cell="0", synapse=syn_new.id) proj0.electrical_connections.append(conn0) if include_muscles: for conn in muscle_conns: if conn.pre_cell in lems_info["cells"] and conn.post_cell in muscles: # take information about each connection and package it into a # NeuroML Projection data structure proj_id = get_projection_id(conn.pre_cell, conn.post_cell, conn.synclass, conn.syntype) elect_conn = False syn0 = params.exc_syn if 'GABA' in conn.synclass: syn0 = params.inh_syn if '_GJ' in conn.synclass: syn0 = params.elec_syn elect_conn = isinstance(params.elec_syn, GapJunction) number_syns = conn.number conn_shorthand = "%s-%s"%(conn.pre_cell, conn.post_cell) if conn_number_override is not None and (conn_number_override.has_key(conn_shorthand)): number_syns = conn_number_override[conn_shorthand] elif conn_number_scaling is not None and (conn_number_scaling.has_key(conn_shorthand)): number_syns = conn.number*conn_number_scaling[conn_shorthand] ''' else: print conn_shorthand print conn_number_override print conn_number_scaling''' if number_syns != conn.number: magnitude, unit = split_neuroml_quantity(syn0.gbase) cond0 = "%s%s"%(magnitude*conn.number, unit) cond1 = "%s%s"%(magnitude*number_syns, unit) print(">> Changing number of effective synapses connection %s -> %s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \ (conn.pre_cell, conn.post_cell, conn.number, cond0, number_syns, cond1)) syn_new = create_n_connection_synapse(syn0, number_syns, nml_doc) if not elect_conn: if not populations_without_location: proj0 = Projection(id=proj_id, \ presynaptic_population=conn.pre_cell, postsynaptic_population=conn.post_cell, synapse=syn_new.id) net.projections.append(proj0) # Add a Connection with the closest locations pre_cell_id="../%s/0/%s"%(conn.pre_cell, params.generic_cell.id) post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_cell.id) conn0 = Connection(id="0", \ pre_cell_id=pre_cell_id, post_cell_id=post_cell_id) proj0.connections.append(conn0) if populations_without_location: # <synapticConnection from="hh1pop[0]" to="hh2pop[0]" synapse="syn1exp" destination="synapses"/> pre_cell_id="%s[0]"%(conn.pre_cell) post_cell_id="%s[0]"%(conn.post_cell) conn0 = SynapticConnection(from_=pre_cell_id, to=post_cell_id, synapse=syn_new.id, destination="synapses") net.synaptic_connections.append(conn0) else: proj0 = ElectricalProjection(id=proj_id, \ presynaptic_population=conn.pre_cell, postsynaptic_population=conn.post_cell) net.electrical_projections.append(proj0) # Add a Connection with the closest locations conn0 = ElectricalConnection(id="0", \ pre_cell="0", post_cell="0", synapse=syn_new.id) proj0.electrical_connections.append(conn0) # import pprint # pprint.pprint(lems_info) template_path = '../' if test else '' # if running test write_to_file(nml_doc, lems_info, net_id, template_path, validate=validate) return nml_doc
def generateExmplicitInput(population, idx, net): exp_input = ExplicitInput(target='%sPop[%d]' % (population, idx), input='baseline_%s%d' % (population, idx), destination='synapses') net.explicit_inputs.append(exp_input)
def createModel(self): # File names of all components pyr_file_name = "../ACnet2_NML2/Cells/pyr_4_sym.cell.nml" bask_file_name = "../ACnet2_NML2/Cells/bask.cell.nml" exc_exc_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn.synapse.nml' exc_inh_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn_inh.synapse.nml' inh_exc_syn_names = '../ACnet2_NML2/Synapses/GABA_syn.synapse.nml' inh_inh_syn_names = '../ACnet2_NML2/Synapses/GABA_syn_inh.synapse.nml' bg_exc_syn_names = '../ACnet2_NML2/Synapses/bg_AMPA_syn.synapse.nml' nml_doc = NeuroMLDocument(id=self.filename + '_doc') net = Network(id=self.filename + '_net') nml_doc.networks.append(net) nml_doc.includes.append(IncludeType(pyr_file_name)) nml_doc.includes.append(IncludeType(bask_file_name)) nml_doc.includes.append(IncludeType(exc_exc_syn_names)) nml_doc.includes.append(IncludeType(exc_inh_syn_names)) nml_doc.includes.append(IncludeType(inh_exc_syn_names)) nml_doc.includes.append(IncludeType(inh_inh_syn_names)) nml_doc.includes.append(IncludeType(bg_exc_syn_names)) # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation(self.filename, self.sim_time, self.dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # The names of the cell type/component used in the Exc & Inh populations exc_group_component = "pyr_4_sym" inh_group_component = "bask" # The names of the Exc & Inh groups/populations exc_group = "pyramidals" #"pyramidals48x48" inh_group = "baskets" #"baskets24x24" # The names of the network connections net_conn_exc_exc = "pyr_pyr" net_conn_exc_inh = "pyr_bask" net_conn_inh_exc = "bask_pyr" net_conn_inh_inh = "bask_bask" # The names of the synapse types exc_exc_syn = "AMPA_syn" exc_exc_syn_seg_id = 3 # Middle apical dendrite exc_inh_syn = "AMPA_syn_inh" exc_inh_syn_seg_id = 1 # Dendrite inh_exc_syn = "GABA_syn" inh_exc_syn_seg_id = 6 # Basal dendrite inh_inh_syn = "GABA_syn_inh" inh_inh_syn_seg_id = 0 # Soma aff_exc_syn = "AMPA_aff_syn" aff_exc_syn_seg_id = 5 # proximal apical dendrite bg_exc_syn = "bg_AMPA_syn" bg_exc_syn_seg_id = 7 # Basal dendrite # Excitatory Parameters XSCALE_ex = 24 #48 ZSCALE_ex = 24 #48 xSpacing_ex = 40 # 10^-6m zSpacing_ex = 40 # 10^-6m # Inhibitory Parameters XSCALE_inh = 12 #24 ZSCALE_inh = 12 #24 xSpacing_inh = 80 # 10^-6m zSpacing_inh = 80 # 10^-6m numCells_ex = XSCALE_ex * ZSCALE_ex numCells_inh = XSCALE_inh * ZSCALE_inh # Connection probabilities (initial value) connection_probability_ex_ex = 0.15 connection_probability_ex_inh = 0.45 connection_probability_inh_ex = 0.6 connection_probability_inh_inh = 0.6 # Generate excitatory cells exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=XSCALE_ex * ZSCALE_ex) net.populations.append(exc_pop) exc_pos = np.zeros((XSCALE_ex * ZSCALE_ex, 2)) for i in range(0, XSCALE_ex): for j in range(0, ZSCALE_ex): # create cells x = i * xSpacing_ex z = j * zSpacing_ex index = i * ZSCALE_ex + j inst = Instance(id=index) exc_pop.instances.append(inst) inst.location = Location(x=x, y=0, z=z) exc_pos[index, 0] = x exc_pos[index, 1] = z # Generate inhibitory cells inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=XSCALE_inh * ZSCALE_inh) net.populations.append(inh_pop) inh_pos = np.zeros((XSCALE_inh * ZSCALE_inh, 2)) for i in range(0, XSCALE_inh): for j in range(0, ZSCALE_inh): # create cells x = i * xSpacing_inh z = j * zSpacing_inh index = i * ZSCALE_inh + j inst = Instance(id=index) inh_pop.instances.append(inst) inst.location = Location(x=x, y=0, z=z) inh_pos[index, 0] = x inh_pos[index, 1] = z proj_exc_exc = Projection(id=net_conn_exc_exc, presynaptic_population=exc_group, postsynaptic_population=exc_group, synapse=exc_exc_syn) net.projections.append(proj_exc_exc) proj_exc_inh = Projection(id=net_conn_exc_inh, presynaptic_population=exc_group, postsynaptic_population=inh_group, synapse=exc_inh_syn) net.projections.append(proj_exc_inh) proj_inh_exc = Projection(id=net_conn_inh_exc, presynaptic_population=inh_group, postsynaptic_population=exc_group, synapse=inh_exc_syn) net.projections.append(proj_inh_exc) proj_inh_inh = Projection(id=net_conn_inh_inh, presynaptic_population=inh_group, postsynaptic_population=inh_group, synapse=inh_inh_syn) net.projections.append(proj_inh_inh) # Generate exc -> * connections exc_exc_conn = np.zeros((numCells_ex, numCells_ex)) exc_inh_conn = np.zeros((numCells_ex, numCells_inh)) count_exc_exc = 0 count_exc_inh = 0 for i in range(0, XSCALE_ex): for j in range(0, ZSCALE_ex): x = i * xSpacing_ex y = j * zSpacing_ex index = i * ZSCALE_ex + j #print("Looking at connections for exc cell at (%i, %i)"%(i,j)) # exc -> exc connections conn_type = net_conn_exc_exc for k in range(0, XSCALE_ex): for l in range(0, ZSCALE_ex): # calculate distance from pre- to post-synaptic neuron xk = k * xSpacing_ex yk = l * zSpacing_ex distance = math.sqrt((x - xk)**2 + (y - yk)**2) connection_probability = connection_probability_ex_ex * math.exp( -(distance / (10.0 * xSpacing_ex))**2) # create a random number between 0 and 1, if it is <= connection_probability # accept connection otherwise refuse a = random.random() if 0 < a <= connection_probability: index2 = k * ZSCALE_ex + l count_exc_exc += 1 add_connection(proj_exc_exc, count_exc_exc, exc_group, exc_group_component, index, 0, exc_group, exc_group_component, index2, exc_exc_syn_seg_id) exc_exc_conn[index, index2] = 1 # exc -> inh connections conn_type = net_conn_exc_inh for k in range(0, XSCALE_inh): for l in range(0, ZSCALE_inh): # calculate distance from pre- to post-synaptic neuron xk = k * xSpacing_inh yk = l * zSpacing_inh distance = math.sqrt((x - xk)**2 + (y - yk)**2) connection_probability = connection_probability_ex_inh * math.exp( -(distance / (10.0 * xSpacing_ex))**2) # create a random number between 0 and 1, if it is <= connection_probability # accept connection otherwise refuse a = random.random() if 0 < a <= connection_probability: index2 = k * ZSCALE_inh + l count_exc_inh += 1 add_connection(proj_exc_inh, count_exc_inh, exc_group, exc_group_component, index, 0, inh_group, inh_group_component, index2, exc_inh_syn_seg_id) exc_inh_conn[index, index2] = 1 inh_exc_conn = np.zeros((numCells_inh, numCells_ex)) inh_inh_conn = np.zeros((numCells_inh, numCells_inh)) count_inh_exc = 0 count_inh_inh = 0 for i in range(0, XSCALE_inh): for j in range(0, ZSCALE_inh): x = i * xSpacing_inh y = j * zSpacing_inh index = i * ZSCALE_inh + j #print("Looking at connections for inh cell at (%i, %i)"%(i,j)) # inh -> exc connections conn_type = net_conn_inh_exc for k in range(0, XSCALE_ex): for l in range(0, ZSCALE_ex): # calculate distance from pre- to post-synaptic neuron xk = k * xSpacing_ex yk = l * zSpacing_ex distance = math.sqrt((x - xk)**2 + (y - yk)**2) connection_probability = connection_probability_inh_ex * math.exp( -(distance / (10.0 * xSpacing_ex))**2) # create a random number between 0 and 1, if it is <= connection_probability # accept connection otherwise refuse a = random.random() if 0 < a <= connection_probability: index2 = k * ZSCALE_ex + l count_inh_exc += 1 add_connection(proj_inh_exc, count_inh_exc, inh_group, inh_group_component, index, 0, exc_group, exc_group_component, index2, inh_exc_syn_seg_id) inh_exc_conn[index, index2] = 1 # inh -> inh connections conn_type = net_conn_inh_inh for k in range(0, XSCALE_inh): for l in range(0, ZSCALE_inh): # calculate distance from pre- to post-synaptic neuron xk = k * xSpacing_inh yk = l * zSpacing_inh distance = math.sqrt((x - xk)**2 + (y - yk)**2) connection_probability = connection_probability_inh_inh * math.exp( -(distance / (10.0 * xSpacing_ex))**2) # create a random number between 0 and 1, if it is <= connection_probability # accept connection otherwise refuse a = random.random() if 0 < a <= connection_probability: index2 = k * ZSCALE_inh + l count_inh_inh += 1 add_connection(proj_inh_inh, count_inh_inh, inh_group, inh_group_component, index, 0, inh_group, inh_group_component, index2, inh_inh_syn_seg_id) inh_inh_conn[index, index2] = 1 print( "Generated network with %i exc_exc, %i exc_inh, %i inh_exc, %i inh_inh connections" % (count_exc_exc, count_exc_inh, count_inh_exc, count_inh_inh)) ####### Create Input ###### # Create a sine generator sgE = SineGenerator(id="sineGen_0", phase="0", delay="0ms", duration=str(self.sim_time) + "ms", amplitude=str(self.Edrive_weight) + "nA", period=str(self.Drive_period) + "ms") sgI = SineGenerator(id="sineGen_1", phase="0", delay="0ms", duration=str(self.sim_time) + "ms", amplitude=str(self.Idrive_weight) + "nA", period=str(self.Drive_period) + "ms") nml_doc.sine_generators.append(sgE) nml_doc.sine_generators.append(sgI) # Create an input object for each excitatory cell for i in range(0, XSCALE_ex): exp_input = ExplicitInput(target="%s[%i]" % (exc_pop.id, i), input=sgE.id) net.explicit_inputs.append(exp_input) # Create an input object for a percentage of inhibitory cells input_probability = 0.65 for i in range(0, XSCALE_inh): ran = random.random() if 0 < ran <= input_probability: inh_input = ExplicitInput(target="%s[%i]" % (inh_pop.id, i), input=sgI.id) net.explicit_inputs.append(inh_input) # Define Poisson noise input # Ex #nml_doc.includes.append(IncludeType('Synapses/bg_AMPA_syn.synapse.nml')) pfs1 = PoissonFiringSynapse(id="poissonFiringSyn1", average_rate=str(self.bg_noise_frequency) + "Hz", synapse=bg_exc_syn, spike_target="./%s" % bg_exc_syn) nml_doc.poisson_firing_synapses.append(pfs1) pfs_input_list1 = InputList(id="pfsInput1", component=pfs1.id, populations=exc_pop.id) net.input_lists.append(pfs_input_list1) for i in range(0, numCells_ex): pfs_input_list1.input.append( Input(id=i, target='../%s/%i/%s' % (exc_pop.id, i, exc_group_component), segment_id=bg_exc_syn_seg_id, destination="synapses")) ####### Write to file ###### print("Saving to file...") nml_file = '../ACnet2_NML2/' + self.filename + '_doc' + '.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: " + nml_file) ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) print "-----------------------------------" ###### Output ####### # Output membrane potential # Ex population Ex_potentials = 'V_Ex' ls.create_output_file(Ex_potentials, "../ACnet2_NML2/Results/v_exc.dat") for j in range(numCells_ex): quantity = "%s[%i]/v" % (exc_pop.id, j) v = 'v' + str(j) ls.add_column_to_output_file(Ex_potentials, v, quantity) # Inh population #Inh_potentials = 'V_Inh' #ls.create_output_file(Inh_potentials, "../ACnet2_NML2/Results/v_inh.dat") #for j in range(numCells_inh): # quantity = "%s[%i]/v"%(inh_pop.id, j) # v = 'v'+str(j) # ls.add_column_to_output_file(Inh_potentials,v, quantity) # include generated network ls.include_neuroml2_file(nml_file) # Save to LEMS XML file lems_file_name = ls.save_to_file(file_name='../ACnet2_NML2/LEMS_' + self.filename + '.xml')
def tune_izh_model(acq_list: List, metrics_from_data: Dict, currents: Dict) -> Dict: """Tune networks model against the data. Here we generate a network with the necessary number of Izhikevich cells, one for each current stimulus, and tune them against the experimental data. :param acq_list: list of indices of acquisitions/sweeps to tune against :type acq_list: list :param metrics_from_data: dictionary with the sweep number as index, and the dictionary containing metrics generated from the analysis :type metrics_from_data: dict :param currents: dictionary with sweep number as index and stimulus current value """ # length of simulation of the cells---should match the length of the # experiment sim_time = 1500.0 # Create a NeuroML template network simulation file that we will use for # the tuning template_doc = NeuroMLDocument(id="IzhTuneNet") # Add an Izhikevich cell with some parameters to the document template_doc.izhikevich2007_cells.append( Izhikevich2007Cell( id="Izh2007", C="100pF", v0="-60mV", k="0.7nS_per_mV", vr="-60mV", vt="-40mV", vpeak="35mV", a="0.03per_ms", b="-2nS", c="-50.0mV", d="100pA", )) template_doc.networks.append(Network(id="Network0")) # Add a cell for each acquisition list popsize = len(acq_list) template_doc.networks[0].populations.append( Population(id="Pop0", component="Izh2007", size=popsize)) # Add a current source for each cell, matching the currents that # were used in the experimental study. counter = 0 for acq in acq_list: template_doc.pulse_generators.append( PulseGenerator( id="Stim{}".format(counter), delay="80ms", duration="1000ms", amplitude="{}pA".format(currents[acq]), )) template_doc.networks[0].explicit_inputs.append( ExplicitInput(target="Pop0[{}]".format(counter), input="Stim{}".format(counter))) counter = counter + 1 # Print a summary print(template_doc.summary()) # Write to a neuroml file and validate it. reference = "TuneIzhFergusonPyr3" template_filename = "{}.net.nml".format(reference) write_neuroml2_file(template_doc, template_filename, validate=True) # Now for the tuning bits # format is type:id/variable:id/units # supported types: cell/channel/izhikevich2007cell # supported variables: # - channel: vShift # - cell: channelDensity, vShift_channelDensity, channelDensityNernst, # erev_id, erev_ion, specificCapacitance, resistivity # - izhikevich2007Cell: all available attributes # we want to tune these parameters within these ranges # param: (min, max) parameters = { "izhikevich2007Cell:Izh2007/C/pF": (100, 300), "izhikevich2007Cell:Izh2007/k/nS_per_mV": (0.01, 2), "izhikevich2007Cell:Izh2007/vr/mV": (-70, -50), "izhikevich2007Cell:Izh2007/vt/mV": (-60, 0), "izhikevich2007Cell:Izh2007/vpeak/mV": (35, 70), "izhikevich2007Cell:Izh2007/a/per_ms": (0.001, 0.4), "izhikevich2007Cell:Izh2007/b/nS": (-10, 10), "izhikevich2007Cell:Izh2007/c/mV": (-65, -10), "izhikevich2007Cell:Izh2007/d/pA": (50, 500), } # type: Dict[str, Tuple[float, float]] # Set up our target data and so on ctr = 0 target_data = {} weights = {} for acq in acq_list: # data to fit to: # format: path/to/variable:metric # metric from pyelectro, for example: # https://pyelectro.readthedocs.io/en/latest/pyelectro.html?highlight=mean_spike_frequency#pyelectro.analysis.mean_spike_frequency mean_spike_frequency = "Pop0[{}]/v:mean_spike_frequency".format(ctr) average_last_1percent = "Pop0[{}]/v:average_last_1percent".format(ctr) first_spike_time = "Pop0[{}]/v:first_spike_time".format(ctr) # each metric can have an associated weight weights[mean_spike_frequency] = 1 weights[average_last_1percent] = 1 weights[first_spike_time] = 1 # value of the target data from our data set target_data[mean_spike_frequency] = metrics_from_data[acq][ "{}:mean_spike_frequency".format(acq)] target_data[average_last_1percent] = metrics_from_data[acq][ "{}:average_last_1percent".format(acq)] target_data[first_spike_time] = metrics_from_data[acq][ "{}:first_spike_time".format(acq)] # only add these if the experimental data includes them # these are only generated for traces with spikes if "{}:average_maximum".format(acq) in metrics_from_data[acq]: average_maximum = "Pop0[{}]/v:average_maximum".format(ctr) weights[average_maximum] = 1 target_data[average_maximum] = metrics_from_data[acq][ "{}:average_maximum".format(acq)] if "{}:average_minimum".format(acq) in metrics_from_data[acq]: average_minimum = "Pop0[{}]/v:average_minimum".format(ctr) weights[average_minimum] = 1 target_data[average_minimum] = metrics_from_data[acq][ "{}:average_minimum".format(acq)] ctr = ctr + 1 # simulator to use simulator = "jNeuroML" return run_optimisation( # Prefix for new files prefix="TuneIzh", # Name of the NeuroML template file neuroml_file=template_filename, # Name of the network target="Network0", # Parameters to be fitted parameters=list(parameters.keys()), # Our max and min constraints min_constraints=[v[0] for v in parameters.values()], max_constraints=[v[1] for v in parameters.values()], # Weights we set for parameters weights=weights, # The experimental metrics to fit to target_data=target_data, # Simulation time sim_time=sim_time, # EC parameters population_size=100, max_evaluations=500, num_selected=30, num_offspring=50, mutation_rate=0.9, num_elites=3, # Seed value seed=12345, # Simulator simulator=simulator, dt=0.025, show_plot_already='-nogui' not in sys.argv, save_to_file="fitted_izhikevich_fitness.png", save_to_file_scatter="fitted_izhikevich_scatter.png", save_to_file_hist="fitted_izhikevich_hist.png", save_to_file_output="fitted_izhikevich_output.png", num_parallel_evaluations=4, )
def run_fitted_cell_simulation(sweeps_to_tune_against: List, tuning_report: Dict, simulation_id: str) -> None: """Run a simulation with the values obtained from the fitting :param tuning_report: tuning report from the optimser :type tuning_report: Dict :param simulation_id: text id of simulation :type simulation_id: str """ # get the fittest variables fittest_vars = tuning_report["fittest vars"] C = str(fittest_vars["izhikevich2007Cell:Izh2007/C/pF"]) + "pF" k = str( fittest_vars["izhikevich2007Cell:Izh2007/k/nS_per_mV"]) + "nS_per_mV" vr = str(fittest_vars["izhikevich2007Cell:Izh2007/vr/mV"]) + "mV" vt = str(fittest_vars["izhikevich2007Cell:Izh2007/vt/mV"]) + "mV" vpeak = str(fittest_vars["izhikevich2007Cell:Izh2007/vpeak/mV"]) + "mV" a = str(fittest_vars["izhikevich2007Cell:Izh2007/a/per_ms"]) + "per_ms" b = str(fittest_vars["izhikevich2007Cell:Izh2007/b/nS"]) + "nS" c = str(fittest_vars["izhikevich2007Cell:Izh2007/c/mV"]) + "mV" d = str(fittest_vars["izhikevich2007Cell:Izh2007/d/pA"]) + "pA" # Create a simulation using our obtained parameters. # Note that the tuner generates a graph with the fitted values already, but # we want to keep a copy of our fitted cell also, so we'll create a NeuroML # Document ourselves also. sim_time = 1500.0 simulation_doc = NeuroMLDocument(id="FittedNet") # Add an Izhikevich cell with some parameters to the document simulation_doc.izhikevich2007_cells.append( Izhikevich2007Cell( id="Izh2007", C=C, v0="-60mV", k=k, vr=vr, vt=vt, vpeak=vpeak, a=a, b=b, c=c, d=d, )) simulation_doc.networks.append(Network(id="Network0")) # Add a cell for each acquisition list popsize = len(sweeps_to_tune_against) simulation_doc.networks[0].populations.append( Population(id="Pop0", component="Izh2007", size=popsize)) # Add a current source for each cell, matching the currents that # were used in the experimental study. counter = 0 for acq in sweeps_to_tune_against: simulation_doc.pulse_generators.append( PulseGenerator( id="Stim{}".format(counter), delay="80ms", duration="1000ms", amplitude="{}pA".format(currents[acq]), )) simulation_doc.networks[0].explicit_inputs.append( ExplicitInput(target="Pop0[{}]".format(counter), input="Stim{}".format(counter))) counter = counter + 1 # Print a summary print(simulation_doc.summary()) # Write to a neuroml file and validate it. reference = "FittedIzhFergusonPyr3" simulation_filename = "{}.net.nml".format(reference) write_neuroml2_file(simulation_doc, simulation_filename, validate=True) simulation = LEMSSimulation( sim_id=simulation_id, duration=sim_time, dt=0.1, target="Network0", simulation_seed=54321, ) simulation.include_neuroml2_file(simulation_filename) simulation.create_output_file("output0", "{}.v.dat".format(simulation_id)) counter = 0 for acq in sweeps_to_tune_against: simulation.add_column_to_output_file("output0", "Pop0[{}]".format(counter), "Pop0[{}]/v".format(counter)) counter = counter + 1 simulation_file = simulation.save_to_file() # simulate run_lems_with_jneuroml(simulation_file, max_memory="2G", nogui=True, plot=False)