The SegTraQ (SegTraQ) class#

The SegTraQ (SegTraQ) class represents the core interface for computing SegTraQ metrics.

class segtraq.SegTraQ(sdata, images_key='morphology_focus', tables_key='table', tables_cell_id_key='cell_id', tables_area_key='cell_area', tables_centroid_x_key='x_centroid', tables_centroid_y_key='y_centroid', tables_gene_key=None, tables_raw_counts_layer=None, points_key='transcripts', points_cell_id_key='cell_id', points_qv_key='qv', points_background_id='UNASSIGNED', points_x_key='x', points_y_key='y', points_z_key='z', points_gene_key='feature_name', shapes_key='cell_boundaries', shapes_cell_id_key='cell_id', nucleus_shapes_key='nucleus_boundaries', nucleus_shapes_cell_id_key='cell_id', filter_low_quality_transcripts=True, filter_kwargs=None)#

Initialize a SegTraQ object, the core interface for computing SegTraQ metrics. Defaults target 10x Genomics Xenium; override keys for other technologies. By default, this removes low-quality and control transcripts that would otherwise skew metrics, but this can be configured via the filter_low_quality_transcripts and filter_kwargs arguments.

Parameters:
  • sdata (SpatialData) – A SpatialData object containing segmented and transcript-assigned spatial transcriptomics data (images, tables, points, shapes and optional labels).

  • images_key (str or None, optional, default "morphology_focus") – Key in sdata.images for a nuclear or morphology image (e.g., DAPI). Used for visualization or to derive a nucleus mask via segtraq.run_cellpose when using the nuclear correlation module (segtraq.nc). If None, no image is expected.

  • tables_key (str, default "table") – Key in sdata.tables for the cell-level metadata table.

  • tables_cell_id_key (str, default "cell_id") – Column in the cell table uniquely identifying each cell.

  • tables_area_key (str or None, optional, default "cell_area") – Column in the cell table with cell area (2D). If None, area will be computed via segtraq.bl.morphological_features.

  • tables_centroid_x_key (str or None, optional, default "x_centroid") – Column in the cell table with the x-coordinate of the cell centroid.

  • tables_centroid_y_key (str or None, optional, default "y_centroid") – Column in the cell table with the y-coordinate of the cell centroid.

  • tables_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing unique gene identifiers matching those in sdata.points[points_key][points_gene_key]. If None, sdata.tables[tables_key].var_names are used.

  • tables_raw_counts_layer (str | None, optional) – Layer containing count data. If None, adata.X is used if it looks like counts. If a layer is specified, it must exist and contain count-like values.

  • points_key (str, default "transcripts") – Key in sdata.points for spot/transcript-level data.

  • points_cell_id_key (str, default "cell_id") – Column in the points table linking each transcript/spot to a cell.

  • points_qv_key (str or None, optional, default "qv") – Column in the points table containing quality values (qv) for each transcript. Ignored if filter_low_quality_transcripts is False or min_qv is None.

  • points_background_id (str or int or None, default "UNASSIGNED") – Identifier for transcripts not assigned to any cell (background).

  • points_x_key (str, default "x") – Column for the x-coordinate of each transcript/spot.

  • points_y_key (str, default "y") – Column for the y-coordinate of each transcript/spot.

  • points_z_key (str or None, optional, default "z") – Column for the z-coordinate (3D data). If None, data are treated as 2D.

  • points_gene_key (str, default "feature_name") – Column specifying the gene/feature name for each transcript/spot.

  • shapes_key (str, default "cell_boundaries") – Key in sdata.shapes for cell boundary polygons.

  • shapes_cell_id_key (str, optional, default "cell_id") – Cell ID key for sdata.shapes[shapes_key]. Must match either the shapes index name or a column name (which will be set as the index if needed). If None, the index is assumed to contain cell IDs and renamed to “segtraq_id”.

  • nucleus_shapes_key (str or None, optional, default "nucleus_boundaries") – Key in sdata.shapes for nucleus boundary polygons, if available. If None, a nucleus mask can be obtained via segtraq.run_cellpose.

  • nucleus_shapes_cell_id_key (str, optional, default "cell_id") – Cell ID key for sdata.shapes[nucleus_shapes_key]. Must match either the shapes index name or a column name (which will be set as the index if needed).

