def test_pFBA(self): model = self.model for solver in solver_dict: optimize_minimal_flux(model, solver=solver) abs_x = [abs(i) for i in model.solution.x] self.assertAlmostEqual(model.solution.f, 0.3800, places=3) self.assertAlmostEqual(sum(abs_x), 343.021, places=3)
def optimise_biomass(model, bm_id, objective_sense=MAXIMIZE, level=logging.INFO): reaction = model.reactions.get_by_id(bm_id) model.change_objective([reaction]) try: optimize_minimal_flux(model, objective_sense=objective_sense) except Exception as e: logging.error("Could not optimise the model %s: %s" % (model.id, e.message)) return None if "optimal" != model.solution.status: logging.error("A problem occurred while calculating the solution for %s: %s" % (format_r_name(reaction), model.solution.status)) return None else: logging.log(level, "%s: %.4g" % (format_r_name(reaction), model.solution.f)) return model.solution.f
def find_egc(cobra_model, solver=settings.LP_SOLVER): """ try to locate EGCs by blocking all transport reactions and maximizing the objective of creating ATP from ADP + Pi """ model = cobra_model.copy() if "EGC_tester" not in model.reactions: obj = Reaction("EGC_tester", lower_bound=1e-3) obj.add_metabolites({model.metabolites.atp_c: -1, model.metabolites.h2o_c: -1, model.metabolites.adp_c: 1, model.metabolites.pi_c: 1}) model.add_reaction(obj) model.objective = "EGC_tester" # disable exchange reactions and ATM maintenance for r in model.reactions: if r.id[0:3] == 'EX_': r.lower_bound = 0 r.upper_bound = 0 model.reactions.ATPM.lower_bound = 0 model.reactions.ATPM.upper_bound = 0 # protons are sometimes not balanced well, so we ignore them model.reactions.EX_h_e.lower_bound = -1000 model.reactions.EX_h_e.upper_bound = 1000 FBA_sol = model.optimize(solver=solver) FBA_sol = optimize_minimal_flux(model) if FBA_sol.status != 'optimal': print('stFBA problem is: ' + FBA_sol.status) return None print_solution(FBA_sol) return FBA_sol
def _perform_pFBA(self, model, cs='glc', gr=1, ur=10): from cobra.flux_analysis.parsimonious import optimize_minimal_flux rxns = dict([(r.id, r) for r in model.reactions]) rxns['EX_glc_e'].lower_bound = 0 # uptake of carbon source reaction is initialized try: rxns['EX_' + cs + '_e'].lower_bound = -ur # redefine sole carbon source uptake reaction in mmol/gr/h except: print cs, ur rxns['EX_glc_e'].lower_bound = -ur rxns['Ec_biomass_iJO1366_core_53p95M'].upper_bound = gr print "solving pFBA", optimize_minimal_flux(model, already_irreversible=True) flux_dist = pd.DataFrame(model.solution.x_dict.items()).set_index(0) return flux_dist
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 perform_pFBA(model, cs, gr, ur): model = deepcopy(model) convert_to_irreversible(model) rxns = dict([(r.id, r) for r in model.reactions]) rxns['EX_glc_e'].lower_bound = 0 # uptake of carbon source reaction is initialized try: rxns['EX_' + cs + '_e'].lower_bound = -ur # redefine sole carbon source uptake reaction in mmol/gr/h except: print cs, ur rxns['EX_glc_e'].lower_bound = -ur rxns['Ec_biomass_iJO1366_core_53p95M'].upper_bound = gr print "solving pFBA", optimize_minimal_flux(model, already_irreversible=True) flux_dist = pd.DataFrame(model.solution.x_dict.items()).set_index(0) return flux_dist
def _perform_pFBA(self, model, cs='glc', gr=1, ur=10): from cobra.flux_analysis.parsimonious import optimize_minimal_flux rxns = dict([(r.id, r) for r in model.reactions]) rxns[ 'EX_glc_e'].lower_bound = 0 # uptake of carbon source reaction is initialized try: rxns[ 'EX_' + cs + '_e'].lower_bound = -ur # redefine sole carbon source uptake reaction in mmol/gr/h except: print cs, ur rxns['EX_glc_e'].lower_bound = -ur rxns['Ec_biomass_iJO1366_core_53p95M'].upper_bound = gr print "solving pFBA", optimize_minimal_flux(model, already_irreversible=True) flux_dist = pd.DataFrame(model.solution.x_dict.items()).set_index(0) return flux_dist
def perform_pFBA(condition): cs = gc['media_key'].loc[condition] gr = gc['growth rate [h-1]'].loc[condition] m = create_cobra_model_from_sbml_file('../data/iJO1366.xml') m.reactions.get_by_id('EX_glc_e').lower_bound = 0 convert_to_irreversible(m) reac = dict([(r.id, r) for r in m.reactions]) try: reac['EX_' + cs + '_e'].lower_bound = -1000 # redefine sole carbon source uptake reaction in mmol/gr/h except KeyError: raise 'media key not in model' reac['Ec_biomass_iJO1366_core_53p95M'].objective_coefficient = 0 reac['Ec_biomass_iJO1366_WT_53p95M'].objective_coefficient = 1 reac['Ec_biomass_iJO1366_WT_53p95M'].upper_bound = gr print "solving pFBA for %s" %condition optimize_minimal_flux(m, already_irreversible=True) return pd.Series(m.solution.x_dict)
def minimize_maximize(sim_setup, biomass_fraction=0.9999, calculate_yield=True, copy=False): """Run FVA at max growth rate. Uses pFBA for max fluxes. """ model = sim_setup.model.copy() if copy else sim_setup.model biomass_reaction = next(iter(model.objective.keys())) substrate_exchanges = sim_setup.environment.substrate_exchanges supplement_exchanges = sim_setup.environment.supplement_exchanges target_exchange = sim_setup.design.target_exchange sol = me_optimize_growth(model) if model.id == 'ME' else model.optimize() growth_rate = 0.0 if sol.f is None else sol.f if growth_rate < min_biomass: yield_minmax = (np.nan, np.nan) minmax = (np.nan, np.nan) max_secretion = np.nan max_flux = np.nan heterologous_pathway_flux = np.nan else: if model.id == 'ME': max_target = sol.x_dict[target_exchange] minmax = (max_target, max_target) max_secretion = get_secretion(model, sol.x_dict) max_flux = model.get_metabolic_flux() min_flux = model.get_metabolic_flux() else: # set the minimum biomass production biomass_reaction.lower_bound = biomass_fraction * growth_rate # max and min model.change_objective(target_exchange) max_sol = optimize_minimal_flux(model) min_sol = model.optimize(objective_sense='minimize') minmax = (min_sol.f, max_sol.f) # get secretions max_secretion = get_secretion(model, max_sol.x_dict) max_flux = max_sol.x_dict min_flux = min_sol.x_dict if calculate_yield: yield_minmax = tuple([ carbon_yield(model, target_exchange, substrate_exchanges, supplement_exchanges, x_dict) for x_dict in (max_flux, min_flux) ]) else: yield_minmax = (np.nan, np.nan) return MinMaxSolution(growth_rate, minmax, yield_minmax, max_secretion, max_flux)
def reduce_model_pfba(cobra_model, cobra_model_outFileName=None, fba_outFileName=None, subs=[]): '''reduce model using pfba''' # Input: cobra_model # cobra_model_outFileName # subs = string of specific subsystems to reduce # Output: cobra_model # the lower and upper bounds have been set to 0.0 # for all reactions that cannot carry a flux cobra_model.optimize() sol_f = cobra_model.solution.f # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model, True, solver='gurobi') # Reduce model rxns_noflux = [] # set lb and ub for all reactions with 0 flux to 0; for k, v in cobra_model.solution.x_dict.items(): if (v < 0.0 or v == 0.0 ) and cobra_model.reactions.get_by_id(k).subsystem in subs: cobra_model.reactions.get_by_id(k).lower_bound = 0.0 cobra_model.reactions.get_by_id(k).upper_bound = 0.0 rxns_noflux.append(k) if cobra_model_outFileName: write_cobra_model_to_sbml_file(cobra_model, cobra_model_outFileName) if pfba_outFileName: # Write pfba solution to file with open(pfba_outFileName, 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]) cobra_model.optimize() sol_reduced_f = cobra_model.solution.f # Check that the reduced model is consistent with the original model if not sol_f == sol_reduced_f: print('reduced model is inconsistent with the original model') print('original model solution: ' + str(sol_f)) print('reduced model solution: ' + str(sol_reduced_f))
def reduce_model_pfba(self,cobra_model,cobra_model_outFileName=None,fba_outFileName=None,subs=[]): '''reduce model using pfba''' # Input: cobra_model # cobra_model_outFileName # subs = string of specific subsystems to reduce # Output: cobra_model # the lower and upper bounds have been set to 0.0 # for all reactions that cannot carry a flux cobra_model.optimize() sol_f = cobra_model.solution.f # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi'); # Reduce model rxns_noflux = []; # set lb and ub for all reactions with 0 flux to 0; for k,v in cobra_model.solution.x_dict.items(): if (v < 0.0 or v == 0.0) and cobra_model.reactions.get_by_id(k).subsystem in subs: cobra_model.reactions.get_by_id(k).lower_bound = 0.0; cobra_model.reactions.get_by_id(k).upper_bound = 0.0; rxns_noflux.append(k); if cobra_model_outFileName: write_cobra_model_to_sbml_file(cobra_model,cobra_model_outFileName) if pfba_outFileName: # Write pfba solution to file with open(pfba_outFileName,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]); cobra_model.optimize() sol_reduced_f = cobra_model.solution.f # Check that the reduced model is consistent with the original model if not sol_f == sol_reduced_f: print('reduced model is inconsistent with the original model') print('original model solution: ' + str(sol_f)) print('reduced model solution: ' + str(sol_reduced_f))
def generate_fba_data(self,cobra_model,allow_loops=True, method_I='fba',solver='glpk'): """perform FBA simulation on the model """ #add in loop law constrain if not allow_loops: cobra_model=construct_loopless_model(cobra_model) #check for the optimization method: cobra_model.solver = solver if method_I=='fba' or method_I=='loopless-fba': sol = cobra_model.optimize() elif method_I =='pfba' or method_I=='loopless-pfba': sol = optimize_minimal_flux(model=cobra_model,solver=solver) else: print('method not recognized.') return self.fba_primal_data={} for k,v in sol.x_dict.items(): self.fba_primal_data[k] = v self.fba_dual_data={} for k,v in sol.y_dict.items(): self.fba_dual_data[k] = v
def find_egc(cobra_model, already_irreversible=False): """ try to locate EGCs by blocking all transport reactions and maximizing the objective of creating ATP from ADP + Pi """ model = cobra_model.copy() obj = Reaction("EGC_tester") obj.add_metabolites({ model.metabolites.atp_c: -1, model.metabolites.h2o_c: -1, model.metabolites.adp_c: 1, model.metabolites.pi_c: 1 }) model.add_reaction(obj) model.objective = "EGC_tester" # disable exchange reactions and ATM maintenance for r in model.reactions: if r.id[0:3] == 'EX_': r.lower_bound = 0 r.upper_bound = 0 model.reactions.ATPM.lower_bound = 0 model.reactions.ATPM.upper_bound = 0 # protons are sometimes not balanced well, so we ignore them model.reactions.EX_h_e.lower_bound = -1000 model.reactions.EX_h_e.upper_bound = 1000 FBA_sol = model.optimize() if FBA_sol.status == 'optimal' and FBA_sol.f > 1e-9: FBA_sol = \ optimize_minimal_flux(model, already_irreversible=already_irreversible) stFBA.print_solution(FBA_sol) return FBA_sol else: print('No EGCs found') return None
def isotopomer_model_iteration3(model_filename,xml_filename,mat_filename,csv_filename,isotopomer_mapping_filename,ko_list=[],flux_dict={},description=None): '''iteration 3: Remove reactions that are thermodynamically unfavorable and add isotopomer data''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(model_filename, print_time=True) # Modify glucose uptake: if cobra_model.reactions.has_id('EX_glc_LPAREN_e_RPAREN__reverse'): lb,ub = cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN__reverse').lower_bound,cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN__reverse').upper_bound; EX_glc_mets = {}; EX_glc_mets[cobra_model.metabolites.get_by_id('glc_DASH_D_e')] = -1; EX_glc = Reaction('EX_glc_LPAREN_e_RPAREN_'); EX_glc.add_metabolites(EX_glc_mets); cobra_model.add_reaction(EX_glc) cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN_').lower_bound = -ub; cobra_model.reactions.get_by_id('EX_glc_LPAREN_e_RPAREN_').upper_bound = lb; cobra_model.remove_reactions(['EX_glc_LPAREN_e_RPAREN__reverse']) ## Remove thermodynamically infeasible reactions: #infeasible = []; #loops = []; #cobra_model.remove_reactions(infeasible + loops); # Apply KOs, if any: for ko in ko_list: cobra_model.reactions.get_by_id(ko).lower_bound = 0.0; cobra_model.reactions.get_by_id(ko).upper_bound = 0.0; # Apply flux constraints, if any: for rxn,flux in flux_dict.items(): cobra_model.reactions.get_by_id(rxn).lower_bound = flux['lb']; cobra_model.reactions.get_by_id(rxn).upper_bound = flux['ub']; # Change description, if any: if description: cobra_model.description = description; # Read in isotopomer model isotopomer_mapping = read_isotopomer_mapping_csv(isotopomer_mapping_filename); isotopomer_str = build_isotopomer_str(isotopomer_mapping); # write model to sbml write_cobra_model_to_sbml_file(cobra_model,xml_filename) # Add isotopomer field to model for r in cobra_model.reactions: if r.id in isotopomer_str: cobra_model.reactions.get_by_id(r.id).isotopomer = isotopomer_str[r.id]; else: cobra_model.reactions.get_by_id(r.id).isotopomer = ''; # Add null basis: cobra_model_array = cobra_model.to_array_based_model(); N = null(cobra_model_array.S.todense()) #convert S from sparse to full and compute the nullspace cobra_model.N = N; # solve and save pFBA for later use: optimize_minimal_flux(cobra_model,True,solver='gurobi'); # add match field: match = numpy.zeros(len(cobra_model.reactions)); cobra_model.match = match; # write model to mat save_matlab_model_isotopomer(cobra_model,mat_filename); with open(csv_filename,mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Formula','LB','UB','Genes','Subsystem','Isotopomer']) for r in cobra_model.reactions: writer.writerow([r.id, r.build_reaction_string(), r.lower_bound, r.upper_bound, r.gene_reaction_rule, r.subsystem, r.isotopomer]);
def isotopomer_model_iteration3(model_filename, xml_filename, mat_filename, csv_filename, isotopomer_mapping_filename, ko_list=[], flux_dict={}, description=None): '''iteration 3: Remove reactions that are thermodynamically unfavorable and add isotopomer data''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(model_filename, print_time=True) # Modify glucose uptake: if cobra_model.reactions.has_id('EX_glc_LPAREN_e_RPAREN__reverse'): lb, ub = cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN__reverse' ).lower_bound, cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN__reverse').upper_bound EX_glc_mets = {} EX_glc_mets[cobra_model.metabolites.get_by_id('glc_DASH_D_e')] = -1 EX_glc = Reaction('EX_glc_LPAREN_e_RPAREN_') EX_glc.add_metabolites(EX_glc_mets) cobra_model.add_reaction(EX_glc) cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN_').lower_bound = -ub cobra_model.reactions.get_by_id( 'EX_glc_LPAREN_e_RPAREN_').upper_bound = lb cobra_model.remove_reactions(['EX_glc_LPAREN_e_RPAREN__reverse']) ## Remove thermodynamically infeasible reactions: #infeasible = []; #loops = []; #cobra_model.remove_reactions(infeasible + loops); # Apply KOs, if any: for ko in ko_list: cobra_model.reactions.get_by_id(ko).lower_bound = 0.0 cobra_model.reactions.get_by_id(ko).upper_bound = 0.0 # Apply flux constraints, if any: for rxn, flux in flux_dict.items(): cobra_model.reactions.get_by_id(rxn).lower_bound = flux['lb'] cobra_model.reactions.get_by_id(rxn).upper_bound = flux['ub'] # Change description, if any: if description: cobra_model.description = description # Read in isotopomer model isotopomer_mapping = read_isotopomer_mapping_csv( isotopomer_mapping_filename) isotopomer_str = build_isotopomer_str(isotopomer_mapping) # write model to sbml write_cobra_model_to_sbml_file(cobra_model, xml_filename) # Add isotopomer field to model for r in cobra_model.reactions: if r.id in isotopomer_str: cobra_model.reactions.get_by_id( r.id).isotopomer = isotopomer_str[r.id] else: cobra_model.reactions.get_by_id(r.id).isotopomer = '' # Add null basis: cobra_model_array = cobra_model.to_array_based_model() N = null(cobra_model_array.S.todense() ) #convert S from sparse to full and compute the nullspace cobra_model.N = N # solve and save pFBA for later use: optimize_minimal_flux(cobra_model, True, solver='gurobi') # add match field: match = numpy.zeros(len(cobra_model.reactions)) cobra_model.match = match # write model to mat save_matlab_model_isotopomer(cobra_model, mat_filename) with open(csv_filename, mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow([ 'Reaction', 'Formula', 'LB', 'UB', 'Genes', 'Subsystem', 'Isotopomer' ]) for r in cobra_model.reactions: writer.writerow([ r.id, r.build_reaction_string(), r.lower_bound, r.upper_bound, r.gene_reaction_rule, r.subsystem, r.isotopomer ])
def isotopomer_model_iteration2(pfba_filename, fva_reduced_model_filename, netrxn_irreversible_model_filename, reduced_lbub_filename): '''iteration 2: addition of finalized lumped reactions that are in pathways that are within the scope of the model and reduction by removing reactions with zero optimal minimal flux outside the scope of the model''' cobra_model = load_ALEWt() # Make the model irreversible for downstream manipulations: convert_to_irreversible(cobra_model) cobra_model.optimize() # Add lumped isotopomer reactions add_net_reaction(cobra_model, isotopomer_rxns_net_irreversible, True) cobra_model.optimize() # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model, True, solver='gurobi') # Write pfba solution to file with open(pfba_filename, mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction', 'Flux', 'Subsystem']) for k, v in cobra_model.solution.x_dict.items(): writer.writerow( [k, v, cobra_model.reactions.get_by_id(k).subsystem]) # Read in pfba solution pfba_sol = {} with open(pfba_filename, mode='r') as infile: dictreader = csv.DictReader(infile) for r in dictreader: pfba_sol[r['Reaction']] = r['Flux'] # remove noflux 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', 'Alternate Carbon Metabolism' ] remove_noflux_reactions(cobra_model, pfba_sol, subs) # Reduce model using FVA: reduce_model(cobra_model, fva_reduced_model_filename) # Reset secretion products that may have been turned off secrete = [ 'EX_meoh_LPAREN_e_RPAREN_', 'EX_5mtr_LPAREN_e_RPAREN_', 'EX_h_LPAREN_e_RPAREN_', 'EX_co2_LPAREN_e_RPAREN_', 'EX_co_LPAREN_e_RPAREN_', 'EX_h2o_LPAREN_e_RPAREN_', 'EX_ac_LPAREN_e_RPAREN_', 'EX_fum_LPAREN_e_RPAREN_', 'EX_for_LPAREN_e_RPAREN_', 'EX_etoh_LPAREN_e_RPAREN_', 'EX_lac_DASH_L_LPAREN_e_RPAREN_', 'EX_pyr_LPAREN_e_RPAREN_', 'EX_succ_LPAREN_e_RPAREN_' ] for s in secrete: cobra_model.reactions.get_by_id(s).upper_bound = 1000.0 # Remove all reactions with 0 flux r1, r2 = get_reactionsInfo(cobra_model) while r2 != 0: remove_noflux_reactions(cobra_model) r1, r2 = get_reactionsInfo(cobra_model) print(r1, r2) # write model to sbml write_cobra_model_to_sbml_file(cobra_model, netrxn_irreversible_model_filename) with open(reduced_lbub_filename, 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 ])
perform_gap_filling = 5 # False to not, otherwise a number indicating how many iterations. Performs gap-filling using all nematode reactions not already added to the wol model. test_removed_wol_rxns = False # Check the effect of removing the wolbachia-only reactions # # # Run steps in_model_files = [os.path.join(files_dir, m_file) for m_file in in_model_files] in_models = [read_excel(m_file, verbose=False) for m_file in in_model_files] in_wol_unique_files = [ os.path.join(files_dir, m_file) for m_file in in_wol_unique_files ] wol_unique_models = [ read_excel(m_file, verbose=False) for m_file in in_wol_unique_files ] wol_common_model = read_excel(os.path.join(files_dir, in_wol_common_file)) fvas = [] for m in in_models: optimize_minimal_flux(m) fvas.append(flux_variability_analysis(m)) wol_models, unused_models, unique_wol_ids = separate_wol_rxns( in_models, wol_unique_models, wol_common_model, wol_model_names, test_removed_wol_rxns) if perform_gap_filling != False and isinstance(perform_gap_filling, int): for wm, unused_m in zip(wol_models, unused_models): # check if it's already solvable. wm.optimize() if wm.solution.f < 0.5: print('\nPerforming gap-filling on %s...' % wm) results = growMatch(wm, unused_m, iterations=perform_gap_filling) # Check for duplicate reaction sets; these aren't useful. for i, res in enumerate(results): print('\nRun %i:' % (i + 1))
def solver(label_model, mode="fsolve", fba_mode="fba", model=None, check_unity=True, hot_start=False): """ Function that computes the steady state isotopologue fractions by solving the emu balances model. label_model: label_model object mode: str, optional Either "fsolve" (default) or "ODE". Indicates how should the problem be solved fba_mode: str,optional Either "fba" (flux balance analysis,default) or "pfba" (parsimonious). Indicates wich method should be used to generate the set of setady state fluxes from the COBRA model model: COBRApy model object, optional COBRApy model that will be used to compute the steady state flux distribution. If none is provided it will use the constrained_model in the label_model object check_unity: bool, optional If set to True it will check that isotoplogues fractions for a given EMU are never larger than 1 hot_start: bool, deprectated currently unnused """ label_model.solver_flag = "success" if model == None: model = label_model.constrained_model apply_ratios(model, label_model.ratio_dict) try: if fba_mode.lower() == "fba": model.optimize( tolerance_feasibility=label_model.lp_tolerance_feasibility) elif fba_mode.lower() == "pfba": #convert_model_to_irreversible(label_model.constrained_model) optimize_minimal_flux(model, already_irreversible=False) #revert_model_to_reversible(label_model.constrained_model, update_solution=True) except: label_model.solver_flag = "fail" error_dump(label_model, e_type="error in optimize") return label_model.solver_flag, label_model.condition_size_yy_dict if model.solution.status == "optimal": if hot_start: yy0 = label_model.condition_size_yy_dict else: yy0 = label_model.condition_size_yy0_dict for n_precision in xrange(10, 16): get_fluxes(label_model, model, precision=n_precision, model=label_model.constrained_model) for condition in label_model.initial_label: label_model.active_condition = condition if mode == "fsolve": for size in label_model.size_emu_c_eqn_dict: label_model.condition_size_yy_dict[condition][ size] = fsolve( label_model.size_emu_c_eqn_dict[size], yy0[condition][size], (0, label_model)) if check_unity: max_value = label_model.condition_size_yy_dict[ condition][size].max() min_value = label_model.condition_size_yy_dict[ condition][size].min() if max_value > 1.001 or min_value < -0.001: label_model.solver_flag = "fail" print mode + " failed unity check" + str( [max_value, min_value]) error_dump(label_model, e_type="fsolve error") break elif mode == "ode": for size in label_model.size_emu_c_eqn_dict: yy = odeint(label_model.size_emu_c_eqn_dict[size], yy0[condition][size], t, (label_model, ), mxstep=5000) label_model.condition_size_yy_dict[condition][ size] = yy[nt] dy = label_model.size_emu_c_eqn_dict[size](yy[nt], 0, label_model) total = sum(dy) if total > 1e-6: #If it is not a strict steady state use fsolve to refine the results label_model.condition_size_yy_dict[condition][ size] = fsolve( label_model.size_emu_c_eqn_dict[size], yy0[condition][size], (0, label_model)) if check_unity: max_value = label_model.condition_size_yy_dict[ condition][size].max() min_value = label_model.condition_size_yy_dict[ condition][size].min() if max_value > 1.001 or min_value < -0.001: label_model.solver_flag = "fail" print mode + " failed unity check" + str( [max_value, min_value]) #error_dump(label_model,e_type="solver error") break dy = check_dy(label_model, condition) if dy > 1e-4: label_model.solver_flag = "fail" print mode + " failed with an error of " + str(dy) if label_model.solver_flag == "fail": if mode != "ode": #If fsolve failes try ode label_model.solver_flag, label_model.condition_size_yy_dict = solver( label_model, mode="ode") else: break if label_model.solver_flag != "fail": break #Break the precision loop if it worked error_dump(label_model, e_type="solver error") else: #remove label_model.solver_flag = "fail" error_dump(label_model, e_type="unfeasible") return label_model.solver_flag, label_model.condition_size_yy_dict
model.reactions.get_by_id('EX_glc_e').lower_bound = 0 model.reactions.get_by_id('EX_' + cobra_c + '_e').lower_bound = -1000 # set growth rate according to measurements biomass = "Ec_biomass_iJO1366_WT_53p95M" model.change_objective(biomass) growth_rate = model.reactions.get_by_id(biomass) growth_rate.upper_bound = gr # growth_rate.lower_bound = gr revs = [] for rid in projections.index: v = projections.loc[rid, c] r_f = model.reactions.get_by_id(rid) if v < 0: r_b = model.reactions.get_by_id(rid+'_reverse') revs.append(r_b) r_f.upper_bound = 0 r_f.lower_bound = 0 r_b.upper_bound = -v r_b.lower_bound = -v else: r_f.upper_bound = v r_f.lower_bound = v f = optimize_minimal_flux(model, already_irreversible=True) mmol_gCDW[c].update(pd.Series(f.x_dict)) umol_gCDW_min = mmol_gCDW * 1000 / 60 mmol_gCDW.to_csv('../data/mmol_gCDW_hr.csv') umol_gCDW_min.to_csv('../data/umol_gCDW_min.csv')
def isotopomer_model_iteration2(pfba_filename,fva_reduced_model_filename,netrxn_irreversible_model_filename,reduced_lbub_filename): '''iteration 2: addition of finalized lumped reactions that are in pathways that are within the scope of the model and reduction by removing reactions with zero optimal minimal flux outside the scope of the model''' cobra_model = load_ALEWt(); # Make the model irreversible for downstream manipulations: convert_to_irreversible(cobra_model); cobra_model.optimize(); # Add lumped isotopomer reactions add_net_reaction(cobra_model,isotopomer_rxns_net_irreversible,True); cobra_model.optimize(); # Find minimal flux solution: pfba = optimize_minimal_flux(cobra_model,True,solver='gurobi'); # Write pfba solution to file with open(pfba_filename,mode='wb') as outfile: writer = csv.writer(outfile) writer.writerow(['Reaction','Flux','Subsystem']) for k,v in cobra_model.solution.x_dict.items(): writer.writerow([k,v,cobra_model.reactions.get_by_id(k).subsystem]); # Read in pfba solution pfba_sol = {}; with open(pfba_filename,mode='r') as infile: dictreader = csv.DictReader(infile) for r in dictreader: pfba_sol[r['Reaction']] = r['Flux']; # remove noflux 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', 'Alternate Carbon Metabolism']; remove_noflux_reactions(cobra_model,pfba_sol,subs) # Reduce model using FVA: reduce_model(cobra_model,fva_reduced_model_filename) # Reset secretion products that may have been turned off secrete = ['EX_meoh_LPAREN_e_RPAREN_', 'EX_5mtr_LPAREN_e_RPAREN_', 'EX_h_LPAREN_e_RPAREN_', 'EX_co2_LPAREN_e_RPAREN_', 'EX_co_LPAREN_e_RPAREN_', 'EX_h2o_LPAREN_e_RPAREN_', 'EX_ac_LPAREN_e_RPAREN_', 'EX_fum_LPAREN_e_RPAREN_', 'EX_for_LPAREN_e_RPAREN_', 'EX_etoh_LPAREN_e_RPAREN_', 'EX_lac_DASH_L_LPAREN_e_RPAREN_', 'EX_pyr_LPAREN_e_RPAREN_', 'EX_succ_LPAREN_e_RPAREN_']; for s in secrete: cobra_model.reactions.get_by_id(s).upper_bound = 1000.0; # Remove all reactions with 0 flux r1,r2 = get_reactionsInfo(cobra_model); while r2 !=0: remove_noflux_reactions(cobra_model); r1,r2 = get_reactionsInfo(cobra_model); print(r1,r2); # write model to sbml write_cobra_model_to_sbml_file(cobra_model,netrxn_irreversible_model_filename) with open(reduced_lbub_filename,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 solver(label_model,mode="fsolve",fba_mode="fba",model=None,check_unity=True,hot_start=False): """ Function that computes the steady state isotopologue fractions by solving the emu balances model. label_model: label_model object mode: str, optional Either "fsolve" (default) or "ODE". Indicates how should the problem be solved fba_mode: str,optional Either "fba" (flux balance analysis,default) or "pfba" (parsimonious). Indicates wich method should be used to generate the set of setady state fluxes from the COBRA model model: COBRApy model object, optional COBRApy model that will be used to compute the steady state flux distribution. If none is provided it will use the constrained_model in the label_model object check_unity: bool, optional If set to True it will check that isotoplogues fractions for a given EMU are never larger than 1 hot_start: bool, deprectated currently unnused """ label_model.solver_flag="success" if model==None: model=label_model.constrained_model apply_ratios(model,label_model.ratio_dict) try: if fba_mode.lower()=="fba": model.optimize(tolerance_feasibility=label_model.lp_tolerance_feasibility) elif fba_mode.lower()=="pfba": #convert_model_to_irreversible(label_model.constrained_model) optimize_minimal_flux(model, already_irreversible=False) #revert_model_to_reversible(label_model.constrained_model, update_solution=True) except: label_model.solver_flag="fail" error_dump(label_model,e_type="error in optimize") return label_model.solver_flag, label_model.condition_size_yy_dict if model.solution.status =="optimal": if hot_start: yy0=label_model.condition_size_yy_dict else: yy0=label_model.condition_size_yy0_dict for n_precision in xrange(10,16): get_fluxes(label_model,model,precision=n_precision) for condition in label_model.initial_label: label_model.active_condition=condition if mode=="fsolve": for size in label_model.size_emu_c_eqn_dict: label_model.condition_size_yy_dict[condition][size] = fsolve(label_model.size_emu_c_eqn_dict[size] , yy0[condition][size],(0,label_model)) if check_unity: max_value=label_model.condition_size_yy_dict[condition][size].max() min_value=label_model.condition_size_yy_dict[condition][size].min() if max_value>1.001 or min_value<-0.001: label_model.solver_flag="fail" print mode+" failed unity check"+str([max_value,min_value]) error_dump(label_model,e_type="fsolve error") break elif mode=="ode": for size in label_model.size_emu_c_eqn_dict: yy=odeint(label_model.size_emu_c_eqn_dict[size], yy0[condition][size], t,(label_model,),mxstep=5000) label_model.condition_size_yy_dict[condition][size]=yy[nt] dy=label_model.size_emu_c_eqn_dict[size](yy[nt],0,label_model) total=sum(dy) if total>1e-6: #If it is not a strict steady state use fsolve to refine the results label_model.condition_size_yy_dict[condition][size] = fsolve(label_model.size_emu_c_eqn_dict[size] , yy0[condition][size],(0,label_model)) if check_unity: max_value=label_model.condition_size_yy_dict[condition][size].max() min_value=label_model.condition_size_yy_dict[condition][size].min() if max_value>1.001 or min_value<-0.001: label_model.solver_flag="fail" print mode+" failed unity check"+str([max_value,min_value]) #error_dump(label_model,e_type="solver error") break dy=check_dy(label_model,condition) if dy>1e-4: label_model.solver_flag="fail" print mode+" failed with an error of "+str(dy) if label_model.solver_flag=="fail": if mode!="ode": #If fsolve failes try ode label_model.solver_flag, label_model.condition_size_yy_dict=solver(label_model,mode="ode") else: break if label_model.solver_flag!="fail": break #Break the precision loop if it worked error_dump(label_model,e_type="solver error") else: #remove label_model.solver_flag="fail" error_dump(label_model,e_type="unfeasible") return label_model.solver_flag, label_model.condition_size_yy_dict