WINTER4000's picture
Initial deploy · DEE Flask app via Docker SDK
060bb47 verified
Raw History Blame Contribute Delete
9.66 kB
"""Phase 3 — Epistatic combinatorial optimizer.
Pure PLM single-site ΔLL is loosely additive but loses calibration as mutations
stack. To avoid both (a) pure greedy stacking into a local fitness trap and
(b) blind enumeration of an intractable combinatorial space, we use Simulated
Annealing over a *pre-filtered* mutation pool (top-percentile single-site
hits). Multiple independent SA runs from different random seeds populate a
hall-of-fame of K unique multi-mutants.
Fitness model:
fitness(M) = sum_{m in M} delta_ll(m) - penalty(M)
where the penalty discourages:
* more than one mutation at the same residue position,
* any mutation to an asterisk/stop symbol (defensive: ESM-2's 20-AA vocab
never emits "*", but synthesis pipelines occasionally do — we keep the
check so external callers can plug in noisier scorers safely).
"""
from __future__ import annotations
import logging
import math
import random
from dataclasses import dataclass, field
from typing import Dict, FrozenSet, List, Optional, Tuple
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
# Sentinel symbol for any non-AA token a scorer might emit. We refuse to
# include such "mutations" in a candidate multi-mutant.
_BAD_AA = {"*", "X", "U", "O", "B", "Z", "J"}
@dataclass(frozen=True)
class Mutation:
"""A single substitution. ``position`` is 0-indexed into the WT protein."""
position: int
wt_aa: str
mut_aa: str
delta_ll: float
@property
def label(self) -> str:
return f"{self.wt_aa}{self.position + 1}{self.mut_aa}"
def _df_to_mutation_pool(pool_df: pd.DataFrame) -> List[Mutation]:
"""Convert a (filtered) score DataFrame into a list of :class:`Mutation`."""
return [
Mutation(
position=int(row.position),
wt_aa=str(row.wt_aa),
mut_aa=str(row.mut_aa),
delta_ll=float(row.delta_ll),
)
for row in pool_df.itertuples(index=False)
if str(row.mut_aa) not in _BAD_AA
]
@dataclass
class SearchConfig:
"""Tunable parameters for :func:`evolve`."""
k: int = 100 # Number of unique multi-mutants to return.
max_mutations: int = 8 # Cap on simultaneous substitutions per variant.
min_mutations: int = 2 # Floor — single-site solutions are uninteresting here.
n_restarts: int = 12 # Independent SA runs feeding the hall of fame.
steps_per_restart: int = 2000
t_initial: float = 1.0
t_final: float = 1e-3
stop_penalty: float = 1e3 # Per stop/non-AA mutation included by mistake.
duplicate_position_penalty: float = 1e3 # Per repeated residue position.
seed: Optional[int] = None
@dataclass
class Variant:
"""Result type for an optimized multi-mutant."""
mutations: Tuple[Mutation, ...]
fitness: float
rank: int = 0
# Filled in later by Phase 4 once we know the mutant protein/DNA.
extras: Dict[str, str] = field(default_factory=dict)
@property
def mutation_labels(self) -> Tuple[str, ...]:
return tuple(m.label for m in self.mutations)
@property
def key(self) -> FrozenSet[Tuple[int, str]]:
"""Identity key — two Variants are duplicates if they share the same
{(position, mut_aa)} set, regardless of order."""
return frozenset((m.position, m.mut_aa) for m in self.mutations)
def _fitness(mutations: List[Mutation], cfg: SearchConfig) -> float:
score = sum(m.delta_ll for m in mutations)
seen_positions: set = set()
for m in mutations:
if m.mut_aa in _BAD_AA:
score -= cfg.stop_penalty
if m.position in seen_positions:
score -= cfg.duplicate_position_penalty
seen_positions.add(m.position)
return score
def _propose(
current: List[Mutation],
pool: List[Mutation],
pool_by_pos: Dict[int, List[Mutation]],
cfg: SearchConfig,
rng: random.Random,
) -> List[Mutation]:
"""Generate a neighboring state by add / remove / swap."""
moves = ["add", "remove", "swap"]
if len(current) <= cfg.min_mutations:
moves.remove("remove")
if len(current) >= cfg.max_mutations:
moves = [m for m in moves if m != "add"]
if not current:
moves = ["add"]
move = rng.choice(moves)
occupied = {m.position for m in current}
if move == "add":
candidates = [m for m in pool if m.position not in occupied]
if not candidates:
return current
return current + [rng.choice(candidates)]
if move == "remove":
idx = rng.randrange(len(current))
return current[:idx] + current[idx + 1 :]
# swap — replace the residue identity at an existing position, OR
# relocate one mutation to a new position. Both moves preserve cardinality.
idx = rng.randrange(len(current))
target = current[idx]
if rng.random() < 0.5:
alts = [m for m in pool_by_pos.get(target.position, []) if m.mut_aa != target.mut_aa]
if not alts:
return current
new_mut = rng.choice(alts)
else:
free_positions = [p for p in pool_by_pos if p not in occupied]
if not free_positions:
return current
new_pos = rng.choice(free_positions)
new_mut = rng.choice(pool_by_pos[new_pos])
return current[:idx] + [new_mut] + current[idx + 1 :]
def _simulated_anneal(
pool: List[Mutation],
pool_by_pos: Dict[int, List[Mutation]],
cfg: SearchConfig,
rng: random.Random,
hall_of_fame: Dict[FrozenSet[Tuple[int, str]], Variant],
) -> None:
"""One SA run. Mutates ``hall_of_fame`` in place with every state visited
that beats its previous best at the same identity key."""
init_k = rng.randint(cfg.min_mutations, min(cfg.max_mutations, max(cfg.min_mutations, 4)))
current: List[Mutation] = []
# Bias the initial state towards high-ΔLL mutations on distinct positions.
top_slice = sorted(pool, key=lambda m: m.delta_ll, reverse=True)[: max(20, init_k * 5)]
rng.shuffle(top_slice)
for cand in top_slice:
if all(cand.position != m.position for m in current):
current.append(cand)
if len(current) >= init_k:
break
current_fitness = _fitness(current, cfg)
best_in_run = current_fitness
# Geometric cooling schedule from t_initial to t_final over steps_per_restart.
cooling = (cfg.t_final / cfg.t_initial) ** (1.0 / max(1, cfg.steps_per_restart - 1))
temperature = cfg.t_initial
for _ in range(cfg.steps_per_restart):
proposal = _propose(current, pool, pool_by_pos, cfg, rng)
proposal_fitness = _fitness(proposal, cfg)
delta = proposal_fitness - current_fitness
if delta >= 0 or rng.random() < math.exp(delta / max(temperature, 1e-12)):
current = proposal
current_fitness = proposal_fitness
# Register every accepted high-quality state.
if current and current_fitness > best_in_run - 1.0:
sorted_muts = tuple(sorted(current, key=lambda m: m.position))
variant = Variant(mutations=sorted_muts, fitness=current_fitness)
prior = hall_of_fame.get(variant.key)
if prior is None or variant.fitness > prior.fitness:
hall_of_fame[variant.key] = variant
best_in_run = max(best_in_run, current_fitness)
temperature *= cooling
def evolve(pool_df: pd.DataFrame, cfg: Optional[SearchConfig] = None) -> List[Variant]:
"""Run the SA search and return the top-K unique multi-mutants.
``pool_df`` should be the *filtered* score table (e.g. top 15% from
:func:`dee.models.scorer.top_percentile_pool`) — restricting the search
space is the spec's epistatic heuristic that compensates for the loss of
PLM additivity at deep mutational depth.
"""
cfg = cfg or SearchConfig()
if pool_df.empty:
raise ValueError("Filtered mutation pool is empty; relax the percentile threshold.")
pool = _df_to_mutation_pool(pool_df)
pool_by_pos: Dict[int, List[Mutation]] = {}
for m in pool:
pool_by_pos.setdefault(m.position, []).append(m)
if len(pool_by_pos) < cfg.min_mutations:
raise ValueError(
f"Pool spans only {len(pool_by_pos)} residue positions; need >= "
f"{cfg.min_mutations} distinct positions for multi-mutant search."
)
rng = random.Random(cfg.seed)
hall_of_fame: Dict[FrozenSet[Tuple[int, str]], Variant] = {}
for restart in range(cfg.n_restarts):
run_rng = random.Random(rng.random())
_simulated_anneal(pool, pool_by_pos, cfg, run_rng, hall_of_fame)
logger.debug(
"Restart %d/%d done. Hall of fame size=%d.",
restart + 1,
cfg.n_restarts,
len(hall_of_fame),
)
ranked = sorted(hall_of_fame.values(), key=lambda v: v.fitness, reverse=True)[: cfg.k]
for i, v in enumerate(ranked):
v.rank = i + 1
logger.info(
"Search done. Returning top %d / %d unique variants. Best fitness=%.3f.",
len(ranked),
len(hall_of_fame),
ranked[0].fitness if ranked else float("nan"),
)
return ranked
def apply_variant(wt_protein: str, variant: Variant) -> str:
"""Apply a :class:`Variant`'s substitutions to the WT protein."""
chars = list(wt_protein)
for m in variant.mutations:
if chars[m.position] != m.wt_aa:
raise ValueError(
f"WT mismatch at position {m.position}: expected {m.wt_aa}, "
f"saw {chars[m.position]}."
)
chars[m.position] = m.mut_aa
return "".join(chars)