Exemplo n.º 1
0
def setCompartmentSolver(modelRoot,solver):
	compts = moose.wildcardFind(modelRoot+'/##[ISA=ChemCompt]')
	for compt in compts:
		if ( solver == 'gsl' ) or (solver == 'Runge Kutta'):
			ksolve = moose.Ksolve( compt.path+'/ksolve' )
		if ( solver == 'gssa' ) or (solver == 'Gillespie'):
			ksolve = moose.Gsolve( compt.path+'/gsolve' )
		if ( solver != 'ee' ):
			stoich = moose.Stoich( compt.path+'/stoich' )
			stoich.compartment = compt
			stoich.ksolve = ksolve
			if moose.exists(compt.path):
				stoich.path = compt.path+"/##"
	stoichList = moose.wildcardFind(modelRoot+'/##[ISA=Stoich]')
	if len( stoichList ) == 2:
		stoichList[1].buildXreacs( stoichList[0] )
	if len( stoichList ) == 3:
		stoichList[1].buildXreacs (stoichList [0])
		stoichList[1].buildXreacs (stoichList [2])

	for i in stoichList:
		i.filterXreacs()
	
	for x in moose.wildcardFind( modelRoot+'/data/graph#/#' ):
		x.tick = 18
Exemplo n.º 2
0
def read_prototype(celltype, cdict):
    """Read the cell prototype file for the specified class. The
    channel properties are updated using values in cdict."""
    filename = '%s/%s.p' % (config.modelSettings.protodir, celltype)
    logger.debug('Reading prototype file %s' % (filename))
    adjust_chanlib(cdict)
    cellpath = '%s/%s' % (config.modelSettings.libpath, celltype)
    if moose.exists(cellpath):
        return moose.element(cellpath)
    for handler in logger.handlers:
        handler.flush()
    proto = moose.loadModel(filename, cellpath)
    # If prototype files do not have absolute compartment positions,
    # set the compartment postions to origin. This will avoid
    # incorrect assignemnt of position when the x/y/z values in
    # prototype file is just to for setting the compartment length.
    if not config.modelSettings.morph_has_postion:
        for comp in moose.wildcardFind('%s/#[TYPE=Compartment]' % (proto.path)):
            comp.x = 0.0
            comp.y = 0.0
            comp.z = 0.0
    leveldict = read_keyvals('%s/%s.levels' % (config.modelSettings.protodir, celltype))
    depths = read_keyvals('%s/%s.depths' % (config.modelSettings.protodir, celltype))
    depthdict = {}
    for level, depthset in list(depths.items()):
        if len(depthset) != 1:
            raise Exception('Depth set must have only one entry.')
        depthdict[level] = depthset.pop()
    assign_depths(proto, depthdict, leveldict)
    config.logger.debug('Read %s with %d compartments' % (celltype, len(moose.wildcardFind('%s/#[TYPE=Compartment]' % (proto.path)))))
    return proto
Exemplo n.º 3
0
def spinetabs(model,neuron,comps='all'):
    if not moose.exists(DATA_NAME):
        moose.Neutral(DATA_NAME)
    #creates tables of calcium and vm for spines
    spcatab = defaultdict(list)
    spvmtab = defaultdict(list)
    for typenum,neurtype in enumerate(neuron.keys()):
        if type(comps)==str and comps in {'*', 'all'}:
            spineHeads=[moose.wildcardFind(neurtype+'/##/#head#[ISA=CompartmentBase]')]
        else:
            spineHeads=[moose.wildcardFind(neurtype+'/'+c+'/#head#[ISA=CompartmentBase]') for c in comps]
        for spinelist in spineHeads:
            for spinenum,spine in enumerate(spinelist):
                compname = spine.parent.name
                sp_num=spine.name.split(NAME_HEAD)[0]
                spvmtab[typenum].append(moose.Table(vm_table_path(neurtype, spine=sp_num, comp=compname)))
                log.debug('{} {} {}',spinenum, spine.path, spvmtab[typenum][-1].path)
                moose.connect(spvmtab[typenum][-1], 'requestOut', spine, 'getVm')
                if model.calYN:
                    for child in spine.children:
                        if child.className == "CaConc" or  child.className == "ZombieCaConc" :
                            spcatab[typenum].append(moose.Table(DATA_NAME+'/%s_%s%s'% (neurtype,sp_num,compname)+child.name))
                            spcal = moose.element(spine.path+'/'+child.name)
                            moose.connect(spcatab[typenum][-1], 'requestOut', spcal, 'getCa')
                        elif child.className == 'DifShell':
                            spcatab[typenum].append(moose.Table(DATA_NAME+'/%s_%s%s'% (neurtype,sp_num,compname)+child.name))
                            spcal = moose.element(spine.path+'/'+child.name)
                            moose.connect(spcatab[typenum][-1], 'requestOut', spcal, 'getC')
    return spcatab,spvmtab
Exemplo n.º 4
0
def loadModel(filename, chanProto, chanDistrib, passiveDistrib):
    """Load the model and insert channels """
    global modelName
    global nchans, ncompts

    # Load in the swc file.
    modelName = "elec"
    cellProto = [ ( filename, modelName ) ]
    rdes = rd.rdesigneur( cellProto = cellProto
            , combineSegments = True
            , passiveDistrib = passiveDistrib
            , chanProto = chanProto
            , chanDistrib = chanDistrib
            )

    rdes.buildModel('/model')

    compts = moose.wildcardFind( "/model/%s/#[ISA=CompartmentBase]"%modelName )
    setupStimuls( compts[0] )

    for compt in compts:
        vtab = moose.Table( '%s/vm' % compt.path )
        moose.connect( vtab, 'requestOut', compt, 'getVm' )
        _records[compt.path] = vtab

    nchans  = len(set([x.path for x in
        moose.wildcardFind('/model/elec/##[TYPE=ZombieHHChannel]')])
        )
    _logger.info("Total channels: %s" % nchans)
    return _records
Exemplo n.º 5
0
    def _loadElec( self, efile, elecname ):
        if ( efile[ len( efile ) - 2:] == ".p" ):
            self.elecid = moose.loadModel( efile, '/library/' + elecname)[0]
            print self.elecid
        elif ( efile[ len( efile ) - 4:] == ".swc" ):
            self.elecid = moose.loadModel( efile, '/library/' + elecname)[0]
        else:
            nm = NeuroML()
            print "in _loadElec, combineSegments = ", self.combineSegments
            nm.readNeuroMLFromFile( efile, \
                    params = {'combineSegments': self.combineSegments, \
                    'createPotentialSynapses': True } )
            if moose.exists( '/cells' ):
                kids = moose.wildcardFind( '/cells/#' )
            else:
                kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]' )
                if ( kids[0].name == 'spine' ):
                    kids = kids[1:]

            assert( len( kids ) > 0 )
            self.elecid = kids[0]
            temp = moose.wildcardFind( self.elecid.path + '/#[ISA=CompartmentBase]' )

        transformNMDAR( self.elecid.path )
        kids = moose.wildcardFind( '/library/##[0]' )
        for i in kids:
            i.tick = -1
Exemplo n.º 6
0
def main():
                simdt = 0.1
                plotdt = 0.1
                runtime = 100.0

		makeModel()

		# Schedule the whole lot
		moose.setClock( 4, simdt ) # for the computational objects
		moose.setClock( 5, simdt ) # for the computational objects
		moose.setClock( 8, plotdt ) # for the plots
		moose.useClock( 4, '/model/compt#/ksolve#', 'init' )
		moose.useClock( 5, '/model/compt#/ksolve#', 'process' )
		moose.useClock( 8, '/model/graphs/#', 'process' )

		moose.reinit()
		moose.start( runtime ) # Run the model for 100 seconds.
		for x in moose.wildcardFind( '/model/compt#/#[ISA=PoolBase]' ):
                    print x.name, x.conc

		# Iterate through all plots, dump their contents to data.plot.
		for x in moose.wildcardFind( '/model/graphs/conc#' ):
				#x.xplot( 'scriptKineticModel.plot', x.name )
				t = numpy.linspace( 0, runtime, x.vector.size ) # sec
				pylab.plot( t, x.vector, label=x.name )
		pylab.legend()
		pylab.show()


		quit()
Exemplo n.º 7
0
def dumpPlots( fname ):
    if ( os.path.exists( fname ) ):
        os.remove( fname )
    for x in moose.wildcardFind( '/graphs/#[ISA=Table]' ):
        moose.element( x[0] ).xplot( fname, x[0].name )
    for x in moose.wildcardFind( '/graphs/elec/#[ISA=Table]' ):
        moose.element( x[0] ).xplot( fname, x[0].name + '_e' )
Exemplo n.º 8
0
def add_synchans(model, container):
    synchans=[]
    #2D array to store all the synapses.  Rows=num synapse types, columns=num comps
    #at the end they are concatenated into a dictionary
    for key in model.SYNAPSE_TYPES:
        synchans.append([])
    allkeys = sorted(model.SYNAPSE_TYPES)

    comp_list = moose.wildcardFind(container + '/#[TYPE=Compartment]')
    for comp in comp_list:
        #create each type of synchan in each compartment.  Add to 2D array
        for key in DendSynChans(model):
            keynum = allkeys.index(key)
            Gbar = model.SYNAPSE_TYPES[key].Gbar
            Gbarvar=model.SYNAPSE_TYPES[key].var
            synchans[keynum].append(addoneSynChan(key,comp,Gbar, model.calYN, Gbarvar))
        
        for key in SpineSynChans(model):
            keynum = allkeys.index(key)
            Gbar = model.SYNAPSE_TYPES[key].Gbar
            Gbarvar=model.SYNAPSE_TYPES[key].var
            for spcomp in moose.wildcardFind(comp.path + '/#[ISA=Compartment]'):
                if NAME_HEAD in spcomp.path:
                    synchans[keynum].append(addoneSynChan(key,spcomp,Gbar, model.calYN, Gbarvar))
                   
    allsynchans={key:synchans[keynum]
                 for keynum, key in enumerate(sorted(model.SYNAPSE_TYPES))}

    return allsynchans
Exemplo n.º 9
0
    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
Exemplo n.º 10
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( '/' )
def deliverStim(currTime):
	global injectionCurrent	
	global spineVm
	global somaVm
	if numpy.fabs( currTime - baselineTime ) < frameRunTime/2.0 :
		#start
		eList = moose.wildcardFind( '/model/elec/#soma#' )
		assert( len(eList) > 0 )
		eList[0].inject = injectionCurrent
		#print "1. injected current = ", injectionCurrent
		injectionCurrent += deltaCurrent
		#print "del stim first ", moose.element('/clock').currentTime
	if numpy.fabs( currTime - baselineTime - currPulseTime) < frameRunTime/2.0 :
		#end
		eList = moose.wildcardFind( '/model/elec/#soma#' )
		assert( len(eList) > 0 )
		eList[0].inject = 0.0
		#print "2. injected current = ", injectionCurrent
		#print "del stim second ", moose.element('/clock').currentTime
	if runtime - currTime < frameRunTime * 2.0 :
		#print "3. reinit-ing"
		somaVm.append( moose.element( '/graphs/VmTab' ).vector )
		spineVm.append( moose.element( '/graphs/eSpineVmTab' ).vector )
		iList.append(injectionCurrent)
		if injectionCurrent < maxCurrent :
			moose.reinit()	
