def importCell (fileName, cellName, cellArgs = None): h.initnrn() if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): h.load_file(fileName) if isinstance(cellArgs, dict): cell = getattr(h, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args elif fileName.endswith('.py'): filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)(*cellArgs) # create cell using template, passing list with args sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return secDic, secListDic, synMechs = getCellParams(cell) return secDic, secListDic, synMechs
def importCell (fileName, cellName, cellArgs = None, cellInstance = False): h.initnrn() varList = mechVarList() # list of properties for all density mechanisms and point processes origGlob = getGlobals(list(varList['mechs'].keys())+list(varList['pointps'].keys())) origGlob['v_init'] = -65 # add by hand since won't be set unless load h.load_file('stdrun') if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc') or fileName.endswith('.tem'): h.load_file(fileName) if not cellInstance: if isinstance(cellArgs, dict): cell = getattr(h, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args else: try: cell = getattr(h, cellName) except: cell = None elif fileName.endswith('.py'): filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) removeFilePath = True else: removeFilePath = False moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name tempModule = importlib.import_module(moduleName) modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)(*cellArgs) # create cell using template, passing list with args if removeFilePath: sys.path.remove(filePath) else: print("File name should be either .hoc or .py file") return secDic, secListDic, synMechs, globs = getCellParams(cell, varList, origGlob) if fileName.endswith('.py'): _delete_module(moduleName) _delete_module('tempModule') del modulePointer elif fileName.endswith('.hoc'): for sec in h.allsec(): try: if h.cas()!=sec: sec.push() h.delete_section() h.pop_section() except: pass h.initnrn() setGlobals(origGlob) # restore original globals return secDic, secListDic, synMechs, globs
def importCellsFromNet(netParams, fileName, labelList, condsList, cellNamesList, importSynMechs): """ importCellsFromNet Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns) """ h.initnrn() if fileName.endswith('.hoc') or fileName.endswith('.tem'): print('Importing from .hoc network not yet supported') return # h.load_file(fileName) # for cellName in cellNames: # cell = getattr(h, cellName) # create cell using template, passing dict with args # secDic, secListDic, synMechs = getCellParams(cell) elif fileName.endswith('.py'): origDir = os.getcwd() filePath, fileNameOnly = os.path.split( fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) removeFilePath = True else: removeFilePath = False moduleName = fileNameOnly.split('.py')[ 0] # remove .py to obtain module name os.chdir(filePath) print('\nRunning network in %s to import cells into NetPyNE ...\n' % (fileName)) from neuron import load_mechanisms load_mechanisms(filePath) tempModule = importlib.import_module(moduleName) modulePointer = tempModule if removeFilePath: sys.path.remove(filePath) else: print("File name should be either .hoc or .py file") return for label, conds, cellName in zip(labelList, condsList, cellNamesList): print('\nImporting %s from %s ...' % (cellName, fileName)) exec('cell = tempModule' + '.' + cellName) #cell = getattr(modulePointer, cellName) # get cell object varList = mechVarList() origGlob = getGlobals( list(varList['mechs'].keys()) + list(varList['pointps'].keys())) secs, secLists, synMechs = getCellParams(cell, varList, origGlob) cellRule = {'conds': conds, 'secs': secs, 'secLists': secLists} netParams.addCellParams(label, cellRule) if importSynMechs: for synMech in synMechs: netParams.addSynMechParams(synMech.pop('label'), synMech)
def reset(self): print("Simulation initialization.") h.initnrn() h.frecord_init() h.finitialize(self.init_v * mV) if self.init_sleep > 0: print("sleep before run for: %s seconds" % self.init_sleep) time.sleep(self.init_sleep) if self.warmup > 0: h.dt = self.warmup / 10 h.continuerun(self.warmup * ms) h.dt = self.dt
def importCellsFromNet(netParams, fileName, labelList, condsList, cellNamesList, importSynMechs): h.initnrn() ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): print 'Importing from .hoc network not yet supported' return # h.load_file(fileName) # for cellName in cellNames: # cell = getattr(h, cellName) # create cell using template, passing dict with args # secDic, secListDic, synMechs = getCellParams(cell) elif fileName.endswith('.py'): origDir = os.getcwd() filePath, fileNameOnly = os.path.split( fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[ 0] # remove .py to obtain module name os.chdir(filePath) print '\nRunning network in %s to import cells into NetPyNE ...\n' % ( fileName) print h.name_declared('hcurrent') from neuron import load_mechanisms load_mechanisms(filePath) exec('import ' + moduleName + ' as tempModule' ) in globals(), locals() # import module dynamically modulePointer = tempModule sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return for label, conds, cellName in zip(labelList, condsList, cellNamesList): print '\nImporting %s from %s ...' % (cellName, fileName) exec('cell = tempModule' + '.' + cellName) #cell = getattr(modulePointer, cellName) # get cell object secs, secLists, synMechs = getCellParams(cell) cellRule = {'conds': conds, 'secs': secs, 'secLists': secLists} netParams.addCellParams(label, cellRule) if importSynMechs: for synMech in synMechs: netParams.addSynMechParams(synMech.pop('label'), synMech)
def importCell (fileName, cellName, cellArgs = None, cellInstance = False): h.initnrn() varList = mechVarList() # list of properties for all density mechanisms and point processes origGlob = getGlobals(varList['mechs'].keys()+varList['pointps'].keys()) if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): h.load_file(fileName) if not cellInstance: if isinstance(cellArgs, dict): cell = getattr(h, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args else: cell = getattr(h, cellName) elif fileName.endswith('.py'): filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)(*cellArgs) # create cell using template, passing list with args sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return secDic, secListDic, synMechs, globs = getCellParams(cell, varList, origGlob) if fileName.endswith('.py'): _delete_module(moduleName) _delete_module('tempModule') del modulePointer setGlobals(origGlob) # restore original globals return secDic, secListDic, synMechs, globs
def importCell(fileName, cellName, cellArgs=None): h.initnrn() if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): h.load_file(fileName) if isinstance(cellArgs, dict): cell = getattr( h, cellName )(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)( *cellArgs ) # create cell using template, passing list with args elif fileName.endswith('.py'): filePath, fileNameOnly = os.path.split( fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[ 0] # remove .py to obtain module name exec('import ' + moduleName + ' as tempModule' ) in globals(), locals() # import module dynamically modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr( modulePointer, cellName )(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)( *cellArgs ) # create cell using template, passing list with args sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return secDic, secListDic, synMechs = getCellParams(cell) return secDic, secListDic, synMechs
def importCellsFromNet (netParams, fileName, labelList, condsList, cellNamesList, importSynMechs): h.initnrn() ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): print 'Importing from .hoc network not yet supported' return # h.load_file(fileName) # for cellName in cellNames: # cell = getattr(h, cellName) # create cell using template, passing dict with args # secDic, secListDic, synMechs = getCellParams(cell) elif fileName.endswith('.py'): origDir = os.getcwd() filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name os.chdir(filePath) print '\nRunning network in %s to import cells into NetPyNE ...\n'%(fileName) from neuron import load_mechanisms load_mechanisms(filePath) exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically modulePointer = tempModule sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return for label, conds, cellName in zip(labelList, condsList, cellNamesList): print '\nImporting %s from %s ...'%(cellName, fileName) exec('cell = tempModule' + '.' + cellName) #cell = getattr(modulePointer, cellName) # get cell object secs, secLists, synMechs = getCellParams(cell) cellRule = {'conds': conds, 'secs': secs, 'secLists': secLists} netParams.addCellParams(label, cellRule) if importSynMechs: for synMech in synMechs: netParams.addSynMechParams(synMech.pop('label'), synMech)
def getCellParams(cell): dirCell = dir(cell) if 'all_sec' in dirCell: secs = cell.all_sec elif 'sec' in dirCell: secs = [cell.sec] elif 'allsec' in dir(h): secs = [sec for sec in h.allsec()] elif 'soma' in dirCell: secs = [cell.soma] else: secs = [] # create dict with hname of each element in dir(cell) dirCellHnames = {} for dirCellName in dirCell: try: dirCellHnames.update( {getattr(cell, dirCellName).hname(): dirCellName}) except: pass # create dict with dir(cell) name corresponding to each hname dirCellSecNames = {} for sec in secs: dirCellSecNames.update({ hname: name for hname, name in dirCellHnames.iteritems() if hname == sec.hname() }) secDic = {} synMechs = [] for sec in secs: # create new section dict with name of section secName = getSecName(sec, dirCellSecNames) if len(secs) == 1: secName = 'soma' # if just one section rename to 'soma' secDic[secName] = { 'geom': {}, 'topol': {}, 'mechs': {} } # create dictionary to store sec info # store geometry properties standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm'] secDir = dir(sec) for geomParam in standardGeomParams: #if geomParam in secDir: try: secDic[secName]['geom'][geomParam] = sec.__getattribute__( geomParam) except: pass # store 3d geometry sec.push() # access current section so ismembrane() works numPoints = int(h.n3d()) if numPoints: points = [] for ipoint in range(numPoints): x = h.x3d(ipoint) y = h.y3d(ipoint) z = h.z3d(ipoint) diam = h.diam3d(ipoint) points.append((x, y, z, diam)) secDic[secName]['geom']['pt3d'] = points # store mechanisms varList = mechVarList( ) # list of properties for all density mechanisms and point processes ignoreMechs = ['dist'] # dist only used during cell creation ignoreVars = [] # mechDic = {} ionDic = {} for mech in dir(sec(0.5)): if h.ismembrane( mech ) and mech not in ignoreMechs: # check if membrane mechanism if not mech.endswith('_ion'): # exclude ions mechDic[mech] = {} # create dic for mechanism properties varNames = [ varName.replace('_' + mech, '') for varName in varList['mechs'][mech] ] varVals = [] for varName in varNames: if varName not in ignoreVars: try: varVals = [ seg.__getattribute__( mech).__getattribute__(varName) for seg in sec ] if len(set(varVals)) == 1: varVals = varVals[0] mechDic[mech][varName] = varVals except: pass #print 'Could not read variable %s from mechanism %s'%(varName,mech) # store ions elif mech.endswith('_ion'): ionName = mech.split('_ion')[0] varNames = [ varName.replace('_' + mech, '').replace(ionName, '') for varName in varList['mechs'][mech] ] varNames.append('e') varVals = [] ionDic[ionName] = {} # create dic for mechanism properties for varName in varNames: varNameSplit = varName if varName not in ignoreVars: try: varVals = [ seg.__getattribute__(varNameSplit + ionName) for seg in sec ] if len(set(varVals)) == 1: varVals = varVals[0] ionDic[ionName][varNameSplit] = varVals except: pass #print 'Could not read variable %s from mechanism %s'%(varName,mech) secDic[secName]['mechs'] = mechDic if len(ionDic) > 0: secDic[secName]['ions'] = ionDic # add synapses and point neurons # for now read fixed params, but need to find way to read only synapse params pointps = {} for seg in sec: for ipoint, point in enumerate(seg.point_processes()): pointpMod = point.hname().split('[')[0] varNames = varList['pointps'][pointpMod] if any([ s in pointpMod.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu'] ]): #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse synMech = {} synMech['label'] = pointpMod + '_' + str(len(synMechs)) synMech['mod'] = pointpMod #synMech['loc'] = seg.x for varName in varNames: try: synMech[varName] = point.__getattribute__(varName) except: print 'Could not read variable %s from synapse %s' % ( varName, synMech['label']) if not [ _equal_dicts( synMech, synMech2, ignore_keys=['label']) for synMech2 in synMechs ]: synMechs.append(synMech) else: # assume its a non-synapse point process pointpName = pointpMod + '_' + str(len(pointps)) pointps[pointpName] = {} pointps[pointpName]['mod'] = pointpMod pointps[pointpName]['loc'] = seg.x for varName in varNames: try: pointps[pointpName][ varName] = point.__getattribute__(varName) # special condition for Izhi model, to set vinit=vr # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) except: print 'Could not read %s variable from point process %s' % ( varName, pointpName) if pointps: secDic[secName]['pointps'] = pointps # store topology (keep at the end since h.SectionRef messes remaining loop) secRef = h.SectionRef(sec=sec) if secRef.has_parent(): secDic[secName]['topol']['parentSec'] = getSecName( secRef.parent().sec, dirCellSecNames) secDic[secName]['topol']['parentX'] = h.parent_connection() secDic[secName]['topol']['childX'] = h.section_orientation() h.pop_section() # to prevent section stack overflow # store section lists secLists = h.List('SectionList') if int(secLists.count()): secListDic = {} for i in xrange(int(secLists.count())): # loop over section lists hname = secLists.o(i).hname() if hname in dirCellHnames: # use python variable name secListName = dirCellHnames[hname] else: secListName = hname secListDic[secListName] = [ getSecName(sec, dirCellSecNames) for sec in secLists.o(i) ] else: secListDic = {} # celsius warning if hasattr(h, 'celsius'): if h.celsius != 6.3: # if not default value print "Warning: h.celsius=%.4g in imported file -- you can set this value in simConfig['hParams']['celsius']" % ( h.celsius) # clean h.initnrn() del (cell) # delete cell import gc gc.collect() return secDic, secListDic, synMechs
def getCellParams(cell): dirCell = dir(cell) if 'all_sec' in dirCell: secs = cell.all_sec elif 'sec' in dirCell: secs = [cell.sec] elif 'allsec' in dir(h): secs = [sec for sec in h.allsec()] elif 'soma' in dirCell: secs = [cell.soma] else: secs = [] # create dict with hname of each element in dir(cell) dirCellHnames = {} for dirCellName in dirCell: try: dirCellHnames.update({getattr(cell, dirCellName).hname(): dirCellName}) except: pass # create dict with dir(cell) name corresponding to each hname dirCellSecNames = {} for sec in secs: dirCellSecNames.update({hname: name for hname,name in dirCellHnames.iteritems() if hname == sec.hname()}) secDic = {} synMechs = [] for sec in secs: # create new section dict with name of section secName = getSecName(sec, dirCellSecNames) if len(secs) == 1: secName = 'soma' # if just one section rename to 'soma' secDic[secName] = {'geom': {}, 'topol': {}, 'mechs': {}} # create dictionary to store sec info # store geometry properties standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm'] secDir = dir(sec) for geomParam in standardGeomParams: #if geomParam in secDir: try: secDic[secName]['geom'][geomParam] = sec.__getattribute__(geomParam) except: pass # store 3d geometry sec.push() # access current section so ismembrane() works numPoints = int(h.n3d()) if numPoints: points = [] for ipoint in range(numPoints): x = h.x3d(ipoint) y = h.y3d(ipoint) z = h.z3d(ipoint) diam = h.diam3d(ipoint) points.append((x, y, z, diam)) secDic[secName]['geom']['pt3d'] = points # store mechanisms varList = mechVarList() # list of properties for all density mechanisms and point processes ignoreMechs = ['dist'] # dist only used during cell creation ignoreVars = [] # mechDic = {} ionDic = {} for mech in dir(sec(0.5)): if h.ismembrane(mech) and mech not in ignoreMechs: # check if membrane mechanism if not mech.endswith('_ion'): # exclude ions mechDic[mech] = {} # create dic for mechanism properties varNames = [varName.replace('_'+mech, '') for varName in varList['mechs'][mech]] varVals = [] for varName in varNames: if varName not in ignoreVars: try: varVals = [seg.__getattribute__(mech).__getattribute__(varName) for seg in sec] if len(set(varVals)) == 1: varVals = varVals[0] mechDic[mech][varName] = varVals except: pass #print 'Could not read variable %s from mechanism %s'%(varName,mech) # store ions elif mech.endswith('_ion'): ionName = mech.split('_ion')[0] varNames = [varName.replace('_'+mech, '').replace(ionName,'') for varName in varList['mechs'][mech]] varNames.append('e') varVals = [] ionDic[ionName] = {} # create dic for mechanism properties for varName in varNames: varNameSplit = varName if varName not in ignoreVars: try: varVals = [seg.__getattribute__(varNameSplit+ionName) for seg in sec] if len(set(varVals)) == 1: varVals = varVals[0] ionDic[ionName][varNameSplit] = varVals except: pass #print 'Could not read variable %s from mechanism %s'%(varName,mech) secDic[secName]['mechs'] = mechDic if len(ionDic)>0: secDic[secName]['ions'] = ionDic # add synapses and point neurons # for now read fixed params, but need to find way to read only synapse params pointps = {} for seg in sec: for ipoint,point in enumerate(seg.point_processes()): pointpMod = point.hname().split('[')[0] varNames = varList['pointps'][pointpMod] if any([s in pointpMod.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']]): #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse synMech = {} synMech['label'] = pointpMod + '_' + str(len(synMechs)) synMech['mod'] = pointpMod #synMech['loc'] = seg.x for varName in varNames: try: synMech[varName] = point.__getattribute__(varName) except: print 'Could not read variable %s from synapse %s'%(varName,synMech['label']) if not [_equal_dicts(synMech, synMech2, ignore_keys=['label']) for synMech2 in synMechs]: synMechs.append(synMech) else: # assume its a non-synapse point process pointpName = pointpMod + '_'+ str(len(pointps)) pointps[pointpName] = {} pointps[pointpName]['mod'] = pointpMod pointps[pointpName]['loc'] = seg.x for varName in varNames: try: pointps[pointpName][varName] = point.__getattribute__(varName) # special condition for Izhi model, to set vinit=vr # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) except: print 'Could not read %s variable from point process %s'%(varName,pointpName) if pointps: secDic[secName]['pointps'] = pointps # store topology (keep at the end since h.SectionRef messes remaining loop) secRef = h.SectionRef(sec=sec) if secRef.has_parent(): secDic[secName]['topol']['parentSec'] = getSecName(secRef.parent().sec, dirCellSecNames) secDic[secName]['topol']['parentX'] = h.parent_connection() secDic[secName]['topol']['childX'] = h.section_orientation() h.pop_section() # to prevent section stack overflow # store section lists secLists = h.List('SectionList') if int(secLists.count()): secListDic = {} for i in xrange(int(secLists.count())): # loop over section lists hname = secLists.o(i).hname() if hname in dirCellHnames: # use python variable name secListName = dirCellHnames[hname] else: secListName = hname secListDic[secListName] = [getSecName(sec, dirCellSecNames) for sec in secLists.o(i)] else: secListDic = {} # celsius warning if hasattr(h, 'celsius'): if h.celsius != 6.3: # if not default value print "Warning: h.celsius=%.4g in imported file -- you can set this value in simConfig['hParams']['celsius']"%(h.celsius) # clean h.initnrn() del(cell) # delete cell import gc; gc.collect() return secDic, secListDic, synMechs
from neuron import h h.initnrn()
def importCell (fileName, cellName, cellArgs = None): h.initnrn() if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): h.load_file(fileName) if isinstance(cellArgs, dict): cell = getattr(h, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args secs = list(cell.allsec()) dirCell = dir(cell) elif fileName.endswith('.py'): filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)(*cellArgs) # create cell using template, passing list with args dirCell = dir(cell) if 'all_sec' in dirCell: secs = cell.all_sec elif 'sec' in dirCell: secs = [cell.sec] elif 'allsec' in dir(h): secs = [sec for sec in h.allsec()] elif 'soma' in dirCell: secs = [cell.soma] else: secs = [] sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return # create dict with hname of each element in dir(cell) dirCellHnames = {} for dirCellName in dirCell: try: dirCellHnames.update({getattr(cell, dirCellName).hname(): dirCellName}) except: pass # create dict with dir(cell) name corresponding to each hname dirCellSecNames = {} for sec in secs: dirCellSecNames.update({hname: name for hname,name in dirCellHnames.iteritems() if hname == sec.hname()}) secDic = {} synMechs = [] for sec in secs: # create new section dict with name of section secName = getSecName(sec, dirCellSecNames) if len(secs) == 1: secName = 'soma' # if just one section rename to 'soma' secDic[secName] = {'geom': {}, 'topol': {}, 'mechs': {}} # create dictionary to store sec info # store geometry properties standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm'] secDir = dir(sec) for geomParam in standardGeomParams: #if geomParam in secDir: try: secDic[secName]['geom'][geomParam] = sec.__getattribute__(geomParam) except: pass # store 3d geometry numPoints = int(h.n3d()) if numPoints: points = [] for ipoint in range(numPoints): x = h.x3d(ipoint) y = h.y3d(ipoint) z = h.z3d(ipoint) diam = h.diam3d(ipoint) points.append((x, y, z, diam)) secDic[secName]['geom']['pt3d'] = points # store mechanisms varList = mechVarList() # list of properties for all density mechanisms and point processes ignoreMechs = ['dist'] # dist only used during cell creation mechDic = {} sec.push() # access current section so ismembrane() works for mech in dir(sec(0.5)): if h.ismembrane(mech) and mech not in ignoreMechs: # check if membrane mechanism mechDic[mech] = {} # create dic for mechanism properties varNames = [varName.replace('_'+mech, '') for varName in varList['mechs'][mech]] varVals = [] for varName in varNames: try: varVals = [seg.__getattribute__(mech).__getattribute__(varName) for seg in sec] if len(set(varVals)) == 1: varVals = varVals[0] mechDic[mech][varName] = varVals except: pass #print 'Could not read variable %s from mechanism %s'%(varName,mech) secDic[secName]['mechs'] = mechDic # add synapses and point neurons # for now read fixed params, but need to find way to read only synapse params pointps = {} for seg in sec: for ipoint,point in enumerate(seg.point_processes()): pointpMod = point.hname().split('[')[0] varNames = varList['pointps'][pointpMod] if any([s in pointpMod.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']]): #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse synMech = {} synMech['label'] = pointpMod + '_' + str(len(synMechs)) synMech['mod'] = pointpMod #synMech['loc'] = seg.x for varName in varNames: try: synMech[varName] = point.__getattribute__(varName) except: print 'Could not read variable %s from synapse %s'%(varName,synMech['label']) if not [_equal_dicts(synMech, synMech2, ignore_keys=['label']) for synMech2 in synMechs]: synMechs.append(synMech) else: # assume its a non-synapse point process pointpName = pointpMod + '_'+ str(len(pointps)) pointps[pointpName] = {} pointps[pointpName]['mod'] = pointpMod pointps[pointpName]['loc'] = seg.x for varName in varNames: try: pointps[pointpName][varName] = point.__getattribute__(varName) # special condition for Izhi model, to set vinit=vr # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) except: print 'Could not read %s variable from point process %s'%(varName,pointpName) if pointps: secDic[secName]['pointps'] = pointps # store topology (keep at the end since h.SectionRef messes remaining loop) secRef = h.SectionRef(sec=sec) if secRef.has_parent(): secDic[secName]['topol']['parentSec'] = getSecName(secRef.parent().sec, dirCellSecNames) secDic[secName]['topol']['parentX'] = h.parent_connection() secDic[secName]['topol']['childX'] = h.section_orientation() h.pop_section() # to prevent section stack overflow # # store synMechs in input argument # if synMechs: # for synMech in synMechs: synMechParams.append(synMech) # store section lists secLists = h.List('SectionList') if int(secLists.count()): secListDic = {} for i in xrange(int(secLists.count())): # loop over section lists hname = secLists.o(i).hname() if hname in dirCellHnames: # use python variable name secListName = dirCellHnames[hname] else: secListName = hname secListDic[secListName] = [getSecName(sec, dirCellSecNames) for sec in secLists.o(i)] else: secListDic = {} # celsius warning if hasattr(h, 'celsius'): if h.celsius != 6.3: # if not default value print "Warning: h.celsius=%.4g in imported file %s -- you can set this value in simConfig['hParams']['celsius']"%(h.celsius, fileName) # clean h.initnrn() del(cell) # delete cell import gc; gc.collect() return secDic, secListDic, synMechs
def createPops(self): # Get info from nodes files for n in self.network_config['networks']['nodes']: nodes_file = self.subs(n['nodes_file']) node_types_file = self.subs(n['node_types_file']) print("\nLoading nodes from %s and %s"%(nodes_file, node_types_file)) h5file = tables.open_file(nodes_file,mode='r') self.parse_group(h5file.root.nodes) h5file.close() self.nodes_info[self.current_node] = load_csv_props(node_types_file) self.current_node = None pp.pprint(self.nodes_info) # Use extracted node/cell info to create populations for sonata_pop in self.cell_info: # iterate over cell types -- will make one netpyne population per cell type for type in self.cell_info[sonata_pop]['type_numbers']: info = self.nodes_info[sonata_pop][type] pop_name = info['pop_name'] if 'pop_name' in info else None ref = info['model_name'] if 'model_name' in info else info['model_type'] model_type = info['model_type'] model_template = info['model_template'] if 'model_template' in info else '- None -' if pop_name: pop_id = '%s_%s'%(sonata_pop, pop_name) else: pop_id = '%s_%s_%s'%(sonata_pop,ref,type) self.pop_id_from_type[(sonata_pop, type)] = pop_id print(" - Adding population: %s which has model info: %s"%(pop_id, info)) size = self.cell_info[sonata_pop]['type_numbers'][type] # create netpyne pop # Note: alternatively could create sim.net.params.popParams and then call sim.createPops() popTags = {} popTags['cellModel'] = model_type popTags['cellType'] = info['model_name'] if 'model_name' in info else pop_id popTags['numCells'] = size popTags['pop'] = pop_id popTags['ei'] = info['ei'] if 'ei' in info else '' sim.net.pops[pop_id] = sim.Pop(pop_id, popTags) sim.net.params.popParams[pop_id] = popTags # create population cell template (sections) from morphology and dynamics params files if model_type == 'biophysical': sim.net.pops[pop_id].cellModelClass = sim.CompartCell # morphology morphology_file = self.subs(self.network_config['components']['morphologies_dir']) +'/'+info['morphology'] + '.swc' cellMorph = EmptyCell() swcData = h.Import3d_SWC_read() swcData.input(morphology_file) swcSecs = h.Import3d_GUI(swcData, 0) swcSecs.instantiate(cellMorph) # replace axon with AIS stub if self.replaceAxon: fix_axon_peri(cellMorph) # extract netpyne parameters secs, secLists, synMechs, globs = neuronPyHoc.getCellParams(cellMorph) # remove sec vinits since imported temporary cell with morph for secName in secs: del secs[secName]['vinit'] # fix nseg based on dL if self.setdLNseg: fix_sec_nseg(secs, sim.cfg.dL) # invert y coordinates # if self.swapSomaXY: # swap_soma_xy(secs) # make soma mid segment (x,y,z) = (0,0,0) # somaLabel = next((s for s in secs.keys() if 'soma' in s), None) # somaPtFirst = secs[somaLabel]['geom']['pt3d'][0] # somaPtLast = secs[somaLabel]['geom']['pt3d'][-1] # somaPt = [(p1+p2)/2.0 for p1,p2 in zip(somaPtFirst, somaPtLast)] # for secLabel in secs: # for ipt3d in range(len(secs[secLabel]['geom']['pt3d'])): # origPt = secs[secLabel]['geom']['pt3d'][ipt3d] # offsetX = 0.0 # if 'apic' in secLabel: # offsetX = 0.0 # newpt = (origPt[0] - somaPt[0] + offsetX, origPt[1] - somaPt[1], origPt[2] - somaPt[2], origPt[3]) # secs[secLabel]['geom']['pt3d'][ipt3d] = newpt # create mapping of sec ids secLists['SONATA_sec_id'] = [sim.conversion.getSecName(sec) for sec in cellMorph.all] cellRule = {'conds': {'pop': pop_id}, 'secs': secs, 'secLists': secLists, 'globals': globs} # dynamics params if info['model_template'].startswith('nml'): dynamics_params_file = self.subs(self.network_config['components']['biophysical_neuron_models_dir']+'/'+info['model_template']) dynamics_params_file = dynamics_params_file.replace('nml:', '') #nml_doc = read_neuroml2_file(dynamics_params_file) #cell_dynamic_params = nml_doc.cells[0] cell_dynamic_params = NMLTree(dynamics_params_file) cellRule = self.setCellRuleDynamicParamsFromNeuroml(cell_dynamic_params, cellRule) elif info['dynamics_params'].endswith('json'): dynamics_params_file = self.subs(self.network_config['components']['biophysical_neuron_models_dir']+'/'+info['dynamics_params']) cell_dynamic_params = load_json(dynamics_params_file) cellRule = self.setCellRuleDynamicParamsFromJson(cell_dynamic_params, cellRule) # set extracted cell params in cellParams rule sim.net.params.cellParams[pop_id] = cellRule # clean up before next import del swcSecs, cellMorph h.initnrn() # create population of virtual cells (VecStims so can add spike times) elif model_type == 'virtual': popTags['cellModel'] = 'VecStim' sim.net.pops[pop_id].cellModelClass = sim.PointCell
def createPops(self): # Get info from nodes files for n in self.network_config['networks']['nodes']: nodes_file = self.subs(n['nodes_file']) node_types_file = self.subs(n['node_types_file']) print("\nLoading nodes from %s and %s" % (nodes_file, node_types_file)) h5file = tables.open_file(nodes_file, mode='r') self.parse_group(h5file.root.nodes) h5file.close() self.nodes_info[self.current_node] = load_csv_props( node_types_file) self.current_node = None pp.pprint(self.nodes_info) # Use extracted node/cell info to create populations for sonata_pop in self.cell_info: # iterate over cell types -- will make one netpyne population per cell type for type in self.cell_info[sonata_pop]['type_numbers']: info = self.nodes_info[sonata_pop][type] pop_name = info['pop_name'] if 'pop_name' in info else None ref = info['model_name'] if 'model_name' in info else info[ 'model_type'] model_type = info['model_type'] model_template = info[ 'model_template'] if 'model_template' in info else '- None -' if pop_name: pop_id = '%s_%s' % (sonata_pop, pop_name) else: pop_id = '%s_%s_%s' % (sonata_pop, ref, type) self.pop_id_from_type[(sonata_pop, type)] = pop_id print(" - Adding population: %s which has model info: %s" % (pop_id, info)) size = self.cell_info[sonata_pop]['type_numbers'][type] # create netpyne pop # Note: alternatively could create sim.net.params.popParams and then call sim.createPops() popTags = {} popTags['cellModel'] = model_type popTags['cellType'] = info[ 'model_name'] if 'model_name' in info else pop_id popTags['numCells'] = size popTags['pop'] = pop_id popTags['ei'] = info['ei'] if 'ei' in info else '' sim.net.pops[pop_id] = sim.Pop(pop_id, popTags) # create population cell template (sections) from morphology and dynamics params files if model_type == 'biophysical': sim.net.pops[pop_id].cellModelClass = sim.CompartCell # morphology morphology_file = self.subs( self.network_config['components']['morphologies_dir'] ) + '/' + info['morphology'] + '.swc' cellMorph = EmptyCell() swcData = h.Import3d_SWC_read() swcData.input(morphology_file) swcSecs = h.Import3d_GUI(swcData, 0) swcSecs.instantiate(cellMorph) # replace axon with AIS stub if self.replaceAxon: fix_axon_peri_v2(cellMorph) # extract netpyne parameters secs, secLists, synMechs, globs = neuronPyHoc.getCellParams( cellMorph) if self.setdLNseg: fix_sec_nseg(secs, sim.cfg.dL) # create mapping of sec ids secLists['SONATA_sec_id'] = [ sim.conversion.getSecName(sec) for sec in cellMorph.all ] cellRule = { 'conds': { 'pop': pop_id }, 'secs': secs, 'secLists': secLists, 'globals': globs } # dynamics params dynamics_params_file = self.subs( self.network_config['components'] ['biophysical_neuron_models_dir'] + '/' + info['model_template']) if info['model_template'].startswith('nml'): dynamics_params_file = dynamics_params_file.replace( 'nml:', '') nml_doc = read_neuroml2_file(dynamics_params_file) cell_dynamic_params = nml_doc.cells[0] cellRule = self.setCellRuleDynamicParamsFromNeuroml( cell_dynamic_params, cellRule) elif info['dynamics_params'].startswith('json'): dynamics_params = load_json(dynamics_params_file) pass # set extracted cell params in cellParams rule sim.net.params.cellParams[pop_id] = cellRule # clean up before next import del swcSecs, cellMorph h.initnrn() # create population of virtual cells (VecStims so can add spike times) elif model_type == 'virtual': popTags['cellModel'] = 'VecStim' sim.net.pops[pop_id].cellModelClass = sim.PointCell
def importCell(fileName, cellName, cellArgs=None, cellInstance=False): """ Function for/to <short description of `netpyne.conversion.neuronPyHoc.importCell`> Parameters ---------- fileName : <type> <Short description of fileName> **Default:** *required* cellName : <type> <Short description of cellName> **Default:** *required* cellArgs : <``None``?> <Short description of cellArgs> **Default:** ``None`` **Options:** ``<option>`` <description of option> cellInstance : bool <Short description of cellInstance> **Default:** ``False`` **Options:** ``<option>`` <description of option> """ h.initnrn() varList = mechVarList( ) # list of properties for all density mechanisms and point processes origGlob = getGlobals( list(varList['mechs'].keys()) + list(varList['pointps'].keys())) origGlob[ 'v_init'] = -65 # add by hand since won't be set unless load h.load_file('stdrun') if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined if fileName.endswith('.hoc') or fileName.endswith('.tem'): h.load_file(fileName) if not cellInstance: if isinstance(cellArgs, dict): cell = getattr(h, cellName)( **cellArgs ) # create cell using template, passing dict with args else: cell = getattr(h, cellName)( *cellArgs ) # create cell using template, passing list with args else: try: cell = getattr(h, cellName) except: cell = None elif fileName.endswith('.py'): filePath, fileNameOnly = os.path.split( fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) removeFilePath = True else: removeFilePath = False moduleName = fileNameOnly.split('.py')[ 0] # remove .py to obtain module name tempModule = importlib.import_module(moduleName) modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr( modulePointer, cellName )(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)( *cellArgs ) # create cell using template, passing list with args if removeFilePath: sys.path.remove(filePath) else: print("File name should be either .hoc or .py file") return secDic, secListDic, synMechs, globs = getCellParams( cell, varList, origGlob) if fileName.endswith('.py'): _delete_module(moduleName) _delete_module('tempModule') del modulePointer elif fileName.endswith('.hoc'): for sec in h.allsec(): try: if h.cas() != sec: sec.push() h.delete_section() h.pop_section() except: pass h.initnrn() setGlobals(origGlob) # restore original globals return secDic, secListDic, synMechs, globs