filter_low_quality_transcriptsbool, default=True

Whether to filter out low-quality and control transcripts that would otherwise skew metrics.

filter_kwargsdict or None, optional

If filter_low_quality_transcripts is True, these keyword arguments are forwarded to the filtering function. Possible keys are: min_qv, control_prefixes, inplace. Please refer to the function _filter_control_and_low_quality_transcripts for details.

Notes

After initializing a SegTraQ instance, all SegTraQ modules can be run directly from the object using its module facades.

Wrappers (run_baseline, run_nuclear_correlation, etc.) to run all metrics of a module are provided below.

filter_cells(col, func, inplace=True)#

Filter cells from the cell table based on a user-defined function.

Parameters:
  • col (str) – Column in the cell table to apply the filtering function on.

  • func (Callable) – A function that takes a single argument (the column value) and returns True if the cell should be kept, False otherwise.

  • inplace (bool, default True) – If True, modifies self.sdata in place. If False, returns a new SpatialData object with the filtered cells.

Returns:

  • If inplace=True: returns None after modifying self.sdata.

  • If inplace=False: returns a new SpatialData object with filtered cells.

Return type:

None or SpatialData

Example

>>> st.filter_cells(col='cell_area', func=lambda x: x > 100)
filter_control_and_low_quality_transcripts(min_qv=20.0, control_prefixes=('NegControlProbe_', 'antisense_', 'NegControlCodeword', 'BLANK_', 'Blank-', 'NegPrb', 'DeprecatedCodeword_', 'UnassignedCodeword_', 'Intergenic_Region_'), inplace=True)#

Filter control and low-quality transcripts from the SpatialData points element.

Control genes matching control_prefixes are removed from both the transcript points and the cell-level expression table. Quality filtering is applied only to transcript points, leaving the expression matrix otherwise unchanged.

After filtering, the genes and cell IDs represented by assigned transcripts are compared with those represented in the cell-level table. Differences are reported as warnings because they may indicate that the transcript assignments and expression matrix were generated using different filtering or assignment procedures.

Parameters:
  • sdata (SpatialData) – The SpatialData object containing transcript data.

  • min_qv (float | None, default 20.0) – Minimum quality value (qv) threshold for transcripts to be retained. If None, no filtering is applied based on quality.

  • control_prefixes (tuple | list | None) – Gene-name prefixes identifying control probes to remove.

  • points_key (str, default "transcripts") – Key containing transcript-level data.

  • points_gene_key (str, default "feature_name") – Column containing gene names.

  • points_cell_id_key (str, default "cell_id") – Column containing transcript-to-cell assignments.

  • points_qv_key (str, default "qv") – Column containing quality values for transcripts.

  • points_background_id (str | int | None, default "UNASSIGNED") – Value indicating unassigned/background transcripts.

  • tables_key (str, default "table") – Key containing the cell-level expression table.

  • tables_cell_id_key (str, default "cell_id") – Column containing cell IDs in the table.

  • tables_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing gene identifiers. If None, var_names are used.

  • inplace (bool, default True) – Whether to modify the SpatialData object in place.

Returns:

SpatialData object with filtered transcript points and control genes removed from the expression table.

Return type:

SpatialData

run_all(*, adata_ref=None, ref_cell_type=None, ref_gene_key=None, query_gene_key=None, ref_raw_counts_layer=None, cell_type_key=None, markers=None, inplace=True, label_transfer_kwargs=None, baseline_kwargs=None, region_similarity_kwargs=None, volume_kwargs=None, clustering_stability_kwargs=None, supervised_kwargs=None, point_statistics_kwargs=None)#

Run all SegTraQ metrics across all modules.

Convenience wrapper that calls, in order, run_baseline, run_region_similarity, run_volume, run_clustering_stability, run_supervised, and run_point_statistics via their respective facades.

If cell_type_key is None and both adata_ref and ref_cell_type are provided, label transfer is run once upfront via self.run_label_transfer(), and the resulting labels (stored under “transferred_cell_type”) are reused by every module that accepts a cell_type_key, instead of each module running its own label transfer.

A module whose prerequisites are not met (e.g. run_volume on 2D data, or run_supervised without a reference dataset) is skipped with a warning instead of aborting the whole call. Pass inplace=False to see exactly which modules ran and why any others were skipped.

