Esempio n. 1
0
    def test_single_gene_deletion(self):
        cobra_model = self.model
        initialize_growth_medium(cobra_model, 'LB')

        # Expected growth rates for the salmonella model with deletions in LB
        the_loci = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id,
                                                the_loci)
        id_to_name = dict([(x.id, x.name) for x in the_genes])
        growth_dict = {'fba': {tpiA.id: 2.41, metN.id: 2.44,
                               atpA.id: 1.87, eno.id: 1.81},
                       'moma': {tpiA.id: 1.62, metN.id: 2.4,
                                atpA.id: 1.40, eno.id: 0.33}}

        # 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)
Esempio n. 2
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)
Esempio n. 3
0
        def test_double_deletion(self):
            """
            """
            from os import name as __name

            if __name == "java":
                warn("cobra.test.flux_analysis.test_double_deletion doesn't yet work with java")
                return
            cobra_model = self.model
            # turn into a double deletion unit test
            the_problem = "return"
            initialize_growth_medium(cobra_model, "LB")
            # Expected growth rates for the salmonella model with deletions in LB medium
            the_loci = ["STM4081", "STM0247", "STM3867", "STM2952"]
            the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id, the_loci)
            growth_dict = {}
            growth_list = [
                [2.41, 2.389, 1.775, 1.81],
                [2.389, 2.437, 1.86, 1.79],
                [1.775, 1.86, 1.87, 1.3269],
                [1.81, 1.79, 1.3269, 1.81],
            ]
            for the_gene, the_rates in zip(the_genes, growth_list):
                growth_dict[the_gene] = dict(zip(the_genes, the_rates))

            the_solution = double_deletion(
                cobra_model, element_list_1=the_genes, element_list_2=the_genes, the_problem=the_problem
            )
            # Potential problem if the data object doesn't have a tolist function
            s_data = the_solution["data"].tolist()
            s_x = the_solution["x"]
            s_y = the_solution["y"]
            for gene_x, rates_x in zip(s_x, s_data):
                for gene_y, the_rate in zip(s_y, rates_x):
                    self.assertAlmostEqual(growth_dict[gene_x][gene_y], the_rate, places=2)
Esempio n. 4
0
    def test_double_deletion(self):
        cobra_model = self.model
        #turn into a double deletion unit test
        initialize_growth_medium(cobra_model, 'LB')
        #Expected growth rates for the salmonella model with deletions in LB medium
        the_loci =  ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = list(map(cobra_model.genes.get_by_id, the_loci))
        growth_dict = {}
        growth_list = [[2.41, 2.389, 1.775, 1.81],
                       [2.389, 2.437, 1.86, 1.79],
                       [1.775, 1.86, 1.87, 1.3269],
                       [1.81, 1.79, 1.3269, 1.81]]
        for the_gene, the_rates in zip(the_genes, growth_list):
            growth_dict[the_gene] = dict(zip(the_genes, the_rates))


        the_solution = double_deletion(cobra_model, element_list_1=the_genes,
                                       element_list_2=the_genes)
        #Potential problem if the data object doesn't have a tolist function
        s_data = the_solution['data'].tolist()
        s_x = the_solution['x']
        s_y = the_solution['y']
        for gene_x, rates_x in zip(s_x, s_data):
            for gene_y, the_rate in zip(s_y, rates_x):
                self.assertAlmostEqual(growth_dict[gene_x][gene_y], the_rate,
                                       places=2)
Esempio n. 5
0
    def test_double_deletion(self):
        cobra_model = self.model
        #turn into a double deletion unit test
        initialize_growth_medium(cobra_model, 'LB')
        #Expected growth rates for the salmonella model with deletions in LB medium
        the_loci = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = list(
            map(cobra_model.genes.get_by_id, the_loci))
        growth_dict = {}
        growth_list = [[2.41, 2.389, 1.775, 1.81], [2.389, 2.437, 1.86, 1.79],
                       [1.775, 1.86, 1.87, 1.3269], [1.81, 1.79, 1.3269, 1.81]]
        for the_gene, the_rates in zip(the_genes, growth_list):
            growth_dict[the_gene] = dict(zip(the_genes, the_rates))

        the_solution = double_deletion(cobra_model,
                                       element_list_1=the_genes,
                                       element_list_2=the_genes)
        #Potential problem if the data object doesn't have a tolist function
        s_data = the_solution['data'].tolist()
        s_x = the_solution['x']
        s_y = the_solution['y']
        for gene_x, rates_x in zip(s_x, s_data):
            for gene_y, the_rate in zip(s_y, rates_x):
                self.assertAlmostEqual(growth_dict[gene_x][gene_y],
                                       the_rate,
                                       places=2)
