P3: Sampling

This protocol covers constructing sets and sampling: windows, reference and control. Residue-level questions (where does a protease cut? which residue is modified?) are never asked over a whole protein. They are asked over short, fixed-length windows anchored on candidate sites. And here is the catch that trips up most newcomers: the known positives are only ever a handful of annotated sites, so the reference they must be compared against does not exist yet, you have to build it. How you draw those reference windows quietly decides what any downstream model or CPP signature can possibly learn.

A fair comparison needs fair reference and control windows. The test group (label=1) is the set of test windows sitting at known P1 anchors; the reference group (label=0) is the set of reference windows you sample around them. Draw that reference unfairly (too easy, too similar, or composition-skewed) and the contrast measures your sampling, not the biology. AAWindowSampler is the tool that builds this set reproducibly, with anti-leakage and redundancy filters baked in.

This protocol is a determinant-discovery / prediction building block at the residue level, the companion to P1: CPP signature (which works at the domain level). Here we manufacture the windowed input that a residue-level CPP run or downstream classifier consumes. For the mechanics of each sampling method, see the AAWindowSampler examples; here we focus on the workflow.

Key mental model. The test windows are given; the reference windows are made. Every sampling choice (how close a negative may sit to a positive, which proteins it comes from, how similar it may be to a test window, whether it is synthetic) changes what “reference” means, and a model or CPP signature can only learn the contrast you built. So look at the reference you drew before you trust anything computed on it.

When to use it. Use this protocol for residue-level prediction: the biological unit is a single site, scored over a fixed-length window (glossary: residue level). Two sub-modes, distinguished only by window parity:

  • between-residues (even window_size): a scissile bond … P2·P1 │ P1′·P2′ … (Schechter–Berger), e.g. protease cleavage, our running caspase-3 example.

  • single-residue (odd window_size): a site on a residue, e.g. a PTM (phosphorylation, glycosylation).

This is distinct from the domain level (P1: CPP signature, comparison over jmd_n/tmd/jmd_c parts) and the protein level (whole-chain). The defining difficulty at the residue level is reference construction: positives are a handful of annotated sites, but the negatives must be manufactured, and how you draw them (same protein, other proteins, or synthetic) changes what the downstream model learns.

When not to use it. Skip this protocol when your data is already windowed (one fixed-length slice per row with a binary label): there is nothing left to sample, so go straight to P4: Prediction levels. Skip it too for domain-level work (contrast jmd_n / tmd / jmd_c parts, see P1: CPP signature) and protein-level work (the whole chain is the unit of comparison), where no window is sampled.

Input. A df_seq with one row per full protein sequence (entry + sequence) and a pos column (default name pos): each cell is a list[int] of 1-based P1 anchors, the known positive sites on that protein (empty list = no annotated site). This is the upstream format produced by an annotation step (e.g. to_df_seq(), or your own curation of literature cleavage sites).

Note: the bundled aa.load_dataset(name="AA_CASPASE3") returns sequences that are already windowed (one 9-mer per row, with a binary label): it is the output of a sampling step, not the input to one. To demonstrate the sampler we therefore start from full sequences with a pos column, which is exactly what AAWindowSampler expects.

Rows that carry positives are substrate proteins; rows with an empty pos cell are non-substrate proteins, the latter form the candidate pool for cross-protein sampling.

import aaanalysis as aa
import numpy as np
import pandas as pd

aa.options["verbose"] = False
aa.options["random_state"] = 42

# Full-sequence df_seq for caspase-3 cleavage (P1 anchor = the Asp of a D-x-x-D motif).
# Substrate proteins carry 1-based P1 anchors in `pos`; non-substrate proteins have [].
df_seq = pd.DataFrame({
    "entry": ["SUB1", "SUB2", "SUB3", "NEG1", "NEG2", "NEG3"],
    "sequence": [
        "MKTAYIAKQRDEVDSGLAPYKVLNMQATGHIWDETDSARKLMNPQRSTV",
        "GASPMNLKDEVDTAGRWFYHCIKLMNPQRSTVWYDQTDSGKLAANPQRS",
        "MQALDEVDGKLMNPQRSTVWYACDEFGHIKLMNPQRSTVWYAKLM",
        "ACDEFGHIKLMNPQRSTVWYACDEFGHIKLMNPQRSTVWYACDEFGHIK",
        "GHIKLMNPQRSTVWYACDEFGHIKLMNPQRSTVWYGHIKLMNPQRSTVW",
        "WYACDEFGHIKLMNPQRSTVWYKLMNPQRSTVWYACDEFGHIKLMNPQR",
    ],
    "pos": [[14, 36], [12, 38], [8], [], [], []],
})
# `n_pos` = number of annotated P1 anchors (>0 -> substrate, 0 -> non-substrate pool).
aa.display_df(df=df_seq.assign(n_pos=df_seq["pos"].apply(len)), n_rows=10, show_shape=True)
DataFrame shape: (6, 4)
  entry sequence pos n_pos
1 SUB1 MKTAYIAKQRDEVDS...TDSARKLMNPQRSTV [14, 36] 2
2 SUB2 GASPMNLKDEVDTAG...DQTDSGKLAANPQRS [12, 38] 2
3 SUB3 MQALDEVDGKLMNPQ...LMNPQRSTVWYAKLM [8] 1
4 NEG1 ACDEFGHIKLMNPQR...RSTVWYACDEFGHIK [] 0
5 NEG2 GHIKLMNPQRSTVWY...YGHIKLMNPQRSTVW [] 0
6 NEG3 WYACDEFGHIKLMNP...ACDEFGHIKLMNPQR [] 0