Arguments that run_all passes to the modules itself (inplace, cell_type_key, markers, and the reference arguments adata_ref, ref_cell_type, ref_gene_key, query_gene_key, ref_raw_counts_layer) must be passed directly to run_all, not via the module *_kwargs; a ValueError is raised before any module runs otherwise.

Progress is reported via tqdm unless disabled through segtraq.settings.progress. An overall bar tracks the modules, and each module shows its own bar for the duration of its run.

Parameters:
  • adata_ref (AnnData or None, default None) – Reference AnnData object used for mutually_exclusive_coexpression_rate, and when needed, label transfer and/or marker extraction. Forwarded to run_volume and run_supervised.

  • ref_cell_type (str or None, default None) – Column in adata_ref.obs containing reference cell-type labels.

  • ref_gene_key (str or None, default None) – Column in adata_ref.var containing gene identifiers matching the query gene identifiers. If None, adata_ref.var_names are used.

  • query_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing gene identifiers matching adata_ref.var[ref_gene_key]. If None, tables_gene_key is used.

  • ref_raw_counts_layer (str or None, default None) – Layer containing raw counts in adata_ref. If None, raw counts are expected in adata_ref.X.

  • cell_type_key (str or None, default None) – Column in sdata.tables[tables_key].obs containing cell-type labels, reused by every module that accepts one (including cluster connectedness and silhouette score in run_clustering_stability). If None and adata_ref/ref_cell_type are provided, label transfer is run once upfront and its result is used instead.

  • markers (dict or None, default None) – Marker genes forwarded to run_supervised, in the form {cell_type: {“positive”: list[str], “negative”: list[str]}}. If None, markers stored in sdata.tables[tables_key].uns[“segtraq_markers”] are used if available. Otherwise, markers are derived from adata_ref.

  • inplace (bool, default True) – If True, results of every successfully run module are merged into sdata and None is returned. If False, per-module results are returned in a dict.

  • label_transfer_kwargs (dict or None, optional) – Extra keyword arguments forwarded to the single, shared self.run_label_transfer() call.

  • baseline_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_baseline.

  • region_similarity_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_region_similarity.

  • volume_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_volume.

  • clustering_stability_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_clustering_stability.

  • supervised_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_supervised.

  • point_statistics_kwargs (dict or None, optional) – Extra keyword arguments forwarded to run_point_statistics.

Returns:

If inplace=True, returns None. If inplace=False, returns a dict with keys “baseline”, “region_similarity”, “volume”, “clustering_stability”, “supervised”, and “point_statistics” (each None for a module that was skipped), plus a “skipped” dict mapping the name of every skipped module to the reason it could not be computed.

Return type:

None or dict

run_baseline(inplace=True, *, morphological_kwargs=None, _leave=True)#

Run baseline (bl) metrics.

Convenience wrapper around global and per-cell summary metrics. Runs, in order:

  1. number of cells

  2. number of transcripts

  3. number of genes

  4. % unassigned transcripts

  5. % unassigned transcripts per gene

  6. transcripts per cell

  7. genes per cell

  8. mean transcripts per detected gene per cell

  9. morphological features

  10. transcript density

Progress is reported via tqdm unless disabled through segtraq.settings.progress.

Parameters:
  • inplace (bool, default True) – If True, results are merged into .uns, .obs, and/or .var as implemented by each metric, and None is returned. If False, per-metric results are returned in a dict.

  • morphological_kwargs (dict or None, optional) – Extra arguments forwarded to bl.morphological_features().

Returns:

If inplace=True, returns None. If inplace=False, returns a dict with keys: - “num_cells” - “num_transcripts” - “num_genes” - “perc_unassigned_transcripts” - “perc_unassigned_transcripts_per_gene” - “transcripts_per_cell” - “genes_per_cell” - “mean_transcripts_per_gene_per_cell” - “morphological_features” - “transcript_density”

Return type:

None or dict

run_clustering_stability(key_prefix='leiden_subset', cell_type_key=None, adata_ref=None, ref_cell_type=None, ref_gene_key=None, query_gene_key=None, ref_raw_counts_layer=None, use_hvg=None, inplace=True, label_transfer_kwargs=None, connectedness_kwargs=None, silhouette_kwargs=None, purity_kwargs=None, ari_kwargs=None, leiden_kwargs=None, n_jobs=None, _leave=True)#

