Пример #1
0
def generate_network(reference, network_seed=1234, temperature='32degC'):
    """
    Generate a network which will contain populations, projections, etc. Arguments:
    
    `reference`
        the reference to use as the id for the network
        
    `network_seed`
        optional, will be used for random elements of the network, e.g. placement of cells in 3D
        
    `temperature`
        optional, will be specified in network and used in temperature dependent elements, e.g. ion channels with Q10. Default: 32degC
        
    """

    del oc_build.all_included_files[:]
    oc_build.all_cells.clear()

    nml_doc = neuroml.NeuroMLDocument(id='%s' % reference)

    random.seed(network_seed)

    nml_doc.properties.append(neuroml.Property("Network seed", network_seed))

    # Create network
    network = neuroml.Network(id='%s' % reference,
                              type='networkWithTemperature',
                              temperature=temperature)
    nml_doc.networks.append(network)

    opencortex.print_comment_v(
        "Created NeuroMLDocument containing a network with id: %s" % reference)

    return nml_doc, network
Пример #2
0
def main():
    c = Configure()
    c['neuronscsv'] = 'https://raw.github.com/openworm/data-viz/master/HivePlots/neurons.csv'
    c['connectomecsv'] = 'https://raw.github.com/openworm/data-viz/master/HivePlots/connectome.csv'
    c['sqldb'] = '/home/markw/work/openworm/PyOpenWorm/db/celegans.db'
    c = Data(c)
    net = PyOpenWorm.Network(c)
    nml_doc = NeuroMLDocument(id="IafNet")
    ns = net.neurons()

    nml_net = neuroml.Network(id="IafNet")
    nml_doc.networks.append(nml_net)

    for n in [net.aneuron_nocheck(n) for n in ns]:
        s(nml_doc, nml_net, n)

    syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms")
    for k in net.synapses():
        n1 = net.aneuron_nocheck(k[0])
        n2 = net.aneuron_nocheck(k[1])
        connect(nml_net, n1, n2, 'syn0')

    f = "test.nml"
    writers.NeuroMLWriter.write(nml_doc, f)
    v(f)
Пример #3
0
def setup(timestep=DEFAULT_TIMESTEP,
          min_delay=DEFAULT_MIN_DELAY,
          **extra_params):
    """ Set up for saving cell models and network structure to NeuroML """
    common.setup(timestep, min_delay, **extra_params)
    simulator.state.clear()
    simulator.state.dt = timestep  # move to common.setup?
    simulator.state.min_delay = min_delay
    simulator.state.max_delay = extra_params.get('max_delay',
                                                 DEFAULT_MAX_DELAY)
    simulator.state.mpi_rank = extra_params.get('rank', 0)
    simulator.state.num_processes = extra_params.get('num_processes', 1)

    logger.debug("Creating network in NeuroML document to store structure")
    nml_doc = simulator._get_nml_doc(extra_params.get('reference',
                                                      "PyNN_NeuroML2_Export"),
                                     reset=True)
    global save_format
    save_format = extra_params.get('save_format', "xml")

    # Create network
    net = neuroml.Network(id=nml_doc.id)
    nml_doc.networks.append(net)

    lems_sim = simulator._get_lems_sim(reset=True)
    lems_sim.dt = '%s' % timestep

    return rank()
Пример #4
0
    def handle_network(self, network_id, notes, temperature=None):

        self.network = neuroml.Network(id=network_id)
        self.nml_doc.networks.append(self.network)
        if notes and len(notes) > 0:
            self.network.notes = notes
        if temperature:
            self.network.temperature = temperature
            self.network.type = "networkWithTemperature"
Пример #5
0
def main():
    """Main"""

    nml2_cell_dir = '../NeuroML2/'

    net_ref = "ManyCells"
    net_doc = neuroml.NeuroMLDocument(id=net_ref)

    net = neuroml.Network(id=net_ref)
    net_doc.networks.append(net)

    cell_dirs = [
        f for f in os.listdir('.')
        if (os.path.isdir(f) and os.path.isfile(f + '/.provenance.json'))
    ]

    clear_neuron()

    inputs_list = []
    for index, cell_dir in enumerate(cell_dirs):
        inputs_list.append((index, cell_dir, nml2_cell_dir, len(cell_dirs)))

    # Parallelise the generation of the files using multiprocessing if the
    # -parallel option is specified
    if parallel:
        import multiprocessing
        pool = multiprocessing.Pool(maxtasksperchild=1)  # pylint: disable=E1123
        nml_cell_files = pool.map(process_celldir, inputs_list, chunksize=1)
    else:
        nml_cell_files = map(process_celldir, inputs_list)

    for nml_cell_file, pop in nml_cell_files:
        net.populations.append(pop)
        net_doc.includes.append(neuroml.IncludeType(nml_cell_file))

    count = len(cell_dirs)
    if not make_zips:
        net_file = '%s/%s.net.nml' % (nml2_cell_dir, net_ref)
        neuroml.writers.NeuroMLWriter.write(net_doc, net_file)

        print("Written network with %i cells in network to: %s" %
              (count, net_file))

        pynml.nml2_to_svg(net_file)
Пример #6
0
def generate_Vm_vs_time_plot(NML2_file, 
                                        cell_id, 
                                     #   inj_amp_nA = 80,
                                     #   delay_ms = 20,
                                     #   inj_dur_ms = 0.5,
                                        sim_dur_ms = 1000, 
                                        dt = 0.05,
                                        temperature = "35",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        show_plot_already=True, 
                                        simulator="jNeuroML_NEURON",
                                        include_included=True):
                                            
	# simulation parameters                                            
    nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
    ref = "iMC1_cell_1_origin"
    print_comment_v("Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s"% # (Inj %snA / %sms dur after %sms delay)"%
        (cell_id, NML2_file, simulator))#, inj_amp_nA, inj_dur_ms, delay_ms))
    
    sim_id = 'Vm_%s'%ref
    duration = sim_dur_ms
    ls = LEMSSimulation(sim_id, sim_dur_ms, dt)
    
    ls.include_neuroml2_file(NML2_file, include_included=include_included)
    ls.assign_simulation_target('network')
    nml_doc = nml.NeuroMLDocument(id=cell_id)
    
    nml_doc.includes.append(nml.IncludeType(href=NML2_file))
    
    net = nml.Network(id="network", type='networkWithTemperature', temperature='%sdegC'%temperature)
    nml_doc.networks.append(net)
    
    #input_id = ("input_%s"%str(inj_amp_nA).replace('.','_'))
    #pg = nml.PulseGenerator(id=input_id,
    #                                delay="%sms"%delay_ms,
    #                                duration='%sms'%inj_dur_ms,
    #                                amplitude='%spA'%inj_amp_nA)
    #nml_doc.pulse_generators.append(pg)
    
    
    pop_id = 'single_cell'
    pop = nml.Population(id=pop_id, component='iMC1_cell_1_origin', size=1, type="populationList")
    
    inst = nml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(pop)
    
    # Add these to cells
    #input_list = nml.InputList(id='il_%s'%input_id,
    #                             component=pg.id,
    #                             populations=pop_id)
    #input = nml.Input(id='0',  target='../hhpop/0/hhcell',
    #                          destination="synapses")  
    
    #input_list.input.append(input)
    #net.input_lists.append(input_list)
    
    sim_file_name = '%s.sim.nml'%sim_id
    pynml.write_neuroml2_file(nml_doc, sim_file_name)
    ls.include_neuroml2_file(sim_file_name)


    disp0 = 'Voltage_display'
    ls.create_display(disp0,"Voltages", "-90", "50")
    ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV')
    
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat"%sim_id)
    ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v")
    
    lems_file_name = ls.save_to_file()
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
                                                
 
    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()
        #plt.plot("t","V")        
        #plt.title("Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"% 
        #    (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms))
        #plt.xlabel('Time (ms)')
        #plt.ylabel('Vmemb (mV)')
        #plt.legend(['Test'], loc='upper right')
        
        
    return of0     
