quadsv.utils#

General-purpose helpers: grid/coordinate generators, periodic-domain distance matrices, Visium I/O, and the Benjamini–Hochberg correction used by every detector / comparator.

Attributes#

Functions#

compute_torus_distance_matrix(phys_coords, domain_dims)

Pairwise Euclidean distances on a rectangular torus.

convert_visium_to_physical(coords)

Convert integer Visium (row, col) indices to physical (y, x).

get_rect_coords([n_rows, n_cols])

Generate rectangular grid coordinates with unit spacing.

get_visium_coords([n_rows, n_cols])

Generate Visium-like hexagonal array indices.

load_visium_sample(path[, matrix_path, in_tissue_only])

Load a Visium Space Ranger output directory as anndata.AnnData.

visium_hex_spacing_um([spot_spacing_um, grid])

Physical (dy, dx) per grid cell for a Visium hex raster.

visium_to_grid(adata[, genes, layer, grid, fill, ...])

Rasterize a Visium adata onto a regular rectangular grid.

Module Contents#

quadsv.utils.compute_torus_distance_matrix(phys_coords, domain_dims)[source]#

Pairwise Euclidean distances on a rectangular torus.

Each pair’s distance is the minimum over direct and wrap-around offsets: d_wrapped = min(|Δp|, D - |Δp|) per axis.

Parameters:
  • phys_coords (np.ndarray) – (n, 2) [[y, x], ...].

  • domain_dims (tuple of float) – Periodic domain extent (height, width).

Returns:

(n, n) pairwise distances.

Return type:

np.ndarray

Examples

>>> coords = np.array([[0.0, 0.0], [1.0, 0.0], [9.9, 0.0]])
>>> dists = compute_torus_distance_matrix(coords, (10.0, 10.0))
>>> round(dists[0, 2], 2)
0.1
quadsv.utils.convert_visium_to_physical(coords)[source]#

Convert integer Visium (row, col) indices to physical (y, x).

Hexagonal geometry with equilateral triangles: Δcol = 2 Δx = 1 and Δrow = 1 Δy = √3/2.

Parameters:

coords (np.ndarray) – (n, 2) [[row, col], ...] (integers, from get_visium_coords() or adata.obs[['array_row','array_col']]).

Returns:

(n, 2) [[y, x], ...] with y = row · √3/2, x = col / 2.

Return type:

np.ndarray

Examples

>>> coords = np.array([[0, 0], [0, 2], [1, 1]])
>>> convert_visium_to_physical(coords)
array([[0.       , 0.       ],
       [0.       , 1.       ],
       [0.8660254, 0.5      ]])
quadsv.utils.get_rect_coords(n_rows=32, n_cols=32)[source]#

Generate rectangular grid coordinates with unit spacing.

Parameters:
  • n_rows (int) – Grid dimensions.

  • n_cols (int) – Grid dimensions.

Returns:

  • coords (np.ndarray) – (n, 2) row-major [[y, x], ...] with n = n_rows · n_cols.

  • grid_dims (tuple of int) – (n_rows, n_cols).

Return type:

tuple[ndarray, tuple[int, int]]

Examples

>>> coords, dims = get_rect_coords(n_rows=10, n_cols=10)
>>> coords.shape
(100, 2)
>>> dims
(10, 10)
quadsv.utils.get_visium_coords(n_rows=78, n_cols=64)[source]#

Generate Visium-like hexagonal array indices.

Offset-column layout: even rows use even array_col indices, odd rows use odd indices. Each row holds n_cols spots.

Parameters:
  • n_rows (int, default 78) – Number of array rows (78 for a full Visium v1 slide).

  • n_cols (int, default 64) – Spots per row.

Returns:

  • coords (np.ndarray) – (n_rows · n_cols, 2) integer [[row, col], ...].

  • grid_dims (tuple of int) – (n_rows, n_cols).

Return type:

tuple[ndarray, tuple[int, int]]

See also

convert_visium_to_physical

Map these indices to physical (y, x).

Examples

