Ejemplo n.º 1
0
def createSpecies(basePath, model, comptSbmlidMooseIdMap, specInfoMap,
                  modelAnnotaInfo):
    # ToDo:
    # - Need to add group name if exist in pool
    # - Notes
    # print "species "
    if not (model.getNumSpecies()):
        return (False, "number of species is zero")
    else:
        for sindex in range(0, model.getNumSpecies()):
            spe = model.getSpecies(sindex)
            group = ""
            specAnnoInfo = {}
            specAnnoInfo = getObjAnnotation(spe, modelAnnotaInfo)
            if "Group" in specAnnoInfo:
                group = specAnnoInfo["Group"]

            sName = None
            sId = spe.getId()
            if spe.isSetName():
                sName = spe.getName()
                sName = sName.replace(" ", "_space_")

            if spe.isSetCompartment():
                comptId = spe.getCompartment()

            if not (sName):
                sName = sId

            constant = spe.getConstant()
            boundaryCondition = spe.getBoundaryCondition()
            comptEl = comptSbmlidMooseIdMap[comptId]["MooseId"].path
            hasonlySubUnit = spe.getHasOnlySubstanceUnits()
            # "false": is {unit of amount}/{unit of size} (i.e., concentration or density).
            # "true": then the value is interpreted as having a unit of amount only.
            if group:
                if moose.exists(comptEl + '/' + group):
                    comptEl = comptEl + '/' + group
                else:
                    comptEl = (moose.Neutral(comptEl + '/' + group)).path
            if (boundaryCondition):
                poolId = moose.BufPool(comptEl + '/' + sName)
            else:
                poolId = moose.Pool(comptEl + '/' + sName)

            if (spe.isSetNotes):
                pullnotes(spe, poolId)

            if specAnnoInfo:
                if not moose.exists(poolId.path + '/info'):
                    poolInfo = moose.Annotator(poolId.path + '/info')
                else:
                    poolInfo = moose.element(poolId.path + '/info')

                for k, v in list(specAnnoInfo.items()):
                    if k == 'xCord':
                        poolInfo.x = float(v)
                    elif k == 'yCord':
                        poolInfo.y = float(v)
                    elif k == 'bgColor':
                        poolInfo.color = v
                    else:
                        poolInfo.textColor = v

            specInfoMap[sId] = {
                "Mpath": poolId,
                "const": constant,
                "bcondition": boundaryCondition,
                "hassubunit": hasonlySubUnit,
                "comptId": comptSbmlidMooseIdMap[comptId]["MooseId"]
            }
            initvalue = 0.0
            unitfactor, unitset, unittype = transformUnit(spe, hasonlySubUnit)
            if hasonlySubUnit == True:
                if spe.isSetInitialAmount():
                    initvalue = spe.getInitialAmount()
                    # populating nInit, will automatically calculate the
                    # concInit.
                    if not (unitset):
                        # if unit is not set,
                        # default unit is assumed as Mole in SBML
                        unitfactor = pow(6.0221409e23, 1)
                        unittype = "Mole"

                    initvalue = initvalue * unitfactor
                elif spe.isSetInitialConcentration():
                    initvalue = spe.getInitialConcentration()
                    print(
                        " Since hasonlySubUnit is true and concentration is set units are not checked"
                    )
                poolId.nInit = initvalue

            elif hasonlySubUnit == False:
                # ToDo : check 00976
                if spe.isSetInitialAmount():
                    initvalue = spe.getInitialAmount()
                    # initAmount is set we need to convert to concentration
                    initvalue = initvalue / comptSbmlidMooseIdMap[comptId][
                        "size"]

                elif spe.isSetInitialConcentration():
                    initvalue = spe.getInitialConcentration()
                if not unitset:
                    # print " unit is not set"
                    unitfactor = pow(10, -3)

                initvalue = initvalue * unitfactor
                poolId.concInit = initvalue
            else:
                nr = model.getNumRules()
                found = False
                for nrItem in range(0, nr):
                    rule = model.getRule(nrItem)
                    assignRule = rule.isAssignment()
                    if (assignRule):
                        rule_variable = rule.getVariable()
                        if (rule_variable == sId):
                            found = True
                            break

                if not (found):
                    print(
                        "Invalid SBML: Either initialConcentration or initialAmount must be set or it should be found in assignmentRule but non happening for ",
                        sName)
                    return (
                        False,
                        "Invalid SBML: Either initialConcentration or initialAmount must be set or it should be found in assignmentRule but non happening for ",
                        sName)

    return (True, " ")
Ejemplo n.º 2
0
    def setData(self, index, value, role=QtCore.Qt.EditRole):
        if not index.isValid() or index.row() >= len(
                self.fields) or index.column() != 1:
            return False
        field = self.fields[index.row()]
        if (role == QtCore.Qt.CheckStateRole):
            if (index.column() == 1):
                self.checkState_ = value
                return True

        else:
            value = str(
                value.strip())  # convert Qt datastructure to Python string
            if len(value) == 0:
                return False
            if field == "Notes":
                field = "notes"
                ann = moose.Annotator(self.mooseObject.path + '/info')
                oldValue = ann.getField(field)
                value = type(oldValue)(value)
                ann.setField(field, value)
                self.undoStack.append((index, oldValue))
            elif field == "vector":
                for ch in ['[', ']']:
                    if ch in value:
                        value = value.replace(ch, " ")
                value = value.replace(",", " ")
                valuelist = []
                if value.find(',') != -1:
                    valuelist = value.split(",")
                elif value.find(' ') != -1:
                    valuelist = value.split(" ")
                else:
                    valuelist = value
                vectorlist = []
                for d in valuelist:
                    try:
                        float(d)
                        vectorlist.append(float(d))
                    except:
                        pass
                from numpy import array
                a = array(vectorlist)
                self.mooseObject.setField(field, a)

            else:
                oldValue = self.mooseObject.getField(field)
                if field != "isBuffered":
                    value = type(oldValue)(value)
                    self.mooseObject.setField(field, value)
                else:
                    if self.mooseObject.className == "ZombiePool" or self.mooseObject.className == "ZombieBufPool":
                        QMessageBox.warning(
                            None, 'Solver is set, Could not set the value',
                            '\n Unset the solver by clicking \n run widget -> Preferences -> Exponential Euler->Apply'
                        )
                    else:
                        if value.lower() in ("yes", "true", "t", "1"):
                            self.mooseObject.setField(field, True)
                        else:
                            self.mooseObject.setField(field, False)
                self.undoStack.append((index, oldValue))
            if field == 'name':
                self.emit(QtCore.SIGNAL('objectNameChanged(PyQt_PyObject)'),
                          self.mooseObject)
            return True

        #self.dataChanged.emit(index, index)
        return True
