def simulate_loops_sbml(self,ijo1366_sbml,data_fva): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) # Change all uptake reactions to 0 for rxn in cobra_model.reactions: if 'EX_' in rxn.id and '_LPAREN_e_RPAREN_' in rxn.id: rxn.lower_bound = 0.0; # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0 # calculate the reaction bounds using FVA reaction_bounds = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', the_reactions=None, allow_loops=True, solver='gurobi', the_problem='return', tolerance_optimality=1e-6, tolerance_feasibility=1e-6, tolerance_barrier=1e-8, lp_method=1, lp_parallel=0, new_objective=None, relax_b=None, error_reporting=None, number_of_processes=1, copy_model=False); # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4);
def categorize_reactions(model, db, category): fva_result_dict = {} # Wide range of ATP Synthase flux values can be positive or negative category_1_dict = {} # ATP Synthase flux can only be negative category_2_dict = {} # ATP Synthase flux can only be positive category_3_dict = {} model = create_cobra_model_from_sbml_file(model) rxn_list = pickle.load(open(db, 'rb')) for run in rxn_list.keys(): model_test = model.copy() fva_list = [model_test.reactions.ATPS] for rxn in rxn_list[run]: addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0) formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0) rxn = Reaction(addID) model_test.add_reaction(rxn) rxn.reaction = formula fva_list.append(rxn) fva_result = flux_analysis.flux_variability_analysis(model_test, fva_list) fva_result_dict[run] = fva_result for run in fva_result_dict: if fva_result_dict[run]['ATPS']['maximum'] > 0 and fva_result_dict[run]['ATPS']['minimum'] < 0: category_1_dict[run] = fva_result_dict[run] elif fva_result_dict[run]['ATPS']['maximum'] > 0: category_2_dict[run] = fva_result_dict[run] else: category_3_dict[run] = fva_result_dict[run] if category == 1: return category_1_dict.keys() elif category == 2: return category_2_dict.keys() else: return category_3_dict.keys()
def _gapsplit(model, depth, cpus): fva = flux_variability_analysis(model, model.reactions, fraction_of_optimum=0.001, processes=cpus) # only split reactions with feasible range >= min_range idxs = (fva.maximum - fva.minimum >= 1e-5).to_numpy().nonzero()[0] weights = (1.0 / (fva.maximum - fva.minimum) ** 2).to_numpy() samples = numpy.zeros((depth, len(model.reactions))) k = 0 for try_ in range(1000): relative, target, width = _maxgap(samples[0:k,idxs], fva.iloc[idxs,:]) primary_var = numpy.argmax(relative) primary_target = target[primary_var] primary_lb = primary_target - 0.001*width[primary_var] primary_ub = primary_target + 0.001*width[primary_var] new_sample = _generate_sample(model, idxs[primary_var], primary_lb, primary_ub) if new_sample is not None: new_sample[new_sample > fva.maximum] = fva.maximum[new_sample > fva.maximum] new_sample[new_sample < fva.minimum] = fva.minimum[new_sample < fva.minimum] samples[k,:] = new_sample k += 1 if k >= depth: break if k < depth: # max_tries reached; return fewer samples samples = samples[:k,:] return pandas.DataFrame(data=samples, columns=fva.maximum.index)
def cobra_fva(pk, model_sbml, reaction_list, loopless, fraction_of_optimum, pfba_factor, deleted_genes): cobra_model = load_sbml(model_sbml) if len(deleted_genes) > 0: cobra.manipulation.delete_model_genes(cobra_model, deleted_genes, cumulative_deletions=True) try: result_frame = json.loads( flux_variability_analysis(cobra_model, reaction_list, loopless, fraction_of_optimum, pfba_factor).to_json()) result = { 'components': [{ 'name': name, 'minimum': result_frame['minimum'][name], 'maximum': result_frame['maximum'][name], } for name in result_frame['minimum'].keys()], } except Exception as error: error_result = report_cobra_computation_error(error) app.send_task( **get_result_kwargs('fba', pk, error_result, is_error=True)) return app.send_task(**get_result_kwargs('fva', pk, result))
def limiting_reactions(cobra_model, reactions=None): """ Determine limiting reactions """ if reactions == None: reactions = cobra_model.reactions sol = cobra_model.optimize() fva_rxns = [] for rxn in reactions: limited_below = isclose(sol.fluxes[rxn.id], rxn.lower_bound, rel_tol=1e-2) limited_above = isclose(sol.fluxes[rxn.id], rxn.upper_bound, rel_tol=1e-2) if limited_below or limited_above: if rxn.lower_bound < rxn.upper_bound and not isclose( rxn.lower_bound, rxn.upper_bound, rel_tol=1e-2): fva_rxns.append(rxn) fva = flux_variability_analysis(cobra_model, reaction_list=fva_rxns) for rxn, fmin, fmax in zip(fva.index, fva['minimum'].values, fva['maximum'].values): if fmin < sol.fluxes[rxn] and not isclose( sol.fluxes[rxn], fmin, rel_tol=1e-2): yield rxn elif fmax > sol.fluxes[rxn] and not isclose( sol.fluxes[rxn], fmax, rel_tol=1e-2): yield rxn
def simulate_loops(self,cobra_model_I=None,data_fva='loops_fva.json'): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' if cobra_model_I: cobra_model = cobra_model_I.copy(); else: cobra_model = self.model.copy(); # Change all uptake reactions to 0 system_boundaries = [x.id for x in cobra_model.reactions if x.boundary == 'system_boundary']; for rxn in cobra_model.reactions: if rxn.id in system_boundaries: cobra_model.reactions.get_by_id(rxn.id).lower_bound = 0.0; cobra_model.reactions.get_by_id(rxn.id).upper_bound = 0.0; # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0; # set the objective function to a default value cobra_model.change_objective('Ec_biomass_iJO1366_WT_53p95M') cobra_model.reactions.get_by_id('Ec_biomass_iJO1366_WT_53p95M').lower_bound=0.0 cobra_model.reactions.get_by_id('Ec_biomass_iJO1366_WT_53p95M').upper_bound=1e6 # calculate the reaction bounds using FVA reaction_bounds = flux_variability_analysis(cobra_model, fraction_of_optimum=1.0, the_reactions=None, solver='gurobi'); # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4);
def simulate_loops(self, cobra_model_I=None, data_fva='loops_fva.json'): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' if cobra_model_I: cobra_model = cobra_model_I.copy() else: cobra_model = self.model.copy() # Change all uptake reactions to 0 system_boundaries = [ x.id for x in cobra_model.reactions if x.boundary == 'system_boundary' ] for rxn in cobra_model.reactions: if rxn.id in system_boundaries: cobra_model.reactions.get_by_id(rxn.id).lower_bound = 0.0 cobra_model.reactions.get_by_id(rxn.id).upper_bound = 0.0 # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0 # set the objective function to a default value cobra_model.change_objective('Ec_biomass_iJO1366_WT_53p95M') cobra_model.reactions.get_by_id( 'Ec_biomass_iJO1366_WT_53p95M').lower_bound = 0.0 cobra_model.reactions.get_by_id( 'Ec_biomass_iJO1366_WT_53p95M').upper_bound = 1e6 # calculate the reaction bounds using FVA reaction_bounds = flux_variability_analysis(cobra_model, fraction_of_optimum=1.0, the_reactions=None, solver='gurobi') # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4)
def _create_visualisation(model_filename, svg_filename, output_filename, analysis_type='FBA', analysis_results=None, intermediate_filename=None): # Check arguments supported_analysis_types = {"FBA", "FVA"} if analysis_type not in supported_analysis_types: message = "Analysis type is wrong. It has to be one of the values: {}" raise ValueError(message.format(supported_analysis_types)) try: model = cio.load_json_model(model_filename) except Exception as exc: raise CobraModelFileError("Failed to load model from given JSON : {}".format(exc.args)) # Set default arguments if none provided if analysis_results is None: fba_results = model.optimize() if analysis_type == 'FBA': fba_results.fluxes = fba_results.fluxes.round(5) analysis_results = fba_results elif analysis_type == 'FVA': fva_results = flux_variability_analysis(model, fraction_of_optimum=0.5) fva_results = fva_results.round(3) analysis_results = fva_results vizan_kwargs = { 'model': model, 'file_source_path': svg_filename, 'analysis_results': analysis_results, 'analysis_type': analysis_type, 'output_filename': output_filename, } if intermediate_filename is None: with NamedTemporaryFile(mode="w") as intermediate_file: vizan_kwargs['intermediate_filename'] = intermediate_file.name produce_output_file(**vizan_kwargs) else: vizan_kwargs['intermediate_filename'] = intermediate_filename produce_output_file(**vizan_kwargs)
def test_metabolite_summary_interface(model, opt_solver): """Test that a summary can be created successfully.""" model.solver = opt_solver metabolite = model.metabolites.get_by_id("q8_c") MetaboliteSummary( metabolite=metabolite, model=model, ) MetaboliteSummary( metabolite=metabolite, model=model, solution=pfba(model), ) MetaboliteSummary( metabolite=metabolite, model=model, fva=0.95, ) MetaboliteSummary( metabolite=metabolite, model=model, fva=flux_variability_analysis( model, reaction_list=["CYTBD", "NADH16", "SUCDi"] ), )
def simulate_loops(ijo1366_sbml,data_fva): '''Simulate FVA after closing exchange reactions and setting ATPM to 0 reactions with flux will be involved in loops''' # Read in the sbml file and define the model conditions cobra_model = create_cobra_model_from_sbml_file(ijo1366_sbml, print_time=True) # Change all uptake reactions to 0 for rxn in cobra_model.reactions: if 'EX_' in rxn.id and '_LPAREN_e_RPAREN_' in rxn.id: rxn.lower_bound = 0.0; # Set ATPM to 0 cobra_model.reactions.get_by_id('ATPM').lower_bound = 0.0 # calculate the reaction bounds using FVA reaction_bounds = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', the_reactions=None, allow_loops=True, solver='gurobi', the_problem='return', tolerance_optimality=1e-6, tolerance_feasibility=1e-6, tolerance_barrier=1e-8, lp_method=1, lp_parallel=0, new_objective=None, relax_b=None, error_reporting=None, number_of_processes=1, copy_model=False); # Update the data file with open(data_fva, 'wb') as outfile: json.dump(reaction_bounds, outfile, indent=4);
def fva(self) -> pd.DataFrame: """Create DataFrame file with minimum and maximum value of FVA. Runs flux variability analysis. see https://cobrapy.readthedocs.io/en/latest/simulating.html#Running-FVA """ model = self.read_model() solution = model.optimize() fluxes = solution.fluxes try: df = flux_variability_analysis(model, model.reactions, fraction_of_optimum=1.0) df_out = pd.DataFrame({ "model": self.model_path.name, "objective": self.objective_id, "reaction": df.index, "flux": fluxes, "status": CuratorConstants.STATUS_OPTIMAL, "minimum": df.minimum, "maximum": df.maximum, }) except OptimizationError as e: logger.error(f"{e}") df_out = pd.DataFrame({ "model": self.model_path.name, "objective": self.objective_id, "reaction": [r.id for r in model.reactions], "flux": fluxes, "status": CuratorConstants.STATUS_INFEASIBLE, "minimum": CuratorConstants.VALUE_INFEASIBLE, "maximum": CuratorConstants.VALUE_INFEASIBLE, }) return df_out
def find_stoichiometrically_balanced_cycles(model): u""" Find metabolic reactions in stoichiometrically balanced cycles (SBCs). Identify forward and reverse cycles by closing all exchanges and using FVA. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- "SBCs are artifacts of metabolic reconstructions due to insufficient constraints (e.g., thermodynamic constraints and regulatory constraints) [1]_." They are defined by internal reactions that carry flux in spite of closed exchange reactions. References ---------- .. [1] Thiele, I., & Palsson, B. Ø. (2010, January). A protocol for generating a high-quality genome-scale metabolic reconstruction. Nature protocols. Nature Publishing Group. http://doi.org/10.1038/nprot.2009.203 """ helpers.close_boundaries_sensibly(model) fva_result = flux_variability_analysis(model, loopless=False) return fva_result.index[(fva_result["minimum"] == -1) | (fva_result["maximum"] == 1)].tolist()
def calculate_common_substrate_flux(model): boundary_reactions = model.exchanges # generate model exchange reactions fva_results = flux_variability_analysis( model, reaction_list=boundary_reactions, fraction_of_optimum=1) # Generate FVA results fva_results = fva_results.sort_values(by='minimum', ascending=True) # sort FVA results ascending order substrates = fva_results['minimum'] < 0 fva_results_substrates = fva_results[substrates].sort_values(by='minimum', ascending=True) # Generate dataframe where only consuming reactions are taken into account reaction_consist_carbon = [] for reaction in fva_results_substrates.index: reaction_cobrapy = model.reactions.get_by_id(reaction) for metabolite in reaction_cobrapy.reactants: if 'C' in metabolite.elements.keys(): reaction_consist_carbon.append(str(reaction)) # Filter from FVA substrate list reactions which HAVE NOT included flux_sum = 0 for reaction in reaction_consist_carbon: flux_sum = flux_sum + fva_results.loc[reaction, 'minimum'] return flux_sum
def get_r_id2fva_bounds(model, threshold=None, rs=None): r_id2min_max = flux_variability_analysis(model, reaction_list=rs) r_id2bounds = {} for r_id, values in r_id2min_max.items(): min_v, max_v = round_value(values['minimum']), round_value(values['maximum']) if threshold is None or abs(min_v) > threshold or abs(max_v) > threshold: r_id2bounds[r_id] = min_v, max_v return r_id2bounds
def find_reactions_with_unbounded_flux_default_condition(model): """ Return list of reactions whose flux is unbounded in the default condition. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- tuple list A list of reactions that in default modeling conditions are able to carry flux as high/low as the systems maximal and minimal bounds. float The fraction of the amount of unbounded reactions to the amount of non-blocked reactions. list A list of reactions that in default modeling conditions are not able to carry flux at all. """ try: fva_result = flux_variability_analysis(model, fraction_of_optimum=1.0) except Infeasible as err: LOGGER.error("Failed to find reactions with unbounded flux " "because '{}'. This may be a bug.".format(err)) raise Infeasible("It was not possible to run flux variability " "analysis on the model. Make sure that the model " "can be solved! Check if the constraints are not " "too strict.") # Per reaction (row) the flux is below threshold (close to zero). conditionally_blocked = fva_result.loc[fva_result.abs().max( axis=1) < TOLERANCE_THRESHOLD].index.tolist() small, large = helpers.find_bounds(model) # Find those reactions whose flux is close to or outside of the median # upper or lower bound, i.e., appears unconstrained. unlimited_flux = fva_result.loc[ np.isclose(fva_result["maximum"], large, atol=TOLERANCE_THRESHOLD) | (fva_result["maximum"] > large) | np.isclose(fva_result["minimum"], small, atol=TOLERANCE_THRESHOLD) | (fva_result["minimum"] < small)].index.tolist() try: fraction = len(unlimited_flux) / \ (len(model.reactions) - len(conditionally_blocked)) except ZeroDivisionError: LOGGER.error("Division by Zero! Failed to calculate the " "fraction of unbounded reactions. Does this model " "have any reactions at all?") raise ZeroDivisionError("It was not possible to calculate the " "fraction of unbounded reactions to " "un-blocked reactions. This may be because" "the model doesn't have any reactions at " "all or that none of the reactions can " "carry a flux larger than zero!") return unlimited_flux, fraction, conditionally_blocked
def simulate(model, biomass_reaction, method, objective_id, objective_direction): if method not in METHODS: raise ValueError(f"Unsupported simulation method '{method}'") if objective_id: model.objective = model.reactions.get_by_id(objective_id) if objective_direction: model.objective_direction = objective_direction try: logger.info(f"Simulating model {model.id} with {method}") if method == "fba": solution = model.optimize(raise_error=True) elif method == "pfba": solution = pfba(model) elif method == "fva": # FIXME: accept list of relevant fva reactions to calculate solution = flux_variability_analysis(model) elif method == "pfba-fva": # FIXME: accept list of relevant fva reactions to calculate solution = flux_variability_analysis(model, fraction_of_optimum=1, pfba_factor=1.05) except OptimizationError as error: logger.info(f"Optimization Error: {error}") raise else: if method in ("fba", "pfba"): flux_distribution = solution.fluxes.to_dict() growth_rate = flux_distribution[biomass_reaction] elif method in ("fva", "pfba-fva"): df = solution.rename(index=str, columns={ "maximum": "upper_bound", "minimum": "lower_bound" }) for key in ["lower_bound", "upper_bound"]: df[key] = df[key].astype("float") flux_distribution = df.T.to_dict() growth_rate = flux_distribution[biomass_reaction]["upper_bound"] logger.info( f"Simulation was successful with growth rate {growth_rate}") return flux_distribution, growth_rate
def test_fastcc_against_fva_nonblocked_rxns(model: Model, all_solvers: List[str]) -> None: """Test non-blocked reactions obtained by FASTCC against FVA.""" model.solver = all_solvers fastcc_consistent_model = fastcc(model) fva = flux_variability_analysis(model, fraction_of_optimum=0.0) nonblocked_rxns_fva = fva.index[(fva.minimum.abs() > model.tolerance) | (fva.maximum.abs() > model.tolerance)] assert all(fastcc_consistent_model.reactions) == all( nonblocked_rxns_fva.tolist())
def _perform_fva(model): '''Perform FVA.''' flux_var = flux_variability_analysis(model, model.reactions) blocked = flux_var.loc[(abs(flux_var['minimum']) < 1e-6) & (abs(flux_var['maximum']) < 1e-6)] print 'Blocked: %d/%d\n' % (len(blocked), len(flux_var)) flux_var.to_csv('flux_var.csv') blocked.to_csv('blocked.csv')
def find_stoichiometrically_balanced_cycles(model): u""" Find metabolic rxns in stoichiometrically balanced cycles (SBCs). The flux distribution of nominal FVA is compared with loopless FVA (loopless=True) to determine reactions that participate in loops, as participation in loops would increase the flux through a given reactions to the maximal bounds. This function then returns reactions where the flux differs between the two FVA calculations. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- "SBCs are artifacts of metabolic reconstructions due to insufficient constraints (e.g., thermodynamic constraints and regulatory constraints) [1]_." They are defined by internal reactions that carry flux in spite of closed exchange reactions. References ---------- .. [1] Thiele, I., & Palsson, B. Ø. (2010, January). A protocol for generating a high-quality genome-scale metabolic reconstruction. Nature protocols. Nature Publishing Group. http://doi.org/10.1038/nprot.2009.203 """ try: fva_result = flux_variability_analysis(model, loopless=False) fva_result_loopless = flux_variability_analysis(model, loopless=True) except Infeasible as err: LOGGER.error("Failed to find stoichiometrically balanced cycles " "because '{}'. This may be a bug.".format(err)) return [] row_ids_max = fva_result[ fva_result.maximum != fva_result_loopless.maximum].index row_ids_min = fva_result[ fva_result.minimum != fva_result_loopless.minimum].index differential_fluxes = set(row_ids_min).union(set(row_ids_max)) return [model.reactions.get_by_id(id) for id in differential_fluxes]
def perform_analysis(model, analysis_type): fba_results = model.optimize() if analysis_type == 'FBA': fba_results.fluxes = fba_results.fluxes.round(5) analysis_results = fba_results elif analysis_type == 'FVA': fva_results = flux_variability_analysis(model, fraction_of_optimum=0.5) fva_results = fva_results.round(3) analysis_results = fva_results return model, analysis_results
def variability_analysis(self, measured_metabolites): if type(self.drug) == list: self.combined_drug_knockout() elif self.drug != '': self.drug_knock_out() elif self.target != '': self.model.genes.get_by_id(self.target).knock_out() self.set_objective(measured_metabolites) return flux_variability_analysis(self.model)
def _constrain_and_analyze_model(model, coefficient_dict, fraction, sampling_depth, objective, tasks, minimum_threshold, cpus): constrained_model = copy.deepcopy(model) # Set previous objective as a constraint, allow deviation if objective == True: prev_obj_val = constrained_model.slim_optimize() prev_obj_constraint = constrained_model.problem.Constraint(constrained_model.objective.expression, lb=prev_obj_val*fraction, ub=prev_obj_val) constrained_model.add_cons_vars([prev_obj_constraint]) constrained_model.solver.update() # Apply weigths to new expression pfba_expr = symengine.RealDouble(0) for rxn in constrained_model.reactions: try: pfba_expr += coefficient_dict[rxn.id] * rxn.forward_variable pfba_expr += coefficient_dict[rxn.id] * rxn.reverse_variable except KeyError: continue if sampling_depth == 0: # Include metabolic task constraints if len(tasks) >= 1: constrained_model = _integrate_tasks(constrained_model, tasks) # Determine reactions that do not carry any flux in highly constrained solution space constrained_model.objective = constrained_model.problem.Objective(pfba_expr, direction='min', sloppy=True) constrained_model.solver.update() solution = constrained_model.optimize() inactive_rxns = set([rxn.id for rxn in constrained_model.reactions if abs(solution.fluxes[rxn.id]) <= minimum_threshold]) return inactive_rxns else: # Explore solution space of constrained model with flux sampling, allow deviation constrained_model.objective = constrained_model.problem.Objective(pfba_expr, direction='max', sloppy=True) constrained_model.solver.update() flux_sum_obj_val = constrained_model.slim_optimize() flux_sum_constraint = constrained_model.problem.Constraint(pfba_expr, lb=flux_sum_obj_val*fraction, ub=flux_sum_obj_val) constrained_model.add_cons_vars([flux_sum_constraint]) constrained_model.solver.update() # Analyze flux ranges and calculate concordance if sampling_depth != 1: warnings.filterwarnings('ignore') # Handle possible infeasible warnings flux_samples = _gapsplit(constrained_model, depth=sampling_depth, cpus=cpus) warnings.filterwarnings('default') concordance = _calc_concordance(flux_samples, coefficient_dict) else: flux_samples = 'Not performed' concordance = 'Not performed' fva = flux_variability_analysis(constrained_model, fraction_of_optimum=fraction, processes=cpus) return flux_samples, fva, concordance
def set_fva_bounds(cobra_model): """ Sets reaction bounds using FVA. """ fva = flux_variability_analysis(cobra_model, fraction_of_optimum=0) for rxn in cobra_model.reactions: assert rxn.lower_bound <= rxn.upper_bound rxn.lower_bound = fva['minimum'][rxn.id] rxn.upper_bound = max(fva['maximum'][rxn.id], fva['minimum'][rxn.id])
def generate_fva_data(self, cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', reaction_list=None, allow_loops=True, solver='glpk'): print('FVA...') #add in loop law constrain if not allow_loops: cobra_model=construct_loopless_model(cobra_model); # calculate the reaction bounds using FVA self.fva_data = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', solver=solver, reaction_list=reaction_list, );
def variability_analysis(self, measured_metabolites): if type(self.drug) == list: self.combined_drug_knockout() elif self.drug != '': self.drug_knock_out() elif self.target != '': self.model.genes.get_by_id(self.target).knock_out() # TODO This is the point where I will add reactions most likely # print(measured_metabolites) self.set_objective(measured_metabolites) return flux_variability_analysis(self.model)
def results_genes_flux(model, rxn_name, flux_gene_off_on): ''' results_genes_flux utility: essential genes of model outputted nicely AND flux through the reactions being changed outputted Input: (1) model: model structure (2) rxn_name: string reaction name in list e.g. ['rxn00123','rxn00456',....] (3) flux_gene_off_on is list containing two binary values to turn off the reaction functionalities either [1,0] [0,0] or [0,1] first element is flux second is gene deletions is on Output: essential genes in pandas data arrary ''' #two models taken from the original try: if flux_gene_off_on[0] == 0: del_results = [] print('no gene del results returned') else: #Essential Genes Before - Biomass Results Before - Gene Knockouts print('Single Gene Deletion of Model Entered') model_genes = copy.deepcopy(model) del_results = single_gene_deletion(model_genes) if flux_gene_off_on[1] == 0: fluxes = [] print('No fluxes returned') else: model_flux = copy.deepcopy(model) #flux through reaction fluxes = [] loop_reactions = [] print('Rxn flux loop entered') for i in range(0, len(rxn_name)): loop_reactions.append( model_flux.reactions.get_by_id(rxn_name[i])) if i % 10 == 0: print('Flux reaction number', i) fluxes = (flux_variability_analysis(model_flux, reaction_list=loop_reactions, loopless=True) ) #range of fluxes through the reaction except: print('You must enter a cobra model structure') raise return [del_results, fluxes]
def generate_fva_data(self, cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', reaction_list=None, allow_loops=True, solver='glpk', verbose_I=True): if verbose_I: print('FVA...') #add in loop law constrain if not allow_loops: cobra_model=construct_loopless_model(cobra_model) # calculate the reaction bounds using FVA cobra_model.solver = solver fva_data = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9, objective_sense='maximize', reaction_list=reaction_list, ) self.fva_data = dict(zip(list(fva_data.index),fva_data.to_dict('records')))
def test_model_summary_interface(model, opt_solver): """Test that a summary can be created successfully.""" model.solver = opt_solver ModelSummary(model=model, ) ModelSummary( model=model, solution=pfba(model), ) ModelSummary( model=model, fva=0.95, ) ModelSummary( model=model, fva=flux_variability_analysis( model, reaction_list=["CYTBD", "NADH16", "SUCDi"]), )
def _generate( self, model: "Model", solution: Optional["Solution"], fva: Optional[Union[float, pd.DataFrame]], ) -> None: """ Prepare the data for the summary instance. Parameters ---------- model : cobra.Model The metabolic model for which to generate a metabolite summary. solution : cobra.Solution, optional A previous model solution to use for generating the summary. If ``None``, the summary method will generate a parsimonious flux distribution. fva : pandas.DataFrame or float, optional Whether or not to include flux variability analysis in the output. If given, `fva` should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched. """ super()._generate(model=model, solution=solution, fva=fva) if solution is None: logger.info("Generating new parsimonious flux distribution.") solution = pfba(model) if isinstance(fva, float): logger.info("Performing flux variability analysis.") fva = flux_variability_analysis( model, reaction_list=[self._reaction], fraction_of_optimum=fva, ) # Create the basic flux table. self._flux = pd.DataFrame( data={"flux": [solution[self._reaction.id]]}, index=[self._reaction.id], ) if fva is not None: self._flux = self._flux.join(fva)
def fva(self, reaction_list=None, loopless=False, fraction_of_optimum=1.0, pfba_factor=None, processes=None): try: return flux_variability_analysis(model=self.model, reaction_list=reaction_list, loopless=loopless, fraction_of_optimum=fraction_of_optimum, pfba_factor=pfba_factor, processes=processes) except Infeasible: return DataFrame()
def simulatingFVA(model): # FBA will not give always give unique solution, because multiple flux # states can achieve the same optimum. FVA (or flux variability analysis) # finds the ranges of each metabolic flux at the optimum. from cobra.flux_analysis import flux_variability_analysis print(flux_variability_analysis(model, model.reactions[:10])) # Setting parameter fraction_of_optimium=0.90 would give the flux ranges for reactions at 90% optimality. print( cobra.flux_analysis.flux_variability_analysis(model, model.reactions[:10], fraction_of_optimum=0.9, loopless=True)) model.optimize() model.summary( fva=0.95 ) # Flux variability analysis can also be embedded in calls to summary methods. model.metabolites.pyr_c.summary(fva=0.95)
def main(): print('================ SUBTASK 1: Building the Model ================') model = build_model() print("Reactions") print("---------") for x in model.reactions: print(f"{x.id}:{x.reaction}") print("") print("Metabolites") print("-----------") for x in model.metabolites: print(x.id) print( '\n================ SUBTASK 2: Computing the maximum flow through the growth reaction ================\n' ) solution = model.optimize() print(model.summary()) print('\n================ SUBTASK 3: FVA ================\n') fva = flux_variability_analysis(model) print(fva) print( '\n================ SUBTASK 4: Find essential reactions ================\n' ) #Knock out each reaction. If the objective value is 0, the reaction is essential. for reaction in model.reactions: with model as model: reaction.knock_out() model.optimize() if round(model.objective.value, 6) == 0: print( f"{reaction.id} blocked, new growth rate {round(model.objective.value,6)} -------> ESSENTIAL" ) else: print( f"{reaction.id} blocked, new growth rate {round(model.objective.value,6)}" )
def find_universally_blocked_reactions(model): """ Find metabolic reactions that are blocked. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- Blocked reactions are those reactions that when optimized for cannot carry any flux while all exchanges are open. """ with model: helpers.open_boundaries(model) fva_result = flux_variability_analysis(model) blocked = fva_result.loc[(fva_result["maximum"] == 0.0) & (fva_result["minimum"] == 0.0)] return [model.reactions.get_by_id(name) for name in blocked.index]
def test_reaction_summary_interface(model, opt_solver): """Test that a summary can be created successfully.""" model.solver = opt_solver reaction = model.reactions.get_by_id("FUM") ReactionSummary( reaction=reaction, model=model, ) ReactionSummary( reaction=reaction, model=model, solution=pfba(model), ) ReactionSummary( reaction=reaction, model=model, fva=0.95, ) ReactionSummary( reaction=reaction, model=model, fva=flux_variability_analysis(model, reaction_list=["FUM"]), )
fva_result_dict = {} atps_dict = {} for run in rxn_list.keys(): model_test = model.copy() rxns_added = [] fva_list = [model_test.reactions.ATPS, model_test.reactions.Eha_FSLASH_Ehb] for rxn in rxn_list[run]: addID = re.search('(rxn\d{5}_reverse)|(rxn\d{5})', rxn).group(0) formula = re.search('(cpd\d{5}.*$)|(\d+.\d+\scpd\d{5}.*$)', rxn).group(0) rxn = Reaction(addID) model_test.add_reaction(rxn) rxn.reaction = formula fva_list.append(rxn) rxns_added.append(rxn) fva_result = flux_analysis.flux_variability_analysis(model_test, fva_list) fva_result_dict[run] = fva_result, rxns_added rxns_added = [] for run in fva_result_dict.keys(): if fva_result_dict[run][0]['ATPS']['minimum'] > 0 and fva_result_dict[run][0]['ATPS']['maximum'] == 1000 \ and fva_result_dict[run][0]['Eha_FSLASH_Ehb']['maximum'] < 0: atps_dict[run] = fva_result_dict[run] for run in atps_dict.keys(): print run model_testing = model.copy() for i in range(len(atps_dict[run][1])): model_testing.add_reaction(atps_dict[run][1][i]) print atps_dict[run][1][i].build_reaction_string(True) print atps_dict[run][1][i].reaction