Ejemplo n.º 1
0
running a simulation, the output tables would be accessible as model.vmtab,
model.catab, etc.'''

# Parameter overrides can be specified:
model.spineYN=False
model.calYN=True

# This function sets up the options specified in param_sim or passed from
# command line:
create_model_sim.setupOptions(model)

# 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)

# There is also a convenience function, `create_model_sim.setupAll(model)` that
# would sequentially call the above four functions: setupOptions, setupNeurons,
# setupOutput, and setupStim

# This function runs all the specified simulations, plotting and saving them
# as specified:
create_model_sim.runAll(model)

# Alternative function to create_model_sim.runAll, that runs a simulation a few
# steps at a time and then updates a plot, to show the live simulation results.
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
running a simulation, the output tables would be accessible as model.vmtab,
model.catab, etc.'''

# Parameter overrides can be specified:
model.spineYN=False
model.calYN=False

# This function sets up the options specified in param_sim or passed from
# command line:
create_model_sim.setupOptions(model)

# 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)

# There is also a convenience function, `create_model_sim.setupAll(model)` that
# would sequentially call the above four functions: setupOptions, setupNeurons,
# setupOutput, and setupStim

# This function runs all the specified simulations, plotting and saving them
# as specified:
create_model_sim.runAll(model)

# Alternative function to create_model_sim.runAll, that runs a simulation a few
# steps at a time and then updates a plot, to show the live simulation results.
Ejemplo n.º 4
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
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
def moose_main(p):
    stop_signal,freqCtx,freqStn,pulsedur,rampdur,fb_npas,fb_lhx,FSI_input,simtime,trial=p
    import numpy as np
    import moose
    import importlib
    from moose_nerp.prototypes import (calcium,
                                       cell_proto,
                                       create_model_sim,
                                       clocks,
                                       inject_func,
                                       create_network,
                                       pop_funcs,
                                       tables,
                                       net_output,
                                       util,
                                       multi_module,
                                       net_sim_graph)
    from moose_nerp import spn_1comp as model
    from moose_nerp import bg_net as net

    #output file names and time table inputs depend on input parameters
    net.confile,net.outfile=net.fname(stop_signal,freqCtx,freqStn,pulsedur,rampdur,fb_npas,fb_lhx,FSI_input)
    net.outfile=net.outfile+'t'+str(trial)
    if stop_signal: #regardless, STN2000_lognorm_freq28.0.npz is used
        print('if stop signal',stop_signal,'param_net',net.param_net.tt_Ctx)
        net.param_net.tt_Ctx.filename='bg_net/Ctx10000_ramp_freq5.0_'+freqCtx+'dur'+str(rampdur)
        net.param_net.tt_STNp.filename='bg_net/STN500_pulse_freq1.0_'+freqStn+'dur'+str(pulsedur)
    else:
        net.param_net.tt_Ctx.filename='bg_net/Ctx10000_osc_freq'+freqCtx+'_osc0.7'
   
    if stop_signal: #add in second "pulse" time table, change postyn fraction for the log normal inpput
        net.connect_dict,net.change_prob=net.add_connect(net.connect_dict,net.change_prob,freqStn) 
    
    net.connect_dict=net.feedback(net.connect_dict,fb_npas,fb_lhx)
    net.connect_delete=net.change_FSI(net.connect_delete,net.p['FSI_input'])

    np.random.seed()
    #names of additional neuron modules to import
    neuron_modules=['ep_1comp','proto154_1compNoCal','Npas2005_1compNoCal','arky140_1compNoCal','FSI01Aug2014']

    ### By importing network modules, no need to repeat all the information in param_net.py
    net_modules=['moose_nerp.ep_net','moose_nerp.gp_net', 'moose_nerp.spn1_net']

    #only save vm trace from save_num neurons of each type if there are more than too_many_neurons
    #consider putting this stuff into param_net
    too_many_neurons=30
    save_num=2
    savett=True
    save_conn=False

    #additional, optional parameter overrides specified from with python terminal
    model.synYN = True
    net.single=False
    outdir="bg_net/output/"
    create_model_sim.setupOptions(model)
    param_sim = model.param_sim
    param_sim.injection_current = [0e-12]
    net.num_inject=0
    param_sim.injection_width=0.3
    param_sim.injection_delay=0.2
    param_sim.save_txt = True
    param_sim.simtime=simtime
    
    #################################-----------create the model: neurons, and synaptic inputs
    #### Do not setup hsolve yet, since there may be additional neuron_modules
    model=create_model_sim.setupNeurons(model,network=True)

    #create dictionary of BufferCapacityDensity - only needed if hsolve, simple calcium dynamics
    buf_cap={neur:model.param_ca_plas.BufferCapacityDensity for neur in model.neurons.keys()}

    #import additional neuron modules, add them to neurons and synapses
    ######## this is skipped if neuron_modules is empty
    if len(neuron_modules):
        buf_cap=multi_module.multi_modules(neuron_modules,model,buf_cap,net.change_syn)

    ########### Create Network. For multiple populations, send in net_modules ###########
    population,[connections,conn_summary],plas=create_network.create_network(model, net, model.neurons,network_list=net_modules)
    #print(net.connect_dict)
    total_neurons=np.sum([len(pop) for pop in population['pop'].values()])
    if total_neurons<too_many_neurons:
        print('populations created and connected!!!',population['pop'],'\n',population['netnames'])
    else:
        print('populations created and connected!!!',[(key,len(pop)) for key,pop in population['pop'].items()])
    ###### 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']

    create_model_sim.setupStim(model)

