# Jupyter Usage

For normal notebook work, use the conda environment.

## Recommended Setup

From the project root:

```bash
mamba env create -f environment.yml
mamba run -n sctk python -m ipykernel install --user --name sctk --display-name "Python (sctk)"
```

Then select the `Python (sctk)` kernel in Jupyter.

If mamba is unavailable:

```bash
conda env create -f environment.yml
```

## Notebook Import

```python
import sctk

sctk.pp.scanpy_preprocess(adata, counts_layer="counts")
pb = sctk.tl.create_pseudobulk(
    adata,
    sample_key="sample",
    groupby="cell_type",
    layer="counts",
)
```

R-backed functions use the same import, but they only load R 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_0.8",
)
```

For SoupX, `adata_raw` should contain the raw droplet matrix. Every filtered
barcode in `adata.obs_names` must occur in `adata_raw.obs_names`; the raw object
may—and normally will—contain many additional droplets.

Basic plotting helpers are available under `sctk.pl`:

```python
sctk.pl.set_colors(adata, "cell_type")
color_map = sctk.pl.get_colors(adata, "cell_type")
sctk.pl.embedding(adata, basis="umap", color=["cell_type", "sample"])
sctk.pl.dotplot(adata, marker_genes, groupby="cell_type", layer="log1p_norm")
sctk.pl.composition(adata, groupby="cell_type", splitby="sample")
sctk.pl.volcano(de_df)
sctk.pl.enrichment_dotplot(enrich_df)
sctk.pl.enrichment_barplot(enrich_df)
sctk.pl.plot_ora_bar(enrich_df, top_n=10, title="ORA")
sctk.pl.violinplot(adata, x="cell_type", y="MS4A1", layer="log1p_norm")
```

## Cached decoupler resources

```python
resource = sctk.tl.get_resource(
    "PanglaoDB",
    organism="human",
)

# Refresh the local Parquet cache.
resource = sctk.tl.get_resource(
    "PanglaoDB",
    organism="human",
    force=True,
)
```

Set `SCTK_CACHE_DIR` to move all sctk caches to a custom location.

`sctk.tl.run_ora()` uses the offline hypergeometric test provided by
`gseapy.enrich`. Supply all genes tested in the experiment through
`background`.

`sctk.tl.run_gsea()` uses multithreaded `gseapy.prerank`:

```python
gsea = sctk.tl.run_gsea(
    de_result["stat"],
    pathway_net,
    permutations=1000,
    threads=8,
)
```

`run_gsea()` accepts one ranking per call. Pass a `pandas.Series`, or pass a
DataFrame and select its single ranking column explicitly with `stat="stat"`.

## R Packages

Python and R dependencies are installed together by `environment.yml`.
`requirements-r.R` is kept only as a fallback for non-conda R installs.

```bash
Rscript requirements-r.R
```