Run. AAWindowSampler exposes five methods, each producing the same segments-mode schema: sample_same_protein (within-protein hard negatives), sample_different_protein (cross-protein unlabeled pool), sample_motif_matched (PWM lookalikes), sample_synthetic (composition controls), and sample_benchmark_set (a reproducible multi-arm orchestrator). The cells below demonstrate each in turn, assigning a fitting role to every sampled window. For per-method parameter details, see the AAWindowSampler examples (this protocol stays at the workflow level).

Role vs. strategy. Every sampled window carries two orthogonal tags (glossary):

  • role (role column): the workflow meaning of the row: Test, Negative, Unlabeled, or Control. It answers “what does this row mean for my training task?” and you set it.

  • strategy (strategy column): the sampling provenance: same_protein, different_protein, synthetic:<generator>, or motif_matched. It answers “which method drew this row?” and is set automatically.

The two are independent: a same_protein window is Negative by default, but you could tag it Unlabeled if your workflow treats within-protein sites as unlabeled. The three strategies below map onto three reference-construction choices: same-protein hard negatives, different-protein unlabeled pool, and synthetic composition controls.

# Anti-leakage + redundancy filters are configured once, on the aaws instance.
aaws = aa.AAWindowSampler(
    verbose=False,
    random_state=42,
    # similarity filters (identity = fraction of identical positions between two windows)
    max_similarity_to_test=0.8,     # drop sampled windows too similar to any test window (anti-leakage)
    max_similarity_within_ref=0.9,  # drop sampled windows too similar to a kept one (redundancy)
    # re-draw behaviour when the filters shrink the pool
    filter_iteratively=True,
    max_sampling_attempts=10,
    custom_filter=None,             # optional keep-predicate (window, entry, source_position) -> bool
)

# A test window is the window at a known P1 anchor. window_size=8 is EVEN -> between-residues (cleavage).
# Geometry: a window starts half_left = (window_size - 1) // 2 residues upstream of its P1 anchor and runs
# for window_size residues. For window_size=8 that is 3 residues upstream, P1 itself, and 4 downstream,
# i.e. P4-P3-P2-P1 | P1'-P2'-P3'-P4': the extra residue of an even window goes C-terminal of P1.
window_size = 8
half_left = (window_size - 1) // 2     # 3
seqp = aa.SequencePreprocessor()
# Test window at P1 anchor 14 on SUB1 -> carries the D-E-V-D caspase motif ('DEVDSGLA').
test_window = seqp.get_aa_window(
    seq=df_seq.loc[0, "sequence"], pos_start=14 - half_left,
    pos_stop=None,               # a pos_stop would end the window there and make window_size unused
    window_size=window_size,
    index1=True,                 # positions are 1-based, as in the `pos` column
    gap="-", accept_gap=True,    # accept_gap=False would reject a window running past the sequence end
)
# Every test window of df_seq; reused below as the leakage reference and as the motif template.
test_windows = [seqp.get_aa_window(seq=seq, pos_start=p - half_left, window_size=window_size, index1=True)
                for seq, list_pos in zip(df_seq["sequence"], df_seq["pos"]) for p in list_pos]

p_sites = ([f"P{i}" for i in range(half_left + 1, 0, -1)] + ["|"]
           + [f"P{i}'" for i in range(1, window_size - half_left)])
df_geometry = pd.DataFrame({"P1 anchor (1-based)": [14], "window": [test_window],
                            "P-site of each residue": [" ".join(p_sites)],
                            "test windows in df_seq": [len(test_windows)]})
aa.display_df(df=df_geometry, n_rows=10, show_shape=True)
DataFrame shape: (1, 4)
  P1 anchor (1-based) window P-site of each residue test windows in df_seq
1 14 DEVDSGLA P4 P3 P2 P1 | P1' P2' P3' P4' 5

The distance band (hard-negative mining). sample_same_protein draws windows from the same proteins that contain positives. The (min_distance_to_pos, max_distance_to_pos) distance band filters candidate anchors by their L1 distance to the nearest positive on that protein:

  • both None (default): every fully-fitting window is admissible, sampled negatives may overlap test windows.

  • min_distance_to_pos=window_size: forces non-overlapping hard negatives (no shared residues with a test window).

  • add a finite max_distance_to_pos: constrains negatives to a neighbourhood of positives (local hard negatives).

# same_protein -> within-protein hard negatives (n=12, non-overlapping windows).
df_same = aaws.sample_same_protein(
    df_seq=df_seq, pos_col="pos", n=12, window_size=8,
    # distance band: non-overlapping hard negatives, no upper bound
    min_distance_to_pos=8, max_distance_to_pos=None,
    # labels, role tag and output schema
    label_test=1, label_ref=0, role="Negative", output_mode="segments",
    # optional residue filters (unused here): per-residue context tags and a motif PWM
    aa_context_col=None, context_in=None, context_out=None,
    motif_pwm=None, motif_score_threshold=None, motif_match="in",
    seed=42,
)
aa.display_df(df=df_same, n_rows=10, show_shape=True)
DataFrame shape: (12, 8)
  entry_win entry sequence window source_position label role strategy