Ejemplo n.º 3
0
def checkCreate(scene, view, modelpath, mobj, string, ret_string, num,
                event_pos, layoutPt):
    # The variable 'compt' will be empty when dropping cubeMesh,cyclMesh, but rest it shd be
    # compartment
    # if modelpath.find('/',1) > -1:
    #     modelRoot = modelpath[0:modelpath.find('/',1)]
    # else:
    #     modelRoot = modelpath
    if moose.exists(modelpath + '/info'):
        mType = moose.Annotator((moose.element(modelpath + '/info'))).modeltype
    itemAtView = view.sceneContainerPt.itemAt(view.mapToScene(event_pos))
    pos = view.mapToScene(event_pos)
    modelpath = moose.element(modelpath)
    if num:
        string_num = ret_string + str(num)
    else:
        string_num = ret_string
    if string == "CubeMesh" or string == "CylMesh":
        if string == "CylMesh":
            mobj = moose.CylMesh(modelpath.path + '/' + string_num)
        else:
            mobj = moose.CubeMesh(modelpath.path + '/' + string_num)

        mobj.volume = 1e-15
        mesh = moose.element(mobj.path + '/mesh')
        qGItem = ComptItem(scene,
                           pos.toPoint().x(),
                           pos.toPoint().y(), 100, 100, mobj)
        qGItem.setPen(
            QtGui.QPen(Qt.QColor(66, 66, 66, 100), 1, Qt.Qt.SolidLine,
                       Qt.Qt.RoundCap, Qt.Qt.RoundJoin))
        view.sceneContainerPt.addItem(qGItem)
        qGItem.cmptEmitter.connect(
            qGItem.cmptEmitter,
            QtCore.SIGNAL("qgtextPositionChange(PyQt_PyObject)"),
            layoutPt.positionChange1)
        qGItem.cmptEmitter.connect(
            qGItem.cmptEmitter,
            QtCore.SIGNAL("qgtextItemSelectedChange(PyQt_PyObject)"),
            layoutPt.objectEditSlot)
        compartment = qGItem
        layoutPt.qGraCompt[mobj] = qGItem
        view.emit(QtCore.SIGNAL("dropped"), mobj)

    elif string == "Pool" or string == "BufPool":
        #getting pos with respect to compartment otherwise if compartment is moved then pos would be wrong
        posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        if string == "Pool":
            poolObj = moose.Pool(mobj.path + '/' + string_num)
        else:
            poolObj = moose.BufPool(mobj.path + '/' + string_num)

        poolinfo = moose.Annotator(poolObj.path + '/info')
        #Compartment's one Pool object is picked to get the font size

        qGItem = PoolItem(poolObj, itemAtView)
        layoutPt.mooseId_GObj[poolObj] = qGItem
        posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        bgcolor = getRandColor()
        qGItem.setDisplayProperties(posWrtComp.x(), posWrtComp.y(),
                                    QtGui.QColor('green'), bgcolor)
        poolinfo.color = str(bgcolor.getRgb())
        view.emit(QtCore.SIGNAL("dropped"), poolObj)
        setupItem(modelpath.path, layoutPt.srcdesConnection)
        layoutPt.drawLine_arrow(False)
        x, y = roundoff(qGItem.scenePos(), layoutPt)
        poolinfo.x = x
        poolinfo.y = y
        #Dropping is on compartment then update Compart size
        if isinstance(mobj, moose.ChemCompt):
            compt = layoutPt.qGraCompt[moose.element(mobj)]
            updateCompartmentSize(compt)

    elif string == "Reac":
        posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        reacObj = moose.Reac(mobj.path + '/' + string_num)
        reacinfo = moose.Annotator(reacObj.path + '/info')
        qGItem = ReacItem(reacObj, itemAtView)
        qGItem.setDisplayProperties(posWrtComp.x(), posWrtComp.y(), "white",
                                    "white")
        #if mType == "new_kkit":
        # reacinfo.x = posWrtComp.x()
        # reacinfo.y = posWrtComp.y()
        layoutPt.mooseId_GObj[reacObj] = qGItem
        view.emit(QtCore.SIGNAL("dropped"), reacObj)
        setupItem(modelpath.path, layoutPt.srcdesConnection)
        layoutPt.drawLine_arrow(False)
        #Dropping is on compartment then update Compart size
        if isinstance(mobj, moose.ChemCompt):
            compt = layoutPt.qGraCompt[moose.element(mobj)]
            updateCompartmentSize(compt)
        x, y = roundoff(qGItem.scenePos(), layoutPt)
        reacinfo.x = x
        reacinfo.y = y

    elif string == "StimulusTable":
        posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        tabObj = moose.StimulusTable(mobj.path + '/' + string_num)
        tabinfo = moose.Annotator(tabObj.path + '/info')
        qGItem = TableItem(tabObj, itemAtView)
        qGItem.setDisplayProperties(posWrtComp.x(), posWrtComp.y(),
                                    QtGui.QColor('white'),
                                    QtGui.QColor('white'))
        #if mType == "new_kkit":
        #tabinfo.x = posWrtComp.x()
        #tabinfo.y = posWrtComp.y()
        layoutPt.mooseId_GObj[tabObj] = qGItem
        view.emit(QtCore.SIGNAL("dropped"), tabObj)
        setupItem(modelpath.path, layoutPt.srcdesConnection)
        layoutPt.drawLine_arrow(False)
        #Dropping is on compartment then update Compart size
        if isinstance(mobj, moose.ChemCompt):
            compt = layoutPt.qGraCompt[moose.element(mobj)]
            updateCompartmentSize(compt)
        x, y = roundoff(qGItem.scenePos(), layoutPt)
        tabinfo.x = x
        tabinfo.y = y

    elif string == "Function":
        posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        funcObj = moose.Function(mobj.path + '/' + string_num)
        funcinfo = moose.Annotator(funcObj.path + '/info')
        #moose.connect( funcObj, 'valueOut', mobj ,'setN' )
        poolclass = ["ZombieBufPool", "BufPool"]
        comptclass = ["CubeMesh", "cyclMesh"]
        if mobj.className in poolclass:
            funcParent = layoutPt.mooseId_GObj[element(mobj.path)]
        elif mobj.className in comptclass:
            funcParent = layoutPt.qGraCompt[moose.element(mobj)]
            posWrtComp = funcParent.mapFromScene(pos).toPoint()
            #posWrtComp = (itemAtView.mapFromScene(pos)).toPoint()
        qGItem = FuncItem(funcObj, funcParent)
        #print " function ", posWrtComp.x(),posWrtComp.y()
        qGItem.setDisplayProperties(posWrtComp.x(), posWrtComp.y(),
                                    QtGui.QColor('red'), QtGui.QColor('green'))
        layoutPt.mooseId_GObj[funcObj] = qGItem
        #if mType == "new_kkit":
        #funcinfo.x = posWrtComp.x()
        #funcinfo.y = posWrtComp.y()
        view.emit(QtCore.SIGNAL("dropped"), funcObj)
        setupItem(modelpath.path, layoutPt.srcdesConnection)
        layoutPt.drawLine_arrow(False)
        #Dropping is on compartment then update Compart size
        mooseCmpt = findCompartment(mobj)
        if isinstance(mooseCmpt, moose.ChemCompt):
            compt = layoutPt.qGraCompt[moose.element(mooseCmpt)]
            updateCompartmentSize(compt)
        x, y = roundoff(qGItem.scenePos(), layoutPt)
        funcinfo.x = x
        funcinfo.y = y

    elif string == "Enz" or string == "MMenz":
        #If 2 enz has same pool parent, then pos of the 2nd enz shd be displaced by some position, need to check how to deal with it
        posWrtComp = pos
        enzPool = layoutPt.mooseId_GObj[mobj]
        if ((mobj.parent).className == "Enz"):
            QtGui.QMessageBox.information(
                None, 'Drop Not possible',
                '\'{newString}\' has to have Pool as its parent and not Enzyme Complex'
                .format(newString=string), QtGui.QMessageBox.Ok)
            return
        else:
            enzparent = findCompartment(mobj)
            parentcompt = layoutPt.qGraCompt[enzparent]
        if string == "Enz":
            enzObj = moose.Enz(moose.element(mobj).path + '/' + string_num)
            enzinfo = moose.Annotator(enzObj.path + '/info')
            moose.connect(enzObj, 'enz', mobj, 'reac')
            qGItem = EnzItem(enzObj, parentcompt)
            layoutPt.mooseId_GObj[enzObj] = qGItem
            posWrtComp = pos
            bgcolor = getRandColor()
            qGItem.setDisplayProperties(posWrtComp.x(),
                                        posWrtComp.y() - 40,
                                        QtGui.QColor('green'), bgcolor)
            x, y = roundoff(qGItem.scenePos(), layoutPt)
            enzinfo.x = x
            enzinfo.y = y
            enzinfo.color = str(bgcolor.name())
            enzinfo.textColor = str(QtGui.QColor('green').name())
            #if mType == "new_kkit":
            #enzinfo.x = posWrtComp.x()
            #enzinfo.y = posWrtComp.y()

            #enzinfo.color = str(bgcolor.name())
            e = moose.Annotator(enzinfo)
            #e.x = posWrtComp.x()
            #e.y = posWrtComp.y()
            Enz_cplx = enzObj.path + '/' + string_num + '_cplx'
            cplxItem = moose.Pool(Enz_cplx)
            cplxinfo = moose.Annotator(cplxItem.path + '/info')
            qGEnz = layoutPt.mooseId_GObj[enzObj]
            qGItem = CplxItem(cplxItem, qGEnz)
            layoutPt.mooseId_GObj[cplxItem] = qGItem
            enzboundingRect = qGEnz.boundingRect()
            moose.connect(enzObj, 'cplx', cplxItem, 'reac')
            qGItem.setDisplayProperties(enzboundingRect.height() / 2,
                                        enzboundingRect.height() - 40,
                                        QtGui.QColor('white'),
                                        QtGui.QColor('white'))
            #cplxinfo.x = enzboundingRect.height()/2
            #cplxinfo.y = enzboundingRect.height()-60
            view.emit(QtCore.SIGNAL("dropped"), enzObj)

        else:
            enzObj = moose.MMenz(mobj.path + '/' + string_num)
            enzinfo = moose.Annotator(enzObj.path + '/info')
            moose.connect(mobj, "nOut", enzObj, "enzDest")
            qGItem = MMEnzItem(enzObj, parentcompt)
            posWrtComp = pos
            bgcolor = getRandColor()
            qGItem.setDisplayProperties(posWrtComp.x(),
                                        posWrtComp.y() - 30,
                                        QtGui.QColor('green'), bgcolor)
            #enzinfo.x = posWrtComp.x()
            #enzinfo.y = posWrtComp.y()
            enzinfo.color = str(bgcolor.name())
            layoutPt.mooseId_GObj[enzObj] = qGItem
            view.emit(QtCore.SIGNAL("dropped"), enzObj)
            x, y = roundoff(qGItem.scenePos(), layoutPt)
            enzinfo.x = x
            enzinfo.y = y
        setupItem(modelpath.path, layoutPt.srcdesConnection)
        layoutPt.drawLine_arrow(False)

        #Dropping is on compartment then update Compart size
        if isinstance(enzparent, moose.ChemCompt):
            updateCompartmentSize(parentcompt)
    if view.iconScale != 1:
        view.updateScale(view.iconScale)
Ejemplo n.º 4
0
def createReaction(model, specInfoMap, modelAnnotaInfo, globparameterIdValue):
    # print " reaction "
    # Things done for reaction
    # --Reaction is not created, if substrate and product is missing
    # --Reaction is created under first substrate's compartment if substrate not found then product
    # --Reaction is created if substrate or product is missing, but while run time in GUI atleast I have stopped
    # ToDo
    # -- I need to check here if any substance/product is if ( constant == true && bcondition == false)
    # cout <<"The species "<< name << " should not appear in reactant or product as per sbml Rules"<< endl;

    errorFlag = True
    reactSBMLIdMooseId = {}
    msg = ""
    rName = ""
    reaction_ = None

    for ritem in range(0, model.getNumReactions()):
        reactionCreated = False
        groupName = ""

        reac = model.getReaction(ritem)
        group = ""
        reacAnnoInfo = {}
        reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
        if "Group" in reacAnnoInfo:
            group = reacAnnoInfo["Group"]

        if (reac.isSetId()):
            rId = reac.getId()
        if (reac.isSetName()):
            rName = reac.getName()
            rName = rName.replace(" ", "_space_")
        if not (rName):
            rName = rId
        rev = reac.getReversible()
        fast = reac.getFast()
        if (fast):
            print(" warning: for now fast attribute is not handled \"", rName,
                  "\"")
        if (reac.getAnnotation() is not None):
            groupName = getEnzAnnotation(reac, modelAnnotaInfo, rev,
                                         globparameterIdValue, specInfoMap)

        if (groupName != ""
                and list(modelAnnotaInfo[groupName]["stage"])[0] == 3):
            reaction_, reactionCreated = setupEnzymaticReaction(
                reac, groupName, rName, specInfoMap, modelAnnotaInfo)
            reaction_.k3 = modelAnnotaInfo[groupName]['k3']
            reaction_.k2 = modelAnnotaInfo[groupName]['k2']
            reaction_.concK1 = modelAnnotaInfo[groupName]['k1']
            if reactionCreated:
                if (reac.isSetNotes):
                    pullnotes(reac, reaction_)
                    reacAnnoInfo = {}
                reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
                if reacAnnoInfo:
                    if not moose.exists(reaction_.path + '/info'):
                        reacInfo = moose.Annotator(reaction_.path + '/info')
                    else:
                        reacInfo = moose.element(reaction_.path + '/info')
                    for k, v in list(reacAnnoInfo.items()):
                        if k == 'xCord':
                            reacInfo.x = float(v)
                        elif k == 'yCord':
                            reacInfo.y = float(v)
                        elif k == 'bgColor':
                            reacInfo.color = v
                        else:
                            reacInfo.textColor = v

        elif (groupName == ""):
            numRcts = reac.getNumReactants()
            numPdts = reac.getNumProducts()
            nummodifiers = reac.getNumModifiers()

            if not (numRcts and numPdts):
                print(
                    "Warning: %s" % (rName),
                    " : Substrate or Product is missing, we will be skiping creating this reaction in MOOSE"
                )
                reactionCreated = False
            elif (reac.getNumModifiers() > 0):
                reactionCreated, reaction_ = setupMMEnzymeReaction(
                    reac, rName, specInfoMap, reactSBMLIdMooseId,
                    modelAnnotaInfo, model, globparameterIdValue)
            # elif (reac.getNumModifiers() > 0):
            #     reactionCreated = setupMMEnzymeReaction(reac,rName,specInfoMap,reactSBMLIdMooseId,modelAnnotaInfo,model,globparameterIdValue)
            #     reaction_ = reactSBMLIdMooseId['classical']['MooseId']
            #     reactionType = "MMEnz"
            elif (numRcts):
                # In moose, reactions compartment are decided from first Substrate compartment info
                # substrate is missing then check for product
                if (reac.getNumReactants()):
                    react = reac.getReactant(reac.getNumReactants() - 1)
                    # react = reac.getReactant(0)
                    sp = react.getSpecies()
                    sp = str(idBeginWith(sp))
                    speCompt = specInfoMap[sp]["comptId"].path
                    if group:
                        if moose.exists(speCompt + '/' + group):
                            speCompt = speCompt + '/' + group
                        else:
                            speCompt = (moose.Neutral(speCompt + '/' +
                                                      group)).path
                    reaction_ = moose.Reac(speCompt + '/' + rName)
                    reactionCreated = True
                    reactSBMLIdMooseId[rName] = {
                        "MooseId": reaction_,
                        "className ": "reaction"
                    }
            elif (numPdts):
                # In moose, reactions compartment are decided from first Substrate compartment info
                # substrate is missing then check for product
                if (reac.getNumProducts()):
                    react = reac.getProducts(0)
                    sp = react.getSpecies()
                    sp = str(idBeginWith(sp))
                    speCompt = specInfoMap[sp]["comptId"].path
                    reaction_ = moose.Reac(speCompt + '/' + rName)
                    reactionCreated = True
                    reactSBMLIdMooseId[rId] = {
                        "MooseId": reaction_,
                        "className": "reaction"
                    }
            if reactionCreated:
                if (reac.isSetNotes):
                    pullnotes(reac, reaction_)
                    reacAnnoInfo = {}
                reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
                if reacAnnoInfo:
                    if not moose.exists(reaction_.path + '/info'):
                        reacInfo = moose.Annotator(reaction_.path + '/info')
                    else:
                        reacInfo = moose.element(reaction_.path + '/info')
                    for k, v in list(reacAnnoInfo.items()):
                        if k == 'xCord':
                            reacInfo.x = float(v)
                        elif k == 'yCord':
                            reacInfo.y = float(v)
                        elif k == 'bgColor':
                            reacInfo.color = v
                        else:
                            reacInfo.textColor = v

                addSubPrd(reac, rName, "sub", reactSBMLIdMooseId, specInfoMap)
                addSubPrd(reac, rName, "prd", reactSBMLIdMooseId, specInfoMap)
                if reac.isSetKineticLaw():
                    klaw = reac.getKineticLaw()
                    mmsg = ""
                    errorFlag, mmsg, kfvalue, kbvalue = getKLaw(
                        model, klaw, rev, globparameterIdValue, specInfoMap)
                    if not errorFlag:
                        msg = "Error while importing reaction \"" + \
                            rName + "\"\n Error in kinetics law "
                        if mmsg != "":
                            msg = msg + mmsg
                        return (errorFlag, msg)
                    else:
                        # print " reactSBMLIdMooseId
                        # ",reactSBMLIdMooseId[rName]["nSub"], " prd
                        # ",reactSBMLIdMooseId[rName]["nPrd"]
                        if reaction_.className == "Reac":
                            subn = reactSBMLIdMooseId[rName]["nSub"]
                            prdn = reactSBMLIdMooseId[rName]["nPrd"]
                            reaction_.Kf = kfvalue  # * pow(1e-3,subn-1)
                            reaction_.Kb = kbvalue  # * pow(1e-3,prdn-1)
                        elif reaction_.className == "MMenz":
                            reaction_.kcat = kfvalue
                            reaction_.Km = kbvalue
    return (errorFlag, msg)
Ejemplo n.º 5
0
def autoCoordinates(meshEntry, srcdesConnection):
    G = nx.Graph()
    for cmpt, memb in meshEntry.items():
        if memb in ["enzyme"]:
            for enzObj in find_index(memb, 'enzyme'):
                #G.add_node(enzObj.path)
                G.add_node(enzObj.path,
                           label='',
                           shape='ellipse',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=12,
                           fontcolor='blue')
    for cmpt, memb in meshEntry.items():
        #if memb.has_key
        if memb in ["pool", "cplx", "reaction"]:
            for poolObj in find_index(memb, 'pool'):
                #G.add_node(poolObj.path)
                G.add_node(poolObj.path,
                           label=poolObj.name,
                           shape='box',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=9,
                           fontcolor='blue')
            for cplxObj in find_index(memb, 'cplx'):
                G.add_node(cplxObj.path)
                G.add_node(cplxObj.path,
                           label=cplxObj.name,
                           shape='box',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=12,
                           fontcolor='blue')
                #G.add_edge((cplxObj.parent).path,cplxObj.path)
            for reaObj in find_index(memb, 'reaction'):
                #G.add_node(reaObj.path)
                G.add_node(reaObj.path, label='', shape='circle', color='')

    for inn, out in list(srcdesConnection.items()):
        if isinstance(out, tuple):
            if len(out[0]) == 0:
                print(inn.className + ':' + inn.name +
                      "  doesn't have input message")
            else:
                for items in (items for items in out[0]):
                    G.add_edge(moose.element(items[0]).path, inn.path)
            if len(out[1]) == 0:
                print(inn.className + ':' + inn.name +
                      "doesn't have output mssg")
            else:
                for items in (items for items in out[1]):
                    G.add_edge(inn.path, moose.element(items[0]).path)
        elif isinstance(out, list):
            if len(out) == 0:
                print("Func pool doesn't have sumtotal")
            else:
                for items in (items for items in out):
                    G.add_edge(moose.element(items[0]).path, inn.path)

    position = graphviz_layout(G)
    xcord, ycord = [], []
    for item in position.items():
        xy = item[1]
        xroundoff = round(xy[0], 0)
        yroundoff = round(xy[1], 0)
        xcord.append(xroundoff)
        ycord.append(yroundoff)

    for item in position.items():
        xy = item[1]
        anno = moose.Annotator(item[0] + '/info')
        anno.x = xy[0]
        anno.y = xy[1]
Ejemplo n.º 6
0
def loadFile(filename, target, solver="gsl", merge=True):
    """Try to load a model from specified `filename` under the element
    `target`.

    if `merge` is True, the contents are just loaded at target. If
    false, everything is deleted from the parent of target unless the
    parent is root.

    Returns
    -------
    a dict containing at least these three entries:

    modeltype: type of the loaded model.

    subtype: subtype of the loaded model, None if no specific subtype

    modelroot: root element of the model, None if could not be located - as is the case with Python scripts
    """
    loaderror = ""
    num = 1
    libsfound = True
    model = '/'
    newTarget = target
    while moose.exists(newTarget):
        newTarget = target + "-" + str(num)
        num = num + 1
    target = newTarget
    istext = True
    with open(filename, 'rb') as infile:
        istext = mtypes.istextfile(infile)
    if not istext:
        print('Cannot handle any binary formats yet')
        return None
    # parent, child = posixpath.split(target)
    # p = moose.Neutral(parent)
    # if not merge and p.path != '/':
    #     for ch in p.children:
    #         moose.delete(ch)
    try:
        modeltype = mtypes.getType(filename)
        subtype = mtypes.getSubtype(filename, modeltype)
    except KeyError:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    pwe = moose.getCwe()
    #self.statusBar.showMessage('Loading model, please wait')
    # app = QtGui.qApp
    # app.setOverrideCursor(QtGui.QCursor(Qt.Qt.BusyCursor)) #shows a hourglass - or a busy/working arrow
    if modeltype == 'genesis':
        if subtype == 'kkit' or subtype == 'prototype':
            model, modelpath = loadGenCsp(target, filename, solver)
            xcord, ycord = [], []
            if moose.exists(moose.element(modelpath).path):
                process = True
                compt = len(moose.wildcardFind(modelpath +
                                               '/##[ISA=CubeMesh]'))
                if not compt:
                    loaderror = "Model has no compartment, atleast one compartment should exist to display the widget"
                    process = False
                else:
                    p = len(moose.wildcardFind(modelpath +
                                               '/##[ISA=PoolBase]'))
                    if p < 2:
                        loaderror = "Model has no pool, atleast two pool should exist to display the widget"
                        process = False
            if process:
                if moose.exists(moose.element(modelpath).path):
                    mObj = moose.wildcardFind(
                        moose.element(modelpath).path + '/##[ISA=PoolBase]' +
                        ',' + moose.element(modelpath).path +
                        '/##[ISA=ReacBase]' + ',' +
                        moose.element(modelpath).path + '/##[ISA=EnzBase]' +
                        ',' + moose.element(modelpath).path +
                        '/##[ISA=StimulusTable]')
                    for p in mObj:
                        if not isinstance(moose.element(p.parent),
                                          moose.CplxEnzBase):
                            xcord.append(moose.element(p.path + '/info').x)
                            ycord.append(moose.element(p.path + '/info').y)
                    recalculatecoordinatesforKkit(mObj, xcord, ycord)

                    for ememb in moose.wildcardFind(
                            moose.element(modelpath).path +
                            '/##[ISA=EnzBase]'):
                        objInfo = ememb.path + '/info'
                        #Enzyme's textcolor (from kkit) will be bgcolor (in moose)
                        if moose.exists(objInfo):
                            bgcolor = moose.element(objInfo).color
                            moose.element(objInfo).color = moose.element(
                                objInfo).textColor
                            moose.element(objInfo).textColor = bgcolor
                    moose.Annotator(moose.element(modelpath).path +
                                    '/info').modeltype = "kkit"
                else:
                    print(" path doesn't exists")
                moose.le(modelpath)
        else:
            print('Only kkit and prototype files can be loaded.')

    elif modeltype == 'cspace':
        model, modelpath = loadGenCsp(target, filename)

        if moose.exists(modelpath):
            moose.Annotator(
                (moose.element(modelpath).path + '/info')).modeltype = "cspace"
        addSolver(modelpath, 'gsl')

    elif modeltype == 'xml':
        if subtype == 'neuroml':
            popdict, projdict = neuroml.loadNeuroML_L123(filename)
            # Circus to get the container of populations from loaded neuroml
            for popinfo in popdict.values():
                for cell in popinfo[1].values():
                    solver = moose.HSolve(cell.path + "/hsolve")
                    solver.target = cell.path
                    # model = cell.parent
                    # break
                # break

            # Moving model to a new location under the model name
            # model name is the filename without extension

            model = moose.Neutral("/" + splitext(basename(filename))[0])
            element = moose.Neutral(model.path + "/model")
            if (moose.exists("/cells")): moose.move("/cells", element.path)
            if (moose.exists("/elec")): moose.move("/elec", model.path)
            if (moose.exists("/library")): moose.move("/library", model.path)

            # moose.move("cells/", cell.path)
        elif subtype == 'sbml':
            foundLibSBML_ = False
            try:
                import libsbml
                foundLibSBML_ = True
            except ImportError:
                pass
            if foundLibSBML_:
                if target != '/':
                    if moose.exists(target):
                        moose.delete(target)
                model, loaderror = mooseReadSBML(filename, target)
                if moose.exists(moose.element(model).path):
                    moose.Annotator(moose.element(model).path +
                                    '/info').modeltype = "sbml"
                addSolver(target, 'gsl')
            libsfound = foundLibSBML_
    else:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    moose.setCwe(
        pwe
    )  # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour

    # TODO: check with Aditya how to specify the target for
    # neuroml reader
    # app.restoreOverrideCursor()
    return {
        'modeltype': modeltype,
        'subtype': subtype,
        'model': model,
        'foundlib': libsfound,
        'loaderror': loaderror
    }
Ejemplo n.º 7
0
def writeEnz(modelpath, f, sceneitems):
    enzList = moose.wildcardFind(modelpath + '/##[ISA=EnzBase]')
    for enz in enzList:
        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
        enzParent = enz.parent
        if (isinstance(enzParent.className, moose.Pool)) or (isinstance(
                enzParent.className, moose.ZombiePool)):
            print(" raise exception enz doesn't have pool as parent")
            return False
        else:
            vol = enzParent.volume * NA * 1e-3
            isMichaelisMenten = 0
            enzClass = enz.className
            if (enzClass == "ZombieMMenz" or enzClass == "MMenz"):
                k1 = enz.numKm
                k3 = enz.kcat
                k2 = 4.0 * k3
                k1 = (k2 + k3) / k1
                isMichaelisMenten = 1

            elif (enzClass == "ZombieEnz" or enzClass == "Enz"):
                k1 = enz.k1
                k2 = enz.k2
                k3 = enz.k3
                cplx = enz.neighbors['cplx'][0]
                nInit = cplx.nInit[0]
            if sceneitems != None:
                # value = sceneitems[enz]
                # x = calPrime(value['x'])
                # y = calPrime(value['y'])
                x = sceneitems[enz]['x']
                y = sceneitems[enz]['y']

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

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

            if color == "" or color == " ":
                color = getRandColor()
            if textcolor == "" or textcolor == " ":
                textcolor = getRandColor()

            f.write("simundump kenz /kinetics/" + trimPath(enz) + " " +
                    str(0) + " " + str(concInit) + " " + str(conc) + " " +
                    str(nInit) + " " + str(n) + " " + str(vol) + " " +
                    str(k1) + " " + str(k2) + " " + str(k3) + " " + str(0) +
                    " " + str(isMichaelisMenten) + " " + "\"\"" + " " +
                    str(textcolor) + " " + str(color) + " \"\"" + " " +
                    str(int(x)) + " " + str(int(y)) + " " + str(0) + "\n")
    return enzList
Ejemplo n.º 8
0
def writeReac(modelpath, cremodel_, sceneitems):
    for reac in moose.wildcardFind(modelpath + '/##[ISA=ReacBase]'):
        reacSub = reac.neighbors["sub"]
        reacPrd = reac.neighbors["prd"]
        if (len(reacSub) != 0 and len(reacPrd) != 0):

            reaction = cremodel_.createReaction()
            reacannoexist = False
            reacGpname = " "
            cleanReacname = convertSpecialChar(reac.name)
            reaction.setId(str(idBeginWith(cleanReacname +
                                           "_" +
                                           str(reac.getId().value) +
                                           "_" +
                                           str(reac.getDataIndex()) +
                                           "_")))
            reaction.setName(cleanReacname)
            #Kf = reac.numKf
            #Kb = reac.numKb
            Kf = reac.Kf
            Kb = reac.Kb
            if Kb == 0.0:
                reaction.setReversible(False)
            else:
                reaction.setReversible(True)

            reaction.setFast(False)
            if moose.exists(reac.path + '/info'):
                Anno = moose.Annotator(reac.path + '/info')
                if Anno.notes != "":
                    cleanNotesR = convertNotesSpecialChar(Anno.notes)
                    notesStringR = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                        cleanNotesR + "\n\t </body>"
                    reaction.setNotes(notesStringR)
                element = moose.element(reac)
                ele = getGroupinfo(element)
                if element.className == "Neutral" or sceneitems or Anno.x or Anno.y:
                    reacannoexist = True
                if reacannoexist:
                    reacAnno = "<moose:ModelAnnotation>\n"
                    if ele.className == "Neutral":
                        reacAnno = reacAnno + "<moose:Group>" + ele.name + "</moose:Group>\n"
                    if sceneitems:
                        #Saved from GUI, then scene co-ordinates are passed
                        reacAnno = reacAnno + "<moose:xCord>" + \
                                str(sceneitems[reac]['x']) + "</moose:xCord>\n" + \
                                "<moose:yCord>" + \
                                str(sceneitems[reac]['y'])+ "</moose:yCord>\n"
                    else:
                        #Saved from cmdline,genesis coordinates are kept as its
                        # SBML, cspace, python, then auto-coordinates are done
                        #and coordinates are updated in moose Annotation field
                        reacAnno = reacAnno + "<moose:xCord>" + \
                                str(Anno.x) + "</moose:xCord>\n" + \
                                "<moose:yCord>" + \
                                str(Anno.y)+ "</moose:yCord>\n"
                    if Anno.color:
                        reacAnno = reacAnno + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
                    if Anno.textColor:
                        reacAnno = reacAnno + "<moose:textColor>" + \
                            Anno.textColor + "</moose:textColor>\n"
                    reacAnno = reacAnno + "</moose:ModelAnnotation>"
                    reaction.setAnnotation(reacAnno)

            kl_s, sRL, pRL, compt = "", "", "", ""

            if not reacSub and not reacPrd:
                print(" Reaction ", reac.name, "missing substrate and product")
            else:
                kfl = reaction.createKineticLaw()
                if reacSub:
                    noofSub, sRateLaw = getSubprd(
                        cremodel_, False, "sub", reacSub)
                    if noofSub:
                        comptVec = findCompartment(moose.element(reacSub[0]))
                        if not isinstance(moose.element(
                                comptVec), moose.ChemCompt):
                            return -2
                        else:
                            compt = comptVec.name + "_" + \
                                str(comptVec.getId().value) + "_" + \
                                str(comptVec.getDataIndex()) + "_"
                        cleanReacname = cleanReacname + "_" + \
                            str(reac.getId().value) + "_" + \
                            str(reac.getDataIndex()) + "_"
                        kfparm = idBeginWith(cleanReacname) + "_" + "Kf"
                        sRL = compt + " * " + \
                            idBeginWith(cleanReacname) + "_Kf * " + sRateLaw
                        unit = parmUnit(noofSub - 1, cremodel_)
                        printParameters(kfl, kfparm, Kf, unit)
                        #kl_s = compt+"(" +sRL
                        kl_s = sRL
                    else:
                        print(reac.name + " has no substrate")
                        return -2
                else:
                    print(" Substrate missing for reaction ", reac.name)

                if reacPrd:
                    noofPrd, pRateLaw = getSubprd(
                        cremodel_, False, "prd", reacPrd)
                    if noofPrd:
                        if Kb:
                            kbparm = idBeginWith(cleanReacname) + "_" + "Kb"
                            pRL = compt + " * " + \
                                idBeginWith(cleanReacname) + \
                                "_Kb * " + pRateLaw
                            unit = parmUnit(noofPrd - 1, cremodel_)
                            printParameters(kfl, kbparm, Kb, unit)
                            #kl_s = kl_s+ "- "+pRL+")"
                            kl_s = kl_s + "-" + pRL
                    else:
                        print(reac.name + " has no product")
                        return -2
                else:
                    print(" Product missing for reaction ", reac.name)
            kfl.setFormula(kl_s)
            kfl.setNotes(
                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                kl_s +
                "\n \t </body>")
            kfl.setFormula(kl_s)
        else:
            print(" Reaction ", reac.name, "missing substrate and product")
