Metadata-Version: 2.5
Name: pmmforecast
Version: 0.25.1
Summary: Bayesian forecasting with Pairwise Gaussian Markov Models (PMM vs HMM, 1D)
Project-URL: Homepage, https://github.com/SDerrode/pmmforecast
Project-URL: Documentation, https://sderrode.github.io/pmmforecast/
Project-URL: Repository, https://github.com/SDerrode/pmmforecast.git
Project-URL: Issues, https://github.com/SDerrode/pmmforecast/issues
Project-URL: Changelog, https://github.com/SDerrode/pmmforecast/blob/main/CHANGELOG.md
Project-URL: Paper, https://doi.org/10.1109/MCSI60294.2023.00009
Author-email: Stéphane Derrode <stephane.derrode@ec-lyon.fr>
Maintainer-email: Stéphane Derrode <stephane.derrode@ec-lyon.fr>
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Keywords: bayesian filtering,bayesian prediction,forecasting,gaussian models,hidden markov models,pairwise markov models,state-space models
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: matplotlib>=3.7
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: rich>=13.0
Requires-Dist: scipy>=1.10
Requires-Dist: tomli-w>=1.0
Requires-Dist: tomli>=2.0; python_version < '3.11'
Requires-Dist: tqdm>=4.65
Provides-Extra: all
Requires-Dist: hypothesis>=6.0; extra == 'all'
Requires-Dist: ipykernel>=6.0; extra == 'all'
Requires-Dist: mypy>=1.10; extra == 'all'
Requires-Dist: nbval>=0.10; extra == 'all'
Requires-Dist: pyqt6>=6.6; extra == 'all'
Requires-Dist: pytest-cov>=4.0; extra == 'all'
Requires-Dist: pytest>=7.0; extra == 'all'
Requires-Dist: ruff>=0.5; extra == 'all'
Requires-Dist: statsmodels>=0.14; extra == 'all'
Requires-Dist: sympy>=1.12; extra == 'all'
Requires-Dist: types-tqdm>=4.65; extra == 'all'
Provides-Extra: bench
Requires-Dist: statsmodels>=0.14; extra == 'bench'
Provides-Extra: dev
Requires-Dist: hypothesis>=6.0; extra == 'dev'
Requires-Dist: ipykernel>=6.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: nbval>=0.10; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: sympy>=1.12; extra == 'dev'
Requires-Dist: types-tqdm>=4.65; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Requires-Dist: mkdocs>=1.6; extra == 'docs'
Requires-Dist: mkdocstrings-python>=1.10; extra == 'docs'
Requires-Dist: mkdocstrings>=0.26; extra == 'docs'
Provides-Extra: gui
Requires-Dist: pyqt6>=6.6; extra == 'gui'
Description-Content-Type: text/markdown

# pmmforecast

