A Python library for analyzing histological annotations alongside spatial transcriptomics data
Project description
HistoMapTx
Documentation is available here : https://histomaptx.readthedocs.io/en/latest/
Features
- Flexible File Support: Read annotations from various formats (GeoJSON, gzipped, or zipped files)
- Comprehensive Metrics: Calculate area, perimeter, circularity, solidity, and other geometric properties
- Interactive Visualization: Generate 2D and 3D visualizations of tissue annotations
- Annotation Ordering: Control the rendering order of annotations for clearer visualization
- Spatial Analysis: Compute overlaps between annotations and Visium spots
- Summary Statistics: Generate detailed morphological summaries for each annotation
Installation
pip install histomap
Dependencies
HistoMap requires:
- geopandas
- pandas
- numpy
- matplotlib
- plotly
- scipy
- shapely
Quick Start
import histomap as hm
import squidpy as sq
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load Visium data (with squidpy for example)
adata = sq.datasets.visium_fluo_moran_test()
spatial_data = adata.uns['spatial']
# Load annotations from a GeoJSON file
histo = hm.HistoMap("annotations.geojson", spatial_data)
# Display a summary of the annotations
print(histo.generate_summary())
# Plot the annotations
histo.plot_annotations()
# Change the plotting order
histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
# Compute overlaps between annotations and Visium spots
histo.compute_overlap_annotation()
# Plot spots colored by their overlap with a specific annotation
histo.plot_annotation_overlay("Tumor")
Core Functionality
Loading and Processing Annotations
HistoMap automatically processes annotation files in various formats and extracts key information:
# Initialize with a GeoJSON file
histo = HistoMap("annotations.geojson", visium_spatial_data, '/path/to/image.tiff')
Generating Statistical Summaries
Get comprehensive morphological statistics about each annotation:
# Generate a summary DataFrame with key metrics
summary = histo.generate_summary()
print(summary)
The summary includes metrics such as:
- Total area and perimeter
- Mean aspect ratio, circularity, and compactness
- Centroid coordinates
- Solidity and extent
- Polygon counts
Visualization
HistoMap offers multiple visualization options:
Basic Annotation Plot
# Plot annotations with default settings
histo.plot_annotations()
# Customize fill and contour colors
histo.plot_annotations(fill=True, contour="black")
# Specify custom colors for each annotation
histo.plot_annotations(fill=["red", "blue", "green"], contour=["black", "black", "black"])
3D Visualization by Annotation Order
# Create a 3D plot with annotations at different z-levels
histo.plot_annotation_order(fill=True, elevation_factor=1.5)
# Create an interactive 3D plot using Plotly
histo.plot_annotation_order_interactive(fill=True, elevation_factor=1.5)
Controlling Annotation Order
The order in which annotations are plotted can be crucial for visualization:
# Display current plot order
histo.display_plot_order()
# Change plot order (annotations listed first will be on top)
histo.change_plot_order(["Tumor", "Stroma", "Immune cells"])
Spatial Analysis with Visium Spots
Analyze the overlap between histological annotations and Visium spots:
# Compute overlap between annotations and spots
histo.compute_overlap_annotation()
# Visualize spots colored by their overlap with a specific annotation
histo.plot_annotation_overlay("Tumor")
# Find spots that overlap with two different annotations
histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
Advanced Usage
Custom Annotation Colors
You can customize the colors used for annotations to make your visualizations match your publication style:
# Define custom colors
annotation_colors = {
"Tumor": "#E41A1C",
"Stroma": "#377EB8",
"Immune cells": "#4DAF4A"
}
# Use a color list matching the annotation order
annotations = histo.data_exploded['Annotation'].unique()
color_list = [annotation_colors[ann] for ann in annotations]
# Plot with custom colors
histo.plot_annotations(fill=color_list, contour="black")
Exporting Results
# Generate and save a summary to CSV
summary = histo.generate_summary()
summary.to_csv("annotation_summary.csv", index=False)
# Save the figure
fig, ax = plt.subplots(figsize=(10, 10))
histo.plot_annotations()
plt.savefig("annotations.png", dpi=300, bbox_inches="tight")
Working with Spot-Level Data
After computing overlaps, you can extract spots that overlap with specific annotations:
# Compute overlaps
histo.compute_overlap_annotation()
# Get spots that overlap with both tumor and immune cells
overlaps = histo.plot_combined_annotation_overlap("Tumor", "Immune cells")
overlapping_spots = overlaps[2] # Third return value contains the overlapping spots
# Get spot IDs for further analysis
overlapping_spot_ids = overlapping_spots.index.tolist()
API Reference
HistoMap Class
The main class for working with histological annotations and spatial data.
Methods
__init__(file_name, visium_spatialdata): Initialize with a GeoJSON file and Visium spatial datagenerate_spot_geodata(): Generate circular geometries for Visium spotsread_geojson_based_on_type(file_name): Read GeoJSON data based on file format_extract_annotations(): Process annotation data from GeoJSONadd_area_column(): Add area calculations to annotationsgenerate_summary(): Create a comprehensive summary of annotation metricsdisplay_plot_order(): Show the current plot order of annotationschange_plot_order(order_list): Modify the order in which annotations are plottedplot_annotations(fill, contour): Create a 2D plot of annotationscompute_overlap_annotation(): Calculate overlap between spots and annotationsplot_annotation_overlay(annotation): Visualize overlap between spots and a specific annotationplot_annotation_order(fill, contour, elevation_factor): Create a 3D plot with annotations at different z-levelsplot_annotation_order_interactive(fill, contour, elevation_factor): Create an interactive 3D plot using Plotlyplot_combined_annotation_overlap(annotation1, annotation2): Find spots overlapping with two annotations
FAQ
How does HistoMap handle large annotation files?
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.
Can I use HistoMap with non-Visium spatial data?
While HistoMap is optimized for Visium data, you can adapt it for other spatial transcriptomics platforms by constructing a compatible spatial data object.
How can I integrate HistoMap with other spatial analysis tools?
HistoMap works well with the broader spatial transcriptomics ecosystem, including:
- Squidpy for additional spatial statistics
- Scanpy for cell-type identification
- Seaborn for advanced visualizations of results
License
This project is licensed under the MIT License - see the LICENSE file for details.
Citation
If you use HistoMap in your research, please cite:
Unpublished
Contact
For questions and feedback, please open an issue on the GitHub repository
Project details
Release history Release notifications | RSS feed
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 histomaptx-0.1.0.tar.gz.
File metadata
- Download URL: histomaptx-0.1.0.tar.gz
- Upload date:
- Size: 32.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a7de104cd704fc6456af70bdff39b76c04ee601c3e2f0df8b5cfe6509295019
|
|
| MD5 |
6d29ce5a648dfc5aeee48ff51be81ff2
|
|
| BLAKE2b-256 |
01bee3dc7be92144d5e5b9d570a4ae45d3c50688a291f937f2d83536924a3ff0
|
File details
Details for the file histomaptx-0.1.0-py3-none-any.whl.
File metadata
- Download URL: histomaptx-0.1.0-py3-none-any.whl
- Upload date:
- Size: 32.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1c98143d3bdaee151ede76eb1375b16aba532daf8dfa1db326bcdea227d22298
|
|
| MD5 |
a758db7531457766a2a9ebe70ead380a
|
|
| BLAKE2b-256 |
ca75736f1eb4acf5287ce479bccf2f9c0e89cdc4d93ec6231ee019c650d27d4a
|