squidpy.gr.spatial_neighbors

squidpy.gr.spatial_neighbors(adata, spatial_key='spatial', elements_to_coordinate_systems=None, table_key=None, library_key=None, coord_type=None, n_neighs=None, radius=None, delaunay=None, n_rings=None, percentile=None, transform=None, set_diag=False, key_added='spatial', copy=False, n_jobs=1)[source]

Create a graph from spatial coordinates.

Deprecated since version 1.7.0: spatial_neighbors is deprecated and will be removed in squidpy v1.9.0. Use one of the mode-specific functions instead:

Parameters:
  • adata (AnnData | SpatialData) – Annotated data object.

  • spatial_key (str) – Key in anndata.AnnData.obsm where spatial coordinates are stored. If adata is a spatialdata.SpatialData, the coordinates of the centroids will be stored in the adata with this key.

  • elements_to_coordinate_systems (dict[str, str] | None) – A dictionary mapping element names of the SpatialData object to coordinate systems. The elements can be either Shapes or Labels. For compatibility, the spatialdata table must annotate all regions keys. Must not be None if adata is a spatialdata.SpatialData.

  • table_key (str | None) – Key in spatialdata.SpatialData.tables where the spatialdata table is stored. Must not be None if adata is a spatialdata.SpatialData.

  • library_key (str | None) – If multiple library_id, column in anndata.AnnData.obs which stores mapping between library_id and obs.

  • coord_type (str | CoordType | None) –

    Type of coordinate system. Valid options are:

    • ’grid’ - grid coordinates.

    • ’generic’ - generic coordinates.

    • None - ‘grid’ if spatial_key is in anndata.AnnData.uns with n_neighs = 6 (Visium), otherwise use ‘generic’.

  • n_neighs (int | None) –

    Depending on the coord_type:

    • ’grid’ - number of neighboring tiles.

    • ’generic’ - number of neighborhoods for non-grid data. Only used when delaunay = False.

    Defaults to 6.

  • radius (float | tuple[float, float] | None) –

    Only available when coord_type = 'generic'. Depending on the type:

    • float - compute the graph based on neighborhood radius.

    • tuple - prune the final graph to only contain edges in interval [min(radius), max(radius)].

  • delaunay (bool | None) – Whether to compute the graph from Delaunay triangulation. Only used when coord_type = 'generic'. Defaults to False.

  • n_rings (int | None) – Number of rings of neighbors for grid data. Only used when coord_type = 'grid'. Defaults to 1.

  • percentile (float | None) – Percentile of the distances to use as threshold. Only used when coord_type = 'generic'.

  • transform (str | Transform | None) –

    Type of adjacency matrix transform. Valid options are:

    • ’spectral’ - spectral transformation of the adjacency matrix.

    • ’cosine’ - cosine transformation of the adjacency matrix.

    • None - no transformation of the adjacency matrix.

  • set_diag (bool) – Whether to set the diagonal of the spatial connectivities to 1.0.

  • key_added (str) – Key which controls where the results are saved if copy = False.

  • copy (bool) – If True, return the result, otherwise save it to the adata object.

  • n_jobs (int) – Number of parallel jobs used to build the per-library graphs when library_key is set. Each library’s graph is computed independently, so this only has an effect for multi-library data. 1 (default) builds the graphs sequentially and does not change behavior; -1 uses all available CPUs. Has no effect when library_key is None. Speedup is sub-linear (memory-bandwidth bound), and process-based backends pay a one-time worker start-up cost, so parallelism mainly pays off for many large libraries.

Notes

spatial_neighbors has 4 graph-construction modes:

  • Grid mode: coord_type='grid'. Uses n_neighs and n_rings. radius is ignored. delaunay is forwarded to the underlying grid connectivity builder. This is the mode used for Visium-like grid coordinates.

  • Generic k-nearest-neighbor mode: coord_type='generic', delaunay=False, radius=None. Uses n_neighs.

  • Generic radius mode: coord_type='generic', delaunay=False, radius set. Uses radius and builds a radius-based neighbor graph. n_neighs is ignored and will throw a warning if passed. If radius is a tuple, the graph is built with the maximum radius and then pruned to the interval [min(radius), max(radius)].

  • Generic Delaunay mode: coord_type='generic', delaunay=True. Builds a Delaunay triangulation graph. n_neighs is ignored by the triangulation and will throw a warning if passed. If radius is a tuple, it is used only as a post-construction pruning interval.

Across these modes:

  • percentile only affects generic graphs.

  • transform and set_diag apply to all modes.

  • By default, observations are not treated as their own neighbors. The distance matrix always has a zero diagonal. The connectivity matrix only gets a nonzero diagonal when set_diag=True.

Argument precedence

The mode is resolved as follows:

  • If coord_type resolves to 'grid', grid mode is used. In that case radius is ignored.

  • Otherwise, if delaunay=True, Delaunay mode is used. n_neighs is ignored (deprecated, removed in v1.9.0). A tuple radius is only used afterward as a pruning interval. A scalar radius is ignored.

  • Otherwise, if radius is set, radius mode is used. In this mode n_neighs is ignored (deprecated, removed in v1.9.0).

  • Otherwise, k-nearest-neighbor mode is used.

Grid-specific behavior

Grid mode currently does not validate n_neighs to a fixed set such as {4, 6}. Internally it first queries the n_neighs nearest candidates and then applies a distance-based correction tuned for grid-like coordinates. As a result:

  • values such as n_neighs=4 and n_neighs=6 are the intended square-grid and hex-grid choices, respectively;

  • other values are accepted for backward compatibility, but their geometric interpretation is not guaranteed to match a continuous ring on the grid;

  • no clockwise or other within-ring ordering is part of the public API.

rtype:

SpatialNeighborsResult | None

returns:

If copy = True, returns a SpatialNeighborsResult with the spatial connectivities and distances matrices.

Otherwise, modifies the adata with the following keys: