SeqOpt.run

SeqOpt.run(df_seq, df_feat, objectives, *, algorithm='nsga2', pop_size=50, n_gen=20, crossover='uniform', mutation='substitution', cx_prob=0.5, mut_prob=0.2, survival='mu_plus_lambda', variation='and', constraints=None, penalty='delta', hof_size=10, n_mut_max=5, region=None, to_aa=None, init='random', seed=None, jmd_n_len=10, jmd_c_len=10, lineage=False)[source]

Run multi-objective directed evolution and return the Pareto front of variants.

A population of multi-mutation variants of the single wild-type df_seq is evolved by NSGA-II (algorithm='nsga2') or an importance-ordered greedy walk (algorithm='greedy'), scored on every objective, and reduced to the non-dominated trade-off front.

Parameters:
  • df_seq (pd.DataFrame, shape (1, n_seq_info)) – DataFrame containing an entry column with unique protein identifiers, in the position-based format (sequence, tmd_start, tmd_stop). See SequenceFeature.get_df_parts() for the full df_seq format specification. Must hold exactly one wild-type sequence (SeqOpt optimizes one sequence per run).

  • df_feat (pd.DataFrame) – CPP feature set (output of CPP.run()) defining the features and the residue attribution (feat_importance / feat_impact, positions) the search reads.

  • objectives (list of (str, str, object)) – (name, goal, source) per objective; goal in {'max','min'} and source in {'delta_pred','delta_cpp','shift_score','n_mut'} or a callable(sequence) -> float. The callable receives the variant sequence and returns a scalar, so any external predictor (scikit / torch model, or a sequence-level tool / web API such as a topology or signal-peptide predictor) can be optimized as an objective; its result is cached per distinct variant. At least two objectives.

  • algorithm (str, default='nsga2') – 'nsga2' (population) or 'greedy' (importance-ordered single path).

  • pop_size (int, default=50) – Population size (NSGA-II only).

  • n_gen (int, default=20) – Number of generations (NSGA-II only).

  • crossover (str, default='uniform') – Crossover operator: 'uniform' / 'one_point' / 'two_point'.

  • mutation (str, default='substitution') – Mutation operator: 'substitution' or 'shift'.

  • cx_prob (float, default=0.5) – Per-pair crossover probability.

  • mut_prob (float, default=0.2) – Per-individual mutation probability.

  • survival (str, default='mu_plus_lambda') – Survival scheme: 'mu_plus_lambda' (elitist), 'mu_comma_lambda' or 'ea_simple' (generational replacement).

  • variation (str, default='and') – Variation scheme: 'and' (varAnd — crossover and mutation) or 'or' (varOr — each offspring is crossover or mutation or reproduction; needs cx_prob+mut_prob<=1).

  • constraints (list of callable or DesignConstraints, optional) –

    Design limits, in either of two forms. A list of callables is the published form: feasibility predicates genome -> bool (True = feasible) over the internal {1-based position: target amino acid} genome; infeasible variants are penalized so the search avoids them. A DesignConstraints object is the shared, declarative form: its mutable_positions / permitted_substitutions / n_mut_max are the object form of region / to_aa / n_mut_max and restrict the search space directly, while its sequence-level limits (immutable positions, forbidden substitutions, identity bounds, motifs) are turned into one feasibility predicate via DesignConstraints.as_predicate() and penalized the same way. Passing the object together with a region / to_aa / non-default n_mut_max that sets the same limit differently raises. None (default) applies no limit.

    Changed in version 1.2.0: Also accepts a DesignConstraints object; the list-of-callables form is unchanged.

  • penalty (str, default='delta') – Penalty applied to infeasible variants: 'delta' (fixed worst objective) or 'closest_valid' (penalty scaled by the number of violated constraints).

  • hof_size (int, default=10) – Size of the single-objective Hall of Fame (SeqOpt.hall_of_fame_) accumulated across generations.

  • n_mut_max (int, default=5) – Maximum number of point mutations per variant. Shorthand for the n_mut_max of constraints, which it builds internally.

  • region (str or list of int, optional) – Restrict the mutable span (see SeqMut.scan()). Shorthand for the mutable_positions of constraints, which it builds internally.

  • to_aa (list of str, optional) – Substitution alphabet (see SeqMut.scan()). Shorthand for the permitted_substitutions of constraints, which it builds internally.

  • init (str, default='random') – Population initialization: 'random' or 'suggest' (warm start from the top single mutations).

  • seed (int, optional) – Per-call seed; overrides the constructor random_state.

  • jmd_n_len (int, default=10) – Length of JMD-N in number of amino acids.

  • jmd_c_len (int, default=10) – Length of JMD-C in number of amino acids.

  • lineage (bool or dict, default=False) –

    Opt in to the candidate-lineage record: the thin, JSON-serializable record of how each returned variant was made (its content-hash candidate_id, its parent, the ordered wild-type-relative mutations, the generating method and algorithm, the objective values, the effective seed, and a digest of the applied design limits). False (default) builds nothing and leaves the returned table exactly as documented below. True builds one record per returned variant, treating the wild-type as the root of the chain. Passing a lineage record (one element of a previous SeqOpt.lineage_ or SeqMut.lineage_) opts in and declares that parent: its candidate_id becomes the parent_id of every record built here, which is how the rounds of a multi-generation design chain up – one run optimizes one wild-type, so a candidate that becomes the next round’s df_seq is linked through its record, not through the internal n_gen counter. When opted in, the records are stored in SeqOpt.lineage_, row-aligned with the returned table, and the candidate_id column is appended.

    Added in version 1.2.0.

