コード例 #1
0
def test_net_injection(calcium, synapses, spines, single, ghk, plasticity):
    "Create the neuron and run a very short simulation"

    # pytest.skip("skipping network tests")

    if ghk and not hasattr(moose, 'GHK'):
        pytest.skip("GHK is missing")

    if spines and not single:
        pytest.skip("spines are too much with multiple neurons")

    d1d2.calYN = bool(calcium)
    d1d2.plasYN = bool(plasticity)
    d1d2.ghkYN = bool(ghk)
    d1d2.spineYN = bool(spines)
    d1d2.synYN = bool(synapses)
    str_net.single = bool(single)

    MSNsyn, neurons = cell_proto.neuronclasses(d1d2)

    population, connection, plas = create_network.create_network(
        d1d2, str_net, neurons)

    pg = inject_func.setupinj(d1d2, 0.02, 0.01, population['pop'])
    pg.firstLevel = 1e-9

    data = moose.Neutral('/data')

    vmtab, catab, plastab, currtab = tables.graphtables(
        d1d2, neurons, False, 'getGk')

    moose.reinit()
    moose.start(0.05)

    vm1 = vmtab[0][0].vector
    vm2 = vmtab[1][0].vector

    # Quick sanity check that the values are not outlandish.
    # We do not check at the beginning because of the initial fluctuation.
    assert -0.01 < vm1[250] < 0.05
    assert -0.01 < vm2[250] < 0.05
    assert -0.01 < vm1[499] < 0.05
    assert -0.01 < vm2[499] < 0.05
    return vm1, vm2
コード例 #2
0
def test_net_injection(calcium, synapses, spines, single, ghk, plasticity):
    "Create the neuron and run a very short simulation"

    #pytest.skip("skipping network tests")

    if ghk and not hasattr(moose, 'GHK'):
        pytest.skip("GHK is missing")

    if spines and not single:
        pytest.skip("spines are too much with multiple neurons")

    d1d2.calYN = bool(calcium)
    d1d2.plasYN = bool(plasticity)
    d1d2.ghkYN = bool(ghk)
    d1d2.spineYN = bool(spines)
    d1d2.synYN = bool(synapses)
    str_net.single = bool(single)

    MSNsyn, neurons = cell_proto.neuronclasses(d1d2)

    population,connection, plas = create_network.create_network(d1d2, str_net, neurons)

    pg = inject_func.setupinj(d1d2, 0.02, 0.01, population['pop'])
    pg.firstLevel = 1e-9

    data = moose.Neutral('/data')

    vmtab, catab, plastab, currtab = tables.graphtables(d1d2, neurons, False, 'getGk')

    moose.reinit()
    moose.start(0.05)

    vm1 = vmtab[0][0].vector
    vm2 = vmtab[1][0].vector

    # Quick sanity check that the values are not outlandish.
    # We do not check at the beginning because of the initial fluctuation.
    assert -0.01 < vm1[250] < 0.05
    assert -0.01 < vm2[250] < 0.05
    assert -0.01 < vm1[499] < 0.05
    assert -0.01 < vm2[499] < 0.05
    return vm1, vm2
コード例 #3
0
def setup(param_sim, model):
    if param_sim.calcium is not None:
        model.calYN = param_sim.calcium
    if param_sim.spines is not None:
        model.spineYN = param_sim.spines

    condset = getattr(model.Condset, param_sim.neuron_type)

    if param_sim.Kir_offset is not None:
        model.Channels.Kir.X.A_vhalf += param_sim.Kir_offset
        model.Channels.Kir.X.B_vhalf += param_sim.Kir_offset

    for cond in sorted(param_sim.cond):
        name, comp, value = cond
        print('cond:', name, comp, value)
        setup_conductance(condset, name, comp, value)

    new_file = morph_morph_file(model,
                                param_sim.neuron_type,
                                param_sim.morph_file,
                                RA=param_sim.RA, RM=param_sim.RM, CM=param_sim.CM,
                                Erest=param_sim.Erest, Eleak=param_sim.Eleak)
    model.morph_file[param_sim.neuron_type] = new_file.name

    MSNsyn, neurons = cell_proto.neuronclasses(model)
    neuron_paths = {ntype:[neuron.path]
                    for ntype, neuron in neurons.items()}
    pg = inject_func.setupinj(model, param_sim.injection_delay, param_sim.injection_width, neuron_paths)
    tables.graphtables(model, neurons,
                       param_sim.plot_current,
                       param_sim.plot_current_message)
    writer = tables.setup_hdf5_output(model, neurons, compartments=['soma'], filename='d1d2_bs.h5')

    simpaths=['/'+param_sim.neuron_type]
    clocks.assign_clocks(simpaths, param_sim.simdt, param_sim.plotdt, param_sim.hsolve,
                         model.param_cond.NAME_SOMA)

    if param_sim.hsolve and model.calYN:
        calcium.fix_calcium(model.neurontypes(), model)

    return pg, writer
コード例 #4
0
def test_single_injection(calcium, synapses, spines, ghk, plasticity):
    "Create the neuron and run a very short simulation"

    if ghk and not hasattr(moose, 'GHK'):
        pytest.skip("GHK is missing")

    d1d2.calYN = bool(calcium)
    d1d2.plasYN = bool(plasticity)
    d1d2.ghkYN = bool(ghk)
    d1d2.spineYN = bool(spines)
    d1d2.synYN = bool(synapses)

    MSNsyn, neurons = cell_proto.neuronclasses(d1d2)
    neuron_paths = {ntype:[neuron.path]
                    for ntype, neuron in neurons.items()}
    pg = inject_func.setupinj(d1d2, 0.02, 0.01, neuron_paths)
    pg.firstLevel = 1e-8

    data = moose.Neutral('/data')

    vmtab, catab, plastab, currtab = tables.graphtables(d1d2, neurons, False, 'getGk')

    moose.reinit()
    moose.start(0.05)

    vm1 = vmtab[0][0].vector
    vm2 = vmtab[1][0].vector

    # Quick sanity check that the values are not outlandish.
    # We do not check at the beginning because of the initial fluctuation.
    exp = (0.174
           - 0.025 * bool(spines)
           - 0.043 * bool(calcium))

    assert exp - 0.01 < vm1[250] < exp + 0.02
    assert exp - 0.01 < vm2[250] < exp + 0.02

    assert -0.01 < vm1[499] < 0.05
    assert -0.01 < vm2[499] < 0.05
