diff --git a/CHANGELOG.md b/CHANGELOG.md index 8146cc5..d8a99cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +* `sensitivity_tuning` selects the first enzyme or reaction of the model when two have equal flux (within a relative 1e-9), as `sensitivityTuning` does. It took the first reaction of an unordered set, so a tie could give a different kcat than MATLAB. * `kcat_evidence` shows, for selected reactions, the kcat of every source file next to the kcat of the model and, for a tuned kcat, the kcat before tuning. The reactions are selected by name (`rxns`), by enzyme (`enzymes`, for example the enzymes that `flexibilize_enz_concs` relaxed) or by the result of `sensitivity_tuning` (`tuned`); `compute=["ec_tree"]` adds the EC-tree estimate without a source file. `kcats_for_reactions` gets the kcats of every source for a few reactions, computes the EC-tree estimate and, with `okp`, predicts them with one, several or all OpenKineticsPredictor methods. `kcats_from_okp` has `job_tag`, which keeps a job for a few reactions apart from the job of all reactions: it has its own job, input and result files. GECKO has `kcatEvidence`, `kcatsForReactions` and the `jobTag` option of `kcatsFromOKP`. * `kcats_from_ec_tree` marks a reverse direction (`_REV`) in `detail` with `direction=reverse`. The estimate depends on the EC number only, as BRENDA measurements have no direction, so the reverse direction has the value of the forward direction. GECKO's `kcatsFromECTree` does the same. * `load_uniprot_tsv` always splits a gene cell of uniprot.tsv with several gene names, separated by semicolons and/or whitespace (`YPR080W; YBR118W`), into one row per gene name; the other columns are repeated on every row and an empty cell stays one row. A model gene that is any of the names finds the entry. The `split_gene_cells` option is removed. GECKO's `loadDatabases` does the same. diff --git a/src/geckopy/kcat_tuning/sensitivity_tuning.py b/src/geckopy/kcat_tuning/sensitivity_tuning.py index fd32c48..c264387 100644 --- a/src/geckopy/kcat_tuning/sensitivity_tuning.py +++ b/src/geckopy/kcat_tuning/sensitivity_tuning.py @@ -54,6 +54,7 @@ # Growth is considered stalled when an iteration improves it by no more # than this (absolute, 1/h). Using a tolerance instead of exact equality # avoids spinning on sub-numerical-noise increases. +_TIE_TOL = 1e-9 _GROWTH_STALL_TOL = 1e-9 @@ -303,17 +304,15 @@ def sensitivity_tuning( tuned_ec_indices.append(ec_rows[0]) continue - # Pick usage rxn with max flux (= most produced enzyme), - # excluding any in prot_to_ignore. + # Pick the usage rxn with the largest flux (the most produced enzyme), + # excluding any in prot_to_ignore. Ties go to the first rxn of the model. + usage_ids = [uid for uid in usage_rxn_ids if uid not in ignore_usage_ids] + usage_fluxes = [float(sol.fluxes.get(uid, 0.0)) for uid in usage_ids] best_usage_id: Optional[str] = None best_usage_flux = -np.inf - for uid in usage_rxn_ids: - if uid in ignore_usage_ids: - continue - f = float(sol.fluxes.get(uid, 0.0)) - if f > best_usage_flux: - best_usage_flux = f - best_usage_id = uid + if usage_ids: + k = _first_tied(usage_fluxes, largest=True) + best_usage_id, best_usage_flux = usage_ids[k], usage_fluxes[k] if best_usage_id is None or best_usage_flux <= 0: logger.warning( @@ -337,17 +336,13 @@ def sensitivity_tuning( # Find the catalysed rxn consuming the most of this protein. # Consumption: S[prot, rxn] < 0 with positive flux -> negative product. # The rxn with the most-negative S[prot] * flux is selected. + # Ties go to the first rxn of the model. + position = {r.id: i for i, r in enumerate(model.reactions)} + consumers = sorted((r for r in prot_met.reactions if r.id != best_usage_id), key=lambda r: position[r.id]) + values = [r.metabolites[prot_met] * float(sol.fluxes.get(r.id, 0.0)) for r in consumers] target_rxn = None - target_value = 0.0 - for rxn in prot_met.reactions: - if rxn.id == best_usage_id: - continue - coeff = rxn.metabolites[prot_met] - flux = float(sol.fluxes.get(rxn.id, 0.0)) - value = coeff * flux - if value < target_value: - target_value = value - target_rxn = rxn + if values and min(values) < 0: + target_rxn = consumers[_first_tied(values, largest=False)] if target_rxn is None: logger.warning( @@ -391,6 +386,16 @@ def sensitivity_tuning( return result +def _first_tied(values: list[float], *, largest: bool) -> int: + """Index of the first value that ties with the extreme value, that is, + that differs from it by less than a relative ``_TIE_TOL``.""" + arr = np.asarray(values, dtype=float) + best = arr.max() if largest else arr.min() + tol = _TIE_TOL * max(1.0, abs(best)) + hits = np.flatnonzero(arr >= best - tol if largest else arr <= best + tol) + return int(hits[0]) + + def _mark_tuned(model: "EcModel", ec_idx: int) -> None: """Add the tuning method to the source of one ec row. @@ -446,17 +451,11 @@ def _light_step( """The ec rows of the reaction with the most flux through the protein pool (gecko-light), or ``None`` when no reaction draws on it.""" pool = model.metabolites.get_by_id(POOL_ID) - best_id: Optional[str] = None - best_value = 0.0 - for rxn in model.reactions: - if rxn.id in ignore_rxn_ids or pool not in rxn.metabolites: - continue - value = rxn.metabolites[pool] * float(sol.fluxes.get(rxn.id, 0.0)) - if value < best_value: - best_value = value - best_id = rxn.id - if best_id is None: + candidates = [r for r in model.reactions if r.id not in ignore_rxn_ids and pool in r.metabolites] + values = [r.metabolites[pool] * float(sol.fluxes.get(r.id, 0.0)) for r in candidates] + if not values or min(values) >= 0: return None + best_id = candidates[_first_tied(values, largest=False)].id rows = [ i for i, ec_id in enumerate(model.ec.rxns) if split_light_rxn_id(ec_id)[1] == best_id diff --git a/tests/test_sensitivity_tuning.py b/tests/test_sensitivity_tuning.py index 48eab70..5b226ba 100644 --- a/tests/test_sensitivity_tuning.py +++ b/tests/test_sensitivity_tuning.py @@ -1,4 +1,5 @@ """Tests for sensitivity_tuning.""" +import importlib from pathlib import Path import cobra @@ -319,3 +320,54 @@ def test_docstrings_name_the_standard_and_advanced_tuning(): assert "standard kcat tuning" in sensitivity_tuning.__doc__ assert "advanced kcat tuning" in cmaes_kcat_tuning.__doc__ + + +# --------------------------------------------------------------------------- # +# Ties +# --------------------------------------------------------------------------- # + +class _Solution: + status = "optimal" + + def __init__(self, objective_value, fluxes): + self.objective_value = objective_value + self.fluxes = fluxes + + +@pytest.mark.parametrize("first", ["R", "R2"]) +def test_a_tie_between_reactions_of_an_enzyme_goes_to_the_first_in_the_model(tmp_path, monkeypatch, first): + """R and R2 consume the same amount of prot_E: the first one in the model is tuned.""" + adapter = _adapter(tmp_path, gr_exp=50.0) + model = _build_toy(adapter) + r2 = cobra.Reaction("R2") + r2.add_metabolites({ + model.metabolites.get_by_id("A_c"): -1.0, + model.metabolites.get_by_id("prot_E"): model.reactions.get_by_id("R").metabolites[model.metabolites.get_by_id("prot_E")], + model.metabolites.get_by_id("bio_met"): 1.0, + }) + r2.bounds = (0.0, 1000.0) + model.add_reactions([r2]) + if first == "R2": + r = model.reactions.get_by_id("R") + model.remove_reactions([r]) + model.add_reactions([r]) + model.ec.rxns = ["R", "R2"] + model.ec.kcat = np.array([1.0, 1.0]) + model.ec.source = ["initial", "initial"] + model.ec.notes = ["", ""] + model.ec.eccodes = ["", ""] + model.ec.rxn_enz_mat = sparse.csr_matrix([[1.0], [1.0]]) + consumption = {"usage_prot_E": 2.0, "R": 1.0, "R2": 1.0} + answers = iter([_Solution(1.0, consumption), _Solution(100.0, consumption)]) + monkeypatch.setattr(importlib.import_module("geckopy.kcat_tuning.sensitivity_tuning"), "optimize_model", lambda m: next(answers)) + result = sensitivity_tuning(model, fold_change=10.0, verbose=False) + assert list(result.rxns) == [first] + + +def test_first_tied_takes_the_first_value_within_the_tolerance(): + from geckopy.kcat_tuning.sensitivity_tuning import _first_tied + + assert _first_tied([1.0, 3.0, 3.0 - 1e-12, 2.0], largest=True) == 1 + assert _first_tied([3.0 - 1e-12, 3.0, 1.0], largest=True) == 0 + assert _first_tied([-1.0, -3.0, -3.0, -2.0], largest=False) == 1 + assert _first_tied([-2.0, -3.0], largest=False) == 1