Beispiel #1
0
    def test_flux_variability(self):
        fva_results = {
            "5DGLCNtex": {"minimum": 0.0, "maximum": 0.0},
            "ABTA": {"minimum": 0.0, "maximum": 0.0},
            "5DOAN": {"minimum": 0.0, "maximum": 0.0},
            "A5PISO": {"minimum": 0.00692, "maximum": 0.00692},
            "AACPS1": {"minimum": 0.0, "maximum": 0.0},
            "AACPS2": {"minimum": 0.0, "maximum": 0.0},
            "ACALDtex": {"minimum": 0.0, "maximum": 0.0},
            "AACPS3": {"minimum": 0.0, "maximum": 0.0},
            "AACPS4": {"minimum": 0.0, "maximum": 0.0},
            "ABUTD": {"minimum": 0.0, "maximum": 0.0},
            "AACPS5": {"minimum": 0.0, "maximum": 0.0},
            "AACPS6": {"minimum": 0.0, "maximum": 0.0},
            "AACPS7": {"minimum": 0.0, "maximum": 0.0},
            "AACPS8": {"minimum": 0.0, "maximum": 0.0},
            "AACPS9": {"minimum": 0.0, "maximum": 0.0},
            "AACTOOR": {"minimum": 0.0, "maximum": 0.0},
            "ABUTt2pp": {"minimum": 0.0, "maximum": 0.0},
            "3OAS140": {"minimum": 0.50419, "maximum": 0.50419},
            "3OAS141": {"minimum": 0.03748, "maximum": 0.03748},
            "3OAS160": {"minimum": 0.41769, "maximum": 0.41769},
            "3OAS161": {"minimum": 0.03748, "maximum": 0.03748},
            "3OAS180": {"minimum": 0.01071, "maximum": 0.01071},
            "3OAS181": {"minimum": 0.01606, "maximum": 0.01606},
            "ABUTtex": {"minimum": 0.0, "maximum": 0.0},
            "3OAS60": {"minimum": 0.54399, "maximum": 0.54399},
            "3OAS80": {"minimum": 0.54399, "maximum": 0.54399},
            "AAMYL": {"minimum": 0.0, "maximum": 0.0},
            "3PEPTabcpp": {"minimum": 0.0, "maximum": 0.0},
            "3PEPTtex": {"minimum": 0.0, "maximum": 0.0},
            "3UMPtex": {"minimum": 0.0, "maximum": 0.0},
            "4HOXPACDtex": {"minimum": 0.0, "maximum": 0.0},
            "ACACtex": {"minimum": 0.0, "maximum": 0.0},
            "4PCP": {"minimum": 0.0, "maximum": 0.0},
            "4PCPpp": {"minimum": 0.0, "maximum": 0.0},
            "AAMYLpp": {"minimum": 0.0, "maximum": 0.0},
            "4PEPTabcpp": {"minimum": 0.0, "maximum": 0.0},
            "4PEPTtex": {"minimum": 0.0, "maximum": 0.0},
            "5DGLCNR": {"minimum": 0.0, "maximum": 0.0},
            "5DGLCNt2rpp": {"minimum": 0.0, "maximum": 0.0},
            "ACALD": {"minimum": 3.35702, "maximum": 7.49572},
        }

        infeasible_model = create_test_model()
        infeasible_model.reactions.get_by_id("EX_glyc_e").lower_bound = 0
        for solver in solver_dict:
            # esolver is really slow
            if solver == "esolver":
                continue
            cobra_model = create_test_model()
            initialize_growth_medium(cobra_model, "LB")
            fva_out = flux_variability_analysis(
                cobra_model, solver=solver, reaction_list=cobra_model.reactions[100:140:2]
            )
            for the_reaction, the_range in iteritems(fva_out):
                for k, v in iteritems(the_range):
                    self.assertAlmostEqual(fva_results[the_reaction][k], v, places=5)
            # ensure that an infeasible model does not run FVA
            self.assertRaises(ValueError, flux_variability_analysis, infeasible_model, solver=solver)
Beispiel #2
0
    def test_modify_reversible(self):
        model1 = create_test_model("textbook")
        model1.optimize()
        model2 = create_test_model("textbook")
        modify.convert_to_irreversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
        modify.revert_to_reversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)

        # Ensure revert_to_reversible is robust to solutions generated both
        # before and after reversibility conversion, or not solved at all.
        model3 = create_test_model("textbook")
        model3.optimize()
        modify.convert_to_irreversible(model3)
        modify.revert_to_reversible(model3)
        self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3)

        # test reaction where both bounds are negative
        model4 = create_test_model("textbook")
        glc = model4.reactions.get_by_id("EX_glc__D_e")
        glc.upper_bound = -1
        modify.convert_to_irreversible(model4)
        model4.optimize()
        self.assertAlmostEqual(model1.solution.f, model4.solution.f, places=3)
        glc_rev = model4.reactions.get_by_id(glc.notes["reflection"])
        self.assertEqual(glc_rev.lower_bound, 1)
        self.assertEqual(glc.upper_bound, 0)
        modify.revert_to_reversible(model4)
        self.assertEqual(glc.upper_bound, -1)
Beispiel #3
0
    def test_flux_variability(self):
        fva_results = {
            '5DGLCNtex': {'minimum': 0.0, 'maximum': 0.0},
            'ABTA': {'minimum': 0.0, 'maximum': 0.0},
            '5DOAN': {'minimum': 0.0, 'maximum': 0.0},
            'A5PISO': {'minimum': 0.00692, 'maximum': 0.00692},
            'AACPS1': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS2': {'minimum': 0.0, 'maximum': 0.0},
            'ACALDtex': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS3': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS4': {'minimum': 0.0, 'maximum': 0.0},
            'ABUTD': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS5': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS6': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS7': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS8': {'minimum': 0.0, 'maximum': 0.0},
            'AACPS9': {'minimum': 0.0, 'maximum': 0.0},
            'AACTOOR': {'minimum': 0.0, 'maximum': 0.0},
            'ABUTt2pp': {'minimum': 0.0, 'maximum': 0.0},
            '3OAS140': {'minimum': 0.50419, 'maximum': 0.50419},
            '3OAS141': {'minimum': 0.03748, 'maximum': 0.03748},
            '3OAS160': {'minimum': 0.41769, 'maximum': 0.41769},
            '3OAS161': {'minimum': 0.03748, 'maximum': 0.03748},
            '3OAS180': {'minimum': 0.01071, 'maximum': 0.01071},
            '3OAS181': {'minimum': 0.01606, 'maximum': 0.01606},
            'ABUTtex': {'minimum': 0.0, 'maximum': 0.0},
            '3OAS60': {'minimum': 0.54399, 'maximum': 0.54399},
            '3OAS80': {'minimum': 0.54399, 'maximum': 0.54399},
            'AAMYL': {'minimum': 0.0, 'maximum': 0.0},
            '3PEPTabcpp': {'minimum': 0.0, 'maximum': 0.0},
            '3PEPTtex': {'minimum': 0.0, 'maximum': 0.0},
            '3UMPtex': {'minimum': 0.0, 'maximum': 0.0},
            '4HOXPACDtex': {'minimum': 0.0, 'maximum': 0.0},
            'ACACtex': {'minimum': 0.0, 'maximum': 0.0},
            '4PCP': {'minimum': 0.0, 'maximum': 0.0},
            '4PCPpp': {'minimum': 0.0, 'maximum': 0.0},
            'AAMYLpp': {'minimum': 0.0, 'maximum': 0.0},
            '4PEPTabcpp': {'minimum': 0.0, 'maximum': 0.0},
            '4PEPTtex': {'minimum': 0.0, 'maximum': 0.0},
            '5DGLCNR': {'minimum': 0.0, 'maximum': 0.0},
            '5DGLCNt2rpp': {'minimum': 0.0, 'maximum': 0.0},
            'ACALD': {'minimum': 3.35702, 'maximum': 7.49572}}

        infeasible_model = create_test_model()
        infeasible_model.reactions.get_by_id("EX_glyc_e").lower_bound = 0
        for solver in solver_dict:
            cobra_model = create_test_model()
            initialize_growth_medium(cobra_model, 'LB')
            fva_out = flux_variability_analysis(
                cobra_model, solver=solver,
                reaction_list=cobra_model.reactions[100:140:2])
            for the_reaction, the_range in iteritems(fva_out):
                for k, v in iteritems(the_range):
                    self.assertAlmostEqual(fva_results[the_reaction][k], v,
                                           places=5)
            # ensure that an infeasible model does not run FVA
            self.assertRaises(ValueError, flux_variability_analysis,
                              infeasible_model, solver=solver)
