Beispiel #1
0
 def testGPR(self):
     model = self.model_class()
     reaction = Reaction("test")
     # set a gpr to  reaction not in a model
     reaction.gene_reaction_rule = "(g1 or g2) and g3"
     self.assertEqual(reaction.gene_reaction_rule, "(g1 or g2) and g3")
     self.assertEqual(len(reaction.genes), 3)
     # adding reaction with a GPR propagates to the model
     model.add_reaction(reaction)
     self.assertEqual(len(model.genes), 3)
     # ensure the gene objects are the same in the model and reaction
     reaction_gene = list(reaction.genes)[0]
     model_gene = model.genes.get_by_id(reaction_gene.id)
     self.assertIs(reaction_gene, model_gene)
     # test ability to handle uppercase AND/OR
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         reaction.gene_reaction_rule = "(b1 AND b2) OR (b3 and b4)"
     self.assertEqual(reaction.gene_reaction_rule,
                      "(b1 and b2) or (b3 and b4)")
     self.assertEqual(len(reaction.genes), 4)
     # ensure regular expressions correctly extract genes from malformed
     # GPR string
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         reaction.gene_reaction_rule = "(a1 or a2"
         self.assertEqual(len(reaction.genes), 2)
         reaction.gene_reaction_rule = "(forT or "
         self.assertEqual(len(reaction.genes), 1)
Beispiel #2
0
    def _replace_adapted_metabolites(self, reaction):
        """
        Replace adapted metabolites by model metabolites

        Parameters
        ----------
        reaction: cameo.core.reaction.Reaction

        Returns
        -------
        cameo.core.reaction.Reaction
        """
        stoichiometry = {}

        for metabolite, coefficient in six.iteritems(reaction.metabolites):
            found = False
            for adapter in self.adapters:
                if metabolite == adapter.products[0]:
                    metabolite = adapter.reactants[0]
                    found = False
                    break
            if not found:
                metabolite = metabolite

            stoichiometry[metabolite] = coefficient

        reaction = Reaction(id=reaction.id,
                            name=reaction.name,
                            lower_bound=reaction.lower_bound,
                            upper_bound=reaction.upper_bound)
        reaction.add_metabolites(stoichiometry)

        return reaction
Beispiel #3
0
 def test_iadd(self):
     model = self.model
     PGI = model.reactions.PGI
     EX_h2o = model.reactions.EX_h2o_e
     original_PGI_gpr = PGI.gene_reaction_rule
     PGI += EX_h2o
     self.assertEqual(PGI.gene_reaction_rule, original_PGI_gpr)
     self.assertEqual(PGI.metabolites[model.metabolites.h2o_e], -1.0)
     # original should not have changed
     self.assertEqual(EX_h2o.gene_reaction_rule, '')
     self.assertEqual(EX_h2o.metabolites[model.metabolites.h2o_e], -1.0)
     # what about adding a reaction not in the model
     new_reaction = Reaction("test")
     new_reaction.add_metabolites({Metabolite("A"): -1, Metabolite("B"): 1})
     PGI += new_reaction
     self.assertEqual(PGI.gene_reaction_rule, original_PGI_gpr)
     self.assertEqual(len(PGI.gene_reaction_rule), 5)
     # and vice versa
     new_reaction += PGI
     self.assertEqual(len(new_reaction.metabolites), 5)  # not 7
     self.assertEqual(len(new_reaction.genes), 1)
     self.assertEqual(new_reaction.gene_reaction_rule, original_PGI_gpr)
     # what about combining 2 gpr's
     model.reactions.ACKr += model.reactions.ACONTa
     self.assertEqual(model.reactions.ACKr.gene_reaction_rule,
                      "(b2296 or b3115 or b1849) and (b0118 or b1276)")
     self.assertEqual(len(model.reactions.ACKr.genes), 5)
Beispiel #4
0
    def test_add_metabolite(self):
        model = self.model
        reaction = model.reactions.get_by_id("PGI")
        reaction.add_metabolites({model.metabolites[0]: 1})
        self.assertIn(model.metabolites[0], reaction._metabolites)
        fake_metabolite = Metabolite("fake")
        reaction.add_metabolites({fake_metabolite: 1})
        self.assertIn(fake_metabolite, reaction._metabolites)
        self.assertTrue(model.metabolites.has_id("fake"))
        self.assertIs(model.metabolites.get_by_id("fake"), fake_metabolite)

        # test adding by string
        reaction.add_metabolites({"g6p_c": -1})  # already in reaction
        self.assertTrue(
            reaction._metabolites[model.metabolites.get_by_id("g6p_c")], -2)
        reaction.add_metabolites({"h_c": 1})  # not currently in reaction
        self.assertTrue(
            reaction._metabolites[model.metabolites.get_by_id("h_c")], 1)
        with self.assertRaises(KeyError):
            reaction.add_metabolites({"missing": 1})

        # test adding to a new Reaction
        reaction = Reaction("test")
        self.assertEqual(len(reaction._metabolites), 0)
        reaction.add_metabolites({Metabolite("test_met"): -1})
        self.assertEqual(len(reaction._metabolites), 1)
Beispiel #5
0
def parsimonious_fba(model, db):
    '''
    :param model: Takes in a model in SBML format and converts it into a cobrapy model
    :param db: Takes in a database of reactions to be added to the model that will make
    it feasible to solve
    :return: Will run a parsimonious FBA on the model which reduces the sum of total fluxes through the model.
     Then the sources and sinks of ATP in the reaction will be printed so that we can analyze where ATP comes from
     and where it goes in this model as that will give us insight into the mechanism by which the GrowMatch algorithm has
     added a reaction that allows the model to produce methanol.
    '''
    model = create_cobra_model_from_sbml_file(model)
    rxn_list = pickle.load(open(db, 'rb'))
    # For loop that adds the reactions in a given run present in the dictionary to the model using regular expressions
    for run in rxn_list.keys():
        model_test = model.copy()
        fva_list = [model_test.reactions.ATPS]
        for rxn in rxn_list[run]:
            addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0)
            formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0)
            rxn = Reaction(addID)
            model_test.add_reaction(rxn)
            rxn.reaction = formula
        # Creates a test model to run ParsFBA on and then prints out the run as well as the sources/sinks of ATP in the
        # reactions
        model_fba_test = model_test.copy()
        flux_analysis.optimize_minimal_flux(model_fba_test)
        # fluxes = findInsAndOuts(model_fba_test)
        # sorted_outs = fluxes[0]
        # sorted_ins = fluxes[1]
        print run
        model_fba_test.metabolites.get_by_id('cpd00002_c0').summary()
Beispiel #6
0
 def test_demand(self, model):
     dm = Reaction("demand")
     model.add_reaction(dm)
     dm.build_reaction_from_string("atp_c ->")
     dm = model.demands
     assert len(dm) == 1
     assert "demand" in [r.id for r in dm]
Beispiel #7
0
    def _add_target_constraints(self, c):
        """Add the target constraints to the dual model"""
        targets = self._target_constraints

        w_reactions = []
        for i, target in enumerate(targets):
            assert isinstance(target, optlang.interface.Constraint)
            if not target.is_Linear:
                raise ValueError("Target constraints must be linear.")
            if (target.lb is None and target.ub is None) or (target.lb is not None and target.ub is not None):
                raise ValueError("Target constraints must be one-sided inequalities.")
            coefficients_dict = target.expression.as_coefficients_dict()
            w_reac = Reaction("w_" + str(i))
            w_reac.lower_bound = c
            if target.ub is not None:
                coefficients = {
                    self._dual_model.metabolites.get_by_id(var.name): coef for var, coef in coefficients_dict.items()
                    if var.name in self._dual_model.metabolites}
            elif target.lb is not None:
                coefficients = {
                    self._dual_model.metabolites.get_by_id(var.name): -coef for var, coef in coefficients_dict.items()
                    if var.name in self._dual_model.metabolites}
            w_reac.add_metabolites(coefficients)
            w_reactions.append(w_reac)
        self._dual_model.add_reactions(w_reactions)

        return None
def add_exchange_reaction(met_id,model,lb=0,ub=1000):
    met=model.metabolites.get_by_id(met_id)
    reaction = Reaction(met.id)
    reaction.lower_bound=lb
    reaction.upper_bound=ub
    reaction.add_metabolites({met: -1.0})
    model.add_reaction(reaction)
