Skip to content

Index

Simulator classes

BernoulliCopula

Bases: SCD3Simulator

Simulator using Bernoulli marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the Bernoulli marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:Bernoulli :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
class BernoulliCopula(SCD3Simulator):
    """Simulator using Bernoulli marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the Bernoulli marginal
        (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a default
        constant-mean formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`Bernoulli`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = Bernoulli({"mean": mean_formula}, device=device)
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

CompositeCopula

Bases: SCD3Simulator

Composite simulator: multiple marginals + a shared Gaussian copula.

The composite simulator fits each marginal model independently on a (potentially different) subset of variables, and then fits a Gaussian copula on the merged uniformized outputs from all marginals to capture cross-feature dependence.

Each marginal is provided as a pair (sel, marginal) where:

  • sel selects which variables in adata the marginal is responsible for (e.g. a list of gene names, a single gene name).
  • marginal is an object implementing the marginal simulator interface

Parameters:

Name Type Description Default
marginals list

List of (sel, marginal) pairs.

required
copula_formula str

Formula passed to :class:~scdesigner.copulas.StandardCopula to determine copula grouping structure (e.g. "group ~ 1"). If None, uses the copula's default.

None

Attributes:

Name Type Description
marginals list

The provided marginal specifications.

copula StandardCopula

The fitted copula component.

template AnnData or None

Training dataset (set during :meth:fit).

parameters dict or None

Fitted parameters, with keys "marginal" and "copula".

merged_formula dict or None

Merged (prefixed) formula dictionary used to construct the copula data loader.

Examples:

Fit two marginal models on disjoint gene sets and then fit a copula:

>>> import numpy as np
>>> import pandas as pd
>>> from anndata import AnnData
>>> from scdesigner.simulators import CompositeCopula
>>> from scdesigner.distributions import NegBin, Poisson
>>>
>>> X = np.random.poisson(1.0, size=(100, 10)).astype(float)
>>> obs = pd.DataFrame({"cell_type": np.random.choice(["A", "B"], size=100)})
>>> adata = AnnData(X=X, obs=obs)
>>> adata.var_names = [f"g{i}" for i in range(adata.n_vars)]
>>>
>>> # Example selectors: first 5 genes vs last 5 genes
>>> sel1 = adata.var_names[:5].tolist()
>>> sel2 = adata.var_names[5:].tolist()
>>> m1 = NegBin(formula={"mean": "~ cell_type", "dispersion": "~ 1"})
>>> m2 = Poisson(formula={"mean": "~ cell_type"})
>>>
>>> composite = CompositeCopula([(sel1, m1), (sel2, m2)])
>>> composite.fit(adata, batch_size=256, verbose=False)
>>> params = composite.predict(adata.obs.iloc[:3], batch_size=3)
Source code in scdesigner/src/scdesigner/simulators/composite.py
 16
 17
 18
 19
 20
 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
class CompositeCopula(SCD3Simulator):
    """
    Composite simulator: multiple marginals + a shared Gaussian copula.

    The composite simulator fits each marginal model independently on a
    (potentially different) subset of variables, and then fits a Gaussian
    copula on the *merged* uniformized outputs from all marginals to capture
    cross-feature dependence.

    Each marginal is provided as a pair ``(sel, marginal)`` where:

    - ``sel`` selects which variables in ``adata`` the marginal is responsible
      for (e.g. a list of gene names, a single gene name).
    - ``marginal`` is an object implementing the marginal simulator interface

    Parameters
    ----------
    marginals : list
        List of ``(sel, marginal)`` pairs.
    copula_formula : str, optional
        Formula passed to :class:`~scdesigner.copulas.StandardCopula`
        to determine copula grouping structure (e.g. ``"group ~ 1"``). If
        ``None``, uses the copula's default.

    Attributes
    ----------
    marginals : list
        The provided marginal specifications.
    copula : StandardCopula
        The fitted copula component.
    template : AnnData or None
        Training dataset (set during :meth:`fit`).
    parameters : dict or None
        Fitted parameters, with keys ``"marginal"`` and ``"copula"``.
    merged_formula : dict or None
        Merged (prefixed) formula dictionary used to construct the copula data loader.

    Examples
    --------
    Fit two marginal models on disjoint gene sets and then fit a copula:

    >>> import numpy as np
    >>> import pandas as pd
    >>> from anndata import AnnData
    >>> from scdesigner.simulators import CompositeCopula
    >>> from scdesigner.distributions import NegBin, Poisson
    >>>
    >>> X = np.random.poisson(1.0, size=(100, 10)).astype(float)
    >>> obs = pd.DataFrame({"cell_type": np.random.choice(["A", "B"], size=100)})
    >>> adata = AnnData(X=X, obs=obs)
    >>> adata.var_names = [f"g{i}" for i in range(adata.n_vars)]
    >>>
    >>> # Example selectors: first 5 genes vs last 5 genes
    >>> sel1 = adata.var_names[:5].tolist()
    >>> sel2 = adata.var_names[5:].tolist()
    >>> m1 = NegBin(formula={"mean": "~ cell_type", "dispersion": "~ 1"})
    >>> m2 = Poisson(formula={"mean": "~ cell_type"})
    >>>
    >>> composite = CompositeCopula([(sel1, m1), (sel2, m2)])
    >>> composite.fit(adata, batch_size=256, verbose=False)
    >>> params = composite.predict(adata.obs.iloc[:3], batch_size=3)
    """
    def __init__(self, marginals: List,
                 copula_formula: Optional[str] = None,
                 estimator=None,
                 top_k: Optional[int] = None) -> None:
        """Create a composite simulator.

        Parameters
        ----------
        marginals : list
            List of ``(sel, marginal)`` pairs. See class docstring for details.
        copula_formula : str, optional
            Copula grouping formula passed to :class:`StandardCopula`.
        estimator : CovarianceEstimator, str, or None, optional
            Covariance estimator for the copula. See :class:`StandardCopula`.
        top_k : int, optional
            Model only the ``top_k`` most expressed genes jointly.
        """
        self.marginals = marginals
        self.copula = StandardCopula(
            copula_formula if copula_formula is not None else "~ 1",
            estimator=estimator,
            top_k=top_k,
        )
        self.template = None
        self.parameters = None
        self.merged_formula = None

    def _loader_kwargs(self, kwargs: dict) -> dict:
        """Build loader options from the shared component device."""
        return {**kwargs, "device": self.marginals[0][1].device}

    def to(self, device):
        """Move each component model to the ``device``."""
        for _, marginal in self.marginals:
            marginal.to(device)
        self.copula.to(device)
        return self

    def fit(
        self,
        adata: AnnData,
        verbose: bool = True,
        val_frac: float = 0.1,
        min_epochs: int = 10,
        loss_tol: float = 1e-4,
        patience: int = 40,
        validation_seed: int = 0,
        **kwargs,):
        """Fit all marginals and then fit the copula on merged uniforms.

        Parameters
        ----------
        adata : AnnData
            Training dataset.
        verbose : bool, optional
            Whether to print verbose output.
        val_frac : float
            Fraction of observations held out for each marginal validation
            split. Set to 0 to disable early stopping.
        min_epochs : int
            Minimum number of marginal epochs before early stopping is allowed.
        loss_tol : float
            Required relative validation-loss decrease to reset patience.
        patience : int
            Number of non-improving validation epochs allowed after warmup.
        validation_seed : int
            Seed controlling deterministic marginal validation splits.
        **kwargs
            Additional keyword arguments forwarded to marginal setup/fit methods
            and to the copula's ``setup_data`` call (e.g. ``batch_size``).
            Copula settings like ``estimator`` and ``top_k`` are given when the
            simulator is constructed, not here.
        """
        kwargs = self._loader_kwargs(kwargs)
        self.template = adata
        merged_formula = {}

        # fit each marginal model
        for m in range(len(self.marginals)):
            marginal = self.marginals[m][1]
            marginal.setup_data(adata[:, self.marginals[m][0]], **kwargs)
            marginal.fit(
                **kwargs,
                verbose=verbose,
                val_frac=val_frac,
                min_epochs=min_epochs,
                loss_tol=loss_tol,
                patience=patience,
                validation_seed=validation_seed,
            )

            # prepare formula for copula loader
            f = marginal.formula
            prefixed_f = {f"group{m}_{k}": v for k, v in f.items()}
            merged_formula = merged_formula | prefixed_f

        # copula simulator
        self.merged_formula = merged_formula
        self.copula.setup_data(adata, merged_formula, **kwargs)
        self.copula.fit(self.merged_uniformize)
        self.parameters = {
            "marginal": [m[1].parameters for m in self.marginals],
            "copula": self.copula.parameters
        }

    def merged_uniformize(self, y: torch.Tensor, x: Dict[str, torch.Tensor]) -> torch.Tensor:
        """Produce a merged uniformized matrix for all marginals.

        Delegates to each marginal's `uniformize` method and places the
        result into the columns of a full matrix according to the variable
        selection given in `self.marginals[m][0]`.
        """
        y_np = y.detach().cpu().numpy()
        u = np.empty_like(y_np, dtype=float)

        for m in range(len(self.marginals)):
            sel = self.marginals[m][0]
            ix = _var_indices(sel, self.template)

            # remove the `group{m}_` prefix we used to distinguish the marginals
            prefix = f"group{m}_"
            cur_x = {k.removeprefix(prefix): v if k.startswith(prefix) else v for k, v in x.items()}

            # slice the subset of y for this marginal and call its uniformize
            y_sub = torch.from_numpy(y_np[:, ix])
            u[:, ix] = self.marginals[m][1].uniformize(y_sub, cur_x)
        return torch.from_numpy(u)

    def predict(self, obs=None, batch_size: int = 1000, **kwargs):
        """Predict marginal parameters for observations (batched).

        This method constructs an internal loader for ``obs`` from the copula's
        fitted design over the merged (prefixed) formulas, then dispatches
        per-marginal ``predict`` calls on each batch after stripping the
        prefixes.

        Parameters
        ----------
        obs : pandas.DataFrame, optional
            Observation metadata. Defaults to ``self.template.obs``.
        batch_size : int, optional
            Batch size for the internal observation loader.
        **kwargs
            Forwarded to :func:`~scdesigner.data.loader.obs_loader`.

        Returns
        -------
        list[dict[str, np.ndarray]]
            List with one element per marginal. Each element is a dict mapping
            parameter names to numpy arrays, concatenated across batches.
        """
        # prepare an internal data loader for this obs
        kwargs = self._loader_kwargs(kwargs)
        if obs is None:
            obs = self.template.obs
        loader = obs_loader(obs, self.copula.design, batch_size=batch_size, **kwargs)

        # prepare per-marginal collectors
        n_marginals = len(self.marginals)
        local_pred = [[] for _ in range(n_marginals)]

        # for each batch, call each marginal's predict on its subset of x
        for _, x_dict in loader:
            for m in range(n_marginals):
                prefix = f"group{m}_"
                # build cur_x where prefixed keys are unprefixed for the marginal
                cur_x = {k.removeprefix(prefix): v for k, v in x_dict.items()}
                params = self.marginals[m][1].predict(cur_x)
                local_pred[m].append(params)

        # merge batch-wise parameter dicts for each marginal and return
        results = []
        for m in range(n_marginals):
            parts = local_pred[m]
            keys = list(parts[0].keys())
            results.append({k: torch.cat([d[k] for d in parts]).detach().cpu().numpy() for k in keys})

        return results

__init__(marginals, copula_formula=None, estimator=None, top_k=None)

Create a composite simulator.

Parameters:

Name Type Description Default
marginals list

List of (sel, marginal) pairs. See class docstring for details.

required
copula_formula str

Copula grouping formula passed to :class:StandardCopula.

None
estimator CovarianceEstimator, str, or None

Covariance estimator for the copula. See :class:StandardCopula.

None
top_k int

Model only the top_k most expressed genes jointly.

None
Source code in scdesigner/src/scdesigner/simulators/composite.py
 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, marginals: List,
             copula_formula: Optional[str] = None,
             estimator=None,
             top_k: Optional[int] = None) -> None:
    """Create a composite simulator.

    Parameters
    ----------
    marginals : list
        List of ``(sel, marginal)`` pairs. See class docstring for details.
    copula_formula : str, optional
        Copula grouping formula passed to :class:`StandardCopula`.
    estimator : CovarianceEstimator, str, or None, optional
        Covariance estimator for the copula. See :class:`StandardCopula`.
    top_k : int, optional
        Model only the ``top_k`` most expressed genes jointly.
    """
    self.marginals = marginals
    self.copula = StandardCopula(
        copula_formula if copula_formula is not None else "~ 1",
        estimator=estimator,
        top_k=top_k,
    )
    self.template = None
    self.parameters = None
    self.merged_formula = None

fit(adata, verbose=True, val_frac=0.1, min_epochs=10, loss_tol=0.0001, patience=40, validation_seed=0, **kwargs)

Fit all marginals and then fit the copula on merged uniforms.

Parameters:

Name Type Description Default
adata AnnData

Training dataset.

required
verbose bool

Whether to print verbose output.

True
val_frac float

Fraction of observations held out for each marginal validation split. Set to 0 to disable early stopping.

0.1
min_epochs int

Minimum number of marginal epochs before early stopping is allowed.

10
loss_tol float

Required relative validation-loss decrease to reset patience.

0.0001
patience int

Number of non-improving validation epochs allowed after warmup.

40
validation_seed int

Seed controlling deterministic marginal validation splits.

0
**kwargs

Additional keyword arguments forwarded to marginal setup/fit methods and to the copula's setup_data call (e.g. batch_size). Copula settings like estimator and top_k are given when the simulator is constructed, not here.

{}
Source code in scdesigner/src/scdesigner/simulators/composite.py
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
def fit(
    self,
    adata: AnnData,
    verbose: bool = True,
    val_frac: float = 0.1,
    min_epochs: int = 10,
    loss_tol: float = 1e-4,
    patience: int = 40,
    validation_seed: int = 0,
    **kwargs,):
    """Fit all marginals and then fit the copula on merged uniforms.

    Parameters
    ----------
    adata : AnnData
        Training dataset.
    verbose : bool, optional
        Whether to print verbose output.
    val_frac : float
        Fraction of observations held out for each marginal validation
        split. Set to 0 to disable early stopping.
    min_epochs : int
        Minimum number of marginal epochs before early stopping is allowed.
    loss_tol : float
        Required relative validation-loss decrease to reset patience.
    patience : int
        Number of non-improving validation epochs allowed after warmup.
    validation_seed : int
        Seed controlling deterministic marginal validation splits.
    **kwargs
        Additional keyword arguments forwarded to marginal setup/fit methods
        and to the copula's ``setup_data`` call (e.g. ``batch_size``).
        Copula settings like ``estimator`` and ``top_k`` are given when the
        simulator is constructed, not here.
    """
    kwargs = self._loader_kwargs(kwargs)
    self.template = adata
    merged_formula = {}

    # fit each marginal model
    for m in range(len(self.marginals)):
        marginal = self.marginals[m][1]
        marginal.setup_data(adata[:, self.marginals[m][0]], **kwargs)
        marginal.fit(
            **kwargs,
            verbose=verbose,
            val_frac=val_frac,
            min_epochs=min_epochs,
            loss_tol=loss_tol,
            patience=patience,
            validation_seed=validation_seed,
        )

        # prepare formula for copula loader
        f = marginal.formula
        prefixed_f = {f"group{m}_{k}": v for k, v in f.items()}
        merged_formula = merged_formula | prefixed_f

    # copula simulator
    self.merged_formula = merged_formula
    self.copula.setup_data(adata, merged_formula, **kwargs)
    self.copula.fit(self.merged_uniformize)
    self.parameters = {
        "marginal": [m[1].parameters for m in self.marginals],
        "copula": self.copula.parameters
    }

merged_uniformize(y, x)

Produce a merged uniformized matrix for all marginals.

Delegates to each marginal's uniformize method and places the result into the columns of a full matrix according to the variable selection given in self.marginals[m][0].

Source code in scdesigner/src/scdesigner/simulators/composite.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def merged_uniformize(self, y: torch.Tensor, x: Dict[str, torch.Tensor]) -> torch.Tensor:
    """Produce a merged uniformized matrix for all marginals.

    Delegates to each marginal's `uniformize` method and places the
    result into the columns of a full matrix according to the variable
    selection given in `self.marginals[m][0]`.
    """
    y_np = y.detach().cpu().numpy()
    u = np.empty_like(y_np, dtype=float)

    for m in range(len(self.marginals)):
        sel = self.marginals[m][0]
        ix = _var_indices(sel, self.template)

        # remove the `group{m}_` prefix we used to distinguish the marginals
        prefix = f"group{m}_"
        cur_x = {k.removeprefix(prefix): v if k.startswith(prefix) else v for k, v in x.items()}

        # slice the subset of y for this marginal and call its uniformize
        y_sub = torch.from_numpy(y_np[:, ix])
        u[:, ix] = self.marginals[m][1].uniformize(y_sub, cur_x)
    return torch.from_numpy(u)

predict(obs=None, batch_size=1000, **kwargs)

Predict marginal parameters for observations (batched).

This method constructs an internal loader for obs from the copula's fitted design over the merged (prefixed) formulas, then dispatches per-marginal predict calls on each batch after stripping the prefixes.

Parameters:

Name Type Description Default
obs DataFrame

Observation metadata. Defaults to self.template.obs.

None
batch_size int

Batch size for the internal observation loader.

1000
**kwargs

Forwarded to :func:~scdesigner.data.loader.obs_loader.

{}

Returns:

Type Description
list[dict[str, ndarray]]

List with one element per marginal. Each element is a dict mapping parameter names to numpy arrays, concatenated across batches.

Source code in scdesigner/src/scdesigner/simulators/composite.py
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
def predict(self, obs=None, batch_size: int = 1000, **kwargs):
    """Predict marginal parameters for observations (batched).

    This method constructs an internal loader for ``obs`` from the copula's
    fitted design over the merged (prefixed) formulas, then dispatches
    per-marginal ``predict`` calls on each batch after stripping the
    prefixes.

    Parameters
    ----------
    obs : pandas.DataFrame, optional
        Observation metadata. Defaults to ``self.template.obs``.
    batch_size : int, optional
        Batch size for the internal observation loader.
    **kwargs
        Forwarded to :func:`~scdesigner.data.loader.obs_loader`.

    Returns
    -------
    list[dict[str, np.ndarray]]
        List with one element per marginal. Each element is a dict mapping
        parameter names to numpy arrays, concatenated across batches.
    """
    # prepare an internal data loader for this obs
    kwargs = self._loader_kwargs(kwargs)
    if obs is None:
        obs = self.template.obs
    loader = obs_loader(obs, self.copula.design, batch_size=batch_size, **kwargs)

    # prepare per-marginal collectors
    n_marginals = len(self.marginals)
    local_pred = [[] for _ in range(n_marginals)]

    # for each batch, call each marginal's predict on its subset of x
    for _, x_dict in loader:
        for m in range(n_marginals):
            prefix = f"group{m}_"
            # build cur_x where prefixed keys are unprefixed for the marginal
            cur_x = {k.removeprefix(prefix): v for k, v in x_dict.items()}
            params = self.marginals[m][1].predict(cur_x)
            local_pred[m].append(params)

    # merge batch-wise parameter dicts for each marginal and return
    results = []
    for m in range(n_marginals):
        parts = local_pred[m]
        keys = list(parts[0].keys())
        results.append({k: torch.cat([d[k] for d in parts]).detach().cpu().numpy() for k in keys})

    return results

to(device)

Move each component model to the device.

Source code in scdesigner/src/scdesigner/simulators/composite.py
109
110
111
112
113
114
def to(self, device):
    """Move each component model to the ``device``."""
    for _, marginal in self.marginals:
        marginal.to(device)
    self.copula.to(device)
    return self

GaussianCopula

Bases: SCD3Simulator

Simulator using Gaussian marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the Gaussian marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
sdev_formula str or None

Model formula for the standard deviation parameter of the Gaussian marginal. If None, a default constant-standard deviation formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:Gaussian :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
class GaussianCopula(SCD3Simulator):
    """Simulator using Gaussian marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the Gaussian marginal
        (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a default
        constant-mean formula is used.
    sdev_formula : str or None, optional
        Model formula for the standard deviation parameter of the Gaussian marginal.
        If ``None``, a default constant-standard deviation formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`Gaussian`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        sdev_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = Gaussian({"mean": mean_formula, "sdev": sdev_formula}, device=device)
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

NegBinCopula

Bases: SCD3Simulator

Simulator using negative binomial marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the negative binomial marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
dispersion_formula str or None

Model formula for the dispersion parameter of the negative binomial marginal. If None, a default constant-dispersion formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group").If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:NegBin :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
class NegBinCopula(SCD3Simulator):
    """Simulator using negative binomial marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the negative binomial
        marginal (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a
        default constant-mean formula is used.
    dispersion_formula : str or None, optional
        Model formula for the dispersion parameter of the negative
        binomial marginal. If ``None``, a default constant-dispersion
        formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental
        or biological conditions (e.g. ``"~ group"``).If ``None``,
        a default intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`NegBin`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        dispersion_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = NegBin(
            {"mean": mean_formula, "dispersion": dispersion_formula}, device=device
        )
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

NegBinEQTLCopula

Bases: SCD3Simulator

NB simulator for single-cell eQTL data

eQTL data present a challenge for our usual negative binomial copula simulators. Since every gene is regulated by its own set of SNPs, we can no longer rely on sharing the same design matrix across all response genes. Further, since gene expression profiles tend to vary from individual to individual, it is important to include some sort of patient-level (random) intercept.

Our approach is as follows. For cell :math:i, gene :math:j, and donor :math:k(i), fit the marginal model,

.. math:: Y_{ij}\mid u_{k(i),j} \sim \operatorname{NB}(\mu_{ij}, r_{ij}),\qquad \operatorname{Var}(Y_{ij}\mid u)=\mu_{ij}+\mu_{ij}^2/r_{ij},

\log\mu_{ij} = W_i^ op heta_j + u_{k(i),j} + \sum_m D_{k(i),jm} \left(eta_{jm}+V_i^ op\zeta_{jm} ight),\qquad \log r_{ij}=Z_i^ op\psi_j,\quad u_{kj}\sim N(0,\sigma_j^2).

:math:W_i and :math:Z_i are cell-level design matrices shared across all genes and :math:D is a :math:D \in R^{K x J x M} is a donor x gene x maximum number of SNPs per gene matrix storing the "dosage" (0, 1, 2) of the variant in the gene for that donor. Notice that M indexes different SNPs for each gene, The specific mapping is stored in snp_map. :math:zeta It allows for interaction between the genotype and cell-level features like cell type. The matrix U stores a donor-level intercept.

The coefficients and the donor-level intercepts are estimated using a ridge regularized negative binomial likelihood. The variance of the random effects u is updated after each epoch using the posterior moments described in donor_moments.py.

Once this marginal model is estimated, the copula proceeds as usual.

Parameters:

Name Type Description Default
mean_formula str

lme4-style formula for :math:\log\mu. It must include a genotype term, which denotes that gene's SNP dosages (see dosage and snp_map). It must also have a donor-level random intercept (1 | donor), where donor is a column of adata.obs. Any other terms define :math:W_i. Interactions with genotype, like genotype:X, define :math:V_i. For example, ~ genotype * cell_type + (1 | donor) gives cell-type-specific eQTLs and ~ genotype * bs(pseudotime, df=5) + (1 | donor) gives dynamic eQTLs.

required
dispersion_formula str

An analog of the mean formula, but for the dispersion. It can have fixed effects but not genotype or donor-level random effects. By default it is constant across all cells.

'~ 1'
copula_formula str

Groups to divide the copula estimation in two

'~ 1'
dosage DataFrame

A donor-by-SNP table giving the genotypes {0, 1, 2} of each individual

required
snp_map dict[str, list[str]]

Gene name -> SNP columns regulating that gene

required
**marginal_kwargs

Additional keyword arguments that are passed to NegBinEQTL

{}
See Also

:class:SCD3Simulator :class:NegBinEQTL :class:StandardCopula

Examples:

>>> from scdesigner import datasets
>>> from scdesigner.simulators import NegBinEQTLCopula
>>>
>>> adata = datasets.dong_eqtl()
>>> snp_map = {gene: [snp] for gene, snp in adata.var["snp"].items()}
>>> sim = NegBinEQTLCopula(
...     "~ genotype * cell_type + (1 | indiv)",
...     dosage=adata.uns["dosage"],
...     snp_map=snp_map,
... )
>>> sim.fit(adata, max_epochs=5, verbose=False)
>>> synthetic = sim.sample()
>>>
>>> # simulate a new cohort of donors
>>> with sim.marginal.simulated_donor_effects(seed=0):
...     new_cohort = sim.sample()
Source code in scdesigner/src/scdesigner/simulators/scd3.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
class NegBinEQTLCopula(SCD3Simulator):
    """NB simulator for single-cell eQTL data

    eQTL data present a challenge for our usual negative binomial copula
    simulators. Since every gene is regulated by its own set of SNPs, we can no
    longer rely on sharing the same design matrix across all response genes.
    Further, since gene expression profiles tend to vary from individual to
    individual, it is important to include some sort of patient-level (random)
    intercept.

    Our approach is as follows. For cell :math:`i`, gene :math:`j`, and donor
    :math:`k(i)`, fit the marginal model,

    .. math::
       Y_{ij}\mid u_{k(i),j} \sim \operatorname{NB}(\mu_{ij}, r_{ij}),\qquad
       \operatorname{Var}(Y_{ij}\mid u)=\mu_{ij}+\mu_{ij}^2/r_{ij},

       \log\mu_{ij}
         = W_i^\top\theta_j + u_{k(i),j}
         + \sum_m D_{k(i),jm}
           \left(\beta_{jm}+V_i^\top\zeta_{jm}\right),\qquad
       \log r_{ij}=Z_i^\top\psi_j,\quad
       u_{kj}\sim N(0,\sigma_j^2).

    :math:`W_i` and :math:`Z_i` are cell-level design matrices shared across all
    genes and :math:D is a :math:`D \in R^{K x J x M}` is a donor x gene x
    maximum number of SNPs per gene matrix storing the "dosage" (0, 1, 2) of the
    variant in the gene for that donor. Notice that M indexes different SNPs for
    each gene, The specific mapping is stored in snp_map. :math:`zeta` It allows
    for interaction between the genotype and cell-level features like cell type.
    The matrix U stores a donor-level intercept.

    The coefficients and the donor-level intercepts are estimated using a ridge
    regularized negative binomial likelihood. The variance of the random effects
    u is updated after each epoch using the posterior moments described in
    donor_moments.py.

    Once this marginal model is estimated, the copula proceeds as usual.

    Parameters
    ----------
    mean_formula : str
        lme4-style formula for :math:`\log\mu`. It must include a ``genotype``
        term, which denotes that gene's SNP dosages (see `dosage` and
        `snp_map`). It must also have a donor-level random intercept ``(1 |
        donor)``, where ``donor`` is a column of `adata.obs`.  Any other terms
        define :math:`W_i`. Interactions with ``genotype``, like ``genotype:X``,
        define :math:`V_i`. For example, ``~ genotype * cell_type + (1 |
        donor)`` gives cell-type-specific eQTLs and ``~ genotype *
        bs(pseudotime, df=5) + (1 | donor)`` gives dynamic eQTLs.
    dispersion_formula : str
        An analog of the mean formula, but for the dispersion. It can have fixed
        effects but not ``genotype`` or donor-level random effects. By default
        it is constant across all cells.
    copula_formula : str
        Groups to divide the copula estimation in two
    dosage : pandas.DataFrame
        A donor-by-SNP table giving the genotypes {0, 1, 2} of each individual
    snp_map : dict[str, list[str]]
        Gene name -> SNP columns regulating that gene
    **marginal_kwargs
        Additional keyword arguments that are passed to `NegBinEQTL`

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`NegBinEQTL`
    :class:`StandardCopula`

    Examples
    --------
    >>> from scdesigner import datasets
    >>> from scdesigner.simulators import NegBinEQTLCopula
    >>>
    >>> adata = datasets.dong_eqtl()
    >>> snp_map = {gene: [snp] for gene, snp in adata.var["snp"].items()}
    >>> sim = NegBinEQTLCopula(
    ...     "~ genotype * cell_type + (1 | indiv)",
    ...     dosage=adata.uns["dosage"],
    ...     snp_map=snp_map,
    ... )
    >>> sim.fit(adata, max_epochs=5, verbose=False)
    >>> synthetic = sim.sample()
    >>>
    >>> # simulate a new cohort of donors
    >>> with sim.marginal.simulated_donor_effects(seed=0):
    ...     new_cohort = sim.sample()
    """

    def __init__(
        self,
        mean_formula: str,
        dispersion_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        *,
        dosage,
        snp_map,
        device: Optional[torch.device | str] = None,
        **marginal_kwargs,
    ) -> None:
        marginal = NegBinEQTL(
            {"mean": mean_formula, "dispersion": dispersion_formula},
            dosage=dosage,
            snp_map=snp_map,
            device=device,
            **marginal_kwargs,
        )
        super().__init__(marginal, StandardCopula(copula_formula))

    def _augment_adata(self, adata: AnnData) -> AnnData:
        """Return a view of ``adata`` with the donor IDs"""
        return AnnData(
            X=adata.X, obs=self.marginal._augment_obs(adata.obs), var=adata.var
        )

    def fit(self, adata: AnnData, **kwargs):
        return super().fit(self._augment_adata(adata), **kwargs)

    def predict(self, obs=None, **kwargs):
        if obs is not None:
            obs = self.marginal._augment_obs(obs)
        return super().predict(obs=obs, **kwargs)

    def sample(self, obs=None, **kwargs):
        if obs is not None:
            obs = self.marginal._augment_obs(obs)
        return super().sample(obs=obs, **kwargs)

    def complexity(self, adata: AnnData = None, **kwargs):
        if adata is not None:
            adata = self._augment_adata(adata)
        return super().complexity(adata, **kwargs)

NegBinIRLSCopula

Bases: SCD3Simulator

Simulator using negative binomial marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the negative binomial marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
dispersion_formula str or None

Model formula for the dispersion parameter of the negative binomial marginal. If None, a default constant-dispersion formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group").If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:NegBin :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
825
826
827
828
829
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
class NegBinIRLSCopula(SCD3Simulator):
    """Simulator using negative binomial marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the negative binomial
        marginal (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a
        default constant-mean formula is used.
    dispersion_formula : str or None, optional
        Model formula for the dispersion parameter of the negative
        binomial marginal. If ``None``, a default constant-dispersion
        formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental
        or biological conditions (e.g. ``"~ group"``).If ``None``,
        a default intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`NegBin`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        dispersion_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
    ) -> None:
        marginal = NegBinIRLS({"mean": mean_formula, "dispersion": dispersion_formula})
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

    def fit(self, adata: AnnData, batch_size: int = 8224, device="cpu", **kwargs):
        super().fit(adata, batch_size=batch_size, device=device, **kwargs)

    def sample(self, obs=None, batch_size: int = 8224, **kwargs):
        return super().sample(obs, batch_size, device="cpu", **kwargs)

    def predict(self, obs=None, batch_size: int = 8224, **kwargs):
        return super().predict(obs, batch_size, device="cpu", **kwargs)

    def complexity(self, adata: AnnData = None, device="cpu", **kwargs):
        return super().complexity(adata, device=device, **kwargs)