1 SUB3_20-27 SUB3 MQALDEVDGKLMNPQ...LMNPQRSTVWYAKLM WYACDEFG 23 0 Negative same_protein
2 SUB3_29-36 SUB3 MQALDEVDGKLMNPQ...LMNPQRSTVWYAKLM IKLMNPQR 32 0 Negative same_protein
3 SUB3_36-43 SUB3 MQALDEVDGKLMNPQ...LMNPQRSTVWYAKLM RSTVWYAK 39 0 Negative same_protein
4 SUB3_35-42 SUB3 MQALDEVDGKLMNPQ...LMNPQRSTVWYAKLM QRSTVWYA 38 0 Negative same_protein
5 SUB2_17-24 SUB2 GASPMNLKDEVDTAG...DQTDSGKLAANPQRS WFYHCIKL 20 0 Negative same_protein
6 SUB2_27-34 SUB2 GASPMNLKDEVDTAG...DQTDSGKLAANPQRS PQRSTVWY 30 0 Negative same_protein
7 SUB2_23-30 SUB2 GASPMNLKDEVDTAG...DQTDSGKLAANPQRS KLMNPQRS 26 0 Negative same_protein
8 SUB2_25-32 SUB2 GASPMNLKDEVDTAG...DQTDSGKLAANPQRS MNPQRSTV 28 0 Negative same_protein
9 SUB1_22-29 SUB1 MKTAYIAKQRDEVDS...TDSARKLMNPQRSTV VLNMQATG 25 0 Negative same_protein
10 SUB1_19-26 SUB1 MKTAYIAKQRDEVDS...TDSARKLMNPQRSTV PYKVLNMQ 22 0 Negative same_protein
# different_protein -> cross-protein unlabeled pool, drawn only from NEG1/NEG2/NEG3
# (proteins with no positive) -> a natural U set for positive-unlabeled learning.
df_diff = aaws.sample_different_protein(
    df_seq=df_seq, pos_col="pos", n=12, window_size=8,
    candidate_proteins=None,   # None: every protein without a positive; or a list of entries
    # labels, role tag and output schema
    label_test=1, label_ref=0, role="Unlabeled", output_mode="segments",
    # optional residue filters (unused here)
    aa_context_col=None, context_in=None, context_out=None,
    motif_pwm=None, motif_score_threshold=None, motif_match="in",
    seed=42,
)
aa.display_df(df=df_diff, n_rows=10, show_shape=True)
DataFrame shape: (12, 8)
  entry_win entry sequence window source_position label role strategy
1 NEG2_31-38 NEG2 GHIKLMNPQRSTVWY...YGHIKLMNPQRSTVW STVWYGHI 34 0 Unlabeled different_protein
2 NEG1_3-10 NEG1 ACDEFGHIKLMNPQR...RSTVWYACDEFGHIK DEFGHIKL 6 0 Unlabeled different_protein
3 NEG2_42-49 NEG2 GHIKLMNPQRSTVWY...YGHIKLMNPQRSTVW NPQRSTVW 45 0 Unlabeled different_protein
4 NEG3_16-23 NEG3 WYACDEFGHIKLMNP...ACDEFGHIKLMNPQR QRSTVWYK 19 0 Unlabeled different_protein
5 NEG2_41-48 NEG2 GHIKLMNPQRSTVWY...YGHIKLMNPQRSTVW MNPQRSTV 44 0 Unlabeled different_protein
6 NEG1_5-12 NEG1 ACDEFGHIKLMNPQR...RSTVWYACDEFGHIK FGHIKLMN 8 0 Unlabeled different_protein
7 NEG1_4-11 NEG1 ACDEFGHIKLMNPQR...RSTVWYACDEFGHIK EFGHIKLM 7 0 Unlabeled different_protein
8 NEG3_1-8 NEG3 WYACDEFGHIKLMNP...ACDEFGHIKLMNPQR WYACDEFG 4 0 Unlabeled different_protein
9 NEG2_5-12 NEG2 GHIKLMNPQRSTVWY...YGHIKLMNPQRSTVW LMNPQRST 8 0 Unlabeled different_protein
10 NEG1_1-8 NEG1 ACDEFGHIKLMNPQR...RSTVWYACDEFGHIK ACDEFGHI 4 0 Unlabeled different_protein

Motif-matched lookalikes. sample_motif_matched is the third protein-sourced reference: it scans every candidate protein with a Position Weight Matrix (PWM) and keeps the windows that score like a positive, the hardest negatives of all. The scan is a FIMO-equivalent computed inside the package, so it needs no external motif tool. The PWM is yours to choose; here we build it from the test windows themselves, as the weight (log-odds) logo of AALogo, with a small pseudocount so that a residue never seen at a position does not veto a whole window. Rows carrying positives are excluded from the scan, so the hits come from the non-substrate pool only.

# motif_matched -> lookalike hard negatives: score every candidate window against a PWM.
aal = aa.AALogo(logo_type="weight")
list_aa = list("ACDEFGHIKLMNPQRSTVWY")
# The PWM must have shape (window_size, 20) with the canonical amino acids as columns.
df_pwm = aal.get_df_logo(df_parts=pd.DataFrame({"tmd": test_windows}),
                         labels=None, label_test=1, tmd_len=window_size, start_n=True,
                         characters_to_ignore=".-", pseudocount=0.5,
                         ).reindex(columns=list_aa).fillna(0.0)

df_motif = aaws.sample_motif_matched(
    df_seq=df_seq, pos_col="pos", n=6, window_size=8,
    # the motif: the PWM and the score a window has to reach to count as a match
    motif_pwm=df_pwm, motif_score_threshold=2.0,
    # labels, role tag and output schema
    label_test=1, label_ref=0, role="Negative", output_mode="segments",
    # optional residue filters (unused here)
    aa_context_col=None, context_in=None, context_out=None,
    seed=42,
)


def pwm_score(window):
    """Sum of the per-position PWM values of a window (the score the sampler ranks by)."""
    return sum(df_pwm.loc[i, aa_symbol] for i, aa_symbol in enumerate(window))


# Put the matched windows next to the real sites, so the scores have a scale.
df_motif_scores = pd.concat([
    pd.DataFrame({"set": "Test window (label=1)", "entry_win": "", "window": test_windows,
                  "motif_score": [pwm_score(w) for w in test_windows]}),
    df_motif.assign(set="Motif-matched negative")[["set", "entry_win", "window", "motif_score"]],
], ignore_index=True).round(2)
aa.display_df(df=df_motif_scores, n_rows=10, show_shape=True)
DataFrame shape: (7, 4)
  set entry_win window motif_score
