Skip to content

scd3

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)

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)

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)