PoissonCopula

Bases: SCD3Simulator

Simulator using Poisson marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the Poisson marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:Poisson :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
668
669
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
class PoissonCopula(SCD3Simulator):
    """Simulator using Poisson marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the Poisson marginal
        (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a default
        constant-mean formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`Poisson`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = Poisson({"mean": mean_formula}, device=device)
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

PositiveNMF

Bases: Simulator

Positive nonnegative matrix factorization (PNMF) simulator with gamma regression.

This simulator fits a low-rank positive factorization on log-transformed expression data and then models the resulting latent scores using a covariate-dependent shifted gamma distribution. Sampling proceeds by drawing gamma latent scores and mapping them back to the gene space via the learned PNMF weights.

Parameters:

Name Type Description Default
formula dict or str

Mean-model formula for the gamma regression. If a string is provided, it is interpreted as the mean formula and stored under the key "mean". The formula is evaluated against adata.obs via :func:formulaic.model_matrix.

required
**kwargs

Keyword arguments forwarded to :func:pnmf (e.g. nbase, maxIter).

{}

Attributes:

Name Type Description
formula dict

Standardized formula dictionary containing at least the "mean" key.

parameters dict or None

Fitted parameters after calling :meth:fit. Keys include:

  • "a" (:class:pandas.DataFrame): gamma shape regression coefficients.
  • "loc" (:class:pandas.DataFrame): gamma location regression coefficients.
  • "beta" (:class:pandas.DataFrame): gamma rate regression coefficients.
  • "W" (:class:pandas.DataFrame): PNMF weight matrix mapping latent scores to genes.
n_outcomes int

Number of simulated outcomes (cells) in the training data.

columns Index

Column names of the design matrix produced from formula["mean"].

Examples:

Fit a PNMF simulator, inspect fitted parameters, and generate samples:

>>> import numpy as np
>>> import pandas as pd
>>> from anndata import AnnData
>>> from scdesigner.simulators import PositiveNMF
>>>
>>> rng = np.random.default_rng(0)
>>> X = rng.poisson(lam=2.0, size=(50, 20)).astype(float)  # (cells × genes)
>>> obs = pd.DataFrame({"condition": rng.choice(["A", "B"], size=50)})
>>> adata = AnnData(X=X, obs=obs)
>>> adata.var_names = [f"g{i}" for i in range(adata.n_vars)]
>>>
>>> sim = PositiveNMF("~ 1 + condition", nbase=3, maxIter=50)
>>> sim.fit(adata, lr=0.1)
>>> isinstance(sim.parameters, dict)
True
>>>
>>> # Predict gamma parameters for new observations
>>> new_obs = pd.DataFrame({"condition": ["A", "B", "A"]})
>>> pred = sim.predict(new_obs)
>>> sorted(pred.keys())
['a', 'beta', 'loc']
>>>
>>> # Sample a new dataset with the same genes
>>> adata_sim = sim.sample(new_obs)
>>> adata_sim.n_obs == 3 and adata_sim.n_vars == adata.n_vars
True
Source code in scdesigner/src/scdesigner/simulators/positive_nonnegative_matrix_factorization.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
class PositiveNMF(Simulator):
    """
    Positive nonnegative matrix factorization (PNMF) simulator with gamma regression.

    This simulator fits a low-rank positive factorization on log-transformed
    expression data and then models the resulting latent scores using a
    covariate-dependent shifted gamma distribution. Sampling proceeds by
    drawing gamma latent scores and mapping them back to the gene space via the
    learned PNMF weights.

    Parameters
    ----------
    formula : dict or str
        Mean-model formula for the gamma regression. If a string is provided,
        it is interpreted as the mean formula and stored under the key
        ``"mean"``. The formula is evaluated against ``adata.obs`` via
        :func:`formulaic.model_matrix`.
    **kwargs
        Keyword arguments forwarded to :func:`pnmf` (e.g. ``nbase``, ``maxIter``).

    Attributes
    ----------
    formula : dict
        Standardized formula dictionary containing at least the ``"mean"`` key.
    parameters : dict or None
        Fitted parameters after calling :meth:`fit`. Keys include:

        * ``"a"`` (:class:`pandas.DataFrame`): gamma shape regression coefficients.
        * ``"loc"`` (:class:`pandas.DataFrame`): gamma location regression coefficients.
        * ``"beta"`` (:class:`pandas.DataFrame`): gamma rate regression coefficients.
        * ``"W"`` (:class:`pandas.DataFrame`): PNMF weight matrix mapping latent
          scores to genes.
    n_outcomes : int
        Number of simulated outcomes (cells) in the training data.
    columns : pandas.Index
        Column names of the design matrix produced from ``formula["mean"]``.

    Examples
    --------
    Fit a PNMF simulator, inspect fitted parameters, and generate samples:

    >>> import numpy as np
    >>> import pandas as pd
    >>> from anndata import AnnData
    >>> from scdesigner.simulators import PositiveNMF
    >>>
    >>> rng = np.random.default_rng(0)
    >>> X = rng.poisson(lam=2.0, size=(50, 20)).astype(float)  # (cells × genes)
    >>> obs = pd.DataFrame({"condition": rng.choice(["A", "B"], size=50)})
    >>> adata = AnnData(X=X, obs=obs)
    >>> adata.var_names = [f"g{i}" for i in range(adata.n_vars)]
    >>>
    >>> sim = PositiveNMF("~ 1 + condition", nbase=3, maxIter=50)
    >>> sim.fit(adata, lr=0.1)
    >>> isinstance(sim.parameters, dict)
    True
    >>>
    >>> # Predict gamma parameters for new observations
    >>> new_obs = pd.DataFrame({"condition": ["A", "B", "A"]})
    >>> pred = sim.predict(new_obs)
    >>> sorted(pred.keys())
    ['a', 'beta', 'loc']
    >>>
    >>> # Sample a new dataset with the same genes
    >>> adata_sim = sim.sample(new_obs)
    >>> adata_sim.n_obs == 3 and adata_sim.n_vars == adata.n_vars
    True
    """
    def __init__(self, formula: Union[Dict, str], **kwargs):
        """
        Parameters
        ----------
        formula : dict or str
            Formula describing the mean model for the gamma regression.
        **kwargs
            Keyword arguments passed through to :func:`pnmf`.
        """
        self.formula = standardize_formula(formula, allowed_keys=['mean'])
        self.parameters = None
        self._hyperparams = kwargs


    def setup_data(self, adata: AnnData, **kwargs):
        self.log_data = np.log1p(adata.X).T #(genes x cells)
        self.n_outcomes = self.log_data.shape[1]
        self._template = adata
        self.x = model_matrix(self.formula["mean"], adata.obs)
        self.columns = self.x.columns
        self.x = np.asarray(self.x)


    def fit(self, adata: AnnData, lr: float=0.1):
        """
        Fit the PNMF marginals on the provided AnnData.

        Parameters
        ----------
        adata : AnnData
            Dataset used to estimate PNMF weights and gamma coefficients.
        lr : float, optional
            Learning rate for the gamma regression solver.
        """
        self.setup_data(adata)
        W, S = pnmf(self.log_data, **self._hyperparams)
        parameters = gamma_regression_array(self.x, S.T, lr)
        parameters["W"] = W
        self.parameters = format_gamma_parameters(
            parameters, list(self._template.var_names), list(self.columns)
        )


    def predict(self, obs=None, **kwargs):
        """
        Predict gamma regression parameters for new observations.

        Parameters
        ----------
        obs : pandas.DataFrame, optional
            Observation metadata used to construct the design matrix. Defaults
            to the training ``AnnData`` observations.

        Returns
        -------
        dict[str, np.ndarray]
            Dictionary with ``"a"``, ``"loc"``, and ``"beta"`` arrays for each
            target feature and observation.
        """
        if obs is None:
            obs = self._template.obs

        x = model_matrix(self.formula["mean"], obs)
        a, loc, beta = (
            x @ np.exp(self.parameters["a"]),
            x @ self.parameters["loc"],
            x @ np.exp(self.parameters["beta"]),
        )
        return {"a": a, "loc": loc, "beta": beta}


    def sample(self, obs=None):
        """
        Generate expression samples from the fitted model.

        Parameters
        ----------
        obs : pandas.DataFrame, optional
            Metadata for the observations to simulate. Defaults to the training
            ``AnnData`` annotations.

        Returns
        -------
        AnnData
            Simulated :class:`AnnData` matrix containing generated expression
            counts on the original feature ordering.
        """
        if obs is None:
            obs = self._template.obs
        W = self.parameters["W"]
        parameters = self.predict(obs)
        a, loc, beta = parameters["a"], parameters["loc"], parameters["beta"]
        sim_score = gamma(a, loc, 1 / beta).rvs()
        samples = np.exp(W @ sim_score.T).T

        # thresholding samples
        floor = np.floor(samples)
        samples = floor + np.where(samples - floor < 0.9, 0, 1) - 1
        samples = np.where(samples < 0, 0, samples)

        result = AnnData(X=samples, obs=obs)
        result.var_names = self._template.var_names
        return result

__init__(formula, **kwargs)

Parameters:

Name Type Description Default
formula dict or str

Formula describing the mean model for the gamma regression.

required
**kwargs

Keyword arguments passed through to :func:pnmf.

{}
Source code in scdesigner/src/scdesigner/simulators/positive_nonnegative_matrix_factorization.py
375
376
377
378
379
380
381
382
383
384
385
386
def __init__(self, formula: Union[Dict, str], **kwargs):
    """
    Parameters
    ----------
    formula : dict or str
        Formula describing the mean model for the gamma regression.
    **kwargs
        Keyword arguments passed through to :func:`pnmf`.
    """
    self.formula = standardize_formula(formula, allowed_keys=['mean'])
    self.parameters = None
    self._hyperparams = kwargs

fit(adata, lr=0.1)

Fit the PNMF marginals on the provided AnnData.

Parameters:

Name Type Description Default
adata AnnData

Dataset used to estimate PNMF weights and gamma coefficients.

required
lr float

Learning rate for the gamma regression solver.

0.1
Source code in scdesigner/src/scdesigner/simulators/positive_nonnegative_matrix_factorization.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def fit(self, adata: AnnData, lr: float=0.1):
    """
    Fit the PNMF marginals on the provided AnnData.

    Parameters
    ----------
    adata : AnnData
        Dataset used to estimate PNMF weights and gamma coefficients.
    lr : float, optional
        Learning rate for the gamma regression solver.
    """
    self.setup_data(adata)
    W, S = pnmf(self.log_data, **self._hyperparams)
    parameters = gamma_regression_array(self.x, S.T, lr)
    parameters["W"] = W
    self.parameters = format_gamma_parameters(
        parameters, list(self._template.var_names), list(self.columns)
    )

predict(obs=None, **kwargs)

Predict gamma regression parameters for new observations.

Parameters:

Name Type Description Default
obs DataFrame

Observation metadata used to construct the design matrix. Defaults to the training AnnData observations.

None

Returns:

Type Description
dict[str, ndarray]

Dictionary with "a", "loc", and "beta" arrays for each target feature and observation.

Source code in scdesigner/src/scdesigner/simulators/positive_nonnegative_matrix_factorization.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def predict(self, obs=None, **kwargs):
    """
    Predict gamma regression parameters for new observations.

    Parameters
    ----------
    obs : pandas.DataFrame, optional
        Observation metadata used to construct the design matrix. Defaults
        to the training ``AnnData`` observations.

    Returns
    -------
    dict[str, np.ndarray]
        Dictionary with ``"a"``, ``"loc"``, and ``"beta"`` arrays for each
        target feature and observation.
    """
    if obs is None:
        obs = self._template.obs

    x = model_matrix(self.formula["mean"], obs)
    a, loc, beta = (
        x @ np.exp(self.parameters["a"]),
        x @ self.parameters["loc"],
        x @ np.exp(self.parameters["beta"]),
    )
    return {"a": a, "loc": loc, "beta": beta}

sample(obs=None)

Generate expression samples from the fitted model.

Parameters:

Name Type Description Default
obs DataFrame

Metadata for the observations to simulate. Defaults to the training AnnData annotations.

None

Returns:

Type Description
AnnData

Simulated :class:AnnData matrix containing generated expression counts on the original feature ordering.

Source code in scdesigner/src/scdesigner/simulators/positive_nonnegative_matrix_factorization.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def sample(self, obs=None):
    """
    Generate expression samples from the fitted model.

    Parameters
    ----------
    obs : pandas.DataFrame, optional
        Metadata for the observations to simulate. Defaults to the training
        ``AnnData`` annotations.

    Returns
    -------
    AnnData
        Simulated :class:`AnnData` matrix containing generated expression
        counts on the original feature ordering.
    """
    if obs is None:
        obs = self._template.obs
    W = self.parameters["W"]
    parameters = self.predict(obs)
    a, loc, beta = parameters["a"], parameters["loc"], parameters["beta"]
    sim_score = gamma(a, loc, 1 / beta).rvs()
    samples = np.exp(W @ sim_score.T).T

    # thresholding samples
    floor = np.floor(samples)
    samples = floor + np.where(samples - floor < 0.9, 0, 1) - 1
    samples = np.where(samples < 0, 0, samples)

    result = AnnData(X=samples, obs=obs)
    result.var_names = self._template.var_names
    return result

SCD3Simulator

Bases: Simulator, ABC

High-level simulation wrapper combining a marginal model and a copula.

The :class:SCD3Simulator class coordinates fitting of a marginal model (e.g. negative binomial, zero-inflated negative binomial) together with a dependence structure specified by a copula (e.g. :class:StandardCopula). Subclasses provide concrete combinations of marginal and copula models tailored to common use cases.

Parameters:

Name Type Description Default
marginal Marginal

Fitted or unfitted marginal model describing the distribution of each feature (e.g. gene) conditional on covariates.

required
copula Copula

Copula object that captures dependence between features and shares the same covariate structure as the marginal model.

required
observation_transform SpatialDesign

For some problems, we want to transform the cell-level obs data in the anndata object to provide additional features for the model. For example, when we use SpatialDesign, we will expand the obs data to include a spatial basis matrix.

None
output_transform ObservedMaxCap

Apply transformation to the sampled values. For example, ObservedMaxCap clips any samples at the maximum value observed in the training data.

None

Attributes:

Name Type Description
marginal Marginal

The marginal model instance used for fitting and simulation.

copula Copula

The copula instance used to model dependence between features.

observation_transform SpatialDesign or None
output_transform ObservedMaxCap or None
template AnnData or None

Reference dataset used to define the observed covariate space and feature set for simulation. Set during :meth:fit.

parameters dict or None

Dictionary containing fitted parameters for both the marginal and copula components after :meth:fit has been called.

Examples:

For the common cases, use one of the concrete subclasses, e.g. :class:NegBinCopula::

>>> import scanpy as sc
>>> from scdesigner.simulators import NegBinCopula
>>>
>>> adata = sc.datasets.pbmc3k()[:, :100].copy()
>>>
>>> # Mean expression depends on group; copula uses the same group structure
>>> sim = NegBinCopula(mean_formula="~ 1", dispersion_formula="~ 1",
...                    copula_formula="~ 1")
>>> sim.fit(adata, batch_size=256, max_epochs=10) # doctest: +SKIP
>>>
>>> # Generate synthetic data with the same obs covariates
>>> synthetic = sim.sample(batch_size=512) # doctest: +SKIP
>>> synthetic.X.shape == adata.shape # doctest: +SKIP
True
>>>
>>> # Compute model complexity via AIC/BIC of the copula component
>>> metrics = sim.complexity() # doctest: +SKIP
>>> sorted(metrics.keys()) # doctest: +SKIP
['aic', 'bic'] # doctest: +SKIP

We can also create models with custom copula approaches. The example below uses a regularized LedoitWolf estimator instead of the default sample covariance.

>>> from scdesigner.simulators import SCD3Simulator
>>> from scdesigner.distributions import NegBin
>>> from scdesigner.copulas import StandardCopula
>>> from scdesigner.covariance import LedoitWolf
>>>
>>> sim = SCD3Simulator(
...     NegBin({"mean": "~ cell_type", "dispersion": "~ 1"}),
...     StandardCopula("~ cell_type", estimator=LedoitWolf()),
... )
>>> sim.fit(adata, batch_size=256, max_epochs=10) # doctest: +SKIP
Source code in scdesigner/src/scdesigner/simulators/scd3.py
 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
323
324
325
326
327
328
329
class SCD3Simulator(Simulator, ABC):
    """High-level simulation wrapper combining a marginal model and a copula.

    The :class:`SCD3Simulator` class coordinates fitting of a marginal model
    (e.g. negative binomial, zero-inflated negative binomial) together with a
    dependence structure specified by a copula (e.g. :class:`StandardCopula`).
    Subclasses provide concrete combinations of marginal and copula models
    tailored to common use cases.

    Parameters
    ----------
    marginal : Marginal
        Fitted or unfitted marginal model describing the distribution of each
        feature (e.g. gene) conditional on covariates.
    copula : Copula
        Copula object that captures dependence between features and shares
        the same covariate structure as the marginal model.
    observation_transform : SpatialDesign, optional
        For some problems, we want to transform the cell-level `obs` data in the
        anndata object to provide additional features for the model. For
        example, when we use SpatialDesign, we will expand the `obs` data to
        include a spatial basis matrix.
    output_transform : ObservedMaxCap, optional
        Apply transformation to the sampled values. For example, ObservedMaxCap
        clips any samples at the maximum value observed in the training data.

    Attributes
    ----------
    marginal : Marginal
        The marginal model instance used for fitting and simulation.
    copula : Copula
        The copula instance used to model dependence between features.
    observation_transform : SpatialDesign or None
    output_transform : ObservedMaxCap or None
    template : AnnData or None
        Reference dataset used to define the observed covariate space and
        feature set for simulation. Set during :meth:`fit`.
    parameters : dict or None
        Dictionary containing fitted parameters for both the marginal and
        copula components after :meth:`fit` has been called.

    Examples
    --------
    For the common cases, use one of the concrete subclasses, e.g.
    :class:`NegBinCopula`::

        >>> import scanpy as sc
        >>> from scdesigner.simulators import NegBinCopula
        >>>
        >>> adata = sc.datasets.pbmc3k()[:, :100].copy()
        >>>
        >>> # Mean expression depends on group; copula uses the same group structure
        >>> sim = NegBinCopula(mean_formula="~ 1", dispersion_formula="~ 1",
        ...                    copula_formula="~ 1")
        >>> sim.fit(adata, batch_size=256, max_epochs=10) # doctest: +SKIP
        >>>
        >>> # Generate synthetic data with the same obs covariates
        >>> synthetic = sim.sample(batch_size=512) # doctest: +SKIP
        >>> synthetic.X.shape == adata.shape # doctest: +SKIP
        True
        >>>
        >>> # Compute model complexity via AIC/BIC of the copula component
        >>> metrics = sim.complexity() # doctest: +SKIP
        >>> sorted(metrics.keys()) # doctest: +SKIP
        ['aic', 'bic'] # doctest: +SKIP

    We can also create models with custom copula approaches. The example below
    uses a regularized LedoitWolf estimator instead of the default sample
    covariance.

        >>> from scdesigner.simulators import SCD3Simulator
        >>> from scdesigner.distributions import NegBin
        >>> from scdesigner.copulas import StandardCopula
        >>> from scdesigner.covariance import LedoitWolf
        >>>
        >>> sim = SCD3Simulator(
        ...     NegBin({"mean": "~ cell_type", "dispersion": "~ 1"}),
        ...     StandardCopula("~ cell_type", estimator=LedoitWolf()),
        ... )
        >>> sim.fit(adata, batch_size=256, max_epochs=10) # doctest: +SKIP
    """

    def __init__(
        self,
        marginal: Marginal,
        copula: Copula,
        *,
        observation_transform: Optional[SpatialDesign] = None,
        output_transform: Optional[ObservedMaxCap] = None,
    ):
        self.marginal = marginal
        self.copula = copula
        self.observation_transform = observation_transform
        self.output_transform = output_transform
        self.template = None
        self.parameters = None
        self._base_penalties = tuple(marginal.penalties)

    def _loader_kwargs(self, kwargs: dict) -> dict:
        """Build loader options that always use the marginal's device."""
        return {**kwargs, "device": self.marginal.device}

    def to(self, device):
        """Move the marginal and copula state to ``device``."""
        self.marginal.to(device)
        self.copula.to(device)
        return self

    def fit(
        self,
        adata: AnnData,
        val_frac: float = 0.1,
        min_epochs: int = 10,
        loss_tol: float = 1e-4,
        patience: int = 40,
        validation_seed: int = 0,
        **kwargs,
    ):
        """Fit marginal and copula components to an AnnData object.

        Parameters
        ----------
        adata : AnnData
            Input dataset with cells in rows and features (e.g. genes) in
            columns. Both the marginal and copula components are fitted to
            this data.
        val_frac : float
            Fraction of observations held out for marginal validation. Set to
            0 to disable early stopping.
        min_epochs : int
            Minimum number of marginal epochs before early stopping is allowed.
        loss_tol : float
            Required relative validation-loss decrease to reset patience.
        patience : int
            Number of non-improving validation epochs allowed after warmup.
        validation_seed : int
            Seed controlling the deterministic marginal validation split.
        **kwargs
            Additional keyword arguments forwarded to the marginal fit routine
            and to both components' data setup (e.g. ``batch_size``,
            ``chunk_size``, optimization settings).

        Notes
        -----
        This method sets the :attr:`template` attribute to ``adata`` and
        stores fitted parameters in :attr:`parameters`. Design state is fitted
        once on ``adata.obs`` and reused by :meth:`predict`, :meth:`sample`
        and :meth:`complexity`.
        """
        kwargs = self._loader_kwargs(kwargs)
        self.template = adata

        # fit the observation transform; its columns are generated per chunk
        transform = getattr(self, "observation_transform", None)
        if transform is not None:
            transform.fit(adata.obs, chunk_size=resolve_chunk_size(adata, kwargs.get("chunk_size")))
            self.marginal.formula = dict(transform.formula)
            self.marginal.penalties = self._base_penalties + transform.penalties

        # define a dataloader on the design and fit
        self.marginal.setup_data(adata, observation_transform=transform, **kwargs)
        self.marginal.fit(
            val_frac=val_frac,
            min_epochs=min_epochs,
            loss_tol=loss_tol,
            patience=patience,
            validation_seed=validation_seed,
            **kwargs,
        )

        # copula simulator
        self.copula.setup_data(
            adata, self.marginal.formula, observation_transform=transform, **kwargs
        )
        self.copula.fit(self.marginal.uniformize)

        # transform the outputs if needed
        output_transform = getattr(self, "output_transform", None)
        if output_transform is not None:
            output_transform.fit(adata, chunk_size=self.marginal.chunk_size)

        self.parameters = {
            "marginal": self.marginal.parameters,
            "copula": self.copula.parameters,
        }

    def predict(self, obs=None, batch_size: int = 1000, **kwargs):
        """Predict marginal parameters for given covariates.

        Parameters
        ----------
        obs : pandas.DataFrame or None, optional
            Observation-level covariate table. If ``None``, use
            ``self.template.obs`` from the dataset provided to :meth:`fit`.
        batch_size : int, optional
            Number of observations per mini-batch used during prediction.
        **kwargs
            Additional keyword arguments passed to :func:`obs_loader`.

        Returns
        -------
        dict
            Dictionary mapping parameter names (e.g. ``"mean"``,
            ``"dispersion"``) to NumPy arrays of shape ``(n_cells, n_genes)``
            containing the predicted marginal parameters.
        """
        # prepare an internal data loader for this obs
        kwargs = self._loader_kwargs(kwargs)
        if obs is None:
            obs = self.template.obs
        loader = obs_loader(obs, self.marginal.design, batch_size=batch_size, **kwargs)

        # get predictions across batches
        local_parameters = []
        for _, x_dict in loader:
            l = self.marginal.predict(x_dict)
            local_parameters.append(l)

        # convert to a merged dictionary
        keys = list(local_parameters[0].keys())
        return {
            k: torch.cat([d[k] for d in local_parameters]).detach().cpu().numpy()
            for k in keys
        }

    def sample(self, obs=None, batch_size: int = 1000, **kwargs):
        """Generate synthetic observations from the fitted model.

        Parameters
        ----------
        obs : pandas.DataFrame or None, optional
            Observation-level covariate table defining the covariate space
            for simulation. If ``None``, use ``self.template.obs``.
        batch_size : int, optional
            Number of observations per mini-batch used during sampling.
        **kwargs
            Additional keyword arguments passed to :func:`obs_loader`.

        Returns
        -------
        AnnData
            An :class:`AnnData` object with simulated counts in ``.X`` and
            ``obs`` equal to the provided covariate table.
        """
        kwargs = self._loader_kwargs(kwargs)
        if obs is None:
            obs = self.template.obs
        loader = obs_loader(obs, self.copula.design, batch_size=batch_size, **kwargs)

        # get samples across batches
        samples = []
        for _, x_dict in loader:
            u = self.copula.pseudo_obs(x_dict)
            u = torch.from_numpy(u)
            samples.append(self.marginal.invert(u, x_dict))
        samples = torch.cat(samples).detach().cpu().numpy()
        output_transform = getattr(self, "output_transform", None)
        if output_transform is not None:
            samples = output_transform.transform(samples)
        return AnnData(X=samples, obs=obs, var=self.template.var)

    def complexity(self, adata: AnnData = None, **kwargs):
        """Compute model complexity metrics (AIC, BIC) for the copula component.

        Parameters
        ----------
        adata : AnnData or None, optional
            Dataset to evaluate the copula log-likelihood on. If ``None``,
            use the template dataset stored during :meth:`fit`.
        **kwargs
            Additional keyword arguments passed to :func:`adata_loader`.
            ``chunk_size`` defaults to the one given to :meth:`fit`.

        Returns
        -------
        dict
            Dictionary with keys ``"aic"`` and ``"bic"`` computed from the
            copula log-likelihood and :meth:`copula.num_params`.
        """
        kwargs = self._loader_kwargs(kwargs)
        use_template_ll = False
        if adata is None:
            use_template_ll = True
            adata = self.template
        kwargs.setdefault("chunk_size", self.marginal.chunk_size)

        N, marginal_ll, copula_ll = 0, 0, 0
        loader = adata_loader(adata, self.copula.design, **kwargs)
        for batch in tqdm(loader, desc="Computing log-likelihood..."):
            with torch.no_grad():
                marginal_ll += self.marginal.likelihood(batch).sum()
            if not use_template_ll:
                copula_ll += self.copula.likelihood(self.marginal.uniformize, batch).sum()
            N += len(batch[0])

        if use_template_ll: copula_ll = self.copula.copula_likelihood

        return {
            "marginal_aic": -2 * marginal_ll.item() + 2 * self.marginal.num_params(),
            "marginal_bic": -2 * marginal_ll.item() + np.log(N) * self.marginal.num_params(),
            "copula_aic": -2 * copula_ll + 2 * self.copula.num_params(),
            "copula_bic": -2 * copula_ll + np.log(N) * self.copula.num_params()
        }