コード例 #5
0
def test_single_injection(calcium, synapses, spines, ghk, plasticity):
    "Create the neuron and run a very short simulation"

    if ghk and not hasattr(moose, 'GHK'):
        pytest.skip("GHK is missing")

    d1d2.calYN = bool(calcium)
    d1d2.plasYN = bool(plasticity)
    d1d2.ghkYN = bool(ghk)
    d1d2.spineYN = bool(spines)
    d1d2.synYN = bool(synapses)

    MSNsyn, neurons = cell_proto.neuronclasses(d1d2)
    neuron_paths = {ntype: [neuron.path] for ntype, neuron in neurons.items()}
    pg = inject_func.setupinj(d1d2, 0.02, 0.01, neuron_paths)
    pg.firstLevel = 1e-8

    data = moose.Neutral('/data')

    vmtab, catab, plastab, currtab = tables.graphtables(
        d1d2, neurons, False, 'getGk')

    moose.reinit()
    moose.start(0.05)

    vm1 = vmtab[0][0].vector
    vm2 = vmtab[1][0].vector

    # Quick sanity check that the values are not outlandish.
    # We do not check at the beginning because of the initial fluctuation.
    exp = (0.174 - 0.025 * bool(spines) - 0.043 * bool(calcium))

    assert exp - 0.01 < vm1[250] < exp + 0.02
    assert exp - 0.01 < vm2[250] < exp + 0.02

    assert -0.01 < vm1[499] < 0.05
    assert -0.01 < vm2[499] < 0.05
コード例 #6
0
        sim_time.append(st)
        plas[ntype] = spines
    param_sim.simtime = max(sim_time)
    param_sim.injection_current = [0]
else:
    ### Current Injection alone, either use values from Paradigm or from command-line options
    if not np.any(param_sim.injection_current):
        param_sim.injection_current = [
            ca1.param_stim.Stimulation.Paradigm.A_inject
        ]
        param_sim.injection_delay = ca1.param_stim.Stimulation.stim_delay
        param_sim.injection_width = ca1.param_stim.Stimulation.Paradigm.width_AP
    all_neurons = {}
    for ntype in neuron.keys():
        all_neurons[ntype] = list([neuron[ntype].path])
    pg = inject_func.setupinj(ca1, param_sim.injection_delay,
                              param_sim.injection_width, all_neurons)

#If calcium and synapses created, could test plasticity at a single synapse in syncomp
#Need to debug this since eliminated param_sim.stimtimes
#See what else needs to be changed in plasticity_test.
if ca1.plasYN:
    plas, stimtab = plasticity_test.plasticity_test(ca1, param_sim.syncomp,
                                                    MSNsyn,
                                                    param_sim.stimtimes)

###############--------------output elements
if param_sim.plot_channels:
    for chan in ca1.Channels.keys():
        libchan = moose.element('/library/' + chan)
        plot_channel.plot_gate_params(libchan, param_sim.plot_activation,
                                      ca1.VMIN, ca1.VMAX, ca1.CAMIN, ca1.CAMAX)
