A Python Package for Getting ROIs and Calculating Group Distances in Spatial Transcriptomics Data
Project description
distanX
distanX是一个用于从手绘区域中提取ROI,并计算空间转录组数据中细胞群体或ROI间距离的python包。
ENGLISH README
English 🌏
distanX is a Python package for extracting ROIs from hand-drawn regions and calculating distances between cell populations or ROIs in spatial transcriptomics data.
Highlights
- Extract ROIs from hand-drawn regions
- Fully customizable distance calculation methods, including minimum distance, average distance, maximum distance, and Chamfer distance.
Installation
pip install distanX
Usage
- Prepare an image that uses colors to distinguish ROIs from the remaining areas. For example, you can create a new layer on a hires image, then draw closed solid areas with white background and black fill, and export only that layer.
- Use the
Curve2Lineclass:load_and_preprocessto load the above imagedetect_contoursto detect contoursapproximate_contoursto approximate contours with line segments (epsilon_factorfor approximation precision)extract_polygonsto extract polygons
- Use the
Line2ROIclass:load_adatato load spatial transcriptomics dataset_scalefactorto extract scale factors (can be overridden using theoverride_scalefactorparameter)append_polygonsto add polygon setsextract_ROIto extract obs_names within ROIs
- Use the
CloudDistanceclass:- (Optional)
set_artificial_ROIto generate artificial ROIs in blank areas without spots set_pp_distance_functionto set the distance calculation method (default Euclidean distance)set_cloud_distance_functionto set the point cloud distance calculation method (themin、mean、maxof the distance from one point to another point cloud, or a custom function, defaultmin)compute_cloud_distanceto calculate the point cloud distance, return the distance from each point to another point cloud, and further calculate the distance between two point clouds
- (Optional)
Demo
See notebook on github or nbviewer
API reference
Curve2Line
The Curve2Line class converts drawn curve regions into line-approximated polygons.
load_and_preprocess(self, image_path: str, threshold_value: int = 127) -> bool
Load and preprocess images.
image_path: Image paththreshold_value: Threshold value for image binarization, default 127
Returns: bool, whether successful
detect_contours(self, retrieval_mode: int = cv2.RETR_LIST) -> bool
Detect contours.
retrieval_mode: Contour retrieval mode
Returns: bool, whether successful
approximate_contours(self, epsilon_factor: float = 0.002) -> bool
Approximate contours with polygons.
epsilon_factor: Approximation precision
Returns: bool, whether successful
extract_polygons(self) -> list[list[tuple[int, int]]]
Output identified hand-drawn regions.
Returns: list[list[tuple[int, int]]], list of polygons
Line2ROI
The Line2ROI class converts line-approximated polygons into ROIs in spatial transcriptomics data.
load_adata(self, adata: ad.AnnData)
Load spatial transcriptomics data.
adata: Spatial transcriptomics data
set_scalefactor(self, image_path: Optional[str] = None, library_id: str | None = None, reference_image_key: str = 'hires', override_scalefactor: float | None = None)
Set the scale factor between hand-drawn images and adata.obsm['spatial'].
image_path: Hand-drawn image pathlibrary_id: library_id in spatial transcriptomics data, defaults to the first onereference_image_key: Reference image in spatial transcriptomics data, used to set the scale factor of hand-drawn images in conjunction with its scale factoroverride_scalefactor: Directly override the scale factor of hand-drawn images
append_polygons(self, polygons: list[list[tuple[int, int]]], ROI_name: str)
Add hand-drawn region sets.
polygons: Hand-drawn region sets returned byCurve2Line().extract_polygons()ROI_name: Name of the ROI to add to
extract_ROI(self, ROI_name: str, method: str = 'winding number') -> list[str]
Export obs_names of specified ROI.
ROI_name: Name of specified ROImethod: Method to determine if a point is within ROI, currently only supportswinding number
Returns: list[str], list of ROI obs_names
set_adata_ROI(self, ROI_name: str) -> ad.AnnData
Set obs['ROI_'+ROI_name] within ROI to True, others to False.
ROI_name: Name of specified ROI
CloudDistance
The CloudDistance class calculates point cloud distances between cell populations or ROIs.
set_pp_distance_function(self, pp_distance_function: Callable[[float, float, float, float], float])
Set the distance calculation method between two points, default is Euclidean distance.
pp_distance_function: Function to calculate distance between two points (x1,y1) and (x2,y2), input is(x1,y1,x2,y2), output isfloat
set_cloud_distance_function(self, cloud_distance_function: Union[Literal['min', 'mean', 'max'], Callable])
Set the point cloud distance calculation method, default is min.
cloud_distance_function: Function to calculate distance from a point in one class to another point cloud, options aremin(np.min),mean(np.mean),max(np.max) or custom function, this function should operate on a one-dimensional array
compute_distance_matrix(self, adata: ad.AnnData, class_key_1: str | None = None, class_name_1: str | None = None, class_key_2: str | None = None, class_name_2: str | None = None) -> pd.DataFrame
Calculate distance matrix between two point clouds.
adata: Spatial transcriptomics dataclass_key_1: First classclass_name_1: First class nameclass_key_2: Second classclass_name_2: Second class name
Returns: pd.DataFrame, distance matrix between two point clouds, row index is the first class, column index is the second class, values are distances between two points
compute_cloud_distance(self, on: Literal['class_1', 'class_2'] = 'class_1')
Calculate point cloud distance.
on: Set to calculate distance from individual points in which class to all points in another class, default is the first class
Returns: Generally numpy.ndarray, custom distance from each point in the class specified by on to all points in another class
extract_points(self, adata: ad.AnnData, class_key: str, class_name: str) -> pd.DataFrame
Extract points and coordinates of specified category.
adata: Spatial transcriptomics dataclass_key: Specified categoryclass_name: Classification name within specified category
Returns: pd.DataFrame, points and coordinates of specified category, row index is adata.obs_names, column index is x, y
set_artificial_ROI(self, polygons: list[list[tuple[int, int]]], img_width: int, img_height: int, class_name: Literal['class_1', 'class_2'] = 'class_2', scale_factor: float = 1.0, density: int = 1000)
Generate artificial ROIs in blank areas without spots.
polygons: Hand-drawn region sets returned byCurve2Line().extract_polygons()img_width: Hand-drawn image widthimg_height: Hand-drawn image heightclass_name: Set the category to store in the instance, default isclass_2scale_factor: Scale factor, can be obtained fromLine2ROI().scalefactordensity: Density of artificial spots, default is 1000, uniformly distributed on one axis
亮点
- 从手绘区域中提取ROI
- 完全可自定义的距离计算方法,可实现最小距离、平均距离、最大距离以及Chamfer距离等。
安装
pip install distanX
用法
- 准备一张用颜色区分出ROI和剩余区域的图像,例如可以在hires图像上新建新图层,然后绘制白底、黑色的封闭实心区域,然后只导出该图层。
- 使用
Curve2Line类load_and_preprocess加载上述图像detect_contours检测轮廓approximate_contours用线段近似轮廓(epsilon_factor为近似精度)extract_polygons提取多边形
- 使用
Line2ROI类load_adata加载空转数据set_scalefactor提取缩放因子(可以使用override_scalefactor参数覆盖)append_polygons添加多边形集extract_ROI提取ROI中的obs_names
- 使用
CloudDistance类- (可选)
set_artificial_ROI在无spot的空白区域生成人工ROI set_pp_distance_function设置两点间距离计算方法(默认欧几里得距离)set_cloud_distance_function设置点云距离计算方法(类中一点到另一点云距离的min、mean、max或自定义函数,默认min)compute_cloud_distance计算点云距离,返回每点到另一个点云的距离(默认从第一类中的点到第二类中的点云),可以进一步计算两点云距离
- (可选)
示例
API参考
Curve2Line
Curve2Line类将绘制的曲线区域转换为直线近似的多边形。
load_and_preprocess(self, image_path: str, threshold_value: int = 127) -> bool
加载、预处理图像。
image_path: 图像路径threshold_value: 阈值,用于二值化图像,默认127
返回值:bool,是否成功
detect_contours(self, retrieval_mode: int = cv2.RETR_LIST) -> bool
检测轮廓。
retrieval_mode: 轮廓检索模式
返回值:bool,是否成功
approximate_contours(self, epsilon_factor: float = 0.002) -> bool
用多边形近似轮廓。
epsilon_factor: 近似精度
返回值:bool,是否成功
extract_polygons(self) -> list[list[tuple[int, int]]]
输出识别出的手绘区域。
返回值:list[list[tuple[int, int]]],多边形列表
Line2ROI
Line2ROI类将直线近似的多边形转换为空转数据中的ROI。
load_adata(self, adata: ad.AnnData)
加载空转数据。
adata: 空转数据
set_scalefactor(self, image_path: Optional[str] = None, library_id: str | None = None, reference_image_key: str = 'hires', override_scalefactor: float | None = None)
设置手绘图像与adata.obsm['spatial']的缩放因子。
image_path: 手绘图像路径library_id: 空转数据中的library_id,默认使用第一个reference_image_key: 空转数据中的参考图像,用于配合其缩放因子设置手绘图像的缩放因子override_scalefactor: 直接覆写手绘图像的缩放因子
append_polygons(self, polygons: list[list[tuple[int, int]]], ROI_name: str)
添加手绘区域集合。
polygons:Curve2Line().extract_polygons()返回的手绘区域集合ROI_name: 添加到的ROI的名称
extract_ROI(self, ROI_name: str, method: str = 'winding number') -> list[str]
导出指定ROI的obs_names。
ROI_name: 指定ROI的名称method: 判断点是否在ROI中的方法,暂时只支持winding number
返回值:list[str],ROI的obs_names列表
set_adata_ROI(self, ROI_name: str) -> ad.AnnData
将ROI内的obs['ROI_'+ROI_name]设置为True,其余设置为False。
ROI_name: 指定ROI的名称
CloudDistance
CloudDistance类计算细胞群体或ROI间的点云距离。
set_pp_distance_function(self, pp_distance_function: Callable[[float, float, float, float], float])
设置两点间距离计算方法,默认是欧几里得距离。
pp_distance_function: 计算两点(x1,y1)、(x2,y2)间距离的函数,输入为(x1,y1,x2,y2),输出为float
set_cloud_distance_function(self, cloud_distance_function: Union[Literal['min', 'mean', 'max'], Callable])
设置点云距离计算方法,默认是min。
cloud_distance_function: 计算类中一点到另一点云距离的函数,可选min(np.min)、mean(np.mean)、max(np.max)或自定义函数,该函数应当对一个一维数组进行操作
compute_distance_matrix(self, adata: ad.AnnData, class_key_1: str | None = None, class_name_1: str | None = None, class_key_2: str | None = None, class_name_2: str | None = None) -> pd.DataFrame
计算两点云距离矩阵。
adata: 空转数据class_key_1: 第一类class_name_1: 第一类名称class_key_2: 第二类class_name_2: 第二类名称
返回值:pd.DataFrame,两点云距离矩阵,行索引为第一类,列索引为第二类,值为两点距离
compute_cloud_distance(self, on: Literal['class_1', 'class_2'] = 'class_1')
计算点云距离。
on: 设置计算从哪类的单个点到另一类所有点的距离,默认是第一类
返回值:一般是numpy.ndarray,是on指定类别中的各个点到另一类所有点的自定义距离
extract_points(self, adata: ad.AnnData, class_key: str, class_name: str) -> pd.DataFrame
提取指定类别的点及坐标。
adata: 空转数据class_key: 指定类别class_name: 指定类别中的分类名称
返回值:pd.DataFrame,指定类别的点及坐标,行索引为adata.obs_names,列索引为x、y
set_artificial_ROI(self, polygons: list[list[tuple[int, int]]], img_width: int, img_height: int, class_name: Literal['class_1', 'class_2'] = 'class_2', scale_factor: float = 1.0, density: int = 1000)
可以在无spot的空白区域生成人工ROI。
polygons:Curve2Line().extract_polygons()返回的手绘区域集合img_width: 手绘图像宽度img_height: 手绘图像高度class_name: 设置储存在实例内的哪个类别,默认是class_2第二类scale_factor: 缩放因子,可以从Line2ROI().scalefactor中获取density: 人工spot的1维点密度,默认是1000个,均匀分布在一个轴上
引用distanX
如果你觉得distanX对你的工作有帮助,欢迎引用它:
@misc{distanX,
author = {Luna Lee},
title = {distanX: A Python Package for Getting ROIs and Calculating Group Distances in Spatial Transcriptomics Data},
howpublished = {Github},
year = {2025},
url = {https://github.com/kusurin/distanX}
}
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file distanx-0.2.2.tar.gz.
File metadata
- Download URL: distanx-0.2.2.tar.gz
- Upload date:
- Size: 24.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fb64a6644301ef91df5b3df326a76bd86ef591c0d90a968ea75a516cc91e5b20
|
|
| MD5 |
b6011c755f2f9e947b50e9bb91edf396
|
|
| BLAKE2b-256 |
5ae7df47260b4fc500e54d1c5381059a2822e1dc457906c76531e8e485a06ec4
|
Provenance
The following attestation bundles were made for distanx-0.2.2.tar.gz:
Publisher:
python-publish.yml on kusurin/distanX
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
distanx-0.2.2.tar.gz -
Subject digest:
fb64a6644301ef91df5b3df326a76bd86ef591c0d90a968ea75a516cc91e5b20 - Sigstore transparency entry: 237405441
- Sigstore integration time:
-
Permalink:
kusurin/distanX@cbb5f4c6b5f3c4bcc28ee5b1da4dcb06141261c9 -
Branch / Tag:
refs/tags/v0.2.2 - Owner: https://github.com/kusurin
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@cbb5f4c6b5f3c4bcc28ee5b1da4dcb06141261c9 -
Trigger Event:
release
-
Statement type:
File details
Details for the file distanx-0.2.2-py3-none-any.whl.
File metadata
- Download URL: distanx-0.2.2-py3-none-any.whl
- Upload date:
- Size: 21.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f339c4466c3594cca9f33b728bc2c9cd7baaab6fedd839da9d066f1479d7338
|
|
| MD5 |
a8f5413d23513c9698a46ebd0c4b8eba
|
|
| BLAKE2b-256 |
d2d4f14c413657324801572e99cac3cbdd0a0acf3ab0d97204e6cea6ee1111f2
|
Provenance
The following attestation bundles were made for distanx-0.2.2-py3-none-any.whl:
Publisher:
python-publish.yml on kusurin/distanX
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
distanx-0.2.2-py3-none-any.whl -
Subject digest:
3f339c4466c3594cca9f33b728bc2c9cd7baaab6fedd839da9d066f1479d7338 - Sigstore transparency entry: 237405444
- Sigstore integration time:
-
Permalink:
kusurin/distanX@cbb5f4c6b5f3c4bcc28ee5b1da4dcb06141261c9 -
Branch / Tag:
refs/tags/v0.2.2 - Owner: https://github.com/kusurin
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@cbb5f4c6b5f3c4bcc28ee5b1da4dcb06141261c9 -
Trigger Event:
release
-
Statement type: