# QC and preprocessing

The recommended sequence is:

1. preserve counts;
2. calculate QC metrics;
3. inspect distributions by sample;
4. create a reviewable decision table;
5. annotate or filter cells;
6. normalize and construct the low-dimensional representation.

## Calculate metrics

```python
import sctk

sctk.pp.calculate_qc_metrics(
    adata,
    layer="counts",
    species="human",
)
```

This adds mitochondrial and ribosomal feature flags plus Scanpy-compatible
columns such as:

- `total_counts`;
- `n_genes_by_counts`;
- `pct_counts_mt`;
- `pct_counts_ribo`.

For mouse data use `species="mouse"`. Override `mito_prefix` or
`ribo_prefixes` when gene identifiers do not use standard symbols.

## Review sample-specific distributions

Library chemistry and sequencing depth often differ by sample. Prefer
sample-aware outlier detection when a valid sample column is available.

```python
adata.obs["counts_outlier"] = sctk.pp.is_outlier(
    adata,
    "total_counts",
    nmads=5,
    groupby="sample",
    log1p=True,
)
```

MAD rules are robust heuristics, not universal biological thresholds. Always
inspect violin/scatter plots and sample-level rejection rates.

## Build a QC decision table

```python
qc = sctk.pp.qc_filter_mask(
    adata,
    min_genes=200,
    max_pct_mito=20,
    outlier_metrics=["total_counts", "n_genes_by_counts"],
    nmads=5,
    groupby="sample",
)

qc["qc_pass"].value_counts()
qc.loc[~qc["qc_pass"], "qc_fail_reasons"].value_counts()
```

The table does not modify the AnnData object. Review it before filtering.

## Annotate or filter

Annotate without removing cells:

```python
sctk.pp.filter_cells_qc(
    adata,
    key_added="qc_pass",
    subset=False,
    min_genes=200,
    max_pct_mito=20,
    outlier_metrics=["total_counts", "n_genes_by_counts"],
    groupby="sample",
)
```

Return a filtered copy:

```python
adata_qc = sctk.pp.filter_cells_qc(
    adata,
    copy=True,
    subset=True,
    min_genes=200,
    max_pct_mito=20,
    outlier_metrics=["total_counts", "n_genes_by_counts"],
    groupby="sample",
)
```

Use `copy=True` in notebooks when you want to preserve the pre-filter object.

## Normalize only

```python
sctk.pp.normalize_layer(
    adata_qc,
    layer="counts",
    norm_layer="log1p_norm",
    target_sum=1e4,
)
```

By default this does not overwrite `.X`. Set
`overwrite_x="norm_layer"` only when a downstream Scanpy call requires the
working matrix in `.X`.

## Standard preprocessing

```python
sctk.pp.scanpy_preprocess(
    adata_qc,
    counts_layer="counts",
    normalized_layer="log1p_norm",
    hvg_flavor="seurat_v3",
    batch_key="sample",
    n_top_genes=3000,
    run_pca=True,
    run_neighbors=True,
    run_umap=True,
)
```

`seurat_v3` HVG selection uses raw counts. The function validates the counts
layer before running. If you want to stop after normalization/HVG selection,
disable the downstream stages explicitly:

```python
sctk.pp.scanpy_preprocess(
    adata_qc,
    run_pca=False,
    run_neighbors=False,
    run_umap=False,
)
```

## Cell cycle and clustering

```python
sctk.pp.score_cell_cycle(
    adata_qc,
    species="human",
    layer="log1p_norm",
)

cluster_keys = sctk.pp.leiden_grid(
    adata_qc,
    start=0.2,
    stop=1.2,
    step=0.2,
    n_jobs=-1,
)

scores = sctk.pp.silhouette_by_resolution(
    adata_qc,
    key_prefix="leiden",
    obsm_key="X_pca",
)
```

Silhouette score is only one diagnostic. Select a resolution using marker
coherence, stability, interpretability, and expected biological granularity.

## Common mistakes

- Creating `counts` from an already log-transformed `.X`.
- Applying one hard QC threshold across incompatible chemistries.
- Filtering before reviewing rejection by sample or condition.
- Scaling counts before pseudobulk or scVI.
- Treating a high silhouette score as proof that clusters are biologically real.
