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.
- __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
[BiocFrame
]) – BiocFrame containing spatial neighborhood graphs.unit (
str
) – Unit for spatial coordinates (‘full_res_image_pixel’ or ‘micron’).validate (
bool
) – Internal use only.
- copy()[source]¶
Alias for
__copy__()
.
- set_annot_geometries(geometries, in_place=False)[source]¶
Set annotation geometries.
- Parameters:
- Return type:
- 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:
- Return type:
- 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:
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 theProxySpatialFeatureExperiment
in place. Defaults to False.
- Return type:
- 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:
- Return type:
- 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:
- Return type:
- Returns:
A modified
ProxySpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
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__ = {}¶
- __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:
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
validate (
bool
) – Internal use only.
- 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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- copy()[source]¶
Alias for
__copy__()
.
- get_image_data()[source]¶
Access image data.
- Return type:
- 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:
- 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:
- 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:
- Returns:
The scale factor(s) of the specified image(s).
- get_spatial_coords()[source]¶
Alias for
get_spatial_coordinates()
.- Return type:
- property image_data: BiocFrame¶
Alias for
get_image_data()
.
- property img_data: BiocFrame¶
Alias for
get_image_data()
.
- relaxed_combine_columns(*other)[source]¶
Wrapper around
relaxed_combine_columns()
.- Return type:
- set_column_data(cols, replace_column_names=False, in_place=False)[source]¶
Override: Set sample data.
- Parameters:
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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- set_spatial_coordinates(spatial_coords, in_place=False)[source]¶
Set new spatial coordinates.
- Parameters:
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.
To remove coordinate information, set spatial_coords=None.
If spatial coordinates is a
DataFrame
or None, it is coerced to aBiocFrame
. Defaults to None.in_place (
bool
) – Whether to modify theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- Return type:
- 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:
- set_spatial_coords_names(spatial_coords_names, in_place=False)[source]¶
Alias for
set_spatial_coordinates_names()
.- Return type:
- 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()
.
- 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:
- Returns:
A combined
SpatialExperiment
.
- spatialexperiment.SpatialExperiment.relaxed_combine_columns(*x)[source]¶
A relaxed version of the
combine_columns()
method forSpatialExperiment
objects. Whereascombine_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 moreSpatialExperiment
objects, possibly with differences in the number and identity of their rows.- Return type:
- Returns:
A
SpatialExperiment
that combines allexperiments
along their columns and contains the union of all rows. Rows absent in anyx
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]¶
Alias for
__copy__()
.
- property image: Image¶
Alias for
get_image()
.
- class spatialexperiment.SpatialImage.RemoteSpatialImage(url, metadata=None, validate=True)[source]¶
Bases:
VirtualSpatialImage
Class for remotely hosted images.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- copy()[source]¶
Alias for
__copy__()
.
- class spatialexperiment.SpatialImage.StoredSpatialImage(path, metadata=None)[source]¶
Bases:
VirtualSpatialImage
Class for images stored on local filesystem.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- copy()[source]¶
Alias for
__copy__()
.
- property path: Path¶
Alias for
get_path()
.
- class spatialexperiment.SpatialImage.VirtualSpatialImage(metadata=None)[source]¶
Bases:
ABC
Base class for spatial images.
- __abstractmethods__ = frozenset({'img_raster'})¶
- __annotations__ = {}¶
- property dimensions: Tuple[int, int]¶
Alias for
get_dimensions()
.
- property metadata: dict¶
Alias for
get_metadata
.
Module contents¶
- class spatialexperiment.LoadedSpatialImage(image, metadata=None)[source]¶
Bases:
VirtualSpatialImage
Class for images loaded into memory.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- copy()[source]¶
Alias for
__copy__()
.
- property image: Image¶
Alias for
get_image()
.
- 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__ = {}¶
- __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
[BiocFrame
]) – BiocFrame containing spatial neighborhood graphs.unit (
str
) – Unit for spatial coordinates (‘full_res_image_pixel’ or ‘micron’).validate (
bool
) – Internal use only.
- copy()[source]¶
Alias for
__copy__()
.
- set_annot_geometries(geometries, in_place=False)[source]¶
Set annotation geometries.
- Parameters:
- Return type:
- 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:
- Return type:
- 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:
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 theProxySpatialFeatureExperiment
in place. Defaults to False.
- Return type:
- 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:
- Return type:
- 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:
- Return type:
- Returns:
A modified
ProxySpatialFeatureExperiment
object, either as a copy of the original or as a reference to the (in-place-modified) original.
- class spatialexperiment.RemoteSpatialImage(url, metadata=None, validate=True)[source]¶
Bases:
VirtualSpatialImage
Class for remotely hosted images.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- copy()[source]¶
Alias for
__copy__()
.
- 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__ = {}¶
- __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:
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
validate (
bool
) – Internal use only.
- 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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- copy()[source]¶
Alias for
__copy__()
.
- get_image_data()[source]¶
Access image data.
- Return type:
- 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:
- 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:
- 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:
- Returns:
The scale factor(s) of the specified image(s).
- get_spatial_coords()[source]¶
Alias for
get_spatial_coordinates()
.- Return type:
- property image_data: BiocFrame¶
Alias for
get_image_data()
.
- property img_data: BiocFrame¶
Alias for
get_image_data()
.
- relaxed_combine_columns(*other)[source]¶
Wrapper around
relaxed_combine_columns()
.- Return type:
- set_column_data(cols, replace_column_names=False, in_place=False)[source]¶
Override: Set sample data.
- Parameters:
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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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 theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- set_spatial_coordinates(spatial_coords, in_place=False)[source]¶
Set new spatial coordinates.
- Parameters:
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.
To remove coordinate information, set spatial_coords=None.
If spatial coordinates is a
DataFrame
or None, it is coerced to aBiocFrame
. Defaults to None.in_place (
bool
) – Whether to modify theSpatialExperiment
in place. Defaults to False.
- Return type:
- 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:
- Return type:
- 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:
- set_spatial_coords_names(spatial_coords_names, in_place=False)[source]¶
Alias for
set_spatial_coordinates_names()
.- Return type:
- 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()
.
- class spatialexperiment.StoredSpatialImage(path, metadata=None)[source]¶
Bases:
VirtualSpatialImage
Class for images stored on local filesystem.
- __abstractmethods__ = frozenset({})¶
- __annotations__ = {}¶
- copy()[source]¶
Alias for
__copy__()
.
- property path: Path¶
Alias for
get_path()
.
- class spatialexperiment.VirtualSpatialImage(metadata=None)[source]¶
Bases:
ABC
Base class for spatial images.
- __abstractmethods__ = frozenset({'img_raster'})¶
- __annotations__ = {}¶
- property dimensions: Tuple[int, int]¶
Alias for
get_dimensions()
.
- property metadata: dict¶
Alias for
get_metadata
.
- spatialexperiment.construct_spatial_image_class(x, is_url=None)[source]¶
Factory function to create appropriate SpatialImage object.
- Return type:
- 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.