Skip to content

ddmc.clustering

The core DDMC model and its supporting functions.

ddmc.clustering

Dual data and motif clustering (DDMC).

Contains the DDMC model itself — a sklearn.mixture.GaussianMixture subclass that jointly clusters peptides on their phosphorylation signal and their sequence motif — and get_pspl_pssm_distances, the helper it uses to compare cluster motifs against kinase specificity profiles.

DDMC

DDMC(
    n_components: int,
    seq_weight: float,
    distance_method: Literal[
        "PAM250", "Binomial"
    ] = "Binomial",
    random_state: int | RandomState | None = None,
    max_iter: int = 200,
    tol: float = 0.0001,
    n_epochs: int = 10,
    include_ptms: bool = True,
)

Bases: GaussianMixture

Cluster peptides by both sequence similarity and condition-wise phosphorylation following an expectation-maximization algorithm.

DDMC subclasses sklearn.mixture.GaussianMixture and reuses its EM loop, but scores each peptide against each cluster using both the usual Gaussian mixture log-probability over its phosphorylation signal and a sequence-motif term (weighted by seq_weight), and refits both the Gaussian mixture parameters and the per-cluster sequence motif at every M step. See ddmc.binomial.Binomial and ddmc.pam250.PAM250 for the two available motif models.

Attributes set by fit: p_signal: The p_signal DataFrame passed to fit. sequences: p_signal.index, as an upper-cased numpy array. seq_dist: The fitted Binomial or PAM250 sequence-distance model. scores_: Per-peptide, per-cluster responsibilities (soft cluster assignments) of shape (n_peptides, n_components). seq_scores_: Per-peptide, per-cluster weighted sequence log-probabilities (seq_weight * seq_dist.logWeights) from the last E step, of shape (n_peptides, n_components).

Parameters:

Name Type Description Default
n_components int

The number of clusters to fit.

required
seq_weight float

Weight applied to the sequence-motif log-probability relative to the Gaussian mixture log-probability when scoring each peptide against each cluster. 0 reduces DDMC to an ordinary Gaussian mixture model.

required
distance_method Literal['PAM250', 'Binomial']

Which sequence-distance model to use for the motif term: "Binomial" (ddmc.binomial.Binomial) or "PAM250" (ddmc.pam250.PAM250).

'Binomial'
random_state int | RandomState | None

Seed or numpy.random.RandomState controlling the random initialization and mini-batch shuffling, for reproducibility.

None
max_iter int

Maximum number of EM iterations (kept for API compatibility).

200
tol float

Convergence threshold (kept for API compatibility).

0.0001
n_epochs int

Number of mini-batch EMA epochs to run before the final exact full-batch EM pass.

10
Source code in ddmc/clustering.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __init__(
    self,
    n_components: int,
    seq_weight: float,
    distance_method: Literal["PAM250", "Binomial"] = "Binomial",
    random_state: int | np.random.RandomState | None = None,
    max_iter: int = 200,
    tol: float = 1e-4,
    n_epochs: int = 10,
    include_ptms: bool = True,
):
    """
    Args:
        n_components: The number of clusters to fit.
        seq_weight: Weight applied to the sequence-motif log-probability
            relative to the Gaussian mixture log-probability when
            scoring each peptide against each cluster. `0` reduces
            `DDMC` to an ordinary Gaussian mixture model.
        distance_method: Which sequence-distance model to use for the
            motif term: `"Binomial"` (`ddmc.binomial.Binomial`) or
            `"PAM250"` (`ddmc.pam250.PAM250`).
        random_state: Seed or `numpy.random.RandomState` controlling the
            random initialization and mini-batch shuffling, for
            reproducibility.
        max_iter: Maximum number of EM iterations (kept for API
            compatibility).
        tol: Convergence threshold (kept for API compatibility).
        n_epochs: Number of mini-batch EMA epochs to run before the final
            exact full-batch EM pass.
    """
    super().__init__(
        n_components=n_components,
        covariance_type="diag",
        n_init=1,
        max_iter=max_iter,
        tol=tol,
        random_state=random_state,
    )
    self.distance_method = distance_method
    self.seq_weight = seq_weight
    self.n_epochs = n_epochs
    self.include_ptms = include_ptms

