Skip to content

Sequence distance models

DDMC supports two interchangeable ways of scoring how well a peptide sequence matches a cluster's motif, selected via DDMC(..., distance_method=...).

ddmc.binomial

ddmc.binomial

Binomial sequence-distance model used by ddmc.clustering.DDMC.

Contains
  • AAfreq / AAlist: reference amino acid frequencies and the fixed amino acid ordering used throughout the package.
  • Position weight matrix helpers (position_weight_matrix, fast_position_weight_matrix, frequencies, GenerateBinarySeqID).
  • Background phosphosite sequence sampling from PhosphoSitePlus (BackgroundSeqs, BackgProportions, CountPsiteTypes, and their cached loaders).
  • The Binomial class: for each cluster, models how enriched each amino acid is at each position (relative to the background) using the binomial-probability approach of Schwartz & Gygi, Nat Biotechnol 2005 (doi:10.1038/nbt1146), and scores every peptide sequence against each cluster's model.

Binomial

Binomial(seqs: ndarray, include_ptms: bool = False)

Binomial sequence-distance model, used by ddmc.clustering.DDMC when distance_method="Binomial".

For each cluster, scores how enriched each amino acid is at each position of a peptide's sequence relative to a background distribution of phosphosites, following Schwartz & Gygi, Nat Biotechnol 2005 (doi:10.1038/nbt1146).

Attributes:

Name Type Description
background

Background PWM (amino acid frequency per position) of shape (len(AAlist), n_pos), built from BackgroundSeqs(seqs).

n_aa

Number of amino acids (len(AAlist)).

n_pos

Number of sequence positions (11).

foreground_flat

Flattened one-hot encoding of seqs, of shape (n_seqs, n_aa * n_pos).

logWeights

Log-probability of each sequence under each cluster's current binomial model, of shape (n_seqs, n_clusters). Set to the scalar 0.0 until from_summaries is first called.

Parameters:

Name Type Description Default
seqs ndarray

The length-11 peptide sequences being clustered.

required
include_ptms bool

If True, preserve modified flanking residue tokens (s, t, y, k) using the expanded 24-token PTM alphabet.

False
Source code in ddmc/binomial.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def __init__(self, seqs: np.ndarray, include_ptms: bool = False):
    """
    Args:
        seqs: The length-11 peptide sequences being clustered.
        include_ptms: If `True`, preserve modified flanking residue tokens
            (`s`, `t`, `y`, `k`) using the expanded 24-token PTM alphabet.
    """
    self.include_ptms = include_ptms
    # Background sequences (memoized across fits; copy since it's mutated)
    self.background = _cached_background_pwm(
        *_background_counts(seqs), include_ptms
    ).copy()
    foreground: np.ndarray = GenerateBinarySeqID(seqs, include_ptms=include_ptms)
    self.n_aa, self.n_pos = foreground.shape[1], foreground.shape[2]
    # Flattened, float view of the one-hot foreground used for fast
    # matrix multiplication in from_summaries (replacing einsum, which
    # is much slower on the boolean input and is called every EM step).
    self.foreground_flat = foreground.reshape(foreground.shape[0], -1).astype(
        np.float32
    )

    self.logWeights = 0.0
    assert np.all(np.isfinite(self.background))
    assert np.all(np.isfinite(self.foreground_flat))

compute_log_weights

compute_log_weights() -> None

Update self.logWeights for all sequences from self.probmat_flat.

Source code in ddmc/binomial.py
461
462
463
464
def compute_log_weights(self) -> None:
    """Update `self.logWeights` for all sequences from `self.probmat_flat`."""
    tempp = self.foreground_flat @ self.probmat_flat.T
    self.logWeights = np.log(np.maximum(tempp, 1e-30))

estimate_log_prob_batch

estimate_log_prob_batch(batch_idx: ndarray) -> np.ndarray

Evaluate sequence log-probabilities on a mini-batch of peptides.

