Example #1
0
def main(procs_per_worker):
    """

    :param procs_per_worker: int
    """

    pc.subworlds(procs_per_worker)
    global_rank = int(pc.id_world())
    global_size = int(pc.nhost_world())
    rank = int(pc.id())
    size = int(pc.nhost())
    print(
        'MPI rank: %i, MPI size: %i, pc local rank: %i, pc local size: %i, pc global rank: %i, '
        'pc global size: %i\r' % (global_comm.rank, global_comm.size, rank,
                                  size, global_rank, global_size))
    sys.stdout.flush()
    time.sleep(1.)
    pc.runworker()
    pc.context(synchronize)
    for _ in range(pc.nhost_bbs() - 1):
        pc.take("sync")
    print('Root has received sync messages from all other workers at %s' %
          (datetime.datetime.now()))
    sys.stdout.flush()
    time.sleep(1.)
    synchronize()
    print('Root has exited synchronize at %s' % (datetime.datetime.now()))
    sys.stdout.flush()
    time.sleep(1.)

    pc.done()
    h.quit()
    os._exit(1)
Example #2
0
def parrun(nruns=0,
           nchannels=50,
           n_trajectory=1,
           modelses="ch3_101p.ses",
           datagen=None):
    mk_tcr(nchannels, modelsed, datagen)

    pc = h.ParallelContext()
    pc.runworker()
    if nruns == 0:
        nruns = int(pc.nhost())
    for i in range(nruns):
        pc.submit(onerun, i + 1, nchannels, n_trajectory)
    f = open(
        'results' + str(nchannels) + '.' + str(n_trajectory) + '.' +
        str(nruns), "w")
    pickle.dump(nruns, f)
    f.flush()
    i = 0
    while (pc.working() != 0.0):
        r = pc.pyret()
        pickle.dump(r, f)
        f.flush()
        i += 1
        print '%d seed %d' % (i, r[0][1])
    f.close()
    pc.done()
    h.quit()
Example #3
0
 def finalize(self, quit=False):
     """Finish using NEURON."""
     self.parallel_context.runworker()
     self.parallel_context.done()
     if quit:
         logger.info("Finishing up with NEURON.")
         h.quit()
Example #4
0
 def finalize(self, quit=False):
     """Finish using NEURON."""
     self.parallel_context.runworker()
     self.parallel_context.done()
     if quit:
         logger.info("Finishing up with NEURON.")
         h.quit()
Example #5
0
def main():

    parser = argparse.ArgumentParser(description='Parallel transfer test.')
    parser.add_argument('--sparse-partrans',
                        dest='sparse_partrans',
                        default=False,
                        action='store_true',
                        help='use sparse parallel transfer')
    parser.add_argument(
        '--result-prefix',
        default='.',
        help='place output files in given directory (must exist before launch)'
    )
    parser.add_argument('--ngids',
                        default=2,
                        type=int,
                        help='number of gids to create (must be even)')

    args, unknown = parser.parse_known_args()

    pc = h.ParallelContext()
    myrank = int(pc.id())

    mkcells(pc, args.ngids)
    mkgjs(pc, args.ngids)

    pc.setup_transfer()

    if args.sparse_partrans:
        if hasattr(h, 'nrn_sparse_partrans'):
            h.nrn_sparse_partrans = 1

    rec_t = h.Vector()
    rec_t.record(h._ref_t)

    wt = time.time()

    h.dt = 0.25
    pc.set_maxstep(10)
    h.finitialize(-65)
    pc.psolve(500)

    total_wt = time.time() - wt

    gjtime = pc.vtransfer_time()

    print('rank %d: parallel transfer time: %.02f' % (myrank, gjtime))
    print('rank %d: total compute time: %.02f' % (myrank, total_wt))

    output = itertools.chain([np.asarray(rec_t.to_python())],
                             [np.asarray(vrec.to_python()) for vrec in vrecs])
    np.savetxt("%s/ParGJ_%04i.dat" % (args.result_prefix, myrank),
               np.column_stack(tuple(output)))

    pc.runworker()
    pc.done()

    h.quit()
Example #6
0
def main():
    # We need to to some hacking to support command line parameters.  NEURON
    # tries to run all of the arguments on the command line, but we want to
    # use these extra parameters for config files.  This is not a disaster
    # because NEURON will try to run the config files after running all of the
    # code in this file, so errors don't prevent us from getting useful work
    # done (and JSON may not even cause an error).  They can, however, cause
    # NEURON to leave the user at a NEURON prompt, which prevents using this
    # code from makefiles, bash scripts, and other non-interactive tools.  To
    # work around this, if we're not running in interactive mode we can
    # terminate NEURON after running this script (before it tries to run the
    # remaining command line arguments).

    # Assume that the user doesn't want a NEURON prompt unless they've invoked
    # nrngui or specified '-' on the command line (standard for NEURON).
    interactive = "nrngui" in sys.argv[0] or "-" in sys.argv

    # extract the config files
    configfiles = (['defaultconfig.yaml'] +
        [arg for arg in sys.argv if ".yaml" in arg])

    print('Using config files: {0}\n'.format(", ".join(configfiles)))

    # read the configuration files in order, allowing later config files
    # to override earlier settings.
    config = {}
    for filename in configfiles:
        with open(filename,'r') as f:
            # read the entire file as text
            config_text = f.read(-1)

            # remove comments (from '#' to the end of the line)
            bare_config_text = re.sub('#[^\n]*\n', '\n', config_text)

            # parse it as JSON
            config.update(json.loads(bare_config_text))
    config = simplify_config(config)

    # If the csv filename was not specified, default to the last config
    # file name.
    if config['csv_filename'] == '':
        config['csv_filename'] = configfiles[-1].replace('.yaml', '.csv')

    if config['param_sweep_steps'] == 1:
        run_single_simulation(config, interactive)
    else:
        run_sweep_simulation(config, interactive)

    # Now that we're done, quit if we're not in interactive mode
    # (see command line options above)
    if not interactive:
        h.quit();
Example #7
0
def main():
    gid  = 0
    model = 'kr'
    cell_size = 120
    N = 20
    neurons = [KhaliqRaman(gid,
                           {'diameter':cell_size,'length':cell_size,
                            'nSynapses':0,'channelNoise':False})
               for gid in range(N)]
    baseline = []
    pulse = []
    for n,current in zip(neurons,np.linspace(0.04,0.07,N)):
        baseline.append(h.IClamp(n.soma(0.5)))
        baseline[-1].amp = -0.17
        baseline[-1].dur = 2000
        baseline[-1].delay = 0
        pulse.append(h.IClamp(n.soma(0.5)))
        pulse[-1].amp = current
        pulse[-1].dur = 1000
        pulse[-1].delay = 500
 
    for i,n in enumerate(neurons):
        n.addSomaticVoltageRecorder()
    time = h.Vector()
    time.record(h._ref_t)

    h.load_file('stdrun.hoc')
    h.tstop = 2000
    h.run()
    
    import pylab as plt
    fig = plt.figure()
    for i,n in enumerate(neurons):
#        fig.add_subplot(len(neurons),1,i)
        plt.plot(time,n.somaticVoltage()+(i-1)*5)
    plt.show()
    ipdb.set_trace()

    h.quit()
def main(block_size, task_limit, procs_per_worker):
    """
    Executes blocks of tasks using pc.submit until a task limit.
    :param block_size: int
    :param task_limit: int
    :param procs_per_worker: int
    """

    pc = h.ParallelContext()
    pc.subworlds(procs_per_worker)
    global_rank = int(pc.id_world())
    global_size = int(pc.nhost_world())
    rank = int(pc.id())
    size = int(pc.nhost())
    task_counter = 0

    print 'test_pc_submit_limits: process id: %i; global rank: %i / %i; local rank: %i / %i' % \
          (os.getpid(), global_rank, global_size, rank, size)
    sys.stdout.flush()
    time.sleep(1.)

    context.update(locals())
    pc.runworker()

    # catch workers escaping from runworker loop
    if global_rank != 0:
        os._exit(1)

    if block_size is None:
        block_size = global_size
    while context.task_counter < task_limit:
        result = pc_map(pc, test, range(block_size))
        print 'Completed tasks count: %i' % context.task_counter
        sys.stdout.flush()
        time.sleep(0.1)

    pc.done()
    h.quit()
Example #9
0
def test_units():
    s = h.Section()
    pp = h.UnitsTest(s(.5))
    h.ion_style("na_ion", 1, 2, 1, 1, 0, sec=s)

    h.finitialize(-65)
    R_std = pp.gasconst
    erev_std = pp.erev
    ghk_std = pp.ghk

    from neuron import coreneuron
    h.CVode().cache_efficient(1)
    coreneuron.enable = True
    coreneuron.gpu = bool(os.environ.get('CORENRN_ENABLE_GPU', ''))
    pc.set_maxstep(10)
    h.finitialize(-65)
    pc.psolve(h.dt)

    assert (R_std == pp.gasconst)  # mod2c needs nrnunits.lib.in
    assert (abs(erev_std - pp.erev) <= (1e-13 if coreneuron.gpu else 0)
            )  # GPU has tiny numerical differences
    assert (ghk_std == pp.ghk)
    h.quit()
Example #10
0
def main():
    '''
    Executes a simulation taking the parameters from a
    configuration file.
    '''
    verbose = True
    counter = 0
    for v in sys.argv:
        counter+=1
        if path.basename(__file__) in v:
            break
    filename = sys.argv[counter]
    par, recpar = readConfigurations(filename)
    createMRGaxon(par,0)
    rec = recordMRGaxon(recpar,0)
    runMRGaxon()
    if recpar['record']:
        append_fiber_to_file(rec,par,recpar)
    if recpar['plot']:
        import pylab as plt
        fig = plotMRGaxon(plt, rec, recpar)
        plt.show()
    h.quit()
Example #11
0
def main():
    '''
    Runs 100 fibers in series at a specified condition.
    Or a single particular fiber if a separate parameter is specified.
    The first parameter is always the name of the cfg file.  
    '''
    verbose = False
    verbose_level1 = True
    plot = False
    if verbose: 
        print('Running HFS simulation.')
    if plot:
        import pylab as plt
    counter = 0
    for v in sys.argv:
        counter+=1
        if path.basename(__file__) in v:
            break
    try: 
        filename = sys.argv[counter]
    except:
        print('This function takes the filename of the configuration'
              ' file as input.')
        sys.exit(1)
    try:
        singleRun = int(sys.argv[counter + 1])
    except:
        print('Running an entire population.') 
        singleRun =  None
    if not path.exists(filename):
        print('File (%s) does not exist.' % (filename))
        sys.exit(1)
    par, recpar = readConfigurations(filename)
    createMRGaxon(par,verbose)
    rec = recordMRGaxon(recpar,verbose)
    simulatePopulation(par,recpar,rec,None,True,True, singleRun)
    h.quit()
