Example #1
0
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
Example #2
0
    def createRecordingTable(self, element, field):
        """Create table to record `field` from element `element`

        Tables are created under `dataRoot`, the names are generally
        created by removing `/model` in the beginning of `elementPath`
        and replacing `/` with `_`. If this conflicts with an existing
        table, the id value of the target element (elementPath) is
        appended to the name.

        """
        if len(field) == 0 or ((element, field) in self._recordingDict):            
            return
        # The table path is not foolproof - conflict is
        # possible: e.g. /model/test_object and
        # /model/test/object will map to same table. So we
        # check for existing table without element field
        # path in recording dict.
        relativePath = element.path.partition('/model/')[-1]
        if relativePath.startswith('/'):
            relativePath = relativePath[1:]
        tablePath = self.dataRoot.path + '/' + relativePath.replace('/', '_') + '.' + field
        if moose.exists(tablePath):
            tablePath = '%s_%d' % (tablePath, element.id_.value)
        if not moose.exists(tablePath):            
            table = moose.Table(tablePath)
            print 'Created', table.path, 'for plotting', '%s.%s' % (element.path, field)
            target = element
            moose.connect(table, 'requestData', target, 'get_%s' % (field))
            self._recordingDict[(target, field)] = table
            self._reverseDict[table] = (target, field)
def mooseAddChemSolver(modelRoot, solver):
    """
    Add the solvers only if all are Chemical compartment
    """
    compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
    if all(isinstance(x, (moose.CubeMesh,moose.CylMesh)) for x in compts):
        if not compts:
            return ("Atleast one compartment is required ")
        elif ( len(compts) > 3 ):
            return ("Warning: setSolverOnCompt Cannot handle " ,  len(compts) , " chemical compartments\n")

        else:
            comptinfo = moose.Annotator(moose.element(compts[0]).path + '/info')

            previousSolver = stdSolvertype(comptinfo.solver)
            currentSolver = stdSolvertype(solver)

            if previousSolver != currentSolver:
                comptinfo.solver = currentSolver
                if (moose.exists(compts[0].path + '/stoich')):
                    # "A: and stoich exists then delete the stoich add solver"
                    mooseDeleteChemSolver(modelRoot)
                setCompartmentSolver(modelRoot, currentSolver)
                return True
            else:
                if not moose.exists(compts[0].path + '/stoich'):
                    # " stoich exist, doing nothing"
                    setCompartmentSolver(modelRoot, currentSolver)
                    return True
    else:
        
        return ("mooseAddChemSolver is only for adding Chemical Model which has to be `CubeMesh` or `CylMesh` found ",list(set([x.className for x in compts]) - set(['CubeMesh',"CylMesh"])))
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
Example #5
0
    def newModelDialogSlot(self):
        if self.popup is not None:
            self.popup.close()
        newModelDialog = DialogWidget()
        if newModelDialog.exec_():
            modelPath = str(newModelDialog.modelPathEdit.text()).strip()
            if len(modelPath) == 0:
                raise mexception.ElementNameError('Model path cannot be empty')
            if re.search('[ /]',modelPath) is not None:
                raise mexception.ElementNameError('Model path should not containe / or whitespace')
            plugin = str(newModelDialog.getcurrentRadioButton())
            if moose.exists(modelPath+'/model'):
                moose.delete(modelPath)

            modelContainer = moose.Neutral('%s' %(modelPath))
            modelRoot = moose.Neutral('%s/%s' %(modelContainer.path,"model"))
            if not moose.exists(modelRoot.path+'/info'):
                moose.Annotator(modelRoot.path+'/info')
            
            modelAnno = moose.element(modelRoot.path+'/info')
            modelAnno.modeltype = "new_kkit"
            modelAnno.dirpath = " "
            self.loadedModelsAction(modelRoot.path,plugin)
            self.setPlugin(plugin, modelRoot.path)
            self.objectEditSlot('/', False)
Example #6
0
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}
Example #7
0
def checkFile_Obj_str(file_Obj_str):
    model = moose.element('/')
    loaded = False
    found = False
    if isinstance(file_Obj_str, str):
        if os.path.isfile(file_Obj_str) == True:
            model,loaded = loadModels(file_Obj_str)
            found = True
        elif file_Obj_str.find('/') != -1 :
            if not isinstance(file_Obj_str,moose.Neutral):
                if moose.exists(file_Obj_str):
                    model = file_Obj_str
                    loaded = True
                    found = True
        elif isinstance(file_Obj_str, moose.Neutral):
            if moose.exists(file_Obj_str.path):
                model = file_Obj_str.path
                loaded = True
                found = True
    elif isinstance(file_Obj_str, moose.Neutral):
        if moose.exists(file_Obj_str.path):
            model = file_Obj_str.path
            loaded = True
            found = True
    if not found:
        print ("%s path or filename doesnot exist. " % (file_Obj_str))
    return model,loaded
Example #8
0
    def buildModel( self, modelPath ):
        if not moose.exists( '/library' ):
            library = moose.Neutral( '/library' )
        if moose.exists( modelPath ):
            print "rdesigneur::buildModel: Build failed. Model '", \
                modelPath, "' already exists."
            return
        self.model = moose.Neutral( modelPath )
        try:
            self.buildCellProto()
            self.buildChanProto()
            self.buildSpineProto()
            self.buildChemProto()
            # Protos made. Now install the elec and chem protos on model.
            self.installCellFromProtos()
            # Now assign all the distributions
            self.buildPassiveDistrib()
            self.buildChanDistrib()
            self.buildSpineDistrib()
            self.buildChemDistrib()
            self._configureSolvers()
            self.buildAdaptors()
            self._configureClocks()
            self._printModelStats()

        except BuildError, msg:
            print "Error: rdesigneur: model build failed: ", msg
            moose.delete( self.model )
Example #9
0
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)
Example #10
0
def deleteSolver(modelRoot):
	compts = moose.wildcardFind(modelRoot+'/##[ISA=ChemCompt]')
	for compt in compts:
		if moose.exists(compt.path+'/stoich'):
			st = moose.element(compt.path+'/stoich')
			st_ksolve = st.ksolve
			moose.delete(st)
			if moose.exists((st_ksolve).path):
				moose.delete(st_ksolve)
Example #11
0
def deleteSolver(modelRoot):
	if moose.wildcardFind(modelRoot+'/##[ISA=ChemCompt]'):
		compt = moose.wildcardFind(modelRoot+'/##[ISA=ChemCompt]')
		if ( moose.exists( compt[0].path+'/stoich' ) ):
			st = moose.element(compt[0].path+'/stoich')
			if moose.exists((st.ksolve).path):
				moose.delete(st.ksolve)
			moose.delete( compt[0].path+'/stoich' )
	for x in moose.wildcardFind( modelRoot+'/data/graph#/#' ):
                x.tick = -1
Example #12
0
 def dump_cell(self, file_path):
     """Dump the cell information compartment by compartment for
     comparison with NEURON in csv format. All parameters are
     converted to SI units."""
     with open(file_path, 'w') as dump_file:
         fieldnames = ["comp", "len", "dia", "sarea", "xarea", "Em", "Cm","Rm","Ra"]
         for chtype in channel_types:
             if chtype != 'cad':
                 fieldnames += ['e_' + chtype, 'gbar_' + chtype]
             else:
                 fieldnames += ['tau_' + chtype, 'beta_' + chtype]
         # print fieldnames
         writer = csv.DictWriter(dump_file, fieldnames=fieldnames, delimiter=',')
         writer.writeheader()
         comps = moose.wildcardFind('%s/##[TYPE=Compartment]' % (self.path))
         comps = sorted(comps, key=lambda x: int(x.name[0].rpartition('_')[-1]))            
         for comp_e in comps:
             comp = moose.element(comp_e)
             row = {}
             row['comp'] = comp.name
             row['len'] = comp.length
             row['dia'] = comp.diameter
             row['sarea'] = comp.length * comp.diameter * np.pi
             row['xarea'] = comp.diameter * comp.diameter * np.pi/4
             row['Em'] = comp.Em
             row['Cm'] = comp.Cm
             row['Rm'] = comp.Rm
             row['Ra'] = comp.Ra
             if moose.exists(comp.path + '/CaPool'):
                 ca_pool = moose.CaConc(comp.path + '/CaPool')
             for chtype in channel_types:
                 found = False
                 for chname in channel_type_dict[chtype]:
                     chpath = comp.path + '/' + chname
                     if moose.exists(chpath):
                         found = True
                         channel = moose.element(chpath)
                         if channel.className == 'HHChannel':
                             row['e_'+chtype] = channel.Ek
                             row['gbar_'+chtype] = channel.Gbar                        
                         elif channel.className == 'CaConc':
                             row['tau_cad'] = channel.tau
                             row['beta_cad'] = channel.B
                         break
                 if not found:
                     if chtype != 'cad':
                         row['e_'+chtype] = 0.0
                         row['gbar_'+chtype] = 0.0
                     else:
                         row['tau_cad'] = 0.0
                         row['beta_cad'] = 0.0
             writer.writerow(row)