コード例 #7
0
ファイル: multisim.py プロジェクト: ziemowit-s/moose_nerp
def moose_main(corticalinput):
    import numpy as np
    import matplotlib.pyplot as plt
    # plt.ion()

    import moose

    from moose_nerp.prototypes import (create_model_sim,
                                       clocks,
                                       inject_func,
                                       create_network,
                                       tables,
                                       net_output)
    from moose_nerp import d1opt as model
    from moose_nerp import str_net as net

    # additional, optional parameter overrides specified from with python terminal
    # model.Condset.D1.NaF[model.param_cond.prox] /= 3
    # model.Condset.D1.KaS[model.param_cond.prox] *= 3

    net.connect_dict['D1']['ampa']['extern1'].dend_loc.postsyn_fraction = 0.8
    net.param_net.tt_Ctx_SPN.filename = corticalinput
    print('cortical_fraction = {}'.format(net.connect_dict['D1']['ampa']['extern1'].dend_loc.postsyn_fraction))
    model.synYN = True
    model.plasYN = True
    model.calYN = True
    model.spineYN = True
    net.single = True
    create_model_sim.setupOptions(model)
    param_sim = model.param_sim
    param_sim.useStreamer = True
    param_sim.plotdt = .1e-3
    param_sim.stim_loc = model.NAME_SOMA
    param_sim.stim_paradigm = 'inject'
    param_sim.injection_current = [0]  # [-0.2e-9, 0.26e-9]
    param_sim.injection_delay = 0.2
    param_sim.injection_width = 0.4
    param_sim.simtime = 21
    net.num_inject = 0
    net.confile = 'str_connect_plas_simd1opt_{}_corticalfraction_{}'.format(net.param_net.tt_Ctx_SPN.filename, 0.8)

    if net.num_inject == 0:
        param_sim.injection_current = [0]
    #################################-----------create the model: neurons, and synaptic inputs
    model = create_model_sim.setupNeurons(model, network=not net.single)
    all_neur_types = model.neurons
    # FSIsyn,neuron = cell_proto.neuronclasses(FSI)
    # all_neur_types.update(neuron)
    population, connections, plas = create_network.create_network(model, net, all_neur_types)

    ###### Set up stimulation - could be current injection or plasticity protocol
    # set num_inject=0 to avoid current injection
    if net.num_inject < np.inf:
        inject_pop = inject_func.inject_pop(population['pop'], net.num_inject)
    else:
        inject_pop = population['pop']
    # Does setupStim work for network?
    # create_model_sim.setupStim(model)
    pg = inject_func.setupinj(model, param_sim.injection_delay, param_sim.injection_width, inject_pop)
    moose.showmsg(pg)

    ##############--------------output elements
    if net.single:
        # fname=model.param_stim.Stimulation.Paradigm.name+'_'+model.param_stim.location.stim_dendrites[0]+'.npz'
        # simpath used to set-up simulation dt and hsolver
        simpath = ['/' + neurotype for neurotype in all_neur_types]
        create_model_sim.setupOutput(model)
    else:  # population of neurons
        spiketab, vmtab, plastab, catab = net_output.SpikeTables(model, population['pop'], net.plot_netvm, plas,
                                                                 net.plots_per_neur)
        # simpath used to set-up simulation dt and hsolver
        simpath = [net.netname]
        clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt, param_sim.hsolve, model.param_cond.NAME_SOMA)
    if model.synYN and (param_sim.plot_synapse or net.single):
        # overwrite plastab above, since it is empty
        syntab, plastab, stp_tab = tables.syn_plastabs(connections, model)
        nonstim_plastab = tables.nonstimplastabs(plas)

    # Streamer to prevent Tables filling up memory on disk
    # This is a hack, should be better implemented
    if param_sim.useStreamer == True:
        allTables = moose.wildcardFind('/##[ISA=Table]')
        streamer = moose.Streamer('/streamer')
        streamer.outfile = 'plas_simd1opt_{}_corticalfraction_{}.npy'.format(net.param_net.tt_Ctx_SPN.filename, 0.8)
        moose.setClock(streamer.tick, 0.1)
        for t in allTables:
            if any(s in t.path for s in ['plas', 'VmD1_0', 'extern', 'Shell_0']):
                streamer.addTable(t)
            else:
                t.tick = -2

    ################### Actually run the simulation
    def run_simulation(injection_current, simtime):
        print(u'◢◤◢◤◢◤◢◤ injection_current = {} ◢◤◢◤◢◤◢◤'.format(injection_current))
        pg.firstLevel = injection_current
        moose.reinit()
        moose.start(simtime, True)

    traces, names = [], []
    for inj in param_sim.injection_current:
        run_simulation(injection_current=inj, simtime=param_sim.simtime)

    weights = [w.value for w in moose.wildcardFind('/##/plas##[TYPE=Function]')]
    plt.figure()
    plt.hist(weights, bins=100)
    plt.title('plas_sim_{}_corticalfraction_{}'.format(net.param_net.tt_Ctx_SPN.filename, cortical_fraction))
    plt.savefig('plas_simd1opt_{}_corticalfraction_{}.png'.format(net.param_net.tt_Ctx_SPN.filename, 0.8))
    if param_sim.useStreamer == True:
        import atexit
        atexit.register(moose.quit)
    return weights
