vibe-sketcherDocumentation

Source code for vibesketcher.document.eos

"""Equation-of-state fits of E(V) scans and their paper plot (#208).

Two four-parameter forms are fitted to energies per formula unit:

- third-order Birch-Murnaghan (F. Birch, Phys. Rev. 71, 809 (1947),
  doi:10.1103/PhysRev.71.809), from the Eulerian finite strain
  f = [(V0/V)^(2/3) - 1] / 2:
  E(V) = E0 + (9 V0 B0 / 16) {[(V0/V)^(2/3) - 1]^3 B0' +
  [(V0/V)^(2/3) - 1]^2 [6 - 4 (V0/V)^(2/3)]};
- Vinet (P. Vinet, J. Ferrante, J. H. Rose and J. R. Smith, J. Geophys.
  Res. 92, 9319 (1987), doi:10.1029/JB092iB09p09319), with
  eta = (V/V0)^(1/3):
  E(V) = E0 + [2 B0 V0 / (B0' - 1)^2] {2 - [5 + 3 B0' (eta - 1) - 3 eta]
  exp[-3 (B0' - 1)(eta - 1) / 2]}.

The Birch-Murnaghan energy is a cubic polynomial in x = V^(-2/3), so its
least-squares fit is linear: the polynomial coefficients are solved exactly
and E0, V0, B0 = V E''(V) and B0' = -(1 + V E'''/E'') are taken at the
polynomial's minimum. Vinet is fitted by damped Gauss-Newton
(Levenberg-Marquardt) least squares from the Birch-Murnaghan parameters.

A fit is reported with flags rather than promoted: a minimum outside the
sampled volumes, too narrow or too wide a range, a large residual, a flat
curve, an unusual B0' or disagreeing forms all say why V0 and B0 should not
be trusted. Unconverged points and points computed with differing settings
are refused before fitting.
"""

from __future__ import annotations

import math
from collections.abc import Sequence
from typing import Any, Literal

import numpy as np
from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.units import HARTREE_TO_EV

#: 1 eV/A^3 in GPa (CODATA 2018 elementary charge, exact).
EV_PER_A3_TO_GPA = 160.2176634
Model = Literal["birch-murnaghan-3", "vinet"]
MODELS: tuple[Model, ...] = ("birch-murnaghan-3", "vinet")
REFERENCES = {
    "birch-murnaghan-3": "F. Birch, Phys. Rev. 71, 809 (1947), doi:10.1103/PhysRev.71.809",
    "vinet": "P. Vinet, J. Ferrante, J. H. Rose and J. R. Smith, J. Geophys. Res. 92, 9319 "
    "(1987), doi:10.1029/JB092iB09p09319",
}