Пример #7
0
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
Пример #8
0
def generate_current_vs_frequency_curve(nml2_file,
                                        cell_id,
                                        start_amp_nA,
                                        end_amp_nA,
                                        step_nA,
                                        analysis_duration,
                                        analysis_delay,
                                        dt=0.05,
                                        temperature="32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        plot_if=True,
                                        plot_iv=False,
                                        xlim_if=None,
                                        ylim_if=None,
                                        xlim_iv=None,
                                        ylim_iv=None,
                                        show_plot_already=True,
                                        save_if_figure_to=None,
                                        save_iv_figure_to=None,
                                        simulator="jNeuroML",
                                        include_included=True):

    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np

    print_comment_v(
        "Generating FI curve for cell %s in %s using %s (%snA->%snA; %snA steps)"
        % (cell_id, nml2_file, simulator, start_amp_nA, end_amp_nA, step_nA))

    sim_id = 'iv_%s' % cell_id
    duration = analysis_duration + analysis_delay
    ls = LEMSSimulation(sim_id, duration, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)

    stims = []
    amp = start_amp_nA
    while amp <= end_amp_nA:
        stims.append(amp)
        amp += step_nA

    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s" % cell_id,
                         component=cell_id,
                         size=number_cells)

    # create network and add populations
    net_id = "network_of_%s" % cell_id
    net = nml.Network(id=net_id,
                      type="networkWithTemperature",
                      temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA" % stims[i]
        input_id = ("input_%s" % stim_amp).replace('.',
                                                   '_').replace('-', 'min')
        pg = nml.PulseGenerator(id=input_id,
                                delay="0ms",
                                duration="%sms" % duration,
                                amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                   component=pg.id,
                                   populations=pop.id)
        input = nml.Input(id='0',
                          target="../%s[%i]" % (pop.id, i),
                          destination="synapses")
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s.net.nml' % sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)

    for i in range(number_cells):
        ref = "v_cell%i" % i
        quantity = "%s[%i]/v" % (pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV",
                               pynml.get_next_hex_color())

        ls.add_column_to_output_file(of0, ref, quantity)

    lems_file_name = ls.save_to_file()

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=plot_voltage_traces,
                                               show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=plot_voltage_traces,
                                                      show_plot_already=False)

    #print(results.keys())
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t']) * 1000
        v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= analysis_delay and s < (analysis_duration +
                                                analysis_delay):
                    count += 1
            freq = 1000 * count / float(analysis_duration)

        mean_freq = mean_spike_frequency(spike_times)
        # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq

        if freq == 0:
            iv_results[stims[i]] = v[-1]

    if plot_if:

        stims = sorted(if_results.keys())
        stims_pA = [ii * 1000 for ii in stims]

        freqs = [if_results[s] for s in stims]

        pynml.generate_plot([stims_pA], [freqs],
                            "Frequency versus injected current for: %s" %
                            nml2_file,
                            colors=['k'],
                            linestyles=['-'],
                            markers=['o'],
                            xaxis='Input current (pA)',
                            yaxis='Firing frequency (Hz)',
                            xlim=xlim_if,
                            ylim=ylim_if,
                            grid=True,
                            show_plot_already=False,
                            save_figure_to=save_if_figure_to)
    if plot_iv:

        stims = sorted(iv_results.keys())
        stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]

        pynml.generate_plot(
            [stims_pA], [vs],
            "Final membrane potential versus injected current for: %s" %
            nml2_file,
            colors=['k'],
            linestyles=['-'],
            markers=['o'],
            xaxis='Input current (pA)',
            yaxis='Membrane potential (mV)',
            xlim=xlim_iv,
            ylim=ylim_iv,
            grid=True,
            show_plot_already=False,
            save_figure_to=save_iv_figure_to)

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    return if_results
"""

Example to build a network using libNeuroML, save it as XML and validate it

"""


#########################################################

import neuroml

nml_doc = neuroml.NeuroMLDocument(id="simplenet")

net = neuroml.Network(id="simplenet")
nml_doc.networks.append(net)

# Create 2 populations
size0 = 5
size1 = 5

pop0 = neuroml.Population(id="Pop0", size = size0, component="myComponent")
net.populations.append(pop0)

p = neuroml.Property(tag="axes_to_plot_tuple", value="(1,1)")
pop0.properties.append(p)


pop1 = neuroml.Population(id="Pop1", size = size1, component="myComponent")
net.populations.append(pop1)

            
Пример #10
0
def create_GoC_network(duration=2000, dt=0.025, seed=123, runid=0, run=False):

    keepFile = open('useParams_FI_14_25.pkl', 'rb')
    runid = pkl.load(keepFile)[runid]
    keepFile.close()

    ### ---------- Component types
    gocID = 'Golgi_040408_C1_' + format(runid, '05d')
    goc_filename = '{}.cell.nml'.format(gocID)
    goc_type = pynml.read_neuroml2_file(goc_filename).cells[0]

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id='MorphoNet_' + format(runid, '05d'),
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=1)
    inst = nml.Instance(id=0)
    goc_pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(href=goc_filename))

    ### --------------  Write files

    net_filename = 'Morpho1_' + format(runid, '05d') + '.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_morpho1_' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
def create_GoC_network(duration=2000,
                       dt=0.025,
                       seed=123,
                       runid=0,
                       run=False,
                       minI=-75,
                       maxI=200,
                       iStep=25,
                       iDur=400,
                       iRest=500):

    file = open('useParams_SpontFreq_7_pm_2.pkl', 'rb')
    use_params = pkl.load(file)["useParams"]
    file.close()

    runid = use_params[0][runid]
    print('Using parameter set = ', runid)
    ### ---------- Component types
    gocID = 'GoC_' + format(runid, '05d')
    goc_filename = '{}.cell.nml'.format(gocID)
    goc_type = pynml.read_neuroml2_file(goc_filename).cells[0]

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id='GoCNet_' + format(runid, '05d'),
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=1)
    inst = nml.Instance(id=0)
    goc_pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(href=goc_filename))

    # Add Current Injection
    ctr = 0
    goc = 0
    p = {
        "iAmp": np.arange(minI, maxI + iStep / 2, iStep),
        "iDuration": iDur,
        "iRest": iRest
    }
    p["nSteps"] = p["iAmp"].shape[0]

    for jj in range(p["nSteps"]):
        input_id = 'stim_{}'.format(ctr)
        istep = nml.PulseGenerator(id=input_id,
                                   delay='{} ms'.format(p["iDuration"] * jj +
                                                        p["iRest"] * (jj + 1)),
                                   duration='{} ms'.format(p["iDuration"]),
                                   amplitude='{} pA'.format(p["iAmp"][jj]))
        net_doc.pulse_generators.append(istep)

        input_list = nml.InputList(id='ilist_{}'.format(ctr),
                                   component=istep.id,
                                   populations=goc_pop.id)
        curr_inj = nml.Input('0',
                             target="../%s[%i]" % (goc_pop.id, goc),
                             destination="synapses")
        input_list.input.append(curr_inj)
        net.input_lists.append(input_list)
        ctr += 1

    ### --------------  Write files

    net_filename = 'GoCNet_istep_' + format(runid, '05d') + '.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_gocnet_istep_' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