Run clustering stability (cs) metrics.

Convenience wrapper around segtraq.cs functions via the instance facade self.cs.

If cell_type_key is provided, it is used to compute connectedness and silhouette score based on existing cell-type annotations.

If cell_type_key is None and adata_ref is provided, label transfer is run first via self.run_label_transfer() using adata_ref and ref_cell_type. The resulting labels are stored under “transferred_cell_type”.

If neither cell_type_key nor adata_ref is provided, connectedness and silhouette score are computed using Leiden clustering. Purity and ARI always assess Leiden clustering stability across random subsets of cells.

Runs, in order:

  1. label transfer, if needed

  2. connectedness (cell-type labels or Leiden clustering)

  3. silhouette score (cell-type labels or Leiden clustering)

  4. purity (Leiden subset stability)

  5. ARI (Leiden subset stability)

Progress is reported via tqdm unless disabled through segtraq.settings.progress. Only the steps that will actually run are counted.

Parameters:
  • key_prefix (str, default "leiden_subset") – Prefix for Leiden clustering labels written to .obs by the underlying methods (where applicable).

  • cell_type_key (str or None, default None) – Column in sdata.tables[tables_key].obs containing cell-type labels. If provided, connectedness and silhouette score are computed using these labels. If None and adata_ref is provided, label transfer is run first and labels are stored under “transferred_cell_type”. If neither is provided, Leiden clustering is used. Purity and ARI always use Leiden clustering on random subsets.

  • adata_ref (AnnData or None, default None) – Reference AnnData object used for label transfer when cell_type_key is None.

  • ref_cell_type (str or None, default None) – Column in adata_ref.obs containing reference cell-type labels. Required if cell_type_key=None and label transfer should be run.

  • ref_gene_key (str or None, default None) – Column in adata_ref.var containing gene identifiers. If None, adata_ref.var_names are used.

  • query_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing gene identifiers matching adata_ref.var[ref_gene_key]. If None, tables_gene_key is used.

  • ref_raw_counts_layer (str or None, default None) – Layer containing raw counts in adata_ref. If None, raw counts are expected in adata_ref.X.

  • use_hvg (bool or None, optional) – If None, use 2,000 HVGs for PCA when the panel contains more than 8,000 genes. If True, always use HVGs. If False, use all genes remaining after exclude_gene_prefixes filtering.

  • inplace (bool, default True) – If True, metrics are written to sdata.tables[“table”].uns by the underlying methods and this function returns None. If False, the computed metrics are returned as a dictionary.

  • label_transfer_kwargs (dict or None, optional) – Extra keyword arguments forwarded to self.run_label_transfer(). Do not include reference parameters, cell_type_key, or inplace.

  • connectedness_kwargs (dict or None, optional) – Additonal keyword arguments forwarded to cs.connectedness().

  • silhouette_kwargs (dict or None, optional) – Additonal keyword arguments forwarded to cs.silhouette_score().

  • purity_kwargs (dict or None, optional) – Additonal keyword arguments forwarded to cs.purity().

  • ari_kwargs (dict or None, optional) – Additonal keyword arguments forwarded to cs.adjusted_rand_index().

  • leiden_kwargs (dict or None, optional) – Additional keyword arguments forwarded to Leiden clustering in all underlying methods that perform clustering. For example, flavor=’igraph’ can be used to specify the Leiden implementation.

  • n_jobs (int or None, optional) – Number of threads used by numba, BLAS and OpenMP for PCA, neighbor graph construction and clustering. If None, uses segtraq.settings.n_jobs (default: 1). Set to -1 to use all CPUs available to the current process. Results are only reproducible for a fixed number of threads.

Returns:

If inplace=True, returns None. If inplace=False, returns a dictionary with keys:

  • ”connectedness_leiden” or “connectedness_{cell_type_key}” : float

  • ”silhouette_score_leiden” or “silhouette_score_{cell_type_key}” : float

  • ”mean_purity_leiden” : float

  • ”mean_ari_leiden” : float

  • ”label_transfer” : pandas.DataFrame, only if label transfer was performed

Return type:

None or dict

