How to use the netpyne.sim.cfg function in netpyne

To help you get started, we’ve selected a few netpyne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Neurosim-lab / netpyne / netpyne / analysis / lfp.py View on Github external
'''

    from .. import sim
    from ..support.scalebar import add_scalebar

    print('Plotting LFP ...')

    if not colors: colors = colorList
    
    # set font size
    plt.rcParams.update({'font.size': fontSize})
    
    # time range
    if timeRange is None:
        timeRange = [0,sim.cfg.duration]

    lfp = np.array(sim.allSimData['LFP'])[int(timeRange[0]/sim.cfg.recordStep):int(timeRange[1]/sim.cfg.recordStep),:]

    if filtFreq:
        from scipy import signal
        fs = 1000.0/sim.cfg.recordStep
        nyquist = fs/2.0    
        if isinstance(filtFreq, list): # bandpass
            Wn = [filtFreq[0]/nyquist, filtFreq[1]/nyquist]
            b, a = signal.butter(filtOrder, Wn, btype='bandpass')
        elif isinstance(filtFreq, Number): # lowpass
            Wn = filtFreq/nyquist
            b, a = signal.butter(filtOrder, Wn)
        for i in range(lfp.shape[1]):
            lfp[:,i] = signal.filtfilt(b, a, lfp[:,i])
github Neurosim-lab / netpyne / netpyne / cell / NML2SpikeSource.py View on Github external
def associateGid (self, threshold = 10.0):
        from .. import sim
        
        if sim.cfg.createNEURONObj: 
            sim.pc.set_gid2node(self.gid, sim.rank) # this is the key call that assigns cell gid to a particular node
         
            nc = h.NetCon(self.secs['soma']['pointps'][self.tags['cellType']].hPointp, None)
                
            #### nc.threshold = threshold  # not used....
            sim.pc.cell(self.gid, nc, 1)  # associate a particular output stream of events
            del nc # discard netcon
        sim.net.gid2lid[self.gid] = len(sim.net.gid2lid)
github Neurosim-lab / netpyne / netpyne / sim / load.py View on Github external
except:
                        if sim.cfg.verbose: print(' Unable to load cell conns')

                    try:
                        cell.stims = [Dict(stim) for stim in cellLoad['stims']]
                    except:
                        if sim.cfg.verbose: print(' Unable to load cell stims')

                    sim.net.cells.append(cell)
                print(('  Created %d cells' % (len(sim.net.cells))))
                print(('  Created %d connections' % (sum([len(c.conns) for c in sim.net.cells]))))
                print(('  Created %d stims' % (sum([len(c.stims) for c in sim.net.cells]))))

                # only create NEURON objs, if there is Python struc (fix so minimal Python struct is created)
                if sim.cfg.createNEURONObj:
                    if sim.cfg.verbose: print("  Adding NEURON objects...")
                    # create NEURON sections, mechs, syns, etc; and associate gid
                    for cell in sim.net.cells:
                        prop = {'secs': cell.secs}
                        cell.createNEURONObj(prop)  # use same syntax as when creating based on high-level specs
                        cell.associateGid()  # can only associate once the hSection obj has been created
                    # create all NEURON Netcons, NetStims, etc
                    sim.pc.barrier()
                    for cell in sim.net.cells:
                        try:
                            cell.addStimsNEURONObj()  # add stims first so can then create conns between netstims
                            cell.addConnsNEURONObj()
                        except:
                            if sim.cfg.verbose: ' Unable to load instantiate cell conns or stims'

                    print(('  Added NEURON objects to %d cells' % (len(sim.net.cells))))
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
def addConn (self, params, netStimParams = None):
        from .. import sim

        # threshold = params.get('threshold', sim.net.params.defaultThreshold)  # depreacated -- use threshold in preSyn cell sec
        if params.get('weight') is None: params['weight'] = sim.net.params.defaultWeight # if no weight, set default
        if params.get('delay') is None: params['delay'] = sim.net.params.defaultDelay # if no delay, set default
        if params.get('loc') is None: params['loc'] = 0.5 # if no loc, set default
        if params.get('synsPerConn') is None: params['synsPerConn'] = 1 # if no synsPerConn, set default

        # Avoid self connections
        if params['preGid'] == self.gid:
            if sim.cfg.verbose: print('  Error: attempted to create self-connection on cell gid=%d, section=%s '%(self.gid, params.get('sec')))
            return  # if self-connection return

        # Get list of section labels
        secLabels = self._setConnSections(params)
        if secLabels == -1: return  # if no section available exit func 

        # Weight
        weights = self._setConnWeights(params, netStimParams, secLabels)
        weightIndex = 0  # set default weight matrix index   

        # Delays
        if isinstance(params['delay'],list):
            delays = params['delay'] 
        else:
            delays = [params['delay']] * params['synsPerConn']
github MetaCell / NetPyNE-UI / netpyne_ui / netpyne_geppetto.py View on Github external
def simulateNetPyNEModelInGeppetto(self, args):
        try:
            with redirect_stdout(sys.__stdout__):
                if args['parallelSimulation']: # TODO mpi is not finding  libmpi.dylib.. set LD_LIBRARY_PATH to openmpi bin folder, but nothing
                    logging.debug('Running parallel simulation')
                    if not 'usePrevInst' in args or not args['usePrevInst']:
                        self.netParams.save("netParams.json")
                        self.simConfig.saveJson = True
                        self.simConfig.save("simParams.json")
                        template = os.path.join(os.path.dirname(__file__), 'template.py')
                    else:
                        sim.cfg.saveJson = True
                        oldName = sim.cfg.filename
                        sim.cfg.filename = 'model_output'
                        sim.saveData()
                        sim.cfg.filename = oldName
                        template = os.path.join(os.path.dirname(__file__), 'template2.py')
                    copyfile(template, './init.py')
                    
                    cp = subprocess.run(["mpiexec", "-n", args['cores'], "nrniv", "-mpi", "-python", "init.py"], capture_output=True)
                    print(cp.stdout.decode()+cp.stderr.decode())
                    if cp.returncode!=0: return utils.getJSONError("Error while simulating the NetPyNE model", cp.stderr.decode())
                    sim.load('model_output.json')
                    self.geppetto_model = self.model_interpreter.getGeppettoModel(sim)
                    netpyne_model = sim
                    
                else: # single cpu computation
                    if not 'usePrevInst' in args or not args['usePrevInst']:
github Neurosim-lab / netpyne / netpyne / cell / cell.py View on Github external
def addNetStim (self, params, stimContainer=None):
        from .. import sim

        if not stimContainer:
            self.stims.append(Dict(params.copy()))  # add new stim to Cell object
            stimContainer = self.stims[-1]

            if sim.cfg.verbose: print(('  Created %s NetStim for cell gid=%d'% (params['source'], self.gid)))
        
        if sim.cfg.createNEURONObj:
            rand = h.Random()
            stimContainer['hRandom'] = rand  # add netcon object to dict in conns list

            if isinstance(params['rate'], basestring):
                if params['rate'] == 'variable':
                    try:
                        netstim = h.NSLOC()
                        netstim.interval = 0.1**-1*1e3 # inverse of the frequency and then convert from Hz^-1 to ms (set very low)
                        netstim.noise = params['noise']
                    except:
                        print('Error: tried to create variable rate NetStim but NSLOC mechanism not available')
                else:
                    print('Error: Unknown stimulation rate type: %s'%(h.params['rate']))
            else:
                netstim = h.NetStim() 
                netstim.interval = params['rate']**-1*1e3 # inverse of the frequency and then convert from Hz^-1 to ms
github Neurosim-lab / netpyne / netpyne / network / modify.py View on Github external
def modifyCells (self, params, updateMasterAllCells=False):
    from .. import sim

    # Instantiate network connections based on the connectivity rules defined in params
    sim.timing('start', 'modifyCellsTime')
    if sim.rank==0: 
        print('Modfying cell parameters...')

    for cell in self.cells:
        cell.modify(params)

    if updateMasterAllCells:
        sim._gatherCells()  # update allCells

    sim.timing('stop', 'modifyCellsTime')
    if sim.rank == 0 and sim.cfg.timing: print('  Done; cells modification time = %0.2f s.' % sim.timingData['modifyCellsTime'])
github Neurosim-lab / netpyne / netpyne / network / stim.py View on Github external
postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if condValue[0] <= tags.get(condKey, None) < condValue[1]}  # dict with post Cell objects}  # dict with pre cell tags
                elif condKey == 'cellList':
                    pass
                elif isinstance(condValue, list): 
                    postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if tags.get(condKey, None) in condValue}  # dict with post Cell objects
                else:
                    postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if tags.get(condKey, None) == condValue}  # dict with post Cell objects
            
            # subset of cells from selected pops (by relative indices)                     
            if 'cellList' in target['conds']:
                orderedPostGids = sorted(postCellsTags.keys())
                gidList = [orderedPostGids[i] for i in target['conds']['cellList']]
                postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if gid in gidList}

            # initialize randomizer in case used in string-based function (see issue #89 for more details)
            self.rand.Random123(sim.id32('stim_'+source['type']), sim.id32('%d%d'%(len(postCellsTags), sum(postCellsTags))), sim.cfg.seeds['stim'])

            # calculate params if string-based funcs
            strParams = self._stimStrToFunc(postCellsTags, source, target)

            # loop over postCells and add stim target
            for postCellGid in postCellsTags:  # for each postsyn cell
                if postCellGid in self.gid2lid:  # check if postsyn is in this node's list of gids
                    postCell = self.cells[sim.net.gid2lid[postCellGid]]  # get Cell object 

                    # stim target params
                    params = {}
                    params['label'] = targetLabel
                    params['source'] = target['source']
                    params['sec'] = strParams['secList'][postCellGid] if 'secList' in strParams else target['sec']
                    params['loc'] = strParams['locList'][postCellGid] if 'locList' in strParams else target['loc']
github Neurosim-lab / netpyne / examples / sonata_300_cells / init.py View on Github external
"""
init.py

Initial script to import, simulate and plot raster of SONATA example 300_cells


Contributors: salvadordura@gmail.com
"""

from netpyne import sim
from netpyne.conversion import sonataImport

sonataConfigFile = '/u/salvadord/Documents/ISB/Models/sonata/examples/300_cells/config.json'
sonataImporter = sonataImport.SONATAImporter()
sonataImporter.importNet(sonataConfigFile, replaceAxon=True, setdLNseg=True)
sim.cfg.recordTraces = {'V_soma':{'sec':'soma_0','loc':0.5,'var':'v'}}
sim.cfg.recordCells = range(10)
sim.cfg.analysis['plotTraces'] = {}  # needed for 9 cell example
sim.setupRecording()
sim.simulate()
fig = sim.analysis.plotRaster(figSize=(14,8), dpi=300, saveFig='model_output_raster_axonv2_dl_300cells.png', marker='.', markerSize=3)
fig = sim.analysis.plotTraces(figSize=(10,14), oneFigPer='trace', include=range(10), saveFig='model_output_traces_axonv2_dl_300cells.png')
github Neurosim-lab / netpyne / netpyne / network / stim.py View on Github external
if 'originalFormat' in source and source['originalFormat'] == 'NeuroML2':
                        if 'weight' in target:
                            params['weight'] = target['weight']

                    for sourceParam in source: # copy source params
                        params[sourceParam] = strParams[sourceParam+'List'][postCellGid] if sourceParam+'List' in strParams else source.get(sourceParam)

                    if source['type'] == 'NetStim':
                        self._addCellStim(params, postCell)  # call method to add connections (sort out synMechs first)
                    else:
                        postCell.addStim(params)  # call cell method to add connection

    print('  Number of stims on node %i: %i ' % (sim.rank, sum([len(cell.stims) for cell in self.cells])))
    sim.pc.barrier()
    sim.timing('stop', 'stimsTime')
    if sim.rank == 0 and sim.cfg.timing: print('  Done; cell stims creation time = %0.2f s.' % sim.timingData['stimsTime'])

    return [cell.stims for cell in self.cells]