Skip to content

Index

Copula implementations for dependency modeling.

StandardCopula

Bases: Copula

Gaussian copula with modular covariance estimators.

The copula estimates the correlation matrix for gaussianized data. We support alternative (e.g., regularized) covariance estimators through :class:~scdesigner.covariance.CovarianceEstimator.

Parameters:

Name Type Description Default
formula str or dict

How the copula depends on experimental or biological conditions. Defaults to "~ 1", a single group.

'~ 1'
estimator CovarianceEstimator, str, or None

An estimator, a registered name such as "ledoit_wolf" or "oas", or None for the ordinary sample covariance.

None
top_k int

Model only the top_k most expressed genes jointly. Rest treated as independent. A simple form of regularization.

None

Attributes:

Name Type Description
loader DataLoader

Yields the batches that are used to estimate the covariance.

n_outcomes int

Number of features (genes) modeled.

parameters Dict[str, CovarianceStructure]

Fitted correlation structure per group.

estimators_ Dict[str, CovarianceEstimator]

Fitted estimator per group, kept for diagnostics.

groups list

Group labels, one per column of the "group" design.

n_groups int

Number of groups.

Examples:

>>> from scdesigner.copulas import StandardCopula
>>> from scdesigner.covariance import LedoitWolf
>>>
>>> copula = StandardCopula("~ cell_type", estimator=LedoitWolf())
>>> copula.formula
{'group': '~ cell_type'}
See Also