run_label_transfer(adata_ref, ref_cell_type, ref_gene_key=None, query_gene_key=None, ref_raw_counts_layer=None, tx_min=10.0, tx_max=inf, gn_min=5.0, gn_max=inf, cell_type_key='transferred_cell_type', use_hvg=None, exclude_gene_prefixes=('MT-', 'RPL', 'RPS'), inplace=True)#

Transfer cell type labels from a reference AnnData object to cells in a SpatialData table using Pearson correlation to reference mean expression profiles.

Raw counts are selected first, normalized with sc.pp.normalize_total, log-transformed with sc.pp.log1p, and then used for label transfer. If a raw-count layer is provided, it is used preferentially. Otherwise, .X is expected to contain raw counts.

Parameters:
  • sdata (SpatialData) – SpatialData object containing the query dataset. Cell-level expression data are expected in sdata.tables[tables_key].

  • adata_ref (AnnData) – Reference AnnData object containing annotated cells.

  • ref_cell_type (str) – Column in adata_ref.obs containing the reference cell type labels.

  • tables_raw_counts_layer (str or None, default None) – Layer in sdata.tables[tables_key].layers containing raw counts for the query data. If None, raw counts are expected in sdata.tables[tables_key].X.

  • ref_raw_counts_layer (str or None, default None) – Layer in adata_ref.layers containing raw counts for the reference data. If None, raw counts are expected in adata_ref.X.

  • tables_key (str, default "table") – Key identifying the cell-level AnnData table in sdata.tables.

  • tables_cell_id_key (str, default "cell_id") – Column in sdata.tables[tables_key].obs containing unique cell identifiers.

  • tables_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing the canonical gene identifiers used by SegTraQ. If None, var_names are used.

  • query_gene_key (str or None, default None) – Alternative column in sdata.tables[tables_key].var containing gene identifiers matching adata_ref.var[ref_gene_key]. If None, tables_gene_key is used.

  • points_key (str, default "transcripts") – Key identifying the transcript-level points element in sdata.points.

  • points_cell_id_key (str, default "cell_id") – Column in the transcript points table containing cell identifiers.

  • points_gene_key (str, default "feature_name") – Column in the transcript points table containing gene names.

  • tx_min (float, default 10.0) – Minimum number of detected transcripts required for a cell to be retained.

  • tx_max (float, default inf) – Maximum number of detected transcripts allowed for a cell to be retained.

  • gn_min (float, default 5.0) – Minimum number of detected genes required for a cell to be retained.

  • gn_max (float, default np.inf) – Maximum number of detected genes allowed for a cell to be retained.

  • cell_type_key (str, default "transferred_cell_type") – Column name used to store transferred labels in the query table’s .obs.

  • ref_gene_key (str or None, default None) – Column in adata_ref.var containing gene identifiers matching the query gene identifiers. If None, adata_ref.var_names are used.

  • use_hvg (bool or None, default None) – If None, restrict label transfer to 2,000 highly variable genes when more than 8,000 genes are shared between query and reference. If True, always use HVGs. If False, always use all shared genes.

  • exclude_gene_prefixes (str, list of str, tuple of str, or None, optional) – Gene prefixes excluded from label transfer. By default (("MT-", "RPL", "RPS")), mitochondrial and ribosomal genes are excluded. This filtering is applied independently of HVG selection. Set to None to use all shared genes.

  • inplace (bool, default True) – If True, write transferred labels to sdata.tables[tables_key].obs[cell_type_key] and return None. If False, return a DataFrame with transferred labels and Pearson correlation scores.

Returns:

If inplace=False, returns a DataFrame with columns including tables_cell_id_key, cell_type_key, and “pearson_score”. If inplace=True, modifies sdata in place and returns None.

Return type:

pandas.DataFrame or None

run_point_statistics(genes=None, cell_type_key='transferred_cell_type', cell_type_query=None, inplace=True, *, centroid_kwargs=None, membrane_kwargs=None, skew_kwargs=None, compartments_kwargs=None, _leave=True)#

Run point-statistics (ps) metrics.

Convenience wrapper around point-level spatial statistics. Applies shared transcript and cell filtering (by gene(s) and cell type) and runs, in order:

  1. percentage of transcripts in compartments (nucleus overlap, cytoplasm, outside)

  2. distance to centroid (cell or nucleus)

  3. distance to membrane (cell or nucleus)

  4. membrane-distance skewness

