Module modelmage :: Module model
[hide private]
[frames] | no frames]

Source Code for Module modelmage.model

  1  #-----------------------------------------------# 
  2  #                  modelMaGe                    # 
  3  #                                               # 
  4  #                 v1.0beta September 2009           # 
  5  #       Joerg Schaber, Max Floettmann and Jian Li   # 
  6  #                                               # 
  7  #                http://modelmage.org               # 
  8  #-----------------------------------------------# 
  9  ## @file    model.py 
 10  ## @brief   Handles SBML models and bipartide graphs. 
 11  ## @author  Max Floettmann und Jian Li 
 12  ##  
 13  ## This file is part of modelMaGe.  Please visit http://modelMaGe.org for more 
 14  ## information about modelMaGe, and the latest version of modelMaGe. 
 15  ## 
 16   
 17  import os 
 18  import libsbml as lSBML 
 19  import networkx as NW 
 20  #from mmexceptions import * 
 21  from xml.dom import minidom 
 22   
23 -class Model:
24 __sbmlDocument = None 25 __graph = None 26 history = None 27 filename = None 28 __idNameMap = {} 29 __nameIdMap = {} 30 __stoich = {} 31 reactionId = {} # {reactionId:reactionObject} 32 speciesId = {} # {speciesId:speciesObject} 33 34 functions = [] # list of user defined functions of a model 35 reactionFunctions = {} # {reactionId:functionId} function that belongs to a reaction 36 reactionSubPar = {} # {reactionId:([substrates and modifiers],[parameters])} 37
38 - def __init__(self, document=None, filename=None, history=None):
39 if filename and not document: 40 self.readSBML(filename) 41 self.__idNameMap, self.__nameIdMap = self.__buildMaps(self.__sbmlDocument.getModel()) 42 if document: 43 self.setSbmlDocument(document) 44 self.__idNameMap, self.__nameIdMap = self.__buildMaps(self.__sbmlDocument.getModel()) 45 46 self.filename = filename 47 self.history = history
48
49 - def getSbmlDocument(self):
50 return self.__sbmlDocument
51
52 - def setSbmlDocument(self, document):
53 self.__sbmlDocument = document 54 self.__graph = self.__buildGraph()
55
56 - def getIdNameMap(self):
57 return self.__idNameMap
58
59 - def getNameIdMap(self):
60 return self.__nameIdMap
61
62 - def getStoich(self):
63 return self.__stoich
64
65 - def setStoich(self, pair, stoich):
66 if self.__stoich.has_key(pair): 67 self.__stoich[pair] += stoich 68 else: 69 self.__stoich[pair] = stoich
70
71 - def getGraph(self):
72 return self.__graph
73
74 - def __buildGraph(self):
75 """ 76 Reads a model and returns a directed bipartite graph containing the reactions and 77 species in the file. 78 79 @rtype: none 80 """ 81 species = self.__sbmlDocument.getModel().getListOfSpecies() 82 reactions = self.__sbmlDocument.getModel().getListOfReactions() 83 self.functions = [x.getId() for x in self.__sbmlDocument.getModel().getListOfFunctionDefinitions()] 84 #Create and initialize graph 85 DG = NW.XDiGraph() 86 DG.allow_multiedges() 87 #Build graph 88 #Add nodes 89 for s in species: 90 DG.add_node(s.getId()) 91 self.speciesId[s.getId()] = s 92 for reaction in reactions: 93 #########///////// 94 # @TODO: files without function definitions or kinetic laws run into trouble here! 95 # get the function of the current reaction 96 if reaction.getKineticLaw(): 97 if [x for x in self.functions if reaction.getKineticLaw().getFormula().find(x) != -1]: 98 self.reactionFunctions[reaction.getId()] = [x for x in self.functions if reaction.getKineticLaw().getFormula().find(x) != -1] 99 # look at the kinetic law of the current reaction 100 globalParameters = [p.getId() for p in self.__sbmlDocument.getModel().getListOfParameters()] 101 self.reactionSubPar[reaction.getId()] = self.inspectKineticLaw(reaction, [s.getId() for s in species], globalParameters) 102 #########///////// 103 104 DG.add_node(reaction.getId()) 105 self.reactionId[reaction.getId()] = reaction 106 #Add edges 107 products = reaction.getListOfProducts() 108 #Get all product names 109 prod_names = [] 110 for pro in products: 111 prod_names.append(pro.getSpecies()) 112 #Get all reactant names 113 reactants = reaction.getListOfReactants() 114 reac_names = [] 115 for rea in reactants: 116 reac_names.append(rea.getSpecies()) 117 #Get all modifier names 118 modifiers = reaction.getListOfModifiers() 119 modi_names = [] 120 for mod in modifiers: 121 modi_names.append(mod.getSpecies()) 122 for product in products: 123 DG.add_edge(reaction.getId(), product.getSpecies(), 'product') 124 self.__stoich[(reaction.getId(), product.getSpecies())] = product.getStoichiometry() 125 126 for reactant in reactants: 127 DG.add_edge(reactant.getSpecies(), reaction.getId(), 'reactant') 128 self.__stoich[(reactant.getSpecies(), reaction.getId())] = reactant.getStoichiometry() 129 130 for modifier in modifiers: 131 DG.add_edge(modifier.getSpecies(), reaction.getId(), 'modifier') 132 133 #########///////// 134 #self.graphHistory['root'] = {} 135 #self.__changedDG['root'] = DG 136 #########///////// 137 return DG
138
139 - def __buildMaps(self, model):
140 """ 141 Creates the dicts for the mapping of species to names and the other way round. 142 143 @rtype: ({str}{str}) 144 @return: Dicts that map ids to names and the other way round. The maps include species, reactions and parameters. 145 """ 146 idNameMap = {} 147 nameIdMap = {} 148 species = model.getListOfSpecies() 149 reactions = model.getListOfReactions() 150 parameters = model.getListOfParameters() 151 for s in species: 152 idNameMap[s.getId()] = s.getName() 153 nameIdMap[s.getName()] = s.getId() 154 for r in reactions: 155 idNameMap[r.getId()] = r.getName() 156 nameIdMap[r.getName()] = r.getId() 157 for p in parameters: 158 idNameMap[p.getId()] = p.getName() 159 nameIdMap[p.getName()] = p.getId() 160 161 return (idNameMap, nameIdMap)
162
163 - def getModelElement(self, element = 'Species', attr = 'id'):
164 """ 165 Returns the given attributes of the given type of elements. 166 167 @rtype: [str] 168 @return: list of attributes 169 """ 170 # capitalize the first letter, because libSBML needs this 171 if type(element) == str: 172 element = element.capitalize() 173 if type(attr) == str: 174 attr = attr.capitalize() 175 176 elemList = getattr(self.__sbmlDocument.getModel(), 'getListOf%s' % element)() 177 178 returnList = [] 179 if type(attr) == list: 180 for elem in elemList: 181 attributes = [] 182 for a in attr: 183 try: 184 attributes.append(getattr(elem, 'get%s' % a)()) 185 except: 186 return [] 187 returnList.append(attributes) 188 return returnList 189 else: 190 attributes = [getattr(x, 'get%s' % attr)() for x in elemList] 191 return attributes
192
193 - def inspectKineticLaw(self, reaction, species, globalParameters):
194 """ 195 Examines the formula of a kinetic law and returns lists of the substrates and parameters. 196 197 @rtype: ([string],[string]) 198 @return: Tupel of lists of substrates/modifiers and parameters 199 """ 200 law = reaction.getKineticLaw() 201 if not law: 202 return ([], []) 203 localParameters = [p.getId() for p in law.getListOfParameters()] 204 formula = law.getFormula() 205 formula = formula.replace('/', ' ').replace('*', ' ').replace('+', ' ').replace('-', ' ').replace('(', ' ').replace(')', ' ').replace('^', ' ').replace(',', ' ') 206 207 #print formula 208 formulaList = formula.split() 209 substrates = [x for x in formulaList if x in species] 210 parameters = [x for x in formulaList if x in localParameters or x in globalParameters] 211 212 return (substrates, parameters)
213 214
215 - def writeSBML(self, filename):
216 """ 217 Writes SBML document to a file and automatically determines the filename if wanted. 218 219 @type filename: str 220 @param filename: the base of the filename, removed will be added to this 221 """ 222 223 #set documentlevel for copasi compatibility 224 self.__sbmlDocument.setLevelAndVersion(2,1) 225 w = lSBML.SBMLWriter() 226 227 return w.writeSBML(self.__sbmlDocument, filename + '.xml')
228 229 230
231 - def getNewFilename(self, base=None):
232 filename = base 233 annotation = self.__sbmlDocument.getModel().getAnnotationString().splitlines() 234 for line in annotation: 235 if '<listOfRemovedNodes>' in line: 236 filename += 'Re' 237 if 'node' in line: 238 filename += line.split('"')[1]#.replace(':','MOD') 239 240 return filename
241
242 - def readSBML(self, filename, verbose=False):
243 """ 244 Reads SBML document from a file or a string and checks if the document is consistent. 245 246 @type filename: str 247 @param filename: the path to the file which should be read 248 249 @rtype: sbml.SBMLDocuments 250 @return: the SBML document which was contained in the file 251 """ 252 reader = lSBML.SBMLReader() 253 254 if os.path.exists(filename): 255 d = reader.readSBML(filename) 256 else: 257 d = reader.readSBMLFromString(filename) 258 259 #print "readSBML filename: %s\n"%filename 260 #print "self.d: %s \ttype: %s"%(self.d, type(self.d)) 261 262 errors = d.checkConsistency() 263 264 if verbose: 265 for i in range(errors-1): 266 print d.getError(i).getMessage() 267 self.setSbmlDocument(d) 268 self.__idNameMap, self.__nameIdMap = self.__buildMaps(self.__sbmlDocument.getModel())
269