1 Test window (label=1) DEVDSGLA 14.940000
2 Test window (label=1) DETDSARK 13.710000
3 Test window (label=1) DEVDTAGR 12.980000
4 Test window (label=1) DQTDSGKL 12.130000
5 Test window (label=1) DEVDGKLM 12.980000
6 Motif-matched negative NEG1_3-10 DEFGHIKL 5.430000
7 Motif-matched negative NEG3_18-25 STVWYKLM 3.050000

Read the motif_score column across the two sets. Every real site scores far above the best lookalike the scan can find, because the three non-substrate sequences carry no D-x-x-D stretch at all: this pool simply holds no genuine lookalike, and the score is what tells you so. Raising motif_score_threshold returns fewer rows, and eventually none, rather than silently handing you weak matches. For the inverse question (“windows that do not match the motif”), pass the same motif_pwm to sample_different_protein with motif_match="out". The figure in What the sampling choices change below puts these scores next to the pool they were drawn from.

Synthetic controls. sample_synthetic manufactures windows from a generator distribution (no source protein), so rows carry entry="", source_position=-1, and entry_win="synth_{i}" (per-call counter). Generator shapes:

  • built-in strings: "uniform", "global_freq" (empirical AA composition of df_seq), "position_specific", "scrambled";

  • an AAontology preset name (e.g. "alpha_helix", "aa_composition_mp"): a curated scale normalized into an AA distribution;

  • a list of preset names for a multiplicative mix (e.g. ["aa_composition_mp", "alpha_helix"] for a membrane-helix prior);

  • a dict {symbol: prob} for a custom-alphabet frequency table.

Synthetic windows are the null baseline / composition-bias control.

# synthetic -> composition controls; entry_win is a per-call counter (synth_0, synth_1, ...).
df_synth = aaws.sample_synthetic(
    df_seq=df_seq, n=10, window_size=8,
    generator="global_freq",   # residue frequencies of df_seq
    pos_col=None,              # positives are not needed to build a composition control
    label_ref=0, role="Control", seed=42,
)
aa.display_df(df=df_synth, n_rows=10, show_shape=True)
DataFrame shape: (10, 8)
  entry_win entry sequence window source_position label role strategy
1 synth_0 SLTRDYSS -1 0 Control synthetic:global_freq
2 synth_1 DLKWQTLG -1 0 Control synthetic:global_freq
3 synth_2 NCTPSKYV -1 0 Control synthetic:global_freq
4 synth_3 SFLAEQRY -1 0 Control synthetic:global_freq
5 synth_4 IKLFDMGQ -1 0 Control synthetic:global_freq
6 synth_5 LTRITTKH -1 0 Control synthetic:global_freq
7 synth_6 QDFASQRS -1 0 Control synthetic:global_freq
8 synth_7 LNDDQLNS -1 0 Control synthetic:global_freq
9 synth_8 QNNIALGK -1 0 Control synthetic:global_freq
10 synth_9 TGAHHQNS -1 0 Control synthetic:global_freq

The benchmark-set orchestrator. sample_benchmark_set runs several named arms in one call and concatenates them, adding an arm column for provenance. Each arm is one ordinary sample_* call ({"method": <strategy>, **kwargs}); per-arm sub-seeds are derived deterministically from the master seed, so the same seed reproduces the same benchmark set. It adds no new sampling behaviour, just reproducible multi-arm orchestration.

arms = {
    "hard_neg":  {"method": "same_protein",      "n": 12, "window_size": 8, "min_distance_to_pos": 8},
    "unlabeled": {"method": "different_protein",  "n": 12, "window_size": 8},
    "control":   {"method": "synthetic",          "n": 10, "window_size": 8, "generator": "global_freq"},
}
df_bench = aaws.sample_benchmark_set(df_seq=df_seq, arms=arms, seed=42)
# One reproducible call -> 34 windows across three arms; the counts confirm each per-arm n.
aa.display_df(df=df_bench[["arm", "role", "strategy"]].value_counts().reset_index(), n_rows=10, show_shape=True)
DataFrame shape: (3, 4)
  arm role strategy count
1 hard_neg Negative same_protein 12
2 unlabeled Unlabeled different_protein 12
3 control Control synthetic:global_freq 10

Output. A few things happened across those four calls, so let’s lay the result out and look at it. The sampled negatives share their source proteins with the positives. Here min_distance_to_pos=8 prevents overlap with a test window, but the missing upper bound means they can still occur anywhere on the substrate protein. The panel on the right then tallies the role composition of the assembled reference set.

The sampler returns a segments-mode DataFrame, one row per window, with the fixed schema entry_win, entry, sequence, window, source_position, label, role, strategy (the benchmark set adds arm).

  • ``entry_win``: "<entry>_<start>-<end>" (1-based inclusive) for protein-sourced windows; identical biological windows across calls share it, so drop_duplicates(subset="entry_win") is the natural cross-call dedupe.

  • synthetic rows use entry_win="synth_{i}" (per-call counter), not call-stable; dedupe control windows on the window string instead.

import matplotlib.pyplot as plt
import seaborn as sns

# House style + one consistent colour per role (gray=Negative, blue=Unlabeled, orange=Control, red=Test).
aa.plot_settings(font_scale=0.9, weight_bold=False)
c_neg, c_unl, c_test, c_ctrl = aa.plot_get_clist(n_colors=4)
role_colors = {"Negative": c_neg, "Unlabeled": c_unl, "Control": c_ctrl}