Beispiel #4
0
 def test_add_reaction_from_other_model(self):
     model = self.model
     other = model.copy()
     for i in other.reactions:
         i.id += "_other"
     other.repair()
     model.add_reactions(other.reactions)
     # what if the other reaction has an error in its GPR
     m1 = create_test_model("textbook")
     m2 = create_test_model("textbook")
     m1.reactions.PGI.remove_from_model()
     m2.genes.b4025._reaction.clear()
     m1.add_reaction(m2.reactions.PGI)
Beispiel #5
0
 def test_double_gene_deletion(self):
     cobra_model = create_test_model("textbook")
     genes = ["b0726", "b4025", "b0724", "b0720",
              "b2935", "b2935", "b1276", "b1241"]
     growth_list = [
         [0.858, 0.857, 0.814, 0.000, 0.858, 0.858, 0.858, 0.858],
         [0.857, 0.863, 0.739, 0.000, 0.863, 0.863, 0.863, 0.863],
         [0.814, 0.739, 0.814, 0.000, 0.814, 0.814, 0.814, 0.814],
         [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874]]
     opts = {"number_of_processes": 1} if name == "nt" else {}
     solution = double_gene_deletion(cobra_model, gene_list1=genes, **opts)
     self.assertEqual(solution["x"], genes)
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list, solution["data"])
     # test when lists differ slightly
     solution = double_gene_deletion(cobra_model, gene_list1=genes[:-1],
                                     gene_list2=genes,
                                     number_of_processes=1)
     self.assertEqual(solution["x"], genes[:-1])
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list[:-1], solution["data"])
Beispiel #6
0
 def test_validate_reaction_bounds(self):
     model = create_test_model("textbook")
     model.reactions[0].lower_bound = float("-inf")
     model.reactions[1].lower_bound = float("nan")
     model.reactions[0].upper_bound = float("inf")
     model.reactions[1].upper_bound = float("nan")
     errors = check_reaction_bounds(model)
     self.assertEqual(len(errors), 4)
Beispiel #7
0
 def test_phenotype_phase_plane(self):
     model = create_test_model("textbook")
     data = calculate_phenotype_phase_plane(
         model, "EX_glc__D_e", "EX_o2_e",
         reaction1_npoints=20, reaction2_npoints=20)
     self.assertEqual(data.growth_rates.shape, (20, 20))
     self.assertAlmostEqual(data.growth_rates.max(), 1.20898, places=4)
     self.assertAlmostEqual(abs(data.growth_rates[0, :]).max(), 0, places=4)
Beispiel #8
0
 def test_pFBA(self):
     model = create_test_model("textbook")
     for solver in solver_dict:
         optimize_minimal_flux(model, solver=solver)
         abs_x = [abs(i) for i in model.solution.x]
         self.assertEqual(model.solution.status, "optimal")
         self.assertAlmostEqual(model.solution.f, 0.8739, places=3)
         self.assertAlmostEqual(sum(abs_x), 518.4221, places=3)
Beispiel #9
0
    def test_single_gene_deletion_fba(self):
        cobra_model = create_test_model("textbook")
        # expected knockouts for textbook model
        growth_dict = {"b0008": 0.87, "b0114": 0.80, "b0116": 0.78, "b2276": 0.21, "b1779": 0.00}

        rates, statuses = single_gene_deletion(cobra_model, gene_list=growth_dict.keys(), method="fba")
        for gene, expected_value in iteritems(growth_dict):
            self.assertEqual(statuses[gene], "optimal")
            self.assertAlmostEqual(rates[gene], expected_value, places=2)
Beispiel #10
0
    def test_flux_variability(self):
        with open(join(data_directory, "textbook_fva.json"), "r") as infile:
            fva_results = load(infile)

        infeasible_model = create_test_model("textbook")
        infeasible_model.reactions.get_by_id("EX_glc__D_e").lower_bound = 0
        for solver in solver_dict:
            # esolver is really slow
            if solver == "esolver":
                continue
            cobra_model = create_test_model("textbook")
            fva_out = flux_variability_analysis(cobra_model, solver=solver, reaction_list=cobra_model.reactions[1::3])
            for name, result in iteritems(fva_out):
                for k, v in iteritems(result):
                    self.assertAlmostEqual(fva_results[name][k], v, places=5)

            # ensure that an infeasible model does not run FVA
            self.assertRaises(ValueError, flux_variability_analysis, infeasible_model, solver=solver)
Beispiel #11
0
 def test_phenotype_phase_plane(self):
     model = create_test_model("textbook")
     data = calculate_phenotype_phase_plane(model,
                                            "EX_glc__D_e",
                                            "EX_o2_e",
                                            reaction1_npoints=20,
                                            reaction2_npoints=20)
     self.assertEqual(data.growth_rates.shape, (20, 20))
     self.assertAlmostEqual(data.growth_rates.max(), 1.20898, places=4)
     self.assertAlmostEqual(abs(data.growth_rates[0, :]).max(), 0, places=4)
Beispiel #12
0
    def test_find_blocked_reactions(self):
        m = create_test_model("textbook")
        result = find_blocked_reactions(m, m.reactions[40:46])
        self.assertEqual(result, ["FRUpts2"])

        result = find_blocked_reactions(m, m.reactions[42:48])
        self.assertEqual(set(result), {"FUMt2_2", "FRUpts2"})

        result = find_blocked_reactions(m, m.reactions[30:50], open_exchanges=True)
        self.assertEqual(result, [])
Beispiel #13
0
 def test_modify_reversible(self):
     model1 = self.model
     model1.optimize()
     model2 = create_test_model()
     modify.convert_to_irreversible(model2)
     model2.optimize()
     self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
     modify.revert_to_reversible(model2)
     model2.optimize()
     self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
Beispiel #14
0
 def test_modify_reversible(self):
     model1 = self.model
     model1.optimize()
     model2 = create_test_model()
     modify.convert_to_irreversible(model2)
     model2.optimize()
     self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
     modify.revert_to_reversible(model2)
     model2.optimize()
     self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
