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
def isotopomer_model_iteration1(): '''iteration 1: identification of reactions that can be lumped in pathways outside the model scope''' cobra_model = load_ALEWt(); # Make the model irreversible for downstream manipulations: convert_to_irreversible(cobra_model); # Add lumped isotopomer reactions add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible); # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi'); # Write pfba solution to file with open('data\\iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Flux']) for k,v in cobra_model.solution.x_dict.items(): writer.writerow([k,v]); # Read in pfba solution pfba_sol = {}; with open('data\\iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='r') as infile: dictreader = csv.DictReader(infile) for r in dictreader: pfba_sol[r['Reaction']] = r['Flux']; # Make net reactions for pathways outside of the scope # of the isotopomer model subs = ['Cell Envelope Biosynthesis', 'Glycerophospholipid Metabolism', 'Lipopolysaccharide Biosynthesis / Recycling', 'Membrane Lipid Metabolism', 'Murein Biosynthesis' 'Murein Recycling', 'Cofactor and Prosthetic Group Biosynthesis', #'Transport, Inner Membrane', #'Transport, Outer Membrane', #'Transport, Outer Membrane Porin', 'tRNA Charging', 'Unassigned', 'Exchange', 'Inorganic Ion Transport and Metabolism', 'Nitrogen Metabolism']; add_net_reaction_subsystem(cobra_model,pfba_sol,subs); remove_noflux_reactions(cobra_model,pfba_sol,['Transport, Outer Membrane Porin','Transport, Inner Membrane','Transport, Outer Membrane']) revert_to_reversible(cobra_model); # write model to sbml write_cobra_model_to_sbml_file(cobra_model,'data\\iteration1_140407_ijo1366_netrxn_irreversible.xml') # Reduce model using FVA: reduce_model(cobra_model,"data\\iteration1_140407_ijo1366_reduced.xml") # Remove all reactions with 0 flux remove_noflux_reactions(cobra_model); with open('data\\iteration1_140407_ijo1366_reduced_netrxn_lbub.csv',mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Formula','LB','UB','Subsystem']) for r in cobra_model.reactions: writer.writerow([r.id, r.build_reaction_string(), r.lower_bound, r.upper_bound, r.subsystem]);
def isotopomer_model_iteration1(): '''iteration 1: identification of reactions that can be lumped in pathways outside the model scope''' cobra_model = load_ALEWt(); # Make the model irreversible for downstream manipulations: convert_to_irreversible(cobra_model); # Add lumped isotopomer reactions add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible); # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi'); # Write pfba solution to file with open('data/iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Flux']) for k,v in cobra_model.solution.x_dict.items(): writer.writerow([k,v]); # Read in pfba solution pfba_sol = {}; with open('data/iteration1_140407_ijo1366_reduced_modified_pfba.csv',mode='r') as infile: dictreader = csv.DictReader(infile) for r in dictreader: pfba_sol[r['Reaction']] = r['Flux']; # Make net reactions for pathways outside of the scope # of the isotopomer model subs = ['Cell Envelope Biosynthesis', 'Glycerophospholipid Metabolism', 'Lipopolysaccharide Biosynthesis / Recycling', 'Membrane Lipid Metabolism', 'Murein Biosynthesis' 'Murein Recycling', 'Cofactor and Prosthetic Group Biosynthesis', #'Transport, Inner Membrane', #'Transport, Outer Membrane', #'Transport, Outer Membrane Porin', 'tRNA Charging', 'Unassigned', 'Exchange', 'Inorganic Ion Transport and Metabolism', 'Nitrogen Metabolism']; add_net_reaction_subsystem(cobra_model,pfba_sol,subs); remove_noflux_reactions(cobra_model,pfba_sol,['Transport, Outer Membrane Porin','Transport, Inner Membrane','Transport, Outer Membrane']) revert_to_reversible(cobra_model); # write model to sbml write_cobra_model_to_sbml_file(cobra_model,'data/iteration1_140407_ijo1366_netrxn_irreversible.xml') # Reduce model using FVA: reduce_model(cobra_model,"data/iteration1_140407_ijo1366_reduced.xml") # Remove all reactions with 0 flux remove_noflux_reactions(cobra_model); with open('data/iteration1_140407_ijo1366_reduced_netrxn_lbub.csv',mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Formula','LB','UB','Subsystem']) for r in cobra_model.reactions: writer.writerow([r.id, r.build_reaction_string(), r.lower_bound, r.upper_bound, r.subsystem]);
def test_modify_reversible(self): model1 = self.model model1.optimize() model2 = create_test_model() modify.convert_to_irreversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) modify.revert_to_reversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3)
def test_modify_reversible(self): model1 = create_test_model("textbook") model1.optimize() model2 = create_test_model("textbook") modify.convert_to_irreversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) modify.revert_to_reversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) # Ensure revert_to_reversible is robust to solutions generated both # before and after reversibility conversion, or not solved at all. model3 = create_test_model("textbook") model3.optimize() modify.convert_to_irreversible(model3) modify.revert_to_reversible(model3) self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3) # test reaction where both bounds are negative model4 = create_test_model("textbook") glc = model4.reactions.get_by_id("EX_glc__D_e") glc.upper_bound = -1 modify.convert_to_irreversible(model4) model4.optimize() self.assertAlmostEqual(model1.solution.f, model4.solution.f, places=3) glc_rev = model4.reactions.get_by_id(glc.notes["reflection"]) self.assertEqual(glc_rev.lower_bound, 1) self.assertEqual(glc.upper_bound, 0) modify.revert_to_reversible(model4) self.assertEqual(glc.upper_bound, -1)
def test_modify_reversible(self): model1 = self.model model1.optimize() model2 = create_test_model() modify.convert_to_irreversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) modify.revert_to_reversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) # Ensure revert_to_reversible is robust to solutions generated both # before and after reversibility conversion, or not solved at all. model3 = create_test_model() model3.optimize() modify.convert_to_irreversible(model3) modify.revert_to_reversible(model3) self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3) model4 = create_test_model() modify.convert_to_irreversible(model4) modify.revert_to_reversible(model4)
def test_modify_reversible(self): model1 = create_test_model("textbook") model1.optimize() model2 = create_test_model("textbook") modify.convert_to_irreversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) modify.revert_to_reversible(model2) model2.optimize() self.assertAlmostEqual(model1.solution.f, model2.solution.f, places=3) # Ensure revert_to_reversible is robust to solutions generated both # before and after reversibility conversion, or not solved at all. model3 = create_test_model("textbook") model3.optimize() modify.convert_to_irreversible(model3) modify.revert_to_reversible(model3) self.assertAlmostEqual(model1.solution.f, model3.solution.f, places=3) model4 = create_test_model("textbook") modify.convert_to_irreversible(model4) modify.revert_to_reversible(model4)
def _pfba_legacy(model, solver, already_irreversible=False, fraction_of_optimum=1.0, desired_objective_value=None, **optimize_kwargs): """Perform basic pFBA (parsimonious FBA) and minimize total flux. The function attempts to act as a drop-in replacement for optimize. It will make the reaction reversible and perform an optimization, then force the objective value to remain the same and minimize the total flux. Finally, it will convert the reaction back to the irreversible form it was in before. See http://dx.doi.org/10.1038/msb.2010.47 Parameters ---------- model : cobra.Model The model solver : solver The solver object to use already_irreversible : bool, optional By default, the model is converted to an irreversible one. However, if the model is already irreversible, this step can be skipped fraction_of_optimum : float, optional Fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal_value * fraction_of_optimum. By default, this option is specified to be 1.0 desired_objective_value : float, optional A desired objective value for the minimal solution that bypasses the initial optimization result. Updates everything in-place, returns model to original state at end. """ objective_reactions = linear_reaction_coefficients(model) if len(objective_reactions) > 1: raise ValueError('pfba only supports models with' ' a single objective function') if 'objective_sense' in optimize_kwargs: if optimize_kwargs['objective_sense'] == 'minimize': raise ValueError('Minimization not supported in pfba') optimize_kwargs.pop('objective_sense', None) if not already_irreversible: convert_to_irreversible(model) lp = solver.create_problem(model, **optimize_kwargs) if not desired_objective_value: solver.solve_problem(lp, objective_sense='maximize') status = solver.get_status(lp) if status != "optimal": revert_to_reversible(model) raise ValueError( "pFBA requires optimal solution status, not {}".format(status)) desired_objective_value = solver.get_objective_value(lp) for i, reaction in enumerate(model.reactions): if reaction.objective_coefficient != 0: # Enforce a certain fraction of the original objective target = (desired_objective_value * fraction_of_optimum / reaction.objective_coefficient) solver.change_variable_bounds(lp, i, target, reaction.upper_bound) # Minimize all reaction fluxes (including objective?) solver.change_variable_objective(lp, i, 1) solver.solve_problem(lp, objective_sense='minimize', **optimize_kwargs) solution = solver.format_solution(lp, model) # Return the model to its original state # model.solution = solution revert_to_reversible(model) # if solution.status == "optimal": # model.solution.f = sum([coeff * reaction.x for reaction, coeff in # iteritems(objective_reactions)]) return solution
copies_fL = pd.read_csv("../data/abundance[copies_fl].csv") copies_fL = copies_fL[['bnumber', 'GLC_BATCH_mu=0.58_S']] abundance = pd.DataFrame.from_csv("../data/g_gCDW.csv") cu = CAPACITY_USAGE(flux, abundance) uni_to_b = {row[48:54]:row[0:5].split(';')[0].strip() for row in open("../data/all_ecoli_genes.txt", 'r')} id_mapper = pd.DataFrame.from_dict(uni_to_b.items()) id_mapper.columns = ["uniprot", "bnumber"] TS = pd.read_csv("../data/thermoal_stability_ecoli.csv") df = TS.merge(id_mapper, on=["uniprot"]) #%% model = cu.model.copy() revert_to_reversible(model) def one2one_mapping(): l = [] for b in cu.model.genes: l+=(list(product([b.id], list(b.reactions)))) df = pd.DataFrame(l) df.columns = ['bnumber', 'reaction'] df.loc[:, '# genes in reaction'] = [len(r.genes) for r in df['reaction']] return df b2r = one2one_mapping() df = df.merge(b2r, on="bnumber", how='outer') df = df.merge(copies_fL, on="bnumber", how='outer') df['reaction'] = df['reaction'].map(str, ) kmax = cu.kmax kmax.name='kmax'
def MergeRev(model, update_solution=True): modify.revert_to_reversible(model, update_solution=update_solution)