Source code in ddmc/binomial.py
456
457
458
459
def estimate_log_prob_batch(self, batch_idx: np.ndarray) -> np.ndarray:
    """Evaluate sequence log-probabilities on a mini-batch of peptides."""
    tempp = self.foreground_flat[batch_idx] @ self.probmat_flat.T
    return np.log(np.maximum(tempp, 1e-30))

finalize_ema

finalize_ema() -> None

Recompute probmat_flat from the current EMA sufficient statistics.

Source code in ddmc/binomial.py
452
453
454
def finalize_ema(self) -> None:
    """Recompute `probmat_flat` from the current EMA sufficient statistics."""
    self.probmat_flat = self._probmat_from_counts(self._k_ema, self._n_ema)

from_summaries

from_summaries(weightsIn: ndarray) -> None

Refit each cluster's binomial model from the current soft cluster assignments, and update self.logWeights with each sequence's log-probability under its (updated) cluster model.

Parameters:

Name Type Description Default
weightsIn ndarray

Soft cluster assignments (responsibilities) of shape (n_seqs, n_clusters), i.e. exp(log_resp) from the EM E step.

required
Source code in ddmc/binomial.py
481
482
483
484
485
486
487
488
489
490
491
492
493
def from_summaries(self, weightsIn: np.ndarray) -> None:
    """Refit each cluster's binomial model from the current soft cluster
    assignments, and update `self.logWeights` with each sequence's
    log-probability under its (updated) cluster model.

    Args:
        weightsIn: Soft cluster assignments (responsibilities) of shape
            (n_seqs, n_clusters), i.e. `exp(log_resp)` from the EM E step.
    """
    k_flat = weightsIn.T.astype(np.float32) @ self.foreground_flat
    n_totals = np.sum(weightsIn, axis=0)
    self.probmat_flat = self._probmat_from_counts(k_flat, n_totals)
    self.compute_log_weights()

init_ema

init_ema(n_clusters: int) -> None

Initialize EMA sufficient-statistic accumulators for mini-batch fitting.

Source code in ddmc/binomial.py
421
422
423
424
425
426
def init_ema(self, n_clusters: int) -> None:
    """Initialize EMA sufficient-statistic accumulators for mini-batch fitting."""
    n_feat = self.n_aa * self.n_pos
    self._k_ema = np.zeros((n_clusters, n_feat), dtype=np.float32)
    self._n_ema = np.zeros(n_clusters, dtype=np.float32)
    self.probmat_flat = np.zeros((n_clusters, n_feat), dtype=np.float32)

score_sequences

score_sequences(seqs: list[str] | ndarray) -> np.ndarray

Score unseen length-11 peptide sequences against the fitted cluster binomial models.

Parameters:

Name Type Description Default
seqs list[str] | ndarray

Peptide sequences to score.

required

Returns:

Type Description
ndarray

Log-probabilities of shape (len(seqs), n_clusters).

Source code in ddmc/binomial.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def score_sequences(self, seqs: list[str] | np.ndarray) -> np.ndarray:
    """Score unseen length-11 peptide sequences against the fitted cluster
    binomial models.

    Args:
        seqs: Peptide sequences to score.

    Returns:
        Log-probabilities of shape `(len(seqs), n_clusters)`.
    """
    foreground = GenerateBinarySeqID(seqs, include_ptms=self.include_ptms)
    fg_flat = foreground.reshape(foreground.shape[0], -1).astype(np.float32)
    tempp = fg_flat @ self.probmat_flat.T
    return np.log(np.maximum(tempp, 1e-30))

split_cluster

split_cluster(donor: int, target: int) -> None

Halve donor's EMA sufficient statistics into target and donor.

Source code in ddmc/binomial.py
443
444
445
446
447
448
449
450
def split_cluster(self, donor: int, target: int) -> None:
    """Halve `donor`'s EMA sufficient statistics into `target` and `donor`."""
    half_k = 0.5 * self._k_ema[donor]
    self._k_ema[target] = half_k
    self._k_ema[donor] = half_k
    half_n = 0.5 * self._n_ema[donor]
    self._n_ema[target] = half_n
    self._n_ema[donor] = half_n

update_ema

update_ema(
    batch_idx: ndarray,
    weights_batch: ndarray,
    alpha: float,
    scale: float = 1.0,
) -> None