Пример #12
0
def create_GoC_network( duration, dt, seed, N_goc=0, run=False, prob_type='Boltzmann', GJw_type='Vervaeke2010' ):


	goc_filename = 'GoC.cell.nml'
	goc_file = pynml.read_neuroml2_file( goc_filename )
	goc_type = goc_file.cells[0]
	
	GJ_filename = 'GapJuncCML.nml'
	GJ_file = pynml.read_neuroml2_file( GJ_filename )
	GJ_type = GJ_file.gap_junctions[0]

	MFSyn_filename = 'MF_GoC_Syn.nml'
	mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename )
	MFSyn_type = mfsyn_file.exp_three_synapses[0]
	
	MF20Syn_filename = 'MF_GoC_SynMult.nml'
	mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename )
	MF20Syn_type = mf20syn_file.exp_three_synapses[0]
	
	# Distribute cells in 3D
	if N_goc>0:
		GoC_pos = nu.GoC_locate(N_goc)
	else:
		GoC_pos = nu.GoC_density_locate()
		N_goc = GoC_pos.shape[0]
		
	# get GJ connectivity
	GJ_pairs, GJWt = nu.GJ_conn( GoC_pos, prob_type, GJw_type )
	tmp1, tmp2 = valnet.gapJuncAnalysis( GJ_pairs, GJWt )
	print("Number of gap junctions per cell: ", tmp1)
	print("Net GJ conductance per cell:", tmp2)
	
	# Create pop List
	goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=N_goc )
	
	# Create NML document for network specification
	net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" )
	net_doc = nml.NeuroMLDocument( id=net.id )
	net_doc.networks.append( net )
	net_doc.includes.append( goc_type )
	
	net.populations.append( goc_pop )
	
	#Add locations for GoC instances in the population:
	for goc in range(N_goc):
		inst = nml.Instance( id=goc )
		goc_pop.instances.append( inst )
		inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2] )
		
	# Define input spiketrains
	input_type = 'spikeGenerator'#'spikeGeneratorPoisson'
	lems_inst_doc = lems.Model()
	mf_inputs = lems.Component( "MF_Input", input_type)
	mf_inputs.set_parameter("period", "2000 ms" )
	#mf_inputs.set_parameter("averageRate", "50 Hz")
	lems_inst_doc.add( mf_inputs )
	
	#synapse_type = 'alphaCurrentSynapse'
	#alpha_syn = lems.Component( "AlphaSyn", synapse_type)
	#alpha_syn.set_parameter("tau", "30 ms" )
	#alpha_syn.set_parameter("ibase", "200 pA")
	#lems_inst_doc.add( alpha_syn )
	
	# Define MF input population
	
	N_mf = 15
	#MF_pop = nml.Population(id=mf_inputs.id+"_pop", component=mf_inputs.id, type="populationList", size=N_mf)
	#net.populations.append( MF_pop )

	mf_type2 = 'spikeGeneratorPoisson'
	#mf_poisson = lems.Component( "MF_Poisson", mf_type2)
	#mf_poisson.set_parameter("averageRate", "5 Hz")
	#lems_inst_doc.add( mf_poisson )
	# adding in neuroml document instead of mf_poisson
	mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" )
	net_doc.spike_generator_poissons.append( mf_poisson )
	
	net_doc.includes.append( goc_type )
	MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=N_mf)
	net.populations.append( MF_Poisson_pop )
	MF_pos = nu.GoC_locate( N_mf )
	for mf in range( N_mf ):
		inst = nml.Instance(id=mf)
		MF_Poisson_pop.instances.append( inst )
		inst.location = nml.Location( x=MF_pos[mf,0], y=MF_pos[mf,1], z=MF_pos[mf,2] )
		
	# Setup Mf->GoC synapses
	#MFprojection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_pop.id, postsynaptic_population=goc_pop.id, synapse=alpha_syn.id)
	#net.projections.append(MFprojection)

	MF2projection = nml.Projection(id="MF2toGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id)#alpha_syn.id
	net.projections.append(MF2projection)


	#Get list of MF->GoC synapse
	mf_synlist = nu.randdist_MF_syn( N_mf, N_goc, pConn=0.3)
	nMFSyn = mf_synlist.shape[1]
	for syn in range( nMFSyn ):
		mf, goc = mf_synlist[:, syn]
		conn2 = nml.Connection(id=syn, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)
		
		
	# Burst of MF input (as explicit input)
	mf_bursttype = 'transientPoissonFiringSynapse'
	mf_burst = lems.Component( "MF_Burst", mf_bursttype)
	mf_burst.set_parameter( "averageRate", "100 Hz" )
	mf_burst.set_parameter( "delay", "2000 ms" )
	mf_burst.set_parameter( "duration", "500 ms" )
	mf_burst.set_parameter( "synapse", MF20Syn_type.id )
	mf_burst.set_parameter( "spikeTarget", './{}'.format(MF20Syn_type.id) )
	lems_inst_doc.add( mf_burst )
	
	
	# Add few burst inputs
	n_bursts = 4
	gocPerm = np.random.permutation( N_goc )
	ctr = 0
	for gg in range(4):
		goc = gocPerm[gg]
		for jj in range( n_bursts ):
			inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id))
			net.explicit_inputs.append( inst )
			ctr += 1
		
	
	'''
	one-to-one pairing of MF and GoC -> no shared inputs
	for goc in range(N_mf):
		#inst = nml.Instance(id=goc)
		#MF_pop.instances.append( inst )
		#inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2]+100 )
		#conn = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_pop.id, goc, mf_inputs.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		#MFprojection.connections.append(conn)

		goc2 = N_goc-goc-1
		inst2 = nml.Instance(id=goc)
		MF_Poisson_pop.instances.append( inst2 )
		inst2.location = nml.Location( x=GoC_pos[goc2,0], y=GoC_pos[goc2,1], z=GoC_pos[goc2,2]+100 )
		conn2 = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, goc, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc2, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)

	'''
	
	# Add electrical synapses
	GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id )
	
	#print(GJ_pairs)
	gj = nml.GapJunction( id="GJ_0", conductance="426pS" )
	net_doc.gap_junctions.append(gj)
	nGJ = GJ_pairs.shape[0]
	for jj in range( nGJ ):
		#gj.append( lems.Component( "GJ_%d"%jj, 'gapJunction') )
		#gj[jj].set_parameter( "conductance", "%fnS"%(GJWt[jj]) )
		#gj = nml.GapJunction(id="GJ_%d"%jj, conductance="%fnS"%(GJWt[jj]))
		#net_doc.gap_junctions.append(gj)
		#lems_inst_doc.add( gj[jj] )
		#print("%fnS"%(GJWt[jj]*0.426))
		conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,0], goc_type.id), pre_segment='1', pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,1], goc_type.id), post_segment='1', post_fraction_along='0.5', synapse=gj.id, weight=GJWt[jj] )#synapse="GapJuncCML" synapse=gj.id , conductance="100E-9mS"
		# ------------ need to create GJ component
		GoCCoupling.electrical_connection_instance_ws.append( conn )
	
	net.electrical_projections.append( GoCCoupling )	
		
		
		
	net_filename = 'gocNetwork.nml'
	pynml.write_neuroml2_file( net_doc, net_filename )
	lems_filename = 'instances.xml'
	pynml.write_lems_file( lems_inst_doc, lems_filename, validate=False )

	simid = 'sim_gocnet'+goc_type.id
	ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed )
	ls.assign_simulation_target( net.id )
	
	#ls.include_lems_file( 'Synapses.xml', include_included=False)
	#ls.include_lems_file( 'Inputs.xml', include_included=False)
	ls.include_neuroml2_file( net_filename)
	ls.include_neuroml2_file( goc_filename)
	ls.include_neuroml2_file( GJ_filename)
	ls.include_neuroml2_file( MFSyn_filename)
	ls.include_neuroml2_file( MF20Syn_filename)
	ls.include_lems_file( lems_filename, include_included=False)
	
	
	# Specify outputs
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	for jj in range( goc_pop.size):
		ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' )
		
	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	for jj in range( goc_pop.size ):
		ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id))
		
	#Create Lems file to run
	lems_simfile = ls.save_to_file()

	#res = pynml.run_lems_with_jneuroml( lems_simfile, max_memory="1G",nogui=True, plot=False)
	#res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", compile_mods = False,nogui=True, plot=False)
	#res=True
	return res
Пример #13
0
                                 synapse=syn1.id,
                                 spike_target="./%s" % syn1.id)
tsi.spikes.append(neuroml.Spike(id="0", time="100ms"))
tsi.spikes.append(neuroml.Spike(id="1", time="500ms"))
tsi.spikes.append(neuroml.Spike(id="2", time="700ms"))
tsi.spikes.append(neuroml.Spike(id="3", time="705ms"))
nml_doc.timed_synaptic_inputs.append(tsi)

# Include cell

cell_id = 'pyr_4_sym'

nml_doc.includes.append(neuroml.IncludeType('%s.cell.nml' % cell_id))