Esempio n. 6
0
    def test_single_deletion(self):
        cobra_model = self.model
        initialize_growth_medium(cobra_model, 'LB')

        #Expected growth rates for the salmonella model with deletions in LB medium
        the_loci =  ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id, the_loci)
        id_to_name = dict([(x.id, x.name) for x in the_genes])
        growth_dict = {'fba':{tpiA.id:2.41, metN.id:2.44, atpA.id:1.87, eno.id:1.81},
                       'moma':{ tpiA.id:1.62, metN.id:2.4, atpA.id:1.40, eno.id:0.33}}

        #MOMA requires cplex or gurobi
        if get_solver_name(qp=True) is None:
            growth_dict.pop('moma')
        for method, the_growth_rates in growth_dict.items():
            element_list = the_growth_rates.keys()
            results = single_deletion(cobra_model, element_list=element_list,
                                      method=method)
            rates = results[0]
            statuses = results[1]

            for the_gene in element_list:
                self.assertEqual(statuses[the_gene], 'optimal')
                self.assertAlmostEqual(rates[the_gene], the_growth_rates[the_gene],
                                       places=2)
Esempio n. 7
0
    def test_single_gene_deletion(self):
        cobra_model = self.model
        initialize_growth_medium(cobra_model, 'LB')

        # Expected growth rates for the salmonella model with deletions in LB
        the_loci = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id,
                                                the_loci)
        id_to_name = dict([(x.id, x.name) for x in the_genes])
        growth_dict = {'fba': {tpiA.id: 2.41, metN.id: 2.44,
                               atpA.id: 1.87, eno.id: 1.81},
                       'moma': {tpiA.id: 1.62, metN.id: 2.4,
                                atpA.id: 1.40, eno.id: 0.33}}

        # 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)
Esempio n. 8
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.4971939913624155},
            }

            cobra_model = self.model
            the_problem = "return"
            initialize_growth_medium(cobra_model, "LB")
            the_problem = cobra_model.optimize(the_problem=the_problem)
            fva_out = flux_variability_analysis(
                cobra_model, the_problem=the_problem, the_reactions=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)
Esempio n. 9
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)
Esempio n. 10
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)
Esempio n. 11
0
 def setUp(self):
     self.solver = solvers.solver_dict[self.solver_name]
     self.model = create_test_model()
     initialize_growth_medium(self.model, 'MgM')
     self.old_solution = 0.320064
     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])
Esempio n. 12
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])
Esempio n. 13
0
def test_solvers():
    from cPickle import load
    from time import time
    from numpy import round
    from cobra.manipulation import initialize_growth_medium
    from cobra.test import salmonella_pickle
    with open(salmonella_pickle) as in_file:
        cobra_model = load(in_file)
    initialize_growth_medium(cobra_model, 'M9')
    from cobra.manipulation import initialize_growth_medium
    the_growth_rate = 0.48
    solver_dict = {
        'glpk': _optimize_glpk,
        'gurobi': _optimize_gurobi,
        'cplex': _optimize_cplex
    }
    try:
        import glpk
    except:
        solver_dict.pop('glpk')
    try:
        from gurobipy import Model
    except:
        solver_dict.pop('gurobi')
    try:
        from cplex import Cplex
    except:
        solver_dict.pop('cplex')
    for the_solver, the_function in solver_dict.items():
        print 'testing ' + the_solver
        start_time = time()
        the_result = the_function(cobra_model,
                                  the_problem='return',
                                  print_solver_time=True)
        the_problem = the_result['the_problem']
        the_solution = the_result['the_solution']
        print '%s cold start: %f' % (the_solver, time() - start_time)
        if round(the_solution.f, 2) != the_growth_rate:
            print 'Simulation failed %f to match expectation %f' % (
                the_solution.f, the_growth_rate)
        the_solution = the_function(cobra_model,
                                    the_problem=the_problem,
                                    print_solver_time=True)
        the_problem = the_result['the_problem']
        the_solution = the_result['the_solution']
        print '%s hot start: %f' % (the_solver, time() - start_time)
        if round(the_solution.f, 2) != the_growth_rate:
            print 'Simulation failed %f to match expectation %f' % (
                the_solution.f, the_growth_rate)