コード例 #8
0
def moose_main(p):
    stimfreq, presyn, stpYN, trialnum, prefix, ttGPe, ttstr, ttSTN = p

    import numpy as np
    import os
    import moose

    from moose_nerp.prototypes import (calcium, create_model_sim, clocks,
                                       inject_func, create_network, tables,
                                       net_output, util)
    from moose_nerp import ep as model
    from moose_nerp import ep_net as net
    from moose_nerp.graph import net_graph, neuron_graph, spine_graph

    np.random.seed()
    #additional, optional parameter overrides specified from with python terminal
    model.synYN = True
    model.stpYN = stpYN
    net.single = True
    stimtype = 'PSP_'
    outdir = "ep_net/output/"
    ############## if stim_freq>0, stim_paradigm adds regular input and synaptic plasticity at single synapse ####################
    if stimfreq > 0:
        model.param_sim.stim_paradigm = stimtype + str(stimfreq) + 'Hz'
        model.param_stim.Stimulation.StimLoc = model.param_stim.location[
            presyn]
    else:
        model.param_sim.stim_paradigm = 'inject'
    create_model_sim.setupOptions(model)
    param_sim = model.param_sim
    param_sim.injection_current = [0e-12]
    param_sim.injection_delay = 0.0
    param_sim.plot_synapse = False

    if prefix.startswith('POST-HFS'):
        net.connect_dict['ep']['ampa']['extern1'].weight = 0.6  #STN - weaker
        net.connect_dict['ep']['gaba']['extern2'].weight = 0.8  #GPe - weaker
        net.connect_dict['ep']['gaba']['extern3'].weight = 1.4  #str - stronger
    if prefix.startswith('POST-NoDa'):
        net.connect_dict['ep']['ampa'][
            'extern1'].weight = 1.0  #STN - no change
        net.connect_dict['ep']['gaba']['extern2'].weight = 2.8  #GPe - stronger
        net.connect_dict['ep']['gaba'][
            'extern3'].weight = 1.0  #str - no change

    #override time tables here - before creating model, e.g.
    fname_part = ''
    if len(ttGPe):
        net.param_net.tt_GPe.filename = ttGPe
        print('!!!!!!!!!!!!!! new tt file for GPe:',
              net.param_net.tt_GPe.filename, 'trial', trialnum)
        fname_part = fname_part + '_tg_' + os.path.basename(ttGPe)
    else:
        print('$$$$$$$$$$$$$$ old tt file for GPe:',
              net.param_net.tt_GPe.filename, 'trial', trialnum)
    if len(ttstr):
        net.param_net.tt_str.filename = ttstr
        print('!!!!!!!!!!!!!! new tt file for str:',
              net.param_net.tt_str.filename, 'trial', trialnum)
        fname_part = fname_part + '_ts_' + os.path.basename(ttstr)
    else:
        print('$$$$$$$$$$$$$$ old tt file for str:',
              net.param_net.tt_str.filename, 'trial', trialnum)
    if len(ttSTN):
        net.param_net.tt_STN.filename = ttSTN
        print('!!!!!!!!!!!!!! new tt file for STN:',
              net.param_net.tt_STN.filename, 'trial', trialnum)
        fname_part = fname_part + '_ts_' + os.path.basename(ttSTN)
    else:
        print('$$$$$$$$$$$$$$ old tt file for STN:',
              net.param_net.tt_STN.filename, 'trial', trialnum)
    #################################-----------create the model: neurons, and synaptic inputs
    if model.stpYN == False:
        remember_stpYN = False
        model.stpYN = True
        #create network with stp, and then turn it off for extra synapse (if model.stpYN is False)
    else:
        remember_stpYN = True
    fname_stp = str(1 if model.stpYN else 0) + str(1 if remember_stpYN else 0)

    model = create_model_sim.setupNeurons(model, network=not net.single)
    print('trialnum', trialnum)
    population, connections, plas = create_network.create_network(
        model, net, model.neurons)
    model.stpYN = remember_stpYN

    ####### Set up stimulation - could be current injection or plasticity protocol
    # set num_inject=0 to avoid current injection
    if net.num_inject < np.inf:
        model.inject_pop = inject_func.inject_pop(population['pop'],
                                                  net.num_inject)
        if net.num_inject == 0:
            param_sim.injection_current = [0]
    else:
        model.inject_pop = population['pop']

    ############## Set-up test of synaptic plasticity at single synapse ####################
    if presyn == 'str':
        stp_params = net.param_net.str_plas
    elif presyn == 'GPe':
        stp_params = net.param_net.GPe_plas
    else:
        print('########### unknown synapse type', 'trial', trialnum)

    param_sim.fname = 'ep' + prefix + stimtype + presyn + '_freq' + str(
        stimfreq) + '_plas' + fname_stp + fname_part + 't' + str(trialnum)
    print(
        '>>>>>>>>>> moose_main, presyn {} stpYN {} stimfreq {} simtime {} trial {} plotcomps {} tt {} {}'
        .format(presyn, model.stpYN, stimfreq, param_sim.simtime, trialnum,
                param_sim.plotcomps, ttGPe, ttstr))

    create_model_sim.setupStim(model)
    print('>>>> After setupStim, simtime:', param_sim.simtime, 'trial',
          trialnum, 'stpYN', model.stpYN)
    ##############--------------output elements
    if net.single:
        create_model_sim.setupOutput(model)
    else:  #population of neurons
        model.spiketab, model.vmtab, model.plastab, model.catab = net_output.SpikeTables(
            model, population['pop'], net.plot_netvm, plas, net.plots_per_neur)
        #simpath used to set-up simulation dt and hsolver
        simpath = [net.netname]
        clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt,
                             param_sim.hsolve, model.param_cond.NAME_SOMA)
        # Fix calculation of B parameter in CaConc if using hsolve
        if model.param_sim.hsolve and model.calYN:
            calcium.fix_calcium(util.neurontypes(model.param_cond), model)
    #
    if model.synYN and (param_sim.plot_synapse or net.single):
        #overwrite plastab above, since it is empty
        model.syntab, model.plastab, model.stp_tab = tables.syn_plastabs(
            connections, model)
    #
    #add short term plasticity to synapse as appropriate
    param_dict = {
        'syn': presyn,
        'freq': stimfreq,
        'plas': model.stpYN,
        'inj': param_sim.injection_current,
        'simtime': param_sim.simtime,
        'trial': trialnum,
        'dt': param_sim.plotdt
    }
    if stimfreq > 0:
        from moose_nerp.prototypes import plasticity_test as plas_test
        extra_syntab = {ntype: [] for ntype in model.neurons.keys()}
        extra_plastabset = {ntype: [] for ntype in model.neurons.keys()}
        for ntype in model.neurons.keys():
            for tt_syn_tuple in model.tuples[ntype].values():
                if model.stpYN:
                    extra_syntab[ntype], extra_plastabset[
                        ntype] = plas_test.short_term_plasticity_test(
                            tt_syn_tuple,
                            syn_delay=0,
                            simdt=model.param_sim.simdt,
                            stp_params=stp_params)
                    print('!!!!!!!!!!!!! setting up plasticity, stpYN',
                          model.stpYN)
                else:
                    extra_syntab[ntype] = plas_test.short_term_plasticity_test(
                        tt_syn_tuple, syn_delay=0)
                    print('!!!!!!!!!!!!! NO plasticity, stpYN', model.stpYN)
            param_dict[ntype] = {
                'syn_tt':
                [(k, tt[0].vector) for k, tt in model.tuples[ntype].items()]
            }
    #
    #################### Actually run the simulation
    param_sim.simtime = 5.0
    print('$$$$$$$$$$$$$$ paradigm=',
          model.param_stim.Stimulation.Paradigm.name, ' inj=0? ',
          np.all([inj == 0 for inj in param_sim.injection_current]),
          'simtime:', param_sim.simtime, 'trial', trialnum, 'fname',
          outdir + param_sim.fname)
    if model.param_stim.Stimulation.Paradigm.name is not 'inject' and not np.all(
        [inj == 0 for inj in param_sim.injection_current]):
        pg = inject_func.setupinj(model, param_sim.injection_delay,
                                  model.param_sim.simtime, model.inject_pop)
        inj = [i for i in param_sim.injection_current if i != 0]
        pg.firstLevel = param_sim.injection_current[0]
        create_model_sim.runOneSim(model, simtime=model.param_sim.simtime)
    else:
        for inj in model.param_sim.injection_current:
            create_model_sim.runOneSim(model,
                                       simtime=model.param_sim.simtime,
                                       injection_current=inj)

    #net_output.writeOutput(model, param_sim.fname+'vm',model.spiketab,model.vmtab,population)
    #
    #Save results: spike time, Vm, parameters, input time tables
    from moose_nerp import ISI_anal
    spike_time, isis = ISI_anal.spike_isi_from_vm(
        model.vmtab, param_sim.simtime, soma=model.param_cond.NAME_SOMA)
    vmout = {
        ntype: [tab.vector for tab in tabset]
        for ntype, tabset in model.vmtab.items()
    }
    if np.any([len(st) for tabset in spike_time.values() for st in tabset]):
        np.savez(outdir + param_sim.fname,
                 spike_time=spike_time,
                 isi=isis,
                 params=param_dict,
                 vm=vmout)
    else:
        print('no spikes for', param_sim.fname, 'saving vm and parameters')
        np.savez(outdir + param_sim.fname, params=param_dict, vm=vmout)
    if net.single:
        #save spiketime of all input time tables
        timtabs = {}
        for neurtype, neurtype_dict in connections.items():
            for neur, neur_dict in neurtype_dict.items():
                for syn, syn_dict in neur_dict.items():
                    timtabs[syn] = {}
                    for pretype, pre_dict in syn_dict.items():
                        timtabs[syn][pretype] = {}
                        for branch, presyn in pre_dict.items():
                            for i, possible_tt in enumerate(presyn):
                                if 'TimTab' in possible_tt:
                                    timtabs[syn][pretype][
                                        branch + '_syn' +
                                        str(i)] = moose.element(
                                            possible_tt).vector
        np.save(outdir + 'tt' + param_sim.fname, timtabs)

    #create dictionary with the output (vectors) from test plasticity
    tab_dict = {}
    if stimfreq > 0:
        for ntype, tabset in extra_syntab.items():
            tab_dict[ntype] = {
                'syn': tabset.vector,
                'syndt': tabset.dt,
                'tt': {
                    ntype + '_' + pt: tab.vector
                    for pt, tab in model.tt[ntype].items()
                }
            }
            if model.stpYN:
                tab_dict[ntype]['plas'] = {
                    tab.name: tab.vector
                    for tab in extra_plastabset[ntype]
                }
    return param_dict, tab_dict, vmout, spike_time, isis