complexity(adata=None, **kwargs)

Compute model complexity metrics (AIC, BIC) for the copula component.

Parameters:

Name Type Description Default
adata AnnData or None

Dataset to evaluate the copula log-likelihood on. If None, use the template dataset stored during :meth:fit.

None
**kwargs

Additional keyword arguments passed to :func:adata_loader. chunk_size defaults to the one given to :meth:fit.

{}

Returns:

Type Description
dict

Dictionary with keys "aic" and "bic" computed from the copula log-likelihood and :meth:copula.num_params.

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
323
324
325
326
327
328
329
def complexity(self, adata: AnnData = None, **kwargs):
    """Compute model complexity metrics (AIC, BIC) for the copula component.

    Parameters
    ----------
    adata : AnnData or None, optional
        Dataset to evaluate the copula log-likelihood on. If ``None``,
        use the template dataset stored during :meth:`fit`.
    **kwargs
        Additional keyword arguments passed to :func:`adata_loader`.
        ``chunk_size`` defaults to the one given to :meth:`fit`.

    Returns
    -------
    dict
        Dictionary with keys ``"aic"`` and ``"bic"`` computed from the
        copula log-likelihood and :meth:`copula.num_params`.
    """
    kwargs = self._loader_kwargs(kwargs)
    use_template_ll = False
    if adata is None:
        use_template_ll = True
        adata = self.template
    kwargs.setdefault("chunk_size", self.marginal.chunk_size)

    N, marginal_ll, copula_ll = 0, 0, 0
    loader = adata_loader(adata, self.copula.design, **kwargs)
    for batch in tqdm(loader, desc="Computing log-likelihood..."):
        with torch.no_grad():
            marginal_ll += self.marginal.likelihood(batch).sum()
        if not use_template_ll:
            copula_ll += self.copula.likelihood(self.marginal.uniformize, batch).sum()
        N += len(batch[0])

    if use_template_ll: copula_ll = self.copula.copula_likelihood

    return {
        "marginal_aic": -2 * marginal_ll.item() + 2 * self.marginal.num_params(),
        "marginal_bic": -2 * marginal_ll.item() + np.log(N) * self.marginal.num_params(),
        "copula_aic": -2 * copula_ll + 2 * self.copula.num_params(),
        "copula_bic": -2 * copula_ll + np.log(N) * self.copula.num_params()
    }