Esempio n. 14
0
        def test_single_deletion(self):

            cobra_model = self.model
            initialize_growth_medium(cobra_model, "LB")

            # Expected growth rates for the salmonella model with deletions in LB medium
            the_loci = ["STM4081", "STM0247", "STM3867", "STM2952"]
            the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id, the_loci)
            id_to_name = dict([(x.id, x.name) for x in the_genes])
            growth_dict = {"fba": {tpiA.id: 2.41, metN.id: 2.44, atpA.id: 1.87, eno.id: 1.81}}

            for method, the_growth_rates in growth_dict.items():
                element_list = the_growth_rates.keys()
                rates, statuses, problems = single_deletion(cobra_model, element_list=element_list, method=method)

                for the_gene in element_list:
                    self.assertEqual(statuses[the_gene], "optimal")
                    self.assertAlmostEqual(rates[the_gene], the_growth_rates[the_gene], places=2)
Esempio n. 15
0
def test_solvers():
    from cPickle import load
    from time import time
    from numpy import round
    from cobra.manipulation import initialize_growth_medium
    from cobra.test import salmonella_pickle
    with open(salmonella_pickle) as in_file:
        cobra_model = load(in_file)
    initialize_growth_medium(cobra_model, 'M9')
    from cobra.manipulation import initialize_growth_medium
    the_growth_rate = 0.48
    solver_dict = {'glpk': _optimize_glpk,
                   'gurobi': _optimize_gurobi,
                   'cplex': _optimize_cplex}
    try:
        import glpk
    except:
        solver_dict.pop('glpk')
    try:
        from gurobipy import Model
    except:
        solver_dict.pop('gurobi')
    try:
        from cplex import Cplex
    except:
        solver_dict.pop('cplex')
    for the_solver, the_function in solver_dict.items():
        print 'testing ' + the_solver
        start_time = time()
        the_result = the_function(cobra_model, the_problem='return', print_solver_time=True)
        the_problem = the_result['the_problem']
        the_solution = the_result['the_solution']
        print '%s cold start: %f'%(the_solver, time() - start_time)
        if round(the_solution.f, 2) != the_growth_rate:
            print 'Simulation failed %f to match expectation %f'%(the_solution.f,
                                                                  the_growth_rate)
        the_solution = the_function(cobra_model, the_problem=the_problem, print_solver_time=True)
        the_problem = the_result['the_problem']
        the_solution = the_result['the_solution']
        print '%s hot start: %f'%(the_solver, time() - start_time)
        if round(the_solution.f, 2) != the_growth_rate:
            print 'Simulation failed %f to match expectation %f'%(the_solution.f,
                                                                  the_growth_rate)                                                                 
Esempio n. 16
0
 def test_double_gene_deletion(self):
     cobra_model = self.model
     # turn into a double deletion unit test
     initialize_growth_medium(cobra_model, 'LB')
     # Expected growth rates for the salmonella model with deletions in LB
     genes = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
     growth_list = [[2.414, 2.390, 1.775, 1.810],
                    [2.390, 2.437, 1.863, 1.795],
                    [1.775, 1.863, 1.875, 1.327],
                    [1.810, 1.795, 1.327, 1.813]]
     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)
     self.assertEqual(solution["x"], genes[:-1])
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list[:-1], solution["data"])
Esempio n. 17
0
 def test_double_gene_deletion(self):
     cobra_model = self.model
     # turn into a double deletion unit test
     initialize_growth_medium(cobra_model, 'LB')
     # Expected growth rates for the salmonella model with deletions in LB
     genes = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
     growth_list = [[2.414, 2.390, 1.775, 1.810],
                    [2.390, 2.437, 1.863, 1.795],
                    [1.775, 1.863, 1.875, 1.327],
                    [1.810, 1.795, 1.327, 1.813]]
     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)
     self.assertEqual(solution["x"], genes[:-1])
     self.assertEqual(solution["y"], genes)
     self.compare_matrices(growth_list[:-1], solution["data"])