Returns:

df_pareto – One row per final-population variant with entry, variant, n_mut, sequence_mut, one column per objective (named by objectives), the non-dominated rank (0 = best front) and the crowding distance, sorted by rank then descending crowding. When lineage is opted in, the candidate_id column is appended.

Return type:

pd.DataFrame

Raises:

ValueError – If df_seq does not hold exactly one position-based wild-type, if objectives or any option string is invalid, if constraints is neither a list of callables nor a DesignConstraints object, if it conflicts with region / to_aa / n_mut_max, if lineage is neither a bool nor a lineage record, or if the resulting search space is empty.

See also

Examples

import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
import aaanalysis as aa
aa.options["verbose"] = False

# Gamma-secretase (GSEC) substrate data + the bundled interpretable CPP feature set.
df_feat = aa.load_features(name="DOM_GSEC")           # 150 CPP features (with positions, feat_importance)
df_seq  = aa.load_dataset(name="DOM_GSEC", n=50)      # 100 TMD sequences, label 1 = GSEC substrate
labels  = df_seq["label"].to_list()

# A simple RandomForest substrate classifier on the CPP feature matrix.
sf = aa.SequenceFeature()
X = np.asarray(sf.feature_matrix(features=df_feat["feature"],
                                 df_parts=sf.get_df_parts(df_seq=df_seq),
                                 df_scales=aa.load_scales()), dtype=float)
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(X, labels)

# Pick a NON-substrate as the wild-type and design a "super substrate": mutate its TMD to
# maximize the predicted substrate probability with as few mutations as possible.
wt = df_seq[df_seq["label"] == 0].iloc[[0]].reset_index(drop=True)
objectives = [("substrate", "max", "delta_pred"),     # raise P(GSEC substrate) (RF prediction shift)
              ("parsimony", "min", "n_mut")]          # with as few mutations as possible

Run NSGA-II and read off the Pareto front (rank=0 = the non-dominated trade-offs):

seqo = aa.SeqOpt(mode="importance", model=model, target_class=1, random_state=42)
df_pareto = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives,
                       algorithm="nsga2", pop_size=40, n_gen=20, n_mut_max=5, region="tmd")