Ejemplo n.º 9
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 += "\n%s doesn't have compartment ignored to write to genesis" % p
        else:
            slave_enable = 0
            if p.isA["BufPool"] or p.isA["ZombieBufPool"]:
                pool_children = p.children
                if pool_children == 0:
                    slave_enable = 4
                else:
                    for pchild in pool_children:
                        if (not pchild.isA["ZombieFunction"]) and (
                                not pchild.isA["Function"]):
                            slave_enable = 4
                        else:
                            slave_enable = 0
                            break

            pp = moose.element(p.parent)
            if (not pp.isA['Enz']) and (not pp.isA['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
Ejemplo n.º 10
0
def enzymeMerge(comptD, comptS, key, poolListind):
    war_msg = ""
    RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], []
    comptDpath = moose.element(comptD[key]).path
    comptSpath = moose.element(comptS[key]).path
    objD = moose.element(comptDpath).parent.name
    objS = moose.element(comptSpath).parent.name
    #nzyListina => enzyListind

    enzyListind = moose.wildcardFind(comptDpath + '/##[ISA=EnzBase]')
    enzyListins = moose.wildcardFind(comptSpath + '/##[ISA=EnzBase]')
    for es in enzyListins:
        eSsubname, eSprdname = [], []
        eSsubname = subprdList(es, "sub")
        eSprdname = subprdList(es, "prd")
        allexists, allexistp = False, False
        allclean = False

        poolinDlist = poolListind[findCompartment(es).name]
        for pD in poolinDlist:
            if es.parent.name == pD.name:
                edpath = es.parent.path.replace(objS, objD)

                if not moose.exists(edpath + '/' + es.name):
                    #This will take care
                    #  -- If same enzparent name but different enzyme name
                    #  -- or different parent/enzyme name
                    if eSsubname and eSprdname:
                        allexists = checkexist(eSsubname, objS, objD)
                        allexistp = checkexist(eSprdname, objS, objD)
                        if allexists and allexistp:
                            enzPool = moose.element(pD.path)
                            edpath = es.parent.path.replace(objS, objD)
                            enz = moose.element(
                                moose.copy(es, moose.element(edpath)))
                            enzPool = enz.parent
                            if es.className in ["ZombieEnz", "Enz"]:
                                moose.connect(moose.element(enz), "enz",
                                              enzPool, "reac")
                            if es.className in ["ZombieMMenz", "MMenz"]:
                                moose.connect(enzPool, "nOut", enz, "enzDest")
                            connectObj(enz, eSsubname, "sub", comptD, war_msg)
                            connectObj(enz, eSprdname, "prd", comptD, war_msg)
                            allclean = True
                        else:
                            # didn't find sub or prd for this Enzyme
                            RE_Notcopiedyet.append(es)
                    else:
                        #   -- it is dagging reaction
                        RE_Daggling.append(es)
                else:
                    #Same Enzyme name
                    #   -- Same substrate and product including same volume then don't copy
                    #   -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme
                    allclean = False
                    ed = moose.element(es.path.replace(objS, objD))
                    eDsubname = subprdList(ed, "sub")
                    eSsubname = subprdList(es, "sub")
                    hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol(
                        eDsubname, eSsubname)

                    eDprdname = subprdList(ed, "prd")
                    eSprdname = subprdList(es, "prd")
                    hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol(
                        eDprdname, eSprdname)
                    if not all((hasSamenoofsublen, hasSameS, hasSamevols,
                                hasSamenoofprdlen, hasSameP, hasSamevolp)):
                        # May be different substrate or product or volume of Sub/prd may be different,
                        # Duplicating the enzyme
                        if eSsubname and eSprdname:
                            allexists, allexistp = False, False
                            allexists = checkexist(eSsubname, objS, objD)
                            allexistp = checkexist(eSprdname, objS, objD)
                            if allexists and allexistp:
                                es.name = es.name + "_duplicated"
                                if es.className in ["ZombieEnz", "Enz"]:
                                    edpath = es.parent.path.replace(objS, objD)
                                    enz = moose.copy(es, moose.element(edpath))
                                    moose.connect(enz, 'enz', edpath, 'reac')

                                if es.className in ["ZombieMMenz", "MMenz"]:
                                    edpath = es.parent.path.replace(objS, objD)
                                    enz = moose.copy(es, moose.element(edpath))
                                    enzinfo = moose.Annotator(enz.path +
                                                              '/info')
                                    moose.connect(
                                        moose.element(enz).parent, "nOut",
                                        moose.element(enz), "enzDest")
                                    #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac")

                                connectObj(enz, eSsubname, "sub", comptD,
                                           war_msg)
                                connectObj(enz, eSprdname, "prd", comptD,
                                           war_msg)
                                RE_Duplicated.append(enz)
                                allclean = True
                            else:
                                allclean = False
                    else:
                        allclean = True

                    if not allclean:
                        # didn't find sub or prd for this enzyme
                        #   --  it may be connected Enzyme cplx
                        if eSsubname and eSprdname:
                            RE_Notcopiedyet.append(es)
                        else:
                            RE_Daggling.append(es)

    return RE_Duplicated, RE_Notcopiedyet, RE_Daggling
Ejemplo n.º 11
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 enzParent.isA['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
                    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
Ejemplo n.º 12
0
def loadFile(filename, target, solver="gsl", merge=True):
    """Try to load a model from specified `filename` under the element
    `target`.

    if `merge` is True, the contents are just loaded at target. If
    false, everything is deleted from the parent of target unless the
    parent is root.

    Returns
    -------
    a dict containing at least these three entries:

    modeltype: type of the loaded model.

    subtype: subtype of the loaded model, None if no specific subtype

    modelroot: root element of the model, None if could not be located - as is the case with Python scripts
    """
    num = 1
    newTarget = target
    while moose.exists(newTarget):
        newTarget = target + "-" + str(num)
        num = num + 1
    target = newTarget
    istext = True
    with open(filename, 'rb') as infile:
        istext = mtypes.istextfile(infile)
    if not istext:
        print 'Cannot handle any binary formats yet'
        return None
    # parent, child = posixpath.split(target)
    # p = moose.Neutral(parent)
    # if not merge and p.path != '/':
    #     for ch in p.children:
    #         moose.delete(ch)
    try:
        modeltype = mtypes.getType(filename)
        subtype = mtypes.getSubtype(filename, modeltype)
    except KeyError:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    pwe = moose.getCwe()
    #self.statusBar.showMessage('Loading model, please wait')
    # app = QtGui.qApp
    # app.setOverrideCursor(QtGui.QCursor(Qt.Qt.BusyCursor)) #shows a hourglass - or a busy/working arrow
    if modeltype == 'genesis':
        if subtype == 'kkit' or subtype == 'prototype':
            model, modelpath = loadGenCsp(target, filename, solver)
            if moose.exists(moose.element(modelpath).path):
                moose.Annotator(moose.element(modelpath).path +
                                '/info').modeltype = "kkit"
            else:
                print " path doesn't exists"
            moose.le(modelpath)
        else:
            print 'Only kkit and prototype files can be loaded.'

    elif modeltype == 'cspace':
        model, modelpath = loadGenCsp(target, filename)
        if moose.exists(modelpath):
            moose.Annotator(
                (moose.element(modelpath).path + '/info')).modeltype = "cspace"
        addSolver(modelpath, 'gsl')

    elif modeltype == 'xml':
        if subtype == 'neuroml':
            popdict, projdict = neuroml.loadNeuroML_L123(filename)
            # Circus to get the container of populations from loaded neuroml
            for popinfo in popdict.values():
                for cell in popinfo[1].values():
                    solver = moose.HSolve(cell.path + "/hsolve")
                    solver.target = cell.path
                    # model = cell.parent
                    # break
                # break

            # Moving model to a new location under the model name
            # model name is the filename without extension

            model = moose.Neutral("/" + splitext(basename(filename))[0])
            element = moose.Neutral(model.path + "/model")
            if (moose.exists("/cells")): moose.move("/cells", element.path)
            if (moose.exists("/elec")): moose.move("/elec", model.path)
            if (moose.exists("/library")): moose.move("/library", model.path)

            # moose.move("cells/", cell.path)
        elif subtype == 'sbml':
            if target != '/':
                if moose.exists(target):
                    moose.delete(target)
            model = mooseReadSBML(filename, target)
            if moose.exists(moose.element(model).path):
                moose.Annotator(moose.element(model).path +
                                '/info').modeltype = "sbml"
            addSolver(target, 'gsl')
    else:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    moose.setCwe(
        pwe
    )  # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour

    # TODO: check with Aditya how to specify the target for
    # neuroml reader
    # app.restoreOverrideCursor()
    return {'modeltype': modeltype, 'subtype': subtype, 'model': model}
Ejemplo n.º 13
0
def autoCoordinates(meshEntry, srcdesConnection):
    global pygraphvizFound_
    positionInfo = {}

    if not pygraphvizFound_:
        print('[warn] python-pygraphviz could not be found.')
        print('\tMOOSE Install pygraphviz to use this feature')
        return positionInfo

    if meshEntry:
        #G = nx.Graph()
        G = pgv.AGraph()

        for cmpt, memb in list(meshEntry.items()):
            for enzObj in find_index(memb, 'enzyme'):
                #G.add_node(enzObj.path)
                G.add_node(enzObj.path,
                           label='',
                           shape='ellipse',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=12,
                           fontcolor='blue')
        for cmpt, memb in list(meshEntry.items()):
            for poolObj in find_index(memb, 'pool'):
                #G.add_node(poolObj.path)
                G.add_node(poolObj.path,
                           label=poolObj.name,
                           shape='box',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=12,
                           fontcolor='blue')
            for cplxObj in find_index(memb, 'cplx'):
                G.add_node(cplxObj.path)
                G.add_node(cplxObj.path,
                           label=cplxObj.name,
                           shape='box',
                           color='',
                           style='filled',
                           fontname='Helvetica',
                           fontsize=12,
                           fontcolor='blue')
                #G.add_edge((cplxObj.parent).path,cplxObj.path)
            for reaObj in find_index(memb, 'reaction'):
                #G.add_node(reaObj.path)
                G.add_node(reaObj.path, label='', shape='circle', color='')

        for inn, out in list(srcdesConnection.items()):
            if (inn.className == 'ZombieReac'): arrowcolor = 'green'
            elif (inn.className == 'ZombieEnz'): arrowcolor = 'red'
            else: arrowcolor = 'blue'
            if isinstance(out, tuple):
                if len(out[0]) == 0:
                    print(inn.className + ':' + inn.name +
                          "  doesn't have input message")
                else:
                    for items in (items for items in out[0]):
                        G.add_edge(moose.element(items[0]).path, inn.path)
                if len(out[1]) == 0:
                    print(inn.className + ':' + inn.name +
                          "doesn't have output mssg")
                else:
                    for items in (items for items in out[1]):
                        G.add_edge(inn.path, moose.element(items[0]).path)
            elif isinstance(out, list):
                if len(out) == 0:
                    print("Func pool doesn't have sumtotal")
                else:
                    for items in (items for items in out):
                        G.add_edge(moose.element(items[0]).path, inn.path)

        # if int( nx.__version__.split( '.' )[-1] ) >= 11:
        #     position = nx.spring_layout( G )
        # else:
        #     position = nx.graphviz_layout(G, prog = 'dot')
        # for item in position.items():
        #     xy = item[1]
        #     ann = moose.Annotator(item[0]+'/info')
        #     ann.x = xy[0]
        #     ann.y = xy[1]
        #     positioninfo[(moose.element(item[0]))] ={'x':float(xy[0]),'y':float(xy[1])}

        G.layout()
        for n in G.nodes():
            value = str(n.attr['pos'])
            valuelist = (value.split(','))
            positionInfo[(moose.element(n))] = {
                'x': float(valuelist[0]),
                'y': float(valuelist[1])
            }
            ann = moose.Annotator(moose.element(n).path + '/info')
            ann.x = float(valuelist[0])
            ann.y = float(valuelist[1])

    return positionInfo
Ejemplo n.º 14
0
def enzymeMerge(comptA, comptB, key, poolListina):
    war_msg = ""
    RE_Duplicated, RE_Notcopiedyet, RE_Daggling = [], [], []
    comptApath = moose.element(comptA[key]).path
    comptBpath = moose.element(comptB[key]).path
    objA = moose.element(comptApath).parent.name
    objB = moose.element(comptBpath).parent.name
    enzyListina = moose.wildcardFind(comptApath + '/##[ISA=EnzBase]')
    enzyListinb = moose.wildcardFind(comptBpath + '/##[ISA=EnzBase]')
    for eb in enzyListinb:
        eBsubname, eBprdname = [], []
        eBsubname = subprdList(eb, "sub")
        eBprdname = subprdList(eb, "prd")
        allexists, allexistp = False, False
        allclean = False

        poolinAlist = poolListina[findCompartment(eb).name]
        for pA in poolinAlist:
            if eb.parent.name == pA.name:
                eapath = eb.parent.path.replace(objB, objA)

                if not moose.exists(eapath + '/' + eb.name):
                    #This will take care
                    #  -- If same enzparent name but different enzyme name
                    #  -- or different parent/enzyme name
                    if eBsubname and eBprdname:
                        allexists = checkexist(eBsubname, objB, objA)
                        allexistp = checkexist(eBprdname, objB, objA)
                        if allexists and allexistp:
                            enzPool = moose.element(pA.path)
                            eapath = eb.parent.path.replace(objB, objA)
                            enz = moose.element(
                                moose.copy(eb, moose.element(eapath)))
                            enzPool = enz.parent
                            if eb.className in ["ZombieEnz", "Enz"]:
                                moose.connect(moose.element(enz), "enz",
                                              enzPool, "reac")
                            if eb.className in ["ZombieMMenz", "MMenz"]:
                                moose.connect(enzPool, "nOut", enz, "enzDest")
                            connectObj(enz, eBsubname, "sub", comptA, war_msg)
                            connectObj(enz, eBprdname, "prd", comptA, war_msg)
                            allclean = True
                        else:
                            # didn't find sub or prd for this Enzyme
                            #print ("didn't find sub or prd for this reaction" )
                            RE_Notcopiedyet.append(eb)
                    else:
                        #   -- it is dagging reaction
                        RE_Daggling.append(eb)
                        #print ("This reaction \""+eb.path+"\" has no substrate/product daggling reaction are not copied")
                        #war_msg = war_msg+"\nThis reaction \""+eb.path+"\" has no substrate/product daggling reaction are not copied"
                else:
                    #Same Enzyme name
                    #   -- Same substrate and product including same volume then don't copy
                    #   -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme
                    allclean = False
                    #ea = moose.element('/'+obj+'/'+enzcompartment.name+'/'+enzparent.name+'/'+eb.name)
                    #ea = moose.element(pA.path+'/'+eb.name)
                    ea = moose.element(eb.path.replace(objB, objA))
                    eAsubname = subprdList(ea, "sub")
                    eBsubname = subprdList(eb, "sub")
                    hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol(
                        eAsubname, eBsubname)

                    eAprdname = subprdList(ea, "prd")
                    eBprdname = subprdList(eb, "prd")
                    hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol(
                        eAprdname, eBprdname)
                    if not all((hasSamenoofsublen, hasSameS, hasSamevols,
                                hasSamenoofprdlen, hasSameP, hasSamevolp)):
                        # May be different substrate or product or volume of Sub/prd may be different,
                        # Duplicating the enzyme
                        if eBsubname and eBprdname:
                            allexists, allexistp = False, False
                            allexists = checkexist(eBsubname, objB, objA)
                            allexistp = checkexist(eBprdname, objB, objA)
                            if allexists and allexistp:
                                eb.name = eb.name + "_duplicated"
                                if eb.className in ["ZombieEnz", "Enz"]:
                                    eapath = eb.parent.path.replace(objB, objA)
                                    enz = moose.copy(eb, moose.element(eapath))
                                    moose.connect(enz, 'enz', eapath, 'reac')

                                if eb.className in ["ZombieMMenz", "MMenz"]:
                                    eapath = eb.parent.path.replace(objB, objA)
                                    enz = moose.copy(eb.name,
                                                     moose.element(eapath))
                                    enzinfo = moose.Annotator(enz.path +
                                                              '/info')
                                    moose.connect(
                                        moose.element(enz).parent, "nOut",
                                        moose.element(enz), "enzDest")
                                    #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac")

                                #moose.connect( cplxItem, 'reac', enz, 'cplx' )
                                connectObj(enz, eBsubname, "sub", comptA,
                                           war_msg)
                                connectObj(enz, eBprdname, "prd", comptA,
                                           war_msg)
                                RE_Duplicated.append(enz)
                                allclean = True
                            else:
                                allclean = False
                    else:
                        allclean = True

                    if not allclean:
                        # didn't find sub or prd for this enzyme
                        #   --  it may be connected Enzyme cplx
                        if eBsubname and eBprdname:
                            RE_Notcopiedyet.append(eb)
                            #print ("This Enzyme \""+eb.path+"\" has no substrate/product must be connect to cplx")
                            #war_msg = war_msg+ "\nThis Enzyme \""+rb.path+"\" has no substrate/product must be connect to cplx"
                        else:
                            RE_Daggling.append(eb)
                            #print ("This enzyme \""+eb.path+"\" has no substrate/product daggling reaction are not copied")
                            #war_msg = war_msg+"\nThis reaction \""+eb.path+"\" has no substrate/product daggling reaction are not copied"
    return RE_Duplicated, RE_Notcopiedyet, RE_Daggling
Ejemplo n.º 15
0
def writeEnz(modelpath, cremodel_, sceneitems,groupInfo):
    for enz in moose.wildcardFind(modelpath + '/##[ISA=EnzBase]'):
        enzannoexist = False
        enzGpnCorCol = " "
        cleanEnzname = convertSpecialChar(enz.name)
        enzSubt = ()
        compt = ""
        notesE = ""
        groupName = moose.element("/")

        if moose.exists(enz.path + '/info'):
            groupName = moose.element("/")
            Anno = moose.Annotator(enz.path + '/info')
            notesE = Anno.notes
            element = moose.element(enz)
            ele = getGroupinfo(element)
            ele = findGroup_compt(element)
            if ele.className == "Neutral" or sceneitems or Anno.x or Anno.y:
                    enzannoexist = True
            if enzannoexist:
                enzAnno = "<moose:ModelAnnotation>\n"
                if ele.className == "Neutral":
                    groupName = ele
                    #enzGpnCorCol =  "<moose:Group>" + ele.name + "</moose:Group>\n"
                    # if ele.name not in groupInfo:
                    #         groupInfo[ele.name]=[setId]
                    #     else:
                    #         groupInfo[ele.name].append(setId)
                if sceneitems:
                    #Saved from GUI, then scene co-ordinates are passed
                    enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
                            str(sceneitems[enz]['x']) + "</moose:xCord>\n" + \
                            "<moose:yCord>" + \
                            str(sceneitems[enz]['y'])+ "</moose:yCord>\n"
                else:
                    #Saved from cmdline,genesis coordinates are kept as its
                    # SBML, cspace, python, then auto-coordinates are done
                    #and coordinates are updated in moose Annotation field
                    enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
                            str(Anno.x) + "</moose:xCord>\n" + \
                            "<moose:yCord>" + \
                            str(Anno.y)+ "</moose:yCord>\n"
                if Anno.color:
                    enzGpnCorCol = enzGpnCorCol + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
                if Anno.textColor:
                    enzGpnCorCol = enzGpnCorCol + "<moose:textColor>" + \
                        Anno.textColor + "</moose:textColor>\n"
        if (enz.className == "Enz" or enz.className == "ZombieEnz"):
            # Enz cplx is written into 2 reaction S+E-> SE*, SE* -> E+P
            foundEnzymeComplex = False
            comptVec = findCompartment(moose.element(enz))
            if not isinstance(moose.element(comptVec), moose.ChemCompt):
                return -2
            else:
                compt = comptVec.name + "_" + \
                    str(comptVec.getId().value) + "_" + \
                    str(comptVec.getDataIndex()) + "_"
            
            #Writting out S+E -> SE*
            enzsetId = str(idBeginWith(cleanEnzname +
                                         "_" + str(enz.getId().value) +
                                         "_" + str(enz.getDataIndex()) +
                                         "_" + "Complex_formation_"))
            #Finding Enzyme parent (E), each enzyme should just have one parent, multiple parent not right!
            secplxerror = ""
            enzSubt = ()
            enzOut = enz.neighbors["enzOut"]
            if not enzOut:
                secplxerror = "enzyme parent missing "
            else:
                enzAnno = "<moose:EnzymaticReaction>\n"
                listofname(enzOut, True)
                enzSubt = enzOut
                if len(nameList_) != 1:
                    secplxerror = secplxerror +" multiple enzyme parent present"
                else:
                    for i in range(0, len(nameList_)):
                        enzAnno = enzAnno + "<moose:enzyme>" + \
                            (str(idBeginWith(convertSpecialChar(
                                nameList_[i])))) + "</moose:enzyme>\n"

                    #Finding Substrate, (S)
                    enzSub = enz.neighbors["sub"]
                    if not enzSub:
                        secplxerror = secplxerror + " substrate missing"
                    else:
                        listofname(enzSub, True)
                        enzSubt += enzSub
                        for i in range(0, len(nameList_)):
                            enzAnno = enzAnno + "<moose:substrates>" + \
                            nameList_[i] + "</moose:substrates>\n"

                        #Finding product, which in this case the cplx (SE*)
                        enzPrd = enz.neighbors["cplxDest"]
                        noofPrd = len(enzPrd)
                        if not enzPrd:
                            secplxerror = secplxerror + " enzymecplx missing which act as product "                            
                        else:
                            listofname(enzPrd, True)
                            for i in range(0, len(nameList_)):
                                enzAnno = enzAnno + "<moose:product>" + \
                                    nameList_[i] + "</moose:product>\n"
                            foundEnzymeComplex = True

            if foundEnzymeComplex:
                # Only if S+E->SE* found, reaction is created
                enzyme = cremodel_.createReaction()
                if notesE != "":
                    cleanNotesE = convertNotesSpecialChar(notesE)
                    notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                                    cleanNotesE + "\n\t </body>"
                    enzyme.setNotes(notesStringE)
                
                enzyme.setId(enzsetId)
                enzyme.setName(str(idBeginWith(convertSpecialCharshot(enz.name))))
                enzyme.setFast(False)
                enzyme.setReversible(True)
                k1 = enz.concK1
                k2 = enz.k2
                k3 = enz.k3
                
                enzAnno = enzAnno + "<moose:groupName>" + cleanEnzname + "_" + \
                str(enz.getId().value) + "_" + \
                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
                enzAnno = enzAnno + "<moose:stage>1</moose:stage>\n"
                if enzannoexist:
                    enzAnno = enzAnno + enzGpnCorCol
                enzAnno = enzAnno + "</moose:EnzymaticReaction>"
                enzyme.setAnnotation(enzAnno)
                if enzSubt:
                    rate_law = "k1"
                    noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSubt)
                    rate_law = compt + " * ( " + rate_law + " * " + sRateLaw
                if enzPrd:
                    noofPrd, sRateLaw = getSubprd(cremodel_, True, "prd", enzPrd)
                    rate_law = rate_law + " - " + " k2 " + ' * ' + sRateLaw +" )"
                kl = enzyme.createKineticLaw()
                kl.setFormula(rate_law)
                kl.setNotes("<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" + \
                            rate_law + "\n \t </body>")
                unit = parmUnit(noofSub - 1, cremodel_)
                printParameters(kl, "k1", k1, unit)
                punit = parmUnit(noofPrd - 1, cremodel_)
                printParameters(kl, "k2", k2, punit)

                if groupName != moose.element('/'):
                    if groupName not in groupInfo:
                        groupInfo[groupName]=[enzsetId]
                    else:
                        groupInfo[groupName].append(enzsetId)       
            else:
                if secplxerror:
                    print ("\'"+enz.name+"\' this enzyme is not written to file because,"+ secplxerror)
            
            #Here SE* -> E+ P
            foundEnzymeEP = False
            enzsetIdP = str(idBeginWith(cleanEnzname +
                                        "_" + str(enz.getId().value) +
                                        "_" + str(enz.getDataIndex()) +
                                        "_" + "Product_formation_"))
            cplxeperror = ""
            #enzSubt = ""
            enzOut = enz.neighbors["enzOut"]
            if not enzOut:
                cplxepeerror = "enzyme parent missing "
            else:
                enzAnno2 = "<moose:EnzymaticReaction>\n"
                listofname(enzOut, True)
                #enzSubt = enzOut
                if len(nameList_) != 1:
                    cplxeperror = cplxeperror +" multiple enzyme parent present"
                else:
                    # for i in range(0, len(nameList_)):
                    #     enzEnz = "<moose:enzyme>" + \
                    #             (str(idBeginWith(convertSpecialChar(
                    #             nameList_[i])))) + "</moose:enzyme>\n"
                    #Finding Substrate, which is (SE*)
                    enzSub = enz.neighbors["cplxDest"]
                    noofSub = len(enzSub)
                    listofname(enzSub, True)
                    if not enzSub:
                        cplxeperror = cplxeperror +"complex missing which act as substrate "
                    else:
                        for i in range(0, len(nameList_)):
                            enzAnno2 =enzAnno2 +"<moose:complex>" + \
                                    nameList_[i] + "</moose:complex>\n"
                        listofname(enzOut, True)
                        for i in range(0, len(nameList_)):
                            enzAnno2 = enzAnno2 +"<moose:enzyme>" + \
                                (str(idBeginWith(convertSpecialChar(
                                nameList_[i])))) + "</moose:enzyme>\n"

                        enzPrd = enz.neighbors["prd"]
                        noofPrd = len(enzPrd)
                        if not enzPrd:
                            cplxeperror = cplxeperror + "product missing "
                        else:
                            listofname(enzPrd,True)
                            for i in range(0, len(nameList_)):
                                enzAnno2 = enzAnno2 + "<moose:product>" + \
                                            nameList_[i] + "</moose:product>\n"
                                enzAnno2 += "<moose:groupName>" + cleanEnzname + "_" + \
                                str(enz.getId().value) + "_" + \
                                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
                                enzAnno2 += "<moose:stage>2</moose:stage> \n"
                                if enzannoexist:
                                    enzAnno2 = enzAnno2 + enzGpnCorCol
                                enzAnno2 += "</moose:EnzymaticReaction>"

                            foundEnzymeEP = True
            
            if foundEnzymeEP:
                enzyme = cremodel_.createReaction()
                enzyme.setId(enzsetIdP)
                enzyme.setName(str(idBeginWith(convertSpecialCharshot(enz.name))))
                enzyme.setFast(False)
                enzyme.setReversible(False)
                enzyme.setAnnotation(enzAnno2)
                noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSub)
                enzprdt = ()
                enzPrdt = enzPrd+enzOut
                noofprd, sRateLaw2 = getSubprd(cremodel_, True, "prd", enzPrdt)
                enzrate_law = compt + " * k3" + '*' + sRateLaw
                kl = enzyme.createKineticLaw()
                kl.setFormula(enzrate_law)
                kl.setNotes(
                        "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                        enzrate_law +
                        "\n \t </body>")
                unit = parmUnit(noofSub - 1, cremodel_)
                printParameters(kl, "k3", k3, unit)
                if groupName != moose.element('/'):
                    if groupName not in groupInfo:
                        groupInfo[groupName]=[enzsetIdP]
                    else:
                        groupInfo[groupName].append(enzsetIdP)
            else:
                print (cplxeperror)
        elif(enz.className == "MMenz" or enz.className == "ZombieMMenz"):

            enzSub = enz.neighbors["sub"]
            enzPrd = enz.neighbors["prd"]
            if (len(enzSub) != 0 and len(enzPrd) != 0):
                enzCompt = findCompartment(enz)
                if not isinstance(moose.element(enzCompt), moose.ChemCompt):
                    return -2
                else:
                    compt = enzCompt.name + "_" + \
                        str(enzCompt.getId().value) + "_" + \
                        str(enzCompt.getDataIndex()) + "_"
                enzyme = cremodel_.createReaction()
                enzAnno = " "
                if notesE != "":
                    cleanNotesE = convertNotesSpecialChar(notesE)
                    notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                        cleanNotesE + "\n\t </body>"
                    enzyme.setNotes(notesStringE)
                mmenzsetId = str(idBeginWith(cleanEnzname +
                                             "_" +
                                             str(enz.getId().value) +
                                             "_" +
                                             str(enz.getDataIndex()) +
                                             "_"))
                enzyme.setId(mmenzsetId)
                if groupName != moose.element('/'):
                    if groupName not in groupInfo:
                        groupInfo[groupName]=[mmenzsetId]
                    else:
                        groupInfo[groupName].append(mmenzsetId)
                enzyme.setName(str(idBeginWith(convertSpecialCharshot(enz.name))))
                #enzyme.setName(cleanEnzname)
                enzyme.setFast(False)
                enzyme.setReversible(True)
                if enzannoexist:
                    enzAnno = enzAnno + enzGpnCorCol
                    enzAnno = "<moose:EnzymaticReaction>\n" + \
                        enzGpnCorCol + "</moose:EnzymaticReaction>"
                    enzyme.setAnnotation(enzAnno)
                Km = enz.Km
                kcat = enz.kcat
                enzSub = enz.neighbors["sub"]
                noofSub, sRateLawS = getSubprd(cremodel_, False, "sub", enzSub)
                #sRate_law << rate_law.str();
                # Modifier
                enzMod = enz.neighbors["enzDest"]
                noofMod, sRateLawM = getSubprd(cremodel_, False, "enz", enzMod)
                enzPrd = enz.neighbors["prd"]
                noofPrd, sRateLawP = getSubprd(cremodel_, False, "prd", enzPrd)
                kl = enzyme.createKineticLaw()
                fRate_law = compt + " * ( kcat * " + sRateLawS + " * " + sRateLawM + \
                    " / ( Km" + " + " + sRateLawS + "))"
                kl.setFormula(fRate_law)
                kl.setNotes(
                    "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                    fRate_law +
                    "\n \t </body>")
                KmUnit(cremodel_)
                printParameters(kl, "Km", Km, "mmole_per_litre")
                kcatUnit = parmUnit(0, cremodel_)
                printParameters(kl, "kcat", kcat, kcatUnit)