fit

fit(p_signal: DataFrame) -> DDMC

Compute EM clustering.

Parameters:

Name Type Description Default
p_signal DataFrame

Dataframe of shape (number of peptides, number of samples) containing the phosphorylation signal. p_signal.index contains the length-11 AA sequence of each peptide, containing the phosphoacceptor in the middle and five AAs flanking it.

required

Returns:

Type Description
DDMC

self, fit to p_signal.

Source code in ddmc/clustering.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def fit(self, p_signal: pd.DataFrame) -> "DDMC":  # ty: ignore[incompatible-method-override]
    """
    Compute EM clustering.

    Args:
        p_signal: Dataframe of shape (number of peptides, number of samples)
            containing the phosphorylation signal. `p_signal.index` contains
            the length-11 AA sequence of each peptide, containing the
            phosphoacceptor in the middle and five AAs flanking it.

    Returns:
        self, fit to `p_signal`.
    """
    assert isinstance(p_signal, pd.DataFrame), (
        "`p_signal` must be a pandas dataframe."
    )
    sequences = p_signal.index.values

    for i, seq in enumerate(sequences):
        assert isinstance(seq, str), (
            f"Sequence {seq} at index {i} is not a string. All sequences must be strings."
        )
        assert len(seq) == 11, (
            f"Sequence {seq} at index {i} is of length {len(seq)}. All sequences must be of length 11."
        )
        assert all([token.upper() in AAlist for token in seq]), (
            f"Sequence {seq} at index {i} contains invalid characters."
        )

    assert (
        p_signal.select_dtypes(include=[np.number]).shape[1] == p_signal.shape[1]
    ), "All values in `p_signal` should be numerical"

    self.p_signal = p_signal
    self._gen_peptide_distances(sequences, self.distance_method)

    if np.any(np.isnan(p_signal)):
        self._missing = True
        X_raw = p_signal.to_numpy(dtype=np.float64)
        obs_mask = ~np.isnan(X_raw)
        self._obs_mask = obs_mask.astype(np.float64)
        col_counts = np.sum(self._obs_mask, axis=0)
        X = np.where(obs_mask, X_raw, 0.0)
        col_means = np.divide(
            np.sum(X, axis=0),
            col_counts,
            out=np.zeros(X.shape[1]),
            where=col_counts > 0,
        )
        self._col_means: np.ndarray | None = col_means
        centered = np.where(obs_mask, X - col_means[None, :], 0.0)
        self._col_vars: np.ndarray | None = np.divide(
            np.sum(centered * centered, axis=0),
            col_counts,
            out=np.ones(X.shape[1]),
            where=col_counts > 0,
        )
    else:
        self._missing = False
        self._col_means = None
        self._col_vars = None
        X = p_signal

    X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)
    if X.shape[0] < self.n_components:
        raise ValueError(
            "Expected n_samples >= n_components "
            f"but got n_components = {self.n_components}, "
            f"n_samples = {X.shape[0]}"
        )
    self._check_parameters(X)
    self._fit_emeans(X)

    assert np.all(np.isfinite(self.scores_))
    assert np.all(np.isfinite(self.seq_scores_))
    return self

fold_in

fold_in(
    p_signal_test: DataFrame,
    cols: ndarray | Sequence[int] | None = None,
) -> np.ndarray

Compute out-of-sample posterior cluster responsibilities for unseen peptides using only the specified sample columns cols and the fitted sequence-motif model.

Parameters:

Name Type Description Default
p_signal_test DataFrame

DataFrame of unseen peptides with length-11 sequences as index and the same sample columns as self.p_signal.

required
cols ndarray | Sequence[int] | None

Integer column indices to condition on. If None, all columns are used; if empty, responsibilities are computed from cluster priors and sequence motifs alone.

None

Returns:

Type Description
ndarray

Posterior cluster responsibilities of shape

ndarray

(len(p_signal_test), n_components).

