Metadata-Version: 2.5
Name: markov-ts
Version: 0.4.0
Summary: AI agent (MCP server) for hidden, pairwise and triplet Markov chains on signals and time series: the Markov libraries as tools for assistants such as Claude.
Project-URL: Homepage, https://github.com/SDerrode/markov-ts
Project-URL: Repository, https://github.com/SDerrode/markov-ts
Project-URL: Issues, https://github.com/SDerrode/markov-ts/issues
Project-URL: Changelog, https://github.com/SDerrode/markov-ts/blob/main/CHANGELOG.md
Author-email: Derrode Stéphane <stephane.derrode@ec-lyon.fr>
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Keywords: ai agent,claude,forecasting,hidden markov model,kalman filter,llm,mcp,model context protocol,pairwise markov chain,signal processing,time series,triplet markov chain
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: French
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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 :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.11
Requires-Dist: matplotlib>=3.7
Requires-Dist: mcp<3,>=2.3
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: pydantic>=2
Requires-Dist: scipy>=1.10
Provides-Extra: all
Requires-Dist: awesomepkf>=2.18; extra == 'all'
Requires-Dist: awesomepmc>=1.7.0; extra == 'all'
Requires-Dist: awesometmc>=3.5; extra == 'all'
Requires-Dist: mpmath>=1.3; extra == 'all'
Requires-Dist: pmmforecast>=0.25; extra == 'all'
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: pkf
Requires-Dist: awesomepkf>=2.18; extra == 'pkf'
Requires-Dist: mpmath>=1.3; extra == 'pkf'
Provides-Extra: pmc
Requires-Dist: awesomepmc>=1.7.0; extra == 'pmc'
Provides-Extra: pmm
Requires-Dist: pmmforecast>=0.25; extra == 'pmm'
Provides-Extra: tmc
Requires-Dist: awesometmc>=3.5; extra == 'tmc'
Description-Content-Type: text/markdown

# markov-ts

<!-- mcp-name: io.github.SDerrode/markov-ts -->

[![CI](https://github.com/SDerrode/markov-ts/actions/workflows/ci.yml/badge.svg)](https://github.com/SDerrode/markov-ts/actions/workflows/ci.yml)
[![License: AGPL v3+](https://img.shields.io/badge/license-AGPL%20v3%2B-blue.svg)](LICENSE)
[![MCP](https://img.shields.io/badge/MCP-server-6f42c1.svg)](https://modelcontextprotocol.io)

**An AI agent for hidden, pairwise and triplet Markov chains on signals and time series.**

`markov-ts` is a [Model Context Protocol](https://modelcontextprotocol.io) server. It exposes the reference
implementations of the *Markov* library family (Pieczynski, Derrode and co-authors) as tools that an AI
assistant such as Claude can call. You ask in plain language, for example *"Is a classical HMM enough for my
series, or do I need a pairwise chain?"*. The agent then runs the published algorithms on your data and
answers with numbers it **computed**, never guessed, together with the model assumptions and the paper to
cite.

> The tools, results and agent instructions are written in **French**. The agent answers in the user's language.

---

## Why an agent?

The Markov libraries are mature research code: on PyPI, tested, documented, each the companion of a paper.
Using them still takes time: choosing the right model, the right estimator, and checking the hypotheses. The agent
connects a question to the right algorithm and follows a few rules:

- **No mental arithmetic.** Every number comes from a library call.
- **Assumptions are stated** (Gaussianity, stationarity, identifiability…).
- **Sources are cited** (DOI, BibTeX).
- **Out of scope? It says so** and points to the right library.
- **No financial or medical advice.** It provides a statistical analysis only.

## Libraries (backends)

Each library is an optional *backend*. The server activates only the ones installed in its environment.

| Library | Model | Tools | Install |
|---|---|---|---|
| [awesomepkf](https://pypi.org/project/awesomepkf/) | Pairwise Kalman filters (PKF, EPKF, UPKF, PPF), linear and nonlinear smoothers, back-action test | 9 `pkf_*` | `markov-ts[pkf]` |
| [awesomepmc](https://pypi.org/project/awesomepmc/) | Copula-based pairwise / hidden Markov chains, discrete states | 6 `pmc_*` | `markov-ts[pmc]` |
| [awesometmc](https://pypi.org/project/awesometmc/) | Triplet Markov chains: exact fast filtering in switching systems | 6 `tmc_*` | `markov-ts[tmc]` |
| [pmmforecast](https://pypi.org/project/pmmforecast/) | Gaussian pairwise Markov model, 1-D (PMM) | 11 `pmm_*` | `markov-ts[pmm]` |

Run `markov-ts --status` to see which backends are active.

### awesomepkf — pairwise Kalman filtering

| Tool | What it does |
|---|---|
| `pkf_list_models` | Linear and nonlinear pairwise models, filters, sigma-point sets |
| `pkf_simulate` | Simulate `(X, Y)` from a library model or a custom linear model `{A, Q, dim_x, dim_y}` |
| `pkf_compare_filters` | EPKF / UPKF / PPF (/ UKF / PF) on simulated data, averaged over `n_seeds` simulations (default 5): MSE and its spread, wins per seed, NEES, run time; numerical failures reported |
| `pkf_smooth` | The six linear smoothers (RTS, BF, MBF, MF, DWY, VAR): smoothing gain and agreement between them |
| `pkf_smooth_nonlinear` | Nonlinear smoothers EPKS, UPKS, particle smoother PPS (and UKS on non-pairwise models), over `n_seeds` simulations: filtering vs smoothing MSE, gain, time; a smoother that degrades the estimate is flagged |
| `pkf_reproduce_tsp` | Reproduces the simulation section of the paper submitted to IEEE TSP: the illustration model (Tables III and V, then the MSE over 30 seeds), the multiplicative-noise experiment (Table IV, Fig. 2) and the back-action experiment against a misspecified Markov EKF (Fig. 3); one experiment per call, ≈ 30–50 s |
| `pkf_reproduce_spl` | Reproduces the experiment of the letter submitted to IEEE SPL: the six linear smoothers against an exact 60-digit reference on 80 random pairwise models, one stress regime per call (broad prior, vanishing state noise, correlated noise, poles near the unit circle), on the pairwise models or on the textbook models `y = Hx + v` (`famille="classique"`): aborts, indefinite covariances, covariance and mean errors, figure (≈ 30 s per parameter value) |
| `pkf_backaction_test` | Likelihood-ratio test of measurement back-action (`A_xy = 0`), partial EM |
| `pkf_filter` | Filter a real 1-D observation series |

### awesomepmc — copula-based pairwise Markov chains

| Tool | What it does |
|---|---|
| `pmc_list_models`, `pmc_get_model` | Bundled TOML models (HMC-IN … general PMC with copulas) |
| `pmc_simulate` | Simulate classes and observations |
| `pmc_classify` | Bayesian MPM classification, exact handling of missing values, error rate if labels are known |
| `pmc_estimate` | Unsupervised ICE / SEM with automatic copula (and margin) selection; returns the fitted TOML |
| `pmc_forecast` | h-step forecasts and future class probabilities |

### awesometmc — triplet Markov chains / switching systems

| Tool | What it does |
|---|---|
| `tmc_list_models` | Paper models M1–M3 and library presets |
| `tmc_describe_model` | AB constraint (exact fast filter available?), exactness domains of IMM and GPB2 |
| `tmc_simulate` | Simulate regimes, states and observations |
| `tmc_compare_filters` | Exact filter vs GPB2, IMM, RBPF, single Kalman, oracle, over `n_seeds` simulations: MSE, regime error, time, maximal gap to the exact filter |
| `tmc_filter` | Filter real observations (exact filter when the model allows it) |
| `tmc_reproduce_tac` | Reproduces Sections V-A to V-C (Fig. 4) of the paper submitted to IEEE TAC: exact errors of the CGOMSM1 and CGOMSM2 approximations along the two families, 100Δ and its decomposition (≈ 15 s, no simulation) |

### pmmforecast — 1-D Gaussian pairwise Markov model

| Tool | What it does |
|---|---|
| `pmm_reference_models` | Canonical `(a, b, c, d, e)` models of the library |
| `pmm_check_model` | Validity, transition matrix, spectral radius, HMM projection |
| `pmm_simulate` | Simulate `(X, Y)` → CSV |
| `pmm_normality_check` | Normality and autocorrelation of a single series |
| `pmm_fit` | Estimation: moments, joint MLE with standard errors, Y-only Kalman likelihood |
| `pmm_lrt_hmm_vs_pmm` | Likelihood-ratio test HMM vs PMM (χ²(3), optional bootstrap), AIC/BIC |
| `pmm_diagnostics` | Ljung-Box and Jarque-Bera tests on whitened innovations |
| `pmm_filter` | `E[X|Y]`, `Var[X|Y]`, prediction of missing values |
| `pmm_forecast` | h-step forecasts with prediction intervals |
| `pmm_theoretical_mse` | Exact closed-form MSE, excess MSE of a mismatched HMM filter |
| `pmm_reproduce_table1` | Reproduces Table 1 of the CMCSI 2023 paper |

Every backend also exposes `markov://<library>/readme` and `markov://<library>/citation` **resources**. The
server exposes `markov://ecosysteme` and guided **prompts**: pmmforecast `choisir_modele`, `reproduire_article`;
awesomePKF `pkf_choisir_filtre`, `pkf_reproduire_tsp`, `pkf_reproduire_spl`; awesomePMC `pmc_classer_serie`;
awesomeTMC `tmc_choisir_filtre`, `tmc_reproduire_tac`.

### Figures

Simulation, filtering, smoothing, forecasting, classification, estimation and filter-comparison tools also
draw a PNG and return its path in a `figure` field, with a caption in `figure_legende`. The agent shows the
figure in its answer. `MARKOV_TS_FIGURES` controls them:

| Value | Effect |
|---|---|
| `fichier` (default) | PNG file only |
| `image` | the PNG is also attached to the tool result, so the agent sees it and the client can display it (about a thousand tokens per figure) |
| `non` | no figures |

### Choosing the active libraries

By default every installed library is active. `MARKOV_TS_BACKENDS` restricts the list, for instance to keep
a client that loads every tool description at each turn light (the 35 tools weigh about 11 000 tokens,
`pmm_*` alone about 4 000):

| Value | Effect |
|---|---|
| unset or empty | every installed library |
| `pmm` | pmmforecast only |
| `pkf,tmc` | awesomePKF and awesomeTMC (extras `pmm`, `pkf`, `pmc`, `tmc` or library names, separated by commas or spaces) |

An excluded library is not imported and declares no tools; `markov://ecosysteme` lists it as disabled, so the
agent can still point to it. `markov-ts --status` shows the result. Names it does not know are reported on
stderr and ignored.

### Your own research documents (optional, local)

The agent can also read your **unpublished manuscripts and reports** to ground its explanations in your own
text: `doc_list`, `doc_search` and `doc_read` (one section at a time, equations numbered as in the document,
publication status always returned). The documents never enter the repository or the package:

```bash
cp corpus_sources.example.toml corpus_sources.toml   # list your LaTeX documents (ignored by git)
python -m markov_ts.documents.build                  # LaTeX -> Markdown sections in corpus/ (needs pandoc)
markov-ts --status                                   # "documents  active"
```

Author-to-author notes (`remarque*` boxes, `\decide{}`, `\todo{}`), comments and author e-mails are removed
during the conversion. Without a corpus, the `doc_*` tools are not registered.

---

## Installation

```bash
pip install "markov-ts[all]"     # server + pmmforecast, awesomepkf, awesomepmc, awesometmc
pip install "markov-ts[pmc]"     # or only the libraries you need
markov-ts --status
```


## Use it with Claude

**Claude Code**

```bash
claude mcp add markov-ts -- markov-ts
```

or commit a project-level `.mcp.json` (see [`examples/mcp.json`](examples/mcp.json)).

Claude Code is a coding agent: asked to *reproduce* a paper, it may first look at the files of the current
folder, then the web, before the markov-ts tools. Put [`examples/CLAUDE.md`](examples/CLAUDE.md) (four lines)
in the folder you work from, or add its content to your own `CLAUDE.md`: it sends these questions to
markov-ts. In the evaluation bench it took the reproduction questions from 4/9 to 9/9 successes.

**Claude Desktop**: add the server to `claude_desktop_config.json` (see
[`examples/claude_desktop_config.json`](examples/claude_desktop_config.json)), then restart Claude Desktop.

**Any MCP client**: `markov-ts` speaks stdio. `markov-ts --http 8765` serves Streamable HTTP on `127.0.0.1`.

Generated files (CSV tables and PNG figures) go to `$MARKOV_TS_OUTPUT` (default: `./markov_ts_outputs`).

### Things to ask

- *Reproduce Table 1 of the CMCSI 2023 paper and explain the gap to the published values.*
- *Simulate 2,000 points of the paper's model, then tell me whether an HMM would be enough.*
- *Here is a series with gaps: `data.csv`. Forecast the next 12 points with 95% intervals.*
- *What should I cite for pairwise Markov chains? Give me the BibTeX.*
- *Are IMM and GPB2 exact on model M1? Show me their gap to the exact filter.*
- *Reproduce Section V of the CGOMSM2 paper and tell me whether you find the manuscript's values.*
- *Segment this series into 2 classes without labels, and tell me which copulas were selected.*
- *Is there measurement back-action in this pairwise linear model?*

---

## Development

```bash
git clone https://github.com/SDerrode/markov-ts.git
cd markov-ts
uv venv --python 3.14 && uv pip install -e ".[dev,all]"
uv pip install -e ../pmmforecast        # optional: work against local pmmforecast sources instead of PyPI
pytest                                   # fast tests; backend tests are skipped if the library is absent
pytest -m slow                           # Monte-Carlo reproduction of the paper (~12 s)
ruff check src tests
```

Backend tests are numbered after the **evaluation questions** (Q1, Q2, Q8, …) listed in
[`evals/questions.toml`](evals/questions.toml). Each question has a reference answer taken from a published
result. Adding a backend means adding a module in `src/markov_ts/backends/`. See
[CONTRIBUTING.md](CONTRIBUTING.md).

### Evaluating the agent

Unit tests check the tools; [`evals/`](evals/) checks the **agent**. It asks Claude the questions of
`evals/questions.toml` (model choice, forecasting, exactness, bibliography, and traps: financial or medical
advice, invented papers, impossible formulas), with only the markov-ts server connected, then grades each
transcript with explicit rules: tools called, numbers within tolerance, required mentions, forbidden claims,
figure shown.

```bash
python evals/run_evals.py                 # every question (uses your Claude account: about $4 for the set)
python evals/run_evals.py --only Q25 Q14  # a few questions
python evals/grade.py evals/results/<run> # re-grade without asking again
python evals/run_evals.py --claude-md examples/CLAUDE.md   # with the recommended CLAUDE.md in each work folder
```

Each run writes `rapport.md` (verdicts), `reponses.md` (full answers, to be read: the rules do not judge the
quality of an explanation) and `resultats.json`. See [`evals/README.md`](evals/README.md).

## Citation

If this agent helps your research, please cite the **papers** of the libraries you used (each backend exposes
a `citation` resource) and this software (see [CITATION.cff](CITATION.cff)).

The pairwise Markov chain model was introduced in: W. Pieczynski, *Pairwise Markov chains*, IEEE TPAMI 25(5),
2003, [doi:10.1109/TPAMI.2003.1195998](https://doi.org/10.1109/TPAMI.2003.1195998).

## License

[AGPL-3.0-or-later](LICENSE). The four libraries it drives, pmmforecast, awesomepkf, awesomepmc (since 1.7.0) and
awesometmc, are under the AGPL too. If you run a modified version of
this server as a network service, you must offer its source code to its users.
