예제 #1
0
def check_to_generate_or_run(argv, sim):
    """
    Useful method for calling in main method after network and simulation are 
    generated, to handle some standard export options like -jnml, -graph etc.
    """

    print_v(
        "Checking arguments: %s to see whether anything should be run in simulation %s (net: %s)..."
        % (argv, sim.id, sim.network))

    if len(argv) == 1:
        print_v("No arguments found. Currently supported export formats:")
        print_v("   -nml | -jnml | -jnmlnrn | -jnmlnetpyne | -netpyne | -pynnnrn "+\
                "| -pynnnest | -pynnbrian | -pynnneuroml | -sonata | -matrix[1-2] | -graph[1-6 n/d/f/c]")

    if '-pynnnest' in argv:
        generate_and_run(sim, simulator='PyNN_NEST')

    elif '-pynnnrn' in argv:
        generate_and_run(sim, simulator='PyNN_NEURON')

    elif '-pynnbrian' in argv:
        generate_and_run(sim, simulator='PyNN_Brian')

    elif '-jnml' in argv:
        generate_and_run(sim, simulator='jNeuroML')

    elif '-jnmlnrn' in argv:
        generate_and_run(sim, simulator='jNeuroML_NEURON')

    elif '-netpyne' in argv:
        generate_and_run(sim, simulator='NetPyNE')

    elif '-pynnneuroml' in argv:
        generate_and_run(sim, simulator='PyNN_NeuroML')

    elif '-sonata' in argv:
        generate_and_run(sim, simulator='sonata')

    elif '-nml' in argv or '-neuroml' in argv:

        network = load_network_json(sim.network)
        generate_neuroml2_from_network(network, validate=True)

    else:
        for a in argv:

            if '-jnmlnetpyne' in a:
                num_processors = 1
                if len(a) > len('-jnmlnetpyne'):
                    num_processors = int(a[12:])
                generate_and_run(sim,
                                 simulator='jNeuroML_NetPyNE',
                                 num_processors=num_processors)
            elif 'graph' in a:  # e.g. -graph3c
                generate_and_run(
                    sim, simulator=a[1:])  # Will not "run" obviously...
            elif 'matrix' in a:  # e.g. -matrix2
                generate_and_run(
                    sim, simulator=a[1:])  # Will not "run" obviously...
예제 #2
0
 def run_once(self, job_dir, ** kwargs):
     
     from neuromllite.utils import print_v
     from neuromllite.utils import load_simulation_json,load_network_json
     from neuromllite.NetworkGenerator import generate_and_run
     from pyneuroml.pynml import get_value_in_si
     
     print_v('Running NeuroMLlite simulation in dir: %s...'%job_dir)
     sim = load_simulation_json(self.nmllite_sim)
     import random
     sim.id = '%s%s'%(sim.id, '_%s'%kwargs['reference'] if 'reference' in kwargs else '')
     network = load_network_json(self.base_dir+'/'+sim.network)
     
     for a in kwargs:
         if a in network.parameters:
             print_v('  Setting %s to %s in network...'%(a, kwargs[a]))
             network.parameters[a] = kwargs[a]
         elif a in sim.fields:
             print_v('  Setting %s to %s in simulator...'%(a, kwargs[a]))
             setattr(sim,a,kwargs[a])
         else:
             print_v('  Cannot set parameter %s to %s in network or simulator...'%(a, kwargs[a]))
             
     traces, events = generate_and_run(sim, 
                                       simulator = self.simulator, 
                                       network = network, 
                                       return_results = True,
                                       base_dir = self.base_dir,
                                       target_dir = job_dir)
                                       
                                       
     print_v("Returned traces: %s, events: %s"%(traces.keys(), events.keys()))
     
     return traces, events 
