def poolMerge(comptA,comptB,poolNotcopiedyet): aCmptGrp = moose.wildcardFind(comptA.path+'/#[TYPE=Neutral]') aCmptGrp = aCmptGrp +(moose.element(comptA.path),) bCmptGrp = moose.wildcardFind(comptB.path+'/#[TYPE=Neutral]') bCmptGrp = bCmptGrp +(moose.element(comptB.path),) objA = moose.element(comptA.path).parent.name objB = moose.element(comptB.path).parent.name for bpath in bCmptGrp: grp_cmpt = ((bpath.path).replace(objB,objA)).replace('[0]','') if moose.exists(grp_cmpt) : if moose.element(grp_cmpt).className != bpath.className: grp_cmpt = grp_cmpt+'_grp' bpath.name = bpath.name+"_grp" l = moose.Neutral(grp_cmpt) else: #moose.Neutral(grp_cmpt) src = bpath srcpath = (bpath.parent).path des = srcpath.replace(objB,objA) moose.copy(bpath,moose.element(des)) apath = moose.element(bpath.path.replace(objB,objA)) bpoollist = moose.wildcardFind(bpath.path+'/#[ISA=PoolBase]') apoollist = moose.wildcardFind(apath.path+'/#[ISA=PoolBase]') for bpool in bpoollist: if bpool.name not in [apool.name for apool in apoollist]: copied = copy_deleteUnlyingPoolObj(bpool,apath) if copied == False: #hold it for later, this pool may be under enzyme, as cplx poolNotcopiedyet.append(bpool)
def creaetHHComp(parent='/library', name='hhcomp', diameter=1e-6, length=1e-6): """Create a compartment with Hodgkin-Huxley type ion channels (Na and K). Returns a 3-tuple: (compartment, nachannel, kchannel) """ compPath = '{}/{}'.format(parent, name) mc = MooseCompartment( compPath, length, diameter, {}) c = mc.mc_ sarea = mc.surfaceArea if moose.exists('/library/na'): moose.copy('/library/na', c.path, 'na') else: create_na_chan(parent = c.path) na = moose.element('%s/na' % (c.path)) # Na-conductance 120 mS/cm^2 na.Gbar = 120e-3 * sarea * 1e4 na.Ek = 115e-3 + EREST_ACT moose.connect(c, 'channel', na, 'channel') if moose.exists('/library/k'): moose.copy('/library/k', c.path, 'k') else: create_k_chan(parent = c.path) k = moose.element('%s/k' % (c.path)) # K-conductance 36 mS/cm^2 k.Gbar = 36e-3 * sarea * 1e4 k.Ek = -12e-3 + EREST_ACT moose.connect(c, 'channel', k, 'channel') return (c, na, k)
def installCellFromProtos( self ): if self.stealCellFromLibrary: moose.move( self.elecid, self.model ) if self.elecid.name != 'elec': self.elecid.name = 'elec' else: moose.copy( self.elecid, self.model, 'elec' ) self.elecid = moose.element( self.model.path + '/elec' ) self.elecid.buildSegmentTree() # rebuild: copy has happened. if hasattr( self, 'chemid' ): self.validateChem() if self.stealCellFromLibrary: moose.move( self.chemid, self.model ) if self.chemid.name != 'chem': self.chemid.name = 'chem' else: moose.copy( self.chemid, self.model, 'chem' ) self.chemid = moose.element( self.model.path + '/chem' ) ep = self.elecid.path somaList = moose.wildcardFind( ep + '/#oma#[ISA=CompartmentBase]' ) if len( somaList ) == 0: somaList = moose.wildcardFind( ep + '/#[ISA=CompartmentBase]' ) if len( somaList ) == 0: raise BuildError( "installCellFromProto: No soma found" ) maxdia = 0.0 for i in somaList: if ( i.diameter > maxdia ): self.soma = i
def create_compartment(path): comp = moose.Compartment(path) comp.diameter = soma_dia comp.Em = EREST_ACT + 10.613e-3 comp.initVm = EREST_ACT sarea = np.pi * soma_dia * soma_dia comp.Rm = 1/(0.3e-3 * 1e4 * sarea) comp.Cm = 1e-6 * 1e4 * sarea if moose.exists('/library/na'): nachan = moose.element(moose.copy('/library/na', comp, 'na')) else: nachan = create_na_chan(comp.path) nachan.Gbar = 120e-3 * sarea * 1e4 moose.showfield(nachan) moose.connect(nachan, 'channel', comp, 'channel') if moose.exists('/library/k'): kchan = moose.element(moose.copy('/library/k', comp, 'k')) else: kchan = create_k_chan(comp.path) kchan.Gbar = 36e-3 * sarea * 1e4 moose.connect(kchan, 'channel', comp, 'channel') synchan = moose.SynChan(comp.path + '/synchan') synchan.Gbar = 1e-8 synchan.tau1 = 2e-3 synchan.tau2 = 2e-3 synchan.Ek = 0.0 m = moose.connect(comp, 'channel', synchan, 'channel') spikegen = moose.SpikeGen(comp.path + '/spikegen') spikegen.threshold = 0.0 m = moose.connect(comp, 'VmOut', spikegen, 'Vm') return comp
def create_hhcomp(parent='/library', name='hhcomp', diameter=-30e-6, length=0.0): """Create a compartment with Hodgkin-Huxley type ion channels (Na and K). Returns a 3-tuple: (compartment, nachannel, kchannel) """ comp, sarea = create_passive_comp(parent, name, diameter, length) if moose.exists('/library/na'): moose.copy('/library/na', comp.path, 'na') else: create_na_chan(parent=comp.path) na = moose.element('%s/na' % (comp.path)) # Na-conductance 120 mS/cm^2 na.Gbar = 120e-3 * sarea * 1e4 na.Ek = 115e-3 + EREST_ACT moose.connect(comp, 'channel', na, 'channel') if moose.exists('/library/k'): moose.copy('/library/k', comp.path, 'k') else: create_k_chan(parent=comp.path) k = moose.element('%s/k' % (comp.path)) # K-conductance 36 mS/cm^2 k.Gbar = 36e-3 * sarea * 1e4 k.Ek = -12e-3 + EREST_ACT moose.connect(comp, 'channel', k, 'channel') return comp, na, k
def __init__(self, path): if not moose.exists(path): path_tokens = path.rpartition('/') moose.copy(self.prototype, path_tokens[0], path_tokens[-1]) moose.Neutral.__init__(self, path) self.solver = moose.HSolve('{}/solver'.format(path, 'solver')) self.solver.target = path self.solver.dt = config.simulationSettings.simulationDt
def buildFromMemory( self, ePath, cPath, doCopy = False ): if not self.validateFromMemory( ePath, cPath ): return if doCopy: x = moose.copy( cPath, self.model ) self.chemid = moose.element( x ) self.chemid.name = 'chem' x = moose.copy( ePath, self.model ) self.elecid = moose.element( x ) self.elecid.name = 'elec' else: self.elecid = moose.element( ePath ) self.chemid = moose.element( cPath ) if self.elecid.path != self.model.path + '/elec': if ( self.elecid.parent != self.model ): moose.move( self.elecid, self.model ) self.elecid.name = 'elec' if self.chemid.path != self.model.path + '/chem': if ( self.chemid.parent != self.model ): moose.move( self.chemid, self.model ) self.chemid.name = 'chem' ep = self.elecid.path somaList = moose.wildcardFind( ep + '/#oma#[ISA=CompartmentBase]' ) if len( somaList ) == 0: somaList = moose.wildcardFind( ep + '/#[ISA=CompartmentBase]' ) assert( len( somaList ) > 0 ) maxdia = 0.0 for i in somaList: if ( i.diameter > maxdia ): self.soma = i #self.soma = self.comptList[0] self._decorateWithSpines() self.spineList = moose.wildcardFind( ep + '/#spine#[ISA=CompartmentBase],' + ep + '/#head#[ISA=CompartmentBase]' ) if len( self.spineList ) == 0: self.spineList = moose.wildcardFind( ep + '/#head#[ISA=CompartmentBase]' ) nmdarList = moose.wildcardFind( ep + '/##[ISA=NMDAChan]' ) self.comptList = moose.wildcardFind( ep + '/#[ISA=CompartmentBase]') print "Rdesigneur: Elec model has ", len( self.comptList ), \ " compartments and ", len( self.spineList ), \ " spines with ", len( nmdarList ), " NMDARs" self._buildNeuroMesh() self._configureSolvers() for i in self.adaptorList: print i self._buildAdaptor( i[0],i[1],i[2],i[3],i[4],i[5],i[6] )
def create_neuron(model, ntype, ghkYN): p_file = find_morph_file(model,ntype) try: cellproto=moose.loadModel(p_file, ntype) except IOError: print('could not load model from {!r}'.format(p_file)) raise #######channels Cond = model.Condset[ntype] for comp in moose.wildcardFind('{}/#[TYPE=Compartment]'.format(ntype)): #If we are using GHK, just create one GHK per compartment, connect it to comp #calcium concentration is connected in a different function if ghkYN: ghkproto=moose.element('/library/ghk') ghk=moose.copy(ghkproto,comp,'ghk')[0] moose.connect(ghk,'channel',comp,'channel') else: ghk=[] for channame in Cond.keys(): c = _util.distance_mapping(Cond[channame], comp) if c > 0: log.debug('Testing Cond If {} {}', channame, c) calciumPermeable = model.Channels[channame].calciumPermeable add_channel.addOneChan(channame, c, comp, ghkYN, ghk, calciumPermeable=calciumPermeable) #Compensate for actual, experimentally estimated spine density. #This gives a model that can be simulated with no explicit spines or #any number of explicitly modeled spines up to the actual spine density: spines.compensate_for_spines(model,comp,model.param_cond.NAME_SOMA) return cellproto
def create_population(container, netparams, name_soma): netpath = container.path proto=[] neurXclass={} locationlist=[] #determine total number of neurons size,numneurons,vol=count_neurons(netparams) pop_percent=[] for neurtype in netparams.pop_dict.keys(): if moose.exists(neurtype): proto.append(moose.element(neurtype)) neurXclass[neurtype]=[] pop_percent.append(netparams.pop_dict[neurtype].percent) #create cumulative array of probabilities for selecting neuron type choicearray=np.cumsum(pop_percent) if choicearray[-1]<1.0: log.info("Warning!!!! fractional populations sum to {}",choicearray[-1]) #array of random numbers that will be used to select neuron type rannum = np.random.uniform(0,choicearray[-1],numneurons) #Error check for last element in choicearray equal to 1.0 log.info("numneurons= {} {} choicarray={}", size, numneurons, choicearray) log.debug("rannum={}", rannum) for i,xloc in enumerate(np.linspace(netparams.grid[0]['xyzmin'], netparams.grid[0]['xyzmax'], size[0])): for j,yloc in enumerate(np.linspace(netparams.grid[1]['xyzmin'], netparams.grid[1]['xyzmax'], size[1])): for k,zloc in enumerate(np.linspace(netparams.grid[2]['xyzmin'], netparams.grid[2]['xyzmax'], size[2])): #for each location in grid, assign neuron type, update soma location, add in spike generator neurnumber=i*size[2]*size[1]+j*size[2]+k neurtypenum=np.min(np.where(rannum[neurnumber]<choicearray)) log.debug("i,j,k {} {} {} neurnumber {} type {}", i,j,k, neurnumber, neurtypenum) typename = proto[neurtypenum].name tag = '{}_{}'.format(typename, neurnumber) new_neuron=moose.copy(proto[neurtypenum],netpath, tag) neurXclass[typename].append(container.path + '/' + tag) comp=moose.element(new_neuron.path + '/'+name_soma) comp.x=i*xloc comp.y=j*yloc comp.z=k*zloc log.debug("x,y,z={},{},{} {}", comp.x, comp.y, comp.z, new_neuron.path) locationlist.append([new_neuron.name,comp.x,comp.y,comp.z]) #spike generator - can this be done to the neuron prototype? spikegen = moose.SpikeGen(comp.path + '/spikegen') #should these be parameters in netparams? spikegen.threshold = 0.0 spikegen.refractT=1e-3 m = moose.connect(comp, 'VmOut', spikegen, 'Vm') #Create variability in neurons of network for neurtype in netparams.chanvar.keys(): for chan,var in netparams.chanvar[neurtype].items(): #single multiplier for Gbar for all the channels compartments if var>0: log.debug('adding variability to {} soma {}, variance: {}', neurtype,chan, var) GbarArray=abs(np.random.normal(1.0, var, len(neurXclass[neurtype]))) for ii,neurname in enumerate(neurXclass[neurtype]): soma_chan_path=neurname+'/'+name_soma+'/'+chan if moose.exists(soma_chan_path): chancomp=moose.element(soma_chan_path) chancomp.Gbar=chancomp.Gbar*GbarArray[ii] # return {'location': locationlist, 'pop':neurXclass}
def setup_single_compartment(container_path, channel_proto, Gbar): comp = make_testcomp(container_path) channel = moose.copy(channel_proto, comp, channel_proto.name)[0] moose.connect(channel, 'channel', comp, 'channel') channel.Gbar = Gbar pulsegen = make_pulsegen(container_path) moose.connect(pulsegen, 'outputOut', comp, 'injectMsg') vm_table = moose.Table('%s/Vm' % (container_path)) moose.connect(vm_table, 'requestData', comp, 'get_Vm') gk_table = moose.Table('%s/Gk' % (container_path)) moose.connect(gk_table, 'requestData', channel, 'get_Gk') ik_table = moose.Table('%s/Ik' % (container_path)) moose.connect(ik_table, 'requestData', channel, 'get_Ik') moose.setClock(0, simdt) moose.setClock(1, simdt) moose.setClock(2, simdt) moose.useClock(0, '%s/##[TYPE=Compartment]' % (container_path), 'init') moose.useClock(1, '%s/##[TYPE=Compartment]' % (container_path), 'process') moose.useClock(2, '%s/##[TYPE!=Compartment]' % (container_path), 'process') return {'compartment': comp, 'stimulus': pulsegen, 'channel': channel, 'Vm': vm_table, 'Gk': gk_table, 'Ik': ik_table}
def create_LIF(): neuromlR = NeuroML() neuromlR.readNeuroMLFromFile('cells_channels/LIF.morph.xml') libcell = moose.Neuron('/library/LIF') LIFCellid = moose.copy(libcell,moose.Neutral('/cells'),'IF1') LIFCell = moose.Neuron(LIFCellid) return LIFCell
def copyChannel(self, chdens, comp, condDensity, erev): """Copy moose prototype for `chdens` condutcance density to `comp` compartment. """ proto_chan = None if chdens.ion_channel in self.proto_chans: proto_chan = self.proto_chans[chdens.ion_channel] else: for innerReader in self.includes.values(): if chdens.ionChannel in innerReader.proto_chans: proto_chan = innerReader.proto_chans[chdens.ion_channel] break if not proto_chan: raise Exception('No prototype channel for %s referred to by %s' % (chdens.ion_channel, chdens.id)) if self.verbose: print('Copying %s to %s, %s; erev=%s'%(chdens.id, comp, condDensity, erev)) orig = chdens.id chid = moose.copy(proto_chan, comp, chdens.id) chan = moose.element(chid) for p in self.paths_to_chan_elements.keys(): pp = p.replace('%s/'%chdens.ion_channel,'%s/'%orig) self.paths_to_chan_elements[pp] = self.paths_to_chan_elements[p].replace('%s/'%chdens.ion_channel,'%s/'%orig) #print(self.paths_to_chan_elements) chan.Gbar = sarea(comp) * condDensity chan.Ek = erev moose.connect(chan, 'channel', comp, 'channel') return chan
def make_new_synapse(syn_name, postcomp, syn_name_full, nml_params): ## if channel does not exist in library load it from xml file if not moose.exists("/library/" + syn_name): cmlR = ChannelML(nml_params) model_filename = syn_name + ".xml" model_path = utils.find_first_file(model_filename, nml_params["model_dir"]) if model_path is not None: cmlR.readChannelMLFromFile(model_path) else: raise IOError( "For mechanism {0}: files {1} not found under {2}.".format( mechanismname, model_filename, self.model_dir ) ) ## deep copies the library SynChan and SynHandler ## to instances under postcomp named as <arg3> synid = moose.copy(moose.element("/library/" + syn_name), postcomp, syn_name_full) # synhandlerid = moose.copy(moose.element('/library/'+syn_name+'/handler'), postcomp,syn_name_full+'/handler') This line was a bug: double handler synhandler = moose.element(synid.path + "/handler") syn = moose.SynChan(synid) synhandler = moose.element(synid.path + "/handler") # returns SimpleSynHandler or STDPSynHandler ## connect the SimpleSynHandler or the STDPSynHandler to the SynChan (double exp) moose.connect(synhandler, "activationOut", syn, "activation") # mgblock connections if required childmgblock = moose_utils.get_child_Mstring(syn, "mgblockStr") #### connect the post compartment to the synapse if childmgblock.value == "True": # If NMDA synapse based on mgblock, connect to mgblock mgblock = moose.Mg_block(syn.path + "/mgblock") moose.connect(postcomp, "channel", mgblock, "channel") else: # if SynChan or even NMDAChan, connect normally moose.connect(postcomp, "channel", syn, "channel")
def create_LIF(): neuromlR = NeuroML() neuromlR.readNeuroMLFromFile("cells_channels/LIF.morph.xml") libcell = moose.Neuron("/library/LIF") LIFCellid = moose.copy(libcell, moose.Neutral("/cells"), "IF1") LIFCell = moose.Neuron(LIFCellid) return LIFCell
def setup_model(model_path, synapse_locations, passive=False, solver='hsolve'): """Set up a single cell model under `model_path` with synapses created in the compartments listed in `synapse_locations`. `model_path` - location where the model should be created. `synapse_locations`: compartment names for the synapses. """ cell = moose.copy(make_prototype(passive), model_path) if solver.lower() == 'hsolve': hsolve = moose.HSolve( '%s/solve' % (cell.path)) hsolve.dt = simdt hsolve.target = cell.path syninfo_list = [] for compname in synapse_locations: comppath = '%s/%s' % (cell.path, compname) print('1111 Creating synapse in', comppath) compartment = moose.element(comppath) syninfo = make_synapse(compartment) syninfo_list.append(syninfo) # connect pulse stimulus stim_path = '%s/%s/stim' % (cell.path, compname) print('2222 Creating stimuls in', stim_path) stim = moose.PulseGen(stim_path) moose.connect(stim, 'output', syninfo['spike'], 'Vm') syninfo['stimulus'] = stim return {'neuron': cell, 'syninfo': syninfo_list}
def _addSpine( self, parent, spineProto, pos, angle, x, y, z, size, k ): spine = moose.copy( spineProto, parent.parent, 'spine' + str(k) ) kids = spine[0].children coords = [] ppos = np.array( [parent.x0, parent.y0, parent.z0] ) for i in kids: #print i.name, k j = i[0] j.name += str(k) #print 'j = ', j coords.append( [j.x0, j.y0, j.z0] ) coords.append( [j.x, j.y, j.z] ) self._scaleSpineCompt( j, size ) moose.move( i, self.elecid ) origin = coords[0] #print 'coords = ', coords # Offset it so shaft starts from surface of parent cylinder origin[0] -= parent.diameter / 2.0 coords = np.array( coords ) coords -= origin # place spine shaft base at origin. rot = np.array( [x, [0,0,0], [0,0,0]] ) coords = np.dot( coords, rot ) moose.delete( spine ) moose.connect( parent, "raxial", kids[0], "axial" ) self._reorientSpine( kids, coords, ppos, pos, size, angle, x, y, z )
def singleCompt( name, params ): mod = moose.copy( '/library/' + name + '/' + name, '/model' ) A = moose.element( mod.path + '/A' ) Z = moose.element( mod.path + '/Z' ) Z.nInit = 1 Ca = moose.element( mod.path + '/Ca' ) CaStim = moose.element( Ca.path + '/CaStim' ) runtime = params['preStimTime'] + params['stimWidth'] + params['postStimTime'] steptime = 100 CaStim.expr += ' + x2 * (t > ' + str( runtime ) + ' ) * ( t < ' + str( runtime + steptime ) + ' )' print(CaStim.expr) tab = moose.Table2( '/model/' + name + '/Atab' ) #for i in range( 10, 19 ): #moose.setClock( i, 0.01 ) ampl = moose.element( mod.path + '/ampl' ) phase = moose.element( mod.path + '/phase' ) moose.connect( tab, 'requestOut', A, 'getN' ) ampl.nInit = params['stimAmplitude'] * 1 phase.nInit = params['preStimTime'] ksolve = moose.Ksolve( mod.path + '/ksolve' ) stoich = moose.Stoich( mod.path + '/stoich' ) stoich.compartment = mod stoich.ksolve = ksolve stoich.path = mod.path + '/##' runtime += 2 * steptime moose.reinit() moose.start( runtime ) t = np.arange( 0, runtime + 1e-9, tab.dt ) return name, t, tab.vector
def addCaPool(model,OutershellThickness,BufCapacity,comp,caproto,tau=None,tauScale=None): #create the calcium pools in each compartment capool = moose.copy(caproto, comp, caproto.name)[0] capool.thick = OutershellThickness capool.diameter = comp.diameter capool.length = comp.length radius = comp.diameter/2. if capool.thick > radius: capool.thick = radius if capool.length: vol = np.pi * comp.length * (radius**2 - (radius-capool.thick)**2) else: vol = 4./3.*np.pi*(radius**3-(radius-capool.thick)**3) if tau is not None: capool.tau = tau#*np.pi*comp.diameter*comp.length *0.125e10 #/(np.pi*comp.length*(comp.diameter/2)**2) # if tauScale is not None: if tauScale == 'SurfaceArea': capool.tau = tau * (np.pi * comp.diameter * comp.length) / 8.478e-11 # normalize to primdend surface area elif tauScale == 'Volume': capool.tau = tau / vol elif tauScale == 'SVR': #surface to volume ratio capool.tau = tau / (np.pi * comp.diameter * comp.length)/vol capool.B = 1. / (constants.Faraday*vol*2) / BufCapacity #volume correction connectVDCC_KCa(model,comp,capool,'current','concOut') connectNMDA(comp,capool,'current','concOut') #print('Adding CaConc to '+capool.path) return capool
def checkAndBuildProto( self, protoType, protoVec, knownClasses, knownFileTypes ): if len(protoVec) != 2: raise BuildError( \ protoType + "Proto: nargs should be 2, is " + \ str( len(protoVec) )) if moose.exists( '/library/' + protoVec[1] ): # Assume the job is already done, just skip it. return True ''' raise BuildError( \ protoType + "Proto: object /library/" + \ protoVec[1] + " already exists." ) ''' # Check and build the proto from a class name if protoVec[0][:5] == 'moose': protoName = protoVec[0][6:] if self.isKnownClassOrFile( protoName, knownClasses ): try: getAttr( moose, protoName )( '/library/' + protoVec[1] ) except AttributeError: raise BuildError( protoType + "Proto: Moose class '" \ + protoVec[0] + "' not found." ) return True if self.buildProtoFromFunction( protoVec[0], protoVec[1] ): return True # Maybe the proto is already in memory # Avoid relative file paths going toward root if protoVec[0][:3] != "../": if moose.exists( protoVec[0] ): moose.copy( protoVec[0], '/library/' + protoVec[1] ) return True if moose.exists( '/library/' + protoVec[0] ): #moose.copy('/library/' + protoVec[0], '/library/', protoVec[1]) print 'renaming /library/' + protoVec[0] + ' to ' + protoVec[1] moose.element( '/library/' + protoVec[0]).name = protoVec[1] #moose.le( '/library' ) return True # Check if there is a matching suffix for file type. if self.isKnownClassOrFile( protoVec[0], knownFileTypes ): return False else: raise BuildError( \ protoType + "Proto: File type '" + protoVec[0] + \ "' not known." ) return True
def insert_channel(compartment, channeclass, gbar, density=False): channel = moose.copy(channeclass.prototype, compartment)[0] if not density: channel.Gbar = gbar else: channel.Gbar = gbar * np.pi * compartment.length * compartment.diameter moose.connect(channel, 'channel', compartment, 'channel') return channel
def create_LIF(): neuromlR = NeuroML() neuromlR.readNeuroMLFromFile('cells_channels/LIF.morph.xml') libcell = moose.Neuron('/library/LIF') LIFCellid = moose.copy(libcell,moose.Neutral('/cells'),'IF1') # FIXME: No LeakyIaF is found in MOOSE. LIFCell = moose.LeakyIaF(LIFCellid) return LIFCell
def addChannelSet(condSet, library_name, cell, comp_type): for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi*comp.length*comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond*SA m = moose.connect(chan, 'channel', comp, 'channel') return
def createPopulations(self): for pop in self.network.populations: mpop = moose.Neutral('%s/%s' % (self.lib.path, pop.id)) self.cells_in_populations[pop.id] ={} for i in range(pop.size): print("Creating %s/%s instances of %s under %s"%(i,pop.size,pop.component, mpop)) self.pop_to_cell_type[pop.id]=pop.component chid = moose.copy(self.proto_cells[pop.component], mpop, '%s'%(i)) self.cells_in_populations[pop.id][i]=chid
def setup_two_cells(): """ Create two cells with leaky integrate and fire compartments. Each cell is a single compartment a1 and b2. a1 is stimulated by a step current injection. The compartment a1 is connected to the compartment b2 through a synaptic channel. """ model = moose.Neutral('/model') data = moose.Neutral('/data') a1 = LIFComp('/model/a1') b2 = LIFComp(moose.copy(a1, '/model', 'b2')) a1.Vthreshold = 10e-3 a1.Vreset = 0 b2.Vthreshold = 10e-3 b2.Vreset = 0 syn = moose.SynChan('%s/syn' % (b2.path)) syn.tau1 = 1e-3 syn.tau2 = 5e-3 syn.Ek = 90e-3 synh = moose.SimpleSynHandler( syn.path + '/synh' ) moose.connect( synh, 'activationOut', syn, 'activation' ) synh.synapse.num += 1 # syn.numSynapses = 1 synh.synapse.delay = delayMax moose.connect(b2, 'channel', syn, 'channel') ## Single message works most of the time but occassionally gives a ## core dump # m = moose.connect(a1.spikegen, 'spikeOut', # syn.synapse.vec, 'addSpike') ## With Sparse message and random connectivity I did not get core ## dump. m = moose.connect(a1.spikegen, 'spikeOut', synh.synapse.vec, 'addSpike', 'Sparse') m.setRandomConnectivity(1.0, 1) stim = moose.PulseGen('/model/stim') stim.delay[0] = 100e-3 stim.width[0] = 1e3 stim.level[0] = 11e-9 moose.connect(stim, 'output', a1, 'injectMsg') tables = [] data = moose.Neutral('/data') for c in moose.wildcardFind('/##[ISA=Compartment]'): tab = moose.Table('%s/%s_Vm' % (data.path, c.name)) moose.connect(tab, 'requestOut', c, 'getVm') tables.append(tab) syntab = moose.Table('%s/%s' % (data.path, 'Gk')) moose.connect(syntab, 'requestOut', syn, 'getGk') tables.append(syntab) synh.synapse[0].delay = 1e-3 syn.Gbar = 1e-6 return tables
def createMultiCompCell(file_name, container_name, library_name, comp_type, channelSet, condSet, rateParams, CaParams = None, CaPoolParams = None, HCNParams = None, cell_RM = None, cell_CM = None, cell_RA = None, cell_initVm = None, cell_Em = None): # Create the channel types and store them in a library to be used by each compartment # in the model createChanLib(library_name, channelSet, rateParams, CaParams, HCNParams) # Load in the model in question if file_name.endswith('.p'): cell = moose.loadModel(file_name, container_name) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi*comp.length*comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond*SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) else: cell = moose.loadModel(file_name, container_name) setCompParameters(cell, comp_type, cell_RM, cell_CM, cell_RA, cell_initVm, cell_Em) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi*comp.length*comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond*SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) return cell
def create_1comp_neuron(path, number=1): """Create single-compartmental neuron with Na+ and K+ channels. Parameters ---------- path : str path of the compartment to be created number : int number of compartments to be created. If n is greater than 1, we create a vec with that size, each having the same property. Returns ------- comp : moose.Compartment a compartment vec with `number` elements. """ comps = moose.vec(path=path, n=number, dtype='Compartment') diameter = 30e-6 length = 50e-6 sarea = np.pi * diameter * length xarea = np.pi * diameter * diameter / 4.0 Em = EREST_ACT + 10.613e-3 comps.Em = Em comps.initVm = EREST_ACT #: CM = 1 uF/cm^2 comps.Cm = 1e-6 * sarea * 1e4 #: RM = 0.3 mS/cm^2 comps.Rm = 1 / (0.3e-3 * sarea * 1e4) container = comps[0].parent.path #: Here we create copies of the prototype channels nachan = moose.copy(create_na_proto(), container, 'na_{}'.format(comps.name), number) #: Gbar_Na = 120 mS/cm^2 nachan.Gbar = [120e-3 * sarea * 1e4] * len(nachan) nachan.Ek = 115e-3 + EREST_ACT moose.connect(nachan, 'channel', comps, 'channel', 'OneToOne') kchan = moose.copy(create_k_proto(), container, 'k_{}'.format(comps.name), number) #: Gbar_K = 36 mS/cm^2 kchan.Gbar = 36e-3 * sarea * 1e4 kchan.Ek = -12e-3 + EREST_ACT moose.connect(kchan, 'channel', comps, 'channel', 'OneToOne') return comps
def addOneChan(chanpath, gbar,comp): SA = np.pi * comp.length * comp.diameter proto = moose.element('/library/' + chanpath) chan = moose.copy(proto, comp, chanpath) chan.Gbar = gbar * SA # If we are using GHK AND it is a calcium channel, connect it to GHK moose.connect(comp, 'VmOut', chan, 'Vm') moose.connect(chan, "channelOut", comp, "handleChannel") return chan
def add_calcium(libraryName, cellname, CaPoolParams, comp_type): Fday = 96485.33289 caproto = CaPoolProto(libraryName, CaPoolParams) for comp in moose.wildcardFind(cellname.path + '/' + '#[TYPE=' + comp_type + ']'): capool = moose.copy(caproto, comp, CaPoolParams.caName,1) capool.length = comp.length capool.diameter = comp.diameter SA = np.pi*capool.length*capool.diameter vol = SA*capool.thick capool.B = 1/(Fday*vol*2)/CaPoolParams.BufCapacity return
def addCapool(comp,caparams): caproto = moose.element('/library/' + caparams.caName) #print caproto capool= moose.copy(caproto, comp, caparams.caName) #print capool len = comp.length #print len dia= comp.diameter SA= np.pi*len*dia vol=SA*capool.thick capool.B=1/(Faraday*vol*2)/caparams.BufCapacity return capool
def createPopulations(self): self.populationDict = {} for population in self.network.findall(".//{"+nml_ns+"}population"): cellname = population.attrib["cell_type"] populationname = population.attrib["name"] print "loading", populationname ## if cell does not exist in library load it from xml file if not moose.exists('/library/'+cellname): mmlR = MorphML(self.nml_params) model_filenames = (cellname+'.xml', cellname+'.morph.xml') success = False for model_filename in model_filenames: model_path = find_first_file(model_filename,self.model_dir) if model_path is not None: cellDict = mmlR.readMorphMLFromFile(model_path) success = True break if not success: raise IOError( 'For cell {0}: files {1} not found under {2}.'.format( cellname, model_filenames, self.model_dir ) ) self.cellSegmentDict.update(cellDict) if cellname == 'LIF': libcell = moose.LeakyIaF('/library/'+cellname) else: libcell = moose.Neuron('/library/'+cellname) #added cells as a Neuron class. self.populationDict[populationname] = (cellname,{}) moose.Neutral('/cells') for instance in population.findall(".//{"+nml_ns+"}instance"): instanceid = instance.attrib['id'] location = instance.find('./{'+nml_ns+'}location') rotationnote = instance.find('./{'+meta_ns+'}notes') if rotationnote is not None: ## the text in rotationnote is zrotation=xxxxxxx zrotation = float(string.split(rotationnote.text,'=')[1]) else: zrotation = 0 ## deep copies the library cell to an instance under '/cells' named as <arg3> ## /cells is useful for scheduling clocks as all sim elements are in /cells cellid = moose.copy(libcell,moose.Neutral('/cells'),populationname+"_"+instanceid) if cellname == 'LIF': cell = moose.LeakyIaF(cellid) self.populationDict[populationname][1][int(instanceid)]=cell else: cell = moose.Neuron(cellid) # No Cell class in MOOSE anymore! :( addded Neuron class - Chaitanya self.populationDict[populationname][1][int(instanceid)]=cell x = float(location.attrib['x'])*self.length_factor y = float(location.attrib['y'])*self.length_factor z = float(location.attrib['z'])*self.length_factor self.translate_rotate(cell,x,y,z,zrotation)
# Set the axial resistance to match the one in the ionchannel.py file # and set the container to be used for channel creation squid.Ra = 1 container = squid.parent.path # Create the external current to be applied to the compartment squid_pulse = u.createPulse(squid, 'rollingWave', pulse_dur, pulse_amp, pulse_delay1, pulse_delay2) # Create the data tables necessary to run the model data = moose.Neutral('/data') squid_Vm, squid_current = u.createDataTables(squid, data, squid_pulse) # Create copies of the prototype channels and connect them to the # compartment nachan = moose.copy(create_na_proto(), container, 'na', 1) nachan.Gbar = 120e-3 * SA * 1e4 # Gbar_Na = 120 mS/cm^2 nachan.Ek = 115e-3 + EREST_ACT moose.connect(nachan, 'channel', squid, 'channel', 'OneToOne') kchan = moose.copy(create_k_proto(), container, 'k', 1) kchan.Gbar = 36e-3 * SA * 1e4 # Gbar_K = 36 mS/cm^2 kchan.Ek = -12e-3 + EREST_ACT moose.connect(kchan, 'channel', squid, 'channel', 'OneToOne') # Plot the simulation simtime = 0.1 simdt = 0.25e-5 plotdt = 0.25e-3 for i in range(10): moose.setClock(i, simdt) moose.setClock(8, plotdt)
def addSpines(model, container, ghkYN, name_soma): headarray = [] SpineParams = model.SpineParams suma = 0 modelcond = model.Condset[container] single_spine_surface = spine_surface(SpineParams) parentComp = container + '/' + SpineParams.spineParent compList = [SpineParams.spineParent] getChildren(parentComp, compList) for comp in moose.wildcardFind(container + '/#[TYPE=Compartment]'): dist = (comp.x**2 + comp.y**2 + comp.z**2)**0.5 if name_soma not in comp.path and comp.name in compList and ( SpineParams.spineEnd > dist > SpineParams.spineStart): #determine the number of spines numSpines = int(np.round(SpineParams.spineDensity * comp.length)) #if spine density is low (less than 1 per comp) use random number to determine whether to add a spine if not numSpines: rand = random.random() if rand > SpineParams.spineDensity * comp.length: numSpines = 1 suma += 1 #calculate total surface area of the added spines total_spine_surface = numSpines * single_spine_surface surface_area = comp.diameter * comp.length * np.pi # if SpineParams.compensationSpineDensity: # compensation_spine_surface = int(np.round(SpineParams.compensationSpineDensity*comp.length))*single_spine_surface # decompensate_compensate_for_spines(comp,total_spine_surface,surface_area,compensation_spine_surface) # else: #increase resistance according to the spines that should be there but aren't compensate_for_spines(comp, total_spine_surface, surface_area) #spineSpace = comp.length/(numSpines+1) #for each spine, make a spine and possibly compensate for its surface area for index in range(numSpines): frac = (index + 0.5) / numSpines #print comp.path,"Spine:", index, "located:", frac head, neck = makeSpine(model, comp, 'sp', index, frac, SpineParams) #now decrease resistance of compartment back to original value?!?! if SpineParams.compensationSpineDensity: decompensate_compensate_for_spines( comp, total_spine_surface, surface_area, compensation_spine_surface) else: #why are we altering head and neck resistance?!?! compensate_for_spines(head, total_spine_surface, surface_area) compensate_for_spines(neck, total_spine_surface, surface_area) headarray.append(head) if SpineParams.spineChanList: if ghkYN: ghkproto = moose.element('/library/ghk') ghk = moose.copy(ghkproto, comp, 'ghk')[0] moose.connect(ghk, 'channel', comp, 'channel') chan_list = [] for c in SpineParams.spineChanList: chan_list.extend(c) for chanpath in chan_list: cond = distance_mapping(modelcond[chanpath], head) if cond > 0: log.debug('Testing Cond If {} {}', chanpath, cond) calciumPermeable = model.Channels[ chanpath].calciumPermeable addOneChan(chanpath, cond, head, ghkYN, calciumPermeable=calciumPermeable) #end for index #end for comp log.info('{} spines created in {}', len(headarray), container) return headarray
from moose.utils import * from moose.neuroml.NeuroML import NeuroML from pylab import * SIMDT = 25e-6 # s PLOTDT = 25e-6 # s RUNTIME = 2.0 # s injectmax = 20e-12 # Amperes neuromlR = NeuroML() neuromlR.readNeuroMLFromFile('cells_channels/Granule_98.morph.xml') libcell = moose.Neuron('/library/Granule_98') granCellid = moose.copy(libcell, moose.Neutral('/cells'), 'granCell') granCell = moose.Neuron(granCellid) ## edge-detect the spikes using spike-gen (table does not have edge detect) spikeGen = moose.SpikeGen(granCell.path + '/spikeGen') spikeGen.threshold = 0e-3 # V granCellSoma = moose.Compartment(granCell.path + '/Soma_0') moose.connect(granCellSoma, 'VmOut', spikeGen, 'Vm') ## save spikes in table table_path = moose.Neutral(granCell.path + '/data').path granCellSpikesTable = moose.Table(table_path + '/spikesTable') moose.connect(spikeGen, 'spikeOut', granCellSpikesTable, 'input') ## from moose_utils.py sets clocks and resets/reinits resetSim(['/cells'], SIMDT, PLOTDT, simmethod='hsolve')
def buildFromMemory(self, ePath, cPath, doCopy=False): if not self.validateFromMemory(ePath, cPath): return if doCopy: x = moose.copy(cPath, self.model) self.chemid = moose.element(x) self.chemid.name = 'chem' x = moose.copy(ePath, self.model) self.elecid = moose.element(x) self.elecid.name = 'elec' else: self.elecid = moose.element(ePath) self.chemid = moose.element(cPath) if self.elecid.path != self.model.path + '/elec': if (self.elecid.parent != self.model): moose.move(self.elecid, self.model) self.elecid.name = 'elec' if self.chemid.path != self.model.path + '/chem': if (self.chemid.parent != self.model): moose.move(self.chemid, self.model) self.chemid.name = 'chem' ep = self.elecid.path somaList = moose.wildcardFind(ep + '/#oma#[ISA=CompartmentBase]') if len(somaList) == 0: somaList = moose.wildcardFind(ep + '/#[ISA=CompartmentBase]') assert (len(somaList) > 0) maxdia = 0.0 for i in somaList: if (i.diameter > maxdia): self.soma = i #self.soma = self.comptList[0] self._decorateWithSpines() self.spineList = moose.wildcardFind(ep + '/#spine#[ISA=CompartmentBase],' + ep + '/#head#[ISA=CompartmentBase]') if len(self.spineList) == 0: self.spineList = moose.wildcardFind(ep + '/#head#[ISA=CompartmentBase]') nmdarList = moose.wildcardFind(ep + '/##[ISA=NMDAChan]') self.comptList = moose.wildcardFind(ep + '/#[ISA=CompartmentBase]') print "Rdesigneur: Elec model has ", len( self.comptList ), \ " compartments and ", len( self.spineList ), \ " spines with ", len( nmdarList ), " NMDARs" #moose.le( self.elecid ) self._buildNeuroMesh() self._configureSolvers() for i in self.adaptorList: self._buildAdaptor(i[0], i[1], i[2], i[3], i[4], i[5], i[6]) for i in range(0, 8): moose.setClock(i, self.elecDt) moose.setClock(10, self.diffDt) for i in range(11, 18): moose.setClock(i, self.chemDt) moose.setClock(18, self.chemDt * 5.0) hsolve = moose.HSolve(ep + '/hsolve') hsolve.dt = self.elecDt hsolve.target = self.soma.path
def __init__(self, path): if not moose.exists(path): path_tokens = path.rpartition('/') moose.copy(self.prototype, path_tokens[0], path_tokens[-1]) moose.Neutral.__init__(self, path)
def test_mgblock(): """ Demonstrates the use of MgBlock. Creates an NMDA channel with MgBlock and another without. Connects them up to the compartment on one hand, and to a SynHandler on the other, so as to receive synaptic input. Delivers two pulses to each receptor, with a small delay in between. Plots out the conductance change at each receptor and the reslting membrane potential rise at the compartment. Note that these NMDA channels do NOT separate out the contributions due to calcium and other ions. To do this correctly one should use the GHK object. """ model = moose.Neutral('/model') data = moose.Neutral('/data') soma = moose.Compartment('/model/soma') soma.Em = -60e-3 soma.Rm = 1e7 soma.Cm = 1e-9 ################################################### # This is where we create the synapse with MgBlock #-------------------------------------------------- nmda = moose.SynChan('/model/soma/nmda') nmda.Gbar = 1e-9 mgblock = moose.MgBlock('/model/soma/mgblock') mgblock.CMg = 2.0 mgblock.KMg_A = 1/0.33 mgblock.KMg_B = 1/60.0 # The synHandler manages the synapses and their learning rules if any. synHandler = moose.SimpleSynHandler( '/model/soma/nmda/handler' ) synHandler.synapse.num = 1 moose.connect( synHandler, 'activationOut', nmda, 'activation' ) # MgBlock sits between original channel nmda and the # compartment. The origChannel receives the channel message from # the nmda SynChan. moose.connect(soma, 'VmOut', nmda, 'Vm' ) moose.connect(nmda, 'channelOut', mgblock, 'origChannel') moose.connect(mgblock, 'channel', soma, 'channel') # This is for comparing with MgBlock nmda_noMg = moose.copy(nmda, soma, 'nmda_noMg') moose.connect( nmda_noMg, 'channel', soma, 'channel') moose.le( nmda_noMg ) ######################################### # The rest is for experiment setup spikegen = moose.SpikeGen('/model/spike') pulse = moose.PulseGen('/model/input') pulse.delay[0] = 10e-3 pulse.level[0] = 1.0 pulse.width[0] = 50e-3 moose.connect(pulse, 'output', spikegen, 'Vm') moose.le( synHandler ) #syn = moose.element(synHandler.path + '/synapse' ) syn = synHandler.synapse[0] syn.delay = simdt * 2 syn.weight = 10 moose.connect(spikegen, 'spikeOut', synHandler.synapse[0], 'addSpike') moose.le( nmda_noMg ) noMgSyn = moose.element(nmda_noMg.path + '/handler/synapse' ) noMgSyn.delay = 0.01 noMgSyn.weight = 1 moose.connect(spikegen, 'spikeOut', noMgSyn, 'addSpike') moose.showfields( syn ) moose.showfields( noMgSyn ) Gnmda = moose.Table('/data/Gnmda') moose.connect(Gnmda, 'requestOut', mgblock, 'getGk') Gnmda_noMg = moose.Table('/data/Gnmda_noMg') moose.connect(Gnmda_noMg, 'requestOut', nmda_noMg, 'getGk') Vm = moose.Table('/data/Vm') moose.connect(Vm, 'requestOut', soma, 'getVm') for i in range( 10 ): moose.setClock( i, simdt ) moose.setClock( Gnmda.tick, plotdt ) print((spikegen.dt, Gnmda.dt)) moose.reinit() moose.start( simtime ) t = pylab.linspace(0, simtime*1e3, len(Vm.vector)) pylab.plot(t, (Vm.vector + 0.06) * 1000, label='Vm (mV)') pylab.plot(t, Gnmda.vector * 1e9, label='Gnmda (nS)') pylab.plot(t, Gnmda_noMg.vector * 1e9, label='Gnmda no Mg (nS)') pylab.legend() #data = pylab.vstack((t, Gnmda.vector, Gnmda_noMg.vector)).transpose() #pylab.savetxt('mgblock.dat', data) pylab.show()
def mergeChemModel(A, B): """ Merges two model or the path """ loadedA = False loadedB = False if os.path.isfile(A): modelA, loadedA = loadModels(A) elif moose.exists(A): modelA = A loadedA = True else: print("%s path or file doesnot exists. Mergering will exist" % (A)) exit(0) if os.path.isfile(B): modelB, loadedB = loadModels(B) elif moose.exists(B): modelB = B loadedB = True else: print("%s path or file doesnot exists. Mergering will exist " % (B)) exit(0) if loadedA and loadedB: ## yet deleteSolver is called to make sure all the moose object are off from solver deleteSolver(modelA) deleteSolver(modelB) global poolListina poolListina = {} grpNotcopiedyet = [] dictComptA = dict([ (i.name, i) for i in moose.wildcardFind(modelA + '/##[ISA=ChemCompt]') ]) dictComptB = dict([ (i.name, i) for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]') ]) poolNotcopiedyet = [] for key in list(dictComptA.keys()): if key not in dictComptB: # if compartmentname from modelB does not exist in modelA, then copy copy = moose.copy(dictComptA[key], moose.element(modelB)) else: #if compartmentname from modelB exist in modelA, #volume is not same, then change volume of ModelB same as ModelA if abs(dictComptB[key].volume - dictComptA[key].volume): #hack for now while (abs(dictComptB[key].volume - dictComptA[key].volume) != 0.0): dictComptA[key].volume = float(dictComptB[key].volume) dictComptB = dict([ (i.name, i) for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]') ]) #Mergering pool poolMerge(dictComptB[key], dictComptA[key], poolNotcopiedyet) if grpNotcopiedyet: # objA = moose.element(comptA).parent.name # if not moose.exists(objA+'/'+comptB.name+'/'+bpath.name): # print bpath # moose.copy(bpath,moose.element(objA+'/'+comptB.name)) pass comptBdict = comptList(modelB) poolListinb = {} poolListinb = updatePoolList(comptBdict) R_Duplicated, R_Notcopiedyet, R_Daggling = [], [], [] E_Duplicated, E_Notcopiedyet, E_Daggling = [], [], [] for key in list(dictComptA.keys()): funcExist, funcNotallowed = [], [] funcExist, funcNotallowed = functionMerge(dictComptB, dictComptA, key) poolListinb = updatePoolList(dictComptB) R_Duplicated, R_Notcopiedyet, R_Daggling = reacMerge( dictComptB, dictComptA, key, poolListinb) poolListinb = updatePoolList(dictComptB) E_Duplicated, E_Notcopiedyet, E_Daggling = enzymeMerge( dictComptB, dictComptA, key, poolListinb) print("\n Model is merged to %s" % modelB) if funcExist: print( "\nPool already connected to a function, this function is not to connect to same pool, since no two function are allowed to connect to same pool:" ) for fl in list(funcExist): print("\t [Pool]: %s [Function]: %s \n" % (str(fl.parent.name), str(fl.path))) if funcNotallowed: print( "\nThis function is not to copied, since pool connected to function input are from different compartment:" ) for fl in list(funcNotallowed): print("\t [Pool]: %s [Function]: %s \n" % (str(fl.parent.name), str(fl.path))) if R_Duplicated or E_Duplicated: print( "Reaction / Enzyme are Duplicate" "\n 1. The once whoes substrate / product names are different for a give reaction name " "\n 2. its compartment to which it belongs to may be is different" "\n Models have to decide to keep or delete these reaction/enzyme" ) if E_Duplicated: print("Reaction: ") for rd in list(R_Duplicated): print("%s " % str(rd.name)) if E_Duplicated: print("Enzyme:") for ed in list(E_Duplicated): print("%s " % str(ed.name)) if R_Notcopiedyet or E_Notcopiedyet: print( "\nThese Reaction/Enzyme in model are not dagging but while copying the associated substrate or product is missing" ) if R_Notcopiedyet: print("Reaction: ") for rd in list(R_Notcopiedyet): print("%s " % str(rd.name)) if E_Notcopiedyet: print("Enzyme:") for ed in list(E_Notcopiedyet): print("%s " % str(ed.name)) if R_Daggling or E_Daggling: print( "\n Daggling reaction/enzyme are not not allowed in moose, these are not merged" ) if R_Daggling: print("Reaction: ") for rd in list(R_Daggling): print("%s " % str(rd.name)) if E_Daggling: print("Enzyme:") for ed in list(E_Daggling): print("%s " % str(ed.name))
def test_mgblock(): model = moose.Neutral('/model') data = moose.Neutral('/data') soma = moose.Compartment('/model/soma') soma.Em = -60e-3 soma.Rm = 1e7 soma.Cm = 1e-9 ################################################### # This is where we create the synapse with MgBlock #-------------------------------------------------- nmda = moose.SynChan('/model/soma/nmda') nmda.Gbar = 1e-9 mgblock = moose.MgBlock('/model/soma/mgblock') mgblock.CMg = 2.0 mgblock.KMg_A = 1 / 0.33 mgblock.KMg_B = 1 / 60.0 # The synHandler manages the synapses and their learning rules if any. synHandler = moose.SimpleSynHandler('/model/soma/nmda/handler') synHandler.synapse.num = 1 moose.connect(synHandler, 'activationOut', nmda, 'activation') # MgBlock sits between original channel nmda and the # compartment. The origChannel receives the channel message from # the nmda SynChan. moose.connect(soma, 'VmOut', nmda, 'Vm') moose.connect(nmda, 'channelOut', mgblock, 'origChannel') moose.connect(mgblock, 'channel', soma, 'channel') # This is for comparing with MgBlock nmda_noMg = moose.copy(nmda, soma, 'nmda_noMg') moose.connect(nmda_noMg, 'channel', soma, 'channel') moose.le(nmda_noMg) ######################################### # The rest is for experiment setup spikegen = moose.SpikeGen('/model/spike') pulse = moose.PulseGen('/model/input') pulse.delay[0] = 10e-3 pulse.level[0] = 1.0 pulse.width[0] = 50e-3 moose.connect(pulse, 'output', spikegen, 'Vm') moose.le(synHandler) #syn = moose.element(synHandler.path + '/synapse' ) syn = synHandler.synapse[0] syn.delay = simdt * 2 syn.weight = 10 moose.connect(spikegen, 'spikeOut', synHandler.synapse[0], 'addSpike') moose.le(nmda_noMg) noMgSyn = moose.element(nmda_noMg.path + '/handler/synapse') noMgSyn.delay = 0.01 noMgSyn.weight = 1 moose.connect(spikegen, 'spikeOut', noMgSyn, 'addSpike') moose.showfields(syn) moose.showfields(noMgSyn) Gnmda = moose.Table('/data/Gnmda') moose.connect(Gnmda, 'requestOut', mgblock, 'getGk') Gnmda_noMg = moose.Table('/data/Gnmda_noMg') moose.connect(Gnmda_noMg, 'requestOut', nmda_noMg, 'getGk') Vm = moose.Table('/data/Vm') moose.connect(Vm, 'requestOut', soma, 'getVm') for i in range(10): moose.setClock(i, simdt) moose.setClock(Gnmda.tick, plotdt) print((spikegen.dt, Gnmda.dt)) moose.reinit() moose.start(simtime) t = pylab.linspace(0, simtime * 1e3, len(Vm.vector)) pylab.plot(t, (Vm.vector + 0.06) * 1000, label='Vm (mV)') pylab.plot(t, Gnmda.vector * 1e9, label='Gnmda (nS)') pylab.plot(t, Gnmda_noMg.vector * 1e9, label='Gnmda no Mg (nS)') pylab.legend() #data = pylab.vstack((t, Gnmda.vector, Gnmda_noMg.vector)).transpose() #pylab.savetxt('mgblock.dat', data) pylab.show()
def set_compartment_param(self, compartment, name, value, mechanismname): """ Set the param for the compartment depending on name and mechanismname. """ if name == 'CM': compartment.Cm = value * math.pi * compartment.diameter * compartment.length elif name == 'RM': compartment.Rm = value / (math.pi * compartment.diameter * compartment.length) elif name == 'RA': compartment.Ra = value * compartment.length / ( math.pi * (compartment.diameter / 2.0)**2) elif name == 'Em': compartment.Em = value elif name == 'initVm': compartment.initVm = value elif name == 'inject': # this reader converts to SI _logger.info("Comparment %s inject %s A." % (compartment.name, value)) compartment.inject = value elif name == 'v_reset': compartment.vReset = value # compartment is a moose.LIF instance (intfire) elif name == 'threshold': compartment.thresh = value # compartment is a moose.LIF instance (intfire) elif name == 't_refrac': compartment.refractoryPeriod = value # compartment is a moose.LIF instance (intfire) elif name == 'g_refrac': _logger.info("SORRY, current moose.LIF doesn't support g_refrac.") elif mechanismname == 'synapse': # synapse being added to the compartment ## these are potential locations, we do not actually make synapses, ## unless the user has explicitly asked for it if self.createPotentialSynapses: syn_name = value if not moose.exists(compartment.path + '/' + syn_name): make_new_synapse(syn_name, compartment, syn_name, self.nml_params) ## I assume below that compartment name has _segid at its end segid = compartment.name.split('_')[ -1] # get segment id from compartment name self.segDict[segid][5].append(value) elif mechanismname == 'spikegen': # spikegen being added to the compartment ## these are potential locations, we do not actually make the spikegens. ## spikegens for different synapses can have different thresholds, ## hence include synapse_type in its name ## value contains name of synapse i.e. synapse_type #spikegen = moose.SpikeGen(compartment.path+'/'+value+'_spikegen') #moose.connect(compartment,"VmSrc",spikegen,"Vm") pass ## previous were mechanism that don't need a ChannelML definition ## including integrate_and_fire (I ignore the ChannelML definition) ## thus integrate_and_fire mechanism default values cannot be used ## i.e. nothing needed in /library, but below mechanisms need. elif mechanismname is not None: ## if mechanism is not present in compartment, deep copy from library ## all mechanisms have been loaded into the library earlier if not moose.exists(compartment.path + '/' + mechanismname): neutralObj = moose.element( "/library/" + mechanismname) # gives error if not present if 'CaConc' == neutralObj.className: # Ion concentration pool libcaconc = moose.CaConc("/library/" + mechanismname) ## deep copies the library caconc under the compartment caconc = moose.copy(libcaconc, compartment, mechanismname) caconc = moose.CaConc(caconc) ## CaConc connections are made later using connect_CaConc() ## Later, when calling connect_CaConc, ## B is set for caconc based on thickness of Ca shell and compartment l and dia ## OR based on the Mstring phi under CaConc path. channel = None elif 'HHChannel2D' == neutralObj.className: ## HHChannel2D libchannel = moose.HHChannel2D("/library/" + mechanismname) ## deep copies the library channel under the compartment channel = moose.copy(libchannel, compartment, mechanismname) channel = moose.HHChannel2D(channel) moose.connect(channel, 'channel', compartment, 'channel') elif 'HHChannel' == neutralObj.className: ## HHChannel libchannel = moose.HHChannel("/library/" + mechanismname) ## deep copies the library channel under the compartment channel = moose.copy(libchannel, compartment, mechanismname) channel = moose.HHChannel(channel) moose.connect(channel, 'channel', compartment, 'channel') ## if mechanism is present in compartment, just wrap it else: neutralObj = moose.element(compartment.path + '/' + mechanismname) if 'CaConc' == neutralObj.className: # Ion concentration pool caconc = moose.CaConc( compartment.path + '/' + mechanismname) # wraps existing channel channel = None elif 'HHChannel2D' == neutralObj.className: ## HHChannel2D channel = moose.HHChannel2D( compartment.path + '/' + mechanismname) # wraps existing channel elif 'HHChannel' == neutralObj.className: ## HHChannel channel = moose.HHChannel( compartment.path + '/' + mechanismname) # wraps existing channel if name == 'Gbar': if channel is None: # if CaConc, neuroConstruct uses gbar for thickness or phi ## If child Mstring 'phi' is present, set gbar as phi ## BUT, value has been multiplied by Gfactor as a Gbar, ## SI or physiological not known here, ## ignoring Gbar for CaConc, instead of passing units here child = moose_utils.get_child_Mstring(caconc, 'phi') if child is not None: #child.value = value pass else: #caconc.thick = value pass else: # if ion channel, usual Gbar channel.Gbar = value * math.pi * compartment.diameter * compartment.length elif name == 'Ek': channel.Ek = value elif name == 'thick': # thick seems to be NEURON's extension to NeuroML level 2. caconc.thick = value ## JUST THIS WILL NOT DO - HAVE TO SET B based on this thick! ## Later, when calling connect_CaConc, ## B is set for caconc based on thickness of Ca shell and compartment l and dia. ## OR based on the Mstring phi under CaConc path. if neuroml_utils.neuroml_debug: _logger.info("Setting %s for comparment %s to %s" % (name, compartment.path, value))
def addSpines(model, container,ghkYN,name_soma,module=None): distance_mapped_spineDensity = {(model.SpineParams.spineStart,model.SpineParams.spineEnd):model.SpineParams.spineDensity} headarray=[] # Sets Spine Params to global values for RM, CM, etc. if value is None: setPassiveSpineParams(model,container,name_soma) SpineParams = model.SpineParams suma = 0 modelcond = model.Condset[container] single_spine_surface = spine_surface(SpineParams) parentComp = container+'/'+SpineParams.spineParent print('Adding spines to parent: ' + parentComp) if not moose.exists(parentComp): raise Exception(parentComp + ' Does not exist in Moose model!') compList = [SpineParams.spineParent] getChildren(parentComp,compList) for comp in moose.wildcardFind(container + '/#[TYPE=Compartment]'): dist = (comp.x**2+comp.y**2+comp.z**2)**0.5 if name_soma not in comp.path and comp.name in compList and (SpineParams.spineEnd > dist > SpineParams.spineStart): #determine the number of spines try: #If SpineParams has this, use this density density=SpineParams.explicitSpineDensity except KeyError: #Else, just use the actual density value density=distance_mapping(distance_mapped_spineDensity,comp) numSpines = int(np.round(density*comp.length)) #if spine density is low (less than 1 per comp) use random number to determine whether to add a spine if not numSpines: rand = random.random() if rand > density*comp.length: numSpines = 1 suma += 1 #calculate total surface area of the added spines total_spine_surface = numSpines*single_spine_surface surface_area = comp.diameter*comp.length*np.pi # if SpineParams.compensationSpineDensity: # compensation_spine_surface = int(np.round(SpineParams.compensationSpineDensity*comp.length))*single_spine_surface # decompensate_compensate_for_spines(comp,total_spine_surface,surface_area,compensation_spine_surface) # else: #increase resistance according to the spines that should be there but aren't reverse_compensate_for_explicit_spines(model,comp,total_spine_surface,surface_area) #spineSpace = comp.length/(numSpines+1) #for each spine, make a spine and possibly compensate for its surface area for index in range(numSpines): frac = (index+0.5)/numSpines #print comp.path,"Spine:", index, "located:", frac head,neck = makeSpine(model, comp, 'sp',index, frac, SpineParams) headarray.append(head) if SpineParams.spineChanList: if ghkYN: ghkproto=moose.element('/library/ghk') ghk=moose.copy(ghkproto,comp,'ghk')[0] moose.connect(ghk,'channel',comp,'channel') chan_list = [] for c in SpineParams.spineChanList: chan_list.extend(c) for chanpath,mult in chan_list: cond = mult*distance_mapping(modelcond[chanpath],head) if cond > 0: log.debug('Testing Cond If {} {}', chanpath, cond) calciumPermeable = model.Channels[chanpath].calciumPermeable addOneChan(chanpath,cond,head,ghkYN,calciumPermeable=calciumPermeable,module=module) #end for index #end for comp log.info('{} spines created in {}', len(headarray), container) return headarray
def create_population(container, netparams, name_soma): netpath = container.path proto = [] neurXclass = {} locationlist = [] #determine total number of neurons size, numneurons, vol = count_neurons(netparams) pop_percent = [] for neurtype in netparams.pop_dict.keys(): if moose.exists(neurtype): proto.append(moose.element(neurtype)) neurXclass[neurtype] = [] pop_percent.append(netparams.pop_dict[neurtype].percent) #create cumulative array of probabilities for selecting neuron type choicearray = np.cumsum(pop_percent) if choicearray[-1] < 1.0: log.info("Warning!!!! fractional populations sum to {}", choicearray[-1]) #array of random numbers that will be used to select neuron type rannum = np.random.uniform(0, choicearray[-1], numneurons) #Error check for last element in choicearray equal to 1.0 log.info("numneurons= {} {} choicarray={} rannum={}", size, numneurons, choicearray, rannum) for i, xloc in enumerate( np.linspace(netparams.grid[0]['xyzmin'], netparams.grid[0]['xyzmax'], size[0])): for j, yloc in enumerate( np.linspace(netparams.grid[1]['xyzmin'], netparams.grid[1]['xyzmax'], size[1])): for k, zloc in enumerate( np.linspace(netparams.grid[2]['xyzmin'], netparams.grid[2]['xyzmax'], size[2])): #for each location in grid, assign neuron type, update soma location, add in spike generator neurnumber = i * size[2] * size[1] + j * size[2] + k neurtypenum = np.min( np.where(rannum[neurnumber] < choicearray)) log.debug("i,j,k {} {} {} neurnumber {} type {}", i, j, k, neurnumber, neurtypenum) typename = proto[neurtypenum].name tag = '{}_{}'.format(typename, neurnumber) new_neuron = moose.copy(proto[neurtypenum], netpath, tag) neurXclass[typename].append(container.path + '/' + tag) comp = moose.Compartment(new_neuron.path + '/' + name_soma) comp.x = i * xloc comp.y = j * yloc comp.z = k * zloc log.debug("x,y,z={},{},{} {}", comp.x, comp.y, comp.z, new_neuron.path) locationlist.append([new_neuron.name, comp.x, comp.y, comp.z]) #spike generator - can this be done to the neuron prototype? spikegen = moose.SpikeGen(comp.path + '/spikegen') #should these be parameters in netparams? spikegen.threshold = 0.0 spikegen.refractT = 1e-3 m = moose.connect(comp, 'VmOut', spikegen, 'Vm') #Create variability in neurons of network for neurtype in netparams.chanvar.keys(): for chan, var in netparams.chanvar[neurtype].items(): #single multiplier for Gbar for all the channels compartments if var > 0: log.info('adding variability to {} soma {}, variance: {}', neurtype, chan, var) GbarArray = abs( np.random.normal(1.0, var, len(neurXclass[neurtype]))) for ii, neurname in enumerate(neurXclass[neurtype]): soma_chan_path = neurname + '/' + name_soma + '/' + chan if moose.exists(soma_chan_path): chancomp = moose.element(soma_chan_path) chancomp.Gbar = chancomp.Gbar * GbarArray[ii] # return {'location': locationlist, 'pop': neurXclass}
def mergeChemModel(src, des): """ Merges two model or the path """ A = src B = des sfile = src dfile = des loadedA = False loadedB = False modelA = moose.element('/') modelB = moose.element('/') modelA, loadedA = checkFile_Obj_str(A) modelB, loadedB = checkFile_Obj_str(B) if loadedA and loadedB: ## yet deleteSolver is called to make sure all the moose object are off from solver deleteSolver(modelA) deleteSolver(modelB) global poolListina poolListina = {} grpNotcopiedyet = [] dictComptA = dict([ (i.name, i) for i in moose.wildcardFind(modelA + '/##[ISA=ChemCompt]') ]) dictComptB = dict([ (i.name, i) for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]') ]) poolNotcopiedyet = [] if len(dictComptA): for key in list(dictComptA.keys()): if key not in dictComptB: # if compartment name from modelB does not exist in modelA, then copy copy = moose.copy(dictComptA[key], moose.element(modelB)) dictComptB[key] = moose.element(copy) else: #if compartment name from modelB exist in modelA, #volume is not same, then change volume of ModelB same as ModelA if abs(dictComptB[key].volume - dictComptA[key].volume): #hack for now while (abs(dictComptB[key].volume - dictComptA[key].volume) != 0.0): dictComptA[key].volume = float( dictComptB[key].volume) dictComptB = dict([ (i.name, i) for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]') ]) #Mergering pool poolMerge(dictComptA[key], dictComptB[key], poolNotcopiedyet) comptBdict = comptList(modelB) poolListinb = {} poolListinb = updatePoolList(comptBdict) R_Duplicated, R_Notcopiedyet, R_Daggling = [], [], [] E_Duplicated, E_Notcopiedyet, E_Daggling = [], [], [] for key in list(dictComptA.keys()): funcExist, funcNotallowed = [], [] funcExist, funcNotallowed = functionMerge( dictComptB, dictComptA, key) poolListinb = updatePoolList(dictComptB) R_Duplicated, R_Notcopiedyet, R_Daggling = reacMerge( dictComptA, dictComptB, key, poolListinb) poolListinb = updatePoolList(dictComptB) E_Duplicated, E_Notcopiedyet, E_Daggling = enzymeMerge( dictComptB, dictComptA, key, poolListinb) # if isinstance(src, str): # if os.path.isfile(src) == True: # spath, sfile = os.path.split(src) # else: # sfile = src # else: # sfile = src # if isinstance(des, str): # print " A str",des # if os.path.isfile(des) == True: # dpath, dfile = os.path.split(des) # else: # dfile = des # else: # dfile = des print("\nThe content of %s (src) model is merged to %s (des)." % (sfile, dfile)) # Here any error or warning during Merge is written it down if funcExist: print( "\nIn model \"%s\" pool already has connection from a function, these function from model \"%s\" is not allowed to connect to same pool,\n since no two function are allowed to connect to same pool:" % (dfile, sfile)) for fl in list(funcExist): print("\t [Pool]: %s [Function]: %s \n" % (str(fl.parent.name), str(fl.path))) if funcNotallowed: print( "\nThese functions is not to copied, since pool connected to function input are from different compartment:" ) for fl in list(funcNotallowed): print("\t [Pool]: %s [Function]: %s \n" % (str(fl.parent.name), str(fl.path))) if R_Duplicated or E_Duplicated: print( "These Reaction / Enzyme are \"Duplicated\" into destination file \"%s\", due to " "\n 1. If substrate / product name's are different for a give reaction/Enzyme name " "\n 2. If product belongs to different compartment " "\n Models have to decide to keep or delete these reaction/enzyme in %s" % (dfile, dfile)) if E_Duplicated: print("Reaction: ") for rd in list(R_Duplicated): print("%s " % str(rd.name)) if E_Duplicated: print("Enzyme:") for ed in list(E_Duplicated): print("%s " % str(ed.name)) if R_Notcopiedyet or E_Notcopiedyet: print( "\nThese Reaction/Enzyme in model are not dagging but while copying the associated substrate or product is missing" ) if R_Notcopiedyet: print("Reaction: ") for rd in list(R_Notcopiedyet): print("%s " % str(rd.name)) if E_Notcopiedyet: print("Enzyme:") for ed in list(E_Notcopiedyet): print("%s " % str(ed.name)) if R_Daggling or E_Daggling: print( "\n Daggling reaction/enzyme are not allowed in moose, these are not merged to %s from %s" % (dfile, sfile)) if R_Daggling: print("Reaction: ") for rd in list(R_Daggling): print("%s " % str(rd.name)) if E_Daggling: print("Enzyme:") for ed in list(E_Daggling): print("%s " % str(ed.name)) ## Model is saved print("\n ") print('\nMerged model is available under moose.element(\'%s\')' % (modelB)) print( ' From the python terminal itself \n to save the model in to genesis format use \n >moose.mooseWriteKkit(\'%s\',\'filename.g\')' % (modelB)) print( ' to save into SBML format \n >moose.mooseWriteSBML(\'%s\',\'filename.xml\')' % (modelB)) return modelB # savemodel = raw_input("Do you want to save the model? \"YES\" \"NO\" ") # if savemodel.lower() == 'yes' or savemodel.lower() == 'y': # mergeto = raw_input("Enter File name ") # if mergeto and mergeto.strip(): # filenameto = 'merge.g' # else: # if str(mergeto).rfind('.') != -1: # mergeto = mergeto[:str(mergeto).rfind('.')] # if str(mergeto).rfind('/'): # mergeto = mergeto+'merge' # filenameto = mergeto+'.g' # error,written = moose.mooseWriteKkit(modelB, filenameto) # if written == False: # print('Could not save the Model, check the files') # else: # if error == "": # print(" \n The merged model is saved into \'%s\' " %(filenameto)) # else: # print('Model is saved but these are not written\n %s' %(error)) # else: # print ('\nMerged model is available under moose.element(\'%s\')' %(modelB)) # print (' If you are in python terminal you could save \n >moose.mooseWriteKkit(\'%s\',\'filename.g\')' %(modelB)) # print (' If you are in python terminal you could save \n >moose.mooseWriteSBML(\'%s\',\'filename.g\')' %(modelB)) #return modelB else: print('\nSource file has no objects to copy(\'%s\')' % (modelA)) return moose.element('/')
def reacMerge(comptS, comptD, key, poolListina): RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], [] war_msg = "" comptSpath = moose.element(comptS[key]).path comptDpath = moose.element(comptD[key]).path objS = moose.element(comptSpath).parent.name objD = moose.element(comptDpath).parent.name reacListins = moose.wildcardFind(comptSpath + '/##[ISA=ReacBase]') reacListind = moose.wildcardFind(comptDpath + '/##[ISA=ReacBase]') for rs in reacListins: rSsubname, rSprdname = [], [] rSsubname = subprdList(rs, "sub") rSprdname = subprdList(rs, "prd") allexists, allexistp = False, False allclean = False if rs.name not in [rd.name for rd in reacListind]: # reaction name not found then copy # And assuming that pools are copied earlier EXPECT POOL CPLX # To be assured the it takes correct compartment name incase reaction sub's # belongs to different compt key = findCompartment(rs).name if rSsubname and rSprdname: allexists = checkexist(rSsubname, objS, objD) allexistp = checkexist(rSprdname, objS, objD) if allexists and allexistp: rdpath = rs.parent.path.replace(objS, objD) reac = moose.copy(rs, moose.element(rdpath)) connectObj(reac, rSsubname, "sub", comptD, war_msg) connectObj(reac, rSprdname, "prd", comptD, war_msg) allclean = True else: # didn't find sub or prd for this reaction # -- it may be connected Enzyme cplx RE_Notcopiedyet.append(rs) else: # -- it is dagging reaction RE_Daggling.append(rs) #print ("This reaction \""+rb.path+"\" has no substrate/product daggling reaction are not copied") #war_msg = war_msg+"\nThis reaction \""+rb.path+"\" has no substrate/product daggling reaction are not copied" else: #Same reaction name # -- Same substrate and product including same volume then don't copy # -- different substrate/product or if sub/prd's volume is different then DUPLICATE the reaction allclean = False for rd in reacListind: if rs.name == rd.name: rSsubname = subprdList(rs, "sub") rDsubname = subprdList(rd, "sub") hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol( rSsubname, rDsubname) rSprdname = subprdList(rs, "prd") rDprdname = subprdList(rd, "prd") hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol( rSprdname, rDprdname) if not all((hasSamenoofsublen, hasSameS, hasSamevols, hasSamenoofprdlen, hasSameP, hasSamevolp)): # May be different substrate or product or volume of Sub/prd may be different, # Duplicating the reaction if rSsubname and rSprdname: allexists, allexistp = False, False allexists = checkexist(rSsubname, objS, objD) allexistp = checkexist(rSprdname, objS, objD) if allexists and allexistp: rs.name = rs.name + "_duplicated" #reac = moose.Reac(comptA[key].path+'/'+rb.name+"_duplicated") rdpath = rs.parent.path.replace(objS, objD) reac = moose.copy(rs, moose.element(rdpath)) connectObj(reac, rSsubname, "sub", comptD, war_msg) connectObj(reac, rSprdname, "prd", comptD, war_msg) RE_Duplicated.append(reac) allclean = True else: allclean = False else: allclean = True if not allclean: # didn't find sub or prd for this reaction # -- it may be connected Enzyme cplx if rSsubname and rSprdname: RE_Notcopiedyet.append(rs) else: RE_Daggling.append(rs) return RE_Duplicated, RE_Notcopiedyet, RE_Daggling
def enzymeMerge(comptD, comptS, key, poolListind): war_msg = "" RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], [] comptDpath = moose.element(comptD[key]).path comptSpath = moose.element(comptS[key]).path objD = moose.element(comptDpath).parent.name objS = moose.element(comptSpath).parent.name #nzyListina => enzyListind enzyListind = moose.wildcardFind(comptDpath + '/##[ISA=EnzBase]') enzyListins = moose.wildcardFind(comptSpath + '/##[ISA=EnzBase]') for es in enzyListins: eSsubname, eSprdname = [], [] eSsubname = subprdList(es, "sub") eSprdname = subprdList(es, "prd") allexists, allexistp = False, False allclean = False poolinDlist = poolListind[findCompartment(es).name] for pD in poolinDlist: if es.parent.name == pD.name: edpath = es.parent.path.replace(objS, objD) if not moose.exists(edpath + '/' + es.name): #This will take care # -- If same enzparent name but different enzyme name # -- or different parent/enzyme name if eSsubname and eSprdname: allexists = checkexist(eSsubname, objS, objD) allexistp = checkexist(eSprdname, objS, objD) if allexists and allexistp: enzPool = moose.element(pD.path) edpath = es.parent.path.replace(objS, objD) enz = moose.element( moose.copy(es, moose.element(edpath))) enzPool = enz.parent if es.className in ["ZombieEnz", "Enz"]: moose.connect(moose.element(enz), "enz", enzPool, "reac") if es.className in ["ZombieMMenz", "MMenz"]: moose.connect(enzPool, "nOut", enz, "enzDest") connectObj(enz, eSsubname, "sub", comptD, war_msg) connectObj(enz, eSprdname, "prd", comptD, war_msg) allclean = True else: # didn't find sub or prd for this Enzyme RE_Notcopiedyet.append(es) else: # -- it is dagging reaction RE_Daggling.append(es) else: #Same Enzyme name # -- Same substrate and product including same volume then don't copy # -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme allclean = False ed = moose.element(es.path.replace(objS, objD)) eDsubname = subprdList(ed, "sub") eSsubname = subprdList(es, "sub") hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol( eDsubname, eSsubname) eDprdname = subprdList(ed, "prd") eSprdname = subprdList(es, "prd") hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol( eDprdname, eSprdname) if not all((hasSamenoofsublen, hasSameS, hasSamevols, hasSamenoofprdlen, hasSameP, hasSamevolp)): # May be different substrate or product or volume of Sub/prd may be different, # Duplicating the enzyme if eSsubname and eSprdname: allexists, allexistp = False, False allexists = checkexist(eSsubname, objS, objD) allexistp = checkexist(eSprdname, objS, objD) if allexists and allexistp: es.name = es.name + "_duplicated" if es.className in ["ZombieEnz", "Enz"]: edpath = es.parent.path.replace(objS, objD) enz = moose.copy(es, moose.element(edpath)) moose.connect(enz, 'enz', edpath, 'reac') if es.className in ["ZombieMMenz", "MMenz"]: edpath = es.parent.path.replace(objS, objD) enz = moose.copy(es, moose.element(edpath)) enzinfo = moose.Annotator(enz.path + '/info') moose.connect( moose.element(enz).parent, "nOut", moose.element(enz), "enzDest") #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac") connectObj(enz, eSsubname, "sub", comptD, war_msg) connectObj(enz, eSprdname, "prd", comptD, war_msg) RE_Duplicated.append(enz) allclean = True else: allclean = False else: allclean = True if not allclean: # didn't find sub or prd for this enzyme # -- it may be connected Enzyme cplx if eSsubname and eSprdname: RE_Notcopiedyet.append(es) else: RE_Daggling.append(es) return RE_Duplicated, RE_Notcopiedyet, RE_Daggling
def set_compartment_param(self, compartment, name, value, mechName): """ Set the param for the compartment depending on name and mechName. """ if name == 'CM': compartment.Cm = value * math.pi * compartment.diameter * compartment.length elif name == 'RM': compartment.Rm = value / (math.pi * compartment.diameter * compartment.length) elif name == 'RA': compartment.Ra = value * compartment.length / \ (math.pi*(compartment.diameter/2.0)**2) elif name == 'Em': compartment.Em = value elif name == 'initVm': compartment.initVm = value elif name == 'inject': msg = " {0} inject {1} A.".format(compartment.name, value) debug.printDebug("INFO", msg) compartment.inject = value elif mechName is 'synapse': # synapse being added to the compartment # these are potential locations, we do not actually make synapses. # I assume below that compartment name has _segid at its end # get segment id from compartment name segid = moose_methods.getCompartmentId(compartment.name) self.segDict[segid][5].append(value) # spikegen being added to the compartment elif mechName is 'spikegen': # these are potential locations, we do not actually make the # spikegens. spikegens for different synapses can have different # thresholds, hence include synapse_type in its name value contains # name of synapse i.e. synapse_type #spikegen = moose.SpikeGen(compartment.path+'/'+value+'_spikegen') #moose.connect(compartment,"VmSrc",spikegen,"Vm") pass elif mechName is not None: # if mechanism is not present in compartment, deep copy from library if not moose.exists(compartment.path + '/' + mechName): # if channel does not exist in library load it from xml file if not moose.exists(self.libraryPath + "/" + mechName): cmlR = ChannelML(self.nml_params) model_filename = mechName + '.xml' model_path = neuroml_utils.find_first_file( model_filename, self.model_dir) if model_path is not None: cmlR.readChannelMLFromFile(model_path) else: msg = 'Mechanism {0}: files {1} not found under {2}'\ .format( mechName , model_filename , self.model_dir ) debug.printDebug("ERROR", msg, frame=inspect.currentframe()) sys.exit(0) neutralObj = moose.Neutral(self.libraryPath + "/" + mechName) # Ion concentration pool if 'CaConc' == neutralObj.className: libcaconc = moose.CaConc(self.libraryPath + "/" + mechName) # deep copies the library caconc under the compartment caconc = moose.copy(libcaconc, compartment, mechName) caconc = moose.CaConc(caconc) # CaConc connections are made later using connect_CaConc() # Later, when calling connect_CaConc, B is set for caconc # based on thickness of Ca shell and compartment l and dia # OR based on the Mstring phi under CaConc path. channel = None elif 'HHChannel2D' == neutralObj.className: ## HHChannel2D libchannel = moose.HHChannel2D(self.libraryPath + "/" + mechName) ## deep copies the library channel under the compartment channel = moose.copy(libchannel, compartment, mechName) channel = moose.HHChannel2D(channel) moose.connect(channel, 'channel', compartment, 'channel') elif 'HHChannel' == neutralObj.className: ## HHChannel libchannel = moose.HHChannel(self.libraryPath + "/" + mechName) # deep copies the library channel under the compartment channel = moose.copy(libchannel, compartment, mechName) channel = moose.HHChannel(channel) moose.connect(channel, 'channel', compartment, 'channel') # if mechanism is present in compartment, just wrap it else: neutralObj = moose.Neutral(compartment.path + '/' + mechName) # Ion concentration pool if 'CaConc' == neutralObj.className: # wraps existing channel caconc = moose.CaConc(compartment.path + '/' + mechName) channel = None elif 'HHChannel2D' == neutralObj.className: ## HHChannel2D # wraps existing channel channel = moose.HHChannel2D(compartment.path + '/' + mechName) elif 'HHChannel' == neutralObj.className: ## HHChannel # wraps existing channel channel = moose.HHChannel(compartment.path + '/' + mechName) if name == 'Gbar': # if CaConc, neuroConstruct uses gbar for thickness or phi if channel is None: # If child Mstring 'phi' is present, set gbar as phi BUT, # value has been multiplied by Gfactor as a Gbar, SI or # physiological not known here, ignoring Gbar for CaConc, # instead of passing units here child = moose_utils.get_child_Mstring(caconc, 'phi') if child is not None: #child.value = value pass else: #caconc.thick = value pass else: # if ion channel, usual Gbar channel.Gbar = value * math.pi * compartment.diameter \ * compartment.length elif name == 'Ek': channel.Ek = value # thick seems to be NEURON's extension to NeuroML level 2. elif name == 'thick': # JUST THIS WILL NOT DO - HAVE TO SET B based on this thick! caconc.thick = value # Later, when calling connect_CaConc, B is set for caconc based # on thickness of Ca shell and compartment l and dia. OR based # on the Mstring phi under CaConc path. if neuroml_utils.neuroml_debug: msg = "Setting {0} for {1} value {2}".format( name, compartment.path, value) debug.printDebug("DEBUG", msg, frame=inspect.currentframe())
def copy_syn_channel_moose_paths(moose_chan, chan_name, moose_paths): for moose_path in moose_paths: _chan = moose.copy(moose_chan, moose_path, chan_name, 1) moose.connect(moose.element(moose_path), 'channel', _chan, 'channel') return moose_paths
def insert_hhchannel(compartment, channelclass, gbar): channel = moose.copy(channelclass.prototype, compartment) channel[0].Gbar = gbar moose.connect(channel, 'channel', compartment, 'channel') return channel[0]
def copy_connect_channel_moose_paths(moose_chan, chan_name, moose_paths): for moose_path in moose_paths: _chan = moose.copy(moose_chan, moose_path, chan_name, 1)[0] comp = moose.element(moose_path) _chan = set_channel_conductance(_chan, _chan.Gbar, _chan.Ek, comp) moose.connect(_chan, 'channel', comp, 'channel', 'OneToOne')
container = squid.parent.path # Create the external current to be applied to the compartment squid_pulse = u.createPulse(squid, 'rollingWave', pulse_dur, pulse_amp, pulse_delay1, pulse_delay2) # Create the data tables necessary to run the model data = moose.Neutral('/data') squid_Vm, squid_current = u.createDataTables(squid, data, squid_pulse) # Create the channels necessary for the giant squid axon and place them in a library u.createChanLib('/library', chan_set, rateParams) # Create copies of the prototype channels and connect them to the # compartment nachan = moose.copy('/library/Na', container, 'na', 1) nachan.Gbar = 120e-3 * SA * 1e4 # Gbar_Na = 120 mS/cm^2 moose.connect(nachan, 'channel', squid, 'channel', 'OneToOne') kchan = moose.copy('/library/K', container, 'k', 1) kchan.Gbar = 36e-3 * SA * 1e4 # Gbar_K = 36 mS/cm^2 moose.connect(kchan, 'channel', squid, 'channel', 'OneToOne') # Plot the simulation simtime = 0.1 simdt = 0.25e-5 plotdt = 0.25e-3 for i in range(10): moose.setClock(i, simdt) moose.setClock(8, plotdt) moose.reinit()
def main(simtime): # Simulation information. simtime = simtime simdt = 0.25e-5 plotdt = 0.25e-3 # Cell Compartment infromation diameter = 30e-6 length = 50e-6 Em = EREST_ACT + 10.613e-3 CM = 1e-6 * 1e4 RM = 1 / (0.3E-3 * 1e4) # Channel information. sa, x_sa = compute_comp_area(diameter, length) na_g = 120E-3 * sa * 1E4 na_ek = 115E-3 + EREST_ACT k_g = 36e-3 * sa * 1E4 k_ek = -12E-3 + EREST_ACT # Stimulus information inj_delay = 20E-3 inj_amp = 0.3E-9 inj_width = 40E-3 # Create cell soma = create_compartment('soma', length, diameter, RM, CM, initVM=EREST_ACT, ELEAK=Em) # Create channels K_chan = create_channel(chan_name='K', vdivs=VDIVS, vmin=VMIN, vmax=VMAX, x_params=K_n_params, xpow=4) Na_chan = create_channel(chan_name='Na', vdivs=VDIVS, vmin=VMIN, vmax=VMAX, x_params=Na_m_params, xpow=3, y_params=Na_h_params, ypow=1) # Set conductances nachan = moose.copy(Na_chan, soma.path, 'Na', 1) kchan = moose.copy(K_chan, soma.path, 'K', 1) nachan = set_channel_conductance(nachan, na_g, na_ek) kchan = set_channel_conductance(kchan, k_g, k_ek) # Add channels to soma moose.connect(nachan, 'channel', soma, 'channel', 'OneToOne') moose.connect(kchan, 'channel', soma, 'channel', 'OneToOne') # connect pulse gen pulse_inject = create_pulse_generator(soma, inj_width, inj_amp, delay=inj_delay) # Output table soma_v_table = create_output_table(table_element='/output', table_name='somaVm') soma_i_table = create_output_table(table_element='/output', table_name='somaIm') # Connect output tables moose.connect(soma_v_table, 'requestOut', soma, 'getVm') moose.connect(soma_i_table, 'requestOut', pulse_inject, 'getOutputValue') # Set moose simulation clocks for lable in range(7): moose.setClock(lable, simdt) moose.setClock(8, plotdt) # Run simulation moose.reinit() moose.start(simtime) # Plot output tables. v_plot = plot_vm_table(simtime, soma_v_table, soma_i_table, title="soma voltage") plt.grid(True) plt.legend(['v', 'i']) plt.show()
def copy_connect_channel_moose_paths(moose_chan, chan_name, moose_paths): for moose_path in moose_paths: _chan = moose.copy(moose_chan, moose_path, chan_name, 1) moose.connect(_chan, 'channel', moose.element(moose_path), 'channel', 'OneToOne')
def enzymeMerge(comptA, comptB, key, poolListina): war_msg = "" RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], [] comptApath = moose.element(comptA[key]).path comptBpath = moose.element(comptB[key]).path objA = moose.element(comptApath).parent.name objB = moose.element(comptBpath).parent.name enzyListina = moose.wildcardFind(comptApath + '/##[ISA=EnzBase]') enzyListinb = moose.wildcardFind(comptBpath + '/##[ISA=EnzBase]') for eb in enzyListinb: eBsubname, eBprdname = [], [] eBsubname = subprdList(eb, "sub") eBprdname = subprdList(eb, "prd") allexists, allexistp = False, False allclean = False poolinAlist = poolListina[findCompartment(eb).name] for pA in poolinAlist: if eb.parent.name == pA.name: eapath = eb.parent.path.replace(objB, objA) if not moose.exists(eapath + '/' + eb.name): #This will take care # -- If same enzparent name but different enzyme name # -- or different parent/enzyme name if eBsubname and eBprdname: allexists = checkexist(eBsubname, objB, objA) allexistp = checkexist(eBprdname, objB, objA) if allexists and allexistp: enzPool = moose.element(pA.path) eapath = eb.parent.path.replace(objB, objA) enz = moose.element( moose.copy(eb, moose.element(eapath))) enzPool = enz.parent if eb.className in ["ZombieEnz", "Enz"]: moose.connect(moose.element(enz), "enz", enzPool, "reac") if eb.className in ["ZombieMMenz", "MMenz"]: moose.connect(enzPool, "nOut", enz, "enzDest") connectObj(enz, eBsubname, "sub", comptA, war_msg) connectObj(enz, eBprdname, "prd", comptA, war_msg) allclean = True else: # didn't find sub or prd for this Enzyme RE_Notcopiedyet.append(eb) else: # -- it is dagging reaction RE_Daggling.append(eb) else: #Same Enzyme name # -- Same substrate and product including same volume then don't copy # -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme allclean = False ea = moose.element(eb.path.replace(objB, objA)) eAsubname = subprdList(ea, "sub") eBsubname = subprdList(eb, "sub") hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol( eAsubname, eBsubname) eAprdname = subprdList(ea, "prd") eBprdname = subprdList(eb, "prd") hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol( eAprdname, eBprdname) if not all((hasSamenoofsublen, hasSameS, hasSamevols, hasSamenoofprdlen, hasSameP, hasSamevolp)): # May be different substrate or product or volume of Sub/prd may be different, # Duplicating the enzyme if eBsubname and eBprdname: allexists, allexistp = False, False allexists = checkexist(eBsubname, objB, objA) allexistp = checkexist(eBprdname, objB, objA) if allexists and allexistp: eb.name = eb.name + "_duplicated" if eb.className in ["ZombieEnz", "Enz"]: eapath = eb.parent.path.replace(objB, objA) enz = moose.copy(eb, moose.element(eapath)) moose.connect(enz, 'enz', eapath, 'reac') if eb.className in ["ZombieMMenz", "MMenz"]: eapath = eb.parent.path.replace(objB, objA) enz = moose.copy(eb.name, moose.element(eapath)) enzinfo = moose.Annotator(enz.path + '/info') moose.connect( moose.element(enz).parent, "nOut", moose.element(enz), "enzDest") #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac") connectObj(enz, eBsubname, "sub", comptA, war_msg) connectObj(enz, eBprdname, "prd", comptA, war_msg) RE_Duplicated.append(enz) allclean = True else: allclean = False else: allclean = True if not allclean: # didn't find sub or prd for this enzyme # -- it may be connected Enzyme cplx if eBsubname and eBprdname: RE_Notcopiedyet.append(eb) else: RE_Daggling.append(eb) return RE_Duplicated, RE_Notcopiedyet, RE_Daggling