"""Deployment and life-cycle management of discovered equations (MLOps).
Equations are small, transparent and portable, which makes them well suited to
industrial deployment -- but like any data-driven model they are valid only on
the data they were fitted to. This module supports the life cycle:
* :func:`fingerprint` -- a hash of the training data, stored with the model;
* :class:`ModelRegistry` -- a file-based registry of versioned equations with
metrics, data fingerprints, tags and stages (``staging``, ``production``,
``archived``), and structural comparison of versions;
* :class:`ModelCard` -- documentation of a model in the spirit of model cards
(Mitchell et al., 2019): intended use, data, equation, metrics, validity range,
constraints, limitations; Markdown and HTML;
* :class:`RunTracker` -- run logging to JSON lines, with an optional MLflow
adapter (MLflow is imported only if installed);
* :class:`DriftMonitor` -- monitoring of new data: population stability index and
Kolmogorov--Smirnov tests per variable, the share of samples outside the
training box (where an equation extrapolates), residual drift by the
Page--Hinkley test (Page, 1954), and a recommendation (ok / warning / retrain);
* :func:`environment_info` -- package versions for reproducibility.
"""
from __future__ import annotations
import datetime as _dt
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
import pandas as pd
from .equation import Equation
__all__ = ["fingerprint", "environment_info", "ModelRegistry", "ModelCard", "RunTracker", "DriftMonitor", "population_stability_index", "psi_critical_value"]
[docs]
def fingerprint(X, y=None) -> str:
"""SHA-256 fingerprint (first 16 hex digits) of the data."""
h = hashlib.sha256()
h.update(np.ascontiguousarray(np.asarray(X, float)).tobytes())
if y is not None:
h.update(np.ascontiguousarray(np.asarray(y, float)).tobytes())
return h.hexdigest()[:16]
[docs]
def environment_info() -> dict:
"""Versions of Python, eqdisco and its main dependencies."""
import scipy
import sklearn
import sympy
from . import __version__
return {
"python": platform.python_version(),
"platform": platform.platform(),
"eqdisco": __version__,
"numpy": np.__version__,
"scipy": scipy.__version__,
"sympy": sympy.__version__,
"scikit-learn": sklearn.__version__,
"pandas": pd.__version__,
}
def _now():
return _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
[docs]
class ModelRegistry:
"""File-based registry of versioned equations.
Layout: ``<root>/<name>/v<k>.json`` (the equation and its record) and
``<root>/<name>/index.json``.
Examples
--------
>>> import tempfile, numpy as np
>>> from eqdisco import Equation
>>> from eqdisco.mlops import ModelRegistry
>>> reg = ModelRegistry(tempfile.mkdtemp())
>>> eq = Equation.from_string("2*x0 + 1")
>>> reg.register("demo", eq, metrics={"r2": 0.99})
1
>>> reg.promote("demo", 1, "production")
>>> print(reg.load("demo", stage="production"))
2 * x0 + 1
"""
def __init__(self, root):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
def _index(self, name):
p = self.root / name / "index.json"
if p.exists():
return json.loads(p.read_text(encoding="utf-8"))
return {"name": name, "versions": []}
def _save_index(self, name, idx):
(self.root / name).mkdir(parents=True, exist_ok=True)
(self.root / name / "index.json").write_text(json.dumps(idx, indent=2), encoding="utf-8")
[docs]
def register(
self,
name: str,
equation: Equation,
metrics: dict | None = None,
X=None,
y=None,
tags: dict | None = None,
description: str = "",
card: ModelCard | None = None,
) -> int:
"""Store a new version; returns its number."""
idx = self._index(name)
v = len(idx["versions"]) + 1
rec = {
"version": v,
"created": _now(),
"stage": "none",
"equation": equation.to_dict(),
"metrics": metrics or dict(equation.metrics),
"data_fingerprint": fingerprint(X, y) if X is not None else None,
"domain": {"lower": np.min(X, 0).tolist(), "upper": np.max(X, 0).tolist()} if X is not None else None,
"tags": tags or {},
"description": description,
"environment": environment_info(),
}
if card is not None:
rec["card"] = card.to_dict()
(self.root / name).mkdir(parents=True, exist_ok=True)
(self.root / name / f"v{v}.json").write_text(json.dumps(rec, indent=2, default=float), encoding="utf-8")
idx["versions"].append({"version": v, "created": rec["created"], "stage": "none", "equation": str(equation), "metrics": rec["metrics"]})
self._save_index(name, idx)
return v
[docs]
def record(self, name: str, version: int | str = "latest") -> dict:
"""The stored record of a version (``"latest"`` or a number)."""
idx = self._index(name)
if not idx["versions"]:
raise KeyError(f"no model {name!r}")
v = idx["versions"][-1]["version"] if version == "latest" else int(version)
return json.loads((self.root / name / f"v{v}.json").read_text(encoding="utf-8"))
[docs]
def load(self, name: str, version: int | str = "latest", stage: str | None = None) -> Equation:
"""Load a version, or the newest version in ``stage``."""
if stage is not None:
idx = self._index(name)
cands = [r["version"] for r in idx["versions"] if r["stage"] == stage]
if not cands:
raise KeyError(f"no version of {name!r} in stage {stage!r}")
version = max(cands)
return Equation.from_dict(self.record(name, version)["equation"])
[docs]
def list(self, name: str | None = None) -> pd.DataFrame:
"""Table of the versions of one model (or of all models)."""
names = [name] if name else sorted(p.name for p in self.root.iterdir() if (p / "index.json").exists())
rows = []
for n in names:
for r in self._index(n)["versions"]:
rows.append({"name": n, **{k: v for k, v in r.items() if k != "metrics"}, **{f"metric_{k}": v for k, v in (r.get("metrics") or {}).items()}})
return pd.DataFrame(rows)
[docs]
def compare(self, name: str, v1: int, v2: int) -> dict:
"""Structural and parametric comparison of two versions."""
from .analysis.building_blocks import _blocks
a, b = self.load(name, v1), self.load(name, v2)
ba, bb = _blocks(a.expr, 2, 9), _blocks(b.expr, 2, 9)
return {
"equation_1": str(a),
"equation_2": str(b),
"same_structure": a.expr.key() == b.expr.key(),
"variables_added": sorted(set(b.variables) - set(a.variables)),
"variables_removed": sorted(set(a.variables) - set(b.variables)),
"blocks_shared": len(ba & bb),
"blocks_new": sorted(bb - ba),
"size_change": b.complexity - a.complexity,
}
[docs]
class ModelCard:
"""Documentation of a discovered equation.
Parameters
----------
equation : Equation
name : str
intended_use, limitations : str, optional
X, y : array-like, optional
Training data: their range becomes the stated validity domain.
metrics : dict, optional
Default: the metrics stored in the equation.
validation : dict, optional
Validation results (e.g. the summary of
:func:`~eqdisco.analysis.validation.cross_validate_search`).
constraints, units : optional
Prior knowledge used or checked.
"""
def __init__(
self,
equation: Equation,
name: str = "model",
intended_use: str = "",
limitations: str = "",
X=None,
y=None,
metrics: dict | None = None,
validation: dict | None = None,
constraints=None,
units: dict | None = None,
method: str | None = None,
authors: str = "",
):
self.equation = equation
self.name = name
self.intended_use = intended_use
self.limitations = limitations
self.metrics = metrics if metrics is not None else dict(equation.metrics)
self.validation = validation or {}
self.constraints = constraints or []
self.units = units or {}
self.method = method or equation.meta.get("method", "")
self.authors = authors
self.created = _now()
if X is not None:
X = np.asarray(X, float)
self.domain = {n: (float(X[:, j].min()), float(X[:, j].max())) for j, n in enumerate(equation.feature_names)}
self.n_samples = len(X)
self.fingerprint = fingerprint(X, y)
else:
self.domain, self.n_samples, self.fingerprint = {}, None, None
def to_dict(self) -> dict:
return {
"name": self.name,
"created": self.created,
"authors": self.authors,
"method": self.method,
"equation": str(self.equation),
"latex": self.equation.latex(),
"variables": self.equation.variables,
"complexity": self.equation.complexity,
"n_params": self.equation.n_params,
"metrics": self.metrics,
"validation": self.validation,
"domain": self.domain,
"n_samples": self.n_samples,
"data_fingerprint": self.fingerprint,
"constraints": [c.label() if hasattr(c, "label") else str(c) for c in self.constraints],
"units": self.units,
"intended_use": self.intended_use,
"limitations": self.limitations,
}
def to_markdown(self) -> str:
d = self.to_dict()
lines = [f"# Model card: {d['name']}", "", f"*Created {d['created']}*" + (f" by {d['authors']}" if d["authors"] else ""), ""]
lines += [
"## Model",
"",
f"$$y = {d['latex']}$$",
"",
f"- Method: {d['method']}",
f"- Variables: {', '.join(d['variables'])}",
f"- Complexity: {d['complexity']} nodes, {d['n_params']} parameters",
"",
]
if d["intended_use"]:
lines += ["## Intended use", "", d["intended_use"], ""]
lines += ["## Performance", ""]
lines += [f"| {k} | {v:.6g} |" if isinstance(v, (int, float)) else f"| {k} | {v} |" for k, v in d["metrics"].items()]
if d["metrics"]:
lines.insert(len(lines) - len(d["metrics"]), "| metric | value |\n|---|---|")
lines.append("")
if d["validation"]:
lines += ["## Validation", ""] + [f"- {k}: {v}" for k, v in d["validation"].items()] + [""]
if d["domain"]:
lines += ["## Validity domain (training data range)", "", "| variable | min | max |", "|---|---|---|"]
lines += [f"| {k} | {lo:.6g} | {hi:.6g} |" for k, (lo, hi) in d["domain"].items()]
lines += ["", f"Training samples: {d['n_samples']}; data fingerprint `{d['data_fingerprint']}`.", ""]
if d["constraints"] or d["units"]:
lines += (
["## Prior knowledge", ""] + [f"- constraint: {c}" for c in d["constraints"]] + [f"- unit of {k}: {v}" for k, v in d["units"].items()] + [""]
)
lines += [
"## Limitations",
"",
d["limitations"] or "The equation is an empirical model; outside the validity domain it extrapolates and must be checked before use.",
"",
]
return "\n".join(lines)
[docs]
def to_html(self) -> str:
"""Self-contained HTML (the Markdown rendered minimally, MathJax for the formula)."""
import html
md = self.to_markdown()
body = []
in_table = False
for line in md.splitlines():
if line.startswith("# "):
body.append(f"<h1>{html.escape(line[2:])}</h1>")
elif line.startswith("## "):
body.append(f"<h2>{html.escape(line[3:])}</h2>")
elif line.startswith("|"):
if set(line.replace("|", "").strip()) <= {"-"}:
continue
if not in_table:
body.append("<table>")
in_table = True
cells = [c.strip() for c in line.strip("|").split("|")]
body.append("<tr>" + "".join(f"<td>{html.escape(c)}</td>" for c in cells) + "</tr>")
continue
elif line.startswith("- "):
body.append(f"<li>{html.escape(line[2:])}</li>")
elif line.startswith("$$"):
body.append(f"<p>\\[{html.escape(line.strip('$'))}\\]</p>")
elif line.strip():
body.append(f"<p>{html.escape(line)}</p>")
if in_table and not line.startswith("|"):
body.append("</table>")
in_table = False
style = "body{font-family:Raleway,Helvetica,sans-serif;max-width:52rem;margin:2rem auto;color:#1F2A36}h1,h2{color:#285780}table{border-collapse:collapse}td{border:1px solid #ccd;padding:2px 8px}"
return f"<!DOCTYPE html><html><head><meta charset='utf-8'><title>{html.escape(self.name)}</title><style>{style}</style><script src='https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js'></script></head><body>{''.join(body)}</body></html>"
def save(self, path) -> None:
path = str(path)
text = (
self.to_html()
if path.endswith(".html")
else (json.dumps(self.to_dict(), indent=2, default=float) if path.endswith(".json") else self.to_markdown())
)
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
[docs]
class RunTracker:
"""Log parameters, metrics and equations of search runs.
Runs are appended to ``<directory>/runs.jsonl``. With ``mlflow=True`` and
MLflow installed, the same information is also logged to the active MLflow
tracking server.
"""
def __init__(self, directory="eqdisco_runs", mlflow: bool = False, experiment: str | None = None):
self.dir = Path(directory)
self.dir.mkdir(parents=True, exist_ok=True)
self.mlflow = mlflow
self.experiment = experiment
[docs]
def log(self, estimator, X, y, X_test=None, y_test=None, tags: dict | None = None) -> dict:
"""Record a fitted estimator: parameters, equation, train/test metrics, history length."""
from .fitness import r2
eq = estimator.equation_
params = {k: (v if isinstance(v, (int, float, str, bool, type(None))) else repr(v)) for k, v in estimator.get_params().items()}
rec = {
"time": _now(),
"method": type(estimator).__name__,
"params": params,
"equation": str(eq),
"equation_json": eq.to_dict(),
"complexity": eq.complexity,
"r2_train": r2(y, eq.predict(X)),
"data_fingerprint": fingerprint(X, y),
"tags": tags or {},
}
if X_test is not None:
rec["r2_test"] = r2(y_test, eq.predict(X_test))
if hasattr(estimator, "n_evaluations_"):
rec["n_evaluations"] = estimator.n_evaluations_
with open(self.dir / "runs.jsonl", "a", encoding="utf-8") as fh:
fh.write(json.dumps(rec, default=float) + "\n")
if self.mlflow:
try:
import mlflow
if self.experiment:
mlflow.set_experiment(self.experiment)
with mlflow.start_run():
mlflow.log_params({k: str(v)[:250] for k, v in params.items()})
mlflow.log_metrics({k: float(rec[k]) for k in ("r2_train", "r2_test", "complexity") if k in rec})
mlflow.set_tags({"equation": rec["equation"][:5000], **(tags or {})})
mlflow.log_dict(eq.to_dict(), "equation.json")
except ImportError:
pass
return rec
[docs]
def runs(self) -> pd.DataFrame:
"""All logged runs as a table."""
p = self.dir / "runs.jsonl"
if not p.exists():
return pd.DataFrame()
rows = [json.loads(line) for line in p.read_text(encoding="utf-8").splitlines() if line.strip()]
for r in rows:
r.pop("equation_json", None)
r.pop("params", None)
return pd.DataFrame(rows)
[docs]
def population_stability_index(ref, new, bins: int = 10) -> float:
"""PSI of a variable between reference and new samples (quantile bins of the reference).
Common reading: below 0.1 stable, 0.1--0.25 moderate shift, above 0.25 major
shift. These constants ignore the sample sizes; see :func:`psi_critical_value`.
"""
ref = np.asarray(ref, float)
new = np.asarray(new, float)
edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1)))
if len(edges) < 3:
return 0.0
edges[0], edges[-1] = -np.inf, np.inf
p = np.histogram(ref, edges)[0] / len(ref)
q = np.histogram(new, edges)[0] / max(len(new), 1)
p = np.clip(p, 1e-6, None)
q = np.clip(q, 1e-6, None)
return float(np.sum((q - p) * np.log(q / p)))
[docs]
def psi_critical_value(n_ref: int, n_new: int, bins: int = 10, level: float = 0.95) -> float:
"""Value that the PSI of two samples of one distribution exceeds with probability ``1 - level``.
A second-order expansion of the logarithm shows that
:math:`\\mathrm{PSI}/(1/N+1/M)` is asymptotically :math:`\\chi^2` with
``bins - 1`` degrees of freedom when both samples come from the same
distribution (Yurdakul and Naranjo, 2020); with 300 reference and 100 new
samples in ten bins the 95 % point is 0.23, above the usual 0.1.
"""
from scipy import stats
return float(stats.chi2.ppf(level, bins - 1) * (1.0 / n_ref + 1.0 / n_new))
[docs]
class DriftMonitor:
"""Monitor the inputs and residuals of a deployed equation.
Parameters
----------
equation : Equation
X_ref, y_ref : array-like
Reference (training) data.
psi_warning, psi_retrain : float
PSI thresholds of a warning and of a retraining recommendation.
sample_size_correction : bool, default=True
Raise each PSI threshold to the 95 % (warning) or 99 % (retraining) point
of the PSI of two same-distribution samples of the actual sizes
(:func:`psi_critical_value`), so that small batches do not raise false alarms.
domain_tolerance : float
Share of new samples allowed outside the training box before a warning.
ph_delta, ph_lambda : float
Page--Hinkley parameters, relative to the reference residual standard
deviation: tolerated drift magnitude and detection threshold.
"""
def __init__(
self,
equation: Equation,
X_ref,
y_ref=None,
psi_warning: float = 0.1,
psi_retrain: float = 0.25,
domain_tolerance: float = 0.05,
ph_delta: float = 0.1,
ph_lambda: float = 10.0,
sample_size_correction: bool = True,
):
self.equation = equation
self.sample_size_correction = sample_size_correction
self.X_ref = np.asarray(X_ref, float)
self.y_ref = None if y_ref is None else np.asarray(y_ref, float)
self.lower = self.X_ref.min(0)
self.upper = self.X_ref.max(0)
self.psi_warning = psi_warning
self.psi_retrain = psi_retrain
self.domain_tolerance = domain_tolerance
self.ph_delta = ph_delta
self.ph_lambda = ph_lambda
if self.y_ref is not None:
r = self.y_ref - equation.predict(self.X_ref)
self.res_sd = float(np.std(r)) or 1.0
self.res_mean = float(np.mean(r))
else:
self.res_sd, self.res_mean = 1.0, 0.0
[docs]
def page_hinkley(self, residuals) -> tuple[bool, int | None]:
"""Page--Hinkley test for an increase of the absolute standardized residual; returns (alarm, index)."""
z = np.abs((np.asarray(residuals, float) - self.res_mean) / self.res_sd)
mean = np.sqrt(2 / np.pi) # E|N(0,1)|
m = 0.0
mmin = 0.0
for t, v in enumerate(z):
m += v - mean - self.ph_delta
mmin = min(mmin, m)
if m - mmin > self.ph_lambda:
return True, t
return False, None
[docs]
def check(self, X_new, y_new=None) -> dict:
"""Drift report of a batch of new data.
Returns a dictionary with per-variable PSI and Kolmogorov--Smirnov p-values,
the share of samples outside the training box, residual statistics and the
Page--Hinkley alarm (if ``y_new`` is given), and ``status`` in
``{"ok", "warning", "retrain"}`` with the ``reasons``.
"""
from scipy import stats
X_new = np.asarray(X_new, float)
feats = {}
reasons = []
status = "ok"
thr_w, thr_r = self.psi_warning, self.psi_retrain
if self.sample_size_correction:
thr_w = max(thr_w, psi_critical_value(len(self.X_ref), len(X_new), level=0.95))
thr_r = max(thr_r, psi_critical_value(len(self.X_ref), len(X_new), level=0.99))
for j, n in enumerate(self.equation.feature_names):
psi = population_stability_index(self.X_ref[:, j], X_new[:, j])
ks = stats.ks_2samp(self.X_ref[:, j], X_new[:, j])
feats[n] = {"psi": psi, "ks_p": float(ks.pvalue), "used": n in self.equation.variables}
if n in self.equation.variables:
if psi > thr_r:
status = "retrain"
reasons.append(f"major shift of {n} (PSI {psi:.2f})")
elif psi > thr_w:
status = "warning" if status == "ok" else status
reasons.append(f"moderate shift of {n} (PSI {psi:.2f})")
used = [j for j, n in enumerate(self.equation.feature_names) if n in self.equation.variables] or list(range(X_new.shape[1]))
outside = np.any((X_new[:, used] < self.lower[used]) | (X_new[:, used] > self.upper[used]), axis=1)
frac = float(np.mean(outside))
if frac > self.domain_tolerance:
status = "warning" if status == "ok" else status
reasons.append(f"{100 * frac:.1f} % of the samples outside the training box (extrapolation)")
report = {"features": feats, "outside_domain": frac, "status": status, "reasons": reasons, "n": len(X_new),
"psi_thresholds": (thr_w, thr_r)}
if y_new is not None:
r = np.asarray(y_new, float) - self.equation.predict(X_new)
alarm, at = self.page_hinkley(r)
report.update(
{
"residual_mean": float(r.mean()),
"residual_sd": float(r.std()),
"residual_sd_ratio": float(r.std() / self.res_sd),
"page_hinkley_alarm": alarm,
"page_hinkley_index": at,
}
)
if alarm:
status = "retrain"
reasons.append(f"residual drift detected at sample {at} (Page-Hinkley)")
elif r.std() > 1.5 * self.res_sd:
status = "warning" if status == "ok" else status
reasons.append(f"residual spread {r.std() / self.res_sd:.2f} times the reference")
report["status"] = status
return report