Exemplo n.º 12
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( '/model' )
        rdes.soma.inject = inject
        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 ) )
        print("[INFO] reinitialzing")
        moose.reinit()
        buildPlots( rdes )
        # Run for baseline, tetanus, and post-tetanic settling time 
        t1 = time.time()
        moose.start( runtime )
        print('runtime = ', runtime, '; real time = ', time.time() - t1)

        saveAndClearPlots( "bigElec" )
        moose.delete( '/model' )
        rdes.elecid = moose.element( '/' )
Exemplo n.º 13
0
def transformNMDAR( path ):
    for i in moose.wildcardFind( path + "/##/#NMDA#[ISA!=NMDAChan]" ):
        chanpath = i.path
        pa = i.parent
        i.name = '_temp'
        if ( chanpath[-3:] == "[0]" ):
            chanpath = chanpath[:-3]
        nmdar = moose.NMDAChan( chanpath )
        sh = moose.SimpleSynHandler( chanpath + '/sh' )
        moose.connect( sh, 'activationOut', nmdar, 'activation' )
        sh.numSynapses = 1
        sh.synapse[0].weight = 1
        nmdar.Ek = i.Ek
        nmdar.tau1 = i.tau1
        nmdar.tau2 = i.tau2
        nmdar.Gbar = i.Gbar
        nmdar.CMg = 12
        nmdar.KMg_A = 1.0 / 0.28
        nmdar.KMg_B = 1.0 / 62
        nmdar.temperature = 300
        nmdar.extCa = 1.5
        nmdar.intCa = 0.00008
        nmdar.intCaScale = 1
        nmdar.intCaOffset = 0.00008
        nmdar.condFraction = 0.02
        moose.delete( i )
        moose.connect( pa, 'channel', nmdar, 'channel' )
        caconc = moose.wildcardFind( pa.path + '/#[ISA=CaConcBase]' )
        if ( len( caconc ) < 1 ):
            print('no caconcs found on ', pa.path)
        else:
            moose.connect( nmdar, 'ICaOut', caconc[0], 'current' )
            moose.connect( caconc[0], 'concOut', nmdar, 'assignIntCa' )
def updateDisplay():
    makeYmodel()
    tabvec = moose.wildcardFind( '/model/graphs/plot#' )
    moose.element( '/model/elec/' ).name = 'Y'
    vecYdend = moose.wildcardFind( '/model/Y/soma,/model/Y/dend#' )
    vecYbranch1 = moose.wildcardFind( '/model/Y/branch1#' )
    vecYbranch2 = moose.wildcardFind( '/model/Y/branch2#' )
    moose.reinit()
    dt = interval1
    currtime = 0.0
    for i in lines:
        moose.start( dt )
        currtime += dt
        #print "############## NumDendData = ", len( vecYdend )
        i.YdendLines.set_ydata( [v.Vm*1000 for v in vecYdend] )
        i.Ybranch1Lines.set_ydata( [v.Vm*1000 for v in vecYbranch1] )
        i.Ybranch2Lines.set_ydata( [v.Vm*1000 for v in vecYbranch2] )
        dt = interval2

    moose.start( runtime - currtime )

    #print "############## len (tabvec)  = ", len( tabvec[0].vector )
    for i, tab in zip( tplot, tabvec ):
        i.set_ydata( tab.vector * 1000 )
    
    moose.delete( '/model' )
    moose.delete( '/library' )
Exemplo n.º 15
0
    def _loadElec( self, efile, elecname, combineSegments ):
        library = moose.Neutral( '/library' )
        if ( efile[ len( efile ) - 2:] == ".p" ):
            self.elecid = moose.loadModel( efile, self.model.path + '/' + elecname )
        else:
            nm = NeuroML()
            nm.readNeuroMLFromFile( efile, \
                    params = {'combineSegments': combineSegments, \
                    'createPotentialSynapses': True } )
            if moose.exists( '/cells' ):
                kids = moose.wildcardFind( '/cells/#' )
            else:
                kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]' )
                if ( kids[0].name == 'spine' ):
                    kids = kids[1:]

            assert( len( kids ) > 0 )
            self.elecid = kids[0]
            temp = moose.wildcardFind( self.elecid.path + '/#[ISA=CompartmentBase]' )
            moose.move( self.elecid, self.model )
            self.elecid.name = elecname

        self._transformNMDAR( self.elecid.path )
        kids = moose.wildcardFind( '/library/##[0]' )
        for i in kids:
            i.tick = -1
Exemplo n.º 16
0
def main():
        #solver = "gsl"  # Pick any of gsl, gssa, ee..
        solver = "gssa"  # Pick any of gsl, gssa, ee..
	mfile = '../../Genesis_files/Repressillator.g'
	runtime = 6000.0
	if ( len( sys.argv ) >= 2 ):
                solver = sys.argv[1]
	modelId = moose.loadModel( mfile, 'model', solver )
        # Increase volume so that the stochastic solver gssa 
        # gives an interesting output
        compt = moose.element( '/model/kinetics' )
        compt.volume = 1e-19 
        dt = moose.element( '/clock' ).dt

	moose.reinit()
	moose.start( runtime ) 

	# Display all plots.
        img = mpimg.imread( 'repressillatorOsc.png' )
        fig = plt.figure( figsize=(12, 10 ) )
        png = fig.add_subplot( 211 )
        imgplot = plt.imshow( img )
        ax = fig.add_subplot( 212 )
	x = moose.wildcardFind( '/model/#graphs/conc#/#' )
        plt.ylabel( 'Conc (mM)' )
        plt.xlabel( 'Time (seconds)' )
	for x in moose.wildcardFind( '/model/#graphs/conc#/#' ):
            t = numpy.arange( 0, x.vector.size, 1 ) * dt
            pylab.plot( t, x.vector, label=x.name )
        pylab.legend()
        pylab.show()
Exemplo n.º 17
0
def writeCompt(modelpath, cremodel_):
    # getting all the compartments
    compts = moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]')
    groupInfo = {}
    for compt in compts:
        comptName = convertSpecialChar(compt.name)
        # converting m3 to litre
        size = compt.volume * pow(10, 3)
        ndim = compt.numDimensions
        c1 = cremodel_.createCompartment()
        c1.setId(str(idBeginWith(comptName +
                                 "_" +
                                 str(compt.getId().value) +
                                 "_" +
                                 str(compt.getDataIndex()) +
                                 "_")))
        c1.setName(comptName)
        c1.setConstant(True)
        c1.setSize(size)
        c1.setSpatialDimensions(ndim)
        c1.setUnits('volume')
        #For each compartment get groups information along
        for grp in moose.wildcardFind(compt.path+'/##[TYPE=Neutral]'):
            grp_cmpt = findGroup_compt(grp.parent)
            try:
                value = groupInfo[moose.element(grp)]
            except KeyError:
                # Grp is not present
                groupInfo[moose.element(grp)] = []


    if compts:
        return True,groupInfo
    else:
        return False,groupInfo
Exemplo n.º 18
0
def transformNMDAR(path):
    for i in moose.wildcardFind(path + "/##/#NMDA#[ISA!=NMDAChan]"):
        chanpath = i.path
        pa = i.parent
        i.name = "_temp"
        if chanpath[-3:] == "[0]":
            chanpath = chanpath[:-3]
        nmdar = moose.NMDAChan(chanpath)
        sh = moose.SimpleSynHandler(chanpath + "/sh")
        moose.connect(sh, "activationOut", nmdar, "activation")
        sh.numSynapses = 1
        sh.synapse[0].weight = 1
        nmdar.Ek = i.Ek
        nmdar.tau1 = i.tau1
        nmdar.tau2 = i.tau2
        nmdar.Gbar = i.Gbar
        nmdar.CMg = 12
        nmdar.KMg_A = 1.0 / 0.28
        nmdar.KMg_B = 1.0 / 62
        nmdar.temperature = 300
        nmdar.extCa = 1.5
        nmdar.intCa = 0.00008
        nmdar.intCaScale = 1
        nmdar.intCaOffset = 0.00008
        nmdar.condFraction = 0.02
        moose.delete(i)
        moose.connect(pa, "channel", nmdar, "channel")
        caconc = moose.wildcardFind(pa.path + "/#[ISA=CaConcBase]")
        if len(caconc) < 1:
            print("no caconcs found on ", pa.path)
        else:
            moose.connect(nmdar, "ICaOut", caconc[0], "current")
            moose.connect(caconc[0], "concOut", nmdar, "assignIntCa")
Exemplo n.º 19
0
def showVisualization():
    makeModel()
    elec = moose.element( '/model/elec' )
    elec.setSpineAndPsdMesh( moose.element('/model/chem/spine'), moose.element('/model/chem/psd') )

    eHead = moose.wildcardFind( '/model/elec/#head#' )
    oldDia = [ i.diameter for i in eHead ]
    graphs = moose.Neutral( '/graphs' )
    #makePlot( 'psd_x', moose.vec( '/model/chem/psd/x' ), 'getN' )
    #makePlot( 'head_x', moose.vec( '/model/chem/spine/x' ), 'getN' )
    makePlot( 'dend_x', moose.vec( '/model/chem/dend/x' ), 'getN' )
    dendZ = makePlot( 'dend_z', moose.vec( '/model/chem/dend/z' ), 'getN' )
    makePlot( 'head_z', moose.vec( '/model/chem/spine/z' ), 'getN' )
    psdZ = makePlot( 'psd_z', moose.vec( '/model/chem/psd/z' ), 'getN' )
    diaTab = makePlot( 'headDia', eHead, 'getDiameter' )
    # print diaTab[0].vector[-1]
    # return
    dendrite = moose.element("/model/elec/dend")
    dendrites = [dendrite.path + "/" + str(i) for i in range(len(dendZ))]
    # print dendrites
    moose.reinit()

    spineHeads = moose.wildcardFind( '/model/elec/#head#')
    # print moose.wildcardFind( '/model/elec/##')

    # print "dendZ", readValues(dendZ)
    # print dendrite

    app = QtGui.QApplication(sys.argv)
    viewer = create_viewer("/model/elec", dendrite, dendZ, diaTab, psdZ)
    viewer.showMaximized()
    viewer.start()
    return app.exec_()
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
def displayPlots():
    pylab.figure(1, figsize = (8,10 ) )
    pylab.subplot( 1,1,1)
    for i in moose.wildcardFind( "/graphs/#VmTab" ):
        t = numpy.arange( 0, i.vector.size, 1 ) * i.dt
        pylab.plot( t, i.vector, label = i.name )
    pylab.xlabel( "Time (s)" )
    pylab.legend()
    pylab.title( 'Vm' )

    pylab.figure(2, figsize= (8,10))
    ax = pylab.subplot( 1,1,1 )
    neuron = moose.element( '/model/elec' )
    comptDistance = dict( zip( neuron.compartments, neuron.pathDistanceFromSoma ) )
    for i in moose.wildcardFind( '/library/#[ISA=ChanBase]' ):
        chans = moose.wildcardFind( '/model/elec/#/' + i.name )
        print i.name, len( chans )
        p = [ 1e6*comptDistance.get( j.parent, 0) for j in chans ]
        Gbar = [ j.Gbar/(j.parent.length * j.parent.diameter * PI) for j in chans ]
        if len( p ) > 2:
            pylab.plot( p, Gbar, linestyle = 'None', marker = ".", label = i.name )
            sortedGbar = sorted(zip(p, Gbar), key=lambda x: x[0])
    ax.set_yscale( 'log' )
    pylab.xlabel( "Distance from soma (microns)" )
    pylab.ylabel( "Channel density (Seimens/sq mtr)" )
    pylab.legend()
    pylab.title( 'Channel distribution' )
    pylab.show()
Exemplo n.º 22
0
def makeGraphics( cPlotDt, ePlotDt ):
        plt.ion()
        fig = plt.figure( figsize=(10,16) )
        chem = fig.add_subplot( 411 )
        chem.set_ylim( 0, 0.006 )
        plt.ylabel( 'Conc (mM)' )
        plt.xlabel( 'time (seconds)' )
        for x in moose.wildcardFind( '/graphs/chem/#[ISA=Table]' ):
            pos = numpy.arange( 0, x.vector.size, 1 ) * cPlotDt
            line1, = chem.plot( pos, x.vector, label=x.name )
        plt.legend()

        elec = fig.add_subplot( 412 )
        plt.ylabel( 'Vm (V)' )
        plt.xlabel( 'time (seconds)' )
        for x in moose.wildcardFind( '/graphs/elec/#[ISA=Table]' ):
            pos = numpy.arange( 0, x.vector.size, 1 ) * ePlotDt
            line1, = elec.plot( pos, x.vector, label=x.name )
        plt.legend()

        ca = fig.add_subplot( 413 )
        plt.ylabel( '[Ca] (mM)' )
        plt.xlabel( 'time (seconds)' )
        for x in moose.wildcardFind( '/graphs/ca/#[ISA=Table]' ):
            pos = numpy.arange( 0, x.vector.size, 1 ) * ePlotDt
            line1, = ca.plot( pos, x.vector, label=x.name )
        plt.legend()

        lenplot = fig.add_subplot( 414 )
        plt.ylabel( 'Ca (mM )' )
        plt.xlabel( 'Voxel#)' )

	spineCa = moose.vec( '/model/chem/spine/Ca' )
	dendCa = moose.vec( '/model/chem/dend/DEND/Ca' )
        line1, = lenplot.plot( range( len( spineCa ) ), spineCa.conc, label='spine' )
        line2, = lenplot.plot( range( len( dendCa ) ), dendCa.conc, label='dend' )

        ca = [ x.Ca * 0.0001 for x in moose.wildcardFind( '/model/elec/##[ISA=CaConcBase]') ]
        line3, = lenplot.plot( range( len( ca ) ), ca, label='elec' )

	spineCaM = moose.vec( '/model/chem/spine/CaM_dash_Ca4' )
        line4, = lenplot.plot( range( len( spineCaM ) ), spineCaM.conc, label='spineCaM' )
	psdCaM = moose.vec( '/model/chem/psd/CaM_dash_Ca4' )
        line5, = lenplot.plot( range( len( psdCaM ) ), psdCaM.conc, label='psdCaM' )
        plt.legend()


        fig.canvas.draw()
        raw_input()
                
        '''
        for x in moose.wildcardFind( '/graphs/##[ISA=Table]' ):
            t = numpy.arange( 0, x.vector.size, 1 )
            pylab.plot( t, x.vector, label=x.name )
        pylab.legend()
        pylab.show()
        '''

	print 'All done'
Exemplo n.º 23
0
def dumpPlots( fname ):
	t = numpy.arange( 0, 100.2, 0.2 ) # msec
	plots = moose.wildcardFind( '/graphs/##[ISA=Table]' )
	for x in moose.wildcardFind( '/graphs/##[ISA=Table]' ):
		pylab.plot( t, x.vector, label=x.name)

	pylab.legend()
	pylab.show()
Exemplo n.º 24
0
def dumpPlots():
	plots = moose.wildcardFind( '/graphs/##[ISA=Table]' )
	for x in moose.wildcardFind( '/graphs/##[ISA=Table]' ):
	    t = numpy.arange( 0, x.size ) * x.dt # msec
	    pylab.plot( t, x.vector, label=x.name)

	pylab.legend()
	pylab.show()
Exemplo n.º 25
0
def dump_plots():
    for x in moose.wildcardFind('/graphs/cpu/##[ISA=Table]'):
        t = numpy.arange(0, len(x.vector), 1)
        pylab.plot(t, x.vector, label=("CPU:%s" % x.name))
    for x in moose.wildcardFind('/graphs/gpu/##[ISA=Table]'):
#         print x.vector
        t = numpy.arange(0, len(x.vector), 1)
        pylab.plot(t, x.vector, label=("GPU:%s" % x.name))
Exemplo n.º 26
0
def main():

        """
        funcRateHarmonicOsc illustrates the use of function objects to
        directly define the rates of change of pool concentration. This
        example shows how to set up a simple harmonic oscillator system
        of differential equations using the script. In normal use one would
        prefer to use SBML.

        The equations are ::

                p' = v - offset1
                v' = -k(p - offset2)

        where the rates for Pools p and v are computed using Functions.
        Note the use of offsets. This is because MOOSE chemical
        systems cannot have negative concentrations.
        
        The model is set up to run using default Exponential Euler 
        integration, and then using the GSL deterministic solver.
        """
        makeModel()

        for i in range( 11, 18 ):
            moose.setClock( i, 0.01 )
        moose.setClock( 18, 0.1 )
        moose.reinit()
        moose.start( runtime ) # Run the model

        # Iterate through all plots, dump their contents to data.plot.
        for x in moose.wildcardFind( '/model/graphs/#' ):
                #x.xplot( 'scriptKineticModel.plot', x.name )
                t = numpy.arange( 0, x.vector.size, 1 ) * x.dt # sec
                pylab.plot( t, x.vector, label=x.name )
        pylab.suptitle( "Integration using ee" )
        pylab.legend()
        pylab.figure()

        compt = moose.element( '/model/harmonic' )
        ksolve = moose.Ksolve( '/model/harmonic/ksolve' )
        stoich = moose.Stoich( '/model/harmonic/stoich' )
        stoich.compartment = compt
        stoich.ksolve = ksolve
        stoich.path = '/model/harmonic/##'
        for i in range( 11, 18 ):
            moose.setClock( i, 0.1 )
        moose.reinit()
        moose.start( runtime ) # Run the model

        for x in moose.wildcardFind( '/model/graphs/#' ):
                t = numpy.arange( 0, x.vector.size, 1 ) * x.dt # sec
                pylab.plot( t, x.vector, label=x.name )
        pylab.suptitle( "Integration using gsl" )
        pylab.legend()
        pylab.show()

        quit()
Exemplo n.º 27
0
def run_model_fig6():
    """Do a simulation for fig6 and plot data."""
    for ch in moose.wildcardFind('/model/##[ISA=ChanBase]'):
        ch.Gk = 1.0/Rm
    print('Starting for', inject_time)
    moose.start(inject_time)
    for ch in moose.wildcardFind('/model/##[ISA=ChanBase]'):
        ch.Gk = 0.0
    moose.start(simtime - inject_time)
Exemplo n.º 28
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
def main():
    """
    This example illustrates a simple cross compartment reaction::

        a <===> b <===> c

    Here each molecule is in a different compartment.
    The initial conditions are such that the end conc on all compartments
    should be 2.0.
    The time course depends on which compartment the Reac object is 
    embedded in.
    The cleanest thing numerically and also conceptually is to have both 
    reactions in the same compartment, in this case the middle one
    (**compt1**).
    The initial conditions have a lot of **B**. The equilibrium with 
    **C** is fast and so **C** shoots up and passes **B**, peaking at 
    about (2.5,9). This is also just 
    about the crossover point.
    **A** starts low and slowly climbs up to equilibrate.

    If we put **reac0** in **compt0** and **reac1** in **compt1**, 
    it behaves the same
    qualitiatively but now the peak is at around (1, 5.2)

    This configuration of reactions makes sense from the viewpoint of 
    having the
    reactions always in the compartment with the smaller volume, which is
    important if we need to have junctions where many small voxels talk to
    one big voxel in another compartment.

    Note that putting the reacs in other compartments doesn't work and in
    some combinations (e.g., **reac0** in **compt0** and **reac1** in 
    **compt2**) give
    numerical instability.
    """
    simdt = 0.1
    plotdt = 0.1
    runtime = 100.0

    makeModel()

    # MOOSE autoschedules everything.
    moose.reinit()
    moose.start( runtime ) # Run the model for 100 seconds.
    print("All concs should converge to 2.0 even though vols differ:")
    for x in moose.wildcardFind( '/model/compt#/#[ISA=PoolBase]' ):
        print((x.name, x.conc))

    # Iterate through all plots, dump their contents to data.plot.
    for x in moose.wildcardFind( '/model/graphs/conc#' ):
        t = numpy.linspace( 0, runtime, x.vector.size ) # sec
        pylab.plot( t, x.vector, label=x.name )
    pylab.legend()
    pylab.show()
    quit()
Exemplo n.º 30
0
 def _scaleSpineCompt( self, compt, size ):
     chans = moose.wildcardFind( compt.path + '/##[ISA=ChanBase]' )
     a = size * size
     for i in chans:
         i.Gbar *= a
     concs = moose.wildcardFind( compt.path + '/##[ISA=CaConcBase]' )
     for i in concs:
         i.B *= size * size * size
     compt.Rm /= a
     compt.Cm *= a
     compt.Ra /= size
Exemplo n.º 31
0
def displayPlots():
    pylab.figure(1, figsize=(8, 10))
    pylab.subplot(4, 1, 1)
    for i in moose.wildcardFind("/graphs/psdRtab[]"):
        t = numpy.arange(0, i.vector.size, 1) * i.dt
        pylab.plot(t, i.vector)
    pylab.title('# receptor in PSD')
    pylab.subplot(4, 1, 2)
    for i in moose.wildcardFind("/graphs/caDendTab[]"):
        t = numpy.arange(0, i.vector.size, 1) * i.dt
        pylab.plot(t, i.vector)
    pylab.title('[Ca] in dend')
    pylab.subplot(4, 1, 3)
    for i in moose.wildcardFind("/graphs/caHeadTab[]"):
        t = numpy.arange(0, i.vector.size, 1) * i.dt
        pylab.plot(t, i.vector)
    pylab.title('[Ca] in spine head')
    pylab.subplot(4, 1, 4)
    for i in moose.wildcardFind("/graphs/#VmTab"):
        t = numpy.arange(0, i.vector.size, 1) * i.dt
        pylab.plot(t, i.vector, label=i.name)
    pylab.xlabel("Time (s)")
    pylab.legend()
    pylab.title('Vm')

    pylab.figure(2, figsize=(8, 10))
    ax = pylab.subplot(1, 1, 1)
    neuron = moose.element('/model/elec')
    comptDistance = dict(zip(neuron.compartments, neuron.pathDistanceFromSoma))
    for i in moose.wildcardFind('/library/#[ISA=ChanBase]'):
        chans = moose.wildcardFind('/model/elec/#/' + i.name)
        print i.name, len(chans)
        p = [1e6 * comptDistance.get(j.parent, 0) for j in chans]
        Gbar = [
            j.Gbar / (j.parent.length * j.parent.diameter * PI) for j in chans
        ]
        if len(p) > 2:
            pylab.plot(p, Gbar, linestyle='None', marker=".", label=i.name)
    ax.set_yscale('log')
    pylab.xlabel("Distance from soma (microns)")
    pylab.ylabel("Channel density (Seimens/sq mtr)")
    pylab.legend()
    pylab.title('Channel distribution')
    pylab.show()