Update EMA sufficient statistics from a mini-batch of responsibilities.

Source code in ddmc/binomial.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def update_ema(
    self,
    batch_idx: np.ndarray,
    weights_batch: np.ndarray,
    alpha: float,
    scale: float = 1.0,
) -> None:
    """Update EMA sufficient statistics from a mini-batch of responsibilities."""
    k_batch = (
        weights_batch.T.astype(np.float32) @ self.foreground_flat[batch_idx]
    ) * np.float32(scale)
    n_batch = (np.sum(weights_batch, axis=0) * scale).astype(np.float32)
    self._k_ema = (1.0 - alpha) * self._k_ema + alpha * k_batch
    self._n_ema = (1.0 - alpha) * self._n_ema + alpha * n_batch

BackgroundSeqs

BackgroundSeqs(forseqs: ndarray) -> list[str]

Build a background data set of length-11 phosphosite motifs sampled from PhosphoSitePlus, matching the proportion of pY, pT, and pS sites found in the foreground set of sequences.

Note this PsP data set contains 51976 pY, 226131 pS, 81321 pT Source: https://www.phosphosite.org/staticDownloads.action - Phosphorylation_site_dataset.gz - Last mod: Wed Dec 04 14:56:35 EST 2019 Cite: Hornbeck PV, Zhang B, Murray B, Kornhauser JM, Latham V, Skrzypek E PhosphoSitePlus, 2014: mutations, PTMs and recalibrations. Nucleic Acids Res. 2015 43:D512-20. PMID: 25514926

Parameters:

Name Type Description Default
forseqs ndarray

The foreground peptide sequences whose pY/pS/pT proportions the background set should match.

required

Returns:

Type Description
list[str]

Length-11 background peptide sequences sampled from PhosphoSitePlus,

list[str]

with the phosphoacceptor lowercased, in pY/pS/pT order.

Source code in ddmc/binomial.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def BackgroundSeqs(forseqs: np.ndarray) -> list[str]:
    """Build a background data set of length-11 phosphosite motifs sampled from
    PhosphoSitePlus, matching the proportion of pY, pT, and pS sites found in
    the foreground set of sequences.

    Note this PsP data set contains 51976 pY, 226131 pS, 81321 pT
    Source: https://www.phosphosite.org/staticDownloads.action -
    Phosphorylation_site_dataset.gz - Last mod: Wed Dec 04 14:56:35 EST 2019
    Cite: Hornbeck PV, Zhang B, Murray B, Kornhauser JM, Latham V, Skrzypek E PhosphoSitePlus, 2014: mutations,
    PTMs and recalibrations. Nucleic Acids Res. 2015 43:D512-20. PMID: 25514926

    Args:
        forseqs: The foreground peptide sequences whose pY/pS/pT proportions
            the background set should match.

    Returns:
        Length-11 background peptide sequences sampled from PhosphoSitePlus,
        with the phosphoacceptor lowercased, in pY/pS/pT order.
    """
    # Build background sequences (cached, since for fixed reference data
    # this only depends on the pY/pS/pT proportions of the foreground set)
    return list(_cached_background_proportions(*_background_counts(forseqs)))

BackgProportions

BackgProportions(
    refseqs: list[str], pYn: int, pSn: int, pTn: int
) -> list[str]

Slice length-11 motifs out of the +/-7 AA reference sequences, keeping up to the requested number of pY, pS, and pT sites.

Parameters:

Name Type Description Default
refseqs list[str]

Raw +/-7 AA PhosphoSitePlus reference sequences.

required
pYn int

Maximum number of pY motifs to keep.

required
pSn int

Maximum number of pS motifs to keep.

required
pTn int

Maximum number of pT motifs to keep.

required

Returns:

Type Description
list[str]

The length-11 background motifs (phosphoacceptor lowercased),

list[str]

concatenated in pY, pS, pT order.

