def getInstanceRate(self, math, compartmentList, reversible, rReactant, rProduct): #remove compartments from expression math = self.getPrunnedTree(math, compartmentList) if reversible: if math.getCharacter() == '-' and math.getNumChildren() > 1: rateL, nl = (self.removeFactorFromMath( math.getLeftChild().deepCopy(), rReactant, rProduct)) rateR, nr = (self.removeFactorFromMath( math.getRightChild().deepCopy(), rProduct, rReactant)) else: rateL, nl = self.removeFactorFromMath(math, rReactant, rProduct) rateL = "if({0} >= 0 ,{0},0)".format(rateL) rateR, nr = self.removeFactorFromMath(math, rReactant, rProduct) rateR = "if({0} < 0 ,-({0}),0)".format(rateR) nl, nr = 1, 1 else: rateL, nl = (self.removeFactorFromMath(math.deepCopy(), rReactant, rProduct)) rateR, nr = '0', '-1' if reversible: pass return rateL, rateR
def removeFactorFromMath(self, math, reactants, products): remainderPatterns = [] highStoichoiMetryFactor = 1 for x in reactants: highStoichoiMetryFactor *= factorial(x[1]) y = [i[1] for i in products if i[0] == x[0]] y = y[0] if len(y) > 0 else 0 #TODO: check if this actually keeps the correct dynamics # this is basically there to address the case where theres more products #than reactants (synthesis) if x[1] > y: highStoichoiMetryFactor /= comb(int(x[1]), int(y)) for counter in range(0, int(x[1])): remainderPatterns.append(x[0]) #for x in products: # highStoichoiMetryFactor /= math.factorial(x[1]) #remainderPatterns = [x[0] for x in reactants] math = self.getPrunnedTree(math, remainderPatterns) rateR = libsbml.formulaToString(math) for element in remainderPatterns: rateR = 'if({0} >0,({1})/{0} ,0)'.format(element, rateR) if highStoichoiMetryFactor != 1: rateR = '{0}*{1}'.format(rateR, int(highStoichoiMetryFactor)) return rateR, math.getNumChildren()
def getPrunnedTree(self, math, remainderPatterns): ''' removes the remainderPatterns leafs from the math tree ''' while (math.getCharacter() == '*' or math.getCharacter() == '/') and len(remainderPatterns) > 0: if libsbml.formulaToString( math.getLeftChild()) in remainderPatterns: remainderPatterns.remove( libsbml.formulaToString(math.getLeftChild())) math = math.getRightChild() elif libsbml.formulaToString( math.getRightChild()) in remainderPatterns: remainderPatterns.remove( libsbml.formulaToString(math.getRightChild())) math = math.getLeftChild() else: if (math.getLeftChild().getCharacter()) == '*': math.replaceChild( 0, self.getPrunnedTree(math.getLeftChild(), remainderPatterns)) if (math.getRightChild().getCharacter()) == '*': math.replaceChild( math.getNumChildren() - 1, self.getPrunnedTree(math.getRightChild(), remainderPatterns)) break return math
def removeFactorFromMath(self, math, reactants, products): remainderPatterns = [] highStoichoiMetryFactor = 1 for x in reactants: highStoichoiMetryFactor *= factorial(x[1]) y = [i[1] for i in products if i[0] == x[0]] y = y[0] if len(y) > 0 else 0 #TODO: check if this actually keeps the correct dynamics # this is basically there to address the case where theres more products #than reactants (synthesis) if x[1] > y: highStoichoiMetryFactor /= comb(int(x[1]), int(y)) for counter in range(0, int(x[1])): remainderPatterns.append(x[0]) #for x in products: # highStoichoiMetryFactor /= math.factorial(x[1]) #remainderPatterns = [x[0] for x in reactants] math = self.getPrunnedTree(math,remainderPatterns) rateR = libsbml.formulaToString(math) for element in remainderPatterns: rateR = 'if({0} >0,({1})/{0} ,0)'.format(element,rateR) if highStoichoiMetryFactor != 1: rateR = '{0}*{1}'.format(rateR, int(highStoichoiMetryFactor)) return rateR,math.getNumChildren()
def getInstanceRate(self,math,compartmentList, reversible,rReactant,rProduct): #remove compartments from expression math = self.getPrunnedTree(math, compartmentList) if reversible: if math.getCharacter() == '-' and math.getNumChildren() > 1: rateL, nl = (self.removeFactorFromMath( math.getLeftChild().deepCopy(), rReactant, rProduct)) rateR, nr = (self.removeFactorFromMath( math.getRightChild().deepCopy(), rProduct, rReactant)) else: rateL, nl = self.removeFactorFromMath(math, rReactant, rProduct) rateL = "if({0} >= 0 ,{0},0)".format(rateL) rateR, nr = self.removeFactorFromMath(math, rReactant, rProduct) rateR = "if({0} < 0 ,-({0}),0)".format(rateR) nl, nr = 1,1 else: rateL, nl = (self.removeFactorFromMath(math.deepCopy(), rReactant,rProduct)) rateR, nr = '0', '-1' if reversible: pass return rateL,rateR
def add_missing_params(self, model, math): if model is None or math is None: return if math.getType() == libsbml.AST_NAME: id = math.getName() param = model.getElementBySId(id) if param is None: param = model.createParameter() param.setId(id) param.setValue(1) for i in range(math.getNumChildren()): self.add_missing_params(model, math.getChild(i))
def getPrunnedTree(self,math,remainderPatterns): ''' removes the remainderPatterns leafs from the math tree ''' while (math.getCharacter() == '*' or math.getCharacter() == '/') and len(remainderPatterns) > 0: if libsbml.formulaToString(math.getLeftChild()) in remainderPatterns: remainderPatterns.remove(libsbml.formulaToString(math.getLeftChild())) math = math.getRightChild() elif libsbml.formulaToString(math.getRightChild()) in remainderPatterns: remainderPatterns.remove(libsbml.formulaToString(math.getRightChild())) math = math.getLeftChild() else: if(math.getLeftChild().getCharacter()) == '*': math.replaceChild(0, self.getPrunnedTree(math.getLeftChild(), remainderPatterns)) if(math.getRightChild().getCharacter()) == '*': math.replaceChild(math.getNumChildren() - 1,self.getPrunnedTree(math.getRightChild(), remainderPatterns)) break return math
def readSBML(self,filename): document = libsbml.readSBML(filename) if (document.getNumErrors() > 0): document.printErrors(); return(1); model = document.getModel(); if (model == None): print("The model is empty." + "\n"); return(1); if model.getNumCompartments()==0: print("There is no compartment in the model." + "\n"); return(1); for cc in range(model.getNumCompartments()): try: self.add_compartment(model.getCompartment(cc).getId(),model.getCompartment(cc).getSize()) except: print("Could not add the compartment number %d."%cc) return(1); if model.getNumSpecies()==0: print("There is no species in the model." + "\n"); return(1); for mm in range(model.getNumSpecies()): try: met_name = model.getSpecies(mm).getId() isConstant = model.getSpecies(mm).getConstant() compart = model.getSpecies(mm).getCompartment() quantity = model.getSpecies(mm).getInitialAmount() if quantity ==0 : concentration = model.getSpecies(mm).getInitialConcentration() met = self.addMetabolite(met_name,compart,concentration=concentration) else: met = self.addMetabolite(met_name,compart,quantity=quantity) if model.getSpecies(mm).getName() is not "": met.longName = model.getSpecies(mm).getName() met.isConstant = isConstant if isConstant: met.exchangeCarbon = False annotation = model.getSpecies(mm).getAnnotationString() compoundID = re.search("C\d{5}",annotation) chebiID = re.search("CHEBI.(\d{5})",annotation) if compoundID is not None: compoundID = compoundID.group(0) met.compoundID = compoundID if chebiID is not None: met.chebiID = chebiID.group(1) except: import pdb;pdb.set_trace() print("Could not add the metabolite number %d."%mm) return(1); for pp in range(model.getListOfParameters().size()): try: param = model.getListOfParameters().get(pp) pname = param.getName() pid = param.getId() if pname == "": pname = pid param = self.addParameter(pname,param.getValue(),None) param.id = pid self.globalParameters.append(param) except: print("Could not add the global parameter number %d."%pp) if model.getNumReactions()==0: print("There is no species in the model." + "\n"); return(1); this_dir, this_filename = os.path.split(__file__) DATA_PATH = os.path.join(this_dir, "knownUnrenderedMathML") knownUnrenderedMathML = [] for line in open(DATA_PATH).read().split("\n"): if line is not "": knownUnrenderedMathML.append(UnrenderedMathML(line)) for ff in range(model.getNumFunctionDefinitions()): isComputable = True try: fd = model.getFunctionDefinition(ff) math = fd.getMath() arguments = [(math.getChild(n)).getName() for n in range ( math.getNumChildren()-1)] math = math.getChild(math.getNumChildren() - 1) formula = libsbml.formulaToString(math) nameFd = fd.getId() for unknown in knownUnrenderedMathML: if unknown.identify(formula): formula = unknown.replace(formula) func = self.addFunctionDefinition(nameFd,formula,arguments) isComputable = bool(func.isComputable()) # if not isComputable: # # import pdb;pdb.set_trace() # assert(isComputable) except: if not bool(func.isComputable()): print("Function number %s is not computable."%ff) print("Could not add the function definition number %d."%ff) return(1); for rr in range(model.getNumReactions()): theSBMLreac = model.getReaction(rr) reac_name = theSBMLreac.getId() metabolite_names = [] stoichiometry = [] try: for mm in range(theSBMLreac.getNumReactants()): metabolite_names.append(theSBMLreac.getReactant(mm).getSpecies()) stoichiometry.append(-theSBMLreac.getReactant(mm).getStoichiometry()) for mm in range(theSBMLreac.getNumModifiers()): metabolite_names.append(theSBMLreac.getModifier(mm).getSpecies()) stoichiometry.append(0) for mm in range(theSBMLreac.getNumProducts()): metabolite_names.append(theSBMLreac.getProduct(mm).getSpecies()) stoichiometry.append(theSBMLreac.getProduct(mm).getStoichiometry()) kineticLaw = theSBMLreac.getKineticLaw() kineticLawMath = libsbml.formulaToString(kineticLaw.getMath()) for unknown in knownUnrenderedMathML: if unknown.identify(kineticLawMath): kineticLawMath = unknown.replace(kineticLawMath) reac = self.addReaction(reac_name,metabolite_names,stoichiometry,kineticLawMath) reac.longName = theSBMLreac.getName() for pp in range(kineticLaw.getListOfParameters().size()): param = kineticLaw.getListOfParameters().get(pp) pname = param.getName() if pname == "": pname = param.getId() self.addParameter(pname,param.getValue(),reac) funcDef = re.findall("(\w+)\([,\s\w]+?\)",kineticLawMath) for ff in funcDef: func_result = self.functionDefinitions[getNames(self.functionDefinitions).index(ff)] reac.functionDefinitions.append(func_result) func_result.reactions.append(reac) except: print("Could not add the reaction number %d."%rr) return(1);