Esempio n. 1
0
    def getGeppettoModel(self, netParams, simConfig):
        sim.create(netParams, simConfig, True)
        sim.gatherData()

        modelInterpreter = NetPyNEModelInterpreter()
        geppettoModel = modelInterpreter.getGeppettoModel(sim)
        sim.analyze()
def M1Cell():
    owd = os.getcwd()
    # os.chdir('models/DuraBernal')
    sys.path.append('models/DuraBernal')
    sys.path.append('models/DuraBernal/cells')
    from netParams_unified import netParams
    from cfg_unified import cfg
    from netpyne import sim
    sim.create(netParams, cfg)
    os.chdir(owd)
    return sim
Esempio n. 3
0
    def instantiateNetPyNEModel(self):
        with redirect_stdout(sys.__stdout__):
            saveData = sim.allSimData if hasattr(
                sim, 'allSimData') and 'spkt' in sim.allSimData.keys() and len(
                    sim.allSimData['spkt']) > 0 else False
            sim.create(self.netParams, self.simConfig)
            sim.net.defineCellShapes(
            )  # creates 3d pt for cells with stylized geometries
            sim.gatherData(gatherLFP=False)
            if saveData:
                sim.allSimData = saveData  # preserve data from previous simulation

        return sim
Esempio n. 4
0
    def instantiateModel(self):
        """

        Instantiates model
        Sets netParams and cellParams given cfg values
        Takes snapshot of cfg

        Returns
        -------
        SimConfig
            generated SimConfig

        """
        netParams_snapshot = set_netParams(self.cfg)
        netParams_snapshot.cellParams = set_cellParams(self.cfg)
        sim.create(simConfig=self.cfg, netParams=netParams_snapshot)
        sim.gatherData(gatherLFP=False)
        self.last_cfg_snapshot = self.cfg.__dict__.copy()
        return sim
Esempio n. 5
0
    def loadModel(self, args):
        """ Imports a model stored as file in json format.

        :param args:
        :return:
        """
        def remove(dictionary):
            # remove reserved keys such as __dict__, __Method__, etc
            # they appear when we do sim.loadAll(json_file)
            if isinstance(dictionary, dict):
                for key, value in list(dictionary.items()):
                    if key.startswith('__'):
                        dictionary.pop(key)
                    else:
                        remove(value)

        if not any([
                args[option] for option in
            ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
        ]):
            return utils.getJSONError(
                "Error while loading data",
                'You have to select at least one option')

        try:
            owd = os.getcwd()
            compileModMechFiles(args['compileMod'], args['modFolder'])
        except:
            return utils.getJSONError("Error while importing/compiling mods",
                                      sys.exc_info())
        finally:
            os.chdir(owd)

        try:
            with redirect_stdout(sys.__stdout__):
                sim.initialize()
                wake_up_geppetto = False
                if all([
                        args[option] for option in
                    ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
                ]):
                    wake_up_geppetto = True
                    if self.doIhaveInstOrSimData()['haveInstance']:
                        sim.clearAll()
                    sim.initialize()
                    sim.loadAll(args['jsonModelFolder'])
                    self.netParams = sim.net.params
                    self.simConfig = sim.cfg
                    remove(self.netParams.todict())
                    remove(self.simConfig.todict())
                else:
                    if args['loadNet']:
                        wake_up_geppetto = True
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.initialize()
                        sim.loadNet(args['jsonModelFolder'])

                    if args['loadSimData']:  # TODO (https://github.com/Neurosim-lab/netpyne/issues/360)
                        wake_up_geppetto = True
                        if not self.doIhaveInstOrSimData()['haveInstance']:
                            sim.create(specs.NetParams(), specs.SimConfig())
                            sim.net.defineCellShapes()
                            sim.gatherData(gatherLFP=False)
                        sim.loadSimData(args['jsonModelFolder'])

                    if args['loadSimCfg']:
                        sim.loadSimCfg(args['jsonModelFolder'])
                        self.simConfig = sim.cfg
                        remove(self.simConfig.todict())

                    if args['loadNetParams']:
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.loadNetParams(args['jsonModelFolder'])
                        self.netParams = sim.net.params
                        remove(self.netParams.todict())

                if wake_up_geppetto:
                    if len(sim.net.cells) > 0:
                        section = list(sim.net.cells[0].secs.keys())[0]
                        if 'pt3d' not in list(
                                sim.net.cells[0].secs[section].geom.keys()):
                            sim.net.defineCellShapes()
                            sim.gatherData()
                            sim.loadSimData(args['jsonModelFolder'])

                    sim.gatherData()
                    self.geppetto_model = self.model_interpreter.getGeppettoModel(
                        sim)
                    return json.loads(
                        GeppettoModelSerializer.serialize(self.geppetto_model))
                else:
                    return utils.getJSONReply()
        except:
            return utils.getJSONError("Error while loading the NetPyNE model",
                                      sys.exc_info())