Source code in ddmc/binomial.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def BackgProportions(refseqs: list[str], pYn: int, pSn: int, pTn: int) -> list[str]:
    """Slice length-11 motifs out of the +/-7 AA reference sequences, keeping
    up to the requested number of pY, pS, and pT sites.

    Args:
        refseqs: Raw +/-7 AA PhosphoSitePlus reference sequences.
        pYn: Maximum number of pY motifs to keep.
        pSn: Maximum number of pS motifs to keep.
        pTn: Maximum number of pT motifs to keep.

    Returns:
        The length-11 background motifs (phosphoacceptor lowercased),
        concatenated in pY, pS, pT order.
    """
    y_seqs: list[str] = []
    s_seqs: list[str] = []
    t_seqs: list[str] = []

    pR = ["y", "t", "s"]
    for seq in refseqs:
        if seq[7] not in pR:
            continue

        motif = str(seq)[7 - 5 : 7 + 6].upper()
        assert len(motif) == 11, f"Wrong sequence length. Sliced: {motif}, Full: {seq}"
        assert motif[5].lower() in pR, (
            f"Wrong central AA in background set. Sliced: {motif}, Full: {seq}"
        )

        if motif[5] == "Y" and len(y_seqs) < pYn:
            y_seqs.append(motif)

        if motif[5] == "S" and len(s_seqs) < pSn:
            s_seqs.append(motif)

        if motif[5] == "T" and len(t_seqs) < pTn:
            t_seqs.append(motif)

    return y_seqs + s_seqs + t_seqs

CountPsiteTypes

CountPsiteTypes(X) -> tuple[int, int, int]

Count the number of different phosphorylation types in an MS data set.

Parameters:

Name Type Description Default
X list[str]

The list of peptide sequences.

required

Returns:

Type Description
tuple[int, int, int]

tuple[int, int, int]: The number of pY, pS, and pT sites.

Source code in ddmc/binomial.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def CountPsiteTypes(X) -> tuple[int, int, int]:
    """Count the number of different phosphorylation types in an MS data set.

    Args:
        X (list[str]): The list of peptide sequences.

    Returns:
        tuple[int, int, int]: The number of pY, pS, and pT sites.
    """
    X = np.char.upper(X)

    # Find the center amino acid
    cA = int((len(X[0]) - 1) / 2)

    phospho_aminos = [seq[cA] for seq in X]
    pS = phospho_aminos.count("S")
    pT = phospho_aminos.count("T")
    pY = phospho_aminos.count("Y")
    return pY, pS, pT

position_weight_matrix

position_weight_matrix(
    seqs: list[str],
    pseudoC: OrderedDict[str, float] = AAfreq,
) -> Any

Build a position weight matrix (PWM) of a given set of same-length sequences.

Parameters:

Name Type Description Default
seqs list[str]

Sequences (all the same length) to build the PWM from.

required
pseudoC OrderedDict[str, float]

Per-amino-acid pseudocounts to add before normalizing, keyed by one-letter amino acid code. Defaults to AAfreq.

AAfreq

Returns:

Type Description
Any

A Biopython PositionWeightMatrix (amino acid frequency per

Any

position, normalized to sum to 1 down each column) of shape

Any

(len(AAlist), sequence length).

Source code in ddmc/binomial.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def position_weight_matrix(
    seqs: list[str], pseudoC: OrderedDict[str, float] = AAfreq
) -> Any:
    """Build a position weight matrix (PWM) of a given set of same-length sequences.

    Args:
        seqs: Sequences (all the same length) to build the PWM from.
        pseudoC: Per-amino-acid pseudocounts to add before normalizing,
            keyed by one-letter amino acid code. Defaults to `AAfreq`.

    Returns:
        A Biopython `PositionWeightMatrix` (amino acid frequency per
        position, normalized to sum to 1 down each column) of shape
        (len(AAlist), sequence length).
    """
    return frequencies(seqs).normalize(pseudocounts=pseudoC)

fast_position_weight_matrix

fast_position_weight_matrix(
    seqs: list[str], include_ptms: bool = False
) -> np.ndarray

Build a (n_aa, seq_length) PWM of a given set of same-length sequences, equivalent to position_weight_matrix but without the overhead of Biopython's general-purpose alignment machinery.

