def main(nml, nrn_file): try: input_file = sys.argv[1] except: input_file = 'Saraga2003.yaml' with open(input_file) as inpf: conf = yaml.load(inpf) conf = preprocess(conf) if nml: with open(".sccct_generated.cell.nml", "w") as outf: outf.write(pystache.Renderer().render_path('nml.cell.mustache', conf)) with open(".sccct_generated.net.nml", "w") as outf: outf.write(pystache.Renderer().render_path('nml.net.mustache', conf)) from neuroml.utils import validate_neuroml2 validate_neuroml2(".sccct_generated.cell.nml") validate_neuroml2(".sccct_generated.net.nml") lems_file = "LEMS_sccct_generated.xml" with open(lems_file, "w") as outf: outf.write(pystache.Renderer().render_path('lems.xml.mustache', conf)) convert_channels_to_mod(lems_file) with open(nrn_file, "w") as outf: outf.write(pystache.Renderer().render_path('nrn.mustache', conf)) compile_channel_files()
def _get_morphology_dict(self, file_obj): """ Helper function to read .nml file and return document object. Parameters ---------- file_obj: str File path or file object. Returns ------- dict A dictionary containing all the information extracted from the given .nml file. """ if isinstance(file_obj, str): # Generate absolute path if not provided already file_obj = abspath(file_obj) # Validating NeuroML file validate_neuroml2(deepcopy(file_obj)) logger.info("Validated provided .nml file") # Load nml file doc = loaders.NeuroMLLoader.load(file_obj) logger.info("Loaded morphology") return doc
def write_to_file(nml_doc, lems_info, reference, template_path='', validate=True, verbose=True, target_directory='.'): ####### Write to file ###### nml_file = target_directory+'/'+reference+'.nml' print_("Writing generated network to: %s"%os.path.realpath(nml_file)) writers.NeuroMLWriter.write(nml_doc, nml_file) if verbose: print_("Written network file to: "+nml_file) lems_file_name = target_directory+'/'+'LEMS_%s.xml'%reference with open(lems_file_name, 'w') as lems: # if running unittest concat template_path merged = merge_with_template(lems_info, template_path+LEMS_TEMPLATE_FILE) lems.write(merged) if verbose: print_("Written LEMS file to: "+lems_file_name) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 try: validate_neuroml2(nml_file) except URLError: print_("Problem validating against remote Schema!")
def write_to_file(nml_doc, lems_info, reference, validate=True): ####### Write to file ###### nml_file = reference+'.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) lems_file_name = 'LEMS_%s.xml'%reference lems = open(lems_file_name, 'w') merged = merge_with_template(lems_info, LEMS_TEMPLATE_FILE) lems.write(merged) print("Written LEMS file to: "+lems_file_name) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 try: validate_neuroml2(nml_file) except URLError as e: print("Problem validating against remote Schema!")
def network_to_neuroml(network, output_file_name, **kwargs): # Unpack neuroml extras from kwargs: doc_id = kwargs.get('doc_id', 'default_dipde_network') # Create neuroml doc: nml_doc = nml.NeuroMLDocument(id=doc_id) print nml_doc validate_neuroml2(nml_doc) # Append types: # nml_doc.iaf_cells.append(nml.IafCell0) population_type_list = {} for p in network.population_list: curr_population_name = p.__class__.__name__ if curr_population_name == 'InternalPopulation': output = neuroml_internal_population_parameter_dict_adapter(p) elif curr_population_name == 'ExternalPopulation': pass # print neuroml_external_population_parameter_dict_adapter(p) else: raise Exception( 'Population Type (%s) not recognize when converting to NeuroML' % curr_population_name)
def SingleCellSim(cell_ref,nc_simConfig,sim_duration): net_doc = pynml.read_neuroml2_file("%s.nml"%nc_simConfig) net_doc.id=nc_simConfig net=net_doc.networks[0] net.id=nc_simConfig net_doc.includes.append(IncludeType("../generatedNeuroML2/%s.cell.nml"%cell_ref)) net_file = '%s.net.nml'%(net_doc.id) writers.NeuroMLWriter.write(net_doc, net_file) print("Written network with 1 cell in network to: %s"%(net_file)) from neuroml.utils import validate_neuroml2 validate_neuroml2(net_file) generate_lems_file_for_neuroml("Sim_"+net_doc.id, net_file, net_doc.id, sim_duration, 0.025, "LEMS_%s.xml"%net_doc.id, ".", gen_plots_for_all_v = True, plot_all_segments = False, gen_saves_for_all_v = True, save_all_segments = False, copy_neuroml = False, seed = 1234)
def write_izhikevich(filename="./tmp/SingleIzhikevich_test.nml"): nml_doc = NeuroMLDocument(id="SingleIzhikevich") nml_filename = filename iz0 = IzhikevichCell(id="iz0", v0="-70mV", thresh="30mV", a="0.02", b="0.2", c="-65.0", d="6") nml_doc.izhikevich_cells.append(iz0) NeuroMLWriter.write(nml_doc, nml_filename) validate_neuroml2(nml_filename)
def load_izhikevich(filename="./test_files/SingleIzhikevich.nml"): nml_filename = filename validate_neuroml2(nml_filename) nml_doc = NeuroMLLoader.load(nml_filename) iz_cells = nml_doc.izhikevich_cells for i, iz in enumerate(iz_cells): if isinstance(iz, IzhikevichCell): neuron_string = "%d %s %s %s %s %s (%s)" % (i, iz.v0, iz.a, iz.b, iz.c, iz.d, iz.id) print(neuron_string) else: print("Error: Cell %d is not an IzhikevichCell" % i)
def load_izhikevich(filename="./test_files/SingleIzhikevich.nml"): nml_filename = filename validate_neuroml2(nml_filename) nml_doc = NeuroMLLoader.load(nml_filename) iz_cells = nml_doc.izhikevich_cells for i, iz in enumerate(iz_cells): if isinstance(iz, IzhikevichCell): neuron_string = "%d %s %s %s %s %s (%s)" % (i, iz.v0, iz.a, iz.b, iz.c, iz.d, iz.id) print neuron_string else: print "Error: Cell %d is not an IzhikevichCell" % i
def test_save_validate_network(): if not have_neuroml: raise SkipTest sim = pyNN.neuroml reference='Test0' sim.setup(reference=reference) spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=numpy.arange(10, 100, 10))) neurons = sim.Population(5, sim.IF_cond_exp(e_rev_I=-75)) sim.end() from neuroml.utils import validate_neuroml2 validate_neuroml2('%s.net.nml'%reference)
def test_save_validate_network(): if not have_neuroml: raise SkipTest sim = pyNN.neuroml reference = 'Test0' sim.setup(reference=reference) spike_source = sim.Population( 1, sim.SpikeSourceArray(spike_times=np.arange(10, 100, 10))) neurons = sim.Population(5, sim.IF_cond_exp(e_rev_I=-75)) sim.end() from neuroml.utils import validate_neuroml2 validate_neuroml2('%s.net.nml' % reference)
def generateLEMS(population, n_units, max_amplitude, min_amplitude): 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) def generatePopulation(population, n_units, net): population_uc = population.upper() pop = Population(id='%sPop' % population, component='%s' % population_uc, size=n_units) net.populations.append(pop) 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) nml_doc = NeuroMLDocument(id='fI_%s' % population) # Add silent synapsis silent_syn = SilentSynapse(id='silent1_%s' % population) nml_doc.silent_synapses.append(silent_syn) step = (max_amplitude - min_amplitude) / n_units amplitudes = np.arange(min_amplitude, max_amplitude, step) net = Network(id='net_%s' % population) nml_doc.networks.append(net) generatePopulation('%s' % population, n_units, net) for idx, amplitude in enumerate(amplitudes): generatePulse('%s' % population, idx, amplitude) generateExmplicitInput('%s' % population, idx, net) # Write to file nml_file = 'fI_%s.nml' % population 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 test_morphology_validates(self): """ Check that we can generate a cell's file and have it validate """ # Load in raw morphology for ADAL self.config['rdf.graph'].parse("tests/test_data/PVDR.nml.rdf.xml",format='trig') n = Neuron(name='PVDR', conf=self.config) doc = PyOpenWorm.NeuroML.generate(n,1) writers.NeuroMLWriter.write(doc, "temp.nml") from neuroml.utils import validate_neuroml2 f = sys.stdout try: sys.stdout = open(os.devnull, 'w') except: sys.stdout = f try: validate_neuroml2("temp.nml") except Exception, e: print e self.fail("Should validate")
def test_morphology_validates(self): """ Check that we can generate a cell's file and have it validate """ # Load in raw morphology for ADAL self.config['rdf.graph'].parse("tests/test_data/PVDR.nml.rdf.xml", format='trig') n = Neuron(name='PVDR', conf=self.config) doc = PyOpenWorm.NeuroML.generate(n, 1) writers.NeuroMLWriter.write(doc, "temp.nml") from neuroml.utils import validate_neuroml2 f = sys.stdout try: sys.stdout = open(os.devnull, 'w') except: sys.stdout = f try: validate_neuroml2("temp.nml") except Exception, e: print e self.fail("Should validate")
def run(): cell_num = 2 nml_doc = NeuroMLDocument(id="demo_attraction") net = Network(id="demo_attraction") nml_doc.networks.append(net) for cell_id in range(0,cell_num): cell = Cell(id="Cell_%i"%cell_id) cell.morphology = generate_with_morphology(db_name,cfg_file) nml_doc.cells.append(cell) pop = Population(id="Pop_%i"%cell_id, component=cell.id, type="populationList") net.populations.append(pop) inst = Instance(id="0") pop.instances.append(inst) inst.location = Location(x=0, y=0, z=0) ####### Write to file ###### nml_file = 'demo_attraction/demo_attraction.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)
def SingleCellSim(simConfig,dt,targetPath): src_files = os.listdir(targetPath) for file_name in src_files: if file_name=="Thalamocortical.net.nml": full_target_path=os.path.join(targetPath,file_name) net_doc = pynml.read_neuroml2_file(full_target_path) net_doc.id=simConfig net=net_doc.networks[0] net.id=simConfig net_file = '%s.net.nml'%(net_doc.id) writers.NeuroMLWriter.write(net_doc, full_target_path) print("Written network with 1 cell in network to: %s"%(full_target_path)) if file_name=="LEMS_Thalamocortical.xml": full_lems_path=os.path.join(targetPath,file_name) sim_duration=get_sim_duration(full_lems_path) validate_neuroml2(full_target_path) generate_lems_file_for_neuroml("Sim_"+net_doc.id, full_target_path, net_doc.id, sim_duration, dt, "LEMS_%s.xml"%net_doc.id, targetPath, gen_plots_for_all_v = True, plot_all_segments = False, gen_saves_for_all_v = True, save_all_segments = False, copy_neuroml = False, seed = 1234)
def SingleCellSim(simConfig, dt, targetPath): src_files = os.listdir(targetPath) for file_name in src_files: if file_name == "Thalamocortical.net.nml": full_target_path = os.path.join(targetPath, file_name) net_doc = pynml.read_neuroml2_file(full_target_path) net_doc.id = simConfig net = net_doc.networks[0] net.id = simConfig net_file = '%s.net.nml' % (net_doc.id) writers.NeuroMLWriter.write(net_doc, full_target_path) print("Written network with 1 cell in network to: %s" % (full_target_path)) if file_name == "LEMS_Thalamocortical.xml": full_lems_path = os.path.join(targetPath, file_name) sim_duration = get_sim_duration(full_lems_path) validate_neuroml2(full_target_path) generate_lems_file_for_neuroml("Sim_" + net_doc.id, full_target_path, net_doc.id, sim_duration, dt, "LEMS_%s.xml" % net_doc.id, targetPath, gen_plots_for_all_v=True, plot_all_segments=False, gen_saves_for_all_v=True, save_all_segments=False, copy_neuroml=False, seed=1234)
def main(nml, nrn_file): try: input_file = sys.argv[1] except: input_file = 'Saraga2003.yaml' with open(input_file) as inpf: conf = yaml.load(inpf) conf = preprocess(conf) if nml: with open(".sccct_generated.cell.nml", "w") as outf: outf.write(pystache.Renderer().render_path( 'nml.cell.mustache', conf)) with open(".sccct_generated.net.nml", "w") as outf: outf.write(pystache.Renderer().render_path( 'nml.net.mustache', conf)) from neuroml.utils import validate_neuroml2 validate_neuroml2(".sccct_generated.cell.nml") validate_neuroml2(".sccct_generated.net.nml") lems_file = "LEMS_sccct_generated.xml" with open(lems_file, "w") as outf: outf.write(pystache.Renderer().render_path( 'lems.xml.mustache', conf)) convert_channels_to_mod(lems_file) with open(nrn_file, "w") as outf: outf.write(pystache.Renderer().render_path('nrn.mustache', conf)) compile_channel_files()
def write_to_file(nml_doc, lems_info, reference, template_path='', validate=True, verbose=True, target_directory='.'): ####### Write to file ###### nml_file = target_directory+'/'+reference+'.nml' print_("Writing generated network to: %s"%os.path.realpath(nml_file)) writers.NeuroMLWriter.write(nml_doc, nml_file) if verbose: print_("Written network file to: "+nml_file) lems_file_name = target_directory+'/'+'LEMS_%s.xml'%reference lems = open(lems_file_name, 'w') # if running unittest concat template_path merged = merge_with_template(lems_info, template_path+LEMS_TEMPLATE_FILE) lems.write(merged) if verbose: print_("Written LEMS file to: "+lems_file_name) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 try: validate_neuroml2(nml_file) except URLError: print_("Problem validating against remote Schema!")
def network_to_neuroml(network, output_file_name, **kwargs): # Unpack neuroml extras from kwargs: doc_id = kwargs.get('doc_id', 'default_dipde_network') # Create neuroml doc: nml_doc = nml.NeuroMLDocument(id=doc_id) print nml_doc validate_neuroml2(nml_doc) # Append types: # nml_doc.iaf_cells.append(nml.IafCell0) population_type_list = {} for p in network.population_list: curr_population_name = p.__class__.__name__ if curr_population_name == 'InternalPopulation': output = neuroml_internal_population_parameter_dict_adapter(p) elif curr_population_name == 'ExternalPopulation': pass # print neuroml_external_population_parameter_dict_adapter(p) else: raise Exception('Population Type (%s) not recognize when converting to NeuroML' % curr_population_name)
Z = zs[0] + random.random() * (zs[1] - zs[0]) Y = ys[layer][0] + random.random() * (ys[layer][1] - ys[layer][0]) inst.location = Location(x=X, y=Y, z=Z) count += 1 net_file = '%s.net.nml' % (net_ref) writers.NeuroMLWriter.write(net_doc, net_file) print("Written network with %i cells in network to: %s" % (count, net_file)) from neuroml.utils import validate_neuroml2 validate_neuroml2(net_file) generate_lems_file_for_neuroml("Sim_" + net_ref, net_file, net_ref, 50, 0.025, "LEMS_%s.xml" % net_ref, ".", gen_plots_for_all_v=True, plot_all_segments=True, gen_saves_for_all_v=True, save_all_segments=True, copy_neuroml=False, seed=1234)
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 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 "-----------------------------------"
import HHTut # import parameters file from netpyne import sim # import netpyne sim module np = HHTut.netParams print( "********************\n*\n* Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************" ) np.stimSourceParams['bkg']['noise'] = 1 HHTut.simConfig.verbose = True sim.createExportNeuroML2( netParams=np, simConfig=HHTut.simConfig, reference='HHTut') # create and export network to NeuroML 2 ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2('HHTut.net.nml') ###### Export also to Python ###### from netpyne.conversion import createPythonScript createPythonScript('HHTut_regen.py', HHTut.netParams, HHTut.simConfig)
def generate_WB_network(cell_id, synapse_id, numCells_bc, connection_probability, I_mean, I_sigma, generate_LEMS_simulation, duration, x_size = 100, y_size = 100, z_size = 100, network_id = ref+'Network', color = '0 0 1', connection = True, temperature = '37 degC', validate = True, dt = 0.001): nml_doc = neuroml.NeuroMLDocument(id=network_id) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiCell.xml')) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiSynapse.xml')) # Create network net = neuroml.Network(id=network_id, type='networkWithTemperature', temperature=temperature) net.notes = 'Network generated using libNeuroML v%s'%__version__ nml_doc.networks.append(net) # Create population pop = neuroml.Population(id=ref+'pop', component=cell_id, type='populationList', size=numCells_bc) if color is not None: pop.properties.append(neuroml.Property('color', color)) net.populations.append(pop) for i in range(0, numCells_bc): inst = neuroml.Instance(id=i) pop.instances.append(inst) inst.location = neuroml.Location(x=str(x_size*rnd.random()), y=str(y_size*rnd.random()), z=str(z_size*rnd.random())) # Add connections proj = neuroml.ContinuousProjection(id=ref+'proj', presynaptic_population=pop.id, postsynaptic_population=pop.id) conn_count = 0 for i in range(0, numCells_bc): for j in range(0, numCells_bc): if i != j and rnd.random() < connection_probability: connection = neuroml.ContinuousConnectionInstance(id=conn_count, pre_cell='../%s/%i/%s'%(pop.id, i, cell_id), pre_component='silent', post_cell='../%s/%i/%s'%(pop.id, j, cell_id), post_component=synapse_id) proj.continuous_connection_instances.append(connection) conn_count += 1 net.continuous_projections.append(proj) # make cell pop inhomogenouos (different V_init-s with voltage-clamp) vc_dur = 2 # ms for i in range(0, numCells_bc): tmp = -75 + (rnd.random()*15) vc = neuroml.VoltageClamp(id='VClamp%i'%i, delay='0ms', duration='%ims'%vc_dur, simple_series_resistance='1e6ohm', target_voltage='%imV'%tmp) nml_doc.voltage_clamps.append(vc) input_list = neuroml.InputList(id='input_%i'%i, component='VClamp%i'%i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s'%(pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Add outer input (IClamp) tmp = rnd.normal(I_mean, I_sigma**2, numCells_bc) # random numbers from Gaussian distribution for i in range(0, numCells_bc): pg = neuroml.PulseGenerator(id='IClamp%i'%i, delay='%ims'%vc_dur, duration='%ims'%(duration-vc_dur), amplitude='%fpA'%(tmp[i])) nml_doc.pulse_generators.append(pg) input_list = neuroml.InputList(id='input%i'%i, component='IClamp%i'%i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s'%(pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Write to file nml_file = '%sNet.nml'%ref print 'Writing network file to:', nml_file, '...' neuroml.writers.NeuroMLWriter.write(nml_doc, nml_file) if validate: # Validate the NeuroML from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_LEMS_simulation: # Vreate a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation(sim_id='%sNetSim'%ref, duration=duration, dt=dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files ls.include_neuroml2_file('WangBuzsakiCell.xml', include_included=False) ls.include_neuroml2_file('WangBuzsakiSynapse.xml', include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) # Specify Display and output files disp_bc = 'display_bc' ls.create_display(disp_bc, 'Basket Cell Voltage trace', '-80', '40') of_bc = 'volts_file_bc' ls.create_output_file(of_bc, 'wangbuzsaki_network.dat') of_spikes_bc = 'spikes_bc' ls.create_event_output_file(of_spikes_bc, 'wangbuzsaki_network_spikes.dat') max_traces = 9 # the 10th color in NEURON is white ... for i in range(numCells_bc): quantity = '%s/%i/%s/v'%(pop.id, i, cell_id) if i < max_traces: ls.add_line_to_display(disp_bc, 'BC %i: Vm'%i, quantity, '1mV', pynml.get_next_hex_color()) ls.add_column_to_output_file(of_bc, 'v_%i'%i, quantity) ls.add_selection_to_event_output_file(of_spikes_bc, i, select='%s/%i/%s'%(pop.id, i, cell_id), event_port='spike') # Save to LEMS file print 'Writing LEMS file...' lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' return ls, lems_file_name
def generate_hippocampal_net(network_id, conndata="430", nrn_runname="TestRun", validate=True, randomSeed=12345, generate_LEMS_simulation=False, duration=100, dt=0.01, temperature="34.0 degC"): seed(randomSeed) cell_types = [ 'axoaxonic', 'bistratified', 'cck', 'cutsuridis', 'ivy', 'ngf', 'olm', 'poolosyn', 'pvbasket', 'sca' ] synapse_types = ['exp2Synapses', 'customGABASynapses'] ###### Create network doc ##### nml_doc = neuroml.NeuroMLDocument(id=network_id) for cell in cell_types: nml_doc.includes.append( neuroml.IncludeType(href="../cells/%s.cell.nml" % cell)) for synapse in synapse_types: nml_doc.includes.append( neuroml.IncludeType(href="../synapses/%s.synapse.nml" % synapse)) nml_doc.includes.append(neuroml.IncludeType(href="stimulations.nml")) # Create network net = neuroml.Network(id=network_id, type="networkWithTemperature", temperature=temperature) from neuroml import __version__ net.notes = "Network generated using libNeuroML v%s" % __version__ nml_doc.networks.append(net) # Create populations print("Creating populations...") dCellIDs, dNumCells = create_populations(net, cell_types, nrn_runname, randomSeed) # Create synapses print("Connecting cells...") add_synapses(net, conndata, nrn_runname, dCellIDs, dNumCells, write_synapse_file=False) # initialise voltage print("Initialising cell voltage..") # TODO: this shouldn't be hard coded ... dClamps = {} dClamps["axoaxonic"] = -65.0127 dClamps["bistratified"] = -67.0184 dClamps["cck"] = -70.6306 dClamps["ivy"] = -59.9512 dClamps["ngf"] = -59.9512 dClamps["olm"] = -71.1411 dClamps["poolosyn"] = -62.9601 dClamps["pvbasket"] = -65.0246 dClamps["sca"] = -70.5652 init_voltage(nml_doc, net, dClamps, dNumCells) ####### 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_' + network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files channel_types = [ 'CavL', 'CavN', 'HCN', 'HCNolm', 'HCNp', 'KCaS', 'Kdrfast', 'Kdrfastngf', 'Kdrp', 'Kdrslow', 'KvA', 'KvAdistp', 'KvAngf', 'KvAolm', 'KvAproxp', 'KvCaB', 'KvGroup', 'Nav', 'Navaxonp', 'Navbis', 'Navcck', 'Navngf', 'Navp', 'leak_chan' ] for channel in channel_types: ls.include_neuroml2_file("../channels/%s.channel.nml" % channel, include_included=False) ls.include_neuroml2_file("../channels/Capool.nml", include_included=False) for cell in cell_types: ls.include_neuroml2_file("../cells/%s.cell.nml" % cell, include_included=False) for synapse in synapse_types: ls.include_neuroml2_file("../synapses/%s.synapse.nml" % synapse, include_included=False) ls.include_neuroml2_file("stimulations.nml", include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) ###### Specify Display and output files ##### max_traces = 9 # the 10th color in NEURON is white ... for cell_type, numCells in dNumCells.iteritems(): PC = False if numCells > 0: of = "of_%s" % cell_type ls.create_output_file(of, "%s.v.dat" % cell_type) if cell_type == 'poolosyn' or cell_type == 'cutsuridis': # TODO: ensure that only one of them is used for modelling pyramidal cells (in a given simulation) PC = True ls.create_event_output_file("spikes_PC", "PC.spikes.dat") ls.create_display("disp_PC", "Voltages Pyramidal cells", "-80", "50") cell_id = "%scell" % cell_type pop_id = "pop_%s" % cell_type for i in range(numCells): quantity = "%s/%i/%s/v" % (pop_id, i, cell_id) ls.add_column_to_output_file(of, "v_%i" % i, quantity) if PC: ls.add_selection_to_event_output_file( "spikes_PC", i, select='%s/%i/%s' % (pop_id, i, cell_id), event_port='spike') if i < max_traces: ls.add_line_to_display("disp_PC", "PC %i: V[mV]" % i, quantity, "1mV", pynml.get_next_hex_color()) # Save to LEMS file print("Writing LEMS file...") lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' print("-----------------------------------") return ls, lems_file_name
import HybridTut # import parameters file from netpyne import sim # import netpyne sim module np = HybridTut.netParams print( "********************\n*\n* Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************" ) np.stimSourceParams['bkg']['noise'] = 1 sim.createExportNeuroML2( netParams=np, simConfig=HybridTut.simConfig, reference='HybridTut') # create and export network to NeuroML 2 ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2('HybridTut.net.nml')
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')
import M1 # import parameters file from netpyne import sim # import netpyne sim module np = M1.netParams print( "********************\n*\n* Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************" ) np.stimSourceParams['background_E']['noise'] = 1 np.stimSourceParams['background_I']['noise'] = 1 sim.createExportNeuroML2( netParams=np, simConfig=M1.simConfig, reference='M1', connections=True, stimulations=True) # create and export network to NeuroML 2 ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2('M1.net.nml')
def generate_granule_cell_layer(network_id, x_size = 0, # um y_size = 0, # um z_size = 0, # um numCells_grc = 0, numCells_gol = 0, connections = True, connections_method = 'random', connection_probability_grc_gol = 0.2, connection_probability_gol_grc = 0.1, inputs = False, input_firing_rate = 50, # Hz num_inputs_per_grc = 4, validate = True, random_seed = 1234, generate_lems_simulation = False, max_plotted_cells_per_pop = 10, duration = 500, # ms dt = 0.025, 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) # The names of the cell type/component used in the populations (Cell Type in neuroConstruct) grc_group_component = "Granule_98" gol_group_component = "Golgi_98" nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component)) nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component)) # The names of the Exc & Inh groups/populations (Cell Group in neuroConstruct) grc_group = "Grans" gol_group = "Golgis" # The names of the network connections net_conn_grc_gol = "NetConn_Grans_Golgis" net_conn_gol_grc = "NetConn_Golgis_Grans" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct) grc_gol_syn = "AMPA_GranGol" gol_grc_syn = "GABAA" for syn in [grc_gol_syn, gol_grc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) if network_id == 'Solinas2010': # Set size and cell numbers for Solinas 2010 network import sys,os NEURON_sim_path = '../NEURON' sys.path.append(NEURON_sim_path) local_path = os.getcwd() os.chdir(NEURON_sim_path) print os.getcwd() import GenerateSolinas2010 as GS2010 structure = GS2010.GenerateSolinas2010(generate=True) os.chdir(local_path) goc_data = structure['Golgis'] grc_data = structure['Granules'] grc_pos = grc_data['positions']['data'] goc_pos = goc_data['positions']['data'] numCells_grc = grc_pos.shape[0] numCells_gol = goc_pos.shape[0] # Generate excitatory cells grc_pop = Population(id=grc_group, component=grc_group_component, type="populationList", size=numCells_grc) net.populations.append(grc_pop) for i in range(0, numCells_grc) : index = i inst = Instance(id=index) grc_pop.instances.append(inst) inst.location = Location(x=str(grc_pos[i,0]), y=str(grc_pos[i,1]), z=str(grc_pos[i,2])) # Generate inhibitory cells gol_pop = Population(id=gol_group, component=gol_group_component, type="populationList", size=numCells_gol) net.populations.append(gol_pop) for i in range(0, numCells_gol) : index = i inst = Instance(id=index) gol_pop.instances.append(inst) inst.location = Location(x=str(goc_pos[i,0]), y=str(goc_pos[i,1]), z=str(goc_pos[i,2])) if connections: proj_grc_gol = Projection(id=net_conn_grc_gol, presynaptic_population=grc_group, postsynaptic_population=gol_group, synapse=grc_gol_syn) net.projections.append(proj_grc_gol) proj_gol_grc = Projection(id=net_conn_gol_grc, presynaptic_population=gol_group, postsynaptic_population=grc_group, synapse=gol_grc_syn) net.projections.append(proj_gol_grc) count_grc_gol = 0 count_gol_grc = 0 # Generate exc -> * connections def add_connection(projection, id, pre_pop, pre_component, pre_cell_id, pre_seg_id, post_pop, post_component, post_cell_id, post_seg_id): connection = Connection(id=id, \ pre_cell_id="../%s/%i/%s"%(pre_pop, pre_cell_id, pre_component), \ pre_segment_id=pre_seg_id, \ pre_fraction_along=0.5, post_cell_id="../%s/%i/%s"%(post_pop, post_cell_id, post_component), \ post_segment_id=post_seg_id, post_fraction_along=0.5) projection.connections.append(connection) # Connect Granule cells to Golgi cells for i in range(0, numCells_grc): # get targets for grc[i] from the structure dict # print 'Granule ', i , structure['Granules']['divergence_to_goc']['data'][i][1:] for j in structure['Granules']['divergence_to_goc']['data'][i][1:]: add_connection(proj_grc_gol, count_grc_gol, grc_group, grc_group_component, i, 0, gol_group, gol_group_component, j, 0) count_grc_gol+=1 # Connect Golgi cells to Granule cells for i in range(0, numCells_gol): # get targets glomeruli for goc[i] from the lol in structure dict # print 'Golgi ', i # print structure['Golgis']['divergence_to_glom']['data'][i][1:] for k in structure['Golgis']['divergence_to_glom']['data'][i][1:]: # get target granule cells for glom[k] from the lol in structure dict # print 'Glom ', k # print structure['Glomeruli']['divergence_to_grc']['data'][k] for j in structure['Glomeruli']['divergence_to_grc']['data'][k][1:]: # print 'Granule ', j add_connection(proj_gol_grc, count_gol_grc, gol_group, gol_group_component, i, 0, grc_group, grc_group_component, j, 0) count_gol_grc+=1 if inputs: mf_input_syn = "MF_AMPA" nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input50Hz" #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/> pfs = PoissonFiringSynapse(id="input50Hz", 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=grc_group) count = 0 for i in range(0, numCells_grc): for j in range(num_inputs_per_grc): input = Input(id=count, target="../%s/%i/%s"%(grc_group, i, grc_group_component), destination="synapses") input_list.input.append(input) count += 1 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'%grc_group_component) ls.include_neuroml2_file('%s.cell.nml'%gol_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files disp_grc = "display_grc" ls.create_display(disp_grc, "Voltages Granule cells", "-95", "-38") of_grc = 'Volts_file_grc' ls.create_output_file(of_grc, "v_grc.dat") disp_gol = "display_gol" ls.create_display(disp_gol, "Voltages Golgi cells", "-95", "-38") of_gol = 'Volts_file_gol' ls.create_output_file(of_gol, "v_gol.dat") for i in range(min(numCells_grc,max_plotted_cells_per_pop)): quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component) ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity) for i in range(min(numCells_gol,max_plotted_cells_per_pop)): quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component) ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() print "-----------------------------------"
def channelpedia_xml_to_neuroml2(cpd_xml, nml2_file_name, unknowns=""): info = 'Automatic conversion of Channelpedia XML file to NeuroML2\n'+\ 'Uses: https://github.com/OpenSourceBrain/BlueBrainProjectShowcase/blob/master/Channelpedia/ChannelpediaToNeuroML2.py' print(info) root = ET.fromstring(cpd_xml) channel_id = 'Channelpedia_%s_%s' % (root.attrib['ModelName'].replace( "/", "_").replace(" ", "_").replace(".", "_"), root.attrib['ModelID']) doc = neuroml.NeuroMLDocument() metadata = osb.metadata.RDF(info) ion = root.findall('Ion')[0] chan = neuroml.IonChannelHH( id=channel_id, conductance='10pS', species=ion.attrib['Name'], notes= "This is an automated conversion to NeuroML 2 of an ion channel model from Channelpedia. " + "\nThe original channel model file can be found at: http://channelpedia.epfl.ch/ionchannels/%s" % root.attrib['ID'] + "\n\nConversion scripts at https://github.com/OpenSourceBrain/BlueBrainProjectShowcase" ) chan.annotation = neuroml.Annotation() model_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s/hhmodels/%s.xml' desc = osb.metadata.Description(channel_id) metadata.descriptions.append(desc) osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDerivedFrom', \ model_url_template%(root.attrib['ID'], root.attrib['ModelID']), \ "Channelpedia channel ID: %s, ModelID: %s; direct link to original XML model" % (root.attrib['ID'], root.attrib['ModelID'])) channel_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s' osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ channel_url_template%(root.attrib['ID']), \ "Channelpedia channel ID: %s; link to main page for channel" % (root.attrib['ID'])) for reference in root.findall('Reference'): pmid = reference.attrib['PubmedID'] #metadata = update_metadata(chan, metadata, channel_id, "http://identifiers.org/pubmed/%s"%pmid) ref_info = reference.text osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ osb.resources.PUBMED_URL_TEMPLATE % (pmid), \ ("PubMed ID: %s is referenced in original XML\n"+\ " %s") % (pmid, ref_info)) for environment in root.findall('Environment'): for animal in environment.findall('Animal'): species = animal.attrib['Name'].lower() if species: if species in osb.resources.KNOWN_SPECIES: known_id = osb.resources.KNOWN_SPECIES[species] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'hasTaxon', \ osb.resources.NCBI_TAXONOMY_URL_TEMPLATE % known_id, \ "Known species: %s; taxonomy id: %s" % (species, known_id)) else: print("Unknown species: %s" % species) unknowns += "Unknown species: %s\n" % species for cell_type_el in environment.findall('CellType'): cell_type = cell_type_el.text.strip().lower() if cell_type: if cell_type in osb.resources.KNOWN_CELL_TYPES: known_id = osb.resources.KNOWN_CELL_TYPES[cell_type] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'isPartOf', \ osb.resources.NEUROLEX_URL_TEMPLATE % known_id, \ "Known cell type: %s; taxonomy id: %s" % (cell_type, known_id)) else: print("Unknown cell_type: %s" % cell_type) unknowns += "Unknown cell_type: %s\n" % cell_type print("Currently unknown: <<<%s>>>" % unknowns) comp_types = {} for gate in root.findall('Gates'): eq_type = gate.attrib['EqType'] gate_name = gate.attrib['Name'] target = chan.gates if eq_type == '1': g = neuroml.GateHHUndetermined(id=gate_name, type='gateHHtauInf', instances=int( float(gate.attrib['Power']))) elif eq_type == '2': g = neuroml.GateHHUndetermined(id=gate_name, type='gateHHrates', instances=int( float(gate.attrib['Power']))) for inf in gate.findall('Inf_Alpha'): equation = check_equation(inf.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'inf') g.steady_state = neuroml.HHVariable(type=new_comp_type) comp_type = lems.ComponentType( new_comp_type, extends="baseVoltageDepVariable") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='x', dimension="none", value="%s" % equation, exposure="x")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'alpha') g.forward_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE" % equation, exposure="r")) comp_types[new_comp_type] = comp_type for tau in gate.findall('Tau_Beta'): equation = check_equation(tau.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_tau" % (channel_id, gate_name) g.time_course = neuroml.HHTime(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepTime") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='t', dimension="time", value="(%s) * TIME_SCALE" % equation, exposure="t")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'beta') g.reverse_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE" % equation, exposure="r")) comp_types[new_comp_type] = comp_type target.append(g) doc.ion_channel_hhs.append(chan) doc.id = channel_id writers.NeuroMLWriter.write(doc, nml2_file_name) print("Written NeuroML 2 channel file to: " + nml2_file_name) for comp_type_name in comp_types.keys(): comp_type = comp_types[comp_type_name] ct_xml = comp_type.toxml() # Quick & dirty pretty printing.. ct_xml = ct_xml.replace('<Const', '\n <Const') ct_xml = ct_xml.replace('<Dyna', '\n <Dyna') ct_xml = ct_xml.replace('</Dyna', '\n </Dyna') ct_xml = ct_xml.replace('<Deriv', '\n <Deriv') ct_xml = ct_xml.replace('</Compone', '\n </Compone') # print("Adding definition for %s:\n%s\n"%(comp_type_name, ct_xml)) nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace("</neuroml>", "\n %s\n\n</neuroml>" % ct_xml) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() print("Inserting metadata...") nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace( "<annotation/>", "\n <annotation>\n%s </annotation>\n" % metadata.to_xml(" ")) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml2_file_name) return unknowns
def v(f): from neuroml.utils import validate_neuroml2 validate_neuroml2(f)
Z=zs[0]+random.random()*(zs[1]-zs[0]) Y = ys[layer][0]+random.random()*(ys[layer][1]-ys[layer][0]) inst.location = Location(x=X, y=Y, z=Z) count+=1 net_file = '%s.net.nml'%(net_ref) writers.NeuroMLWriter.write(net_doc, net_file) print("Written network with %i cells in network to: %s"%(count,net_file)) from neuroml.utils import validate_neuroml2 validate_neuroml2(net_file) generate_lems_file_for_neuroml("Sim_"+net_ref, net_file, net_ref, 50, 0.025, "LEMS_%s.xml"%net_ref, ".", gen_plots_for_all_v = True, plot_all_segments = True, gen_saves_for_all_v = True, save_all_segments = True, copy_neuroml = False, seed = 1234)
def validate_nml2(self, nml2_file): """ Validated NeuroML2 file """ return validate_neuroml2(nml2_file)
h_gate.forward_rate = neuroml.HHRate(type="HHExpLinearRate", rate="0.1per_ms", midpoint="-55mV", scale="10mV") h_gate.reverse_rate = neuroml.HHRate(type="HHExpRate", rate="0.125per_ms", midpoint="-65mV", scale="-80mV") chan.gate_hh_rates.append(m_gate) chan.gate_hh_rates.append(h_gate) doc = neuroml.NeuroMLDocument() doc.ion_channel_hhs.append(chan) doc.id = "ChannelMLDemo" nml_file = './tmp/ionChannelTest.xml' writers.NeuroMLWriter.write(doc,nml_file) print("Written channel file to: "+nml_file) ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file)
def channelpedia_xml_to_neuroml2(cpd_xml, nml2_file_name, unknowns=""): info = 'Automatic conversion of Channelpedia XML file to NeuroML2\n'+\ 'Uses: https://github.com/OpenSourceBrain/BlueBrainProjectShowcase/blob/master/Channelpedia/ChannelpediaToNeuroML2.py' print(info) root = ET.fromstring(cpd_xml) channel_id='Channelpedia_%s_%s'%(root.attrib['ModelName'].replace("/","_").replace(" ","_").replace(".","_"), root.attrib['ModelID']) doc = neuroml.NeuroMLDocument() metadata = osb.metadata.RDF(info) ion = root.findall('Ion')[0] chan = neuroml.IonChannelHH(id=channel_id, conductance='10pS', species=ion.attrib['Name'], notes="This is an automated conversion to NeuroML 2 of an ion channel model from Channelpedia. "+ "\nThe original model can be found at: http://channelpedia.epfl.ch/ionchannels/%s"%root.attrib['ID']+ "\n\nConversion scripts at https://github.com/OpenSourceBrain/BlueBrainProjectShowcase") chan.annotation = neuroml.Annotation() model_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s/hhmodels/%s.xml' desc = osb.metadata.Description(channel_id) metadata.descriptions.append(desc) osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDerivedFrom', \ model_url_template%(root.attrib['ID'], root.attrib['ModelID']), \ "Channelpedia channel ID: %s, ModelID: %s; direct link to original XML model" % (root.attrib['ID'], root.attrib['ModelID'])) channel_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s' osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ channel_url_template%(root.attrib['ID']), \ "Channelpedia channel ID: %s; link to main page for channel" % (root.attrib['ID'])) for reference in root.findall('Reference'): pmid = reference.attrib['PubmedID'] #metadata = update_metadata(chan, metadata, channel_id, "http://identifiers.org/pubmed/%s"%pmid) ref_info = reference.text osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ osb.resources.PUBMED_URL_TEMPLATE % (pmid), \ ("PubMed ID: %s is referenced in original XML\n"+\ " %s") % (pmid, ref_info)) for environment in root.findall('Environment'): for animal in environment.findall('Animal'): species = animal.attrib['Name'].lower() if species: if osb.resources.KNOWN_SPECIES.has_key(species): known_id = osb.resources.KNOWN_SPECIES[species] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'hasTaxon', \ osb.resources.NCBI_TAXONOMY_URL_TEMPLATE % known_id, \ "Known species: %s; taxonomy id: %s" % (species, known_id)) else: print("Unknown species: %s"%species) unknowns += "Unknown species: %s\n"%species for cell_type_el in environment.findall('CellType'): cell_type = cell_type_el.text.strip().lower() if cell_type: if osb.resources.KNOWN_CELL_TYPES.has_key(cell_type): known_id = osb.resources.KNOWN_CELL_TYPES[cell_type] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'isPartOf', \ osb.resources.NEUROLEX_URL_TEMPLATE % known_id, \ "Known cell type: %s; taxonomy id: %s" % (cell_type, known_id)) else: print("Unknown cell_type: %s"%cell_type) unknowns += "Unknown cell_type: %s\n"%cell_type print("Currently unknown: <<<%s>>>"%unknowns) comp_types = {} for gate in root.findall('Gates'): eq_type = gate.attrib['EqType'] gate_name = gate.attrib['Name'] target = None if eq_type == '1': g = neuroml.GateHHTauInf(id=gate_name,instances=int(float(gate.attrib['Power']))) target = chan.gate_hh_tau_infs elif eq_type == '2': g = neuroml.GateHHRates(id=gate_name,instances=int(float(gate.attrib['Power']))) target = chan.gate_hh_rates for inf in gate.findall('Inf_Alpha'): equation = check_equation(inf.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_%s"%(channel_id, gate_name, 'inf') g.steady_state = neuroml.HHVariable(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepVariable") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add(lems.DerivedVariable(name='x', dimension="none", value="%s"%equation, exposure="x")) comp_type.dynamics.add(lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s"%(channel_id, gate_name, 'alpha') g.forward_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add(lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE"%equation, exposure="r")) comp_type.dynamics.add(lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_types[new_comp_type] = comp_type for tau in gate.findall('Tau_Beta'): equation = check_equation(tau.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_tau"%(channel_id, gate_name) g.time_course = neuroml.HHTime(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepTime") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add(lems.DerivedVariable(name='t', dimension="none", value="(%s) * TIME_SCALE"%equation, exposure="t")) comp_type.dynamics.add(lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s"%(channel_id, gate_name, 'beta') g.reverse_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add(lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE"%equation, exposure="r")) comp_type.dynamics.add(lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_types[new_comp_type] = comp_type target.append(g) doc.ion_channel_hhs.append(chan) doc.id = channel_id writers.NeuroMLWriter.write(doc,nml2_file_name) print("Written NeuroML 2 channel file to: "+nml2_file_name) for comp_type_name in comp_types.keys(): comp_type = comp_types[comp_type_name] ct_xml = comp_type.toxml() # Quick & dirty pretty printing.. ct_xml = ct_xml.replace('<Const','\n <Const') ct_xml = ct_xml.replace('<Dyna','\n <Dyna') ct_xml = ct_xml.replace('</Dyna','\n </Dyna') ct_xml = ct_xml.replace('<Deriv','\n <Deriv') ct_xml = ct_xml.replace('</Compone','\n </Compone') # print("Adding definition for %s:\n%s\n"%(comp_type_name, ct_xml)) nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace("</neuroml>", "\n %s\n\n</neuroml>"%ct_xml) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() print("Inserting metadata...") nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace("<annotation/>", "\n <annotation>\n%s </annotation>\n"%metadata.to_xml(" ")) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml2_file_name) return unknowns
def run(): cell_num = 10 x_size = 500 y_size = 500 z_size = 500 nml_doc = NeuroMLDocument(id="Net3DExample") syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms") nml_doc.exp_one_synapses.append(syn0) net = Network(id="Net3D") nml_doc.networks.append(net) proj_count = 0 #conn_count = 0 for cell_id in range(0,cell_num): cell = Cell(id="Cell_%i"%cell_id) cell.morphology = generateRandomMorphology() nml_doc.cells.append(cell) pop = Population(id="Pop_%i"%cell_id, component=cell.id, type="populationList") net.populations.append(pop) inst = Instance(id="0") pop.instances.append(inst) inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random())) prob_connection = 0.5 for post in range(0,cell_num): if post is not cell_id and random() <= prob_connection: from_pop = "Pop_%i"%cell_id to_pop = "Pop_%i"%post pre_seg_id = 0 post_seg_id = 1 projection = Projection(id="Proj_%i"%proj_count, presynaptic_population=from_pop, postsynaptic_population=to_pop, synapse=syn0.id) net.projections.append(projection) connection = Connection(id=proj_count, \ pre_cell_id="%s[%i]"%(from_pop,0), \ pre_segment_id=pre_seg_id, \ pre_fraction_along=random(), post_cell_id="%s[%i]"%(to_pop,0), \ post_segment_id=post_seg_id, post_fraction_along=random()) projection.connections.append(connection) proj_count += 1 #net.synaptic_connections.append(SynapticConnection(from_="%s[%i]"%(from_pop,0), to="%s[%i]"%(to_pop,0))) ####### Write to file ###### nml_file = 'tmp/net3d.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)
y=parent_segment.distal.y, z=parent_segment.distal.z, diameter=0.1) axon_segment = neuroml.Segment(proximal=p, distal=d, parent=parent) axon_segment.id = seg_id axon_segment.name = 'axon_segment_' + str(axon_segment.id) #now reset everything: parent = neuroml.SegmentParent(segments=axon_segment.id) parent_segment = axon_segment seg_id += 1 axon_segments.append(axon_segment) doc.cells[0].morphology.segments += axon_segments nml_file = './tmp/modified_morphology.nml' writers.NeuroMLWriter.write(doc, nml_file) print("Saved modified morphology file to: " + nml_file) ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file)
def generate_granule_cell_layer(network_id, x_size, # um y_size, # um z_size, # um numCells_mf, numCells_grc, numCells_gol, mf_group_component = "MossyFiber", grc_group_component = "Granule_98", gol_group_component = "Golgi_98", connections = True, connection_probability_grc_gol = 0.2, connection_probability_gol_grc = 0.1, inputs = False, input_firing_rate = 50, # Hz num_inputs_per_mf = 4, validate = True, random_seed = 1234, generate_lems_simulation = False, duration = 500, # ms dt = 0.005, 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) if numCells_mf>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%mf_group_component)) if numCells_grc>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component)) if numCells_gol>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component)) # The names of the groups/populations mf_group = "MossyFibers" grc_group = "Grans" gol_group = "Golgis" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)= mf_grc_syn = "MF_AMPA" grc_gol_syn = "AMPA_GranGol" gol_grc_syn = "GABAA" for syn in [mf_grc_syn, grc_gol_syn, gol_grc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) # Generate Gran cells if numCells_mf>0: add_population_in_rectangular_region(net, mf_group, mf_group_component, numCells_mf, 0, 0, 0, x_size, y_size, z_size, color="0 0 1") # Generate Gran cells if numCells_grc>0: add_population_in_rectangular_region(net, grc_group, grc_group_component, numCells_grc, 0, 0, 0, x_size, y_size, z_size, color="1 0 0") # Generate Golgi cells if numCells_gol>0: add_population_in_rectangular_region(net, gol_group, gol_group_component, numCells_gol, 0, 0, 0, x_size, y_size, z_size, color="0 1 0") if connections: add_probabilistic_projection(net, mf_group, mf_group_component, grc_group, grc_group_component, 'NetConn', mf_grc_syn, numCells_mf, numCells_grc, 0.01) add_probabilistic_projection(net, grc_group, grc_group_component, gol_group, gol_group_component, 'NetConn', grc_gol_syn, numCells_grc, numCells_gol, connection_probability_grc_gol) add_probabilistic_projection(net, gol_group, gol_group_component, grc_group, grc_group_component, 'NetConn', gol_grc_syn, numCells_gol, numCells_grc, connection_probability_gol_grc) if inputs: mf_input_syn = "MFSpikeSyn" nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input%sHz"%input_firing_rate #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/> 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=mf_group) count = 0 for i in range(0, numCells_mf): for j in range(num_inputs_per_mf): input = Input(id=count, target="../%s/%i/%s"%(mf_group, i, mf_group_component), destination="synapses") input_list.input.append(input) count += 1 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'%grc_group_component) ls.include_neuroml2_file('%s.cell.nml'%gol_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files if numCells_mf>0: disp_mf = "display_mf" ls.create_display(disp_mf, "Voltages Mossy fibers", "-70", "10") of_mf = 'Volts_file_mf' ls.create_output_file(of_mf, "v_mf.dat") for i in range(numCells_mf): quantity = "%s/%i/%s/v"%(mf_group, i, mf_group_component) ls.add_line_to_display(disp_mf, "MF %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_mf, "v_%i"%i, quantity) # Specify Displays and Output Files if numCells_grc>0: disp_grc = "display_grc" ls.create_display(disp_grc, "Voltages Granule cells", "-75", "30") of_grc = 'Volts_file_grc' ls.create_output_file(of_grc, "v_grc.dat") for i in range(numCells_grc): quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component) ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity) if numCells_gol>0: disp_gol = "display_gol" ls.create_display(disp_gol, "Voltages Golgi cells", "-75", "30") of_gol = 'Volts_file_gol' ls.create_output_file(of_gol, "v_gol.dat") for i in range(numCells_gol): quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component) ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() else: ls = None print "-----------------------------------" return nml_doc, ls
def run(): cell_num = 10 x_size = 500 y_size = 500 z_size = 500 nml_doc = NeuroMLDocument(id="Net3DExample") syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms") nml_doc.exp_one_synapses.append(syn0) net = Network(id="Net3D") nml_doc.networks.append(net) proj_count = 0 #conn_count = 0 for cell_id in range(0, cell_num): cell = Cell(id="Cell_%i" % cell_id) cell.morphology = generateRandomMorphology() nml_doc.cells.append(cell) pop = Population(id="Pop_%i" % cell_id, component=cell.id, type="populationList") net.populations.append(pop) pop.properties.append(Property(tag="color", value="1 0 0")) inst = Instance(id="0") pop.instances.append(inst) inst.location = Location(x=str(x_size * random()), y=str(y_size * random()), z=str(z_size * random())) prob_connection = 0.5 for post in range(0, cell_num): if post is not cell_id and random() <= prob_connection: from_pop = "Pop_%i" % cell_id to_pop = "Pop_%i" % post pre_seg_id = 0 post_seg_id = 1 projection = Projection(id="Proj_%i" % proj_count, presynaptic_population=from_pop, postsynaptic_population=to_pop, synapse=syn0.id) net.projections.append(projection) connection = Connection(id=proj_count, \ pre_cell_id="%s[%i]"%(from_pop,0), \ pre_segment_id=pre_seg_id, \ pre_fraction_along=random(), post_cell_id="%s[%i]"%(to_pop,0), \ post_segment_id=post_seg_id, post_fraction_along=random()) projection.connections.append(connection) proj_count += 1 #net.synaptic_connections.append(SynapticConnection(from_="%s[%i]"%(from_pop,0), to="%s[%i]"%(to_pop,0))) ####### Write to file ###### nml_file = 'tmp/net3d.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)
def generate_WB_network(cell_id, synapse_id, numCells_bc, connection_probability, I_mean, I_sigma, generate_LEMS_simulation, duration, x_size=100, y_size=100, z_size=100, network_id=ref + 'Network', color='0 0 1', connection=True, temperature='37 degC', validate=True, dt=0.01): nml_doc = neuroml.NeuroMLDocument(id=network_id) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsaki.cell.nml')) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiSynapse.xml')) # Create network net = neuroml.Network(id=network_id, type='networkWithTemperature', temperature=temperature) net.notes = 'Network generated using libNeuroML v%s' % __version__ nml_doc.networks.append(net) # Create population pop = neuroml.Population(id=ref + 'pop', component=cell_id, type='populationList', size=numCells_bc) if color is not None: pop.properties.append(neuroml.Property('color', color)) net.populations.append(pop) for i in range(0, numCells_bc): inst = neuroml.Instance(id=i) pop.instances.append(inst) inst.location = neuroml.Location(x=str(x_size * rnd.random()), y=str(y_size * rnd.random()), z=str(z_size * rnd.random())) # Add connections proj = neuroml.ContinuousProjection(id=ref + 'proj', presynaptic_population=pop.id, postsynaptic_population=pop.id) conn_count = 0 for i in range(0, numCells_bc): for j in range(0, numCells_bc): if i != j and rnd.random() < connection_probability: connection = neuroml.ContinuousConnectionInstance( id=conn_count, pre_cell='../%s/%i/%s' % (pop.id, i, cell_id), pre_component='silent', post_cell='../%s/%i/%s' % (pop.id, j, cell_id), post_component=synapse_id) proj.continuous_connection_instances.append(connection) conn_count += 1 net.continuous_projections.append(proj) # make cell pop inhomogenouos (different V_init-s with voltage-clamp) vc_dur = 2 # ms for i in range(0, numCells_bc): tmp = -75 + (rnd.random() * 15) vc = neuroml.VoltageClamp(id='VClamp%i' % i, delay='0ms', duration='%ims' % vc_dur, simple_series_resistance='1e6ohm', target_voltage='%imV' % tmp) nml_doc.voltage_clamps.append(vc) input_list = neuroml.InputList(id='input_%i' % i, component='VClamp%i' % i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s' % (pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Add outer input (IClamp) tmp = rnd.normal(I_mean, I_sigma**2, numCells_bc) # random numbers from Gaussian distribution for i in range(0, numCells_bc): pg = neuroml.PulseGenerator(id='IClamp%i' % i, delay='%ims' % vc_dur, duration='%ims' % (duration - vc_dur), amplitude='%fpA' % (tmp[i])) nml_doc.pulse_generators.append(pg) input_list = neuroml.InputList(id='input%i' % i, component='IClamp%i' % i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s' % (pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Write to file nml_file = '%s100Cells.net.nml' % ref print 'Writing network file to:', nml_file, '...' neuroml.writers.NeuroMLWriter.write(nml_doc, nml_file) if validate: # Validate the NeuroML from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_LEMS_simulation: # Vreate a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation(sim_id='%sNetSim' % ref, duration=duration, dt=dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files ls.include_neuroml2_file('WangBuzsaki.cell.nml', include_included=False) ls.include_neuroml2_file('WangBuzsakiSynapse.xml', include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) # Specify Display and output files disp_bc = 'display_bc' ls.create_display(disp_bc, 'Basket Cell Voltage trace', '-80', '40') of_bc = 'volts_file_bc' ls.create_output_file(of_bc, 'wangbuzsaki_network.dat') of_spikes_bc = 'spikes_bc' ls.create_event_output_file(of_spikes_bc, 'wangbuzsaki_network_spikes.dat') max_traces = 9 # the 10th color in NEURON is white ... for i in range(numCells_bc): quantity = '%s/%i/%s/v' % (pop.id, i, cell_id) if i < max_traces: ls.add_line_to_display(disp_bc, 'BC %i: Vm' % i, quantity, '1mV', pynml.get_next_hex_color()) ls.add_column_to_output_file(of_bc, 'v_%i' % i, quantity) ls.add_selection_to_event_output_file(of_spikes_bc, i, select='%s/%i/%s' % (pop.id, i, cell_id), event_port='spike') # Save to LEMS file print 'Writing LEMS file...' lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' return ls, lems_file_name