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_neighborsis 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(default:'spatial') Key in
anndata.AnnData.obsmwhere spatial coordinates are stored. If adata is aspatialdata.SpatialData, the coordinates of the centroids will be stored in the adata with this key.- elements_to_coordinate_systems
dict[str,str] |None(default: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(default:None) Key in
spatialdata.SpatialData.tableswhere the spatialdata table is stored. Must not be None if adata is aspatialdata.SpatialData.- library_key
str|None(default:None) If multiple library_id, column in
anndata.AnnData.obswhich stores mapping betweenlibrary_idand obs.- coord_type
Literal['grid','generic'] |None(default:None) Type of coordinate system. Valid options are:
’grid’ - grid coordinates.
’generic’ - generic coordinates.
None - ‘grid’ if
spatial_keyis inanndata.AnnData.unswithn_neighs = 6(Visium), otherwise use ‘generic’.
- n_neighs
int|None(default: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(default:None) Only available when
coord_type = 'generic'. Depending on the type:- delaunay
bool|None(default:None) Whether to compute the graph from Delaunay triangulation. Only used when
coord_type = 'generic'. Defaults toFalse.- n_rings
int|None(default:None) Number of rings of neighbors for grid data. Only used when
coord_type = 'grid'. Defaults to1.- percentile
float|None(default:None) Percentile of the distances to use as threshold. Only used when
coord_type = 'generic'.- transform
Literal['spectral','cosine'] |None(default: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(default:False) Whether to set the diagonal of the spatial connectivities to 1.0.
- key_added
str(default:'spatial') Key which controls where the results are saved if
copy = False.- copy
bool(default:False) If
True, return the result, otherwise save it to theadataobject.- n_jobs
int(default:1) Number of parallel jobs used to build the per-library graphs when
library_keyis set. Each library’s graph is computed independently, so this only has an effect for multi-library data.1builds the graphs sequentially and does not change behavior, and it has no effect whenlibrary_keyisNone. None and-1use numba’s default thread count (NUMBA_NUM_THREADS); asking for more threads than that warns and falls back to it, while0and values below-1raise, since scanpy only supportsn_jobs >= -1. Speedup is sub-linear (memory-bandwidth bound), so parallelism mainly pays off for many large libraries.
- adata
Notes
spatial_neighborshas 4 graph-construction modes:Grid mode:
coord_type='grid'. Usesn_neighsandn_rings.radiusis ignored.delaunayis 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. Usesn_neighs.Generic radius mode:
coord_type='generic',delaunay=False,radiusset. Usesradiusand builds a radius-based neighbor graph.n_neighsis ignored and will throw a warning if passed. Ifradiusis 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_neighsis ignored by the triangulation and will throw a warning if passed. Ifradiusis a tuple, it is used only as a post-construction pruning interval.
Across these modes:
percentileonly affects generic graphs.transformandset_diagapply 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_typeresolves to'grid', grid mode is used. In that caseradiusis ignored.Otherwise, if
delaunay=True, Delaunay mode is used.n_neighsis ignored (deprecated, removed in v1.9.0). A tupleradiusis only used afterward as a pruning interval. A scalarradiusis ignored.Otherwise, if
radiusis set, radius mode is used. In this moden_neighsis ignored (deprecated, removed in v1.9.0).Otherwise, k-nearest-neighbor mode is used.
Grid-specific behavior#
Grid mode currently does not validate
n_neighsto a fixed set such as{4, 6}. Internally it first queries then_neighsnearest candidates and then applies a distance-based correction tuned for grid-like coordinates. As a result:values such as
n_neighs=4andn_neighs=6are 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.
- return:
SpatialNeighborsResult|None– Ifcopy = True, returns aSpatialNeighborsResultwith the spatial connectivities and distances matrices.Otherwise, modifies the
adatawith the following keys:anndata.AnnData.obsp['{key_added}_connectivities']- the spatial connectivities.anndata.AnnData.obsp['{key_added}_distances']- the spatial distances.anndata.AnnData.uns['{key_added}']-dictcontaining parameters.