fit(adata, val_frac=0.1, min_epochs=10, loss_tol=0.0001, patience=40, validation_seed=0, **kwargs)

Fit marginal and copula components to an AnnData object.

Parameters:

Name Type Description Default
adata AnnData

Input dataset with cells in rows and features (e.g. genes) in columns. Both the marginal and copula components are fitted to this data.

required
val_frac float

Fraction of observations held out for marginal validation. Set to 0 to disable early stopping.

0.1
min_epochs int

Minimum number of marginal epochs before early stopping is allowed.

10
loss_tol float

Required relative validation-loss decrease to reset patience.

0.0001
patience int

Number of non-improving validation epochs allowed after warmup.

40
validation_seed int

Seed controlling the deterministic marginal validation split.

0
**kwargs

Additional keyword arguments forwarded to the marginal fit routine and to both components' data setup (e.g. batch_size, chunk_size, optimization settings).

{}
Notes

This method sets the :attr:template attribute to adata and stores fitted parameters in :attr:parameters. Design state is fitted once on adata.obs and reused by :meth:predict, :meth:sample and :meth:complexity.

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
def fit(
    self,
    adata: AnnData,
    val_frac: float = 0.1,
    min_epochs: int = 10,
    loss_tol: float = 1e-4,
    patience: int = 40,
    validation_seed: int = 0,
    **kwargs,
):
    """Fit marginal and copula components to an AnnData object.

    Parameters
    ----------
    adata : AnnData
        Input dataset with cells in rows and features (e.g. genes) in
        columns. Both the marginal and copula components are fitted to
        this data.
    val_frac : float
        Fraction of observations held out for marginal validation. Set to
        0 to disable early stopping.
    min_epochs : int
        Minimum number of marginal epochs before early stopping is allowed.
    loss_tol : float
        Required relative validation-loss decrease to reset patience.
    patience : int
        Number of non-improving validation epochs allowed after warmup.
    validation_seed : int
        Seed controlling the deterministic marginal validation split.
    **kwargs
        Additional keyword arguments forwarded to the marginal fit routine
        and to both components' data setup (e.g. ``batch_size``,
        ``chunk_size``, optimization settings).

    Notes
    -----
    This method sets the :attr:`template` attribute to ``adata`` and
    stores fitted parameters in :attr:`parameters`. Design state is fitted
    once on ``adata.obs`` and reused by :meth:`predict`, :meth:`sample`
    and :meth:`complexity`.
    """
    kwargs = self._loader_kwargs(kwargs)
    self.template = adata

    # fit the observation transform; its columns are generated per chunk
    transform = getattr(self, "observation_transform", None)
    if transform is not None:
        transform.fit(adata.obs, chunk_size=resolve_chunk_size(adata, kwargs.get("chunk_size")))
        self.marginal.formula = dict(transform.formula)
        self.marginal.penalties = self._base_penalties + transform.penalties

    # define a dataloader on the design and fit
    self.marginal.setup_data(adata, observation_transform=transform, **kwargs)
    self.marginal.fit(
        val_frac=val_frac,
        min_epochs=min_epochs,
        loss_tol=loss_tol,
        patience=patience,
        validation_seed=validation_seed,
        **kwargs,
    )

    # copula simulator
    self.copula.setup_data(
        adata, self.marginal.formula, observation_transform=transform, **kwargs
    )
    self.copula.fit(self.marginal.uniformize)

    # transform the outputs if needed
    output_transform = getattr(self, "output_transform", None)
    if output_transform is not None:
        output_transform.fit(adata, chunk_size=self.marginal.chunk_size)

    self.parameters = {
        "marginal": self.marginal.parameters,
        "copula": self.copula.parameters,
    }