Beispiel #15
0
    def test_summary_methods(self):

        # Test model summary methods
        model = create_test_model("textbook")
        model.optimize()
        desired_entries = [
            u'glc__D_e     -9.76 \u00B1 0.24'
            u'co2_e       21.81 \u00B1 2.86',
            u'nh4_e        -4.84 \u00B1 0.32'
            u'h_e         19.51 \u00B1 2.86',
            u'pi_e         -3.13 \u00B1 0.08'
            u'for_e        2.86 \u00B1 2.86',
            u'ac_e         0.95 \u00B1 0.95',
            u'acald_e      0.64 \u00B1 0.64',
            u'pyr_e        0.64 \u00B1 0.64',
            u'etoh_e       0.55 \u00B1 0.55',
            u'lac__D_e     0.54 \u00B1 0.54',
            u'succ_e       0.42 \u00B1 0.42',
            u'akg_e        0.36 \u00B1 0.36',
            u'glu__L_e     0.32 \u00B1 0.32']

        with captured_output() as (out, err):
            model.summary(fva=0.95)

        output = out.getvalue().strip()
        output_set = set((re.sub('\s', '', l) for l in output.splitlines()))

        for item in desired_entries:
            self.assertIn(re.sub('\s', '', item), output_set)

        # Test metabolite summary methods

        desired_entries = [
            'PRODUCING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '%      FLUX   RXN ID'
            'REACTION',
            '100.0%     44    CYTBD'
            '2.0 h_c + 0.5 o2_c + q8h2_c --> h2o_c + 2.0 h_e +...',
            'CONSUMING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '88.4%    -39   NADH16'
            '4.0 h_c + nadh_c + q8_c --> 3.0 h_e + nad_c + q8h2_c',
            '11.6%   -5.1    SUCDi                       '
            'q8_c + succ_c --> fum_c + q8h2_c',
        ]

        with captured_output() as (out, err):
            model.metabolites.q8_c.summary()

        output = out.getvalue().strip()
        output_set = set((re.sub('\s', '', l) for l in output.splitlines()))

        for item in desired_entries:
            self.assertIn(re.sub('\s', '', item), output_set)
Beispiel #16
0
 def test_optknock(self):
     model = create_test_model("textbook")
     model.reactions.get_by_id("EX_o2_e").lower_bound = 0
     knockable_reactions = ["ACKr", "AKGDH", "ACALD", "LDH_D"]
     optknock_problem = set_up_optknock(model, "EX_lac__D_e",
                                        knockable_reactions, n_knockouts=2,
                                        copy=False)
     solution = run_optknock(optknock_problem, tolerance_integer=1e-9)
     self.assertIn("ACKr", solution.knockouts)
     self.assertIn("ACALD", solution.knockouts)
     self.assertAlmostEqual(solution.f, 17.891, places=3)
Beispiel #17
0
 def test_validate_mass_balance(self):
     model = create_test_model("textbook")
     self.assertEqual(len(check_mass_balance(model)), 0)
     # if we remove the SBO term which marks the reaction as
     # mass balanced, then the reaction should be detected as
     # no longer mass balanced
     EX_rxn = model.reactions.query("EX")[0]
     EX_rxn.annotation.pop("SBO")
     balance = check_mass_balance(model)
     self.assertEqual(len(balance), 1)
     self.assertIn(EX_rxn, balance)
Beispiel #18
0
 def test_canonical_form(self):
     model = create_test_model("textbook")
     # add G constraint to test
     g_constr = Metabolite("SUCCt2_2__test_G_constraint")
     g_constr._constraint_sense = "G"
     g_constr._bound = 5.0
     model.reactions.get_by_id("SUCCt2_2").add_metabolites({g_constr: 1})
     self.assertAlmostEqual(model.optimize("maximize").f, 0.855, places=3)
     # convert to canonical form
     model = canonical_form(model)
     self.assertAlmostEqual(model.optimize("maximize").f, 0.855, places=3)
Beispiel #19
0
 def test_validate_mass_balance(self):
     model = create_test_model("textbook")
     self.assertEqual(len(check_mass_balance(model)), 0)
     # if we remove the SBO term which marks the reaction as
     # mass balanced, then the reaction should be detected as
     # no longer mass balanced
     EX_rxn = model.reactions.query("EX")[0]
     EX_rxn.annotation.pop("SBO")
     balance = check_mass_balance(model)
     self.assertEqual(len(balance), 1)
     self.assertIn(EX_rxn, balance)
Beispiel #20
0
 def test_canonical_form(self):
     model = create_test_model("textbook")
     # add G constraint to test
     g_constr = Metabolite("SUCCt2_2__test_G_constraint")
     g_constr._constraint_sense = "G"
     g_constr._bound = 5.0
     model.reactions.get_by_id("SUCCt2_2").add_metabolites({g_constr: 1})
     self.assertAlmostEqual(model.optimize("maximize").f, 0.855, places=3)
     # convert to canonical form
     model = canonical_form(model)
     self.assertAlmostEqual(model.optimize("maximize").f, 0.855, places=3)
Beispiel #21
0
    def test_find_blocked_reactions(self):
        m = create_test_model("textbook")
        result = find_blocked_reactions(m, m.reactions[40:46])
        self.assertEqual(result, ['FRUpts2'])

        result = find_blocked_reactions(m, m.reactions[42:48])
        self.assertEqual(set(result), {'FUMt2_2', 'FRUpts2'})

        result = find_blocked_reactions(m, m.reactions[30:50],
                                        open_exchanges=True)
        self.assertEqual(result, [])
Beispiel #22
0
 def test_phenotype_phase_plane(self):
     model = create_test_model("textbook")
     data = calculate_phenotype_phase_plane(
         model, "EX_glc__D_e", "EX_o2_e",
         reaction1_npoints=20, reaction2_npoints=20)
     self.assertEqual(data.growth_rates.shape, (20, 20))
     self.assertAlmostEqual(data.growth_rates.max(), 1.20898, places=4)
     self.assertAlmostEqual(abs(data.growth_rates[0, :]).max(), 0, places=4)
     if matplotlib is None:
         self.skipTest("can't test plots without matplotlib")
     data.plot()
Beispiel #23
0
    def test_single_reaction_deletion(self):
        cobra_model = create_test_model("textbook")
        expected_results = {"FBA": 0.70404, "FBP": 0.87392, "CS": 0, "FUM": 0.81430, "GAPD": 0, "GLUDy": 0.85139}

        results, status = single_reaction_deletion(cobra_model, reaction_list=expected_results.keys())
        self.assertEqual(len(results), 6)
        self.assertEqual(len(status), 6)
        for status_value in status.values():
            self.assertEqual(status_value, "optimal")
        for reaction, value in results.items():
            self.assertAlmostEqual(value, expected_results[reaction], 5)
Beispiel #24
0
 def test_phenotype_phase_plane(self):
     model = create_test_model("textbook")
     data = calculate_phenotype_phase_plane(
         model, "EX_glc__D_e", "EX_o2_e", reaction1_npoints=20, reaction2_npoints=20
     )
     self.assertEqual(data.growth_rates.shape, (20, 20))
     self.assertAlmostEqual(data.growth_rates.max(), 1.20898, places=4)
     self.assertAlmostEqual(abs(data.growth_rates[0, :]).max(), 0, places=4)
     if matplotlib is None:
         self.skipTest("can't test plots without matplotlib")
     data.plot()
Beispiel #25
0
    def test_pFBA(self):
        model = create_test_model("textbook")
        for solver in solver_dict:
            optimize_minimal_flux(model, solver=solver)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f, 0.8739, places=3)
            self.assertAlmostEqual(sum(abs_x), 518.4221, places=3)

            # Test desired_objective_value
            desired_objective = 0.8
            optimize_minimal_flux(model,
                                  solver=solver,
                                  desired_objective_value=desired_objective)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f,
                                   desired_objective,
                                   places=3)
            self.assertAlmostEqual(sum(abs_x), 476.1594, places=3)

            # Test fraction_of_optimum
            optimize_minimal_flux(model,
                                  solver=solver,
                                  fraction_of_optimum=0.95)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f, 0.95 * 0.8739, places=3)
            self.assertAlmostEqual(sum(abs_x), 493.4400, places=3)

            # Make sure the model works for non-unity objective values
            model.reactions.Biomass_Ecoli_core.objective_coefficient = 2
            optimize_minimal_flux(model, solver=solver)
            self.assertAlmostEqual(model.solution.f, 2 * 0.8739, places=3)
            model.reactions.Biomass_Ecoli_core.objective_coefficient = 1

            # Test some erroneous inputs -- multiple objectives
            model.reactions.ATPM.objective_coefficient = 1
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model, solver=solver)
            model.reactions.ATPM.objective_coefficient = 0

            # Minimization of objective
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model,
                                      solver=solver,
                                      objective_sense='minimize')

            # Infeasible solution
            atpm = float(model.reactions.ATPM.lower_bound)
            model.reactions.ATPM.lower_bound = 500
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model, solver=solver)
            model.reactions.ATPM.lower_bound = atpm
Beispiel #26
0
    def test_single_gene_deletion_fba(self):
        cobra_model = create_test_model("textbook")
        # expected knockouts for textbook model
        growth_dict = {"b0008": 0.87, "b0114": 0.80, "b0116": 0.78,
                       "b2276": 0.21, "b1779": 0.00}

        rates, statuses = single_gene_deletion(cobra_model,
                                               gene_list=growth_dict.keys(),
                                               method="fba")
        for gene, expected_value in iteritems(growth_dict):
            self.assertEqual(statuses[gene], 'optimal')
            self.assertAlmostEqual(rates[gene], expected_value, places=2)
Beispiel #27
0
 def test_dual_integer_vars_as_lp(self):
     model = create_test_model("textbook")
     var = _add_decision_variable(model, "AKGDH")
     self.assertAlmostEqual(model.optimize("maximize").f, 0.874, places=3)
     # as lp: make integer continuous, set to 1
     dual = dual_problem(model, "maximize", [var.id], copy=True)
     r = dual.reactions.get_by_id(var.id)
     r.variable_kind = "continuous"
     r.lower_bound = r.upper_bound = 1
     self.assertAlmostEqual(dual.optimize("minimize").f, 0.874, places=3)
     r.lower_bound = r.upper_bound = 0
     self.assertAlmostEqual(dual.optimize("minimize").f, 0.858, places=3)
Beispiel #28
0
    def test_flux_variability(self):
        with open(join(data_directory, "textbook_fva.json"), "r") as infile:
            fva_results = load(infile)

        infeasible_model = create_test_model("textbook")
        infeasible_model.reactions.get_by_id("EX_glc__D_e").lower_bound = 0
        for solver in solver_dict:
            # esolver is really slow
            if solver == "esolver":
                continue
            cobra_model = create_test_model("textbook")
            fva_out = flux_variability_analysis(
                cobra_model, solver=solver,
                reaction_list=cobra_model.reactions[1::3])
            for name, result in iteritems(fva_out):
                for k, v in iteritems(result):
                    self.assertAlmostEqual(fva_results[name][k], v, places=5)

            # ensure that an infeasible model does not run FVA
            self.assertRaises(ValueError, flux_variability_analysis,
                              infeasible_model, solver=solver)
Beispiel #29
0
 def test_rename_gene(self):
     model = create_test_model('textbook')
     original_name = model.genes.b1241.name
     modify.rename_genes(model, {"b1241": "foo", "hello": "world"})
     self.assertNotIn("b1241", model.genes)
     self.assertIn("foo", model.genes)
     # make sure the object name was preserved
     self.assertEqual(model.genes.foo.name, original_name)
     # make sure the reactions are correct
     self.assertEqual(len(model.genes.foo.reactions), 2)
     self.assertEqual(model.reactions.ACALD.gene_reaction_rule,
                      "b0351 or foo")
Beispiel #30
0
    def test_summary_methods(self):

        # Test model summary methods
        model = create_test_model("textbook")
        model.optimize()
        desired_entries = [
            u'glc__D_e     -9.76 \u00B1 0.24'
            u'co2_e       21.81 \u00B1 2.86', u'nh4_e        -4.84 \u00B1 0.32'
            u'h_e         19.51 \u00B1 2.86', u'pi_e         -3.13 \u00B1 0.08'
            u'for_e        2.86 \u00B1 2.86', u'ac_e         0.95 \u00B1 0.95',
            u'acald_e      0.64 \u00B1 0.64', u'pyr_e        0.64 \u00B1 0.64',
            u'etoh_e       0.55 \u00B1 0.55', u'lac__D_e     0.54 \u00B1 0.54',
            u'succ_e       0.42 \u00B1 0.42', u'akg_e        0.36 \u00B1 0.36',
            u'glu__L_e     0.32 \u00B1 0.32'
        ]
        with captured_output() as (out, err):
            model.summary(fva=0.95)
        self.check_entries(out, desired_entries)

        # test non-fva version (these should be fixed for textbook model
        desired_entries = [
            "o2_e       -21.80", "glc__D_e   -10.00", "nh4_e       -4.77",
            "pi_e        -3.21", "h2o_e    29.18", "co2_e    22.81",
            "h_e      17.53", "Biomass_Ecoli_core    0.874"
        ]
        # Need to use a different method here because
        # there are multiple entries per line.
        with captured_output() as (out, err):
            model.summary()
        s = out.getvalue()
        for i in desired_entries:
            self.assertIn(i, s)

        # Test metabolite summary methods

        desired_entries = [
            'PRODUCING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '%      FLUX   RXN ID'
            'REACTION',
            '100.0%     44    CYTBD'
            '2.0 h_c + 0.5 o2_c + q8h2_c --> h2o_c + 2.0 h_e +...',
            'CONSUMING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '88.4%    -39   NADH16'
            '4.0 h_c + nadh_c + q8_c --> 3.0 h_e + nad_c + q8h2_c',
            '11.6%   -5.1    SUCDi                       '
            'q8_c + succ_c --> fum_c + q8h2_c',
        ]
        with captured_output() as (out, err):
            model.metabolites.q8_c.summary()
        self.check_entries(out, desired_entries)
Beispiel #31
0
    def test_single_reaction_deletion(self):
        cobra_model = create_test_model("textbook")
        expected_results = {'FBA': 0.70404, 'FBP': 0.87392, 'CS': 0,
                            'FUM': 0.81430, 'GAPD': 0, 'GLUDy': 0.85139}

        results, status = single_reaction_deletion(
            cobra_model, reaction_list=expected_results.keys())
        self.assertEqual(len(results), 6)
        self.assertEqual(len(status), 6)
        for status_value in status.values():
            self.assertEqual(status_value, "optimal")
        for reaction, value in results.items():
            self.assertAlmostEqual(value, expected_results[reaction], 5)