:class:~scdesigner.covariance.CovarianceEstimator

Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
167
168
169
170
171
172
173
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
class StandardCopula(Copula):
    """
    Gaussian copula with modular covariance estimators.

    The copula estimates the correlation matrix for gaussianized data. We
    support alternative (e.g., regularized) covariance estimators through
    :class:`~scdesigner.covariance.CovarianceEstimator`.

    Parameters
    ----------
    formula : str or dict, optional
        How the copula depends on experimental or biological conditions.
        Defaults to ``"~ 1"``, a single group.
    estimator : CovarianceEstimator, str, or None, optional
        An estimator, a registered name such as ``"ledoit_wolf"`` or ``"oas"``,
        or ``None`` for the ordinary sample covariance.
    top_k : int, optional
        Model only the ``top_k`` most expressed genes jointly. Rest treated as
        independent. A simple form of regularization.

    Attributes
    ----------
    loader : torch.utils.data.DataLoader
        Yields the batches that are used to estimate the covariance.
    n_outcomes : int
        Number of features (genes) modeled.
    parameters : Dict[str, CovarianceStructure]
        Fitted correlation structure per group.
    estimators_ : Dict[str, CovarianceEstimator]
        Fitted estimator per group, kept for diagnostics.
    groups : list
        Group labels, one per column of the ``"group"`` design.
    n_groups : int
        Number of groups.

    Examples
    --------
    >>> from scdesigner.copulas import StandardCopula
    >>> from scdesigner.covariance import LedoitWolf
    >>>
    >>> copula = StandardCopula("~ cell_type", estimator=LedoitWolf())
    >>> copula.formula
    {'group': '~ cell_type'}

    See Also
    --------
    :class:`~scdesigner.covariance.CovarianceEstimator`
    """

    def __init__(
        self,
        formula: Union[str, dict] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
    ):
        formula = standardize_formula(formula, allowed_keys=["group"])
        super().__init__(formula)

        # convert string name to an estimator object
        as_covariance_estimator(estimator)
        self.estimator = estimator
        self.top_k = top_k

        self.groups = None
        self.copula_likelihood = 0
        self.estimators_ = {}

    # ------------------------------------------------------------------
    # setup
    # ------------------------------------------------------------------
    def setup_data(
        self,
        adata: AnnData,
        marginal_formula: Dict[str, str],
        *,
        observation_transform=None,
        **kwargs,
    ):
        """
        Build the loader and the group design.

        Parameters
        ----------
        adata : AnnData
            Cells in rows, features in columns.
        marginal_formula : dict of {str: str}
            Formulas used by the marginal models, we merge it with the copula's.
        observation_transform : SpatialDesign, optional
            Fitted transform that appends spatial columns to ``adata.obs``.
        **kwargs
            Data-loading arguments, such as ``batch_size`` and ``chunk_size``,
            passed to :func:`~scdesigner.data.adata_loader`.
        """
        data_kwargs = _filter_kwargs(kwargs, DEFAULT_ALLOWED_KWARGS["data"])
        super().setup_data(
            adata, marginal_formula, observation_transform=observation_transform, **data_kwargs
        )

        self.groups = self.design.predictor_names["group"]
        self.n_groups = len(self.groups)
        self._group_col = {g: i for i, g in enumerate(self.groups)}

    # ------------------------------------------------------------------
    # fitting
    # ------------------------------------------------------------------
    def fit(self, uniformizer: Callable):
        r"""
        Estimate a correlation matrix for each group.

        The data are first gaussianized using the estimated marginals then we
        stream across batches to estimate the covariance.

        The fit is controlled entirely by the copula's construction: ``estimator``
        and ``top_k`` are set in :meth:`__init__`, and the batching is set in
        :meth:`setup_data`.

        Parameters
        ----------
        uniformizer : callable
            ``uniformizer(y, x_dict) -> np.ndarray`` mapping expression data to
            uniform \([0, 1]\) values.
        """
        prototype = as_covariance_estimator(self.estimator)
        modeled_indices, remaining_indices = self._gene_partitions()

        self.copula_likelihood = 0
        self.estimators_ = self._fit_estimators(prototype, uniformizer, modeled_indices)
        self.parameters = self._build_covariances(modeled_indices, remaining_indices)

    def _gene_partitions(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Split genes into those modeled jointly and those left independent.

        The top_k genes by mean expression, which orders genes as totals do,
        are modeled jointly. The rest are modeled independently.
        """
        top_k = self.top_k
        if top_k is None:
            return np.arange(self.n_outcomes), np.array([], dtype=int)

        means = summarize_features(self.adata, chunk_size=self.chunk_size).mean
        sorted_indices = np.argsort(means)
        return np.sort(sorted_indices[-top_k:]), np.sort(sorted_indices[:-top_k])

    def _fit_estimators(
        self, prototype, uniformizer: Callable, modeled_indices: np.ndarray
    ) -> Dict[Union[str, int], object]:
        """
        Estimate covariance matrices for each group
        """
        n_modeled = len(modeled_indices)
        estimators = {g: prototype.clone() for g in self.groups}
        for estimator in estimators.values():
            estimator.start(n_modeled)

        desc = (
            "Estimating top-k copula correlation"
            if n_modeled < self.n_outcomes
            else "Estimating copula correlation"
        )
        for y, x_dict in tqdm(self.loader, desc=desc):
            memberships = x_dict["group"].cpu().numpy()
            z = np.asarray(norm.ppf(uniformizer(y, x_dict)), dtype=float)

            for g, estimator in estimators.items():
                mask = memberships[:, self._group_col[g]] == 1
                if np.any(mask):
                    estimator.update(z[mask][:, modeled_indices])

        for estimator in estimators.values():
            estimator.finalize()
        return estimators

    def _build_covariances(
        self, modeled_indices: np.ndarray, remaining_indices: np.ndarray
    ) -> Dict[Union[str, int], CovarianceStructure]:
        """Turn each fitted estimate into a correlation structure for sampling."""
        covariances = {}
        has_remainder = len(remaining_indices) > 0
        remaining_var = np.ones(len(remaining_indices)) if has_remainder else None

        for g, estimator in self.estimators_.items():
            corr = covariance_to_correlation(estimator.covariance_)
            corr, factor = factorize_correlation(corr, g, jitter=estimator.regularized)
            self._add_loglikelihood(factor, estimator)
            estimator.release()

            covariances[g] = CovarianceStructure(
                cov=corr,
                modeled_names=self.adata.var_names[modeled_indices],
                modeled_indices=modeled_indices,
                remaining_var=remaining_var,
                remaining_indices=remaining_indices if has_remainder else None,
                remaining_names=(
                    self.adata.var_names[remaining_indices] if has_remainder else None
                ),
            )
        return covariances

    def _add_loglikelihood(self, factor, estimator) -> None:
        """
        Add one group's contribution to the log-likelihood.

        This will update the likelihood for any method that has a non-null
        copula_likelihood and running second_moment calculation. If these aren't
        present, you can run ``complexity(adata=...)`` to recompute it in a
        second pass.
        """
        if self.copula_likelihood is None:
            return

        second_moment = estimator.second_moment_
        if second_moment is None:
            self.copula_likelihood = None
            warnings.warn(
                f"""{type(estimator).__name__} does not return copula likelihoods
                in the first pass. Call complexity(adata=...) to recompute it
                from the data."""
            )
            return

        self.copula_likelihood += group_log_likelihood(
            factor, second_moment, estimator.n_samples_
        )

    # ------------------------------------------------------------------
    # sampling and evaluation
    # ------------------------------------------------------------------
    def _group_indices(self, x_dict: Dict) -> Dict[Union[str, int], np.ndarray]:
        """Row indices belonging to each group, for one batch."""
        memberships = x_dict["group"].cpu().numpy()
        return {
            g: np.where(memberships[:, self._group_col[g]] == 1)[0] for g in self.groups
        }

    def pseudo_obs(self, x_dict: Dict):
        """
        Draw dependent uniform pseudo-observations.

        Parameters
        ----------
        x_dict : dict
            Batch covariates, including the ``"group"`` indicator matrix.

        Returns
        -------
        np.ndarray
            Uniform values, shape ``(n_cells, n_genes)``.
        """
        group_ix = self._group_indices(x_dict)
        n_cells = len(x_dict["group"])

        u = np.zeros((n_cells, self.n_outcomes))
        for group, cov_struct in self.parameters.items():
            indices = group_ix[group]
            if len(indices) > 0:
                u[indices] = sample_pseudo_obs(len(indices), cov_struct)
        return u

    def likelihood(self, uniformizer: Callable, batch):
        """
        Per-cell copula log-likelihood for one batch.

        Parameters
        ----------
        uniformizer : callable
            Maps expression data to uniform values.
        batch : tuple of (torch.Tensor, dict)
            Expression tensor and covariates, as yielded by the loader.

        Returns
        -------
        np.ndarray
            Log-likelihood per cell.
        """
        y, x_dict = batch
        z = norm.ppf(uniformizer(y, x_dict))
        group_ix = self._group_indices(x_dict)

        ll = np.zeros(len(z))
        for group, cov_struct in self.parameters.items():
            indices = group_ix[group]
            if len(indices) > 0:
                ll[indices] = batch_log_likelihood(z[indices], cov_struct)
        return ll

    def num_params(self, **kwargs):
        """
        Number of correlation parameters, summed over groups.
        """
        return int(
            sum(
                estimator.num_params(estimator.n_features_)
                for estimator in self.estimators_.values()
                if estimator.n_samples_ > 0
            )
        )

    @property
    def diagnostics(self) -> Dict:
        """Per-group estimator diagnostics, such as the fitted shrinkage intensity."""
        return {g: e.diagnostics() for g, e in self.estimators_.items()}

diagnostics property

Per-group estimator diagnostics, such as the fitted shrinkage intensity.

fit(uniformizer)

Estimate a correlation matrix for each group.

The data are first gaussianized using the estimated marginals then we stream across batches to estimate the covariance.

The fit is controlled entirely by the copula's construction: estimator and top_k are set in :meth:__init__, and the batching is set in :meth:setup_data.

Parameters:

Name Type Description Default
uniformizer callable

uniformizer(y, x_dict) -> np.ndarray mapping expression data to uniform ([0, 1]) values.

required
Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def fit(self, uniformizer: Callable):
    r"""
    Estimate a correlation matrix for each group.

    The data are first gaussianized using the estimated marginals then we
    stream across batches to estimate the covariance.

    The fit is controlled entirely by the copula's construction: ``estimator``
    and ``top_k`` are set in :meth:`__init__`, and the batching is set in
    :meth:`setup_data`.

    Parameters
    ----------
    uniformizer : callable
        ``uniformizer(y, x_dict) -> np.ndarray`` mapping expression data to
        uniform \([0, 1]\) values.
    """
    prototype = as_covariance_estimator(self.estimator)
    modeled_indices, remaining_indices = self._gene_partitions()

    self.copula_likelihood = 0
    self.estimators_ = self._fit_estimators(prototype, uniformizer, modeled_indices)
    self.parameters = self._build_covariances(modeled_indices, remaining_indices)

likelihood(uniformizer, batch)

Per-cell copula log-likelihood for one batch.

Parameters:

Name Type Description Default
uniformizer callable

Maps expression data to uniform values.

required
batch tuple of (torch.Tensor, dict)

Expression tensor and covariates, as yielded by the loader.

required

Returns:

Type Description
ndarray

Log-likelihood per cell.

Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def likelihood(self, uniformizer: Callable, batch):
    """
    Per-cell copula log-likelihood for one batch.

    Parameters
    ----------
    uniformizer : callable
        Maps expression data to uniform values.
    batch : tuple of (torch.Tensor, dict)
        Expression tensor and covariates, as yielded by the loader.

    Returns
    -------
    np.ndarray
        Log-likelihood per cell.
    """
    y, x_dict = batch
    z = norm.ppf(uniformizer(y, x_dict))
    group_ix = self._group_indices(x_dict)

    ll = np.zeros(len(z))
    for group, cov_struct in self.parameters.items():
        indices = group_ix[group]
        if len(indices) > 0:
            ll[indices] = batch_log_likelihood(z[indices], cov_struct)
    return ll

num_params(**kwargs)

Number of correlation parameters, summed over groups.

Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
307
308
309
310
311
312
313
314
315
316
317
def num_params(self, **kwargs):
    """
    Number of correlation parameters, summed over groups.
    """
    return int(
        sum(
            estimator.num_params(estimator.n_features_)
            for estimator in self.estimators_.values()
            if estimator.n_samples_ > 0
        )
    )

pseudo_obs(x_dict)

Draw dependent uniform pseudo-observations.

Parameters:

Name Type Description Default
x_dict dict

Batch covariates, including the "group" indicator matrix.

required

Returns:

Type Description
ndarray

Uniform values, shape (n_cells, n_genes).

Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def pseudo_obs(self, x_dict: Dict):
    """
    Draw dependent uniform pseudo-observations.

    Parameters
    ----------
    x_dict : dict
        Batch covariates, including the ``"group"`` indicator matrix.

    Returns
    -------
    np.ndarray
        Uniform values, shape ``(n_cells, n_genes)``.
    """
    group_ix = self._group_indices(x_dict)
    n_cells = len(x_dict["group"])

    u = np.zeros((n_cells, self.n_outcomes))
    for group, cov_struct in self.parameters.items():
        indices = group_ix[group]
        if len(indices) > 0:
            u[indices] = sample_pseudo_obs(len(indices), cov_struct)
    return u

setup_data(adata, marginal_formula, *, observation_transform=None, **kwargs)

Build the loader and the group design.

Parameters:

Name Type Description Default
adata AnnData

Cells in rows, features in columns.

required
marginal_formula dict of {str: str}

Formulas used by the marginal models, we merge it with the copula's.

required
observation_transform SpatialDesign

Fitted transform that appends spatial columns to adata.obs.

None
**kwargs

Data-loading arguments, such as batch_size and chunk_size, passed to :func:~scdesigner.data.adata_loader.

{}
Source code in scdesigner/src/scdesigner/copulas/standard_copula.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def setup_data(
    self,
    adata: AnnData,
    marginal_formula: Dict[str, str],
    *,
    observation_transform=None,
    **kwargs,
):
    """
    Build the loader and the group design.

    Parameters
    ----------
    adata : AnnData
        Cells in rows, features in columns.
    marginal_formula : dict of {str: str}
        Formulas used by the marginal models, we merge it with the copula's.
    observation_transform : SpatialDesign, optional
        Fitted transform that appends spatial columns to ``adata.obs``.
    **kwargs
        Data-loading arguments, such as ``batch_size`` and ``chunk_size``,
        passed to :func:`~scdesigner.data.adata_loader`.
    """
    data_kwargs = _filter_kwargs(kwargs, DEFAULT_ALLOWED_KWARGS["data"])
    super().setup_data(
        adata, marginal_formula, observation_transform=observation_transform, **data_kwargs
    )

    self.groups = self.design.predictor_names["group"]
    self.n_groups = len(self.groups)
    self._group_col = {g: i for i, g in enumerate(self.groups)}