Exemplo n.º 32
0
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)):
        xloc = moose.Compartment(comp).x
        yloc = moose.Compartment(comp).y
        #Possibly this should be replaced by pathlength
        dist = np.sqrt(xloc * xloc + yloc * yloc)
        log.debug('comp {.path} dist {}', comp, dist)
        #
        #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, chanparams in model.Channels.items():
            c = _util.distance_mapping(Cond[channame], comp)
            if c > 0:
                log.debug('Testing Cond If {} {}', channame, c)
                calciumPermeable = chanparams.calciumPermeable
                add_channel.addOneChan(channame,
                                       c,
                                       comp,
                                       ghkYN,
                                       ghk,
                                       calciumPermeable=calciumPermeable)
    return cellproto
Exemplo n.º 33
0
def writeFunc(modelpath, cremodel_):
    funcs = moose.wildcardFind(modelpath + '/##[ISA=Function]')
    # if func:
    foundFunc = False
    for func in funcs:
        if func:
            if func.parent.className == "CubeMesh" or func.parent.className == "CyclMesh":
                if len(moose.element(func).neighbors["valueOut"]) > 0:
                    funcEle = moose.element(
                        moose.element(func).neighbors["valueOut"][0])
                    funcEle1 = moose.element(funcEle)
                    fName = idBeginWith(convertSpecialChar(
                    funcEle.name + "_" + str(funcEle.getId().value) + "_" + str(funcEle.getDataIndex()) + "_"))
                    expr = " "
                    expr = str(moose.element(func).expr)
                    if not expr:
                        foundFunc = True
            else:
                foundFunc = True
                fName = idBeginWith(convertSpecialChar(func.parent.name +
                                                       "_" + str(func.parent.getId().value) +
                                                       "_" + str(func.parent.getDataIndex()) +
                                                       "_"))
                item = func.path + '/x[0]'
                sumtot = moose.element(item).neighbors["input"]
                expr = moose.element(func).expr
                for i in range(0, len(sumtot)):
                    v = "x" + str(i)
                    if v in expr:
                        z = str(idBeginWith(str(convertSpecialChar(sumtot[i].name + "_" + str(moose.element(
                            sumtot[i]).getId().value) + "_" + str(moose.element(sumtot[i]).getDataIndex())) + "_")))
                        expr = expr.replace(v, z)
            if foundFunc:
                rule = cremodel_.createAssignmentRule()
                rule.setVariable(fName)
                rule.setFormula(expr)
Exemplo n.º 34
0
def writeCompt(modelpath, cremodel_):
    # getting all the compartments
    compts = moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]')
    for compt in compts:
        comptName = convertSpecialChar(compt.name)
        # converting m3 to litre
        size = compt.volume * pow(10, 3)
        ndim = compt.numDimensions
        c1 = cremodel_.createCompartment()
        c1.setId(str(idBeginWith(comptName +
                                 "_" +
                                 str(compt.getId().value) +
                                 "_" +
                                 str(compt.getDataIndex()) +
                                 "_")))
        c1.setName(comptName)
        c1.setConstant(True)
        c1.setSize(size)
        c1.setSpatialDimensions(ndim)
        c1.setUnits('volume')
    if compts:
        return True
    else:
        return False
Exemplo n.º 35
0
def addSolver(modelRoot, solver):
    compt = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
    comptinfo = moose.Annotator(moose.element(compt[0]).path + '/info')
    previousSolver = comptinfo.solver
    currentSolver = previousSolver
    if solver == "Gillespie":
        currentSolver = "gssa"
    elif solver == "Runge Kutta":
        currentSolver = "gsl"
    elif solver == "Exponential Euler":
        currentSolver = "ee"
    if previousSolver != currentSolver:
        # if previousSolver != currentSolver
        comptinfo.solver = currentSolver
        if (moose.exists(compt[0].path + '/stoich')):
            # "A: and stoich exists then delete the stoich add solver"
            deleteSolver(modelRoot)
            setCompartmentSolver(modelRoot, currentSolver)
            return True
        else:
            # " B: stoich doesn't exists then addSolver, this is when object is deleted which delete's the solver "
            #  " and solver is also changed, then add addsolver "
            setCompartmentSolver(modelRoot, currentSolver)
            return True
    else:

        # " solver is same "
        if moose.exists(compt[0].path + '/stoich'):
            # " stoich exist, doing nothing"
            return False
        else:
            # "but stoich doesn't exist,this is when object is deleted which deletes the solver
            # " but solver are not changed, then also call addSolver"
            setCompartmentSolver(modelRoot, currentSolver)
            return True
    return False
Exemplo n.º 36
0
def main():
    solver = "old_gsl"  # Pick any of gsl, gssa, ee..
    mfile = '../Genesis_files/kkit_objects_example.g'
    runtime = 20.0
    if (len(sys.argv) >= 3):
        mfile = '../Genesis_files/' + sys.argv[1]
        runtime = float(sys.argv[2])
    if (len(sys.argv) == 4):
        solver = sys.argv[3]
    modelId = moose.loadModel(mfile, 'model', solver)
    # Increase volume so that the stochastic solver gssa
    # gives an interesting output
    #compt = moose.element( '/model/kinetics' )
    #compt.volume = 1e-19

    moose.reinit()
    moose.start(runtime)

    # Report parameters
    '''
	for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ):
		print x.name, x.nInit, x.concInit
	for x in moose.wildcardFind( '/model/kinetics/##[ISA=ReacBase]' ):
		print x.name, 'num: (', x.numKf, ', ',  x.numKb, '), conc: (', x.Kf, ', ', x.Kb, ')'
	for x in moose.wildcardFind('/model/kinetics/##[ISA=EnzBase]'):
		print x.name, '(', x.Km, ', ',  x.numKm, ', ', x.kcat, ')'
                '''

    # Display all plots.
    for x in moose.wildcardFind('/model/#graphs/conc#/#'):
        t = numpy.arange(0, x.vector.size, 1) * x.dt
        pylab.plot(t, x.vector, label=x.name)
    pylab.legend()
    pylab.show()

    quit()
Exemplo n.º 37
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
Exemplo n.º 38
0
def create_comp_model(container_name,
                      file_name,
                      comp_RM=None,
                      comp_CM=None,
                      comp_RA=None,
                      comp_ELEAK=None,
                      comp_initVm=None):
    'Create compartmental model from *.p file or a *.swc file.'
    if file_name.endswith('.p'):
        root_comp = moose.loadModel(file_name, container_name)
    elif file_name.endswith('swc'):
        assert comp_RM is not None, "comp_RM needs valid value."
        assert comp_CM is not None, "comp_CM needs valid value."
        assert comp_RA is not None, "comp_RA needs valid value."
        assert comp_ELEAK is not None, "comp_ELEAK needs valid value."
        assert comp_initVm is not None, "comp_initVm needs valid value."
        root_comp = moose.loadModel(file_name, container_name)
        for comp in moose.wildcardFind(root_comp.path +
                                       '/#[TYPE=Compartment]'):
            set_comp_values(comp, comp_RM, comp_CM, comp_RA, comp_initVm,
                            comp_ELEAK)
    else:
        raise "Invalid cell model file type."
    return root_comp
Exemplo n.º 39
0
    def __init__(self, modelRoot, *args, **kwargs):
        super(PlotWidgetContainer, self).__init__(*args)
        self.modelRoot = modelRoot
        if len(moose.wildcardFind(modelRoot + "/##[ISA=ChemCompt]")) == 0:
            self.modelType = ELECTRICAL
        else:
            self.modelType = CHEMICAL

        self.model = moose.element(self.modelRoot)
        if self.modelRoot != "/":
            self.modelRoot = self.findModelPath(self.modelRoot)
            if moose.exists(modelRoot + "/data"):
                self.data = moose.element(self.modelRoot + "/data")
            else:
                self.data = moose.Neutral(self.modelRoot + "/data")
        else:
            self.data = moose.element("/data")

        self._layout = QVBoxLayout()
        self.graphs = QSplitter()
        self.graphs.setOrientation(QtCore.Qt.Vertical)
        self.graphsArea = QScrollArea()
        self.rowIndex = 0
        self.graphs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setAcceptDrops(True)
        self.graphsArea.setWidget(self.graphs)
        self.graphsArea.setWidgetResizable(True)
        self.graphWidgets = []
        self._layout.addWidget(self.graphsArea)
        self.setLayout(self._layout)

        for graph in self.data.children:
            self.addPlotWidget(graph=graph)

        if len(self.data.children) == 0:
            self.addPlotWidget()
Exemplo n.º 40
0
def test_travelling_osc():
    """Test travelling wave.
    """
    rdes = rd.rdesigneur(
        turnOffElec = True,
        diffusionLength = 2e-6, 
        chemProto = [['makeChemOscillator()', 'osc']],
        chemDistrib = [['osc', 'soma', 'install', '1' ]],
        plotList = [
            ['soma', '1', 'dend/a', 'conc', 'Concentration of a'],
            ['soma', '1', 'dend/b', 'conc', 'Concentration of b'],
            ['soma', '1', 'dend/a', 'conc', 'Concentration of a', 'wave'],
        ],
        moogList = [['soma', '1', 'dend/a', 'conc', 'a Conc', 0, 360 ]]
    )
    a = moose.element( '/library/osc/kinetics/a' )
    b = moose.element( '/library/osc/kinetics/b' )
    s = moose.element( '/library/osc/kinetics/s' )
    a.diffConst = 0
    b.diffConst = 0
    a.motorConst = 1e-6
    rdes.buildModel()
    moose.reinit()
    #  rdes.displayMoogli( 1, 400, rotation = 0, azim = -np.pi/2, elev = 0.0 )
    moose.start(400)
    data = []
    for t in moose.wildcardFind('/##[TYPE=Table2]'): 
        data.append(t.vector[::10])
    m = np.mean(data, axis=0)
    u = np.std(data, axis=0)
    # The expected values are computed with GSL solver. These values will vary
    # a little with BOOST solver. Give some leeway for these tests.
    assert np.allclose(expected[0], m, rtol=1e-2), "Error is %s " % (expected[0]-m)
    A, B = expected[1], u
    assert np.allclose(B, A, rtol=1e-1), "Error is %s, base=%s" % ((A-B), B)
    print('done')
Exemplo n.º 41
0
def test_axon_propagation():
    """ Test squid axon propagation.
    """
    moose.Neutral( '/library' )
    makeAxonProto()

    rdes = rd.rdesigneur(
        chanProto = [['make_HH_Na()', 'Na'], ['make_HH_K()', 'K']],
        cellProto = [['elec','axon']],
        chanDistrib = [
            ['Na', '#', 'Gbar', '1200' ],
            ['K', '#', 'Gbar', '360' ]],
        stimList = [['soma', '1', '.', 'inject', '(t>0.005 && t<0.2) * 2e-11' ]],
        plotList = [['soma', '1', '.', 'Vm', 'Membrane potential']],
        moogList = [['#', '1', '.', 'Vm', 'Vm (mV)']]
    )

    rdes.buildModel()
    moose.reinit()
    moose.start(0.04)
    data = moose.wildcardFind('/##[TYPE=Table]')[0].vector[::10]
    assert np.allclose(data, expected), "Error is %s" % (data-expected)
    print('Add done')
    return data
