matter-os / simulation /convergence.py
tmepass000's picture
MATTER OS v0.1.0
87b48de verified
Raw History Blame Contribute Delete
2.51 kB
"""Convergence tests and sensitivity analysis (decision 45; section 7 'failed convergence is not success')."""
from __future__ import annotations
from typing import Any
from core.representation import MatterStructure
from simulation.contract import RunContext, SolverAdapter
def is_converged(conv: dict[str, Any]) -> bool:
return conv.get("status") == "converged"
def parameter_sensitivity(adapter: SolverAdapter, ms: MatterStructure, observable: str, base_params: dict,
vary: dict[str, list], ctx: RunContext, key: str | None = None) -> dict[str, Any]:
"""Re-run with varied parameters and report the spread of `key` (default: first observable)."""
rows = []
for pname, values in vary.items():
for v in values:
p = dict(base_params); p[pname] = v
ctx_i = RunContext(workdir=ctx.workdir, seed=ctx.seed, wall_time_s=ctx.wall_time_s, cancel_check=ctx.cancel_check)
out = adapter.run(ms, observable, p, ctx_i)
k = key or next(iter(out.observables), None)
val = out.observables.get(k, {}).get("value") if k else None
rows.append({"param": pname, "value": v, "status": out.status, "convergence": out.convergence.get("status"), "result": val})
vals = [r["result"] for r in rows if isinstance(r["result"], (int, float))]
spread = (max(vals) - min(vals)) if len(vals) >= 2 else None
return {"observable_key": key, "rows": rows, "spread": spread}
def tighter_criterion_check(adapter: SolverAdapter, ms: MatterStructure, observable: str, params: dict, tight_params: dict,
ctx: RunContext, key: str, tol: float, per_atom: bool = True) -> dict[str, Any]:
"""Run at standard and tighter criteria; converged if |delta| <= tol (per atom if requested)."""
a = adapter.run(ms, observable, params, RunContext(workdir=ctx.workdir, seed=ctx.seed, wall_time_s=ctx.wall_time_s))
b = adapter.run(ms, observable, {**params, **tight_params}, RunContext(workdir=ctx.workdir, seed=ctx.seed, wall_time_s=ctx.wall_time_s))
va = a.observables.get(key, {}).get("value"); vb = b.observables.get(key, {}).get("value")
if va is None or vb is None:
return {"status": "unknown", "reason": "missing values", "a": a.status, "b": b.status}
d = abs(va - vb) / (ms.n_atoms if per_atom else 1)
return {"status": "converged" if d <= tol else "not_converged", "delta": d, "tol": tol, "per_atom": per_atom,
"standard": va, "tight": vb}