Ejemplo n.º 16
0
def writeEnz(modelpath, cremodel_, sceneitems):
    for enz in moose.wildcardFind(modelpath + '/##[ISA=EnzBase]'):
        enzannoexist = False
        enzGpnCorCol = " "
        cleanEnzname = convertSpecialChar(enz.name)
        enzSubt = ()
        compt = ""
        notesE = ""
        if moose.exists(enz.path + '/info'):
            Anno = moose.Annotator(enz.path + '/info')
            notesE = Anno.notes
            element = moose.element(enz)
            ele = getGroupinfo(element)
            if element.className == "Neutral" or sceneitems or Anno.x or Anno.y:
                    enzannoexist = True
            if enzannoexist:
                enzAnno = "<moose:ModelAnnotation>\n"
                if ele.className == "Neutral":
                    enzGpnCorCol =  "<moose:Group>" + ele.name + "</moose:Group>\n"
                if sceneitems:
                    #Saved from GUI, then scene co-ordinates are passed
                    enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
                            str(sceneitems[enz]['x']) + "</moose:xCord>\n" + \
                            "<moose:yCord>" + \
                            str(sceneitems[enz]['y'])+ "</moose:yCord>\n"
                else:
                    #Saved from cmdline,genesis coordinates are kept as its
                    # SBML, cspace, python, then auto-coordinates are done
                    #and coordinates are updated in moose Annotation field
                    enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
                            str(Anno.x) + "</moose:xCord>\n" + \
                            "<moose:yCord>" + \
                            str(Anno.y)+ "</moose:yCord>\n"
                if Anno.color:
                    enzGpnCorCol = enzGpnCorCol + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
                if Anno.textColor:
                    enzGpnCorCol = enzGpnCorCol + "<moose:textColor>" + \
                        Anno.textColor + "</moose:textColor>\n"

        if (enz.className == "Enz" or enz.className == "ZombieEnz"):
            enzyme = cremodel_.createReaction()
            if notesE != "":
                cleanNotesE = convertNotesSpecialChar(notesE)
                notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                    cleanNotesE + "\n\t </body>"
                enzyme.setNotes(notesStringE)
            comptVec = findCompartment(moose.element(enz))
            if not isinstance(moose.element(comptVec), moose.ChemCompt):
                return -2
            else:
                compt = comptVec.name + "_" + \
                    str(comptVec.getId().value) + "_" + \
                    str(comptVec.getDataIndex()) + "_"

            enzyme.setId(str(idBeginWith(cleanEnzname +
                                         "_" +
                                         str(enz.getId().value) +
                                         "_" +
                                         str(enz.getDataIndex()) +
                                         "_" +
                                         "Complex_formation_")))
            enzyme.setName(cleanEnzname)
            enzyme.setFast(False)
            enzyme.setReversible(True)
            k1 = enz.concK1
            k2 = enz.k2
            k3 = enz.k3
            enzAnno = " "
            enzAnno = "<moose:EnzymaticReaction>\n"

            enzOut = enz.neighbors["enzOut"]

            if not enzOut:
                print(" Enzyme parent missing for ", enz.name)
            else:
                listofname(enzOut, True)
                enzSubt = enzOut
                for i in range(0, len(nameList_)):
                    enzAnno = enzAnno + "<moose:enzyme>" + \
                        (str(idBeginWith(convertSpecialChar(
                            nameList_[i])))) + "</moose:enzyme>\n"
            #noofSub,sRateLaw = getSubprd(cremodel_,True,"sub",enzSub)
            # for i in range(0,len(nameList_)):
            #    enzAnno=enzAnno+"<moose:enzyme>"+nameList_[i]+"</moose:enzyme>\n"
            #rec_order  = noofSub
            #rate_law = "k1"+"*"+sRateLaw

            enzSub = enz.neighbors["sub"]
            if not enzSub:
                print("Enzyme \"", enz.name, "\" substrate missing")
            else:
                listofname(enzSub, True)
                enzSubt += enzSub
                for i in range(0, len(nameList_)):
                    enzAnno = enzAnno + "<moose:substrates>" + \
                        nameList_[i] + "</moose:substrates>\n"
            if enzSubt:
                rate_law = "k1"
                noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSubt)
                #rec_order = rec_order + noofSub
                rec_order = noofSub
                rate_law = compt + " * " + rate_law + "*" + sRateLaw

            enzPrd = enz.neighbors["cplxDest"]
            if not enzPrd:
                print("Enzyme \"", enz.name, "\"product missing")
            else:
                noofPrd, sRateLaw = getSubprd(cremodel_, True, "prd", enzPrd)
                for i in range(0, len(nameList_)):
                    enzAnno = enzAnno + "<moose:product>" + \
                        nameList_[i] + "</moose:product>\n"
                rate_law = rate_law + " - " + compt + "* k2" + '*' + sRateLaw

            prd_order = noofPrd
            enzAnno = enzAnno + "<moose:groupName>" + cleanEnzname + "_" + \
                str(enz.getId().value) + "_" + \
                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
            enzAnno = enzAnno + "<moose:stage>1</moose:stage>\n"
            if enzannoexist:
                enzAnno = enzAnno + enzGpnCorCol
            enzAnno = enzAnno + "</moose:EnzymaticReaction>"
            enzyme.setAnnotation(enzAnno)
            kl = enzyme.createKineticLaw()
            kl.setFormula(rate_law)
            kl.setNotes(
                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                rate_law +
                "\n \t </body>")
            punit = parmUnit(prd_order - 1, cremodel_)
            printParameters(kl, "k2", k2, punit)

            unit = parmUnit(rec_order - 1, cremodel_)
            printParameters(kl, "k1", k1, unit)
            enzyme = cremodel_.createReaction()
            enzyme.setId(str(idBeginWith(cleanEnzname +
                                         "_" +
                                         str(enz.getId().value) +
                                         "_" +
                                         str(enz.getDataIndex()) +
                                         "_" +
                                         "Product_formation_")))
            enzyme.setName(cleanEnzname)
            enzyme.setFast(False)
            enzyme.setReversible(False)
            enzAnno2 = "<moose:EnzymaticReaction>"

            enzSub = enz.neighbors["cplxDest"]
            if not enzSub:
                print(" complex missing from ", enz.name)
            else:
                noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSub)
                for i in range(0, len(nameList_)):
                    enzAnno2 = enzAnno2 + "<moose:complex>" + \
                        nameList_[i] + "</moose:complex>\n"

            enzEnz = enz.neighbors["enzOut"]
            if not enzEnz:
                print("Enzyme parent missing for ", enz.name)
            else:
                noofEnz, sRateLaw1 = getSubprd(cremodel_, True, "prd", enzEnz)
                for i in range(0, len(nameList_)):
                    enzAnno2 = enzAnno2 + "<moose:enzyme>" + \
                        nameList_[i] + "</moose:enzyme>\n"
            enzPrd = enz.neighbors["prd"]
            if enzPrd:
                noofprd, sRateLaw2 = getSubprd(cremodel_, True, "prd", enzPrd)
            else:
                print("Enzyme \"", enz.name, "\" product missing")
            for i in range(0, len(nameList_)):
                enzAnno2 = enzAnno2 + "<moose:product>" + \
                    nameList_[i] + "</moose:product>\n"
            enzAnno2 += "<moose:groupName>" + cleanEnzname + "_" + \
                str(enz.getId().value) + "_" + \
                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
            enzAnno2 += "<moose:stage>2</moose:stage> \n"
            if enzannoexist:
                enzAnno2 = enzAnno2 + enzGpnCorCol
            enzAnno2 += "</moose:EnzymaticReaction>"
            enzyme.setAnnotation(enzAnno2)

            enzrate_law = compt + " * k3" + '*' + sRateLaw
            kl = enzyme.createKineticLaw()
            kl.setFormula(enzrate_law)
            kl.setNotes(
                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                enzrate_law +
                "\n \t </body>")
            unit = parmUnit(noofPrd - 1, cremodel_)
            printParameters(kl, "k3", k3, unit)

        elif(enz.className == "MMenz" or enz.className == "ZombieMMenz"):
            enzSub = enz.neighbors["sub"]
            enzPrd = enz.neighbors["prd"]
            if (len(enzSub) != 0 and len(enzPrd) != 0):
                enzCompt = findCompartment(enz)
                if not isinstance(moose.element(enzCompt), moose.ChemCompt):
                    return -2
                else:
                    compt = enzCompt.name + "_" + \
                        str(enzCompt.getId().value) + "_" + \
                        str(enzCompt.getDataIndex()) + "_"
                enzyme = cremodel_.createReaction()
                enzAnno = " "
                if notesE != "":
                    cleanNotesE = convertNotesSpecialChar(notesE)
                    notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                        cleanNotesE + "\n\t </body>"
                    enzyme.setNotes(notesStringE)
                enzyme.setId(str(idBeginWith(cleanEnzname +
                                             "_" +
                                             str(enz.getId().value) +
                                             "_" +
                                             str(enz.getDataIndex()) +
                                             "_")))
                enzyme.setName(cleanEnzname)
                enzyme.setFast(False)
                enzyme.setReversible(True)
                if enzannoexist:
                    enzAnno = enzAnno + enzGpnCorCol
                    enzAnno = "<moose:EnzymaticReaction>\n" + \
                        enzGpnCorCol + "</moose:EnzymaticReaction>"
                    enzyme.setAnnotation(enzAnno)
                Km = enz.Km
                kcat = enz.kcat
                enzSub = enz.neighbors["sub"]
                noofSub, sRateLawS = getSubprd(cremodel_, False, "sub", enzSub)
                #sRate_law << rate_law.str();
                # Modifier
                enzMod = enz.neighbors["enzDest"]
                noofMod, sRateLawM = getSubprd(cremodel_, False, "enz", enzMod)
                enzPrd = enz.neighbors["prd"]
                noofPrd, sRateLawP = getSubprd(cremodel_, False, "prd", enzPrd)
                kl = enzyme.createKineticLaw()
                fRate_law = "kcat *" + sRateLawS + "*" + sRateLawM + \
                    "/(" + compt + " * (" + "Km" + "+" + sRateLawS + "))"
                kl.setFormula(fRate_law)
                kl.setNotes(
                    "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
                    fRate_law +
                    "\n \t </body>")
                printParameters(kl, "Km", Km, "substance")
                kcatUnit = parmUnit(0, cremodel_)
                printParameters(kl, "kcat", kcat, kcatUnit)