Parameters:

Name Type Description Default
seqs list[str]

Sequences, all of the same length, to build the PWM from.

required
include_ptms bool

If True, use the expanded 24-token PTM alphabet (PTM_AAlist) preserving flanking s, t, y, k.

False

Returns:

Type Description
ndarray

Array of shape (len(AAlist), sequence length) (or `(len(PTM_AAlist),

ndarray

sequence length)wheninclude_ptms=True`) giving the

ndarray

pseudocount-smoothed frequency of each token at each position.

Source code in ddmc/binomial.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def fast_position_weight_matrix(
    seqs: list[str], include_ptms: bool = False
) -> np.ndarray:
    """Build a `(n_aa, seq_length)` PWM of a given set of same-length
    sequences, equivalent to `position_weight_matrix` but without the
    overhead of Biopython's general-purpose alignment machinery.

    Args:
        seqs: Sequences, all of the same length, to build the PWM from.
        include_ptms: If `True`, use the expanded 24-token PTM alphabet
            (`PTM_AAlist`) preserving flanking `s`, `t`, `y`, `k`.

    Returns:
        Array of shape `(len(AAlist), sequence length)` (or `(len(PTM_AAlist),
        sequence length)` when `include_ptms=True`) giving the
        pseudocount-smoothed frequency of each token at each position.
    """
    seq_len = len(seqs[0])
    norm_seqs = (
        normalize_ptm_sequences(seqs, include_ptms=True).tolist()
        if include_ptms
        else seqs
    )
    lookup = _PTM_AAbyteLookup if include_ptms else _AAbyteLookup
    pseudo = _PTM_pseudoCounts if include_ptms else _pseudoCounts
    n_aa = len(PTM_AAlist) if include_ptms else len(AAlist)

    # Convert to fixed-width bytes and view as a 2D uint8 array so the
    # char->index lookup is a single vectorized gather instead of a nested
    # Python loop over every character of every sequence.
    seqs_bytes = np.asarray(norm_seqs, dtype=f"S{seq_len}")
    byte_view = seqs_bytes.view(np.uint8).reshape(len(norm_seqs), seq_len)
    idx = lookup[byte_view]

    counts = np.zeros((n_aa, seq_len))
    for pos in range(seq_len):
        counts[:, pos] = np.bincount(idx[:, pos], minlength=n_aa)

    return (counts + pseudo[:, None]) / (
        counts.sum(axis=0, keepdims=True) + pseudo.sum()
    )

frequencies

frequencies(seqs: list[str]) -> Any

Build a per-position amino acid counts matrix of a given set of same-length sequences.

Parameters:

Name Type Description Default
seqs list[str]

Sequences, all of the same length, to count.

required

Returns:

Type Description
Any

A Biopython FrequencyPositionMatrix giving the raw count of each

Any

amino acid at each position across seqs.

Source code in ddmc/binomial.py
169
170
171
172
173
174
175
176
177
178
179
def frequencies(seqs: list[str]) -> Any:
    """Build a per-position amino acid counts matrix of a given set of same-length sequences.

    Args:
        seqs: Sequences, all of the same length, to count.

    Returns:
        A Biopython `FrequencyPositionMatrix` giving the raw count of each
        amino acid at each position across `seqs`.
    """
    return motifs.create(seqs, alphabet="".join(AAlist)).counts

GenerateBinarySeqID

GenerateBinarySeqID(
    seqs: list[str] | ndarray, include_ptms: bool = False
) -> np.ndarray

Build a one-hot encoding of amino acid (or flanking PTM) identity at each position, for every sequence.

Parameters:

Name Type Description Default
seqs list[str] | ndarray

Length-11 peptide sequences to encode.

required
include_ptms bool

If True, use the expanded 24-token PTM alphabet (PTM_AAlist) preserving flanking s, t, y, k.

False

Returns:

Type Description
ndarray

Boolean array of shape (len(seqs), n_aa, 11), where

ndarray

result[i, j, k] is True if sequence i has token j at position k.