fig, axes = plt.subplots(1, 2, figsize=(11, 3.9), gridspec_kw={"width_ratios": [3, 2]})

# Panel A: where windows sit on the three substrate proteins (a fair reference hugs the positives).
ax = axes[0]
substrates = ["SUB1", "SUB2", "SUB3"]
for i, entry in enumerate(substrates):
    row = df_seq[df_seq["entry"] == entry].iloc[0]
    ax.broken_barh([(1, len(row["sequence"]))], (i - 0.11, 0.22), color="0.9", zorder=1)
    for s in df_same.loc[df_same["entry"] == entry, "source_position"]:   # sampled same-protein negatives
        ax.broken_barh([(s - half_left, 8)], (i - 0.30, 0.60), color=c_neg,
                       edgecolor="white", linewidth=1.2, zorder=2)
    for p in row["pos"]:                                                  # known test windows at P1 anchors
        ax.broken_barh([(p - half_left, 8)], (i - 0.30, 0.60), color=c_test,
                       edgecolor="white", linewidth=1.2, zorder=3)
ax.set_yticks(range(len(substrates)))
ax.set_yticklabels(substrates)
ax.set_ylim(-0.6, len(substrates) - 0.4)
ax.set_xlabel("Residue position")
ax.set_title("Windows on substrate proteins", size=aa.plot_gcfs())
sns.despine(ax=ax)
aa.plot_legend(ax=ax, dict_color={"Test window (label=1)": c_test, "Same-protein negative": c_neg},
               n_cols=2, loc="upper left", loc_out=True, x=0, y=-0.3, fontsize=aa.plot_gcfs() - 2)

# Panel B: role composition of the assembled reference set.
ax = axes[1]
counts = df_bench["role"].value_counts()
ax.bar(counts.index, counts.values,
       color=[role_colors.get(r, "0.5") for r in counts.index],
       edgecolor="white", linewidth=1.2)
ax.set_ylabel("n windows")
ax.set_title("Reference set composition", size=aa.plot_gcfs())
sns.despine(ax=ax)

plt.tight_layout()
plt.show()
../_images/protocol3_sampling_1_output_19_0.png
# Dedupe correctly per provenance: entry_win for protein-sourced, window for synthetic.
is_synth = df_bench["strategy"].str.startswith("synthetic")
df_protein = df_bench[~is_synth].drop_duplicates(subset="entry_win")
df_control = df_bench[is_synth].drop_duplicates(subset="window")
df_clean = pd.concat([df_protein, df_control], ignore_index=True)
# df_clean is the assembled window set fed to feature engineering (Protocol 4).
aa.display_df(df=df_clean["role"].value_counts().reset_index(), n_rows=10, show_shape=True)
DataFrame shape: (3, 2)
  role count
1 Negative 12
2 Unlabeled 12
3 Control 10

What the sampling choices change. The figure above shows one reference set. The four figures below hold the proteins and n fixed and change a single sampling choice each (the distance band, the source strategy, the motif filter, the similarity filters), so every difference you see comes from that one choice.

The distance band, shown. Each dot is one sampled same-protein window, placed by its distance to the nearest positive on its protein. Anything closer than window_size (red zone) shares residues with a test window; distance 0 is a test window. The shaded strip is the admissible band each setting allows.

# A plain sampler (no similarity filters), so only the distance band differs between rows.
aaws = aa.AAWindowSampler(random_state=42, verbose=False)
dict_pos = df_seq.set_index("entry")["pos"].to_dict()
bands = {
    "No band (default)": (None, None),
    "Non-overlapping: min=8": (8, None),
    "Neighbourhood: min=8, max=16": (8, 16),
}
x_max = 32
fig, axes = plt.subplots(len(bands), 1, figsize=(8, 5.2), sharex=True)
rng = np.random.default_rng(0)                      # jitter only, for legibility
for ax, (name, (d_min, d_max)) in zip(axes, bands.items()):
    df_band = aaws.sample_same_protein(df_seq=df_seq, n=12, window_size=8,
                                       min_distance_to_pos=d_min, max_distance_to_pos=d_max, seed=42)
    dist = np.array([min(abs(s - p) for p in dict_pos[e])
                     for e, s in zip(df_band["entry"], df_band["source_position"])])
    lo, hi = (d_min or 0), (d_max if d_max is not None else x_max)
    ax.axvspan(-0.5, window_size - 0.5, color=c_test, alpha=0.12, lw=0)
    ax.axvspan(lo - 0.5, hi + 0.5, ymin=0.08, ymax=0.92, color=c_unl, alpha=0.15, lw=0)
    overlap = dist < window_size
    ax.scatter(dist[~overlap], rng.uniform(-0.25, 0.25, (~overlap).sum()), color=c_neg, s=36, zorder=3)
    ax.scatter(dist[overlap], rng.uniform(-0.25, 0.25, overlap.sum()), color=c_test, s=36, zorder=3)
    ax.set_yticks([])
    ax.set_ylim(-0.5, 0.5)
    ax.set_title(f"{name}:  {overlap.sum()} of {len(dist)} windows overlap a test window",
                 size=aa.plot_gcfs() - 1, loc="left")
    sns.despine(ax=ax, left=True)
axes[-1].set_xlim(-1, x_max)
axes[-1].set_xlabel("Distance of sampled P1 anchor to the nearest positive [residues]")
aa.plot_legend(ax=axes[0], dict_color={"Overlaps a test window": c_test, "Non-overlapping": c_neg,
                                       "Admissible band": c_unl},
               loc="upper left", loc_out=True, y=1.7, x=0, n_cols=3, fontsize=aa.plot_gcfs() - 2)
plt.tight_layout()
plt.show()
../_images/protocol3_sampling_2_output_23_0.png