def test_rdes():
    rdes = rd.rdesigneur(
        cellProto=[['somaProto', 'soma', 20e-6, 200e-6]],
        chanProto=[['make_glu()', 'glu']],
        chanDistrib=[['glu', 'soma', 'Gbar', '1']],
        stimList=[['soma', '0.5', 'glu', 'randsyn', '50']],
        # Deliver stimulus to glu synapse on soma, at mean 50 Hz Poisson.
        plotList=[['soma', '1', '.', 'Vm', 'Soma membrane potential']])
    rdes.buildModel()
    print('[INFO] built rdesigneur')
    moose.reinit()
    moose.start(0.3)
    tables = moose.wildcardFind('/##[TYPE=Table]')
    res = []
    for t in tables:
        y = t.vector
        u, s = np.mean(y), np.std(y)
        res.append((u, s))

    # Got these values from version compiled on Sep 20, 2018 with moose.seed
    # set to 100.
    expected = [(-0.051218660048699974, 0.01028490481294165)]
    assert np.isclose(expected, res,
                      atol=1e-5).all(), "Expected %s, got %s" % (expected, res)
Exemplo n.º 43
0
def writeNotes(modelpath, f):
    notes = ""
    #items = moose.wildcardFind(modelpath+"/##[ISA=ChemCompt],/##[ISA=ReacBase],/##[ISA=PoolBase],/##[ISA=EnzBase],/##[ISA=Function],/##[ISA=StimulusTable]")
    items = []
    items = moose.wildcardFind(modelpath+"/##[0][ISA=ChemCompt]") +\
            moose.wildcardFind(modelpath+"/##[0][ISA=PoolBase]") +\
            moose.wildcardFind(modelpath+"/##[0][ISA=ReacBase]") +\
            moose.wildcardFind(modelpath+"/##[0][ISA=EnzBase]") +\
            moose.wildcardFind(modelpath+"/##[0][ISA=Function]") +\
            moose.wildcardFind(modelpath+"/##[0][ISA=StimulusTable]")
    for item in items:
        if not re.search(r"xfer", item.name):
            if not moose.exists(item.path + '/info'):
                continue
            info = item.path + '/info'
            notes = moose.Annotator(info).getField('notes')
            if not notes:
                continue
            m = r'call /kinetics/{0}/notes LOAD \ \n"{1}"\n'.format(
                trimPath(item),
                moose.Annotator(info).getField('notes'))
            f.write(m)
Exemplo n.º 44
0
try:
    import matplotlib
except Exception as e:
    print("[INFO ] matplotlib is not found. This test wont run.")
    quit()

import rdesigneur as rd

rdes = rd.rdesigneur(
    cellProto=[['somaProto', 'soma', 20e-6, 200e-6]],
    chanProto=[['make_glu()', 'glu']],
    chanDistrib=[['glu', 'soma', 'Gbar', '1']],
    stimList=[['soma', '0.5', 'glu', 'randsyn', '50']],
    # Deliver stimulus to glu synapse on soma, at mean 50 Hz Poisson.
    plotList=[['soma', '1', '.', 'Vm', 'Soma membrane potential']])
rdes.buildModel()
moose.reinit()
moose.start(0.3)
tables = moose.wildcardFind('/##[TYPE=Table]')
res = []
for t in tables:
    y = t.vector
    u, s = np.mean(y), np.std(y)
    res.append((u, s))

# Got these values from version compiled on Sep 20, 2018 with moose.seed set to
# 100.
expected = [(-0.051218660048699974, 0.01028490481294165)]
assert np.isclose(expected, res,
                  atol=1e-5).all(), "Expected %s, got %s" % (expected, res)
Exemplo n.º 45
0
popdict, projdict = moose.neuroml.loadNeuroML_L123(filename)

# setting up hsolve object for each neuron
for popinfo in popdict.values():
    for cell in popinfo[1].values():
        solver = moose.HSolve(cell.path + "/hsolve")
        solver.target = cell.path

# reinit moose to bring to a reliable initial state.
moose.reinit()

SIMULATION_DELTA = 0.001
SIMULATION_TIME  = 0.03

ALL_COMPARTMENTS = map( lambda x : x.path
                      , moose.wildcardFind("/cells[0]/##[ISA=CompartmentBase]")
                      )

BASE_RM_VALUE = min( map( lambda x : moose.element(x).Rm
                        , ALL_COMPARTMENTS
                        )
                   )
PEAK_RM_VALUE = max( map( lambda x : moose.element(x).Rm
                        , ALL_COMPARTMENTS
                        )
                   )
BASE_RM_COLOR = [0.0, 1.0, 0.0, 0.1]
PEAK_RM_COLOR = [1.0, 0.0, 0.0, 1.0]

BASE_VM_VALUE = -0.065
PEAK_VM_VALUE = -0.060
Exemplo n.º 46
0
def convert_morphology(root, positions='auto'):
    """Convert moose neuron morphology contained under `root` into a
    NeuroML object. The id of the return object is
    {root.name}_morphology. Each segment object gets the numeric value
    of the moose id of the object. The name of the segments are same
    as the corresponding moose compartment.

    Parameters
    ----------
    root : a moose element containing a single cell model.

    positions : string
    flag to indicate if the positions of the end points of the
    compartments are explicitly available in the compartments or
    should be automatically generated.  Possible values:

    `auto` - automatically generate z coordinates using length of the
    compartments.

    `explicit` - model has explicit coordinates for all compartments.

    Return
    ------
    a neuroml.Morphology instance.

    """
    if positions == 'auto':
        queue = deque([autoposition(root)])
    elif positions == 'explicit':
        compartments = moose.wildcardFind('%s/##[TYPE=Compartment]' % (root.path))
        queue = deque([compartment for compartment in map(moose.element, compartments)
                  if len(compartment.neighbours['axial']) == 0])
        if len(queue) != 1:
            raise Exception('There must be one and only one top level compartment. Found %d' % (len(topcomp_list)))
    else:
        raise Exception('allowed values for keyword argument positions=`auto` or `explicit`')
    comp_seg = {}
    parent = None
    while len(queue) > 0:
        compartment = queue.popleft()
        proximal = neuroml.Point3DWithDiam(x=compartment.x0,
                                           y=compartment.y0,
                                           z=compartment.z0,
                                           diameter=compartment.diameter)
        distal = neuroml.Point3DWithDiam(x=compartment.x,
                                         y=compartment.y,
                                         z=compartment.z,
                                         diameter=compartment.diameter)
        plist = list(map(moose.element, compartment.neighbours['axial']))
        try:
            parent = neuroml.SegmentParent(segments=comp_seg[moose.element(plist[0])].id)
        except (KeyError, IndexError) as e:
            parent = None
        segment = neuroml.Segment(id=compartment.id_.value,
                                  proximal=proximal,
                                  distal=distal,
                                  parent=parent)
        # TODO: For the time being using numerical value of the moose
        # id for neuroml id.This needs to be updated for handling
        # array elements
        segment.name = compartment.name
        comp_seg[compartment] = segment
        queue.extend([comp for comp in map(moose.element, compartment.neighbours['raxial'])])
    morph = neuroml.Morphology(id='%s_morphology' % (root.name))
    morph.segments.extend(comp_seg.values())
    return morph
Exemplo n.º 47
0
def setupItem(modelPath, cntDict):
    '''This function collects information of what is connected to what. \
    eg. substrate and product connectivity to reaction's and enzyme's \
    sumtotal connectivity to its pool are collected '''
    #print " setupItem"
    sublist = []
    prdlist = []
    zombieType = ['ReacBase', 'EnzBase', 'Function', 'StimulusTable']
    for baseObj in zombieType:
        path = '/##[ISA=' + baseObj + ']'
        if modelPath != '/':
            path = modelPath + path
        if ((baseObj == 'ReacBase') or (baseObj == 'EnzBase')):
            for items in moose.wildcardFind(path):
                sublist = []
                prdlist = []
                uniqItem, countuniqItem = countitems(items, 'subOut')
                subNo = uniqItem
                for sub in uniqItem:
                    sublist.append(
                        (moose.element(sub), 's', countuniqItem[sub]))

                uniqItem, countuniqItem = countitems(items, 'prd')
                prdNo = uniqItem
                if (len(subNo) == 0 or len(prdNo) == 0):
                    print("\nSubstrate Product is empty for " + items.path)

                for prd in uniqItem:
                    prdlist.append(
                        (moose.element(prd), 'p', countuniqItem[prd]))

                if (baseObj == 'CplxEnzBase'):
                    uniqItem, countuniqItem = countitems(items, 'toEnz')
                    for enzpar in uniqItem:
                        sublist.append((moose.element(enzpar), 't',
                                        countuniqItem[enzpar]))

                    uniqItem, countuniqItem = countitems(items, 'cplxDest')
                    for cplx in uniqItem:
                        prdlist.append(
                            (moose.element(cplx), 'cplx', countuniqItem[cplx]))

                if (baseObj == 'EnzBase'):
                    uniqItem, countuniqItem = countitems(items, 'enzDest')
                    for enzpar in uniqItem:
                        sublist.append((moose.element(enzpar), 't',
                                        countuniqItem[enzpar]))
                cntDict[items] = sublist, prdlist
        elif baseObj == 'Function':
            for items in moose.wildcardFind(path):
                sublist = []
                prdlist = []
                item = items.path + '/x[0]'
                uniqItem, countuniqItem = countitems(item, 'input')
                for funcpar in uniqItem:
                    sublist.append((moose.element(funcpar), 'sts',
                                    countuniqItem[funcpar]))

                uniqItem, countuniqItem = countitems(items, 'valueOut')
                for funcpar in uniqItem:
                    prdlist.append((moose.element(funcpar), 'stp',
                                    countuniqItem[funcpar]))
                cntDict[items] = sublist, prdlist

        # elif baseObj == 'Function':
        #     #ZombieSumFunc adding inputs
        #     inputlist = []
        #     outputlist = []
        #     funplist = []
        #     nfunplist = []
        #     for items in moose.wildcardFind(path):
        #         for funplist in moose.element(items).neighbors['valueOut']:
        #             for func in funplist:
        #                 funcx = moose.element(items.path+'/x[0]')
        #                 uniqItem,countuniqItem = countitems(funcx,'input')
        #                 for inPut in uniqItem:
        #                     inputlist.append((inPut,'st',countuniqItem[inPut]))
        #             cntDict[func] = inputlist
        else:
            for tab in moose.wildcardFind(path):
                tablist = []
                uniqItem, countuniqItem = countitems(tab, 'output')
                for tabconnect in uniqItem:
                    tablist.append((moose.element(tabconnect), 'tab',
                                    countuniqItem[tabconnect]))
                cntDict[tab] = tablist