Source code in ddmc/binomial.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def GenerateBinarySeqID(
    seqs: list[str] | np.ndarray, include_ptms: bool = False
) -> np.ndarray:
    """Build a one-hot encoding of amino acid (or flanking PTM) identity at
    each position, for every sequence.

    Args:
        seqs: Length-11 peptide sequences to encode.
        include_ptms: If `True`, use the expanded 24-token PTM alphabet
            (`PTM_AAlist`) preserving flanking `s`, `t`, `y`, `k`.

    Returns:
        Boolean array of shape `(len(seqs), n_aa, 11)`, where
        `result[i, j, k]` is True if sequence `i` has token `j` at position `k`.
    """
    norm_seqs = normalize_ptm_sequences(seqs, include_ptms=include_ptms)
    alphabet = PTM_AAlist if include_ptms else AAlist
    index_map = _PTM_AAindex if include_ptms else _AAindex
    res = np.zeros((len(norm_seqs), len(alphabet), 11), dtype=bool)
    for ii, seq in enumerate(norm_seqs):
        for pos, aa in enumerate(seq):
            res[ii, index_map[aa], pos] = 1
    return res

ddmc.pam250

ddmc.pam250

PAM250 sequence-distance model used by ddmc.clustering.DDMC.

Contains the PAM250 class, which scores peptide sequences against each cluster by their average PAM250 substitution-matrix similarity to the other sequences currently assigned to that cluster, and get_pam250_scores, which precomputes the full pairwise PAM250 similarity matrix used to do so.

PAM250

PAM250(
    seqs: list[str] | ndarray, include_ptms: bool = False
)

PAM250 sequence-distance model, used by ddmc.clustering.DDMC when distance_method="PAM250".

Scores each peptide sequence against a cluster by its (responsibility weighted) average pairwise PAM250 substitution score against every other sequence, using the fixed set of pairwise scores computed once at construction time.

Attributes:

Name Type Description
background

Pairwise PAM250 similarity matrix between all input sequences, of shape (n_seqs, n_seqs).

logWeights

Log-probability (average PAM250 score) of each sequence under each cluster's current model, of shape (n_seqs, n_clusters). Set to the scalar 0.0 until from_summaries is first called.

Parameters:

Name Type Description Default
seqs list[str] | ndarray

The length-11 peptide sequences being clustered.

required
include_ptms bool

If True, preserve modified flanking residue tokens (s, t, y, k) using the PTM-extended PAM250 matrix.

False
Source code in ddmc/pam250.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(self, seqs: list[str] | np.ndarray, include_ptms: bool = False):
    """
    Args:
        seqs: The length-11 peptide sequences being clustered.
        include_ptms: If `True`, preserve modified flanking residue tokens
            (`s`, `t`, `y`, `k`) using the PTM-extended PAM250 matrix.
    """
    self.include_ptms = include_ptms
    self.seqs = normalize_ptm_sequences(seqs, include_ptms=include_ptms)
    # Compute all pairwise distances. Cast to float32 once here rather
    # than in from_summaries, which runs every EM iteration and would
    # otherwise re-convert this (potentially large) int8 matrix each time.
    self.background = get_pam250_scores(
        self.seqs, include_ptms=include_ptms
    ).astype(np.float32)
    self.logWeights = 0.0

compute_log_weights

compute_log_weights() -> None

Update self.logWeights for all sequences from the current EMA.

Source code in ddmc/pam250.py
138
139
140
141
def compute_log_weights(self) -> None:
    """Update `self.logWeights` for all sequences from the current EMA."""
    sums = np.clip(self._n_ema, 1e-5, np.inf)
    self.logWeights = self._m_ema / sums

estimate_log_prob_batch

estimate_log_prob_batch(batch_idx: ndarray) -> np.ndarray

Evaluate sequence log-probabilities on a mini-batch of peptides.

Source code in ddmc/pam250.py
133
134
135
136
def estimate_log_prob_batch(self, batch_idx: np.ndarray) -> np.ndarray:
    """Evaluate sequence log-probabilities on a mini-batch of peptides."""
    sums = np.clip(self._n_ema, 1e-5, np.inf)
    return self._m_ema[batch_idx] / sums