aa.display_df(df_pareto, n_rows=10, show_shape=True)
DataFrame shape: (7, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 0.000000 0 inf
2 Q14802 L37T+I55T+V56L+S58Q+A59R 5 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 37.000000 5.000000 0 inf
3 Q14802 L37G+A59R 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 29.000000 2.000000 0 0.429730
4 Q14802 A59R 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.316216
5 Q14802 L37G+V56L+A59R 3 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 33.000000 3.000000 0 0.281081
6 Q14802 A59K 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.275676
7 Q14802 L37G+V56L+S58Q+A59R 4 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 35.000000 4.000000 0 0.254054

Guidance mode. Above used mode=\"importance\" (static feat_importance). The headline mode=\"impact\" refits a ShapModel every generation (fuzzy labeling) to mutate the residues SHAP deems most important — pass the labeled reference set:

df_shap = aa.SeqOpt(mode="impact", model=model, target_class=1, df_seq_ref=df_seq,
                    labels=labels, random_state=0).run(
    df_seq=wt, df_feat=df_feat, objectives=objectives, pop_size=12, n_gen=4,
    n_mut_max=4, region="tmd")
aa.display_df(df_shap, n_rows=10, show_shape=True)
DataFrame shape: (9, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 0.000000 0 inf
2 Q14802 C49E+S58R 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 21.000000 2.000000 0 inf
3 Q14802 S58F 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 8.000000 1.000000 0 0.559524
4 Q14802 V56M 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 8.000000 1.000000 0 0.440476
5 Q14802 C49E 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 8.000000 1.000000 0 0.000000
6 Q14802 C49E+S58R+A59W 3 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 20.000000 3.000000 1 inf
7 Q14802 A50G 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 1.000000 1 inf
8 Q14802 A50G+S58R 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 14.000000 2.000000 1 1.000000
9 Q14802 C49Y+A50G+S58R+A59W 4 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 20.000000 4.000000 2 inf

Constructor defaults. mode="importance" is the default, so a bare aa.SeqOpt() constructs in a base install (no model, no reference set, and no pro extra needed). df_scales sets the amino acid scales used for featurization, verbose toggles progress output, and random_state seeds the evolutionary search:

# A bare SeqOpt() constructs in a base install: the default mode is "importance".
print("bare construction:", type(aa.SeqOpt()).__name__)

seqo = aa.SeqOpt(mode="importance", model=model, target_class=1,
                 df_scales=aa.load_scales(),  # amino acid scales used for featurization
                 verbose=False,               # no progress output
                 random_state=42)
df_defaults = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives,
                       pop_size=12, n_gen=4, n_mut_max=3, region="tmd")
aa.display_df(df_defaults, n_rows=10, show_shape=True)
bare construction: SeqOpt
DataFrame shape: (4, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 0.000000 0 inf
2 Q14802 I43P+A59Q 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 14.000000 2.000000 0 inf
3 Q14802 A59Y 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 6.000000 1.000000 0 0.535714
4 Q14802 A59Q 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 6.000000 1.000000 0 0.464286

Algorithm + operators. Swap the search and the evolutionary operators: a deterministic importance-ordered greedy baseline, or NSGA-II with varOr variation, ea_simple survival, two-point crossover, shift mutation.

df_greedy = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives,
                       algorithm="greedy", n_mut_max=5, region="tmd")
df_or = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives, pop_size=40,
                   n_gen=20, n_mut_max=5, region="tmd", variation="or",
                   survival="ea_simple", crossover="two_point", mutation="shift",
                   cx_prob=0.5, mut_prob=0.3)
aa.display_df(df_greedy, n_rows=10, show_shape=True)
DataFrame shape: (5, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 A59K 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 inf
2 Q14802 I55A+V56L+M57A+S58K+A59K 5 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 29.000000 5.000000 0 inf
3 Q14802 S58K+A59K 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 23.000000 2.000000 0 0.596154
4 Q14802 M57A+S58K+A59K 3 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 25.000000 3.000000 0 0.442308
5 Q14802 I55A+M57A+S58K+A59K 4 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 28.000000 4.000000 0 0.403846

Constraints + Hall of Fame. The design limits live in one DesignConstraints object — the same shared container AAMut and SeqMut accept — which SeqOpt.run takes directly as constraints: the position and residue limits restrict the search space, the sequence-level limits are penalized through its feasibility path. Here the first TMD residue is immutable, the substitution alphabet is restricted, and the mutation budget is part of the same set. hall_of_fame_ then holds the single-objective best-k variants:

tmd_start = int(wt["tmd_start"].iloc[0])
# ONE constraints object for the whole campaign: SeqMut and AAMut accept the same instance.
dc = aa.DesignConstraints(immutable_positions=[tmd_start],
                          permitted_substitutions=["A", "L", "V", "K", "R"],
                          n_mut_max=5,
                          parent=wt["sequence"].iloc[0])
df_con = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives, pop_size=40,
                    n_gen=20, region="tmd",
                    constraints=dc, penalty="delta",
                    hof_size=5)