simConfig.createPyStruct = True
simConfig.verbose = False

simConfig.recordCells = ['all']
simConfig.recordTraces = {'v_soma': {'sec': 'soma', 'loc': 0.5, 'var': 'v'}}
simConfig.recordStim = True
simConfig.recordStep = simConfig.dt

simConfig.filename = 'Netpyne-cell_output'
simConfig.saveTxt = True

#simConfig.analysis['plotRaster'] = True
#simConfig.analysis['plotTraces'] = {'include': [0,1,2], 'oneFigPer': 'trace'}
#simConfig.analysis['plot2Dnet'] = True  # Plot 2D net cells and connections

data = sim.create(netParams=netParams, simConfig=simConfig, output=True)
soma = data[1][0].secs.soma.hSec
dend = data[1][0].secs.dend.hSec
mutype = 'S'
if mutype == "S" or mutype == "s":
    mus(soma, dend)
elif mutype == "FR" or mutype == "fr":
    mufr(soma, dend)
elif mutype == "FF" or mutype == "ff":
    muff(soma, dend)

#for i in range(len(data[1])):
#    data[1][i].secs.soma.hSec.L =  75 + 5*i
#    data[1][i].secs.soma.hSec.diam = 75 + 5*i

#data[1][0].secs.soma.hSec.__getattribute__('ena')
Esempio n. 7
0
Starting script to run NetPyNE-based M1 model.

Usage:
    python init.py # Run simulation, optionally plot a raster

MPI usage:
    mpiexec -n 4 nrniv -python -mpi init.py