finalize_ema

finalize_ema() -> None

No-op for PAM250 (cluster ratios are computed on demand).

Source code in ddmc/pam250.py
130
131
def finalize_ema(self) -> None:
    """No-op for PAM250 (cluster ratios are computed on demand)."""

from_summaries

from_summaries(weightsIn: ndarray) -> None

Update self.logWeights with each sequence's responsibility weighted average PAM250 similarity to all sequences, per cluster.

Parameters:

Name Type Description Default
weightsIn ndarray

Soft cluster assignments (responsibilities) of shape (n_seqs, n_clusters), i.e. exp(log_resp) from the EM E step.

required
Source code in ddmc/pam250.py
159
160
161
162
163
164
165
166
167
168
169
170
171
def from_summaries(self, weightsIn: np.ndarray) -> None:
    """Update `self.logWeights` with each sequence's responsibility
    weighted average PAM250 similarity to all sequences, per cluster.

    Args:
        weightsIn: Soft cluster assignments (responsibilities) of shape
            (n_seqs, n_clusters), i.e. `exp(log_resp)` from the EM E step.
    """
    sums = np.sum(weightsIn, axis=0)
    sums = np.clip(sums, 0.00001, np.inf)  # Avoid empty cluster divide by 0
    self._last_weights = weightsIn.astype(np.float32, copy=False)
    self._last_sums = sums.astype(np.float32, copy=False)
    self.logWeights = (self.background @ weightsIn) / sums

init_ema

init_ema(n_clusters: int) -> None

Initialize EMA sufficient-statistic accumulators for mini-batch fitting.

Source code in ddmc/pam250.py
102
103
104
105
def init_ema(self, n_clusters: int) -> None:
    """Initialize EMA sufficient-statistic accumulators for mini-batch fitting."""
    self._m_ema = np.zeros((self.background.shape[0], n_clusters), dtype=np.float32)
    self._n_ema = np.zeros(n_clusters, dtype=np.float32)

score_sequences

score_sequences(seqs: list[str] | ndarray) -> np.ndarray

Score unseen length-11 peptide sequences against the fitted cluster PAM250 similarity profiles.

Parameters:

Name Type Description Default
seqs list[str] | ndarray

Peptide sequences to score.

required

Returns:

Type Description
ndarray

Average PAM250 similarity scores of shape (len(seqs), n_clusters).

Source code in ddmc/pam250.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def score_sequences(self, seqs: list[str] | np.ndarray) -> np.ndarray:
    """Score unseen length-11 peptide sequences against the fitted cluster
    PAM250 similarity profiles.

    Args:
        seqs: Peptide sequences to score.

    Returns:
        Average PAM250 similarity scores of shape `(len(seqs), n_clusters)`.
    """
    seqs_norm = normalize_ptm_sequences(seqs, include_ptms=self.include_ptms)
    bg_test = get_pam250_scores(
        seqs_norm, self.seqs, include_ptms=self.include_ptms
    ).astype(np.float32)
    return (bg_test @ self._last_weights) / self._last_sums

split_cluster

split_cluster(donor: int, target: int) -> None

Halve donor's EMA sufficient statistics into target and donor.

Source code in ddmc/pam250.py
121
122
123
124
125
126
127
128
def split_cluster(self, donor: int, target: int) -> None:
    """Halve `donor`'s EMA sufficient statistics into `target` and `donor`."""
    half_m = 0.5 * self._m_ema[:, donor]
    self._m_ema[:, target] = half_m
    self._m_ema[:, donor] = half_m
    half_n = 0.5 * self._n_ema[donor]
    self._n_ema[target] = half_n
    self._n_ema[donor] = half_n

update_ema

update_ema(
    batch_idx: ndarray,
    weights_batch: ndarray,
    alpha: float,
    scale: float = 1.0,
) -> None

Update EMA sufficient statistics from a mini-batch of responsibilities.