Exemplo n.º 48
0
def moose_main(corticalinput):
    import numpy as np
    import matplotlib.pyplot as plt
    # plt.ion()

    import moose

    from moose_nerp.prototypes import (create_model_sim,
                                       clocks,
                                       inject_func,
                                       create_network,
                                       tables,
                                       net_output)
    from moose_nerp import d1opt as model
    from moose_nerp import str_net as net

    # additional, optional parameter overrides specified from with python terminal
    # model.Condset.D1.NaF[model.param_cond.prox] /= 3
    # model.Condset.D1.KaS[model.param_cond.prox] *= 3

    net.connect_dict['D1']['ampa']['extern1'].dend_loc.postsyn_fraction = 0.8
    net.param_net.tt_Ctx_SPN.filename = corticalinput
    print('cortical_fraction = {}'.format(net.connect_dict['D1']['ampa']['extern1'].dend_loc.postsyn_fraction))
    model.synYN = True
    model.plasYN = True
    model.calYN = True
    model.spineYN = True
    net.single = True
    create_model_sim.setupOptions(model)
    param_sim = model.param_sim
    param_sim.useStreamer = True
    param_sim.plotdt = .1e-3
    param_sim.stim_loc = model.NAME_SOMA
    param_sim.stim_paradigm = 'inject'
    param_sim.injection_current = [0]  # [-0.2e-9, 0.26e-9]
    param_sim.injection_delay = 0.2
    param_sim.injection_width = 0.4
    param_sim.simtime = 21
    net.num_inject = 0
    net.confile = 'str_connect_plas_simd1opt_{}_corticalfraction_{}'.format(net.param_net.tt_Ctx_SPN.filename, 0.8)

    if net.num_inject == 0:
        param_sim.injection_current = [0]
    #################################-----------create the model: neurons, and synaptic inputs
    model = create_model_sim.setupNeurons(model, network=not net.single)
    all_neur_types = model.neurons
    # FSIsyn,neuron = cell_proto.neuronclasses(FSI)
    # all_neur_types.update(neuron)
    population, connections, plas = create_network.create_network(model, net, all_neur_types)

    ###### Set up stimulation - could be current injection or plasticity protocol
    # set num_inject=0 to avoid current injection
    if net.num_inject < np.inf:
        inject_pop = inject_func.inject_pop(population['pop'], net.num_inject)
    else:
        inject_pop = population['pop']
    # Does setupStim work for network?
    # create_model_sim.setupStim(model)
    pg = inject_func.setupinj(model, param_sim.injection_delay, param_sim.injection_width, inject_pop)
    moose.showmsg(pg)

    ##############--------------output elements
    if net.single:
        # fname=model.param_stim.Stimulation.Paradigm.name+'_'+model.param_stim.location.stim_dendrites[0]+'.npz'
        # simpath used to set-up simulation dt and hsolver
        simpath = ['/' + neurotype for neurotype in all_neur_types]
        create_model_sim.setupOutput(model)
    else:  # population of neurons
        spiketab, vmtab, plastab, catab = net_output.SpikeTables(model, population['pop'], net.plot_netvm, plas,
                                                                 net.plots_per_neur)
        # simpath used to set-up simulation dt and hsolver
        simpath = [net.netname]
        clocks.assign_clocks(simpath, param_sim.simdt, param_sim.plotdt, param_sim.hsolve, model.param_cond.NAME_SOMA)
    if model.synYN and (param_sim.plot_synapse or net.single):
        # overwrite plastab above, since it is empty
        syntab, plastab, stp_tab = tables.syn_plastabs(connections, model)
        nonstim_plastab = tables.nonstimplastabs(plas)

    # Streamer to prevent Tables filling up memory on disk
    # This is a hack, should be better implemented
    if param_sim.useStreamer == True:
        allTables = moose.wildcardFind('/##[ISA=Table]')
        streamer = moose.Streamer('/streamer')
        streamer.outfile = 'plas_simd1opt_{}_corticalfraction_{}.npy'.format(net.param_net.tt_Ctx_SPN.filename, 0.8)
        moose.setClock(streamer.tick, 0.1)
        for t in allTables:
            if any(s in t.path for s in ['plas', 'VmD1_0', 'extern', 'Shell_0']):
                streamer.addTable(t)
            else:
                t.tick = -2

    ################### Actually run the simulation
    def run_simulation(injection_current, simtime):
        print(u'◢◤◢◤◢◤◢◤ injection_current = {} ◢◤◢◤◢◤◢◤'.format(injection_current))
        pg.firstLevel = injection_current
        moose.reinit()
        moose.start(simtime, True)

    traces, names = [], []
    for inj in param_sim.injection_current:
        run_simulation(injection_current=inj, simtime=param_sim.simtime)

    weights = [w.value for w in moose.wildcardFind('/##/plas##[TYPE=Function]')]
    plt.figure()
    plt.hist(weights, bins=100)
    plt.title('plas_sim_{}_corticalfraction_{}'.format(net.param_net.tt_Ctx_SPN.filename, cortical_fraction))
    plt.savefig('plas_simd1opt_{}_corticalfraction_{}.png'.format(net.param_net.tt_Ctx_SPN.filename, 0.8))
    if param_sim.useStreamer == True:
        import atexit
        atexit.register(moose.quit)
    return weights
Exemplo n.º 49
0
def makeNeuroMeshModel():
    diffLength = 10e-6  # Aim for 2 soma compartments.
    elec = loadElec()
    loadChem(diffLength)
    neuroCompt = moose.element('/model/chem/dend')
    neuroCompt.diffLength = diffLength
    neuroCompt.cellPortion(elec, '/model/elec/#')
    for x in moose.wildcardFind('/model/chem/##[ISA=PoolBase]'):
        if (x.diffConst > 0):
            x.diffConst = 1e-11
    for x in moose.wildcardFind('/model/chem/##/Ca'):
        x.diffConst = 1e-10

    # Put in dend solvers
    ns = neuroCompt.numSegments
    ndc = neuroCompt.numDiffCompts
    print 'ns = ', ns, ', ndc = ', ndc
    assert (neuroCompt.numDiffCompts == neuroCompt.mesh.num)
    assert (ns == 36)  #
    assert (ndc == 278)  #
    nmksolve = moose.Ksolve('/model/chem/dend/ksolve')
    nmdsolve = moose.Dsolve('/model/chem/dend/dsolve')
    nmstoich = moose.Stoich('/model/chem/dend/stoich')
    nmstoich.compartment = neuroCompt
    nmstoich.ksolve = nmksolve
    nmstoich.dsolve = nmdsolve
    nmstoich.path = "/model/chem/dend/##"
    print 'done setting path, numPools = ', nmdsolve.numPools
    assert (nmdsolve.numPools == 1)
    assert (nmdsolve.numAllVoxels == ndc)
    assert (nmstoich.numAllPools == 1)
    # oddly, numLocalFields does not work.
    ca = moose.element('/model/chem/dend/DEND/Ca')
    assert (ca.numData == ndc)

    # Put in spine solvers. Note that these get info from the neuroCompt
    spineCompt = moose.element('/model/chem/spine')
    sdc = spineCompt.mesh.num
    print 'sdc = ', sdc
    assert (sdc == 13)
    smksolve = moose.Ksolve('/model/chem/spine/ksolve')
    smdsolve = moose.Dsolve('/model/chem/spine/dsolve')
    smstoich = moose.Stoich('/model/chem/spine/stoich')
    smstoich.compartment = spineCompt
    smstoich.ksolve = smksolve
    smstoich.dsolve = smdsolve
    smstoich.path = "/model/chem/spine/##"
    print 'spine num Pools = ', smstoich.numAllPools, smdsolve.numPools
    assert (smstoich.numAllPools == 35)
    assert (smdsolve.numPools == 30)
    assert (smdsolve.numAllVoxels == sdc)

    # Put in PSD solvers. Note that these get info from the neuroCompt
    psdCompt = moose.element('/model/chem/psd')
    pdc = psdCompt.mesh.num
    assert (pdc == 13)
    pmksolve = moose.Ksolve('/model/chem/psd/ksolve')
    pmdsolve = moose.Dsolve('/model/chem/psd/dsolve')
    pmstoich = moose.Stoich('/model/chem/psd/stoich')
    pmstoich.compartment = psdCompt
    pmstoich.ksolve = pmksolve
    pmstoich.dsolve = pmdsolve
    pmstoich.path = "/model/chem/psd/##"
    print 'psd num Pools = ', pmstoich.numAllPools, pmdsolve.numPools
    assert (pmstoich.numAllPools == 55)
    assert (pmdsolve.numPools == 48)
    assert (pmdsolve.numAllVoxels == pdc)
    foo = moose.element('/model/chem/psd/Ca')
    print 'PSD: numfoo = ', foo.numData
    print 'PSD: numAllVoxels = ', pmksolve.numAllVoxels

    # Put in junctions between the diffusion solvers
    nmdsolve.buildNeuroMeshJunctions(smdsolve, pmdsolve)
    """
	CaNpsd = moose.vec( '/model/chem/psdMesh/PSD/PP1_PSD/CaN' )
	print 'numCaN in PSD = ', CaNpsd.nInit, ', vol = ', CaNpsd.volume
	CaNspine = moose.vec( '/model/chem/spine/SPINE/CaN_BULK/CaN' )
	print 'numCaN in spine = ', CaNspine.nInit, ', vol = ', CaNspine.volume
	"""

    ##################################################################
    # set up adaptors
    aCa = moose.Adaptor('/model/chem/spine/adaptCa', sdc)
    adaptCa = moose.vec('/model/chem/spine/adaptCa')
    chemCa = moose.vec('/model/chem/spine/Ca')
    #print 'aCa = ', aCa, ' foo = ', foo, "len( ChemCa ) = ", len( chemCa ), ", numData = ", chemCa.numData, "len( adaptCa ) = ", len( adaptCa )
    assert (len(adaptCa) == sdc)
    assert (len(chemCa) == sdc)
    for i in range(sdc):
        elecCa = moose.element('/model/elec/spine_head_14_' + str(i + 1) +
                               '/NMDA_Ca_conc')
        #print elecCa
        moose.connect(elecCa, 'concOut', adaptCa[i], 'input', 'Single')
    moose.connect(adaptCa, 'output', chemCa, 'setConc', 'OneToOne')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 0.00008  # 80 nM offset in chem.
    adaptCa.scale = 5e-3  # 520 to 0.0052 mM
    #print adaptCa.outputOffset

    moose.le('/model/chem/dend/DEND')

    compts = neuroCompt.elecComptList
    begin = neuroCompt.startVoxelInCompt
    end = neuroCompt.endVoxelInCompt
    aCa = moose.Adaptor('/model/chem/dend/DEND/adaptCa', len(compts))
    adaptCa = moose.vec('/model/chem/dend/DEND/adaptCa')
    chemCa = moose.vec('/model/chem/dend/DEND/Ca')
    #print 'aCa = ', aCa, ' foo = ', foo, "len( ChemCa ) = ", len( chemCa ), ", numData = ", chemCa.numData, "len( adaptCa ) = ", len( adaptCa )
    assert (len(chemCa) == ndc)
    for i in zip(compts, adaptCa, begin, end):
        name = i[0].path + '/Ca_conc'
        if (moose.exists(name)):
            elecCa = moose.element(name)
            #print i[2], i[3], '   ', elecCa
            #print i[1]
            moose.connect(elecCa, 'concOut', i[1], 'input', 'Single')
            for j in range(i[2], i[3]):
                moose.connect(i[1], 'output', chemCa[j], 'setConc', 'Single')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 0.00008  # 80 nM offset in chem.
    adaptCa.scale = 20e-6  # 10 arb units to 2 uM.