def cad_reaction(core_model):
    reaction = Reaction(id="CAD", name="Cis-Aconitate Decarboxylase")
    acon = core_model.metabolites.acon_DASH_C_c
    co2_c = core_model.metabolites.co2_c
    ita_c = Metabolite(id="ita_c", name="Itaconate", compartment="c")
    reaction.add_metabolites({acon: -1, co2_c: 1, ita_c: 1})
    return reaction
Beispiel #10
0
def categorize_reactions(model, db, category):
    fva_result_dict = {}
    # Wide range of ATP Synthase flux values can be positive or negative
    category_1_dict = {}
    # ATP Synthase flux can only be negative
    category_2_dict = {}
    # ATP Synthase flux can only be positive
    category_3_dict = {}
    model = create_cobra_model_from_sbml_file(model)
    rxn_list = pickle.load(open(db, 'rb'))
    for run in rxn_list.keys():
        model_test = model.copy()
        fva_list = [model_test.reactions.ATPS]
        for rxn in rxn_list[run]:
            addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0)
            formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0)
            rxn = Reaction(addID)
            model_test.add_reaction(rxn)
            rxn.reaction = formula
            fva_list.append(rxn)
        fva_result = flux_analysis.flux_variability_analysis(model_test, fva_list)
        fva_result_dict[run] = fva_result
    for run in fva_result_dict:
        if fva_result_dict[run]['ATPS']['maximum'] > 0 and fva_result_dict[run]['ATPS']['minimum'] < 0:
            category_1_dict[run] = fva_result_dict[run]
        elif fva_result_dict[run]['ATPS']['maximum'] > 0:
            category_2_dict[run] = fva_result_dict[run]
        else:
            category_3_dict[run] = fva_result_dict[run]
    if category == 1:
        return category_1_dict.keys()
    elif category == 2:
        return category_2_dict.keys()
    else:
        return category_3_dict.keys()
Beispiel #11
0
 def test_add_reaction(self):
     old_reaction_count = len(self.model.reactions)
     old_metabolite_count = len(self.model.metabolites)
     dummy_metabolite_1 = Metabolite("test_foo_1")
     dummy_metabolite_2 = Metabolite("test_foo_2")
     actual_metabolite = self.model.metabolites[0]
     copy_metabolite = self.model.metabolites[1].copy()
     dummy_reaction = Reaction("test_foo_reaction")
     dummy_reaction.add_metabolites({dummy_metabolite_1: -1,
                                     dummy_metabolite_2: 1,
                                     copy_metabolite: -2,
                                     actual_metabolite: 1})
     self.model.add_reaction(dummy_reaction)
     self.assertEqual(self.model.reactions.get_by_id(dummy_reaction.id),
                      dummy_reaction)
     for x in [dummy_metabolite_1, dummy_metabolite_2]:
         self.assertEqual(self.model.metabolites.get_by_id(x.id), x)
     # should have added 1 reaction and 2 metabolites
     self.assertEqual(len(self.model.reactions), old_reaction_count + 1)
     self.assertEqual(len(self.model.metabolites), old_metabolite_count + 2)
     # tests on theadded reaction
     reaction_in_model = self.model.reactions.get_by_id(dummy_reaction.id)
     self.assertIs(type(reaction_in_model), Reaction)
     self.assertIs(reaction_in_model, dummy_reaction)
     self.assertEqual(len(reaction_in_model._metabolites), 4)
     for i in reaction_in_model._metabolites:
         self.assertEqual(type(i), Metabolite)
     # tests on the added metabolites
     met1_in_model = self.model.metabolites.get_by_id(dummy_metabolite_1.id)
     self.assertIs(met1_in_model, dummy_metabolite_1)
     #assertIsNot is not in python 2.6
     copy_in_model = self.model.metabolites.get_by_id(copy_metabolite.id)
     self.assertTrue(copy_metabolite is not copy_in_model)
     self.assertIs(type(copy_in_model), Metabolite)
     self.assertTrue(dummy_reaction in actual_metabolite._reaction)
Beispiel #12
0
 def test_find_dead_end_reactions(self, core_model):
     assert len(structural.find_dead_end_reactions(core_model)) == 0
     met1 = Metabolite("fake_metabolite_1")
     met2 = Metabolite("fake_metabolite_2")
     reac = Reaction("fake_reac")
     reac.add_metabolites({met1: -1, met2: 1})
     core_model.add_reaction(reac)
     assert structural.find_dead_end_reactions(core_model) == {reac}
Beispiel #13
0
 def test_sink(self, model):
     sn = Reaction("sink")
     model.add_reaction(sn)
     sn.build_reaction_from_string("atp_c <->")
     sn.bounds = -1000, 1000
     sn = model.sinks
     assert len(sn) == 1
     assert "sink" in [r.id for r in sn]
Beispiel #14
0
def tiny_toy_model():
    tiny = Model("Toy Model")
    m1 = Metabolite("M1")
    d1 = Reaction("ex1")
    d1.add_metabolites({m1: -1})
    d1.upper_bound = 0
    d1.lower_bound = -1000
    tiny.add_reactions([d1])
    tiny.objective = 'ex1'
    return tiny
Beispiel #15
0
def create_minimal_fux_model(metabolic_model,fraction_of_optimum_objective=0.8, fraction_of_flux_minimum=2,boundaries_precision=0.001,label_model=None,metabolite_list_file_name=None):
    model=copy.deepcopy(metabolic_model)
    if len(model.objective)>1:
      raise ValueError('Error:Only one objective supported')
    original_objective=copy.deepcopy(model.objective)
    for reaction in model.objective:
         fva=flux_variability_analysis(model,reaction_list=[reaction.id], fraction_of_optimum=fraction_of_optimum_objective)
         if reaction.objective_coefficient>0:
            reaction.lower_bound=min(fva[reaction.id]["maximum"],reaction.upper_bound)
            reaction.upper_bound=min(fva[reaction.id]["maximum"],reaction.upper_bound)
         elif reaction.objective_coefficient<0:
            reaction.lower_bound=max(fva[reaction.id]["minimum"],reaction.lower_bound)
            reaction.upper_bound=max(fva[reaction.id]["minimum"],reaction.lower_bound)
         reaction.lower_bound-=boundaries_precision/2.0
         reaction.upper_bound+=boundaries_precision/2.0
         reaction.objective_coefficient=0
    reversible_reactions=[]
    #convert_to_irreversible(model)
    for reaction in model.reactions:
        if reaction.lower_bound<0:
           reversible_reactions.append(reaction.id)  
    convert_to_irreversible_with_indicators(model,reversible_reactions,metabolite_list=[], mutually_exclusive_directionality_constraint = True)
    if metabolite_list_file_name!=None and metabolite_list_file_name!="":
       metabolite_id_list=read_metabolomics_data(model,metabolite_list_fname=metabolite_list_file_name)
    else:
       metabolite_id_list=[]
    add_turnover_metabolites(model, metabolite_id_list=metabolite_id_list, epsilon=1e-6,label_model=label_model)
    flux_reporter = Metabolite('flux_reporter_0',formula='',name='',compartment='0')
    reporter_coef=1
    for reaction in model.reactions:
        if "IRRMILP_" in reaction.id or "RATIO_" in reaction.id or "RGROUP_" in reaction.id or "TMS_" in reaction.id:
            continue
        reaction.add_metabolites({flux_reporter:reporter_coef})        
    total_flux_reaction = Reaction('total_flux')
    total_flux_reaction.name = 'total_flux'
    total_flux_reaction.subsystem = 'misc'
    total_flux_reaction.lower_bound = 0  
    total_flux_reaction.upper_bound = 1000*reporter_coef*len(model.reactions)
    total_flux_reaction.objective_coefficient=-1  
    total_flux_reaction.add_metabolites({flux_reporter:-1}) 
    model.add_reaction(total_flux_reaction)
    minimal_flux=-1*model.optimize().f
    total_flux_reaction.upper_bound = minimal_flux*fraction_of_flux_minimum
    total_flux_reaction.objective_coefficient=0.0
    for objective in original_objective:
        reaction=model.reactions.get_by_id(objective.id)
        reaction.lower_bound=(fva[reaction.id]["minimum"]-boundaries_precision/2.0)
        reaction.upper_bound=(fva[reaction.id]["maximum"]+boundaries_precision/2.0)
    milp_reactions=model.reactions.query("IRRMILP_")
    non_milp_reactions=[]
    for reaction in  model.reactions:
      if reaction not in milp_reactions:
         non_milp_reactions.append(reaction)
    return model,minimal_flux,non_milp_reactions 