predict(obs=None, batch_size=1000, **kwargs)

Predict marginal parameters for given covariates.

Parameters:

Name Type Description Default
obs DataFrame or None

Observation-level covariate table. If None, use self.template.obs from the dataset provided to :meth:fit.

None
batch_size int

Number of observations per mini-batch used during prediction.

1000
**kwargs

Additional keyword arguments passed to :func:obs_loader.

{}

Returns:

Type Description
dict

Dictionary mapping parameter names (e.g. "mean", "dispersion") to NumPy arrays of shape (n_cells, n_genes) containing the predicted marginal parameters.

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
def predict(self, obs=None, batch_size: int = 1000, **kwargs):
    """Predict marginal parameters for given covariates.

    Parameters
    ----------
    obs : pandas.DataFrame or None, optional
        Observation-level covariate table. If ``None``, use
        ``self.template.obs`` from the dataset provided to :meth:`fit`.
    batch_size : int, optional
        Number of observations per mini-batch used during prediction.
    **kwargs
        Additional keyword arguments passed to :func:`obs_loader`.

    Returns
    -------
    dict
        Dictionary mapping parameter names (e.g. ``"mean"``,
        ``"dispersion"``) to NumPy arrays of shape ``(n_cells, n_genes)``
        containing the predicted marginal parameters.
    """
    # prepare an internal data loader for this obs
    kwargs = self._loader_kwargs(kwargs)
    if obs is None:
        obs = self.template.obs
    loader = obs_loader(obs, self.marginal.design, batch_size=batch_size, **kwargs)

    # get predictions across batches
    local_parameters = []
    for _, x_dict in loader:
        l = self.marginal.predict(x_dict)
        local_parameters.append(l)

    # convert to a merged dictionary
    keys = list(local_parameters[0].keys())
    return {
        k: torch.cat([d[k] for d in local_parameters]).detach().cpu().numpy()
        for k in keys
    }