Notice what the default does on this small set: with no band, some “negatives” overlap the positives, and one sits at distance 0, the positive site itself relabelled as a negative. min_distance_to_pos=window_size removes every overlap, and a finite max_distance_to_pos then keeps the hard negatives local.

Where the reference comes from. The sampling strategies do not just differ in provenance, they draw windows with different residue composition. The heatmap puts the amino-acid composition of the test windows next to each candidate reference: the two protein-sourced strategies and three synthetic generators ("global_freq", an AAontology preset, and "uniform", where every residue is equally likely). The table scores each reference by how far its composition sits from the test windows (total variation distance, 0 = identical, 1 = disjoint) and lists its aspartate (D) share, the P1 residue of every caspase site.

# Residue composition (%) of the test windows and of each candidate reference (same n where possible).
aaws = aa.AAWindowSampler(random_state=42, verbose=False)
dict_sets = {
    "Test windows (label=1)": test_windows,
    "same_protein": aaws.sample_same_protein(df_seq=df_seq, n=30, window_size=8, min_distance_to_pos=8, seed=42)["window"],
    "different_protein": aaws.sample_different_protein(df_seq=df_seq, n=30, window_size=8, seed=42)["window"],
    "synthetic: global_freq": aaws.sample_synthetic(df_seq=df_seq, n=30, window_size=8, generator="global_freq", seed=42)["window"],
    "synthetic: alpha_helix": aaws.sample_synthetic(df_seq=df_seq, n=30, window_size=8, generator="alpha_helix", seed=42)["window"],
    "synthetic: uniform": aaws.sample_synthetic(df_seq=df_seq, n=30, window_size=8, generator="uniform", seed=42)["window"],
}
list_aa = list("ACDEFGHIKLMNPQRSTVWY")
df_comp = pd.DataFrame({name: pd.Series(list("".join(windows))).value_counts(normalize=True)
                        for name, windows in dict_sets.items()}).T.reindex(columns=list_aa).fillna(0) * 100

fig, ax = plt.subplots(figsize=(10, 3.4))
sns.heatmap(df_comp, ax=ax, cmap="Blues", vmin=0, linewidths=0.4, linecolor="white",
            cbar_kws={"label": "Residues [%]", "pad": 0.02})
ax.set_xlabel("Amino acid")
ax.set_ylabel("")
ax.tick_params(axis="x", rotation=0)
plt.tight_layout()
plt.show()
../_images/protocol3_sampling_3_output_26_0.png
# The same picture as numbers: how far each reference sits from the test composition.
df_tvd = pd.DataFrame({
    "reference": df_comp.index[1:],
    "n_windows": [len(dict_sets[name]) for name in df_comp.index[1:]],
    "distance to test composition": [0.5 * (df_comp.loc[name] - df_comp.iloc[0]).abs().sum() / 100
                                     for name in df_comp.index[1:]],
    "D [%]": [df_comp.loc[name, "D"] for name in df_comp.index[1:]],
}).round(2)
aa.display_df(df=df_tvd, n_rows=10, show_shape=True)
DataFrame shape: (5, 4)
  reference n_windows distance to test composition D [%]
1 same_protein 30 0.460000 1.670000
2 different_protein 30 0.450000 4.580000
3 synthetic: global_freq 30 0.380000 10.000000
4 synthetic: alpha_helix 30 0.400000 8.750000
5 synthetic: uniform 30 0.430000 3.750000

The test windows are dominated by D (over 20 % of residues), with E and V next: the D-x-x-D caspase motif. No reference matches that, which is the point of a contrast, but look at which reference comes closest: "global_freq". It builds its frequencies from every residue in df_seq, including the substrate proteins and their cleavage sites, so this control inherits part of the motif (its D share is about twice that of the different-protein windows). A composition control is only a neutral baseline if the frequencies it copies are neutral too. The protein-sourced references, in contrast, draw from real sequence around (same-protein) or away from (different-protein) the sites. The toy set is small, so treat the exact numbers as illustrative, but the check itself (compare each reference’s composition with the test windows before training) carries over to real data.

Motif-matched lookalikes, shown. The table above gave the scores; this figure gives them a distribution. Left: the motif score of every window in three sets, the test windows, the motif_matched hits, and the different_protein pool those hits are drawn from. sample_motif_matched keeps only windows clearing motif_score_threshold, so it returns the top tail of that pool and nothing else. Right: the mean per-position PWM contribution, which shows where along the window a score is won or lost, with positions named by the Schechter-Berger convention (P4-P3-P2-P1 | P1'-P2'-P3'-P4').

# The motif view of the same pool: score every window against the PWM built from the test windows.
aaws = aa.AAWindowSampler(random_state=42, verbose=False)
windows_diff = aaws.sample_different_protein(df_seq=df_seq, n=30, window_size=8, seed=42)["window"].to_list()
# Colours match the y-axis labels on the left (red = test, gray = motif_matched, blue = different_protein).
dict_motif_sets = {
    "Test windows (label=1)": (list(test_windows), c_test),
    "motif_matched": (df_motif["window"].to_list(), c_neg),
    "different_protein": (windows_diff, c_unl),
}
p_labels = ["P4", "P3", "P2", "P1", "P1'", "P2'", "P3'", "P4'"]

fig, axes = plt.subplots(1, 2, figsize=(11, 3.6), gridspec_kw={"width_ratios": [1.15, 1]})

# Left: the motif score of every window, per set. motif_matched keeps only the top of the pool.
ax = axes[0]
df_motif_dist = pd.DataFrame([{"set": name, "motif_score": pwm_score(w)}
                              for name, (windows, _) in dict_motif_sets.items() for w in windows])