[docs] class EosPoint(BaseModel): """One scan point: the cell volume and its total energy, both per cell.""" model_config = ConfigDict(extra="forbid") volume_angstrom3: float = Field(gt=0, allow_inf_nan=False) energy_hartree: float = Field(allow_inf_nan=False) converged: bool | None = None label: str | None = None #: Settings the point was computed with (method, basis, k-mesh, engine version). settings: dict[str, Any] = Field(default_factory=dict)
[docs] class EosTable(BaseModel): """Per-cell energies of a volume scan and the cell's formula units.""" model_config = ConfigDict(extra="forbid") schema_id: Literal["vibe-eos-table/1"] = Field(default="vibe-eos-table/1", alias="schema") formula: str | None = None formula_units: int = Field(default=1, ge=1, le=100000) points: list[EosPoint] = Field(min_length=4, max_length=500) #: Drop unconverged points instead of refusing the table. drop_unconverged: bool = False
[docs] def birch_murnaghan(v: np.ndarray, e0: float, v0: float, b0: float, bp: float) -> np.ndarray: """Third-order Birch-Murnaghan E(V) (Birch 1947).""" eta2 = (v0 / v) ** (2.0 / 3.0) return e0 + 9.0 * v0 * b0 / 16.0 * ( (eta2 - 1.0) ** 3 * bp + (eta2 - 1.0) ** 2 * (6.0 - 4.0 * eta2) )
[docs] def vinet(v: np.ndarray, e0: float, v0: float, b0: float, bp: float) -> np.ndarray: """Vinet universal E(V) (Vinet et al. 1987).""" eta = (v / v0) ** (1.0 / 3.0) a = 1.5 * (bp - 1.0) return e0 + 2.0 * b0 * v0 / (bp - 1.0) ** 2 * ( 2.0 - (5.0 + 3.0 * bp * (eta - 1.0) - 3.0 * eta) * np.exp(-a * (eta - 1.0)) )
[docs] def birch_murnaghan_pressure(v: np.ndarray, v0: float, b0: float, bp: float) -> np.ndarray: """P(V) = -dE/dV of the third-order Birch-Murnaghan form, in the units of b0.""" x = (v0 / v) ** (1.0 / 3.0) return 1.5 * b0 * (x**7 - x**5) * (1.0 + 0.75 * (bp - 4.0) * (x**2 - 1.0))
[docs] def vinet_pressure(v: np.ndarray, v0: float, b0: float, bp: float) -> np.ndarray: """P(V) of the Vinet form, in the units of b0.""" eta = (v / v0) ** (1.0 / 3.0) return 3.0 * b0 * (1.0 - eta) / eta**2 * np.exp(1.5 * (bp - 1.0) * (1.0 - eta))
_FORMS = {"birch-murnaghan-3": birch_murnaghan, "vinet": vinet} def _fit_birch_murnaghan(v: np.ndarray, e: np.ndarray) -> tuple[float, float, float, float]: """Exact linear least squares of E = c0 + c1 x + c2 x^2 + c3 x^3, x = V^(-2/3).""" x = v ** (-2.0 / 3.0) scale = float(np.mean(x)) t = x / scale coefficients = np.linalg.lstsq(np.vander(t, 4, increasing=True), e, rcond=None)[0] c = coefficients / scale ** np.arange(4) # in powers of x d1 = np.array([c[1], 2 * c[2], 3 * c[3]]) # dE/dx roots = np.roots(d1[::-1]) if abs(d1[2]) > 0 else np.array([-d1[0] / d1[1]]) candidates = [ float(r.real) for r in np.atleast_1d(roots) if abs(r.imag) < 1e-12 * max(1.0, abs(r.real)) and r.real > 0 ] def second(xx: float) -> float: return float(2 * c[2] + 6 * c[3] * xx) minima = [xx for xx in candidates if second(xx) > 0] if not minima: raise ValueError("the Birch-Murnaghan polynomial has no minimum") centre = float(np.mean(x)) x0 = min(minima, key=lambda xx: abs(xx - centre)) v0 = x0 ** (-1.5) f1 = 0.0 f2 = second(x0) f3 = 6 * c[3] dx1 = -2.0 / 3.0 * v0 ** (-5.0 / 3.0) dx2 = 10.0 / 9.0 * v0 ** (-8.0 / 3.0) dx3 = -80.0 / 27.0 * v0 ** (-11.0 / 3.0) e_vv = f2 * dx1**2 + f1 * dx2 e_vvv = f3 * dx1**3 + 3 * f2 * dx1 * dx2 + f1 * dx3 e0 = float(c[0] + c[1] * x0 + c[2] * x0**2 + c[3] * x0**3) b0 = v0 * e_vv bp = -(1.0 + v0 * e_vvv / e_vv) return e0, float(v0), float(b0), float(bp) def _fit_vinet( v: np.ndarray, e: np.ndarray, start: tuple[float, float, float, float] ) -> tuple[float, float, float, float]: """Levenberg-Marquardt least squares (K. Levenberg 1944; D. W. Marquardt 1963).""" p = np.array(start, dtype=float) p[3] = max(p[3], 1.05) span = max(float(np.ptp(e)), 1e-12) def residual(q: np.ndarray) -> np.ndarray: out: np.ndarray = (vinet(v, *q) - e) / span return out r = residual(p) cost = float(r @ r) damping = 1e-3 for _ in range(500): jac = np.empty((v.size, 4)) for k in range(4): step = 1e-6 * max(abs(p[k]), 1e-6) q = p.copy() q[k] += step jac[:, k] = (residual(q) - r) / step normal = jac.T @ jac gradient = jac.T @ r improved = False for _ in range(30): try: delta = np.linalg.solve( normal + damping * np.diag(np.diag(normal) + 1e-30), -gradient ) except np.linalg.LinAlgError: damping *= 10 continue trial = p + delta if trial[1] <= 0 or trial[2] <= 0 or trial[3] <= 1.0: damping *= 10 continue r_trial = residual(trial) c_trial = float(r_trial @ r_trial) if c_trial < cost: converged = abs(cost - c_trial) <= 1e-15 * max(cost, 1e-300) or np.all( np.abs(delta) <= 1e-13 * np.maximum(np.abs(p), 1e-12) ) p, r, cost = trial, r_trial, c_trial damping = max(damping / 10, 1e-12) improved = True if converged: return tuple(float(x) for x in p) # type: ignore[return-value] break damping *= 10 if not improved: break return tuple(float(x) for x in p) # type: ignore[return-value]
[docs] def fit( volumes: Sequence[float] | np.ndarray, energies: Sequence[float] | np.ndarray, model: Model = "birch-murnaghan-3", ) -> dict[str, float]: """Fit one form to volumes (A^3) and energies (eV); returns E0, V0, B0 (eV/A^3), B0'.""" v = np.asarray(volumes, dtype=float) e = np.asarray(energies, dtype=float) if v.size != e.size or v.size < 4: raise ValueError("an EOS fit needs at least four volumes with one energy each") if not (np.all(np.isfinite(v)) and np.all(np.isfinite(e)) and np.all(v > 0)): raise ValueError("volumes must be positive and energies finite") if np.unique(np.round(v, 10)).size != v.size: raise ValueError("the scan repeats a volume") order = np.argsort(v) v, e = v[order], e[order] bm = _fit_birch_murnaghan(v, e) params = bm if model == "birch-murnaghan-3" else _fit_vinet(v, e, bm) fitted = _FORMS[model](v, *params) rmse = float(np.sqrt(np.mean((fitted - e) ** 2))) return { "e0_ev": params[0], "v0_angstrom3": params[1], "b0_ev_per_angstrom3": params[2], "b0_prime": params[3], "rmse_ev": rmse, }
#: Flag thresholds; a flag is a warning on the fit, never a silent correction. LIMITS: dict[str, float] = { "min_points": 5, "min_range_fraction": 0.06, "max_range_fraction": 0.40, "max_rmse_to_span": 0.02, "min_span_ev": 1e-4, "b0_prime_low": 1.5, "b0_prime_high": 8.0, "model_v0_agreement": 0.005, "model_b0_agreement": 0.05, } def _flags(v: np.ndarray, e: np.ndarray, result: dict[str, float]) -> list[dict[str, str]]: flags: list[dict[str, str]] = [] v0 = result["v0_angstrom3"] span = float(np.ptp(e)) def add(code: str, message: str) -> None: flags.append({"code": code, "message": message}) if v.size < LIMITS["min_points"]: add("few_points", f"{v.size} points leave {v.size - 4} degrees of freedom for 4 parameters") if not v.min() <= v0 <= v.max(): add("minimum_not_bracketed", f"V0 = {v0:.4f} A^3 lies outside the sampled volumes") i_min = int(np.argmin(e)) if i_min in (0, v.size - 1): add("minimum_at_edge", "the lowest energy is the first or last sampled volume") width = float((v.max() - v.min()) / v0) if width < LIMITS["min_range_fraction"]: add("narrow_range", f"the volumes span {100 * width:.1f}% of V0; B0' is poorly determined") if width > LIMITS["max_range_fraction"]: add("wide_range", f"the volumes span {100 * width:.1f}% of V0; a four-parameter form " "may not hold over it") # fmt: skip if span < LIMITS["min_span_ev"]: add("flat_curve", f"the energies span {span:.3g} eV per formula unit") ratio = result["rmse_ev"] / span if span > 0 else math.inf if ratio > LIMITS["max_rmse_to_span"]: add("poor_residual", f"RMS residual is {100 * ratio:.2f}% of the energy span") if result["b0_ev_per_angstrom3"] <= 0: add("unphysical_b0", "B0 is not positive") low, high = LIMITS["b0_prime_low"], LIMITS["b0_prime_high"] if not low <= result["b0_prime"] <= high: add("unusual_b0_prime", f"B0' = {result['b0_prime']:.2f} is outside {low}-{high}") return flags
[docs] def analyse(table: EosTable) -> dict[str, Any]: """Fit both forms to a table and report V0, E0, B0, B0' per formula unit with flags.""" points = list(table.points) dropped: list[str] = [] unconverged = [p for p in points if p.converged is False] if unconverged and not table.drop_unconverged: names = ", ".join(p.label or f"{p.volume_angstrom3:g} A^3" for p in unconverged) raise ValueError( f"refusing to fit unconverged points ({names}); an unconverged energy is not a point " "of E(V). Rerun them or set drop_unconverged" ) if unconverged: dropped = [p.label or f"{p.volume_angstrom3:g}" for p in unconverged] points = [p for p in points if p.converged is not False] keys = sorted({k for p in points for k in p.settings}) for key in keys: values = {repr(p.settings.get(key)) for p in points} if len(values) > 1: raise ValueError( f"the points were computed with different {key} ({', '.join(sorted(values))}); " "an EOS needs one Hamiltonian, basis and k-mesh" ) if len(points) < 4: raise ValueError("an EOS fit needs at least four converged points") z = table.formula_units v = np.array([p.volume_angstrom3 for p in points]) / z e = np.array([p.energy_hartree for p in points]) * HARTREE_TO_EV / z order = np.argsort(v) v, e = v[order], e[order] fits: dict[str, Any] = {} for model in MODELS: try: result = fit(v, e, model) except (ValueError, np.linalg.LinAlgError) as error: fits[model] = {"status": "failed", "reason": str(error), "flags": []} continue b0 = result["b0_ev_per_angstrom3"] fits[model] = { "status": "fitted", "v0_angstrom3_per_fu": result["v0_angstrom3"], "e0_ev_per_fu": result["e0_ev"], "e0_hartree_per_cell": result["e0_ev"] * z / HARTREE_TO_EV, "b0_gpa": b0 * EV_PER_A3_TO_GPA, "b0_ev_per_angstrom3": b0, "b0_prime": result["b0_prime"], "rmse_ev_per_fu": result["rmse_ev"], "flags": _flags(v, e, result), "reference": REFERENCES[model], } fitted = [fits[m] for m in MODELS if fits[m]["status"] == "fitted"] agreement: list[dict[str, str]] = [] if len(fitted) == 2: a, b = fitted dv = abs(a["v0_angstrom3_per_fu"] - b["v0_angstrom3_per_fu"]) / a["v0_angstrom3_per_fu"] db = abs(a["b0_gpa"] - b["b0_gpa"]) / max(abs(a["b0_gpa"]), 1e-12) if dv > LIMITS["model_v0_agreement"]: message = f"V0 differs by {100 * dv:.2f}% between the forms" agreement.append({"code": "models_disagree_v0", "message": message}) if db > LIMITS["model_b0_agreement"]: message = f"B0 differs by {100 * db:.1f}% between the forms" agreement.append({"code": "models_disagree_b0", "message": message}) if not fitted: raise ValueError("neither EOS form could be fitted: " + "; ".join( str(fits[m].get("reason")) for m in MODELS)) # fmt: skip trusted = all(not f["flags"] for f in fitted) and not agreement and len(fitted) == 2 return { "formula": table.formula, "formula_units": z, "normalisation": f"per formula unit ({z} per cell)", "units": { "volume": "A^3 per formula unit", "energy": "eV per formula unit", "pressure": "GPa", "input_energy": "hartree per cell", }, # fmt: skip "points": [ {"volume_angstrom3_per_fu": float(x), "energy_ev_per_fu": float(y)} for x, y in zip(v, e, strict=True) ], "dropped_unconverged": dropped, "settings": {k: points[0].settings.get(k) for k in keys}, "fits": fits, "agreement_flags": agreement, "status": "fit" if trusted else "flagged", "limits": dict(LIMITS), }
def _ticks(low: float, high: float, count: int = 5) -> list[float]: raw = (high - low) / max(count, 1) magnitude = 10 ** math.floor(math.log10(raw)) if raw > 0 else 1.0 step = next(m * magnitude for m in (1, 2, 2.5, 5, 10) if m * magnitude >= raw) start = math.ceil(low / step) * step ticks = [] value = start while value <= high + 1e-9 * step: ticks.append(round(value, 12)) value += step return ticks def _label(value: float) -> str: text = f"{value:.6g}" return text.replace("-", "−")
[docs] def plot_svg(report: dict[str, Any], *, title: str | None = None) -> str: """A paper-ready E(V) plot of an :func:`analyse` report: points, both fits, V0 and B0.""" width, height = 480.0, 340.0 left, right, top, bottom = 72.0, 18.0, 28.0 if title else 14.0, 52.0 points = report["points"] v = np.array([p["volume_angstrom3_per_fu"] for p in points]) fitted = {m: f for m, f in report["fits"].items() if f.get("status") == "fitted"} reference = min(f["e0_ev_per_fu"] for f in fitted.values()) if fitted else float(min( p["energy_ev_per_fu"] for p in points)) # fmt: skip e = np.array([p["energy_ev_per_fu"] for p in points]) - reference pad = 0.04 * float(np.ptp(v)) vx = np.linspace(v.min() - pad, v.max() + pad, 160) curves = {m: _FORMS[m](vx, f["e0_ev_per_fu"] - reference, f["v0_angstrom3_per_fu"], f["b0_ev_per_angstrom3"], f["b0_prime"]) for m, f in fitted.items()} # fmt: skip ys = np.concatenate([e, *curves.values()]) if curves else e y_low, y_high = float(ys.min()), float(ys.max()) y_pad = 0.06 * (y_high - y_low or 1.0) y_low, y_high = y_low - y_pad, y_high + y_pad x_low, x_high = float(vx.min()), float(vx.max()) plot_w, plot_h = width - left - right, height - top - bottom def sx(x: float) -> float: return left + (x - x_low) / (x_high - x_low) * plot_w def sy(y: float) -> float: return top + (y_high - y) / (y_high - y_low) * plot_h font = 'font-family="Helvetica, Arial, sans-serif"' out = [ f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:g}" height="{height:g}" ' f'viewBox="0 0 {width:g} {height:g}" role="img">', "<title>Energy-volume equation of state</title>", f'<rect x="0" y="0" width="{width:g}" height="{height:g}" fill="#ffffff"/>', f'<rect x="{left:g}" y="{top:g}" width="{plot_w:g}" height="{plot_h:g}" fill="none" ' 'stroke="#000000" stroke-width="1"/>', ] if title: out.append(f'<text x="{left:g}" y="18" {font} font-size="13">{_escape(title)}</text>') for tick in _ticks(x_low, x_high): x = sx(tick) out.append(f'<line x1="{x:.2f}" y1="{top + plot_h:g}" x2="{x:.2f}" ' f'y2="{top + plot_h - 5:g}" stroke="#000000"/>') # fmt: skip out.append(f'<text x="{x:.2f}" y="{top + plot_h + 16:g}" {font} font-size="11" ' f'text-anchor="middle">{_label(tick)}</text>') # fmt: skip for tick in _ticks(y_low, y_high): y = sy(tick) out.append(f'<line x1="{left:g}" y1="{y:.2f}" x2="{left + 5:g}" y2="{y:.2f}" ' 'stroke="#000000"/>') # fmt: skip out.append(f'<text x="{left - 6:g}" y="{y + 4:.2f}" {font} font-size="11" ' f'text-anchor="end">{_label(tick)}</text>') # fmt: skip out.append(f'<text x="{left + plot_w / 2:g}" y="{height - 12:g}" {font} font-size="12" ' 'text-anchor="middle">Volume per formula unit (ų)</text>') # fmt: skip out.append(f'<text transform="translate(16 {top + plot_h / 2:g}) rotate(-90)" {font} ' 'font-size="12" text-anchor="middle">E − E₀ (eV per formula unit)' "</text>") # fmt: skip styles = {"birch-murnaghan-3": ("#1f4e9a", ""), "vinet": ("#b5462c", ' stroke-dasharray="5 3"')} names = {"birch-murnaghan-3": "Birch-Murnaghan (3rd order)", "vinet": "Vinet"} out.append(f'<clipPath id="eos-plot"><rect x="{left:g}" y="{top:g}" width="{plot_w:g}" ' f'height="{plot_h:g}"/></clipPath>') # fmt: skip for model, curve in curves.items(): colour, dash = styles[model] path = " ".join(f"{'M' if i == 0 else 'L'}{sx(float(a)):.2f},{sy(float(b)):.2f}" for i, (a, b) in enumerate(zip(vx, curve, strict=True))) # fmt: skip out.append(f'<path d="{path}" fill="none" stroke="{colour}" stroke-width="1.6"{dash} ' 'clip-path="url(#eos-plot)"/>') # fmt: skip for a, b in zip(v, e, strict=True): out.append(f'<circle cx="{sx(float(a)):.2f}" cy="{sy(float(b)):.2f}" r="3.2" ' 'fill="#ffffff" stroke="#000000" stroke-width="1.2"/>') # fmt: skip y = top + 16 for model, f in fitted.items(): colour, dash = styles[model] x = left + plot_w * 0.30 out.append(f'<line x1="{x:g}" y1="{y - 4:g}" x2="{x + 22:g}" y2="{y - 4:g}" ' f'stroke="{colour}" stroke-width="1.6"{dash}/>') # fmt: skip text = (f"{names[model]}: V₀ = {f['v0_angstrom3_per_fu']:.3f} ų, " f"B₀ = {f['b0_gpa']:.1f} GPa, B₀′ = {f['b0_prime']:.2f}") # fmt: skip out.append(f'<text x="{x + 28:g}" y="{y:g}" {font} font-size="10.5">{text}</text>') y += 15 if report.get("status") != "fit": out.append(f'<text x="{_right_edge(left, plot_w)}" y="{top + plot_h - 8:g}" {font} ' 'font-size="10" text-anchor="end" fill="#7a1f12">flagged fit: see report' "</text>") # fmt: skip out.append("</svg>") return "\n".join(out) + "\n"
def _right_edge(left: float, plot_w: float) -> str: return f"{left + plot_w - 8:g}" def _escape(text: str) -> str: return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")