Example #13
0
def getModelAnnotation(obj, baseId, basepath):
    annotationNode = obj.getAnnotation()
    if annotationNode is not None:
        numchild = annotationNode.getNumChildren()
        for child_no in range(0, numchild):
            childNode = annotationNode.getChild(child_no)
            if (childNode.getPrefix() ==
                    "moose" and childNode.getName() == "ModelAnnotation"):
                num_gchildren = childNode.getNumChildren()
                for gchild_no in range(0, num_gchildren):
                    grandChildNode = childNode.getChild(gchild_no)
                    nodeName = grandChildNode.getName()
                    if (grandChildNode.getNumChildren() == 1):
                        baseinfo = moose.Annotator(baseId.path + '/info')
                        baseinfo.modeltype = "xml"
                        if nodeName == "runTime":
                            runtime = float(
                                (grandChildNode.getChild(0).toXMLString()))
                            baseinfo.runtime = runtime
                        if nodeName == "solver":
                            solver = (grandChildNode.getChild(0).toXMLString())
                            baseinfo.solver = solver
                        if(nodeName == "plots"):
                            plotValue = (
                                grandChildNode.getChild(0).toXMLString())
                            p = moose.element(baseId)
                            datapath = moose.element(baseId).path + "/data"
                            if not moose.exists(datapath):
                                datapath = moose.Neutral(baseId.path + "/data")
                                graph = moose.Neutral(
                                    datapath.path + "/graph_0")
                                plotlist = plotValue.split(";")
                                tablelistname = []
                                for plots in plotlist:
                                    plots = plots.replace(" ", "")
                                    plotorg = plots
                                    if( moose.exists(basepath.path + plotorg) and isinstance(moose.element(basepath.path+plotorg),moose.PoolBase)) :
                                        plotSId = moose.element(
                                            basepath.path + plotorg)
                                        # plotorg = convertSpecialChar(plotorg)
                                        plot2 = plots.replace('/', '_')
                                        plot3 = plot2.replace('[', '_')
                                        plotClean = plot3.replace(']', '_')
                                        plotName = plotClean + ".conc"
                                        fullPath = graph.path + '/' + \
                                            plotName.replace(" ", "")
                                        # If table exist with same name then
                                        # its not created
                                        if not fullPath in tablelistname:
                                            tab = moose.Table2(fullPath)
                                            tablelistname.append(fullPath)
                                            moose.connect(tab, "requestOut", plotSId, "getConc")
def moosedeleteChemSolver(modelRoot):
    """Delete solvers from Chemical Compartment

    """
    compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
    for compt in compts:
        if moose.exists(compt.path + '/stoich'):
            st = moose.element(compt.path + '/stoich')
            st_ksolve = st.ksolve
            moose.delete(st)
            if moose.exists((st_ksolve).path):
                moose.delete(st_ksolve)
                print("Solver is deleted for modelpath %s " % modelRoot)
Example #15
0
def addSpineProto(
    name="spine",
    parent="/library",
    RM=1.0,
    RA=1.0,
    CM=0.01,
    shaftLen=1.0e-6,
    shaftDia=0.2e-6,
    headLen=0.5e-6,
    headDia=0.5e-6,
    synList=(),
    chanList=(),
    caTau=0.0,
):
    assert moose.exists(parent), "%s must exist" % parent
    spine = moose.Neutral(parent + "/" + name)
    shaft = buildComptWrapper(spine, "shaft", shaftLen, shaftDia, 0.0, RM, RA, CM)
    head = buildComptWrapper(spine, "head", headLen, headDia, shaftLen, RM, RA, CM)
    moose.connect(shaft, "axial", head, "raxial")

    if caTau > 0.0:
        conc = moose.CaConc(head.path + "/Ca_conc")
        conc.tau = caTau
        conc.length = head.length
        conc.diameter = head.diameter
        conc.thick = 0.0
        # The 'B' field is deprecated.
        # B = 1/(ion_charge * Faraday * volume)
        # vol = head.length * head.diameter * head.diameter * PI / 4.0
        # conc.B = 1.0 / ( 2.0 * FaradayConst * vol )
        conc.Ca_base = 0.0
    for i in synList:
        syn = buildSyn(i[0], head, i[1], i[2], i[3], i[4], CM)
        if i[5] and caTau > 0.0:
            moose.connect(syn, "IkOut", conc, "current")
    for i in chanList:
        if moose.exists(parent + "/" + i[0]):
            chan = moose.copy(parent + "/" + i[0], head)
        else:
            moose.setCwe(head)
            chan = make_LCa()
            chan.name = i[0]
            moose.setCwe("/")
        chan.Gbar = i[1] * head.Cm / CM
        # print "CHAN = ", chan, chan.tick, chan.Gbar
        moose.connect(head, "channel", chan, "channel")
        if i[2] and caTau > 0.0:
            moose.connect(chan, "IkOut", conc, "current")
    transformNMDAR(parent + "/" + name)
    return spine
Example #16
0
 def _buildAdaptor( self, meshName, elecRelPath, elecField, \
         chemRelPath, isElecToChem, offset, scale ):
     mesh = moose.element( '/model/chem/' + meshName )
     elecComptList = mesh.elecComptList
     if len( elecComptList ) == 0:
         raise BuildError( \
             "buildAdaptor: no elec compts in elecComptList on: " + \
             mesh.path )
     startVoxelInCompt = mesh.startVoxelInCompt
     endVoxelInCompt = mesh.endVoxelInCompt
     capField = elecField[0].capitalize() + elecField[1:]
     chemPath = mesh.path + '/' + chemRelPath
     if not( moose.exists( chemPath ) ):
         raise BuildError( \
             "Error: buildAdaptor: no chem obj in " + chemPath )
     chemObj = moose.element( chemPath )
     assert( chemObj.numData >= len( elecComptList ) )
     adName = '/adapt'
     for i in range( 1, len( elecRelPath ) ):
         if ( elecRelPath[-i] == '/' ):
             adName += elecRelPath[1-i]
             break
     ad = moose.Adaptor( chemObj.path + adName, len( elecComptList ) )
     print 'building ', len( elecComptList ), 'adaptors ', adName, \
            ' for: ', mesh.name, elecRelPath, elecField, chemRelPath
     av = ad.vec
     chemVec = moose.element( mesh.path + '/' + chemRelPath ).vec
 
     for i in zip( elecComptList, startVoxelInCompt, endVoxelInCompt, av ):
         i[3].inputOffset = 0.0
         i[3].outputOffset = offset
         i[3].scale = scale
         ePath = i[0].path + '/' + elecRelPath
         if not( moose.exists( ePath ) ):
             raise BuildError( \
                     "Error: buildAdaptor: no elec obj in " + ePath )
         elObj = moose.element( i[0].path + '/' + elecRelPath )
         if ( isElecToChem ):
             elecFieldSrc = 'get' + capField
             #print ePath, elecFieldSrc, scale
             moose.connect( i[3], 'requestOut', elObj, elecFieldSrc )
             for j in range( i[1], i[2] ):
                 moose.connect( i[3], 'output', chemVec[j], 'setConc')
         else:
             elecFieldDest = 'set' + capField
             for j in range( i[1], i[2] ):
                 moose.connect( i[3], 'requestOut', chemVec[j], 'getConc')
             moose.connect( i[3], 'output', elObj, elecFieldDest )
Example #17
0
def make_NMDA():
	if moose.exists( 'NMDA' ):
		return
	NMDA = moose.SynChan( 'NMDA' )
	NMDA.Ek = 0.0
	NMDA.tau1 = 20.0e-3
	NMDA.tau2 = 20.0e-3
	NMDA.Gbar = 5 * SOMA_A

	block = moose.MgBlock( '/library/NMDA/block' )
	block.CMg = 1.2		#	[Mg] in mM
	block.Zk = 2
	block.KMg_A = 1.0/0.28
	block.KMg_B = 1.0/62

	moose.connect( NMDA, 'channelOut', block, 'origChannel', 'OneToOne' )
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. channel	./block	channel'
	#Here we want to also tell the cell reader to _remove_ the original
	#Gk, Ek term going from the channel to the compartment, as this is
	# now handled by the MgBlock.
	#addmsg2 = moose.Mstring( 'NMDA/addmsg2'
	#addmsg2.value = 'DropMsg	..	channel'
	addmsg3 = moose.Mstring( '/library/NMDA/addmsg3' )
	addmsg3.value = '.. VmOut	.	Vm'