コード例 #9
0
ファイル: __main__.py プロジェクト: asiaszmek/moose_nerp
    param_dict={'syn':presyn,'freq':stimfreq,'plas':model.stpYN,'inj':param_sim.injection_current,'simtime':param_sim.simtime}
    for ntype in model.neurons.keys():
        for tt_syn_tuple in model.tuples[ntype].values():
            if model.stpYN:
                syntab[ntype],plastabset[ntype]=plas_test.short_term_plasticity_test(tt_syn_tuple,syn_delay=0,
                                                                       simdt=model.param_sim.simdt,stp_params=stp_params)
            else:
                syntab[ntype]=plas_test.short_term_plasticity_test(tt_syn_tuple,syn_delay=0)
        param_dict[ntype]={'syn_tt': [(k,tt[0].vector) for k,tt in model.tuples[ntype].items()]}

#additional current injection, e.g. if an offset current is desired
if model.param_stim.Stimulation.Paradigm.name is not 'inject' and not np.all([inj==0 for inj in param_sim.injection_current]):
    print('$$$$$$$$$$$$$$ stim paradigm',model.param_stim.Stimulation.Paradigm.name, 'inject', param_sim.injection_current)
    neuron_pop = {ntype:[neur.path] for ntype, neur in model.neurons.items()}
    #set injection width to simulation time
    pg=inject_func.setupinj(model, param_sim.injection_delay,param_sim.simtime,neuron_pop)
    pg.firstLevel = param_sim.injection_current[0]

##################### for debugging: shows that some spikes elicit 2x increase in weight
fac=moose.element('/ep/p0b1b1b2/gaba/fac0')
x0=fac.x[0]
x1=fac.x[1]
x0tab=moose.Table('x0tab')
x1tab=moose.Table('x1tab')
moose.connect(x0tab,'requestOut',x0,'getValue')
moose.connect(x1tab,'requestOut',x1,'getValue')
ttstate=moose.Table('/data/ttstate')
tt=list(model.tuples['ep'].values())[0][0]
moose.connect(ttstate, 'requestOut', tt, 'getState')
param_sim.simtime=0.1
##################### 
コード例 #10
0
ファイル: __main__.py プロジェクト: neurord/spspine
#################################-----------create the model: neurons, and synaptic inputs
model=create_model_sim.setupNeurons(model,network=not net.single)
all_neur_types=model.neurons
#FSIsyn,neuron = cell_proto.neuronclasses(FSI)
#all_neur_types.update(neuron)
population,connections,plas=create_network.create_network(model, net, all_neur_types)

###### Set up stimulation - could be current injection or plasticity protocol
# set num_inject=0 to avoid current injection
if net.num_inject<np.inf :
    inject_pop=inject_func.inject_pop(population['pop'],net.num_inject)
else:
    inject_pop=population['pop']
#Does setupStim work for network?
#create_model_sim.setupStim(model)
pg=inject_func.setupinj(model, param_sim.injection_delay,param_sim.injection_width,inject_pop)
moose.showmsg(pg)

##############--------------output elements
if net.single:
    #fname=model.param_stim.Stimulation.Paradigm.name+'_'+model.param_stim.location.stim_dendrites[0]+'.npz'
    #simpath used to set-up simulation dt and hsolver
    simpath=['/'+neurotype for neurotype in all_neur_types]
    create_model_sim.setupOutput(model)