sns.stripplot(data=df_motif_dist, x="motif_score", y="set", hue="set", ax=ax, jitter=0.22, size=6,
              palette={name: color for name, (_, color) in dict_motif_sets.items()},
              legend=False, orient="h")
ax.axvline(2.0, color="0.3", ls="--", lw=1)
ax.text(2.0, 1.02, "threshold 2.0", transform=ax.get_xaxis_transform(),
        ha="center", va="bottom", size=aa.plot_gcfs() - 2)
ax.set_xlabel("Motif score (PWM log-odds sum)")
ax.set_ylabel("")
ax.set_ylim(2.6, -0.6)
sns.despine(ax=ax)

# Right: where along the window that score is won or lost (mean per-position PWM contribution).
ax = axes[1]
x = np.arange(window_size)
for i, (name, (windows, color)) in enumerate(dict_motif_sets.items()):
    contribution = np.array([[df_pwm.loc[j, aa_symbol] for j, aa_symbol in enumerate(w)]
                             for w in windows]).mean(axis=0)
    ax.bar(x + (i - 1) * 0.27, contribution, width=0.27, color=color)
ax.axhline(0, color="0.3", lw=0.8)
ax.set_xticks(x)
ax.set_xticklabels(p_labels)
ax.set_xlabel("Window position")
ax.set_ylabel("Mean PWM contribution")
sns.despine(ax=ax)
plt.tight_layout()
plt.show()
../_images/protocol3_sampling_4_output_30_0.png

Both reference sets top out at the same score: motif_matched is exactly the high-scoring tail of the different_protein pool, deduplicated by the similarity filters, not a different kind of window. And that best lookalike still sits far below the weakest real site, because the toy non-substrate pool carries no D-x-x-D stretch to find. The right panel says where the gap opens: the test windows earn their score at P1 and P4, the two aspartates of the caspase motif, while the lookalikes pick up what they can at the neutral positions and contribute almost nothing at P1. On real data this is the check that tells you whether your hard negatives are genuinely hard, or merely the best of a pool that holds no lookalike.

Anti-leakage and redundancy filters, shown. Two samplers draw from the same proteins with the same seed; only the filters differ. Left: each same-protein window’s identity to its most similar test window (no distance band, so leakage is possible). Right: each different-protein window’s identity to its most similar other reference window. The dashed line is the filter threshold.

def identity(a, b):
    """Fraction of identical positions between two equal-length windows (the sampler's similarity)."""
    return sum(x == y for x, y in zip(a, b)) / len(a)


settings = {"No filters": dict(), "Filtered": dict(max_similarity_to_test=0.8, max_similarity_within_ref=0.9)}
rows = []
for name, filter_kws in settings.items():
    aaws = aa.AAWindowSampler(random_state=42, verbose=False, **filter_kws)
    for w in aaws.sample_same_protein(df_seq=df_seq, n=12, window_size=8, seed=42)["window"]:
        rows.append({"setting": name, "check": "to_test", "identity": max(identity(w, t) for t in test_windows)})
    wins = aaws.sample_different_protein(df_seq=df_seq, n=12, window_size=8, seed=42)["window"].to_list()
    for i, w in enumerate(wins):
        rows.append({"setting": name, "check": "within_ref",
                     "identity": max(identity(w, v) for j, v in enumerate(wins) if j != i)})
df_ident = pd.DataFrame(rows)

fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), sharey=True)
titles = {"to_test": ("Same-protein: vs nearest test window", 0.8),
          "within_ref": ("Different-protein: vs nearest other window", 0.9)}
for ax, (check, (title, threshold)) in zip(axes, titles.items()):
    df_c = df_ident[df_ident["check"] == check]
    sns.stripplot(data=df_c, x="setting", y="identity", hue="setting", ax=ax, jitter=0.2, size=6,
                  palette={"No filters": c_test, "Filtered": c_neg}, legend=False)
    ax.axhline(threshold, color="0.3", ls="--", lw=1)
    ax.text(1.45, threshold + 0.03, f"threshold {threshold}", ha="right", va="bottom", size=aa.plot_gcfs() - 2)
    ax.set_title(title, size=aa.plot_gcfs() - 1)
    ax.set_xlabel("")
    ax.set_ylim(-0.05, 1.12)
    sns.despine(ax=ax)
axes[0].set_ylabel("Sequence identity")
plt.tight_layout()
plt.show()
../_images/protocol3_sampling_5_output_33_0.png
# The same strips as numbers: worst identity and how many windows sit above the threshold.
df_ident_summary = (df_ident.assign(above=lambda d: d["identity"] > d["check"].map({"to_test": 0.8, "within_ref": 0.9}))
                    .groupby(["check", "setting"], sort=False)
                    .agg(n_windows=("identity", "size"), max_identity=("identity", "max"), n_above_threshold=("above", "sum"))
                    .reset_index().round(2))
aa.display_df(df=df_ident_summary, n_rows=10, show_shape=True)
DataFrame shape: (4, 5)
  check setting n_windows max_identity n_above_threshold
1 to_test No filters 12 0.120000 0
2 within_ref No filters 12 1.000000 2
3 to_test Filtered 12 0.120000 0
4 within_ref Filtered 12 0.620000 0

Without filters, one same-protein “negative” is identical to a test window (identity 1.0, the leak the default distance band allows), and the different-protein pool contains exact duplicates, because the non-substrate proteins repeat the same stretches. With the filters on, both are gone and the sampler re-draws to keep n.

How to interpret. Read the table one row at a time, each row is a single window, and the columns tell you where it came from and what it means for training:

Column / value

Reading

one row

one fixed-length window; protein-sourced rows are anchored at a P1 site

window

the residue slice the model/CPP actually sees

source_position

