How to use the netpyne.specs.Dict 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 / sim / gather.py View on Github external
if node:
                node.clear()
                del node
        for item in data:
            if item:
                item.clear()
                del item

    else:  # if single node, save data in same format as for multiple nodes for consistency
        if sim.cfg.createNEURONObj:
            sim.net.allCells = [Dict(c.__getstate__()) for c in sim.net.cells]
        else:
            sim.net.allCells = [c.__dict__ for c in sim.net.cells]
        sim.net.allPops = ODict()
        for popLabel,pop in sim.net.pops.items(): sim.net.allPops[popLabel] = pop.__getstate__() # can't use dict comprehension for OrderedDict
        sim.allSimData = Dict()
        for k in list(sim.simData.keys()):  # initialize all keys of allSimData dict
            sim.allSimData[k] = Dict()
        for key,val in sim.simData.items():  # update simData dics of dics of h.Vector
                if key in simDataVecs+singleNodeVecs:          # simData dicts that contain Vectors
                    if isinstance(val,dict):
                        for cell,val2 in val.items():
                            if isinstance(val2,dict):
                                sim.allSimData[key].update(Dict({cell:Dict()}))
                                for stim,val3 in val2.items():
                                    sim.allSimData[key][cell].update({stim:list(val3)}) # udpate simData dicts which are dicts of dicts of Vectors (eg. ['stim']['cell_1']['backgrounsd']=h.Vector)
                            else:
                                sim.allSimData[key].update({cell:list(val2)})  # udpate simData dicts which are dicts of Vectors (eg. ['v']['cell_1']=h.Vector)
                    else:
                        sim.allSimData[key] = list(sim.allSimData[key])+list(val) # udpate simData dicts which are Vectors
                else:
                    sim.allSimData[key] = val           # update simData dicts which are not Vectors
github Neurosim-lab / netpyne / netpyne / sim / gather.py View on Github external
for key in singleNodeVecs:  # store single node vectors (eg. 't')
                    sim.allSimData[key] = list(nodeData['simData'][key])

                # fill in allSimData taking into account if data is dict of h.Vector (code needs improvement to be more generic)
                for node in gather:  # concatenate data from each node
                    allCells.extend(node['netCells'])  # extend allCells list
                    for popLabel,popCellGids in node['netPopsCellGids'].items():
                        allPopsCellGids[popLabel].extend(popCellGids)

                    for key,val in node['simData'].items():  # update simData dics of dics of h.Vector
                        if key in simDataVecs:          # simData dicts that contain Vectors
                            if isinstance(val,dict):
                                for cell,val2 in val.items():
                                    if isinstance(val2,dict):
                                        sim.allSimData[key].update(Dict({cell:Dict()}))
                                        for stim,val3 in val2.items():
                                            sim.allSimData[key][cell].update({stim:list(val3)}) # udpate simData dicts which are dicts of dicts of Vectors (eg. ['stim']['cell_1']['backgrounsd']=h.Vector)
                                    else:
                                        sim.allSimData[key].update({cell:list(val2)})  # udpate simData dicts which are dicts of Vectors (eg. ['v']['cell_1']=h.Vector)
                            else:
                                sim.allSimData[key] = list(sim.allSimData[key])+list(val) # udpate simData dicts which are Vectors
                        elif gatherLFP and key == 'LFP':
                            sim.allSimData[key] += np.array(val)
                        elif key not in singleNodeVecs:
                            sim.allSimData[key].update(val)           # update simData dicts which are not Vectors

                if len(sim.allSimData['spkt']) > 0:
                    sim.allSimData['spkt'], sim.allSimData['spkid'] = zip(*sorted(zip(sim.allSimData['spkt'], sim.allSimData['spkid']))) # sort spks
                    sim.allSimData['spkt'], sim.allSimData['spkid'] = list(sim.allSimData['spkt']), list(sim.allSimData['spkid'])

                sim.net.allCells =  sorted(allCells, key=lambda k: k['gid'])
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
def __init__ (self, gid, tags, create=True, associateGid=True):
        super(CompartCell, self).__init__(gid, tags)
        self.secs = Dict()  # dict of sections
        self.secLists = Dict()  # dict of sectionLists

        if create: self.create()  # create cell 
        if associateGid: self.associateGid() # register cell for this node