Source code in ddmc/clustering.py
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
def fold_in(
    self,
    p_signal_test: pd.DataFrame,
    cols: np.ndarray | Sequence[int] | None = None,
) -> np.ndarray:
    """Compute out-of-sample posterior cluster responsibilities for unseen
    peptides using only the specified sample columns `cols` and the
    fitted sequence-motif model.

    Args:
        p_signal_test: DataFrame of unseen peptides with length-11 sequences
            as index and the same sample columns as `self.p_signal`.
        cols: Integer column indices to condition on. If `None`, all
            columns are used; if empty, responsibilities are computed from
            cluster priors and sequence motifs alone.

    Returns:
        Posterior cluster responsibilities of shape
        `(len(p_signal_test), n_components)`.
    """
    check_is_fitted(self, ["means_", "precisions_cholesky_", "weights_"])
    assert (
        self.means_ is not None
        and self.precisions_cholesky_ is not None
        and self.weights_ is not None
    )
    col_idx = (
        np.arange(p_signal_test.shape[1], dtype=int)
        if cols is None
        else np.asarray(cols, dtype=int)
    )
    log_prob = np.broadcast_to(
        np.log(self.weights_), (len(p_signal_test), self.n_components)
    ).copy()

    if col_idx.size > 0:
        X_raw = p_signal_test.to_numpy(dtype=np.float64)[:, col_idx]
        obs_mask = (~np.isnan(X_raw)).astype(np.float64)
        X_zero = np.where(obs_mask > 0, X_raw, 0.0)
        log_prob += self._diagonal_gaussian_log_prob(
            X_zero,
            obs_mask,
            self.means_[:, col_idx],
            self.precisions_cholesky_[:, col_idx],
        )

    if self.seq_weight != 0:
        log_prob += self.seq_weight * self.seq_dist.score_sequences(
            np.asarray(p_signal_test.index.values, dtype=str)
        )

    log_resp = log_prob - logsumexp(log_prob, axis=1, keepdims=True)
    return np.exp(log_resp)

get_nonempty_clusters

get_nonempty_clusters() -> np.ndarray

List the clusters that at least one peptide is assigned to.

Returns:

Type Description
ndarray

Sorted array of the distinct cluster indices present in

ndarray

self.labels(); shorter than n_components if any clusters

ndarray

are empty.

Source code in ddmc/clustering.py
862
863
864
865
866
867
868
869
870
def get_nonempty_clusters(self) -> np.ndarray:
    """List the clusters that at least one peptide is assigned to.

    Returns:
        Sorted array of the distinct cluster indices present in
        `self.labels()`; shorter than `n_components` if any clusters
        are empty.
    """
    return np.unique(self.labels())

get_pssms

get_pssms(
    PsP_background: bool = False, clusters: None = None
) -> tuple[np.ndarray, np.ndarray]
get_pssms(
    PsP_background: bool = False, *, clusters: list[int]
) -> np.ndarray
get_pssms(
    PsP_background: bool = False,
    clusters: list[int] | None = None,
) -> tuple[np.ndarray, np.ndarray] | np.ndarray

Compute position-specific scoring matrix of each cluster. Note, to normalize by amino acid frequency this uses either all the sequences in the data set or a collection of random MS phosphosites in PhosphoSitePlus.

Parameters:

Name Type Description Default
PsP_background bool

Whether or not PhosphoSitePlus should be used for background frequency.

False
clusters list[int] | None

cluster indices to get pssms for

None

Returns:

Type Description
tuple[ndarray, ndarray] | ndarray

If the clusters argument is used, an array of shape (len(clusters), 20, 11),

tuple[ndarray, ndarray] | ndarray

else two arrays, where the first (of shape (n_pssms,))

tuple[ndarray, ndarray] | ndarray

contains the clusters of the pssms in the second

tuple[ndarray, ndarray] | ndarray

(of shape (n_pssms, 20, 11)).