the 1-based P1 anchor on the source protein (-1 for synthetic, which has no anchor)

role = Negative

same-protein reference window (used as a hard negative in this example)

role = Unlabeled

cross-protein site of unknown status, the U pool for PU-learning

role = Control

synthetic composition baseline (null)

label

window-level target (1 test / 0 reference) for downstream training

Once you combine the annotated test windows with the selected references, that set is the contrast the downstream residue-level CPP run profiles: test vs. all reference, or test vs. a single role (e.g. hard negatives only). Choosing roles is choosing the biological question.

Figure

Choice it isolates

What to look for

windows + role composition

the assembled reference set

sources, non-overlap rule, and role counts match the arms

distance band

`` min_distance_to_pos`` / `` max_distance_to_pos``

overlaps (and the positive itself) under the default

composition heatmap

the sampling strategy

how far each reference sits from the test composition

motif score + contribution

s ample_motif_matched vs the pool it draws from

the best lookalike still scores far below every real site

identity strips

max _similarity_to_test / max_si milarity_within_ref

identity-1.0 leaks and duplicates without filters

Key takeaways

  • One row = one fixed-length window; its role (Test / Negative / Unlabeled / Control) is the workflow meaning you assign, while its strategy is the sampling provenance set for you.

  • Choosing which roles enter the reference group (label=0) is choosing the biological question: the residue-level CPP contrast is only ever as fair as the reference and control windows you draw.

  • entry_win is the dedupe key for protein-sourced windows across calls; synthetic control windows carry a per-call entry_win, so dedupe them on the window string instead.

Common mistakes.

  • Feeding pre-windowed data to the sampler: AA_CASPASE3 from load_dataset() is already windowed; the sampler needs full sequences + a ``pos`` column.

  • Forgetting ``pos_col``: without the P1 anchors the sampler cannot identify positives (to exclude them and to drive the anti-leakage filter).

  • Leaving the distance band and filters at their defaults: as the band figure shows, the default admits windows overlapping the positives, even the positive site itself. Set min_distance_to_pos=window_size and max_similarity_to_test.

  • Trusting a composition control blindly: "global_freq" copies the residue frequencies of all of df_seq, positives included, so it can carry part of the site signal (see the heatmap); "uniform" carries none of the proteome’s real composition. Use synthetic windows as a control next to a protein-sourced reference, not as the only reference, and check their composition.

  • Wrong ``window_size`` parity: cleavage is between residues (an even window); a single-residue PTM needs an odd window. Match the biology.

  • Over-sampling a tiny pool: asking for more windows than the pool holds returns fewer rows than requested (the sampler re-draws, then stops at the pool size); keep n well below the number of admissible windows and check len of the result.

  • Mixing roles without intent: decide upfront: PU-learning (Unlabeled)? hard negatives (Negative)? composition control (Control)?

  • Naive dedupe: drop_duplicates("entry_win") is right for protein-sourced rows but wrong for synthetic (per-call entry_win); dedupe controls on window.

The last three are quick to check in code.

# Parity: the same P1 anchor (14 on SUB1) with an even vs an odd window.
rows = []
for size in (8, 9):
    left = (size - 1) // 2
    rows.append({"window_size": size, "mode": "between-residues" if size % 2 == 0 else "single-residue",
                 "residues left of P1 (incl.)": left + 1, "residues right of P1": size - left - 1,
                 "window": seqp.get_aa_window(seq=df_seq.loc[0, "sequence"], pos_start=14 - left,
                                              window_size=size, index1=True)})
aa.display_df(df=pd.DataFrame(rows), n_rows=10, show_shape=True)
DataFrame shape: (2, 5)
  window_size mode residues left of P1 (incl.) residues right of P1 window
1 8 between-residues 4 4 DEVDSGLA
2 9 single-residue 5 4 RDEVDSGLA
# Over-sampling: 3 non-substrate proteins x 42 admissible 8-mers = 126 windows in the pool.
aaws = aa.AAWindowSampler(random_state=42, verbose=False)
rows = [{"n requested": n, "n returned": len(aaws.sample_different_protein(df_seq=df_seq, n=n, window_size=8, seed=42))}
        for n in (12, 100, 500)]
aa.display_df(df=pd.DataFrame(rows), n_rows=10, show_shape=True)
DataFrame shape: (3, 2)
  n requested n returned
1 12 12
2 100 100
3 500 126
# Naive dedupe: two synthetic calls both number their rows synth_0 ... synth_9.
df_two_calls = pd.concat([aaws.sample_synthetic(df_seq=df_seq, n=10, window_size=8, generator="uniform", seed=seed)
                          for seed in (1, 2)], ignore_index=True)
df_dedupe = pd.DataFrame({
    "rows after concat": [len(df_two_calls)],
    "drop_duplicates('entry_win')": [len(df_two_calls.drop_duplicates(subset="entry_win"))],
    "drop_duplicates('window')": [len(df_two_calls.drop_duplicates(subset="window"))],
})
aa.display_df(df=df_dedupe, n_rows=10, show_shape=True)
DataFrame shape: (1, 3)
  rows after concat drop_duplicates('entry_win') drop_duplicates('window')
1 20 10 20

Deduping on entry_win silently throws away half of the distinct synthetic windows; deduping on window keeps them.

Next step. Before P4: Prediction levels, combine one test row per annotated anchor (label=1) with the selected, deduplicated reference rows in df_clean (label=0). Select entry_win, window, and label, then rename entry_win to entry and window to sequence to form the residue-level df_seq. P4 shows how get_df_parts() turns those windows into one tmd part (list_parts=["tmd"], jmd_n_len=0, jmd_c_len=0) before run() profiles the contrast. For numeric per-window representations, build aligned numeric parts and use run_num().