histomaptx 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.4
2
+ Name: histomaptx
3
+ Version: 0.1.0
4
+ Summary: A Python library for analyzing histological annotations alongside spatial transcriptomics data
5
+ Author-email: Your Name <your.email@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/must-bioinfo/HistoMap
8
+ Project-URL: Documentation, https://histomaptx.readthedocs.io
9
+ Project-URL: Repository, https://github.com/must-bioinfo/HistoMap
10
+ Keywords: spatial transcriptomics,histology,annotations,visium
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: geopandas
14
+ Requires-Dist: pandas
15
+ Requires-Dist: numpy
16
+ Requires-Dist: matplotlib
17
+ Requires-Dist: plotly
18
+ Requires-Dist: scipy
19
+ Requires-Dist: shapely
20
+ Requires-Dist: rtree
21
+
22
+ # HistoMapTx
23
+ <img src="figures/logo.png" align="right" width="150px" />
24
+ HistoMap is a Python library for analyzing and visualizing histological annotations alongside spatially resolved transcriptomics data (Visium). It provides tools for processing, analyzing, and visualizing GeoJSON-based tissue annotations with spatial transcriptomics spot data.
25
+ It is integrated with QuPath and ImageJ annotations, and interface with scanpy, squidpy and Seurat through either SpatialData or generation of MetaData.
26
+
27
+ Documentation is available here : https://histomaptx.readthedocs.io/en/latest/
28
+
29
+ ## Features
30
+
31
+ - **Flexible File Support**: Read annotations from various formats (GeoJSON, gzipped, or zipped files)
32
+ - **Comprehensive Metrics**: Calculate area, perimeter, circularity, solidity, and other geometric properties
33
+ - **Interactive Visualization**: Generate 2D and 3D visualizations of tissue annotations
34
+ - **Annotation Ordering**: Control the rendering order of annotations for clearer visualization
35
+ - **Spatial Analysis**: Compute overlaps between annotations and Visium spots
36
+ - **Summary Statistics**: Generate detailed morphological summaries for each annotation
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install histomap
42
+ ```
43
+
44
+ ## Dependencies
45
+
46
+ HistoMap requires:
47
+ - geopandas
48
+ - pandas
49
+ - numpy
50
+ - matplotlib
51
+ - plotly
52
+ - scipy
53
+ - shapely
54
+
55
+ ## Quick Start
56
+
57
+ ```python
58
+ import histomap as hm
59
+ import squidpy as sq
60
+ import numpy as np
61
+ import pandas as pd
62
+ import matplotlib.pyplot as plt
63
+
64
+ # Load Visium data (with squidpy for example)
65
+ adata = sq.datasets.visium_fluo_moran_test()
66
+ spatial_data = adata.uns['spatial']
67
+
68
+ # Load annotations from a GeoJSON file
69
+ histo = hm.HistoMap("annotations.geojson", spatial_data)
70
+
71
+ # Display a summary of the annotations
72
+ print(histo.generate_summary())
73
+
74
+ # Plot the annotations
75
+ histo.plot_annotations()
76
+
77
+ # Change the plotting order
78
+ histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
79
+
80
+ # Compute overlaps between annotations and Visium spots
81
+ histo.compute_overlap_annotation()
82
+
83
+ # Plot spots colored by their overlap with a specific annotation
84
+ histo.plot_annotation_overlay("Tumor")
85
+ ```
86
+
87
+ ## Core Functionality
88
+
89
+ ### Loading and Processing Annotations
90
+
91
+ HistoMap automatically processes annotation files in various formats and extracts key information:
92
+
93
+ ```python
94
+ # Initialize with a GeoJSON file
95
+ histo = HistoMap("annotations.geojson", visium_spatial_data, '/path/to/image.tiff')
96
+
97
+ ```
98
+
99
+ ### Generating Statistical Summaries
100
+
101
+ Get comprehensive morphological statistics about each annotation:
102
+
103
+ ```python
104
+ # Generate a summary DataFrame with key metrics
105
+ summary = histo.generate_summary()
106
+ print(summary)
107
+ ```
108
+
109
+ The summary includes metrics such as:
110
+ - Total area and perimeter
111
+ - Mean aspect ratio, circularity, and compactness
112
+ - Centroid coordinates
113
+ - Solidity and extent
114
+ - Polygon counts
115
+
116
+ ### Visualization
117
+
118
+ HistoMap offers multiple visualization options:
119
+
120
+ #### Basic Annotation Plot
121
+
122
+ ```python
123
+ # Plot annotations with default settings
124
+ histo.plot_annotations()
125
+
126
+ # Customize fill and contour colors
127
+ histo.plot_annotations(fill=True, contour="black")
128
+
129
+ # Specify custom colors for each annotation
130
+ histo.plot_annotations(fill=["red", "blue", "green"], contour=["black", "black", "black"])
131
+ ```
132
+
133
+ #### 3D Visualization by Annotation Order
134
+
135
+ ```python
136
+ # Create a 3D plot with annotations at different z-levels
137
+ histo.plot_annotation_order(fill=True, elevation_factor=1.5)
138
+
139
+ # Create an interactive 3D plot using Plotly
140
+ histo.plot_annotation_order_interactive(fill=True, elevation_factor=1.5)
141
+ ```
142
+
143
+ ### Controlling Annotation Order
144
+
145
+ The order in which annotations are plotted can be crucial for visualization:
146
+
147
+ ```python
148
+ # Display current plot order
149
+ histo.display_plot_order()
150
+
151
+ # Change plot order (annotations listed first will be on top)
152
+ histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
153
+ ```
154
+
155
+ ### Spatial Analysis with Visium Spots
156
+
157
+ Analyze the overlap between histological annotations and Visium spots:
158
+
159
+ ```python
160
+ # Compute overlap between annotations and spots
161
+ histo.compute_overlap_annotation()
162
+
163
+ # Visualize spots colored by their overlap with a specific annotation
164
+ histo.plot_annotation_overlay("Tumor")
165
+
166
+ # Find spots that overlap with two different annotations
167
+ histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
168
+ ```
169
+
170
+ ## Advanced Usage
171
+
172
+ ### Custom Annotation Colors
173
+
174
+ You can customize the colors used for annotations to make your visualizations match your publication style:
175
+
176
+ ```python
177
+ # Define custom colors
178
+ annotation_colors = {
179
+ "Tumor": "#E41A1C",
180
+ "Stroma": "#377EB8",
181
+ "Immune cells": "#4DAF4A"
182
+ }
183
+
184
+ # Use a color list matching the annotation order
185
+ annotations = histo.data_exploded['Annotation'].unique()
186
+ color_list = [annotation_colors[ann] for ann in annotations]
187
+
188
+ # Plot with custom colors
189
+ histo.plot_annotations(fill=color_list, contour="black")
190
+ ```
191
+
192
+ ### Exporting Results
193
+
194
+ ```python
195
+ # Generate and save a summary to CSV
196
+ summary = histo.generate_summary()
197
+ summary.to_csv("annotation_summary.csv", index=False)
198
+
199
+ # Save the figure
200
+ fig, ax = plt.subplots(figsize=(10, 10))
201
+ histo.plot_annotations()
202
+ plt.savefig("annotations.png", dpi=300, bbox_inches="tight")
203
+ ```
204
+
205
+ ### Working with Spot-Level Data
206
+
207
+ After computing overlaps, you can extract spots that overlap with specific annotations:
208
+
209
+ ```python
210
+ # Compute overlaps
211
+ histo.compute_overlap_annotation()
212
+
213
+ # Get spots that overlap with both tumor and immune cells
214
+ overlaps = histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
215
+ overlapping_spots = overlaps[2] # Third return value contains the overlapping spots
216
+
217
+ # Get spot IDs for further analysis
218
+ overlapping_spot_ids = overlapping_spots.index.tolist()
219
+ ```
220
+
221
+ ## API Reference
222
+
223
+ ### HistoMap Class
224
+
225
+ The main class for working with histological annotations and spatial data.
226
+
227
+ #### Methods
228
+
229
+ - `__init__(file_name, visium_spatialdata)`: Initialize with a GeoJSON file and Visium spatial data
230
+ - `generate_spot_geodata()`: Generate circular geometries for Visium spots
231
+ - `read_geojson_based_on_type(file_name)`: Read GeoJSON data based on file format
232
+ - `_extract_annotations()`: Process annotation data from GeoJSON
233
+ - `add_area_column()`: Add area calculations to annotations
234
+ - `generate_summary()`: Create a comprehensive summary of annotation metrics
235
+ - `display_plot_order()`: Show the current plot order of annotations
236
+ - `change_plot_order(order_list)`: Modify the order in which annotations are plotted
237
+ - `plot_annotations(fill, contour)`: Create a 2D plot of annotations
238
+ - `compute_overlap_annotation()`: Calculate overlap between spots and annotations
239
+ - `plot_annotation_overlay(annotation)`: Visualize overlap between spots and a specific annotation
240
+ - `plot_annotation_order(fill, contour, elevation_factor)`: Create a 3D plot with annotations at different z-levels
241
+ - `plot_annotation_order_interactive(fill, contour, elevation_factor)`: Create an interactive 3D plot using Plotly
242
+ - `plot_combined_annotation_overlap(annotation1, annotation2)`: Find spots overlapping with two annotations
243
+
244
+ ## FAQ
245
+
246
+ ### How does HistoMap handle large annotation files?
247
+
248
+ HistoMap efficiently processes GeoJSON files using GeoPandas' spatial indexing capabilities, which helps manage large datasets. For very large files, you may need to increase your system's memory allocation.
249
+
250
+ ### Can I use HistoMap with non-Visium spatial data?
251
+
252
+ While HistoMap is optimized for Visium data, you can adapt it for other spatial transcriptomics platforms by constructing a compatible spatial data object.
253
+
254
+ ### How can I integrate HistoMap with other spatial analysis tools?
255
+
256
+ HistoMap works well with the broader spatial transcriptomics ecosystem, including:
257
+ - Squidpy for additional spatial statistics
258
+ - Scanpy for cell-type identification
259
+ - Seaborn for advanced visualizations of results
260
+
261
+
262
+ ## License
263
+
264
+ This project is licensed under the MIT License - see the LICENSE file for details.
265
+
266
+ ## Citation
267
+
268
+ If you use HistoMap in your research, please cite:
269
+
270
+ ```
271
+ Unpublished
272
+ ```
273
+
274
+ ## Contact
275
+
276
+ For questions and feedback, please open an issue on the GitHub repository
@@ -0,0 +1,255 @@
1
+ # HistoMapTx
2
+ <img src="figures/logo.png" align="right" width="150px" />
3
+ HistoMap is a Python library for analyzing and visualizing histological annotations alongside spatially resolved transcriptomics data (Visium). It provides tools for processing, analyzing, and visualizing GeoJSON-based tissue annotations with spatial transcriptomics spot data.
4
+ It is integrated with QuPath and ImageJ annotations, and interface with scanpy, squidpy and Seurat through either SpatialData or generation of MetaData.
5
+
6
+ Documentation is available here : https://histomaptx.readthedocs.io/en/latest/
7
+
8
+ ## Features
9
+
10
+ - **Flexible File Support**: Read annotations from various formats (GeoJSON, gzipped, or zipped files)
11
+ - **Comprehensive Metrics**: Calculate area, perimeter, circularity, solidity, and other geometric properties
12
+ - **Interactive Visualization**: Generate 2D and 3D visualizations of tissue annotations
13
+ - **Annotation Ordering**: Control the rendering order of annotations for clearer visualization
14
+ - **Spatial Analysis**: Compute overlaps between annotations and Visium spots
15
+ - **Summary Statistics**: Generate detailed morphological summaries for each annotation
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install histomap
21
+ ```
22
+
23
+ ## Dependencies
24
+
25
+ HistoMap requires:
26
+ - geopandas
27
+ - pandas
28
+ - numpy
29
+ - matplotlib
30
+ - plotly
31
+ - scipy
32
+ - shapely
33
+
34
+ ## Quick Start
35
+
36
+ ```python
37
+ import histomap as hm
38
+ import squidpy as sq
39
+ import numpy as np
40
+ import pandas as pd
41
+ import matplotlib.pyplot as plt
42
+
43
+ # Load Visium data (with squidpy for example)
44
+ adata = sq.datasets.visium_fluo_moran_test()
45
+ spatial_data = adata.uns['spatial']
46
+
47
+ # Load annotations from a GeoJSON file
48
+ histo = hm.HistoMap("annotations.geojson", spatial_data)
49
+
50
+ # Display a summary of the annotations
51
+ print(histo.generate_summary())
52
+
53
+ # Plot the annotations
54
+ histo.plot_annotations()
55
+
56
+ # Change the plotting order
57
+ histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
58
+
59
+ # Compute overlaps between annotations and Visium spots
60
+ histo.compute_overlap_annotation()
61
+
62
+ # Plot spots colored by their overlap with a specific annotation
63
+ histo.plot_annotation_overlay("Tumor")
64
+ ```
65
+
66
+ ## Core Functionality
67
+
68
+ ### Loading and Processing Annotations
69
+
70
+ HistoMap automatically processes annotation files in various formats and extracts key information:
71
+
72
+ ```python
73
+ # Initialize with a GeoJSON file
74
+ histo = HistoMap("annotations.geojson", visium_spatial_data, '/path/to/image.tiff')
75
+
76
+ ```
77
+
78
+ ### Generating Statistical Summaries
79
+
80
+ Get comprehensive morphological statistics about each annotation:
81
+
82
+ ```python
83
+ # Generate a summary DataFrame with key metrics
84
+ summary = histo.generate_summary()
85
+ print(summary)
86
+ ```
87
+
88
+ The summary includes metrics such as:
89
+ - Total area and perimeter
90
+ - Mean aspect ratio, circularity, and compactness
91
+ - Centroid coordinates
92
+ - Solidity and extent
93
+ - Polygon counts
94
+
95
+ ### Visualization
96
+
97
+ HistoMap offers multiple visualization options:
98
+
99
+ #### Basic Annotation Plot
100
+
101
+ ```python
102
+ # Plot annotations with default settings
103
+ histo.plot_annotations()
104
+
105
+ # Customize fill and contour colors
106
+ histo.plot_annotations(fill=True, contour="black")
107
+
108
+ # Specify custom colors for each annotation
109
+ histo.plot_annotations(fill=["red", "blue", "green"], contour=["black", "black", "black"])
110
+ ```
111
+
112
+ #### 3D Visualization by Annotation Order
113
+
114
+ ```python
115
+ # Create a 3D plot with annotations at different z-levels
116
+ histo.plot_annotation_order(fill=True, elevation_factor=1.5)
117
+
118
+ # Create an interactive 3D plot using Plotly
119
+ histo.plot_annotation_order_interactive(fill=True, elevation_factor=1.5)
120
+ ```
121
+
122
+ ### Controlling Annotation Order
123
+
124
+ The order in which annotations are plotted can be crucial for visualization:
125
+
126
+ ```python
127
+ # Display current plot order
128
+ histo.display_plot_order()
129
+
130
+ # Change plot order (annotations listed first will be on top)
131
+ histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
132
+ ```
133
+
134
+ ### Spatial Analysis with Visium Spots
135
+
136
+ Analyze the overlap between histological annotations and Visium spots:
137
+
138
+ ```python
139
+ # Compute overlap between annotations and spots
140
+ histo.compute_overlap_annotation()
141
+
142
+ # Visualize spots colored by their overlap with a specific annotation
143
+ histo.plot_annotation_overlay("Tumor")
144
+
145
+ # Find spots that overlap with two different annotations
146
+ histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
147
+ ```
148
+
149
+ ## Advanced Usage
150
+
151
+ ### Custom Annotation Colors
152
+
153
+ You can customize the colors used for annotations to make your visualizations match your publication style:
154
+
155
+ ```python
156
+ # Define custom colors
157
+ annotation_colors = {
158
+ "Tumor": "#E41A1C",
159
+ "Stroma": "#377EB8",
160
+ "Immune cells": "#4DAF4A"
161
+ }
162
+
163
+ # Use a color list matching the annotation order
164
+ annotations = histo.data_exploded['Annotation'].unique()
165
+ color_list = [annotation_colors[ann] for ann in annotations]
166
+
167
+ # Plot with custom colors
168
+ histo.plot_annotations(fill=color_list, contour="black")
169
+ ```
170
+
171
+ ### Exporting Results
172
+
173
+ ```python
174
+ # Generate and save a summary to CSV
175
+ summary = histo.generate_summary()
176
+ summary.to_csv("annotation_summary.csv", index=False)
177
+
178
+ # Save the figure
179
+ fig, ax = plt.subplots(figsize=(10, 10))
180
+ histo.plot_annotations()
181
+ plt.savefig("annotations.png", dpi=300, bbox_inches="tight")
182
+ ```
183
+
184
+ ### Working with Spot-Level Data
185
+
186
+ After computing overlaps, you can extract spots that overlap with specific annotations:
187
+
188
+ ```python
189
+ # Compute overlaps
190
+ histo.compute_overlap_annotation()
191
+
192
+ # Get spots that overlap with both tumor and immune cells
193
+ overlaps = histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
194
+ overlapping_spots = overlaps[2] # Third return value contains the overlapping spots
195
+
196
+ # Get spot IDs for further analysis
197
+ overlapping_spot_ids = overlapping_spots.index.tolist()
198
+ ```
199
+
200
+ ## API Reference
201
+
202
+ ### HistoMap Class
203
+
204
+ The main class for working with histological annotations and spatial data.
205
+
206
+ #### Methods
207
+
208
+ - `__init__(file_name, visium_spatialdata)`: Initialize with a GeoJSON file and Visium spatial data
209
+ - `generate_spot_geodata()`: Generate circular geometries for Visium spots
210
+ - `read_geojson_based_on_type(file_name)`: Read GeoJSON data based on file format
211
+ - `_extract_annotations()`: Process annotation data from GeoJSON
212
+ - `add_area_column()`: Add area calculations to annotations
213
+ - `generate_summary()`: Create a comprehensive summary of annotation metrics
214
+ - `display_plot_order()`: Show the current plot order of annotations
215
+ - `change_plot_order(order_list)`: Modify the order in which annotations are plotted
216
+ - `plot_annotations(fill, contour)`: Create a 2D plot of annotations
217
+ - `compute_overlap_annotation()`: Calculate overlap between spots and annotations
218
+ - `plot_annotation_overlay(annotation)`: Visualize overlap between spots and a specific annotation
219
+ - `plot_annotation_order(fill, contour, elevation_factor)`: Create a 3D plot with annotations at different z-levels
220
+ - `plot_annotation_order_interactive(fill, contour, elevation_factor)`: Create an interactive 3D plot using Plotly
221
+ - `plot_combined_annotation_overlap(annotation1, annotation2)`: Find spots overlapping with two annotations
222
+
223
+ ## FAQ
224
+
225
+ ### How does HistoMap handle large annotation files?
226
+
227
+ HistoMap efficiently processes GeoJSON files using GeoPandas' spatial indexing capabilities, which helps manage large datasets. For very large files, you may need to increase your system's memory allocation.
228
+
229
+ ### Can I use HistoMap with non-Visium spatial data?
230
+
231
+ While HistoMap is optimized for Visium data, you can adapt it for other spatial transcriptomics platforms by constructing a compatible spatial data object.
232
+
233
+ ### How can I integrate HistoMap with other spatial analysis tools?
234
+
235
+ HistoMap works well with the broader spatial transcriptomics ecosystem, including:
236
+ - Squidpy for additional spatial statistics
237
+ - Scanpy for cell-type identification
238
+ - Seaborn for advanced visualizations of results
239
+
240
+
241
+ ## License
242
+
243
+ This project is licensed under the MIT License - see the LICENSE file for details.
244
+
245
+ ## Citation
246
+
247
+ If you use HistoMap in your research, please cite:
248
+
249
+ ```
250
+ Unpublished
251
+ ```
252
+
253
+ ## Contact
254
+
255
+ For questions and feedback, please open an issue on the GitHub repository
@@ -0,0 +1,17 @@
1
+ from .histomap_object import HistoMap
2
+ from .visualization import *
3
+ from .histomap_utils import load_histomap
4
+ from .distances import *
5
+ import geopandas as gpd
6
+ import pandas as pd
7
+ import ast
8
+ import gzip
9
+ import io
10
+ import zipfile
11
+ import matplotlib.pyplot as plt
12
+ import matplotlib.cm as cm
13
+ import warnings
14
+ import geopandas as gpd
15
+ from shapely.geometry import Polygon, Point
16
+ from rtree import index
17
+ import numpy as np