Beispiel #32
0
 def test_canonical_form_minimize(self):
     model = create_test_model("textbook")
     # make a minimization problem
     model.reactions.get_by_id("Biomass_Ecoli_core").lower_bound = 0.5
     for reaction in model.reactions:
         reaction.objective_coefficient = reaction.id == "GAPD"
     self.assertAlmostEqual(model.optimize("minimize").f, 6.27, places=3)
     # convert to canonical form. Convert minimize to maximize
     model = canonical_form(model, objective_sense="minimize")
     self.assertAlmostEqual(model.optimize("maximize").f, -6.27, places=3)
     # lower bounds should now be <= constraints
     self.assertEqual(
         model.reactions.get_by_id("Biomass_Ecoli_core").lower_bound, 0.0)
Beispiel #33
0
    def test_modify_reversible(self):
        model1 = self.model
        model1.optimize()
        model2 = create_test_model()
        modify.convert_to_irreversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
        modify.revert_to_reversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)

        # Ensure revert_to_reversible is robust to solutions generated both
        # before and after reversibility conversion, or not solved at all.
        model3 = create_test_model()
        model3.optimize()
        modify.convert_to_irreversible(model3)
        modify.revert_to_reversible(model3)
        self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3)

        model4 = create_test_model()
        modify.convert_to_irreversible(model4)
        modify.revert_to_reversible(model4)
Beispiel #34
0
 def setUp(self):
     self.solver = solvers.solver_dict[self.solver_name]
     self.model = create_test_model()
     self.old_solution = 0.380008
     self.infeasible_model = Model()
     metabolite_1 = Metabolite("met1")
     reaction_1 = Reaction("rxn1")
     reaction_2 = Reaction("rxn2")
     reaction_1.add_metabolites({metabolite_1: 1})
     reaction_2.add_metabolites({metabolite_1: 1})
     reaction_1.lower_bound = 1
     reaction_2.upper_bound = 2
     self.infeasible_model.add_reactions([reaction_1, reaction_2])
Beispiel #35
0
 def test_canonical_form_minimize(self):
     model = create_test_model("textbook")
     # make a minimization problem
     model.reactions.get_by_id("Biomass_Ecoli_core").lower_bound = 0.5
     for reaction in model.reactions:
         reaction.objective_coefficient = reaction.id == "GAPD"
     self.assertAlmostEqual(model.optimize("minimize").f, 6.27, places=3)
     # convert to canonical form. Convert minimize to maximize
     model = canonical_form(model, objective_sense="minimize")
     self.assertAlmostEqual(model.optimize("maximize").f, -6.27, places=3)
     # lower bounds should now be <= constraints
     self.assertEqual(
         model.reactions.get_by_id("Biomass_Ecoli_core").lower_bound, 0.0)
Beispiel #36
0
 def test_array_based_model_add(self):
     for matrix_type in ["scipy.dok_matrix", "scipy.lil_matrix"]:
         model = create_test_model().to_array_based_model(matrix_type=matrix_type)
         test_reaction = Reaction("test")
         test_reaction.add_metabolites({model.metabolites[0]: 4})
         test_reaction.lower_bound = -3.14
         model.add_reaction(test_reaction)
         self.assertEqual(len(model.reactions), 2547)
         self.assertEqual(model.S.shape[1], 2547)
         self.assertEqual(len(model.lower_bounds), 2547)
         self.assertEqual(model.S[0, 2546], 4)
         self.assertEqual(model.S[1605, 0], -1)
         self.assertEqual(model.lower_bounds[2546], -3.14)
Beispiel #37
0
 def setUp(self):
     self.solver = solvers.solver_dict[self.solver_name]
     self.model = create_test_model("textbook")
     self.old_solution = 0.8739215
     self.infeasible_model = Model()
     metabolite_1 = Metabolite("met1")
     reaction_1 = Reaction("rxn1")
     reaction_2 = Reaction("rxn2")
     reaction_1.add_metabolites({metabolite_1: 1})
     reaction_2.add_metabolites({metabolite_1: 1})
     reaction_1.lower_bound = 1
     reaction_2.upper_bound = 2
     self.infeasible_model.add_reactions([reaction_1, reaction_2])
Beispiel #38
0
    def test_modify_reversible(self):
        model1 = create_test_model("textbook")
        model1.optimize()
        model2 = create_test_model("textbook")
        modify.convert_to_irreversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
        modify.revert_to_reversible(model2)
        model2.optimize()
        self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)

        # Ensure revert_to_reversible is robust to solutions generated both
        # before and after reversibility conversion, or not solved at all.
        model3 = create_test_model("textbook")
        model3.optimize()
        modify.convert_to_irreversible(model3)
        modify.revert_to_reversible(model3)
        self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3)

        model4 = create_test_model("textbook")
        modify.convert_to_irreversible(model4)
        modify.revert_to_reversible(model4)
Beispiel #39
0
    def test_flux_variability(self):
        fva_results = {
            '5DGLCNtex': {'minimum': -1.9748300208638403e-05, 'maximum': 0.0},
            'ABTA': {'minimum': 0.0, 'maximum': 0.00014811225541408996},
            '5DOAN': {'minimum': 0.0, 'maximum': 3.2227507421302166e-06},
            'A5PISO': {'minimum': 0.006920856282000001, 'maximum': 0.006922717378372606},
            'AACPS1': {'minimum': 0.0, 'maximum': 3.7028063376249126e-05},
            'AACPS2': {'minimum': 0.0, 'maximum': 3.7028063733878864e-05},
            'ACALDtex': {'minimum': -0.00011848980305159615, 'maximum': 0.0},
            'AACPS3': {'minimum': 0.0, 'maximum': 3.702806337623859e-05},
            'AACPS4': {'minimum': 0.0, 'maximum': 3.702806373387888e-05},
            'ABUTD': {'minimum': 0.0, 'maximum': 0.00014811225541406058},
            'AACPS5': {'minimum': 0.0, 'maximum': 2.8211857518389774e-05},
            'AACPS6': {'minimum': 0.0, 'maximum': 2.821185753295664e-05},
            'AACPS7': {'minimum': 0.0, 'maximum': 3.702806368868028e-05},
            'AACPS8': {'minimum': 0.0, 'maximum': 3.702806338788376e-05},
            'AACPS9': {'minimum': 0.0, 'maximum': 3.702806309933293e-05},
            'AACTOOR': {'minimum': 0.0, 'maximum': 1.5388286124597477e-05},
            'ABUTt2pp': {'minimum': 0.0, 'maximum': 0.0},
            '3OAS140': {'minimum': 0.5041754136687804, 'maximum': 0.5042009621703677},
            '3OAS141': {'minimum': 0.037484893950000084, 'maximum': 0.03750284695065363},
            '3OAS160': {'minimum': 0.41767086529953557, 'maximum': 0.41769641380045963},
            '3OAS161': {'minimum': 0.03748489395, 'maximum': 0.03750284695060761},
            '3OAS180': {'minimum': 0.01069201669939239, 'maximum': 0.010717565200387778},
            '3OAS181': {'minimum': 0.01606495455, 'maximum': 0.01608290755044158},
            'ABUTtex': {'minimum': 0.0, 'maximum': 0.0},
            '3OAS60': {'minimum': 0.5439852127139995, 'maximum': 0.5439896193596934},
            '3OAS80': {'minimum': 0.5439852127140001, 'maximum': 0.5439896193596934},
            'AAMYL': {'minimum': 0.0, 'maximum': 0.0},
            '3PEPTabcpp': {'minimum': 0.0, 'maximum': 5.808323730923103e-06},
            '3PEPTtex': {'minimum': -3.4245609402880297e-06, 'maximum': 0.0},
            '3UMPtex': {'minimum': 0.0, 'maximum': 0.0},
            '4HOXPACDtex': {'minimum': 0.0, 'maximum': 0.0},
            'ACACtex': {'minimum': 0.0, 'maximum': 0.0},
            '4PCP': {'minimum': 0.0, 'maximum': 6.171343917391756e-06},
            '4PCPpp': {'minimum': 0.0, 'maximum': 5.58914186256664e-06},
            'AAMYLpp': {'minimum': 0.0, 'maximum': 0.0},
            '4PEPTabcpp': {'minimum': 0.0, 'maximum': 5.696625084349692e-06},
            '4PEPTtex': {'minimum': -3.2198316806921494e-06, 'maximum': 0.0},
            '5DGLCNR': {'minimum': -2.1942555793285538e-05, 'maximum': 0.0},
            '5DGLCNt2rpp': {'minimum': -1.9748300208638403e-05, 'maximum': 0.0},
            'ACALD': {'minimum': 3.356574143593833, 'maximum': 7.4957163478682105}}

        for solver in solver_dict:
            cobra_model = create_test_model()
            initialize_growth_medium(cobra_model, 'LB')
            fva_out = flux_variability_analysis(cobra_model, solver=solver,
                    reaction_list=cobra_model.reactions[100:140])
            for the_reaction, the_range in fva_out.iteritems():
                for k, v in the_range.iteritems():
                    self.assertAlmostEqual(fva_results[the_reaction][k], v, places=3)
