pyPrecipTHR 1.0.0
Flexible Temporal Hierarchical Reconciliation Package for Precipitation Forecasting
Requires Python: >=3.8
Keywords: forecasting, temporal-hierarchy, reconciliation, precipitation, uncertainty-quantification, machine-learning, time-series, flexible-models

# pyPrecipTHR: Python Package for Temporal Hierarchical Reconciliation of Precipitation Forecasts

[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![PyPI version](https://badge.fury.io/py/pyPrecipTHR.svg)](https://badge.fury.io/py/pyPrecipTHR)

A comprehensive Python package for probabilistic temporal hierarchical reconciliation methods with uncertainty quantification for precipitation forecasting across multiple timescales.

## 🌟 Features

- **Flexible Model Architecture**: Support for multiple forecasting models (Random Forest, ETS, SARIMA, and custom models)
- **Temporal Hierarchical Reconciliation**: Advanced reconciliation methods (MinT, OLS) for consistent forecasts across time scales
- **Uncertainty Quantification**: Robust bootstrap and quantile-based uncertainty estimation
- **Multi-scale Forecasting**: Simultaneous forecasting at monthly, quarterly, and annual scales
- **Comprehensive Evaluation**: Built-in evaluation metrics and visualization tools
- **Easy Integration**: Simple API for quick implementation and experimentation

## 📋 Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Features](#features)
- [Usage Examples](#usage-examples)
- [API Documentation](#api-documentation)
- [Contributing](#contributing)
- [License](#license)

## 🚀 Installation

### Prerequisites

- Python 3.8 or higher
- pip package manager

### Install from PyPI

```bash
pip install pyPrecipTHR
```

### Install from Source

```bash
git clone https://github.com/yourusername/pyPrecipTHR.git
cd pyPrecipTHR
pip install -e .
```

### Dependencies

The package requires the following core dependencies:
- pandas >= 1.3.0
- numpy >= 1.21.0
- scikit-learn >= 1.0.0
- statsmodels >= 0.13.0
- scipy >= 1.7.0
- matplotlib >= 3.5.0
- seaborn >= 0.11.0

## 🎯 Quick Start

### Basic Usage

```python
from pyPrecipTHR import FlexibleTemporalHierarchicalReconciliation

# Initialize the system
thr = FlexibleTemporalHierarchicalReconciliation(
    model_name='random_forest',
    n_bootstrap=500,
    reconciliation_method='mint'
)

# Load and process data
data = thr.load_data('basin_name')

# Generate forecasts with uncertainty
forecasts = thr.forecast_with_uncertainty(data, hierarchy)

# Reconcile forecasts
reconciled = thr.reconcile_forecasts(forecasts)

# Evaluate results
evaluation = thr.evaluate_forecasts(forecasts, reconciled)
```

### Command Line Demo

```bash
# Run the built-in demo
pyPrecipTHR-demo

# Or run specific demos
python -m pyPrecipTHR.demo
```

## 🔧 Features

### 1. Flexible Model Architecture

The package supports multiple forecasting models:

- **Random Forest**: Primary model with robust uncertainty quantification
- **ETS (Exponential Smoothing)**: Traditional time series model
- **SARIMA**: Statistical time series model
- **Custom Models**: Easy integration of your own models

```python
from pyPrecipTHR import ModelRegistry

# Register and use different models
registry = ModelRegistry()
registry.register_model('my_model', MyCustomModel)

thr = FlexibleTemporalHierarchicalReconciliation(
    model_name='my_model'
)
```

### 2. Temporal Hierarchical Reconciliation

Advanced reconciliation methods ensure consistency across time scales:

- **MinT Reconciliation**: Minimum Trace reconciliation
- **OLS Reconciliation**: Ordinary Least Squares reconciliation
- **Custom Reconciliation**: Extensible reconciliation methods

### 3. Uncertainty Quantification

Robust uncertainty estimation through:

- **Bootstrap Methods**: Non-parametric uncertainty estimation
- **Quantile Methods**: Distribution-based uncertainty
- **Heteroscedastic Models**: Variance-aware forecasting

### 4. Multi-scale Forecasting

Simultaneous forecasting at multiple temporal scales:

- Monthly forecasts
- Quarterly forecasts  
- Annual forecasts
- Custom temporal aggregations

## 📊 Usage Examples

### Example 1: Basic Forecasting

```python
from pyPrecipTHR import FlexibleTemporalHierarchicalReconciliation
import pandas as pd

# Initialize system
thr = FlexibleTemporalHierarchicalReconciliation(
    model_name='random_forest',
    n_bootstrap=500
)

# Load precipitation data
data = pd.read_csv('precipitation_data.csv')
series = data['precipitation'].set_index(data['date'])

# Create temporal hierarchy
hierarchy = thr.create_temporal_hierarchy(series)

# Generate forecasts
forecasts = thr.forecast_with_uncertainty(series, hierarchy)

# Reconcile forecasts
reconciled = thr.reconcile_forecasts(forecasts)

print("Forecast completed successfully!")
```

### Example 2: Model Comparison

```python
from pyPrecipTHR import FlexibleTemporalHierarchicalReconciliation

models = ['random_forest', 'ets', 'sarima']
results = {}

for model_name in models:
    thr = FlexibleTemporalHierarchicalReconciliation(
        model_name=model_name,
        n_bootstrap=100
    )
    
    # Generate forecasts
    forecasts = thr.forecast_with_uncertainty(data, hierarchy)
    reconciled = thr.reconcile_forecasts(forecasts)
    
    # Evaluate
    evaluation = thr.evaluate_forecasts(forecasts, reconciled)
    results[model_name] = evaluation

print("Model comparison completed!")
```

### Example 3: Custom Model Integration

```python
from pyPrecipTHR import BaseModel, FlexibleTemporalHierarchicalReconciliation

class MyCustomModel(BaseModel):
    def __init__(self, n_bootstrap=500):
        super().__init__(n_bootstrap)
    
    def forecast_with_uncertainty(self, series, forecast_horizon):
        # Your custom forecasting logic here
        return {
            'forecast': predictions,
            'lower': lower_bounds,
            'upper': upper_bounds
        }

# Register and use custom model
thr = FlexibleTemporalHierarchicalReconciliation()
thr.register_custom_model('my_custom', MyCustomModel)
thr.switch_model('my_custom')
```

### Example 4: Ensemble Forecasting

```python
from pyPrecipTHR import EnsembleModel, FlexibleTemporalHierarchicalReconciliation

# Create ensemble of models
ensemble_models = [
    RandomForestModel(n_bootstrap=100),
    ETSModel(n_bootstrap=100),
    SARIMAModel(n_bootstrap=100)
]

ensemble = EnsembleModel(models=ensemble_models)

# Use ensemble for forecasting
thr = FlexibleTemporalHierarchicalReconciliation(
    custom_model=ensemble
)
```

## 📚 API Documentation

### Core Classes

#### `FlexibleTemporalHierarchicalReconciliation`

Main class for temporal hierarchical reconciliation.

**Parameters:**
- `model_name` (str): Name of the forecasting model
- `model_params` (dict): Parameters for the model
- `n_bootstrap` (int): Number of bootstrap samples
- `reconciliation_method` (str): Reconciliation method ('mint' or 'ols')
- `forecast_horizon` (int): Forecast horizon in periods

**Methods:**
- `load_data(basin_name)`: Load precipitation data
- `create_temporal_hierarchy(data)`: Create temporal hierarchy
- `forecast_with_uncertainty(data, hierarchy)`: Generate forecasts
- `reconcile_forecasts(forecasts)`: Reconcile forecasts
- `evaluate_forecasts(forecasts, reconciled)`: Evaluate results

#### `ModelRegistry`

Registry for managing forecasting models.

**Methods:**
- `register_model(name, model_class)`: Register a new model
- `get_model(name, **kwargs)`: Get model instance
- `list_models()`: List available models

### Built-in Models

#### `RandomForestModel`

Random Forest model with robust uncertainty quantification.

#### `ETSModel`

Exponential Smoothing model for time series forecasting.

#### `SARIMAModel`

SARIMA model for statistical time series forecasting.

### Uncertainty Quantification

#### `BootstrapUncertainty`

Bootstrap-based uncertainty quantification.

#### `QuantileUncertainty`

Quantile-based uncertainty quantification.

### Reconciliation Methods

#### `MinTReconciliation`

Minimum Trace reconciliation method.

#### `OLSReconciliation`

Ordinary Least Squares reconciliation method.

## 🧪 Testing

Run the test suite:

```bash
# Install development dependencies
pip install -e .[dev]

# Run tests
pytest

# Run with coverage
pytest --cov=pyPrecipTHR
```

## 📖 Jupyter Notebooks

The project includes several Jupyter notebooks demonstrating different aspects:

- `FINAL_ETS.ipynb`: ETS model implementation
- `final_sarima.ipynb`: SARIMA model implementation
- `Copy_of_randomforest.ipynb`: Random Forest implementation

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.

### Development Setup

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Run the test suite
6. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- Built on top of scikit-learn, statsmodels, and other open-source libraries
- Inspired by research in temporal hierarchical reconciliation
- Developed for precipitation forecasting applications

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/yourusername/pyPrecipTHR/issues)
- **Documentation**: [Read the Docs](https://pyPrecipTHR.readthedocs.io/)
- **Email**: your.email@example.com

## 🔄 Version History

- **v1.0.0**: Initial release with core functionality
  - Flexible model architecture
  - Temporal hierarchical reconciliation
  - Uncertainty quantification
  - Multi-scale forecasting

---

**Made with ❤️ for the forecasting community**