else:   #population of neurons
    spiketab,vmtab,plastab,catab=net_output.SpikeTables(model, population['pop'], net.plot_netvm, plas, net.plots_per_neur)
    #simpath used to set-up simulation dt and hsolver
    simpath=[net.netname]
    clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt, param_sim.hsolve,model.param_cond.NAME_SOMA)
if model.synYN and (param_sim.plot_synapse or net.single):
    #overwrite plastab above, since it is empty
コード例 #11
0
def setup(param_sim, model):
    #these next two overrides are not used in optimization as they are not passed in from optimize
    #they could be used if running basic_simulation directly
    '''
    if param_sim.calcium is not None:
        model.calYN = param_sim.calcium
    if param_sim.spines is not None:
        model.spineYN = param_sim.spines
     '''
    '''
    if model.type = nml:
        this block of code updates neuroml files
        write a bunch of new  code
    else:
        #this block of code updates moose_nerp foramt files
    '''
    condset = getattr(
        model.Condset,
        param_sim.neuron_type)  # Fetch reference for model condutances.
    chanset = model.Channels  # Fetch reference for model channels.

    for cond in sorted(param_sim.cond):
        name, comp, value = cond
        if logger.level == logging.DEBUG:
            print('cond:', name, comp, value)
        setup_conductance(condset, name, comp, value)

    for chan in param_sim.chan:
        chan_name, opt, gate, value = chan
        if logger.level == logging.DEBUG:
            print('chan:', chan_name, opt, gate, value)
        if opt == 'taumul':
            scale_voltage_dependents_tau_muliplier(chanset, chan_name, gate,
                                                   value)
        elif opt == 'vshift':
            offset_voltage_dependents_vshift(chanset, chan_name, gate, value)

    new_file = morph_morph_file(model,
                                param_sim.neuron_type,
                                param_sim.morph_file,
                                RA=param_sim.RA,
                                RM=param_sim.RM,
                                CM=param_sim.CM,
                                Erest=param_sim.Erest,
                                Eleak=param_sim.Eleak)
    logger.info('morph_file: {}'.format(new_file.name))
    model.morph_file[param_sim.neuron_type] = new_file.name
    #end of code that updates moose_nerp files

    plotcomps = [model.param_cond.NAME_SOMA]
    fname = param_sim.neuron_type + '.h5'
    param_sim.save = 1
    #create neuron model and set up output
    model.param_sim = param_sim
    setup_CaPool(param_sim, model)
    #syn,neurons,writer,tables=create_model_sim.create_model_sim(model,fname,param_sim,plotcomps)
    create_model_sim.setupNeurons(model)
    #set up current injection
    neuron_paths = {
        ntype: [neuron.path]
        for ntype, neuron in model.neurons.items()
    }
    pg = inject_func.setupinj(model, param_sim.injection_delay,
                              param_sim.injection_width, neuron_paths)
    writer = tables.setup_hdf5_output(model,
                                      model.neurons,
                                      filename=fname,
                                      compartments=plotcomps)
    tables.graphtables(model, model.neurons, model.param_sim.plot_current,
                       model.param_sim.plot_current_message, model.plas,
                       plotcomps)
    if logger.level == logging.DEBUG:
        print_params.print_elem_params(model, param_sim.neuron_type, param_sim)
    return pg, writer
コード例 #12
0
ファイル: __main__.py プロジェクト: ziemowit-s/moose_nerp
#################################-----------create the model: neurons, and synaptic inputs
model = create_model_sim.setupNeurons(model, network=not net.single)
all_neur_types = model.neurons
# FSIsyn,neuron = cell_proto.neuronclasses(FSI)
# all_neur_types.update(neuron)
population, connections, plas = create_network.create_network(model, net, all_neur_types)

###### Set up stimulation - could be current injection or plasticity protocol
# set num_inject=0 to avoid current injection
if net.num_inject < np.inf:
    inject_pop = inject_func.inject_pop(population['pop'], net.num_inject)
else:
    inject_pop = population['pop']
# Does setupStim work for network?
# create_model_sim.setupStim(model)
pg = inject_func.setupinj(model, param_sim.injection_delay, param_sim.injection_width, inject_pop)
moose.showmsg(pg)

##############--------------output elements
if net.single:
    # fname=model.param_stim.Stimulation.Paradigm.name+'_'+model.param_stim.location.stim_dendrites[0]+'.npz'
    # simpath used to set-up simulation dt and hsolver
    simpath = ['/' + neurotype for neurotype in all_neur_types]
    create_model_sim.setupOutput(model)
else:  # population of neurons
    spiketab, vmtab, plastab, catab = net_output.SpikeTables(model, population['pop'], net.plot_netvm, plas,
                                                             net.plots_per_neur)
    # simpath used to set-up simulation dt and hsolver
    simpath = [net.netname]
    clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt, param_sim.hsolve, model.param_cond.NAME_SOMA)