def main(import_mpi4py, run_nrnmpi_init, procs_per_worker, sleep):
    """

    :param import_mpi4py: int
    :param run_nrnmpi_init: bool
    :param procs_per_worker: int
    :param sleep: float
    """
    time.sleep(sleep)
    if import_mpi4py == 1:
        order = 'before'
        from mpi4py import MPI
        time.sleep(1.)
        print('test_mpiguard: getting past import mpi4py')
        sys.stdout.flush()
        time.sleep(1.)

    from neuron import h
    time.sleep(1.)
    print('test_mpiguard: getting past from neuron import h')
    sys.stdout.flush()
    time.sleep(1.)

    if run_nrnmpi_init:
        try:
            h.nrnmpi_init()
            time.sleep(1.)
            print('test_mpiguard: getting past h.nrnmpi_init()')
            sys.stdout.flush()
            time.sleep(1.)
        except:
            print(
                'test_mpiguard: problem calling h.nrnmpi_init(); may not be defined in this version of NEURON'
            )
            time.sleep(1.)
            sys.stdout.flush()
            time.sleep(1.)
    else:
        print('test_mpiguard: h.nrnmpi_init() not executed')
        time.sleep(1.)
        sys.stdout.flush()
        time.sleep(1.)
    if import_mpi4py == 2:
        order = 'after'
        from mpi4py import MPI
        print('test_mpiguard: getting past import mpi4py')
        time.sleep(1.)
        sys.stdout.flush()
        time.sleep(1.)

    if import_mpi4py > 0:
        comm = MPI.COMM_WORLD

    pc = h.ParallelContext()
    pc.subworlds(procs_per_worker)
    global_rank = int(pc.id_world())
    global_size = int(pc.nhost_world())
    rank = int(pc.id())
    size = int(pc.nhost())

    if import_mpi4py > 0:
        print(
            'test_mpiguard: mpi4py imported %s neuron: process id: %i; global rank: %i / %i; local rank: %i / %i; '
            'comm.rank: %i; comm.size: %i' %
            (order, os.getpid(), global_rank, global_size, rank, size,
             comm.rank, comm.size))
    else:
        print(
            'test_mpiguard: mpi4py not imported: process id: %i; global rank: %i / %i; local rank: %i / %i'
            % (os.getpid(), global_rank, global_size, rank, size))
    time.sleep(1.)
    sys.stdout.flush()
    time.sleep(1.)

    pc.runworker()
    time.sleep(1.)
    print('test_mpiguard: got past pc.runworker()')
    time.sleep(1.)
    sys.stdout.flush()
    time.sleep(1.)

    # catch workers escaping from runworker loop
    if global_rank != 0:
        print(
            'test_mpiguard: global_rank: %i escaped from the pc.runworker loop'
        )
        sys.stdout.flush()
        time.sleep(1.)
        os._exit(1)

    pc.done()
    time.sleep(1.)
    print('test_mpiguard: got past pc.done()')
    time.sleep(1.)
    sys.stdout.flush()
    time.sleep(1.)

    print('calling h_quit')
    sys.stdout.flush()
    time.sleep(1.)
    h.quit()
    time.sleep(1.)
    sys.stdout.flush()
    time.sleep(1.)
Example #13
0
 def finalize(self):
     logger.info("Finishing up with NEURON.")
     h.quit()
Example #14
0
def run_simulation(params):
    """
    Function get parameters and run the model
    """
    pc = h.ParallelContext()

    pc.timeout(3600)
    h.load_file("stdgui.hoc")
    h.load_file("stdrun.hoc")
    h.load_file("import3d.hoc")

    RNG = np.random.default_rng()

    load_mechanisms("./mods/")
    # h.dt = 0.1 * ms
    h.cvode.use_fast_imem(1)
    # h.CVode().fixed_step(1)
    # h.cvode.use_local_dt(1)

    sys.path.append("../LFPsimpy/")  # path to LFPsimpy
    from LFPsimpy import LfpElectrode

    # load all cells
    cell_path = "./cells/"
    for file in os.listdir(cell_path):
        if file.find(".hoc") != -1:
            h.load_file(cell_path + file)

    gid_vect = np.asarray(
        [neuron_param["gid"] for neuron_param in params["neurons"]])

    all_cells = h.List()
    hh_cells = h.List()

    pyramidal_sec_list = h.SectionList()
    is_pyrs_thread = False
    radius_for_pyramids = params["common_params"]["radius4piramids"]

    spike_count_obj = []
    spike_times_vecs = []

    soma_v_vecs = []

    # create objects for neurons simulation
    for neuron_param in params["neurons"]:

        celltypename = neuron_param["celltype"]
        cellclass_name = neuron_param["cellclass"]
        gid = neuron_param["gid"]

        cellclass = getattr(h, cellclass_name)

        cell = cellclass(gid, 0)

        pc.set_gid2node(gid, pc.id())

        if celltypename == "pyr":
            # x and y position of pyramidal cells

            angle = 2 * np.pi * (RNG.random() - 0.5)
            radius = radius_for_pyramids * 2 * (RNG.random() - 0.5)
            pyr_coord_in_layer_x = radius * np.cos(angle)
            pyr_coord_in_layer_y = radius * np.sin(angle)

            cell.position(pyr_coord_in_layer_x, 0, pyr_coord_in_layer_y)

            for sec in cell.all:
                pyramidal_sec_list.append(sec)
            is_pyrs_thread = True

        # set counters for spike generation
        if cell.is_art() == 0:
            for sec in cell.all:
                sec.insert("IextNoise")
                sec.myseed_IextNoise = RNG.integers(0, 1000000000000000, 1)
                sec.sigma_IextNoise = 0.005
                sec.mean_IextNoise = neuron_param["cellparams"]["iext"]

            if hasattr(cell, "axon_list"):
                mt = h.MechanismType(0)
                mt.select('IextNoise')
                for sec in cell.axon_list:
                    mt.remove(sec=sec)

            firing = h.NetCon(cell.soma[0](0.5)._ref_v, None, sec=cell.soma[0])
            firing.threshold = -30 * mV

        else:
            cell.celltype = celltypename

            for p_name, p_val in neuron_param["cellparams"].items():
                if hasattr(cell.acell, p_name):
                    setattr(cell.acell, p_name, p_val)

            setattr(cell.acell, "delta_t", h.dt)

            setattr(cell.acell, "myseed", RNG.integers(0, 1000000000000000, 1))

            firing = h.NetCon(cell.acell, None)

        pc.cell(gid, firing)
        fring_vector = h.Vector()
        firing.record(fring_vector)
        spike_count_obj.append(firing)
        spike_times_vecs.append(fring_vector)

        # check is need to save Vm of soma
        if np.sum(params["save_soma_v"] == gid) == 1:
            soma_v = h.Vector()
            soma_v.record(cell.soma[0](0.5)._ref_v)
            soma_v_vecs.append(soma_v)
        else:
            soma_v_vecs.append(np.empty(shape=0))

        if cell.is_art() == 0:
            hh_cells.append(cell)

        all_cells.append(cell)

    pc.barrier()
    if pc.id() == 0:
        print("End of neurons settings")

    # set connection
    connections = h.List()
    synapses = h.List()

    for syn_params in params["synapses_params"]:
        post_idx = np.argwhere(gid_vect == syn_params["post_gid"]).ravel()
        post_idx = post_idx[0]

        postsynaptic_cell = all_cells[post_idx]

        post_list = getattr(postsynaptic_cell,
                            syn_params["target_compartment"])
        len_postlist = sum([1 for _ in post_list])

        if len_postlist == 1:
            post_idx = 0
        else:
            post_idx = RNG.integers(0, len_postlist - 1)

        for idx_tmp, post_comp_tmp in enumerate(post_list):
            if idx_tmp == post_idx: post_comp = post_comp_tmp

        syn = h.Exp2Syn(post_comp(0.5))
        syn.e = syn_params["Erev"]
        syn.tau1 = syn_params["tau_rise"]
        syn.tau2 = syn_params["tau_decay"]

        conn = pc.gid_connect(syn_params["pre_gid"], syn)
        conn.delay = syn_params["delay"]
        conn.weight[0] = syn_params["gmax"]
        conn.threshold = -30 * mV

        connections.append(conn)
        synapses.append(syn)

        try:
            # check NMDA in synapse
            gmax_nmda = syn_params["NMDA"]["gNMDAmax"]
            syn_nmda = h.NMDA(post_comp(0.5), sec=post_comp)
            syn_nmda.tcon = syn_params["NMDA"]["tcon"]
            syn_nmda.tcoff = syn_params["NMDA"]["tcoff"]
            syn_nmda.gNMDAmax = gmax_nmda

            conn2 = pc.gid_connect(syn_params["pre_gid"], syn_nmda)
            conn2.delay = syn_params["delay"]
            conn2.weight[0] = syn_params["NMDA"]["gNMDAmax"]
            conn2.threshold = -30 * mV

            connections.append(conn2)
            synapses.append(syn_nmda)

        except KeyError:
            pass

    pc.barrier()

    # create gap junction objects
    gap_junctions = h.List()

    for gap_params in params["gap_junctions"]:

        idx1 = np.argwhere(gid_vect == gap_params["gid1"]).ravel()
        idx2 = np.argwhere(gid_vect == gap_params["gid2"]).ravel()

        if idx1.size != 0 and idx2.size != 0:

            idx1 = idx1[0]
            idx2 = idx2[0]

            cell1 = all_cells[idx1]
            cell2 = all_cells[idx2]

            comp1_list = getattr(cell1, gap_params["compartment1"])
            len_list = sum([1 for _ in comp1_list])

            if len_list == 1:
                idx1 = 0
            else:
                idx1 = RNG.integers(0, len_list - 1)

            for idx_tmp, comp_tmp in enumerate(comp1_list):
                if idx_tmp == idx1: comp1 = comp_tmp

            comp2_list = getattr(cell2, gap_params["compartment2"])
            len_list = sum([1 for _ in comp2_list])

            if len_list == 1:
                idx2 = 0
            else:
                idx2 = RNG.integers(0, len_list - 1)

            for idx_tmp, comp_tmp in enumerate(comp2_list):
                if idx_tmp == idx2: comp2 = comp_tmp

            pc.source_var(comp1(0.5)._ref_v, gap_params["sgid_gap"],
                          sec=comp1)  # gap_params["gid1"]

            gap = h.GAP(comp1(0.5), sec=comp1)
            gap.r = gap_params["r"]
            pc.target_var(gap._ref_vgap,
                          gap_params["sgid_gap"] + 1)  # gap_params["gid2"]

            gap_junctions.append(gap)

            pc.source_var(comp2(0.5)._ref_v,
                          gap_params["sgid_gap"] + 1,
                          sec=comp2)  # gap_params["gid2"]
            gap = h.GAP(comp2(0.5), sec=comp2)
            gap.r = gap_params["r"]
            pc.target_var(gap._ref_vgap,
                          gap_params["sgid_gap"])  # gap_params["gid1"]
            gap_junctions.append(gap)

        elif idx1.size != 0 or idx2.size != 0:

            if idx1.size != 0 and idx2.size != 0: continue

            if idx1.size != 0:
                this_idx = idx1[0]
                this_gid = gap_params["gid1"]
                out_gid = gap_params["gid2"]
                comp_name = gap_params["compartment1"]

                sgid_gap_src = gap_params["sgid_gap"]
                sgid_gap_trg = gap_params["sgid_gap"] + 1
            else:
                this_idx = idx2[0]
                this_gid = gap_params["gid2"]
                out_gid = gap_params["gid1"]
                comp_name = gap_params["compartment2"]

                sgid_gap_src = gap_params["sgid_gap"] + 1
                sgid_gap_trg = gap_params["sgid_gap"]

            cell = all_cells[this_idx]
            comp_list = getattr(cell, comp_name)

            for idx_tmp, comp_tmp in enumerate(comp_list):
                if idx_tmp == 0: comp = comp_tmp

            pc.source_var(comp(0.5)._ref_v, sgid_gap_src, sec=comp)

            gap = h.GAP(0.5, sec=comp)
            gap.r = gap_params["r"]

            pc.target_var(gap._ref_vgap, sgid_gap_trg)

    pc.setup_transfer()
    pc.barrier()
    if pc.id() == 0:
        print("End of connection settings")

    # create electrodes objects for LFP simulation
    el_x = params["elecs"]["el_x"]
    el_y = params["elecs"]["el_y"]
    el_z = params["elecs"]["el_z"]

    electrodes = []

    for idx_el in range(el_x.size):
        if is_pyrs_thread:
            le = LfpElectrode(x=el_x[idx_el], y=el_y[idx_el], z=el_z[idx_el], sampling_period=h.dt, \
                              method='Line', sec_list=pyramidal_sec_list)
            electrodes.append(le)
        else:
            electrodes.append(None)

    if pc.id() == 0:
        t_sim = h.Vector()
        t_sim.record(h._ref_t)
    else:
        t_sim = None

    h.tstop = params["duration"] * ms

    pc.set_maxstep(5 * ms)

    h.finitialize()
    pc.barrier()
    if pc.id() == 0:
        print("Start simulation")

    timer = time()

    pc.psolve(params["duration"] * ms)
    pc.barrier()
    if pc.id() == 0:
        print("End of the simulation!")
        print("Time of simulation in sec ", time() - timer)

    # unite data from all threads to 0 thread
    comm = MPI.COMM_WORLD
    lfp_data = join_lfp(comm, electrodes)
    spike_trains = join_vect_lists(comm, spike_times_vecs, gid_vect)
    soma_v_list = join_vect_lists(comm, soma_v_vecs, gid_vect)

    if (pc.id() == 0) and (params["file_results"] != None):

        t_sim = np.asarray(t_sim)
        rem_time = params["del_start_time"]
        if rem_time > t_sim[-1]:
            rem_time = 0
        rem_idx = int(rem_time / h.dt)

        # save results to file
        with h5py.File(params["file_results"], 'w') as h5file:
            celltypes = params["cell_types_in_model"]
            t_sim = t_sim[rem_idx:] - rem_time

            h5file.create_dataset("time", data=t_sim)

            # save LFP data
            extracellular_group = h5file.create_group("extracellular")
            ele_group = extracellular_group.create_group('electrode_1')
            lfp_group = ele_group.create_group('lfp')

            lfp_group_origin = lfp_group.create_group('origin_data')
            lfp_group_origin.attrs['SamplingRate'] = 1000 / h.dt  # dt in ms

            for idx_el, lfp in enumerate(lfp_data):
                lfp_group_origin.create_dataset("channel_" + str(idx_el + 1),
                                                data=lfp[rem_idx:])

            # save firing data
            firing_group = h5file.create_group(
                "extracellular/electrode_1/firing/origin_data")

            for celltype in set(celltypes):
                cell_friring_group = firing_group.create_group(celltype)

                for cell_idx, sp_times in enumerate(spike_trains):
                    if celltype != celltypes[cell_idx]:
                        continue
                    sp_times = sp_times[sp_times >= rem_time] - rem_time
                    cell_friring_group.create_dataset(
                        "neuron_" + str(cell_idx + 1),
                        data=sp_times)  # cell_spikes_dataset

            # save intracellular membrane potential
            intracellular_group = h5file.create_group("intracellular")
            intracellular_group_origin = intracellular_group.create_group(
                "origin_data")

            for soma_v_idx in params["save_soma_v"]:
                soma_v = soma_v_list[soma_v_idx]
                if soma_v.size == 0: continue
                soma_v_dataset = intracellular_group_origin.create_dataset(
                    "neuron_" + str(soma_v_idx + 1), data=soma_v[rem_idx:])
                cell_type = celltypes[soma_v_idx]
                soma_v_dataset.attrs["celltype"] = cell_type

    pc.done()
    h.quit()

    return