Beispiel #40
0
    def test_pFBA(self):
        model = create_test_model("textbook")
        for solver in solver_dict:
            optimize_minimal_flux(model, solver=solver)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f, 0.8739, places=3)
            self.assertAlmostEqual(sum(abs_x), 518.4221, places=3)

            # Test desired_objective_value
            desired_objective = 0.8
            optimize_minimal_flux(model, solver=solver,
                                  desired_objective_value=desired_objective)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f, desired_objective,
                                   places=3)
            self.assertAlmostEqual(sum(abs_x), 476.1594, places=3)

            # Test fraction_of_optimum
            optimize_minimal_flux(model, solver=solver,
                                  fraction_of_optimum=0.95)
            abs_x = [abs(i) for i in model.solution.x]
            self.assertEqual(model.solution.status, "optimal")
            self.assertAlmostEqual(model.solution.f, 0.95*0.8739, places=3)
            self.assertAlmostEqual(sum(abs_x), 493.4400, places=3)

            # Make sure the model works for non-unity objective values
            model.reactions.Biomass_Ecoli_core.objective_coefficient = 2
            optimize_minimal_flux(model, solver=solver)
            self.assertAlmostEqual(model.solution.f, 2*0.8739, places=3)
            model.reactions.Biomass_Ecoli_core.objective_coefficient = 1

            # Test some erroneous inputs -- multiple objectives
            model.reactions.ATPM.objective_coefficient = 1
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model, solver=solver)
            model.reactions.ATPM.objective_coefficient = 0

            # Minimization of objective
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model, solver=solver,
                                      objective_sense='minimize')

            # Infeasible solution
            atpm = float(model.reactions.ATPM.lower_bound)
            model.reactions.ATPM.lower_bound = 500
            with self.assertRaises(ValueError):
                optimize_minimal_flux(model, solver=solver)
            model.reactions.ATPM.lower_bound = atpm
Beispiel #41
0
 def setUp(self):
     self.model = create_test_model()
     initialize_growth_medium(self.model, 'MgM')
     self.old_solution = 0.320064
     self.infeasible_model = Model()
     metabolite_1 = Metabolite("met1")
     #metabolite_2 = Metabolite("met2")
     reaction_1 = Reaction("rxn1")
     reaction_2 = Reaction("rxn2")
     reaction_1.add_metabolites({metabolite_1: 1})
     reaction_2.add_metabolites({metabolite_1: 1})
     reaction_1.lower_bound = 1
     reaction_2.upper_bound = 2
     self.infeasible_model.add_reactions([reaction_1, reaction_2])
Beispiel #42
0
 def test_SBO_annotation(self):
     model = create_test_model("textbook")
     rxns = model.reactions
     rxns.EX_o2_e.annotation.clear()
     fake_DM = Reaction("DM_h_c")
     model.add_reaction(fake_DM)
     fake_DM.add_metabolites({model.metabolites.get_by_id("h_c"): -1})
     # this exchange will be set wrong. The function should not overwrite
     # an existing SBO annotation
     rxns.get_by_id("EX_h_e").annotation["SBO"] = "SBO:0000628"
     add_SBO(model)
     self.assertEqual(rxns.EX_o2_e.annotation["SBO"], "SBO:0000627")
     self.assertEqual(rxns.DM_h_c.annotation["SBO"], "SBO:0000628")
     self.assertEqual(rxns.EX_h_e.annotation["SBO"], "SBO:0000628")
Beispiel #43
0
    def test_summary_methods(self):

        # Test model summary methods
        model = create_test_model("textbook")
        model.optimize()
        desired_entries = [
            u'glc__D_e     -9.76 \u00B1 0.24'
            u'co2_e       21.81 \u00B1 2.86', u'nh4_e        -4.84 \u00B1 0.32'
            u'h_e         19.51 \u00B1 2.86', u'pi_e         -3.13 \u00B1 0.08'
            u'for_e        2.86 \u00B1 2.86', u'ac_e         0.95 \u00B1 0.95',
            u'acald_e      0.64 \u00B1 0.64', u'pyr_e        0.64 \u00B1 0.64',
            u'etoh_e       0.55 \u00B1 0.55', u'lac__D_e     0.54 \u00B1 0.54',
            u'succ_e       0.42 \u00B1 0.42', u'akg_e        0.36 \u00B1 0.36',
            u'glu__L_e     0.32 \u00B1 0.32'
        ]

        with captured_output() as (out, err):
            model.summary(fva=0.95)

        output = out.getvalue().strip()
        output_set = set((re.sub('\s', '', l) for l in output.splitlines()))

        for item in desired_entries:
            self.assertIn(re.sub('\s', '', item), output_set)

        # Test metabolite summary methods

        desired_entries = [
            'PRODUCING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '%      FLUX   RXN ID'
            'REACTION',
            '100.0%     44    CYTBD'
            '2.0 h_c + 0.5 o2_c + q8h2_c --> h2o_c + 2.0 h_e +...',
            'CONSUMING REACTIONS -- Ubiquinone-8',
            '-----------------------------------',
            '88.4%    -39   NADH16'
            '4.0 h_c + nadh_c + q8_c --> 3.0 h_e + nad_c + q8h2_c',
            '11.6%   -5.1    SUCDi                       '
            'q8_c + succ_c --> fum_c + q8h2_c',
        ]

        with captured_output() as (out, err):
            model.metabolites.q8_c.summary()

        output = out.getvalue().strip()
        output_set = set((re.sub('\s', '', l) for l in output.splitlines()))

        for item in desired_entries:
            self.assertIn(re.sub('\s', '', item), output_set)
Beispiel #44
0
    def test_double_reaction_deletion(self):
        cobra_model = create_test_model("textbook")
        reactions = ['FBA', 'ATPS4r', 'ENO', 'FRUpts2']
        growth_list = [[0.704, 0.135, 0.000, 0.704],
                       [0.135, 0.374, 0.000, 0.374],
                       [0.000, 0.000, 0.000, 0.000],
                       [0.704, 0.374, 0.000, 0.874]]

        solution = double_reaction_deletion(cobra_model,
                                            reaction_list1=reactions,
                                            number_of_processes=1)
        self.assertEqual(solution["x"], reactions)
        self.assertEqual(solution["y"], reactions)
        self.compare_matrices(growth_list, solution["data"])
