spatialexperiment package

Subpackages

Submodules

spatialexperiment.ProxySFE module

class spatialexperiment.ProxySFE.ProxySpatialFeatureExperiment(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.

__copy__()[source]
Returns:

A shallow copy of the current SpatialExperiment.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current SpatialExperiment.

__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:
  • assays (Dict[str, Any]) –

    A dictionary containing matrices, with assay names as keys and 2-dimensional matrices represented as either ndarray or spmatrix.

    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_pairs (Optional[Any]) –

    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 or BiocFrame 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 a BiocFrame. 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.

  • 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[BiocFrame]) – BiocFrame containing spatial neighborhood graphs.

  • unit (str) – Unit for spatial coordinates (‘full_res_image_pixel’ or ‘micron’).

  • validate (bool) – Internal use only.

__repr__()[source]

Get string representation.

Return type:

str

property annot_geometries: Dict[str, GeoDataFrame]

Get annotation geometries.

property col_geometries: Dict[str, GeoDataFrame]

Get column geometries.

copy()[source]

Alias for __copy__().

get_annot_geometries()[source]

Get annotation geometries.

Return type:

Dict[str, GeoDataFrame]

get_col_geometries()[source]

Get column geometries.

Return type:

Dict[str, GeoDataFrame]

get_row_geometries()[source]

Get row geometries.

Return type:

Dict[str, GeoDataFrame]

get_slice(rows=None, columns=None)[source]

Get a slice of the experiment.

Parameters:
Return type:

ProxySpatialFeatureExperiment

Returns:

Sliced ProxySpatialFeatureExperiment.

get_spatial_graphs()[source]

Get spatial neighborhood graphs.

Return type:

Optional[BiocFrame]

get_unit()[source]

Get the coordinate unit.

Return type:

str

property row_geometries: Dict[str, GeoDataFrame]

Get row geometries.

set_annot_geometries(geometries, in_place=False)[source]

Set annotation geometries.

Parameters:
  • geometries (Dict[str, GeoDataFrame]) – New annotation geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • geometries (Dict[str, GeoDataFrame]) – New column geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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 the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • geometries (Dict[str, GeoDataFrame]) – New row geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • graphs (Optional[BiocFrame]) – New spatial graphs as BiocFrame.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_unit(unit, in_place=False)[source]

Set the coordinate unit.

Parameters:
  • unit (str) – New unit (‘full_res_image_pixel’ or ‘micron’).

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

property spatial_graphs: BiocFrame | None

Get spatial graphs.

property unit: str

Get coordinate unit.

spatialexperiment.SpatialExperiment module

class spatialexperiment.SpatialExperiment.SpatialExperiment(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, validate=True, **kwargs)[source]

Bases: SingleCellExperiment

Container class for storing data from spatial -omics experiments, extending SingleCellExperiment to provide slots for image data and spatial coordinates.

In contrast to R, ndarray or scipy matrices are unnamed and do not contain rownames and colnames. Hence, these matrices cannot be directly used as values in assays or alternative experiments. We strictly enforce type checks in these cases.

__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current SpatialExperiment.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current SpatialExperiment.

__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, validate=True, **kwargs)[source]

Initialize a spatial experiment.

Parameters:
  • assays (Dict[str, Any]) –

    A dictionary containing matrices, with assay names as keys and 2-dimensional matrices represented as either ndarray or spmatrix.

    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_pairs (Optional[Any]) –

    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 or BiocFrame 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 a BiocFrame. 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.

  • validate (bool) – Internal use only.

__repr__()[source]
Return type:

str

Returns:

A string representation.

add_img(image_source, scale_factor, sample_id, image_id, load=True, in_place=False)[source]

Add a new image entry.

Parameters:
  • image_source (Union[Image, ndarray, str, Path]) – The file path to the image.

  • scale_factor (float) – The scaling factor associated with the image.

  • sample_id (Union[str, bool, None]) – The sample id of the image.

  • image_id (Union[str, bool, None]) – The image id of the image.

  • load (bool) – Whether to load the image into memory. If True, the method reads the image file from image_source. Defaults to True.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

Raises:

ValueError – If the sample_id and image_id pair already exists.

combine_columns(*other)[source]

Wrapper around combine_columns().

Return type:

SpatialExperiment

copy()[source]