예제 #3
0
def generate_and_run(simulation,
                     simulator,
                     network=None,
                     return_results=False,
                     base_dir=None,
                     target_dir=None,
                     num_processors=1):
    """
    Generates the network in the specified simulator and runs, if appropriate
    """

    if network == None:
        network = load_network_json(simulation.network)

    print_v("Generating network %s and running in simulator: %s..." %
            (network.id, simulator))

    if simulator == 'NEURON':

        _generate_neuron_files_from_neuroml(network,
                                            dir_for_mod_files=target_dir)

        from neuromllite.NeuronHandler import NeuronHandler

        nrn_handler = NeuronHandler()

        for c in network.cells:
            if c.neuroml2_source_file:
                src_dir = os.path.dirname(
                    os.path.abspath(c.neuroml2_source_file))
                nrn_handler.executeHoc('load_file("%s/%s.hoc")' %
                                       (src_dir, c.id))

        generate_network(network, nrn_handler, generate_network, base_dir)
        if return_results:
            raise NotImplementedError(
                "Reloading results not supported in Neuron yet...")

    elif simulator.lower() == 'sonata':  # Will not "run" obviously...

        from neuromllite.SonataHandler import SonataHandler

        sonata_handler = SonataHandler()

        generate_network(network,
                         sonata_handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with Sonata...")

    elif simulator.lower().startswith('graph'):  # Will not "run" obviously...

        from neuromllite.GraphVizHandler import GraphVizHandler, engines

        try:
            if simulator[-1].isalpha():
                engine = engines[simulator[-1]]
                level = int(simulator[5:-1])
            else:
                engine = 'dot'
                level = int(simulator[5:])

        except Exception as e:
            print_v("Error parsing: %s: %s" % (simulator, e))
            print_v(
                "Graphs of the network structure can be generated at many levels of detail (1-6, required) and laid out using GraphViz engines (d - dot (default); c - circo; n - neato; f - fdp), so use: -graph3c, -graph2, -graph4f etc."
            )
            return

        handler = GraphVizHandler(level, engine=engine, nl_network=network)

        generate_network(network,
                         handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with GraphViz...")

    elif simulator.lower().startswith('matrix'):  # Will not "run" obviously...

        from neuromllite.MatrixHandler import MatrixHandler

        try:
            level = int(simulator[6:])
        except:
            print_v("Error parsing: %s" % simulator)
            print_v(
                "Matrices of the network structure can be generated at many levels of detail (1-n, required), so use: -matrix1, -matrix2, etc."
            )
            return

        handler = MatrixHandler(level, nl_network=network)

        generate_network(network,
                         handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with MatrixHandler...")

    elif simulator.startswith('PyNN'):

        #_generate_neuron_files_from_neuroml(network)
        simulator_name = simulator.split('_')[1].lower()

        from neuromllite.PyNNHandler import PyNNHandler

        pynn_handler = PyNNHandler(simulator_name, simulation.dt, network.id)

        syn_cell_params = {}
        for proj in network.projections:

            synapse = network.get_child(proj.synapse, 'synapses')
            post_pop = network.get_child(proj.postsynaptic, 'populations')

            if not post_pop.component in syn_cell_params:
                syn_cell_params[post_pop.component] = {}
            for p in synapse.parameters:
                post = ''
                if synapse.pynn_receptor_type == "excitatory":
                    post = '_E'
                elif synapse.pynn_receptor_type == "inhibitory":
                    post = '_I'
                syn_cell_params[post_pop.component][
                    '%s%s' % (p, post)] = synapse.parameters[p]

        cells = {}
        for c in network.cells:
            if c.pynn_cell:
                cell_params = {}
                if c.parameters:
                    for p in c.parameters:
                        cell_params[p] = evaluate(c.parameters[p],
                                                  network.parameters)

                dont_set_here = [
                    'tau_syn_E', 'e_rev_E', 'tau_syn_I', 'e_rev_I'
                ]
                for d in dont_set_here:
                    if d in c.parameters:
                        raise Exception(
                            'Synaptic parameters like %s should be set ' +
                            'in individual synapses, not in the list of parameters associated with the cell'
                            % d)
                if c.id in syn_cell_params:
                    cell_params.update(syn_cell_params[c.id])
                print_v("Creating cell with params: %s" % cell_params)
                exec('cells["%s"] = pynn_handler.sim.%s(**cell_params)' %
                     (c.id, c.pynn_cell))

                if c.pynn_cell != 'SpikeSourcePoisson':
                    exec(
                        "cells['%s'].default_initial_values['v'] = cells['%s'].parameter_space['v_rest'].base_value"
                        % (c.id, c.id))

        pynn_handler.set_cells(cells)

        receptor_types = {}
        for s in network.synapses:
            if s.pynn_receptor_type:
                receptor_types[s.id] = s.pynn_receptor_type

        pynn_handler.set_receptor_types(receptor_types)

        for input_source in network.input_sources:
            if input_source.pynn_input:
                pynn_handler.add_input_source(input_source)

        generate_network(network,
                         pynn_handler,
                         always_include_props=True,
                         base_dir=base_dir)

        for pid in pynn_handler.populations:
            pop = pynn_handler.populations[pid]
            if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:
                if pop.can_record('v'):
                    pop.record('v')

        pynn_handler.sim.run(simulation.duration)
        pynn_handler.sim.end()

        traces = {}
        events = {}

        if not 'NeuroML' in simulator:
            from neo.io import PyNNTextIO

            for pid in pynn_handler.populations:
                pop = pynn_handler.populations[pid]

                if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:

                    filename = "%s.%s.v.dat" % (simulation.id, pop.label)
                    all_columns = []
                    print_v("Writing data for %s to %s" %
                            (pop.label, filename))
                    for i in range(len(pop)):
                        if pop.can_record('v'):
                            ref = '%s[%i]' % (pop.label, i)
                            traces[ref] = []
                            data = pop.get_data('v', gather=False)
                            for segment in data.segments:
                                vm = segment.analogsignals[0].transpose()[i]

                                if len(all_columns) == 0:
                                    tt = np.array([
                                        t * simulation.dt / 1000.
                                        for t in range(len(vm))
                                    ])
                                    all_columns.append(tt)
                                vm_si = [float(v / 1000.) for v in vm]
                                traces[ref] = vm_si
                                all_columns.append(vm_si)

                            times_vm = np.array(all_columns).transpose()

                    np.savetxt(filename, times_vm, delimiter='\t', fmt='%s')

        if return_results:
            _print_result_info(traces, events)
            return traces, events

    elif simulator == 'NetPyNE':

        if target_dir == None:
            target_dir = './'

        _generate_neuron_files_from_neuroml(network,
                                            dir_for_mod_files=target_dir)

        from netpyne import specs
        from netpyne import sim
        # Note NetPyNE from this branch is required: https://github.com/Neurosim-lab/netpyne/tree/neuroml_updates
        from netpyne.conversion.neuromlFormat import NetPyNEBuilder

        import pprint
        pp = pprint.PrettyPrinter(depth=6)

        netParams = specs.NetParams()
        simConfig = specs.SimConfig()
        netpyne_handler = NetPyNEBuilder(netParams,
                                         simConfig=simConfig,
                                         verbose=True)

        generate_network(network, netpyne_handler, base_dir=base_dir)

        netpyne_handler.finalise()

        simConfig = specs.SimConfig()
        simConfig.tstop = simulation.duration
        simConfig.duration = simulation.duration
        simConfig.dt = simulation.dt
        simConfig.seed = simulation.seed
        simConfig.recordStep = simulation.dt

        simConfig.recordCells = ['all']
        simConfig.recordTraces = {}

        for pop in netpyne_handler.popParams.values():
            if 'all' in simulation.recordTraces or pop.id in simulation.recordTraces:
                for i in pop['cellsList']:
                    id = pop['pop']
                    index = i['cellLabel']
                    simConfig.recordTraces['v_%s_%s' % (id, index)] = {
                        'sec': 'soma',
                        'loc': 0.5,
                        'var': 'v',
                        'conds': {
                            'pop': id,
                            'cellLabel': index
                        }
                    }

        simConfig.saveDat = True

        print_v("NetPyNE netParams: ")
        pp.pprint(netParams.todict())
        #print_v("NetPyNE simConfig: ")
        #pp.pprint(simConfig.todict())

        sim.initialize(
            netParams,
            simConfig)  # create network object and set cfg and net params

        sim.net.createPops()
        cells = sim.net.createCells(
        )  # instantiate network cells based on defined populations

        for proj_id in netpyne_handler.projection_infos.keys():
            projName, prePop, postPop, synapse, ptype = netpyne_handler.projection_infos[
                proj_id]
            print_v("Creating connections for %s (%s): %s->%s via %s" %
                    (projName, ptype, prePop, postPop, synapse))

            preComp = netpyne_handler.pop_ids_vs_components[prePop]

            for conn in netpyne_handler.connections[projName]:

                pre_id, pre_seg, pre_fract, post_id, post_seg, post_fract, delay, weight = conn

                #connParam = {'delay':delay,'weight':weight,'synsPerConn':1, 'sec':post_seg, 'loc':post_fract, 'threshold':threshold}
                connParam = {
                    'delay': delay,
                    'weight': weight,
                    'synsPerConn': 1,
                    'sec': post_seg,
                    'loc': post_fract
                }

                if ptype == 'electricalProjection':

                    if weight != 1:
                        raise Exception(
                            'Cannot yet support inputs where weight !=1!')
                    connParam = {
                        'synsPerConn': 1,
                        'sec': post_seg,
                        'loc': post_fract,
                        'gapJunction': True,
                        'weight': weight
                    }
                else:
                    connParam = {
                        'delay': delay,
                        'weight': weight,
                        'synsPerConn': 1,
                        'sec': post_seg,
                        'loc': post_fract
                    }
                    #'threshold': threshold}

                connParam['synMech'] = synapse

                if post_id in sim.net.gid2lid:  # check if postsyn is in this node's list of gids
                    sim.net._addCellConn(connParam, pre_id, post_id)

        stims = sim.net.addStims(
        )  # add external stimulation to cells (IClamps etc)
        simData = sim.setupRecording(
        )  # setup variables to record for each cell (spikes, V traces, etc)
        sim.runSim()  # run parallel Neuron simulation
        sim.gatherData()  # gather spiking data and cell info from each node
        sim.saveData(
        )  # save params, cell info and sim output to file (pickle,mat,txt,etc)

        if return_results:
            raise NotImplementedError(
                "Reloading results not supported in NetPyNE yet...")

    elif simulator == 'jNeuroML' or simulator == 'jNeuroML_NEURON' or simulator == 'jNeuroML_NetPyNE':

        from pyneuroml.lems import generate_lems_file_for_neuroml
        from pyneuroml import pynml

        lems_file_name = 'LEMS_%s.xml' % simulation.id

        nml_file_name, nml_doc = generate_neuroml2_from_network(
            network, base_dir=base_dir, target_dir=target_dir)
        included_files = ['PyNN.xml']

        for c in network.cells:
            if c.lems_source_file:
                included_files.append(c.lems_source_file)
        '''
        if network.cells:
            for c in network.cells:
                included_files.append(c.neuroml2_source_file)
        '''
        if network.synapses:
            for s in network.synapses:
                if s.lems_source_file:
                    included_files.append(s.lems_source_file)

        print_v("Generating LEMS file prior to running in %s" % simulator)

        pops_plot_save = []
        pops_spike_save = []
        gen_plots_for_quantities = {}
        gen_saves_for_quantities = {}

        for p in network.populations:

            if simulation.recordTraces and ('all' in simulation.recordTraces or
                                            p.id in simulation.recordTraces):
                pops_plot_save.append(p.id)

            if simulation.recordSpikes and ('all' in simulation.recordSpikes or
                                            p.id in simulation.recordSpikes):
                pops_spike_save.append(p.id)

            if simulation.recordRates and ('all' in simulation.recordRates
                                           or p.id in simulation.recordRates):
                size = evaluate(p.size, network.parameters)
                for i in range(size):
                    quantity = '%s/%i/%s/r' % (p.id, i, p.component)
                    gen_plots_for_quantities['%s_%i_r' %
                                             (p.id, i)] = [quantity]
                    gen_saves_for_quantities['%s_%i.r.dat' %
                                             (p.id, i)] = [quantity]

            if simulation.recordVariables:
                for var in simulation.recordVariables:
                    to_rec = simulation.recordVariables[var]
                    if ('all' in to_rec or p.id in to_rec):
                        size = evaluate(p.size, network.parameters)
                        for i in range(size):
                            quantity = '%s/%i/%s/%s' % (p.id, i, p.component,
                                                        var)
                            gen_plots_for_quantities['%s_%i_%s' %
                                                     (p.id, i, var)] = [
                                                         quantity
                                                     ]
                            gen_saves_for_quantities['%s_%i.%s.dat' %
                                                     (p.id, i, var)] = [
                                                         quantity
                                                     ]

        generate_lems_file_for_neuroml(
            simulation.id,
            nml_file_name,
            network.id,
            simulation.duration,
            simulation.dt,
            lems_file_name,
            target_dir=target_dir if target_dir else '.',
            nml_doc=
            nml_doc,  # Use this if the nml doc has already been loaded (to avoid delay in reload)
            include_extra_files=included_files,
            gen_plots_for_all_v=False,
            plot_all_segments=False,
            gen_plots_for_quantities=
            gen_plots_for_quantities,  # Dict with displays vs lists of quantity paths
            gen_plots_for_only_populations=
            pops_plot_save,  # List of populations, all pops if = []
            gen_saves_for_all_v=False,
            save_all_segments=False,
            gen_saves_for_only_populations=
            pops_plot_save,  # List of populations, all pops if = []
            gen_saves_for_quantities=
            gen_saves_for_quantities,  # Dict with file names vs lists of quantity paths
            gen_spike_saves_for_all_somas=False,
            gen_spike_saves_for_only_populations=
            pops_spike_save,  # List of populations, all pops if = []
            gen_spike_saves_for_cells=
            {},  # Dict with file names vs lists of quantity paths
            spike_time_format='ID_TIME',
            copy_neuroml=True,
            lems_file_generate_seed=12345,
            report_file_name='report.%s.txt' % simulation.id,
            simulation_seed=simulation.seed if simulation.seed else 12345,
            verbose=True)

        lems_file_name = _locate_file(lems_file_name, target_dir)

        if simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(
                lems_file_name,
                nogui=True,
                load_saved_data=return_results,
                reload_events=return_results)
        elif simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(
                lems_file_name,
                nogui=True,
                load_saved_data=return_results,
                reload_events=return_results)
        elif simulator == 'jNeuroML_NetPyNE':
            results = pynml.run_lems_with_jneuroml_netpyne(
                lems_file_name,
                nogui=True,
                verbose=True,
                load_saved_data=return_results,
                reload_events=return_results,
                num_processors=num_processors)

        print_v("Finished running LEMS file %s in %s (returning results: %s)" %
                (lems_file_name, simulator, return_results))

        if return_results:
            traces, events = results
            _print_result_info(traces, events)
            return results  # traces, events =
예제 #4
0
from neuromllite import *
from neuromllite.NetworkGenerator import *
from neuromllite.utils import load_network_json
import sys

################################################################################
###   Reuse network from Example2

filename = 'Example2_TestNetwork.json'
net = load_network_json(filename)
net.id = 'Example3_Network'
net.notes = 'Example 3: simple network with 2 populations of NeuroML2 cells, a projection between them and spiking input.'
print(net)
new_file = net.to_json_file()

################################################################################
###   Build Simulation object & save as JSON

sim = Simulation(id='SimExample3',
                 network=new_file,
                 duration='1000',
                 dt='0.025',
                 recordTraces={'all': '*'})

sim.to_json_file()

################################################################################
###   Run in some simulators

from neuromllite.NetworkGenerator import check_to_generate_or_run
import sys
예제 #5
0
    def __init__(self, nml_sim_file, parent=None):
        """Constructor for the GUI"""
        
        super(NMLliteUI, self).__init__(parent)
        
        self.SPIKES_RASTERPLOT = "Rasterplot"
        self.SPIKES_POP_RATE_AVE = "Pop rate averages"
        
        #print('Styles available: %s'%QStyleFactory.keys())
        QApplication.setStyle(QStyleFactory.create('Fusion'))
        
        header_font = QFont()
        header_font.setBold(True)
        
        self.backup_colors = {} # to ensure consistent random colors for traces... 
        
        self.simulation = load_simulation_json(nml_sim_file)
        self.sim_base_dir = dirname(nml_sim_file)
        if len(self.sim_base_dir) == 0:
            self.sim_base_dir = '.' 
        
        self.network = load_network_json('%s/%s' % (self.sim_base_dir, self.simulation.network))

        nameLabel = QLabel("NMLlite file: %s" % realpath(nml_sim_file))
        nameLabel.setFont(header_font)
        
        paramLayout = QGridLayout()
        topLayout = QGridLayout()
        midLayout = QGridLayout()
        
        self.tabs = QTabWidget()
        self.nmlliteTab = QWidget()
        self.nml2Tab = QWidget()
        self.matrixTab = QWidget()
        
        self.tabs.resize(300, 200)
        
        # Add tabs
        self.simTab = QWidget()
        self.tabs.addTab(self.simTab, "Simulation")
        
        self.simTabLayout = QGridLayout()
        self.simTab.setLayout(self.simTabLayout)
        
        self.plotTabs = QTabWidget()
        
        self.tracesTab = QWidget()
        self.plotTabs.addTab(self.tracesTab, "Traces")
        self.heatmapTab = QWidget()
        self.plotTabs.addTab(self.heatmapTab, "Heatmap")
        
        if self.simulation.plots2D is not None:
            
            self.plot2DTab = QTabWidget()
            self.plotTabs.addTab(self.plot2DTab, "2D plots")

            self.plot2DTabLayout = QGridLayout()
            self.plot2DTab.setLayout(self.plot2DTabLayout)
        
            for plot2D in self.simulation.plots2D:
                info = self.simulation.plots2D[plot2D]
                pLayout = self.add_tab(plot2D, self.plot2DTab, figure=True, toolbar=True, options=True)
        
        if self.simulation.plots3D is not None:
            
            self.plot3DTab = QTabWidget()
            self.plotTabs.addTab(self.plot3DTab, "3D plots")

            self.plot3DTabLayout = QGridLayout()
            self.plot3DTab.setLayout(self.plot3DTabLayout)
        
            for plot3D in self.simulation.plots3D:
                info = self.simulation.plots3D[plot3D]
                pLayout = self.add_tab(plot3D, self.plot3DTab, figure=True, toolbar=False, options=True)
                
        
        offset_opt = 1
        rasterOptionsLayout = self.add_tab(self.SPIKES_RASTERPLOT,self.plotTabs, figure=True, toolbar=True, options=True)
        self.rasterLegend = QCheckBox("Show legend")
        self.rasterLegend.setChecked(True)
        rasterOptionsLayout.addWidget(self.rasterLegend, 0, 0+offset_opt)
        self.rasterLegend.toggled.connect(self.replotSimResults)
        self.rasterInPops = QCheckBox("Include input pops")
        self.rasterInPops.setChecked(True)
        rasterOptionsLayout.addWidget(self.rasterInPops, 0, 1+offset_opt)
        self.rasterInPops.toggled.connect(self.replotSimResults)
        
        spikeStatOptionsLayout = self.add_tab(self.SPIKES_POP_RATE_AVE,self.plotTabs, figure=True, toolbar=True, options=True)
        self.spikeStatInPops = QCheckBox("Include input pops")
        self.spikeStatInPops.setChecked(True)
        spikeStatOptionsLayout.addWidget(self.spikeStatInPops, 0, 0+offset_opt)
        self.spikeStatInPops.toggled.connect(self.replotSimResults)
        
        self.simTabLayout.addWidget(self.plotTabs)
        
        self.tracesTabTopLayout = QGridLayout()
        self.tracesTab.setLayout(self.tracesTabTopLayout)
        
        self.tracesTabOptionsLayout = QGridLayout()
        self.tracesTabTopLayout.addLayout(self.tracesTabOptionsLayout, 0, 0)
        
        self.showTracesLegend = QCheckBox("Legend")
        self.tracesTabOptionsLayout.addWidget(self.showTracesLegend, 0, 0)
        
        self.traceSelectButton = QPushButton("Select traces...")
        self.traceSelectButton.show()
        self.traceSelectButton.setEnabled(False)
        
        self.traceSelectButton.clicked.connect(self.traceSelect)
        self.tracesTabOptionsLayout.addWidget(self.traceSelectButton, 0, 1)
        
        self.tracesTabLayout = QGridLayout()
        self.tracesTabTopLayout.addLayout(self.tracesTabLayout, 1, 0)
        
        self.heatmapLayout = QGridLayout()
        self.heatmapTab.setLayout(self.heatmapLayout)
        self.heatmapColorbar = None
        
        self.tracesFigure = Figure()
        self.tracesCanvas = FigureCanvas(self.tracesFigure)
        self.tracesToolbar = NavigationToolbar(self.tracesCanvas, self)
        self.tracesTabLayout.addWidget(self.tracesCanvas)
        self.tracesTabLayout.addWidget(self.tracesToolbar)
        
        self.heatmapFigure = Figure()
        self.heatmapCanvas = FigureCanvas(self.heatmapFigure)
        self.heatmapLayout.addWidget(self.heatmapCanvas)
        
        
        self.add_tab(self.GRAPH_TAB, self.tabs, image=True, options = True)
        
        graphTabOptionsLayout = self.all_options_layouts[self.GRAPH_TAB]
        
        offset_opt = 4
        graphTabOptionsLayout.addWidget(QLabel("Graph level:"), 0, offset_opt+0)
        
        self.graphLevelComboBox = QComboBox(self)
        self.graphLevelComboBox.addItem('-3')
        self.graphLevelComboBox.addItem('-2')
        self.graphLevelComboBox.addItem('-1')
        self.graphLevelComboBox.addItem('0')
        self.graphLevelComboBox.addItem('1')
        self.graphLevelComboBox.addItem('2')
        self.graphLevelComboBox.addItem('3')
        self.graphLevelComboBox.addItem('4')
        self.graphLevelComboBox.addItem('5')
        self.graphLevelComboBox.addItem('6')
        self.graphLevelComboBox.setCurrentIndex(6)
        graphTabOptionsLayout.addWidget(self.graphLevelComboBox, 0, offset_opt+1)
        self.graphLevelComboBox.currentIndexChanged.connect(self.showGraph)
        
        self.graphTypeComboBox = QComboBox(self)
        self.graphTypeComboBox.addItem('d - dot')
        self.graphTypeComboBox.addItem('c - circo')
        self.graphTypeComboBox.addItem('n - neato')
        self.graphTypeComboBox.addItem('f - fdp')
        self.graphTypeComboBox.setCurrentIndex(0)
        graphTabOptionsLayout.addWidget(QLabel("GraphViz engine:"), 0, offset_opt+2)
        graphTabOptionsLayout.addWidget(self.graphTypeComboBox, 0, offset_opt+3)
        self.graphTypeComboBox.currentIndexChanged.connect(self.showGraph)
        
        
        self.graphShowExtInputs = QCheckBox("Show ext inputs")
        self.graphShowExtInputs.setChecked(True)
        graphTabOptionsLayout.addWidget(self.graphShowExtInputs, 0, offset_opt+4)
        self.graphShowExtInputs.toggled.connect(self.showGraph)
        
        self.graphShowInputPops = QCheckBox("Show input pops")
        self.graphShowInputPops.setChecked(True)
        graphTabOptionsLayout.addWidget(self.graphShowInputPops, 0, offset_opt+5)
        self.graphShowInputPops.toggled.connect(self.showGraph)
        
        
        self.add_tab(self.LEMS_VIEW_TAB, self.tabs, image=True, options = True)
        
        self.add_tab(self.IMAGE_3D_TAB, self.tabs, image=True, options = True)        
        
        self.tabs.addTab(self.matrixTab, "Matrix")
        self.matrixTabLayout = QGridLayout()
        self.matrixTab.setLayout(self.matrixTabLayout)
        
        
        # Add tabs
        self.tabs.addTab(self.nmlliteTab, "NeuroMLlite")
        
        self.nmlliteTabLayout = QGridLayout()
        self.nmlliteTab.setLayout(self.nmlliteTabLayout)
        
        self.nmlliteTabs = QTabWidget()
        self.nmlliteTabLayout.addWidget(self.nmlliteTabs)
        
        self.nmlliteSimTab = QWidget()
        self.nmlliteTabs.addTab(self.nmlliteSimTab, "Simulation")
        self.nmlliteSimTabLayout = QGridLayout()
        self.nmlliteSimTab.setLayout(self.nmlliteSimTabLayout)
        self.nmlliteSimText = QPlainTextEdit()
        self.nmlliteSimTabLayout.addWidget(self.nmlliteSimText,0,0)
        
        self.nmlliteNetTab = QWidget()
        self.nmlliteTabs.addTab(self.nmlliteNetTab, "Network")
        self.nmlliteNetTabLayout = QGridLayout()
        self.nmlliteNetTab.setLayout(self.nmlliteNetTabLayout)
        self.nmlliteNetText = QPlainTextEdit()
        self.nmlliteNetTabLayout.addWidget(self.nmlliteNetText,0,0)
        
        
        self.tabs.addTab(self.nml2Tab, "NeuroML 2")
        self.nml2Layout = QGridLayout()
        self.nml2Tab.setLayout(self.nml2Layout)
        self.nml2Text = QPlainTextEdit()
        self.nml2Text.insertPlainText("\n   Generate an instance of the populations and projections in this network in NeuroML 2"+
                                      "\n   format by pressing the Generate NeuroML 2 button on the left"+
                                      "\n\n\n   WARNING: depending on the size of the generated network, text may take some time to load!")
        self.nml2Layout.addWidget(self.nml2Text,0,0)
        
        
        # Add tabs to widget
        midLayout.addWidget(self.tabs, 0, 0)
        mainLayout = QGridLayout()

        topLayout.addWidget(nameLabel, 0, 0)
        #topLayout.addWidget(self.nameLine, 0, 1)
        
        rows = 0
        
        l = QLabel("Network parameters")
        l.setFont(header_font)
        paramLayout.addWidget(l, rows, 0)
        
        self.param_entries = {}

        if self.network.parameters is not None and len(self.network.parameters) > 0:
            for p in sorted(self.network.parameters.keys()):
                rows += 1
                pval = self.network.parameters[p]
                label = QLabel("%s" % p)
                paramLayout.addWidget(label, rows, 0)
                entry = self.get_value_entry(p, pval, self.param_entries)
                paramLayout.addWidget(entry, rows, 1)
        
        if self.network.seed is not None:
            rows += 1
            pval = self.network.seed
            label = QLabel('Net generation seed')
            paramLayout.addWidget(label, rows, 0)
            entry = self.get_value_entry('seed', pval, self.param_entries)
            paramLayout.addWidget(entry, rows, 1)
            
        if self.network.temperature is not None:
            rows += 1
            pval = self.network.temperature
            label = QLabel('Temperature')
            paramLayout.addWidget(label, rows, 0)
            entry = self.get_value_entry('temperature', pval, self.param_entries)
            paramLayout.addWidget(entry, rows, 1)
            
                
                
        self.graphButton = QPushButton("Generate graph")
        self.graphButton.show()
        self.graphButton.clicked.connect(self.showGraph)
        
        rows += 1
        paramLayout.addWidget(self.graphButton, rows, 0)
                
        self.lemsViewButton = QPushButton("Generate LEMS View")
        self.lemsViewButton.show()
        self.lemsViewButton.clicked.connect(self.showLemsView)
        
        rows += 1
        paramLayout.addWidget(self.lemsViewButton, rows, 0)
                
        self.image3DButton = QPushButton("Generate 3D image")
        self.image3DButton.show()
        self.image3DButton.clicked.connect(self.show3Dimage)
        
        rows += 1
        paramLayout.addWidget(self.image3DButton, rows, 0)
                
        self.matrixButton = QPushButton("Generate matrix")
        self.matrixButton.show()
        self.matrixButton.clicked.connect(self.showMatrix)
        
        rows += 1
        paramLayout.addWidget(self.matrixButton, rows, 0)
                
        self.nml2Button = QPushButton("Generate NeuroML 2")
        self.nml2Button.show()
        self.nml2Button.clicked.connect(self.generateNeuroML2)
        
        rows += 1
        paramLayout.addWidget(self.nml2Button, rows, 0)
                
        rows += 1
        l = QLabel("Simulation parameters")
        l.setFont(header_font)
        paramLayout.addWidget(l, rows, 0)

        self.sim_entries = {}
        svars = ['dt', 'duration', 'seed']

        for s in svars:
            rows += 1
            sval = self.simulation.__getattr__(s)
            if sval is not None:
                label = QLabel("%s" % s)
                paramLayout.addWidget(label, rows, 0)
                
                
                entry = self.get_value_entry(s, sval, self.sim_entries)
                paramLayout.addWidget(entry, rows, 1)

        rows += 1
        
        paramLayout.addWidget(QLabel("Simulator:"), rows, 0)
        
        self.simulatorComboBox = QComboBox(self)
        for sim in self.simulators:
            self.simulatorComboBox.addItem(sim)
        
        paramLayout.addWidget(self.simulatorComboBox, rows, 1)
        rows += 1

        self.runButton = QPushButton("Run simulation")
        self.runButton.show()
        self.runButton.clicked.connect(self.runSimulation)
        
        self.autoRunCheckBox = QCheckBox("Auto run")
        rows += 1
        paramLayout.addWidget(self.runButton, rows, 0)
        paramLayout.addWidget(self.autoRunCheckBox, rows, 1)
        
        
        mainLayout.addLayout(topLayout, 0, 1)
        mainLayout.addLayout(paramLayout, 1, 0)
        mainLayout.addLayout(midLayout, 1, 1)
        
        #self.setLayout(paramLayout)
        self.setLayout(mainLayout)
        
        self.setWindowTitle("NeuroMLlite GUI")
        
        self.update_network_json()
        self.update_simulation_json()
예제 #6
0
from neuromllite import (
    RelativeLayout,
    Cell,
    Synapse,
    InputSource,
    Input,
    RectangularRegion,
)
from neuromllite.NetworkGenerator import generate_network
from neuromllite.utils import load_network_json
from neuromllite.DefaultNetworkHandler import DefaultNetworkHandler

################################################################################
###   Reuse network from Example1

net = load_network_json("../../../examples/Example1_TestNetwork.json")
net.id = "Example_Layout"

net.notes = "...."


################################################################################
###   Add some elements to the network & save new JSON

r1 = RectangularRegion(id="region1", x=0, y=0, z=0, width=1000, height=100, depth=1000)
r2 = RectangularRegion(
    id="region2", x=1000, y=1000, z=1000, width=1000, height=100, depth=1000
)
net.regions.append(r1)
net.regions.append(r2)
예제 #7
0
from neuromllite import (
    RandomLayout,
    Cell,
    Synapse,
    InputSource,
    Input,
    RectangularRegion,
)
from neuromllite.NetworkGenerator import generate_network
from neuromllite.utils import load_network_json
from neuromllite.DefaultNetworkHandler import DefaultNetworkHandler

################################################################################
###   Reuse network from Example1

net = load_network_json("Example1_TestNetwork.json")
net.id = "Example2_TestNetwork"

net.notes = (
    "A simple network with 2 populations & projection between them. " +
    "Cells are specified to be NeuroML 2 HH cell models & pre population "
    "is given a spiking input.")

################################################################################
###   Add some elements to the network & save new JSON

r1 = RectangularRegion(id="region1",
                       x=0,
                       y=0,
                       z=0,
                       width=1000,
예제 #8
0
from neuromllite import RandomLayout, Cell, Synapse, InputSource, Input, RectangularRegion
from neuromllite.NetworkGenerator import generate_network
from neuromllite.utils import load_network_json
from neuromllite.DefaultNetworkHandler import DefaultNetworkHandler

################################################################################
###   Reuse network from Example1

net = load_network_json('Example1_TestNetwork.json')
net.id = 'Example2_TestNetwork'

net.notes = "A simple network with 2 populations & projection between them. "+ \
            "Cells are specified to be NeuroML 2 HH cell models & pre population " \
            "is given a spiking input."


################################################################################
###   Add some elements to the network & save new JSON

r1 = RectangularRegion(id='region1', x=0,y=0,z=0,width=1000,height=100,depth=1000)
r2 = RectangularRegion(id='region2', x=0,y=200,z=0,width=1000,height=100,depth=1000)
net.regions.append(r1)
net.regions.append(r2)

net.populations[0].random_layout = RandomLayout(region=r1.id)
net.populations[1].random_layout = RandomLayout(region=r2.id)

net.populations[0].component = 'hhcell'
net.populations[1].component = 'hhcell'

net.cells.append(Cell(id='hhcell', neuroml2_source_file='test_files/hhcell.cell.nml'))