github Neurosim-lab / netpyne / netpyne / specs.py View on Github external
def __init__(self, simConfigDict = None):
        # Simulation parameters
        self.duration = self.tstop = 1*1e3 # Duration of the simulation, in ms
        self.dt = 0.025 # Internal integration timestep to use
        self.hParams = Dict({'celsius': 6.3, 'v_init': -65.0, 'clamp_resist': 0.001})  # parameters of h module
        self.cache_efficient = False  # use CVode cache_efficient option to optimize load when running on many cores
        self.cvode_active = False  # Use CVode variable time step
        self.cvode_atol = 0.001  # absolute error tolerance
        self.seeds = Dict({'conn': 1, 'stim': 1, 'loc': 1}) # Seeds for randomizers (connectivity, input stimulation and cell locations)
        self.rand123GlobalIndex = None  # Sets the global index used by all instances of the Random123 instances of Random
        self.createNEURONObj = True  #  create runnable network in NEURON when instantiating netpyne network metadata
        self.createPyStruct = True  # create Python structure (simulator-independent) when instantiating network
        self.enableRxD = False  # import rxd module
        self.addSynMechs = True  # whether to add synaptich mechanisms or not
        self.includeParamsLabel = True  # include label of param rule that created that cell, conn or stim
        self.gatherOnlySimData = False  # omits gathering of net+cell data thus reducing gatherData time
        self.compactConnFormat = False  # replace dict format with compact list format for conns (need to provide list of keys to include)
        self.connRandomSecFromList = True  # select random section (and location) from list even when synsPerConn=1 
        self.saveCellSecs = True  # save all the sections info for each cell (False reduces time+space; available in netParams; prevents re-simulation)
        self.saveCellConns = True  # save all the conns info for each cell (False reduces time+space; prevents re-simulation)
        self.timing = True  # show timing of each process
        self.saveTiming = False  # save timing data to pickle file
        self.printRunTime = False  # print run time at interval (in sec) specified here (eg. 0.1)
        self.printPopAvgRates = False  # print population avg firing rates after run
        self.printSynsAfterRule = False  # print total of connections after each conn rule is applied 
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
# Python Structure
            if sim.cfg.createPyStruct:
                connParams = {k:v for k,v in params.items() if k not in ['synsPerConn']} 
                connParams['weight'] = weights[i]
                connParams['delay'] = delays[i]
                if not pointp:
                    connParams['sec'] = synMechSecs[i]
                    connParams['loc'] = synMechLocs[i]
                if netStimParams:
                    connParams['preGid'] = 'NetStim'
                    connParams['preLabel'] = netStimParams['source']
                if params.get('gapJunction', 'False') == True:  # only run for post gap junc (not pre)
                    connParams['gapId'] = postGapId
                    connParams['preGapId'] = preGapId
                    connParams['gapJunction'] = 'post'
                self.conns.append(Dict(connParams))                
            else:  # do not fill in python structure (just empty dict for NEURON obj)
                self.conns.append(Dict())

            # NEURON objects
            if sim.cfg.createNEURONObj:
                # gap junctions
                if params.get('gapJunction', 'False') in [True, 'pre', 'post']:  # create NEURON obj for pre and post
                    synMechs[i]['hObj'].weight = weights[i]
                    sourceVar = self.secs[synMechSecs[i]]['hObj'](synMechLocs[i])._ref_v
                    targetVar = synMechs[i]['hObj']._ref_vpeer  # assumes variable is vpeer -- make a parameter
                    sec = self.secs[synMechSecs[i]]
                    sim.pc.target_var(targetVar, connParams['gapId'])
                    self.secs[synMechSecs[i]]['hObj'].push()
                    sim.pc.source_var(sourceVar, connParams['preGapId'])
                    h.pop_section()
                    netcon = None