Esempio n. 18
0
    def test_single_deletion(self):
        cobra_model = self.model
        initialize_growth_medium(cobra_model, 'LB')

        #Expected growth rates for the salmonella model with deletions in LB medium
        the_loci = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
        the_genes = tpiA, metN, atpA, eno = map(cobra_model.genes.get_by_id,
                                                the_loci)
        id_to_name = dict([(x.id, x.name) for x in the_genes])
        growth_dict = {
            'fba': {
                tpiA.id: 2.41,
                metN.id: 2.44,
                atpA.id: 1.87,
                eno.id: 1.81
            },
            'moma': {
                tpiA.id: 1.62,
                metN.id: 2.4,
                atpA.id: 1.40,
                eno.id: 0.33
            }
        }

        #MOMA requires cplex or gurobi
        if get_solver_name(qp=True) is None:
            growth_dict.pop('moma')
        for method, the_growth_rates in growth_dict.items():
            element_list = the_growth_rates.keys()
            results = single_deletion(cobra_model,
                                      element_list=element_list,
                                      method=method)
            rates = results[0]
            statuses = results[1]

            for the_gene in element_list:
                self.assertEqual(statuses[the_gene], 'optimal')
                self.assertAlmostEqual(rates[the_gene],
                                       the_growth_rates[the_gene],
                                       places=2)
Esempio n. 19
0
def create_test_model(test_pickle=salmonella_pickle):
    """Returns a cobra model for testing.  The default model is the
    version of the Salmonella enterica Typhimurium LT2 model published in
    Thiele et al. 2011 BMC Sys Bio 5:8, which has some updated metabolite
    KEGG id data for Schmidt et al. 2013 Bioinformatics

    test_pickle: The complete file name of a pickled cobra.Model or SBML XML
    file to be read.  We currently provide Salmonella enterica Typhimurium
    and Escherichia coli core models whose paths are stored in cobra.test.salmonella_pickle
    and cobra.test.ecoli_pickle, respectively.

    """
    from os import name as __name
    try:
        from cPickle import load
    except:
        from pickle import load

    with open(test_pickle, "rb") as infile:
        model = load(infile)
    initialize_growth_medium(model, 'LB')

    return model
Esempio n. 20
0
def create_test_model(test_pickle=salmonella_pickle):
    """Returns a cobra model for testing.  The default model is the
    version of the Salmonella enterica Typhimurium LT2 model published in
    Thiele et al. 2011 BMC Sys Bio 5:8, which has some updated metabolite
    KEGG id data for Schmidt et al. 2013 Bioinformatics

    test_pickle: The complete file name of a pickled cobra.Model or SBML XML
    file to be read.  We currently provide Salmonella enterica Typhimurium
    and Escherichia coli core models whose paths are stored in cobra.test.salmonella_pickle
    and cobra.test.ecoli_pickle, respectively.

    """
    from os import name as __name
    try:
        from cPickle import load
    except:
        from pickle import load

    with open(test_pickle, "rb") as infile:
        model = load(infile)
    initialize_growth_medium(model, 'LB')

    return model
Esempio n. 21
0
    matlab_struct.description = cobra_model.description
    return(matlab_struct)



if __name__ == '__main__':
    from cPickle import load
    from time import time
    from numpy import round
    from cobra.manipulation import initialize_growth_medium
    try:
        matlab.changeCobraSolver('glpk','LP')
    except AttributeError:
        raise Exception('Could not run matlab function changeCobraSolver.  Is the ' +\
                        'COBRA Toolbox in your MATLAB path?')
    test_directory = '../test/data/'
    with open(test_directory + 'salmonella.pickle') as in_file:
        cobra_model = load(in_file)
    initialize_growth_medium(cobra_model, 'LPM')
    py_cobra_solution = repr(cobra_model.solution.f)
    matlab_struct = cobra_model_object_to_cobra_matlab_struct(cobra_model)

    matlab_result = matlab.optimizeCbModel(matlab_struct)
    matlab_solution = repr(float(matlab_result.f))
    if py_cobra_solution[:4] == matlab_solution[:4]:
        print 'SUCCESS: growth rate match between pyCOBRA and COBRA Toolbox: %s ~ %s'%(py_cobra_solution,
                                                                                       matlab_solution)
    else:
        print 'FAILURE: pyCOBRA and COBRA Toolbox do not match: %s !~ %s'%(py_cobra_solution,
                                                                                       matlab_solution)