# Create network
net = neuroml.Network(id=ref + "_network")
nml_doc.networks.append(net)

# Create populations
size0 = 3
pyr_cells_pop0 = neuroml.Population(id="PoissonFiringSynCells",
                                    size=size0,
                                    component=cell_id)
net.populations.append(pyr_cells_pop0)

size1 = 3
pyr_cells_pop1 = neuroml.Population(id="SpikeArrayCells",
                                    size=size1,
                                    component=cell_id)
net.populations.append(pyr_cells_pop1)
def generate_grc_layer_network(
        runID,
        correlationRadius,
        NADT,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz
        OFFRate,  # Hz
        run=False):
    ########################################
    # Load parameters for this run
    file = open('../params_file.pkl', 'r')
    p = pkl.load(file)
    N_syn = p['N_syn'][int(runID) - 1]
    f_mf = p['f_mf'][int(runID) - 1]
    run_num = p['run_num'][int(runID) - 1]
    file.close()
    #################################################################################
    # Get connectivity matrix between cells
    file = open('../../network_structures/GCLconnectivity_' + str(N_syn) +
                '.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == N_syn)), 'Connectivity matrix is incorrect.'
    # Get MF activity pattern
    if correlationRadius == 0:  # Activate MFs randomly
        N_mf_ON = int(N_mf * f_mf)
        mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
        mf_indices_ON.sort()
    elif correlationRadius > 0:  # Spatially correlated MFs
        f_mf_range = np.linspace(.05, .95, 19)
        f_mf_ix = np.where(f_mf_range == f_mf)[0][0]
        p = io.loadmat('../../input_statistics/mf_patterns_r' +
                       str(correlationRadius) + '.mat')
        R = p['Rs'][:, :, f_mf_ix]
        g = p['gs'][f_mf_ix]
        t = np.dot(R.transpose(), np.random.randn(N_mf))
        S = (t > -g * np.ones(N_mf))
        mf_indices_ON = np.where(S)[0]
        N_mf_ON = len(mf_indices_ON)
    #
    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()
    #################################################################################
    # load NeuroML components, LEMS components and LEMS componentTypes from external files
    # Spike generator (for Poisson MF spiking)
    spike_generator_file_name = "../../grc_lemsDefinitions/spikeGenerators.xml"
    spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)
    # Integrate-and-fire GC model
    # if NADT = 1, loads model GC
    iaf_nml2_file_name = "../../grc_lemsDefinitions/IaF_GrC.nml" if NADT == 0 else "../../grc_lemsDefinitions/IaF_GrC_" + '{:.2f}'.format(
        f_mf) + ".nml"
    iaF_GrC_doc = pynml.read_neuroml2_file(iaf_nml2_file_name)
    iaF_GrC = iaF_GrC_doc.iaf_ref_cells[0]
    # AMPAR and NMDAR mediated synapses
    ampa_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCAMPA_" + str(
        N_syn) + ".xml"
    nmda_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCNMDA_" + str(
        N_syn) + ".xml"
    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)
    #
    # Define components from the componentTypes we just loaded
    # Refractory poisson input -- representing active MF
    spike_generator_ref_poisson_type = spike_generator_doc.component_types[
        'spikeGeneratorRefPoisson']
    lems_instances_doc = lems.Model()
    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type.name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)
    # Refractory poisson input -- representing silent MF
    spike_generator_off = lems.Component("mossySpikerOFF",
                                         spike_generator_ref_poisson_type.name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)
    # Synapses
    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id
    #
    # Create ON MF, OFF MF, and GC populations
    GrCPop = nml.Population(id="GrCPop", component=iaF_GrC.id, size=N_grc)
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       size=N_mf_ON)
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    #
    # Create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)
    #
    # MF-GC connectivity
    # First connect ON MFs to GCs
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopON.id, mf_ix_ON),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Now connect OFF MFs to GCs
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopOFF.id, mf_ix_OFF),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Write network to file
    net_file_name = 'generated_network_' + runID + '.net.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)
    # Write LEMS instances to file
    lems_instances_file_name = 'instances_' + runID + '.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)
    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation('sim_' + runID,
                        duration,
                        dt,
                        lems_seed=int(np.round(1000 * random.random())))
    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)
    # Include generated/existing NeuroML2 files
    ls.include_neuroml2_file(iaf_nml2_file_name)
    ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)
    # Specify Displays and Output Files
    # Details for saving output files
    basedir = '../data_r' + str(
        correlationRadius) + '/' if NADT == 0 else '../data_r' + str(
            correlationRadius) + '_NADT/'
    end_filename = str(N_syn) + '_{:.2f}'.format(f_mf) + '_' + str(
        run_num)  # Add parameter values to spike time filename
    # Save MF spike times under basedir + MF_spikes_ + end_filename
    eof0 = 'MFspikes_file'
    ls.create_event_output_file(eof0,
                                basedir + "MF_spikes_" + end_filename + ".dat")
    # ON MFs
    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], "%s[%i]" % (mossySpikersPopON.id, i),
            'spike')
    # OFF MFs
    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i], "%s[%i]" % (mossySpikersPopOFF.id, i),
            'spike')
    # Save GC spike times under basedir + GrC_spikes_ + end_filename
    eof1 = 'GrCspikes_file'
    ls.create_event_output_file(
        eof1, basedir + "GrC_spikes_" + end_filename + ".dat")
    #
    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(eof1, i,
                                              "%s[%i]" % (GrCPop.id, i),
                                              'spike')
    #
    lems_file_name = ls.save_to_file()
    #
    if run:
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results
Пример #15
0
def create_GoC_network( duration, dt, seed, runid, run=False):

	### ---------- Load Params
	noPar = True
	pfile = Path('params_file.pkl')
	if pfile.exists():
		print('Reading parameters from file:')
		file = open('params_file.pkl','rb')
		params_list = pkl.load(file)
		if len(params_list)>runid:
			p = params_list[runid]
			file.close()
	if noPar:
		p = inp.get_simulation_params( runid )
    
	### ---------- Component types
	goc_filename = 'GoC.cell.nml'							# Golgi cell with channels
	goc_file = pynml.read_neuroml2_file( goc_filename )
	goc_type = goc_file.cells[0]
	goc_ref = nml.IncludeType( href=goc_filename )

	MFSyn_filename = 'MF_GoC_Syn.nml'						# small conductance synapse for background inputs
	mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename )
	MFSyn_type = mfsyn_file.exp_three_synapses[0]
	mfsyn_ref = nml.IncludeType( href=MFSyn_filename )
	
	MF20Syn_filename = 'MF_GoC_SynMult.nml'					# multi-syn conductance for strong/coincident transient input
	mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename )
	MF20Syn_type = mf20syn_file.exp_three_synapses[0]
	mf20syn_ref = nml.IncludeType( href=MF20Syn_filename )

	mf_type2 = 'spikeGeneratorPoisson'						# Spike source for background inputs
	mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" )	# Not tuned to any data - qqq !
	
	mf_bursttype = 'transientPoissonFiringSynapse'			# Burst of MF input (as explicit input)
	mf_burst = nml.TransientPoissonFiringSynapse( id="MF_Burst", average_rate="100 Hz", delay="2000 ms", duration="500 ms", synapse=MF20Syn_type.id, spike_target='./{}'.format(MF20Syn_type.id) )

	gj = nml.GapJunction( id="GJ_0", conductance="426pS" )	# GoC synapse
	
	### --------- Populations

	# Build network to specify cells and connectivity
	net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" )
		
	# Create GoC population
	goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=p["nGoC"] )
	for goc in range( p["nGoC"] ):
		inst = nml.Instance( id=goc )
		goc_pop.instances.append( inst )
		inst.location = nml.Location( x=p["GoC_pos"][goc,0], y=p["GoC_pos"][goc,1], z=p["GoC_pos"][goc,2] )
	net.populations.append( goc_pop )


	### MF population
	MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=p["nMF"])
	for mf in range( p["nMF"] ):
		inst = nml.Instance(id=mf)
		MF_Poisson_pop.instances.append( inst )
		inst.location = nml.Location( x=p["MF_pos"][mf,0], y=p["MF_pos"][mf,1], z=p["MF_pos"][mf,2] )		
	net.populations.append( MF_Poisson_pop )
	
	# Create NML document for network specification
	net_doc = nml.NeuroMLDocument( id=net.id )
	net_doc.networks.append( net )
	net_doc.includes.append( goc_ref )
	net_doc.includes.append( mfsyn_ref )
	net_doc.includes.append( mf20syn_ref )
	net_doc.spike_generator_poissons.append( mf_poisson )	
	net_doc.transient_poisson_firing_synapses.append( mf_burst )
	net_doc.gap_junctions.append(gj)
	
	
	### ------------ Connectivity

	### 1. Background excitatory inputs: 	MF to GoC populations
	MFProjection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id)
	net.projections.append(MFProjection)

	# MF_> GoC synapses (with syn_count equivalent to integer scaling of Mf synapse strength)
	nMFSyn = p["MF_GoC_pairs"].shape[1]
	ctr=0
	for syn in range( nMFSyn ):
		mf, goc = p["MF_GoC_pairs"][:, syn]
		for syn_count in range(p["MF_GoC_wt"][ctr]):
			conn2 = nml.Connection(id=ctr, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")	#on soma
			MFProjection.connections.append(conn2)
			ctr+=1

	### 2. Perturbation as High Freq MF Inputs
	ctr=0
	for goc in p["Burst_GoC"]:
		for jj in range( p["nBurst"] ):				# Each Perturbed GoC gets nBurst random Burst sources
			inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id))
			net.explicit_inputs.append( inst )
			ctr += 1

	### 3. Electrical coupling between GoCs
		
	GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id )
	net.electrical_projections.append( GoCCoupling )
	dend_id = [1,2,5]
	for jj in range( p["GJ_pairs"].shape[0] ):
		conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,0], goc_type.id), pre_segment=dend_id[p["GJ_loc"][jj,0]], pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,1], goc_type.id), post_segment=dend_id[p["GJ_loc"][jj,1]], post_fraction_along='0.5', synapse=gj.id, weight=p["GJ_wt"][jj] )
		GoCCoupling.electrical_connection_instance_ws.append( conn )
		
		
	### --------------  Write files
		
	net_filename = 'gocNetwork.nml'
	pynml.write_neuroml2_file( net_doc, net_filename )

	simid = 'sim_gocnet_'+goc_type.id+'_run_{}'.format(runid)
	ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed )
	ls.assign_simulation_target( net.id )
	ls.include_neuroml2_file( net_filename)
	ls.include_neuroml2_file( goc_filename)
	ls.include_neuroml2_file( MFSyn_filename)
	ls.include_neuroml2_file( MF20Syn_filename)
	
	
	# Specify outputs
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	for jj in range( goc_pop.size):
		ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' )
		
	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	for jj in range( goc_pop.size ):
		ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id))
		
	#Create Lems file to run
	lems_simfile = ls.save_to_file()

	if run:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", nogui=True, plot=False)
	else:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	
	
	return res
