HierGWAS (Hierarchical Multi-Scale Attention for Genome-Wide Association Studies) is a novel deep learning method that captures genomic interactions at multiple biological scales using hierarchical attention mechanisms.
This guide provides complete step-by-step instructions to run all HierGWAS files successfully.
# Run advanced analysis with synthetic data
python examples/advanced_usage.py --use-synthetic --output-dir results_advanced
# Or with your own data
python examples/advanced_usage.py --data-path /path/to/your/data --config config.json
# Create your data loading script
from hiergwas.data import GWASData
# Load your GWAS data
data = GWASData(
data_path="path/to/your/gwas/data",
snp_features="enformer", # or "baseline", "pops"
gene_features="esm", # or "go", "ppi"
pathway_features="node2vec", # or "onehot"
load_precomputed=True
)
Step 2: Configure Model
from hiergwas.config import HierGWASConfig, HierGWASConfigs
# Use predefined configuration
config = HierGWASConfigs.medium()
# Or create custom configuration
config = HierGWASConfig(
num_scales=3,
attention_heads=8,
hidden_dim=128,
num_layers=3,
biological_priors=True,
cross_scale_fusion=True
)
Step 3: Train Model
from hiergwas import HierGWASModel
# Create and train model
model = HierGWASModel(data=data, config=config)
# Training loop (see examples/basic_usage.py for complete code)
# ... training code ...
Usage Examples
Example 1: Quick Model Training
#!/usr/bin/env python3
"""Quick HierGWAS training example"""
import torch
from hiergwas import HierGWASModel
from hiergwas.config import HierGWASConfigs
from hiergwas.data import GWASData
from hiergwas.utils import create_synthetic_gwas_data, compute_metrics
# 1. Create synthetic data
data_dict = create_synthetic_gwas_data(
num_samples=1000,
num_snps=500,
num_genes=200,
save_path="data/quick_test"
)
# 2. Load data
gwas_data = GWASData("data/quick_test")
# 3. Configure model
config = HierGWASConfigs.small() # Fast training
config.update(
snp_feature_dim=gwas_data.snp_feature_dim,
gene_feature_dim=gwas_data.gene_feature_dim,
pathway_feature_dim=gwas_data.pathway_feature_dim,
max_epochs=10 # Quick training
)
# 4. Create model
model = HierGWASModel(data=gwas_data, config=config)
# 5. Create data loaders
train_loader, val_loader, test_loader = gwas_data.create_data_loaders(
batch_size=config.batch_size
)
# 6. Quick training loop
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=config.learning_rate)
print(" Starting quick training...")
for epoch in range(config.max_epochs):
model.train()
for batch in train_loader:
batch = batch.to(device)
optimizer.zero_grad()
x_dict = {node_type: batch[node_type].x for node_type in batch.node_types}
edge_index_dict = {edge_type: batch[edge_type].edge_index for edge_type in batch.edge_types}
predictions = model(x_dict, edge_index_dict, batch_size=batch['SNP'].batch_size)
labels = batch['SNP'].y[:batch['SNP'].batch_size]
loss = criterion(predictions.squeeze(), labels)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}/{config.max_epochs}, Loss: {loss.item():.4f}")
print(" Quick training completed!")
Example 2: Attention Analysis
#!/usr/bin/env python3
"""Attention analysis example"""
from hiergwas.utils import visualize_attention, analyze_biological_relevance
# Load trained model (from previous example)
# model = ... (your trained model)
# Get attention weights
model.eval()
with torch.no_grad():
for batch in test_loader:
batch = batch.to(device)
x_dict = {node_type: batch[node_type].x for node_type in batch.node_types}
edge_index_dict = {edge_type: batch[edge_type].edge_index for edge_type in batch.edge_types}
predictions, attention = model(
x_dict, edge_index_dict,
batch_size=batch['SNP'].batch_size,
return_attention_weights=True
)
break # Just analyze first batch
# Visualize attention patterns
visualize_attention(
attention,
scales=['local', 'regional', 'global'],
save_path='attention_visualization.png'
)
# Analyze biological relevance
biological_analysis = analyze_biological_relevance(
attention,
save_path='biological_analysis.pkl'
)
print(" Attention analysis completed!")
print(f"Attention entropy: {biological_analysis['attention_statistics']['attention_entropy']:.4f}")
Configuration Options
Predefined Configurations
from hiergwas.config import HierGWASConfigs
# Small: For quick testing and limited resources
config = HierGWASConfigs.small()
# Medium: For typical GWAS studies (recommended)
config = HierGWASConfigs.medium()
# Large: For large-scale studies
config = HierGWASConfigs.large()
# Research: Maximum performance
config = HierGWASConfigs.research()
Custom Configuration
from hiergwas.config import HierGWASConfig
config = HierGWASConfig(
# Architecture parameters
num_scales=3, # Number of biological scales
attention_heads=8, # Attention heads per scale
hidden_dim=128, # Hidden dimension
num_layers=3, # Number of layers
dropout=0.1, # Dropout rate
# Training parameters
learning_rate=1e-4, # Learning rate
weight_decay=5e-4, # L2 regularization
batch_size=512, # Batch size
max_epochs=100, # Maximum epochs
patience=10, # Early stopping patience
# Feature parameters
biological_priors=True, # Use biological priors
cross_scale_fusion=True, # Enable cross-scale fusion
# Hardware parameters
device='auto' # 'auto', 'cpu', 'cuda'
)
Getting Help
Check the examples: Look at examples/basic_usage.py and examples/advanced_usage.py
Read the installation guide: See INSTALLATION.md for detailed setup instructions
Check system requirements: Ensure your system meets the minimum requirements
Enable verbose logging: Add verbose=True to see detailed progress
Start small: Use HierGWASConfigs.small() for initial testing
Advanced Features
Hyperparameter Optimization
# Run with hyperparameter optimization
python examples/advanced_usage.py --use-synthetic
Training Time: 10-30 minutes (depending on data size and hardware)
Memory Usage: 2-8 GB RAM
Performance: AUC 0.80-0.85 on synthetic data
Files Generated: Model weights, visualizations, analysis results
Performance Benchmarks
Small Config: ~5 minutes training, 2 GB RAM
Medium Config: ~15 minutes training, 4 GB RAM
Large Config: ~30 minutes training, 8 GB RAM
Next Steps
Start with basic example: Run python examples/basic_usage.py
Try your own data: Modify the data loading section
Experiment with configurations: Try different HierGWASConfigs
Analyze results: Use the visualization and analysis tools
Scale up: Move to larger datasets and configurations
Support
Documentation: Check INSTALLATION.md for detailed setup
Examples: See examples/ directory for complete tutorials
Issues: Report bugs and ask questions on GitHub
Email: Contact the development team
HierGWAS introduces a groundbreaking Hierarchical Multi-Scale Attention (HMSA) architecture that revolutionizes genome-wide association studies by simultaneously capturing genomic interactions across multiple biological scales. Our method addresses the fundamental challenge in GWAS: understanding how genetic variants interact at different organizational levels of the genome.
🎯 Key Innovation
Traditional GWAS methods operate at a single scale, missing crucial multi-level interactions. HierGWAS pioneers a hierarchical attention mechanism that:
🧬 Captures Local Effects: SNP-SNP interactions within genes (1-10 kb)
🔗 Models Regional Patterns: Gene-gene interactions within pathways (10-100 kb)
🌐 Discovers Global Networks: Pathway-pathway interactions across chromosomes (>100 kb)
🧠 Learns Hierarchical Weights: Automatically balances scale importance for each phenotype
🏆 Breakthrough Results
🎯 10.9% AUC Improvement: ROC AUC increased from 0.742 to 0.823
📈 13.0% PR-AUC Boost: Enhanced precision-recall performance for rare variants
🔬 Biological Validation: 85% overlap with known Gene Ontology terms
class MultiScaleProcessor(nn.Module):
def __init__(self, num_scales=3):
self.scale_encoders = nn.ModuleList([
ScaleSpecificEncoder(scale_id=i)
for i in range(num_scales)
])
def forward(self, genomic_data):
scale_features = []
for i, encoder in enumerate(self.scale_encoders):
features = encoder(genomic_data, scale=i)
scale_features.append(features)
return scale_features
2. Hierarchical Attention Mechanism
class HierarchicalAttention(nn.Module):
def __init__(self, hidden_dim, num_scales):
self.scale_attention = nn.MultiheadAttention(hidden_dim, num_heads=8)
self.hierarchical_weights = nn.Sequential(
nn.Linear(hidden_dim * num_scales, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, num_scales),
nn.Softmax(dim=-1)
)
def forward(self, scale_features):
# Compute scale-specific attention
attended_features = []
for features in scale_features:
attended, _ = self.scale_attention(features, features, features)
attended_features.append(attended)
# Hierarchical weighting
concat_features = torch.cat(attended_features, dim=-1)
weights = self.hierarchical_weights(concat_features)
# Weighted combination
output = sum(w * f for w, f in zip(weights.unbind(-1), attended_features))
return output, weights
HierGWAS: Hierarchical Multi-Scale Attention for Genome-Wide Association Studies and Genomic Discovery
Paper | Documentation | Tutorials | Results
HierGWAS (Hierarchical Multi-Scale Attention for Genome-Wide Association Studies) is a novel deep learning method that captures genomic interactions at multiple biological scales using hierarchical attention mechanisms.
This guide provides complete step-by-step instructions to run all HierGWAS files successfully.
Quick Start
Main steps to run HierGWAS:
System Requirements
Minimum Requirements
Recommended Requirements
Installation Steps
Step 1: Environment Setup
Option A: Using Virtual Environment (Recommended)
Option B: Using Conda
Step 2: Install PyTorch
For CPU-only systems:
For CUDA 11.8 systems:
For CUDA 12.1 systems:
Step 3: Install PyTorch Geometric
Step 4: Install Other Dependencies
Step 5: Install HierGWAS
Step 6: Verify Installation
File Structure
Step-by-Step Execution
Method 1: Basic Usage (Recommended for Beginners)
Step 1: Run Basic Example
What this does:
Expected Output:
Generated Files:
best_model.pth- Trained model weightshiergwas_model/- Complete model packageattention_analysis.png- Attention visualizationstraining_curves.png- Training progress plotsbiological_analysis.pkl- Biological relevance analysisMethod 2: Advanced Usage (For Researchers)
Step 1: Run Advanced Example
What this does:
Expected Output:
Method 3: Custom Usage (For Specific Datasets)
Step 1: Prepare Your Data
Step 2: Configure Model
Step 3: Train Model
Usage Examples
Example 1: Quick Model Training
Example 2: Attention Analysis
Configuration Options
Predefined Configurations
Custom Configuration
Getting Help
examples/basic_usage.pyandexamples/advanced_usage.pyINSTALLATION.mdfor detailed setup instructionsverbose=Trueto see detailed progressHierGWASConfigs.small()for initial testingAdvanced Features
Hyperparameter Optimization
Cross-Validation
Custom Data Loading
Model Interpretation
Expected Performance
Typical Results
Performance Benchmarks
Next Steps
python examples/basic_usage.pyHierGWASConfigsSupport
INSTALLATION.mdfor detailed setupexamples/directory for complete tutorialsHierGWAS introduces a groundbreaking Hierarchical Multi-Scale Attention (HMSA) architecture that revolutionizes genome-wide association studies by simultaneously capturing genomic interactions across multiple biological scales. Our method addresses the fundamental challenge in GWAS: understanding how genetic variants interact at different organizational levels of the genome.
🎯 Key Innovation
Traditional GWAS methods operate at a single scale, missing crucial multi-level interactions. HierGWAS pioneers a hierarchical attention mechanism that:
🏆 Breakthrough Results
HierGWAS Hierarchical Multi-Scale Attention captures genomic interactions at three biological scales
🌟 Method Overview
🧠 Hierarchical Multi-Scale Attention (HMSA)
Our core innovation is the HMSA mechanism that processes genomic data through three biologically-motivated scales:
Scale 1: Local Genomic Context (1-10 kb)
Scale 2: Regional Genomic Architecture (10-100 kb)
Scale 3: Global Genomic Networks (>100 kb)
Hierarchical Integration
The hierarchical weighting module learns to optimally combine information from all scales:
Where
Aᵢ(Xᵢ)represents scale-specific attention andαᵢare learned hierarchical weights.Performance Results
Benchmark Comparison
Ablation Study
Biological Validation Results
Installation
Quick Setup
Environment Setup
Quick Start
Basic Usage
Advanced Configuration
Attention Analysis
Method Details
🏗Architecture Overview
1. Multi-Scale Feature Processing
2. Hierarchical Attention Mechanism
3. Biological Prior Integration
🔬 Biological Motivation
Scale-Specific Biological Processes
• Haplotype structure
• Local epistasis
Sharp attention kernels
• Protein complexes
• Metabolic pathways
Pathway-aware kernels
• Chromatin domains
• Epistatic networks
Long-range kernels
Learned Hierarchical Weights
Across diverse phenotypes, HierGWAS learns biologically meaningful scale preferences:
Documentation
User Guides
Research Documentation
Tutorials and Examples
tutorials/basic_usage.ipynb- Getting startedtutorials/advanced_features.ipynb- Advanced configurationstutorials/attention_analysis.ipynb- Interpreting resultstutorials/biological_insights.ipynb- Biological discoveryReproducibility
Reproduce Paper Results
Custom Experiments
Comparison with State-of-the-Art
📈 Performance Benchmarks
Novel Contributions
Contributing
We welcome contributions from the genomics and machine learning communities!
Development Setup
Citation
If you use HierGWAS in your research, please cite our paper:
HierGWAS Quick Start Guide
Run HierGWAS in 5 Minutes
Step 1: Setup Environment (2 minutes)
Step 2: Install Dependencies (2 minutes)
Step 3: Run Basic Example (1 minute)
What Each File Does
Core Files
hiergwas/hiergwas.py- Main model classhiergwas/attention.py- Hierarchical attention mechanismhiergwas/model.py- Neural network architecturehiergwas/config.py- Configuration managementhiergwas/data.py- Data loading and preprocessinghiergwas/utils.py- Visualization and analysis toolsExample Files
examples/basic_usage.py- Complete tutorial (run this first!)examples/advanced_usage.py- Advanced features and analysisExecution Order
For Beginners:
python examples/basic_usage.pyFor Advanced Users:
python examples/advanced_usage.py --use-syntheticExpected Output
When you run
python examples/basic_usage.py, you should see:Generated Files:
best_model.pth- Trained modelattention_analysis.png- Attention visualizationstraining_curves.png- Training progresshiergwas_model/- Complete model packageNext Steps
examples/basic_usage.pyto understand the workflowexamples/advanced_usage.py💡 Key Commands Summary
Related Resources
Datasets
Tools & Libraries
Research Papers
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contact & Support
Made with ❤️ for the scientific community