Python API¶
Everything the app does to a dataset goes through one Python class, DataAdaptor, in the skopia package. You can use it directly from Python: the notebooks Skopia exports do exactly that for steps labeled skopia. This page covers what those notebooks rely on and how to use the same calls in your own scripts.
Not yet a stable API
The Python API is not declared stable. Skopia follows semantic versioning, and before 1.0 a breaking change can arrive in any minor release (0.7 to 0.8); the changelog marks those entries Breaking:. Version 1.0 will be declared when the saved-file layout and the Python API are meant to stay put. Pin the Skopia version a notebook was exported with (its header and metadata name it) if you need it to keep running. See Versioning and releases.
Install and import¶
The package lives in the repository's backend/ folder and is installed in Skopia's pixi environments. From the repository root:
Outside pixi, pip install -e backend in a Python 3.10+ environment installs it. Jupyter is not part of Skopia's environments; add it to run an exported notebook.
Create an adaptor¶
DataAdaptor(filepath, *, adata=None) reads an .h5ad, a 10x .h5, a 10x matrix folder, or the *_matrix.mtx(.gz) file of a prefixed 10x file trio. Passing adata= wraps an AnnData you already have and skips reading the file; filepath is then used only as the recorded source and for display:
adata = sc.read_h5ad("data.h5ad")
xa = DataAdaptor("data.h5ad", adata=adata) # what an exported notebook does
The adaptor works on that object in place: xa.adata is adata. On construction it:
- renames
unskeys written by Skopia's earlier name (xcell_*toskopia_*), - turns columns listed in
uns['skopia_string_columns']back into string columns and drops that record, - restores drawn lines, text labels and the analysis record from
uns, and records a load step, - copies
.Xtolayers['counts']when.Xlooks like integer counts and nocountslayer exists.
See What Skopia writes to AnnData for every key involved.
How an exported notebook uses it¶
A notebook's first code cell loads the data, then, when any step needs Skopia, sets up the adaptor and two helpers:
SOURCE_PATH = 'data.h5ad'
adata = sc.read_h5ad(SOURCE_PATH)
import inspect
from skopia.adaptor import DataAdaptor
xa = DataAdaptor(SOURCE_PATH, adata=adata)
def _skopia_run(prepared):
"""Drive one of skopia's two-phase (prepare_*) operations to completion."""
compute, apply = prepared
# A compute_fn taking one argument is opting into progress reporting.
needs_report = bool(inspect.signature(compute).parameters)
return apply(compute(lambda *a, **k: None) if needs_report else compute())
Each skopia step is then one call with the parameters the session recorded, for example:
xa.run_leiden(resolution=0.5, key_added='leiden_chondro', cell_subset='chondro')
_skopia_run(xa.prepare_cnv(key='cnv', reference_column='celltype', reference_categories=['T cell']))
xa.run_marker_genes(obs_column='leiden', top_n=25, active_cell_indices=SELECTIONS['step_7'])
SELECTIONS is read from the <name>_selections.json file written beside the notebook; see Analysis record and notebook export.
Two kinds of method¶
Direct methods (run_*, create_*, update_*) do the work and return a JSON-serializable dict describing the result.
Two-phase methods (prepare_*) are the long-running operations the app runs in the background. They validate their arguments at once (raising ValueError on bad input) and return a pair (compute_fn, apply_fn):
compute_fn()does the computation without changing the AnnData. If it takes one argument, it accepts a progress callbackreport(fraction, message).apply_fn(result)writes the result intoxa.adataand returns the summary dict.
_skopia_run above is the simplest driver: apply(compute()).
Methods exported notebooks call¶
| Method | Kind | What it does |
|---|---|---|
run_highly_variable_genes, run_pca, run_neighbors, run_umap, run_leiden |
direct | The clustering chain. Each takes cell_subset=<name> to run on a named subset and write to suffixed keys. |
run_diffmap, run_dpt |
direct | Diffusion map and diffusion pseudotime on any graph. |
run_smooth |
direct | Graph smoothing into a layer (default smoothed). |
run_marker_genes |
direct | One-vs-rest marker genes; stores the ranking in uns['skopia_marker_genes']. |
run_gene_neighbors, run_gene_pca, run_cluster_genes |
direct | Gene-side analyses. |
run_overlap_enrichment, run_overlap_enrichment_batch |
direct | Overlap (ORA) enrichment. |
sum_counts_by_species |
direct | Per-species count sums for multi-genome data. |
create_cell_subset, delete_cell_subset, create_pca_subset |
direct | Named subsets and PC subsets. |
prepare_gsea, prepare_gsea_batch |
two-phase | Preranked GSEA. |
prepare_cnv |
two-phase | Copy-number inference. |
prepare_pyscn_classify, prepare_pyscn_train |
two-phase | Cell typing with PySingleCellNet (optional dependency). |
prepare_stemfinder |
two-phase | Differentiation scores with PyStemFinder (optional dependency). |
prepare_contourize, finalize_multicontour, prepare_ligrec, prepare_neighborhood |
two-phase / direct | Spatial tools. |
prepare_gene_nmf, prepare_meta_programs, prepare_gene_set_decomposition, prepare_gene_map, prepare_cluster_cells_by_gene_set |
two-phase | Gene programs and gene-set analyses. |
create_figure, update_figure, delete_figure, figure_data |
direct | Figure records (below). |
Signatures change between releases; read them with help(xa.run_leiden) in the version you have.
Figures¶
Figure records are stored in uns['skopia_figures'] and can be listed, read and rendered as data:
for f in xa.list_figures():
print(f['id'], f['kind'], f['title'])
record = xa.get_figure('fig_3') # kind, inputs, params, provenance
table = xa.figure_data('fig_3') # the plotted table or graph, as a dict
# an enrichment heatmap with a different Top N, previewed without saving or recording
preview = xa.figure_data('fig_3', params_override={'top_n': 10})
figure_data raises an error naming the missing input when a figure's input result was deleted or re-made. An exported notebook replays each figure step with create_figure(...) followed by fig_data = xa.figure_data(...); because the replay can number figures differently, it maps each recorded id to the new one through a small _skopia_fig lookup.
Save the result¶
Write the dataset the way the app's Save does, so it carries the analysis record, the build stamp and the string-column record:
prepare_export_with_lines() returns a copy of xa.adata with those additions and with each drawn line's cell projections in .obsm['X_<line>_projection']. Writing xa.adata directly also works, but string .obs columns come back as categoricals and the record is not included.
Errors¶
Methods raise ValueError for invalid arguments (the app shows these as a 400) and KeyError for a name that does not exist, such as a column, figure or subset (a 404). An optional dependency that is not installed raises ValueError with install instructions.