Ejemplo n.º 17
0
def mooseWriteSBML(modelpath, filename, sceneitems={}):
    global foundLibSBML_
    msg = " "
    if not foundLibSBML_:
        print('No python-libsbml found.'
            '\nThis module can be installed by following command in terminal:'
            '\n\t easy_install python-libsbml or'
            '\n\t apt-get install python-libsbml'
            )
        return -2, "Could not save the model in to SBML file. \nThis module can be installed by following command in terminal: \n\t easy_install python-libsbml or \n\t apt-get install python-libsbml",''

    #sbmlDoc = SBMLDocument(3, 1)
    filepath, filenameExt = os.path.split(filename)
    if filenameExt.find('.') != -1:
        filename = filenameExt[:filenameExt.find('.')]
    else:
        filename = filenameExt
    # validatemodel
    sbmlOk = False
    global spe_constTrue
    spe_constTrue = []
    global nameList_
    nameList_ = []

    xcord,ycord = [],[]
    if not moose.exists(modelpath):
        return False, "Path doesn't exist"
    elif moose.exists(modelpath):
        mObj = moose.wildcardFind(moose.element(modelpath).path+'/##[ISA=PoolBase]'+','+
                                  moose.element(modelpath).path+'/##[ISA=ReacBase]'+','+
                                  moose.element(modelpath).path+'/##[ISA=EnzBase]'+','+
                                  moose.element(modelpath).path+'/##[ISA=StimulusTable]')
        for p in mObj:
            if not isinstance(moose.element(p.parent),moose.CplxEnzBase):
                if moose.exists(p.path+'/info'):
                    xcord.append(moose.element(p.path+'/info').x)
                    ycord.append(moose.element(p.path+'/info').y)
        recalculatecoordinates(modelpath,mObj,xcord,ycord)
    positionInfoexist = False

    xmlns = SBMLNamespaces(3, 1)
    xmlns.addNamespace("http://www.w3.org/1999/xhtml", "xhtml")
    xmlns.addNamespace("http://www.moose.ncbs.res.in", "moose")
    xmlns.addNamespace("http://www.sbml.org/sbml/level3/version1/groups/version1", "groups")
    sbmlDoc = SBMLDocument(xmlns)
    sbmlDoc.setPackageRequired("groups",bool(0))

    cremodel_ = sbmlDoc.createModel()
    cremodel_.setId(filename)
    cremodel_.setTimeUnits("time")
    cremodel_.setExtentUnits("substance")
    cremodel_.setSubstanceUnits("substance")
    cremodel_.setVolumeUnits("volume")
    cremodel_.setAreaUnits("area")
    cremodel_.setLengthUnits("length")
    neutralNotes = ""

    specieslist = moose.wildcardFind(modelpath + '/##[ISA=PoolBase]')
    if specieslist:
        neutralPath = getGroupinfo(specieslist[0])
        if moose.exists(neutralPath.path + '/info'):
            neutralInfo = moose.element(neutralPath.path + '/info')
            neutralNotes = neutralInfo.notes
        if neutralNotes != "":
            cleanNotes = convertNotesSpecialChar(neutralNotes)
            notesString = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                neutralNotes + "\n\t </body>"
            cremodel_.setNotes(notesString)

    srcdesConnection = {}

    writeUnits(cremodel_)
    modelAnno = writeSimulationAnnotation(modelpath)
    if modelAnno:
        cremodel_.setAnnotation(modelAnno)
    groupInfo = {}
    compartexist, groupInfo = writeCompt(modelpath, cremodel_)
    if compartexist == True:
        species = writeSpecies( modelpath,cremodel_,sbmlDoc,sceneitems,groupInfo)
        if species:
            writeFunc(modelpath, cremodel_)
        reacGroup = {}
        writeReac(modelpath, cremodel_, sceneitems,groupInfo)
        writeEnz(modelpath, cremodel_, sceneitems,groupInfo)
        if groupInfo:
            for key,value in groupInfo.items():
                mplugin = cremodel_.getPlugin("groups")
                group = mplugin.createGroup()
                name = str(idBeginWith(moose.element(key).name))
                group.setId(name)
                group.setKind("collection")
                if moose.exists(key.path+'/info'):
                    ginfo = moose.element(key.path+'/info')
                else:
                    moose.Annotator(key.path+'/info')
                groupCompartment = findCompartment(key)
                if ginfo.color != '':
                    grpAnno = "<moose:GroupAnnotation>"
                    grpAnno = grpAnno + "<moose:Compartment>" + groupCompartment.name + "</moose:Compartment>\n"
                    if ginfo.color:
                        grpAnno = grpAnno + "<moose:bgColor>" + ginfo.color + "</moose:bgColor>\n"
                    grpAnno = grpAnno + "</moose:GroupAnnotation>"
                    group.setAnnotation(grpAnno)

                for values in value:
                    member = group.createMember()
                    member.setIdRef(values)
        consistencyMessages = ""
        SBMLok = validateModel(sbmlDoc)
        if (SBMLok):
            writeTofile = filepath + "/" + filename + '.xml'
            writeSBMLToFile(sbmlDoc, writeTofile)
            return True, consistencyMessages, writeTofile

        if (not SBMLok):
            #cerr << "Errors encountered " << endl
            consistencyMessages = "Errors encountered"
            return -1, consistencyMessages
    else:
        return False, "Atleast one compartment should exist to write SBML"
Ejemplo n.º 18
0
def writeSpecies(modelpath, cremodel_, sbmlDoc, sceneitems):
    # getting all the species
    for spe in moose.wildcardFind(modelpath + '/##[ISA=PoolBase]'):
        sName = convertSpecialChar(spe.name)
        comptVec = findCompartment(spe)
        speciannoexist = False
        speciGpname = ""

        if not isinstance(moose.element(comptVec), moose.ChemCompt):
            return -2
        else:
            compt = comptVec.name + "_" + \
                str(comptVec.getId().value) + "_" + \
                str(comptVec.getDataIndex()) + "_"
            s1 = cremodel_.createSpecies()
            spename = sName + "_" + \
                str(spe.getId().value) + "_" + str(spe.getDataIndex()) + "_"
            spename = str(idBeginWith(spename))
            s1.setId(spename)

            if spename.find(
                    "cplx") != -1 and isinstance(moose.element(spe.parent), moose.EnzBase):
                enz = spe.parent
                if (moose.element(enz.parent), moose.PoolBase):
                    # print " found a cplx name ",spe.parent,
                    # moose.element(spe.parent).parent
                    enzname = enz.name
                    enzPool = (enz.parent).name
                    sName = convertSpecialChar(
                        enzPool + "_" + enzname + "_" + sName)

            s1.setName(sName)
            # s1.setInitialAmount(spe.nInit)
            s1.setInitialConcentration(spe.concInit)
            s1.setCompartment(compt)
            #  Setting BoundaryCondition and constant as per this rule for BufPool
            #  -constanst  -boundaryCondition  -has assignment/rate Rule  -can be part of sub/prd
            #   false           true              yes                       yes
            #   true            true               no                       yes
            if spe.className == "BufPool" or spe.className == "ZombieBufPool":
                # BoundaryCondition is made for buff pool
                s1.setBoundaryCondition(True)

                if moose.exists(spe.path + '/func'):
                    bpf = moose.element(spe.path)
                    for fp in bpf.children:
                        if fp.className == "Function" or fp.className == "ZombieFunction":
                            if len(moose.element(
                                    fp.path + '/x').neighbors["input"]) > 0:
                                s1.setConstant(False)
                            else:
                                # if function exist but sumtotal object doesn't
                                # exist
                                spe_constTrue.append(spename)
                                s1.setConstant(True)
                else:
                    spe_constTrue.append(spename)
                    s1.setConstant(True)
            else:
                # if not bufpool then Pool, then
                s1.setBoundaryCondition(False)
                s1.setConstant(False)
            s1.setUnits("substance")
            s1.setHasOnlySubstanceUnits(False)
            if moose.exists(spe.path + '/info'):
                Anno = moose.Annotator(spe.path + '/info')
                if Anno.notes != "":
                    cleanNotesS = convertNotesSpecialChar(Anno.notes)
                    notesStringS = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
                        cleanNotesS + "\n\t </body>"
                    s1.setNotes(notesStringS)


                element = moose.element(spe)
                ele = getGroupinfo(element)
                if element.className == "Neutral" or Anno.color or Anno.textColor or sceneitems or Anno.x or Anno.y:
                    speciannoexist = True
                if speciannoexist:
                    speciAnno = "<moose:ModelAnnotation>\n"
                    if ele.className == "Neutral":
                        speciAnno = speciAnno + "<moose:Group>" + ele.name + "</moose:Group>\n"
                    if sceneitems:
                        #Saved from GUI, then scene co-ordinates are passed
                        speciAnno = speciAnno + "<moose:xCord>" + \
                                str(sceneitems[spe]['x']) + "</moose:xCord>\n" + \
                                "<moose:yCord>" + \
                                str(sceneitems[spe]['y'])+ "</moose:yCord>\n"
                    else:
                        #Saved from cmdline,genesis coordinates are kept as its
                        # SBML, cspace, python, then auto-coordinates are done
                        #and coordinates are updated in moose Annotation field
                        speciAnno = speciAnno + "<moose:xCord>" + \
                                str(Anno.x) + "</moose:xCord>\n" + \
                                "<moose:yCord>" + \
                                str(Anno.y)+ "</moose:yCord>\n"
                    if Anno.color:
                        speciAnno = speciAnno + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
                    if Anno.textColor:
                        speciAnno = speciAnno + "<moose:textColor>" + \
                            Anno.textColor + "</moose:textColor>\n"
                    speciAnno = speciAnno + "</moose:ModelAnnotation>"
                    s1.setAnnotation(speciAnno)
    return True
Ejemplo n.º 19
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
    positionInfoExist = True
    meshEntry = {}
    if meshEntry:
        meshEntry.clear()
    else:
        meshEntry = {}
    xcord = []
    ycord = []
    objPar = collections.OrderedDict()

    for compt in moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]'):
        groupColor = []
        try:
            meshEntry[moose.element(compt)]
        except KeyError:
            # Compt  is not present
            meshEntry[moose.element(compt)] = {}
            objPar[moose.element(compt)] = moose.element('/')

        for grp in moose.wildcardFind(compt.path + '/##[TYPE=Neutral]'):
            grpinfo = moose.Annotator(moose.element(grp).path + '/info')
            validatecolor = colorCheck(grpinfo.color, "bg")
            validatedgrpcolor = str(QColor(validatecolor).name())

            groupColor.append(validatedgrpcolor)
            grp_cmpt = findGroup_compt(grp.parent)

            try:
                meshEntry[moose.element(grp)]
            except KeyError:
                # Grp is not present
                meshEntry[moose.element(grp)] = {}
                objPar[moose.element(grp)] = moose.element(grp_cmpt)

    for compt in moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]'):
        for m in moose.wildcardFind(compt.path + '/##[ISA=PoolBase]'):
            if not re.search("xfer", m.name):
                grp_cmpt = findGroup_compt(m)
                xcord.append(xyPosition(m.path + '/info', 'x'))
                ycord.append(xyPosition(m.path + '/info', 'y'))
                if isinstance(moose.element(grp_cmpt), moose.Neutral):
                    if isinstance(moose.element(m.parent), moose.EnzBase):
                        populateMeshEntry(meshEntry, grp_cmpt, "cplx", m)
                    else:
                        populateMeshEntry(meshEntry, grp_cmpt, "pool", m)
                else:
                    if isinstance(moose.element(m.parent), moose.EnzBase):
                        populateMeshEntry(meshEntry, compt, "cplx", m)
                    else:
                        populateMeshEntry(meshEntry, compt, "pool", m)

        for r in moose.wildcardFind(compt.path + '/##[ISA=ReacBase]'):
            rgrp_cmpt = findGroup_compt(r)
            xcord.append(xyPosition(r.path + '/info', 'x'))
            ycord.append(xyPosition(r.path + '/info', 'y'))
            if isinstance(moose.element(rgrp_cmpt), moose.Neutral):
                populateMeshEntry(meshEntry, rgrp_cmpt, "reaction", r)
            else:
                populateMeshEntry(meshEntry, compt, "reaction", r)

        for e in moose.wildcardFind(compt.path + '/##[ISA=EnzBase]'):
            egrp_cmpt = findGroup_compt(e)
            xcord.append(xyPosition(e.path + '/info', 'x'))
            ycord.append(xyPosition(e.path + '/info', 'y'))
            if isinstance(moose.element(egrp_cmpt), moose.Neutral):
                populateMeshEntry(meshEntry, egrp_cmpt, "enzyme", e)
            else:
                populateMeshEntry(meshEntry, compt, "enzyme", e)

        for f in moose.wildcardFind(compt.path + '/##[ISA=Function]'):
            fgrp_cmpt = findGroup_compt(f)
            if isinstance(moose.element(fgrp_cmpt), moose.Neutral):
                populateMeshEntry(meshEntry, fgrp_cmpt, "function", f)
            else:
                populateMeshEntry(meshEntry, compt, "function", f)

        for t in moose.wildcardFind(compt.path + '/##[ISA=StimulusTable]'):
            tgrp_cmpt = findGroup_compt(t)
            xcord.append(xyPosition(t.path + '/info', 'x'))
            ycord.append(xyPosition(t.path + '/info', 'y'))
            if isinstance(moose.element(tgrp_cmpt), moose.Neutral):
                populateMeshEntry(meshEntry, tgrp_cmpt, "stimTab", t)
            else:
                populateMeshEntry(meshEntry, compt, "stimTab", t)

    xmin = min(xcord)
    xmax = max(xcord)
    ymin = min(ycord)
    ymax = max(ycord)
    positionInfoExist = not (len(np.nonzero(xcord)[0]) == 0
                             and len(np.nonzero(ycord)[0]) == 0)
    return (objPar, meshEntry, xmin, xmax, ymin, ymax, positionInfoExist)