Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self.parse_group(h5file.root.edges)
h5file.close()
self.edges_info[self.current_edge] = load_csv_props(edge_types_file)
self.current_edge = None
for conn in self.conn_info:
pre_node = self.conn_info[conn]['pre_node']
post_node = self.conn_info[conn]['post_node']
print(' Adding projection %s: %s -> %s '%(conn, pre_node, post_node))
# add all synMechs in this projection to netParams.synMechParams
for type in self.edges_info[conn]:
syn_label = self.edges_info[conn][type]['dynamics_params'].split('.')[0]
if syn_label not in sim.net.params.synMechParams:
dynamics_params_file = self.subs(self.network_config['components']['synaptic_models_dir']) +'/'+self.edges_info[conn][type]['dynamics_params']
syn_dyn_params = load_json(dynamics_params_file)
synMechParams = dict(syn_dyn_params)
for k in synMechParams: # replace keys
if k in synMechSubs:
synMechParams[synMechSubs[k]] = synMechParams.pop(k)
synMechParams['mod'] = self.edges_info[conn][type]['model_template']
sim.net.params.synMechParams[syn_label] = synMechParams
print(' Added synMech %s '%(syn_label))
# add individual connections in this projection
for i in range(len(self.conn_info[conn]['pre_id'])):
pre_id = self.conn_info[conn]['pre_id'][i]
post_id = self.conn_info[conn]['post_id'][i]
pre_gid = self.cell_info[pre_node]['gid_from_id'][pre_id]
post_gid = self.cell_info[post_node]['gid_from_id'][post_id]
ip.resistivities.append(neuroml.Resistivity(value="%s ohm_cm"%np_sec['geom']['Ra'],
segment_groups=nml_seg_group.id))
'''
See https://github.com/Neurosim-lab/netpyne/issues/130
'''
cm = np_sec['geom']['cm'] if 'cm' in np_sec['geom'] else 1
if isinstance(cm,dict) and len(cm)==0:
cm = 1
mp.specific_capacitances.append(neuroml.SpecificCapacitance(value="%s uF_per_cm2"%cm,
segment_groups=nml_seg_group.id))
mp.init_memb_potentials.append(neuroml.InitMembPotential(value="%s mV"%'-65'))
mp.spike_threshes.append(neuroml.SpikeThresh(value="%s mV"%sim.net.params.defaultThreshold))
for mech_name in list(np_sec['mechs'].keys()):
mech = np_sec['mechs'][mech_name]
if mech_name == 'hh':
for chan in chans_doc.ion_channel_hhs:
if (chan.id == 'leak_hh' or chan.id == 'na_hh' or chan.id == 'k_hh'):
if not chan.id in chans_added:
nml_doc.ion_channel_hhs.append(chan)
chans_added.append(chan.id)
leak_cd = neuroml.ChannelDensity(id='leak_%s'%nml_seg_group.id,
ion_channel='leak_hh',
cond_density='%s S_per_cm2'%mech['gl'],
erev='%s mV'%mech['el'],
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
borderCorrect = [0,0,0]
for icoord,coord in enumerate(coords):
# calculate borders
size = getattr(sim.net.params, 'size'+coord.upper())
borders = [0, size]
if coord+'borders' in sim.net.params.correctBorder:
borders = [b*size for b in sim.net.params.correctBorder[coord+'borders']]
elif coord+'Range' in popParams[pop]:
borders = popParams[pop][coord+'Range']
elif coord+'normRange' in popParams[pop]:
borders = [popParams[pop][coord+'normRange'][0] * size,
popParams[pop][coord+'normRange'][1] * size]
# calcualte distance to border
borderDist = min([abs(self.tags[coord] - border) for border in borders])
borderThreshold = sim.net.params.correctBorder['threshold'][icoord]
borderCorrect[icoord] = max(0, borderThreshold - borderDist)
self.tags['borderCorrect'] = borderCorrect
targetFolder = os.path.dirname(sim.cfg.filename)
if targetFolder and not os.path.exists(targetFolder):
try:
os.mkdir(targetFolder)
except OSError:
print(' Could not create target folder: %s' % (targetFolder))
# saving data
if not include: include = sim.cfg.saveDataInclude
dataSave = {}
net = {}
dataSave['netpyne_version'] = sim.version(show=False)
dataSave['netpyne_changeset'] = sim.gitChangeset(show=False)
if getattr(sim.net.params, 'version', None): dataSave['netParams_version'] = sim.net.params.version
if 'netParams' in include:
sim.net.params.__dict__.pop('_labelid', None)
net['params'] = utils.replaceFuncObj(sim.net.params.__dict__)
if 'net' in include: include.extend(['netPops', 'netCells'])
if 'netCells' in include: net['cells'] = sim.net.allCells
if 'netPops' in include: net['pops'] = sim.net.allPops
if net: dataSave['net'] = net
if 'simConfig' in include: dataSave['simConfig'] = sim.cfg.__dict__
if 'simData' in include:
if 'LFP' in sim.allSimData:
sim.allSimData['LFP'] = sim.allSimData['LFP'].tolist()
dataSave['simData'] = sim.allSimData
if dataSave:
if sim.cfg.timestampFilename:
pop.cellGids.append(gid) # add gid list of cells belonging to this population - not needed?
self.cell_info[sonata_pop]['gid_from_id'][icell] = gid
model_type = pop.tags['cellModel']
# set cell tags
cellTags = {k: v for (k, v) in pop.tags.items() if k in sim.net.params.popTagsCopiedToCells} # copy all pop tags to cell tags, except those that are pop-specific
cellTags['pop'] = pop.tags['pop']
if model_type == 'biophysical':
cellTags['x'] = cellLocs[node_group_id][icell]['x'] # set x location (um)
cellTags['y'] = -1*cellLocs[node_group_id][icell]['y'] # set y location (um) (reversed since netpyne assumes depth)
cellTags['z'] = cellLocs[node_group_id][icell]['z'] # set z location (um)
cellTags['xnorm'] = cellTags['x'] / sim.net.params.sizeX # set x location (um)
cellTags['ynorm'] = cellTags['y'] / sim.net.params.sizeY # set y location (um)
cellTags['znorm'] = cellTags['z'] / sim.net.params.sizeZ # set z location (um)
if 'rotation_angle_yaxis' in cellLocs[node_group_id][icell]:
cellTags['rot_y'] = cellLocs[node_group_id][icell]['rotation_angle_yaxis'] # set y-axis rotation (implementation MISSING!)
if 'rotation_angle_zaxis' in cellLocs[node_group_id][icell]:
cellTags['rot_z'] = cellLocs[node_group_id][icell]['rotation_angle_zaxis'] # set z-axis rotation
# sim.net.cells[-1].randrandRotationAngle = cellTags['rot_z'] # rotate cell in z-axis (y-axis rot missing) MISSING!
elif model_type in ['virtual', 'VecStim', 'NetStim']:
if 'spkTimes' in pop.tags: # if VecStim, copy spike times to params
cellTags['params'] = {}
if isinstance(pop.tags['spkTimes'][0], list):
try:
cellTags['params']['spkTimes'] = pop.tags['spkTimes'][icell] # 2D list
except:
pass
def addSynMech (self, synLabel, secLabel, loc):
from .. import sim
synMechParams = sim.net.params.synMechParams.get(synLabel) # get params for this synMech
sec = self.secs.get(secLabel, None)
# add synaptic mechanism to python struct
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
try:
os.mkdir(targetFolder)
except OSError:
print(' Could not create target folder: %s' % (targetFolder))
# saving data
if not include: include = sim.cfg.saveDataInclude
dataSave = {}
net = {}
dataSave['netpyne_version'] = sim.version(show=False)
dataSave['netpyne_changeset'] = sim.gitChangeset(show=False)
if getattr(sim.net.params, 'version', None): dataSave['netParams_version'] = sim.net.params.version
if 'netParams' in include:
sim.net.params.__dict__.pop('_labelid', None)
net['params'] = utils.replaceFuncObj(sim.net.params.__dict__)
if 'net' in include: include.extend(['netPops', 'netCells'])
if 'netCells' in include: net['cells'] = sim.net.allCells
if 'netPops' in include: net['pops'] = sim.net.allPops
if net: dataSave['net'] = net
if 'simConfig' in include: dataSave['simConfig'] = sim.cfg.__dict__
if 'simData' in include:
if 'LFP' in saveData:
saveData['LFP'] = saveData['LFP'].tolist()
dataSave['simData'] = saveData
if dataSave:
if sim.cfg.timestampFilename:
timestamp = time()
timestampStr = '-' + datetime.fromtimestamp(timestamp).strftime('%Y%m%d_%H%M%S')
self.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)
def _setConnWeights (self, params, netStimParams):
from .. import sim
if netStimParams:
scaleFactor = sim.net.params.scaleConnWeightNetStims
elif isinstance(sim.net.params.scaleConnWeightModels, dict) and sim.net.params.scaleConnWeightModels.get(self.tags['cellModel'], None) is not None:
scaleFactor = sim.net.params.scaleConnWeightModels[self.tags['cellModel']] # use scale factor specific for this cell model
else:
scaleFactor = sim.net.params.scaleConnWeight # use global scale factor
if isinstance(params['weight'],list):
weights = [scaleFactor * w for w in params['weight']]
else:
weights = [scaleFactor * params['weight']] * params['synsPerConn']
return weights