Beispiel #16
0
 def test_remove_breaks(self):
     model = Model("test model")
     A = Metabolite("A")
     r = Reaction("r")
     r.add_metabolites({A: -1})
     r.lower_bound = -1000
     r.upper_bound = 1000
     model.add_reaction(r)
     convert_to_irreversible(model)
     model.remove_reactions(["r"])
     with pytest.raises(KeyError):
         revert_to_reversible(model)
Beispiel #17
0
 def test_add_reaction(self):
     """test adding and deleting reactions"""
     old_reaction_count = len(self.model.reactions)
     old_metabolite_count = len(self.model.metabolites)
     dummy_metabolite_1 = Metabolite("test_foo_1")
     dummy_metabolite_2 = Metabolite("test_foo_2")
     dummy_reaction = Reaction("test_foo_reaction")
     dummy_reaction.add_metabolites({dummy_metabolite_1: -1, dummy_metabolite_2: 1})
     self.model.add_reaction(dummy_reaction)
     self.assertEqual(self.model.reactions._object_dict[dummy_reaction.id], dummy_reaction)
     for x in [dummy_metabolite_1, dummy_metabolite_2]:
         self.assertEqual(self.model.metabolites._object_dict[x.id], x)
Beispiel #18
0
def convert_to_cobra_model(the_network):
    """ Take a generic NAMpy model and convert to
    a COBRA model.  The model is assumed to be monopartite.
    You need a functional COBRApy for this.

    Arguments:
     the_network

    kwargs:
     flux_bounds


    """
    continue_flag = True
    try:
        from cobra import Model, Reaction, Metabolite
    except:
        print 'This function requires a functional COBRApy, exiting ...'

    if continue_flag:
        __default_objective_coefficient = 0
        
        if 'flux_bounds' in kwargs:
            flux_bounds = kwargs['flux_bounds'] 
        else:
            flux_bounds = len(the_nodes)

        metabolite_dict = {}
        for the_node in the_network.nodetypes[0].nodes: 
            the_metabolite = Metabolite(the_node.id)
            metabolite_dict.update({the_node.id: the_metabolite})

        cobra_reaction_list = []
        for the_edge in the_network.edges:
            the_reaction = Reaction(the_edge.id)
            cobra_reaction_list.append(the_reaction)
            the_reaction.upper_bound = flux_bounds
            the_reaction.lower_bound = -1 * flux_bounds
            cobra_metabolites = {}
            the_metabolite_id_1 = the_edge._nodes[0].id
            the_metabolite_id_2 = the_edge._nodes[1].id
            cobra_metabolites[metabolite_dict[the_metabolite_id_1]] = 1.
            cobra_metabolites[metabolite_dict[the_metabolite_id_2]] = -1.
            reaction.add_metabolites(cobra_metabolites)
            reaction.objective_coefficient = __default_objective_coefficient

        cobra_model = Model(model_id)
        cobra_model.add_reactions(cobra_reaction_list)

        return cobra_model
    else:
        return None
Beispiel #19
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 #20
0
 def test_inequality(self):
     # The space enclosed by the constraints is a 2D triangle with
     # vertexes as (3, 0), (1, 2), and (0, 1)
     solver = self.solver
     # c1 encodes y - x > 1 ==> y > x - 1
     # c2 encodes y + x < 3 ==> y < 3 - x
     c1 = Metabolite("c1")
     c2 = Metabolite("c2")
     x = Reaction("x")
     x.lower_bound = 0
     y = Reaction("y")
     y.lower_bound = 0
     x.add_metabolites({c1: -1, c2: 1})
     y.add_metabolites({c1: 1, c2: 1})
     c1._bound = 1
     c1._constraint_sense = "G"
     c2._bound = 3
     c2._constraint_sense = "L"
     m = Model()
     m.add_reactions([x, y])
     # test that optimal values are at the vertices
     m.change_objective("x")
     self.assertAlmostEqual(solver.solve(m).f, 1.0)
     self.assertAlmostEqual(solver.solve(m).x_dict["y"], 2.0)
     m.change_objective("y")
     self.assertAlmostEqual(solver.solve(m).f, 3.0)
     self.assertAlmostEqual(solver.solve(m, objective_sense="minimize").f,
                           1.0)
 def testGPR(self):
     model = self.model_class()
     reaction = Reaction("test")
     # set a gpr to  reaction not in a model
     reaction.gene_reaction_rule = "(g1 or g2) and g3"
     self.assertEqual(reaction.gene_reaction_rule, "(g1 or g2) and g3")
     self.assertEqual(len(reaction.genes), 3)
     # adding reaction with a GPR propagates to the model
     model.add_reaction(reaction)
     self.assertEqual(len(model.genes), 3)
     # ensure the gene objects are the same in the model and reaction
     reaction_gene = list(reaction.genes)[0]
     model_gene = model.genes.get_by_id(reaction_gene.id)
     self.assertIs(reaction_gene, model_gene)
Beispiel #22
0
def LPLIPA2(model):
    s1 = {
        model.metabolites.get_by_id("C_BOIMMG_291_c"): -1,
        model.metabolites.get_by_id("hdca_c"): 1
    }

    s2 = {
        model.metabolites.get_by_id("C_BOIMMG_27923_c"): -1,
        model.metabolites.get_by_id("hdcea_c"): 1
    }

    s3 = {
        model.metabolites.get_by_id("C_BOIMMG_27877_c"): -1,
        model.metabolites.get_by_id("ocdcea_c"): 1
    }

    s4 = {
        model.metabolites.get_by_id("C_BOIMMG_27943_c"): -1,
        model.metabolites.get_by_id("ttdca_c"): 1
    }

    s5 = {
        model.metabolites.get_by_id("C_BOIMMG_27925_c"): -1,
        model.metabolites.get_by_id("ttdcea_c"): 1
    }

    r1 = Reaction("LPLIPA2_1")
    r2 = Reaction("LPLIPA2_2")
    r3 = Reaction("LPLIPA2_3")
    r4 = Reaction("LPLIPA2_4")
    r5 = Reaction("LPLIPA2_5")

    s = [s1, s2, s3, s4, s5]
    r = [r1, r2, r3, r4, r5]

    for i in range(len(r)):
        si = s[i]

        ri = r[i]

        si[model.metabolites.get_by_id("h2o_c")] = -1
        si[model.metabolites.get_by_id("h_c")] = 1
        si[model.metabolites.get_by_id("g3pe_c")] = 1

        ri.add_metabolites(si)

    model.add_reactions(r)
Beispiel #23
0
def _build_reaction(identifier, stoichiometry, upper, lower, name, comments):
    reaction = Reaction(identifier)
    reaction.id = identifier
    reaction.name = name
    reaction.add_metabolites(stoichiometry)
    reaction.upper_bound = upper
    reaction.lower_bound = lower
    reaction.notes["pathway_note"] = comments
    return reaction
Beispiel #24
0
def Test():
    model = Model('TEST')

    nombre = "test_reaction"
    reaction = Reaction(nombre)
    reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
    reaction.subsystem = 'Cell Envelope Biosynthesis'
    reaction.lower_bound = 0.  # This is the default
    reaction.upper_bound = 1000.  # This is the default

    reaction.add_metabolites({
        Metabolite('malACP_c',
                   formula='C14H22N2O10PRS',
                   name='Malonyl-acyl-carrier-protein',
                   compartment='c'):
        -1.0,
        Metabolite('h_c', formula='H', name='H', compartment='c'):
        -1.0,
        Metabolite('ddcaACP_c',
                   formula='C23H43N2O8PRS',
                   name='Dodecanoyl-ACP-n-C120ACP',
                   compartment='c'):
        -1.0,
        Metabolite('co2_c', formula='CO2', name='CO2', compartment='c'):
        1.0,
        Metabolite('ACP_c',
                   formula='C11H21N2O7PRS',
                   name='acyl-carrier-protein',
                   compartment='c'):
        1.0,
        Metabolite('3omrsACP_c',
                   formula='C25H45N2O9PRS',
                   name='3-Oxotetradecanoyl-acyl-carrier-protein',
                   compartment='c'):
        1.0
    })

    reaction.reaction
    reaction.gene_reaction_rule = '( STM2378 or STM1197 )'
    reaction.genes

    model.add_reactions([reaction])

    print('%i reaction' % len(model.reactions))
    print('%i metabolites' % len(model.metabolites))
    print('%i genes' % len(model.genes))

    MostrarSistema()

    model.objective = nombre
    print(model.objective.expression)
    print(model.objective.direction)