sample(obs=None, batch_size=1000, **kwargs)

Generate synthetic observations from the fitted model.

Parameters:

Name Type Description Default
obs DataFrame or None

Observation-level covariate table defining the covariate space for simulation. If None, use self.template.obs.

None
batch_size int

Number of observations per mini-batch used during sampling.

1000
**kwargs

Additional keyword arguments passed to :func:obs_loader.

{}

Returns:

Type Description
AnnData

An :class:AnnData object with simulated counts in .X and obs equal to the provided covariate table.

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
def sample(self, obs=None, batch_size: int = 1000, **kwargs):
    """Generate synthetic observations from the fitted model.

    Parameters
    ----------
    obs : pandas.DataFrame or None, optional
        Observation-level covariate table defining the covariate space
        for simulation. If ``None``, use ``self.template.obs``.
    batch_size : int, optional
        Number of observations per mini-batch used during sampling.
    **kwargs
        Additional keyword arguments passed to :func:`obs_loader`.

    Returns
    -------
    AnnData
        An :class:`AnnData` object with simulated counts in ``.X`` and
        ``obs`` equal to the provided covariate table.
    """
    kwargs = self._loader_kwargs(kwargs)
    if obs is None:
        obs = self.template.obs
    loader = obs_loader(obs, self.copula.design, batch_size=batch_size, **kwargs)

    # get samples across batches
    samples = []
    for _, x_dict in loader:
        u = self.copula.pseudo_obs(x_dict)
        u = torch.from_numpy(u)
        samples.append(self.marginal.invert(u, x_dict))
    samples = torch.cat(samples).detach().cpu().numpy()
    output_transform = getattr(self, "output_transform", None)
    if output_transform is not None:
        samples = output_transform.transform(samples)
    return AnnData(X=samples, obs=obs, var=self.template.var)

to(device)

Move the marginal and copula state to device.

Source code in scdesigner/src/scdesigner/simulators/scd3.py
129
130
131
132
133
def to(self, device):
    """Move the marginal and copula state to ``device``."""
    self.marginal.to(device)
    self.copula.to(device)
    return self

ZeroInflatedNegBinCopula

Bases: SCD3Simulator

Simulator using zero-inflated negative binomial marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the zero-inflated negative binomial marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
dispersion_formula str or None

Model formula for the dispersion parameter of the zero-inflated negative binomial marginal. If None, a default constant-dispersion formula is used.

'~ 1'
zero_inflation_formula str or None

Model formula for the zero-inflation parameter of the zero-inflated negative binomial marginal. If None, a default constant-zero-inflation formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:ZeroInflatedNegBin :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
class ZeroInflatedNegBinCopula(SCD3Simulator):
    """Simulator using zero-inflated negative binomial marginals with
    a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the zero-inflated
        negative binomial marginal (e.g. ``"~ 1"`` or ``"~ group"``).
        If ``None``, a default constant-mean formula is used.
    dispersion_formula : str or None, optional
        Model formula for the dispersion parameter of the zero-inflated
        negative binomial marginal. If ``None``, a default
        constant-dispersion formula is used.
    zero_inflation_formula : str or None, optional
        Model formula for the zero-inflation parameter of the zero-inflated
        negative binomial marginal. If ``None``, a default
        constant-zero-inflation formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`ZeroInflatedNegBin`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        dispersion_formula: Optional[str] = "~ 1",
        zero_inflation_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = ZeroInflatedNegBin(
            {
                "mean": mean_formula,
                "dispersion": dispersion_formula,
                "zero_inflation": zero_inflation_formula,
            },
            device=device,
        )
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

ZeroInflatedPoissonCopula

Bases: SCD3Simulator

Simulator using zero-inflated Poisson marginals with a Gaussian copula.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the mean parameter of the zero-inflated Poisson marginal (e.g. "~ 1" or "~ group"). If None, a default constant-mean formula is used.

'~ 1'
zero_inflation_formula str or None

Model formula for the zero-inflation parameter of the zero-inflated Poisson marginal. If None, a default constant-zero-inflation formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:ZeroInflatedPoisson :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
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
class ZeroInflatedPoissonCopula(SCD3Simulator):
    """Simulator using zero-inflated Poisson marginals with a Gaussian copula.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the mean parameter of the zero-inflated Poisson marginal
        (e.g. ``"~ 1"`` or ``"~ group"``). If ``None``, a default
        constant-mean formula is used.
    zero_inflation_formula : str or None, optional
        Model formula for the zero-inflation parameter of the zero-inflated Poisson
        marginal. If ``None``, a default constant-zero-inflation formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`ZeroInflatedPoisson`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        zero_inflation_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = ZeroInflatedPoisson(
            {"mean": mean_formula, "zero_inflation": zero_inflation_formula},
            device=device,
        )
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

ZeroInflatedTruncatedGaussianCopula

Bases: SCD3Simulator

Simulator using zero-inflated truncated Gaussian marginals with a Gaussian copula.

The marginal is a mixture of a point mass at zero and a Gaussian component truncated to the positive half-line, appropriate for nonnegative data.

Parameters:

Name Type Description Default
mean_formula str or None

Model formula for the latent (pre-truncation) Gaussian-component mean of the zero-inflated truncated Gaussian marginal. If None, a default constant-mean formula is used.

'~ 1'
sdev_formula str or None

Model formula for the standard deviation parameter of the zero-inflated truncated Gaussian marginal. If None, a default constant-sdev formula is used.

'~ 1'
zero_inflation_formula str or None

Model formula for the zero-inflation parameter. If None, a default constant-zero-inflation formula is used.

'~ 1'
copula_formula str or None

Copula formula describing how copula depends on experimental or biological conditions (e.g. "~ group"). If None, a default intercept-only formula is used.

'~ 1'
prior_alpha float

Alpha for Beta(alpha, alpha) prior on zero-inflation probabilities. Values > 1 discourage extreme π, improving generalization for sparse genes.

1.1
estimator CovarianceEstimator, str, or None

How to estimate each copula group's covariance. Supports "ledoit_wolf" and "oas" for regularized covariance estimation. If None, defaults to the sample covariance.

None
top_k int

Model correlation for only the top_k most highly expressed genes. The remaining are modeled independently. This can be used to simplify estimation in high-dimensional settings.

None
See Also

:class:SCD3Simulator :class:ZeroInflatedTruncatedGaussian :class:StandardCopula

Source code in scdesigner/src/scdesigner/simulators/scd3.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
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
class ZeroInflatedTruncatedGaussianCopula(SCD3Simulator):
    """Simulator using zero-inflated truncated Gaussian marginals with a Gaussian copula.

    The marginal is a mixture of a point mass at zero and a Gaussian
    component truncated to the positive half-line, appropriate for
    nonnegative data.

    Parameters
    ----------
    mean_formula : str or None, optional
        Model formula for the latent (pre-truncation) Gaussian-component
        mean of the zero-inflated truncated Gaussian marginal. If ``None``,
        a default constant-mean formula is used.
    sdev_formula : str or None, optional
        Model formula for the standard deviation parameter of the
        zero-inflated truncated Gaussian marginal. If ``None``, a default
        constant-sdev formula is used.
    zero_inflation_formula : str or None, optional
        Model formula for the zero-inflation parameter. If ``None``, a
        default constant-zero-inflation formula is used.
    copula_formula : str or None, optional
        Copula formula describing how copula depends on experimental or
        biological conditions (e.g. ``"~ group"``). If ``None``, a default
        intercept-only formula is used.
    prior_alpha : float, default=1.1
        Alpha for Beta(alpha, alpha) prior on zero-inflation probabilities.
        Values > 1 discourage extreme π, improving generalization for sparse genes.
    estimator : CovarianceEstimator, str, or None, optional
        How to estimate each copula group's covariance. Supports "ledoit_wolf"
        and "oas" for regularized covariance estimation. If None, defaults to
        the sample covariance.
    top_k : int, optional
        Model correlation for only the ``top_k`` most highly expressed genes.
        The remaining are modeled independently. This can be used to simplify
        estimation in high-dimensional settings.

    See Also
    --------
    :class:`SCD3Simulator`
    :class:`ZeroInflatedTruncatedGaussian`
    :class:`StandardCopula`
    """

    def __init__(
        self,
        mean_formula: Optional[str] = "~ 1",
        sdev_formula: Optional[str] = "~ 1",
        zero_inflation_formula: Optional[str] = "~ 1",
        copula_formula: Optional[str] = "~ 1",
        prior_alpha: float = 1.1,
        estimator=None,
        top_k: Optional[int] = None,
        device: Optional[torch.device | str] = None,
    ) -> None:
        marginal = ZeroInflatedTruncatedGaussian(
            {
                "mean": mean_formula,
                "sdev": sdev_formula,
                "zero_inflation": zero_inflation_formula,
            },
            prior_alpha=prior_alpha,
            device=device,
        )
        copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
        super().__init__(marginal, copula)