Example #18
0
def make_Ca_conc():
	if moose.exists( 'Ca_conc' ):
		return
	conc = moose.CaConc( 'Ca_conc' )
	conc.tau = 0.013333  # sec
	conc.B  = 17.402e12 # Curr to conc conversion for soma
	conc.Ca_base = 0.0
Example #19
0
def make_LCa( name = 'LCa', parent = '/library' ):
        if moose.exists( parent + '/' + name ):
                return
        Ca = moose.HHChannel( parent + '/' + name )
        Ca.Ek = ECA
        Ca.Gbar = 0
        Ca.Gk = 0
        Ca.Xpower = 2
        Ca.Ypower = 1
        Ca.Zpower = 0

        xgate = moose.element( parent + '/' + name + '/gateX' )
        xA = np.array( [ 1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389, -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT), 5.0e-3, 3000, -0.1, 0.05 ] )
        xgate.alphaParms = xA
        ygate = moose.element( parent + '/' + name + '/gateY' )
        ygate.min = -0.1
        ygate.max = 0.05
        ygate.divs = 3000
        yA = np.zeros( (ygate.divs + 1), dtype=float)
        yB = np.zeros( (ygate.divs + 1), dtype=float)


#Fill the Y_A table with alpha values and the Y_B table with (alpha+beta)
        dx = (ygate.max - ygate.min)/ygate.divs
        x = ygate.min
        for i in range( ygate.divs + 1 ):
                if ( x > EREST_ACT):
                        yA[i] = 5.0 * math.exp( -50 * (x - EREST_ACT) )
                else:
                        yA[i] = 5.0
                yB[i] = 5.0
                x += dx
        ygate.tableA = yA
        ygate.tableB = yB
        return Ca
Example #20
0
def main():
    global synSpineList 
    global synDendList 
    numpy.random.seed( 1234 )
    rdes = buildRdesigneur( )
    for i in elecFileNames:
        print(i)
        rdes.cellProtoList = [ ['./cells/' + i, 'elec'] ]
        rdes.buildModel( )
        assert( moose.exists( '/model' ) )
        synSpineList = moose.wildcardFind( "/model/elec/#head#/glu,/model/elec/#head#/NMDA" )
        temp = set( moose.wildcardFind( "/model/elec/#/glu,/model/elec/#/NMDA" ) )

        synDendList = list( temp - set( synSpineList ) )
        moose.reinit()
        buildPlots( rdes )
        # Run for baseline, tetanus, and post-tetanic settling time 
        t1 = time.time()
        probeStimulus( baselineTime )
        tetanicStimulus( tetTime )
        probeStimulus( postTetTime )
        print(('real time = ', time.time() - t1))

        printPsd( i + ".fig5" )
        saveAndClearPlots( i + ".fig5" )
        moose.delete( '/model' )
        rdes.elecid = moose.element( '/' )
Example #21
0
def make_NMDA( name ):
    if moose.exists( '/library/' + name ):
        return
    NMDA = moose.NMDAChan( '/library/' + name )
    NMDA.Ek = 0.0
    NMDA.tau1 = 20.0e-3
    NMDA.tau2 = 20.0e-3
    NMDA.Gbar = 5 * SOMA_A
    NMDA.CMg = 1.2		#	[Mg]ext in mM
    NMDA.KMg_A = 1.0/0.28
    NMDA.KMg_B = 1.0/62
    NMDA.temperature = 300  # Temperature in Kelvin.
    NMDA.extCa = 1.5        # [Ca]ext in mM
    NMDA.intCa = 0.00008        # [Ca]int in mM
    NMDA.intCaScale = 1         # Scale factor from elec Ca units to mM
    NMDA.intCaOffset = 0.00008  # Basal [Ca]int in mM
    NMDA.condFraction = 0.02  # Fraction of conductance due to Ca

    addmsg1 = moose.Mstring( NMDA.path + '/addmsg1' )
    addmsg1.value = '.	ICaOut ../Ca_conc current'
    addmsg2 = moose.Mstring( NMDA.path + '/addmsg2' )
    addmsg2.value = '../Ca_conc	concOut . assignIntCa'

    sh = moose.SimpleSynHandler( NMDA.path + '/sh' )
    moose.connect( sh, 'activationOut', NMDA, 'activation' )
    sh.numSynapses = 1
    sh.synapse[0].weight = 1
    return NMDA
Example #22
0
def make_K_AHP( name ):
    if moose.exists( '/library/' + name ):
        return
    K_AHP = moose.HHChannel( '/library/' + name )
    K_AHP.Ek = EK    #            V
    K_AHP.Gbar = 8 * SOMA_A #    S
    K_AHP.Gk = 0    #    S
    K_AHP.Xpower = 0
    K_AHP.Ypower = 0
    K_AHP.Zpower = 1
    K_AHP.useConcentration = 1

    zgate = moose.element( K_AHP.path + '/gateZ' )
    xmax = 0.02 # 20 micromolar.
    zgate.min = 0
    zgate.max = xmax
    zgate.divs = 3000
    zA = np.zeros( (zgate.divs + 1), dtype=float)
    zB = np.zeros( (zgate.divs + 1), dtype=float)
    dx = (zgate.max - zgate.min)/zgate.divs
    x = zgate.min
    for i in range( zgate.divs + 1 ):
            zA[i] = min( 250.00 * CA_SCALE * x, 10 )
            zB[i] = 1.0 + zA[i]
            x = x + dx

    zgate.tableA = zA
    zgate.tableB = zB
    addmsg1 = moose.Mstring( K_AHP.path + '/addmsg1' )
    addmsg1.value = '../Ca_conc    concOut    . concen'
Example #23
0
def make_Na( name ):
    if moose.exists( '/library/' + name ):
        return
    Na = moose.HHChannel( '/library/' + name )
    Na.Ek = 0.055             #    V
    Na.Gbar = 300 * SOMA_A    #    S
    Na.Gk = 0                 #    S
    Na.Xpower = 2
    Na.Ypower = 1
    Na.Zpower = 0

    xgate = moose.element( Na.path + '/gateX' )
    xA = np.array( [ 320e3 * (0.0131 + EREST_ACT),
        -320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004, 
        -280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, 
        -1.0 * (0.0401 + EREST_ACT), 5.0e-3, 
        3000, -0.1, 0.05 ] )
    xgate.alphaParms = xA

    ygate = moose.element( Na.path + '/gateY' )
    yA = np.array( [ 128.0, 0.0, 0.0, -1.0 * (0.017 + EREST_ACT), 0.018,
        4.0e3, 0.0, 1.0, -1.0 * (0.040 + EREST_ACT), -5.0e-3, 
        3000, -0.1, 0.05 ] )
    ygate.alphaParms = yA
    return Na
Example #24
0
def make_K_A():
	if moose.exists( 'K_A' ):
		return
	K_A = moose.HHChannel( 'K_A' )
	K_A.Ek = EK				#	V
	K_A.Gbar = 50 * SOMA_A	#	S
	K_A.Gk = 0				#	S
	K_A.Xpower = 1
	K_A.Ypower = 1
	K_A.Zpower = 0

	xgate = moose.element( 'K_A/gateX' )
	xA = numpy.array( [ 20e3 * (0.0131 + EREST_ACT), 
		-20e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.01,
		-17.5e3 * (0.0401 + EREST_ACT), 
		17.5e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 0.01,
		3000, -0.1, 0.05 ] )
	xgate.alphaParms = xA
	# xgate.alpha( 20e3 * (0.0131 + EREST_ACT), -20e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.01 )
	# xgate.beta( -17.5e3 * (0.0401 + EREST_ACT), 17.5e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 0.01 )

	ygate = moose.element( 'K_A/gateY' )
	yA = numpy.array( [ 1.6, 0.0, 0.0, 0.013 - EREST_ACT, 0.018,
		50.0, 0.0, 1.0, -1.0 * (0.0101 + EREST_ACT), -0.005,
		3000, -0.1, 0.05 ] )
	ygate.alphaParms = yA
Example #25
0
def make_NMDA_Ca_conc():
	if moose.exists( 'NMDA_Ca_conc' ):
		return
	NMDA_Ca_conc = moose.CaConc( 'NMDA_Ca_conc' )
	NMDA_Ca_conc.tau = 0.004   	# sec. Faster in spine than dend
	NMDA_Ca_conc.B = 17.402e12	# overridden by cellreader.
	NMDA_Ca_conc.Ca_base = 0.0