Esempio n. 22
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)
Esempio n. 23
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])
            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)
Esempio n. 24
0
def assess_medium_component_essentiality(cobra_model, the_components=None,
                                         the_medium=None,
                                         medium_compartment='e', solver='glpk',
                                         the_condition=None, method='fba'):
    """Determines which components in an in silico medium are essential for
    growth in the context of the remaining components.

    cobra_model: A Model object.

    the_components: None or a list of external boundary reactions that will be
    sequentially disabled.

    the_medium: Is None, a string, or a dictionary.  If a string then the
    initialize_growth_medium function expects that the_model has an attribute
    dictionary called media_compositions, which is a dictionary of dictionaries
    for various medium compositions.  Where a medium composition is a
    dictionary of external boundary reaction ids for the medium components and
    the external boundary fluxes for each medium component.

    medium_compartment: the compartment in which the boundary reactions
    supplying the medium components exist

    NOTE: that these fluxes must be negative because the convention is
    backwards means something is feed into the system.

    solver: 'glpk', 'gurobi', or 'cplex'

    returns: essentiality_dict:  A dictionary providing the maximum growth rate
    accessible when the respective component is removed from the medium.

    """
    if method.lower() == 'moma':
        wt_model = cobra_model.copy()
    cobra_model = cobra_model.copy()

    if isinstance(the_medium, str):
        try:
            the_medium = cobra_model.media_compositions[the_medium]
        except:
            raise Exception(
                the_medium + " is not in cobra_model.media_compositions")
    if the_medium is not None:
        initialize_growth_medium(cobra_model, the_medium, medium_compartment)
        if the_components is None:
            the_components = the_medium.keys()
    if not the_components:
        raise Exception("You need to specify the_components or the_medium")
    essentiality_dict = {}
    for the_component in the_components:
        the_reaction = cobra_model.reactions.get_by_id(the_component)
        original_lower_bound = float(the_reaction.lower_bound)
        the_reaction.lower_bound = 0.
        if method.lower() == 'fba':
            cobra_model.optimize(solver=solver)
            objective_value = cobra_model.solution.f
        elif method.lower() == 'moma':
            objective_value = moma(wt_model, cobra_model, solver=solver)[
                'objective_value']
        essentiality_dict[the_component] = objective_value
        the_reaction.lower_bound = original_lower_bound

    return(essentiality_dict)
Esempio n. 25
0
fp = open(data_dir + "metabolomics_dict.pickle", "rb")
metabolomics_dict = pickle.load(fp)
fp.close()

# Make models not informed by omics first by initializing the media
import pickle
fp = open(data_dir + "salmonella_gem.pickle", "rb")
STM = pickle.load(fp)
fp.close()

if cobra_version == '0.2.0':
    STM_LB = deepcopy(STM)
else:
    STM_LB = STM.copy()
initialize_growth_medium(STM_LB, 'LB')

## This is how to set up LPM
# if cobra_version == '0.2.0':
#     STM_LPM = deepcopy(STM)
# else:
#     STM_LPM = STM.copy()
# initialize_growth_medium(STM_LPM, 'LPM')
## Protons should only have a net positive diffusion 
## from the extracellular space into the perplasm in LPM condition
# STM_LPM.reactions.get_by_id('Htex').lower_bound = 0

