|
| 1 | +"""Flux Scanning based on Enforced Objective Flux — FSEOF (port + redesign). |
| 2 | +
|
| 3 | +FSEOF (Choi et al., Appl Environ Microbiol 2010) finds metabolic-engineering targets |
| 4 | +for over-producing a metabolite: enforce an increasing flux toward the target product |
| 5 | +while optimising growth, and watch how each reaction's flux responds. This is a port |
| 6 | +of RAVEN's ``FSEOF`` with a substantially richer, more robust output (RAVEN's |
| 7 | +weaknesses are noted in IMPROVEMENTS, FS1–FS4): |
| 8 | +
|
| 9 | +* **Robust trend, not strict monotonicity.** Each reaction's flux is regressed against |
| 10 | + the enforced product flux across the scan; the **slope** is the response and the |
| 11 | + **correlation** (|r|) is a quality score. A reaction is a target if it tracks the |
| 12 | + product cleanly (|r| ≥ ``correlation_threshold``) — one noisy step from LP |
| 13 | + alternative optima no longer discards it (and pFBA per step keeps the scan stable). |
| 14 | +* **Direction classification RAVEN lacks.** Targets are labelled ``amplify`` (|flux| |
| 15 | + rises with the product → over-express), ``knockdown`` (|flux| falls), or ``knockout`` |
| 16 | + (|flux| → ~0 → delete). RAVEN only ever reports the amplification targets. |
| 17 | +* **Gene-level view** via :attr:`FSEOFResult.gene_targets`, and the full flux scan is |
| 18 | + retained in :attr:`FSEOFResult.scan` — all as DataFrames, not a printed TSV. |
| 19 | +""" |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +from dataclasses import dataclass |
| 23 | + |
| 24 | +import cobra |
| 25 | +import numpy as np |
| 26 | +import pandas as pd |
| 27 | +from cobra.exceptions import OptimizationError |
| 28 | +from cobra.flux_analysis import pfba |
| 29 | +from scipy.stats import linregress |
| 30 | + |
| 31 | + |
| 32 | +@dataclass |
| 33 | +class FSEOFResult: |
| 34 | + """FSEOF output. |
| 35 | +
|
| 36 | + ``scan`` is reactions × enforced-flux-levels (the full flux scan); ``enforced`` are |
| 37 | + the enforced target fluxes; ``targets`` is the classified per-reaction table |
| 38 | + (sorted by score). :attr:`gene_targets` aggregates targets to genes. |
| 39 | + """ |
| 40 | + |
| 41 | + scan: pd.DataFrame |
| 42 | + enforced: list[float] |
| 43 | + targets: pd.DataFrame |
| 44 | + |
| 45 | + @property |
| 46 | + def amplification(self) -> pd.DataFrame: |
| 47 | + return self.targets[self.targets["target_type"] == "amplify"].reset_index(drop=True) |
| 48 | + |
| 49 | + @property |
| 50 | + def knockout(self) -> pd.DataFrame: |
| 51 | + mask = self.targets["target_type"].isin(["knockout", "knockdown"]) |
| 52 | + return self.targets[mask].reset_index(drop=True) |
| 53 | + |
| 54 | + @property |
| 55 | + def gene_targets(self) -> pd.DataFrame: |
| 56 | + """Per-gene aggregation: the target reactions each gene is associated with.""" |
| 57 | + rows = [] |
| 58 | + for _, t in self.targets.iterrows(): |
| 59 | + for gene in t["genes"]: |
| 60 | + rows.append({"gene": gene, "reaction": t["reaction"], |
| 61 | + "target_type": t["target_type"], "slope": t["slope"]}) |
| 62 | + if not rows: |
| 63 | + return pd.DataFrame(columns=["gene", "target_type", "reactions", "max_abs_slope"]) |
| 64 | + df = pd.DataFrame(rows) |
| 65 | + agg = df.groupby("gene").agg( |
| 66 | + target_type=("target_type", lambda s: ";".join(sorted(set(s)))), |
| 67 | + reactions=("reaction", lambda s: ";".join(sorted(set(s)))), |
| 68 | + max_abs_slope=("slope", lambda s: float(np.max(np.abs(s)))), |
| 69 | + ).reset_index() |
| 70 | + return agg.sort_values("max_abs_slope", ascending=False, ignore_index=True) |
| 71 | + |
| 72 | + |
| 73 | +def fseof( |
| 74 | + model: cobra.Model, |
| 75 | + target_rxn: str, |
| 76 | + *, |
| 77 | + biomass_rxn: str | None = None, |
| 78 | + n_steps: int = 10, |
| 79 | + max_fraction: float = 0.9, |
| 80 | + correlation_threshold: float = 0.9, |
| 81 | + flux_eps: float = 1e-6, |
| 82 | +) -> FSEOFResult: |
| 83 | + """Run FSEOF for over-production of ``target_rxn``'s product. |
| 84 | +
|
| 85 | + Enforces target flux from ``max_fraction/n_steps`` up to ``max_fraction`` of the |
| 86 | + theoretical maximum in ``n_steps`` steps, maximising growth (``biomass_rxn`` or the |
| 87 | + model's current objective) with pFBA at each step. Returns an :class:`FSEOFResult`. |
| 88 | + """ |
| 89 | + with model: # find the theoretical maximum target flux |
| 90 | + model.objective = target_rxn |
| 91 | + target_opt = model.slim_optimize() |
| 92 | + # slim_optimize returns NaN on an infeasible model; np.isfinite catches that too. |
| 93 | + if target_opt is None or not np.isfinite(target_opt) or target_opt <= flux_eps: |
| 94 | + raise ValueError(f"{target_rxn!r} cannot carry positive flux; nothing to scan.") |
| 95 | + target_max = target_opt * max_fraction |
| 96 | + levels = [target_max * (i + 1) / n_steps for i in range(n_steps)] |
| 97 | + |
| 98 | + columns: dict[float, pd.Series] = {} |
| 99 | + enforced: list[float] = [] |
| 100 | + for level in levels: |
| 101 | + with model: |
| 102 | + if biomass_rxn is not None: |
| 103 | + model.objective = biomass_rxn |
| 104 | + model.reactions.get_by_id(target_rxn).lower_bound = level |
| 105 | + try: |
| 106 | + columns[level] = pfba(model).fluxes |
| 107 | + except OptimizationError: |
| 108 | + break # enforced flux became infeasible — stop scanning |
| 109 | + enforced.append(level) |
| 110 | + if len(enforced) < 2: |
| 111 | + raise RuntimeError("FSEOF needs at least two feasible enforced-flux levels.") |
| 112 | + |
| 113 | + scan = pd.DataFrame(columns) |
| 114 | + targets = _classify(model, scan, np.asarray(enforced), correlation_threshold, flux_eps) |
| 115 | + return FSEOFResult(scan=scan, enforced=enforced, targets=targets) |
| 116 | + |
| 117 | + |
| 118 | +def _classify(model, scan, enforced, corr_threshold, flux_eps) -> pd.DataFrame: |
| 119 | + rows = [] |
| 120 | + for rxn in model.reactions: |
| 121 | + flux = scan.loc[rxn.id, enforced.tolist() if hasattr(enforced, "tolist") else enforced] |
| 122 | + flux = flux.to_numpy(dtype=float) |
| 123 | + initial, final = flux[0], flux[-1] |
| 124 | + if flux.std() < flux_eps: # flat -> no response |
| 125 | + continue |
| 126 | + fit = linregress(enforced, flux) |
| 127 | + slope, corr = float(fit.slope), float(fit.rvalue) |
| 128 | + if abs(corr) < corr_threshold or abs(slope) < flux_eps: |
| 129 | + continue |
| 130 | + # Classify on the slope of |flux| vs the enforced product flux — the |
| 131 | + # criterion the docstring states (|flux| rises = amplify, etc.). The |
| 132 | + # old endpoint-only check (``abs(final) vs abs(initial)``) could |
| 133 | + # mislabel a track whose first/last values straddled a peak/trough but |
| 134 | + # whose overall trend was the opposite. Keep ``knockout`` for tracks |
| 135 | + # the regression drives essentially to zero. |
| 136 | + abs_fit = linregress(enforced, np.abs(flux)) |
| 137 | + abs_slope = float(abs_fit.slope) |
| 138 | + if abs(final) < flux_eps and abs_slope < 0: |
| 139 | + ttype = "knockout" |
| 140 | + elif abs_slope > 0: |
| 141 | + ttype = "amplify" |
| 142 | + else: |
| 143 | + ttype = "knockdown" |
| 144 | + rows.append({ |
| 145 | + "reaction": rxn.id, |
| 146 | + "name": rxn.name, |
| 147 | + "subsystem": rxn.subsystem, |
| 148 | + "gene_reaction_rule": rxn.gene_reaction_rule, |
| 149 | + "genes": sorted(g.id for g in rxn.genes), |
| 150 | + "target_type": ttype, |
| 151 | + "slope": slope, |
| 152 | + "correlation": corr, |
| 153 | + "initial_flux": initial, |
| 154 | + "final_flux": final, |
| 155 | + "score": abs(slope) * abs(corr), |
| 156 | + }) |
| 157 | + table = pd.DataFrame(rows, columns=[ |
| 158 | + "reaction", "name", "subsystem", "gene_reaction_rule", "genes", |
| 159 | + "target_type", "slope", "correlation", "initial_flux", "final_flux", "score", |
| 160 | + ]) |
| 161 | + return table.sort_values("score", ascending=False, ignore_index=True) |
0 commit comments