def add_prot_pool_reaction(model: cobra.Model, id_addition: str, p_total: float, p_measured: float, unmeasured_protein_fraction: float, mean_saturation: float) -> cobra.Model: """Adds a protein pool reaction with the given parameters, in accordance with the GECKO paper. The protein pool reaction gets the id 'ER_pool'+id_addition Arguments ---------- * model: cobra.Model ~ The model to which the protein pool reaction shall be added :D * id_addition: str ~ A string that may be added ad the end of the protein pool reaction's id. * p_total: float ~ g/gDW of all proteins per 1 gDW cells * p_measured: float ~ g/gDW of all proteins with measured concentrations. * unmeasured_protein_fraction: float ~ The fraction of the meass of the unmeasured proteins on the total protein mass per gDW cells * mean_saturation: float ~ A fitted value of all unmeasured protein's mean saturation. Output ---------- The given cobra model with a protein pool reaction :D """ # See suppl. data of GECKO paper, equation S28 pp_reaction = cobra.Reaction("ER_pool"+id_addition) pp_reaction.name = "prot_pool reaction for unmeasured proteins" pp_reaction.subsystem = "AutoPACMEN" pp_reaction.lower_bound = 0 pp_reaction.upper_bound = (p_total - p_measured) * unmeasured_protein_fraction * mean_saturation # The flux is in g/gDW prot_pool_metabolite = cobra.Metabolite( "prot_pool", name="prot_pool pseudometabolite for unmeasured proteins", compartment="AutoPACMEN") pp_reaction.add_metabolites({prot_pool_metabolite: 1.0}) model.add_reactions([pp_reaction]) return model, prot_pool_metabolite
def test_model_history(tmp_path): """Testing reading and writing of ModelHistory.""" model = Model("test") model._sbml = { "creators": [{ "familyName": "Mustermann", "givenName": "Max", "organisation": "Muster University", "email": "*****@*****.**", }] } sbml_path = join(str(tmp_path), "test.xml") with open(sbml_path, "w") as f_out: write_sbml_model(model, f_out) with open(sbml_path, "r") as f_in: model2 = read_sbml_model(f_in) assert "creators" in model2._sbml assert len(model2._sbml["creators"]) is 1 c = model2._sbml["creators"][0] assert c["familyName"] == "Mustermann" assert c["givenName"] == "Max" assert c["organisation"] == "Muster University" assert c["email"] == "*****@*****.**"
def fva_prot_pool(model: cobra.Model, pp_upper_bounds: List[float], objective: str = "") -> None: """Performs an FVA for the given protein-constraint-enhanced model with the given protein pools. Output ---------- Standard cobrapy FVA result summaries for each given protein pool. Arguments ---------- * model: cobra.Model ~ The FVAed model as cobrapy Model instance * pp_upper_bounds: List[float] ~ The list of upper protein pool bounds. * objective: str = "" ~ If set, the objecive will be changed to the given term. Otherwise, the standard objective is used. """ for pp_upper_bound in pp_upper_bounds: with model: if objective != "": model.objective = objective model.reactions.get_by_id( "ER_pool_TG_").upper_bound = pp_upper_bound solution = model.optimize() print( f"\sMOMENT-enhanced model, FVA solution for prot_pool upper bound of {pp_upper_bound}:" ) model.summary(fva=1.0) print( abs(solution.fluxes.EX_glc__D_e) / abs(solution.fluxes.EX_ac_e)) model.metabolites.prot_pool.summary()
def test_solve_mip(self): solver = self.solver if not hasattr(solver, "_SUPPORTS_MILP") or not solver._SUPPORTS_MILP: self.skipTest("no milp support") cobra_model = Model('MILP_implementation_test') constraint = Metabolite("constraint") constraint._bound = 2.5 x = Reaction("x") x.lower_bound = 0. x.objective_coefficient = 1. x.add_metabolites({constraint: 2.5}) y = Reaction("y") y.lower_bound = 0. y.objective_coefficient = 1. y.add_metabolites({constraint: 1.}) cobra_model.add_reactions([x, y]) float_sol = solver.solve(cobra_model) # add an integer constraint y.variable_kind = "integer" int_sol = solver.solve(cobra_model) self.assertAlmostEqual(float_sol.f, 2.5) self.assertAlmostEqual(float_sol.x_dict["y"], 2.5) self.assertEqual(int_sol.status, "optimal") self.assertAlmostEqual(int_sol.f, 2.2) self.assertAlmostEqual(int_sol.x_dict["y"], 2.0)
def test_single_reaction_deletion_linear_room( room_model: Model, room_solution: Solution, all_solvers: List[str] ) -> None: """Test single reaction deletion using linear ROOM.""" room_model.solver = all_solvers expected = pd.Series( { "v1": 10.0, "v2": 5.0, "v3": 0.0, "v4": 5.0, "v5": 5.0, "v6": 0.0, "b1": 10.0, "b2": 5.0, "b3": 5.0, }, index=["v1", "v2", "v3", "v4", "v5", "v6", "b1", "b2", "b3"], ) with room_model: room_model.reactions.v6.knock_out() add_room( room_model, solution=room_solution, delta=0.0, epsilon=0.0, linear=True, ) linear_room_sol = room_model.optimize() assert np.allclose(linear_room_sol.fluxes, expected)
def test_fva_minimization(model: Model) -> None: """Test minimization using FVA.""" model.objective = model.reactions.EX_glc__D_e model.objective_direction = "min" solution = flux_variability_analysis(model, fraction_of_optimum=0.95) assert solution.at["EX_glc__D_e", "minimum"] == -10.0 assert solution.at["EX_glc__D_e", "maximum"] == -9.5
def test_change_coefficient(self): solver = self.solver c = Metabolite("c") c._bound = 6 x = Reaction("x") x.lower_bound = 1. y = Reaction("y") y.lower_bound = 0. x.add_metabolites({c: 1}) #y.add_metabolites({c: 1}) z = Reaction("z") z.add_metabolites({c: 1}) z.objective_coefficient = 1 m = Model("test_model") m.add_reactions([x, y, z]) # change an existing coefficient lp = solver.create_problem(m) solver.solve_problem(lp) sol1 = solver.format_solution(lp, m) solver.change_coefficient(lp, 0, 0, 2) solver.solve_problem(lp) sol2 = solver.format_solution(lp, m) self.assertAlmostEqual(sol1.f, 5.0) self.assertAlmostEqual(sol2.f, 4.0) # change a new coefficient z.objective_coefficient = 0. y.objective_coefficient = 1. lp = solver.create_problem(m) solver.change_coefficient(lp, 0, 1, 2) solver.solve_problem(lp) solution = solver.format_solution(lp, m) self.assertAlmostEqual(solution.x_dict["y"], 2.5)
def create_model_from_rxns(name, rxns_d5, objective_rxn_id): model = Model(name) for rxn_d4 in rxns_d5: new_rxn = create_rxn(rxn_d4) model.add_reactions([new_rxn]) model.objective = objective_rxn_id return model
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.objective = "x" self.assertAlmostEqual(solver.solve(m).f, 1.0) self.assertAlmostEqual(solver.solve(m).x_dict["y"], 2.0) m.objective = "y" self.assertAlmostEqual(solver.solve(m).f, 3.0) self.assertAlmostEqual(solver.solve(m, objective_sense="minimize").f, 1.0)
def from_cobra(self, model: cobra.Model, name: str): """Initialize from cobra model.""" # gather prots from by naming convention super().__init__(model.id, name) g_proteins = [ met for met in model.metabolites if met.id.startswith("prot_") ] # gather prots from by SBML group if model.groups.query("Protein"): g_proteins += model.groups.Protein.members g_proteins = set(g_proteins) model.remove_metabolites(g_proteins) self.add_metabolites( [met for met in model.metabolites if met not in g_proteins]) self.add_reactions([ reac for reac in model.reactions if not reac.id.startswith("prot_") ]) self.add_proteins([Protein(prot) for prot in g_proteins]) # point every previous protein Metabolite to an actual Protein object for reac in self.reactions: reac._metabolites = { met if met not in g_proteins else self.proteins.get_by_id( met.id): val for met, val in reac.metabolites.items() } self.__setstate__(self.__dict__) self._populate_solver(self.reactions, self.metabolites, self.proteins)
def swap_from_generic(self, targets: list, components: list, same_components=False, progress_bar_processes_left=1): """ Swap compounds from a generic target and components. The algorithm acts as follows: 1st: Starts for identifying the reactions present in the requested biosynthetic pathway; 2nd: Creates a virtual model; 3rd: Calls the granulator to granulate the biosynthetic pathway; :param list<str> targets: list of lipid targets :param list<str> components: list of components :param bool same_components: boolean for same or mix of components :param int progress_bar_processes_left: :return: """ targets_generic_ontology_id, components_ont_ids = \ self.transform_targets_and_components_into_boimmg_ids(targets,components) self.__virtual_model = Model("virtual_model") self.__add_hydrogen_to_virtual_model() self.__virtual_model_mapper = ModelMapper( self.__virtual_model, self.__compoundsAnnotationConfigs, self.__compoundsIdConverter) self.__virtual_compounds_revisor = CompoundsRevisor( self.__virtual_model, self.__universal_model, self.__compoundsAnnotationConfigs) self.__virtual_compounds_revisor.set_model_mapper( self.__virtual_model_mapper) self.granulator.set_virtual_model(self.__virtual_model, self.__virtual_model_mapper, self.__virtual_compounds_revisor) for target_generic_ontology_id in targets_generic_ontology_id: biosynthesis_reactions = self.granulator.identify_biosynthesis_pathway( target_generic_ontology_id) self.__biosynthesis_reactions = deepcopy(biosynthesis_reactions) self.__add_new_reactions_to_virtual_model( self.__biosynthesis_reactions) self.__model.remove_reactions(biosynthesis_reactions) self.granulator.granulate(target_generic_ontology_id, components_ont_ids, same_components, progress_bar_processes_left) self.generateISAreactions()
def fva_comparison(model_original: cobra.Model, model_smoment: cobra.Model, objective: str = "") -> None: """Compares the original model with the AutoPACMEN model using FVA for 100% of the objective value. The results are printed in the console, and are using cobrapy's FVA summary function. Arguments ---------- * model_original: cobra.Model ~ The original SBML model for which the FVA shall be performed. * model_smoment: cobra.Model ~ The AutoPACMENed model for which an FVA shall be performed. * objective: str = "" ~ An alternative objective for both models. Keep in mind that due to the separation of reversible reactions in the sMOMENTed model, there may be differential reaction names for the raction that you want to be the objective. """ # Set objective if given for the original model :D if objective != "": model_original.objective = objective # Perform and print FVA for the original model :D model_original.optimize() print( "Original model, FVA solution (for 100% of the maximal objective value):" ) model_original.summary(fva=1.0) # Set objective if given for the sMOMENTed model :D if objective != "": model_smoment.objective = objective # Perform and print FVA for the sMOMENTed model :D model_smoment.optimize() print( "\sMOMENT-enhanced model, FVA solution (for 100% of the maximal objective value):" ) model_smoment.summary()
def opposing_model() -> Model: """Generate a toy model with opposing reversible reactions. This toy model ensures that two opposing reversible reactions do not appear as blocked. """ test_model = Model("opposing") v1 = Reaction("v1") v2 = Reaction("v2") v3 = Reaction("v3") v4 = Reaction("v4") test_model.add_reactions([v1, v2, v3, v4]) v1.reaction = "-> 2 A" v2.reaction = "A -> C" # Later made reversible via bounds. v3.reaction = "D -> C" # Later made reversible via bounds. v4.reaction = "D ->" v1.bounds = 0.0, 3.0 v2.bounds = -3.0, 3.0 v3.bounds = -3.0, 3.0 v4.bounds = 0.0, 3.0 test_model.objective = v4 return test_model
def test_room_sanity( model: Model, all_solvers: List[str], linear: bool, delta: float, eps: float ) -> None: """Test optimization criterion and optimality for ROOM.""" model.solver = all_solvers sol = model.optimize() with model: model.reactions.PYK.knock_out() knock_sol = model.optimize() with model: # let it calculate its own reference solution (pFBA) add_room(model, linear=linear, delta=delta, epsilon=eps) model.reactions.PYK.knock_out() room_sol = model.optimize() with model: # use the more distant FBA reference add_room(model, solution=sol, linear=linear, delta=delta, epsilon=eps) model.reactions.PYK.knock_out() room_sol_ref = model.optimize() # The flux_change = (sol.fluxes - knock_sol.fluxes).abs() flux_change_room = (sol.fluxes - room_sol.fluxes).abs() flux_change_room_ref = (sol.fluxes - room_sol_ref.fluxes).abs() rxn_count_naive = (flux_change > delta * sol.fluxes.abs() + eps + 1e-6).sum() rxn_count_room = (flux_change_room > delta * sol.fluxes.abs() + eps + 1e-6).sum() rxn_count_room_ref = ( flux_change_room_ref > delta * sol.fluxes.abs() + eps + 1e-6 ).sum() # Expect the ROOM solution to have less changed reactions then a pFBA or FBA assert rxn_count_room <= rxn_count_naive assert rxn_count_room_ref <= rxn_count_naive
def test_linear_moma_sanity(model: Model, all_solvers: List[str]) -> None: """Test optimization criterion and optimality for linear MOMA.""" model.solver = all_solvers sol = model.optimize() with model: model.reactions.PFK.knock_out() knock_sol = model.optimize() sabs = (knock_sol.fluxes - sol.fluxes).abs().sum() with model: add_moma(model, linear=True) model.reactions.PFK.knock_out() moma_sol = model.optimize() moma_sabs = (moma_sol.fluxes - sol.fluxes).abs().sum() # Use normal FBA as reference solution. with model: add_moma(model, solution=sol, linear=True) model.reactions.PFK.knock_out() moma_ref_sol = model.optimize() moma_ref_sabs = (moma_ref_sol.fluxes - sol.fluxes).abs().sum() assert np.allclose(moma_sol.objective_value, moma_sabs) assert moma_sabs < sabs assert np.isclose(moma_sol.objective_value, moma_ref_sol.objective_value) assert np.isclose(moma_sabs, moma_ref_sabs) with model: add_moma(model, linear=True) with pytest.raises(ValueError): add_moma(model)
def test_moma_sanity(model: Model, qp_solvers: List[str]) -> None: """Test optimization criterion and optimality for MOMA.""" model.solver = qp_solvers sol = model.optimize() with model: model.reactions.PFK.knock_out() knock_sol = model.optimize() ssq = (knock_sol.fluxes - sol.fluxes).pow(2).sum() with model: add_moma(model, linear=False) model.reactions.PFK.knock_out() moma_sol = model.optimize() moma_ssq = (moma_sol.fluxes - sol.fluxes).pow(2).sum() # Use normal FBA as reference solution. with model: add_moma(model, solution=sol, linear=False) model.reactions.PFK.knock_out() moma_ref_sol = model.optimize() moma_ref_ssq = (moma_ref_sol.fluxes - sol.fluxes).pow(2).sum() assert np.isclose(moma_sol.objective_value, moma_ssq) assert moma_ssq < ssq assert np.isclose(moma_sol.objective_value, moma_ref_sol.objective_value) assert np.isclose(moma_ssq, moma_ref_ssq)
def minimized_shuffle(small_model): model = small_model.copy() chosen = sample(list(set(model.reactions) - set(model.exchanges)), 10) new = Model("minimized_shuffle") new.add_reactions(chosen) LOGGER.debug("'%s' has %d metabolites, %d reactions, and %d genes.", new.id, new.metabolites, new.reactions, new.genes) return new
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
def __init__(self, model, name): """ Very much model specific """ Model.__init__(self, model.copy(), name) self._cons_queue = list() self._var_queue = list()
def remove_reactions(self, reactions, remove_orphans=False): # Remove the constraints and variables associated to these reactions all_cons_subclasses = get_all_subclasses(ReactionConstraint) all_var_subclasses = get_all_subclasses(ReactionVariable) self._remove_associated_consvar(all_cons_subclasses, all_var_subclasses, reactions) Model.remove_reactions(self, reactions, remove_orphans)
def remove_metabolites(self, metabolite_list, destructive=False): # Remove the constraints and variables associated to these reactions all_cons_subclasses = get_all_subclasses(MetaboliteConstraint) all_var_subclasses = get_all_subclasses(MetaboliteVariable) self._remove_associated_consvar(all_cons_subclasses, all_var_subclasses, metabolite_list) Model.remove_metabolites(self, metabolite_list, destructive)
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
def repair(self): """ Updates references to variables and constraints :return: """ # self.add_cons_vars([x.constraint for x in self._cons_dict.values()]) # self.add_cons_vars([x.variable for x in self._var_dict.values()]) Model.repair(self) self.regenerate_constraints() self.regenerate_variables()
def setUp(self): self.model = Model("test model") A = Metabolite("A") r = Reaction("r") r.add_metabolites({A: -1}) r.lower_bound = -1000 r.upper_bound = 1000 self.model.add_reaction(r) convert_to_irreversible(self.model) self.model.remove_reactions(["r"])
def restore_reaction_by_json(cobra_model: cobra.Model, info: Dict[str, Any]) -> cobra.Reaction: reaction = cobra.Reaction(id=info['cobra_id'], name=info['name'], subsystem=info['subsystem'], lower_bound=info['lower_bound'], upper_bound=info['upper_bound']) cobra_model.add_reactions([reaction]) reaction.gene_reaction_rule = info['gene_reaction_rule'] return reaction
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
def get_reference(mod, newR, delete_unbalanced, verbose=1): from cobra import Model, Reaction, Metabolite import pandas import re import os dir = os.path.dirname(__file__) seedmDB = pandas.read_csv(dir + "/../dat/seed_metabolites.tsv", sep="\t") seedrDB = pandas.read_csv(dir + "/../dat/seed_reactions.tsv", sep="\t") #refdb = seedrDB.loc[seedrDB['abbreviation'].isin(newR)] # vmh refdb = seedrDB.loc[(seedrDB['id'].isin(newR)) & (seedrDB['status'] == "OK" )] # only choose reaction which have status okay 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").replace("[2]", "_m0") r.build_reaction_from_string(rstr, verbose=0) #r.reaction = rstr for m in refmod.metabolites: if verbose == 2: print m.id 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] if verbose > 0: print Calready, "reactions already in the model" print Cold, "removed deprecated reactions" refmod = repair_mass_balance(refmod, delete_unbalanced, verbose) if verbose > 0: print len( refmod.reactions), "remaining reaction in reference database:", return (refmod)
def model(request, solver): if request.param == "empty": model = Model(id_or_model=request.param, name=request.param) elif request.param == "textbook": model = read_sbml_model(join(dirname(__file__), "data", "EcoliCore.xml.gz")) else: builder = getattr(request.module, "MODEL_REGISTRY")[request.param] model = builder(Model(id_or_model=request.param, name=request.param)) model.solver = solver return model
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)
def createDict(file): Universal = Model("Universal Reactions") f = open('file', 'r') rxn_dict = {} for line in f: rxn_items = line.split('\t') rxn_dict[rxn_items[0]] = rxn_items[2] for rxnName in rxn_dict.keys(): rxn = Reaction(rxnName) Universal.add_reaction(rxn) rxn.reaction = rxn_dict[rxnName] return Universal
def test_quadratic(self): solver = self.solver if not hasattr(solver, "set_quadratic_objective"): self.skipTest("no qp support") c = Metabolite("c") c._bound = 2 x = Reaction("x") x.objective_coefficient = -0.5 x.lower_bound = 0. y = Reaction("y") y.objective_coefficient = -0.5 y.lower_bound = 0. x.add_metabolites({c: 1}) y.add_metabolites({c: 1}) m = Model() m.add_reactions([x, y]) lp = self.solver.create_problem(m) quadratic_obj = scipy.sparse.eye(2) * 2 solver.set_quadratic_objective(lp, quadratic_obj) solver.solve_problem(lp, objective_sense="minimize") solution = solver.format_solution(lp, m) self.assertEqual(solution.status, "optimal") # Respecting linear objectives also makes the objective value 1. self.assertAlmostEqual(solution.f, 1.) self.assertAlmostEqual(solution.x_dict["y"], 1.) self.assertAlmostEqual(solution.x_dict["y"], 1.) # When the linear objectives are removed the objective value is 2. solver.change_variable_objective(lp, 0, 0.) solver.change_variable_objective(lp, 1, 0.) solver.solve_problem(lp, objective_sense="minimize") solution = solver.format_solution(lp, m) self.assertEqual(solution.status, "optimal") self.assertAlmostEqual(solution.f, 2.) # test quadratic from solve function solution = solver.solve(m, quadratic_component=quadratic_obj, objective_sense="minimize") self.assertEqual(solution.status, "optimal") self.assertAlmostEqual(solution.f, 1.) c._bound = 6 z = Reaction("z") x.objective_coefficient = 0. y.objective_coefficient = 0. z.lower_bound = 0. z.add_metabolites({c: 1}) m.add_reaction(z) solution = solver.solve(m, quadratic_component=scipy.sparse.eye(3), objective_sense="minimize") # should be 12 not 24 because 1/2 (V^T Q V) self.assertEqual(solution.status, "optimal") self.assertAlmostEqual(solution.f, 6) self.assertAlmostEqual(solution.x_dict["x"], 2, places=6) self.assertAlmostEqual(solution.x_dict["y"], 2, places=6) self.assertAlmostEqual(solution.x_dict["z"], 2, places=6)
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
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)
def setUp(self): self.solver = solvers.solver_dict[self.solver_name] self.model = create_test_model() self.old_solution = 0.380008 self.infeasible_model = Model() metabolite_1 = Metabolite("met1") reaction_1 = Reaction("rxn1") reaction_2 = Reaction("rxn2") reaction_1.add_metabolites({metabolite_1: 1}) reaction_2.add_metabolites({metabolite_1: 1}) reaction_1.lower_bound = 1 reaction_2.upper_bound = 2 self.infeasible_model.add_reactions([reaction_1, reaction_2])
def cobra_model(self, name, reversible=True, bound=1000): """Constructs a cobra model for the reconstruction. Args: name (str): The name of the cobra model. reversible (Optiona[bool]): Whether the returned model should be reversible. Default is yes. bound (Optional[float]): The default flux bound for the reactions. Returns: A cobra model containing the reconstruction. The original objective will be conserved if it is still included in the model. """ new_mod = Model(name) m = deepcopy(self.model) for rid in self.conf: r = m.reactions.get_by_id(rid) if self.conf[rid] == 3 and "mock" not in r.notes: if r not in new_mod.reactions: r.upper_bound = bound new_mod.add_reaction(r) if "reflection" in r.notes: rev = m.reactions.get_by_id(r.notes["reflection"]) if rev not in new_mod.reactions: rev.upper_bound = bound new_mod.add_reaction(rev) if reversible: revert_to_reversible(new_mod) still_valid = True for r in self.objective: still_valid &= (self.conf[r.id] == 3) if still_valid: new_mod.change_objective(self.objective) return new_mod
class TestCobraSolver(TestCase): 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])
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'})
def test_loopless(self): try: solver = get_solver_name(mip=True) except: self.skipTest("no MILP solver found") test_model = Model() test_model.add_metabolites(Metabolite("A")) test_model.add_metabolites(Metabolite("B")) test_model.add_metabolites(Metabolite("C")) EX_A = Reaction("EX_A") EX_A.add_metabolites({test_model.metabolites.A: 1}) DM_C = Reaction("DM_C") DM_C.add_metabolites({test_model.metabolites.C: -1}) v1 = Reaction("v1") v1.add_metabolites({test_model.metabolites.A: -1, test_model.metabolites.B: 1}) v2 = Reaction("v2") v2.add_metabolites({test_model.metabolites.B: -1, test_model.metabolites.C: 1}) v3 = Reaction("v3") v3.add_metabolites({test_model.metabolites.C: -1, test_model.metabolites.A: 1}) DM_C.objective_coefficient = 1 test_model.add_reactions([EX_A, DM_C, v1, v2, v3]) feasible_sol = construct_loopless_model(test_model).optimize() v3.lower_bound = 1 infeasible_sol = construct_loopless_model(test_model).optimize() self.assertEqual(feasible_sol.status, "optimal") self.assertEqual(infeasible_sol.status, "infeasible")
def model(): A = Metabolite("A") B = Metabolite("B") C = Metabolite("C") r1 = Reaction("r1") r1.add_metabolites({A: -1, C: 1}) r2 = Reaction("r2") r2.add_metabolites({B: -1, C: 1}) r3 = Reaction("EX_A") r3.add_metabolites({A: 1}) r4 = Reaction("EX_B") r4.add_metabolites({B: 1}) r5 = Reaction("EX_C") r5.add_metabolites({C: -1}) mod = Model("test model") mod.add_reactions([r1, r2, r3, r4, r5]) conf = {"r1": 1, "r2": -1, "EX_A": 1, "EX_B": 1, "EX_C": 1} return (mod, conf)
def test_solve_mip(self): solver = self.solver cobra_model = Model('MILP_implementation_test') constraint = Metabolite("constraint") constraint._bound = 2.5 x = Reaction("x") x.lower_bound = 0. x.objective_coefficient = 1. x.add_metabolites({constraint: 2.5}) y = Reaction("y") y.lower_bound = 0. y.objective_coefficient = 1. y.add_metabolites({constraint: 1.}) cobra_model.add_reactions([x, y]) float_sol = solver.solve(cobra_model) # add an integer constraint y.variable_kind = "integer" int_sol = solver.solve(cobra_model) self.assertAlmostEqual(float_sol.f, 2.5) self.assertAlmostEqual(float_sol.x_dict["y"], 2.5) self.assertAlmostEqual(int_sol.f, 2.2) self.assertAlmostEqual(int_sol.x_dict["y"], 2.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])
def test_remove_genes(self): m = Model("test") m.add_reactions([Reaction("r" + str(i + 1)) for i in range(8)]) self.assertEqual(len(m.reactions), 8) rxns = m.reactions rxns.r1.gene_reaction_rule = "(a and b) or (c and a)" rxns.r2.gene_reaction_rule = "(a and b and d and e)" rxns.r3.gene_reaction_rule = "(a and b) or (b and c)" rxns.r4.gene_reaction_rule = "(f and b) or (b and c)" rxns.r5.gene_reaction_rule = "x" rxns.r6.gene_reaction_rule = "y" rxns.r7.gene_reaction_rule = "x or z" rxns.r8.gene_reaction_rule = "" self.assertIn("a", m.genes) self.assertIn("x", m.genes) delete.remove_genes(m, ["a"], remove_reactions=False) self.assertNotIn("a", m.genes) self.assertIn("x", m.genes) self.assertEqual(rxns.r1.gene_reaction_rule, "") self.assertEqual(rxns.r2.gene_reaction_rule, "") self.assertEqual(rxns.r3.gene_reaction_rule, "b and c") self.assertEqual(rxns.r4.gene_reaction_rule, "(f and b) or (b and c)") self.assertEqual(rxns.r5.gene_reaction_rule, "x") self.assertEqual(rxns.r6.gene_reaction_rule, "y") self.assertEqual(rxns.r7.genes, {m.genes.x, m.genes.z}) self.assertEqual(rxns.r8.gene_reaction_rule, "") delete.remove_genes(m, ["x"], remove_reactions=True) self.assertEqual(len(m.reactions), 7) self.assertNotIn("r5", m.reactions) self.assertNotIn("x", m.genes) self.assertEqual(rxns.r1.gene_reaction_rule, "") self.assertEqual(rxns.r2.gene_reaction_rule, "") self.assertEqual(rxns.r3.gene_reaction_rule, "b and c") self.assertEqual(rxns.r4.gene_reaction_rule, "(f and b) or (b and c)") self.assertEqual(rxns.r6.gene_reaction_rule, "y") self.assertEqual(rxns.r7.gene_reaction_rule, "z") self.assertEqual(rxns.r7.genes, {m.genes.z}) self.assertEqual(rxns.r8.gene_reaction_rule, "")
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])
def build_model(): m = Model("Blazier et al 2012") m1_e = Metabolite("M1_e") m1 = Metabolite("M1") m2 = Metabolite("M2") m3 = Metabolite("M3") m4_e = Metabolite("M4_e") m4 = Metabolite("M4") m5 = Metabolite("M5") r1 = Reaction("R1") r1.add_metabolites({m1_e: -1, m1: 1}) r2 = Reaction("R2") r2.add_metabolites({m1: -1, m2: 1}) r2.gene_reaction_rule = "Gene2" r3 = Reaction("R3") r3.add_metabolites({m2: -1, m3: 1}) r3.gene_reaction_rule = "Gene3" r4 = Reaction("R4") r4.add_metabolites({m3: -1}) r5 = Reaction("R5") r5.add_metabolites({m4_e: -1, m4: 1}) r6 = Reaction("R6") r6.add_metabolites({m4: -1, m5: 1}) r6.gene_reaction_rule = "Gene6" r7 = Reaction("R7") r7.add_metabolites({m5: -1, m2: 1}) r7.lower_bound = -r7.upper_bound r7.gene_reaction_rule = "Gene7" r8 = Reaction("R8") r8.add_metabolites({m5: -1}) m.add_reactions([r1, r2, r3, r4, r5, r6, r7, r8]) EX_M1_e = m.add_boundary(m1_e) EX_M1_e.lower_bound = -10 EX_M4_e = m.add_boundary(m4_e) EX_M4_e.lower_bound = -10 m.objective = r4 return m
###Date Last Modified: May 25, 2016 ###Contributors: Fahim, Zakary, Heba, Mike # import these things from cobra import Model, Reaction, Metabolite, Gene import cobra.test import os import copy from os.path import join # create new model from sbml file print("importing the existing the ecoli model...") eco = cobra.io.sbml.create_cobra_model_from_sbml_file("/home/protoxpire0/Documents/igem/Gol_FBA/msb201165-s3.xml",old_sbml=False,legacy_metabolite=False,print_time=False,use_hyphens=False) print("Creating new_model...") new_model = Model('new_model') print("Adding compartment 'a' for 'all'...") new_model.compartments['a'] = 'all' #Adding all metabolites from existing model removing duplications print("Adding all metabolites from existing model removing duplications...") for x in eco.metabolites: dup = False for y in new_model.metabolites: if x.id[:-2] == y.id: dup = True break if dup == False: met = copy.deepcopy(x) met.id = met.id[:-2]+'_a'
print(('Cones cost me $%1.2f to produce.'%(cone_production_cost))) print(('I can sell popsicles for $%1.2f.'%(popsicle_selling_price))) print(('Popsicles cost me $%1.2f to produce.'%(popsicle_production_cost))) print(('My total budget was capped at $%1.2f today.'%(starting_budget))) # problem is: # max profit # s.t. # cone_production_cost*cone_production + popsidle_production_cost*popsicle_production <= starting_budget # number of cones and popsicles has to be integer... # first, we'll solve the continuous case just to make sure everything is # working (it should only make cones)...then we'll tighten the constraints to # integer... and it should make popsicles. cobra_model = Model('MILP_implementation_test') cone_out = Metabolite(id='cone_out', compartment='c') cone_in = Metabolite(id='cone_in', compartment='c') cone_consumed = Metabolite(id='cone_consumed', compartment='c') popsicle_out = Metabolite(id='popsicle_out', compartment='c') popsicle_in = Metabolite(id='popsicle_in', compartment='c') popsicle_consumed = Metabolite(id='popsicle_consumed', compartment='c') the_reactions = [] # SOURCE Cone_source = Reaction(name='Cone_source') temp_metabolite_dict = {cone_out: 1} Cone_source.add_metabolites(temp_metabolite_dict) the_reactions.append(Cone_source)
def create_modelFromReactionsAndMetabolitesTables(self,rxns_table_I,mets_table_I): '''generate a cobra model from isotopomer_modelReactions and isotopomer_modelMetabolites tables''' cobra_model = Model(rxns_table_I[0]['model_id']); for rxn_cnt,rxn_row in enumerate(rxns_table_I): #if rxn_row['rxn_id'] == 'HEX1': # print 'check' mets = {} print(rxn_row['rxn_id']) # parse the reactants for rxn_met_cnt,rxn_met in enumerate(rxn_row['reactants_ids']): for met_cnt,met_row in enumerate(mets_table_I): if met_row['met_id']==rxn_met:# and met_row['balanced']: compartment = met_row['compartment'] if not compartment: met_id_tmp = met_row['met_id'].split('.')[0] compartment = met_id_tmp.split('_')[-1]; met_tmp = Metabolite(met_row['met_id'],met_row['formula'],met_row['met_name'],compartment) met_tmp.charge = met_row['charge'] # check for duplicate metabolites met_keys = list(mets.keys()); met_keys_ids = {}; if met_keys: for cnt,met in enumerate(met_keys): met_keys_ids[met.id]=cnt; if met_tmp.id in list(met_keys_ids.keys()): mets[met_keys[met_keys_ids[met_tmp.id]]]-=1 else: mets[met_tmp] = rxn_row['reactants_stoichiometry'][rxn_met_cnt]; break; # parse the products for rxn_met_cnt,rxn_met in enumerate(rxn_row['products_ids']): for met_cnt,met_row in enumerate(mets_table_I): if met_row['met_id']==rxn_met:# and met_row['balanced']: compartment = met_row['compartment'] if not compartment: met_id_tmp = met_row['met_id'].split('.')[0] compartment = met_id_tmp.split('_')[-1]; met_tmp = Metabolite(met_row['met_id'],met_row['formula'],met_row['met_name'],compartment) met_tmp.charge = met_row['charge'] # check for duplicate metabolites met_keys = list(mets.keys()); met_keys_ids = {}; if met_keys: for cnt,met in enumerate(met_keys): met_keys_ids[met.id]=cnt; if met_tmp.id in list(met_keys_ids.keys()): mets[met_keys[met_keys_ids[met_tmp.id]]]+=1 else: mets[met_tmp] = rxn_row['products_stoichiometry'][rxn_met_cnt]; break; rxn = None; rxn = Reaction(rxn_row['rxn_id']); rxn.add_metabolites(mets); rxn.lower_bound=rxn_row['lower_bound']; rxn.upper_bound=rxn_row['upper_bound']; rxn.subsystem=rxn_row['subsystem']; rxn.gpr=rxn_row['gpr']; rxn.objective_coefficient=rxn_row['objective_coefficient']; cobra_model.add_reactions([rxn]); cobra_model.repair(); return cobra_model
def solve_mip(self): cone_selling_price = 7.0 cone_production_cost = 3.0 popsicle_selling_price = 2.0 popsicle_production_cost = 1.0 starting_budget = 100.0 cobra_model = Model("MILP_implementation_test") cone_out = Metabolite(id="cone_out", compartment="c") cone_in = Metabolite(id="cone_in", compartment="c") cone_consumed = Metabolite(id="cone_consumed", compartment="c") popsicle_out = Metabolite(id="popsicle_out", compartment="c") popsicle_in = Metabolite(id="popsicle_in", compartment="c") popsicle_consumed = Metabolite(id="popsicle_consumed", compartment="c") the_reactions = [] # SOURCE Cone_source = Reaction(name="Cone_source") temp_metabolite_dict = {cone_out: 1} Cone_source.add_metabolites(temp_metabolite_dict) the_reactions.append(Cone_source) Popsicle_source = Reaction(name="Popsicle_source") temp_metabolite_dict = {popsicle_out: 1} Popsicle_source.add_metabolites(temp_metabolite_dict) the_reactions.append(Popsicle_source) ## PRODUCTION Cone_production = Reaction(name="Cone_production") temp_metabolite_dict = {cone_out: -1, cone_in: 1} Cone_production.add_metabolites(temp_metabolite_dict) the_reactions.append(Cone_production) Popsicle_production = Reaction(name="Popsicle_production") temp_metabolite_dict = {popsicle_out: -1, popsicle_in: 1} Popsicle_production.add_metabolites(temp_metabolite_dict) the_reactions.append(Popsicle_production) ## CONSUMPTION Cone_consumption = Reaction(name="Cone_consumption") temp_metabolite_dict = {cone_in: -1, cone_consumed: 1} Cone_consumption.add_metabolites(temp_metabolite_dict) the_reactions.append(Cone_consumption) Popsicle_consumption = Reaction(name="Popsicle_consumption") temp_metabolite_dict = {popsicle_in: -1, popsicle_consumed: 1} Popsicle_consumption.add_metabolites(temp_metabolite_dict) the_reactions.append(Popsicle_consumption) # SINK Cone_consumed_sink = Reaction(name="Cone_consumed_sink") temp_metabolite_dict = {cone_consumed: -1} Cone_consumed_sink.add_metabolites(temp_metabolite_dict) the_reactions.append(Cone_consumed_sink) Popsicle_consumed_sink = Reaction(name="Popsicle_consumed_sink") temp_metabolite_dict = {popsicle_consumed: -1} Popsicle_consumed_sink.add_metabolites(temp_metabolite_dict) the_reactions.append(Popsicle_consumed_sink) ## add all reactions cobra_model.add_reactions(the_reactions) # set objective coefficients Cone_consumption.objective_coefficient = cone_selling_price Popsicle_consumption.objective_coefficient = popsicle_selling_price Cone_production.objective_coefficient = -1 * cone_production_cost Popsicle_production.objective_coefficient = -1 * popsicle_production_cost # Make sure we produce whole cones Cone_production.variable_kind = "integer" Popsicle_production.variable_kind = "integer" production_capacity_constraint = Metabolite(id="production_capacity_constraint") production_capacity_constraint._constraint_sense = "L" production_capacity_constraint._bound = starting_budget Cone_production.add_metabolites({production_capacity_constraint: cone_production_cost}) Popsicle_production.add_metabolites({production_capacity_constraint: popsicle_production_cost}) cobra_model.optimize(solver=solver_name) self.assertEqual(133, cobra_model.solution.f) self.assertEqual(33, cobra_model.solution.x_dict["Cone_consumption"])
cone = Reaction("cone") popsicle = Reaction("popsicle") # constrainted to a budget budget = Metabolite("budget") budget._constraint_sense = "L" budget._bound = starting_budget cone.add_metabolites({budget: cone_production_cost}) popsicle.add_metabolites({budget: popsicle_production_cost}) # objective coefficient is the profit to be made from each unit cone.objective_coefficient = cone_selling_price - cone_production_cost popsicle.objective_coefficient = popsicle_selling_price - \ popsicle_production_cost m = Model("lerman_ice_cream_co") m.add_reactions((cone, popsicle)) m.optimize().x_dict # Output: # {'cone': 33.333333333333336, 'popsicle': 0.0} # In reality, cones and popsicles can only be sold in integer amounts. We can # use the variable kind attribute of a cobra.Reaction to enforce this. cone.variable_kind = "integer" popsicle.variable_kind = "integer" m.optimize().x_dict # Output: # {'cone': 33.0, 'popsicle': 1.0}
from cobra.io.sbml import create_cobra_model_from_sbml_file from cobra import Model, Reaction, flux_analysis from copy import deepcopy mattModel = create_cobra_model_from_sbml_file("2016_06_23_gapped_meoh_producing.xml") Universal = Model("Universal Reactions") f = open('2015_test_db_2.txt', 'r') def uniq(lst): last = object() for item in lst: if item == last: continue yield item last = item def sort_and_deduplicate(l): return list(uniq(sorted(l, reverse=True))) rxn_dict = {} for line in f: rxn_items = line.split('\t') rxn_dict[rxn_items[0]] = rxn_items[2] for rxnName in rxn_dict.keys(): rxn = Reaction(rxnName) Universal.add_reaction(rxn) rxn.reaction = rxn_dict[rxnName] growthValue = [] its = 4
from cobra import Model, Reaction, Metabolite cobra_model = Model('firstModel') reaction = Reaction('3OAS140') reaction.name = '3 oxoacyl carrier protein synthase n C140' reaction.subsystem = 'Cell Envelope Biosynthesis' ACP_c = Metabolite( 'ACP_c', formula='C11H21N2O7PRS', name='acyl-carrier-protein', compartment='c') omrsACP_c = Metabolite( '3omrsACP_c', formula='C25H45N2O9PRS', name='3-Oxotetradecanoyl-acyl-carrier-protein', compartment='c') co2_c = Metabolite( 'co2_c', formula='CO2', name='CO2', compartment='c') malACP_c = Metabolite( 'malACP_c', formula='C14H22N2O10PRS', name='Malonyl-acyl-carrier-protein', compartment='c') h_c = Metabolite( 'h_c', formula='H',
def test_gene_knockout_computation(self): cobra_model = create_test_model() # helper functions for running tests delete_model_genes = delete.delete_model_genes find_gene_knockout_reactions = delete.find_gene_knockout_reactions def find_gene_knockout_reactions_fast(cobra_model, gene_list): compiled_rules = delete.get_compiled_gene_reaction_rules( cobra_model) return find_gene_knockout_reactions( cobra_model, gene_list, compiled_gene_reaction_rules=compiled_rules) def get_removed(m): return {x.id for x in m._trimmed_reactions} def test_computation(m, gene_ids, expected_reaction_ids): genes = [m.genes.get_by_id(i) for i in gene_ids] expected_reactions = {m.reactions.get_by_id(i) for i in expected_reaction_ids} removed1 = set(find_gene_knockout_reactions(m, genes)) removed2 = set(find_gene_knockout_reactions_fast(m, genes)) self.assertEqual(removed1, expected_reactions) self.assertEqual(removed2, expected_reactions) delete.delete_model_genes(m, gene_ids, cumulative_deletions=False) self.assertEqual(get_removed(m), expected_reaction_ids) delete.undelete_model_genes(m) gene_list = ['STM1067', 'STM0227'] dependent_reactions = {'3HAD121', '3HAD160', '3HAD80', '3HAD140', '3HAD180', '3HAD100', '3HAD181', '3HAD120', '3HAD60', '3HAD141', '3HAD161', 'T2DECAI', '3HAD40'} test_computation(cobra_model, gene_list, dependent_reactions) test_computation(cobra_model, ['STM4221'], {'PGI'}) test_computation(cobra_model, ['STM1746.S'], {'4PEPTabcpp'}) # test cumulative behavior delete_model_genes(cobra_model, gene_list[:1]) delete_model_genes(cobra_model, gene_list[1:], cumulative_deletions=True) delete_model_genes(cobra_model, ["STM4221"], cumulative_deletions=True) dependent_reactions.add('PGI') self.assertEqual(get_removed(cobra_model), dependent_reactions) # non-cumulative following 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) test_computation(test_model, ["eggs"], set()) test_computation(test_model, ["eggs", "spam"], {'test1'}) # test computation with nested boolean expression test_reaction_1.gene_reaction_rule = \ "g1 and g2 and (g3 or g4 or (g5 and g6))" test_computation(test_model, ["g3"], set()) test_computation(test_model, ["g1"], {'test1'}) test_computation(test_model, ["g5"], set()) test_computation(test_model, ["g3", "g4", "g5"], {'test1'}) # test computation when gene names are python expressions test_reaction_1.gene_reaction_rule = "g1 and (for or in)" test_computation(test_model, ["for", "in"], {'test1'}) test_computation(test_model, ["for"], set()) test_reaction_1.gene_reaction_rule = "g1 and g2 and g2.conjugate" test_computation(test_model, ["g2"], {"test1"}) test_computation(test_model, ["g2.conjugate"], {"test1"}) test_reaction_1.gene_reaction_rule = "g1 and (try:' or 'except:1)" test_computation(test_model, ["try:'"], set()) test_computation(test_model, ["try:'", "'except:1"], {"test1"})
def test_gapfilling(self): try: solver = get_solver_name(mip=True) except: self.skipTest("no MILP solver found") m = Model() m.add_metabolites(map(Metabolite, ["a", "b", "c"])) r = Reaction("EX_A") m.add_reaction(r) r.add_metabolites({m.metabolites.a: 1}) r = Reaction("r1") m.add_reaction(r) r.add_metabolites({m.metabolites.b: -1, m.metabolites.c: 1}) r = Reaction("DM_C") m.add_reaction(r) r.add_metabolites({m.metabolites.c: -1}) r.objective_coefficient = 1 U = Model() r = Reaction("a2b") U.add_reaction(r) r.build_reaction_from_string("a --> b", verbose=False) r = Reaction("a2d") U.add_reaction(r) r.build_reaction_from_string("a --> d", verbose=False) # GrowMatch result = gapfilling.growMatch(m, U)[0] self.assertEqual(len(result), 1) self.assertEqual(result[0].id, "a2b") # SMILEY result = gapfilling.SMILEY(m, "b", U)[0] self.assertEqual(len(result), 1) self.assertEqual(result[0].id, "a2b") # 2 rounds of GrowMatch with exchange reactions result = gapfilling.growMatch(m, None, ex_rxns=True, iterations=2) self.assertEqual(len(result), 2) self.assertEqual(len(result[0]), 1) self.assertEqual(len(result[1]), 1) self.assertEqual({i[0].id for i in result}, {"SMILEY_EX_b", "SMILEY_EX_c"})
def build_model(): m = Model("Zur et al 2012") m1 = Metabolite("M1") m2 = Metabolite("M2") m3 = Metabolite("M3") m4 = Metabolite("M4") m5 = Metabolite("M5") m6 = Metabolite("M6") m7 = Metabolite("M7") m8 = Metabolite("M8") m9 = Metabolite("M9") m10 = Metabolite("M10") r1 = Reaction("R1") r1.add_metabolites({m3: 1}) r2 = Reaction("R2") r2.add_metabolites({m1: 1}) r2.gene_reaction_rule = "G1 or G2" r3 = Reaction("R3") r3.add_metabolites({m2: 1}) r3.gene_reaction_rule = "G5" r4 = Reaction("R4") r4.add_metabolites({m1: -1, m10: 1}) r4.lower_bound = -r4.upper_bound r5 = Reaction("R5") r5.add_metabolites({m10: -1, m4: 1}) r5.lower_bound = -r5.upper_bound r6 = Reaction("R6") r6.add_metabolites({m1: -1, m4: 1}) r7 = Reaction("R7") r7.add_metabolites({m1: -1, m2: -1, m5: 1, m6: 1}) r7.gene_reaction_rule = "G6" r8 = Reaction("R8") r8.add_metabolites({m3: -1, m4: -1, m7: 1, m8: 1}) r8.gene_reaction_rule = "G3" r9 = Reaction("R9") r9.add_metabolites({m5: -1}) r10 = Reaction("R10") r10.add_metabolites({m6: -1, m9: 1}) r10.gene_reaction_rule = "G7" r11 = Reaction("R11") r11.add_metabolites({m7: -1}) r12 = Reaction("R12") r12.add_metabolites({m8: -1}) r12.gene_reaction_rule = "G4" r13 = Reaction("R13") r13.add_metabolites({m9: -1}) m.add_reactions([r1, r2, r3, r4, r5, r6, r7, r8]) m.objective = r4 return m
# We need to use a solver that supports quadratic programming, such as gurobi # or cplex. If a solver which supports quadratic programming is installed, this # function will return its name. print(solvers.get_solver_name(qp=True)) # Prints: # gurobi c = Metabolite("c") c._bound = 2 x = Reaction("x") y = Reaction("y") x.add_metabolites({c: 1}) y.add_metabolites({c: 1}) m = Model() m.add_reactions([x, y]) sol = m.optimize(quadratic_component=Q, objective_sense="minimize") sol.x_dict # Output: # {'x': 1.0, 'y': 1.0} # Suppose we change the problem to have a mixed linear and quadratic objective. # # > **min** $\frac{1}{2}\left(x^2 + y^2 \right) - y$ # # > *subject to* # # > $x + y = 2$ # # > $x \ge 0$