if model.synYN and (param_sim.plot_synapse or net.single):
コード例 #13
0
ファイル: multisim.py プロジェクト: ziemowit-s/moose_nerp
def moose_main(p):
    stimfreq, presyn, stpYN, inj = p
    import numpy as np
    from moose_nerp.prototypes import create_model_sim, inject_func
    from moose_nerp import ep as model

    model.synYN = True
    model.stpYN = stpYN
    outdir = "ep/output/"
    stimtype = 'PSP_'  # choose from AP and PSP
    model.param_sim.stim_paradigm = stimtype + str(stimfreq) + 'Hz'
    create_model_sim.setupOptions(model)
    # Parameter overrides can be specified:

    param_sim = model.param_sim
    param_sim.injection_current = [inj]
    param_sim.injection_delay = 0.0
    param_sim.save_txt = True
    param_sim.plot_synapse = False
    param_sim.plot_calcium = False

    # this is only needed if adding short term plasticity to synapse
    from moose_nerp import ep_net as net
    if presyn == 'str' and model.stpYN:
        stp_params = net.param_net.str_plas
    elif presyn == 'GPe' and model.stpYN:
        stp_params = net.param_net.GPe_plas
    else:
        print('########### unknown synapse type', presyn)

    param_sim.fname = 'ep' + stimtype + presyn + '_freq' + str(
        stimfreq) + '_plas' + str(1 if model.stpYN else 0) + '_inj' + str(
            param_sim.injection_current[0])
    print(
        '>>>>>>>>>> moose_main, stimfreq {} presyn {} stpYN {} plot comps {}'.
        format(stimfreq, presyn, stpYN, param_sim.plotcomps))

    # This function creates the neuron(s) in Moose:
    create_model_sim.setupNeurons(model)

    # This function sets up the Output options, e.g. saving, graph tables, etc.

    create_model_sim.setupOutput(model)

    # This function sets up the stimulation in Moose, e.g. pulsegen for current
    # injection or synaptic stimulation:
    create_model_sim.setupStim(model)

    # add short term plasticity to synapse as appropriate
    param_dict = {
        'syn': presyn,
        'freq': stimfreq,
        'plas': model.stpYN,
        'inj': param_sim.injection_current,
        'simtime': param_sim.simtime,
        'dt': param_sim.plotdt
    }
    from moose_nerp.prototypes import plasticity_test as plas_test
    syntab = {ntype: [] for ntype in model.neurons.keys()}
    plastabset = {ntype: [] for ntype in model.neurons.keys()}
    param_dict = {
        'syn': presyn,
        'freq': stimfreq,
        'plas': model.stpYN,
        'inj': param_sim.injection_current,
        'simtime': param_sim.simtime
    }
    for ntype in model.neurons.keys():
        for tt_syn_tuple in model.tuples[ntype].values():
            if model.stpYN:
                syntab[ntype], plastabset[
                    ntype] = plas_test.short_term_plasticity_test(
                        tt_syn_tuple,
                        syn_delay=0,
                        simdt=model.param_sim.simdt,
                        stp_params=stp_params)
            else:
                syntab[ntype] = plas_test.short_term_plasticity_test(
                    tt_syn_tuple, syn_delay=0)
        param_dict[ntype] = {
            'syn_tt':
            [(k, tt[0].vector) for k, tt in model.tuples[ntype].items()]
        }

    # simulate the model
    if model.param_stim.Stimulation.Paradigm.name is not 'inject' and not np.all(
        [ij == 0 for ij in param_sim.injection_current]):
        print('$$$$$$$$$$$$$$ stim paradigm',
              model.param_stim.Stimulation.Paradigm.name, 'inject',
              param_sim.injection_current)
        neuron_pop = {
            ntype: [neur.path]
            for ntype, neur in model.neurons.items()
        }
        # set injection width to simulation time
        pg = inject_func.setupinj(model, param_sim.injection_delay,
                                  model.param_sim.simtime, neuron_pop)
        # for ij in model.param_sim.injection_current:
        pg.firstLevel = param_sim.injection_current[0]
    '''
            create_model_sim.runOneSim(model, simtime=model.param_sim.simtime)
    else:
    '''
    create_model_sim.runAll(model, printParams=True)
    print('<<<<<<<<<<< moose_main, sim {} finished'.format(param_sim.fname))

    # Extract spike times and calculate ISI if spikes occur
    vmtab = {
        ntype: [tab.vector for tab in tabset]
        for ntype, tabset in model.vmtab.items()
    }
    import numpy as np
    import ISI_anal
    # stim_spikes are spikes that occur during stimulation - they prevent correct psp_amp calculation
    spike_time, isis = ISI_anal.spike_isi_from_vm(
        model.vmtab, param_sim.simtime, soma=model.param_cond.NAME_SOMA)
    stim_spikes = ISI_anal.stim_spikes(spike_time,
                                       model.tt,
                                       soma=model.param_cond.NAME_SOMA)
    if not np.all(
        [len(st) for tabset in stim_spikes.values() for st in tabset]):
        psp_amp, psp_norm = ISI_anal.psp_amp(model.vmtab,
                                             model.tt,
                                             soma=model.param_cond.NAME_SOMA)
        np.savez(outdir + param_sim.fname,
                 amp=psp_amp,
                 norm=psp_norm,
                 params=param_dict,
                 vm=vmtab)
        print('&&&&&&&&&&&&&&&&& Saving PSP amplitude &&&&&&&&&&&&&&&&&&&',
              param_sim.fname)
    if np.any([len(st) for tabset in stim_spikes.values() for st in tabset]):
        np.savez(outdir + param_sim.fname,
                 spike_time=spike_time,
                 isi=isis,
                 params=param_dict,
                 vm=vmtab)
        print('&&&&&&&&&&&&&&&&& Saving spike times &&&&&&&&&&&&&&&&&&&',
              param_sim.fname)
    #
    # create dictionary with the output (vectors) from tables
    tab_dict = {}
    for ntype, tabset in syntab.items():
        tab_dict[ntype] = {
            'syn': tabset.vector,
            'syndt': tabset.dt,
            'tt': {
                ntype + '_' + pt: tab.vector
                for pt, tab in model.tt[ntype].items()
            }
        }  # ,'tt_dt':tabset.dt}
        if model.stpYN:
            tab_dict[ntype]['plas'] = {
                tab.name: tab.vector
                for tab in plastabset[ntype]
            }

    return param_dict, tab_dict, vmtab, spike_time, isis