Beispiel #45
0
 def test_SBO_annotation(self):
     model = create_test_model("textbook")
     rxns = model.reactions
     rxns.EX_o2_e.annotation.clear()
     fake_DM = Reaction("DM_h_c")
     model.add_reaction(fake_DM)
     fake_DM.add_metabolites({model.metabolites.get_by_id("h_c"): -1})
     # this exchange will be set wrong. The function should not overwrite
     # an existing SBO annotation
     rxns.get_by_id("EX_h_e").annotation["SBO"] = "SBO:0000628"
     add_SBO(model)
     self.assertEqual(rxns.EX_o2_e.annotation["SBO"], "SBO:0000627")
     self.assertEqual(rxns.DM_h_c.annotation["SBO"], "SBO:0000628")
     self.assertEqual(rxns.EX_h_e.annotation["SBO"], "SBO:0000628")
Beispiel #46
0
 def test_array_based_model_add(self):
     for matrix_type in ["scipy.dok_matrix", "scipy.lil_matrix"]:
         model = create_test_model().to_array_based_model(
             matrix_type=matrix_type)
         test_reaction = Reaction("test")
         test_reaction.add_metabolites({model.metabolites[0]: 4})
         test_reaction.lower_bound = -3.14
         model.add_reaction(test_reaction)
         self.assertEqual(len(model.reactions), 2547)
         self.assertEqual(model.S.shape[1], 2547)
         self.assertEqual(len(model.lower_bounds), 2547)
         self.assertEqual(model.S[0, 2546], 4)
         self.assertEqual(model.S[0, 0], -1)
         self.assertEqual(model.lower_bounds[2546], -3.14)
Beispiel #47
0
 def setUp(self):
     self.model = create_test_model()
     initialize_growth_medium(self.model, "MgM")
     self.old_solution = 0.320064
     self.infeasible_model = Model()
     metabolite_1 = Metabolite("met1")
     # metabolite_2 = Metabolite("met2")
     reaction_1 = Reaction("rxn1")
     reaction_2 = Reaction("rxn2")
     reaction_1.add_metabolites({metabolite_1: 1})
     reaction_2.add_metabolites({metabolite_1: 1})
     reaction_1.lower_bound = 1
     reaction_2.upper_bound = 2
     self.infeasible_model.add_reactions([reaction_1, reaction_2])
Beispiel #48
0
    def test_double_reaction_deletion(self):
        cobra_model = create_test_model("textbook")
        reactions = ["FBA", "ATPS4r", "ENO", "FRUpts2"]
        growth_list = [
            [0.704, 0.135, 0.000, 0.704],
            [0.135, 0.374, 0.000, 0.374],
            [0.000, 0.000, 0.000, 0.000],
            [0.704, 0.374, 0.000, 0.874],
        ]

        solution = double_reaction_deletion(cobra_model, reaction_list1=reactions, number_of_processes=1)
        self.assertEqual(solution["x"], reactions)
        self.assertEqual(solution["y"], reactions)
        self.compare_matrices(growth_list, solution["data"])
Beispiel #49
0
    def test_single_gene_deletion_moma(self):
        # MOMA requires a QP solver
        try:
            get_solver_name(qp=True)
        except:
            self.skipTest("no qp support")

        cobra_model = create_test_model("textbook")
        # expected knockouts for textbook model
        growth_dict = {"b0008": 0.87, "b0114": 0.71, "b0116": 0.56, "b2276": 0.11, "b1779": 0.00}

        rates, statuses = single_gene_deletion(cobra_model, gene_list=growth_dict.keys(), method="moma")
        for gene, expected_value in iteritems(growth_dict):
            self.assertEqual(statuses[gene], "optimal")
            self.assertAlmostEqual(rates[gene], expected_value, places=2)
Beispiel #50
0
def create_fba_model(solver=GLPK):

    # g6p_c = cobra.Metabolite(id = 'g6p_c', formula = 'C6H13O9P')
    # f6p_c = cobra.Metabolite(id = 'f6p_c', formula = 'C6H13O9P')
    #
    # g6p_ex = cobra.Reaction(id='EX_g6p')
    # g6p_ex.add_metabolites({g6p_c: -1})
    #
    # f6p_ex = cobra.Reaction(id='EX_g6p')
    # f6p_ex.add_metabolites({f6p_c: -1})
    #
    # pgi = cobra.Reaction(id='PGI')
    # pgi.add_metabolites({g6p_c: -1, f6p_c: 1})
    # pgi.gene_reaction_rule = 'b4025'
    #
    # pgi.lower_bound = -1000
    # g6p_ex.lower_bound = -1000
    # f6p_ex.lower_bound = -1000

    # the_model = cobra.Model()
    the_model = create_test_model('textbook')
    # the_model.add_reactions([g6p_ex, pgi, f6p_ex])

    pi = the_model.metabolites.pi_c
    h = the_model.metabolites.h_c
    h2o = the_model.metabolites.h2o_c

    ppi = cobra.Metabolite(id='ppi_c', formula='P2O7', compartment='c')
    ppi_hydrolysis = cobra.Reaction(id='pi_to_ppi')
    ppi_hydrolysis.add_metabolites({ppi: -1, h2o: -1, pi: 2, h: 2})

    gdp = cobra.Metabolite(id='gdp_c',
                           formula='C10H15N5O11P2',
                           compartment='c')
    gdp_ex = cobra.Reaction(id='EX_g6p')
    gdp_ex.add_metabolites({gdp: -1})

    the_model.add_reactions([ppi_hydrolysis, gdp_ex])

    add_e_metabolites(the_model)

    for met in ['dttp', 'dctp', 'datp', 'dgtp']:
        the_ex = the_model.reactions.get_by_id('EX_' + met + '_c')
        the_ex.lower_bound = -1
    # add_growth(the_model)

    the_model.solver = solver
    return the_model
Beispiel #51
0
    def setUp(self):
        self.test_model = create_test_model()
        self.test_file = salmonella_pickle
        self.load = load
        self.dump = dump

        def read_function(filename):
            with open(filename, "rb") as infile:
                return self.load(infile)

        def write_function(model, filename):
            with open(filename, "wb") as outfile:
                self.dump(model, outfile)

        self.read_function = read_function
        self.write_function = write_function