Example #26
0
def make_K_AHP():
	if moose.exists( 'K_AHP' ):
		return

	K_AHP = moose.HHChannel( 'K_AHP' )
	K_AHP.Ek = EK	#			V
	K_AHP.Gbar = 8 * SOMA_A #	S
	K_AHP.Gk = 0	#	S
	K_AHP.Xpower = 0
	K_AHP.Ypower = 0
	K_AHP.Zpower = 1

	zgate = moose.element( 'K_AHP/gateZ' )
	xmax = 500.0
	zgate.min = 0
	zgate.max = xmax
	zgate.divs = 3000
	zA = numpy.zeros( (zgate.divs + 1), dtype=float)
	zB = numpy.zeros( (zgate.divs + 1), dtype=float)
	dx = (zgate.max - zgate.min)/zgate.divs
	x = zgate.min
	for i in range( zgate.divs + 1 ):
		if (x < (xmax / 2.0 )):
			zA[i] = 0.02*x
		else:
			zA[i] = 10.0
		zB[i] = zA[i] + 1.0
		x = x + dx

	zgate.tableA = zA
	zgate.tableB = zB
	addmsg1 = moose.Mstring( '/library/K_AHP/addmsg1' )
	addmsg1.value = '../Ca_conc	concOut	. concen'
Example #27
0
def syncDataHandler(target):
    """Synchronize data handlers for target.

    Parameters
    ----------
    target : melement/vec/str
        Target element or vec or path string.

    Raises
    ------
    NotImplementedError
        The call to the underlying C++ function does not work.

    Notes
    -----
    This function is defined for completeness, but currently it does not work.

    """
    raise NotImplementedError(
        'The implementation is not working for IntFire - goes to invalid objects. \
First fix that issue with SynBase or something in that line.')
    if isinstance(target, str):
        if not moose.exists(target):
            raise ValueError('%s: element does not exist.' % (target))
        target = vec(target)
        moose.syncDataHandler(target)
    def addSyapseProperties(self, projection,  syn_props, source, target):
        '''Add Synapse properties'''
        synName = syn_props.attrib['synapse_type']
        ## if synapse does not exist in library load it from xml file
        if not moose.exists(os.path.join(self.libraryPath, synName)):
            cmlR = ChannelML.ChannelML(self.nml_params)
            modelFileName = synName+'.xml'
            model_path = nmu.find_first_file(modelFileName
                    , self.modelDir
                    )
            if model_path is not None:
                cmlR.readChannelMLFromFile(model_path)
            else:
                msg = 'For mechanism {0}: files {1} not found under {2}.'.format(
                        synName, modelFileName, self.modelDir
                    )
                raise UserWarning(msg)

        weight = float(syn_props.attrib['weight'])
        threshold = float(syn_props.attrib['threshold']) * self.Efactor
        if 'prop_delay' in syn_props.attrib:
            propDelay = float(syn_props.attrib['prop_delay']) * self.Tfactor
        elif 'internal_delay' in syn_props.attrib:
            propDelay = float(syn_props.attrib['internal_delay']) * self.Tfactor
        else:
            propDelay = 0.0

        options = { 'syn_name' : synName , 'weight' : weight
                   , 'source' : source , 'target' : target
                   , 'threshold' : threshold , 'prop_delay' : propDelay 
                   }
        return options
Example #29
0
    def updateCoords( self ):
        ''' Obtains coords from the associated cell'''
        self.compts_ = moose.wildcardFind( self.neuronId.path + "/#[ISA=CompartmentBase]" )
        # Matplotlib3d isn't able to do full rotations about an y axis,
        # which is what the NeuroMorpho models use, so
        # here we shuffle the axes around. Should be an option.
        #coords = np.array([[[i.x0,i.y0,i.z0],[i.x,i.y,i.z]] 
            #for i in self.compts_])
        coords = np.array([[[i.z0,i.x0,i.y0],[i.z,i.x,i.y]] 
            for i in self.compts_])
        dia = np.array([i.diameter for i in self.compts_])
        if self.relativeObj == '.':
            self.activeCoords = coords
            self.activeDia = dia
            self.activeObjs = self.compts_
        else:
            self.activeObjs = []
            self.activeCoords = []
            self.activeDia = []
            for i,j,k in zip( self.compts_, coords, dia ):
                if moose.exists( i.path + '/' + self.relativeObj ):
                    elm = moose.element( i.path + '/' + self.relativeObj )
                    self.activeObjs.append( elm )
                    self.activeCoords.append( j )
                    self.activeDia.append( k )

        self.activeCoords = np.array( self.activeCoords ) * self.lenScale
        self.coordMax = np.amax( self.activeCoords )
        self.coordMin = np.amin( self.activeCoords )
        self.linewidth = np.array( [ min(self.maxLineWidth, 1 + int(i * self.diaScale )) for i in self.activeDia ] )

        return
Example #30
0
def make_NMDA():
	if moose.exists( 'NMDA' ):
		return
	NMDA = moose.SynChan( 'NMDA' )
	NMDA.Ek = 0.0
	NMDA.tau1 = 20.0e-3
	NMDA.tau2 = 20.0e-3
	NMDA.Gbar = 5 * SOMA_A

	block = moose.MgBlock( '/library/NMDA/block' )
	block.CMg = 1.2		#	[Mg] in mM
	block.Zk = 2
	block.KMg_A = 1.0/0.28
	block.KMg_B = 1.0/62

	moose.connect( NMDA, 'channelOut', block, 'origChannel', 'OneToOne' )
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. channel	./block	channel'
	#Here we want to also tell the cell reader to _remove_ the original
	#Gk, Ek term going from the channel to the compartment, as this is
	# now handled by the MgBlock.
	#addmsg2 = moose.Mstring( 'NMDA/addmsg2'
	#addmsg2.value = 'DropMsg	..	channel'
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. VmOut	./block	Vm'
	addmsg2 = moose.Mstring( '/library/NMDA/addmsg2' )
	addmsg2.value = './block	IkOut ../Ca_conc current'
	addmsg3 = moose.Mstring( '/library/NMDA/addmsg3' )
	addmsg3.value = '.. VmOut	.	Vm'

	sh = moose.SimpleSynHandler( 'NMDA/sh' )
	moose.connect( sh, 'activationOut', NMDA, 'activation' )
	sh.numSynapses = 1
	sh.synapse[0].weight = 1
Example #31
0
def make_Na():
	if moose.exists( 'Na' ):
		return
	Na = moose.HHChannel( 'Na' )
	Na.Ek = ENA				#	V
	Na.Gbar = 300 * SOMA_A	#	S
	Na.Gk = 0				#	S
	Na.Xpower = 2
	Na.Ypower = 1
	Na.Zpower = 0

	xgate = moose.element( 'Na/gateX' )
	xA = numpy.array( [ 320e3 * (0.0131 + EREST_ACT),
		-320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004, 
		-280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, 
		-1.0 * (0.0401 + EREST_ACT), 5.0e-3, 
		3000, -0.1, 0.05 ] )
	xgate.alphaParms = xA


	#xgate.alpha( 320e3 * (0.0131 + EREST_ACT), -320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004 )
	#xgate.beta( -280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 5.0e-3 )

	ygate = moose.element( 'Na/gateY' )
	yA = numpy.array( [ 128.0, 0.0, 0.0, -1.0 * (0.017 + EREST_ACT), 0.018,
		4.0e3, 0.0, 1.0, -1.0 * (0.040 + EREST_ACT), -5.0e-3, 
		3000, -0.1, 0.05 ] )
	ygate.alphaParms = yA
Example #32
0
def run_model():
    model = moose.Neutral('/model')
    data = moose.Neutral('/data')
    cell = TuftedIB('/model/TuftedIB')
    stim = alpha_stimulus('/model/stim', 1.0e-9, 15e-3, 20e-3, simtime, simdt)
    stim.startTime = 1e9
    p1 = cell.path + '/' + d1
    p2 = cell.path + '/' + d2
    comp_d1 = moose.element(p1) if moose.exists(p1) else moose.Compartment(p1)
    comp_d2 = moose.element(p2) if moose.exists(p2) else moose.Compartment(p2)
    s = '%s/%s' % (cell.path, 'comp_1')
    comp_soma = moose.element(s) if moose.exists(s) else moose.Compartment(s)
    comp_soma.inject = -0.2e-9
    moose.connect(stim, 'output', comp_d1, 'injectMsg')
    tab_d1 = moose.Table('%s/d1_Vm' % (data.path))
    tab_d2 = moose.Table('%s/d2_Vm' % (data.path))
    tab_soma = moose.Table('%s/soma_Vm' % (data.path))
    tab_stim = moose.Table('%s/stim' % (data.path))
    moose.connect(tab_d1, 'requestOut', comp_d1, 'getVm')
    moose.connect(tab_d2, 'requestOut', comp_d2, 'getVm')
    moose.connect(tab_soma, 'requestOut', comp_soma, 'getVm')
    moose.connect(stim, 'output', tab_stim, 'input')
    solver = moose.HSolve('%s/solver' % (cell.path))
    solver.dt = simdt
    solver.target = cell.path
    utils.setDefaultDt(elecdt=simdt, plotdt2=plotdt)
    utils.assignDefaultTicks()
    moose.reinit()
    utils.stepRun(simtime, 1e5 * simdt, logger=config.logger)
    pylab.subplot(211)
    pylab.plot(np.linspace(0, simtime, len(tab_d1.vector)),
               tab_d1.vector * 1e3,
               label='D1 Vm (mV)')
    pylab.plot(np.linspace(0, simtime, len(tab_d2.vector)),
               tab_d2.vector * 1e3,
               label='D2 Vm (mV)')
    pylab.plot(np.linspace(0, simtime, len(tab_soma.vector)),
               tab_soma.vector * 1e3,
               label='SOMA Vm (mV)')
    pylab.legend()
    pylab.subplot(212)
    pylab.plot(np.linspace(0, simtime, len(tab_stim.vector)),
               tab_stim.vector * 1e9,
               label='Stimulus (nA)')
    pylab.legend()
    pylab.savefig('fig_a4c.png')
    pylab.show()
Example #33
0
def make_Ca(name):
    if moose.exists('/library/' + name):
        return
    Ca = moose.HHChannel('/library/' + name)
    Ca.Ek = ECA
    Ca.Gbar = 40 * SOMA_A
    Ca.Gk = 0
    Ca.Xpower = 2
    Ca.Ypower = 1
    Ca.Zpower = 0

    xgate = moose.element(Ca.path + '/gateX')
    xA = np.array([
        1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389,
        -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT),
        5.0e-3, 3000, -0.1, 0.05
    ])
    #    xgate.min = -0.1
    #    xgate.max = 0.05
    #    xgate.divs = 3000
    #// Converting Traub's expressions for the gCa/s alpha and beta functions
    #// to SI units and entering the A, B, C, D and F parameters, we get:
    #    xgate.alpha( 1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389 )
    #    xgate.beta( -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT), 5.0e-3 )
    #xgate.setupAlpha( xA )
    xgate.alphaParms = xA

    #  The Y gate (gCa/r) is not quite of this form.  For V > EREST_ACT, alpha =
    #  5*{exp({-50*(V - EREST_ACT)})}.  Otherwise, alpha = 5.  Over the entire
    #  range, alpha + beta = 5.  To create the Y_A and Y_B tables, we use some
    #  of the pieces of the setupalpha function.
    ygate = moose.element(Ca.path + '/gateY')
    ygate.min = -0.1
    ygate.max = 0.05
    ygate.divs = 3000
    yA = np.zeros((ygate.divs + 1), dtype=float)
    yB = np.zeros((ygate.divs + 1), dtype=float)

    #Fill the Y_A table with alpha values and the Y_B table with (alpha+beta)
    dx = (ygate.max - ygate.min) / ygate.divs
    x = ygate.min
    for i in range(ygate.divs + 1):
        if (x > EREST_ACT):
            yA[i] = 5.0 * math.exp(-50 * (x - EREST_ACT))
        else:
            yA[i] = 0.0
        #yB[i] = 6.0 - yA[i]
        yB[i] = 5.0
        x += dx
    ygate.tableA = yA
    ygate.tableB = yB
    # Tell the cell reader that the current from this channel must be fed into
    # the Ca_conc pool of calcium.
    addmsg1 = moose.Mstring(Ca.path + '/addmsg1')
    addmsg1.value = '.    IkOut    ../Ca_conc    current'
    # in some compartments, whe have an NMDA_Ca_conc object to put the current
    # into.
    addmsg2 = moose.Mstring(Ca.path + '/addmsg2')
    addmsg2.value = '.    IkOut    ../NMDA_Ca_conc    current'
Example #34
0
def compensate_for_spines(model, comp,
                          name_soma):  # ,total_spine_surface,surface_area):
    setPassiveSpineParams(model, comp.parent.name, name_soma)
    SpineParams = model.SpineParams
    distance_mapped_spineDensity = {
        (SpineParams.spineStart, SpineParams.spineEnd):
        SpineParams.spineDensity
    }
    if SpineParams.spineDensity == 0:
        return
    if not compensate_for_spines.has_been_called:
        print('Compensating for spines using SpineParams.spineDensity = ' +
              str(SpineParams.spineDensity) +
              ' ; Set to zero skip spine compensation.')
        compensate_for_spines.has_been_called = True
    dist = (comp.x**2 + comp.y**2 + comp.z**2)**0.5
    if name_soma not in comp.path and (SpineParams.spineEnd > dist >
                                       SpineParams.spineStart):
        # determine the number of spines
        spineDensity = distance_mapping(distance_mapped_spineDensity, comp)
        if spineDensity < 0 or spineDensity > 20e6:
            print('SpineDensity {} may be unrealistic; check function'.format(
                spineDensity))
        numSpines = int(np.round(spineDensity * comp.length))
        # print('Spine Density = ' + str(spineDensity), 'NumSpines={}'.format(numSpines))

        # 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 > spineDensity * comp.length:
                numSpines = 1
        # calculate total surface area of the added spines
        single_spine_surface = spine_surface(SpineParams)
        total_spine_surface = numSpines * single_spine_surface
        surface_area = comp.diameter * comp.length * np.pi

        ## Compensate RM and CM
        old_Cm = comp.Cm
        old_Rm = comp.Rm
        scaling_factor = (surface_area + total_spine_surface) / surface_area

        comp.Cm = old_Cm * scaling_factor
        comp.Rm = old_Rm / scaling_factor

        ## Additionally, compensate for ion channels in spines
        # Flatten the nested chan list:
        chan_list = []
        for c in SpineParams.spineChanList:
            chan_list.extend(c)
        # Get the conductance for each channel:
        for chanpath, mult in chan_list:
            if moose.exists(comp.path + '/' + chanpath):
                chan = moose.element(comp.path + '/' + chanpath)
                old_gbar = chan.Gbar / surface_area
                spine_dend_gbar_ratio = 1.0  # TODO: Change if spine has different gbar than dendrite
                gbar_factor = (surface_area + spine_dend_gbar_ratio *
                               total_spine_surface) / surface_area
                new_gbar = old_gbar * gbar_factor
                chan.Gbar = new_gbar * surface_area
Example #35
0
def create_channel(chan_name, vdivs, vmin, vmax, cadivs, camin, camax,
                   x_params, xpow, tick=-1, y_params=None, ypow=0):
    if not moose.exists('/library'):
        moose.Neutral('/library')
    chan_comp = moose.HHChannel('/library/' + chan_name)
    chan_comp.tick = tick
    if ypow:
        chan_comp.Ypower = ypow
        params = y_params + (vdivs, vmin, vmax)
        create_gate(chan_comp, list(params), gate='y')
    if xpow:
        chan_comp.Xpower = xpow
        params = x_params + (vdivs, vmin, vmax)
        create_gate(chan_comp, list(params), gate='x')
    if zpow:

    return chan_comp

def create_gate(chan, gate_params, gate):
    print(gate_params)
    if gate.upper() == 'X':
        moose.element(chan.path + '/gateX').setupAlpha(gate_params)
    elif gate.upper() == 'Y':
        moose.element(chan.path+ '/gateY').setupAlpha(gate_params)

def set_channel_conductance(chan, gbar, E_nerst):
    chan.Gbar = gbar
    chan.Ek = E_nerst
    return chan

def create_set_of_channels(channel_settings, vdivs, vmin, vmax, cadivs, camin, camax):
    chan_set = {}
    for settings in channel_settings:
        chan = create_channel(chan_name=settings.get('chan_name'),
                              vdivs=vdivs, vmin=vmin, vmax=vmax,
                              x_params=settings.get('x_params'), xpow=settings.get('x_pow'),
                              y_params=settings.get('y_params'), ypow=settings.get('y_pow'))
        set_channel_conductance(chan, gbar=settings.get('g_max'), E_nerst=settings.get('e_k'))
    return chan_set

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 create_swc_model(root_name, file_name, RM, CM, RA, ELEAK, initVM):
 if file_name.endswith('.swc'):
     root_comp = moose.loadModel(file_name, root_name)
 else:
     raise ValueError("Please provide valid swc file as input.")

 for comp in moose.wildcardFind(root_comp.path+'/#[TYPE=Compartment]'):
     set_comp_values(comp, RM, CM, RA, initVM, ELEAK)
 return root_comp

def create_p_model(root_name, file_name):
    if file_name.endswith('.p'):
        root_comp = moose.loadModel(file_name, root_name)
        return root_comp
