# API Overview

This is the recommended notebook flow for the rebuilt `sctk` API.

## Preprocess

```python
import scanpy as sc
import sctk

sctk.pp.calculate_qc_metrics(adata, layer="counts", species="human")
qc = sctk.pp.qc_filter_mask(
    adata,
    groupby="sample",
    outlier_metrics=["total_counts", "n_genes_by_counts"],
)

sctk.pp.normalize_layer(adata, layer="counts", norm_layer="log1p_norm")
sctk.pp.scanpy_preprocess(adata, counts_layer="counts", normalized_layer="log1p_norm")
sctk.pp.leiden_grid(adata, start=0.2, stop=1.2, step=0.2, n_jobs=-1)
sctk.pp.score_cell_cycle(adata, species="human", layer="log1p_norm")
```

## Analyze

```python
markers = sctk.tl.markers_in_data(adata, marker_dict)
mean_expr = sctk.tl.grouped_obs_mean(adata, groupby="cell_type", layer="log1p_norm")

# Provisional marker-based labels with an explicit ambiguity margin.
annotation = sctk.tl.annotate_by_markers(
    adata,
    marker_dict,
    layer="log1p_norm",
    method="scanpy",
    min_genes=3,
    min_margin=0.1,
    inplace=False,
)

sample_detection = sctk.tl.grouped_gene_detection_rate(
    adata,
    "CA12",
    groupby="sample",
    layer="counts",
)
sample_groups, thresholds = sctk.tl.split_groups_by_fraction(
    sample_detection["positive_fraction"],
    method="tertile",
)

# Zero-inflated expression split, checked within each biological sample.
sctk.tl.split_cells_by_gene(
    adata,
    "CA12",
    layer="counts",
    method="detected",
    groupby="tumor_id",
    min_cells_per_group=25,
    drop_invalid_groups=True,
)

# For a bimodal continuous score, Otsu or GMM are also available.
sctk.tl.split_cells_by_gene(
    adata,
    "state_score",
    method="otsu",
    groupby="tumor_id",
    min_cells_per_group=25,
)

pb = sctk.tl.create_pseudobulk(
    adata,
    sample_key="sample",
    groupby="cell_type",
    layer="counts",
    chunk_size=5000,  # useful for backed or very large AnnData objects
)
pb_qc = sctk.tl.pseudobulk_qc(pb, condition_key="condition")

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

`run_deseq2()` reports the treatment/control contrast. For paired analyses,
place the pairing variable before the condition in `design_factors`.

## Enrich

```python
# Cached OmniPath/decoupler resource. The second call reads local Parquet.
panglao = sctk.tl.get_resource(
    "PanglaoDB",
    organism="human",
)

# Ignore an existing cache and fetch the resource again.
panglao_refreshed = sctk.tl.get_resource(
    "PanglaoDB",
    organism="human",
    force=True,
)

net = sctk.tl.read_gmt("pathways.gmt")

# Offline hypergeometric ORA with gseapy.enrich.
ora = sctk.tl.run_ora(
    ["ISG15", "IFIT1"],
    net,
    background=all_tested_genes,
)

# Preranked GSEA with gseapy.prerank.
gsea = sctk.tl.run_gsea(
    de["stat"],
    net,
    min_size=15,
    max_size=500,
    permutations=1000,
    threads=8,
)
```

`run_gsea()` accepts one ranking per call. A DataFrame input requires `stat=`
to identify the single ranking column.

Resource caches are stored as Parquet under
`$SCTK_CACHE_DIR/resources`, `$XDG_CACHE_HOME/sctk/resources`, or
`~/.cache/sctk/resources`. Cache files are separated by resource name,
organism, and license.

## Plot

```python
sctk.pl.set_colors(adata, "cell_type")
sctk.pl.embedding(adata, basis="umap", color=["cell_type", "sample"])
sctk.pl.composition(adata, groupby="cell_type", splitby="sample")
sctk.pl.volcano(de)
sctk.pl.enrichment_dotplot(ora)
sctk.pl.plot_ora_bar(ora, top_n=10, title="ORA")
```

## R-backed Tools

R-backed tools live under `sctk.r` and load R only when called.

```python
sctk.r.pp.scdblfinder(adata, layer="counts", batch_key="sample")
sctk.r.pp.remove_ambient(
    adata,
    adata_raw,
    layer="counts",
    raw_layer="counts",
    cluster_key="leiden",
)

de, diagnostics = sctk.r.tl.run_voom(
    pb,
    design="~ 0 + condition",
    contrast="conditiontreated-conditioncontrol",
    block_key="sample_pair",
)
```

## Integrate and benchmark

```python
sctk.pp.harmony_integrate(
    adata,
    key="sample",
    basis="X_pca",
    adjusted_basis="X_pca_harmony",
)
sc.pp.neighbors(adata, use_rep="X_pca_harmony")

metrics = sctk.tl.integration_metrics(
    adata,
    batch_key="sample",
    label_key="cell_type",
    basis="X_pca_harmony",
)
```

Optional scVI integration is available through `sctk.pp.scvi_integrate()`.
It requires raw counts and the `sctk[integration]` extra.

## Cell-cell communication

```python
liana_res = sctk.tl.run_liana(
    adata,
    groupby="cell_type",
    layer="log1p_norm",
    use_raw=False,
)
edges = sctk.tl.summarize_interactions(liana_res)
```

LIANA is optional and installed with `sctk[ccc]`. Its input should be
natural-log normalized expression rather than raw counts or scaled values.