def create_GoC_network(duration, dt, seed, runid, run=False):

    ### ---------- Load Params
    noPar = True
    pfile = Path('params_file.pkl')
    if pfile.exists():
        print('Reading parameters from file:')
        file = open('params_file.pkl', 'rb')
        params_list = pkl.load(file)
        if len(params_list) > runid:
            p = params_list[runid]
            file.close()
    if noPar:
        p = inp.get_simulation_params(runid)

    ### ---------- Component types
    goc_filename = 'GoC.cell.nml'  # Golgi cell with channels
    goc_file = pynml.read_neuroml2_file(goc_filename)
    goc_type = goc_file.cells[0]
    goc_ref = nml.IncludeType(href=goc_filename)

    gj = nml.GapJunction(id="GJ_0", conductance="426pS")  # GoC synapse

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id="gocNetwork",
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=p["nGoC"])
    for goc in range(p["nGoC"]):
        inst = nml.Instance(id=goc)
        goc_pop.instances.append(inst)
        inst.location = nml.Location(x=p["GoC_pos"][goc, 0],
                                     y=p["GoC_pos"][goc, 1],
                                     z=p["GoC_pos"][goc, 2])
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(goc_ref)
    net_doc.gap_junctions.append(gj)

    ### ------------ Connectivity

    ### 1. Input Current to one cell
    ctr = 0
    for goc in p["Test_GoC"]:
        for jj in range(p["nSteps"]):
            input_id = 'stim_{}'.format(ctr)
            istep = nml.PulseGenerator(
                id=input_id,
                delay='{} ms'.format(p["iDuration"] * jj + p["iRest"] *
                                     (jj + 1)),
                duration='{} ms'.format(p["iDuration"]),
                amplitude='{} pA'.format(p["iAmp"][jj]))
            net_doc.pulse_generators.append(istep)

            input_list = nml.InputList(id='ilist_{}'.format(ctr),
                                       component=istep.id,
                                       populations=goc_pop.id)
            curr_inj = nml.Input('0',
                                 target="../%s[%i]" % (goc_pop.id, goc),
                                 destination="synapses")
            input_list.input.append(curr_inj)
            net.input_lists.append(input_list)
            ctr += 1

    ### 2. Electrical coupling between GoCs

    GoCCoupling = nml.ElectricalProjection(id="gocGJ",
                                           presynaptic_population=goc_pop.id,
                                           postsynaptic_population=goc_pop.id)
    net.electrical_projections.append(GoCCoupling)
    dend_id = [1, 2, 5]
    for jj in range(p["GJ_pairs"].shape[0]):
        conn = nml.ElectricalConnectionInstanceW(
            id=jj,
            pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 0],
                                          goc_type.id),
            pre_segment=dend_id[p["GJ_loc"][jj, 0]],
            pre_fraction_along='0.5',
            post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 1],
                                           goc_type.id),
            post_segment=dend_id[p["GJ_loc"][jj, 1]],
            post_fraction_along='0.5',
            synapse=gj.id,
            weight=p["GJ_wt"][jj])
        GoCCoupling.electrical_connection_instance_ws.append(conn)

    ### --------------  Write files

    net_filename = 'gocNetwork.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_gocnet_' + goc_type.id + '_run_{}'.format(runid)
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    ctr = 0
    for jj in p["Test_GoC"]:
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, ctr, goc_type.id))
        ctr += 1

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
Пример #17
0
pp = pprint.PrettyPrinter(depth=6)

if __name__ == '__main__':

    root_dir = 'test_data/ca1'
    cell_file = 'cells/olm.cell.nml'
    cell_comp = 'olmcell'
    reference = 'TestOLMChannels'

    nml_doc = neuroml.NeuroMLDocument(id=reference)

    incl = neuroml.IncludeType(cell_file)
    nml_doc.includes.append(incl)

    net = neuroml.Network(id=reference)
    net.notes = "A test network model: %s" % reference
    net.temperature = '35degC'

    nml_doc.networks.append(net)

    pop = neuroml.Population(id="%sPop" % cell_comp,
                             component=cell_comp,
                             size=1,
                             type="populationList")

    inst = neuroml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = neuroml.Location(x=0, y=0, z=0)

    net.populations.append(pop)