Beispiel #25
0
def LPLIPA1(model):
    s1 = {
        model.metabolites.get_by_id("C_BOIMMG_314_c"): -1,
        model.metabolites.get_by_id("hdca_c"): 1
    }

    s2 = {
        model.metabolites.get_by_id("C_BOIMMG_16363_c"): -1,
        model.metabolites.get_by_id("hdcea_c"): 1
    }

    s3 = {
        model.metabolites.get_by_id("C_BOIMMG_16317_c"): -1,
        model.metabolites.get_by_id("ocdcea_c"): 1
    }

    s4 = {
        model.metabolites.get_by_id("C_BOIMMG_452_c"): -1,
        model.metabolites.get_by_id("ttdca_c"): 1
    }

    s5 = {
        model.metabolites.get_by_id("C_BOIMMG_16364_c"): -1,
        model.metabolites.get_by_id("ttdcea_c"): 1
    }

    r1 = Reaction("LPLIPA1_1")
    r2 = Reaction("LPLIPA1_2")
    r3 = Reaction("LPLIPA1_3")
    r4 = Reaction("LPLIPA1_4")
    r5 = Reaction("LPLIPA1_5")

    s = [s1, s2, s3, s4, s5]
    r = [r1, r2, r3, r4, r5]

    for i in range(len(r)):
        si = s[i]

        ri = r[i]

        si[model.metabolites.get_by_id("h2o_c")] = -1
        si[model.metabolites.get_by_id("h_c")] = 1
        si[model.metabolites.get_by_id("g3pg_c")] = 1

        ri.add_metabolites(si)

    model.add_reactions(r)
Beispiel #26
0
def PASYN_EC(model):
    s1 = {
        model.metabolites.get_by_id("palmACP_c"): -1,
        model.metabolites.get_by_id("C_BOIMMG_423_c"): 1
    }

    s2 = {
        model.metabolites.get_by_id("myrsACP_c"): -1,
        model.metabolites.get_by_id("C_BOIMMG_38435_c"): 1
    }

    s3 = {
        model.metabolites.get_by_id("hdeACP_c"): -1,
        model.metabolites.get_by_id("C_BOIMMG_38416_c"): 1
    }

    s4 = {
        model.metabolites.get_by_id("octeACP_c"): -1,
        model.metabolites.get_by_id("C_BOIMMG_38371_c"): 1
    }

    s5 = {
        model.metabolites.get_by_id("tdeACP_c"): -1,
        model.metabolites.get_by_id("C_BOIMMG_38417_c"): 1
    }

    r1 = Reaction("reaction_1")
    r2 = Reaction("reaction_2")
    r3 = Reaction("reaction_3")
    r4 = Reaction("reaction_4")
    r5 = Reaction("reaction_5")

    s = [s1, s2, s3, s4, s5]
    r = [r1, r2, r3, r4, r5]

    for i in range(len(r)):
        si = s[i]

        ri = r[i]

        si[model.metabolites.get_by_id("glyc3p_c")] = -1
        si[model.metabolites.get_by_id("ACP_c")] = 2

        ri.add_metabolites(si)

    model.add_reactions(r)
Beispiel #27
0
def addFromSeedDB(mod, lineFromSeedDB):
    import pandas
    from cobra import Model, Reaction, Metabolite
    comp = {'0':'_c0', '1':'_e0', '2':'_p0'}
    model = mod.copy()
    formula = lineFromSeedDB["stoichiometry"].values[0]
    rea_met = {m.split(":")[1]+comp[m.split(":")[2]]:float(m.split(":")[0]) for m in formula.split(";")}
    rea_id  = lineFromSeedDB["id"].values[0] + "_c0" # always the case??
    rea_name= lineFromSeedDB["name"].values[0]
    rea = Reaction(id=rea_id, name=rea_name)
    for m in rea_met:
        if m not in model.metabolites:
            model.add_metabolites(Metabolite(m))
    model.add_reactions(rea)
    rea_stoich = {model.metabolites.get_by_id(m):rea_met[m] for m in rea_met}
    rea.add_metabolites(rea_stoich)
    return(model)
Beispiel #28
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 #29
0
    def add_reaction_basic(self, r_id, r_name):
        if r_id not in self.reactions:
            ##############
            # model_data #
            ##############
            self.reactions[r_id] = r_name
            self.listed_reactions.append(r_id)
            self.reaction_position[r_id] = len(self.listed_reactions) - 1

            self.reaction_bounds[r_id] = (-1000, 1000)

            #########
            # cobra #
            #########
            reaction = Reaction(r_id)
            self.model.add_reactions([reaction])

            reaction.name = r_name

            r_metabolites = {}
            reaction.add_metabolites(r_metabolites)

            reaction.lower_bound = -1000
            reaction.upper_bound = 1000
            return 1
        else:
            return 0