コード例 #14
0
ファイル: multisim.py プロジェクト: neurord/spspine
def moose_main(p):
    stimfreq,presyn,stpYN,trialnum=p

    import numpy as np
    import moose

    from moose_nerp.prototypes import (create_model_sim,
                                       clocks,
                                       inject_func,
                                       create_network,
                                       tables,
                                       net_output,
                                       util)
    from moose_nerp import ep as model
    from moose_nerp import ep_net as net
    from moose_nerp.graph import net_graph, neuron_graph, spine_graph


    #additional, optional parameter overrides specified from with python terminal
    model.synYN = True
    model.stpYN = stpYN
    net.single=True
    model.param_sim.stim_paradigm='PSP_'+str(stimfreq)+'Hz'
    model.param_stim.Stimulation.StimLoc=model.param_stim.location[presyn]

    create_model_sim.setupOptions(model)
    param_sim = model.param_sim
    param_sim.injection_current = [0e-12]
    param_sim.injection_delay = 0.0
    param_sim.plot_synapse=False

    #################################-----------create the model: neurons, and synaptic inputs
    model=create_model_sim.setupNeurons(model,network=not net.single)
    population,connections,plas=create_network.create_network(model, net, model.neurons)

    ####### Set up stimulation - could be current injection or plasticity protocol
    # set num_inject=0 to avoid current injection
    if net.num_inject<np.inf :
        model.inject_pop=inject_func.inject_pop(population['pop'],net.num_inject)
    else:
        model.inject_pop=population['pop']
        if net.num_inject==0:
            param_sim.injection_current=[0]

    ############## Set-up test of synaptic plasticity at single synapse ####################
    if presyn=='str':
        stp_params=net.param_net.str_plas
    elif presyn=='GPe':
        stp_params=net.param_net.GPe_plas
    else:
        print('########### unknown synapse type')

    param_sim.fname='epGABA_syn'+presyn+'_freq'+str(stimfreq)+'_plas'+str(1 if model.stpYN else 0)+'_inj'+str(param_sim.injection_current[0])+'t'+str(trialnum)
    print('>>>>>>>>>> moose_main, presyn {} stpYN {} stimfreq {} trial {}'.format(presyn,model.stpYN,stimfreq,trialnum))

    create_model_sim.setupStim(model)
    if model.param_stim.Stimulation.Paradigm.name is not 'inject' and not np.all([inj==0 for inj in param_sim.injection_current]):
        pg=inject_func.setupinj(model, param_sim.injection_delay,param_sim.injection_width,model.inject_pop)
        pg.firstLevel = param_sim.injection_current[0]


    ##############--------------output elements
    if net.single:
        #fname=model.param_stim.Stimulation.Paradigm.name+'_'+model.param_stim.location.stim_dendrites[0]+'.npz'
        create_model_sim.setupOutput(model)
    else:   #population of neurons
        spiketab,vmtab,plastab,catab=net_output.SpikeTables(model, population['pop'], net.plot_netvm, plas, net.plots_per_neur)
        #simpath used to set-up simulation dt and hsolver
        simpath=[net.netname]
        clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt, param_sim.hsolve,model.param_cond.NAME_SOMA)
        # Fix calculation of B parameter in CaConc if using hsolve
        if model.param_sim.hsolve and model.calYN:
            calcium.fix_calcium(util.neurontypes(model.param_cond), model)

    if model.synYN and (param_sim.plot_synapse or net.single):
        #overwrite plastab above, since it is empty
        syntab, plastab, stp_tab=tables.syn_plastabs(connections,model)

    from moose_nerp.prototypes import plasticity_test as plas_test
    extra_syntab={ntype:[] for ntype in  model.neurons.keys()}
    extra_plastabset={ntype:[] for ntype in  model.neurons.keys()}
    param_dict={'syn':presyn,'freq':stimfreq,'plas':model.stpYN,'inj':param_sim.injection_current,'simtime':param_sim.simtime, 'trial': trialnum}
    for ntype in model.neurons.keys():
        for tt_syn_tuple in model.tuples[ntype].values():
            if model.stpYN:
                extra_syntab[ntype],extra_plastabset[ntype]=plas_test.short_term_plasticity_test(tt_syn_tuple,syn_delay=0,
                                                                        simdt=model.param_sim.simdt,stp_params=stp_params)
            else:
                extra_syntab[ntype]=plas_test.short_term_plasticity_test(tt_syn_tuple,syn_delay=0)
        param_dict[ntype]={'syn_tt': [(k,tt[0].vector) for k,tt in model.tuples[ntype].items()]}
    #
    #################### Actually run the simulation
    if not np.all([inj==0 for inj in param_sim.injection_current]):
        inj=[i for i in param_sim.injection_current if i !=0]
        create_model_sim.runOneSim(model, simtime=model.param_sim.simtime, injection_current=inj[0])
    else:
        create_model_sim.runOneSim(model)
    #net_output.writeOutput(model, param_sim.fname+'vm',spiketab,vmtab,population)
    #
    import ISI_anal
    #stim_spikes are spikes that occur during stimulation - they prevent correct psp_amp calculation
    spike_time,isis=ISI_anal.spike_isi_from_vm(model.vmtab,param_sim.simtime)
    stim_spikes=ISI_anal.stim_spikes(spike_time,model.tt)
    if np.any([len(st) for tabset in spike_time.values() for st in tabset]):
        np.savez(param_sim.fname,spike_time=spike_time,isi=isis,params=param_dict)
    else:
        print('no spikes for',param_sim.fname)
    #create dictionary with the output (vectors) from tables 
    tab_dict={}
    for ntype,tabset in extra_syntab.items():
        tab_dict[ntype]={'syn':tabset.vector,'syndt':tabset.dt, 
        'tt': {ntype+'_'+pt:tab.vector for pt,tab in model.tt[ntype].items()}}#,'tt_dt':tabset.dt}
        if model.stpYN:
            tab_dict[ntype]['plas']={tab.name:tab.vector for tab in extra_plastabset[ntype]}
    vmtab={ntype:[tab.vector for tab in tabset] for ntype,tabset in model.vmtab.items()}
    return param_dict,tab_dict,vmtab,spike_time,isis