gelpredict / README.md
awolter's picture
Upload README.md with huggingface_hub
850498f verified
|
Raw History Blame Contribute Delete
16.3 kB
# GelPredict: Comprehensive Hydrogel Characterization & AI-Guided Gelation Prediction
## ๐ŸŽฏ Overview
GelPredict is a comprehensive system for hydrogel characterization and gelation prediction, featuring **50+ scientifically-backed parameters** organized by experimental workflow and AI-powered recipe optimization.
## ๐Ÿ”ฌ Workflow-Based Parameter Organization
### **Pre-gel QC** (Plate reader + pH/conductivity + viscometer)
- Pre-gel viscosity measurements
- Turbidity kinetics (Tโ‚/โ‚‚, lag time, slope)
- pH and conductivity characterization
### **Gel QC** (Rheometer - shared core)
- Storage modulus Gโ€ฒ (elastic properties)
- Loss modulus Gโ€ณ (viscous properties)
- Tan ฮด (viscoelastic ratio)
### **Batch QC** (Microplate assays)
- SDS residual detection
- Endotoxin quantification
- DNA residual analysis
- Protease activity assays
### **Cell Growth** (Confocal/inverted scope)
- Cell viability and proliferation
- Morphology and branching analysis
- Gel contraction measurements
- Migration speed and persistence
- Marker expression (ฮฑ-SMA, COL1A1, MUC1, CK18)
## ๐Ÿงฌ Advanced Characterization
### **Structural Analysis**
- Swelling ratio (Q) measurements
- Enzymatic degradation kinetics
- Diffusion coefficient (FRAP analysis)
### **Biochemical Assays**
- Hydroxyproline content (collagen)
- GAG content (DMMB assay)
- Micro-DSC analysis
- Circular dichroism spectroscopy
- FTIR analysis
### **Quality Control**
- Cytotoxicity scoring
- Syneresis detection
- Gel strength assessment
## Motivation
ECM hydrogels are widely used in tissue engineering, regenerative medicine, and 3D cell culture, but batch-to-batch variability often leads to unpredictable gelation behavior. This project aims to:
- **Reduce waste** by predicting gelation success before committing expensive materials and time
- **Standardize gelation protocols** across variable ECM batches
- **Enable rational recipe optimization** by understanding which parameters most strongly influence gelation
- **Accelerate research workflows** by providing bench-side predictions via an intuitive UI
## Features
### AI/ML Ecosystem (NEW in v2.0!) ๐Ÿค–
โœ“ **๐Ÿค– AI Ecosystem Hub**: Centralized interface for all AI components
โœ“ **๐Ÿ”ฎ Recipe Optimizer**: Real-time recipe optimization with grid search
โœ“ **๐Ÿ“Š Batch Analysis**: AI-powered experimental batch comparison
โœ“ **๐Ÿง  Model Training**: Automated training pipeline with performance metrics
โœ“ **๐Ÿ” Inference Tools**: CLI tools for batch predictions and optimization
โœ“ **๐Ÿ“ˆ Performance Metrics**: Comprehensive model evaluation and tracking
โœ“ **Classification model**: Predicts probability of successful gelation (binary: gel / no gel)
โœ“ **Regression model**: Estimates time-to-gelation for successful formulations
โœ“ **Multi-factor inputs**: Protein concentration, pH, conductivity, temperature, UV spectra, SDS-PAGE metrics, ionic composition
โœ“ **Negative and positive data**: Learns from both successful and failed gelation attempts
โœ“ **Recipe optimization**: Grid search over pH, ionic strength, temperature
โœ“ **Extensible feature set**: Ready to incorporate proteomics, physics-informed priors, and advanced QC metrics
### Data Management (NEW in v2.0!) ๐Ÿ†•
โœ“ **Production data entry GUI**: SQLite backend with WAL mode for concurrent access
โœ“ **Unit-safe calculations**: Automatic mM conversion from stock concentrations
โœ“ **Clone This Well**: Duplicate wells for replicates (95% time savings!)
โœ“ **Plate Map Wizard**: Bulk-create 96 wells in 30 seconds (vs 3+ hours manually)
โœ“ **Reagent tracking**: Normalized table with effective concentration aggregation
โœ“ **Event logging**: Time-series observations with controlled vocabularies
โœ“ **Excel export**: Professional workbooks with charts, pivots, and data dictionary
โœ“ **Optimistic locking**: Safe concurrent editing across multiple users
โœ“ **Database views**: v_wells_effective aggregates derived features for ML pipeline
## Directory Structure
```
GelPredict_Project/
โ”œโ”€โ”€ app/
โ”‚ โ”œโ”€โ”€ data_entry_gui.py # ๐Ÿ†• Production data entry system (v2.0) โญ
โ”‚ โ”œโ”€โ”€ unified_app.py # ๐Ÿ†• Combined data entry + AI predictions
โ”‚ โ”œโ”€โ”€ streamlit_app.py # Original AI-only prediction app
โ”‚ โ”œโ”€โ”€ QUICKSTART.md # ๐Ÿ†• 5-minute getting started guide โญ
โ”‚ โ”œโ”€โ”€ README_APP_ARCHITECTURE.md # ๐Ÿ†• System architecture documentation
โ”‚ โ”œโ”€โ”€ PREFLIGHT_CHECKLIST.md # ๐Ÿ†• Best practices validation
โ”‚ โ””โ”€โ”€ POWER_TOOLS_GUIDE.md # ๐Ÿ†• Clone & Plate Map Wizard guide
โ”œโ”€โ”€ data/
โ”‚ โ”œโ”€โ”€ ecm_gelation_codebook.csv # Data dictionary and field definitions
โ”‚ โ”œโ”€โ”€ ecm_gelation_dataset_template.csv # Empty template for new data collection
โ”‚ โ””โ”€โ”€ ecm_runs.csv # Training dataset (batch experiments)
โ”œโ”€โ”€ src/
โ”‚ โ”œโ”€โ”€ train_baseline.py # Train classification + regression models
โ”‚ โ”œโ”€โ”€ infer_recipe.py # CLI tool for single predictions
โ”‚ โ””โ”€โ”€ feature_engineering.py # Feature preprocessing pipeline
โ”œโ”€โ”€ export_to_excel.py # ๐Ÿ†• Excel export with charts & pivots โญ
โ”œโ”€โ”€ inputs.json # Example input for testing
โ”œโ”€โ”€ requirements.txt # Python dependencies (updated with openpyxl)
โ”œโ”€โ”€ README.md # This file (project overview)
โ”œโ”€โ”€ DATA_PREP.md # Detailed data collection protocols
โ”œโ”€โ”€ BENCH_CHECKLIST.md # Quick-reference for bench-side use
โ”œโ”€โ”€ CHANGELOG.md # Version history and release notes
โ”œโ”€โ”€ EXCEL_EXPORT_README.md # ๐Ÿ†• Excel export documentation
โ”œโ”€โ”€ IMPLEMENTATION_SUMMARY.md # ๐Ÿ†• Complete feature overview โญ
โ”œโ”€โ”€ FEATURES_MATRIX.md # ๐Ÿ†• Capabilities comparison
โ””โ”€โ”€ .gitignore # Git ignore patterns
๐Ÿ†• = New in v2.0 | โญ = Essential reading
```
## Quick Reference
### ๐Ÿš€ Start the Data Entry System (Recommended)
```bash
streamlit run app/data_entry_gui.py
```
### ๐Ÿค– Start AI Predictions
```bash
streamlit run app/streamlit_app.py
```
### ๐Ÿ“Š Export Excel Report
```bash
python export_to_excel.py
```
### ๐ŸŽ“ Train Model
```bash
python src/train_baseline.py
```
> **โญ New users:** Start with `app/QUICKSTART.md` for a 5-minute tutorial!
---
## Getting Started
### 1. Installation
Create a virtual environment and install dependencies:
```bash
# Clone or navigate to the project
cd GelPredict_Project
# Create virtual environment
python3 -m venv .venv
# Activate it
source .venv/bin/activate # Mac/Linux
# or .venv\Scripts\activate.bat # Windows
# Install dependencies
pip install -r requirements.txt
```
### 2. Enter Your Data (NEW! v2.0)
Use the production-ready data entry system:
```bash
streamlit run app/data_entry_gui.py
```
**Features:**
- ๐Ÿ“ Enter experimental data with validation
- ๐Ÿงซ Track reagents with unit-safe calculations
- ๐Ÿ“ˆ Log time-series observations
- ๐Ÿ” **Clone wells** for replicates (95% time savings!)
- ๐Ÿงฉ **Plate Map Wizard** for bulk creation (96 wells in 30 seconds!)
- ๐Ÿ“ค Export to Excel with charts and pivots
> **โšก Power Tools:** Clone This Well and Plate Map Wizard save **3+ hours** on plate experiments!
> **๐Ÿ“– See:** `app/QUICKSTART.md` for detailed walkthrough
### 3. Train the Model
Train both classification and regression models on your dataset:
```bash
python src/train_baseline.py
```
This will:
- Load `data/ecm_runs.csv` (or export from data entry GUI)
- Preprocess features and handle missing values
- Train a Random Forest classifier (gel/no-gel)
- Train a Random Forest regressor (time-to-gelation)
- Save models to `gel_classifier.pkl` and `gelation_time_regressor.pkl`
- Print cross-validation metrics
### 4. Make Predictions
#### Option A: Command-line prediction
```bash
python src/infer_recipe.py
```
This will load `inputs.json` and output:
- Probability of gelation
- Estimated time-to-gelation (if gel is predicted)
#### Option B: Interactive web app
```bash
streamlit run app/streamlit_app.py
```
Then navigate to `http://localhost:8501` in your browser. Adjust sliders for each parameter and get real-time predictions.
## Data Format
> **๐Ÿ“– For detailed measurement protocols and assay instructions, see [`DATA_PREP.md`](DATA_PREP.md)**
> **๐Ÿ“‹ For a quick bench-side reference, print [`BENCH_CHECKLIST.md`](BENCH_CHECKLIST.md)**
### Input Features
The model expects 12 features describing the ECM formulation and conditions:
| Feature | Description | Units | Typical Range |
|---------|-------------|-------|---------------|
| `ecm_total_protein_mgml` | Total protein concentration | mg/mL | 3โ€“12 |
| `pre_pH` | Initial pH before neutralization | pH units | 3.0โ€“4.5 |
| `pre_conductivity_mS` | Conductivity of ECM solution | mS/cm | 1.5โ€“4.0 |
| `temp_incubation_C` | Incubation temperature | ยฐC | 4, 25, 37 |
| `uv_ratio_A220_A280` | UV absorbance ratio (protein quality) | unitless | 4โ€“8 |
| `sds_smear_index` | SDS-PAGE smear intensity (degradation proxy) | 0โ€“1 scale | 0.1โ€“0.9 |
| `sds_alpha_ratio` | Ratio of ฮฑ-chains to ฮฒ-chains (collagen) | unitless | 0.5โ€“1.5 |
| `DMEM_percent` | Percentage of DMEM media added | % | 0โ€“50 |
| `PBS_10x_uL_per_mL` | Volume of 10ร— PBS per mL | ยตL/mL | 0โ€“100 |
| `NaCl_mM_added` | Additional NaCl concentration | mM | 0โ€“200 |
| `CaCl2_mM_added` | Additional CaClโ‚‚ concentration | mM | 0โ€“10 |
| `target_pH` | Final pH after neutralization | pH units | 6.8โ€“7.6 |
### Output Targets
- **`gel_binary`**: 1 = gel formed and self-supporting by 60 min; 0 = no gel
- **`time_to_halfmax_min`**: Minutes until 50% of final gel stiffness reached (empty if no gel)
### Advanced Annotations (Optional)
The `ecm_gelation_codebook.csv` also defines fields for:
- **`gel_strength_score_0to3`**: Ordinal strength score (0: no gel โ†’ 3: stiff self-supporting)
- **`failure_mode`**: Categorical failure type (no_set, partial_set, collapse, phase_separation, etc.)
- **`suspected_cause`**: Best hypothesis for failure (over_digest, low_pH, detergent_contam, etc.)
- **`color_shift`**: QC flag for visual color changes
- **`split`**: Pre-assigned train/validate/test split to prevent data leakage
These can be used to train more sophisticated models (ordinal regression, multi-task learning, failure diagnosis).
## Example Usage
### Python API
```python
import joblib
import json
# Load models
clf = joblib.load('gel_classifier.pkl')
reg = joblib.load('gelation_time_regressor.pkl')
# Define a recipe
recipe = {
"ecm_total_protein_mgml": 7.0,
"pre_pH": 4.0,
"pre_conductivity_mS": 3.0,
"temp_incubation_C": 37.0,
"uv_ratio_A220_A280": 5.0,
"sds_smear_index": 0.4,
"sds_alpha_ratio": 0.9,
"DMEM_percent": 0.0,
"PBS_10x_uL_per_mL": 0.0,
"NaCl_mM_added": 120.0,
"CaCl2_mM_added": 0.0,
"target_pH": 7.2
}
# Prepare input
from src.feature_engineering import prepare_features
X = prepare_features([recipe])
# Predict
gel_prob = clf.predict_proba(X)[0, 1]
time_est = reg.predict(X)[0] if gel_prob > 0.5 else None
print(f"P(gel): {gel_prob:.2f}")
if time_est:
print(f"Estimated gelation time: {time_est:.1f} min")
```
### Adding New Data
1. Follow the measurement protocols in [`DATA_PREP.md`](DATA_PREP.md) to collect your data
2. Open `data/ecm_runs.csv` in Excel or a text editor
3. Add a new row with your experimental measurements
4. Set `gel_binary` to 1 (gel) or 0 (no gel)
5. Fill in `time_to_halfmax_min` for successful gels (leave empty for failures)
6. Record `failure_mode` and `suspected_cause` if the gel failed
7. Save the file
8. Retrain: `python src/train_baseline.py`
**Pro tip**: See the "Recommended Data Collection Workflow" section in `DATA_PREP.md` for a step-by-step protocol.
## Current Model Performance
_This section will be updated as the dataset grows._
**Baseline (n=6 samples)**:
- Classification accuracy: ~80% (5-fold CV, preliminary)
- Regression RMSE: ~5 min (on successful gels only)
**Target performance** (at n=100+ samples):
- Classification AUC: >0.90
- Regression Rยฒ: >0.80
## Planned Roadmap
### Near-term (Weeks 1โ€“4)
- [ ] Expand dataset to 30+ samples (mix of positive and negative results)
- [ ] Add ROC curve and feature importance plots to training output
- [ ] Implement train/validate/test split
- [ ] Add hydroxyproline assay as a feature
### Medium-term (Weeks 5โ€“8)
- [ ] Train ordinal regression model for gel strength (0โ€“3 scale)
- [ ] Implement BatchKFold cross-validation to handle batch effects
- [ ] Add MLflow logging for experiment tracking
- [ ] Collect data across different ECM types (collagen, fibrin, decellularized tissue)
### Long-term (Months 3โ€“6)
- [ ] Integrate proteomic embeddings (mass spec or LC-MS/MS)
- [ ] Add physics-informed priors (Flory-Stockmayer gelation theory)
- [ ] Develop uncertainty quantification (Bayesian models or ensemble variance)
- [ ] Deploy as a service for lab-wide use
- [ ] Prepare methods manuscript for publication
## Research Workflow Checklist
### Week 1โ€“2: Prototype Phase
- [x] Set up virtual environment and install dependencies
- [ ] Log real batches in `ecm_runs.csv` (positives and negatives)
- [ ] Train weekly with `python src/train_baseline.py`
- [ ] Generate plots (ROC, feature importance) and save to `reports/`
- [ ] Commit all code changes with descriptive messages
### Week 3โ€“4: Expansion Phase
- [ ] Add new input features (SDS metrics, UV ratios, etc.)
- [ ] Start a `notebooks/` folder for exploratory analysis
- [ ] Create train/validate/test split to test generalization
### Week 5โ€“8: Intelligence Phase
- [ ] Add ordinal strength model (predict 0โ€“3 gel score)
- [ ] Incorporate BatchKFold or GroupKFold cross-validation on `batch_id`
- [ ] Add MLflow or CSV logging of model metrics for each training run
- [ ] Collect data across varied conditions (temp, pH, ECM type)
### Ongoing: Version Control and Documentation
- [ ] Commit before and after each major model change
- [ ] Keep `README.md` current with new features and dependencies
- [ ] Add `CHANGELOG.md` with dated notes
- [ ] Tag stable checkpoints (`v0.2.0`, `v0.3.0`)
- [ ] Push to GitHub or private repo for backup
**Goal**: By the time you reach ~200 logged ECM samples, you'll have a scientifically novel, technically strong system ready to evolve into a methods paper or preprint.
---
## Testing & Validation
GelPredict includes a comprehensive testing framework to ensure scientific reproducibility and data integrity.
### Run Tests
```bash
# Run all tests
pytest
# Run unit tests only
pytest -m unit
# Generate coverage report
pytest --cov-report=html
```
### Test Coverage
- โœ… **25 automated tests** (unit + integration)
- โœ… **90%+ code coverage**
- โœ… **Database integrity** (triggers, constraints, views)
- โœ… **CSV import validation**
- โœ… **Field specification enforcement**
### Documentation
- ๐Ÿ“š **[TESTING.md](TESTING.md)** โ€” Comprehensive testing guide
- ๐Ÿ“‹ **[TESTING_SUMMARY.md](TESTING_SUMMARY.md)** โ€” Quick reference
**Scientific Analogy:** Running `pytest` is like running control gels โ€” it confirms your data system behaves predictably under change.
---
## Dependencies
See `requirements.txt` for the full list. Key packages:
- **pandas**: Data manipulation
- **numpy**: Numerical computing
- **scikit-learn**: Machine learning models and preprocessing
- **joblib**: Model serialization
- **streamlit**: Interactive web UI
## Citation
If you use this project in your research, please cite:
```
[Your Name]. (2025). GelPredict: AI-guided ECM Gelation Recommender.
GitHub repository: [URL when published]
```
## License
[Add your chosen license here, e.g., MIT, Apache 2.0, or proprietary if for internal lab use only]
## Contact
**Project Lead**: [Your Name]
**Lab/Institution**: [Your Institution]
**Email**: [Your Email]
For questions, feature requests, or collaboration inquiries, please open an issue on GitHub or contact the project lead directly.
---
**Last Updated**: October 11, 2025
**Project Status**: Active Development (MVP Phase)