Alias for __copy__().

get_image_data()[source]

Access image data.

Return type:

BiocFrame

Returns:

A BiocFrame object containing the image data.

get_img(sample_id=None, image_id=None)[source]

Retrieve spatial images based on the provided sample and image ids.

Parameters:
  • sample_id (Union[str, bool, None]) –

    • sample_id=True: Matches all samples.

    • sample_id=None: Matches the first sample.

    • sample_id=”<str>”: Matches a sample by its id.

  • image_id (Union[str, bool, None]) –

    • image_id=True: Matches all images for the specified sample(s).

    • image_id=None: Matches the first image for the sample(s).

    • image_id=”<str>”: Matches image(s) by its(their) id.

Return type:

Union[VirtualSpatialImage, List[VirtualSpatialImage]]

Returns:

Zero, one, or more VirtualSpatialImage objects.

Behavior:
  • sample_id = True, image_id = True:

    Returns all images from all samples.

  • sample_id = None, image_id = None:

    Returns the first image entry in the dataset.

  • sample_id = True, image_id = None:

    Returns the first image for each sample.

  • sample_id = None, image_id = True:

    Returns all images for the first sample.

  • sample_id = <str>, image_id = True:

    Returns all images for the specified sample.

  • sample_id = <str>, image_id = None:

    Returns the first image for the specified sample.

  • sample_id = <str>, image_id = <str>:

    Returns the image matching the specified sample and image identifiers.

get_img_data()[source]

Alias for get_image_data().

Return type:

BiocFrame

get_scale_factors(sample_id=None, image_id=None)[source]
Return scale factor(s) of image(s) based on the provided sample and image ids.

See get_img() for more details on the behavior for various combinations of sample_id and image_id values.

Parameters:
  • sample_id (Union[str, bool, None]) –

    • sample_id=True: Matches all samples.

    • sample_id=None: Matches the first sample.

    • sample_id=”<str>”: Matches a sample by its id.

  • image_id (Union[str, bool, None]) –

    • image_id=True: Matches all images for the specified sample(s).

    • image_id=None: Matches the first image for the sample(s).

    • image_id=”<str>”: Matches image(s) by its(their) id.

Return type:

List[float]

Returns:

The scale factor(s) of the specified image(s).

get_slice(rows, columns)[source]

Alias for __getitem__.

Return type:

SpatialExperiment

get_spatial_coordinates()[source]

Access spatial coordinates.

Return type:

Union[BiocFrame, ndarray]

Returns:

A BiocFrame containing columns of spatial coordinates.

get_spatial_coordinates_names()[source]

Access spatial coordinates names.

Return type:

List[str]

Returns:

The defined names of the spatial coordinates.

get_spatial_coords()[source]

Alias for get_spatial_coordinates().

Return type:

BiocFrame

get_spatial_coords_names()[source]

Alias for get_spatial_coordinate_names().

Return type:

List[str]

property image_data: BiocFrame

Alias for get_image_data().

property img_data: BiocFrame

Alias for get_image_data().

img_raster(sample_id=None, image_id=None)[source]
img_source(sample_id=None, image_id=None, path=False)[source]
mirror_img(sample_id=None, image_id=None, axis=('h', 'v'))[source]
relaxed_combine_columns(*other)[source]

Wrapper around relaxed_combine_columns().

Return type:

SpatialExperiment

rmv_img(sample_id=None, image_id=None)[source]
Return type:

SpatialExperiment

rotate_img(sample_id=None, image_id=None, degrees=90)[source]
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 the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_image_data(img_data, in_place=False)[source]

Set new image data.

Parameters:
  • img_data (Optional[BiocFrame]) –

    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.

    Image data are coerced to a BiocFrame.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_img_data(img_data, in_place=False)[source]

Alias for set_image_data().

Return type:

SpatialExperiment

set_spatial_coordinates(spatial_coords, in_place=False)[source]

Set new spatial coordinates.

Parameters:
  • spatial_coords (Union[BiocFrame, ndarray, None]) –

    Optional ndarray or BiocFrame 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.

    To remove coordinate information, set spatial_coords=None.

    If spatial coordinates is a DataFrame or None, it is coerced to a BiocFrame. Defaults to None.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_spatial_coordinates_names(spatial_coords_names, in_place=False)[source]

Set new spatial coordinates names.

Parameters:
  • spatial_coords_names (List[str]) – New spatial coordinates names.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_spatial_coords(spatial_coords, in_place=False)[source]

Alias for set_spatial_coordinates().

Return type:

SpatialExperiment

set_spatial_coords_names(spatial_coords_names, in_place=False)[source]

Alias for set_spatial_coordinates_names().

Return type:

SpatialExperiment

property spatial_coordinates: BiocFrame

Alias for get_spatial_coordinates().

property spatial_coordinates_names: List[str]

Alias for get_spatial_coordinates_names().

property spatial_coords: BiocFrame

Alias for get_spatial_coordinates().

property spatial_coords_names: List[str]

Alias for get_spatial_coordinates_names().

static to_spatial_experiment()[source]
spatialexperiment.SpatialExperiment.combine_columns(*x)[source]

Combine multiple SpatialExperiment objects by column.

All assays must contain the same assay names. If you need a flexible combine operation, checkout relaxed_combine_columns().

Return type:

SpatialExperiment

Returns:

A combined SpatialExperiment.

spatialexperiment.SpatialExperiment.relaxed_combine_columns(*x)[source]

A relaxed version of the combine_columns() method for SpatialExperiment objects. Whereas combine_columns expects that all objects have the same rows, relaxed_combine_columns allows for different rows. Absent columns in any object are filled in with appropriate placeholder values before combining.

Parameters:

x (SpatialExperiment) – One or more SpatialExperiment objects, possibly with differences in the number and identity of their rows.

Return type:

SpatialExperiment

Returns:

A SpatialExperiment that combines all experiments along their columns and contains the union of all rows. Rows absent in any x are filled in with placeholders consisting of Nones or masked NumPy values.

spatialexperiment.SpatialImage module

class spatialexperiment.SpatialImage.LoadedSpatialImage(image, metadata=None)[source]

Bases: VirtualSpatialImage

Class for images loaded into memory.

__abstractmethods__ = frozenset({})
__copy__()[source]
Returns:

A shallow copy of the current LoadedSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current LoadedSpatialImage.

__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(image, metadata=None)[source]

Initialize the object.

Parameters:
__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_image()[source]

Get the image as a PIL Image object.

Return type:

Image

property image: Image

Alias for get_image().

img_raster()[source]

Get the image as a PIL Image object.

Return type:

Image

set_image(image, in_place=False)[source]

Set new image.

Parameters:
  • image (Union[Image, ndarray]) – Image represented as a ndarray or Image.

  • in_place (bool) – Whether to modify the LoadedSpatialImage in place. Defaults to False.

Return type:

LoadedSpatialImage

class spatialexperiment.SpatialImage.RemoteSpatialImage(url, metadata=None, validate=True)[source]

Bases: VirtualSpatialImage

Class for remotely hosted images.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current RemoteSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current RemoteSpatialImage.

__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(url, metadata=None, validate=True)[source]

Initialize the object.

Parameters:
  • url (str) – URL to the image file.

  • metadata (Optional[dict]) – Additional image metadata. Defaults to None.

  • validate (bool) – Whether to validate if the URL is valid. Defaults to True.

__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_url()[source]

Get the url to the image file.

Return type:

str

img_raster()[source]

Download (if needed) and load the image.

Return type:

Image

img_source(as_path=False)[source]

Get the source URL or cached path of the image.

Return type:

str

set_url(url, in_place=False)[source]

Update the url to the image file.

Parameters:
  • url (str) – New URL for this image.

  • in_place (bool) – Whether to modify the RemoteSpatialImage in place.

Return type:

RemoteSpatialImage

Returns:

A modified RemoteSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

property url: Path

Alias for get_url().

class spatialexperiment.SpatialImage.StoredSpatialImage(path, metadata=None)[source]

Bases: VirtualSpatialImage

Class for images stored on local filesystem.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current StoredSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current StoredSpatialImage.

__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__init__(path, metadata=None)[source]

Initialize the object.

Parameters:
  • path (Union[str, Path]) – Path to the image file.

  • metadata (Optional[dict]) – Additional image metadata. Defaults to None.

__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_path()[source]

Get the path to the image file.

Return type:

Path

img_raster()[source]

Load and cache the image.

Return type:

Image

img_source(as_path=False)[source]