Example #36
0
def main():
    filename = os.path.join( os.path.split(os.path.realpath(__file__))[0]
                           , "../neuroml/CA1/CA1.morph.pop.xml")


    # filename = os.path.join( os.path.split(os.path.realpath(__file__))[0]
    #                        , "../neuroml/PurkinjeCellPassivePulseInput/PurkinjePassive.net.xml")
    # filename = os.path.join( os.path.split(os.path.realpath(__file__))[0]
    #                        , "../neuroml/OlfactoryBulbPassive/OBpassive_numgloms3_seed750.0.xml")

    popdict, projdict = moose.neuroml.loadNeuroML_L123(filename)
    modelRoot   = moose.Neutral("/" + os.path.splitext(os.path.basename(filename))[0])
    element = moose.Neutral(modelRoot.path + "/model")
    if(moose.exists("/cells"))  : moose.move("/cells"  , element.path)
    if(moose.exists("/elec"))   : moose.move("/elec"   , modelRoot.path)
    if(moose.exists("/library")): moose.move("/library", modelRoot.path)
    show_morphology(modelRoot.path)
Example #37
0
    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
Example #38
0
def addSpineProto( name = 'spine', \
        RM = 1.0, RA = 1.0, CM = 0.01, \
        shaftLen = 1.e-6 , shaftDia = 0.2e-6, \
        headLen = 0.5e-6, headDia = 0.5e-6, \
        synList = ( ['glu', 0.0, 2e-3, 9e-3, 200.0, False],
                    ['NMDA', 0.0, 20e-3, 20e-3, 80.0, True] ),
        chanList = ( ['Ca', 1.0, True ], ),
        caTau = 13.333e-3
        ):
    if not moose.exists( '/library' ):
        library = moose.Neutral( '/library' )
    spine = moose.Neutral( '/library/spine' )
    shaft = buildCompt( spine, 'shaft', shaftLen, shaftDia, 0.0, RM, RA, CM )
    head = buildCompt( spine, 'head', headLen, headDia, shaftLen, RM, RA, CM )
    moose.connect( shaft, 'axial', head, 'raxial' )

    if caTau > 0.0:
        conc = moose.CaConc( head.path + '/Ca_conc' )
        conc.tau = caTau
        conc.length = head.length
        conc.diameter = head.diameter
        conc.thick = 0.0
        # The 'B' field is deprecated.
        # B = 1/(ion_charge * Faraday * volume)
        #vol = head.length * head.diameter * head.diameter * PI / 4.0
        #conc.B = 1.0 / ( 2.0 * FaradayConst * vol )
        conc.Ca_base = 0.0
    for i in synList:
        syn = buildSyn( i[0], head, i[1], i[2], i[3], i[4], CM )
        if i[5] and caTau > 0.0:
            moose.connect( syn, 'IkOut', conc, 'current' )
    for i in chanList:
        if ( moose.exists( '/library/' + i[0] ) ):
            chan = moose.copy( '/library/' + i[0], head )
        else:
            moose.setCwe( head )
            chan = make_LCa()
            chan.name = i[0]
            moose.setCwe( '/' )
        chan.Gbar = i[1] * head.Cm / CM
        print "CHAN = ", chan, chan.tick, chan.Gbar
        moose.connect( head, 'channel', chan, 'channel' )
        if i[2] and caTau > 0.0:
            moose.connect( chan, 'IkOut', conc, 'current' )
    transformNMDAR( '/library/spine' )
    return spine
Example #39
0
def chanlib(model,module=None):
    if not moose.exists('/library'):
        lib = moose.Neutral('/library')
    else:
        lib=moose.element('/library')

    if module is not None and not moose.exists('/library/'+module):
        lib=moose.Neutral('/library/'+module)
        print('new chan library for',module, lib.path)
    #Adding all the channels to the library.
    
    chan = [make_channel(model, lib.path + '/'+key, value) for key, value in model.Channels.items()]
    if model.ghkYN:
        ghk = moose.GHK('/library/ghk')
        ghk.T = model.Temp
        ghk.Cout = model.ConcOut
        ghk.valency=2
Example #40
0
 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
Example #41
0
def make_glu():
    if moose.exists('glu'):
        return
    glu = moose.SynChan('glu')
    glu.Ek = 0.0
    glu.tau1 = 2.0e-3
    glu.tau2 = 9.0e-3
    glu.Gbar = 40 * SOMA_A
Example #42
0
def make_Ca_conc( name ):
    if moose.exists( '/library/' + name ):
        return
    conc = moose.CaConc( '/library/tempName' )
    conc.name = name
    conc.tau = 0.013333  # sec
    conc.B  = 17.402e12 # Curr to conc conversion for soma
    conc.Ca_base = 0.00000
Example #43
0
def writeEnz(modelpath, f):
    enzList = wildcardFind(modelpath + '/##[ISA=EnzBase]')
    for enz in enzList:
        x = random.randrange(0, 10)
        y = random.randrange(0, 10)
        textcolor = "green"
        color = "red"
        k1 = 0
        k2 = 0
        k3 = 0
        nInit = 0
        concInit = 0
        n = 0
        conc = 0
        enzParent = enz.parent
        if (isinstance(enzParent.className, Pool)) or (isinstance(
                enzParent.className, ZombiePool)):
            print(" raise exception enz doesn't have pool as parent")
            return False
        else:
            vol = enzParent.volume * NA * 1e-3
            isMichaelisMenten = 0
            enzClass = enz.className
            if (enzClass == "ZombieMMenz" or enzClass == "MMenz"):
                k1 = enz.numKm
                k3 = enz.kcat
                k2 = 4.0 * k3
                k1 = (k2 + k3) / k1
                isMichaelisMenten = 1

            elif (enzClass == "ZombieEnz" or enzClass == "Enz"):
                k1 = enz.k1
                k2 = enz.k2
                k3 = enz.k3
                cplx = enz.neighbors['cplx'][0]
                nInit = cplx.nInit[0]

            xe = cord[enz]['x']
            ye = cord[enz]['y']
            x = ((xe - xmin) / (xmax - xmin)) * multi
            y = ((ye - ymin) / (ymax - ymin)) * multi
            #y = ((ymax-ye)/(ymax-ymin))*multi
            einfo = enz.path + '/info'
            if exists(einfo):
                color = Annotator(einfo).getField('color')
                color = getColorCheck(color, GENESIS_COLOR_SEQUENCE)

                textcolor = Annotator(einfo).getField('textColor')
                textcolor = getColorCheck(textcolor, GENESIS_COLOR_SEQUENCE)

            f.write("simundump kenz /kinetics/" + trimPath(enz) + " " +
                    str(0) + " " + str(concInit) + " " + str(conc) + " " +
                    str(nInit) + " " + str(n) + " " + str(vol) + " " +
                    str(k1) + " " + str(k2) + " " + str(k3) + " " + str(0) +
                    " " + str(isMichaelisMenten) + " " + "\"\"" + " " +
                    str(color) + " " + str(textcolor) + " \"\"" + " " +
                    str(int(x)) + " " + str(int(y)) + " " + str(0) + "\n")
    return enzList
Example #44
0
def loadGenCsp(target, filename, solver="gsl"):
    target = target.replace(" ", "")
    path = '/' + target
    #Moving the model under /modelname/model and graphs under /model/graphs.
    #This is passed while loading-time which will be easy for setting the stoich path
    mpath = '/' + target + '/' + "model"
    if moose.exists(mpath):
        moose.delete(mpath)
    modelpath1 = moose.Neutral('%s' % (target))
    modelpath = moose.Neutral('%s/%s' % (modelpath1.path, "model"))
    model = moose.loadModel(filename, modelpath.path, solver)

    if not moose.exists(modelpath1.path + '/data'):
        graphspath = moose.Neutral('%s/%s' % (modelpath1.path, "data"))
    dataPath = moose.element(modelpath1.path + '/data')
    i = 0
    nGraphs = moose.wildcardFind(modelpath.path + '/graphs/##[TYPE=Table2]')
    for graphs in nGraphs:
        if not moose.exists(dataPath.path + '/graph_' + str(i)):
            graphspath = moose.Neutral('%s/%s' %
                                       (dataPath.path, "graph_" + str(i)))
        else:
            graphspath = moose.element(dataPath.path + '/graph_' + str(i))
        moose.move(graphs.path, graphspath)

    if len(nGraphs) > 0:
        i = i + 1

    for moregraphs in moose.wildcardFind(modelpath.path +
                                         '/moregraphs/##[TYPE=Table2]'):
        if not moose.exists(dataPath.path + '/graph_' + str(i)):
            graphspath = moose.Neutral('%s/%s' %
                                       (dataPath.path, "graph_" + str(i)))
        else:
            graphspath = moose.element(dataPath.path + '/graph_' + str(i))
        moose.move(moregraphs.path, graphspath)
    if moose.exists(modelpath.path + '/info'):
        AnnotatorOld = moose.element(modelpath.path + '/info')
        AnnotatorNew = moose.Annotator(modelpath1.path + '/info')
        AnnotatorNew.runtime = AnnotatorOld.runtime
        AnnotatorNew.solver = AnnotatorOld.solver
        moose.delete(AnnotatorOld)
    moose.delete(modelpath.path + '/graphs')
    moose.delete(modelpath.path + '/moregraphs')
    return (modelpath1, modelpath1.path)