Example #15
0
def test_direct_memory_transfer():
    #h('''create soma''')
    cell = h.rinzelnrn()
    #h.psection()
    #dir(h)
    #h.soma.L=5.6419
    #h.soma.diam=5.6419
    #h.soma.insert("rinzelnrn")
    gc = 2.1
    pp = 0.5

    cell.soma.Ra = 1
    cell.dend.Ra = 1
    global_Ra = (1e-6 / (gc / pp *
                         (h.area(0.5) * 1e-8) * 1e-3)) / (2 * h.ri(0.5))
    cell.soma.Ra = global_Ra
    cell.soma.cm = 3
    cell.dend.Ra = global_Ra
    cell.dend.cm = 3

    # soma
    cell.soma.insert("pas")
    cell.soma.insert("kdr")
    cell.soma.insert("nafPR")

    cell.soma.gmax_nafPR = 30e-3
    cell.soma.gmax_kdr = 15e-3
    cell.soma.g_pas = 0.1e-3
    cell.soma.e_pas = -60

    # dend
    cell.dend.insert("pas")
    cell.dend.insert("rcadecay")
    cell.dend.insert("cal")
    cell.dend.insert("kcRT03")
    cell.dend.insert("rkq")

    cell.dend.g_pas = 0.1e-3
    cell.dend.e_pas = -60
    cell.dend.phi_rcadecay = 130
    cell.dend.gmax_cal = 00010e-3
    cell.dend.erev_cal = 80
    cell.dend.gmax_kcRT03 = 00015e-3
    cell.dend.gmax_rkq = 0000.8e-3
    cell.dend.ek = -75

    ic = h.IClamp(cell.soma(.5))
    ic.delay = .5
    ic.dur = 0.1
    ic.amp = 0.3

    #for testing external mod file
    #h.soma.insert("hh")

    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    h.tstop = 50
    h.celsius = 37.0
    h.v_init = -60
    v = h.Vector()
    v.record(cell.soma(.5)._ref_v, sec=cell.soma)
    i_mem = h.Vector()
    i_mem.record(cell.soma(.5)._ref_i_membrane_, sec=cell.soma)
    tv = h.Vector()
    tv.record(h._ref_t, sec=cell.soma)
    h.run()
    vstd = v.cl()
    tvstd = tv.cl()
    i_memstd = i_mem.cl()
    # Save current (after run) value to compare with transfer back from coreneuron
    #tran_std = [h.t, cell.soma(.5).v, cell.soma(.5).hh.m]

    from neuron import coreneuron
    coreneuron.enable = True

    pc = h.ParallelContext()
    pc.set_maxstep(10)

    h.stdinit()
    pc.psolve(h.tstop)
    #tran = [h.t, cell.soma(.5).v, cell.soma(.5).hh.m]

    assert (tv.eq(tvstd))
    #assert(v.cl().sub(vstd).abs().max() < 1e-10)
    assert (i_mem.cl().sub(i_memstd).abs().max() < 1e-10)
    #assert(h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10)

    f = open('v.dat', 'w')
    for i in range(tv.size()):
        print('{} {}'.format(tv[i], v[i]), file=open("v.dat", "a"))

    h.quit()
Example #16
0
def finish():
    ''' proper exit '''
    pc.runworker()
    pc.done()
    h.quit()
