Skip to main content

pmmforecast

PyPI version Python versions CI status License: AGPL v3+ Code style: ruff Docs Paper DOI DOI

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 · HAL hal-04450999 · arXiv 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

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
pip install "pmmforecast[gui]"
pip install "pmmforecast[all]"

From source

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

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:

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):

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

pmmforecast-gui: parameter sliders, run controls, trajectory and MSE plots


Tutorials

Before diving in, the Notation Glossary 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 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 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 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 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 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 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 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 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 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 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 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 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 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.

[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:

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:

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:

# 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) ∈ grid5:

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/.


Tests

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). 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

@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.

Metadata

Release files for pmmforecast 0.25.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pmmforecast 0.25.1
File Size Uploaded Provenance Actions
pmmforecast-0.25.1.tar.gz 194.2 kB With provenance Details for pmmforecast-0.25.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pmmforecast 0.25.1
File Interpreter ABI Platform Actions
pmmforecast-0.25.1-py3-none-any.whl Python 3 none any Details for pmmforecast-0.25.1-py3-none-any.whl

Total release size: 299.1 kB

Release files / pmmforecast-0.25.1.tar.gz

Download URL pmmforecast-0.25.1.tar.gz
Size 194.2 kB
Tags Source
SHA-256 checksum
How to use checksums
df286be6e69625aca3bb22d68301ff2afed80f96ea82fd3971a0c86c4c61be7a
BLAKE2b-256 checksum
How to use checksums
fa21190c3877c62b1ca7259d91bda10af223cfec526f6c765c28412782cc8ea9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Release files / pmmforecast-0.25.1-py3-none-any.whl

Download URL pmmforecast-0.25.1-py3-none-any.whl
Size 104.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
558012b97adc4ea5c86e09ab146411976ff0603bc492c504cf2274605c9dc379
BLAKE2b-256 checksum
How to use checksums
fe10c63641f31e73804c6ff0ffc9b4598392c8023f8be7969306cbca6b272785
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Security for pmmforecast 0.25.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pmmforecast-0.25.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.25.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page