Exemplo n.º 50
0
def writePool(modelpath,f,volIndex,sceneitems):
    error = ""
    color = ""
    textcolor = ""

    for p in moose.wildcardFind(modelpath+'/##[0][ISA=PoolBase]'):
        if findCompartment(p) == moose.element('/'):
            error = error + " \n "+p.path+ " doesn't have compartment ignored to write to genesis"
        else:
            slave_enable = 0
            if (p.className == "BufPool" or p.className == "ZombieBufPool"):
                pool_children = p.children
                if pool_children== 0:
                    slave_enable = 4
                else:
                    for pchild in pool_children:
                        if not(pchild.className == "ZombieFunction") and not(pchild.className == "Function"):
                            slave_enable = 4
                        else:
                            slave_enable = 0
                            break
            if (p.parent.className != "Enz" and p.parent.className !='ZombieEnz'):
                #Assuming "p.parent.className !=Enzyme is cplx which is not written to genesis"

                # x = sceneitems[p]['x']
                # y = sceneitems[p]['y']
                # if sceneitems != None:
                #     value = sceneitems[p]
                #     x = calPrime(value['x'])
                #     y = calPrime(value['y'])
                    
                pinfo = p.path+'/info'
                if moose.exists(pinfo):
                    x = sceneitems[p]['x']
                    y = sceneitems[p]['y']
                else:
                    x = 0
                    y = 0
                    error = error  + " \n x and y co-ordinates are not specified for `" + p.name+ "` zero will be assigned"+ " \n "

                if moose.exists(pinfo):
                    color = moose.Annotator(pinfo).getField('color')
                    color = getColorCheck(color,GENESIS_COLOR_SEQUENCE)
                    textcolor = moose.Annotator(pinfo).getField('textColor')
                    textcolor = getColorCheck(textcolor,GENESIS_COLOR_SEQUENCE)
                poolsCmpt = findCompartment(p)
                geometryName = volIndex[float(poolsCmpt.volume)]
                volume = p.volume * NA * 1e-3
                if color == "" or color == " ":
                    color = getRandomColor()
                if textcolor == ""  or textcolor == " ":
                    textcolor = getRandomColor()
                f.write("simundump kpool /kinetics/" + trimPath(p) + " 0 " +
                        str(p.diffConst) + " " +
                        str(0) + " " +
                        str(0) + " " +
                        str(0) + " " +
                        str(p.nInit) + " " +
                        str(0) + " " + str(0) + " " +
                        str(volume)+ " " +
                        str(slave_enable) +
                        " /kinetics"+ geometryName + " " +
                        str(color) +" " + str(textcolor) + " " + str(int(x)) + " " + str(int(y)) + " "+ str(0)+"\n")
    return error
Exemplo n.º 51
0
def writeStimulus(modelpath,f):
    error = ""
    if len(moose.wildcardFind(modelpath+'/##[0][ISA=StimulusTable]')):
        error = error +'\n StimulusTable is not written into genesis. This is in Todo List'
    return error
Exemplo n.º 52
0
def writeEnz( modelpath,f,sceneitems):
    error = ""
    enzList = moose.wildcardFind(modelpath+'/##[0][ISA=EnzBase]')
    for enz in enzList:
        if findCompartment(enz) == moose.element('/'):
            error = error + " \n "+enz.path+ " doesn't have compartment ignored to write to genesis"
        else:
            x = random.randrange(0,10)
            y = random.randrange(0,10)
            textcolor = ""
            color = ""
            k1 = 0;
            k2 = 0;
            k3 = 0;
            nInit = 0;
            concInit = 0;
            n = 0;
            conc = 0;
            if len(moose.element(enz).neighbors['enzDest']) == 1:
                enzParent = moose.element(moose.element(enz).neighbors['enzDest'][0])
    
            if not (isinstance(enzParent,moose.PoolBase)):
                print(" raise exception enz doesn't have pool as parent %s",moose.element(enz).path)
                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
                    if enz.neighbors['cplx']:
                        cplx = enz.neighbors['cplx'][0]
                        nInit = cplx.nInit[0];
                    else:
                        cplx = moose.Pool(enz.path+"/cplx")
                        moose.Annotator(cplx.path+'/info')
                        moose.connect( enz, 'cplx', cplx, 'reac' )
                        nInit = cplx.nInit

                einfo = enz.path+'/info'
                if moose.exists(einfo):
                    x = sceneitems[enz]['x']
                    y = sceneitems[enz]['y']
                    color = moose.Annotator(einfo).getField('color')
                    color = getColorCheck(color,GENESIS_COLOR_SEQUENCE)

                    textcolor = moose.Annotator(einfo).getField('textColor')
                    textcolor = getColorCheck(textcolor,GENESIS_COLOR_SEQUENCE)
                else:
                    error = error + "\n x and y co-ordinates are not specified for `" + enz.name+ "` zero will be assigned \n "
                if color == "" or color == " ":
                    color = getRandomColor()
                if textcolor == ""  or textcolor == " ":
                    textcolor = getRandomColor()
            
                f.write("simundump kenz /kinetics/" + trimPath(enz) + " " + str(int(0))+  " " +
                    str(concInit) + " " +
                    str(conc) + " " +
                    str(nInit) + " " +
                    str(n) + " " +
                    str(vol) + " " +
                    str(k1) + " " +
                    str(k2) + " " +
                    str(k3) + " " +
                    str(0) + " " +
                    str(isMichaelisMenten) + " " +
                    "\"\"" + " " +
                    str(textcolor) + " " + str(color) + " \"\"" +
                    " " + str(int(x)) + " " + str(int(y)) + " "+str(int(0))+"\n")
    return enzList,error
def main():
    # Simulation information.
    simtime = 0.1
    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)
    RA = 4

    # Stimulus information
    inj_delay = 20E-3
    inj_amp = 1E-9
    inj_width = 40E-3

    # Create cell
    chicken_model = create_swc_model(
        root_name='E19',
        file_name='E19-cell_filling-caudal.CNG.swc',
        RM=RM,
        CM=CM,
        RA=RA,
        ELEAK=Em,
        initVM=Em)
    soma = moose.element('/E19[0]/soma')

    # Create channels
    channels_set = create_set_of_channels(channel_settings, VDIVS, VMIN, VMAX)

    # Fetch all compartment paths.
    moose_paths = []
    for comp in moose.wildcardFind(chicken_model.path +
                                   '/#[TYPE=Compartment]'):
        moose_paths.append(comp.path)

    # Copy all channels to compartments.
    for channel_name, channel_obj in channels_set.items():
        copy_connect_channel_moose_paths(channel_obj, channel_name,
                                         moose_paths)

    # 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')
    chicken_dend_table = create_output_table(table_element='/output',
                                             table_name='chkdend')

    # Connect output tables
    moose.connect(soma_v_table, 'requestOut', soma, 'getVm')
    moose.connect(soma_i_table, 'requestOut', pulse_inject, 'getOutputValue')
    moose.connect(chicken_dend_table, 'requestOut',
                  moose.element('/E19[0]/dend_36_0'), 'getVm')

    # 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,
                           chicken_dend_table,
                           title="soma vs dend new k1 chan g_bar = 0.05")
    v_plot.legend(['soma_v', 'i', 'dend_v'])
    plt.grid(True)
    plt.show()
def displayPlots():
    for x in moose.wildcardFind('/graphs/##[ISA=Table]'):
        t = numpy.arange(0, x.vector.size, 1) * x.dt
        pylab.plot(t, x.vector, label=x.name)
    pylab.legend()
    pylab.show()
Exemplo n.º 55
0
def main():
    """
    This example illustrates loading, and running a kinetic model 
    for a delayed -ve feedback oscillator, defined in kkit format. 
    The model is one by  Boris N. Kholodenko from 
    Eur J Biochem. (2000) 267(6):1583-8 

    This model has a high-gain MAPK stage,
    whose effects are visible whem one looks at the traces from
    successive stages in the plots. The upstream pools have small
    early peaks, and the downstream pools have large delayed ones.
    The negative feedback step is mediated by a simple binding reaction
    of the end-product of oscillation with an upstream activator.

    We use the gsl solver here. The model already
    defines some plots and sets the runtime to 4000 seconds.
    The model does not really play nicely with the GSSA solver, since it
    involves some really tiny amounts of the MAPKKK.

    Things to do with the model:

        - Look at model once it is loaded in::

                moose.le( '/model' )
                moose.showfields( '/model/kinetics/MAPK/MAPK' )

        - Behold the amplification properties of the cascade.
          Could do this by blocking the feedback step and giving a 
          small pulse input.
        - Suggest which parameters you would alter to change
          the period of the oscillator:

            - Concs of various molecules, for example::
            
                ras_MAPKKKK = moose.element( '/model/kinetics/MAPK/Ras_dash_MKKKK' )
                moose.showfields( ras_MAPKKKK )
                ras_MAPKKKK.concInit = 1e-5
            - Feedback reaction rates
            - Rates of all the enzymes::

                for i in moose.wildcardFind( '/##[ISA=EnzBase]'):
                     i.kcat *= 10.0
    """

    solver = "gsl"
    mfile = '../../Genesis_files/Kholodenko.g'
    runtime = 5000.0
    if (len(sys.argv) >= 2):
        solver = sys.argv[1]
    modelId = moose.loadModel(mfile, 'model', solver)
    dt = moose.element('/clock').tickDt[18]
    moose.reinit()
    moose.start(runtime)

    # Display all plots.
    img = mpimg.imread('Kholodenko_tut.png')
    fig = plt.figure(figsize=(12, 10))
    png = fig.add_subplot(211)
    imgplot = plt.imshow(img)
    ax = fig.add_subplot(212)
    x = moose.wildcardFind('/model/#graphs/conc#/#')
    t = numpy.arange(0, x[0].vector.size, 1) * dt
    ax.plot(t, x[0].vector * 100, 'b-', label='Ras-MKKK * 100')
    ax.plot(t, x[1].vector, 'y-', label='MKKK-P')
    ax.plot(t, x[2].vector, 'm-', label='MKK-PP')
    ax.plot(t, x[3].vector, 'r-', label='MAPK-PP')
    plt.ylabel('Conc (mM)')
    plt.xlabel('Time (seconds)')
    pylab.legend()
    pylab.show()