Source code in ddmc/clustering.py
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
def get_pssms(
    self, PsP_background: bool = False, clusters: list[int] | None = None
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
    """
    Compute position-specific scoring matrix of each cluster.
    Note, to normalize by amino acid frequency this uses either
    all the sequences in the data set or a collection of random MS phosphosites in PhosphoSitePlus.

    Args:
        PsP_background: Whether or not PhosphoSitePlus should be used for background frequency.
        clusters: cluster indices to get pssms for

    Returns:
        If the clusters argument is used, an array of shape (len(clusters), 20, 11),
        else two arrays, where the first (of shape (n_pssms,))
        contains the clusters of the pssms in the second
        (of shape (n_pssms, 20, 11)).
    """
    pssm_names, pssms = [], []
    if PsP_background:
        bg_seqs = BackgroundSeqs(self.sequences)
        back_pssm = compute_control_pssm(bg_seqs)
    else:
        back_pssm = np.zeros((len(AAlist), 11), dtype=float)
        for seq in self.sequences:
            seq = seq.upper()
            for kk, aa in enumerate(seq):
                back_pssm[AAlist.index(aa), kk] += 1.0
        for pos in range(back_pssm.shape[1]):
            if pos == 5:
                continue
            back_pssm[:, pos] /= np.mean(back_pssm[:, pos])

    l1 = list(np.arange(self.n_components))
    l2 = list(set(self.labels()))
    ec = [i for i in l1 + l2 if i not in l1 or i not in l2]
    for ii in range(self.n_components):
        # Check for empty clusters and ignore them, if there are
        if ii in ec:
            continue

        # Compute PSSM
        pssm = np.zeros((len(AAlist), 11), dtype=float)
        for jj, seq in enumerate(self.sequences):
            seq = seq.upper()
            for kk, aa in enumerate(seq):
                pssm[AAlist.index(aa), kk] += self.scores_[jj, ii]

        # Normalize by position across residues
        for pos in range(pssm.shape[1]):
            if pos == 5:
                continue
            pssm[:, pos] /= np.mean(pssm[:, pos])

        # Normalize to background PSSM to account for AA frequencies per position
        old_settings = np.seterr(divide="ignore", invalid="ignore")
        pssm /= back_pssm.copy()
        np.seterr(**old_settings)

        # Log2 transform
        pssm = np.ma.log2(pssm)
        pssm = pssm.filled(0)
        pssm = np.nan_to_num(pssm)
        pssm = pd.DataFrame(pssm)
        pssm.index = AAlist

        # Normalize phosphoacceptor position to frequency
        df = pd.DataFrame({"Sequence": self.sequences})
        df["Cluster"] = self.labels()
        clSeq = df[df["Cluster"] == ii]["Sequence"]
        clSeq = pd.DataFrame(
            frequencies(np.char.upper(clSeq.to_numpy(dtype=str)).tolist())
        ).T
        tm = np.mean([clSeq.loc["S", 5], clSeq.loc["T", 5], clSeq.loc["Y", 5]])
        for p_site in ["S", "T", "Y"]:
            pssm.loc[p_site, 5] = np.log2(clSeq.loc[p_site, 5] / tm)

        pssms.append(np.clip(pssm, a_min=0, a_max=3))
        pssm_names.append(ii)

    pssm_names, pssms = np.array(pssm_names), np.array(pssms)

    if clusters is not None:
        return pssms[
            [np.where(pssm_names == cluster)[0][0] for cluster in clusters]
        ]

    return pssm_names, pssms

has_empty_clusters

has_empty_clusters() -> bool

Checks whether the most recent call to fit() resulted in empty clusters.

Returns:

Type Description
bool

True if any of the n_components clusters has no peptides

bool

assigned to it.

Source code in ddmc/clustering.py
872
873
874
875
876
877
878
879
880
881
def has_empty_clusters(self) -> bool:
    """
    Checks whether the most recent call to fit() resulted in empty clusters.

    Returns:
        True if any of the `n_components` clusters has no peptides
        assigned to it.
    """
    check_is_fitted(self, ["scores_"])
    return self.get_nonempty_clusters().size != self.n_components

impute

impute(
    mode: Literal["soft", "hard"] = "soft",
    return_var: Literal[False] = False,
) -> pd.DataFrame
impute(
    mode: Literal["soft", "hard"] = "soft",
    *,
    return_var: Literal[True],
) -> tuple[pd.DataFrame, pd.DataFrame]
impute(
    mode: Literal["soft", "hard"] = "soft",
    return_var: bool = False,
) -> pd.DataFrame | tuple[pd.DataFrame, pd.DataFrame]

Imputes missing values in the dataset passed in fit() and returns the imputed dataset (and optionally posterior predictive variances).

Parameters:

Name Type Description Default
mode Literal['soft', 'hard']

Imputation strategy for missing entries: - "soft" (default): Posterior expectation sum_c gamma_{ic} * mu_{cj} weighted by each peptide's cluster responsibilities self.scores_. - "hard": Assigned cluster center mu_{c*, j} where c* = argmax_c gamma_{ic}.

'soft'
return_var bool

If True, also return a DataFrame of the same shape containing the posterior predictive variance for each entry (0.0 for observed entries).

False

Returns:

Type Description
DataFrame | tuple[DataFrame, DataFrame]

The imputed p_signal DataFrame, or (imputed_df, variance_df)

DataFrame | tuple[DataFrame, DataFrame]

when return_var=True.

Source code in ddmc/clustering.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
def impute(
    self,
    mode: Literal["soft", "hard"] = "soft",
    return_var: bool = False,
) -> pd.DataFrame | tuple[pd.DataFrame, pd.DataFrame]:
    """
    Imputes missing values in the dataset passed in fit() and returns the
    imputed dataset (and optionally posterior predictive variances).

    Args:
        mode: Imputation strategy for missing entries:
            - `"soft"` (default): Posterior expectation
              `sum_c gamma_{ic} * mu_{cj}` weighted by each peptide's
              cluster responsibilities `self.scores_`.
            - `"hard"`: Assigned cluster center `mu_{c*, j}` where
              `c* = argmax_c gamma_{ic}`.
        return_var: If `True`, also return a DataFrame of the same shape
            containing the posterior predictive variance for each entry
            (`0.0` for observed entries).

    Returns:
        The imputed `p_signal` DataFrame, or `(imputed_df, variance_df)`
        when `return_var=True`.
    """
    check_is_fitted(self, ["means_", "covariances_", "scores_"])
    assert self.means_ is not None and self.covariances_ is not None
    if mode not in ("soft", "hard"):
        raise ValueError(
            f"Unknown imputation mode {mode!r}; expected 'soft' or 'hard'."
        )

    values = self.p_signal.to_numpy(dtype=np.float64, copy=True)
    missing_mask = np.isnan(values)

    if mode == "soft":
        expected = self.scores_ @ self.means_
        values[missing_mask] = expected[missing_mask]
        if return_var:
            second_moment = self.scores_ @ (
                self.covariances_ + self.means_ * self.means_
            )
            post_var = np.maximum(second_moment - expected * expected, 0.0)
    else:
        labels = self.labels()
        expected = self.means_[labels]
        values[missing_mask] = expected[missing_mask]
        if return_var:
            post_var = self.covariances_[labels]

    assert np.all(np.isfinite(values))
    imputed_df = pd.DataFrame(
        values, index=self.p_signal.index, columns=self.p_signal.columns
    )
    if not return_var:
        return imputed_df

    var_values = np.zeros_like(values)
    var_values[missing_mask] = post_var[missing_mask]
    var_df = pd.DataFrame(
        var_values, index=self.p_signal.index, columns=self.p_signal.columns
    )
    return imputed_df, var_df

labels

labels() -> np.ndarray

Find cluster assignment with highest likelihood for each peptide.

Returns:

Type Description
ndarray

Array of shape (n_peptides,) giving each peptide's cluster

ndarray

index. Equivalent to predict().

Source code in ddmc/clustering.py
990
991
992
993
994
995
996
997
def labels(self) -> np.ndarray:
    """Find cluster assignment with highest likelihood for each peptide.

    Returns:
        Array of shape (n_peptides,) giving each peptide's cluster
        index. Equivalent to `predict()`.
    """
    return self.predict()

predict

predict() -> np.ndarray

Provided the current model parameters, predict the cluster each peptide belongs to.

Returns:

Type Description
ndarray

Array of shape (n_peptides,) giving the index of the

ndarray

highest-likelihood cluster for each peptide in self.p_signal.

Source code in ddmc/clustering.py
980
981
982
983
984
985
986
987
988
def predict(self) -> np.ndarray:  # ty: ignore[incompatible-method-override]
    """Provided the current model parameters, predict the cluster each peptide belongs to.

    Returns:
        Array of shape (n_peptides,) giving the index of the
        highest-likelihood cluster for each peptide in `self.p_signal`.
    """
    check_is_fitted(self, ["scores_"])
    return np.argmax(self.scores_, axis=1)

predict_upstream_kinases

predict_upstream_kinases(
    PsP_background: bool = True,
    metric: Literal[
        "frobenius", "js", "kl", "cosine", "zscore"
    ] = "frobenius",
) -> pd.DataFrame

Compute matrix-matrix similarity between kinase specificity profiles and cluster PSSMs to identify upstream kinases regulating clusters.

Parameters:

Name Type Description Default
PsP_background bool

Whether or not PhosphoSitePlus should be used for the background amino acid frequency when building each cluster's PSSM (see get_pssms).

True
metric Literal['frobenius', 'js', 'kl', 'cosine', 'zscore']

Distance metric passed to get_pspl_pssm_distances ("frobenius", "js", "kl", "cosine", or "zscore").

'frobenius'

Returns:

Type Description
DataFrame

DataFrame of shape (n_kinases, n_nonempty_clusters) with the

DataFrame

distance between each kinase's specificity profile and each

DataFrame

cluster's PSSM; smaller values indicate a better match.

Source code in ddmc/clustering.py
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def predict_upstream_kinases(
    self,
    PsP_background: bool = True,
    metric: Literal["frobenius", "js", "kl", "cosine", "zscore"] = "frobenius",
) -> pd.DataFrame:
    """Compute matrix-matrix similarity between kinase specificity profiles
    and cluster PSSMs to identify upstream kinases regulating clusters.

    Args:
        PsP_background: Whether or not PhosphoSitePlus should be used
            for the background amino acid frequency when building each
            cluster's PSSM (see `get_pssms`).
        metric: Distance metric passed to `get_pspl_pssm_distances`
            (`"frobenius"`, `"js"`, `"kl"`, `"cosine"`, or `"zscore"`).

    Returns:
        DataFrame of shape (n_kinases, n_nonempty_clusters) with the
        distance between each kinase's specificity profile and each
        cluster's PSSM; smaller values indicate a better match.
    """
    kinases, pspls = get_pspls()
    clusters, pssms = self.get_pssms(PsP_background=PsP_background)
    distances = get_pspl_pssm_distances(
        pspls,
        pssms,
        as_df=True,
        pssm_names=clusters,
        kinases=kinases,
        metric=metric,
    )
    return distances

score

score() -> float

Generate score of the fitting.

Returns:

Type Description
float

The lower bound on the log-likelihood of the fitted model

float

(self.lower_bound_, set by GaussianMixture.fit).

Source code in ddmc/clustering.py
 999
1000
1001
1002
1003
1004
1005
1006
1007
def score(self) -> float:  # ty: ignore[incompatible-method-override]
    """Generate score of the fitting.

    Returns:
        The lower bound on the log-likelihood of the fitted model
        (`self.lower_bound_`, set by `GaussianMixture.fit`).
    """
    check_is_fitted(self, ["lower_bound_"])
    return self.lower_bound_

score_held_out

score_held_out(
    p_signal_test: DataFrame,
    train_cols: ndarray | Sequence[int],
    test_cols: ndarray | Sequence[int],
) -> tuple[float, float, int, float, float]

Evaluate bi-cross-validation metrics on held-out entries (I_test, J_test) after folding in p_signal_test using train_cols.

Returns:

Type Description
float

Tuple (ll_sum, sq_err_sum, n_obs, sum_y, sum_y2) aggregated over

float

all observed entries in p_signal_test.iloc[:, test_cols].

Source code in ddmc/clustering.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
def score_held_out(
    self,
    p_signal_test: pd.DataFrame,
    train_cols: np.ndarray | Sequence[int],
    test_cols: np.ndarray | Sequence[int],
) -> tuple[float, float, int, float, float]:
    """Evaluate bi-cross-validation metrics on held-out entries
    `(I_test, J_test)` after folding in `p_signal_test` using `train_cols`.

    Returns:
        Tuple `(ll_sum, sq_err_sum, n_obs, sum_y, sum_y2)` aggregated over
        all observed entries in `p_signal_test.iloc[:, test_cols]`.
    """
    check_is_fitted(self, ["means_", "precisions_cholesky_", "weights_"])
    assert self.means_ is not None and self.precisions_cholesky_ is not None

    gamma = self.fold_in(p_signal_test, cols=train_cols)
    test_idx = np.asarray(test_cols, dtype=int)
    X_te_raw = p_signal_test.to_numpy(dtype=np.float64)[:, test_idx]
    obs_te = ~np.isnan(X_te_raw)
    n_obs = int(np.sum(obs_te))
    if n_obs == 0:
        return 0.0, 0.0, 0, 0.0, 0.0

    X_te_zero = np.where(obs_te, X_te_raw, 0.0)
    log_prob_te = self._diagonal_gaussian_log_prob(
        X_te_zero,
        obs_te.astype(np.float64),
        self.means_[:, test_idx],
        self.precisions_cholesky_[:, test_idx],
    )
    has_obs = np.any(obs_te, axis=1)
    log_gamma = np.log(np.maximum(gamma[has_obs], 1e-300))
    ll_sum = float(np.sum(logsumexp(log_gamma + log_prob_te[has_obs], axis=1)))

    pred = gamma @ self.means_[:, test_idx]
    diff = X_te_raw[obs_te] - pred[obs_te]
    sq_err_sum = float(np.sum(diff * diff))
    y_obs = X_te_raw[obs_te]
    sum_y = float(np.sum(y_obs))
    sum_y2 = float(np.sum(y_obs * y_obs))
    return ll_sum, sq_err_sum, n_obs, sum_y, sum_y2

transform

transform(as_df: Literal[False] = False) -> np.ndarray
transform(as_df: Literal[True]) -> pd.DataFrame
transform(as_df: bool = False) -> np.ndarray | pd.DataFrame

Return cluster centers.

Parameters:

Name Type Description Default
as_df bool

Whether or not the result should be wrapped in a dataframe with labeled axes.

False

Returns:

Type Description
ndarray | DataFrame

The cluster centers, either a np array or pd df of shape (n_samples, n_components).

Source code in ddmc/clustering.py
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def transform(self, as_df: bool = False) -> np.ndarray | pd.DataFrame:
    """
    Return cluster centers.

    Args:
        as_df: Whether or not the result should be wrapped in a dataframe with labeled axes.

    Returns:
        The cluster centers, either a np array or pd df of shape (n_samples, n_components).
    """
    check_is_fitted(self, ["means_"])
    assert self.means_ is not None
    centers = self.means_.T
    if as_df:
        centers = pd.DataFrame(
            centers,
            index=self.p_signal.columns,
            columns=np.arange(self.n_components),
        )
    return centers

get_pspl_pssm_distances

get_pspl_pssm_distances(
    pspls: ndarray,
    pssms: ndarray,
    as_df: Literal[False] = False,
    pssm_names: Sequence | ndarray | None = None,
    kinases: Sequence | ndarray | None = None,
    metric: Literal[
        "frobenius", "js", "kl", "cosine", "zscore"
    ] = "frobenius",
) -> np.ndarray
get_pspl_pssm_distances(
    pspls: ndarray,
    pssms: ndarray,
    as_df: Literal[True],
    pssm_names: Sequence | ndarray | None = None,
    kinases: Sequence | ndarray | None = None,
    metric: Literal[
        "frobenius", "js", "kl", "cosine", "zscore"
    ] = "frobenius",
) -> pd.DataFrame
get_pspl_pssm_distances(
    pspls: ndarray,
    pssms: ndarray,
    as_df: bool = False,
    pssm_names: Sequence | ndarray | None = None,
    kinases: Sequence | ndarray | None = None,
    metric: Literal[
        "frobenius", "js", "kl", "cosine", "zscore"
    ] = "frobenius",
) -> np.ndarray | pd.DataFrame

Computes a distance matrix between PSPLs and PSSMs.

Parameters:

Name Type Description Default
pspls ndarray

kinase specificity profiles of shape (n_kinase, 20, 9)

required
pssms ndarray

position-specific scoring matrices of shape (n_pssms, 20, 11)

required
as_df bool

Whether or not the returned matrix should be returned as a dataframe. Requires pssm_names and kinases.

False
pssm_names Sequence | ndarray | None

list of names for the pssms of shape (n_pssms,)

None
kinases Sequence | ndarray | None

list of names for the pspls of shape (n_kinase,)

None
metric Literal['frobenius', 'js', 'kl', 'cosine', 'zscore']

Distance metric ("frobenius", "js", "kl", "cosine", or "zscore"). Smaller values always indicate a better match.

'frobenius'

Returns:

Type Description
ndarray | DataFrame

Distance matrix of shape (n_kinase, n_pssms).

Source code in ddmc/clustering.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
def get_pspl_pssm_distances(
    pspls: np.ndarray,
    pssms: np.ndarray,
    as_df: bool = False,
    pssm_names: Sequence | np.ndarray | None = None,
    kinases: Sequence | np.ndarray | None = None,
    metric: Literal["frobenius", "js", "kl", "cosine", "zscore"] = "frobenius",
) -> np.ndarray | pd.DataFrame:
    """
    Computes a distance matrix between PSPLs and PSSMs.

    Args:
        pspls: kinase specificity profiles of shape (n_kinase, 20, 9)
        pssms: position-specific scoring matrices of shape (n_pssms, 20, 11)
        as_df: Whether or not the returned matrix should be returned as a
            dataframe. Requires pssm_names and kinases.
        pssm_names: list of names for the pssms of shape (n_pssms,)
        kinases: list of names for the pspls of shape (n_kinase,)
        metric: Distance metric (`"frobenius"`, `"js"`, `"kl"`, `"cosine"`, or
            `"zscore"`). Smaller values always indicate a better match.

    Returns:
        Distance matrix of shape (n_kinase, n_pssms).
    """
    assert pssms.shape[1:3] == (20, 11)
    assert pspls.shape[1:3] == (20, 9)
    pssms_9 = np.delete(pssms, [5, 10], axis=2)

    if metric == "frobenius":
        dists = np.linalg.norm(
            pspls[:, None, :, :] - pssms_9[None, :, :, :], axis=(2, 3)
        )
    elif metric in ("js", "kl"):
        p_raw = np.exp2(np.clip(pspls, -20.0, 20.0))
        q_raw = np.exp2(np.clip(pssms_9, -20.0, 20.0))
        p = np.maximum(p_raw / np.sum(p_raw, axis=1, keepdims=True), 1e-12)
        q = np.maximum(q_raw / np.sum(q_raw, axis=1, keepdims=True), 1e-12)
        p_exp = p[:, None, :, :]
        q_exp = q[None, :, :, :]
        if metric == "kl":
            dists = np.sum(q_exp * np.log2(q_exp / p_exp), axis=2).mean(axis=2)
        else:
            m = 0.5 * (p_exp + q_exp)
            kl_pm = np.sum(p_exp * np.log2(p_exp / m), axis=2)
            kl_qm = np.sum(q_exp * np.log2(q_exp / m), axis=2)
            dists = 0.5 * (kl_pm + kl_qm).mean(axis=2)
    elif metric == "cosine":
        a = pspls.reshape(pspls.shape[0], -1)
        b = pssms_9.reshape(pssms_9.shape[0], -1)
        a_norm = np.maximum(np.linalg.norm(a, axis=1, keepdims=True), 1e-12)
        b_norm = np.maximum(np.linalg.norm(b, axis=1, keepdims=True), 1e-12)
        dists = 1.0 - (a / a_norm) @ (b / b_norm).T
    elif metric == "zscore":
        a = pspls.reshape(pspls.shape[0], -1)
        b = pssms_9.reshape(pssms_9.shape[0], -1)
        sim = a @ b.T
        mean_k = np.mean(sim, axis=0, keepdims=True)
        std_k = np.maximum(np.std(sim, axis=0, keepdims=True), 1e-12)
        dists = -(sim - mean_k) / std_k
    else:
        raise ValueError(f"Unsupported metric: {metric!r}")

    if as_df:
        kinases = list(kinases) if kinases is not None else None
        pssm_names = list(pssm_names) if pssm_names is not None else None
        dists = pd.DataFrame(dists, index=kinases, columns=pssm_names)
    return dists