Exemplo n.º 1
0
def load_file_from_games(num):

  format_num = format(num, '03d')
  file = os.path.join(os.getcwd(), os.pardir, 'data/biomodels/BIOMD0000000' + format_num + '_url.xml')
  simple = SimpleSBML()
  simple.initialize(file)
  return simple
Exemplo n.º 2
0
class TestSOMReaction(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        self.simple.initialize(cn.TEST_FILE_GAMES_PP1)
        self.reaction = self.simple.getReaction(PGA_CONS)
        self.pga = self.reaction.reactants[0]
        self.pga_ss = SOMStoichiometry(som=SOM([self.pga.molecule]),
                                       stoichiometry=self.pga.stoichiometry)
        self.rubp = self.reaction.products[0]
        self.rubp_ss = SOMStoichiometry(som=SOM([self.rubp.molecule]),
                                        stoichiometry=self.rubp.stoichiometry)
        self.som_reaction = SOMReaction(reactants=[self.pga_ss],
                                        products=[self.rubp_ss],
                                        label=self.reaction.label)

    def testConstructor(self):
        self.assertTrue(isinstance(self.reaction, Reaction))
        self.assertEqual(self.pga.molecule.name, PGA)
        self.assertEqual(self.rubp.molecule.name, RUBP)
        self.assertTrue(isinstance(self.pga_ss, SOMStoichiometry))
        self.assertTrue(isinstance(self.rubp_ss, SOMStoichiometry))
        self.assertTrue(isinstance(self.som_reaction, SOMReaction))

    def testMakeId(self):
        self.assertEqual(self.som_reaction.makeId(),
                         PGA_CONS_SOMREACTION_IDENTIFIER)

    def testGetCategory(self):
        self.assertEqual(self.som_reaction.category, cn.REACTION_1_1)
Exemplo n.º 3
0
 def analyzeReactions(cls, model_reference):
     """
 Analyzes all reactions to detect moiety imbalances.
 :param libsbml.Model or SimpleSBML model:
 :return MoietyComparatorResult:
 If model_reference is SimpleSBML, it must have been initialized.
 """
     if isinstance(model_reference, SimpleSBML):
         simple = model_reference
     else:
         simple = SimpleSBML()
         simple.initialize(model_reference)
     num_imbalances = 0
     report = NULL_STR
     for reaction in simple.reactions:
         comparator = cls(reaction.reactants, reaction.products)
         stg = comparator.reportDifference()
         if len(stg) > 0:
             num_imbalances += 1
             report = "%s\n***%s\n%s" % (
                 report, reaction.getId(is_include_kinetics=False), stg)
     num_reactions = len(simple.reactions)
     report = "\n%d of %d reactions have imbalances.\n%s" % (
         num_imbalances, num_reactions, report)
     result = MoietyComparatorResult(num_reactions=num_reactions,
                                     num_imbalances=num_imbalances,
                                     report=report)
     return result
Exemplo n.º 4
0
 def testInitialize(self):
     if IGNORE_TEST:
         return
     simple = SimpleSBML()
     simple.initialize(cn.TEST_FILE)
     self.assertEqual(len(simple.reactions), cn.NUM_REACTIONS)
     self.assertEqual(len(simple.molecules), len(simple.moietys))
Exemplo n.º 5
0
def load_file_from_curated_data(num):

  format_num = format(num, '03d')
  file = os.path.join(os.getcwd(), os.pardir, os.pardir, 'curated_data/curated_' + format_num + '.xml')
  simple = SimpleSBML()
  simple.initialize(file)
  return simple
Exemplo n.º 6
0
class TestSOM(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        self.simple.initialize(cn.TEST_FILE3)
        self.molecules = self.simple.molecules
        self.soms = []
        for mole in self.molecules:
            self.soms.append(SOM({mole}))

    def testConstructor(self):
        if IGNORE_TEST:
            return
        self.assertEqual(len(self.soms), len(self.molecules))
        self.assertEqual(self.soms[0].molecules, {self.molecules[0]})

    def testMakeId(self):
        if IGNORE_TEST:
            return
        som = self.soms[0]
        self.assertTrue(som.molecules.intersection(self.molecules))
        molecule = list(re.findall(NAMEFILTER, som.identifier))[0]
        self.assertEqual(
            list(som.molecules)[0], self.simple.getMolecule(molecule))

    def testMerge(self):
        if IGNORE_TEST:
            return
        som1 = self.soms[0]
        som2 = self.soms[1]
        molecule1 = list(som1.molecules)[0]
        molecule2 = list(som2.molecules)[0]
        new_som = som1.merge(som2)
        self.assertEqual(len(new_som.molecules), NUM_MERGED_SOMS)
        self.assertTrue(molecule1 in new_som.molecules)
        self.assertTrue(molecule2 in new_som.molecules)
Exemplo n.º 7
0
 def testConstructor2(self):
   if IGNORE_TEST:
     return
   simple = SimpleSBML()
   simple.initialize(cn.TEST_FILE2)
   reaction = simple.reactions[0]
   self.assertEqual(reaction.reactants[0].stoichiometry, NUM_S1)
   self.assertEqual(reaction.products[0].stoichiometry, NUM_S2)
Exemplo n.º 8
0
class TestSimpleSBML(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        self.simple.initialize(cn.TEST_FILE)

    def testInitialize(self):
        if IGNORE_TEST:
            return
        simple = SimpleSBML()
        simple.initialize(cn.TEST_FILE)
        self.assertEqual(len(simple.reactions), cn.NUM_REACTIONS)
        self.assertEqual(len(simple.molecules), len(simple.moietys))

    def testGetMolecule(self):
        if IGNORE_TEST:
            return
        molecule1 = self.simple.molecules[0]
        name = molecule1.name
        molecule2 = self.simple.getMolecule(name)
        self.assertTrue(molecule1.isEqual(molecule2))
        self.assertIsNone(self.simple.getMolecule(NO_NAME))

    def testAdd(self):
        if IGNORE_TEST:
            return

        def test():
            self.assertEqual(len(self.simple.reactions), 2)
            for reaction in [reaction0, reaction1]:
                self.assertTrue(reaction in self.simple.reactions)

        #
        reaction0 = self.simple.reactions[0]
        reaction1 = self.simple.reactions[1]
        self.simple.reactions = [reaction0]
        self.simple.add(reaction1)
        test()
        self.simple.add(reaction1)
        test()

    def testRemove(self):
        num_reactions = len(self.simple.reactions)
        reaction0 = self.simple.reactions[0]
        reaction1 = self.simple.reactions[1]
        self.simple.remove(reaction0)
        self.assertTrue(reaction0 not in self.simple.reactions)
        self.assertTrue(reaction1 in self.simple.reactions)
        self.simple.add(reaction0)
        self.assertTrue(len(self.simple.reactions), num_reactions)

    def testGetReaction(self):
        if IGNORE_TEST:
            return
        reaction = self.simple.reactions[0]
        label = reaction.label
        reaction1 = self.simple.getReaction(label)
        self.assertTrue(reaction.isEqual(reaction1))
Exemplo n.º 9
0
 def testAnalyzeReactions(self):
     if IGNORE_TEST:
         return
     simple = SimpleSBML()
     simple.initialize(SBML)
     result = analyze(simple)
     self.assertGreaterEqual(result.num_reactions, 0)
     self.assertGreaterEqual(result.num_imbalances, 0)
     self.assertTrue('2' in result.report)
     self.assertGreater(result.report.count('\n'), 5)
Exemplo n.º 10
0
 def testRemoveImplicit(self):
     implicit = "MA"
     path = os.path.join(cn.BIOMODELS_DIR, cn.TEST_FILE13)
     simple = SimpleSBML()
     simple.initialize(path)
     simple = sbmllint.removeImplicit(simple, implicit)
     implicit_reactions = []
     for r in simple.reactions:
         reactants = [reactant.molecule.name for reactant in r.reactants]
         products = [product.molecule.name for product in r.products]
         if (implicit in reactants) or (implicit in products):
             implicit_reactions.append(r.label)
     self.assertTrue(len(implicit_reactions) == 0)
Exemplo n.º 11
0
class TestSOMStoichiometry(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        self.simple.initialize(cn.TEST_FILE_GAMES_PP1)
        self.reaction = self.simple.getReaction(PGA_CONS)
        self.rubp = self.reaction.products[0]
        self.rubl_ss = SOMStoichiometry(som=SOM([self.rubp.molecule]),
                                        stoichiometry=self.rubp.stoichiometry)

    def testConstructor(self):
        if IGNORE_TEST:
            return
        self.assertTrue(isinstance(self.rubl_ss, SOMStoichiometry))
        self.assertTrue(isinstance(self.rubl_ss.som, SOM))
        self.assertTrue(isinstance(self.rubl_ss.stoichiometry, float))

    def testMakeId(self):
        self.assertEqual(self.rubl_ss.identifier, RUBP_ONE)
Exemplo n.º 12
0
def prettyPrint(model_reference, file_out=sys.stdout, **kwargs):
    """
  Prints the reactions in a model.
  :param str model_reference: file, xml string, antimony string
  :param dict kwargs: arguments to Reaction.getId
  """
    xml = util.getXML(model_reference)
    reader = libsbml.SBMLReader()
    document = reader.readSBMLFromString(xml)
    util.checkSBMLDocument(document)
    model = document.getModel()
    simple = SimpleSBML()
    simple.initialize(model)
    stgs = []
    for reaction in simple.reactions:
        stg = reaction.getId(**kwargs)
        stgs.append(stg)
        file_out.write("%s\n" % stg)
    return stgs
Exemplo n.º 13
0
class TestMolecule(unittest.TestCase):
    def _init(self):
        Molecule.molecules = []
        self.simple = SimpleSBML()
        self.simple = self.simple.initialize(cn.TEST_FILE)

    def setUp(self):
        if IGNORE_TEST:
            return
        self._init()

    def testConstructor(self):
        if IGNORE_TEST:
            return
        molecule = Molecule(NAME)
        self.assertEqual(molecule.name, NAME)

    def testAppend(self):
        if IGNORE_TEST:
            return
        moiety2 = Moiety(MOIETY_NAME2)
        molecule = Molecule(MOIETY_NAME1)
        new_molecule = molecule.append(moiety2)
        self.assertEqual(new_molecule.name, Molecule(MOLECULE_NAME).name)

    def testGetMoietys(self):
        if IGNORE_TEST:
            return
        m_s1 = MoietyStoichiometry(Moiety(MOIETY_NAME1), NUM1)
        m_s2 = MoietyStoichiometry(MOIETY_NAME2, NUM2)
        m_s3 = MoietyStoichiometry(MOIETY_NAME1, NUM2)
        molecule = Molecule(str(m_s1))
        molecule = molecule.append(Moiety(str(m_s2)))
        moietys = molecule.getMoietys()
        expected = [Moiety(MOIETY_NAME1), Moiety(MOIETY_NAME2)]
        for moiety in moietys:
            self.assertTrue(any([moiety.isEqual(e) for e in expected]))

    def testHasMoiety(self):
        if IGNORE_TEST:
            return
        molecule = Molecule(MOLECULE_NAME)
        self.assertTrue(molecule.hasMoiety(Moiety(MOIETY_NAME1)))
        self.assertTrue(molecule.hasMoiety(Moiety(MOIETY_NAME2)))

    def testMoietyStoichiometrys(self):
        if IGNORE_TEST:
            return
        config.setConfiguration(TEST_CFG_FILE)
        #
        molecule = Molecule("Glu6P")
        self.assertEqual(molecule.moiety_stoichiometrys[0].moiety.name, "Glu")
        #
        molecule = Molecule("ATP")
        self.assertEqual(len(molecule.moiety_stoichiometrys), 2)
class TestStoichiometryMatrix(unittest.TestCase):
    def setUp(self):
        self.simple_consistent = SimpleSBML()
        self.simple_consistent.initialize(cn.TEST_FILE8)
        self.consistent_matrix = StoichiometryMatrix(self.simple_consistent)
        #
        self.simple_inconsistent = SimpleSBML()
        self.simple_inconsistent.initialize(cn.TEST_FILE9)
        self.inconsistent_matrix = StoichiometryMatrix(
            self.simple_inconsistent)

    def testConstructor(self):
        remaining_reactions = [
            r.label for r in self.consistent_matrix.reactions
        ]
        print(remaining_reactions)
        remaining_molecules = self.consistent_matrix.molecules
        self.assertFalse(REACTION1 in remaining_reactions)
        self.assertTrue(REACTION4 in remaining_reactions)
        self.assertFalse(MOLECULE_C in remaining_molecules)
        self.assertTrue(MOLECULE_M in remaining_molecules)
        #
        self.assertEqual(len(self.inconsistent_matrix.reactions),
                         REMAINIG_REACTIONS)
        self.assertEqual(len(self.inconsistent_matrix.molecules),
                         REMAINING_MOLECULES)

    def testMakeStoichiometryMatrix(self):
        self.assertEqual(type(self.consistent_matrix), StoichiometryMatrix)
        self.assertEqual(type(self.inconsistent_matrix), StoichiometryMatrix)
        self.assertEqual(self.inconsistent_matrix.stoichiometry_matrix.shape,
                         (REMAINING_MOLECULES, REMAINIG_REACTIONS))

    def testIsConsistent(self):
        self.assertTrue(self.consistent_matrix.consistent is None)
        self.assertTrue(self.inconsistent_matrix.consistent is None)
        self.assertTrue(self.consistent_matrix.isConsistent())
        self.assertFalse(self.inconsistent_matrix.isConsistent())
Exemplo n.º 15
0
class TestSimplifiedReaction(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        # BIOMD0000000248 - originally for canceling_error
        self.simple.initialize(cn.TEST_FILE_GAMESREPORT1)
        self.mesgraph = GAMES_PP(self.simple)
        self.mesgraph.analyze(error_details=False)
        # Construct SimplifiedReaction
        self.reaction = self.simple.getReaction(CREATINEKINASE)
        self.simplified_reaction = SimplifiedReaction(self.reaction.reactants,
                                                      self.reaction.products,
                                                      self.reaction.label,
                                                      self.mesgraph)

    def testConstructor(self):
        if IGNORE_TEST:
            return
        self.assertEqual(type(self.simplified_reaction.reactants[0]),
                         MoleculeStoichiometry)
        self.assertEqual(type(self.simplified_reaction.products[0]),
                         MoleculeStoichiometry)
        self.assertEqual(self.simplified_reaction.label, CREATINEKINASE)
        self.assertEqual(type(self.simplified_reaction.mesgraph), GAMES_PP)
        self.assertEqual(
            self.simplified_reaction.makeIdentifier(),
            self.reaction.makeIdentifier(is_include_kinetics=False))

    def testReduceBySOMs(self):
        if IGNORE_TEST:
            return
        self.simplified_reaction.reduceBySOMs()
        self.assertEqual(len(self.simplified_reaction.reactants), 1)
        self.assertEqual(len(self.simplified_reaction.products), 1)
        self.assertTrue(
            self.simplified_reaction.reactants[0].molecule.name == PCR)
        self.assertTrue(
            self.simplified_reaction.products[0].molecule.name == CR)
Exemplo n.º 16
0
class TestMESGraph(unittest.TestCase):

  def setUp(self):
    # SimpleSBML with type I error
    self.simple = SimpleSBML()
    self.simple.initialize(cn.TEST_FILE6)
    # SimpleSBML with type II error
    self.simple2 = SimpleSBML()
    self.simple2.initialize(cn.TEST_FILE7)
    # SimpleSBML for type III error
    self.simple3 = SimpleSBML()
    self.simple3.initialize(cn.TEST_FILE10)
    # SimpleSBML for type IV error
    self.simple4 = SimpleSBML()
    self.simple4.initialize(cn.TEST_FILE11)
    # simple5 for type V error    
    self.simple5 = SimpleSBML()
    self.simple5.initialize(cn.TEST_FILE12)
    # simple6 will test multi-multi model with no errors
    self.simple6 = SimpleSBML()
    self.simple6.initialize(cn.TEST_FILE3)
    self.mesgraph = MESGraph(self.simple)
  
  def testConstructor(self):
    if IGNORE_TEST:
      return
    self.assertEqual(len(self.mesgraph.nodes), INITIAL_NODES)
    self.assertEqual(len(self.mesgraph.edges), INITIAL_EDGES)
    dfg = self.simple.getMolecule(DFG)
    # molecules is a list of one-molecule sets
    molecules = [som.molecules for som in self.mesgraph.nodes]
    self.assertTrue({self.simple.getMolecule(DFG)} in molecules)
    self.assertEqual(len(self.mesgraph.type_one_errors), 0)
    self.assertEqual(len(self.mesgraph.type_two_errors), 0)
    self.assertEqual(len(self.mesgraph.type_three_errors), 0)
    self.assertEqual(len(self.mesgraph.type_four_errors), 0)
    self.assertEqual(len(self.mesgraph.type_five_errors), 0)

  def testInitializeSOMs(self):
    if IGNORE_TEST:
      return
    for node in self.mesgraph.nodes:
      self.assertEqual(type(node), SOM)
  
  def testMakeId(self):
    if IGNORE_TEST:
      return
    identifier = ""
    for key, som in enumerate(self.mesgraph.nodes):
      identifier = identifier + som.identifier
      if key < len(self.mesgraph.nodes)-1:
        identifier = identifier + ";"
    self.assertEqual(identifier, self.mesgraph.identifier)

  def testGetNode(self):
    if IGNORE_TEST:
      return
    aa = self.simple.getMolecule(AA)
    aa_node = self.mesgraph.getNode(aa)
    self.assertEqual(type(aa_node), SOM)
    self.assertEqual(aa_node.molecules, {aa})
  
  def testMergeNodes(self):
    if IGNORE_TEST:
      return
    m3 = MESGraph(self.simple3)
    v1_reaction = self.simple3.getReaction(V1)
    v2_reaction = self.simple3.getReaction(V2)
    amp_molecule = self.simple3.getMolecule(AMP)
    adp_molecule = self.simple3.getMolecule(ADP)
    atp_molecule = self.simple3.getMolecule(ATP)
    amp_som = m3.getNode(amp_molecule)
    adp_som = m3.getNode(adp_molecule)
    atp_som = m3.getNode(atp_molecule)
    ampatp_som = m3.mergeNodes(amp_som, atp_som, v1_reaction)
    self.assertTrue(amp_molecule in ampatp_som.molecules)
    self.assertTrue(atp_molecule in ampatp_som.molecules)
    self.assertTrue(ampatp_som in m3.nodes)
    # tests if anohter merge will remove previous nodes
    ampadpatp_som = m3.mergeNodes(ampatp_som, adp_som, v2_reaction)
    self.assertFalse(ampatp_som in m3.nodes)
    self.assertFalse(adp_som in m3.nodes)  
    self.assertTrue(ampadpatp_som in m3.nodes)

  def testProcessUniUniReaction(self):
    if IGNORE_TEST:
      return
    self.mesgraph.processUniUniReaction(
        self.simple.reactions[UNIUNI0])
    dfg = self.mesgraph.getNode(self.simple.getMolecule(DFG))
    e1 = self.mesgraph.getNode(self.simple.getMolecule(E1))
    self.assertTrue(self.mesgraph.has_node(dfg))
    self.assertTrue(self.mesgraph.has_node(e1))
    self.assertEqual(dfg, e1)
  
  def testProcessUniMultiReaction(self):
    if IGNORE_TEST:
      return
    unimulti_reaction = self.simple.reactions[UNIMULTI]
    self.mesgraph.processUniMultiReaction(unimulti_reaction)
    prods = [self.mesgraph.getNode(product.molecule) for product in unimulti_reaction.products]
    dfg = self.mesgraph.getNode(self.simple.getMolecule(DFG))
    for prod in prods:
      self.assertTrue(self.mesgraph.has_edge(prod, dfg))
  
  def testProcessMultiUniReaction(self):
    if IGNORE_TEST:
      return
    multiuni_reaction = self.simple.reactions[MULTIUNI]
    self.mesgraph.processMultiUniReaction(multiuni_reaction)
    reacts = [self.mesgraph.getNode(reactant.molecule) for reactant in multiuni_reaction.reactants]
    mel = self.mesgraph.getNode(self.simple.getMolecule(MEL))
    for react in reacts:
      self.assertTrue(self.mesgraph.has_edge(react, mel))
  
  def testAddMultiMultiReaction(self):
    if IGNORE_TEST:
      return
    m3 = MESGraph(self.simple3)
    v2 = self.simple3.getReaction(V2)
    m3.addMultiMultiReaction(v2)
    self.assertTrue(v2 in m3.multimulti_reactions)

  def testAddTypeThreeError(self):
    if IGNORE_TEST:
      return
    m3 = MESGraph(self.simple3)
    v1 = self.simple3.getReaction(V1)
    v2 = self.simple3.getReaction(V2)
    v3 = self.simple3.getReaction(V3)
    m3.processUniUniReaction(v1)
    m3.processUniMultiReaction(v3)
    amp = m3.getNode(self.simple3.getMolecule(AMP))
    atp = m3.getNode(self.simple3.getMolecule(ATP))
    self.assertTrue(m3.addTypeThreeError(amp, atp, v2))
    self.assertTrue(len(m3.type_three_errors), 1)
    error = m3.type_three_errors[0]
    self.assertEqual(error.node1, amp)
    self.assertEqual(error.node2, atp)
    self.assertEqual(error.reactions, [v2.label])

  def testCheckTypeThreeError(self):
    if IGNORE_TEST:
      return
    m3 = MESGraph(self.simple3)
    v1 = self.simple3.getReaction(V1)
    v2 = self.simple3.getReaction(V2)
    v3 = self.simple3.getReaction(V3)
    m3.processUniUniReaction(v1)
    adp = m3.getNode(self.simple3.getMolecule(ADP))
    atp = m3.getNode(self.simple3.getMolecule(ATP))
    self.assertFalse(m3.checkTypeThreeError(adp, atp, v3))
    m3.processUniMultiReaction(v3) 
    self.assertTrue(m3.checkTypeThreeError(adp, atp, v2))
    self.assertTrue(m3.checkTypeThreeError(atp, adp, v2))

  def testReduceReaction(self):
    if IGNORE_TEST:
      return
    m4 = MESGraph(self.simple4)
    atpase = m4.simple.getReaction(ATPASE)
    lower = m4.simple.getReaction(LOWER)
    self.assertFalse(m4.reduceReaction(atpase))
    m4.processUniUniReaction(atpase)
    reduced_reaction = m4.reduceReaction(lower)
    self.assertEqual(type(reduced_reaction), Reaction)
    self.assertEqual(len(reduced_reaction.reactants), 1)
    self.assertEqual(reduced_reaction.products, [])   
    self.assertEqual(reduced_reaction.reactants[0].molecule.name, FRU16P2)

  def testProcessMultiMultiReactions(self):
    if IGNORE_TEST:
      return
    # type III error
    m3 = MESGraph(self.simple3)
    v1 = self.simple3.getReaction(V1)
    v2 = self.simple3.getReaction(V2)
    v3 = self.simple3.getReaction(V3)
    m3.processUniUniReaction(v1)
    m3.processUniMultiReaction(v3) 
    self.assertEqual(m3.type_three_errors, [])
    self.assertTrue(m3.processMultiMultiReaction(v2))
    self.assertEqual(len(m3.type_three_errors), 1) 
    # type IV error
    m4 = MESGraph(self.simple4)
    atpase = m4.simple.getReaction(ATPASE)
    lower = m4.simple.getReaction(LOWER)
    m4.processUniUniReaction(atpase)  
    self.assertEqual(m4.type_four_errors, []) 
    self.assertTrue(m4.processMultiMultiReaction(lower))
    self.assertEqual(len(m4.type_four_errors), 1)
    # no error
    m6 = MESGraph(self.simple6)
    r5 = m6.simple.getReaction(R5)
    r12 = m6.simple.getReaction(R12)
    m6.processUniUniReaction(r12)
    ac = m6.getNode(self.simple6.getMolecule(AC))
    acp = m6.getNode(self.simple6.getMolecule(ACP))
    self.assertFalse(ac==acp)
    self.assertTrue(m6.processMultiMultiReaction(r5))
    ac = m6.getNode(self.simple6.getMolecule(AC))
    acp = m6.getNode(self.simple6.getMolecule(ACP))
    self.assertTrue(ac==acp)

  def testAddArc(self):
    if IGNORE_TEST:
      return
    source = [self.mesgraph.getNode(self.simple.getMolecule(FRU)), 
              self.mesgraph.getNode(self.simple.getMolecule(GLY))]
    destination = [self.mesgraph.getNode(self.simple.getMolecule(E2))]
    dummy_reaction = self.simple.reactions[INEQUAL2]
    self.mesgraph.addArc(source[0], destination[0], dummy_reaction)
    self.mesgraph.addArc(source[1], destination[0], dummy_reaction)
    arc1 = [source[0], destination[0]]
    arc2 = [source[1], destination[0]]
    self.assertTrue(self.mesgraph.has_edge(arc1[0], arc1[1]))
    self.assertTrue(self.mesgraph.has_edge(arc2[0], arc2[1]))
    reaction_label1 = self.mesgraph.get_edge_data(arc1[0], arc1[1])[cn.REACTION][0]
    reaction_label2 = self.mesgraph.get_edge_data(arc2[0], arc1[1])[cn.REACTION][0]
    self.assertEqual(reaction_label1, dummy_reaction.label)
    self.assertEqual(reaction_label1, reaction_label2)
  
  def testGetSOMPath(self):
    if IGNORE_TEST:
      return
    uniuni_reaction = self.simple.reactions[UNIUNI0]
    self.mesgraph.processUniUniReaction(uniuni_reaction)
    dfg = self.simple.getMolecule(DFG)
    e1 = self.simple.getMolecule(E1)
    som = self.mesgraph.getNode(dfg)
    som_path = self.mesgraph.getSOMPath(som, e1, dfg)
    self.assertEqual(type(som_path[0]), cn.PathComponents)
    self.assertEqual(som_path[0].reactions, [uniuni_reaction.label])
    self.assertEqual(len(som_path), 1)

  def testPrintSOMPath(self):
    if IGNORE_TEST:
      return
    uniuni_reaction = self.simple.reactions[UNIUNI0]
    self.mesgraph.processUniUniReaction(uniuni_reaction)
    self.assertTrue(type(self.mesgraph.printSOMPath(DFG, E1))==str)
    self.assertFalse(self.mesgraph.printSOMPath(GLY, MEL))

  def testCheckTypeOneError(self):
    if IGNORE_TEST:
      return
    uniuni_reaction1 = self.simple.reactions[UNIUNI1]
    uniuni_reaction2 = self.simple.reactions[UNIUNI2]
    inequality_reaction1 = self.simple.reactions[INEQUAL1]
    inequality_reaction2 = self.simple.reactions[INEQUAL2]
    self.mesgraph.processUniUniReaction(uniuni_reaction1)
    self.mesgraph.processUniUniReaction(uniuni_reaction2)
    aa = self.simple.getMolecule(AA)
    cn = self.simple.getMolecule(CN)
    mg = self.simple.getMolecule(MG)
    self.assertTrue(self.mesgraph.checkTypeOneError((aa, cn), inequality_reaction1))
    self.assertFalse(self.mesgraph.checkTypeOneError((mg, aa), inequality_reaction2))
    self.assertTrue(len(self.mesgraph.type_one_errors)>0)
    self.assertFalse(len(self.mesgraph.type_two_errors)>0)

  def testCheckTypeTwoError(self):
    if IGNORE_TEST:
      return
    mesgraph2 = MESGraph(self.simple2)
    mesgraph2.processUniUniReaction(self.simple2.getReaction(REACTION1))
    mesgraph2.processMultiUniReaction(self.simple2.getReaction(REACTION2))
    mesgraph2.processMultiUniReaction(self.simple2.getReaction(REACTION3))
    self.assertTrue(mesgraph2.checkTypeTwoError())
    self.assertFalse(len(mesgraph2.type_one_errors)>0)
    self.assertTrue(len(mesgraph2.type_two_errors)>0)

  def testAnalyze(self):
    if IGNORE_TEST:
      return
    mesgraph1 = MESGraph(self.simple)
    mesgraph1.analyze(self.simple.reactions)
    self.assertEqual(len(mesgraph1.nodes), FINAL_NODES)
    self.assertEqual(len(mesgraph1.edges), FINAL_EDGES)
    self.assertTrue(len(mesgraph1.type_one_errors)>0)
    self.assertFalse(len(mesgraph1.type_two_errors)>0)
    #
    mesgraph2 = MESGraph(self.simple2)
    mesgraph2.analyze(self.simple2.reactions)
    self.assertTrue(len(mesgraph2.type_one_errors)>0)
    self.assertTrue(len(mesgraph2.type_two_errors)>0)
    #
    mesgraph3 = MESGraph(self.simple3)
    mesgraph3.analyze(self.simple3.reactions) 
    self.assertTrue(len(mesgraph3.type_three_errors)>0) 
    #
    mesgraph4 = MESGraph(self.simple4)
    mesgraph4.analyze(self.simple4.reactions) 
    self.assertTrue(len(mesgraph4.type_four_errors)>0)  
    #
    # mesgraph5 = MESGraph(self.simple5)
    # mesgraph5.analyze(self.simple5.reactions) 
    # dih = mesgraph5.getNode(self.simple5.getMolecule(DIH))
    # din = mesgraph5.getNode(self.simple5.getMolecule(DIN))
    # self.assertTrue(mesgraph5.has_edge(dih, din))  
    # self.assertTrue(mesgraph5.has_edge(din, dih)) 
    # self.assertEqual(len(mesgraph5.type_five_errors), 1)
    #   
    mesgraph6 = MESGraph(self.simple6)
    mesgraph6.analyze(self.simple6.reactions) 
    total_errors = len(mesgraph6.type_one_errors) + \
                   len(mesgraph6.type_two_errors) + \
                   len(mesgraph6.type_three_errors) + \
                   len(mesgraph6.type_four_errors) +\
                   len(mesgraph6.type_five_errors) 
    self.assertTrue(total_errors==0)
Exemplo n.º 17
0
def lint(model_reference=None,
         file_out=sys.stdout,
         mass_balance_check=GAMES,
         config_fid=None,
         is_report=True,
         implicit_games=False):
    """
  Reports on errors found in a model
  :param str model_reference: 
      libsbml_model file in
      file, antimony string, xml string
  :param TextIOWrapper model_fid: fid for an XML file
  :param TextIOWrapper file_out:
  :param str mass_balance_check: how check for mass balance
  :param TextIOWrapper config_fid: readable stream
  :param bool is_report: print result
  :return MoietyComparatorResult/null/None:
  """
    config.setConfiguration(fid=config_fid)
    config_dct = config.getConfiguration()
    if util.isSBMLModel(model_reference):
        model = model_reference
    else:
        xml = util.getXML(model_reference)
        reader = libsbml.SBMLReader()
        document = reader.readSBMLFromString(xml)
        util.checkSBMLDocument(document)
        model = document.getModel()
    #
    simple = SimpleSBML()
    simple.initialize(model)
    if mass_balance_check == cn.MOIETY_ANALYSIS:
        result = MoietyComparator.analyzeReactions(simple)
        if is_report:
            for line in result.report.split('\n'):
                file_out.write("%s\n" % line)
        return result
    elif mass_balance_check == GAMES:
        if implicit_games:
            for ignored in config_dct[cn.CFG_IGNORED_MOLECULES]:
                simple = removeIgnored(simple, ignored)
        m = GAMES_PP(simple)
        games_result = m.analyze(simple.reactions)
        if games_result and is_report:
            gr = GAMESReport(
                m, explain_threshold=config_dct[cn.CFG_GAMES_THRESHOLD])
            errortype_dic = {
                TYPE_I: gr.reportTypeOneError,
                TYPE_II: gr.reportTypeTwoError,
                TYPE_III: gr.reportTypeThreeError,
                CANCELING: gr.reportCancelingError,
                ECHELON: gr.reportEchelonError
            }
            for errors in m.error_summary:
                for category in errortype_dic.keys():
                    if errors.type == category:
                        func = errortype_dic[category]
                        report, _ = func(errors.errors, explain_details=True)
                        print(report)
        return games_result
    else:
        print("Specified method doesn't exist")
        return None
Exemplo n.º 18
0
class TestReaction(unittest.TestCase):

  def setUp(self):
    self.simple = SimpleSBML()
    self.simple.initialize(cn.TEST_FILE)
    self.reactions = self.simple.reactions
    self.reaction = self.reactions[2]

  def testGetId(self):
    identifier1 = self.reaction.getId()
    self.assertTrue(REACTION_SEPARATOR in identifier1)
    identifier2 = self.reaction.getId(is_include_kinetics=False)
    self.assertGreater(len(identifier1), len(identifier2))
    self.assertFalse(cn.KINETICS_SEPARATOR in identifier2)
    identifier3 = self.reaction.getId(is_include_kinetics=False,
        is_include_label=False)
    self.assertGreater(len(identifier2), len(identifier3))
    self.assertFalse(cn.LABEL_SEPARATOR in identifier3)

  def testConstructor(self):
    if IGNORE_TEST:
      return
    self.assertTrue(isinstance(self.reaction.reactants[0],
        MoleculeStoichiometry))
    self.assertTrue(isinstance(self.reaction.products[0],
        MoleculeStoichiometry))
    self.assertEqual(self.reaction.category, cn.REACTION_1_n)
    self.assertGreater(len(self.simple.molecules), 0)
    count = len(self.simple.reactions)
    reaction = self.simple.reactions[3]
    self.assertEqual(len(self.simple.reactions), count)

  # Test the stoichiometry
  def testConstructor2(self):
    if IGNORE_TEST:
      return
    simple = SimpleSBML()
    simple.initialize(cn.TEST_FILE2)
    reaction = simple.reactions[0]
    self.assertEqual(reaction.reactants[0].stoichiometry, NUM_S1)
    self.assertEqual(reaction.products[0].stoichiometry, NUM_S2)

  def testIsEqual(self):
    if IGNORE_TEST:
      return
    for reaction in self.simple.reactions[1:]:
      self.assertTrue(reaction.isEqual(reaction))
      self.assertFalse(reaction.isEqual(self.simple.reactions[0]))

  def testMakeIdentifier(self):
    if IGNORE_TEST:
      return
    for reaction in self.simple.reactions:
      parts = reaction.identifier.split('->')
      self.assertTrue(";" in parts[-1])  # Kinetics is last

  def testFindReactions(self):
    if IGNORE_TEST:
      return
    reactions = Reaction.find(self.reactions,
        category=cn.REACTION_1_n)
    trues = [r.category == cn.REACTION_1_n for r in reactions]
    self.assertTrue(all(trues))
Exemplo n.º 19
0
class TestMoleculeStoichiometry(unittest.TestCase):
    def setUp(self):
        self.simple = SimpleSBML()
        self.simple = self.simple.initialize(cn.TEST_FILE)
        Molecule.molecules = []

    def testConstructor(self):
        if IGNORE_TEST:
            return
        molecule = Molecule(MOLECULE_NAME)
        m_s = MoleculeStoichiometry(molecule, NUM1)
        self.assertTrue(m_s.molecule.isEqual(molecule))
        self.assertEqual(m_s.stoichiometry, NUM1)

    def testExtractMoietyStoichiometrys(self):
        if IGNORE_TEST:
            return
        for expected, strings in MOLECULE_STOICHIOMETRY_STGS.items():
            moietys = list(set([e[0] for e in expected]))
            moietys.sort()
            m_ss = [MoietyStoichiometry(m, 1) for m in moietys]
            for stg in strings:
                result = Molecule.getMoietyStoichiometrys(stg)
                trues = [x.isEqual(y) for x, y in zip(result, m_ss)]
                self.assertTrue(all(trues))

    def testExtractMoietyStoichiometrys(self):
        if IGNORE_TEST:
            return
        moiety_stoich = MoietyStoichiometry(Molecule(MOIETY_NAME1), NUM1)
        mole_stoich = MoleculeStoichiometry(Molecule(str(moiety_stoich)), NUM2)

    def testCountMoietys(self):
        if IGNORE_TEST:
            return
        moiety_stoich = MoietyStoichiometry(Molecule(MOIETY_NAME1), NUM1)
        mole_stoich = MoleculeStoichiometry(Molecule(str(moiety_stoich)), NUM2)
        df = mole_stoich.countMoietys()
        self.assertEqual(df.columns.tolist(), [cn.VALUE])
        expected = NUM1 * NUM2
        trues = [expected == n for n in df[cn.VALUE]]

    def testCountMoietys2(self):
        if IGNORE_TEST:
            return
        m_ss = [
            MoleculeStoichiometry(Molecule("A_P_P_P"), 1),
            MoleculeStoichiometry(Molecule("A__P_3"), 1),
        ]
        dfs = []
        for m_s in m_ss:
            dfs.append(m_s.countMoietys())
        self.assertTrue(dfs[0].equals(dfs[1]))

    def testCountMoietysInCollection(self):
        if IGNORE_TEST:
            return
        m_ss = [
            MoleculeStoichiometry(Molecule(n), NUM1)
            for n in MOLECULE_NAME_SET[:3]
        ]
        df = MoleculeStoichiometry.countMoietysInCollection(m_ss)
        indexes = df.index.tolist()
        self.assertEqual(len(indexes), len(set(indexes)))

    def testGetMolecules(self):
        if IGNORE_TEST:
            return
        names = ["a", "b", "c"]
        full_names = list(names)
        full_names.extend(names)
        m_ss = [MoleculeStoichiometry(Molecule(n), NUM1) for n in full_names]
        molecules = MoleculeStoichiometry.getMolecules(m_ss)
        self.assertEqual(len(molecules), len(names))
Exemplo n.º 20
0
class TestGAMESReport(unittest.TestCase):
    def setUp(self):
        self.simple1 = SimpleSBML()
        self.simple2 = SimpleSBML()
        self.simple3 = SimpleSBML()
        self.simple4 = SimpleSBML()
        # BIOMD0000000248 - canceling_error
        self.simple1.initialize(cn.TEST_FILE_GAMESREPORT1)
        # BIOMD0000000007 - Type I error
        self.simple2.initialize(cn.TEST_FILE_GAMESREPORT2)
        # BIOMD0000000018 - Type II error
        self.simple3.initialize(cn.TEST_FILE_GAMES_PP2)
        # BIOMD0000000167 - Echelon, Type III error
        self.simple4.initialize(cn.TEST_FILE_GAMESREPORT3)

    def testReportCancelingError(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple1)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        report, error_num = gr.reportCancelingError(m.canceling_errors,
                                                    explain_details=True)
        extended_report = NULL_STR
        extended_report = extended_report + "We detected a mass imbalance\n"
        extended_report = extended_report + ": OxidativePhosphorylation: CTtis -> \n\n"
        extended_report = extended_report + "from the following reaction isolation set:\n\n"
        extended_report = extended_report + "1. OxidativePhosphorylation: 6.00 ADP + CTtis -> 6.00 ATP\n"
        extended_report = extended_report + "2. ATPase: ATP -> ADP\n"
        extended_report = extended_report + "*ATP and ADP have the same mass according to the above reaction\n"
        extended_report = extended_report + "\n%s%s\n" % (PARAGRAPH_DIVIDER,
                                                          PARAGRAPH_DIVIDER)
        extended_report = extended_report + "\n%s\n" % REPORT_DIVIDER
        self.assertEqual(extended_report, report)
        self.assertEqual(error_num, [2])

    def testGetMoleculeEqualityPath(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple2)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        som = m.getNode(self.simple2.getMolecule(G2K))
        equality_path = gr.getMoleculeEqualityPath(som, G2K, PG2R)
        self.assertTrue(len(equality_path) == 2)
        self.assertEqual(type(equality_path[0]), cn.PathComponents)
        self.assertEqual(equality_path[0].node1, G2K)
        self.assertEqual(equality_path[0].reactions, [CDC2PHOS])
        self.assertEqual(equality_path[1].node2, PG2R)
        self.assertEqual(equality_path[1].reactions, [RUM1DEGINPG2R])

    def testGetMoleculeEqualityPathReport(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple2)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        count, report1 = gr.getMoleculeEqualityPathReport(
            G2K, PG2R, 0, explain_details=False)
        self.assertEqual(count, 2)
        self.assertEqual(
            report1,
            "1. Cdc2Phos: G2K -> PG2\n2. Rum1DegInPG2R: PG2R -> PG2\n")
        count, report2 = gr.getMoleculeEqualityPathReport(G2K,
                                                          PG2R,
                                                          0,
                                                          explain_details=True)
        self.assertEqual(count, 2)
        self.assertEqual(
            report2,
            "\nG2K = PG2 by reaction(s):\n1. Cdc2Phos: G2K -> PG2\n\nPG2 = PG2R by reaction(s):\n2. Rum1DegInPG2R: PG2R -> PG2\n"
        )

    def testGetMoleculeInequalityPathReport(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple2)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        count, report1 = gr.getMoleculeInequalityPathReport(
            G2K, PG2R, ["G2R_Creation"], 0, explain_details=False)
        self.assertEqual(count, 1)
        self.assertEqual(report1, "1. G2R_Creation: G2K + R -> G2R\n")
        count, report2 = gr.getMoleculeInequalityPathReport(
            G2K, PG2R, ["G2R_Creation"], 0, explain_details=True)
        self.assertEqual(count, 1)
        self.assertEqual(
            report2,
            "G2K < PG2R by reaction(s):\n1. G2R_Creation: G2K + R -> G2R\n")

    def testReportTypeOneError(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple2)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        error = [
            cn.PathComponents(node1=G2K, node2=G2R, reactions=[G2R_CREATION])
        ]
        report, error_num = gr.reportTypeOneError(error, explain_details=True)
        self.assertEqual(error_num, [2])
        extended_report = NULL_STR
        extended_report = extended_report + "\nG2K = G2R by reaction(s):\n1. Rum1DegInG2R: G2R -> G2K\n\n"
        extended_report = extended_report + "However, G2K < G2R by reaction(s):\n2. G2R_Creation: G2K + R -> G2R\n\n"
        extended_report = extended_report + "\n----------------------------------------------------------------------\n\n"
        extended_report = extended_report + "\n\n**********************************************************************\n\n"
        self.assertEqual(report, extended_report)

    def testReportTypeTwoError(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple3)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        som1 = m.getNode(self.simple3.getMolecule(CH3FH4))
        som2 = m.getNode(self.simple3.getMolecule(FH4))
        error = [[som1, som2]]
        report, error_num = gr.reportTypeTwoError(error, explain_details=True)
        self.assertEqual(error_num, [5])
        LOC_START = 241
        extended_report = NULL_STR
        extended_report = extended_report + "{CH3FH4} < {CH2FH4=FFH2=FH2f=FH4} < {CH3FH4}\n\n"
        extended_report = extended_report + "This indicates a mass conflict between reactions.\n"
        extended_report = extended_report + "%s%s\n" % (PARAGRAPH_DIVIDER,
                                                        PARAGRAPH_DIVIDER)
        self.assertEqual(report[-LOC_START:], extended_report)

    def testConvertOperationSeriesToReactionOperations(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        op = pd.Series([1.0, 0.5, 0.0],
                       index=[
                           STATPHOSPHORYLATION, PSTATDIMERISATION,
                           PSTATDIMERISATIONNUC
                       ])
        ro = gr.convertOperationSeriesToReactionOperations(op)
        self.assertEqual(len(ro), 2)
        self.assertEqual(ro[0].reaction, STATPHOSPHORYLATION)
        self.assertEqual(ro[0].operation, 1.0)
        self.assertEqual(ro[1].reaction, PSTATDIMERISATION)
        self.assertEqual(ro[1].operation, 0.5)

    def testGetOperationMatrix(self):
        if IGNORE_TEST:
            return
        m1 = GAMES_PP(self.simple1)
        m1.analyze(error_details=False)
        gr1 = GAMESReport(m1)
        self.assertTrue(gr1.getOperationMatrix() is None)
        m4 = GAMES_PP(self.simple4)
        m4.analyze(error_details=False)
        gr4 = GAMESReport(m4)
        op_mat = gr4.getOperationMatrix()
        self.assertEqual(op_mat.loc[STATPHOSPHORYLATION, STATPHOSPHORYLATION],
                         1.0)
        self.assertEqual(op_mat.loc[PSTATDIMERISATION, PSTATDIMERISATION], 1.0)
        self.assertEqual(
            op_mat.loc[PSTATDIMERISATIONNUC, PSTATDIMERISATIONNUC], 1.0)
        self.assertEqual(op_mat.loc[PSTATDIMERISATIONNUC, STATPHOSPHORYLATION],
                         0.0)
        self.assertEqual(op_mat.loc[STATPHOSPHORYLATION, PSTATDIMERISATIONNUC],
                         -0.5)

    def testGetResultingSeries(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        resulting_series = gr.getResultingSeries(STATPHOSPHORYLATION)
        print(resulting_series)
        self.assertEqual(resulting_series["{" + SPECIES_TEST + "}"], 1.0)
        self.assertEqual(resulting_series["{" + PSTAT_SOL + "}"], 0.0)
        self.assertEqual(
            resulting_series[m.getNode(
                m.simple.getMolecule(PSTATDIMER_NUC)).identifier], 0.0)
        self.assertEqual(
            resulting_series[m.getNode(
                m.simple.getMolecule(PSTAT_NUC)).identifier], 0.0)

    def testGetOperationStoichiometryMatrix(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        op = pd.Series([1.0, 0.5, 0.0],
                       index=[
                           STATPHOSPHORYLATION, PSTATDIMERISATION,
                           PSTATDIMERISATIONNUC
                       ])
        ro = gr.convertOperationSeriesToReactionOperations(op)
        osm = gr.getOperationStoichiometryMatrix(ro)
        self.assertEqual(osm.loc[SPECIES_TEST, STATPHOSPHORYLATION], 1.0)
        self.assertEqual(osm.loc[SPECIES_TEST, PSTATDIMERISATION], 0.0)
        self.assertEqual(osm.loc[PSTAT_SOL, STATPHOSPHORYLATION], 1.0)
        self.assertEqual(osm.loc[PSTAT_SOL, PSTATDIMERISATION], -2.0)

    def testGeInferredReaction(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        op = pd.Series([1.0, 0.5, 0.0],
                       index=[
                           STATPHOSPHORYLATION, PSTATDIMERISATION,
                           PSTATDIMERISATIONNUC
                       ])
        ro = gr.convertOperationSeriesToReactionOperations(op)
        inferred_reaction = gr.getInferredReaction(ro)
        self.assertEqual(len(inferred_reaction.reactants), 1)
        self.assertEqual(len(inferred_reaction.products), 2)
        self.assertEqual(inferred_reaction.reactants[0].molecule.name,
                         STAT_SOL)
        self.assertTrue(inferred_reaction.products[0].molecule.name in
                        {PSTATDIMER_SOL, SPECIES_TEST})
        self.assertTrue(inferred_reaction.products[1].molecule.name in
                        {PSTATDIMER_SOL, SPECIES_TEST})
        self.assertEqual(inferred_reaction.reactants[0].stoichiometry, 1.0)
        self.assertEqual({p.stoichiometry
                          for p in inferred_reaction.products}, {0.5, 1.0})

    def testReportReactionsInSOM(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        som = m.getNode(m.simple.getMolecule(PSTATDIMER_NUC))
        report, error_num = gr.reportReactionsInSOM(som, 0)
        common_part = "1. PstatDimer__import: PstatDimer_sol -> PstatDimer_nuc\n"
        self.assertEqual(error_num, 1)
        self.assertTrue(report == common_part)

    def testReportEchelonError(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        report, error_num = gr.reportEchelonError(m.echelon_errors,
                                                  explain_details=True)
        self.assertEqual(error_num, [3])
        extended_report = NULL_STR
        extended_report = extended_report + "will result in empty reactant with zero mass:\n\n:  -> {species_test}\n\n"
        extended_report = extended_report + "\n----------------------------------------------------------------------\n"
        extended_report = extended_report + "\n----------------------------------------------------------------------\n\n"
        extended_report = extended_report + "\n\n**********************************************************************\n\n"
        self.assertEqual(report[-288:], extended_report)

    def testReportTypeThreeError(self):
        if IGNORE_TEST:
            return
        m = GAMES_PP(self.simple4)
        m.analyze(error_details=False)
        gr = GAMESReport(m)
        report, error_num = gr.reportTypeThreeError(m.type_three_errors,
                                                    explain_details=True)
        self.assertEqual(error_num, [3])
        pseudo_inequality_report = NULL_STR
        pseudo_inequality_report = pseudo_inequality_report + "6. statPhosphorylation: stat_sol -> Pstat_sol + species_test\n"
        pseudo_inequality_report = pseudo_inequality_report + "(pseudo 6.) statPhosphorylation: {Pstat_nuc=stat_nuc=stat_sol} -> "
        pseudo_inequality_report1 = pseudo_inequality_report + "{species_test} + {Pstat_sol}"
        pseudo_inequality_report2 = pseudo_inequality_report + "{Pstat_sol} + {species_test}"
        inference_report1 = "the masses of {Pstat_sol} and {Pstat_nuc=stat_nuc=stat_sol} are unequal."
        inference_report2 = "the masses of {Pstat_nuc=stat_nuc=stat_sol} and {Pstat_sol} are unequal."
        self.assertTrue(report[-460:-305] == pseudo_inequality_report1
                        or report[-460:-305] == pseudo_inequality_report2)
        self.assertTrue(report[-293:-221] == inference_report1
                        or report[-293:-221] == inference_report2)
Exemplo n.º 21
0
class TestGAMES_PP(unittest.TestCase):
    def setUp(self):
        # BIOMD0000000383
        self.simple1 = SimpleSBML()
        self.simple1.initialize(cn.TEST_FILE_GAMES_PP1)
        self.games_pp = GAMES_PP(self.simple1)
        # BIOMD0000000018
        self.simple2 = SimpleSBML()
        self.simple2.initialize(cn.TEST_FILE_GAMES_PP2)

    def testConstructor(self):
        if IGNORE_TEST:
            return
        self.assertEqual(len(self.games_pp.reactions), NUM_REACTIONS)
        for r in self.games_pp.reactions:
            print(r.category)
            self.assertFalse(r.category == cn.REACTION_BOUNDARY)
        self.assertEqual(len(self.games_pp.molecules), NUM_MOLECULES)
        for m in self.games_pp.molecules:
            self.assertTrue(isinstance(m, Molecule))
        self.assertEqual(len(self.games_pp.soms), NUM_MOLECULES)
        self.assertTrue(isinstance(self.games_pp.soms[0], SOM))
        init_identifier = ""
        for som in self.games_pp.soms:
            init_identifier = init_identifier + som.identifier
            if som != self.games_pp.soms[-1]:
                init_identifier = init_identifier + ";"
        self.assertEqual(self.games_pp.identifier, init_identifier)

    def testConvertReactionToSOMReaction(self):
        if IGNORE_TEST:
            return
        reaction1 = self.games_pp.simple.getReaction(PGA_CONS)
        reaction2 = self.games_pp.simple.getReaction(PGA_PROD_VC)
        som_reaction1 = self.games_pp.convertReactionToSOMReaction(reaction1)
        som_reaction2 = self.games_pp.convertReactionToSOMReaction(reaction2)
        self.assertTrue(isinstance(som_reaction1, SOMReaction))
        self.assertTrue(isinstance(som_reaction2, SOMReaction))
        ms_rubp = som_reaction1.products[0]
        self.assertTrue(isinstance(ms_rubp, SOMStoichiometry))
        self.assertEqual(
            list(ms_rubp.som.molecules)[0],
            self.games_pp.simple.getMolecule(RUBP))
        ms_nadph = None
        for ms in som_reaction2.reactants:
            if ms.som.identifier == SOM_NADPH:
                ms_nadph = ms
                break
        self.assertTrue(ms_nadph.som.identifier == SOM_NADPH)
        self.assertEqual(ms_nadph.stoichiometry, NADPH_STOICHIOMETRY)

    def testGetStoichiometryMatrix(self):
        if IGNORE_TEST:
            return
        # For regular stoichiometry matrix
        mat = self.games_pp.getStoichiometryMatrix(self.games_pp.reactions,
                                                   self.games_pp.molecules,
                                                   som=False)
        self.assertTrue(isinstance(mat, pd.DataFrame))
        self.assertEqual(mat.shape, (NUM_MOLECULES, NUM_REACTIONS))
        self.assertEqual(mat[PGA_CONS][PGA], PGA_CONS_WITH_PGA)
        self.assertEqual(mat[PGA_PROD_VC][RUBP], PGA_PROD_VC_WITH_RUBP)
        # For SOM stoichiometry matrix
        som_reactions = []
        for r in self.games_pp.reactions:
            som_reactions.append(self.games_pp.convertReactionToSOMReaction(r))
        som_mat = self.games_pp.getStoichiometryMatrix(som_reactions,
                                                       self.games_pp.nodes,
                                                       som=True)
        self.assertTrue(isinstance(som_mat, pd.DataFrame))
        self.assertEqual(som_mat[PGA_CONS][SOM_PGA], PGA_CONS_WITH_PGA)
        self.assertEqual(som_mat[PGA_PROD_VC][SOM_RUBP], PGA_PROD_VC_WITH_RUBP)

    def testDecomposeMatrix(self):
        if IGNORE_TEST:
            return
        # should be all None before decomposition
        self.assertTrue(self.games_pp.perm_inverse is None)
        self.assertTrue(self.games_pp.permuted_matrix is None)
        self.assertTrue(self.games_pp.lower_inverse is None)
        self.assertTrue(self.games_pp.echelon_df is None)
        som_reactions = []
        for r in self.games_pp.reactions:
            som_reactions.append(self.games_pp.convertReactionToSOMReaction(r))
        som_mat = self.games_pp.getStoichiometryMatrix(som_reactions,
                                                       self.games_pp.nodes,
                                                       som=True)
        echelon = self.games_pp.decomposeMatrix(som_mat).T
        self.assertFalse(self.games_pp.perm_inverse is None)
        self.assertFalse(self.games_pp.permuted_matrix is None)
        self.assertFalse(self.games_pp.lower_inverse is None)
        self.assertFalse(self.games_pp.echelon_df is None)
        self.assertTrue(isinstance(self.games_pp.perm_inverse, np.ndarray))
        self.assertTrue(isinstance(self.games_pp.permuted_matrix,
                                   pd.DataFrame))
        self.assertTrue(isinstance(self.games_pp.lower_inverse, pd.DataFrame))
        self.assertTrue(isinstance(self.games_pp.echelon_df, pd.DataFrame))
        # Checking lower echelon - lower left element should be 0.0 (zero)
        self.assertTrue(echelon.iloc[echelon.shape[0] - 1][0] == ZERO_F)
        # On the ohter hand, upper left should be nonzero
        self.assertFalse(echelon.iloc[0][0] == ZERO_F)

    def testGetRREFMatrix(self):
        if IGNORE_TEST:
            return
        self.assertTrue(self.games_pp.rref_operation is None)
        self.assertTrue(self.games_pp.rref_df is None)
        som_reactions = []
        for r in self.games_pp.reactions:
            som_reactions.append(self.games_pp.convertReactionToSOMReaction(r))
        som_mat = self.games_pp.getStoichiometryMatrix(som_reactions,
                                                       self.games_pp.nodes,
                                                       som=True)
        echelon = self.games_pp.decomposeMatrix(som_mat).T
        rref = self.games_pp.getRREFMatrix(echelon)
        self.assertTrue(isinstance(self.games_pp.rref_operation, pd.DataFrame))
        self.assertTrue(isinstance(self.games_pp.rref_df, pd.DataFrame))
        # Choose the last row of rref.T
        last_row = rref.T.iloc[-1:]
        # Get the first nonzero index
        nonzero_species = (last_row != 0).idxmax(axis=1)[0]
        # The SUM of nonzero species column must be the same as the single value
        self.assertEqual(last_row[nonzero_species][0],
                         sum(rref.T[nonzero_species]))

    def testConverMatrixToSOMReactions(self):
        if IGNORE_TEST:
            return
        som_reactions1 = []
        for r in self.games_pp.reactions:
            som_reactions1.append(
                self.games_pp.convertReactionToSOMReaction(r))
        som_mat = self.games_pp.getStoichiometryMatrix(som_reactions1,
                                                       self.games_pp.nodes,
                                                       som=True)
        som_reactions2 = self.games_pp.convertMatrixToSOMReactions(som_mat)
        sr1 = None
        sr2 = None
        for sr in som_reactions1:
            if sr.label == PGA_PROD_VC:
                sr1 = sr
                break
        for sr in som_reactions2:
            if sr.label == PGA_PROD_VC:
                sr2 = sr
                break
        sr1_reactants = {ms.som for ms in sr1.reactants}
        sr2_reactants = {ms.som for ms in sr2.reactants}
        sr1_products = {ms.som for ms in sr1.products}
        sr2_products = {ms.som for ms in sr2.products}
        sr1_reactsom = sum([ms.stoichiometry for ms in sr1.reactants])
        sr2_reactsom = sum([ms.stoichiometry for ms in sr2.reactants])
        sr1_prodsom = sum([ms.stoichiometry for ms in sr1.products])
        sr2_prodsom = sum([ms.stoichiometry for ms in sr2.products])
        self.assertEqual(sr1_reactants, sr2_reactants)
        self.assertEqual(sr1_products, sr2_products)
        self.assertEqual(sr1_reactsom, sr2_reactsom)
        self.assertEqual(sr1_prodsom, sr2_prodsom)

    def testGetNode(self):
        if IGNORE_TEST:
            return
        co2 = self.games_pp.simple.getMolecule(CO2)
        co2_node = self.games_pp.getNode(co2)
        self.assertEqual(type(co2_node), SOM)
        self.assertEqual(co2_node.molecules, {co2})

    def testMergeNodes(self):
        if IGNORE_TEST:
            return
        reaction = self.games_pp.simple.getReaction(PGA_CONS)
        pga = self.games_pp.simple.getMolecule(PGA)
        rubp = self.games_pp.simple.getMolecule(RUBP)
        som_pga = self.games_pp.getNode(pga)
        som_rubp = self.games_pp.getNode(rubp)
        som_pga_rubp = self.games_pp.mergeNodes(som_pga, som_rubp, reaction)
        self.assertTrue(isinstance(som_pga_rubp, SOM))
        self.assertTrue(pga in som_pga_rubp.molecules)
        self.assertTrue(rubp in som_pga_rubp.molecules)
        self.assertTrue(reaction in som_pga_rubp.reactions)

    def testAddReaction(self):
        if IGNORE_TEST:
            return
        self.assertEqual(len(self.games_pp.reactions_lu), 0)
        reaction = self.games_pp.simple.getReaction(PGA_CONS)
        self.games_pp.addReaction(reaction)
        self.assertTrue(reaction in self.games_pp.reactions_lu)
        self.games_pp.addReaction(reaction)
        self.assertTrue(len(self.games_pp.reactions_lu), 1)

    def testProcessUniUniReaction(self):
        if IGNORE_TEST:
            return
        reaction = self.games_pp.simple.getReaction(PGA_CONS)
        som = self.games_pp.processUniUniReaction(reaction)
        self.assertTrue(isinstance(som, SOM))
        self.assertTrue(som in self.games_pp.nodes)
        pga = self.games_pp.simple.getMolecule(PGA)
        rubp = self.games_pp.simple.getMolecule(RUBP)
        self.assertTrue(pga in som.molecules)
        self.assertTrue(rubp in som.molecules)

    def testAddArc(self):
        if IGNORE_TEST:
            return
        reaction = self.games_pp.simple.getReaction(PGA_PROD_VC)
        co2 = self.games_pp.simple.getMolecule(CO2)
        pga = self.games_pp.simple.getMolecule(PGA)
        som_co2 = self.games_pp.getNode(co2)
        som_pga = self.games_pp.getNode(pga)
        self.games_pp.addArc(som_co2, som_pga, reaction)
        self.assertTrue(self.games_pp.has_edge(som_co2, som_pga))
        self.assertEqual(
            self.games_pp.get_edge_data(som_co2, som_pga)[REACTION],
            [PGA_PROD_VC])

    def testProcessUniMultiReaction(self):
        if IGNORE_TEST:
            return
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(isinstance(games_pp2, GAMES_PP))
        reaction = games_pp2.simple.getReaction(CH2FH4toHCHO)
        reactant1 = games_pp2.simple.getMolecule(CH2FH4)
        product1 = games_pp2.simple.getMolecule(FH4)
        product2 = games_pp2.simple.getMolecule(HCHO)
        games_pp2.processUniMultiReaction(reaction)
        som_reactant1 = games_pp2.getNode(reactant1)
        som_product1 = games_pp2.getNode(product1)
        som_product2 = games_pp2.getNode(product2)
        self.assertTrue(games_pp2.has_edge(som_product1, som_reactant1))
        self.assertTrue(games_pp2.has_edge(som_product2, som_reactant1))

    def testProcessMultiUniReaction(self):
        if IGNORE_TEST:
            return
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(isinstance(games_pp2, GAMES_PP))
        reaction = games_pp2.simple.getReaction(HCHOtoCH2FH4)
        reactant1 = games_pp2.simple.getMolecule(FH4)
        reactant2 = games_pp2.simple.getMolecule(HCHO)
        product1 = games_pp2.simple.getMolecule(CH2FH4)
        games_pp2.processMultiUniReaction(reaction)
        som_product1 = games_pp2.getNode(product1)
        som_reactant1 = games_pp2.getNode(reactant1)
        som_reactant2 = games_pp2.getNode(reactant2)
        self.assertTrue(games_pp2.has_edge(som_reactant1, som_product1))
        self.assertTrue(games_pp2.has_edge(som_reactant2, som_product1))

    def testProcessEqualSOMReaction(self):
        if IGNORE_TEST:
            return
        print("type three", self.games_pp.type_three_errors)
        self.assertEqual(len(self.games_pp.type_three_errors), ZERO)
        # Add an arc
        reaction = self.games_pp.simple.getReaction(PGA_PROD_VC)
        co2 = self.games_pp.simple.getMolecule(CO2)
        pga = self.games_pp.simple.getMolecule(PGA)
        som_co2 = self.games_pp.getNode(co2)
        som_pga = self.games_pp.getNode(pga)
        self.games_pp.addArc(som_co2, som_pga, reaction)
        # Process a dummy reaction
        soms_co2 = SOMStoichiometry(som_co2, 1.0)
        soms_pga = SOMStoichiometry(som_pga, 1.0)
        som_reaction = SOMReaction([soms_co2], [soms_pga], "dummy")
        self.games_pp.processEqualSOMReaction(som_reaction)
        self.assertTrue(len(self.games_pp.type_three_errors) > ZERO)

    def testProcessUnequalSOMReaction(self):
        if IGNORE_TEST:
            return
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(len(games_pp2.edges) == 0)
        reaction = games_pp2.simple.getReaction(CH2FH4toHCHO)
        som_reaction = games_pp2.convertReactionToSOMReaction(reaction)
        games_pp2.processUnequalSOMReaction(som_reaction)
        self.assertTrue(len(games_pp2.edges) == 2)
        reactant1 = games_pp2.simple.getMolecule(FH4)
        reactant2 = games_pp2.simple.getMolecule(HCHO)
        product1 = games_pp2.simple.getMolecule(CH2FH4)
        games_pp2.processUniMultiReaction(reaction)
        som_product1 = games_pp2.getNode(product1)
        som_reactant1 = games_pp2.getNode(reactant1)
        som_reactant2 = games_pp2.getNode(reactant2)
        self.assertTrue(games_pp2.has_edge(som_reactant1, som_product1))
        self.assertTrue(games_pp2.has_edge(som_reactant2, som_product1))

    def testAddTypeOneError(self):
        if IGNORE_TEST:
            return
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(len(games_pp2.type_one_errors) == ZERO)
        reaction = games_pp2.simple.getReaction(CH2FH4toHCHO)
        reactant1 = games_pp2.simple.getMolecule(FH4)
        product1 = games_pp2.simple.getMolecule(CH2FH4)
        games_pp2.addTypeOneError(reactant1, product1, reaction)
        self.assertTrue(len(games_pp2.type_one_errors) == ONE)
        error = games_pp2.type_one_errors[ZERO]
        self.assertEqual(error.node1, reactant1.name)
        self.assertEqual(error.node2, product1.name)
        self.assertEqual(error.reactions, [reaction.label])

    def testChekcTypeOneError(self):
        if IGNORE_TEST:
            return
        games_pp1 = GAMES_PP(self.simple1)
        reaction = games_pp1.simple.getReaction(PGA_CONS)
        pga = games_pp1.simple.getMolecule(PGA)
        rubp = games_pp1.simple.getMolecule(RUBP)
        som_pga = games_pp1.getNode(pga)
        som_rubp = games_pp1.getNode(rubp)
        som_pga_rubp = games_pp1.mergeNodes(som_pga, som_rubp, reaction)
        self.assertTrue(len(games_pp1.type_one_errors) == ZERO)
        is_error = games_pp1.checkTypeOneError((pga, rubp), reaction)
        self.assertTrue(is_error)
        error = games_pp1.type_one_errors[ZERO]
        self.assertEqual(error.node1, pga.name)
        self.assertEqual(error.node2, rubp.name)
        self.assertEqual(error.reactions, [reaction.label])

    def testCheckTypeTwoError(self):
        if IGNORE_TEST:
            return
        # Create a dummy cycle by adding two conflicting arcs
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(isinstance(games_pp2, GAMES_PP))
        unimulti_reaction = games_pp2.simple.getReaction(CH2FH4toHCHO)
        multiuni_reaction = games_pp2.simple.getReaction(HCHOtoCH2FH4)
        fh4 = games_pp2.simple.getMolecule(FH4)
        # hcho = games_pp2.simple.getMolecule(HCHO)
        ch2fh4 = games_pp2.simple.getMolecule(CH2FH4)
        som_fh4 = games_pp2.getNode(fh4)
        som_ch2fh4 = games_pp2.getNode(ch2fh4)
        # do we need the next two methods if we're giving a cycle?
        games_pp2.addArc(som_fh4, som_ch2fh4, unimulti_reaction)
        games_pp2.addArc(som_ch2fh4, som_fh4, multiuni_reaction)
        self.assertTrue(len(games_pp2.type_two_errors) == ZERO)
        games_pp2.checkTypeTwoError()
        self.assertTrue(len(games_pp2.type_two_errors) == ONE)
        error = games_pp2.type_two_errors[ZERO]
        self.assertTrue(games_pp2.has_edge(error[ZERO], error[ONE]))
        self.assertTrue(games_pp2.has_edge(error[ONE], error[ZERO]))
        error_reactions = set(
            games_pp2.get_edge_data(error[ZERO], error[ONE])[REACTION])
        error_reactions = error_reactions.union(
            set(games_pp2.get_edge_data(error[ONE], error[ZERO])[REACTION]))
        self.assertTrue(CH2FH4toHCHO in error_reactions)
        self.assertTrue(HCHOtoCH2FH4 in error_reactions)

    def testProcessErrorReaction(self):
        if IGNORE_TEST:
            return
        games_pp1 = GAMES_PP(self.simple1)
        self.assertTrue(len(games_pp1.echelon_errors) == ZERO)
        reaction = self.games_pp.simple.getReaction(PGA_PROD_VO)
        games_pp1.processErrorReaction(reaction)
        self.assertTrue(len(games_pp1.echelon_errors) == ONE)
        self.assertTrue(reaction in games_pp1.echelon_errors)

    def testAnalyze(self):
        if IGNORE_TEST:
            return
        games_pp1 = GAMES_PP(self.simple1)
        games_pp2 = GAMES_PP(self.simple2)
        self.assertTrue(games_pp1.analyze(rref=False))
        self.assertTrue(games_pp2.analyze())
        self.assertTrue(len(games_pp1.echelon_errors) > ZERO)
        self.assertTrue(len(games_pp1.type_one_errors) == ZERO)
        self.assertTrue(len(games_pp1.type_two_errors) == ZERO)
        self.assertTrue(len(games_pp2.type_one_errors) > ZERO)