##############--------------output elements
    if net.single:
        #simpath used to set-up simulation dt and hsolver
        simpath=['/'+neurotype for neurotype in model.neurons.keys()]
        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=[netname for netname in population['netnames']]
        print('simpath',simpath)

    #### Set up hsolve and fix calcium
    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 and calcium
    ######### Need to use CaPlasticityParams.BufferCapacityDensity from EACH neuron_module
    if model.param_sim.hsolve and model.calYN:
        calcium.fix_calcium(model.neurons.keys(), model, buf_cap)

    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)

    ################### Actually run the simulation
    #net_sim_graph.sim_plot(model,net,connections,population)
    for inj in model.param_sim.injection_current:
        print('ready to simulation with', inj)
        create_model_sim.runOneSim(model, simtime=model.param_sim.simtime, injection_current=inj)
    
    ##### extract spikes and save information
    from moose_nerp import ISI_anal
    spike_time,isis=ISI_anal.spike_isi_from_vm(model.vmtab,model.param_sim.simtime,soma=model.param_cond.NAME_SOMA,print_comp=False)

    for neurtype in isis:
        if len(isis):
            print(neurtype,': mean rate of ',np.round(np.nanmean([len(st) for st in spike_time[neurtype]])/param_sim.simtime,3),'from', len(spike_time[neurtype]),'neurons')
        else:
            print(neurtype,': no neurons')

    ####### conn_dict is summary of number of connection properties
    from moose_nerp.prototypes.ttables import TableSet
    conn_dict=[]
    for ntype in net.connect_dict.keys():
        for syntype in net.connect_dict[ntype].keys():
            for pretype,info in net.connect_dict[ntype][syntype].items():
                if isinstance(info.pre,TableSet):
                    conn_dict.append({'neur':ntype,'syn':syntype,'pre':pretype,'params':{'infil':info.pre.filename,'wt':info.weight}})
                else:
                    conn_dict.append({'neur':ntype,'syn':syntype,'pre':pretype,'params':{'nc':info.num_conns,'prob':info.probability,'sc':info.space_const,'wt':info.weight}})

    params={'simtime':model.param_sim.simtime,'numSyn':model.NumSyn,'connect_dict':conn_dict}

    ######### Actually save data - just spikes if they occur.  also conn_dict
    print('************ output file name',net.outfile)
    if model.param_sim.save_txt:
        if np.any([len(st) for tabset in spike_time.values() for st in tabset]):
            np.savez(outdir+net.outfile,spike_time=spike_time,isi=isis,params=params)
        elif total_neurons<too_many_neurons:
            print('no spikes for',param_sim.fname, 'saving vm and parameters')
            vmout={ntype:[tab.vector for tab in tabset] for ntype,tabset in model.vmtab.items()}
            np.savez(outdir+net.outfile,vm=vmout)
        else:
            print('no spikes for',param_sim.fname,'and too many neurons. Saving vm for',save_num,' neurons of each population')
            vmout={ntype:[tab.vector for tab in tabset[0:save_num]] for ntype,tabset in model.vmtab.items()}
            np.savez(outdir+net.outfile,vm=vmout)

        #save/write out the list of connections and location of each neuron

        if save_conn:
            np.savez(net.confile,conn=connections,loc=population['location'],summary=conn_summary)
        else:
            np.savez(net.confile,summary=conn_summary)
        #
    return spike_time,isis,params,conn_summary
Ejemplo n.º 8
0
def moose_main(p):
    stimfreq,presyn,stpYN,inj=p
    import moose
    from moose_nerp.prototypes import create_model_sim
    from moose_nerp import ep as model

    model.synYN = True
    model.stpYN = stpYN
    model.param_sim.stim_paradigm='PSP_'+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

    from moose_nerp import ep_net as net
    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='ep_syn'+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 {}'.format(stimfreq,presyn,stpYN))

    # 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 - need to modify this to NOT create or hook up tt, just create plas and output tables
    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
    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
    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)
    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)
    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)

    #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]}
    vmtab={ntype:[tab.vector for tab in tabset] for ntype,tabset in model.vmtab.items()}
    return param_dict,tab_dict,vmtab,spike_time,isis