Пример #18
0
def generate_Vm_vs_time_plot(nml2_file,
                             cell_id,
                             inj_amp_nA=80,
                             delay_ms=20,
                             inj_dur_ms=60,
                             sim_dur_ms=100,
                             dt=0.05,
                             plot_voltage_traces=False,
                             show_plot_already=True,
                             simulator="jNeuroML",
                             include_included=True):

    ref = "Test"
    print_comment_v(
        "Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"
        % (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms))

    sim_id = 'Vm_%s' % ref
    duration = sim_dur_ms
    ls = LEMSSimulation(sim_id, sim_dur_ms, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)
    ls.assign_simulation_target('network')
    nml_doc = nml.NeuroMLDocument(id=cell_id)

    nml_doc.includes.append(nml.IncludeType(href=nml2_file))

    net = nml.Network(id="network")
    nml_doc.networks.append(net)

    input_id = ("input_%s" % str(inj_amp_nA).replace('.', '_'))
    pg = nml.PulseGenerator(id=input_id,
                            delay="%sms" % delay_ms,
                            duration='%sms' % inj_dur_ms,
                            amplitude='%spA' % inj_amp_nA)
    nml_doc.pulse_generators.append(pg)

    pop_id = 'hhpop'
    pop = nml.Population(id=pop_id,
                         component='hhcell',
                         size=1,
                         type="populationList")

    inst = nml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(pop)

    # Add these to cells
    input_list = nml.InputList(id='il_%s' % input_id,
                               component=pg.id,
                               populations=pop_id)
    input = nml.Input(id='0',
                      target='../hhpop/0/hhcell',
                      destination="synapses")

    input_list.input.append(input)
    net.input_lists.append(input_list)

    sim_file_name = '%s.sim.nml' % sim_id
    pynml.write_neuroml2_file(nml_doc, sim_file_name)
    ls.include_neuroml2_file(sim_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)
    ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v")

    lems_file_name = ls.save_to_file()

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=plot_voltage_traces,
                                               show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=plot_voltage_traces,
                                                      show_plot_already=False)

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    return of0
Пример #19
0
def create_GoC_network(duration,
                       dt,
                       seed,
                       N_goc=0,
                       N_mf=15,
                       run=False,
                       prob_type='Boltzmann',
                       GJw_type='Vervaeke2010'):

    ### ---------- Component types
    goc_filename = 'GoC.cell.nml'  # Golgi cell with channels
    goc_file = pynml.read_neuroml2_file(goc_filename)
    goc_type = goc_file.cells[0]
    goc_ref = nml.IncludeType(href=goc_filename)

    MFSyn_filename = 'MF_GoC_Syn.nml'  # small conductance synapse for background inputs
    mfsyn_file = pynml.read_neuroml2_file(MFSyn_filename)
    MFSyn_type = mfsyn_file.exp_three_synapses[0]
    mfsyn_ref = nml.IncludeType(href=MFSyn_filename)

    MF20Syn_filename = 'MF_GoC_SynMult.nml'  # multi-syn conductance for strong/coincident transient input
    mf20syn_file = pynml.read_neuroml2_file(MF20Syn_filename)
    MF20Syn_type = mf20syn_file.exp_three_synapses[0]
    mf20syn_ref = nml.IncludeType(href=MF20Syn_filename)

    mf_type2 = 'spikeGeneratorPoisson'  # Spike source for background inputs
    mf_poisson = nml.SpikeGeneratorPoisson(
        id="MF_Poisson", average_rate="5 Hz")  # Not tuned to any data - qqq !

    mf_bursttype = 'transientPoissonFiringSynapse'  # Burst of MF input (as explicit input)
    mf_burst = nml.TransientPoissonFiringSynapse(id="MF_Burst",
                                                 average_rate="100 Hz",
                                                 delay="2000 ms",
                                                 duration="500 ms",
                                                 synapse=MF20Syn_type.id,
                                                 spike_target='./{}'.format(
                                                     MF20Syn_type.id))

    gj = nml.GapJunction(id="GJ_0", conductance="426pS")  # GoC synapse

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id="gocNetwork",
                      type="networkWithTemperature",
                      temperature="23 degC")

    ### Golgi cells
    if N_goc > 0:
        GoC_pos = nu.GoC_locate(N_goc)
    else:
        GoC_pos = nu.GoC_density_locate()
        N_goc = GoC_pos.shape[0]

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=N_goc)
    for goc in range(N_goc):
        inst = nml.Instance(id=goc)
        goc_pop.instances.append(inst)
        inst.location = nml.Location(x=GoC_pos[goc, 0],
                                     y=GoC_pos[goc, 1],
                                     z=GoC_pos[goc, 2])
    net.populations.append(goc_pop)

    ### MF population
    MF_Poisson_pop = nml.Population(id=mf_poisson.id + "_pop",
                                    component=mf_poisson.id,
                                    type="populationList",
                                    size=N_mf)
    MF_pos = nu.GoC_locate(N_mf)
    for mf in range(N_mf):
        inst = nml.Instance(id=mf)
        MF_Poisson_pop.instances.append(inst)
        inst.location = nml.Location(x=MF_pos[mf, 0],
                                     y=MF_pos[mf, 1],
                                     z=MF_pos[mf, 2])
    net.populations.append(MF_Poisson_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(goc_ref)
    net_doc.includes.append(mfsyn_ref)
    net_doc.includes.append(mf20syn_ref)
    net_doc.spike_generator_poissons.append(mf_poisson)
    net_doc.transient_poisson_firing_synapses.append(mf_burst)
    net_doc.gap_junctions.append(gj)

    ### ------------ Connectivity

    ### background excitatory inputs: 	MF to GoC populations
    MFProjection = nml.Projection(id="MFtoGoC",
                                  presynaptic_population=MF_Poisson_pop.id,
                                  postsynaptic_population=goc_pop.id,
                                  synapse=MFSyn_type.id)
    net.projections.append(MFProjection)

    #Get list of MF->GoC synapse
    mf_synlist = nu.randdist_MF_syn(N_mf, N_goc,
                                    pConn=0.3)  # Not tuned to any data - qqq!
    nMFSyn = mf_synlist.shape[1]
    for syn in range(nMFSyn):
        mf, goc = mf_synlist[:, syn]
        conn2 = nml.Connection(
            id=syn,
            pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf,
                                             mf_poisson.id),
            post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id),
            post_segment_id='0',
            post_fraction_along="0.5")  #on soma
        MFProjection.connections.append(conn2)

    ### Add few burst inputs
    n_bursts = 4
    gocPerm = np.random.permutation(
        N_goc)  # change to central neurons later -qqq !!!
    ctr = 0
    for gg in range(4):
        goc = gocPerm[gg]
        for jj in range(n_bursts):
            inst = nml.ExplicitInput(
                id=ctr,
                target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id),
                input=mf_burst.id,
                synapse=MF20Syn_type.id,
                spikeTarget='./{}'.format(MF20Syn_type.id))
            net.explicit_inputs.append(inst)
            ctr += 1

    ### Electrical coupling between GoCs

    # get GJ connectivity
    GJ_pairs, GJWt = nu.GJ_conn(GoC_pos, prob_type, GJw_type)
    #tmp1, tmp2 = valnet.gapJuncAnalysis( GJ_pairs, GJWt )
    #print("Number of gap junctions per cell: ", tmp1)
    #print("Net GJ conductance per cell:", tmp2)

    # Add electrical synapses
    GoCCoupling = nml.ElectricalProjection(id="gocGJ",
                                           presynaptic_population=goc_pop.id,
                                           postsynaptic_population=goc_pop.id)
    nGJ = GJ_pairs.shape[0]
    for jj in range(nGJ):
        conn = nml.ElectricalConnectionInstanceW(
            id=jj,
            pre_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj, 0],
                                          goc_type.id),
            pre_segment='1',
            pre_fraction_along='0.5',
            post_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj, 1],
                                           goc_type.id),
            post_segment='1',
            post_fraction_along='0.5',
            synapse=gj.id,
            weight=GJWt[jj])
        GoCCoupling.electrical_connection_instance_ws.append(conn)
    net.electrical_projections.append(GoCCoupling)

    ### --------------  Write files

    net_filename = 'gocNetwork.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)
    #lems_filename = 'instances.xml'
    #pynml.write_lems_file( lems_inst_doc, lems_filename, validate=False )

    simid = 'sim_gocnet' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)

    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)
    ls.include_neuroml2_file(MFSyn_filename)
    ls.include_neuroml2_file(MF20Syn_filename)
    #ls.include_lems_file( lems_filename, include_included=False)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