Exemplo n.º 56
0
def mooseWriteKkit( modelpath, filename, sceneitems={}):
    global foundmatplotlib_
    if not foundmatplotlib_:
        print('No maplotlib found.'
            '\nThis module can be installed by following command in terminal:'
            '\n\t sudo apt install python-maplotlib', "")
        return False
    else:
        error = ""

        if filename.rfind('.') != -1:
            filename = filename[:filename.rfind('.')]
        else:
            filename = filename[:len(filename)]
        filename = filename+'.g'
        global NA
        NA = 6.0221415e23
        global cmin,cmax,xmin,xmax,ymin,ymax
        cmin, xmin, ymin = 0, 0, 0
        cmax, xmax, ymax = 1, 1, 1
        moose.fixXreacs.restoreXreacs(modelpath)
        compt = moose.wildcardFind(modelpath+'/##[0][ISA=ChemCompt]')
        maxVol = estimateDefaultVol(compt)
        positionInfoExist = True
        if compt:
            if bool(sceneitems):
                cmin,cmax,xmin1,xmax1,ymin1,ymax1 = findMinMax(sceneitems)
            elif not bool(sceneitems):
                srcdesConnection = {}
                setupItem(modelpath,srcdesConnection)
                meshEntry,xmin,xmax,ymin,ymax,positionInfoExist,sceneitems = setupMeshObj(modelpath)
                if not positionInfoExist:
                    #cmin,cmax,sceneitems = autoCoordinates(meshEntry,srcdesConnection)
                    sceneitems = autoCoordinates(meshEntry,srcdesConnection)

            if not positionInfoExist:
                # if position are not from kkit, then zoom factor is applied while
                # writing to genesis. Like if position is from pyqtSceneItem or auto-coordinates
                cmin,cmax,xmin1,xmax1,ymin1,ymax1 = findMinMax(sceneitems)
                for k,v in list(sceneitems.items()):
                    anno = moose.element(k.path+'/info')
                    #x1 = calPrime(v['x'])
                    #y1 = calPrime(v['y'])
                    #sceneitems[k]['x'] = x1
                    #sceneitems[k]['y'] = y1

            f = open(filename, 'w')
            writeHeader (f,maxVol)

            gtId_vol = writeCompartment(modelpath,compt,f)
            errors = ""
            error = writePool(modelpath,f,gtId_vol,sceneitems)
            errors = errors+error

            reacList,error= writeReac(modelpath,f,sceneitems)
            errors = errors+error
            
            enzList,error = writeEnz(modelpath,f,sceneitems)
            errors = errors+error

            chanList, error = writeConcChan(modelpath,f,sceneitems)
            errors = errors+error
            
            error = writeStimulus(modelpath,f)
            errors = errors+error

            error = writeSumtotal(modelpath,f)
            errors = errors+error

            #writeSumtotal(modelpath,f)
            f.write("simundump xgraph /graphs/conc1 0 0 99 0.001 0.999 0\n"
                    "simundump xgraph /graphs/conc2 0 0 100 0 1 0\n")
            tgraphs = moose.wildcardFind(modelpath+'/##[0][ISA=Table2]')
            first, second = " ", " "
            if tgraphs:
                first,second = writeplot(tgraphs,f)
            if first:
                f.write(first)
            f.write("simundump xgraph /moregraphs/conc3 0 0 100 0 1 0\n"
                    "simundump xgraph /moregraphs/conc4 0 0 100 0 1 0\n")
            if second:
                f.write(second)
            f.write("simundump xcoredraw /edit/draw 0 -6 4 -2 6\n"
                    "simundump xtree /edit/draw/tree 0 \\\n"
                    "  /kinetics/#[],/kinetics/#[]/#[],/kinetics/#[]/#[]/#[][TYPE!=proto],/kinetics/#[]/#[]/#[][TYPE!=linkinfo]/##[] \"edit_elm.D <v>; drag_from_edit.w <d> <S> <x> <y> <z>\" auto 0.6\n"
                    "simundump xtext /file/notes 0 1\n")
            storeReacMsg(reacList,f)
        
            storeEnzMsg(enzList,f)
            storeChanMsg(chanList,f)
            if tgraphs:
                storePlotMsgs(tgraphs,f)
            writeFooter1(f)
            writeNotes(modelpath,f)
            writeFooter2(f)
            print('Written to file '+filename)
            return errors, True
        else:
            print("Warning: writeKkit:: No model found on " , modelpath)
            return False
Exemplo n.º 57
0
def makeGraphics(cPlotDt, ePlotDt):
    plt.ion()
    fig = plt.figure(figsize=(10, 16))
    chem = fig.add_subplot(411)
    chem.set_ylim(0, 0.006)
    plt.ylabel('Conc (mM)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/chem/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * cPlotDt
        line1, = chem.plot(pos, x.vector, label=x.name)
    plt.legend()

    elec = fig.add_subplot(412)
    plt.ylabel('Vm (V)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/elec/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * ePlotDt
        line1, = elec.plot(pos, x.vector, label=x.name)
    plt.legend()

    ca = fig.add_subplot(413)
    plt.ylabel('[Ca] (mM)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/ca/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * ePlotDt
        line1, = ca.plot(pos, x.vector, label=x.name)
    plt.legend()

    lenplot = fig.add_subplot(414)
    plt.ylabel('Ca (mM )')
    plt.xlabel('Voxel#)')

    spineCa = moose.vec('/model/chem/spine/Ca')
    dendCa = moose.vec('/model/chem/dend/DEND/Ca')
    line1, = lenplot.plot(range(len(spineCa)), spineCa.conc, label='spine')
    line2, = lenplot.plot(range(len(dendCa)), dendCa.conc, label='dend')

    ca = [
        x.Ca * 0.0001
        for x in moose.wildcardFind('/model/elec/##[ISA=CaConcBase]')
    ]
    line3, = lenplot.plot(range(len(ca)), ca, label='elec')

    spineCaM = moose.vec('/model/chem/spine/CaM_dash_Ca4')
    line4, = lenplot.plot(range(len(spineCaM)),
                          spineCaM.conc,
                          label='spineCaM')
    psdCaM = moose.vec('/model/chem/psd/CaM_dash_Ca4')
    line5, = lenplot.plot(range(len(psdCaM)), psdCaM.conc, label='psdCaM')
    plt.legend()

    fig.canvas.draw()
    raw_input()
    '''
        for x in moose.wildcardFind( '/graphs/##[ISA=Table]' ):
            t = numpy.arange( 0, x.vector.size, 1 )
            pylab.plot( t, x.vector, label=x.name )
        pylab.legend()
        pylab.show()
        '''

    print 'All done'
Exemplo n.º 58
0
def setupMeshObj(modelRoot):
    ''' Setup compartment and its members pool,reaction,enz cplx under self.meshEntry dictionaries \
    self.meshEntry with "key" as compartment,
    value is key2:list where key2 represents moose object type,list of objects of a perticular type
    e.g self.meshEntry[meshEnt] = { 'reaction': reaction_list,'enzyme':enzyme_list,'pool':poollist,'cplx': cplxlist }
    '''
    xmin = 0.0
    xmax = 1.0
    ymin = 0.0
    ymax = 1.0
    listOfitems = {}
    positionInfoExist = True
    meshEntry = {}
    if meshEntry:
        meshEntry.clear()
    else:
        meshEntry = {}
    xcord = []
    ycord = []
    meshEntryWildcard = '/##[ISA=ChemCompt]'
    if modelRoot != '/':
        meshEntryWildcard = modelRoot + meshEntryWildcard
    for meshEnt in moose.wildcardFind(meshEntryWildcard):
        mollist = []
        realist = []
        enzlist = []
        cplxlist = []
        tablist = []
        funclist = []

        mol_cpl = moose.wildcardFind(meshEnt.path + '/##[ISA=PoolBase]')
        funclist = moose.wildcardFind(meshEnt.path + '/##[ISA=Function]')
        enzlist = moose.wildcardFind(meshEnt.path + '/##[ISA=EnzBase]')
        realist = moose.wildcardFind(meshEnt.path + '/##[ISA=ReacBase]')
        tablist = moose.wildcardFind(meshEnt.path + '/##[ISA=StimulusTable]')
        if mol_cpl or funclist or enzlist or realist or tablist:
            for m in mol_cpl:
                objInfo = None
                # if m.parent.isA['CplxEnzBase']: # New bindings
                if moose.element(m.parent).isA['CplxEnzBase']:
                    cplxlist.append(m)
                    objInfo = m.parent.path + '/info'
                elif m.isA['PoolBase']:
                    mollist.append(m)
                    objInfo = m.path + '/info'
                if objInfo is not None and moose.exists(objInfo):
                    listOfitems[moose.element(
                        moose.element(objInfo).parent)] = {
                            'x': xyPosition(objInfo, 'x'),
                            'y': xyPosition(objInfo, 'y')
                        }

                xcord.append(xyPosition(objInfo, 'x'))
                ycord.append(xyPosition(objInfo, 'y'))

            getxyCord(xcord, ycord, funclist, listOfitems)
            getxyCord(xcord, ycord, enzlist, listOfitems)
            getxyCord(xcord, ycord, realist, listOfitems)
            getxyCord(xcord, ycord, tablist, listOfitems)

            meshEntry[meshEnt] = {
                'enzyme': enzlist,
                'reaction': realist,
                'pool': mollist,
                'cplx': cplxlist,
                'table': tablist,
                'function': funclist
            }
            positionInfoExist = not(len(np.nonzero(xcord)[0]) == 0 \
                and len(np.nonzero(ycord)[0]) == 0)
            if positionInfoExist:
                xmin = min(xcord)
                xmax = max(xcord)
                ymin = min(ycord)
                ymax = max(ycord)
    return meshEntry, xmin, xmax, ymin, ymax, positionInfoExist, listOfitems
Exemplo n.º 59
0
def displayPlots():
    for x in moose.wildcardFind('/model/graphs/conc#'):
        t = numpy.arange(0, x.vector.size, 1)  #sec
        pylab.plot(t, x.vector, label=x.name)
Exemplo n.º 60
0
def createObj(scene, view, modelpath, string, pos, layoutPt):
    event_pos = pos
    num = 0
    ret_string = " "
    pos = view.mapToScene(event_pos)
    itemAt = view.sceneContainerPt.itemAt(pos)
    chemMesh = moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]')
    deleteSolver(modelpath)
    mobj = ""

    if itemAt != None:
        itemAtView = view.sceneContainerPt.itemAt(view.mapToScene(event_pos))
        itemClass = type(itemAtView).__name__
        if (itemClass == 'QGraphicsRectItem'):
            mobj = itemAtView.parentItem().mobj
        elif (itemClass == 'QGraphicsSvgItem'):
            mobj = itemAtView.parent().mobj
        else:
            mobj = itemAtView.mobj
    if string == "CubeMesh" or string == "CylMesh":
        ret_string, num = findUniqId(moose.element(modelpath), "Compartment",
                                     0)
        comptexist = moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]')
        if not len(comptexist):
            if itemAt != None:
                QtGui.QMessageBox.information(
                    None, 'Drop Not possible',
                    '\'{newString}\' currently single compartment model building is allowed'
                    .format(newString=string), QtGui.QMessageBox.Ok)
                return
            else:
                mobj = moose.element(modelpath)
        else:
            QtGui.QMessageBox.information(
                None, 'Drop Not possible',
                '\'{newString}\' currently single compartment model building is allowed'
                .format(newString=string), QtGui.QMessageBox.Ok)
            return

    elif string == "Pool" or string == "BufPool" or string == "Reac" or string == "StimulusTable":
        if itemAt == None:
            QtGui.QMessageBox.information(
                None, 'Drop Not possible',
                '\'{newString}\' has to have compartment as its parent'.format(
                    newString=string), QtGui.QMessageBox.Ok)
            return
        else:
            mobj = findCompartment(mobj)
            ret_string, num = findUniqId(mobj, string, num)

    elif string == "Function":
        mobj = findCompartment(mobj)
        ret_string, num = findUniqId(mobj, string, num)
        '''
        if itemAt != None:
            if ((mobj).className != "BufPool"):    
                QtGui.QMessageBox.information(None,'Drop Not possible','\'{newString}\' has to have BufPool as its parent'.format(newString =string),QtGui.QMessageBox.Ok)
                return
            else:
                ret_string,num = findUniqId(mobj,string,num)
        else:
            QtGui.QMessageBox.information(None,'Drop Not possible','\'{newString}\' has to have BufPool as its parent'.format(newString =string),QtGui.QMessageBox.Ok)
            return
        '''
    elif string == "Enz" or string == "MMenz":
        if itemAt != None:
            if ((mobj).className != "Pool" and (mobj).className != "BufPool"):
                QtGui.QMessageBox.information(
                    None, 'Drop Not possible',
                    '\'{newString}\' has to have Pool as its parent'.format(
                        newString=string), QtGui.QMessageBox.Ok)
                return
            else:
                ret_string, num = findUniqId(mobj, string, num)
        else:
            QtGui.QMessageBox.information(
                None, 'Drop Not possible',
                '\'{newString}\' has to have Pool as its parent'.format(
                    newString=string), QtGui.QMessageBox.Ok)
            return

    if ret_string != " ":
        checkCreate(scene, view, modelpath, mobj, string, ret_string, num,
                    event_pos, layoutPt)