Beispiel #30
0
 def test_gene_knockout_computation(self):
     cobra_model = self.model
     delete_model_genes = delete.delete_model_genes
     get_removed = lambda m: {x.id for x in m._trimmed_reactions}
     gene_list = ['STM1067', 'STM0227']
     dependent_reactions = {
         '3HAD121', '3HAD160', '3HAD80', '3HAD140', '3HAD180', '3HAD100',
         '3HAD181', '3HAD120', '3HAD60', '3HAD141', '3HAD161', 'T2DECAI',
         '3HAD40'
     }
     delete_model_genes(cobra_model, gene_list)
     self.assertEqual(get_removed(cobra_model), dependent_reactions)
     # cumulative
     delete_model_genes(cobra_model, ["STM4221"], cumulative_deletions=True)
     dependent_reactions.add('PGI')
     self.assertEqual(get_removed(cobra_model), dependent_reactions)
     # non-cumulative
     delete_model_genes(cobra_model, ["STM4221"],
                        cumulative_deletions=False)
     self.assertEqual(get_removed(cobra_model), {'PGI'})
     # make sure on reset that the bounds are correct
     reset_bound = cobra_model.reactions.get_by_id("T2DECAI").upper_bound
     self.assertEqual(reset_bound, 1000.)
     # test computation when gene name is a subset of another
     test_model = Model()
     test_reaction_1 = Reaction("test1")
     test_reaction_1.gene_reaction_rule = "eggs or (spam and eggspam)"
     test_model.add_reaction(test_reaction_1)
     delete.delete_model_genes(test_model, ["eggs"])
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["spam"], cumulative_deletions=True)
     self.assertEqual(get_removed(test_model), {'test1'})
     # test computation with nested boolean expression
     delete.undelete_model_genes(test_model)
     test_reaction_1.gene_reaction_rule = \
         "g1 and g2 and (g3 or g4 or (g5 and g6))"
     delete_model_genes(test_model, ["g3"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["g1"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), {'test1'})
     delete_model_genes(test_model, ["g5"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["g3", "g4", "g5"],
                        cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), {'test1'})
Beispiel #31
0
    def create_new_stoichiometric_matrix(self):
        """
        Extracts the new graph without the small metabolites, inorganics and cofactor pairs.

        :return: Networkx graph of the new network
        """
        kept_rxns = []
        kept_metabolites = set()
        for rxn in self._redgem.reactions:
            metabolites = {}
            for metabolite, coefficient in rxn.metabolites.items():
                metabolite_id = metabolite.id
                if metabolite_id in self._cofactor_pairs \
                        or metabolite_id in self._small_metabolites \
                        or metabolite_id in self._inorganics:
                    continue
                new_metabolite = Metabolite(metabolite_id,
                                            formula=metabolite.formula,
                                            name=metabolite.name,
                                            compartment=metabolite.compartment)
                metabolites[new_metabolite] = coefficient
                kept_metabolites.add(metabolite)
            new_rxn = Reaction(rxn.id,
                               name=rxn.name,
                               subsystem=rxn.subsystem,
                               lower_bound=rxn.lower_bound,
                               upper_bound=rxn.upper_bound)
            new_rxn.add_metabolites(metabolites)
            kept_rxns.append(new_rxn)

        paths_struct = [{} for _ in range(self._d + 1)
                        ]  # Comprehension list to create multiple dicts
        to_struct = [""] * (self._d + 1)
        for metabolite in kept_metabolites:
            self._graph.add_node(metabolite.id,
                                 paths=paths_struct,
                                 to=to_struct)
        for rxn in kept_rxns:
            for reactant in rxn.reactants:
                for product in rxn.products:
                    self._graph.add_edge(reactant.id,
                                         product.id,
                                         rxn_id=rxn.id,
                                         weight=1)
        return self._graph
Beispiel #32
0
def LP7(model, the_reactions=None, epsilon=1e-3, solver=None):
    model_lp7 = model.copy()

    for reaction in model_lp7.reactions:
        reaction.objective_coefficient = 0

    if the_reactions is None:
        the_reactions = [r.id for r in model_lp7.reactions]

    if not hasattr(list(the_reactions)[0], 'id'):
        the_reactions = map(model_lp7.reactions.get_by_id, the_reactions)

    for reaction in the_reactions:
        dummy_reaction = Reaction("dummy_rxn_" + reaction.id)
        dummy_reaction.lower_bound = 0
        dummy_reaction.upper_bound = epsilon
        dummy_reaction.objective_coefficient = 1

        model_lp7.add_reaction(dummy_reaction)

        dummy_metabolite = Metabolite("dummy_met_" + reaction.id)
        dummy_metabolite._constraint_sense = "L"
        dummy_metabolite._bound = 0

        reaction.add_metabolites({dummy_metabolite: -1})
        dummy_reaction.add_metabolites({dummy_metabolite: 1})

    model_lp7.optimize(solver=solver)
    if model_lp7.solution is None or model_lp7.solution.x_dict is None:
        print "INFEASIBLE LP7"
        return {}

    return dict([(k, v) for k, v in model_lp7.solution.x_dict.items()
                 if not k.startswith('dummy_')])
Beispiel #33
0
def eval_ind(individual, initial_pop, model, base_biomass, exp_ess, distance):
    # Set this as warning
    model.solver = 'gurobi'
    old_biomass = list(linear_reaction_coefficients(model).keys())[0]  # index removed
    old_biomass.remove_from_model()
    # Make a biomass reaction and optimize for it
    biomass = Reaction('BIOMASS')
    model.add_reaction(biomass)
    index = initial_pop.index
    for i in range(len(index)):
        if individual[i] == 1:
            biomass.add_metabolites({initial_pop.index[i]: -0.1})
    biomass.add_metabolites(base_biomass)
    biomass.objective_coefficient = 1.
    # Generate deletion results --> BOTTLENECK FOR SURE
    deletion_results = single_gene_deletion(model, model.genes, processes=1)

    # Filter the results to get a boolean result
    a = [(str(next(iter(i))), 1) for i in deletion_results[deletion_results['growth'] > 1e-3].index]
    b = [(str(next(iter(i))), 0) for i in deletion_results[deletion_results['growth'] <= 1e-3].index]
    c = a + b
    pred_ess = pd.DataFrame(c, columns=['Genes', 'Predicted_growth'])
    compare_df = pd.merge(right=exp_ess, left=pred_ess, on='Genes', how='inner')

    # Apply hamming distance
    u = np.array([f for f in compare_df.Measured_growth])
    v = np.array([x for x in compare_df.Predicted_growth])
    if distance == 'hd':
        dist = hamming(u, v)
    elif distance == 'mcc':
        dist = matthews_corrcoef(u, v)
    else:
        print('Error: Invalid distance metric')

    return dist, sum(individual)
Beispiel #34
0
 def test_gene_knockout_computation(self):
     cobra_model = self.model
     delete_model_genes = delete.delete_model_genes
     get_removed = lambda m: {x.id for x in m._trimmed_reactions}
     gene_list = ['STM1067', 'STM0227']
     dependent_reactions = {'3HAD121', '3HAD160', '3HAD80', '3HAD140',
                            '3HAD180', '3HAD100', '3HAD181','3HAD120',
                            '3HAD60', '3HAD141', '3HAD161', 'T2DECAI',
                            '3HAD40'}
     delete_model_genes(cobra_model, gene_list)
     self.assertEqual(get_removed(cobra_model), dependent_reactions)
     # cumulative
     delete_model_genes(cobra_model, ["STM4221"],
                        cumulative_deletions=True)
     dependent_reactions.add('PGI')
     self.assertEqual(get_removed(cobra_model), dependent_reactions)
     # non-cumulative
     delete_model_genes(cobra_model, ["STM4221"],
                        cumulative_deletions=False)
     self.assertEqual(get_removed(cobra_model), {'PGI'})
     # make sure on reset that the bounds are correct
     reset_bound = cobra_model.reactions.get_by_id("T2DECAI").upper_bound
     self.assertEqual(reset_bound, 1000.)
     # test computation when gene name is a subset of another
     test_model = Model()
     test_reaction_1 = Reaction("test1")
     test_reaction_1.gene_reaction_rule = "eggs or (spam and eggspam)"
     test_model.add_reaction(test_reaction_1)
     delete.delete_model_genes(test_model, ["eggs"])
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["spam"], cumulative_deletions=True)
     self.assertEqual(get_removed(test_model), {'test1'})
     # test computation with nested boolean expression
     delete.undelete_model_genes(test_model)
     test_reaction_1.gene_reaction_rule = \
         "g1 and g2 and (g3 or g4 or (g5 and g6))"
     delete_model_genes(test_model, ["g3"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["g1"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), {'test1'})
     delete_model_genes(test_model, ["g5"], cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), set())
     delete_model_genes(test_model, ["g3", "g4", "g5"],
                        cumulative_deletions=False)
     self.assertEqual(get_removed(test_model), {'test1'})
Beispiel #35
0
def createTokens(model,reactionmap):
    from cobra import Reaction
    from cobra import Metabolite
    '''
    Compares a CobraPy model and a reaction map. If several model reactions are
    associated with the same experimental reaction, a token reaction is created
    whose flux will equal a linear combination of those reactions (the token flux). This token
    reaction can be used as a decision variable during quadratic optimization attempting
    to match the token flux to that of the experimental reaction. 
    Noe that limiting the token flux to zero will prevent any flux through the separate reactions.
    '''
    for linkdict in reactionmap:
        if len(linkdict['modrxns']) > 1:
            experimental_r_id = linkdict['exprxns'][0]['rxid']
            token_id = 't_{exprxnid}'.format(exprxnid = experimental_r_id)
            new_token_reaction = Reaction(token_id)
            new_token_reaction.name = 'Token exchange reaction for experimental reaction {exprxnid}'.format(exprxnid = experimental_r_id)
            new_token_reaction.lower_bound = -1000
            new_token_reaction.upper_bound = 1000
            new_token_metabolite = Metabolite(token_id,name = 'Token metabolite for experimental reaction {exprxnid}'.format(exprxnid = experimental_r_id),compartment='c')
            new_token_reaction.add_metabolites({new_token_metabolite: -1.0})
            model.add_reactions(new_token_reaction)
            for dictionary in linkdict['modrxns']:
                modelreaction = model.reactions.get_by_id(dictionary['rxid'])
                modelreaction.add_metabolites({new_token_metabolite: float(dictionary['coef'])})
    return model
Beispiel #36
0
def fix_reaction_to_min(model: cobra.Model,
                        reac: cobra.Reaction) -> Tuple[str, float]:
    """Fix a reaction to its minimum."""
    rev_id = _apply_rev(reac.id, model)
    rev_reac = model.reactions.get_by_id(rev_id) if rev_id else None
    with model:
        if rev_reac is not None:
            prev_bounds = reac.bounds
            set_objective(model, {rev_reac: 1})
            reac.bounds = 0, 0
            lb = model.slim_optimize()
            reac.bounds = prev_bounds
            reac_to_fix = rev_id
        else:
            set_objective(model, {reac: -1})
            lb = model.slim_optimize()
            reac_to_fix = reac.id
    return reac_to_fix, lb
Beispiel #37
0
def three_components_closed(base):
    """Returns a simple model with 3 metabolites in a closed system."""
    met_a = Metabolite("A")
    met_b = Metabolite("B")
    met_c = Metabolite("C")
    rxn_1 = Reaction("R1", lower_bound=-1000, upper_bound=1000)
    rxn_1.add_metabolites({met_a: -1, met_b: 1})
    rxn_2 = Reaction("R2", lower_bound=-1000, upper_bound=1000)
    rxn_2.add_metabolites({met_b: -1, met_c: 1})
    base.add_reactions([rxn_1, rxn_2])
    return base