github Neurosim-lab / netpyne / netpyne / specs.py View on Github external
def addSynMechParams(self, label=None, params=None):
        if not label:
            label = int(self._labelid)
            self._labelid += 1
        self.synMechParams[label] = Dict(params)
github Neurosim-lab / netpyne / netpyne / sim / save.py View on Github external
for pop in list(sim.net.pops.values()):
            try:
                del pop._morphSegCoords
            except:
                pass

    simDataVecs = ['spkt','spkid','stims']+list(sim.cfg.recordTraces.keys())
    singleNodeVecs = ['t']

    if sim.cfg.createNEURONObj:
        sim.net.allCells = [Dict(c.__getstate__()) for c in sim.net.cells]
    else:
        sim.net.allCells = [c.__dict__ for c in sim.net.cells]
    sim.net.allPops = ODict()
    for popLabel,pop in sim.net.pops.items(): sim.net.allPops[popLabel] = pop.__getstate__() # can't use dict comprehension for OrderedDict
    saveData = Dict()
    for k in list(sim.simData.keys()):  # initialize all keys of allSimData dict
        saveData[k] = Dict()
    for key,val in sim.simData.items():  # update simData dics of dics of h.Vector
            if key in simDataVecs+singleNodeVecs:          # simData dicts that contain Vectors
                if isinstance(val,dict):
                    for cell,val2 in val.items():
                        if isinstance(val2,dict):
                            saveData[key].update(Dict({cell:Dict()}))
                            for stim,val3 in val2.items():
                                saveData[key][cell].update({stim:list(val3)}) # udpate simData dicts which are dicts of dicts of Vectors (eg. ['stim']['cell_1']['backgrounsd']=h.Vector)
                        else:
                            saveData[key].update({cell:list(val2)})  # udpate simData dicts which are dicts of Vectors (eg. ['v']['cell_1']=h.Vector)
                else:
                    saveData[key] = list(saveData[key])+list(val) # udpate simData dicts which are Vectors
            else:
                saveData[key] = val           # update simData dicts which are not Vectors
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
# synMech = next((synMech for synMech in sec['synMechs'] if synMech['label']==synLabel and synMech['loc']==loc), None)
                synMech = None
                if not synMech:  # if synMech not in section, then create
                    synMech = Dict({'label': synLabel, 'loc': loc})
                    for paramName, paramValue in synMechParams.items():
                        synMech[paramName] = paramValue
                    sec['synMechs'].append(synMech)
            else:
                synMech = None

            if sim.cfg.createNEURONObj and sim.cfg.addSynMechs: 
                # add synaptic mechanism NEURON objectes 
                if not synMech:  # if pointer not created in createPyStruct, then check 
                    synMech = next((synMech for synMech in sec['synMechs'] if synMech['label']==synLabel and synMech['loc']==loc), None)
                if not synMech:  # if still doesnt exist, then create
                    synMech = Dict()
                    sec['synMechs'].append(synMech)
                if not synMech.get('hObj'):  # if synMech doesn't have NEURON obj, then create
                    synObj = getattr(h, synMechParams['mod'])
                    synMech['hObj'] = synObj(loc, sec=sec['hObj'])  # create h Syn object (eg. h.Exp2Syn)
                    for synParamName,synParamValue in synMechParams.items():  # add params of the synaptic mechanism
                        if synParamName not in ['label', 'mod', 'selfNetCon', 'loc']:
                            setattr(synMech['hObj'], synParamName, synParamValue)
                        elif synParamName == 'selfNetcon':  # create self netcon required for some synapses (eg. homeostatic)
                            secLabelNetCon = synParamValue.get('sec', 'soma')
                            locNetCon = synParamValue.get('loc', 0.5)
                            secNetCon = self.secs.get(secLabelNetCon, None)
                            synMech['hObj'] = h.NetCon(secNetCon['hObj'](locNetCon)._ref_v, synMech[''], sec=secNetCon['hObj'])
                            for paramName,paramValue in synParamValue.items():
                                if paramName == 'weight':
                                    synMech['hObj'].weight[0] = paramValue
                                elif paramName not in ['sec', 'loc']:
github Neurosim-lab / netpyne / netpyne / specs.py View on Github external
def __init__(self, simConfigDict = None):
        # Simulation parameters
        self.duration = self.tstop = 1*1e3 # Duration of the simulation, in ms
        self.dt = 0.025 # Internal integration timestep to use
        self.hParams = Dict({'celsius': 6.3, 'v_init': -65.0, 'clamp_resist': 0.001})  # parameters of h module
        self.cache_efficient = False  # use CVode cache_efficient option to optimize load when running on many cores
        self.cvode_active = False  # Use CVode variable time step
        self.cvode_atol = 0.001  # absolute error tolerance
        self.seeds = Dict({'conn': 1, 'stim': 1, 'loc': 1}) # Seeds for randomizers (connectivity, input stimulation and cell locations)
        self.rand123GlobalIndex = None  # Sets the global index used by all instances of the Random123 instances of Random
        self.createNEURONObj = True  #  create runnable network in NEURON when instantiating netpyne network metadata
        self.createPyStruct = True  # create Python structure (simulator-independent) when instantiating network
        self.enableRxD = False  # import rxd module
        self.addSynMechs = True  # whether to add synaptich mechanisms or not
        self.includeParamsLabel = True  # include label of param rule that created that cell, conn or stim
        self.gatherOnlySimData = False  # omits gathering of net+cell data thus reducing gatherData time
        self.compactConnFormat = False  # replace dict format with compact list format for conns (need to provide list of keys to include)
        self.connRandomSecFromList = True  # select random section (and location) from list even when synsPerConn=1 
        self.saveCellSecs = True  # save all the sections info for each cell (False reduces time+space; available in netParams; prevents re-simulation)
        self.saveCellConns = True  # save all the conns info for each cell (False reduces time+space; prevents re-simulation)
        self.timing = True  # show timing of each process
github Neurosim-lab / netpyne / netpyne / cell / compartCell.py View on Github external
#if sim.cfg.verbose: print("Updated ion: %s in %s, e: %s, o: %s, i: %s" % \
                    #         (ionName, sectName, seg.__getattribute__('e'+ionName), seg.__getattribute__(ionName+'o'), seg.__getattribute__(ionName+'i')))

            # add synMechs (only used when loading)
            if 'synMechs' in sectParams:
                for synMech in sectParams['synMechs']:
                    if 'label' in synMech and 'loc' in synMech:
                        self.addSynMech(synLabel=synMech['label'], secLabel=sectName, loc=synMech['loc'])

            # add point processes
            if 'pointps' in sectParams:
                for pointpName,pointpParams in sectParams['pointps'].items(): 
                    #if self.tags['cellModel'] == pointpParams:  # only required if want to allow setting various cell models in same rule
                    if pointpName not in sec['pointps']:
                        sec['pointps'][pointpName] = Dict() 
                    pointpObj = getattr(h, pointpParams['mod'])
                    loc = pointpParams['loc'] if 'loc' in pointpParams else 0.5  # set location
                    sec['pointps'][pointpName]['hPointp'] = pointpObj(loc, sec = sec['hSec'])  # create h Pointp object (eg. h.Izhi2007b)
                    for pointpParamName,pointpParamValue in pointpParams.items():  # add params of the point process
                        if pointpParamValue == 'gid': 
                            pointpParamValue = self.gid
                        if pointpParamName not in ['mod', 'loc', 'vref', 'synList'] and not pointpParamName.startswith('_'):
                            setattr(sec['pointps'][pointpName]['hPointp'], pointpParamName, pointpParamValue)


        # set topology 
        for sectName,sectParams in prop['secs'].items():  # iterate sects again for topology (ensures all exist)
            sec = self.secs[sectName]  # pointer to section # pointer to child sec
            if 'topol' in sectParams:
                if sectParams['topol']:
                    sec['hSec'].connect(self.secs[sectParams['topol']['parentSec']]['hSec'], sectParams['topol']['parentX'], sectParams['topol']['childX'])  # make topol connection