Skip to content

sopa._sdata

Note

These are convenient tools that operates on SpatialData objects

sopa._sdata.get_boundaries(sdata, return_key=False, warn=False)

Gets the baysor boundaries or cellpose boundaries of a SpatialData object after running Sopa

Parameters:

Name Type Description Default
sdata SpatialData

A SpatialData object

required
return_key bool

Whether to return the key of the shapes or not.

False
warn bool

If True, prints a warning if no boundary is found. Else, raises an error.

False

Returns:

Type Description
GeoDataFrame | tuple[str, GeoDataFrame] | None

A GeoDataFrame containing the boundaries, or a tuple (shapes_key, geo_df)

Source code in sopa/_sdata.py
def get_boundaries(
    sdata: SpatialData, return_key: bool = False, warn: bool = False
) -> gpd.GeoDataFrame | tuple[str, gpd.GeoDataFrame] | None:
    """Gets the baysor boundaries or cellpose boundaries of a SpatialData object after running Sopa

    Args:
        sdata: A SpatialData object
        return_key: Whether to return the key of the shapes or not.
        warn: If `True`, prints a warning if no boundary is found. Else, raises an error.

    Returns:
        A `GeoDataFrame` containing the boundaries, or a tuple `(shapes_key, geo_df)`
    """
    VALID_BOUNDARIES = [
        SopaKeys.BAYSOR_BOUNDARIES,
        SopaKeys.COMSEG_BOUNDARIES,
        SopaKeys.CELLPOSE_BOUNDARIES,
    ]
    for shapes_key in VALID_BOUNDARIES:
        res = _try_get_boundaries(sdata, shapes_key, return_key)
        if res is not None:
            return res

    error_message = "sdata object has no valid segmentation boundary. Consider running Sopa segmentation first."

    if not warn:
        raise ValueError(error_message)

    log.warn(error_message)
    return (None, None) if return_key else None

sopa._sdata.get_intrinsic_cs(sdata, element, name=None)

Gets the name of the intrinsic coordinate system of an element

Parameters:

Name Type Description Default
sdata SpatialData

A SpatialData object

required
element SpatialElement | str

SpatialElement, or its key

required
name str | None

Name to provide to the intrinsic coordinate system if not existing. By default, uses the element id.

None

Returns:

Type Description
str

Name of the intrinsic coordinate system

Source code in sopa/_sdata.py
def get_intrinsic_cs(sdata: SpatialData, element: SpatialElement | str, name: str | None = None) -> str:
    """Gets the name of the intrinsic coordinate system of an element

    Args:
        sdata: A SpatialData object
        element: `SpatialElement`, or its key
        name: Name to provide to the intrinsic coordinate system if not existing. By default, uses the element id.

    Returns:
        Name of the intrinsic coordinate system
    """
    if name is None:
        name = f"_{element if isinstance(element, str) else id(element)}_intrinsic"

    if isinstance(element, str):
        element = sdata[element]

    for cs, transform in get_transformation(element, get_all=True).items():
        if isinstance(transform, Identity):
            return cs

    set_transformation(element, Identity(), name)
    return name

sopa._sdata.to_intrinsic(sdata, element, element_cs)

Transforms a SpatialElement into the intrinsic coordinate system of another SpatialElement

Parameters:

Name Type Description Default
sdata SpatialData

A SpatialData object

required
element SpatialElement | str

SpatialElement to transform, or its key

required
element_cs SpatialElement | str

SpatialElement of the target coordinate system, or its key

required

Returns:

Type Description
SpatialElement

The SpatialElement after transformation in the target coordinate system

Source code in sopa/_sdata.py
def to_intrinsic(sdata: SpatialData, element: SpatialElement | str, element_cs: SpatialElement | str) -> SpatialElement:
    """Transforms a `SpatialElement` into the intrinsic coordinate system of another `SpatialElement`

    Args:
        sdata: A SpatialData object
        element: `SpatialElement` to transform, or its key
        element_cs: `SpatialElement` of the target coordinate system, or its key

    Returns:
        The `SpatialElement` after transformation in the target coordinate system
    """
    if isinstance(element, str):
        element = sdata[element]
    cs = get_intrinsic_cs(sdata, element_cs)
    return sdata.transform_element_to_coordinate_system(element, cs)

sopa._sdata.get_intensities(sdata)

Gets the intensity dataframe of shape n_obs x n_channels

Source code in sopa/_sdata.py
def get_intensities(sdata: SpatialData) -> pd.DataFrame | None:
    """Gets the intensity dataframe of shape `n_obs x n_channels`"""
    assert SopaKeys.TABLE in sdata.tables, f"No '{SopaKeys.TABLE}' found in sdata.tables"

    adata = sdata.tables[SopaKeys.TABLE]

    if not adata.uns[SopaKeys.UNS_KEY][SopaKeys.UNS_HAS_INTENSITIES]:
        return None

    if adata.uns[SopaKeys.UNS_KEY][SopaKeys.UNS_HAS_TRANSCRIPTS]:
        return adata.obsm[SopaKeys.INTENSITIES_OBSM]

    return adata.to_df()

sopa._sdata.iter_scales(image)

Iterates through all the scales of a DataTree

Parameters:

Name Type Description Default
image DataTree

a DataTree

required

Yields:

Type Description
DataArray

Each scale (as a DataArray)

Source code in sopa/_sdata.py
def iter_scales(image: DataTree) -> Iterator[DataArray]:
    """Iterates through all the scales of a `DataTree`

    Args:
        image: a `DataTree`

    Yields:
        Each scale (as a `DataArray`)
    """
    assert isinstance(image, DataTree), f"Multiscale iteration is reserved for type DataTree. Found {type(image)}"

    for scale in image:
        yield next(iter(image[scale].values()))

sopa._sdata.get_spatial_image(sdata, key=None, return_key=False, valid_attr=SopaAttrs.CELL_SEGMENTATION)

Gets a DataArray from a SpatialData object (if the image has multiple scale, the scale0 is returned)

Parameters:

Name Type Description Default
sdata SpatialData

SpatialData object.

required
key str | None

Optional image key. If None, returns the only image (if only one), or tries to find an image with valid_attr.

None
return_key bool

Whether to also return the key of the image.

False
valid_attr str

Attribute that the image must have to be considered valid.

CELL_SEGMENTATION

Returns:

Type Description
DataArray | tuple[str, DataArray]

If return_key is False, only the image is returned, else a tuple (image_key, image)

Source code in sopa/_sdata.py
def get_spatial_image(
    sdata: SpatialData,
    key: str | None = None,
    return_key: bool = False,
    valid_attr: str = SopaAttrs.CELL_SEGMENTATION,
) -> DataArray | tuple[str, DataArray]:
    """Gets a DataArray from a SpatialData object (if the image has multiple scale, the `scale0` is returned)

    Args:
        sdata: SpatialData object.
        key: Optional image key. If `None`, returns the only image (if only one), or tries to find an image with `valid_attr`.
        return_key: Whether to also return the key of the image.
        valid_attr: Attribute that the image must have to be considered valid.

    Returns:
        If `return_key` is False, only the image is returned, else a tuple `(image_key, image)`
    """
    return get_spatial_element(
        sdata.images,
        key=key,
        valid_attr=valid_attr,
        return_key=return_key,
        as_spatial_image=True,
    )