Step 1 requires nucleus shapes. If nucleus_shapes_key is None or does not exist in sdata.shapes, a warning is raised and step 1 is skipped.

[… Parameters section unchanged …]

Returns:

If inplace=True, returns None. If inplace=False, returns a dict with keys: - “percentage_transcripts_in_compartments” (None if skipped) - “distance_to_centroid” - “distance_to_membrane” - “membrane_distance_skewness”

Return type:

None or dict

run_region_similarity(n_jobs=None, parallel_backend='threading', inplace=True, iou_kwargs=None, similarity_nucleus_cell_kwargs=None, similarity_nucleus_cytoplasm_kwargs=None, border_admixture_score_kwargs=None, _leave=True)#

Compute region similarity metrics and optionally merge them into the cell table.

This runs, in order: 1) matching between each cell and its best-matching nucleus 2) similarity between per-cell expression and its matched nucleus 3) similarity between the cell’s nucleus-overlapping and cytoplasmic expression 4) border admixture score

Steps 1-3 require nucleus shapes. If nucleus_shapes_key is None or does not exist in sdata.shapes, a warning is raised, these steps are skipped, and only the border admixture score is computed.

Progress is reported via tqdm unless disabled through segtraq.settings.progress.

Returns:

If inplace=True, returns None after writing to sdata. If inplace=False, returns a dictionary of DataFrames. Entries for metrics that were skipped because no nucleus shapes were available are None.

Return type:

None or dict

run_supervised(*, adata_ref=None, ref_cell_type=None, ref_gene_key=None, query_gene_key=None, ref_raw_counts_layer=None, markers=None, cell_type_key=None, inplace=True, label_transfer_kwargs=None, markers_from_reference_kwargs=None, purity_kwargs=None, contamination_kwargs=None, mecr_kwargs=None, _leave=True)#

Run supervised (sp) metrics.

If markers is None, stored SegTraQ markers are used if available; otherwise they are generated from adata_ref.

If cell_type_key is None, label transfer is run first via self.run_label_transfer() using adata_ref and ref_cell_type. The resulting labels are stored under “transferred_cell_type”.

Runs, in order:

  1. label transfer

  2. marker generation from reference

  3. marker_purity

  4. neighbor_contamination

  5. mutually_exclusive_coexpression_rate

Progress is reported via tqdm unless disabled through segtraq.settings.progress. Only the steps that will actually run are counted.

Parameters:
  • adata_ref (AnnData) – Reference AnnData object used for mutually_exclusive_coexpression_rate and, when needed, label transfer and marker generation.

  • ref_cell_type (str) – Column in adata_ref.obs containing reference cell-type labels.

  • ref_gene_key (str or None, default None) – Column in adata_ref.var containing gene identifiers matching the query gene identifiers. If None, adata_ref.var_names are used.

  • query_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing gene identifiers matching adata_ref.var[ref_gene_key]. If None, tables_gene_key is used.

  • ref_raw_counts_layer (str or None, default None) – Layer containing raw counts. If None, raw counts are expected in adata.X.

  • markers (dict or None, default None) – Marker genes forwarded to run_supervised, in the form {cell_type: {“positive”: list[str], “negative”: list[str]}}. If None, markers stored in sdata.tables[tables_key].uns[“segtraq_markers”] are used if available. Otherwise, markers are derived from adata_ref.

  • cell_type_key (str | None = None) – Column in the query AnnData .obs with cell-type labels. If None, label transfer is run first using adata_ref and ref_cell_type, and the transferred labels are stored under “transferred_cell_type”.

  • inplace (bool, default True) – If True, writes results into .obs and/or .uns as implemented by the underlying functions and returns None. If False, returns all results as a dictionary.

  • label_transfer_kwargs (dict or None, optional) – Extra keyword arguments forwarded to self.run_label_transfer(). Must not contain arguments that run_supervised passes explicitly (the reference arguments, cell_type_key, inplace); pass the reference arguments directly to run_supervised instead.

  • markers_from_reference_kwargs (dict or None, optional) – Extra keyword arguments forwarded to self.markers_from_reference(). Must not contain the reference arguments (adata_ref, ref_cell_type, ref_gene_key, query_gene_key, ref_raw_counts_layer); pass them directly to run_supervised.

  • purity_kwargs (dict or None, optional) – Extra arguments for sp.marker_purity.

  • contamination_kwargs (dict or None, optional) – Extra arguments for sp.neighbor_contamination.

  • mecr_kwargs (dict or None, optional) – Extra arguments for sp.mutually_exclusive_coexpression_rate.