"""

import matplotlib
matplotlib.use('Agg')  # to avoid graphics error in servers

from netpyne import sim
from cfg import cfg
from netParams import netParams

print("Starting sim ...")

(pops, cells, conns, stims, rxd, simData) = sim.create(netParams,
                                                       cfg,
                                                       output=True)

# saveInterval defines how often the data is saved
sim.runSimWithIntervalFunc(cfg.saveInterval, sim.intervalSave)

# we run fileGather() instead of gather
sim.fileGather()
sim.analyze()

sim.checkOutput('M1detailed')
Esempio n. 8
0
    'ca': {
        'sec': 'soma',
        'loc': 0.5,
        'var': 'cai'
    },
    'buf': {
        'sec': 'soma',
        'loc': 0.5,
        'var': 'bufi'
    },
    'cabuf': {
        'sec': 'soma',
        'loc': 0.5,
        'var': 'cabufi'
    }
}

cfg.analysis['plotTraces'] = {
    'include': ['cell'],
    'ylim': [0, 0.0001],
    'overlay': True
}

#------------------------------------------------------------------------------
# RUN MODEL
#------------------------------------------------------------------------------
sim.create(netParams, cfg)
h.finitialize()
sim.simulate()
sim.analyze()
Esempio n. 9
0
from netpyne import sim
import params

# Create network and save
sim.create(netParams=params.netParams, simConfig=params.simConfig)
sim.gatherData()
sim.saveData()
Esempio n. 10
0
simConfig.verbose = False

simConfig.recordCells = ['all']
simConfig.recordTraces = {'v_soma': {'sec': 'soma', 'loc': 0.5, 'var': 'v'}}
simConfig.recordStim = True
simConfig.recordStep = simConfig.dt

simConfig.filename = 'Netpyne-cell_output'
simConfig.saveTxt = True

#simConfig.analysis['plotRaster'] = True
#simConfig.analysis['plotTraces'] = {'include': [0,1,2], 'oneFigPer': 'trace'}
#simConfig.analysis['plot2Dnet'] = True  # Plot 2D net cells and connections

(pops, cells, conns, stims, simData) = sim.create(netParams=netParams,
                                                  simConfig=simConfig,
                                                  output=True)
mutype = []
for n in range(len(cells)):
    soma = cells[n].secs.soma.hSec
    dend = cells[n].secs.dend.hSec
    if n == 0:
        ner.mus(soma, dend)
        mutype.append('S')
    elif n == 1:
        ner.mufr(soma, dend)
        mutype.append('FR')
    elif n == 2:
        ner.muff(soma, dend)
        mutype.append('FF')
Esempio n. 11
0
from netParams_unified import netParams 
from cfg_unified import cfg
from netpyne import sim as s
s.create(netParams, cfg)

sec_num = 'apic_20' # indicates stimulated section
loc = 0.5 # indicates stimulated compartment (0-1)
seg = s.net.cells[0].secs[sec_num]['hObj'](loc)
soma_seg = s.net.cells[0].secs['soma']['hObj'](0.5)

## record voltages
from neuron import h, gui
soma_v = h.Vector().record(soma_seg._ref_v)
dend_v = h.Vector().record(seg._ref_v)
time = h.Vector().record(h._ref_t)

## parameters of the chirp stimulus
from chirpUtils import applyChirp, getChirp
amp = 0.025 # amplitude of chirp stim
f0, f1, t0, Fs, delay = 0.5, 20, 20, 1000, 5 # initial and final frequencies, duration, sampling freq, delay
I, t = getChirp(f0, f1, t0, amp, Fs, delay) # defines current clamp

## run simulation
print('Running chirp on ' + str(seg))
out = applyChirp(I, t, seg, soma_seg, t0, delay, Fs, f1)

## plotting 
from matplotlib import pyplot as plt 
### traces
trace_fig = plt.figure(figsize=(8,10))
plt.subplot(3,1,1)
Esempio n. 12
0
simConfig.duration = 620000  # Duration of the simulation, in ms
simConfig.dt = 0.025  # Internal integration timestep to use
simConfig.verbose = False  # Show detailed messages
simConfig.recordTraces = {
    'V_soma': {
        'sec': 'soma',
        'loc': 0.5,
        'var': 'v'
    }
}  # Dict with traces to record
simConfig.recordStep = 0.25  # Step size in ms to save data (eg. V traces, LFP, etc)
simConfig.filename = 'model_output'  # Set file output name

simConfig.saveMat = True  # Save params, network a sim output to mat file
sim.create()
sim.simulate()

simConfig.analysis['plotRaster'] = True  # Plot a raster
simConfig.analysis['plotTraces'] = {
    'include': all,
    'showFig': False
}  # Plot recorded traces for this list of cells
simConfig.analysis['plot2Dnet'] = {
    'saveData': True
}  # plot 2D visualization of cell positions and connections
simConfig.analysis['plotConn'] = {'feature': 'numConns'}
sim.analyze()
#simConfig.timestampFilename = True
# Create network and run simulation
#sim.createSimulateAnalyze(netParams, simConfig)
# Create network and run simulation
sim.createSimulate(netParams=netParams, simConfig=simConfig)
sim.saveData()
import pylab

pylab.show(
)  # this line is only necessary in certain systems where figures appear empty
'''
# Methods to modify your network
modifyCells(params) 				# Modify the cells in your network
modifySynMechs(params) 				# Modify the Synapse Mechanisms
modifyConns(params)					# Modify the connections of your network
modifyStims(params)					# Modify the stimulations of you network
'''
'''
#### Simulation setup to run multiple runs at once
simConfig = specs.SimConfig()								# Object of class SimConfig to store simulation configuration
simConfig.duration = simTime								# Duration of the simulation, in ms
simConfig.dt = 0.05  										# Internal integration timestep to use
simConfig.hParams = {'celsius': 31,'clamp_resist': 0.001,'steps_per_ms': 20}
simConfig.verbose = 0										# Show detailed messages
simConfig.recordTraces = {'V_soma':{'sec':'soma','loc':0.5,'var':'v'}}  # Dict with traces to record
simConfig.recordStep = 0.01		 							# Step size in ms to save data (eg. V traces, LFP, etc)
simConfig.saveMat = True;									# Save .mat file after simulation
simConfig.timestampFilename = True							# Add time stamp to filename

# Create simulation
sim.create(netParams, simConfig)

# Create network and run simulation
Esempio n. 14
0
from netpyne import sim
from neuron import h
import wlutils as wl
import numpy as np
from netpyne import sim
from simConfig import cfg
from netParams import npar
sim.create(npar, cfg)
ax = sim.net.cells[0].secs.axon.hObj


def lp():
    for perc in np.linspace(0.0, 0.8, 9):  # now is percent block
        h.gnablock_ina2005 = perc  # h.perc_ina2005
        sim.runSim()
        sim.gatherData()
        sim.saveData(include=['simData'],
                     filename='data/19dec06blkA_%02d' % (100 * perc))


lp()
Esempio n. 15
0
    def loadModel(self, args):
        """ Imports a model stored as file in json format.

        :param args:
        :return:
        """
        if not any([
                args[option] for option in
            ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
        ]):
            return utils.getJSONError(
                "Error while loading data",
                'You have to select at least one option')

        try:
            owd = os.getcwd()
            compileModMechFiles(args['compileMod'], args['modFolder'])
        except Exception:
            message = "Error while importing/compiling mods"
            logging.exception(message)
            return utils.getJSONError(message, sys.exc_info())
        finally:
            os.chdir(owd)

        try:
            with redirect_stdout(sys.__stdout__):
                sim.initialize()
                wake_up_geppetto = False
                if all([
                        args[option] for option in
                    ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
                ]):
                    wake_up_geppetto = True
                    if self.doIhaveInstOrSimData()['haveInstance']:
                        sim.clearAll()
                    sim.initialize()
                    sim.loadAll(args['jsonModelFolder'])
                    self.netParams = sim.net.params
                    self.simConfig = sim.cfg
                    netpyne_ui_utils.remove(self.netParams.todict())
                    netpyne_ui_utils.remove(self.simConfig.todict())
                else:
                    if args['loadNet']:
                        wake_up_geppetto = True
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.initialize()
                        sim.loadNet(args['jsonModelFolder'])

                    # TODO (https://github.com/Neurosim-lab/netpyne/issues/360)
                    if args['loadSimData']:
                        wake_up_geppetto = True
                        if not self.doIhaveInstOrSimData()['haveInstance']:
                            sim.create(specs.NetParams(), specs.SimConfig())
                            sim.net.defineCellShapes()
                            sim.gatherData(gatherLFP=False)
                        sim.loadSimData(args['jsonModelFolder'])

                    if args['loadSimCfg']:
                        sim.loadSimCfg(args['jsonModelFolder'])
                        self.simConfig = sim.cfg
                        netpyne_ui_utils.remove(self.simConfig.todict())

                    if args['loadNetParams']:
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.loadNetParams(args['jsonModelFolder'])
                        self.netParams = sim.net.params
                        netpyne_ui_utils.remove(self.netParams.todict())

                if wake_up_geppetto:
                    self._create3D_shapes(args['jsonModelFolder'])

                    # TODO: Fix me - gatherData will remove allSimData!
                    sim.gatherData()

                    self.geppetto_model = self.model_interpreter.getGeppettoModel(
                        sim)
                    return json.loads(
                        GeppettoModelSerializer.serialize(self.geppetto_model))
                else:
                    return utils.getJSONReply()
        except Exception:
            message = "Error while loading the NetPyNE model"
            logging.exception(message)
            return utils.getJSONError(message, sys.exc_info())
Esempio n. 16
0
simConfig.saveDataInclude = ['simData', 'simConfig', 'netParams']  #, 'net']
simConfig.saveCellSecs = 0  #False
simConfig.saveCellConns = 0
# simConfig.recordLFP = [[150, y, 150] for y in [600, 800, 1000]] # only L5 (Zagha) [[150, y, 150] for y in range(200,1300,100)]

simConfig.analysis['plotRaster'] = True  # Plot a raster
simConfig.analysis['plotTraces'] = {
    'include': [1]
}  # Plot recorded traces for this list of cells
#simConfig.analysis['plot2Dnet'] = True           # plot 2D visualization of cell positions and connections
#simConfig.analysis['plotLFP'] = True
simConfig.printPopAvgRates = True

# def modifyGnabar(t):
#     params = {'conds': {'cellType': 'PYR'}, 'secs': {'soma': {'mechs': {'hh': {'gnabar': 0.0}}}}}
#     sim.net.modifyCells(params)
#     print(sim.net.cells[0].secs['soma']['mechs']['hh'])

# Create network and run simulation
sim.create(netParams=netParams, simConfig=simConfig)
sim.runSimWithIntervalFunc(200, sim.saveSimDataInNode)
#sim.gatherData()                  			# gather spiking data and cell info from each node
sim.fileGather()
sim.saveData(
)  # save params, cell info and sim output to file (pickle,mat,txt,etc)#
sim.analysis.plotData()  # plot spike raster etc

# import pylab; pylab.show()  # this line is only necessary in certain systems where figures appear empty

# check model output
#sim.checkOutput('tut2')
import time
from netpyne import sim  # import netpyne init module
from neuron import h

simConfig, netParams = sim.readCmdLineArgs('cfg.py', 'netParams.py')
sim.create(simConfig=simConfig, netParams=netParams)

seed = int(time.time() * 1e7) & 0xffffffff
rndm = sim.h.Random()
rndm.Random123(
    sim.rank, 0, 0
)  #initialize with seed as second argument to achieve different results for each run
for TCsoma in [
        x.secs.soma for x in sim.net.cells if x.tags['cellType'] == 'TC'
]:
    TCsoma.hObj.ghbar_iar = rndm.normal(17.5, 0.0008) * 1e-6
    TCsoma.pointps.kleak_0.hObj.gmax = rndm.normal(40, 0.003) * 1e-4

sim.simulate()
sim.analyze()
Esempio n. 18
0
netparms = M1.netParams
print(
    "********************\n*\n*  Note: setting noise to 1, since noise can only be 0 or 1 in NeuroML export currently!\n*\n********************"
)
netparms.stimSourceParams['background_E']['noise'] = 1
netparms.stimSourceParams['background_I']['noise'] = 1

if disable_output:
    M1.simConfig.analysis = {}
    M1.simConfig.recordTraces = {}
    M1.simConfig.recordCellsSpikes = []

if do_simulate:
    tic = time.time()
    sim.create(netparms, M1.simConfig, output=False)
    sim.runSim()

    print(sim.simData, len(sim.simData['spkid']))

    print(sim.timingData)
    # print( len(sim.simData) )
    # print( len( sim.simData['V']['cell_10'] ) )
    # print( M1.simConfig.analysis )
    # print( sim.simData['spkid'] )
    # print( len( sim.simData['spkid'] ) )
    # print( [ x for x in sim.simData['V']['cell_10'] ] )
else:
    sim.createExportNeuroML2(
        netParams=netparms,
        simConfig=M1.simConfig,