Beispiel #38
0
    def add_reactions_for_metabolites(self, measured_metabolites):

        for metabolite, change in measured_metabolites.items():
            reaction = Reaction('R_{m}_spill'.format(m=metabolite))
            reaction.lower_bound = 0.  # This is the default
            reaction.upper_bound = 1000.  # This is the default
            if change > 0:
                reaction.add_metabolites({self.model.metabolites.get_by_id(metabolite): -1.0})
            else:
                reaction.add_metabolites({self.model.metabolites.get_by_id(metabolite): 1.0})
            self.model.add_reactions([reaction])
Beispiel #39
0
    def __process_reaction(
        self, new_reaction: Reaction, new_compound: int,
        model_parent: Metabolite, parent_and_precursors: dict,
        new_reaction_metabolites: List[Metabolite]
    ) -> Tuple[Reaction, List[Tuple[Metabolite, int]]]:
        """
        Granulates a given reaction. Replaces the generic metabolite by its structurally defined child and corrects the
        precursors.

        :param Reaction new_reaction: the new reaction
        :param int new_compound: the reaction structurally defined product
        :param Metabolite model_parent: the model parent of the structurally defined product
        :param dict parent_and_precursors: dictionary with lipid parents and their children
        :param List[Metabolite] new_reaction_metabolites: list of possibly new metabolites
        :return Tuple[Reaction, List[Tuple[Metabolite, int]]]: returns a tuple with the granulated model reaction
        and the new added compounds that will be processed further.
        """

        i = 0
        found = False

        while not found and i < len(new_reaction_metabolites):
            if new_reaction_metabolites[i].id == model_parent.id:
                new_model_parent = new_reaction_metabolites[i]
                found = True

            i += 1

        coef = new_reaction.get_coefficient(model_parent.id)

        self.add_boimmg_metabolites_to_reaction(new_compound, coef,
                                                new_reaction,
                                                model_parent.compartment)

        met_to_subtract = {}

        met_to_subtract[new_model_parent] = coef
        new_reaction.subtract_metabolites(met_to_subtract)

        added = self._correct_precursors(new_reaction, new_compound,
                                         parent_and_precursors)

        return new_reaction, added
Beispiel #40
0
    def add_metabolites(self, metabolites, rescale = True):
        """
        We need to override this method if the reaction is scaled

        v_hat = v/vmax

        dM/dt = n1*v1 + ...

        dM/dt = n1*vmax1 * v1_hat + ...

        :param metabolites:
        :return:
        """

        if not hasattr(self, '_scaled') or not rescale or not self._scaled:
            Reaction.add_metabolites(self, metabolites)
        else:
            Reaction.add_metabolites(self, {k:v*self.scaling_factor
                                        for k,v in metabolites.items()})
 def convert_to_irreversible(model,reactions_to_convert): ##### TO DO : implement ATP cost in reverse reaction (1 ATP)
     """
     Split reversible reactions into two irreversible reactions.
     
     cobra_model: A Cobra model object which will be modified in place.
     reactions_to convert: list of reaction_id to convert 
     
     """
     reactions_to_add = []
     convertedlist = []
     
     atp_metabolites = [
     model.metabolites.ppi_c,
     model.metabolites.pi_c,
     model.metabolites.atp_c,
     model.metabolites.adp_c,
     model.metabolites.adp_c] 
     
     for r in reactions_to_convert:
          
          reaction = model.reactions.get_by_id(r)
          if reaction.lower_bound < 0 and reaction.upper_bound > 0:
               reverse_reaction = Reaction(id=reaction.id + '_reverse',
                                           lower_bound = reaction.lower_bound,
                                           upper_bound = 0)
               
               reaction.lower_bound = 0
               reaction.upper_bound = reaction.upper_bound
               
             
               reverse_reaction_dict = {k: v * -1 for k, v in reaction.metabolites.items() 
                    if k not in atp_metabolites} # <- disallows recovery of ATP metabolites from protein degradation
               
               reverse_reaction.add_metabolites(reverse_reaction_dict)
                                  
               reverse_reaction.subsystem = reaction.subsystem
               reactions_to_add.append(reverse_reaction)
               convertedlist.append(reverse_reaction.id) 
               
     model.add_reactions(reactions_to_add)
     
     return convertedlist
Beispiel #42
0
def create_adapter_reactions(original_metabolites, universal_model, mapping, compartment_regexp):
    """Create adapter reactions that connect host and universal model.

    Arguments
    ---------
    original_metabolites : list
        List of host metabolites.
    universal_model : cobra.Model
        The universal model.
    mapping : dict
        A mapping between between host and universal model metabolite IDs.
    compartment_regexp : regex
        A compiled regex that matches metabolites that should be connected to the universal model.

    Returns
    -------
    reactions : list
        The list of adapter reactions.
    """
    adapter_reactions = []
    metabolites_in_main_compartment = [m for m in original_metabolites if compartment_regexp.match(m.compartment)]
    if len(metabolites_in_main_compartment) == 0:
        raise ValueError('no metabolites matching regex for main compartment %s' % compartment_regexp)
    for metabolite in metabolites_in_main_compartment:  # model is the original host model
        name = re.sub('_{}$'.format(metabolite.compartment), '', metabolite.id)  # TODO: still a hack
        mapped_name = None
        for prefix in ['bigg:', 'kegg:', 'rhea:', 'brenda:', '']:  # try no prefix at last
            if prefix + name in mapping:
                mapped_name = mapping[prefix + name]
                break
        if mapped_name is not None:
            adapter_reaction = Reaction(str('adapter_' + metabolite.id + '_' + mapped_name))
            adapter_reaction.lower_bound = -1000
            try:
                adapter_reaction.add_metabolites({metabolite: -1,
                                                  universal_model.metabolites.get_by_id(mapped_name): 1})
            except KeyError:
                pass
            else:
                adapter_reactions.append(adapter_reaction)

    return adapter_reactions
Beispiel #43
0
    def constrain_pool(self):
        """Constrain the draw reactions for the unmeasured (common protein pool) proteins.

        Proteins without their own protein pool are collectively constrained by the common protein pool. Remove
        protein pools for all proteins that don't have measurements, along with corresponding draw reactions,
        and add these to the common protein pool and reaction.
        """
        new_reactions = []
        to_remove = []
        # * section 2.5.1
        # 1. and 2. introduce `prot_pool` and exchange reaction done in __init__
        # 3. limiting total usage with the unmeasured amount of protein
        # looks like the matlab code:
        # self.fs_matched_adjusted = ((self.p_total - self.p_measured) / self.p_base *
        #                             self.f_mass_fraction_measured_matched_to_total *
        #                             self.sigma_saturation_factor)
        # but this gives results more like reported:
        self.fs_matched_adjusted = (
            (self.p_total - self.p_measured) *
            self.f_mass_fraction_measured_matched_to_total *
            self.sigma_saturation_factor)
        self.reactions.prot_pool_exchange.bounds = 0, self.fs_matched_adjusted
        # 4. Remove other enzyme usage reactions and replace with pool exchange reactions
        average_mmw = self.protein_properties['mw'].mean() / 1000.
        for protein_id in self.unmeasured_proteins:
            to_remove.extend(
                self.reactions.query('prot_{}_exchange'.format(protein_id)))
            draw_reaction_id = 'draw_prot_{}'.format(protein_id)
            if draw_reaction_id not in self.reactions:
                draw_rxn = Reaction(draw_reaction_id)
                draw_rxn.annotation['uniprot'] = protein_id
                protein_pool = self.metabolites.get_by_id(
                    'prot_{}_c'.format(protein_id))
                try:
                    mmw = self.protein_properties.loc[protein_id, 'mw'] / 1000.
                except KeyError:
                    mmw = average_mmw
                metabolites = {self.common_protein_pool: -mmw, protein_pool: 1}
                draw_rxn.add_metabolites(metabolites)
                new_reactions.append(draw_rxn)
        self.add_reactions(new_reactions)
        self.remove_reactions(to_remove)
