API 参考¶
包入口¶
AnnData-native tools for spatial perturbation analysis.
- class spatialperturb.PanelSpec(panel_id, figure_id, label, width_mm, height_mm, output_formats=('pdf', 'png', 'svg'), dpi=300, rasterize_dense=True, source_data_required=True, metadata=<factory>)[source]¶
Publication panel output contract.
- exception spatialperturb.SpatialPerturbSchemaError[source]¶
Raised when an AnnData object does not satisfy the SpatialPerturb schema.
- spatialperturb.aggregate_program_scores(adata, score_key, *, groupby)[source]¶
Aggregate per-cell program scores into a tidy long table.
- Return type:
DataFrame
- spatialperturb.assign_perturbations(adata, *, barcode_columns=None, barcode_prefix=None, barcode_to_perturbation=None, min_counts=1.0, negative_label='unassigned', multiple_label='multiple', perturbation_col='perturbation', status_col='perturbation_status', include_col='include_for_inference', copy=False)[source]¶
Assign a perturbation label to each cell from barcode feature counts.
- Return type:
AnnData
- spatialperturb.available_benchmarks()[source]¶
Return available benchmark tracks and their required inputs.
- Return type:
DataFrame
- spatialperturb.available_datasets()[source]¶
Return the bundled dataset catalog.
- Return type:
DataFrame
- spatialperturb.bootstrap_program_score_intervals(adata, score_key='program_scores', *, groupby=('cell_type', 'roi'), n_bootstrap=200, min_cells=50, seed=0)[source]¶
Estimate bootstrap confidence intervals for grouped program means.
- Return type:
DataFrame
- spatialperturb.build_reference_programs(adata, *, control='control', groupby=None, perturbation_col='perturbation', status_col='perturbation_status', method='auto', sample_col=None, covariates=None, top_n=50, direction='both', min_cells_per_group=2, min_samples_per_group=2, effect_size_only=False, cell_type=None, roi=None, return_de_results=False)[source]¶
Build per-perturbation reference programs from a Perturb-seq AnnData object.
- Return type:
dict[str,list[str]] |tuple[dict[str,list[str]],DataFrame]
- spatialperturb.build_signature_matrix(programs)[source]¶
Convert a program-to-gene mapping into a binary membership matrix.
- Return type:
DataFrame
- spatialperturb.build_spatial_graph(adata, *, mode='knn', k=15, radius=None, spatial_key='spatial', graph_key=None, include_self=False, copy=False)[source]¶
Construct a spatial neighbor graph and store it in
adata.obsp.- Return type:
AnnData
- spatialperturb.calibrate_program_scores(adata, programs=None, *, score_key='program_scores', groupby=('cell_type', 'roi'), n_random=100, n_label_shuffles=None, n_bins=20, min_cells=50, seed=0, layer=None, return_nulls=False)[source]¶
Calibrate grouped program scores with expression-matched and label-shuffle nulls.
The returned table keeps every group, but marks groups with fewer than
min_cellsas exploratory so downstream reports do not overclaim tiny ROIs.- Return type:
DataFrame|tuple[DataFrame,DataFrame]
- spatialperturb.collect_neighbors(adata, *, cells=None, graph_key=None, exclude_perturbed=True, status_col='perturbation_status', include_self=False, as_frame=False)[source]¶
Collect neighbors for a set of cells from a stored spatial graph.
- Return type:
dict[str,list[str]] |DataFrame
- spatialperturb.compare_program_concordance(left, right)[source]¶
Compare program definitions or program scores across two inputs.
- Return type:
DataFrame
- spatialperturb.dense_spatial_scatter(ax, coords, *, values=None, threshold=50000, force_rasterized=None, **kwargs)[source]¶
Scatter spatial points with automatic rasterization for dense point clouds.
- Return type:
PathCollection
- spatialperturb.derive_perturbation_programs(de_results, *, group_col='perturbation', gene_col='gene', score_col='log2fc', top_n=50, direction='both')[source]¶
Derive per-perturbation programs from a tidy DE table.
- Return type:
dict[str,list[str]]
- spatialperturb.differential_lr(adata, *, perturbation, control, graph_key=None, lr_network=None, groupby='perturbation', status_col='perturbation_status', source_groupby=None, target_groupby=None, layer=None, cell_type=None, roi=None)[source]¶
Score ligand-receptor interactions between perturbed cells and their neighbors.
- Return type:
DataFrame
- spatialperturb.ensure_spatialperturb_schema(adata, *, metadata=None, copy=False)[source]¶
Ensure required schema fields exist, filling defaults when needed.
- Return type:
AnnData
- spatialperturb.fetch_dataset(name, *, cache_dir, force=False)[source]¶
Download and cache the raw public files for a registered dataset.
- Return type:
dict[str,Any]
- spatialperturb.from_tables(expression, *, obs=None, var=None, spatial=None, layers=None, metadata=None)[source]¶
Build a schema-compliant AnnData object from tabular inputs.
- Return type:
AnnData
- spatialperturb.intrinsic_de(adata, *, perturbation, control, groupby='perturbation', status_col='perturbation_status', features=None, layer=None, cell_type=None, roi=None, min_cells_per_group=2, min_samples_per_group=2, method='simple', sample_col=None, covariates=None, effect_size_only=False, min_cells=None)[source]¶
Compare perturbed cells against control cells in the same ROI/cell type context.
- Return type:
DataFrame
- spatialperturb.load_demo_dataset(*, platform='spatial', paired=False, annotate=True, seed=0)[source]¶
Return a deterministic demo dataset for tests, docs, and end-to-end examples.
- Return type:
AnnData|tuple[AnnData,AnnData]
- spatialperturb.load_public_dataset(name, *, cache_dir, prepared=True)[source]¶
Load a prepared public dataset as an AnnData object.
- Return type:
AnnData
- spatialperturb.neighbor_de(adata, *, perturbation, control, graph_key=None, groupby='perturbation', status_col='perturbation_status', exclude_perturbed=True, drop_shared_neighbors=False, weight_by_distance=False, aggregate='mean', features=None, layer=None, cell_type=None, roi=None, min_cells_per_group=2, min_samples_per_group=2, method='simple', sample_col=None, covariates=None, effect_size_only=False, min_cells=None)[source]¶
Compare neighbors around perturbed cells against neighbors around control cells.
- Return type:
DataFrame
- spatialperturb.neighbor_program_scores(adata, *, score_key='program_scores', graph_key=None, key_added='neighbor_program_scores', exclude_perturbed=True)[source]¶
Average program scores across each cell’s neighborhood.
- Return type:
DataFrame
- spatialperturb.platform_concordance(left, right, *, group_col='perturbation', gene_col='gene', score_col='log2fc', top_n=50, level='both')[source]¶
Compare per-perturbation gene effects between two result tables.
- Return type:
DataFrame
- spatialperturb.power_curve(adata, *, perturbation, control, mode='intrinsic', feature=None, sample_sizes=(5, 10, 20, 30), n_boot=100, alpha=0.05, groupby='perturbation', status_col='perturbation_status', graph_key=None, layer=None, method='simple', sample_col=None, cell_type=None, roi=None, random_state=0)[source]¶
Estimate detection power across sample sizes by bootstrap resampling.
- Return type:
DataFrame
- spatialperturb.prepare_dataset(name, *, cache_dir, output_dir=None)[source]¶
Standardize a public dataset into SpatialPerturb-compatible prepared outputs.
- Return type:
dict[str,Any]
- spatialperturb.program_redundancy_table(programs, *, threshold=0.5)[source]¶
Return pairwise Jaccard overlap and coarse redundancy groups for programs.
- Return type:
DataFrame
- spatialperturb.qc_perturbations(adata, *, control, target_map=None, perturbation_col='perturbation', status_col='perturbation_status', layer=None, min_cells=5)[source]¶
Summarize perturbation calling quality and target knockdown sanity checks.
- Return type:
DataFrame
- spatialperturb.read_stereoseq(path, **_)[source]¶
Read a simple Stereo-seq-style cell-level export into AnnData.
- Return type:
AnnData
- spatialperturb.read_xenium(path, *, cell_group_path=None, roi_geojson_path=None, sample_name=None, load_molecules=False)[source]¶
Read a simple Xenium-style cell-level export into AnnData.
- Return type:
AnnData
- spatialperturb.render_nature_methods_panels(report_dir, output_dir, *, strict=True)[source]¶
Render fixed Nature Methods panel files from a completed report directory.
- Return type:
dict[str,dict[str,str]]
- spatialperturb.render_paper_figures(results, *, output_dir)[source]¶
Render the canonical paper figures from benchmark result tables.
- Return type:
dict[str,str]
- spatialperturb.run_core_benchmark(dataset_or_adata, *, perturbations=None, control=None, target_map=None, lr_network=None, graph_key=None, sample_sizes=None, cell_type=None, roi=None, config=None, output_dir=None)[source]¶
Run the core benchmark suite for a spatial perturbation dataset.
- Return type:
dict[str,Any]
- spatialperturb.run_cross_platform_benchmark(spatial_results, reference_results, *, config=None, output_dir=None)[source]¶
Run the cross-platform concordance benchmark on paired DE result tables.
- Return type:
DataFrame
- spatialperturb.run_nature_methods_breast_analysis(spatial_input, *, reference_datasets=None, config=None, output_dir=None)[source]¶
Run the publication-grade breast Xenium analysis for a Nature Methods Brief Communication.
- Return type:
dict[str,Any]
- spatialperturb.run_reference_projection_benchmark(spatial_input, *, reference_datasets, config=None, output_dir=None)[source]¶
Project reference-derived programs onto a spatial or Xenium dataset.
- Return type:
dict[str,Any]
- spatialperturb.save_panel(fig, spec, source_data, output_dir, *, strict=True)[source]¶
Save a production panel and its source data under a shared manifest.
- Return type:
dict[str,str]
- spatialperturb.score_programs(adata, programs, *, layer=None)[source]¶
Score each program as the mean expression of its member genes per cell.
- Return type:
DataFrame
- spatialperturb.set_publication_rcparams()[source]¶
Apply Nature-style editable-vector and small-panel Matplotlib defaults.
- Return type:
None
- spatialperturb.spatial_autocorrelation_scores(adata, *, score_key='program_scores', graph_key=None, n_permutations=100, seed=0)[source]¶
Compute graph Moran-style spatial autocorrelation for program scores.
- Return type:
DataFrame
- spatialperturb.validate_reference_programs(reference_adata, *, programs=None, query_adata=None, control='control', perturbation_col='perturbation', status_col='perturbation_status', split_strategy='auto', top_n=50, direction='both', method='simple', seed=0, min_cells_per_group=2)[source]¶
Validate reference programs by held-out recovery of perturbation labels.
- Return type:
DataFrame
I/O 与 Schema¶
AnnData I/O helpers for SpatialPerturb.
- spatialperturb.io.from_tables(expression, *, obs=None, var=None, spatial=None, layers=None, metadata=None)[source]¶
Build a schema-compliant AnnData object from tabular inputs.
- Return type:
AnnData
- spatialperturb.io.read_stereoseq(path, **_)[source]¶
Read a simple Stereo-seq-style cell-level export into AnnData.
- Return type:
AnnData
- spatialperturb.io.read_xenium(path, *, cell_group_path=None, roi_geojson_path=None, sample_name=None, load_molecules=False)[source]¶
Read a simple Xenium-style cell-level export into AnnData.
- Return type:
AnnData
Schema helpers for AnnData objects consumed by SpatialPerturb.
- exception spatialperturb.schema.SpatialPerturbSchemaError[source]¶
Raised when an AnnData object does not satisfy the SpatialPerturb schema.
- spatialperturb.schema.ensure_spatialperturb_schema(adata, *, metadata=None, copy=False)[source]¶
Ensure required schema fields exist, filling defaults when needed.
- Return type:
AnnData
预处理与图¶
Preprocessing and perturbation assignment utilities.
- spatialperturb.pp.assign_perturbations(adata, *, barcode_columns=None, barcode_prefix=None, barcode_to_perturbation=None, min_counts=1.0, negative_label='unassigned', multiple_label='multiple', perturbation_col='perturbation', status_col='perturbation_status', include_col='include_for_inference', copy=False)[source]¶
Assign a perturbation label to each cell from barcode feature counts.
- Return type:
AnnData
- spatialperturb.pp.qc_perturbations(adata, *, control, target_map=None, perturbation_col='perturbation', status_col='perturbation_status', layer=None, min_cells=5)[source]¶
Summarize perturbation calling quality and target knockdown sanity checks.
- Return type:
DataFrame
Spatial graph construction and neighborhood collection.
分析工具¶
Core analysis tools for spatial perturbation inference.
- spatialperturb.tl.differential_lr(adata, *, perturbation, control, graph_key=None, lr_network=None, groupby='perturbation', status_col='perturbation_status', source_groupby=None, target_groupby=None, layer=None, cell_type=None, roi=None)[source]¶
Score ligand-receptor interactions between perturbed cells and their neighbors.
- Return type:
DataFrame
- spatialperturb.tl.intrinsic_de(adata, *, perturbation, control, groupby='perturbation', status_col='perturbation_status', features=None, layer=None, cell_type=None, roi=None, min_cells_per_group=2, min_samples_per_group=2, method='simple', sample_col=None, covariates=None, effect_size_only=False, min_cells=None)[source]¶
Compare perturbed cells against control cells in the same ROI/cell type context.
- Return type:
DataFrame
- spatialperturb.tl.neighbor_de(adata, *, perturbation, control, graph_key=None, groupby='perturbation', status_col='perturbation_status', exclude_perturbed=True, drop_shared_neighbors=False, weight_by_distance=False, aggregate='mean', features=None, layer=None, cell_type=None, roi=None, min_cells_per_group=2, min_samples_per_group=2, method='simple', sample_col=None, covariates=None, effect_size_only=False, min_cells=None)[source]¶
Compare neighbors around perturbed cells against neighbors around control cells.
- Return type:
DataFrame
- spatialperturb.tl.platform_concordance(left, right, *, group_col='perturbation', gene_col='gene', score_col='log2fc', top_n=50, level='both')[source]¶
Compare per-perturbation gene effects between two result tables.
- Return type:
DataFrame
- spatialperturb.tl.power_curve(adata, *, perturbation, control, mode='intrinsic', feature=None, sample_sizes=(5, 10, 20, 30), n_boot=100, alpha=0.05, groupby='perturbation', status_col='perturbation_status', graph_key=None, layer=None, method='simple', sample_col=None, cell_type=None, roi=None, random_state=0)[source]¶
Estimate detection power across sample sizes by bootstrap resampling.
- Return type:
DataFrame
Program and signature helpers for SpatialPerturb.
- spatialperturb.signatures.aggregate_program_scores(adata, score_key, *, groupby)[source]¶
Aggregate per-cell program scores into a tidy long table.
- Return type:
DataFrame
- spatialperturb.signatures.bootstrap_program_score_intervals(adata, score_key='program_scores', *, groupby=('cell_type', 'roi'), n_bootstrap=200, min_cells=50, seed=0)[source]¶
Estimate bootstrap confidence intervals for grouped program means.
- Return type:
DataFrame
- spatialperturb.signatures.build_reference_programs(adata, *, control='control', groupby=None, perturbation_col='perturbation', status_col='perturbation_status', method='auto', sample_col=None, covariates=None, top_n=50, direction='both', min_cells_per_group=2, min_samples_per_group=2, effect_size_only=False, cell_type=None, roi=None, return_de_results=False)[source]¶
Build per-perturbation reference programs from a Perturb-seq AnnData object.
- Return type:
dict[str,list[str]] |tuple[dict[str,list[str]],DataFrame]
- spatialperturb.signatures.build_signature_matrix(programs)[source]¶
Convert a program-to-gene mapping into a binary membership matrix.
- Return type:
DataFrame
- spatialperturb.signatures.calibrate_program_scores(adata, programs=None, *, score_key='program_scores', groupby=('cell_type', 'roi'), n_random=100, n_label_shuffles=None, n_bins=20, min_cells=50, seed=0, layer=None, return_nulls=False)[source]¶
Calibrate grouped program scores with expression-matched and label-shuffle nulls.
The returned table keeps every group, but marks groups with fewer than
min_cellsas exploratory so downstream reports do not overclaim tiny ROIs.- Return type:
DataFrame|tuple[DataFrame,DataFrame]
- spatialperturb.signatures.compare_program_concordance(left, right)[source]¶
Compare program definitions or program scores across two inputs.
- Return type:
DataFrame
- spatialperturb.signatures.derive_perturbation_programs(de_results, *, group_col='perturbation', gene_col='gene', score_col='log2fc', top_n=50, direction='both')[source]¶
Derive per-perturbation programs from a tidy DE table.
- Return type:
dict[str,list[str]]
- spatialperturb.signatures.neighbor_program_scores(adata, *, score_key='program_scores', graph_key=None, key_added='neighbor_program_scores', exclude_perturbed=True)[source]¶
Average program scores across each cell’s neighborhood.
- Return type:
DataFrame
- spatialperturb.signatures.program_redundancy_table(programs, *, threshold=0.5)[source]¶
Return pairwise Jaccard overlap and coarse redundancy groups for programs.
- Return type:
DataFrame
- spatialperturb.signatures.score_programs(adata, programs, *, layer=None)[source]¶
Score each program as the mean expression of its member genes per cell.
- Return type:
DataFrame
- spatialperturb.signatures.spatial_autocorrelation_scores(adata, *, score_key='program_scores', graph_key=None, n_permutations=100, seed=0)[source]¶
Compute graph Moran-style spatial autocorrelation for program scores.
- Return type:
DataFrame
- spatialperturb.signatures.validate_reference_programs(reference_adata, *, programs=None, query_adata=None, control='control', perturbation_col='perturbation', status_col='perturbation_status', split_strategy='auto', top_n=50, direction='both', method='simple', seed=0, min_cells_per_group=2)[source]¶
Validate reference programs by held-out recovery of perturbation labels.
- Return type:
DataFrame
数据集与 benchmark¶
Dataset registry, lifecycle helpers, and demo data for SpatialPerturb.
- class spatialperturb.datasets.DatasetCard(name, title, platform, accession, benchmark_track, source_url, description, status='metadata_only', raw_format='none', parser='demo', prepared_kind='adata', raw_archive_name=None, prepared_filename=None, matrix_filename=None, supports_auto_prepare=True, validation_note=None, supplementary_files=())[source]¶
Metadata for a benchmarkable dataset.
- spatialperturb.datasets.available_datasets()[source]¶
Return the bundled dataset catalog.
- Return type:
DataFrame
- spatialperturb.datasets.fetch_dataset(name, *, cache_dir, force=False)[source]¶
Download and cache the raw public files for a registered dataset.
- Return type:
dict[str,Any]
- spatialperturb.datasets.load_demo_dataset(*, platform='spatial', paired=False, annotate=True, seed=0)[source]¶
Return a deterministic demo dataset for tests, docs, and end-to-end examples.
- Return type:
AnnData|tuple[AnnData,AnnData]
- spatialperturb.datasets.load_public_dataset(name, *, cache_dir, prepared=True)[source]¶
Load a prepared public dataset as an AnnData object.
- Return type:
AnnData
- spatialperturb.datasets.prepare_dataset(name, *, cache_dir, output_dir=None)[source]¶
Standardize a public dataset into SpatialPerturb-compatible prepared outputs.
- Return type:
dict[str,Any]
Benchmark orchestration for SpatialPerturb analyses.
- spatialperturb.benchmarks.available_benchmarks()[source]¶
Return available benchmark tracks and their required inputs.
- Return type:
DataFrame
- spatialperturb.benchmarks.run_core_benchmark(dataset_or_adata, *, perturbations=None, control=None, target_map=None, lr_network=None, graph_key=None, sample_sizes=None, cell_type=None, roi=None, config=None, output_dir=None)[source]¶
Run the core benchmark suite for a spatial perturbation dataset.
- Return type:
dict[str,Any]
- spatialperturb.benchmarks.run_cross_platform_benchmark(spatial_results, reference_results, *, config=None, output_dir=None)[source]¶
Run the cross-platform concordance benchmark on paired DE result tables.
- Return type:
DataFrame
- spatialperturb.benchmarks.run_nature_methods_breast_analysis(spatial_input, *, reference_datasets=None, config=None, output_dir=None)[source]¶
Run the publication-grade breast Xenium analysis for a Nature Methods Brief Communication.
- Return type:
dict[str,Any]
- spatialperturb.benchmarks.run_reference_projection_benchmark(spatial_input, *, reference_datasets, config=None, output_dir=None)[source]¶
Project reference-derived programs onto a spatial or Xenium dataset.
- Return type:
dict[str,Any]
Paper-grade reporting and figure rendering helpers.
投稿级 FigureKit¶
Production-grade panel rendering for publication workflows.
- exception spatialperturb.figurekit.FigureKitError[source]¶
Raised when a production figure contract is violated.
- class spatialperturb.figurekit.PanelSpec(panel_id, figure_id, label, width_mm, height_mm, output_formats=('pdf', 'png', 'svg'), dpi=300, rasterize_dense=True, source_data_required=True, metadata=<factory>)[source]¶
Publication panel output contract.
- spatialperturb.figurekit.dense_spatial_scatter(ax, coords, *, values=None, threshold=50000, force_rasterized=None, **kwargs)[source]¶
Scatter spatial points with automatic rasterization for dense point clouds.
- Return type:
PathCollection
- spatialperturb.figurekit.render_nature_methods_panels(report_dir, output_dir, *, strict=True)[source]¶
Render fixed Nature Methods panel files from a completed report directory.
- Return type:
dict[str,dict[str,str]]
绘图与 CLI¶
Plotting helpers for SpatialPerturb result tables.
- spatialperturb.pl.barcode_spread(adata, *, status_col='perturbation_status', ax=None)[source]¶
Plot perturbation assignment status counts.
- Return type:
Axes
- spatialperturb.pl.lr_map(adata, lr_results, *, perturbation, graph_key=None, ligand=None, receptor=None, ax=None)[source]¶
Plot perturbed cells and their neighbors colored by ligand and receptor expression.
- Return type:
Axes
- spatialperturb.pl.lr_pairs(lr_results, *, top_n=20, ax=None)[source]¶
Plot top ligand-receptor differential scores.
- Return type:
Axes
- spatialperturb.pl.own_vs_neighbor(intrinsic_results, neighbor_results, *, perturbation=None, ax=None)[source]¶
Plot intrinsic versus neighbor log fold changes for shared genes.
- Return type:
Axes
- spatialperturb.pl.platform_concordance(concordance_results, *, metric='spearman', ax=None)[source]¶
Plot per-perturbation cross-platform concordance.
- Return type:
Axes
- spatialperturb.pl.power_curve(power_results, *, ax=None)[source]¶
Plot empirical power as a function of sample size.
- Return type:
Axes
Command-line interface for SpatialPerturb.
- spatialperturb.cli.fetch_dataset_command(name, cache_dir=PosixPath('.spatialperturb-cache'), force=False)[source]¶
Download raw public files for a registered dataset.
- Return type:
None
- spatialperturb.cli.prepare_dataset_command(name, cache_dir=PosixPath('.spatialperturb-cache'), output_dir=None)[source]¶
Prepare a dataset into SpatialPerturb-compatible outputs.
- Return type:
None
- spatialperturb.cli.prepare_xenium_command(path, output_path, cell_group_path=None, roi_geojson_path=None, sample_name=None, load_molecules=False)[source]¶
Prepare a Xenium directory into a schema-compliant h5ad file.
- Return type:
None
- spatialperturb.cli.render_paper_figures_command(dataset, cache_dir=PosixPath('.spatialperturb-cache'), output_dir=None, reference_dataset=None)[source]¶
Render the canonical paper figures for a dataset.
- Return type:
None
- spatialperturb.cli.run_benchmark_command(dataset, cache_dir=PosixPath('.spatialperturb-cache'), output_dir=None, reference_dataset=None, method='auto')[source]¶
Run the paper-grade benchmark workflow for a dataset.
- Return type:
None
- spatialperturb.cli.run_nature_methods_breast_analysis_command(spatial_input, output_dir, cache_dir=PosixPath('.spatialperturb-cache'), cell_group_path=None, roi_geojson_path=None, sample_name=None, reference_datasets='gse241115_breast_cropseq,gse281048_pathway_atlas', n_random=25, n_spatial_permutations=25, n_bootstrap=100, min_claim_cells=50)[source]¶
Run the publication-grade Nature Methods breast short-communication workflow.
- Return type:
None
- spatialperturb.cli.run_reference_benchmark_command(spatial_input, output_dir, cache_dir=PosixPath('.spatialperturb-cache'), cell_group_path=None, roi_geojson_path=None, sample_name=None, reference_datasets='gse241115_breast_cropseq,gse281048_pathway_atlas')[source]¶
Run the Xenium + Perturb-seq reference projection workflow.
- Return type:
None