# Required numeric tolerances were 
# determined previously from FVA 
# on model reactions
selected_tolerance = 1E-8
Esempio n. 26
0
def assess_medium_component_essentiality(
    cobra_model,
    the_components=None,
    the_medium=None,
    solver="glpk",
    the_problem="return",
    the_condition=None,
    method="fba",
):
    """Deterimes which components in an in silico medium are essential for growth in the
    context of the remaining components.

    cobra_model: A Model object.

    the_components: None or a list of exchange reactions that will be sequentially
    disabled.

    the_medium: Is None, a string, or a dictionary.  If a string then the
    initialize_growth_medium function expects that the_model has an
    attribute dictionary called media_compositions, which is a dictionary of
    dictionaries for various medium compositions.  Where a medium
    composition is a dictionary of exchange reaction ids for the medium
    components and the exchange fluxes for each medium component; note that
    these fluxes must be negative because they are being exchanged into the
    system.

    solver: 'glpk', 'gurobi', or 'cplex'

    the_problem: Is None, 'return', or an LP model object for the solver.
       
    the_condition: None or a String that provides a description of the medium
    simulation

    returns:
     essentiality_dict:  A dictionary providing the minimum lower bounds for
     each component of the growth medium.

    """
    warn("assess_medium_component_essentiality needs to be updated to " + "deal with new style reactions")
    from cobra.core.ArrayBasedModel import ArrayBasedModel

    if method.lower() == "moma":
        wt_model = ArrayBasedModel(cobra_model.copy())
    if isinstance(cobra_model, tuple):
        if len(cobra_model) == 3:
            the_condition = cobra_model[2]
        the_components = cobra_model[1]
        cobra_model = cobra_model[0]
    cobra_model = ArrayBasedModel(cobra_model.copy())
    if not the_components:
        if the_medium:
            if hasattr(the_medium, "keys") or (
                hasattr(cobra_model, "media_compositions") and the_medium in cobra_model.media_compositions
            ):
                initialize_growth_medium(cobra_model, the_medium)
                the_components = cobra_model.media_compositions[the_medium]
            else:
                raise Exception("%s is not a dict and not in the model's media list" % the_medium)
        else:
            raise Exception("You need to specify the_components or the_medium")
    essentiality_dict = {}
    for the_component in the_components:
        component_index = cobra_model.reactions.index(the_component)
        tmp_lb = float(cobra_model.lower_bounds[component_index])
        cobra_model.reactions[component_index].lower_bound = cobra_model.lower_bounds[component_index] = 0
        if method.lower() == "fba":
            cobra_model.optimize(solver=solver, the_problem=the_problem)
            objective_value = cobra_model.solution.f
        elif method.lower() == "moma":
            objective_value = moma(wt_model, cobra_model, solver=solver)["objective_value"]
        essentiality_dict[the_component] = objective_value
        cobra_model.reactions[component_index].lower_bound = cobra_model.lower_bounds[component_index] = tmp_lb
    if the_condition:
        essentiality_dict["the_condition"] = the_condition
    return essentiality_dict
