DesignConstraints
- class DesignConstraints(*, immutable_positions=None, mutable_positions=None, permitted_substitutions=None, forbidden_substitutions=None, n_mut_max=None, min_identity=None, max_identity=None, forbidden_motifs=None, required_motifs=None, parent=None)[source]
Design Constraints (DesignConstraints) container for the sequence-design limits shared by
AAMut,SeqMutandSeqOpt[Breimann24a].A design campaign expresses the same limits over and over: which residues may change, how many substitutions are allowed, which target residues are off-limits, how close a variant must stay to its parent.
DesignConstraintsis the single place those limits are written down, so a constraint set built for one class is accepted by the other two, and a discarded candidate can say why it was discarded instead of vanishing silently.The primary contract is
DesignConstraints.check(), which answers(ok, reasons)for a candidate sequence; it is the only shape all three classes share.DesignConstraints.as_predicate()adapts the same limits to the genome-shaped feasibility callableSeqOpt.run()already consumes, andDesignConstraints.to_dict()/DesignConstraints.from_dict()round-trip a constraint set through JSON.The object subsumes the limits that already ship: the
regionandto_aaofSeqMut.scan()and then_mut_max/region/to_aaofSeqOpt.run()stay as shorthand and build aDesignConstraintsinternally, so a limit is never expressed by two independent mechanisms. Passing both an object and a conflicting scalar raises.Coordinate convention. Every position is a 1-based position in the parent (wild-type) sequence – the same convention as the
regionparameter ofSeqMut.scan()and theposcolumn of theSeqMut/SeqOptmutation tables. A candidate is a substitution-only variant and therefore has the parent’s length; insertions and deletions are out of scope.- mutable_positions
The span a substitution may fall in (a part name or explicit positions).
- permitted_substitutions
The only target residues allowed, globally or per position.
- forbidden_substitutions
Target residues that are never allowed, globally or per position.
- .. versionadded:: 1.2.0
- Parameters:
Methods
as_predicate([parent])Adapt the limits to the genome-shaped feasibility callable the optimizer consumes.
check(candidate[, parent])Check one candidate sequence against every limit and report why it was rejected.
from_dict(dict_constraints)Rebuild a constraint set from the dictionary produced by
DesignConstraints.to_dict().to_dict()Export the constraint set as a plain, JSON-serializable dictionary.
- __init__(*, immutable_positions=None, mutable_positions=None, permitted_substitutions=None, forbidden_substitutions=None, n_mut_max=None, min_identity=None, max_identity=None, forbidden_motifs=None, required_motifs=None, parent=None)[source]
- Parameters:
immutable_positions (list of int, optional) – 1-based parent positions that must keep their wild-type residue. A candidate that substitutes any of them is rejected, and
SeqMut.scan()/SeqOpt.run()drop them from the search space.None(default) leaves every position mutable.mutable_positions (str or list of int, optional) – The span a substitution may fall in: a sequence-part name (
'jmd_n','tmd'or'jmd_c') or a list of 1-based parent positions. This is the object form of theregionshorthand.None(default) places no span limit. A part name needs the TMD coordinates of adf_seqand is therefore applied by the calling class, not byDesignConstraints.check(), which evaluates an explicit position list only.permitted_substitutions (list of str or dict, optional) – The only target amino acids a substitution may introduce: a list of canonical amino acids (applies everywhere) or a
{1-based position: list of amino acids}dict (applies only to the positions it lists; an unlisted position stays unrestricted). This is the object form of theto_aashorthand.None(default) permits all 20 canonical amino acids.forbidden_substitutions (list of str or dict, optional) – Target amino acids a substitution may never introduce, in the same two shapes as
permitted_substitutions. Applied on top of it, so a residue that is permitted and forbidden is forbidden.None(default) forbids nothing.n_mut_max (int, optional) – Maximum number of substitutions a candidate may carry relative to the parent (
>= 1). This is the object form of then_mut_maxshorthand ofSeqOpt.run().None(default) places no limit.min_identity (float, optional) – Lowest sequence identity to the parent a candidate may have, as a fraction in
[0, 1](identity = fraction of positions carrying the parent residue, so a candidate withksubstitutions over a parent of lengthLhas identity1 - k / L).None(default) places no lower bound.max_identity (float, optional) – Highest sequence identity to the parent a candidate may have, as a fraction in
[0, 1]. Use it to force a minimum amount of change.None(default) places no upper bound.forbidden_motifs (list of str, optional) – Literal amino acid motifs (plain substrings, not regular expressions) that must not occur anywhere in a candidate, e.g. a protease site the design must avoid creating.
None(default) forbids no motif.required_motifs (list of str, optional) – Literal amino acid motifs that must occur in a candidate, e.g. a binding epitope the design must retain.
None(default) requires no motif.parent (str, optional) – Default parent (wild-type) sequence the limits are evaluated against, so
DesignConstraints.check()can be called with the candidate alone.None(default) leaves it unset, and the parent is then passed per call.
- Raises:
ValueError – If a position is not a 1-based integer, an amino acid is not canonical, a motif is empty or non-canonical,
n_mut_max < 1, an identity bound falls outside[0, 1]ormin_identity > max_identity, a position is both mutable and immutable, or the global substitution rules leave no amino acid allowed.
See also
DesignConstraints.check(): the primary(ok, reasons)contract.SeqMut.scan(): whoseregion/to_aathis object subsumes.SeqOpt.run(): whoseconstraintsaccepts this object directly.
Examples
:class:
DesignConstraintsis the one validated container of sequence-design limits that :class:AAMut, :class:SeqMutand :class:SeqOptall accept asconstraints, so a constraint set written for one of them is accepted by the other two and every rejected candidate carries its reasons. The constructor takes the position- and residue-level limits first:immutable_positions(positions that must keep their wild-type residue),mutable_positions(the span a substitution may fall in),permitted_substitutions/forbidden_substitutions(the target residues allowed or banned, globally or per position), and theparent(wild-type) sequence the limits are evaluated against. Every position is a 1-based position in the parent sequence.import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier import aaanalysis as aa aa.options["verbose"] = False # One protein as the parent (wild-type) sequence df_seq = aa.load_dataset(name="DOM_GSEC", n=50) wt = df_seq[df_seq["label"] == 0].iloc[[0]].reset_index(drop=True) seq = wt["sequence"].iloc[0] tmd_start, tmd_stop = int(wt["tmd_start"].iloc[0]), int(wt["tmd_stop"].iloc[0]) # Position- and residue-level limits dc = aa.DesignConstraints(immutable_positions=[tmd_start, tmd_stop], mutable_positions=list(range(tmd_start + 1, tmd_stop)), permitted_substitutions=["A", "L", "V", "K", "R"], forbidden_substitutions={tmd_start + 6: ["V"]}, parent=seq) df_dc = pd.DataFrame({"field": list(dc.to_dict()), "value": [str(v)[:60] for v in dc.to_dict().values()]}) aa.display_df(df_dc, n_rows=10, show_shape=True)
DataFrame shape: (10, 2)
field value 1 immutable_positions [37, 59] 2 mutable_positions [38, 39, 40, 41...49, 50, 51, 52, 3 permitted_substitutions ['A', 'L', 'V', 'K', 'R'] 4 forbidden_substitutions {43: ['V']} 5 n_mut_max None 6 min_identity None 7 max_identity None 8 forbidden_motifs None 9 required_motifs None 10 parent MQKVTLGLLVFLAGF...GVLCAMGIIIVMSAK The remaining constructor parameters judge a candidate as a whole:
n_mut_maxis the mutation budget,min_identity/max_identitybound how close a candidate stays to its parent, andforbidden_motifs/required_motifsare literal substrings it must avoid or keep. :meth:DesignConstraints.checkreports every violated limit at once:def mutate(sequence, pos, to_aa): """Substitute one 1-based position.""" return sequence[:pos - 1] + to_aa + sequence[pos:] pos_a, pos_b, pos_c = tmd_start + 3, tmd_start + 6, tmd_start + 9 dc = aa.DesignConstraints(n_mut_max=2, min_identity=0.95, max_identity=0.999, forbidden_motifs=["WW"], required_motifs=[seq[tmd_start - 1:tmd_start + 2]], parent=seq) candidates = {"single": mutate(seq, pos_a, "A"), "double": mutate(mutate(seq, pos_a, "A"), pos_b, "L"), "triple": mutate(mutate(mutate(seq, pos_a, "A"), pos_b, "L"), pos_c, "V"), "parent": seq} rows = [] for name, candidate in candidates.items(): ok, reasons = dc.check(candidate=candidate) rows.append(dict(variant=name, n_reasons=len(reasons), is_feasible=ok, reasons="; ".join(reasons) or "-")) aa.display_df(pd.DataFrame(rows), n_rows=10, show_shape=True)
DataFrame shape: (4, 4)
variant n_reasons is_feasible reasons 1 single 0 True - 2 double 0 True - 3 triple 1 False n_mut_max: 3 mu...he maximum of 2 4 parent 1 False max_identity: i...ximum of 0.9990 One object, two tools. The point of the class is that a single instance drives the whole design stack: :meth:
SeqMut.combineappends anis_feasible/reasonscolumn from it, :meth:SeqOpt.runaccepts the very same object asconstraints, and :meth:DesignConstraints.checkjudges a candidate directly. All three read the same limits, so they accept and reject the same candidates. Below, one constraint set is built once and handed to each of them:# A substrate classifier on the bundled CPP feature set (the fitness engine of SeqMut / SeqOpt) df_feat = aa.load_features(name="DOM_GSEC") labels = df_seq["label"].to_list() 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) # ONE shared constraint set for the whole design campaign dc = aa.DesignConstraints(immutable_positions=[tmd_start], permitted_substitutions=["A", "L", "V", "K", "R"], n_mut_max=2, parent=seq) # Candidate variants, in the tidy format SeqMut.combine consumes entry = wt["entry"].iloc[0] dict_genomes = {"ok_single": {pos_a: "A"}, "ok_double": {pos_a: "A", pos_b: "L"}, "over_budget": {pos_a: "A", pos_b: "L", pos_c: "V"}, "anchor_hit": {tmd_start: "A"}, "banned_aa": {pos_a: "W"}} variants = pd.DataFrame([dict(entry=entry, variant=name, pos=pos, to_aa=to_aa) for name, genome in dict_genomes.items() for pos, to_aa in genome.items()]) # The same object drives SeqMut ... seqm = aa.SeqMut(model=model, target_class=1) df_variant = seqm.combine(df_seq=wt, variants=variants, df_feat=df_feat, constraints=dc) aa.display_df(df_variant[["variant", "n_mut", "is_feasible", "reasons"]], n_rows=10, show_shape=True)
DataFrame shape: (5, 4)
variant n_mut is_feasible reasons 1 L37A 1 False immutable_posit...] are immutable 2 G40W 1 False permitted_subst...e not permitted 3 G40A 1 True 4 G40A+I43L 2 True 5 G40A+I43L+G46V 3 False n_mut_max: 3 mu...he maximum of 2 … and :class:
SeqOpt, which consumes the limits in its genome shape through :meth:DesignConstraints.as_predicate. Comparing the three verdicts side by side shows the accepted and the rejected set are identical, whichever tool applies them:is_feasible = dc.as_predicate() # the shape SeqOpt.run applies internally seqmut_verdict = dict(zip(df_variant["sequence_mut"], df_variant["is_feasible"])) rows = [] for name, genome in dict_genomes.items(): candidate = seq for pos, to_aa in genome.items(): candidate = mutate(candidate, pos, to_aa) ok, reasons = dc.check(candidate=candidate) rows.append(dict(variant=name, check=ok, seqmut=bool(seqmut_verdict[candidate]), seqopt=is_feasible(genome), reasons="; ".join(reasons) or "-")) df_agree = pd.DataFrame(rows) df_agree["same_verdict"] = df_agree["check"] == df_agree[["seqmut", "seqopt"]].all(axis=1) aa.display_df(df_agree, n_rows=10, show_shape=True)
DataFrame shape: (5, 6)
variant check seqmut seqopt reasons same_verdict 1 ok_single True True True - True 2 ok_double True True True - True 3 over_budget False False False n_mut_max: 3 mu...he maximum of 2 True 4 anchor_hit False False False immutable_posit...] are immutable True 5 banned_aa False False False permitted_subst...e not permitted True Handing the object to :meth:
SeqOpt.runrestricts the search itself: the optimizer never proposes a substitution at an immutable position, never leaves the permitted alphabet, and stays inside the mutation budget, so every variant on the returned Pareto front is feasible by the same constraint set. Theregion/to_aa/n_mut_maxshorthands keep working and build aDesignConstraintsinternally, so a limit is never defined twice:objectives = [("substrate", "max", "delta_pred"), ("parsimony", "min", "n_mut")] 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, pop_size=12, n_gen=4, region="tmd", constraints=dc) df_pareto["is_feasible"] = [dc.check(candidate=s)[0] for s in df_pareto["sequence_mut"]] aa.display_df(df_pareto[["variant", "n_mut", "substrate", "parsimony", "is_feasible"]], n_rows=10, show_shape=True)
DataFrame shape: (6, 5)
variant n_mut substrate parsimony is_feasible 1 I54R+S58R 2 14.000000 2.000000 True 2 0 0.000000 0.000000 True 3 I54L+S58R 2 14.000000 2.000000 True 4 S58A 1 11.000000 1.000000 True 5 I54K+S58R 2 14.000000 2.000000 True 6 I54A+S58R 2 14.000000 2.000000 True