Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def loadAll (filename, data=None, instantiate=True, createNEURONObj=True):
from .. import sim
if not data: data = _loadFile(filename)
loadSimCfg(filename, data=data)
sim.cfg.createNEURONObj = createNEURONObj # set based on argument
loadNetParams(filename, data=data)
if hasattr(sim.cfg, 'compactConnFormat'):
connFormat = sim.cfg.compactConnFormat
else:
print('Error: no connFormat provided in simConfig')
sys.exit()
loadNet(filename, data=data, instantiate=instantiate, compactConnFormat=connFormat)
loadSimData(filename, data=data)
cell.conns = [Dict(conn) for conn in cellLoad['conns']]
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))))
def setupRecordLFP():
from .. import sim
from netpyne.support.recxelectrode import RecXElectrode
nsites = len(sim.cfg.recordLFP)
saveSteps = int(np.ceil(sim.cfg.duration/sim.cfg.recordStep))
sim.simData['LFP'] = np.zeros((saveSteps, nsites))
if sim.cfg.saveLFPCells:
for c in sim.net.cells:
sim.simData['LFPCells'][c.gid] = np.zeros((saveSteps, nsites))
if not sim.net.params.defineCellShapes: sim.net.defineCellShapes() # convert cell shapes (if not previously done already)
sim.net.calcSegCoords() # calculate segment coords for each cell
sim.net.recXElectrode = RecXElectrode(sim) # create exctracellular recording electrode
if sim.cfg.createNEURONObj:
for cell in sim.net.compartCells:
nseg = cell._segCoords['p0'].shape[1]
sim.net.recXElectrode.calcTransferResistance(cell.gid, cell._segCoords) # transfer resistance for each cell
cell.imembPtr = h.PtrVector(nseg) # pointer vector
cell.imembPtr.ptr_update_callback(cell.setImembPtr) # used for gathering an array of i_membrane values from the pointer vector
cell.imembVec = h.Vector(nseg)
sim.cvode.use_fast_imem(1) # make i_membrane_ a range variable
for popLoadLabel, popLoad in data['net']['pops'].items():
pop = sim.Pop(popLoadLabel, popLoad['tags'])
pop.cellGids = popLoad['cellGids']
sim.net.pops[popLoadLabel] = pop
for cellLoad in cellsNode:
# create new CompartCell object and add attributes, but don't create sections or associate gid yet
# TO DO: assumes CompartCell -- add condition to load PointCell
cell = sim.CompartCell(gid=cellLoad['gid'], tags=cellLoad['tags'], create=False, associateGid=False)
try:
if sim.cfg.saveCellSecs:
cell.secs = Dict(cellLoad['secs'])
else:
createNEURONObjorig = sim.cfg.createNEURONObj
sim.cfg.createNEURONObj = False # avoid creating NEURON Objs now; just needpy struct
cell.create()
sim.cfg.createNEURONObj = createNEURONObjorig
except:
if sim.cfg.verbose: print(' Unable to load cell secs')
try:
cell.conns = [Dict(conn) for conn in cellLoad['conns']]
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]))))
data[sim.rank] = None
gather = sim.pc.py_alltoall(data) # collect cells data from other nodes (required to generate connections)
sim.pc.barrier()
for dataNode in gather:
if dataNode: sim.net.preGapJunctions.extend(dataNode)
# add gap junctions of presynaptic cells (need to do separately because could be in different ranks)
for preGapParams in getattr(sim.net, 'preGapJunctions', []):
if preGapParams['gid'] in self.lid2gid: # only cells in this rank
cell = self.cells[self.gid2lid[preGapParams['gid']]]
cell.addConn(preGapParams)
# apply subcellular connectivity params (distribution of synaspes)
if self.params.subConnParams:
self.subcellularConn(allCellTags, allPopTags)
sim.cfg.createNEURONObj = origCreateNEURONObj # set to original value
sim.cfg.addSynMechs = origAddSynMechs # set to original value
cellsUpdate = [c for c in sim.net.cells if c.tags['cellModel'] not in ['NetStim', 'VecStim']]
if sim.cfg.createNEURONObj:
for cell in cellsUpdate:
# Add synMechs, stim and conn NEURON objects
cell.addStimsNEURONObj()
#cell.addSynMechsNEURONObj()
cell.addConnsNEURONObj()
nodeSynapses = sum([len(cell.conns) for cell in sim.net.cells])
if sim.cfg.createPyStruct:
nodeConnections = sum([len(set([conn['preGid'] for conn in cell.conns])) for cell in sim.net.cells])
else:
nodeConnections = nodeSynapses
print((' Number of connections on node %i: %i ' % (sim.rank, nodeConnections)))
netstim = self.addNetStim(netStimParams)
# 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 netStimParams:
connParams['preGid'] = 'NetStim'
connParams['preLabel'] = netStimParams['source']
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:
if 'vref' in self.tags:
postTarget = getattr(self.hPointp, '_ref_'+self.tags['vref']) # local point neuron
else:
postTarget = self.hPointp
if netStimParams:
netcon = h.NetCon(netstim, postTarget) # create Netcon between netstim and target
else:
netcon = sim.pc.gid_connect(params['preGid'], postTarget) # create Netcon between global gid and target
netcon.weight[weightIndex] = weights[i] # set Netcon weight
netcon.delay = delays[i] # set Netcon delay
#netcon.threshold = threshold # set Netcon threshold
self.conns[-1]['hObj'] = netcon # add netcon object to dict in conns list
data[sim.rank] = None
gather = sim.pc.py_alltoall(data) # collect cells data from other nodes (required to generate connections)
sim.pc.barrier()
for dataNode in gather:
if dataNode: sim.net.preGapJunctions.extend(dataNode)
# add gap junctions of presynaptic cells (need to do separately because could be in different ranks)
for preGapParams in getattr(sim.net, 'preGapJunctions', []):
if preGapParams['gid'] in self.gid2lid: # only cells in this rank
cell = self.cells[self.gid2lid[preGapParams['gid']]]
cell.addConn(preGapParams)
# apply subcellular connectivity params (distribution of synaspes)
if self.params.subConnParams:
self.subcellularConn(allCellTags, allPopTags)
sim.cfg.createNEURONObj = origCreateNEURONObj # set to original value
sim.cfg.addSynMechs = origAddSynMechs # set to original value
cellsUpdate = [c for c in sim.net.cells if c.tags['cellModel'] not in ['NetStim', 'VecStim']]
if sim.cfg.createNEURONObj:
for cell in cellsUpdate:
# Add synMechs, stim and conn NEURON objects
cell.addStimsNEURONObj()
#cell.addSynMechsNEURONObj()
cell.addConnsNEURONObj()
nodeSynapses = sum([len(cell.conns) for cell in sim.net.cells])
if sim.cfg.createPyStruct:
nodeConnections = sum([len(set([conn['preGid'] for conn in cell.conns])) for cell in sim.net.cells])
else:
nodeConnections = nodeSynapses
print((' Number of connections on node %i: %i ' % (sim.rank, nodeConnections)))
cellsNode = [data['net']['cells'][i] for i in range(int(sim.rank), len(data['net']['cells']), sim.nhosts)]
if sim.cfg.createPyStruct:
for popLoadLabel, popLoad in data['net']['pops'].items():
pop = sim.Pop(popLoadLabel, popLoad['tags'])
pop.cellGids = popLoad['cellGids']
sim.net.pops[popLoadLabel] = pop
for cellLoad in cellsNode:
# create new CompartCell object and add attributes, but don't create sections or associate gid yet
# TO DO: assumes CompartCell -- add condition to load PointCell
cell = sim.CompartCell(gid=cellLoad['gid'], tags=cellLoad['tags'], create=False, associateGid=False)
try:
if sim.cfg.saveCellSecs:
cell.secs = Dict(cellLoad['secs'])
else:
createNEURONObjorig = sim.cfg.createNEURONObj
sim.cfg.createNEURONObj = False # avoid creating NEURON Objs now; just needpy struct
cell.create()
sim.cfg.createNEURONObj = createNEURONObjorig
except:
if sim.cfg.verbose: print(' Unable to load cell secs')
try:
cell.conns = [Dict(conn) for conn in cellLoad['conns']]
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)
if 'synMechs' not in sec or not isinstance(sec['synMechs'], list):
sec['synMechs'] = []
if synMechParams and sec: # if both the synMech and the section exist
if sim.cfg.createPyStruct and sim.cfg.addSynMechs:
# 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)
for dataNode in gather:
if dataNode: sim.net.preGapJunctions.extend(dataNode)
# add gap junctions of presynaptic cells (need to do separately because could be in different ranks)
for preGapParams in getattr(sim.net, 'preGapJunctions', []):
if preGapParams['gid'] in self.gid2lid: # only cells in this rank
cell = self.cells[self.gid2lid[preGapParams['gid']]]
cell.addConn(preGapParams)
# apply subcellular connectivity params (distribution of synaspes)
if self.params.subConnParams:
self.subcellularConn(allCellTags, allPopTags)
sim.cfg.createNEURONObj = origCreateNEURONObj # set to original value
sim.cfg.addSynMechs = origAddSynMechs # set to original value
cellsUpdate = [c for c in sim.net.cells if c.tags['cellModel'] not in ['NetStim', 'VecStim']]
if sim.cfg.createNEURONObj:
for cell in cellsUpdate:
# Add synMechs, stim and conn NEURON objects
cell.addStimsNEURONObj()
#cell.addSynMechsNEURONObj()
cell.addConnsNEURONObj()
nodeSynapses = sum([len(cell.conns) for cell in sim.net.cells])
if sim.cfg.createPyStruct:
nodeConnections = sum([len(set([conn['preGid'] for conn in cell.conns])) for cell in sim.net.cells])
else:
nodeConnections = nodeSynapses
print((' Number of connections on node %i: %i ' % (sim.rank, nodeConnections)))
if nodeSynapses != nodeConnections:
print((' Number of synaptic contacts on node %i: %i ' % (sim.rank, nodeSynapses)))
sim.pc.barrier()