def generate_network_for_sweeps(cell_type, dataset_id, cell_file_name, cell_id, target_dir, data_dir="../../data"):

    target_sweep_numbers = DH.DATASET_TARGET_SWEEPS[dataset_id]

    net_id = "network_%s_%s"%(dataset_id, cell_type)
    net = neuroml.Network(id=net_id, type="networkWithTemperature", temperature=DH.SIMULATION_TEMPERATURE)


    net_doc = neuroml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)

    net_doc.includes.append(neuroml.IncludeType(cell_file_name))


    number_cells = len(target_sweep_numbers)
    pop = neuroml.Population(id="Pop0",
                        component=cell_id,
                        size=number_cells,
                        type="populationList")
                        
    net.populations.append(pop)
    for i in range(number_cells):
        location = neuroml.Location(x=100*i,y=0,z=0)
        pop.instances.append(neuroml.Instance(id=i,location=location))

    print target_sweep_numbers
    f = "%s/%s_analysis.json"%(data_dir,dataset_id)
    with open(f, "r") as json_file:
        data = json.load(json_file) 

    id = data['data_set_id']
    sweeps = data['sweeps']

    print("Looking at data analysis in %s (dataset: %s)"%(f,id))

    index = 0
    for s in target_sweep_numbers:
        current = float(sweeps['%i'%s]["sweep_metadata"]["aibs_stimulus_amplitude_pa"])
        print("Sweep %s (%s pA)"%(s, current))

        stim_amp = "%s pA"%current
        input_id = ("input_%i"%s)
        pg = neuroml.PulseGenerator(id=input_id,
                                    delay="270ms",
                                    duration="1000ms",
                                    amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        input_list = neuroml.InputList(id=input_id,
                                 component=pg.id,
                                 populations=pop.id)
        input = neuroml.Input(id='0', 
                              target="../%s/%i/%s"%(pop.id, index, cell_id), 
                              destination="synapses")
        index+=1
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s/%s.net.nml'%(target_dir,net_id)
    
    print("Saving generated network to: %s"%net_file_name)
    pynml.write_neuroml2_file(net_doc, net_file_name)
    
    return net_file_name
Пример #21
0
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
Пример #22
0
def generate_current_vs_frequency_curve(nml2_file,
                                        cell_id,
                                        start_amp_nA=-0.1,
                                        end_amp_nA=0.1,
                                        step_nA=0.01,
                                        custom_amps_nA=[],
                                        analysis_duration=1000,
                                        analysis_delay=0,
                                        pre_zero_pulse=0,
                                        post_zero_pulse=0,
                                        dt=0.05,
                                        temperature="32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        plot_if=True,
                                        plot_iv=False,
                                        xlim_if=None,
                                        ylim_if=None,
                                        xlim_iv=None,
                                        ylim_iv=None,
                                        label_xaxis=True,
                                        label_yaxis=True,
                                        show_volts_label=True,
                                        grid=True,
                                        font_size=12,
                                        if_iv_color='k',
                                        linewidth=1,
                                        bottom_left_spines_only=False,
                                        show_plot_already=True,
                                        save_voltage_traces_to=None,
                                        save_if_figure_to=None,
                                        save_iv_figure_to=None,
                                        save_if_data_to=None,
                                        save_iv_data_to=None,
                                        simulator="jNeuroML",
                                        num_processors=1,
                                        include_included=True,
                                        title_above_plot=False,
                                        return_axes=False,
                                        verbose=False):

    print_comment(
        "Running generate_current_vs_frequency_curve() on %s (%s)" %
        (nml2_file, os.path.abspath(nml2_file)), verbose)
    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np
    traces_ax = None
    if_ax = None
    iv_ax = None

    sim_id = 'iv_%s' % cell_id
    total_duration = pre_zero_pulse + analysis_duration + analysis_delay + post_zero_pulse
    pulse_duration = analysis_duration + analysis_delay
    end_stim = pre_zero_pulse + analysis_duration + analysis_delay
    ls = LEMSSimulation(sim_id, total_duration, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)

    stims = []
    if len(custom_amps_nA) > 0:
        stims = [float(a) for a in custom_amps_nA]
        stim_info = ['%snA' % float(a) for a in custom_amps_nA]
    else:
        amp = start_amp_nA
        while amp <= end_amp_nA:
            stims.append(amp)
            amp += step_nA

        stim_info = '(%snA->%snA; %s steps of %snA; %sms)' % (
            start_amp_nA, end_amp_nA, len(stims), step_nA, total_duration)

    print_comment_v("Generating an IF curve for cell %s in %s using %s %s" %
                    (cell_id, nml2_file, simulator, stim_info))

    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s" % cell_id,
                         component=cell_id,
                         size=number_cells)

    # create network and add populations
    net_id = "network_of_%s" % cell_id
    net = nml.Network(id=net_id,
                      type="networkWithTemperature",
                      temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA" % stims[i]
        input_id = ("input_%s" % stim_amp).replace('.',
                                                   '_').replace('-', 'min')
        pg = nml.PulseGenerator(id=input_id,
                                delay="%sms" % pre_zero_pulse,
                                duration="%sms" % pulse_duration,
                                amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                   component=pg.id,
                                   populations=pop.id)
        input = nml.Input(id='0',
                          target="../%s[%i]" % (pop.id, i),
                          destination="synapses")
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s.net.nml' % sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)

    for i in range(number_cells):
        ref = "v_cell%i" % i
        quantity = "%s[%i]/v" % (pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV",
                               pynml.get_next_hex_color())

        ls.add_column_to_output_file(of0, ref, quantity)

    lems_file_name = ls.save_to_file()

    print_comment(
        "Written LEMS file %s (%s)" %
        (lems_file_name, os.path.abspath(lems_file_name)), verbose)

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=False,
                                               show_plot_already=False,
                                               verbose=verbose)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=False,
                                                      show_plot_already=False,
                                                      verbose=verbose)
    elif simulator == "jNeuroML_NetPyNE":
        results = pynml.run_lems_with_jneuroml_netpyne(
            lems_file_name,
            nogui=True,
            load_saved_data=True,
            plot=False,
            show_plot_already=False,
            num_processors=num_processors,
            verbose=verbose)
    else:
        raise Exception(
            "Sorry, cannot yet run current vs frequency analysis using simulator %s"
            % simulator)

    print_comment(
        "Completed run in simulator %s (results: %s)" %
        (simulator, results.keys()), verbose)

    #print(results.keys())
    times_results = []
    volts_results = []
    volts_labels = []
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t']) * 1000
        v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000

        if plot_voltage_traces:
            times_results.append(t)
            volts_results.append(v)
            volts_labels.append("%s nA" % stims[i])

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= pre_zero_pulse + analysis_delay and s < (
                        pre_zero_pulse + analysis_duration + analysis_delay):
                    count += 1
            freq = 1000 * count / float(analysis_duration)

        mean_freq = mean_spike_frequency(spike_times)
        #print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq

        if freq == 0:
            if post_zero_pulse == 0:
                iv_results[stims[i]] = v[-1]
            else:
                v_end = None
                for j in range(len(t)):
                    if v_end == None and t[j] >= end_stim:
                        v_end = v[j]
                iv_results[stims[i]] = v_end

    if plot_voltage_traces:

        traces_ax = pynml.generate_plot(
            times_results,
            volts_results,
            "Membrane potential traces for: %s" % nml2_file,
            xaxis='Time (ms)' if label_xaxis else ' ',
            yaxis='Membrane potential (mV)' if label_yaxis else '',
            xlim=[total_duration * -0.05, total_duration * 1.05],
            show_xticklabels=label_xaxis,
            font_size=font_size,
            bottom_left_spines_only=bottom_left_spines_only,
            grid=False,
            labels=volts_labels if show_volts_label else [],
            show_plot_already=False,
            save_figure_to=save_voltage_traces_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

    if plot_if:

        stims = sorted(if_results.keys())
        stims_pA = [ii * 1000 for ii in stims]

        freqs = [if_results[s] for s in stims]

        if_ax = pynml.generate_plot(
            [stims_pA], [freqs],
            "Firing frequency versus injected current for: %s" % nml2_file,
            colors=[if_iv_color],
            linestyles=['-'],
            markers=['o'],
            linewidths=[linewidth],
            xaxis='Input current (pA)' if label_xaxis else ' ',
            yaxis='Firing frequency (Hz)' if label_yaxis else '',
            xlim=xlim_if,
            ylim=ylim_if,
            show_xticklabels=label_xaxis,
            show_yticklabels=label_yaxis,
            font_size=font_size,
            bottom_left_spines_only=bottom_left_spines_only,
            grid=grid,
            show_plot_already=False,
            save_figure_to=save_if_figure_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

        if save_if_data_to:
            with open(save_if_data_to, 'w') as if_file:
                for i in range(len(stims_pA)):
                    if_file.write("%s\t%s\n" % (stims_pA[i], freqs[i]))
    if plot_iv:

        stims = sorted(iv_results.keys())
        stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]

        xs = []
        ys = []
        xs.append([])
        ys.append([])

        for si in range(len(stims)):
            stim = stims[si]
            if len(custom_amps_nA) == 0 and si > 1 and (
                    stims[si] - stims[si - 1]) > step_nA * 1.01:
                xs.append([])
                ys.append([])

            xs[-1].append(stim * 1000)
            ys[-1].append(iv_results[stim])

        iv_ax = pynml.generate_plot(
            xs,
            ys,
            "V at %sms versus I below threshold for: %s" %
            (end_stim, nml2_file),
            colors=[if_iv_color for s in xs],
            linestyles=['-' for s in xs],
            markers=['o' for s in xs],
            xaxis='Input current (pA)' if label_xaxis else '',
            yaxis='Membrane potential (mV)' if label_yaxis else '',
            xlim=xlim_iv,
            ylim=ylim_iv,
            show_xticklabels=label_xaxis,
            show_yticklabels=label_yaxis,
            font_size=font_size,
            linewidths=[linewidth for s in xs],
            bottom_left_spines_only=bottom_left_spines_only,
            grid=grid,
            show_plot_already=False,
            save_figure_to=save_iv_figure_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

        if save_iv_data_to:
            with open(save_iv_data_to, 'w') as iv_file:
                for i in range(len(stims_pA)):
                    iv_file.write("%s\t%s\n" % (stims_pA[i], vs[i]))

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    if return_axes:
        return traces_ax, if_ax, iv_ax

    return if_results
Пример #23
0
    def handleNetwork(self, network_id, notes):

        self.network = neuroml.Network(id=network_id)
        self.nml_doc.networks.append(self.network)
        if notes and len(notes) > 0:
            self.network.notes = notes
import neuroml

import neuroml.loaders as loaders
import neuroml.writers as writers

from pyneuroml.lems import generate_lems_file_for_neuroml

net_ref = "BC_StimNet"
net_doc = neuroml.NeuroMLDocument(id=net_ref)

net = neuroml.Network(id=net_ref)
net_doc.networks.append(net)

cell_id = 'BC2_na_k'

net_doc.includes.append(neuroml.IncludeType(cell_id + '.cell.nml'))

pop = neuroml.Population(id="BC", component=cell_id, type="populationList")

inst = neuroml.Instance(id="0")
pop.instances.append(inst)
inst.location = neuroml.Location(x=0, y=0, z=0)
net.populations.append(pop)

stim = neuroml.PulseGenerator(id='stim0',
                              delay='50ms',
                              duration='200ms',
                              amplitude='0.5nA')

net_doc.pulse_generators.append(stim)
Пример #25
0
def generate_grc_layer_network(
        p_mf_ON,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz 
        OFFRate,  # Hz
        run=False):

    # Load connectivity matrix

    file = open('GCLconnectivity.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == 4)), 'Connectivity matrix is incorrect.'

    # Load GrC and MF rosette positions

    grc_pos = p['grc_pos']
    glom_pos = p['glom_pos']

    # Choose which mossy fibers are on, which are off

    N_mf_ON = int(N_mf * p_mf_ON)
    mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
    mf_indices_ON.sort()

    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()

    # load NeuroML components, LEMS components and LEMS componentTypes from external files

    ##spikeGeneratorRefPoisson is now a standard nml type...
    ##spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)

    iaF_GrC = nml.IafRefCell(id="iaF_GrC",
                             refract="2ms",
                             C="3.22pF",
                             thresh="-40mV",
                             reset="-63mV",
                             leak_conductance="1.498nS",
                             leak_reversal="-79.67mV")

    ampa_syn_filename = "RothmanMFToGrCAMPA.xml"
    nmda_syn_filename = "RothmanMFToGrCNMDA.xml"

    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)

    # define some components from the componentTypes we just loaded
    ##spike_generator_ref_poisson_type = spike_generator_doc.component_types['spikeGeneratorRefPoisson']

    lems_instances_doc = lems.Model()
    spike_generator_ref_poisson_type_name = 'spikeGeneratorRefPoisson'

    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type_name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)

    spike_generator_off = lems.Component(
        "mossySpikerOFF", spike_generator_ref_poisson_type_name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)

    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id

    # create populations
    GrCPop = nml.Population(id=iaF_GrC.id + "Pop",
                            component=iaF_GrC.id,
                            type="populationList",
                            size=N_grc)
    GrCPop.properties.append(nml.Property(tag='color', value='0 0 0.8'))
    GrCPop.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       type="populationList",
                                       size=N_mf_ON)
    mossySpikersPopON.properties.append(
        nml.Property(tag='color', value='0.8 0 0'))
    mossySpikersPopON.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    mossySpikersPopOFF.properties.append(
        nml.Property(tag='color', value='0 0.8 0'))
    mossySpikersPopOFF.properties.append(nml.Property(tag='radius', value=2))

    # create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.iaf_ref_cells.append(iaF_GrC)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)

    #net_doc.includes.append(nml.IncludeType(href=iaf_nml2_file_name))

    # Add locations for GCs

    for grc in range(N_grc):
        inst = nml.Instance(id=grc)
        GrCPop.instances.append(inst)
        inst.location = nml.Location(x=grc_pos[grc, 0],
                                     y=grc_pos[grc, 1],
                                     z=grc_pos[grc, 2])

    # ON MFs: locations and connectivity

    ONprojectionAMPA = nml.Projection(
        id="ONProjAMPA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    ONprojectionNMDA = nml.Projection(
        id="ONProjNMDA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(ONprojectionAMPA)
    net.projections.append(ONprojectionNMDA)

    ix = 0
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        inst = nml.Instance(id=mf_ix_ON)
        mossySpikersPopON.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopON.id,
                                                     mf_ix_ON,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                ONprojectionAMPA.connections.append(connection)
                ONprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # OFF MFs: locations and connectivity

    OFFprojectionAMPA = nml.Projection(
        id="OFFProjAMPA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    OFFprojectionNMDA = nml.Projection(
        id="OFFProjNMDA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(OFFprojectionAMPA)
    net.projections.append(OFFprojectionNMDA)

    ix = 0
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        inst = nml.Instance(id=mf_ix_OFF)
        mossySpikersPopOFF.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopOFF.id,
                                                     mf_ix_OFF,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                OFFprojectionAMPA.connections.append(connection)
                OFFprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # Write network to file
    net_file_name = 'OSBnet.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)

    # Write LEMS instances to file
    lems_instances_file_name = 'instances.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)

    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation(
        'sim', duration, dt,
        simulation_seed=123)  # int(np.round(1000*random.random())))

    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)

    # Include generated/existing NeuroML2 files
    ###ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)

    # Specify Displays and Output Files

    basedir = ''

    eof0 = 'Volts_file'
    ls.create_event_output_file(eof0, basedir + "MF_spikes.dat")

    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], '{}/{}/{}'.format(mossySpikersPopON.id, i,
                                                      spike_generator_on.id),
            'spike')

    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i],
            '{}/{}/{}'.format(mossySpikersPopOFF.id, i,
                              spike_generator_on.id), 'spike')

    eof1 = 'GrCspike_file'
    ls.create_event_output_file(eof1, basedir + "GrC_spikes.dat")

    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(
            eof1, i, '{}/{}/{}'.format(GrCPop.id, i, iaF_GrC.id), 'spike')

    lems_file_name = ls.save_to_file()

    if run:
        print('Running the generated LEMS file: %s for simulation of %sms' %
              (lems_file_name, duration))
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results