Esempio n. 27
0
def deletion_analysis(
    cobra_model,
    the_medium=None,
    deletion_type="single",
    work_directory=None,
    growth_cutoff=0.001,
    the_problem="return",
    n_processes=6,
    element_type="gene",
    solver="glpk",
    error_reporting=None,
    method="fba",
    element_list=None,
):
    """Performs single and/or double deletion analysis on all the genes in the model.  Provides
    an interface to parallelize the deletion studies.

    cobra_model: A Model object.

    the_medium: Is None, a string, or a dictionary.  If a string then the
    initialize_growth_medium function expects that cobra_model has an
    attribute dictionary called media_compositions, which is a dictionary of
    dictionaries for various medium compositions.  Where a medium
    composition is a dictionary of exchange reaction ids for the medium
    components and the exchange fluxes for each medium component; note that
    these fluxes must be negative because they are being exchanged into the
    system.

    deletion_type: 'single', 'double', or 'double-only'

    work_directory: None or String indicating where to save the output from the simulations.

    growth_cutoff: Float.  Indiates the minimum growth rate that is considered viable.

    the_problem: Is None, 'return', or an LP model object for the solver.
       
    element_type: 'gene' or 'reaction'

    solver: 'glpk', 'gurobi', or 'cplex'

    n_processes: number of parallel processes to break the double deletion simulations
    into.

    error_reporting: None or True

    element_list: None or a list of genes to delete from the model.

    Returns: Nothing.  However, the script will add attributes single_deletion_* and
    double_deletion_* to cobra_model containing the simulation results.

    """
    if element_type == "reaction":
        warn("deletion_analysis is not perfect for element_type = 'reaction'")
    # When using ppmap, it's easier to feed in the parameters as a list,
    # if the defaults need to be changed
    if isinstance(cobra_model, list):
        tmp_model = cobra_model
        cobra_model = tmp_model[0]
        if len(tmp_model) > 1:
            the_medium = tmp_model[1]
            if len(tmp_model) > 2:
                deletion_type = tmp_model[2]
                if len(tmp_model) > 3:
                    work_directory = tmp_model[3]
                    if len(tmp_model) > 4:
                        growth_cutoff = tmp_model[4]
    if the_medium is not None:
        initialize_growth_medium(cobra_model, the_medium)
    the_problem = cobra_model.optimize(the_problem=the_problem, solver=solver)
    # Store the basal model for the simulations
    if element_list is None:
        element_list = getattr(cobra_model, element_type + "s")
    if deletion_type != "double_only":
        cobra_model.single_deletion_growth_wt = cobra_model.solution.f
        growth_rate_dict, growth_solution_status_dict, problem_dict = single_deletion(
            deepcopy(cobra_model),
            element_list=element_list,
            the_problem=the_problem,
            element_type=element_type,
            solver=solver,
            error_reporting=error_reporting,
            method=method,
        )
        del problem_dict
        cobra_model.single_deletion_growth_dict = growth_rate_dict
        cobra_model.single_deletion_solution_status_dict = growth_solution_status_dict
        setattr(cobra_model, "single_deletion_%ss" % element_type, deepcopy(growth_rate_dict.keys()))
        cobra_model.single_deletion_lethal = [x for x in growth_rate_dict.keys() if growth_rate_dict[x] < growth_cutoff]

        cobra_model.single_deletion_growth_medium = the_medium
        cobra_model.single_deletion_nonlethal = list(
            set(growth_rate_dict.keys()).difference(cobra_model.single_deletion_lethal)
        )
        if work_directory is not None:
            if not path.lexists(work_directory):
                mkdir(work_directory)
            with open(work_directory + the_medium + "_single_" + cobra_model.description, "w") as out_file:
                dump(cobra_model, out_file)

    if deletion_type == "double" or deletion_type == "double_only":
        # It appears that the glpk interface no longer works will with sending
        # a glpk.LPX object through ppmap, so just set the basis to return
        if the_problem:
            the_problem = "return"
        cobra_model.double_deletion_growth_medium = the_medium
        cobra_model.double_deletion_growth_wt = cobra_model.solution.f
        if not __parallel_mode_available:
            if n_processes > 0:
                print "Couldn't import ppmap from cobra.external is parallel python installed?"
                return

        else:
            cobra_model = double_deletion_parallel(
                deepcopy(cobra_model),
                genes_of_interest=element_list,
                the_problem=the_problem,
                n_processes=n_processes,
                element_type=element_type,
                solver=solver,
                error_reporting=error_reporting,
                method=method,
            )
        # This indicates the genes that were run through double deletion but
        # the x and y lists specify the order
        setattr(cobra_model, "double_deletion_%ss" % element_type, deepcopy(cobra_model.genes))
        if work_directory is not None:
            with open(work_directory + the_medium + "_double_" + cobra_model.description, "w") as out_file:
                dump(cobra_model, out_file)
    return cobra_model
Esempio n. 28
0
# This example demonstrates a single gene deletion simulation
from time import time

from cobra.flux_analysis.single_deletion import single_deletion
from cobra.manipulation import initialize_growth_medium
from cobra.test import create_test_model, salmonella_pickle  # test filename

cobra_model = create_test_model(salmonella_pickle)
initialize_growth_medium(cobra_model, 'LB')

target_genes = ['STM4081', 'STM0247', 'STM3867', 'STM2952']
# Expected growth rates for the salmonella model after a deletions in LB medium
expected_growth_rates = {
    "STM4081": 2.41,
    "STM0247": 2.43,
    "STM3867": 1.87,
    "STM2952": 1.81}

start_time = time()  # start timer

# Perform deletions for all genes in the list
rates, statuses = single_deletion(cobra_model, target_genes)

total_time = time() - start_time  # stop timer

# print out results
passed_string = 'PASSED: %s simulation (%1.3f) ~= expectation (%1.2f)'
failed_string = 'FAILED: %s simulation (%1.3f) != expectation (%1.2f)'
for gene_locus, rate in rates.items():
    # get gene name from gene locus (i.e. STM4081 -> tpiA)
    name = cobra_model.genes.get_by_id(gene_locus).name