Returns:

If inplace=True, returns None. If inplace=False, returns a dictionary with keys “label_transfer”, “markers”, “marker_purity”, “neighbor_contamination”, and “mutually_exclusive_coexpression_rate”.

Return type:

None or dict

run_volume(*, adata_ref=None, ref_cell_type=None, ref_gene_key=None, query_gene_key=None, ref_raw_counts_layer=None, cell_type_key=None, run_ovrlpy=False, inplace=True, label_transfer_kwargs=None, similarity_kwargs=None, heterotypic_overlap_kwargs=None, vsi_kwargs=None, _leave=True)#

Run volume (vl) metrics.

Convenience wrapper around segtraq.vl functions via the instance facade self.vl.

If cell_type_key is provided, it is used for cell-type-aware metrics and to infer the number of ovrlpy components from sdata.tables[tables_key].obs[cell_type_key].

If cell_type_key is None and adata_ref is provided, label transfer is run first via self.run_label_transfer() using adata_ref and ref_cell_type. The resulting labels are stored under “transferred_cell_type”.

If neither cell_type_key nor adata_ref is provided, cell-type-aware metrics are skipped and ovrlpy is run with its default number of components.

A precomputed ovrlpy.Ovrlp object can be passed via vsi_kwargs={“ovrlp”: ovrlp}. In that case, ovrlpy is not run internally and n_components is not inferred.

Runs, in order:

  1. similarity_top_bottom

  2. label transfer, if needed and possible

  3. vertical_signal_integrity_per_cell (disabled by default, use run_ovrlpy=True)

  4. fraction_heterotypic_overlap, only if cell-type labels and valid shapes are available

Progress is reported via tqdm unless disabled through segtraq.settings.progress. Only the steps that will actually run are counted.

Parameters:
  • adata_ref (AnnData or None, default None) – Reference AnnData object used for label transfer and/or to infer the number of ovrlpy components from reference cell-type labels.

  • ref_cell_type (str or None, default None) – Column in adata_ref.obs containing reference cell-type labels. Required if cell_type_key=None and label transfer should be run, or if adata_ref is used to infer n_components.

  • ref_gene_key (str or None, default None) – Column in adata_ref.var containing gene identifiers. If None, adata_ref.var_names are used.

  • query_gene_key (str or None, default None) – Column in sdata.tables[tables_key].var containing gene identifiers matching adata_ref.var[ref_gene_key]. If None, tables_gene_key is used.

  • ref_raw_counts_layer (str or None, default None) – Layer containing raw counts. If None, raw counts are expected in adata.X.

  • cell_type_key (str or None, default None) – Column in sdata.tables[tables_key].obs containing cell-type labels. If provided, this column is used for fraction_heterotypic_overlap and to infer ovrlpy n_components. If None and adata_ref is provided, label transfer is run first and labels are stored under “transferred_cell_type”.

  • run_ovrlpy (bool, default False) – If True, runs ovrlpy to compute vertical signal integrity per cell. If False, this step is skipped and vsi_kwargs are ignored.

  • inplace (bool, default True) – If True, writes results into sdata.tables[tables_key].obs as implemented by the underlying functions and returns None. If False, returns all results as a dictionary.

  • label_transfer_kwargs (dict or None, optional) – Extra keyword arguments forwarded to self.run_label_transfer(). Do not include adata_ref or ref_cell_type here; pass them directly to run_volume.

  • similarity_kwargs (dict or None, optional) – Extra keyword arguments forwarded to vl.similarity_top_bottom.

  • heterotypic_overlap_kwargs (dict or None, optional) – Extra keyword arguments forwarded to vl.fraction_heterotypic_overlap.

  • vsi_kwargs (dict or None, optional) – Extra keyword arguments forwarded to vl.vertical_signal_integrity_per_cell. To use a precomputed ovrlpy object, pass it here as {“ovrlp”: ovrlp}.

Returns:

If inplace=True, returns None.

If inplace=False, returns a dictionary with available metric results.

Return type:

None or dict[str, object]