# Pseudobulk differential expression

Pseudobulk aggregates cells from each biological sample before applying
bulk-RNA differential-expression methods. It is the recommended default for
condition-level inference from replicated single-cell experiments.

## Metadata requirements

At minimum, `adata.obs` should contain:

- a biological sample identifier;
- the condition;
- the cell type or population to test.

For paired data, retain a patient/subject column in the pseudobulk metadata.
Each condition should normally contain at least two biological replicates;
larger numbers are strongly preferable.

## Create pseudobulk profiles

```python
pb = sctk.tl.create_pseudobulk(
    adata,
    sample_key="sample",
    groupby="cell_type",
    layer="counts",
    mode="sum",
    min_cells=20,
    min_counts=1_000,
)
```

This creates one row per sample × cell-type combination. For backed or large
objects:

```python
pb = sctk.tl.create_pseudobulk(
    adata,
    sample_key="sample",
    groupby="cell_type",
    layer="counts",
    chunk_size=5_000,
)
```

Chunked aggregation currently supports sum aggregation only.

## Preserve sample metadata

Aggregation metadata must be available in the resulting `pb.obs`. If condition
or patient is not carried through by the backend, join it from a sample table:

```python
sample_metadata = (
    adata.obs[["sample", "condition", "patient"]]
    .drop_duplicates()
    .set_index("sample")
)

pb.obs["condition"] = pb.obs["sample"].map(sample_metadata["condition"])
pb.obs["patient"] = pb.obs["sample"].map(sample_metadata["patient"])
```

Verify that each sample maps to exactly one condition before this join.

## Review pseudobulk quality

```python
pb_qc = sctk.tl.pseudobulk_qc(
    pb,
    condition_key="condition",
    min_counts=10_000,
    min_detected_genes=200,
)

pb_qc.groupby("condition")["qc_pass"].agg(["sum", "count"])
```

This function reports decisions but does not remove samples. Investigate failed
profiles and condition imbalance before filtering.

## Select one population

DESeq2 expects rows to represent comparable samples. When pseudobulk contains
multiple cell types, analyze one cell type at a time:

```python
pb_t = pb[pb.obs["cell_type"] == "T_cell"].copy()
```

Do not include cell type as though each sample × cell-type profile were an
independent biological replicate unless the design explicitly models repeated
measurements.

## Unpaired DESeq2 design

```python
de, dds = sctk.tl.run_deseq2(
    pb_t,
    condition_key="condition",
    treatment="treated",
    control="control",
    design_factors=["condition"],
    min_replicates=2,
    min_total_count=10,
)
```

`log2FoldChange > 0` means higher expression in `treated` relative to `control`.

## Paired or blocked DESeq2 design

```python
de, dds = sctk.tl.run_deseq2(
    pb_t,
    condition_key="condition",
    treatment="treated",
    control="control",
    design_factors=["patient", "condition"],
)
```

Put the pairing/block variable before condition. The wrapper checks:

- raw non-negative integer counts;
- finite design metadata;
- presence of treatment and control;
- minimum biological replication;
- presence of an explicitly requested reference level.

## limma-voom

```python
de_voom, diagnostics = sctk.r.tl.run_voom(
    pb_t,
    design="~ 0 + condition",
    contrast="conditiontreated-conditioncontrol",
)
```

Blocked design:

```python
de_voom, diagnostics = sctk.r.tl.run_voom(
    pb_t,
    design="~ 0 + condition",
    contrast="conditiontreated-conditioncontrol",
    block_key="patient",
)
```

Inspect:

```python
diagnostics["design_columns"]
diagnostics["n_genes_tested"]
diagnostics["normalization_factors"]
diagnostics["library_sizes"]
diagnostics["consensus_correlation"]
```

## Plot and export

```python
ax = sctk.pl.volcano(
    de,
    pvalue="padj",
    logfc="log2FoldChange",
    top=15,
)

de.to_csv("T_cell_treated_vs_control.csv")
pb_qc.to_csv("T_cell_pseudobulk_qc.csv")
```

## Common mistakes

- Passing normalized or scaled expression; `sctk` now raises instead of rounding.
- Using cells as replicates.
- Combining multiple cell types without modeling repeated sample structure.
- Testing a condition with one biological sample.
- Using a paired design when subjects are not observed in both conditions.
- Filtering samples after looking at the desired DE result.
- Interpreting statistical significance without effect size and expression QC.