Source code in ddmc/pam250.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def update_ema(
    self,
    batch_idx: np.ndarray,
    weights_batch: np.ndarray,
    alpha: float,
    scale: float = 1.0,
) -> None:
    """Update EMA sufficient statistics from a mini-batch of responsibilities."""
    w = (weights_batch * scale).astype(np.float32)
    m_batch = self.background[:, batch_idx] @ w
    n_batch = np.sum(w, axis=0)
    self._m_ema = (1.0 - alpha) * self._m_ema + alpha * m_batch
    self._n_ema = (1.0 - alpha) * self._n_ema + alpha * n_batch

get_pam250_scores

get_pam250_scores(
    seqs: list[str] | ndarray,
    seqs_b: list[str] | ndarray | None = None,
    include_ptms: bool = False,
) -> np.ndarray

Compute the pairwise PAM250 similarity matrix between sequences.

Parameters:

Name Type Description Default
seqs list[str] | ndarray

Sequences (all the same length) to score pairwise.

required
seqs_b list[str] | ndarray | None

Optional second sequence list. If omitted, computes the symmetric (len(seqs), len(seqs)) self-similarity matrix; otherwise computes the (len(seqs), len(seqs_b)) cross-matrix.

None
include_ptms bool

If True, score flanking PTM tokens (s, t, y, k) with the PTM-extended PAM250 substitution matrix.

False

Returns:

Type Description
ndarray

Array of shape (len(seqs), len(seqs)) (or (len(seqs), len(seqs_b))

ndarray

when seqs_b is given), where entry [i, j] is the summed PAM250

ndarray

substitution score between seqs[i] and the target sequence j

ndarray

(aligned position-by-position, no gaps).

Source code in ddmc/pam250.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def get_pam250_scores(
    seqs: list[str] | np.ndarray,
    seqs_b: list[str] | np.ndarray | None = None,
    include_ptms: bool = False,
) -> np.ndarray:
    """Compute the pairwise PAM250 similarity matrix between sequences.

    Args:
        seqs: Sequences (all the same length) to score pairwise.
        seqs_b: Optional second sequence list. If omitted, computes the
            symmetric `(len(seqs), len(seqs))` self-similarity matrix;
            otherwise computes the `(len(seqs), len(seqs_b))` cross-matrix.
        include_ptms: If `True`, score flanking PTM tokens (`s`, `t`, `y`, `k`)
            with the PTM-extended PAM250 substitution matrix.

    Returns:
        Array of shape `(len(seqs), len(seqs))` (or `(len(seqs), len(seqs_b))`
        when `seqs_b` is given), where entry `[i, j]` is the summed PAM250
        substitution score between `seqs[i]` and the target sequence `j`
        (aligned position-by-position, no gaps).
    """
    alphabet, pam250m = _load_pam250_alphabet_and_matrix(include_ptms)
    seq_idx = np.array(
        [[alphabet.find(aa) for aa in seq] for seq in seqs],
        dtype=np.int8,
    )

    # int32, not int8: an int8 accumulator overflows for realistic peptide
    # lengths (e.g. 11 tryptophans score 11 * 17 = 187, above int8's 127
    # ceiling), silently wrapping self-similarity scores to negative values.
    if seqs_b is None:
        out = np.zeros((seq_idx.shape[0], seq_idx.shape[0]), dtype=np.int32)
        i_idx, j_idx = np.tril_indices(seq_idx.shape[0])
        out[i_idx, j_idx] = np.sum(pam250m[seq_idx[i_idx], seq_idx[j_idx]], axis=1)

        i_upper = np.triu_indices_from(out, k=1)
        out[i_upper] = out.T[i_upper]  # pylint: disable=unsubscriptable-object
        return out

    seq_idx_b = np.array(
        [[alphabet.find(aa) for aa in seq] for seq in seqs_b],
        dtype=np.int8,
    )
    out = np.zeros((seq_idx.shape[0], seq_idx_b.shape[0]), dtype=np.int32)
    chunk = 256
    for start in range(0, seq_idx.shape[0], chunk):
        end = min(start + chunk, seq_idx.shape[0])
        out[start:end] = np.sum(
            pam250m[seq_idx[start:end, None, :], seq_idx_b[None, :, :]],
            axis=2,
        )
    return out