print("Hall of Fame (best by substrate gain):", seqo.hall_of_fame_)
# Every variant on the front satisfies the same limits, whichever tool applies them:
print("all feasible by dc.check:", all(dc.check(candidate=s)[0] for s in df_con["sequence_mut"]))
aa.display_df(df_con, n_rows=10, show_shape=True)
Hall of Fame (best by substrate gain): ['C49L+G52V+S58R+A59R', 'C49L+G52L+S58A+A59R', 'C49L+G52V+S58A+A59R', 'C49L+S58R+A59R', 'L48V+C49L+I55L+S58A+A59R']
all feasible by dc.check: True
DataFrame shape: (6, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 0.000000 0 inf
2 Q14802 C49L+G52V+S58R+A59R 4 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 40.000000 4.000000 0 inf
3 Q14802 S58R+A59R 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 27.000000 2.000000 0 0.500000
4 Q14802 C49L+S58R+A59R 3 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 36.000000 3.000000 0 0.412500
5 Q14802 A59R 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.325000
6 Q14802 A59K 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.262500

Any predictor as an objective. Besides the features-model (delta_pred), an objective can be any callable(sequence) -> float — a scikit/torch model or a sequence-level tool / web API (e.g. a topology or signal-peptide predictor such as Phobius / TMHMM). Results are cached per variant. Here a simple aromatic-stretch proxy:

import re
def aromatic_stretch(sequence):
    return float(max((len(r) for r in re.findall(r"[FWY]+", sequence)), default=0))
obj_ext = [("substrate", "max", "delta_pred"),
           ("aromatic", "min", aromatic_stretch),  # external predictor / API goes here
           ("parsimony", "min", "n_mut")]
df_ext = seqo.run(df_seq=wt, df_feat=df_feat, objectives=obj_ext, pop_size=30,
                    n_gen=15, n_mut_max=4, region="tmd")
aa.display_df(df_ext, n_rows=10, show_shape=True)
DataFrame shape: (6, 9)
  entry variant n_mut sequence_mut substrate aromatic parsimony rank crowding
1 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 3.000000 0.000000 0 inf
2 Q14802 C49F+G52L+S58R+A59K 4 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 36.000000 3.000000 4.000000 0 inf
3 Q14802 A59R 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 3.000000 1.000000 0 inf
4 Q14802 C49F+A59K 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 26.000000 3.000000 2.000000 0 0.305556
5 Q14802 C49F+S58R+A59K 3 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 31.000000 3.000000 3.000000 0 0.259259
6 Q14802 A59K 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 3.000000 1.000000 0 0.231481

Further parameters. init chooses the population start ('random' or 'suggest', a warm start from the top single mutations), to_aa restricts the substitution alphabet, seed makes a single run reproducible (overriding the constructor random_state), and jmd_n_len / jmd_c_len set the split geometry used to place mutations and build the CPP features. Kept small (few generations) so it finishes fast:

df_further = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives,
                        algorithm="nsga2", pop_size=12, n_gen=4, n_mut_max=4,
                        region="tmd",
                        init="suggest",                   # warm start from top single mutations
                        to_aa=["A", "L", "V", "K", "R"],  # restrict substitution alphabet
                        seed=1,                           # reproducible run (overrides random_state)
                        jmd_n_len=10, jmd_c_len=10)        # split geometry
aa.display_df(df_further, n_rows=10, show_shape=True)
DataFrame shape: (4, 8)
  entry variant n_mut sequence_mut substrate parsimony rank crowding
1 Q14802 S58R+A59K 2 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 23.000000 2.000000 0 inf
2 Q14802 0 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.000000 0.000000 0 inf
3 Q14802 A59R 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.597826
4 Q14802 A59K 1 MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 16.000000 1.000000 0 0.402174

Candidate lineage. lineage attaches a thin, JSON-serializable record to every returned variant: a content-hash candidate_id over the wild-type and the ordered mutations, the parent_id, the mutations themselves, the method (with the algorithm), the objective_values, the effective seed and a digest of the applied design limits. Opt-in and purely additive: lineage=True appends the candidate_id column and fills lineage_, and passing a record instead chains this run onto the candidate it came from, which SeqOpt.trace_lineage replays:

import json

df_lineage = seqo.run(df_seq=wt, df_feat=df_feat, objectives=objectives, pop_size=12,
                      n_gen=4, n_mut_max=3, region="tmd", lineage=True)
aa.display_df(df_lineage[["variant", "n_mut", "candidate_id"]], n_rows=10,
              show_shape=True)
# The front may also hold the unmutated wild-type, so show a record with mutations
print(json.dumps(next(r for r in seqo.lineage_ if r["mutations"]), indent=1))
DataFrame shape: (4, 3)
  variant n_mut candidate_id
1 0 sha256:6292830e...a80db325eb43f23
2 I43P+A59Q 2 sha256:ec354651...da7c3e975d21b45
3 A59Y 1 sha256:0918dd19...0533796e2f6490c
4 A59Q 1 sha256:233be575...acd613e0b89f40c
{
 "candidate_id": "sha256:ec35465159d47932e6b36a7837a7b17e656524284d90d7484da7c3e975d21b45",
 "parent_id": "sha256:6292830e38478ba10f73868d050a2d353cb2011b5e40b9022a80db325eb43f23",
 "source_seq_id": "sha256:6292830e38478ba10f73868d050a2d353cb2011b5e40b9022a80db325eb43f23",
 "mutations": [
  {
   "pos": 43,
   "from_aa": "I",
   "to_aa": "P"
  },
  {
   "pos": 59,
   "from_aa": "A",
   "to_aa": "Q"
  }
 ],
 "method": "SeqOpt.run:nsga2",
 "objective_values": {
  "substrate": 14.000000000000002,
  "parsimony": 2.0
 },
 "seed": 42,
 "constraints_digest": "sha256:0fdc5ae18ab65f75b1798c4654baf8dc9e4dba9f70382bdc2ad550da026c1ffb"
}