spatialfeatureexperiment package¶
Submodules¶
spatialfeatureexperiment.aligned_spatialimage module¶
- class spatialfeatureexperiment.aligned_spatialimage.AlignedSpatialImage(metadata=None)[source]¶
Bases:
VirtualSpatialImage
Base class for spatial images with extent.
All images in SpatialFeatureExperiment have an extent in spatial coordinates.
- __abstractmethods__ = frozenset({'img_raster', 'img_source'})¶
- property extent: Dict[str, float]¶
Alias for
get_extent()
.
- get_extent()[source]¶
Get the spatial extent of the image.
Subclasses must implement this to return their specific extent.
- class spatialfeatureexperiment.aligned_spatialimage.BioFormatsImage(path, extent=None, is_full=True, origin=None, transformation=None, metadata=None, validate=True)[source]¶
Bases:
AlignedSpatialImage
On-disk representation of BioFormats images (e.g., OME-TIFF) in SFE objects.
This class uses aicsimageio for reading, aligning with R’s BioFormatsImage.
Transformations are stored and applied lazily.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {'_combined_affine_matrix': 'Optional[np.ndarray]', '_transformation_list': 'List[Dict[str, Any]]'}¶
- __init__(path, extent=None, is_full=True, origin=None, transformation=None, metadata=None, validate=True)[source]¶
Initialize the BioFormatsImage.
- Parameters:
path (
Union
[str
,Path
]) – Path to the image file (e.g., OME-TIFF).extent (
Optional
[Dict
[str
,float
]]) – The spatial extent of the image IF KNOWN and potentially different from full. If None, it’s inferred from metadata (full extent).is_full (
bool
) – Whether the provided/inferred extent is the full image.origin (
Optional
[List
[float
]]) – Spatial coordinates [x, y] of the image’s own origin (often [0,0] in its coordinate system).transformation (
Union
[List
[Dict
[str
,Any
]],ndarray
,None
]) – Stored transformation(s) to be applied. Can be a list of dicts (e.g. [{‘type’: ‘rotate’, ‘degrees’: 90}]) or a single 2x3 or 3x3 affine numpy matrix.validate (
bool
) – Internal use only.
- get_dimensions()[source]¶
Get the dimensions of the image (X, Y, C, Z, T) from metadata.
This refers to the dimensions of the source image file, not affected by transformations.
- get_extent()[source]¶
Get the spatial extent of the image, applying stored transformations to the base extent.
- img_raster(resolution=None, scene=0, channel=None, **kwargs)[source]¶
Load the image data as a PIL Image, applying transformations.
This calls to_ext_image and then extracts the PIL image. resolution here might map to scene in aicsimageio if multi-resolution is stored as scenes.
Defaulting to scene 0.
- Return type:
Image
- class spatialfeatureexperiment.aligned_spatialimage.ExtImage(image, extent=None, metadata=None)[source]¶
Bases:
AlignedSpatialImage
In-memory image using PIL/numpy arrays with spatial extent information.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {'_array': 'np.ndarray', '_pil_image_cache': 'Optional[Image.Image]'}¶
- __init__(image, extent=None, metadata=None)[source]¶
Initialize an ExtImage.
- Parameters:
image (
Union
[Image
,ndarray
]) – The image data (PIL Image or numpy array).extent (
Optional
[Dict
[str
,float
]]) – The spatial extent of the image. Must have keys: ‘xmin’, ‘xmax’, ‘ymin’, ‘ymax’. If None, and image is numpy array, defaults to pixel extent.metadata (
Optional
[dict
]) – Additional image metadata. Defaults to None.
- property array: ndarray¶
Get the image as a numpy array (height, width, channels) or (height, width).
- get_dimensions()[source]¶
Get the dimensions of the image array (height, width, channels) or (height, width).
- img_source(as_path=False)[source]¶
Get the source file path (always None for in-memory ExtImage).
- Return type:
- class spatialfeatureexperiment.aligned_spatialimage.SpatRasterImage(image, extent=None, metadata=None)[source]¶
Bases:
AlignedSpatialImage
SpatRaster representation of images in SpatialFeatureExperiment objects.
This class is a wrapper around rasterio for handling GeoTIFF images, aligning with R’s SpatRasterImage which uses terra::SpatRaster.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {'_img_source': 'Optional[str]', '_in_memory': 'bool', '_src': 'Optional[rasterio.DatasetReader]'}¶
- __init__(image, extent=None, metadata=None)[source]¶
Initialize a SpatRasterImage.
- Parameters:
image (
Union
[DatasetReader
,ndarray
]) – The image data, either as a rasterio dataset or a numpy array.extent (
Optional
[Dict
[str
,float
]]) –The spatial extent of the image. Required if image is a numpy array.
If image is a rasterio.DatasetReader, extent is inferred if not provided.
Must have keys: ‘xmin’, ‘xmax’, ‘ymin’, ‘ymax’.
metadata (
Optional
[dict
]) – Additional image metadata. Defaults to None.
- property array: ndarray¶
Get the image as a numpy array (loads into memory if not already).
- Returns:
NumPy array in (height, width, channels) or (height, width) format.
- img_raster(window=None, out_shape=None, resampling_method_str='nearest')[source]¶
Load the image data as a numpy array.
- Parameters:
- Return type:
- Returns:
Image data as a numpy array (bands, height, width) or (height, width) if single band.
- property shape: Tuple[int, int, int]¶
Get the shape of the image (height, width, channels/bands).
This matches common numpy/PIL dimension order after loading.
spatialfeatureexperiment.coercions module¶
- spatialfeatureexperiment.coercions.dataframe_to_geopandas(coords_df, spatial_coordinates_names=None, spot_diameter=None, buffer_radius=1.0, vertices_col=None, geometry_type='POINT', end_cap_style='ROUND')[source]¶
Convert DataFrame coordinates to a Geopandas DataFrame.
- Parameters:
coords_df (
DataFrame
) – DataFrame with coordinates.spatial_coordinates_names (
list
) – Names of the coordinate columns.spot_diameter (
float
) – Diameter of spots for creating buffers.buffer_radius (
float
) – Radius for buffering, used if geometry_type is ‘POLYGON’ and ‘vertices_col’ is not provided, or for ‘POINT’ if spot_diameter is given.vertices_col (
Optional
[str
]) – Name of a column in coords_df that contains lists of coordinate tuples for creating POLYGON or MULTIPOINT geometries. For POLYGON: [(x1,y1), (x2,y2), …, (xn,yn)] For MULTIPOINT: [(x1,y1), (x2,y2)] or list of Point objects.geometry_type (
Literal
['POINT'
,'POLYGON'
,'MULTIPOINT'
]) – Type of geometry to create (‘POINT’, ‘POLYGON’, ‘MULTIPOINT’).end_cap_style (
Literal
['ROUND'
,'FLAT'
,'SQUARE'
]) – Style of the end cap for buffered geometries (“ROUND”, “FLAT”, “SQUARE”).
- Return type:
GeoDataFrame
- Returns:
GeoDataFrame with geometries.
- spatialfeatureexperiment.coercions.df_dict_to_gdf_dict(df_dict, spatial_coordinates_names=None, geometry_type='POINT', spot_diameter=None, buffer_radius=1.0, vertices_col=None, end_cap_style='ROUND')[source]¶
Convert a list of DataFrames to a list of GeoPandas DataFrames.
- Parameters:
df_dict – Dictionary of DataFrames with coordinates.
spatial_coordinates_names (
list
) – Names of the coordinate columns.spot_diameter (
float
) – Diameter of spots for creating buffers.geometry_type (
Literal
['POINT'
,'POLYGON'
,'MULTIPOINT'
]) – Type of geometry to create (‘POINT’, ‘POLYGON’, ‘MULTIPOINT’).buffer_radius (
float
) – Radius for buffering, used if geometry_type is ‘POLYGON’ and ‘vertices_col’ is not provided, or for ‘POINT’ if spot_diameter is given.vertices_col (
Optional
[str
]) – Name of a column in coords_df that contains lists of coordinate tuples for creating POLYGON or MULTIPOINT geometries. For POLYGON: [(x1,y1), (x2,y2), …, (xn,yn)] For MULTIPOINT: [(x1,y1), (x2,y2)] or list of Point objects.end_cap_style (
Literal
['ROUND'
,'FLAT'
,'SQUARE'
]) – Style of the end cap for buffered geometries.
- Return type:
- Returns:
Dictionary of GeoDataFrames.
- spatialfeatureexperiment.coercions.spatial_coords_to_col_geometries(coords, spot_diameter=None, end_cap_style='ROUND')[source]¶
Convert spatial coordinates to column geometries.
- spatialfeatureexperiment.coercions.spe_to_sfe(spe, row_geometries=None, column_geometries=None, annotation_geometries=None, spatial_coordinates_names=None, row_geometry_type='POINT', annotation_geometry_type='POLYGON', vertices_col_row=None, vertices_col_annot=None, buffer_radius_row=1.0, buffer_radius_annot=1.0, spatial_graphs=None, spot_diameter=None, unit=None, end_cap_style='ROUND', add_centroids_if_spots_are_polygons=True)[source]¶
Convert a SpatialExperiment to a SpatialFeatureExperiment.
- Parameters:
spe (
SpatialExperiment
) – SpatialExperiment object.column_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Column geometries.row_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Row geometries.annotation_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Annotation geometries.spatial_coordinates_names (
list
) – Names of spatial coordinates.row_geometry_type (
Literal
['POINT'
,'POLYGON'
,'MULTIPOINT'
]) – Default geometry type for row_geometries if converting from DataFrame.annotation_geometry_type (
Literal
['POINT'
,'POLYGON'
,'MULTIPOINT'
]) – Default geometry type for annot_geometries if converting from DataFrame.vertices_col_row (
Optional
[str
]) – Column name with vertex lists for complex row geometries.vertices_col_annot (
Optional
[str
]) – Column name with vertex lists for complex annotation geometries.buffer_radius_row (
float
) – Buffer radius for simple row polygons.buffer_radius_annot (
float
) – Buffer radius for simple annotation polygons.spatial_graphs (
Optional
[Dict
[str
,Union
[Graph
,Any
]]]) – Spatial graphs.spot_diameter (
float
) – Diameter of spots.unit (
str
) – Unit of measurement.end_cap_style (
Literal
['ROUND'
,'FLAT'
,'SQUARE'
]) – Style of end cap for buffered geometries.add_centroids – Whether to add centroids to column geometries.
add_centroids_if_spots_are_polygons (
bool
) – If spot diameter is set, also add ‘centroids’.
- Returns:
SpatialFeatureExperiment object.
spatialfeatureexperiment.sfe module¶
- class spatialfeatureexperiment.sfe.SpatialFeatureExperiment(assays=None, row_ranges=None, row_data=None, column_data=None, row_names=None, column_names=None, metadata=None, reduced_dims=None, main_experiment_name=None, alternative_experiments=None, alternative_experiment_check_dim_names=True, row_pairs=None, column_pairs=None, spatial_coords=None, img_data=None, col_geometries=None, row_geometries=None, annot_geometries=None, spatial_graphs=None, unit='full_res_image_pixel', validate=True, **kwargs)[source]¶
Bases:
SpatialExperiment
Container class for storing data from spatial-omics experiments with feature geometries.
This class extends SpatialExperiment to provide slots for geometries of spots/cells, tissue boundaries, pathologist annotations and other spatial features.
- __init__(assays=None, row_ranges=None, row_data=None, column_data=None, row_names=None, column_names=None, metadata=None, reduced_dims=None, main_experiment_name=None, alternative_experiments=None, alternative_experiment_check_dim_names=True, row_pairs=None, column_pairs=None, spatial_coords=None, img_data=None, col_geometries=None, row_geometries=None, annot_geometries=None, spatial_graphs=None, unit='full_res_image_pixel', validate=True, **kwargs)[source]¶
Initialize a spatial feature class.
- Parameters:
A dictionary containing matrices, with assay names as keys and 2-dimensional matrices represented as either
ndarray
orspmatrix
.Alternatively, you may use any 2-dimensional matrix that has the
shape
property and implements the slice operation using the__getitem__
dunder method.All matrices in assays must be 2-dimensional and have the same shape (number of rows, number of columns).
row_ranges (
Union
[GenomicRanges
,GenomicRangesList
,None
]) – Genomic features, must be the same length as the number of rows of the matrices in assays.row_data (
Optional
[BiocFrame
]) –Features, must be the same length as the number of rows of the matrices in assays.
Feature information is coerced to a
BiocFrame
. Defaults to None.column_data (
Optional
[BiocFrame
]) –Sample data, must be the same length as the number of columns of the matrices in assays. For instances of the
SpatialExperiment
class, the sample data must include a column named sample_id. If any ‘sample_id’ in the sample data is not present in the ‘sample_id’s of ‘img_data’, a warning will be issued.If sample_id is not present, a column with this name will be created and filled with the default value sample01.
Sample information is coerced to a
BiocFrame
. Defaults to None.row_names (
Optional
[List
[str
]]) – A list of strings, same as the number of rows.Defaults to None.column_names (
Optional
[List
[str
]]) – A list of strings, same as the number of columns. Defaults to None.metadata (
Optional
[dict
]) – Additional experimental metadata describing the methods. Defaults to None.reduced_dims (
Optional
[Dict
[str
,Any
]]) –Slot for low-dimensionality embeddings.
Usually a dictionary with the embedding method as keys (e.g., t-SNE, UMAP) and the dimensions as values.
Embeddings may be represented as a matrix or a data frame, must contain a shape.
main_experiment_name (
Optional
[str
]) – A string, specifying the main experiment name.alternative_experiments (
Optional
[Dict
[str
,Any
]]) –Used to manage multi-modal experiments performed on the same sample/cells.
Alternative experiments must contain the same cells (rows) as the primary experiment. It’s a dictionary with keys as the names of the alternative experiments (e.g., sc-atac, crispr) and values as subclasses of
SummarizedExperiment
.alternative_experiment_check_dim_names (
bool
) –Whether to check if the column names of the alternative experiment match the column names of the main experiment. This is the equivalent to the
withDimnames
parameter in the R implementation.Defaults to True.
Row pairings/relationships between features.
Defaults to None.
column_pairs (
Optional
[Any
]) –Column pairings/relationships between cells.
Defaults to None.
spatial_coords (
Union
[BiocFrame
,ndarray
,None
]) –Optional
ndarray
orBiocFrame
containing columns of spatial coordinates. Must be the same length as column_data.If spatial_coords is a
BiocFrame
, typical column names might include:[‘x’, ‘y’]: For simple 2D coordinates.
[‘pxl_col_in_fullres’, ‘pxl_row_in_fullres’]: For pixel-based
coordinates in full-resolution images.
If spatial coordinates is a
DataFrame
or None, it is coerced to aBiocFrame
. Defaults to None.img_data (
Optional
[BiocFrame
]) –- Optional
BiocFrame
containing the image data, structured with the following columns: sample_id (str): A string identifier for the sample to which an image corresponds.
image_id (str): A unique string identifier for each image within each sample.
data (VirtualSpatialImage): The image itself, represented as a VirtualSpatialImage object or one of its subclasses.
scale_factor (float): A numerical value that indicates the scaling factor applied to the image.
All ‘sample_id’s in ‘img_data’ must be present in the ‘sample_id’s of ‘column_data’.
Image data are coerced to a
BiocFrame
. Defaults to None.- Optional
col_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Dictionary of GeoDataFrames containing geometries for columns (e.g. cells, spots).row_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Dictionary of GeoDataFrames containing geometries for rows (e.g. genes).annot_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Dictionary of GeoDataFrames containing annotation geometries (e.g. tissue boundaries).spatial_graphs (
Optional
[Dict
[str
,Union
[Graph
,Any
]]]) – A Dictionary containing spatial neighborhood graphs represented asGraph
.unit (
str
) – Unit for spatial coordinates (‘full_res_image_pixel’ or ‘micron’).validate (
bool
) – Internal use only.
- copy()[source]¶
Alias for
__copy__()
.
- classmethod from_spatial_experiment(input, row_geometries=None, column_geometries=None, annotation_geometries=None, spatial_coordinates_names=None, annotation_geometry_type='POLYGON', spatial_graphs=None, spot_diameter=None, unit=None)[source]¶
Coerce a :py:class:~`spatialexperiment.SpatialExperiment` to a SpatialFeatureExperiment.
- Parameters:
input (
SpatialExperiment
) – SpatialExperiment object.row_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Row geometries. Defaults to None.column_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Column geometries. Defaults to None.annotation_geometries (
Optional
[Dict
[str
,GeoDataFrame
]]) – Annotation geometries. Defaults to None.spatial_coordinates_names (
list
) – Names of spatial coordinates. Defaults to None.annotation_geometry_type (
str
) – Type og annotation geometry. Defaults to “POLYGON”.spatial_graphs (
BiocFrame
) – Spatial graphs. Defaults to None.spot_diameter (
float
) – Diameter of spots. Defaults to None.unit (
str
) – Unit of measurement. Defaults to None.
- Return type:
- set_annot_geometries(geometries, in_place=False)[source]¶
Set annotation geometries.
- Parameters:
- Return type:
- Returns:
A modified
SpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
- set_col_geometries(geometries, in_place=False)[source]¶
Set column geometries.
- Parameters:
- Return type:
- Returns:
A modified
SpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
- set_column_data(cols, replace_column_names=False, in_place=False)[source]¶
Override: Set sample data.
- Parameters:
cols (
Optional
[BiocFrame
]) –New sample data. If ‘cols’ contains a column named ‘sample_id’s, a check is performed to ensure that all ‘sample_id’s in the ‘img_data’ are present. If any ‘sample_id’ in the ‘cols’ is not present in the ‘sample_id’s of ‘img_data’, a warning will be issued.
If ‘sample_id’ is not present or ‘cols’ is None, the original ‘sample_id’s are retained.
replace_column_names (
bool
) – Whether to replace experiment’s column_names with the names from the new object. Defaults to False.in_place (
bool
) – Whether to modify theSpatialFeatureExperiment
in place. Defaults to False.
- Return type:
- Returns:
A modified
SpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
- set_row_geometries(geometries, in_place=False)[source]¶
Set row geometries.
- Parameters:
- Return type:
- Returns:
A modified
SpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
- set_spatial_graphs(graphs, in_place=False)[source]¶
Set spatial neighborhood graphs.
- Parameters:
- Return type:
- Returns:
A modified
SpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.