Example #45
0
    def _buildAdaptor( self, meshName, elecRelPath, elecField, \
            chemRelPath, isElecToChem, offset, scale ):
        mesh = moose.element('/model/chem/' + meshName)
        elecComptList = mesh.elecComptList
        startVoxelInCompt = mesh.startVoxelInCompt
        endVoxelInCompt = mesh.endVoxelInCompt
        capField = elecField[0].capitalize() + elecField[1:]
        chemPath = mesh.path + '/' + chemRelPath
        if not (moose.exists(chemPath)):
            print "Error: buildAdaptor: no chem obj in ", chemPath
            return
        chemObj = moose.element(chemPath)
        assert (chemObj.numData >= len(elecComptList))
        adName = '/adapt'
        for i in range(1, len(elecRelPath)):
            if (elecRelPath[-i] == '/'):
                adName += elecRelPath[1 - i]
                break
        ad = moose.Adaptor(chemObj.path + adName, len(elecComptList))
        av = ad.vec
        # print 'building ', len( elecComptList ), 'adaptors ', adName, \
        #        ' for: ', mesh.name, elecRelPath, elecField, chemRelPath
        chemVec = moose.element(mesh.path + '/' + chemRelPath).vec

        for i in zip(elecComptList, startVoxelInCompt, endVoxelInCompt, av):
            i[3].inputOffset = 0.0
            i[3].outputOffset = offset
            i[3].scale = scale
            ePath = i[0].path + '/' + elecRelPath
            if not (moose.exists(ePath)):
                print "Error: buildAdaptor: no elec obj in ", ePath
                #moose.le( '/model[0]/elec[0]/Seg0_spine0_2001445' )
                return
            elObj = moose.element(i[0].path + '/' + elecRelPath)
            if (isElecToChem):
                elecFieldSrc = 'get' + capField
                print ePath, elecFieldSrc, scale
                moose.connect(i[3], 'requestOut', elObj, elecFieldSrc)
                for j in range(i[1], i[2]):
                    moose.connect(i[3], 'output', chemVec[j], 'setConc')
            else:
                elecFieldDest = 'set' + capField
                for j in range(i[1], i[2]):
                    moose.connect(i[3], 'requestOut', chemVec[j], 'getConc')
                moose.connect(i[3], 'output', elObj, elecFieldDest)
Example #46
0
def addSpineProto( name = 'spine',
        parent = '/library',
        RM = 1.0, RA = 1.0, CM = 0.01,
        shaftLen = 1.e-6 , shaftDia = 0.2e-6,
        headLen = 0.5e-6, headDia = 0.5e-6,
        synList = (),
        chanList = (),
        caTau = 0.0
        ):
    assert( moose.exists( parent ) ), "%s must exist" % parent
    spine = moose.Neutral( parent + '/' + name )
    shaft = buildComptWrapper( spine, 'shaft', shaftLen, shaftDia, 0.0, RM, RA, CM )
    head = buildComptWrapper( spine, 'head', headLen, headDia, shaftLen, RM, RA, CM )
    moose.connect( shaft, 'axial', head, 'raxial' )

    if caTau > 0.0:
        conc = moose.CaConc( head.path + '/Ca_conc' )
        conc.tau = caTau
        conc.length = head.length
        conc.diameter = head.diameter
        conc.thick = 0.0
        # The 'B' field is deprecated.
        # B = 1/(ion_charge * Faraday * volume)
        #vol = head.length * head.diameter * head.diameter * PI / 4.0
        #conc.B = 1.0 / ( 2.0 * FaradayConst * vol )
        conc.Ca_base = 0.0
    for i in synList:
        syn = buildSyn( i[0], head, i[1], i[2], i[3], i[4], CM )
        if i[5] and caTau > 0.0:
            moose.connect( syn, 'IkOut', conc, 'current' )
    for i in chanList:
        if ( moose.exists( parent + '/' + i[0] ) ):
            chan = moose.copy( parent + '/' + i[0], head )
        else:
            moose.setCwe( head )
            chan = make_LCa()
            chan.name = i[0]
            moose.setCwe( '/' )
        chan.Gbar = i[1] * head.Cm / CM
        #print "CHAN = ", chan, chan.tick, chan.Gbar
        moose.connect( head, 'channel', chan, 'channel' )
        if i[2] and caTau > 0.0:
            moose.connect( chan, 'IkOut', conc, 'current' )
    transformNMDAR( parent + '/' + name )
    return spine
Example #47
0
def reload_moose():
    import moose
    print('reloading moose')
    for p in ['/model', '/library']:
        if moose.exists(p):
            moose.delete(p)
    # If someone has changed the clock-ticks then we need to reset them.
    # And relaod just to make sure and other values are initialized.
    reload(moose)
Example #48
0
def chanlib2(chan_set):
    if not moose.exists('/library'):
        #only create ‘/library’ if it has not been created already
        lib = moose.Neutral('/library')
    for params in chan_set:
        if params.name == 'BKCa':
            chan = BKchan_proto(params)
        else:
            chan = chan_proto(params)
Example #49
0
def add_table( moose_elem, field, tableName = None):
    global tables_
    tablePath = '%s/tab%s' % (moose_elem.path, field)
    if moose.exists( tablePath ):
        return None
    t = moose.Table2( tablePath )
    moose.connect( t, 'requestOut', moose_elem, 'get'+field[0].upper()+field[1:])
    tables_[ moose_elem.name ].append( t )
    _logger.debug( 'Added table on %s' % moose_elem.path )
Example #50
0
def create_channel(ntype, chan_name, vdivs, vmin, vmax, cadivs, camin, camax,
                   x_params, xpow, tick=-1, y_params=None, ypow=0, zpow=0, z_params=None):
    lib =  moose.Neutral('/library') if not moose.exists('/library') else moose.element('/library')
    typelib = moose.Neutral(lib.path+'/'+ntype) if not moose.exists(lib.path+'/'+ntype) else moose.element(lib.path+'/'+ntype)
    chan_comp = moose.HHChannel(typelib.path + '/' + chan_name)
    chan_comp.tick = tick
    if xpow: # GateX
        chan_comp.Xpower = xpow
        params = x_params + (vdivs, vmin, vmax)
        moose.element(chan_comp.path + '/gateX').setupAlpha(list(params))
    if ypow: # GateY
        chan_comp.Ypower = ypow
        params = y_params + (vdivs, vmin, vmax)
        moose.element(chan_comp.path + '/gateY').setupAlpha(list(params))
    if zpow: # GateZ
        chan_comp.Zpower = zpow
        create_conc_dependent_z_gate(chan_comp, z_params, cadivs, camin, camax)
    return chan_comp
Example #51
0
def CaProto(model):
    if not model.calYN:
        return

    capar = model.CaPlasticityParams.CalciumParams

    if not moose.exists('/library'):
        lib = moose.Neutral('/library')

    if not moose.exists('/library/' + capar.CaName):
        concproto = moose.CaConc('/library/' + capar.CaName)
        concproto.tau = capar.tau
        concproto.CaBasal = capar.Ceq
        concproto.ceiling = 1.
        concproto.floor = 0.0
        concproto.tick = -1

    return moose.element('/library/' + capar.CaName)
Example #52
0
 def createPassiveChannel(self, chan):
     epath = '%s/%s' % (self.lib.path, chan.id)
     if moose.exists(epath):
         mchan = moose.element(epath)
     else:
         mchan = moose.Leakage(epath)
     logger_.info('%s: Created %s for %s' %
                  (self.filename, mchan.path, chan.id))
     return mchan
Example #53
0
def test_msgs():
    if moose.exists('/model'):
        moose.delete('/model')
    rdes = rd.rdesigneur(
        stimList=[['soma', '1', '.', 'inject', '(t>0.1 && t<0.2) * 2e-8']],
        plotList=[['soma', '1', '.', 'Vm', 'Soma membrane potential']])
    rdes.buildModel()
    msgs = moose.listmsg(rdes.soma)
    assert len(msgs) == 3, msgs