Example #17
0
def Node(stimdir):
    """This is the program for the node model in the paper _.
    When using this program use the following command:

        ./x86_64/special -python nodetest.py (number)

    Where the numbers are for the direction of the signal:

    (number)
    0: 'rl'
    1: 'du'
    2: 'lr'
    3: 'ud'
    4: 'full' (forward direction)

    The data will be saved in the ./data/node directory."""

    #--------------------------------------------------------------------------------------------------------------------------------------------

    datafile = open(datadict['L1data'], 'r')
    L1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi1data'], 'r')
    Mi1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Tm3data'], 'r')
    Tm3list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi4data'], 'r')
    Mi4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi9data'], 'r')
    Mi9list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4data'], 'r')
    T4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4adata'], 'r')
    T4alist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4bdata'], 'r')
    T4blist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4cdata'], 'r')
    T4clist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4ddata'], 'r')
    T4dlist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict[stimdir], 'r')
    stimdata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['totaldata'], 'r')
    fulldata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['areas'], 'r')
    area = simplejson.load(datafile)
    datafile.close()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    neurdic = {}

    print('Creating cells...')

    count = 0

    #--------------------------------------------------------------------------------------------------------------------------------------------

    for f in range(len(fulldata)):

        if fulldata[f] == None:

            continue

        else:

            #--------------------------------------------------------------------------------------------------------------------------------------------

            if str(fulldata[f].cellID) in area.keys():

                neurdic[fulldata[f].cellID] = node_neur.cell(
                    fulldata[f], area[str(fulldata[f].cellID)])

                print(area[str(fulldata[f].cellID)])

                count += 1

    #-------------------------------------------------------------------------------

    print('Compartments: ' + str(count))

    #-------------------------------------------------------------------------------

    print('Connecting cells..')

    #-------------------------------------------------------------------------------

    from structneur import node_syn

    connections = {
        #L1
        'L1_L1': [L1list, L1list],
        'L1_Mi1': [L1list, Mi1list],
        'L1_Mi4': [L1list, Mi4list],
        'L1_Mi9': [L1list, Mi9list],
        'L1_Tm3': [L1list, Tm3list],
        'L1_T4': [L1list, T4list],

        #Mi1
        'Mi1_Mi1': [Mi1list, Mi1list],
        'Mi1_L1': [Mi1list, L1list],
        'Mi1_Tm3': [Mi1list, Tm3list],
        'Mi1_Mi4': [Mi1list, Mi4list],
        'Mi1_Mi9': [Mi1list, Mi9list],
        'Mi1_T4': [Mi1list, T4list],

        #Tm3
        'Tm3_Tm3': [Tm3list, Tm3list],
        'Tm3_L1': [Tm3list, L1list],
        'Tm3_Mi1': [Tm3list, Mi1list],
        'Tm3_Mi4': [Tm3list, Mi4list],
        'Tm3_Mi9': [Tm3list, Mi9list],
        'Tm3_T4': [Tm3list, T4list],

        #Mi4
        'Mi4_Mi4': [Mi4list, Mi4list],
        'Mi4_L1': [Mi4list, L1list],
        'Mi4_Mi1': [Mi4list, Mi1list],
        'Mi4_Tm3': [Mi4list, Tm3list],
        'Mi4_Mi9': [Mi4list, Mi9list],
        'Mi4_T4': [Mi4list, T4list],

        #Mi9
        'Mi9_Mi9': [Mi9list, Mi9list],
        'Mi9_L1': [Mi9list, L1list],
        'Mi9_Mi1': [Mi9list, Mi1list],
        'Mi9_Tm3': [Mi9list, Tm3list],
        'Mi9_Mi4': [Mi9list, Mi4list],
        'Mi9_T4': [Mi9list, T4list],

        #T4
        'T4_T4': [T4list, T4list],
        'T4_L1': [T4list, L1list],
        'T4_Mi1': [T4list, Mi1list],
        'T4_Tm3': [T4list, Tm3list],
        'T4_Mi4': [T4list, Mi4list],
        'T4_Mi9': [T4list, Mi9list],
    }

    synlist = []

    for key in neurdic.keys():

        #Stimuli-----------------------------------------------------------------------------------------------
        if str(stimdir) == 'full':
            if key in stimdata:
                neurdic[key].create_stim(55)
        else:
            if key in stimdata[0]:
                neurdic[key].create_stim(55)
            if key in stimdata[1]:
                neurdic[key].create_stim(155)
            if key in stimdata[2]:
                neurdic[key].create_stim(255)
            if key in stimdata[3]:
                neurdic[key].create_stim(355)
            if key in stimdata[4]:
                neurdic[key].create_stim(455)

        #-----------------------------------------------------------------------------------------------------------------------------------------------

        for p in neurdic[key].partners:

            part = p[0]

            if part in neurdic.keys():

                #L1-----------------------------------------------------------------------------------------------
                """if key in connections['L1_L1'][0] and part in connections['L1_L1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],tau=50)

                    synlist.append(info)"""

                if key in connections['L1_Mi1'][0] and part in connections[
                        'L1_Mi1'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['L1_Tm3'][0] and part in connections[
                        'L1_Tm3'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                #Mi1-----------------------------------------------------------------------------------------------
                """if key in connections['Mi1_Mi1'][0] and part in connections['Mi1_Mi1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""
                """if key in connections['Mi1_L1'][0] and part in connections['Mi1_L1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                if key in connections['Mi1_Tm3'][0] and part in connections[
                        'Mi1_Tm3'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_Mi4'][0] and part in connections[
                        'Mi1_Mi4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_Mi9'][0] and part in connections[
                        'Mi1_Mi9'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_T4'][0] and part in connections[
                        'Mi1_T4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                #Tm3-----------------------------------------------------------------------------------------------
                """if key in connections['Tm3_Tm3'][0] and part in connections['Tm3_Tm3'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""
                """if key in connections['Tm3_L1'][0] and part in connections['Tm3_L1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                if key in connections['Tm3_Mi1'][0] and part in connections[
                        'Tm3_Mi1'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_Mi4'][0] and part in connections[
                        'Tm3_Mi4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_Mi9'][0] and part in connections[
                        'Tm3_Mi9'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_T4'][0] and part in connections[
                        'Tm3_T4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part])

                    synlist.append(info)

                #Mi4-----------------------------------------------------------------------------------------------
                """if key in connections['Mi4_Mi4'][0] and part in connections['Mi4_Mi4'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Mi1'][0] and part in connections['Mi4_Mi1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Tm3'][0] and part in connections['Mi4_Tm3'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""

                if key in connections['Mi4_Mi9'][0] and part in connections[
                        'Mi4_Mi9'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part], e=-80)

                    synlist.append(info)

                if key in connections['Mi4_T4'][0] and part in connections[
                        'Mi4_T4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part], e=-80)

                    synlist.append(info)

                #Mi9-----------------------------------------------------------------------------------------------
                """if key in connections['Mi9_Mi9'][0] and part in connections['Mi9_Mi9'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Mi1'][0] and part in connections['Mi9_Mi1'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Tm3'][0] and part in connections['Mi9_Tm3'][1]:
                    info = node_syn.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""

                if key in connections['Mi9_Mi4'][0] and part in connections[
                        'Mi9_Mi4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part], e=-80)

                    synlist.append(info)

                if key in connections['Mi9_T4'][0] and part in connections[
                        'Mi9_T4'][1]:
                    info = node_syn.synapse(neurdic[key], neurdic[part], e=-80)

                    synlist.append(info)

    print('Synapses: ' + str(len(synlist)))
    #--------------------------------------------------------------------------------------------------------------------------------------------

    tlist = []
    Mi1simlist = []
    L1simlist = []
    Tm3simlist = []
    Mi4simlist = []
    Mi9simlist = []
    T4simlist = []

    T4asimlist = []
    T4bsimlist = []
    T4csimlist = []
    T4dsimlist = []

    Mi1data = []
    L1data = []
    Tm3data = []
    Mi4data = []
    Mi9data = []
    T4data = []

    T4adata = []
    T4bdata = []
    T4cdata = []
    T4ddata = []

    heatmap = []

    #------------------------------------------------------------------------------------------------------------

    for val in neurdic.values():

        v_vec = h.Vector()
        t_vec = h.Vector()

        v_vec.record(val.soma(0.5)._ref_v)
        t_vec.record(h._ref_t)

        sim = (t_vec, v_vec)
        ID_sim = numpy.array([val.cellID, v_vec], dtype=list)

        if val.cellID in Mi1list:

            Mi1simlist.append(sim)
            Mi1data.append(v_vec)

        if val.cellID in L1list:

            L1simlist.append(sim)
            L1data.append(v_vec)

        if val.cellID in Tm3list:

            Tm3simlist.append(sim)
            Tm3data.append(v_vec)

        if val.cellID in Mi4list:

            Mi4simlist.append(sim)
            Mi4data.append(v_vec)

        if val.cellID in Mi4list:

            Mi9simlist.append(sim)
            Mi9data.append(v_vec)

        if val.cellID in T4list:

            T4simlist.append(sim)
            T4data.append(v_vec)

        if val.cellID in T4alist:

            T4asimlist.append(sim)
            T4adata.append(v_vec)

        if val.cellID in T4blist:

            T4bsimlist.append(sim)
            T4bdata.append(v_vec)

        if val.cellID in T4clist:

            T4csimlist.append(sim)
            T4cdata.append(v_vec)

        if val.cellID in T4dlist:

            T4dsimlist.append(sim)
            T4ddata.append(v_vec)

    #--------------------------------------------------------------------------------------------------------------------------------------------

    h.tstop = 1000

    print('Running simulation...')

    import time
    start_time = time.time()

    h.run()

    print("--- %s seconds ---" % (time.time() - start_time))

    print('Done!')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.figure(str(stimdir))
    pyplot.subplot(2, 3, 1)
    for token in Mi1simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi1')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 2)
    for token in L1simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('L1')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 3)
    for token in Tm3simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Tm3')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 4)
    for token in Mi4simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi4')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 5)
    for token in Mi9simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi9')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 6)
    for token in T4simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.figure('T4: ' + str(stimdir))

    pyplot.subplot(2, 2, 1)
    for token in T4asimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4a')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 2)
    for token in T4bsimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4b')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 3)
    for token in T4csimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4c')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 4)
    for token in T4dsimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4d')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.show()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    import os
    datafolder = datadict['dataloc'] + 'node/' + str(stimdir)

    filename = datafolder + 'Mi1simlist' + '.csv'
    numpy.savetxt(filename, Mi1data, delimiter=',')

    filename = datafolder + 'L1simlist' + '.csv'
    numpy.savetxt(filename, L1data, delimiter=',')

    filename = datafolder + 'Tm3simlist' + '.csv'
    numpy.savetxt(filename, Tm3data, delimiter=',')

    filename = datafolder + 'Mi4simlist' + '.csv'
    numpy.savetxt(filename, Mi4data, delimiter=',')

    filename = datafolder + 'Mi9simlist' + '.csv'
    numpy.savetxt(filename, Mi9data, delimiter=',')

    filename = datafolder + 'T4simlist' + '.csv'
    numpy.savetxt(filename, T4data, delimiter=',')

    filename = datafolder + 'T4asimlist' + '.csv'
    numpy.savetxt(filename, T4adata, delimiter=',')

    filename = datafolder + 'T4bsimlist' + '.csv'
    numpy.savetxt(filename, T4bdata, delimiter=',')

    filename = datafolder + 'T4csimlist' + '.csv'
    numpy.savetxt(filename, T4cdata, delimiter=',')

    filename = datafolder + 'T4dsimlist' + '.csv'
    numpy.savetxt(filename, T4ddata, delimiter=',')

    h.quit()
Example #18
0
def Compartment(stimdir):
    """This is the program for the compartment model in the paper _.
    When using this program use the following command:

        ./x86_64/special -python compartmenttest.py (number)

    Where the numbers are for the direction of the signal:

    (number)
    0: 'rl'
    1: 'du'
    2: 'lr'
    3: 'ud'
    4: 'full' (forward direction)

    The data will be saved in the ./data/compartment directory."""

    #--------------------------------------------------------------------------------------------------------------------------------------------

    datafile = open(datadict['L1data'], 'r')
    L1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi1data'], 'r')
    Mi1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Tm3data'], 'r')
    Tm3list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi4data'], 'r')
    Mi4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi9data'], 'r')
    Mi9list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4data'], 'r')
    T4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4adata'], 'r')
    T4alist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4bdata'], 'r')
    T4blist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4cdata'], 'r')
    T4clist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4ddata'], 'r')
    T4dlist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict[stimdir], 'r')
    stimdata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['totaldata'], 'r')
    fulldata = pickle.load(datafile)
    datafile.close()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    area = {}

    neurdic = {}

    print('Creating cells...')

    count = 0

    #--------------------------------------------------------------------------------------------------------------------------------------------

    for f in range(len(fulldata)):

        if fulldata[f] == None:

            continue

        else:

            #--------------------------------------------------------------------------------------------------------------------------------------------

            if fulldata[f].cellID in L1list:

                neurdic[fulldata[f].cellID] = compressed_neur.cell(fulldata[f])
                area[fulldata[f].cellID] = neurdic[
                    fulldata[f].cellID].totalarea

                print(area[fulldata[f].cellID])
                count += len(neurdic[fulldata[f].cellID].compartmentdict)
                break

    #--------------------------------------------------------------------------------------------------------------------------------------------

    print('Compartments: ' + str(count))

    datadict['areas'] = datadict['dataloc'] + 'areas.json'

    datafile = open(datadict['areas'], 'w')
    simplejson.dump(area, datafile)
    datafile.close()

    fileloc = open('locationdic.json', 'w')
    simplejson.dump(datadict, fileloc)
    fileloc.close()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    print('Connecting cells..')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    from structneur import compressed_syn

    connections = {
        #L1
        'L1_L1': [L1list, L1list],
        'L1_Mi1': [L1list, Mi1list],
        'L1_Mi4': [L1list, Mi4list],
        'L1_Mi9': [L1list, Mi9list],
        'L1_Tm3': [L1list, Tm3list],
        'L1_T4': [L1list, T4list],

        #Mi1
        'Mi1_Mi1': [Mi1list, Mi1list],
        'Mi1_L1': [Mi1list, L1list],
        'Mi1_Tm3': [Mi1list, Tm3list],
        'Mi1_Mi4': [Mi1list, Mi4list],
        'Mi1_Mi9': [Mi1list, Mi9list],
        'Mi1_T4': [Mi1list, T4list],

        #Tm3
        'Tm3_Tm3': [Tm3list, Tm3list],
        'Tm3_L1': [Tm3list, L1list],
        'Tm3_Mi1': [Tm3list, Mi1list],
        'Tm3_Mi4': [Tm3list, Mi4list],
        'Tm3_Mi9': [Tm3list, Mi9list],
        'Tm3_T4': [Tm3list, T4list],

        #Mi4
        'Mi4_Mi4': [Mi4list, Mi4list],
        'Mi4_L1': [Mi4list, L1list],
        'Mi4_Mi1': [Mi4list, Mi1list],
        'Mi4_Tm3': [Mi4list, Tm3list],
        'Mi4_Mi9': [Mi4list, Mi9list],
        'Mi4_T4': [Mi4list, T4list],

        #Mi9
        'Mi9_Mi9': [Mi9list, Mi9list],
        'Mi9_L1': [Mi9list, L1list],
        'Mi9_Mi1': [Mi9list, Mi1list],
        'Mi9_Tm3': [Mi9list, Tm3list],
        'Mi9_Mi4': [Mi9list, Mi4list],
        'Mi9_T4': [Mi9list, T4list],

        #T4
        'T4_T4': [T4list, T4list],
        'T4_L1': [T4list, L1list],
        'T4_Mi1': [T4list, Mi1list],
        'T4_Tm3': [T4list, Tm3list],
        'T4_Mi4': [T4list, Mi4list],
        'T4_Mi9': [T4list, Mi9list],
    }

    #--------------------------------------------------------------------------------------------------------------------------------------------

    datadict['connections'] = datadict['dataloc'] + 'connections.json'

    datafile = open(datadict['connections'], 'w')
    simplejson.dump(connections, datafile)
    datafile.close()

    fileloc = open('locationdic.json', 'w')
    simplejson.dump(datadict, fileloc)
    fileloc.close()

    synlist = []

    #--------------------------------------------------------------------------------------------------------------------------------------------

    for key in neurdic.keys():

        neurdic[key].create_stim(55)

        #Stimuli-----------------------------------------------------------------------------------------------
        if str(stimdir) == 'full':
            if key in stimdata:
                neurdic[key].create_stim(55)
        else:
            if key in stimdata[0]:
                neurdic[key].create_stim(55)
            if key in stimdata[1]:
                neurdic[key].create_stim(155)
            if key in stimdata[2]:
                neurdic[key].create_stim(255)
            if key in stimdata[3]:
                neurdic[key].create_stim(355)
            if key in stimdata[4]:
                neurdic[key].create_stim(455)

        for p in neurdic[key].partners:

            pID = p[0]
            ploc = p[1]

            sdistances = []
            rdistances = []

            if pID in neurdic.keys():

                receiver = neurdic[pID]
                sender = neurdic[key]
                synloc = ploc

                #L1-----------------------------------------------------------------------------------------------
                """if key in connections['L1_L1'][0] and pID in connections['L1_L1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,tau=50)

                    synlist.append(info)"""

                if key in connections['L1_Mi1'][0] and pID in connections[
                        'L1_Mi1'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['L1_Tm3'][0] and pID in connections[
                        'L1_Tm3'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Mi1-----------------------------------------------------------------------------------------------
                """if key in connections['Mi1_Mi1'][0] and pID in connections['Mi1_Mi1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc)

                    synlist.append(info)"""
                """if key in connections['Mi1_L1'][0] and pID in connections['Mi1_L1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc)

                    synlist.append(info)"""

                if key in connections['Mi1_Tm3'][0] and pID in connections[
                        'Mi1_Tm3'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_Mi4'][0] and pID in connections[
                        'Mi1_Mi4'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_Mi9'][0] and pID in connections[
                        'Mi1_Mi9'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_T4'][0] and pID in connections[
                        'Mi1_T4'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Tm3-----------------------------------------------------------------------------------------------
                """if key in connections['Tm3_Tm3'][0] and pID in connections['Tm3_Tm3'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc)

                    synlist.append(info)"""
                """if key in connections['Tm3_L1'][0] and pID in connections['Tm3_L1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc)

                    synlist.append(info)"""

                if key in connections['Tm3_Mi1'][0] and pID in connections[
                        'Tm3_Mi1'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_Mi4'][0] and pID in connections[
                        'Tm3_Mi4'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_Mi9'][0] and pID in connections[
                        'Tm3_Mi9'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_T4'][0] and pID in connections[
                        'Tm3_T4'][1]:
                    info = compressed_syn.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Mi4-----------------------------------------------------------------------------------------------
                """if key in connections['Mi4_Mi4'][0] and pID in connections['Mi4_Mi4'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Mi1'][0] and pID in connections['Mi4_Mi1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Tm3'][0] and pID in connections['Mi4_Tm3'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""

                if key in connections['Mi4_Mi9'][0] and pID in connections[
                        'Mi4_Mi9'][1]:
                    info = compressed_syn.synapse(sender,
                                                  receiver,
                                                  synloc,
                                                  e=-80)

                    synlist.append(info)

                if key in connections['Mi4_T4'][0] and pID in connections[
                        'Mi4_T4'][1]:
                    info = compressed_syn.synapse(sender,
                                                  receiver,
                                                  synloc,
                                                  e=-80)

                    synlist.append(info)

                #Mi9-----------------------------------------------------------------------------------------------
                """if key in connections['Mi9_Mi9'][0] and pID in connections['Mi9_Mi9'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Mi1'][0] and pID in connections['Mi9_Mi1'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Tm3'][0] and pID in connections['Mi9_Tm3'][1]:
                    info = compressed_syn.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""

                if key in connections['Mi9_Mi4'][0] and pID in connections[
                        'Mi9_Mi4'][1]:
                    info = compressed_syn.synapse(sender,
                                                  receiver,
                                                  synloc,
                                                  e=-80)

                    synlist.append(info)

                if key in connections['Mi9_T4'][0] and pID in connections[
                        'Mi9_T4'][1]:
                    info = compressed_syn.synapse(sender,
                                                  receiver,
                                                  synloc,
                                                  e=-80)

                    synlist.append(info)

    print('Synapses: ' + str(len(synlist)))

    #--------------------------------------------------------------------------------------------------------------------------------------------

    tlist = []
    Mi1simlist = []
    L1simlist = []
    Tm3simlist = []
    Mi4simlist = []
    Mi9simlist = []
    T4simlist = []

    T4asimlist = []
    T4bsimlist = []
    T4csimlist = []
    T4dsimlist = []

    Mi1data = []
    L1data = []
    Tm3data = []
    Mi4data = []
    Mi9data = []
    T4data = []

    T4adata = []
    T4bdata = []
    T4cdata = []
    T4ddata = []

    heatmap = []

    #------------------------------------------------------------------------------------------------------------

    for val in neurdic.values():

        heat_vec = h.Vector()
        t_vec = h.Vector()

        heat_vec.record(
            val.compartmentdict[val.compartmentdict.keys()[0]][1](0.5)._ref_v)
        heatmap.append(heat_vec)
        t_vec.record(h._ref_t)

        if val.cellID in Mi1list:

            Mi1soma_v_vec = h.Vector()
            Mi1t_vec = h.Vector()

            Mi1soma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            Mi1t_vec.record(h._ref_t)

            Mi1sim = (Mi1t_vec, Mi1soma_v_vec)
            Mi1simlist.append(Mi1sim)

            Mi1data.append(Mi1soma_v_vec)

        if val.cellID in L1list:

            L1soma_v_vec = h.Vector()
            L1t_vec = h.Vector()

            L1soma_v_vec.record(val.compartmentdict[val.compartmentdict.keys()
                                                    [0]][1](0.5)._ref_v)
            L1t_vec.record(h._ref_t)

            L1sim = (L1t_vec, L1soma_v_vec)
            L1simlist.append(L1sim)

            L1data.append(L1soma_v_vec)

        if val.cellID in Tm3list:

            Tm3soma_v_vec = h.Vector()
            Tm3t_vec = h.Vector()

            Tm3soma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            Tm3t_vec.record(h._ref_t)

            Tm3sim = (Tm3t_vec, Tm3soma_v_vec)
            Tm3simlist.append(Tm3sim)

            Tm3data.append(Tm3soma_v_vec)

        if val.cellID in Mi4list:

            Mi4soma_v_vec = h.Vector()
            Mi4t_vec = h.Vector()

            Mi4soma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            Mi4t_vec.record(h._ref_t)

            Mi4sim = (Mi4t_vec, Mi4soma_v_vec)
            Mi4simlist.append(Mi4sim)

            Mi4data.append(Mi4soma_v_vec)

        if val.cellID in Mi4list:

            Mi9soma_v_vec = h.Vector()
            Mi9t_vec = h.Vector()

            Mi9soma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            Mi9t_vec.record(h._ref_t)

            Mi9sim = (Mi9t_vec, Mi9soma_v_vec)
            Mi9simlist.append(Mi9sim)

            Mi9data.append(Mi9soma_v_vec)

        if val.cellID in T4list:

            T4soma_v_vec = h.Vector()
            T4t_vec = h.Vector()

            T4soma_v_vec.record(val.compartmentdict[val.compartmentdict.keys()
                                                    [0]][1](0.5)._ref_v)
            T4t_vec.record(h._ref_t)

            T4sim = (T4t_vec, T4soma_v_vec)
            T4simlist.append(T4sim)

            T4data.append(T4soma_v_vec)

        if val.cellID in T4alist:

            T4asoma_v_vec = h.Vector()
            T4at_vec = h.Vector()

            T4asoma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            T4at_vec.record(h._ref_t)

            T4asim = (T4at_vec, T4asoma_v_vec)
            T4asimlist.append(T4asim)

            T4adata.append(T4asoma_v_vec)

        if val.cellID in T4blist:

            T4bsoma_v_vec = h.Vector()
            T4bt_vec = h.Vector()

            T4bsoma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            T4bt_vec.record(h._ref_t)

            T4bsim = (T4bt_vec, T4bsoma_v_vec)
            T4bsimlist.append(T4bsim)

            T4bdata.append(T4bsoma_v_vec)

        if val.cellID in T4clist:

            T4csoma_v_vec = h.Vector()
            T4ct_vec = h.Vector()

            T4csoma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            T4ct_vec.record(h._ref_t)

            T4csim = (T4ct_vec, T4csoma_v_vec)
            T4csimlist.append(T4csim)

            T4cdata.append(T4csoma_v_vec)

        if val.cellID in T4dlist:

            T4dsoma_v_vec = h.Vector()
            T4dt_vec = h.Vector()

            T4dsoma_v_vec.record(val.compartmentdict[
                val.compartmentdict.keys()[0]][1](0.5)._ref_v)
            T4dt_vec.record(h._ref_t)

            T4dsim = (T4dt_vec, T4dsoma_v_vec)
            T4dsimlist.append(T4dsim)

            T4ddata.append(T4dsoma_v_vec)

    #--------------------------------------------------------------------------------------------------------------------------------------------

    Mi1data = numpy.array(Mi1data, dtype=list)

    print('Starting simulation...')

    h.tstop = 1000

    print('Running simulation...')

    import time
    start_time = time.time()

    h.run()

    print("--- %s seconds ---" % (time.time() - start_time))

    print('Done!')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.figure(str(stimdir))
    pyplot.subplot(2, 3, 1)
    for token in Mi1simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi1')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 2)
    for token in L1simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('L1')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 3)
    for token in Tm3simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Tm3')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 4)
    for token in Mi4simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi4')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 5)
    for token in Mi9simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('Mi9')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 3, 6)
    for token in T4simlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.figure('T4: ' + str(stimdir))

    pyplot.subplot(2, 2, 1)
    for token in T4asimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4a')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 2)
    for token in T4bsimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4b')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 3)
    for token in T4csimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4c')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    pyplot.subplot(2, 2, 4)
    for token in T4dsimlist:
        pyplot.plot(token[0], token[1])

    pyplot.title('T4d')
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    pyplot.show()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    import os

    datafolder = datadict['dataloc'] + 'compressed/' + str(stimdir)

    filename = datafolder + 'Mi1simlist' + '.csv'
    numpy.savetxt(filename, Mi1data, delimiter=',')

    filename = datafolder + 'L1simlist' + '.csv'
    numpy.savetxt(filename, L1data, delimiter=',')

    filename = datafolder + 'Tm3simlist' + '.csv'
    numpy.savetxt(filename, Tm3data, delimiter=',')

    filename = datafolder + 'Mi4simlist' + '.csv'
    numpy.savetxt(filename, Mi4data, delimiter=',')

    filename = datafolder + 'Mi9simlist' + '.csv'
    numpy.savetxt(filename, Mi9data, delimiter=',')

    filename = datafolder + 'T4simlist' + '.csv'
    numpy.savetxt(filename, T4data, delimiter=',')

    filename = datafolder + 'T4asimlist' + '.csv'
    numpy.savetxt(filename, T4adata, delimiter=',')

    filename = datafolder + 'T4bsimlist' + '.csv'
    numpy.savetxt(filename, T4bdata, delimiter=',')

    filename = datafolder + 'T4csimlist' + '.csv'
    numpy.savetxt(filename, T4cdata, delimiter=',')

    filename = datafolder + 'T4dsimlist' + '.csv'
    numpy.savetxt(filename, T4ddata, delimiter=',')

    h.quit()
Example #19
0
def Node(stimdir):

    """This is the program for the efficiency of the node model in the paper _.
    When using this program use the following command:

        ./x86_64/special -python nodetime.py (number)

    Where the numbers are for the direction of the signal:

    (number)
    0: 'rl'
    1: 'du'
    2: 'lr'
    3: 'ud'
    4: 'full' (forward direction)

    The data will be saved in the ./data/times/node directory."""

    datafile = open(datadict['L1data'],'r')
    L1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi1data'],'r')
    Mi1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Tm3data'],'r')
    Tm3list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi4data'],'r')
    Mi4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi9data'],'r')
    Mi9list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4data'],'r')
    T4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4adata'],'r')
    T4alist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4bdata'],'r')
    T4blist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4cdata'],'r')
    T4clist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4ddata'],'r')
    T4dlist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict[stimdir],'r')
    stimdata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['totaldata'],'r')
    fulldata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['areas'],'r')
    area = simplejson.load(datafile)
    datafile.close()

    neurdic = {}

    print('Creating cells...')

    cellids = []

    count = 0

    for f in range(len(fulldata)):

        if fulldata[f] == None:

            continue

        else:

            if str(fulldata[f].cellID) in area.keys():

                #if fulldata[f].cellID in L1list:

                neurdic[fulldata[f].cellID] = neurnode.cell(fulldata[f],area[str(fulldata[f].cellID)])

                #if fulldata[f].cellID in Mi1list:

                #    neurdic[fulldata[f].cellID] = neurnode.cell(fulldata[f],area[str(fulldata[f].cellID)])

    print('Connecting cells..')

    synlist = []

    count = 0

    looklist = []
    nclist = []


    connections = {
    #L1
    'L1_L1'     :[L1list,L1list],
    'L1_Mi1'    :[L1list,Mi1list],
    'L1_Mi4'    :[L1list,Mi4list],
    'L1_Mi9'    :[L1list,Mi9list],
    'L1_Tm3'    :[L1list,Tm3list],
    'L1_T4'     :[L1list,T4list],

    #Mi1
    'Mi1_Mi1'   :[Mi1list,Mi1list],
    'Mi1_L1'    :[Mi1list,L1list],
    'Mi1_Tm3'   :[Mi1list,Tm3list],
    'Mi1_Mi4'   :[Mi1list,Mi4list],
    'Mi1_Mi9'   :[Mi1list,Mi9list],
    'Mi1_T4'    :[Mi1list,T4list],

    #Tm3
    'Tm3_Tm3'   :[Tm3list,Tm3list],
    'Tm3_L1'    :[Tm3list,L1list],
    'Tm3_Mi1'   :[Tm3list,Mi1list],
    'Tm3_Mi4'   :[Tm3list,Mi4list],
    'Tm3_Mi9'   :[Tm3list,Mi9list],
    'Tm3_T4'    :[Tm3list,T4list],

    #Mi4
    'Mi4_Mi4'   :[Mi4list,Mi4list],
    'Mi4_L1'    :[Mi4list,L1list],
    'Mi4_Mi1'   :[Mi4list,Mi1list],
    'Mi4_Tm3'   :[Mi4list,Tm3list],
    'Mi4_Mi9'   :[Mi4list,Mi9list],
    'Mi4_T4'    :[Mi4list,T4list],

    #Mi9
    'Mi9_Mi9'   :[Mi9list,Mi9list],
    'Mi9_L1'    :[Mi9list,L1list],
    'Mi9_Mi1'   :[Mi9list,Mi1list],
    'Mi9_Tm3'   :[Mi9list,Tm3list],
    'Mi9_Mi4'   :[Mi9list,Mi4list],
    'Mi9_T4'    :[Mi9list,T4list],

    #T4
    'T4_T4'     :[T4list,T4list],
    'T4_L1'     :[T4list,L1list],
    'T4_Mi1'    :[T4list,Mi1list],
    'T4_Tm3'    :[T4list,Tm3list],
    'T4_Mi4'    :[T4list,Mi4list],
    'T4_Mi9'    :[T4list,Mi9list],
    }

    for key in neurdic.keys():
        for part in neurdic[key].partners:
            if part in neurdic.keys():

                #L1-----------------------------------------------------------------------------------------------
                """if key in connections['L1_L1'][0] and part in connections['L1_L1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],tau=50)

                    synlist.append(info)"""

                if key in connections['L1_Mi1'][0] and part in connections['L1_Mi1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],tau=50)

                    synlist.append(info)

                if key in connections['L1_Tm3'][0] and part in connections['L1_Tm3'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],tau=50)

                    synlist.append(info)

                #Mi1-----------------------------------------------------------------------------------------------
                """if key in connections['Mi1_Mi1'][0] and part in connections['Mi1_Mi1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                """if key in connections['Mi1_L1'][0] and part in connections['Mi1_L1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                if key in connections['Mi1_Tm3'][0] and part in connections['Mi1_Tm3'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_Mi4'][0] and part in connections['Mi1_Mi4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_Mi9'][0] and part in connections['Mi1_Mi9'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Mi1_T4'][0] and part in connections['Mi1_T4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                #Tm3-----------------------------------------------------------------------------------------------
                """if key in connections['Tm3_Tm3'][0] and part in connections['Tm3_Tm3'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                """if key in connections['Tm3_L1'][0] and part in connections['Tm3_L1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)"""

                if key in connections['Tm3_Mi1'][0] and part in connections['Tm3_Mi1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_Mi4'][0] and part in connections['Tm3_Mi4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_Mi9'][0] and part in connections['Tm3_Mi9'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                if key in connections['Tm3_T4'][0] and part in connections['Tm3_T4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part])

                    synlist.append(info)

                #Mi4-----------------------------------------------------------------------------------------------
                """if key in connections['Mi4_Mi4'][0] and part in connections['Mi4_Mi4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""

                if key in connections['Mi4_Mi1'][0] and part in connections['Mi4_Mi1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi4_Tm3'][0] and part in connections['Mi4_Tm3'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi4_Mi9'][0] and part in connections['Mi4_Mi9'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi4_T4'][0] and part in connections['Mi4_T4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                #Mi9-----------------------------------------------------------------------------------------------
                """if key in connections['Mi9_Mi9'][0] and part in connections['Mi9_Mi9'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)"""

                if key in connections['Mi9_Mi1'][0] and part in connections['Mi9_Mi1'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi9_Tm3'][0] and part in connections['Mi9_Tm3'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi9_Mi4'][0] and part in connections['Mi9_Mi4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)

                if key in connections['Mi9_T4'][0] and part in connections['Mi9_T4'][1]:
                    info = synnode.synapse(neurdic[key],neurdic[part],e=-80)

                    synlist.append(info)
        #Stimuli-----------------------------------------------------------------------------------------------
        if str(stimdir) == 'full':
            if key in stimdata:
                neurdic[key].create_stim(55)
        else:
            if key in stimdata[0]:
                neurdic[key].create_stim(55)
            if key in stimdata[1]:
                neurdic[key].create_stim(155)
            if key in stimdata[2]:
                neurdic[key].create_stim(255)
            if key in stimdata[3]:
                neurdic[key].create_stim(355)
            if key in stimdata[4]:
                neurdic[key].create_stim(455)

    print('Connecting stimulus..')

    print('Running Trials...')

    import time

    for t_space in range(100,1100,100):
        timing = []
        for _ in range(10):

            h.tstop = t_space

            start_time = time.time()

            h.run()

            timing.append(time.time() - start_time)

        timing = numpy.array(timing)
        numpy.savetxt('/groups/scheffer/home/gornetj/Documents/em_neuron/data/times/node/' + str(t_space) + '_' + str(stimdir) + '_data.csv',timing,delimiter=',')

    print('Done!')

    h.quit()
Example #20
0
from neuron import h
pc = h.ParallelContext()
pc.subworlds(1)

s = 'world ({0}, {1}) bbs ({2}, {3}) net ({4}, {5})'.format(
    pc.id_world(), pc.nhost_world(), pc.id_bbs(), pc.nhost_bbs(), pc.id(), pc.nhost()
)

print(s)

from ring import runring

pc.runworker()

for ncell in range(5, 10):
  pc.submit(runring, ncell, 1, 100)

while (pc.working()):
  print(pc.pyret())  

pc.done()
h.quit()

Example #21
0
def nrn_stop():
    h.quit()
def finish():
    ''' proper exit '''
    pc.runworker()
    pc.done()
    h.quit()
Example #23
0
def nrnquit():
    h.quit()
Example #24
0
 def stop(self):
     self.pc.done()
     h.quit()
     self._running = False
Example #25
0
def Compartment(stimdir):
    """This is the program for the compartment model in the paper _.
    When using this program use the following command:

        ./x86_64/special -python compartmenttest.py (number)

    Where the numbers are for the direction of the signal:

    (number)
    0: 'rl'
    1: 'du'
    2: 'lr'
    3: 'ud'
    4: 'full' (forward direction)

    The data will be saved in the ./data/compartment directory."""

    #--------------------------------------------------------------------------------------------------------------------------------------------

    datafile = open(datadict['L1data'], 'r')
    L1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi1data'], 'r')
    Mi1list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Tm3data'], 'r')
    Tm3list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi4data'], 'r')
    Mi4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['Mi9data'], 'r')
    Mi9list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4data'], 'r')
    T4list = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4adata'], 'r')
    T4alist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4bdata'], 'r')
    T4blist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4cdata'], 'r')
    T4clist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['T4ddata'], 'r')
    T4dlist = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict[stimdir], 'r')
    stimdata = pickle.load(datafile)
    datafile.close()

    datafile = open(datadict['totaldata'], 'r')
    fulldata = pickle.load(datafile)
    datafile.close()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    area = {}

    neurdic = {}

    print('Creating cells...')

    count = 0

    #--------------------------------------------------------------------------------------------------------------------------------------------

    for f in range(len(fulldata)):

        if fulldata[f] == None:

            continue

        else:

            #--------------------------------------------------------------------------------------------------------------------------------------------

            neurdic[fulldata[f].cellID] = compressed_neur.cell(fulldata[f])
            area[fulldata[f].cellID] = neurdic[fulldata[f].cellID].totalarea

            count += len(neurdic[fulldata[f].cellID].compartmentdict)

    #--------------------------------------------------------------------------------------------------------------------------------------------

    print('Compartments: ' + str(count))

    datadict['areas'] = datadict['dataloc'] + 'areas.json'

    datafile = open(datadict['areas'], 'w')
    simplejson.dump(area, datafile)
    datafile.close()

    fileloc = open('locationdic.json', 'w')
    simplejson.dump(datadict, fileloc)
    fileloc.close()

    #--------------------------------------------------------------------------------------------------------------------------------------------

    print('Connecting cells..')

    #--------------------------------------------------------------------------------------------------------------------------------------------

    from structneur import compressed_syndend

    connections = {
        #L1
        'L1_L1': [L1list, L1list],
        'L1_Mi1': [L1list, Mi1list],
        'L1_Mi4': [L1list, Mi4list],
        'L1_Mi9': [L1list, Mi9list],
        'L1_Tm3': [L1list, Tm3list],
        'L1_T4': [L1list, T4list],

        #Mi1
        'Mi1_Mi1': [Mi1list, Mi1list],
        'Mi1_L1': [Mi1list, L1list],
        'Mi1_Tm3': [Mi1list, Tm3list],
        'Mi1_Mi4': [Mi1list, Mi4list],
        'Mi1_Mi9': [Mi1list, Mi9list],
        'Mi1_T4': [Mi1list, T4list],

        #Tm3
        'Tm3_Tm3': [Tm3list, Tm3list],
        'Tm3_L1': [Tm3list, L1list],
        'Tm3_Mi1': [Tm3list, Mi1list],
        'Tm3_Mi4': [Tm3list, Mi4list],
        'Tm3_Mi9': [Tm3list, Mi9list],
        'Tm3_T4': [Tm3list, T4list],

        #Mi4
        'Mi4_Mi4': [Mi4list, Mi4list],
        'Mi4_L1': [Mi4list, L1list],
        'Mi4_Mi1': [Mi4list, Mi1list],
        'Mi4_Tm3': [Mi4list, Tm3list],
        'Mi4_Mi9': [Mi4list, Mi9list],
        'Mi4_T4': [Mi4list, T4list],

        #Mi9
        'Mi9_Mi9': [Mi9list, Mi9list],
        'Mi9_L1': [Mi9list, L1list],
        'Mi9_Mi1': [Mi9list, Mi1list],
        'Mi9_Tm3': [Mi9list, Tm3list],
        'Mi9_Mi4': [Mi9list, Mi4list],
        'Mi9_T4': [Mi9list, T4list],

        #T4
        'T4_T4': [T4list, T4list],
        'T4_L1': [T4list, L1list],
        'T4_Mi1': [T4list, Mi1list],
        'T4_Tm3': [T4list, Tm3list],
        'T4_Mi4': [T4list, Mi4list],
        'T4_Mi9': [T4list, Mi9list],
    }

    #--------------------------------------------------------------------------------------------------------------------------------------------

    datadict['connections'] = datadict['dataloc'] + 'connections.json'

    datafile = open(datadict['connections'], 'w')
    simplejson.dump(connections, datafile)
    datafile.close()

    fileloc = open('locationdic.json', 'w')
    simplejson.dump(datadict, fileloc)
    fileloc.close()

    synlist = []

    #--------------------------------------------------------------------------------------------------------------------------------------------

    for key in neurdic.keys():

        #Stimuli-----------------------------------------------------------------------------------------------
        if str(stimdir) == 'full':
            if key in stimdata:
                neurdic[key].create_stim(55)
        else:
            if key in stimdata[0]:
                neurdic[key].create_stim(55)
            if key in stimdata[1]:
                neurdic[key].create_stim(155)
            if key in stimdata[2]:
                neurdic[key].create_stim(255)
            if key in stimdata[3]:
                neurdic[key].create_stim(355)
            if key in stimdata[4]:
                neurdic[key].create_stim(455)

        for p in neurdic[key].partners:

            pID = p[0]
            ploc = p[1]

            sdistances = []
            rdistances = []

            if pID in neurdic.keys():

                receiver = neurdic[pID]
                sender = neurdic[key]
                synloc = ploc

                #L1-----------------------------------------------------------------------------------------------
                """if key in connections['L1_L1'][0] and pID in connections['L1_L1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,tau=50)

                    synlist.append(info)"""

                if key in connections['L1_Mi1'][0] and pID in connections[
                        'L1_Mi1'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['L1_Tm3'][0] and pID in connections[
                        'L1_Tm3'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Mi1-----------------------------------------------------------------------------------------------
                """if key in connections['Mi1_Mi1'][0] and pID in connections['Mi1_Mi1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc)

                    synlist.append(info)"""
                """if key in connections['Mi1_L1'][0] and pID in connections['Mi1_L1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc)

                    synlist.append(info)"""

                if key in connections['Mi1_Tm3'][0] and pID in connections[
                        'Mi1_Tm3'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_Mi4'][0] and pID in connections[
                        'Mi1_Mi4'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_Mi9'][0] and pID in connections[
                        'Mi1_Mi9'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Mi1_T4'][0] and pID in connections[
                        'Mi1_T4'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Tm3-----------------------------------------------------------------------------------------------
                """if key in connections['Tm3_Tm3'][0] and pID in connections['Tm3_Tm3'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc)

                    synlist.append(info)"""
                """if key in connections['Tm3_L1'][0] and pID in connections['Tm3_L1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc)

                    synlist.append(info)"""

                if key in connections['Tm3_Mi1'][0] and pID in connections[
                        'Tm3_Mi1'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_Mi4'][0] and pID in connections[
                        'Tm3_Mi4'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_Mi9'][0] and pID in connections[
                        'Tm3_Mi9'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                if key in connections['Tm3_T4'][0] and pID in connections[
                        'Tm3_T4'][1]:
                    info = compressed_syndend.synapse(sender, receiver, synloc)

                    synlist.append(info)

                #Mi4-----------------------------------------------------------------------------------------------
                """if key in connections['Mi4_Mi4'][0] and pID in connections['Mi4_Mi4'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Mi1'][0] and pID in connections['Mi4_Mi1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi4_Tm3'][0] and pID in connections['Mi4_Tm3'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""

                if key in connections['Mi4_Mi9'][0] and pID in connections[
                        'Mi4_Mi9'][1]:
                    info = compressed_syndend.synapse(sender,
                                                      receiver,
                                                      synloc,
                                                      e=-80)

                    synlist.append(info)

                if key in connections['Mi4_T4'][0] and pID in connections[
                        'Mi4_T4'][1]:
                    info = compressed_syndend.synapse(sender,
                                                      receiver,
                                                      synloc,
                                                      e=-80)

                    synlist.append(info)

                #Mi9-----------------------------------------------------------------------------------------------
                """if key in connections['Mi9_Mi9'][0] and pID in connections['Mi9_Mi9'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Mi1'][0] and pID in connections['Mi9_Mi1'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""
                """if key in connections['Mi9_Tm3'][0] and pID in connections['Mi9_Tm3'][1]:
                    info = compressed_syndend.synapse(sender,receiver,synloc,e=-80)

                    synlist.append(info)"""

                if key in connections['Mi9_Mi4'][0] and pID in connections[
                        'Mi9_Mi4'][1]:
                    info = compressed_syndend.synapse(sender,
                                                      receiver,
                                                      synloc,
                                                      e=-80)

                    synlist.append(info)

                if key in connections['Mi9_T4'][0] and pID in connections[
                        'Mi9_T4'][1]:
                    info = compressed_syndend.synapse(sender,
                                                      receiver,
                                                      synloc,
                                                      e=-80)

                    synlist.append(info)

    print('Synapses: ' + str(len(synlist)))

    #--------------------------------------------------------------------------------------------------------------------------------------------

    print('Running Trials...')

    import time

    for t_space in range(100, 1100, 100):
        timing = []
        for _ in range(10):

            h.tstop = t_space

            start_time = time.time()

            h.run()

            timing.append(time.time() - start_time)

        timing = numpy.array(timing)
        numpy.savetxt(
            '/groups/scheffer/home/gornetj/Documents/em_neuron/data/times/compartment/'
            + str(t_space) + '_' + str(stimdir) + '_data.csv',
            timing,
            delimiter=',')

    print('Done!')

    h.quit()
Example #26
0
    ic = h.IClamp(s(0.5))
    pc.target_var(ic._ref_amp, rank)
    pc.setup_transfer()
    expect_error(h.finitialize, (-65, ))
    teardown()
    del ic, s

    # threads
    mkmodel(ncell)
    transfer1()
    pc.nthread(2)
    init_values()
    run()
    check_values()
    pc.nthread(1)

    # extracellular means use v = vm+vext[0]
    for cell in model[0].values():
        cell.soma.insert("extracellular")
    init_values()
    run()
    check_values()

    teardown()


if __name__ == "__main__":
    test_partrans()
    pc.barrier()
    h.quit()
Example #27
0
def test_spikes(use_mpi4py=False, use_nrnmpi_init=False, file_mode=False):
    # mpi4py needs tp be imported before importing h
    if use_mpi4py:
        from mpi4py import MPI
        from neuron import h, gui
    # without mpi4py we need to call nrnmpi_init explicitly
    elif use_nrnmpi_init:
        from neuron import h, gui
        h.nrnmpi_init()
    # otherwise serial execution
    else:
        from neuron import h, gui

    h('''create soma''')
    h.soma.L=5.6419
    h.soma.diam=5.6419
    h.soma.insert("hh")
    h.soma.nseg = 3
    ic = h.IClamp(h.soma(.25))
    ic.delay = .1
    ic.dur = 0.1
    ic.amp = 0.3

    ic2 = h.IClamp(h.soma(.75))
    ic2.delay = 5.5
    ic2.dur = 1
    ic2.amp = 0.3

    h.tstop = 10
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    pc = h.ParallelContext()

    pc.set_gid2node(pc.id()+1, pc.id())
    myobj = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    pc.cell(pc.id()+1, myobj)

    # NEURON run
    nrn_spike_t = h.Vector()
    nrn_spike_gids = h.Vector()

    # rank 0 record spikes for all gid while others
    # for specific gid. this is for better test coverage.
    pc.spike_record(-1 if pc.id() == 0 else (pc.id()+1), nrn_spike_t, nrn_spike_gids)

    h.run()

    nrn_spike_t = nrn_spike_t.to_python()
    nrn_spike_gids = nrn_spike_gids.to_python()

    # CORENEURON run
    from neuron import coreneuron
    coreneuron.enable = True
    coreneuron.file_mode = file_mode
    coreneuron.verbose = 0
    h.stdinit()
    corenrn_all_spike_t = h.Vector()
    corenrn_all_spike_gids = h.Vector()

    pc.spike_record(-1, corenrn_all_spike_t, corenrn_all_spike_gids )
    pc.psolve(h.tstop)

    corenrn_all_spike_t = corenrn_all_spike_t.to_python()
    corenrn_all_spike_gids = corenrn_all_spike_gids.to_python()

    # check spikes match
    assert(len(nrn_spike_t)) # check we've actually got spikes
    assert(len(nrn_spike_t) == len(nrn_spike_gids)); # matching no. of gids
    assert(nrn_spike_t == corenrn_all_spike_t)
    assert(nrn_spike_gids == corenrn_all_spike_gids)

    h.quit()
Example #28
0
    # write time and calculated dipole to data file only if on the first proc
    # only execute this statement on one proc
    savedat(p, pcID, t_vec, dp_rec_L2, dp_rec_L5, net)

    for elec in lelec:
        print('end; t_vec.size()', t_vec.size(), 'elec.lfp_t.size()',
              elec.lfp_t.size())

    if pcID == 0:
        if debug: print("Simulation run time: %4.4f s" % (time.time() - t0))
        if debug: print("Simulation directory is: %s" % ddir.dsim)
        if paramrw.find_param(doutf['file_param'],
                              'save_spec_data') or usingOngoingInputs(
                                  doutf['file_param']):
            runanalysis(p, doutf['file_param'], doutf['file_dpl_norm'],
                        doutf['file_spec'])  # run spectral analysis
        if paramrw.find_param(doutf['file_param'], 'save_figs'):
            savefigs(ddir, p, p_exp)  # save output figures

    pc.barrier()  # make sure all done in case multiple trials


if __name__ == "__main__":
    if dconf['dorun']:
        if ntrial > 1: runtrials(ntrial, p['inc_evinput'])
        else: runsim()
        pc.runworker()
        pc.done()
    if dconf['doquit']: h.quit()
Example #29
0
def test_spikes(use_mpi4py=False):
    if use_mpi4py:
        from mpi4py import MPI
    h('''create soma''')
    h.soma.L = 5.6419
    h.soma.diam = 5.6419
    h.soma.insert("hh")
    h.soma.nseg = 3
    ic = h.IClamp(h.soma(.25))
    ic.delay = .1
    ic.dur = 0.1
    ic.amp = 0.3

    ic2 = h.IClamp(h.soma(.75))
    ic2.delay = 5.5
    ic2.dur = 1
    ic2.amp = 0.3

    h.tstop = 10
    h.cvode.use_fast_imem(1)
    h.cvode.cache_efficient(1)

    pc = h.ParallelContext()

    pc.set_gid2node(pc.id() + 1, pc.id())
    myobj = h.NetCon(h.soma(0.5)._ref_v, None, sec=h.soma)
    pc.cell(pc.id() + 1, myobj)

    # NEURON spikes run
    nrn_spike_t = h.Vector()
    nrn_spike_gids = h.Vector()
    pc.spike_record(-1, nrn_spike_t, nrn_spike_gids)

    h.run()

    nrn_spike_t = nrn_spike_t.to_python()
    nrn_spike_gids = nrn_spike_gids.to_python()

    # CORENEURON spike_record(-1) / spike_record(gidlist):
    from neuron import coreneuron
    coreneuron.enable = True
    coreneuron.verbose = 0
    h.stdinit()
    corenrn_all_spike_t = h.Vector()
    corenrn_all_spike_gids = h.Vector()

    pc.spike_record(-1 if pc.id() == 0 else (pc.id()), corenrn_all_spike_t,
                    corenrn_all_spike_gids)
    pc.psolve(h.tstop)

    corenrn_all_spike_t = corenrn_all_spike_t.to_python()
    corenrn_all_spike_gids = corenrn_all_spike_gids.to_python()

    # check spikes match
    assert (len(nrn_spike_t))  # check we've actually got spikes
    assert (len(nrn_spike_t) == len(nrn_spike_gids))
    # matching no. of gids
    assert (nrn_spike_t == corenrn_all_spike_t)
    assert (nrn_spike_gids == corenrn_all_spike_gids)

    h.quit()