PenalizedBernoulliCopula(mean_formula='~ 1', copula_formula='~ 1', *, penalties=(), estimator=None, top_k=None, device=None)

A Bernoulli copula simulator with user-specified coefficient penalties.

Parameters:

Name Type Description Default
mean_formula str

Formula for the logit of the success probability.

'~ 1'
copula_formula str
'~ 1'
penalties sequence of CoefficientPenalty

See :mod:scdesigner.distributions.penalties.

()
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None

Examples:

>>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
>>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
>>> sim = PenalizedBernoulliCopula("~ x", penalties=[penalty])
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def PenalizedBernoulliCopula(
    mean_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    penalties: Sequence[CoefficientPenalty] = (),
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
) -> SCD3Simulator:
    """A Bernoulli copula simulator with user-specified coefficient penalties.

    Parameters
    ----------
    mean_formula : str
        Formula for the logit of the success probability.
    copula_formula : str
    penalties : sequence of CoefficientPenalty
        See :mod:`scdesigner.distributions.penalties`.
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.

    Examples
    --------
    >>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
    >>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
    >>> sim = PenalizedBernoulliCopula("~ x", penalties=[penalty])
    >>> sim.fit(adata)  # doctest: +SKIP
    """
    marginal = PenalizedBernoulli({"mean": mean_formula}, penalties=penalties, device=device)
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return SCD3Simulator(marginal, copula)

PenalizedNegBinCopula(mean_formula='~ 1', dispersion_formula='~ 1', copula_formula='~ 1', *, penalties=(), cap_at_observed_max=True, estimator=None, top_k=None, device=None)

A regularized negative binomial simulator

The simulator is well-suited to count data with many covariates relative to the number of cells.

Parameters:

Name Type Description Default
mean_formula str
'~ 1'
dispersion_formula str
'~ 1'
copula_formula str
'~ 1'
penalties sequence of CoefficientPenalty

See :mod:scdesigner.distributions.penalties.

()
cap_at_observed_max bool

Cap samples with :class:~scdesigner.simulators.output.ObservedMaxCap.

True
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None

Examples:

>>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
>>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
>>> sim = PenalizedNegBinCopula("~ x", penalties=[penalty])
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
311
312
313
314
315
316
317
318
319
320
321
322
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
def PenalizedNegBinCopula(
    mean_formula: str = "~ 1",
    dispersion_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    penalties: Sequence[CoefficientPenalty] = (),
    cap_at_observed_max: bool = True,
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
) -> SCD3Simulator:
    """A regularized negative binomial simulator

    The simulator is well-suited to count data with many covariates relative to
    the number of cells.

    Parameters
    ----------
    mean_formula, dispersion_formula, copula_formula : str
    penalties : sequence of CoefficientPenalty
        See :mod:`scdesigner.distributions.penalties`.
    cap_at_observed_max : bool
        Cap samples with :class:`~scdesigner.simulators.output.ObservedMaxCap`.
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.

    Examples
    --------
    >>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
    >>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
    >>> sim = PenalizedNegBinCopula("~ x", penalties=[penalty])
    >>> sim.fit(adata)  # doctest: +SKIP
    """
    marginal = PenalizedNegBin(
        {"mean": mean_formula, "dispersion": dispersion_formula},
        penalties=penalties,
        device=device,
    )
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return SCD3Simulator(
        marginal,
        copula,
        output_transform=ObservedMaxCap() if cap_at_observed_max else None,
    )

PenalizedZeroInflatedTruncatedGaussianCopula(mean_formula='~ 1', sdev_formula='~ 1', zero_inflation_formula='~ 1', copula_formula='~ 1', *, penalties=(), prior_alpha=1.1, cap_at_observed_max=False, estimator=None, top_k=None, device=None)

A regularized zero-inflated truncated Gaussian model

This can be used for nonnegative continuous data and when there are many covariates relative to the number of cells.

Parameters:

Name Type Description Default
mean_formula str
'~ 1'
sdev_formula str
'~ 1'
zero_inflation_formula str
'~ 1'
copula_formula str
'~ 1'
penalties sequence of CoefficientPenalty

See :mod:scdesigner.distributions.penalties.

()
prior_alpha float

See :class:ZeroInflatedTruncatedGaussian.

1.1
cap_at_observed_max bool

Cap samples with :class:~scdesigner.simulators.output.ObservedMaxCap.

False
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None

Examples:

>>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
>>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
>>> sim = PenalizedZeroInflatedTruncatedGaussianCopula("~ x", penalties=[penalty])
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def PenalizedZeroInflatedTruncatedGaussianCopula(
    mean_formula: str = "~ 1",
    sdev_formula: str = "~ 1",
    zero_inflation_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    penalties: Sequence[CoefficientPenalty] = (),
    prior_alpha: float = 1.1,
    cap_at_observed_max: bool = False,
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
) -> SCD3Simulator:
    """A regularized zero-inflated truncated Gaussian model

    This can be used for nonnegative continuous data and when there are many
    covariates relative to the number of cells.

    Parameters
    ----------
    mean_formula, sdev_formula, zero_inflation_formula, copula_formula : str
    penalties : sequence of CoefficientPenalty
        See :mod:`scdesigner.distributions.penalties`.
    prior_alpha : float
        See :class:`ZeroInflatedTruncatedGaussian`.
    cap_at_observed_max : bool
        Cap samples with :class:`~scdesigner.simulators.output.ObservedMaxCap`.
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.

    Examples
    --------
    >>> from scdesigner.distributions.penalties import CoefficientPenalty, QuadraticPenalty
    >>> penalty = CoefficientPenalty("mean", ["x"], [1.0], QuadraticPenalty(lam=0.1))
    >>> sim = PenalizedZeroInflatedTruncatedGaussianCopula("~ x", penalties=[penalty])
    >>> sim.fit(adata)  # doctest: +SKIP
    """
    marginal = PenalizedZeroInflatedTruncatedGaussian(
        {"mean": mean_formula, "sdev": sdev_formula, "zero_inflation": zero_inflation_formula},
        prior_alpha=prior_alpha,
        penalties=penalties,
        device=device,
    )
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return SCD3Simulator(
        marginal,
        copula,
        output_transform=ObservedMaxCap() if cap_at_observed_max else None,
    )

SpatialBernoulliCopula(mean_formula='~ 1', copula_formula='~ 1', *, mean_df=15, basis='gp', standardize=True, lam=1.0, spatial_cols=('spatial1', 'spatial2'), estimator=None, top_k=None, device=None, **basis_kwargs)

A Bernoulli simulator with a penalized spatial logit of success probability.

Parameters:

Name Type Description Default
mean_formula str

Nonspatial part of the logit formula.

'~ 1'
copula_formula str
'~ 1'
mean_df int

Number of spatial basis columns.

15
basis (gp, tps)
"gp"
standardize bool

Rescale basis columns by their training standard deviations.

True
lam float

Strength of the inverse-mean-weighted quadratic penalty; see :mod:scdesigner.distributions.penalties.

1.0
spatial_cols tuple of str

Coordinate columns in adata.obs.

('spatial1', 'spatial2')
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None
**basis_kwargs

Passed to the basis, e.g. n_landmarks or length_scale.

{}

Examples:

>>> sim = SpatialBernoulliCopula("~ 0 + cell_type", basis="tps")
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
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
def SpatialBernoulliCopula(
    mean_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    mean_df: int = 15,
    basis: str = "gp",
    standardize: bool = True,
    lam: float = 1.0,
    spatial_cols: Tuple[str, str] = ("spatial1", "spatial2"),
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
    **basis_kwargs,
) -> SCD3Simulator:
    """A Bernoulli simulator with a penalized spatial logit of success probability.

    Parameters
    ----------
    mean_formula : str
        Nonspatial part of the logit formula.
    copula_formula : str
    mean_df : int
        Number of spatial basis columns.
    basis : {"gp", "tps"}
    standardize : bool
        Rescale basis columns by their training standard deviations.
    lam : float
        Strength of the inverse-mean-weighted quadratic penalty; see
        :mod:`scdesigner.distributions.penalties`.
    spatial_cols : tuple of str
        Coordinate columns in ``adata.obs``.
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.
    **basis_kwargs
        Passed to the basis, e.g. ``n_landmarks`` or ``length_scale``.

    Examples
    --------
    >>> sim = SpatialBernoulliCopula("~ 0 + cell_type", basis="tps")
    >>> sim.fit(adata)  # doctest: +SKIP
    """
    terms = {"mean": SpatialTerm(
        BASES[basis](df=mean_df, standardize=standardize, **basis_kwargs),
        QuadraticPenalty(lam=lam, weighting="inverse_mean"),
    )}
    marginal = Bernoulli({"mean": mean_formula}, device=device)
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return spatial_copula(marginal, terms, copula=copula, spatial_cols=spatial_cols)

SpatialNegBinCopula(mean_formula='~ 1', dispersion_formula='~ 1', copula_formula='~ 1', *, mean_df=100, disp_df=None, basis='gp', standardize=True, lam=1.0, lam_disp=1.0, spatial_cols=('spatial1', 'spatial2'), cap_at_observed_max=True, estimator=None, top_k=None, device=None, **basis_kwargs)

A negative binomial simulator suited to spatial data

This is a convenience wrapper of spatial_copula specialized to negative binomial marginal models. It automatically constructs the design matrix and applies regularization terms in a way that suits spatial count data.

Internally, we construct SpatialTerm(basis(df, standardize, **basis_kwargs), QuadraticPenalty(lam, "inverse_mean")) objects, which are then fed in to :func:spatial_copula.

We do not use a Poisson IRLS initialization for spatial models. This is because the spatial basis greatly increases the problem dimension, which destabilizes ordinary regression fits. To use this initialization, you may set max_iter larger than zero in your call to :meth:fit.

Parameters:

Name Type Description Default
mean_formula str

Nonspatial part of each parameter's formula.

'~ 1'
dispersion_formula str

Nonspatial part of each parameter's formula.

'~ 1'
copula_formula str
'~ 1'
mean_df int

Level of complexity for the mean and dispersion functions. Larger df corresponds to higher complexity. Setting disp_df=None means that the dispersion does not depend on the spatial coordinate.

100
disp_df int

Level of complexity for the mean and dispersion functions. Larger df corresponds to higher complexity. Setting disp_df=None means that the dispersion does not depend on the spatial coordinate.

100
basis (gp, tps)

Whether to use a Gaussian process (:class:GPBasis) or thin-plate spline (:class:TPSBasis) basis for the mean and (optionally) dispersion parameters

"gp"
standardize bool
True
lam float

Penalty strength for the mean and dispersion terms.

1.0
lam_disp float

Penalty strength for the mean and dispersion terms.

1.0
spatial_cols tuple of str
('spatial1', 'spatial2')
cap_at_observed_max bool
True
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None
**basis_kwargs

Passed to both bases, e.g. n_landmarks or length_fraction.

{}

Examples:

>>> sim = SpatialNegBinCopula("~ 0 + cell_type", basis="tps", disp_df=5)
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
 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