Esempio n. 29
0
def double_gene_deletion_parallel(
    cobra_model,
    n_processes=4,
    genes_of_interest=None,
    method="fba",
    the_medium=None,
    the_problem="return",
    solver="glpk",
    error_reporting=None,
):
    """Provides a wrapper to run the double_deletion function on
    multicore systems.

    cobra_model: a Model object

    n_processes: is the number of parallel processes to start

    genes_of_interest: Is None, a list of genes, or a list of two lists of
    genes.  If None then double_deletion is run on all genes in
    cobra_model.genes.  If a list of genes then double_deletion is run for all
    combinations of genes in double_deletion.  If a list of of two lists of
    genes then double_deletion is run for each member of one list vs. each
    member of the second list.

    method: 'fba' or 'moma' to run flux balance analysis or minimization
    of metabolic adjustments.

    the_medium: Is None, a string, or a dictionary.  If a string then the
    initialize_growth_medium function expects that cobra_model has an
    attribute dictionary called media_compositions, which is a dictionary of
    dictionaries for various medium compositions.  Where a medium
    composition is a dictionary of exchange reaction ids for the medium
    components and the exchange fluxes for each medium component; note that
    these fluxes must be negative because they are being exchanged into the
    system.

    the_problem: Is None or 'reuse'

    solver: 'glpk', 'gurobi', or 'cplex'.

    error_reporting: None or True

    Adds the following attributes to the cobra_model:
          double_deletion_growth_rate: A numpy array of the simulation results
          double_deletion_genes_x: A list of the genes for the x dimension of
          double_deletion_growth_rate.
          double_deletion_genes_y: A list of the genes for the y dimension of
          double_deletion_growth_rate.

    """
    if not __parallel_mode_available:
        print "Parallel mode not available is Parallel Python installed"
        return
    if the_problem:
        the_problem = "return"
    if the_medium:
        initialize_growth_medium(cobra_model, the_medium)
    if not genes_of_interest:
        # If no genes_of_interest are specified then assume we want to
        # compare all genetic interactions in the network
        all_genes = [x.id for x in cobra_model.genes]
        second_gene_list = all_genes
    elif isinstance(genes_of_interest[0], str):
        # If genes_of_interest is a list then assume the list be scanned
        # for interactions with all genes in the network
        all_genes = genes_of_interest
        second_gene_list = all_genes
    elif hasattr(genes_of_interest[0], "id"):
        # Make sure we're dealing with strings instead of objects because we
        # haven't audited this for thread safety
        second_gene_list = all_genes = [x.id for x in genes_of_interest]
    elif hasattr(genes_of_interest[0], "__iter__"):
        all_genes = genes_of_interest[0]
        if len(genes_of_interest) == 2:
            second_gene_list = genes_of_interest[1]
        else:
            second_gene_list = all_genes
    # Get basic numbers to guide how the problem should be divided for parallel execution.
    total_gene_count = len(all_genes)
    division_count = total_gene_count / n_processes
    the_rows = []

    for i in range(n_processes - 1):
        the_rows.append(
            {
                "cobra_model": cobra_model.copy(),
                "method": method,
                "gene_list_1": deepcopy(all_genes[i * division_count : division_count * (i + 1)]),
                "gene_list_2": deepcopy(second_gene_list),
                "the_problem": the_problem,
                "solver": solver,
                "error_reporting": error_reporting,
            }
        )
    the_rows.append(
        {
            "cobra_model": cobra_model.copy(),
            "method": method,
            "gene_list_1": deepcopy(all_genes[(n_processes - 1) * division_count :]),
            "gene_list_2": deepcopy(second_gene_list),
            "the_problem": the_problem,
            "solver": solver,
            "error_reporting": error_reporting,
        }
    )

    tmp_pp = list(ppmap(n_processes, double_gene_deletion, the_rows))
    gene_list_x = tmp_pp[0]["x"]
    gene_list_y = tmp_pp[0]["y"]
    double_deletion_data = tmp_pp[0]["data"]
    for the_result in tmp_pp[1:]:
        gene_list_x += the_result["x"]
        double_deletion_data = vstack((double_deletion_data, the_result["data"]))

    cobra_model.double_deletion_growth_rate = double_deletion_data
    cobra_model.double_deletion_genes_x = gene_list_x
    cobra_model.double_deletion_genes_y = gene_list_y
    return cobra_model