Get the source path of the image.

Return type:

str

property path: Path

Alias for get_path().

set_path(path, in_place=False)[source]

Update the path to the image file.

Parameters:
  • path (Union[str, Path]) – New path for this image.

  • in_place (bool) – Whether to modify the StoredSpatialImage in place.

Return type:

StoredSpatialImage

Returns:

A modified StoredSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

class spatialexperiment.SpatialImage.VirtualSpatialImage(metadata=None)[source]

Bases: ABC

Base class for spatial images.

__abstractmethods__ = frozenset({'img_raster'})
__annotations__ = {}
__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(metadata=None)[source]
property dimensions: Tuple[int, int]

Alias for get_dimensions().

get_dimensions()[source]

Get image dimensions (width, height).

Return type:

Tuple[int, int]

get_metadata()[source]
Return type:

dict

Returns:

Dictionary of metadata for this object.

abstractmethod img_raster()[source]

Get the image as a PIL Image object.

Return type:

Image

property metadata: dict

Alias for get_metadata.

mirror_img(axis='h')[source]

Mirror image horizontally or vertically.

Return type:

LoadedSpatialImage

rotate_img(degrees=90)[source]

Rotate image by specified degrees clockwise.

Return type:

LoadedSpatialImage

set_metadata(metadata, in_place=False)[source]

Set additional metadata.

Parameters:
  • metadata (dict) – New metadata for this object.

  • in_place (bool) – Whether to modify the VirtualSpatialImage in place.

Return type:

VirtualSpatialImage

Returns:

A modified VirtualSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

spatialexperiment.SpatialImage.construct_spatial_image_class(x, is_url=None)[source]

Factory function to create appropriate SpatialImage object.

Return type:

VirtualSpatialImage

Module contents

class spatialexperiment.LoadedSpatialImage(image, metadata=None)[source]

Bases: VirtualSpatialImage

Class for images loaded into memory.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current LoadedSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current LoadedSpatialImage.

__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(image, metadata=None)[source]

Initialize the object.

Parameters:
__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_image()[source]

Get the image as a PIL Image object.

Return type:

Image

property image: Image

Alias for get_image().

img_raster()[source]

Get the image as a PIL Image object.

Return type:

Image

set_image(image, in_place=False)[source]

Set new image.

Parameters:
  • image (Union[Image, ndarray]) – Image represented as a ndarray or Image.

  • in_place (bool) – Whether to modify the LoadedSpatialImage in place. Defaults to False.

Return type:

LoadedSpatialImage

class spatialexperiment.ProxySpatialFeatureExperiment(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.

__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current SpatialExperiment.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current SpatialExperiment.

__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:
  • assays (Dict[str, Any]) –

    A dictionary containing matrices, with assay names as keys and 2-dimensional matrices represented as either ndarray or spmatrix.

    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_pairs (Optional[Any]) –

    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 or BiocFrame 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 a BiocFrame. 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.

  • 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[BiocFrame]) – BiocFrame containing spatial neighborhood graphs.

  • unit (str) – Unit for spatial coordinates (‘full_res_image_pixel’ or ‘micron’).

  • validate (bool) – Internal use only.

__repr__()[source]

Get string representation.

Return type:

str

property annot_geometries: Dict[str, GeoDataFrame]

Get annotation geometries.

property col_geometries: Dict[str, GeoDataFrame]

Get column geometries.

copy()[source]

Alias for __copy__().

get_annot_geometries()[source]

Get annotation geometries.

Return type:

Dict[str, GeoDataFrame]

get_col_geometries()[source]

Get column geometries.

Return type:

Dict[str, GeoDataFrame]

get_row_geometries()[source]

Get row geometries.

Return type:

Dict[str, GeoDataFrame]

get_slice(rows=None, columns=None)[source]

Get a slice of the experiment.

Parameters:
Return type:

ProxySpatialFeatureExperiment

Returns:

Sliced ProxySpatialFeatureExperiment.

get_spatial_graphs()[source]

Get spatial neighborhood graphs.

Return type:

Optional[BiocFrame]

get_unit()[source]

Get the coordinate unit.

Return type:

str

property row_geometries: Dict[str, GeoDataFrame]

Get row geometries.

set_annot_geometries(geometries, in_place=False)[source]

Set annotation geometries.