Beispiel #52
0
    def test_array_based_model(self):
        m = len(self.model.metabolites)
        n = len(self.model.reactions)
        assertEqual = self.assertEqual  # alias
        for matrix_type in ["scipy.dok_matrix", "scipy.lil_matrix"]:
            model = create_test_model("textbook").\
                to_array_based_model(matrix_type=matrix_type)
            assertEqual(model.S[7, 0], -1)
            assertEqual(model.S[43, 0], 0)
            model.S[43, 0] = 1
            assertEqual(model.S[43, 0], 1)
            assertEqual(
                model.reactions[0].metabolites[model.metabolites[43]], 1)
            model.S[43, 0] = 0
            assertEqual(model.lower_bounds[0], model.reactions[0].lower_bound)
            assertEqual(model.lower_bounds[5], model.reactions[5].lower_bound)
            assertEqual(model.upper_bounds[0], model.reactions[0].upper_bound)
            assertEqual(model.upper_bounds[5], model.reactions[5].upper_bound)
            model.lower_bounds[6] = 2
            self.assertEqual(model.lower_bounds[6], 2)
            self.assertEqual(model.reactions[6].lower_bound, 2)
            # this should fail because it is the wrong size
            with self.assertRaises(Exception):
                model.upper_bounds = [0, 1]
            model.upper_bounds = [0] * len(model.reactions)
            self.assertEqual(max(model.upper_bounds), 0)

            # test something for all the attributes
            model.lower_bounds[2] = -1
            assertEqual(model.reactions[2].lower_bound, -1)
            assertEqual(model.lower_bounds[2], -1)
            model.objective_coefficients[2] = 1
            assertEqual(model.reactions[2].objective_coefficient, 1)
            assertEqual(model.objective_coefficients[2], 1)
            model.b[2] = 1
            assertEqual(model.metabolites[2]._bound, 1)
            assertEqual(model.b[2], 1)
            model.constraint_sense[2] = "L"
            assertEqual(model.metabolites[2]._constraint_sense, "L")
            assertEqual(model.constraint_sense[2], "L")

            # test resize matrix on reaction removal
            m, n = model.S.shape
            model.remove_reactions([model.reactions[2]], remove_orphans=False)
            self.assertEqual(len(model.metabolites), model.S.shape[0])
            self.assertEqual(len(model.reactions), model.S.shape[1])
            self.assertEqual(model.S.shape, (m, n - 1))
Beispiel #53
0
 def test_array_based_model_add(self):
     m = len(self.model.metabolites)
     n = len(self.model.reactions)
     for matrix_type in ["scipy.dok_matrix", "scipy.lil_matrix"]:
         model = create_test_model("textbook").\
             to_array_based_model(matrix_type=matrix_type)
         test_reaction = Reaction("test")
         test_reaction.add_metabolites({model.metabolites[0]: 4})
         test_reaction.lower_bound = -3.14
         model.add_reaction(test_reaction)
         self.assertEqual(len(model.reactions), n + 1)
         self.assertEqual(model.S.shape, (m, n + 1))
         self.assertEqual(len(model.lower_bounds), n + 1)
         self.assertEqual(len(model.upper_bounds), n + 1)
         self.assertEqual(model.S[0, n], 4)
         self.assertEqual(model.S[7, 0], -1)
         self.assertEqual(model.lower_bounds[n], -3.14)
Beispiel #54
0
def fluxSampling(model):
    from cobra.test import create_test_model
    from cobra.flux_analysis import sample
    model = create_test_model("textbook")
    s = sample(model, 100)  #number of samples to generate
    s.head()
    s = sample(model, 1000)
    s

    #The sampling process can be controlled on a lower level by using the sampler classes directly.
    from cobra.flux_analysis.sampling import OptGPSampler, ACHRSampler
    achr = ACHRSampler(
        model, thinning=10
    )  #“Thinning” means only recording samples every n iterations. A higher thinning factor means less correlated samples but also larger computation times.
    optgp = OptGPSampler(
        model, processes=4
    )  #an additional processes argument specifying how many processes are used to create parallel sampling chains.

    #For OptGPSampler the number of samples should be a multiple of the number of
    # processes, otherwise it will be increased to the nearest multiple automatically.
    s1 = achr.sample(100)
    s2 = optgp.sample(100)

    # Sampling and validation
    import numpy as np
    bad = np.random.uniform(-1000, 1000, size=len(model.reactions))
    achr.validate(np.atleast_2d(bad))  #should not be feasible
    achr.validate(s1)

    # Batch sampling
    counts = [
        np.mean(s.Biomass_Ecoli_core > 0.1) for s in optgp.batch(100, 10)
    ]
    print("Usually {:.2f}% +- {:.2f}% grow...".format(
        np.mean(counts) * 100.0,
        np.std(counts) * 100.0))

    # Adding constraints
    co = model.problem.Constraint(
        model.reactions.Biomass_Ecoli_core.flux_expression, lb=0.1)
    model.add_cons_vars([co])

    # Note that this is only for demonstration purposes. usually you could set
    # the lower bound of the reaction directly instead of creating a new constraint.
    s = sample(model, 10)
    print(s.Biomass_Ecoli_core)
Beispiel #55
0
    def test_single_gene_deletion_moma(self):
        # MOMA requires a QP solver
        try:
            get_solver_name(qp=True)
        except:
            self.skipTest("no qp support")

        cobra_model = create_test_model("textbook")
        # expected knockouts for textbook model
        growth_dict = {"b0008": 0.87, "b0114": 0.71, "b0116": 0.56,
                       "b2276": 0.11, "b1779": 0.00}

        rates, statuses = single_gene_deletion(cobra_model,
                                               gene_list=growth_dict.keys(),
                                               method="moma")
        for gene, expected_value in iteritems(growth_dict):
            self.assertEqual(statuses[gene], 'optimal')
            self.assertAlmostEqual(rates[gene], expected_value, places=2)
Beispiel #56
0
    def test_single_gene_deletion(self):
        cobra_model = create_test_model("textbook")
        # expected knockouts for textbook model
        growth_dict = {"fba": {"b0008": 0.87, "b0114": 0.80, "b0116": 0.78,
                               "b2276": 0.21, "b1779": 0.00},
                       "moma": {"b0008": 0.87, "b0114": 0.71, "b0116": 0.56,
                                "b2276": 0.11, "b1779": 0.00},
                       }

        # MOMA requires cplex or gurobi
        try:
            get_solver_name(qp=True)
        except:
            growth_dict.pop('moma')
        for method, expected in growth_dict.items():
            rates, statuses = single_gene_deletion(cobra_model,
                                                   gene_list=expected.keys(),
                                                   method=method)
            for gene, expected_value in iteritems(expected):
                self.assertEqual(statuses[gene], 'optimal')
                self.assertAlmostEqual(rates[gene], expected_value, places=2)
Beispiel #57
0
 def test_double_gene_deletion(self):
     cobra_model = create_test_model("textbook")
     genes = ["b0726", "b4025", "b0724", "b0720",
              "b2935", "b2935", "b1276", "b1241"]
     growth_list = [
         [0.858, 0.857, 0.814, 0.000, 0.858, 0.858, 0.858, 0.858],
         [0.857, 0.863, 0.739, 0.000, 0.863, 0.863, 0.863, 0.863],
         [0.814, 0.739, 0.814, 0.000, 0.814, 0.814, 0.814, 0.814],
         [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874],
         [0.858, 0.863, 0.814, 0.000, 0.874, 0.874, 0.874, 0.874]]
     solution = double_gene_deletion(cobra_model, gene_list1=genes)
     self.assertEqual(solution["x"], genes)
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list, solution["data"])
     # test when lists differ slightly
     solution = double_gene_deletion(cobra_model, gene_list1=genes[:-1],
                                     gene_list2=genes,
                                     number_of_processes=1)
     self.assertEqual(solution["x"], genes[:-1])
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list[:-1], solution["data"])
Beispiel #58
0
 def setUp(self):
     self.test_model = create_test_model(ecoli_pickle)
     self.test_file = ecoli_mat
     self.read_function = io.load_matlab_model
     self.write_function = io.save_matlab_model
Beispiel #59
0
 def setUp(self):
     self.test_model = create_test_model()
     self.test_file = salmonella_fbc_sbml
     self.read_function = io.read_sbml_model
     self.write_function = partial(io.write_sbml_model,
                                   use_fbc_package=True)
Beispiel #60
0
 def setUp(self):
     self.test_model = create_test_model()
     self.test_file = salmonella_sbml
     self.read_function = io.read_sbml_model
     self.write_function = io.write_sbml_model