>>> coords, dims = get_visium_coords(n_rows=78, n_cols=64)
>>> coords.shape[0]
4992
quadsv.utils.load_visium_sample(path, matrix_path=None, in_tissue_only=True)[source]#

Load a Visium Space Ranger output directory as anndata.AnnData.

Accepts either the flat layout (<path>/<sample>_filtered_feature_bc_matrix.h5 + <path>/spatial/) or the canonical Space Ranger outs/ layout (<path>/filtered_feature_bc_matrix.h5 + <path>/spatial/); auto-detects.

Parameters:
  • path (str or Path) – Directory holding the filtered matrix and spatial/ subfolder.

  • matrix_path (str or Path, optional) – Explicit path to the filtered .h5 matrix. Defaults to <path>/filtered_feature_bc_matrix.h5 or *_filtered_feature_bc_matrix.h5.

  • in_tissue_only (bool, default True) – Restrict to spots with in_tissue == 1.

Returns:

adata.obs has in_tissue, array_row, array_col, pxl_row_in_fullres, pxl_col_in_fullres. adata.obsm['spatial'] holds (pxl_col, pxl_row) full-resolution pixel coords. adata.uns['spatial'] stores scalefactors_json.json and the source path.

Return type:

AnnData

Raises:
  • FileNotFoundError – If the matrix or spatial folder cannot be located.

  • ImportError – If anndata / scanpy are not installed.

quadsv.utils.visium_hex_spacing_um(spot_spacing_um=VISIUM_V1_SPOT_SPACING_UM, grid='dense')[source]#

Physical (dy, dx) per grid cell for a Visium hex raster.

Parameters:
  • spot_spacing_um (float, default 100.0) – Center-to-center distance between adjacent spots (100 μm for Visium v1).

  • grid ({'dense', 'collapsed'}, default 'dense') – Rasterization mode — see visium_to_grid().

Returns:

(dy, dx) in micrometres per grid cell.

Return type:

tuple of float

Raises:

ValueError – If grid is unknown.

quadsv.utils.visium_to_grid(adata, genes=None, layer=None, grid='dense', fill='nearest', spot_spacing_um=VISIUM_V1_SPOT_SPACING_UM, max_row=None, max_col=None)[source]#

Rasterize a Visium adata onto a regular rectangular grid.

Rasterization modes:

  • grid='dense' (default): (78, 128) array filled from real spots on half the cells; remaining cells imputed from their two nearest hex neighbours on the same row. Physical spacing (100·√3/2, 50) μm. Exact hex geometry preserved.

  • grid='collapsed': (78, 64) array using array_col // 2 as column index. Physical spacing (100·√3/2, 100) μm. Faster, but drops the 50 μm horizontal offset between alternating rows (≤5 % geometric distortion).

Parameters:
  • adata (AnnData) – Must carry adata.obs['array_row'] and adata.obs['array_col'] (e.g. from load_visium_sample()).

  • genes (list of str, optional) – Gene subset. None → all adata.var_names.

  • layer (str, optional) – adata.layers key. Noneadata.X.

  • grid ({'dense', 'collapsed'}, default 'dense')

  • fill ({'nearest', 'zero'}, default 'nearest') – Empty-cell handling. 'nearest' averages the two row-neighbour spots (avoids FFT aliasing); 'zero' leaves cells at 0. Ignored when grid='collapsed'.

  • spot_spacing_um (float, default 100.0)

  • max_row (int, optional) – Pad output to a common size; defaults to the maxima observed in adata.

  • max_col (int, optional) – Pad output to a common size; defaults to the maxima observed in adata.

Returns:

  • grid_arr (np.ndarray) – (n_genes, ny, nx) float64, ready for quadsv.power_spectrum_2d().

  • spacing_um (tuple of float) – (dy, dx) in μm.

Raises:
  • KeyError – If array_row / array_col are absent from adata.obs.

  • ValueError – If grid / fill are unknown, or layer is missing.

Return type:

tuple[ndarray, tuple[float, float]]

quadsv.utils.VISIUM_V1_SPOT_SPACING_UM: float = 100.0[source]#