def SpatialNegBinCopula(
    mean_formula: str = "~ 1",
    dispersion_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    mean_df: int = 100,
    disp_df: Optional[int] = None,
    basis: str = "gp",
    standardize: bool = True,
    lam: float = 1.0,
    lam_disp: float = 1.0,
    spatial_cols: Tuple[str, str] = ("spatial1", "spatial2"),
    cap_at_observed_max: bool = True,
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
    **basis_kwargs,
) -> SCD3Simulator:
    """A negative binomial simulator suited to spatial data

    This is a convenience wrapper of `spatial_copula` specialized to negative
    binomial marginal models. It automatically constructs the design matrix and
    applies regularization terms in a way that suits spatial count data.

    Internally, we construct ``SpatialTerm(basis(df, standardize,
    **basis_kwargs), QuadraticPenalty(lam, "inverse_mean"))`` objects, which are
    then fed in to :func:`spatial_copula`.

    We do not use a Poisson IRLS initialization for spatial models. This is
    because the spatial basis greatly increases the problem dimension, which
    destabilizes ordinary regression fits. To use this initialization, you may
    set ``max_iter`` larger than zero in your call to :meth:`fit`.

    Parameters
    ----------
    mean_formula, dispersion_formula : str
        Nonspatial part of each parameter's formula.
    copula_formula : str
    mean_df, disp_df : int
        Level of complexity for the mean and dispersion functions. Larger ``df``
        corresponds to higher complexity.  Setting ``disp_df=None`` means that
        the dispersion does not depend on the spatial coordinate.
    basis : {"gp", "tps"}
       Whether to use a Gaussian process  (:class:`GPBasis`) or thin-plate
       spline (:class:`TPSBasis`) basis for the mean and (optionally) dispersion
       parameters
    standardize : bool
    lam, lam_disp : float
        Penalty strength for the mean and dispersion terms.
    spatial_cols : tuple of str
    cap_at_observed_max : bool
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.
    **basis_kwargs
        Passed to both bases, e.g. ``n_landmarks`` or ``length_fraction``.

    Examples
    --------
    >>> sim = SpatialNegBinCopula("~ 0 + cell_type", basis="tps", disp_df=5)
    >>> sim.fit(adata)  # doctest: +SKIP
    """

    def term(df, strength):
        return SpatialTerm(
            BASES[basis](df=df, standardize=standardize, **basis_kwargs),
            QuadraticPenalty(lam=strength, weighting="inverse_mean"),
        )

    terms = {"mean": term(mean_df, lam)}
    if disp_df is not None:
        terms["dispersion"] = term(disp_df, lam_disp)

    marginal = NegBin({"mean": mean_formula, "dispersion": dispersion_formula}, device=device)
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return spatial_copula(
        marginal,
        terms,
        copula=copula,
        spatial_cols=spatial_cols,
        cap_at_observed_max=cap_at_observed_max,
    )

SpatialZeroInflatedTruncatedGaussianCopula(mean_formula='~ 1', sdev_formula='~ 1', zero_inflation_formula='~ 1', copula_formula='~ 1', *, mean_df=100, sdev_df=None, zi_df=15, basis='gp', standardize=True, lam=1.0, lam_sdev=1.0, lam_zi=1.0, prior_alpha=1.1, spatial_cols=('spatial1', 'spatial2'), cap_at_observed_max=False, estimator=None, top_k=None, device=None, **basis_kwargs)

A zero-inflated truncated gaussian model for spatial data

This applies :func:spatial_copula to a :class:ZeroInflatedTruncatedGaussian marginal. It is appropriate for spatial modeling of already normalized data. The spatial coordinates can enter into the mean, dispersion, or zero-inflation parameters.

Parameters:

Name Type Description Default
mean_formula str

Nonspatial part of each parameter's formula.

'~ 1'
sdev_formula str

Nonspatial part of each parameter's formula.

'~ 1'
zero_inflation_formula str

Nonspatial part of each parameter's formula.

'~ 1'
copula_formula str
'~ 1'
mean_df int

Basis columns of the latent-mean term.

100
sdev_df int or None

Basis columns of the standard-deviation and zero-inflation terms; None omits the term. zi_df is set by default because zeros arise only from the zero-inflation probability.

None
zi_df int or None

Basis columns of the standard-deviation and zero-inflation terms; None omits the term. zi_df is set by default because zeros arise only from the zero-inflation probability.

None
basis (gp, tps)

:class:GPBasis or :class:TPSBasis, for every term.

"gp"
standardize bool

Divide basis columns by their training standard deviations.

True
lam float

Penalty strength of each term; see :mod:scdesigner.distributions.penalties.

1.0
lam_sdev float

Penalty strength of each term; see :mod:scdesigner.distributions.penalties.

1.0
lam_zi float

Penalty strength of each term; see :mod:scdesigner.distributions.penalties.

1.0
prior_alpha float

See :class:ZeroInflatedTruncatedGaussian.

1.1
spatial_cols tuple of str

Coordinate columns of adata.obs.

('spatial1', 'spatial2')
cap_at_observed_max bool

Cap samples with :class:~scdesigner.simulators.output.ObservedMaxCap.

False
estimator

Passed to :class:StandardCopula.

None
top_k

Passed to :class:StandardCopula.

None
device device or str

Marginal device.

None
**basis_kwargs

Passed to every basis, e.g. n_landmarks or length_fraction.

{}

Examples:

>>> from scdesigner import datasets
>>> sim = SpatialZeroInflatedTruncatedGaussianCopula(
...     spatial_cols=("UMAP1_integrated", "UMAP2_integrated"))
>>> sim.fit(datasets.scgemrna())
Source code in scdesigner/src/scdesigner/simulators/recipes.py
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
def SpatialZeroInflatedTruncatedGaussianCopula(
    mean_formula: str = "~ 1",
    sdev_formula: str = "~ 1",
    zero_inflation_formula: str = "~ 1",
    copula_formula: str = "~ 1",
    *,
    mean_df: int = 100,
    sdev_df: Optional[int] = None,
    zi_df: Optional[int] = 15,
    basis: str = "gp",
    standardize: bool = True,
    lam: float = 1.0,
    lam_sdev: float = 1.0,
    lam_zi: float = 1.0,
    prior_alpha: float = 1.1,
    spatial_cols: Tuple[str, str] = ("spatial1", "spatial2"),
    cap_at_observed_max: bool = False,
    estimator=None,
    top_k: Optional[int] = None,
    device=None,
    **basis_kwargs,
) -> SCD3Simulator:
    """A zero-inflated truncated gaussian model for spatial data

    This applies :func:`spatial_copula` to a
    :class:`ZeroInflatedTruncatedGaussian` marginal. It is appropriate for
    spatial modeling of already normalized data. The spatial coordinates can
    enter into the mean, dispersion, or zero-inflation parameters.

    Parameters
    ----------
    mean_formula, sdev_formula, zero_inflation_formula : str
        Nonspatial part of each parameter's formula.
    copula_formula : str
    mean_df : int
        Basis columns of the latent-mean term.
    sdev_df, zi_df : int or None
        Basis columns of the standard-deviation and zero-inflation terms;
        ``None`` omits the term. ``zi_df`` is set by default because zeros
        arise only from the zero-inflation probability.
    basis : {"gp", "tps"}
        :class:`GPBasis` or :class:`TPSBasis`, for every term.
    standardize : bool
        Divide basis columns by their training standard deviations.
    lam, lam_sdev, lam_zi : float
        Penalty strength of each term; see
        :mod:`scdesigner.distributions.penalties`.
    prior_alpha : float
        See :class:`ZeroInflatedTruncatedGaussian`.
    spatial_cols : tuple of str
        Coordinate columns of ``adata.obs``.
    cap_at_observed_max : bool
        Cap samples with :class:`~scdesigner.simulators.output.ObservedMaxCap`.
    estimator, top_k
        Passed to :class:`StandardCopula`.
    device : torch.device or str, optional
        Marginal device.
    **basis_kwargs
        Passed to every basis, e.g. ``n_landmarks`` or ``length_fraction``.

    Examples
    --------
    >>> from scdesigner import datasets
    >>> sim = SpatialZeroInflatedTruncatedGaussianCopula(
    ...     spatial_cols=("UMAP1_integrated", "UMAP2_integrated"))
    >>> sim.fit(datasets.scgemrna())  # doctest: +SKIP
    """

    def term(df, strength):
        return SpatialTerm(
            BASES[basis](df=df, standardize=standardize, **basis_kwargs),
            QuadraticPenalty(lam=strength, weighting="inverse_mean"),
        )

    terms = {"mean": term(mean_df, lam)}
    if sdev_df is not None:
        terms["sdev"] = term(sdev_df, lam_sdev)
    if zi_df is not None:
        terms["zero_inflation"] = term(zi_df, lam_zi)

    marginal = ZeroInflatedTruncatedGaussian(
        {"mean": mean_formula, "sdev": sdev_formula, "zero_inflation": zero_inflation_formula},
        prior_alpha=prior_alpha,
        device=device,
    )
    copula = StandardCopula(copula_formula, estimator=estimator, top_k=top_k)
    return spatial_copula(
        marginal,
        terms,
        copula=copula,
        spatial_cols=spatial_cols,
        cap_at_observed_max=cap_at_observed_max,
    )

spatial_copula(marginal, terms, *, copula=None, spatial_cols=('spatial1', 'spatial2'), cap_at_observed_max=False)

:class:SCD3Simulator with spatial basis columns added

This is a light wrapper of the SCD3Simulator that adds spatial design columns. Philosophically, we think of this as a part of a "recipe" approach to combining simulation properties. Earlier, we layered penalties onto the marginal model. At this step, we layer on spatial design matrices.

Parameters:

Name Type Description Default
marginal NegBin, Bernoulli, or ZeroInflatedTruncatedGaussian

Copied; its formula and penalties are the nonspatial base.

required
terms mapping of str to SpatialTerm

Term per marginal parameter; see :class:~scdesigner.data.spatial.SpatialDesign.

required
copula Copula

Copied. Defaults to StandardCopula("~ 1").

None
spatial_cols tuple of str
('spatial1', 'spatial2')
cap_at_observed_max bool

Cap samples with :class:~scdesigner.simulators.output.ObservedMaxCap. In earlier experiments, we found that this prevented extreme outliers that happen in high-dimensional negbin models. Must be False for Bernoulli marginals.

False

Examples:

>>> from scdesigner.data import GPBasis, SpatialTerm
>>> from scdesigner.distributions import NegBin
>>> from scdesigner.distributions.penalties import QuadraticPenalty
>>> term = SpatialTerm(GPBasis(df=15, standardize=True), QuadraticPenalty(lam=1.0))
>>> sim = spatial_copula(NegBin({"mean": "~ 1", "dispersion": "~ 1"}), {"mean": term})
>>> sim.fit(adata)
Source code in scdesigner/src/scdesigner/simulators/recipes.py
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
def spatial_copula(
    marginal: NegBin | Bernoulli | ZeroInflatedTruncatedGaussian,
    terms: Mapping[str, SpatialTerm],
    *,
    copula: Optional[Copula] = None,
    spatial_cols: Tuple[str, str] = ("spatial1", "spatial2"),
    cap_at_observed_max: bool = False,
) -> SCD3Simulator:
    """:class:`SCD3Simulator` with spatial basis columns added

    This is a light wrapper of the SCD3Simulator that adds spatial design
    columns. Philosophically, we think of this as a part of a "recipe" approach
    to combining simulation properties. Earlier, we layered penalties onto the
    marginal model. At this step, we layer on spatial design matrices.

    Parameters
    ----------
    marginal : NegBin, Bernoulli, or ZeroInflatedTruncatedGaussian
        Copied; its formula and penalties are the nonspatial base.
    terms : mapping of str to SpatialTerm
        Term per marginal parameter; see
        :class:`~scdesigner.data.spatial.SpatialDesign`.
    copula : Copula, optional
        Copied. Defaults to ``StandardCopula("~ 1")``.
    spatial_cols : tuple of str
    cap_at_observed_max : bool
        Cap samples with
        :class:`~scdesigner.simulators.output.ObservedMaxCap`. In earlier
        experiments, we found that this prevented extreme outliers that happen
        in high-dimensional negbin models. Must be False for Bernoulli marginals.

    Examples
    --------
    >>> from scdesigner.data import GPBasis, SpatialTerm
    >>> from scdesigner.distributions import NegBin
    >>> from scdesigner.distributions.penalties import QuadraticPenalty
    >>> term = SpatialTerm(GPBasis(df=15, standardize=True), QuadraticPenalty(lam=1.0))
    >>> sim = spatial_copula(NegBin({"mean": "~ 1", "dispersion": "~ 1"}), {"mean": term})
    >>> sim.fit(adata)  # doctest: +SKIP
    """
    if type(marginal) not in (NegBin, Bernoulli, ZeroInflatedTruncatedGaussian):
        raise NotImplementedError(
            "spatial_copula currently supports only NegBin, Bernoulli, and "
            "ZeroInflatedTruncatedGaussian marginals."
        )

    marginal = copy.deepcopy(marginal)
    copula = StandardCopula("~ 1") if copula is None else copy.deepcopy(copula)
    return SCD3Simulator(
        marginal,
        copula,
        observation_transform=SpatialDesign(marginal.formula, terms, spatial_cols),
        output_transform=ObservedMaxCap() if cap_at_observed_max else None,
    )