Parameters:
  • geometries (Dict[str, GeoDataFrame]) – New annotation geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • geometries (Dict[str, GeoDataFrame]) – New column geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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 the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • geometries (Dict[str, GeoDataFrame]) – New row geometries.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment 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:
  • graphs (Optional[BiocFrame]) – New spatial graphs as BiocFrame.

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_unit(unit, in_place=False)[source]

Set the coordinate unit.

Parameters:
  • unit (str) – New unit (‘full_res_image_pixel’ or ‘micron’).

  • in_place (bool) – Whether to modify the ProxySpatialFeatureExperiment in place. Defaults to False.

Return type:

ProxySpatialFeatureExperiment

Returns:

A modified ProxySpatialFeatureExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

property spatial_graphs: BiocFrame | None

Get spatial graphs.

property unit: str

Get coordinate unit.

class spatialexperiment.RemoteSpatialImage(url, metadata=None, validate=True)[source]

Bases: VirtualSpatialImage

Class for remotely hosted images.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current RemoteSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current RemoteSpatialImage.

__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(url, metadata=None, validate=True)[source]

Initialize the object.

Parameters:
  • url (str) – URL to the image file.

  • metadata (Optional[dict]) – Additional image metadata. Defaults to None.

  • validate (bool) – Whether to validate if the URL is valid. Defaults to True.

__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_url()[source]

Get the url to the image file.

Return type:

str

img_raster()[source]

Download (if needed) and load the image.

Return type:

Image

img_source(as_path=False)[source]

Get the source URL or cached path of the image.

Return type:

str

set_url(url, in_place=False)[source]

Update the url to the image file.

Parameters:
  • url (str) – New URL for this image.

  • in_place (bool) – Whether to modify the RemoteSpatialImage in place.

Return type:

RemoteSpatialImage

Returns:

A modified RemoteSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

property url: Path

Alias for get_url().

class spatialexperiment.SpatialExperiment(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, validate=True, **kwargs)[source]

Bases: SingleCellExperiment

Container class for storing data from spatial -omics experiments, extending SingleCellExperiment to provide slots for image data and spatial coordinates.

In contrast to R, ndarray or scipy matrices are unnamed and do not contain rownames and colnames. Hence, these matrices cannot be directly used as values in assays or alternative experiments. We strictly enforce type checks in these cases.

__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current SpatialExperiment.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current SpatialExperiment.

__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, validate=True, **kwargs)[source]

Initialize a spatial experiment.

Parameters:
  • assays (Dict[str, Any]) –

    A dictionary containing matrices, with assay names as keys and 2-dimensional matrices represented as either ndarray or spmatrix.

    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_pairs (Optional[Any]) –

    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 or BiocFrame 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 a BiocFrame. 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.

  • validate (bool) – Internal use only.

__repr__()[source]
Return type:

str

Returns:

A string representation.

add_img(image_source, scale_factor, sample_id, image_id, load=True, in_place=False)[source]

Add a new image entry.

Parameters:
  • image_source (Union[Image, ndarray, str, Path]) – The file path to the image.

  • scale_factor (float) – The scaling factor associated with the image.

  • sample_id (Union[str, bool, None]) – The sample id of the image.

  • image_id (Union[str, bool, None]) – The image id of the image.

  • load (bool) – Whether to load the image into memory. If True, the method reads the image file from image_source. Defaults to True.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

Raises:

ValueError – If the sample_id and image_id pair already exists.

combine_columns(*other)[source]

Wrapper around combine_columns().

Return type:

SpatialExperiment

copy()[source]

Alias for __copy__().

get_image_data()[source]

Access image data.

Return type:

BiocFrame

Returns:

A BiocFrame object containing the image data.

get_img(sample_id=None, image_id=None)[source]

Retrieve spatial images based on the provided sample and image ids.

Parameters:
  • sample_id (Union[str, bool, None]) –

    • sample_id=True: Matches all samples.

    • sample_id=None: Matches the first sample.

    • sample_id=”<str>”: Matches a sample by its id.

  • image_id (Union[str, bool, None]) –

    • image_id=True: Matches all images for the specified sample(s).

    • image_id=None: Matches the first image for the sample(s).

    • image_id=”<str>”: Matches image(s) by its(their) id.

Return type:

Union[VirtualSpatialImage, List[VirtualSpatialImage]]

Returns:

Zero, one, or more VirtualSpatialImage objects.

Behavior:
  • sample_id = True, image_id = True:

    Returns all images from all samples.

  • sample_id = None, image_id = None:

    Returns the first image entry in the dataset.

  • sample_id = True, image_id = None:

    Returns the first image for each sample.

  • sample_id = None, image_id = True:

    Returns all images for the first sample.

  • sample_id = <str>, image_id = True:

    Returns all images for the specified sample.

  • sample_id = <str>, image_id = None:

    Returns the first image for the specified sample.

  • sample_id = <str>, image_id = <str>:

    Returns the image matching the specified sample and image identifiers.

get_img_data()[source]

Alias for get_image_data().

Return type:

BiocFrame

get_scale_factors(sample_id=None, image_id=None)[source]
Return scale factor(s) of image(s) based on the provided sample and image ids.

See get_img() for more details on the behavior for various combinations of sample_id and image_id values.

Parameters:
  • sample_id (Union[str, bool, None]) –

    • sample_id=True: Matches all samples.

    • sample_id=None: Matches the first sample.

    • sample_id=”<str>”: Matches a sample by its id.

  • image_id (Union[str, bool, None]) –

    • image_id=True: Matches all images for the specified sample(s).

    • image_id=None: Matches the first image for the sample(s).

    • image_id=”<str>”: Matches image(s) by its(their) id.

Return type:

List[float]

Returns:

The scale factor(s) of the specified image(s).

get_slice(rows, columns)[source]

Alias for __getitem__.

Return type:

SpatialExperiment

get_spatial_coordinates()[source]

Access spatial coordinates.

Return type:

Union[BiocFrame, ndarray]

Returns:

A BiocFrame containing columns of spatial coordinates.

get_spatial_coordinates_names()[source]

Access spatial coordinates names.

Return type:

List[str]

Returns:

The defined names of the spatial coordinates.

get_spatial_coords()[source]

Alias for get_spatial_coordinates().

Return type:

BiocFrame

get_spatial_coords_names()[source]

Alias for get_spatial_coordinate_names().

Return type:

List[str]

property image_data: BiocFrame

Alias for get_image_data().

property img_data: BiocFrame

Alias for get_image_data().

img_raster(sample_id=None, image_id=None)[source]
img_source(sample_id=None, image_id=None, path=False)[source]
mirror_img(sample_id=None, image_id=None, axis=('h', 'v'))[source]
relaxed_combine_columns(*other)[source]

Wrapper around relaxed_combine_columns().

Return type:

SpatialExperiment

rmv_img(sample_id=None, image_id=None)[source]
Return type:

SpatialExperiment

rotate_img(sample_id=None, image_id=None, degrees=90)[source]
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 the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_image_data(img_data, in_place=False)[source]

Set new image data.

Parameters:
  • img_data (Optional[BiocFrame]) –

    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.

    Image data are coerced to a BiocFrame.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_img_data(img_data, in_place=False)[source]

Alias for set_image_data().

Return type:

SpatialExperiment

set_spatial_coordinates(spatial_coords, in_place=False)[source]

Set new spatial coordinates.

Parameters:
  • spatial_coords (Union[BiocFrame, ndarray, None]) –

    Optional ndarray or BiocFrame 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.

    To remove coordinate information, set spatial_coords=None.

    If spatial coordinates is a DataFrame or None, it is coerced to a BiocFrame. Defaults to None.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_spatial_coordinates_names(spatial_coords_names, in_place=False)[source]

Set new spatial coordinates names.

Parameters:
  • spatial_coords_names (List[str]) – New spatial coordinates names.

  • in_place (bool) – Whether to modify the SpatialExperiment in place. Defaults to False.

Return type:

SpatialExperiment

Returns:

A modified SpatialExperiment object, either as a copy of the original or as a reference to the (in-place-modified) original.

set_spatial_coords(spatial_coords, in_place=False)[source]

Alias for set_spatial_coordinates().

Return type:

SpatialExperiment

set_spatial_coords_names(spatial_coords_names, in_place=False)[source]

Alias for set_spatial_coordinates_names().

Return type:

SpatialExperiment

property spatial_coordinates: BiocFrame

Alias for get_spatial_coordinates().

