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 create_models(self): self.generic_cell = IafCell(id="generic_iaf_cell", C = self.get_bioparameter("iaf_C").value, thresh = self.get_bioparameter("iaf_thresh").value, reset = self.get_bioparameter("iaf_reset").value, leak_conductance = self.get_bioparameter("iaf_conductance").value, leak_reversal = self.get_bioparameter("iaf_leak_reversal").value) self.exc_syn = ExpTwoSynapse(id="exc_syn", gbase = self.get_bioparameter("chem_exc_syn_gbase").value, erev = self.get_bioparameter("chem_exc_syn_erev").value, tau_decay = self.get_bioparameter("chem_exc_syn_decay").value, tau_rise = self.get_bioparameter("chem_exc_syn_rise").value) self.inh_syn = ExpTwoSynapse(id="inh_syn", gbase = self.get_bioparameter("chem_inh_syn_gbase").value, erev = self.get_bioparameter("chem_inh_syn_erev").value, tau_decay = self.get_bioparameter("chem_inh_syn_decay").value, tau_rise = self.get_bioparameter("chem_inh_syn_rise").value) self.elec_syn = ExpTwoSynapse(id="elec_syn", gbase = self.get_bioparameter("elec_syn_gbase").value, erev = self.get_bioparameter("elec_syn_erev").value, tau_decay = self.get_bioparameter("elec_syn_decay").value, tau_rise = self.get_bioparameter("elec_syn_rise").value) self.offset_current = PulseGenerator(id="offset_current", delay= self.get_bioparameter("unphysiological_offset_current_del").value, duration= self.get_bioparameter("unphysiological_offset_current_dur").value, amplitude= self.get_bioparameter("unphysiological_offset_current").value)
def create_offset(self): self.offset_current = PulseGenerator( id="offset_current", delay=self.get_bioparameter( "unphysiological_offset_current_del").value, duration=self.get_bioparameter( "unphysiological_offset_current_dur").value, amplitude=self.get_bioparameter( "unphysiological_offset_current").value)
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 create_offsetcurrent_concentrationmodel(self): self.offset_current = PulseGenerator(id="offset_current", delay=self.get_bioparameter("unphysiological_offset_current_del").value, duration=self.get_bioparameter("unphysiological_offset_current_dur").value, amplitude=self.get_bioparameter("unphysiological_offset_current").value) self.concentration_model = FixedFactorConcentrationModel(id="CaPool", ion="ca", resting_conc="0 mM", decay_constant=self.get_bioparameter("ca_conc_decay_time").value, rho=self.get_bioparameter("ca_conc_rho").value)
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 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) target = get_cell_id_string(cell, params) input_list = InputList(id="Input_%s_%s"%(cell,stim.id), component=stim.id, populations='%s'%cell) input_list.input.append(Input(id=0, target=target, destination="synapses")) nml_doc.networks[0].input_lists.append(input_list)
def add_new_input(nml_doc, cell, delay, duration, amplitude, params): i = 1 for stim in nml_doc.pulse_generators: if stim.id.startswith("%s_%s" % ("stim", cell)): i += 1 id = "%s_%s_%s" % ("stim", cell, i) stim = PulseGenerator(id=id, delay=delay, duration=duration, amplitude=amplitude) nml_doc.pulse_generators.append(stim) target = get_cell_id_string(cell, params, muscle=is_muscle(cell)) input_list = InputList(id="Input_%s_%s"%(cell,stim.id), component=stim.id, populations='%s'%cell) input_list.input.append(Input(id=0, target=target, destination="synapses")) nml_doc.networks[0].input_lists.append(input_list)
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 = False # isinstance(params.elec_syn, GapJunction) target ="../%s/0/%s"%(cell, params.generic_cell.id) if populations_without_location: target ="%s[0]"%(cell) input_list = InputList(id="Input_%s_%s"%(cell,stim.id), component=stim.id, populations='%s'%cell) input_list.input.append(Input(id=0, target=target, destination="synapses")) nml_doc.networks[0].input_lists.append(input_list)
def create_models(self): self.generic_cell = IafActivityCell( id="generic_iaf_cell", C=self.get_bioparameter("iaf_C").value, thresh=self.get_bioparameter("iaf_thresh").value, reset=self.get_bioparameter("iaf_reset").value, leak_conductance=self.get_bioparameter("iaf_conductance").value, leak_reversal=self.get_bioparameter("iaf_leak_reversal").value, tau1=self.get_bioparameter("iaf_tau1").value) self.exc_syn = GradedSynapse( id="exc_syn", conductance=self.get_bioparameter("exc_syn_conductance").value, delta=self.get_bioparameter("exc_syn_delta").value, Vth=self.get_bioparameter("exc_syn_vth").value, erev=self.get_bioparameter("exc_syn_erev").value, k=self.get_bioparameter("exc_syn_k").value) self.inh_syn = GradedSynapse( id="inh_syn", conductance=self.get_bioparameter("inh_syn_conductance").value, delta=self.get_bioparameter("inh_syn_delta").value, Vth=self.get_bioparameter("inh_syn_vth").value, erev=self.get_bioparameter("inh_syn_erev").value, k=self.get_bioparameter("inh_syn_k").value) self.elec_syn = GapJunction( id="elec_syn", conductance=self.get_bioparameter("elec_syn_gbase").value) self.offset_current = PulseGenerator( id="offset_current", delay=self.get_bioparameter( "unphysiological_offset_current_del").value, duration=self.get_bioparameter( "unphysiological_offset_current_dur").value, amplitude=self.get_bioparameter( "unphysiological_offset_current").value)
id="izh2007RS0", v0="-60mV", C="100pF", k="0.7nS_per_mV", vr="-60mV", vt="-40mV", vpeak="35mV", a="0.03per_ms", b="-2nS", c="-50.0mV", d="100pA") nml_doc.izhikevich2007_cells.append(izh0) # Create a network and add it to the model net = Network(id="IzhNet") nml_doc.networks.append(net) # Create a population of defined cells and add it to the model size0 = 1 pop0 = Population(id="IzhPop0", component=izh0.id, size=size0) net.populations.append(pop0) # Define an external stimulus and add it to the model pg = PulseGenerator( id="pulseGen_%i" % 0, delay="0ms", duration="1000ms", amplitude="0.07 nA" ) nml_doc.pulse_generators.append(pg) exp_input = ExplicitInput(target="%s[%i]" % (pop0.id, 0), input=pg.id) net.explicit_inputs.append(exp_input) # Write the NeuroML model to a file nml_file = 'izhikevich2007_single_cell_network.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: " + nml_file) # Validate the NeuroML model against the NeuroML schema validate_neuroml2(nml_file) ################################################################################ ## The NeuroML file has now been created and validated. The rest of the code
def create_models(self): self.generic_cell = Cell(id = "GenericCell") morphology = Morphology() morphology.id = "morphology_"+self.generic_cell.id self.generic_cell.morphology = morphology prox_point = Point3DWithDiam(x="0", y="0", z="0", diameter=self.get_bioparameter("cell_diameter").value) dist_point = Point3DWithDiam(x="0", y="0", z=self.get_bioparameter("cell_length").value, diameter=self.get_bioparameter("cell_diameter").value) segment = Segment(id="0", name="soma", proximal = prox_point, distal = dist_point) morphology.segments.append(segment) self.generic_cell.biophysical_properties = BiophysicalProperties(id="biophys_"+self.generic_cell.id) mp = MembraneProperties() self.generic_cell.biophysical_properties.membrane_properties = mp mp.init_memb_potentials.append(InitMembPotential(value=self.get_bioparameter("initial_memb_pot").value)) mp.specific_capacitances.append(SpecificCapacitance(value=self.get_bioparameter("specific_capacitance").value)) mp.spike_threshes.append(SpikeThresh(value=self.get_bioparameter("spike_thresh").value)) mp.channel_densities.append(ChannelDensity(cond_density=self.get_bioparameter("leak_cond_density").value, id="Leak_all", ion_channel="Leak", erev=self.get_bioparameter("leak_erev").value, ion="non_specific")) mp.channel_densities.append(ChannelDensity(cond_density=self.get_bioparameter("k_slow_cond_density").value, id="k_slow_all", ion_channel="k_slow", erev=self.get_bioparameter("k_slow_erev").value, ion="k")) mp.channel_densities.append(ChannelDensity(cond_density=self.get_bioparameter("k_fast_cond_density").value, id="k_fast_all", ion_channel="k_fast", erev=self.get_bioparameter("k_fast_erev").value, ion="k")) mp.channel_densities.append(ChannelDensity(cond_density=self.get_bioparameter("ca_boyle_cond_density").value, id="ca_boyle_all", ion_channel="ca_boyle", erev=self.get_bioparameter("ca_boyle_erev").value, ion="ca")) ip = IntracellularProperties() self.generic_cell.biophysical_properties.intracellular_properties = ip # NOTE: resistivity/axial resistance not used for single compartment cell models, so value irrelevant! ip.resistivities.append(Resistivity(value="0.1 kohm_cm")) # NOTE: Ca reversal potential not calculated by Nernst, so initial_ext_concentration value irrelevant! species = Species(id="ca", ion="ca", concentration_model="CaPool", initial_concentration="0 mM", initial_ext_concentration="2E-6 mol_per_cm3") ip.species.append(species) self.exc_syn = GradedSynapse(id="exc_syn", conductance = self.get_bioparameter("exc_syn_conductance").value, delta = self.get_bioparameter("exc_syn_delta").value, Vth = self.get_bioparameter("exc_syn_vth").value, erev = self.get_bioparameter("exc_syn_erev").value, k = self.get_bioparameter("exc_syn_k").value) self.inh_syn = GradedSynapse(id="inh_syn", conductance = self.get_bioparameter("inh_syn_conductance").value, delta = self.get_bioparameter("inh_syn_delta").value, Vth = self.get_bioparameter("inh_syn_vth").value, erev = self.get_bioparameter("inh_syn_erev").value, k = self.get_bioparameter("inh_syn_k").value) self.elec_syn = GapJunction(id="elec_syn", conductance = self.get_bioparameter("elec_syn_gbase").value) self.offset_current = PulseGenerator(id="offset_current", delay=self.get_bioparameter("unphysiological_offset_current_del").value, duration=self.get_bioparameter("unphysiological_offset_current_dur").value, amplitude=self.get_bioparameter("unphysiological_offset_current").value)
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) 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)
def generate_example_network(network_id, numCells_exc, numCells_inh, x_size = 1000, y_size = 100, z_size = 1000, exc_group_component = "SimpleIaF", inh_group_component = "SimpleIaF_inh", validate = True, random_seed = 1234, generate_lems_simulation = False, connections = True, connection_probability_exc_exc = 0.4, connection_probability_inh_exc = 0.4, connection_probability_exc_inh = 0.4, connection_probability_inh_inh = 0.4, inputs = False, input_firing_rate = 50, # Hz input_offset_min = 0, # nA input_offset_max = 0, # nA num_inputs_per_exc = 4, duration = 500, # ms dt = 0.05, temperature="32.0 degC"): seed(random_seed) nml_doc = NeuroMLDocument(id=network_id) net = Network(id = network_id, type = "networkWithTemperature", temperature = temperature) net.notes = "Network generated using libNeuroML v%s"%__version__ nml_doc.networks.append(net) for cell_comp in set([exc_group_component, inh_group_component]): # removes duplicates nml_doc.includes.append(IncludeType(href='%s.cell.nml'%cell_comp)) # The names of the Exc & Inh groups/populations exc_group = "Exc" inh_group = "Inh" # The names of the network connections net_conn_exc_inh = "NetConn_Exc_Inh" net_conn_inh_exc = "NetConn_Inh_Exc" net_conn_exc_exc = "NetConn_Exc_Exc" net_conn_inh_inh = "NetConn_Inh_Inh" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct) exc_inh_syn = "AMPAR" inh_exc_syn = "GABAA" exc_exc_syn = "AMPAR" inh_inh_syn = "GABAA" for syn in [exc_inh_syn, inh_exc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) # Generate excitatory cells exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=numCells_exc) net.populations.append(exc_pop) for i in range(0, numCells_exc) : index = i inst = Instance(id=index) exc_pop.instances.append(inst) inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random())) # Generate inhibitory cells inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=numCells_inh) net.populations.append(inh_pop) for i in range(0, numCells_inh) : index = i inst = Instance(id=index) inh_pop.instances.append(inst) inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random())) if connections: 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) count_exc_inh = 0 count_inh_exc = 0 count_exc_exc = 0 count_inh_inh = 0 for i in range(0, numCells_exc): for j in range(0, numCells_inh): if i != j: if random()<connection_probability_exc_inh: add_connection(proj_exc_inh, count_exc_inh, exc_group, exc_group_component, i, 0, inh_group, inh_group_component, j, 0) count_exc_inh+=1 if random()<connection_probability_inh_exc: add_connection(proj_inh_exc, count_inh_exc, inh_group, inh_group_component, j, 0, exc_group, exc_group_component, i, 0) count_inh_exc+=1 for i in range(0, numCells_exc): for j in range(0, numCells_exc): if i != j: if random()<connection_probability_exc_exc: add_connection(proj_exc_exc, count_exc_exc, exc_group, exc_group_component, i, 0, exc_group, exc_group_component, j, 0) count_exc_exc+=1 for i in range(0, numCells_inh): for j in range(0, numCells_inh): if i != j: if random()<connection_probability_inh_inh: add_connection(proj_inh_inh, count_inh_inh, inh_group, inh_group_component, j, 0, inh_group, inh_group_component, i, 0) count_inh_inh+=1 if inputs: if input_firing_rate>0: mf_input_syn = "AMPAR" if mf_input_syn!=exc_inh_syn and mf_input_syn!=inh_exc_syn: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input_%sHz"%input_firing_rate pfs = PoissonFiringSynapse(id=rand_spiker_id, average_rate="%s per_s"%input_firing_rate, synapse=mf_input_syn, spike_target="./%s"%mf_input_syn) nml_doc.poisson_firing_synapses.append(pfs) input_list = InputList(id="Input_0", component=rand_spiker_id, populations=exc_group) count = 0 for i in range(0, numCells_exc): for j in range(num_inputs_per_exc): input = Input(id=count, target="../%s/%i/%s"%(exc_group, i, exc_group_component), destination="synapses") input_list.input.append(input) count += 1 net.input_lists.append(input_list) if input_offset_max != 0 or input_offset_min != 0: for i in range(0, numCells_exc): pg = PulseGenerator(id="PulseGenerator_%i"%i, delay="0ms", duration="%sms"%duration, amplitude="%fnA"%(input_offset_min+(input_offset_max-input_offset_min)*random())) nml_doc.pulse_generators.append(pg) input_list = InputList(id="Input_Pulse_List_%i"%i, component=pg.id, populations=exc_group) input = Input(id=0, target="../%s/%i/%s"%(exc_group, i, exc_group_component), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) ####### Write to file ###### print("Saving to file...") nml_file = network_id+'.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_lems_simulation: # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation("Sim_%s"%network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Include generated/existing NeuroML2 files ls.include_neuroml2_file('%s.cell.nml'%exc_group_component) ls.include_neuroml2_file('%s.cell.nml'%inh_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files disp_exc = "display_exc" ls.create_display(disp_exc, "Voltages Exc cells", "-80", "50") of_exc = 'Volts_file_exc' ls.create_output_file(of_exc, "v_exc.dat") disp_inh = "display_inh" ls.create_display(disp_inh, "Voltages Inh cells", "-80", "50") of_inh = 'Volts_file_inh' ls.create_output_file(of_inh, "v_inh.dat") for i in range(numCells_exc): quantity = "%s/%i/%s/v"%(exc_group, i, exc_group_component) ls.add_line_to_display(disp_exc, "Exc %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_exc, "v_%i"%i, quantity) for i in range(numCells_inh): quantity = "%s/%i/%s/v"%(inh_group, i, inh_group_component) ls.add_line_to_display(disp_inh, "Inh %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_inh, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() print "-----------------------------------"
def generatePulse(population, idx, amplitude): pulse = PulseGenerator(id='baseline_%s%d' % (population, idx), delay='0ms', duration='200ms', amplitude='%.02f pA' % amplitude) nml_doc.pulse_generators.append(pulse)
unphysiological_offset_current = BioParameter("unphysiological_offset_current", "0.21nA", "KnownError", "0") unphysiological_offset_current_dur = BioParameter("unphysiological_offset_current_dur", "200ms", "KnownError", "0") generic_cell = IafCell(id="generic_iaf_cell", C = iaf_C.value, thresh = iaf_thresh.value, reset = iaf_reset.value, leak_conductance = iaf_conductance.value, leak_reversal = iaf_leak_reversal.value) exc_syn = ExpTwoSynapse(id="exc_syn", gbase = chem_exc_syn_gbase.value, erev = chem_exc_syn_erev.value, tau_decay = chem_exc_syn_decay.value, tau_rise = chem_exc_syn_rise.value) inh_syn = ExpTwoSynapse(id="inh_syn", gbase = chem_inh_syn_gbase.value, erev = chem_inh_syn_erev.value, tau_decay = chem_inh_syn_decay.value, tau_rise = chem_inh_syn_rise.value) offset_current = PulseGenerator(id="offset_current", delay="0ms", duration=unphysiological_offset_current_dur.value, amplitude=unphysiological_offset_current.value)
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)
def add_new_input(nml_doc, cell, delay, duration, amplitude, params): id = get_next_stim_id(nml_doc, cell) input = PulseGenerator(id=id, delay=delay, duration=duration, amplitude=amplitude) nml_doc.pulse_generators.append(input) append_input_to_nml_input_list(input, nml_doc, cell, params)
def generatePopulationLEMS(pops, n_pops, amplitudes, baseline, sim_length, delay): def generatePopulationProjection(from_pop, to_pop, n_from_pop, n_to_pop, w_to_from_pop, p_to_from_pop, net): connection_count = 0 projection = ContinuousProjection( id='%s_%s' % (from_pop, to_pop), presynaptic_population='%sPop' % from_pop, postsynaptic_population='%sPop' % to_pop) for idx_from_pop in range(n_from_pop): for idx_to_pop in range(n_to_pop): if random.random() <= p_to_from_pop: pre_comp = from_pop.upper() to_comp = to_pop.upper() connection = ContinuousConnectionInstanceW( id=connection_count, pre_cell='../%sPop/%i/%s' % (from_pop, idx_from_pop, pre_comp), post_cell='../%sPop/%i/%s' % (to_pop, idx_to_pop, to_comp), pre_component='silent1', post_component='rs', weight=w_to_from_pop / (p_to_from_pop * n_from_pop)) projection.continuous_connection_instance_ws.append( connection) connection_count += 1 if connection_count > 0: net.continuous_projections.append(projection) # Connection probabilities for each pop in the population w_to_from_pops = np.array([[2.42, -.33, -0.80, 0], [2.97, -3.45, -2.13, 0], [4.64, 0, 0, -2.79], [0.71, 0, -0.16, 0]]) # p_to_from_pop = np.array([[1, 1, 1, 0], # [1, 1, 1, 0], # [1, 0, 0, 1], # [1, 0, 1, 0]]) p_to_from_pop = np.array([[0.02, 1, 1, 0], [0.01, 1, 0.85, 0], [0.01, 0, 0, 0.55], [0.01, 0, 0.5, 0]]) nml_doc = NeuroMLDocument(id='RandomPopulation') # Add silent synapsis silent_syn = SilentSynapse(id='silent1') nml_doc.silent_synapses.append(silent_syn) for pop_idx, pop in enumerate(pops): pulse = PulseGenerator(id='baseline_%s' % pop, delay='0ms', duration=str(sim_length) + 'ms', amplitude=amplitudes[pop_idx]) nml_doc.pulse_generators.append(pulse) if pop == 'vip': # time point when additional current is induced pulse_mod = PulseGenerator(id='modVIP', delay=str(delay) + 'ms', duration=str(sim_length - delay) + 'ms', amplitude='10 pA') nml_doc.pulse_generators.append(pulse_mod) # Create the network and add the 4 different populations net = Network(id='net2') nml_doc.networks.append(net) colours = ['0 0 1', '1 0 0', '.5 0 .5', '0 1 0'] centres = [(0, 0, 0), (-1200, 0, 0), (-800, 800, 0), (0, 1200, 0)] radii = [800, 200, 200, 200] # Populate the network with the 4 populations for pop_idx, pop in enumerate(pops): pop = Population(id='%sPop' % pop, component=(pops[pop_idx]).upper(), size=n_pops[pop_idx], type='populationList') net.populations.append(pop) pop.properties.append(Property(tag='color', value=colours[pop_idx])) pop.properties.append(Property(tag='radius', value=10)) for n_pop in range(n_pops[pop_idx]): inst = Instance(id=n_pop) pop.instances.append(inst) x, y, z = centres[pop_idx] r = (random.random() * radii[pop_idx]**3)**(1. / 3) theta = random.random() * math.pi phi = random.random() * math.pi * 2 inst.location = Location( x=str(x + r * math.sin(theta) * math.cos(phi)), y=str(y + r * math.sin(theta) * math.sin(phi)), z=str(z + r * math.cos(theta))) 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], p_to_from_pop[to_idx, from_idx], net) # Add inputs for pop_idx, pop in enumerate(pops): input_list = InputList(id='baseline_%s' % pop, component='baseline_%s' % pops[pop_idx], populations='%sPop' % pop) net.input_lists.append(input_list) if pop == 'vip': input_list_mod = InputList(id='modulation_%s' % pop, component='modVIP', populations='%sPop' % pop) net.input_lists.append(input_list_mod) for n_idx in range(n_pops[pop_idx]): input = Input(id=n_idx, target='../%sPop/%i/%s' % (pop, n_idx, pop.upper()), destination='synapses') input_list.input.append(input) # if vip add modulatory input if pop == 'vip': mod_input = Input(id=n_idx, target='../vipPop/%i/VIP' % n_idx, destination='synapses') input_list_mod.input.append(mod_input) nml_file = 'RandomPopulationRate_%s_baseline.nml' % baseline writers.NeuroMLWriter.write(nml_doc, nml_file) print('Written network file to: %s' % nml_file) # Validate the NeuroML from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file)
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, )