def gapfillfunc(model, database, runs):
    """ This function gapfills the model using the growMatch algorithm that is built into cobrapy

    Returns a dictionary which contains the pertinent information about the gapfilled model such as
    the reactions added, the major ins and outs of the system and the objective value of the gapfilled
    model.
    This function calls on two other functions sort_and_deduplicate to assure the uniqueness of the solutions
    and findInsAndOuts to find major ins and outs of the model when gapfilled when certain reactions
    Args:
        model: a model in SBML format
        database: an external database database of reactions to be used for gapfilling
        runs: integer number of iterations the gapfilling algorithm will run through
    """
    # Read model from SBML file and create Universal model to add reactions to
    func_model = create_cobra_model_from_sbml_file(model)
    Universal = Model("Universal Reactions")
    f = open(database, 'r')
    next(f)
    rxn_dict = {}
    # Creates a dictionary of the reactions from the tab delimited database, storing their ID and the reaction string
    for line in f:
        rxn_items = line.split('\t')
        rxn_dict[rxn_items[0]] = rxn_items[6], rxn_items[1]
    # Adds the reactions from the above dictionary to the Universal model
    for rxnName in rxn_dict.keys():
        rxn = Reaction(rxnName)
        Universal.add_reaction(rxn)
        rxn.reaction = rxn_dict[rxnName][0]
        rxn.name = rxn_dict[rxnName][1]

    # Runs the growMatch algorithm filling gaps from the Universal model
    result = flux_analysis.growMatch(func_model, Universal, iterations=runs)
    resultShortened = sort_and_deduplicate(uniq(result))
    rxns_added = {}
    rxn_met_list = []
    print resultShortened
    for x in range(len(resultShortened)):
        func_model_test = deepcopy(func_model)
        # print func_model_test.optimize().f
        for i in range(len(resultShortened[x])):
            addID = resultShortened[x][i].id
            rxn = Reaction(addID)
            func_model_test.add_reaction(rxn)
            rxn.reaction = resultShortened[x][i].reaction
            rxn.reaction = re.sub('\+ dummy\S+', '', rxn.reaction)
            rxn.name = resultShortened[x][i].name
            mets = re.findall('cpd\d{5}_c0|cpd\d{5}_e0', rxn.reaction)
            for met in mets:
                y = func_model_test.metabolites.get_by_id(met)
                rxn_met_list.append(y.name)
        obj_value = func_model_test.optimize().f
        fluxes = findInsAndOuts(func_model_test)
        sorted_outs = fluxes[0]
        sorted_ins = fluxes[1]
        rxns_added[x] = resultShortened[x], obj_value, sorted_ins, sorted_outs, rxn_met_list
        rxn_met_list = []
    return rxns_added
Beispiel #45
0
    def change_boimmg_reaction_id(self, reaction: Reaction):

        new_id = self.__reactionsAnnotationConfigs["BOIMMG_ID_CONSTRUCTION"]
        metabolites = reaction.metabolites

        metabolites = sorted([metabolite.id for metabolite in metabolites])
        new_id += "_".join(metabolites)

        reaction.id = new_id

        return reaction.id
Beispiel #46
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 #47
0
def create_reaction(rxn_id, name, subsystem, lower_bound, upper_bound, metabolites_d3):
    reaction = Reaction(rxn_id)
    reaction.name = name
    reaction.subsystem = subsystem
    reaction.lower_bound = lower_bound
    reaction.upper_bound = upper_bound
    for metabolite_d2 in metabolites_d3:
        metabolite_data = metabolite_d2[0]
        metabolite_coeff = metabolite_d2[1]
        new_met = create_metabolite(metabolite_data)
        reaction.add_metabolites({ new_met: metabolite_coeff })

    return reaction
Beispiel #48
0
def PLIPA3(model):
    s1 = {model.metabolites.get_by_id("BMGC427_c"): -1,
          model.metabolites.get_by_id("hdca_c"): 1,
          model.metabolites.get_by_id("BMGC314_c"): 1}

    s2 = {model.metabolites.get_by_id("BMGC7454_c"): -1,
          model.metabolites.get_by_id("hdcea_c"): 1,
          model.metabolites.get_by_id("BMGC16363_c"): 1}

    s3 = {model.metabolites.get_by_id("BMGC7408_c"): -1,
          model.metabolites.get_by_id("ocdcea_c"): 1,
          model.metabolites.get_by_id("BMGC16317_c"): 1}

    s4 = {model.metabolites.get_by_id("BMGC7474_c"): -1,
          model.metabolites.get_by_id("ttdca_c"): 1,
          model.metabolites.get_by_id("BMGC452_c"): 1}

    s5 = {model.metabolites.get_by_id("BMGC7456_c"): -1,
          model.metabolites.get_by_id("ttdcea_c"): 1,
          model.metabolites.get_by_id("BMGC16364_c"): 1}

    r1 = Reaction("PLIPA3_1")
    r2 = Reaction("PLIPA3_2")
    r3 = Reaction("PLIPA3_3")
    r4 = Reaction("PLIPA3_4")
    r5 = Reaction("PLIPA3_5")

    s = [s1, s2, s3, s4, s5]
    r = [r1, r2, r3, r4, r5]

    for i in range(len(r)):
        si = s[i]

        ri = r[i]

        si[model.metabolites.get_by_id("h2o_c")] = -1
        si[model.metabolites.get_by_id("h_c")] = 1

        ri.add_metabolites(si)

    model.add_reactions(r)
Beispiel #49
0
def get_reference(mod, newR, delete_unbalanced, verbose):
    #refdb  = seedrDB.loc[seedrDB['abbreviation'].isin(newR)] # vmh
    refdb = seedrDB.loc[seedrDB['id'].isin(newR)]
    refmod = Model("reaction_database")
    Rmod = [re.sub("_.*$", "", r.id) for r in mod.reactions]
    print "Consider", len(refdb.index), "reactions"
    Cold = 0
    Calready = 0
    for i, row in refdb.iterrows():
        #rid = row["abbreviation"] # vmh
        rid = row["id"]
        if row["is_obsolete"] == 1:  # do not add old reactions
            Cold += 1
            continue
        #if rid in Rmod: # vmh
        elif rid in Rmod:
            Calready += 1
            continue
        r = Reaction(rid + "_c0")  # default seed model have compartment tag
        refmod.add_reaction(r)
        #rstr = row["formula"] # vmh
        rstr = row["equation"]
        #rstr = row["code"]
        rstr = rstr.replace("[0]", "_c0").replace("[1]",
                                                  "_e0").replace("[3]", "_p0")
        if "[2]" in rstr:  # TODO: consider all compartments!
            continue
        r.build_reaction_from_string(rstr, verbose=False)
        #r.reaction = rstr
    for m in refmod.metabolites:
        mid = re.sub("_.*$", "", m.id)
        hit = seedmDB.loc[seedmDB["id"] == mid]
        m.name = hit["name"].values[0]
        m.formula = hit["formula"].values[0]
        m.charge = hit["charge"].values[0]

    print Calready, "reactions already in the model"
    print Cold, "removed deprecated reactions"
    #refmod = repair_mass_balance(refmod, delete_unbalanced, verbose)
    print len(refmod.reactions), "remaining reaction in reference database:",
    return (refmod)
     def add_bigg_reactions(model,BiGG_id_list):
          for r in BiGG_id_list:
               d=cobrababel.get_bigg_reaction(r, model_bigg_id='universal')
               
               reaction = Reaction(id=d['bigg_id'].replace('_e','(e)'),
                                   name = d['name'],
                                              subsystem = '',
                                              lower_bound = -1000 ,
                                              upper_bound =  1000 ,
                                              objective_coefficient=0.0)
               
          for k, val in enumerate(d['metabolites']):
                    met=Metabolite(val['bigg_id'].replace('__', '_')+'_'+val['compartment_bigg_id'])
                    met.name=val['name']
                    met.compartment=val['compartment_bigg_id']
                    reaction.add_metabolites({met:val['stoichiometry']})

          if reaction not in model.reactions:
                    model.add_reaction(reaction)
          
          return model
Beispiel #51
0
def LP7(model,the_reactions=None,epsilon=1e-3,solver=None):
    model_lp7 = model.copy()
    
    for reaction in model_lp7.reactions:
        reaction.objective_coefficient = 0

    if the_reactions is None:
        the_reactions = [r.id for r in model_lp7.reactions]

    if not hasattr(list(the_reactions)[0], 'id'):
        the_reactions = map(model_lp7.reactions.get_by_id,the_reactions)

    for reaction in the_reactions:
        dummy_reaction = Reaction("dummy_rxn_" + reaction.id)
        dummy_reaction.lower_bound = 0
        dummy_reaction.upper_bound = epsilon
        dummy_reaction.objective_coefficient = 1

        model_lp7.add_reaction(dummy_reaction)

        dummy_metabolite = Metabolite("dummy_met_" + reaction.id)
        dummy_metabolite._constraint_sense = "L"
        dummy_metabolite._bound = 0

        reaction.add_metabolites({dummy_metabolite: -1})
        dummy_reaction.add_metabolites({dummy_metabolite: 1})

    model_lp7.optimize(solver=solver)
    if model_lp7.solution is None or model_lp7.solution.x_dict is None:
        print "INFEASIBLE LP7"
        return {}

    
    return dict([(k,v) for k,v in model_lp7.solution.x_dict.items() if not k.startswith('dummy_')])
Beispiel #52
0
def generateSinkReactions(M, sink_mets, setting):
    ''' When performing metabolomics mode: add sink reactions for the metabolites the user supplied. 
    setting is either '''
    def sink_exists(met):
        ''' Figure out if an exchange for met exists'''

        for r in M.reactions:
            if len(r.metabolites) == 1 and met in r.metabolites:
                return True, r

        # if we get here such a reaction was not found
        return False, ''

    # make sure sink_mets are metabolite objects
    if all([type(m) == str or type(m) == str for m in sink_mets]):
        sink_mets = [M.metabolites.get_by_id(m) for m in sink_mets]

    # add sink reactions
    sinks = []
    for met in sink_mets:
        b, existing_sink = sink_exists(met)
        if b:
            sinks.append(existing_sink)
            print(('Using existing sink reaction', existing_sink))
        else:
            rxn = Reaction('tmp_sink_' + met.id)
            M.add_reaction(rxn)
            rxn.add_metabolites({met: -1})  # X -> nothing
            rxn.upper_bound = 0
            rxn.lower_bound = 0  # Block by default. Only activate when simulating
            sinks.append(rxn)

    return M, sinks, sink_mets
Beispiel #53
0
def add_exchange_reaction(met_id, model, lb=0, ub=1000):
    met = model.metabolites.get_by_id(met_id)
    reaction = Reaction(met.id)
    reaction.lower_bound = lb
    reaction.upper_bound = ub
    reaction.add_metabolites({met: -1.0})
    model.add_reaction(reaction)
Beispiel #54
0
def excel_sbml(modelname,outputname):
    import datetime
    import cobra
    from cobra import Metabolite, Reaction, Model
    from cobra.io import write_sbml_model
    #from __future__ import print_function
    import pandas as pd
    #myfolder='/media/jupyter/zhang_x/study/'
    #mname="seed_1"

    #若需包括更多代谢物信息,则可先在模型中创建代谢物对象并添加到模型
    #A = Metabolite('A')
    #model.add_metabolites([A, B, C, D, E, P])
    starttime = datetime.datetime.now()
    model = Model('model')
    colnames=['id','reaction_eq','name','lower_bound','upper_bound','Object']
#将上述值改为excel表格中的相应列名称数据以便正确读出值,表格中不一定包括所有列,不需要改变列的顺序,通过列头识别
#objr='Objective'  #目标反应的名字
#rin=[['PGI',-10,10]] #可设置多个输入反应及其上下限
#若表格中不包括目标反应数据需人为给出,同样对输入反应需人为添加约束,若已有相应数据则这两个值不用改
#data = pd.read_csv(mname+'.csv', delimiter=",", na_values=['(none)']).fillna('')
    data = pd.read_excel(modelname, sheet_name='reactions', header=0, na_values=['(none)']).fillna('')  #'(none)'变NaN,NaN数据用''填充
#print(data)
#直接从excel文件读取不用再转换txt,header行为数据起始行和表头(因前面行可能有模型说明文件) 表中空值替换为空字符以便处理,不能用dropna,否则整行数据都会丢掉
    keys=data.keys()
    for index, row in data.iterrows():
        r = Reaction(row[colnames[0]].strip())  #r即每个反应对应的反应名字(name)
        model.add_reaction(r)
        r.build_reaction_from_string(row[colnames[1]],fwd_arrow='-->', rev_arrow='<--', reversible_arrow='<=>', term_split='+')  #excel中方程式colnames[1],转成SBML格式
        if colnames[2] in keys:
            r.subsystem=row[colnames[2]]
        if colnames[3]in keys:
            r.lower_bound=row[colnames[3]]
            r.upper_bound=row[colnames[4]]
        if colnames[4] in keys: #目标反应
            if row[colnames[5]]:
               r.objective_coefficient=row[colnames[5]]
    #if colnames[5] in keys:
    #    if row[colnames[5]]:
    #       r.objective_coefficient=1
    #s=row[colnames[6]] #对基因关系处理要看表格中是如何存储and/or关系的
    #if s:
    #    genes=s.split(", ")
    #   r.gene_reaction_rule='('+" or ".join(genes)+' )'
#if colnames[3] not in keys:  #需人为设定输入反应边界,注意根据反应方向确定是改下限还是上限及值的正负
#    for r in rin:
#        rea=model.reactions.get_by_id(r[0])
#        rea.lower_bound=r[1]
#        rea.upper_bound=r[2]
    write_sbml_model(model, outputname)
Beispiel #55
0
def generateSinkReactions(M, sink_mets, setting):
    def sink_exists(met):
        ''' Find if an exchange for met exists'''
        for r in M.reactions:
            if len(r.metabolites) == 1 and met in r.metabolites:
                return True, r
        # if we get here such a reaction was not found
        return False, ''

    # make sure sink_mets are metabolite objects
    if all([type(m) == str or type(m) == str for m in sink_mets]):
        sink_mets = [M.metabolites.get_by_id(m) for m in sink_mets]

    # add sink reactions
    sinks = []
    for met in sink_mets:
        b, existing_sink = sink_exists(met)
        if not b:
            rxn = Reaction('tmp_sink_' + met.id)
            M.add_reaction(rxn)
            rxn.add_metabolites({met: -1})
            rxn.upper_bound = 0
            rxn.lower_bound = 0  # have to init to zero. Only activate when simulating
            sinks.append(rxn)
        else:
            sinks.append(existing_sink)
            print(('Taking existing sink reaction', existing_sink))

    return M, sinks, sink_mets
Beispiel #56
0
 def testGPR(self):
     model = self.model_class()
     reaction = Reaction("test")
     # set a gpr to  reaction not in a model
     reaction.gene_reaction_rule = "(g1 or g2) and g3"
     self.assertEqual(reaction.gene_reaction_rule, "(g1 or g2) and g3")
     self.assertEqual(len(reaction.genes), 3)
     # adding reaction with a GPR propagates to the model
     model.add_reaction(reaction)
     self.assertEqual(len(model.genes), 3)
     # ensure the gene objects are the same in the model and reaction
     reaction_gene = list(reaction.genes)[0]
     model_gene = model.genes.get_by_id(reaction_gene.id)
     self.assertIs(reaction_gene, model_gene)
     # test ability to handle uppercase AND/OR
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         reaction.gene_reaction_rule = "(b1 AND b2) OR (b3 and b4)"
     self.assertEqual(reaction.gene_reaction_rule,
                      "(b1 and b2) or (b3 and b4)")
     self.assertEqual(len(reaction.genes), 4)
     # ensure regular expressions correctly extract genes from malformed
     # GPR string
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         reaction.gene_reaction_rule = "(a1 or a2"
         self.assertEqual(len(reaction.genes), 2)
         reaction.gene_reaction_rule = "(forT or "
         self.assertEqual(len(reaction.genes), 1)
Beispiel #57
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 #58
0
def set2respiration(model):
    mod = model.copy()
    mql = mod.metabolites.get_by_id("cpd15499_c0")
    mqn = mod.metabolites.get_by_id("cpd15500_c0")
    uql = mod.metabolites.get_by_id("cpd15561_c0")
    uqn = mod.metabolites.get_by_id("cpd15560_c0")
    h = mod.metabolites.get_by_id("cpd00067_c0")
    esp1 = Reaction(id="ESP1", lower_bound=0, upper_bound=1000)
    esp2 = Reaction(id="ESP2", lower_bound=0, upper_bound=1000)
    esp1.add_metabolites({mql: -1, h: 2, mqn: 1})
    esp2.add_metabolites({uql: -1, h: 2, uqn: 1})
    mod.add_reactions([esp1, esp2])
    mod.objective = {esp1: 1, esp2: 1}
    return (mod)