property spatial_coordinates_names: List[str]

Alias for get_spatial_coordinates_names().

property spatial_coords: BiocFrame

Alias for get_spatial_coordinates().

property spatial_coords_names: List[str]

Alias for get_spatial_coordinates_names().

static to_spatial_experiment()[source]
class spatialexperiment.StoredSpatialImage(path, metadata=None)[source]

Bases: VirtualSpatialImage

Class for images stored on local filesystem.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__copy__()[source]
Returns:

A shallow copy of the current StoredSpatialImage.

__deepcopy__(memo=None, _nil=[])[source]
Returns:

A deep copy of the current StoredSpatialImage.

__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__init__(path, metadata=None)[source]

Initialize the object.

Parameters:
  • path (Union[str, Path]) – Path to the image file.

  • metadata (Optional[dict]) – Additional image metadata. Defaults to None.

__repr__()[source]
Return type:

str

Returns:

A string representation.

copy()[source]

Alias for __copy__().

get_path()[source]

Get the path to the image file.

Return type:

Path

img_raster()[source]

Load and cache the image.

Return type:

Image

img_source(as_path=False)[source]

Get the source path of the image.

Return type:

str

property path: Path

Alias for get_path().

set_path(path, in_place=False)[source]

Update the path to the image file.

Parameters:
  • path (Union[str, Path]) – New path for this image.

  • in_place (bool) – Whether to modify the StoredSpatialImage in place.

Return type:

StoredSpatialImage

Returns:

A modified StoredSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

class spatialexperiment.VirtualSpatialImage(metadata=None)[source]

Bases: ABC

Base class for spatial images.

__abstractmethods__ = frozenset({'img_raster'})
__annotations__ = {}
__eq__(other)[source]

Return self==value.

Return type:

bool

__hash__()[source]

Return hash(self).

__init__(metadata=None)[source]
property dimensions: Tuple[int, int]

Alias for get_dimensions().

get_dimensions()[source]

Get image dimensions (width, height).

Return type:

Tuple[int, int]

get_metadata()[source]
Return type:

dict

Returns:

Dictionary of metadata for this object.

abstractmethod img_raster()[source]

Get the image as a PIL Image object.

Return type:

Image

property metadata: dict

Alias for get_metadata.

mirror_img(axis='h')[source]

Mirror image horizontally or vertically.

Return type:

LoadedSpatialImage

rotate_img(degrees=90)[source]

Rotate image by specified degrees clockwise.

Return type:

LoadedSpatialImage

set_metadata(metadata, in_place=False)[source]

Set additional metadata.

Parameters:
  • metadata (dict) – New metadata for this object.

  • in_place (bool) – Whether to modify the VirtualSpatialImage in place.

Return type:

VirtualSpatialImage

Returns:

A modified VirtualSpatialImage object, either as a copy of the original or as a reference to the (in-place-modified) original.

spatialexperiment.construct_spatial_image_class(x, is_url=None)[source]

Factory function to create appropriate SpatialImage object.

Return type:

VirtualSpatialImage

spatialexperiment.read_tenx_visium(samples, sample_ids=None, type='HDF5', data='filtered', images='lowres', load=True)[source]

Create a SpatialExperiment from the Space Ranger output directories for 10x Genomics Visium spatial gene expression data.

Parameters:
  • samples (List[Union[str, PathLike]]) – A list of strings specifying one or more directories, each corresponding to a 10x Genomics Visium sample; if provided, names will be used as sample identifiers.

  • sample_ids (Optional[List[str]]) – A list of strings specifying unique sample identifiers, one for each directory specified via samples.

  • type (str) – A string specifying the type of format to read count data from. Valid values are [‘auto’, ‘sparse’, ‘prefix’, ‘HDF5’] (see [read10xCounts](https://rdrr.io/github/MarioniLab/DropletUtils/man/read10xCounts.html)).

  • data (str) – A string specifying whether to read in filtered (spots mapped to tissue) or raw data (all spots). Valid values are “filtered”, “raw”.

  • images (List[str]) – A single string or a list of strings specifying which images to include. Valid values are “lowres”, “hires”, “fullres”, “detected”, “aligned”.

  • load (bool) – A boolean specifying whether the image(s) should be loaded into memory? If False, will store the path/URL instead. Defaults to True.