[![PyPI version](https://img.shields.io/pypi/v/pmmforecast.svg?logo=pypi&logoColor=white&label=PyPI)](https://pypi.org/project/pmmforecast/)
[![Python versions](https://img.shields.io/pypi/pyversions/pmmforecast.svg?logo=python&logoColor=white)](https://pypi.org/project/pmmforecast/)
[![CI status](https://github.com/SDerrode/pmmforecast/actions/workflows/ci.yml/badge.svg)](https://github.com/SDerrode/pmmforecast/actions/workflows/ci.yml)
[![License: AGPL v3+](https://img.shields.io/badge/license-AGPL%20v3%2B-blue.svg)](https://github.com/SDerrode/pmmforecast/blob/main/LICENSE)
[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-261230.svg)](https://github.com/astral-sh/ruff)
[![Docs](https://img.shields.io/badge/docs-API%20reference-blue.svg)](https://sderrode.github.io/pmmforecast/)
[![Paper DOI](https://img.shields.io/badge/paper%20DOI-10.1109%2FMCSI60294.2023.00009-blue.svg)](https://doi.org/10.1109/MCSI60294.2023.00009)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24728232.svg)](https://doi.org/10.5281/zenodo.24728232)

Bayesian forecasting with **Pairwise Gaussian Markov Models (PMM)** — a strict
generalisation of the classical Hidden Markov Model that lets the hidden
state $X$ and the observation $Y$ co-evolve. Companion code for :

> Marc Escudier, Ikram Abdelkefi, Clément Fernandes, Wojciech Pieczynski.
> **Forecasting with Pairwise Gaussian Markov Models**.
> 8th IEEE Int. Conf. on Mathematics and Computers in Sciences and Industry
> (CMCSI 23), Oct. 2023, Athens, Greece.
> [DOI 10.1109/MCSI60294.2023.00009](https://doi.org/10.1109/MCSI60294.2023.00009)
> · [HAL hal-04450999](https://hal.science/hal-04450999v1)
> · [arXiv 2402.07532](https://arxiv.org/abs/2402.07532).

---

## Why pmmforecast ?

`pmmforecast` ships a **complete, end-to-end pipeline** for stationary 1-D
Pairwise Gaussian Markov Models with five free parameters $(a, b, c, d, e)$ :

- 🎲 **Simulation** of state-observation trajectories `(X_n, Y_n)` from any
  PMM (`PMMSimulator1D`).
- 🔧 **Bayesian filtering and forecasting** with closed-form recursions
  (`PMMFilter1D`, `PMMPredictor1D`), including **missing observations**
  (`NaN` in $Y$ : prediction without update) and multi-step forecasts with
  their uncertainty (`PMMFilter1D.filter_state`, `PMMFilter1D.forecast`).
- 📐 **Closed-form theoretical MSE** : the per-instant prediction MSE
  recursion of paper Eqs. (18)-(24) (`TheoreticalMSE`), and the excess MSE
  of the mismatched HMM filter in $O(n)$
  (`TheoreticalMSE.compute_instant_mse_diff_vs`).
- 🧮 **Three estimators** with multi-start and uncertainty quantification :
  fast moment-matching, joint-MLE on $(X, Y)$, and Y-only MLE via the Kalman
  likelihood, which accepts missing values (about 1 s for a complete
  20 000-sample series, about 10 s with 15 % gaps) (`pmmforecast.inference.estimation`).
- ✅ **Hypothesis testing** : likelihood-ratio test of HMM vs PMM (Wilks
  $\chi^2(3)$) with a parametric-bootstrap fallback for short series
  (`pmmforecast.inference.hypothesis_test`).
- 📊 **Goodness-of-fit diagnostics** : Ljung-Box, Jarque-Bera, ACF,
  QQ-plots — all from `pmmforecast.inference.diagnostics`.
- 📈 **Asymptotic theory** : closed-form filter-MSE asymptote and Lyapunov
  fixed-point of the prediction covariance, with full algebraic-boundary
  characterisation via sympy (`pmmforecast.analysis`).
- 📚 **13 didactic notebooks** taking you from "what is a PMM" to a real
  out-of-sample forecast on the AirPassengers dataset, with a benchmark
  vs `statsmodels` SARIMAX / UnobservedComponents.
- 🔬 **Reproducible** : every figure of the paper Table 1 is reproduced by a
  pinned-seed Monte-Carlo regression test (`pytest -m slow`).

---

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Tutorials](#tutorials)
- [Programs](#programs)
- [Reproducing the Paper](#reproducing-the-paper)
- [Configuration](#configuration)
- [Logging](#logging)
- [Tests](#tests)
- [Limitations](#limitations)
- [Citation](#citation)
- [License](#license)

---

## Installation

### From PyPI (recommended)

```bash
pip install pmmforecast
```

Optional extras :

| Extras    | What it adds                                                     |
| --------- | ---------------------------------------------------------------- |
| `[gui]`   | PyQt6, enabling the interactive `pmmforecast-gui` desktop window |
| `[bench]` | `statsmodels`, used by Tutorial 12 to benchmark vs SARIMAX       |
| `[dev]`   | pytest, ruff, mypy, hypothesis, nbval, ipykernel — everything    |
|           | needed to run the test suite and the notebooks                   |
| `[docs]`  | MkDocs, Material and mkdocstrings, to build the API reference    |
| `[all]`   | `dev`, `bench` and `gui` together                                |

```bash
pip install "pmmforecast[gui]"
pip install "pmmforecast[all]"
```

### From source

```bash
git clone https://github.com/SDerrode/pmmforecast.git
cd pmmforecast
pip install -e ".[all]"
```

### Requirements

- Python ≥ 3.10
- numpy, scipy, matplotlib, pandas, tqdm

---

## Quick Start

```python
from pmmforecast.models import ParamPMM, PMMSimulator1D
from pmmforecast.inference import PMMFilter1D, PMMPredictor1D

# 5-parameter PMM (a, b, c, d, e). HMM corresponds to c=a*b**2, d=e=a*b.
a, b = 0.9, -0.2
params = ParamPMM(a, b, a * b * b, a * b, a * b - 0.4)

# Simulate 100 samples of (X_n, Y_n).
simulator = PMMSimulator1D(params, n_samples=100)
trajectory = list(simulator.simulate_generator())

# Filter then forecast from index 50 onwards.
predictor = PMMPredictor1D(params, params, params, n_samples=100, start_predict_index=50)
predictor.set_seed(42)
mse_predict, mse_x, mse_y = predictor.run(exp_id=0)
print(f"Prediction MSE = {mse_predict:.3f}")
```

Or use the CLI entry points installed with the package:

```bash
pmmforecast-simulate --n-samples 1000000 --n-exp 10
pmmforecast-filter   --n-samples 80 --n-exp 500
pmmforecast-predict  --n-samples 80 --start-predict-index 40 --n-exp 100 --plot
pmmforecast-therror  --n-samples 80 --start-predict-index 40 --plot
pmmforecast-grid     --grid-samples 10 --n-samples 20 --start-predict-index 10
```

For an interactive Qt GUI (sliders for $(a,b,c,d,e)$, embedded matplotlib panel,
TOML round-trip):

```bash
pip install -e ".[gui]"
pmmforecast-gui
```

![pmmforecast-gui: parameter sliders, run controls, trajectory and MSE plots](https://raw.githubusercontent.com/SDerrode/pmmforecast/main/docs/images/gui.png)

---

## Tutorials

> Before diving in, the [Notation Glossary](https://github.com/SDerrode/pmmforecast/blob/main/docs/notation.md) maps the LaTeX
> symbols of the paper and the LaTeX companion report to the corresponding
> Python identifiers (which equation lives in which method, what
> `tab_gamma[i, n]` corresponds to, …).

| # | Notebook | Description |
|---|----------|-------------|
| 00 | [`tutorial_00_reproduce_paper.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_00_reproduce_paper.ipynb) | Reproduce Table 1 of the paper: with the second model $a=0.9, b=-0.2, c=ab^2, d=ab-0.2, e=ab-0.4$, $N=80$ samples, prediction starting at $n=40$, the empirical prediction MSE on 1 000 experiments lands within ±0.01 of the paper's 100 000-experiment headline values (HMM 0.817, PMM 0.575). The CLI command for the full 100 000 reproduction is included. |
| 01 | [`tutorial_01_pmm_vs_hmm.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_01_pmm_vs_hmm.ipynb) | End-to-end walkthrough: simulate a PMM, filter under PMM and HMM hypotheses, forecast, and overlay the closed-form theoretical MSE on the empirical estimate. |
| 02 | [`tutorial_02_filter_asymptote.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_02_filter_asymptote.ipynb) | Paper Section 5.1 — closed-form filter MSE asymptote: extract $(O, P, Q)$, solve the quadratic for $\ell_1, \ell_2$, and compare with the deterministic and Monte-Carlo recursions for both PMM and HMM. |
| 03 | [`tutorial_03_prediction_asymptote.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_03_prediction_asymptote.ipynb) | Paper Section 6 — prediction-covariance Lyapunov equation: build the $\Lambda$ matrix from the $\alpha_i$'s, solve $\Lambda\,\Sigma_\infty = \beta$ in closed form, and verify the deterministic recursion converges at rate $\rho(A)^{2k}$. |
| 04 | [`tutorial_04_grid_scan.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_04_grid_scan.ipynb) | Sweep a $3^5$ grid of $(a,b,c,d,e)$ in-memory, feed the results to `GridAnalysis`, and surface the structurally interesting cohorts (det $BB^\top = 0$, det $A = 0$, constant filter MSE, etc.). Mirrors what `pmmforecast-therror --grid-samples …` does on disk. |
| 05 | [`tutorial_05_real_data.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_05_real_data.ipynb) | Filter data that is *not* generated by a PMM — an AR(2) state with a delayed observation $Y_n = (1-\theta)X_n + \theta X_{n-1} + \eta_n$. Match the five-tuple to empirical covariances, run the closed-form filter on the empirical $Y$, and compare against the HMM-constrained filter and the marginal baseline. |
| 06 | [`tutorial_06_algebraic_boundaries.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_06_algebraic_boundaries.ipynb) | Algebraic boundaries of the PMM-valid region: numerical $b$-sweep showing where $BB^\top$ becomes singular (and the constructor raises `ParamPMMError`), then a sympy factorisation of $\det \Lambda$ into three clean linear conditions, including the volume-preserving surface $\det A = 1$. Replaces the legacy Annexe 2 / Section 5 sympy scripts. |
| 07 | [`tutorial_07_parameter_estimation.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_07_parameter_estimation.ipynb) | Recover the $(a,b,c,d,e)$ tuple from observed data using two estimators that ship in `pmmforecast.inference.estimation`: a fast moment-based estimator (matching empirical lag-0/lag-1 covariances to $\Gamma_{\mathrm{PMM}}$) and a maximum-likelihood estimator (`scipy.optimize.minimize` on the joint log-likelihood, *experimental*). Sanity-check on simulated PMM data, error-vs-sample-size scan, and a real-ish AR(2) example reusing Tutorial 05's dataset. |
| 08 | [`tutorial_08_hypothesis_test.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_08_hypothesis_test.ipynb) | Likelihood-ratio test of HMM ($H_0$: $c=ab^2$, $d=e=ab$) vs PMM ($H_1$: free), exposed as `pmmforecast.inference.hypothesis_test.likelihood_ratio_test_hmm_vs_pmm`. Verifies Wilks' theorem on simulated data (the empirical null distribution matches $\chi^2(3)$ within Monte-Carlo noise), demonstrates the parametric-bootstrap alternative for short series, and applies the test to the AR(2) dataset of Tutorial 05. |
| 09 | [`tutorial_09_y_only_estimation.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_09_y_only_estimation.ipynb) | **Y-only MLE** — recover $(a,b,c,d,e)$ from observations $Y$ alone (the realistic filtering scenario where $X$ is hidden), using the **Kalman likelihood** (prediction-error decomposition) implemented in `pmmforecast.inference.estimation.estimate_pmm_mle_y_only`. Shows that the tuple is only identifiable up to a 2-dimensional class (same $(c, \mathrm{tr}\,A, \det A)$, which includes the sign flip $(b,d,e) \mapsto -(b,d,e)$), quantifies the variance penalty vs the joint-MLE estimator (typically 2-5x wider error bars at $n=1000$), applies the method to the AR(2) dataset, and filters / forecasts through **missing observations** (10 % random gaps plus a 40-step outage) with `filter_state` and `forecast`. |
| 10 | [`tutorial_10_diagnostics.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_10_diagnostics.ipynb) | Post-fit diagnostics : Hessian-based confidence intervals on every estimated parameter (`compute_standard_errors` + `confidence_intervals`), and the goodness-of-fit suite from `pmmforecast.inference.diagnostics` (Ljung-Box on innovations whiteness, Jarque-Bera on normality, ACF / QQ / histogram plots). Demonstrates how the diagnostics pass on well-specified PMM data and reject on the AR(2) dataset. |
| 11 | [`tutorial_11_real_dataset.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_11_real_dataset.ipynb) | **Real-world data** — applies the full estimation → diagnostics → forecasting pipeline to the public-domain Box-Jenkins *AirPassengers* monthly series (1949-1960, 144 obs). Y-only MLE with multi-start (`n_restarts=8`) on log-detrended-deseasonalised residuals ; AIC/BIC comparison vs HMM-constrained fit ; out-of-sample MSE on the held-out last 24 months. |
| 12 | [`tutorial_12_external_benchmarks.ipynb`](https://github.com/SDerrode/pmmforecast/blob/main/notebooks/tutorial_12_external_benchmarks.ipynb) | **Comparison vs `statsmodels`** — positions the PMM filter against `SARIMAX` (ARMA(1,0)) and `UnobservedComponents` (local-level state-space) on the same AirPassengers test set. Optional dependency : install `pip install -e ".[bench]"` to enable. Cells gracefully skip when statsmodels is not available. |

---

## Programs

| CLI                       | Module                          | Purpose |
|---------------------------|---------------------------------|---------|
| `pmmforecast-simulate`    | `pmmforecast.run_simulator`             | Simulate samples from a 1D PMM and report empirical means. |
| `pmmforecast-filter`      | `pmmforecast.run_filter`                | Simulate and Bayesian-filter under PMM and HMM hypotheses; compare MSE. |
| `pmmforecast-predict`     | `pmmforecast.run_predictor`             | Filter until `start_predict_index`, then forecast; save trajectories and per-step MSE. |
| `pmmforecast-therror`     | `pmmforecast.run_theoretical_error`     | Closed-form MSE recursion (single model or grid scan); pickle the results. |
| `pmmforecast-grid`        | `pmmforecast.run_grid_analysis`         | Inspect grid-scan output (degenerate determinants, asymptotes, etc.). |
| `pmmforecast-gui`         | `pmmforecast.gui`                       | Interactive PyQt6 window — sliders for $(a,b,c,d,e)$, embedded matplotlib panel, TOML round-trip. Requires the `[gui]` extras. |

The underlying code is split into three focussed subpackages (since v0.18.0):

- `pmmforecast.models` — `ParamPMM`, `PMMSimulator1D`, `ReferenceModel` and the canonical-tuples registry.
- `pmmforecast.inference` — `PMMFilter1D`, `PMMPredictor1D`, the estimation API (`estimate_pmm_*`, `neg_log_likelihood_*`) and the LRT (`likelihood_ratio_test_hmm_vs_pmm`, `bootstrap_lrt_p_value`).
- `pmmforecast.analysis` — `TheoreticalMSE`, `GridAnalysis`, `FilterLimitQuadratic` and the closed-form recursions.

The legacy `pmmforecast.classes` namespace is preserved as a thin re-export layer for backward compatibility.

The underlying classes:

- `ParamPMM`, `ParamPMMGenerator`, `check_th_pmm_hmm`, `check_cov_matrix`
- `PMMSimulator1D` — 1D PMM sampler (with reproducible seeding).
- `PMMFilter1D` — Bayesian filter, exposes `var_filter_generator` and `filter_generator`.
- `PMMPredictor1D` — filter+forecast, exposes `predict_generator` and `var_predict_generator`.
- `TheoreticalMSE` — closed-form MSE recursion implementing eq. (18)–(24) of the paper.
- `GridAnalysis` — post-hoc inspection of the saved LZMA-pickled grid scans.

Plotting utilities are in `pmmforecast/utils/plot.py` (`PlotManager`).

---

## Configuration

Every CLI accepts a `--config session.toml` flag. The TOML file groups every
parameter that defines a reproducible run, and any flag passed on the command
line overrides the file. Sections may be omitted; their dataclass defaults
apply.

```toml
[model]
a = 0.5454545454545454
b = 0.2727272727272727
c = 0.09090909090909091
d = 0.9090909090909092
e = 0.9090909090909092

[simulation]
n_samples = 200
n_exp = 1
seed = 0xdeadbeef          # optional

[predictor]
start_predict_index = 80

[theoretical]
grid_samples = 0
predict_threshold = 0.01

[output]
repobase = "./data"
plot = false
with_2sigma = false
log_file = "logs/run.log"  # optional
```

Programmatic API:

```python
from pmmforecast.utils import SessionConfig, load_session, save_session

session = load_session("session.toml")
print(session.model.as_tuple())
session.simulation.n_samples = 1000
save_session(session, "session_modified.toml")
```

Validation is strict: unknown sections, unknown keys, malformed TOML, or bad
override paths raise `pmmforecast.utils.ConfigError`.

---

## Logging

The package exposes a `pmmforecast` logger with a child per module
(`pmmforecast.classes.pmm_filter`, `pmmforecast.run_predictor`, …). Library
use stays silent thanks to a `NullHandler` attached at import time; CLI use
opts in via `setup_logging`.

Verbose mapping:

| `--verbose` | Level     | What you see                                                              |
|-------------|-----------|---------------------------------------------------------------------------|
| `0`         | `WARNING` | only invalid tuples, slow-mixing models, overshoot of the marginal variance |
| `1` (def)   | `INFO`    | run summary (model + size + final MSEs) and the warnings above            |
| `2`         | `DEBUG`   | + per-experiment seed and final MSE                                       |

Add `--log-file logs/run.log` to also archive every record at `DEBUG` level.

Programmatic:

```python
from pmmforecast.utils import setup_logging, get_logger
setup_logging(verbose=2)
log = get_logger(__name__)
log.info("ready")
```

---

## Reproducing the Paper

The single-model figures of the paper are produced by combining
`pmmforecast-predict` and `pmmforecast-therror`:

```bash
# Numerical mean MSE vs. theoretical MSE for one model
pmmforecast-predict --n-samples 80 --start-predict-index 40 --n-exp 100000 --plot
pmmforecast-therror --n-samples 80 --start-predict-index 40 --plot --predict-threshold 0.01
```

The 5-D parameter sweep (a, b, c, d, e) ∈ grid<sup>5</sup>:

```bash
pmmforecast-therror --n-samples 60 --start-predict-index 61 --grid-samples 10 --predict-threshold 0.01
pmmforecast-grid    --grid-samples 10 --n-samples 60 --start-predict-index 61
```

`pmmforecast-grid` accepts `--filter <name>` (repeatable) to restrict the
report to one or more of the eight `GridAnalysis` filters
(`det_bbt_zero`, `det_gamma_zero`, `det_a_zero`, `det_lambda_zero`,
`l1_or_l2_zero`, `constant_filtering_mse`, `zero_filtering_mse`,
`non_one_prediction_mse`). The default is to run all eight.

Outputs: figures under `<repobase>/Plot/`, intermediate numpy bundles
under `<repobase>/Numpy/`, LZMA-compressed grid results under
`<repobase>/lzma/` (default `<repobase>` is `./data`).

> A LaTeX companion report with detailed derivations of the paper's equations
> is provided in [`docs/PMCParametersAnalysis/`](https://github.com/SDerrode/pmmforecast/tree/main/docs/PMCParametersAnalysis/).

---

## Tests

```bash
pip install -e ".[dev]"
pytest pmmforecast/tests/ -v
```

The 332 tests cover the `ParamPMM` validity rules, the simulator's seed
reproducibility, the filter (checked against exact Gaussian conditioning,
including with missing observations), the predictor, the three estimators,
the HMM-vs-PMM test and the diagnostics, the `TheoreticalMSE` recursions
(matched against a Monte-Carlo estimator and against the paper-faithful
equations), property-based invariants (Hypothesis), a subprocess smoke test on
every CLI entry point, and the reproduction of the paper's Table 1 (marked
`slow`).

CI on every push and PR runs ruff lint + **mypy type check** + the pytest
matrix on Python 3.10 / 3.11 / 3.12 (with a **`pytest --nbval-lax
--current-env notebooks/`** step that executes the 74 cells of the 13
tutorials end-to-end) + a strict build of the API documentation site + a
`python -m build` wheel/sdist build (see
[`.github/workflows/ci.yml`](https://github.com/SDerrode/pmmforecast/blob/main/.github/workflows/ci.yml)).
Type checking uses the *balanced* mypy preset (annotated signatures
everywhere, ``Any`` allowed on external scipy/matplotlib/PyQt6 surfaces).

---

## Limitations

- **Missing values are supported for `Y` only.** Mark them with `NaN` : the
  filter (`PMMFilter1D.filter_observations`, `filter_state`, `forecast`) and
  the Y-only estimator (`estimate_pmm_mle_y_only`) predict through the gaps.
  The joint $(X, Y)$ estimators, the HMM-vs-PMM test and the diagnostics
  need complete data and raise a `ValueError` on `NaN`.
- **The Y-only fit is not interpretable parameter by parameter.** The law of
  `Y` depends on $(a, b, c, d, e)$ only through $(c, \mathrm{tr}\,A, \det A)$,
  so a 2-dimensional set of tuples gives the same likelihood. Only the
  resulting forecasts of `Y` are meaningful ; see the docstring of
  `estimate_pmm_mle_y_only` and Tutorial 09.
- **`TheoreticalMSE` outputs and cost.** `compute_th_mse_for_pmm()[0]` is the
  MSE of `X` ; the MSE of the `Y` forecast is `compute_th_mse_for_pmm()[1][:, 1, 1]`.
  This method and `compute_instant_mse_diff_vs` (excess MSE of the HMM) run in
  $O(n)$. Only the paper-faithful pair `compute_gamma` + `compute_instant_mse_diff`
  (equations (18)–(24)) needs $O(n^2)$ memory, about 3.7 GB for $n = 21\,600$.

---

## Citation

```bibtex
@inproceedings{escudier2023forecasting,
  author    = {Escudier, Marc and Abdelkefi, Ikram and Fernandes, Cl\'{e}ment
               and Pieczynski, Wojciech},
  title     = {Forecasting with Pairwise Gaussian Markov Models},
  booktitle = {2023 8th International Conference on Mathematics and Computers
               in Sciences and Industry (CMCSI)},
  publisher = {IEEE},
  year      = {2023},
  doi       = {10.1109/MCSI60294.2023.00009},
  url       = {https://hal.science/hal-04450999v1},
}
```

A `CITATION.cff` is also provided at the repo root for GitHub's "Cite this
repository" widget.

---

## License

Distributed under the **GNU Affero General Public License v3.0 or later**
(AGPL-3.0-or-later) — see [`LICENSE`](https://github.com/SDerrode/pmmforecast/blob/main/LICENSE).