Example #54
0
def main():
    numpy.random.seed( 1234 )
    rdes = buildRdesigneur()
    rdes.buildModel( '/model' )
    assert( moose.exists( '/model' ) )
    moose.element( '/model/elec/hsolve' ).tick = -1
    for i in range( 0, 10 ):
        moose.setClock( i, 100 )
    for i in range( 10, 18 ):
        moose.setClock( i, dt )
    moose.setClock( 18, plotdt )
    moose.reinit()
    buildPlots()
    # Run for baseline, tetanus, and post-tetanic settling time 
    print('starting...')
    t1 = time.time()
    moose.start( baselineTime )
    caPsd = moose.vec( '/model/chem/psd/Ca_input' )
    caDend = moose.vec( '/model/chem/dend/DEND/Ca_input' )
    castim = (numpy.random.rand( len( caPsd.concInit ) ) * 0.8 + 0.2) * psdTetCa
    caPsd.concInit = castim
    caDend.concInit = numpy.random.rand( len( caDend.concInit ) ) * dendTetCa
    moose.start( tetTime )
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start( interTetTime )
    caPsd.concInit = castim
    caDend.concInit = numpy.random.rand( len( caDend.concInit ) ) * dendTetCa
    moose.start( tetTime )
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start( postTetTime )
    caPsd.concInit = ltdCa
    caDend.concInit = ltdCa
    moose.start( ltdTime )
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start( postLtdTime )
    print(('real time = ', time.time() - t1))

    if do3D:
        app = QtGui.QApplication(sys.argv)
        compts = moose.wildcardFind( "/model/elec/#[ISA=compartmentBase]" )
        ecomptPath = [x.path for x in compts]
        morphology = moogli.read_morphology_from_moose(name = "", path = "/model/elec")
        morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
            [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 0.9] )
        viewer = moogli.DynamicMorphologyViewerWidget(morphology)
        def callback( morphology, viewer ):
            moose.start( 0.1 )
            return True
        viewer.set_callback( callback, idletime = 0 )
        viewer.showMaximized()
        viewer.show()
        app.exec_()

    displayPlots()
Example #55
0
def functionMerge(comptA, comptB, key):
    funcNotallowed = []
    comptApath = moose.element(comptA[key]).path
    comptBpath = moose.element(comptB[key]).path
    funcListina = moose.wildcardFind(comptApath + '/##[ISA=PoolBase]')
    funcListinb = moose.wildcardFind(comptBpath + '/##[ISA=Function]')
    objA = moose.element(comptApath).parent.name
    objB = moose.element(comptBpath).parent.name
    #For function mergering pool name is taken as reference
    funcNotcopiedyet = []
    for fb in funcListinb:

        if fb.parent.className in [
                'ZombiePool', 'Pool', 'ZombieBufPool', 'BufPool'
        ]:
            objA = moose.element(comptApath).parent.name
            fbpath = fb.path
            #funcpath = fbpath[fbpath.find(findCompartment(fb).name)-1:len(fbpath)]
            funcparentB = fb.parent.path
            funcpath = fbpath.replace(objB, objA)
            funcparentA = funcparentB.replace(objB, objA)
            tt = moose.element(funcparentA).neighbors['setN']
            if tt:
                funcNotallowed.append(fb)
            else:
                if len(moose.element(fb.path + '/x').neighbors["input"]):
                    #inputB = moose.element(fb.path+'/x').neighbors["input"]
                    inputB = subprdList(moose.element(fb.path + '/x'), "input")
                    inputB_expr = fb.expr
                    if moose.exists(funcpath):
                        #inputA = moose.element(objA+funcpath+'/x').neighbors["input"]
                        inputA = subprdList(moose.element(funcpath + '/x'),
                                            "input")
                        inputA_expr = moose.element(funcpath).expr
                        hassameExpr = False
                        if inputA_expr == inputB_expr:
                            hassameExpr = True
                        hassameLen, hassameS, hassameVols = same_len_name_vol(
                            inputA, inputB)
                        if not all(
                            (hassameLen, hassameS, hassameVols, hassameExpr)):
                            fb.name = fb.name + '_duplicatedF'
                            createFunction(fb, inputB, objB, objA)
                    else:
                        #function doesnot exist then copy
                        if len(inputB):
                            volinput = []
                            for inb in inputB:
                                volinput.append(
                                    findCompartment(moose.element(inb)).volume)
                                if len(set(volinput)) == 1:
                                    # If all the input connected belongs to one compartment then copy
                                    createFunction(fb, inputB, objB, objA)
                                else:
                                    # moose doesn't allow function input to come from different compartment
                                    funcNotallowed.append(fb)
    return funcNotallowed
 def __init__(self, name, field = 'modulation', initVal = 0.0, suffix = "Modulation", scale = 1.0, valmax = 10.0 ):
     self.name = name
     self.path = '/model/elec/soma/' + name
     self.field = field
     assert( moose.exists( self.path ) )
     self.val = initVal
     self.suffix = suffix
     self.scale = scale
     self.valmax = valmax
Example #57
0
def graphtables(model, neuron,pltcurr,curmsg, plas=[],compartments='all'):
    print("GRAPH TABLES, of ", neuron.keys(), "plas=",len(plas),"curr=",pltcurr)
    #tables for Vm and calcium in each compartment
    vmtab={}
    catab={key:[] for key in neuron.keys()}
    currtab={}

    # Make sure /data exists
    if not moose.exists(DATA_NAME):
        moose.Neutral(DATA_NAME)

    for typenum,neur_type in enumerate(neuron.keys()):
        if type(compartments)==str and compartments in {'all', '*'}:
                neur_comps = moose.wildcardFind(neur_type + '/#[TYPE=Compartment]')
        else:
            neur_comps=[moose.element(neur_type+'/'+comp) for comp in compartments]
        vmtab[neur_type] = [moose.Table(vm_table_path(neur_type, comp=ii)) for ii in range(len(neur_comps))]

        for ii,comp in enumerate(neur_comps):
            moose.connect(vmtab[neur_type][ii], 'requestOut', comp, 'getVm')

        if model.calYN:
            for ii,comp in enumerate(neur_comps):
                for child in comp.children:
                    if child.className in {"CaConc", "ZombieCaConc"}:
                        catab[neur_type].append(moose.Table(DATA_NAME+'/%s_%d_' % (neur_type,ii)+child.name))
                        cal = moose.element(comp.path+'/'+child.name)
                        moose.connect(catab[neur_type][-1], 'requestOut', cal, 'getCa')
                    elif  child.className == 'DifShell':
                        catab[neur_type].append(moose.Table(DATA_NAME+'/%s_%d_' % (neur_type,ii)+child.name))
                        cal = moose.element(comp.path+'/'+child.name)
                        moose.connect(catab[neur_type][-1], 'requestOut', cal, 'getC')

        if pltcurr:
            currtab[neur_type]={}
            #CHANNEL CURRENTS (Optional)
            for channame in model.Channels:
                tabs = [moose.Table(DATA_NAME+'/chan%s%s_%d' %(channame,neur_type,ii))
                        for ii in range(len(neur_comps))]
                currtab[neur_type][channame] = tabs
                for tab, comp in zip(tabs, neur_comps):
                    path = comp.path+'/'+channame
                    try:
                        chan=moose.element(path)
                        moose.connect(tab, 'requestOut', chan, curmsg)
                    except Exception:
                        log.debug('no channel {}', path)
    #
    # synaptic weight and plasticity (Optional) for one synapse per neuron
    plastab={key:[] for key in neuron.keys()}
    if len(plas):
        for num,neur_type in enumerate(plas.keys()):
            if len(plas[neur_type]):
                for comp_name in plas[neur_type]:
                    plastab[neur_type].append(add_one_table(DATA_NAME,plas[neur_type],comp_name))
    return vmtab,catab,plastab,currtab
Example #58
0
def addPlot(objpath, field, plot, tick):
    if moose.exists(objpath):
        tab = moose.Table('/graphs/' + plot)
        obj = moose.element(objpath)
        moose.connect(tab, 'requestOut', obj, field)
        tab.tick = tick
        return tab
    else:
        print "failed in addPlot(", objpath, field, plot, tick, ")"
        return 0
Example #59
0
def findUniqId(mobj, string, num):
    if num == 0:
        path = mobj.path + '/' + string
    else:
        path = mobj.path + '/' + string + str(num)
    if not moose.exists(path):
        return (string, num)
    else:
        num += 1
        return (findUniqId(mobj, string, num))
Example #60
0
def chanlib(model):
    if not moose.exists('/library'):
        moose.Neutral('/library')
    #Adding all the channels to the library.
    chan = [make_channel(model, '/library/'+key, value) for key, value in model.Channels.items()]
    if model.ghkYN:
        ghk = moose.GHK('/library/ghk')
        ghk.T = model.Temp
        ghk.Cout = model.ConcOut
        ghk.valency=2