vibe-sketcherDocumentation
Source code for vibesketcher.document.periodic_recipes
"""Periodic scan, phonon and free-energy recipes that write one input per point (#208).
A recipe is planned against the pinned engine table in
:mod:`vibesketcher.document.periodic_capabilities`. Where the engine runs the
task, the plan writes one vibe-qc input per point plus a ``run_all.py`` driver
that runs them in order and collects ``scan-results.json``; where it does not,
the plan is still written (what would be computed, with every parameter) but
its execution is refused with the engine's reason and the tracker item that
owns the missing capability.
- ``volume_scan``: isotropic strains of a 3-D cell at fixed fractional
coordinates (or with fixed-cell atomic relaxation), one fixed k-mesh, the
energy normalised per formula unit, fitted with
:mod:`vibesketcher.document.eos` (Birch 1947; Vinet et al. 1987).
- ``coordinate_scan``: a distance or angle between named sites set to each
target value by moving named sites (rigid points), or relaxed with the
defining atoms frozen where the engine freezes atoms.
- ``phonons``: a finite-displacement supercell plan (K. Parlinski, Z. Q. Li
and Y. Kawazoe, Phys. Rev. Lett. 78, 4063 (1997); A. Togo and I. Tanaka,
Scr. Mater. 108, 1 (2015)): supercell, displacement amplitude, q-mesh and
masses. Planned only: periodic Hessians fail closed in the engine.
- ``free_energy``: harmonic or quasi-harmonic F(T) / G(T, p) recipes (Togo
and Tanaka 2015, section 4), gated with the phonons and listing the terms
the model omits.
A Gamma-only Hessian of the unit cell treated as a molecule is never accepted
or relabelled as a phonon spectrum.
"""
from __future__ import annotations
import json
import math
from collections import Counter
from functools import reduce
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, field_validator
from vibesketcher.document import periodic_capabilities as caps
from vibesketcher.document.model import Document, PeriodicSite, PeriodicStructure
from vibesketcher.inputs.base import InputBundle, InputFile, WriterRefusal
from vibesketcher.inputs.vibeqc_periodic import (
MaceStage,
PeriodicJobSpec,
write_periodic_input,
)
from vibesketcher.units import EV_TO_CM1
PLAN_SCHEMA = "vibe-periodic-recipe/1"
#: Boltzmann constant in eV/K (CODATA 2018, exact).
KB_EV = 8.617333262e-5
#: SCF defaults the engine applies when the input leaves them unset.
ENGINE_SCF_DEFAULTS = {"max_iter": 80, "conv_tol_energy_hartree": 1e-7}
MAX_SCAN_SITES = 500
REFERENCES = {
"birch": "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",
"parlinski": "K. Parlinski, Z. Q. Li and Y. Kawazoe, Phys. Rev. Lett. 78, 4063 (1997), "
"doi:10.1103/PhysRevLett.78.4063",
"togo": "A. Togo and I. Tanaka, Scr. Mater. 108, 1 (2015), "
"doi:10.1016/j.scriptamat.2015.07.021",
"monkhorst": "H. J. Monkhorst and J. D. Pack, Phys. Rev. B 13, 5188 (1976)",
}
[docs]
class RecipeRefused(ValueError):
"""A recipe the engine (or the planner) cannot run; ``report`` says why."""
def __init__(self, message: str, report: dict[str, Any] | None = None) -> None:
self.report = report or {}
super().__init__(message)
class _Recipe(BaseModel):
model_config = ConfigDict(extra="forbid")
structure: str
spec: PeriodicJobSpec = Field(default_factory=PeriodicJobSpec)
[docs]
class VolumeScanRecipe(_Recipe):
kind: Literal["volume_scan"] = "volume_scan"
#: V / V_input of each point; the cell is scaled isotropically.
volume_fractions: list[float] = Field(
default_factory=lambda: [0.94, 0.96, 0.98, 1.0, 1.02, 1.04, 1.06],
min_length=5,
max_length=25,
)
relax: Literal["none", "positions"] = "none"
#: Formula units per cell; derived from the composition when left out.
formula_units: int | None = Field(default=None, ge=1, le=100000)
@field_validator("volume_fractions")
@classmethod
def _fractions(cls, values: list[float]) -> list[float]:
if any(not math.isfinite(v) or not 0.6 <= v <= 1.5 for v in values):
raise ValueError("volume fractions must be between 0.6 and 1.5")
if len({round(v, 6) for v in values}) != len(values):
raise ValueError("volume fractions must be distinct")
return sorted(values)
[docs]
class CoordinateScanRecipe(_Recipe):
kind: Literal["coordinate_scan"] = "coordinate_scan"
coordinate: Literal["distance", "angle"]
#: Two site IDs for a distance, three (vertex in the middle) for an angle.
sites: list[str] = Field(min_length=2, max_length=3)
#: Target values in angstrom (distance) or degrees (angle).
values: list[float] = Field(min_length=2, max_length=60)
#: Sites moved to reach each value; default the last site.
moving: list[str] = Field(default_factory=list, max_length=MAX_SCAN_SITES)
relax: Literal["none", "positions"] = "none"
min_contact_angstrom: float = Field(default=0.5, gt=0, le=3)
[docs]
class PhononRecipe(_Recipe):
kind: Literal["phonons"] = "phonons"
supercell: tuple[int, int, int] = (2, 2, 2)
displacement_angstrom: float = Field(default=0.01, gt=0, le=0.1)
q_mesh: tuple[int, int, int] = (8, 8, 8)
#: Mass overrides in amu (isotopes); every other element uses the standard atomic weight.
masses: dict[str, float] = Field(default_factory=dict)
acoustic_sum_rule: bool = True
#: Where force constants would come from. A molecular Gamma Hessian is refused.
hessian_source: Literal["periodic-supercell", "molecular-gamma"] = "periodic-supercell"
@field_validator("supercell", "q_mesh")
@classmethod
def _mesh(cls, value: tuple[int, int, int]) -> tuple[int, int, int]:
if any(n < 1 or n > 64 for n in value):
raise ValueError("supercell and q-mesh entries must be between 1 and 64")
return value
@field_validator("masses")
@classmethod
def _masses(cls, value: dict[str, float]) -> dict[str, float]:
if any(not math.isfinite(m) or m <= 0 for m in value.values()):
raise ValueError("masses must be positive (amu)")
return value
[docs]
class FreeEnergyRecipe(_Recipe):
kind: Literal["free_energy"] = "free_energy"
approximation: Literal["harmonic", "quasi-harmonic"] = "harmonic"
temperatures_k: list[float] = Field(
default_factory=lambda: [0.0, 100.0, 200.0, 300.0, 500.0, 800.0, 1000.0],
min_length=1,
max_length=500,
)
#: Pressures for G(T, p) (quasi-harmonic only).
pressures_gpa: list[float] = Field(default_factory=lambda: [0.0], max_length=100)
#: Volumes of the quasi-harmonic grid (V / V_input).
volume_fractions: list[float] = Field(
default_factory=lambda: [0.94, 0.96, 0.98, 1.0, 1.02, 1.04, 1.06], max_length=25
)
phonons: PhononRecipe | None = None
@field_validator("temperatures_k")
@classmethod
def _temperatures(cls, values: list[float]) -> list[float]:
if any(not math.isfinite(t) or not 0 <= t <= 5000 for t in values):
raise ValueError("temperatures must be between 0 and 5000 K")
return values
Recipe = VolumeScanRecipe | CoordinateScanRecipe | PhononRecipe | FreeEnergyRecipe
[docs]
class RecipePlan(BaseModel):
"""What a recipe computes, every parameter it fixes, and whether it can run."""
model_config = ConfigDict(extra="forbid")
schema_id: Literal["vibe-periodic-recipe/1"] = Field(
default="vibe-periodic-recipe/1", alias="schema"
)
kind: str
structure: str
status: Literal["ready", "refused"]
engine: dict[str, str]
capabilities: list[dict[str, Any]]
spec: dict[str, Any]
recipe: dict[str, Any]
points: list[dict[str, Any]] = Field(default_factory=list)
normalisation: dict[str, Any] = Field(default_factory=dict)
units: dict[str, str] = Field(default_factory=dict)
convergence: dict[str, Any] = Field(default_factory=dict)
formula: str | None = None
assumptions: list[str] = Field(default_factory=list)
warnings: list[str] = Field(default_factory=list)
omitted_terms: list[dict[str, str]] = Field(default_factory=list)
refusal: dict[str, Any] | None = None
references: list[str] = Field(default_factory=list)
files: list[str] = Field(default_factory=list)
[docs]
def parse_recipe(data: dict[str, Any]) -> Recipe:
"""Validate a recipe by its ``kind``."""
from pydantic import TypeAdapter
adapter: TypeAdapter[Recipe] = TypeAdapter(Recipe)
recipe: Recipe = adapter.validate_python(data)
return recipe
def _structure(document: Document, identifier: str) -> PeriodicStructure:
found = {s.id: s for s in document.periodic_structures}
if identifier not in found:
raise ValueError(f"periodic structure {identifier!r} not found")
return found[identifier]
def _dim(structure: PeriodicStructure) -> int:
return sum(structure.pbc)
def _hill(counts: dict[str, int]) -> str:
order = (["C", "H"] if "C" in counts else []) + sorted(
k for k in counts if "C" not in counts or k not in ("C", "H")
)
return "".join(f"{k}{counts[k] if counts[k] != 1 else ''}" for k in order)
[docs]
def formula_units(structure: PeriodicStructure, given: int | None = None) -> tuple[str, int]:
"""The reduced formula and the formula units per cell (stated or the composition's gcd)."""
counts = Counter(site.symbol for site in structure.sites)
divisor = reduce(math.gcd, counts.values())
if given is not None:
if any(n % given for n in counts.values()):
raise ValueError(
f"{given} formula units do not divide the cell composition {dict(counts)}"
)
divisor = given
reduced = {k: v // divisor for k, v in counts.items()}
return _hill(reduced), divisor
def _convergence(spec: PeriodicJobSpec) -> dict[str, Any]:
return {
"max_iter": spec.max_iter or ENGINE_SCF_DEFAULTS["max_iter"],
"max_iter_source": "input" if spec.max_iter else "engine default",
"conv_tol_energy_hartree": ENGINE_SCF_DEFAULTS["conv_tol_energy_hartree"],
"conv_tol_energy_source": "engine default",
"kpoints": spec.kpoints.model_dump(mode="json"),
"kpoints_note": "one fixed mesh for every point; the k-point density changes with the "
"cell by (V / V_input)^(-1/3) per direction",
}
def _require(task: str, spec: PeriodicJobSpec, dim: int) -> caps.Capability:
row = caps.admitted(task, spec.model, dim)
if row is None:
report = caps.refusal(task, spec.model, dim)
raise RecipeRefused(f"{task} on {spec.model}: " + "; ".join(report["reasons"]), report)
return row
def _fixed_builder_sites(structure: PeriodicStructure) -> list[str]:
builder = structure.provenance.get("builder")
if isinstance(builder, dict):
recorded = builder.get("fixed_sites")
if isinstance(recorded, list):
return [str(x) for x in recorded]
return []
def _scan_spec(
structure: PeriodicStructure, spec: PeriodicJobSpec, relax: str, frozen: list[str]
) -> tuple[PeriodicJobSpec, list[caps.Capability]]:
"""The per-point specification, or a refusal naming the missing engine capability."""
dim = _dim(structure)
if spec.task != "sp":
raise RecipeRefused("set relax on the recipe, not task on the spec")
if spec.preoptimize is not None:
raise RecipeRefused(
"a scan point is one Hamiltonian at one constrained geometry; a MACE "
"pre-optimisation would move it. Use relax='positions' instead"
)
if spec.mace is not None and spec.mace.relax == "cell":
raise RecipeRefused("a scan point keeps its cell; MACE cell relaxation is refused here")
if relax == "none":
return spec, [_require("energy", spec, dim)]
rows = [_require("energy", spec, dim)]
frozen = sorted({*frozen, *(_fixed_builder_sites(structure) if spec.model == "pbc" else [])})
if frozen:
rows.append(_require("relax_positions_frozen", spec, dim))
stage = (spec.mace or MaceStage()).model_copy(
update={"relax": "positions", "fixed_sites": sorted({*frozen})}
)
return spec.model_copy(update={"task": "opt", "mace": stage}), rows
rows.append(_require("relax_positions", spec, dim))
return spec.model_copy(update={"task": "opt"}), rows
def _record_lines(label: str, record: str) -> list[str]:
return [
"",
"# Scan-point record read back by `vibe-sketcher solid recipe analyse`.",
"import json as _json",
"",
"_converged = getattr(result, 'converged', None)",
f"with open({record!r}, 'w', encoding='utf-8') as _handle:",
" _json.dump(",
" {",
' "schema": "vibe-scan-point/1",',
f' "label": {label!r},',
' "energy_hartree": float(result.energy),',
' "converged": None if _converged is None else bool(_converged),',
' "vibeqc_version": getattr(vq, "__version__", None),',
" },",
" _handle,",
" )",
]
def _point_input(point: PeriodicStructure, spec: PeriodicJobSpec, label: str) -> InputFile:
bundle = write_periodic_input(point, spec)
file = bundle.files[0]
record = f"{label}.energy.json"
return InputFile(file.name, file.content + "\n".join(_record_lines(label, record)) + "\n",
file.media_type) # fmt: skip
def _driver(plan_name: str, points: list[dict[str, Any]]) -> InputFile:
rows = [f" ({p['label']!r}, {p['input']!r}, {p['record']!r})," for p in points]
lines = [
f'"""Run every point of {plan_name} in order and collect scan-results.json.',
"",
"Each point runs in its own interpreter; a failed point is recorded, not hidden.",
'Run: python3 run_all.py"""',
"",
"import json",
"import subprocess",
"import sys",
"import time",
"from pathlib import Path",
"",
"POINTS = [",
*rows,
"]",
"results = []",
"for label, script, record in POINTS:",
" start = time.time()",
" done = subprocess.run([sys.executable, script], capture_output=True, text=True)",
" Path(f'{label}.log').write_text(done.stdout + done.stderr, encoding='utf-8')",
" entry = {'label': label, 'returncode': done.returncode,",
" 'seconds': round(time.time() - start, 1)}",
" if Path(record).exists():",
" entry.update(json.loads(Path(record).read_text(encoding='utf-8')))",
" results.append(entry)",
" print(json.dumps(entry), flush=True)",
" Path('scan-results.json').write_text(",
f" json.dumps({{'schema': 'vibe-scan-results/1', 'plan': {plan_name!r},",
" 'points': results}, indent=2),",
" encoding='utf-8',",
" )",
]
return InputFile("run_all.py", "\n".join(lines) + "\n", "text/x-python")
def _point_id(base: str, suffix: str) -> str:
return f"{base[: 63 - len(suffix)]}{suffix}"
[docs]
def plan_volume_scan(
document: Document, recipe: VolumeScanRecipe
) -> tuple[RecipePlan, InputBundle]:
"""One input per volume at fixed fractional coordinates (or relaxed positions)."""
structure = _structure(document, recipe.structure)
if _dim(structure) != 3:
raise RecipeRefused(
"an equation of state needs a three-dimensional cell; a slab or wire changes "
"area or length, not volume"
)
spec, rows = _scan_spec(structure, recipe.spec, recipe.relax, [])
formula, z = formula_units(structure, recipe.formula_units)
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
v_input = abs(float(np.linalg.det(lattice)))
files: list[InputFile] = []
points: list[dict[str, Any]] = []
for fraction in recipe.volume_fractions:
scale = fraction ** (1.0 / 3.0)
label = _point_id(structure.id, f"-v{round(fraction * 1000):04d}")
rows_scaled = tuple(tuple(float(x) * scale for x in row) for row in lattice)
point = structure.model_copy(update={"id": label, "lattice_angstrom": rows_scaled})
point = PeriodicStructure.model_validate(point.model_dump())
file = _point_input(point, spec, label)
files.append(file)
lengths = [float(np.linalg.norm(r)) for r in np.asarray(rows_scaled)]
points.append({
"label": label,
"volume_fraction": fraction,
"linear_scale": scale,
"volume_angstrom3": v_input * fraction,
"volume_angstrom3_per_fu": v_input * fraction / z,
"lattice_lengths_angstrom": lengths,
"input": file.name,
"record": f"{label}.energy.json",
}) # fmt: skip
assumptions = [
"isotropic strain of the input cell; cell shape and angles are kept",
"fractional coordinates are fixed" if recipe.relax == "none"
else "atomic positions are relaxed in each fixed cell",
"energies are total energies per cell divided by the formula units",
"the basis set follows the atoms; no basis-set or Pulay-stress correction is applied",
] # fmt: skip
warnings: list[str] = []
if spec.model == "pbc" and spec.kpoints.kind == "gamma":
warnings.append("Gamma-only sampling: converge the k-mesh before trusting V0 or B0")
if recipe.relax == "none" and len(structure.sites) > 2:
warnings.append(
"internal coordinates are not relaxed; for structures with free Wyckoff "
"parameters use relax='positions'"
)
if spec.model in ("seccm", "aiccm"):
warnings.append(f"{spec.model.upper()} is experimental in vibe-qc")
plan = RecipePlan(
kind="volume_scan",
structure=structure.id,
status="ready",
engine=dict(caps.ENGINE),
capabilities=[r.model_dump(mode="json") for r in rows],
spec=spec.model_dump(mode="json"),
recipe=recipe.model_dump(mode="json"),
points=points,
normalisation={
"formula": formula,
"formula_units": z,
"per": "formula unit",
"composition": dict(sorted(Counter(s.symbol for s in structure.sites).items())),
"input_volume_angstrom3": v_input,
}, # fmt: skip
units={
"energy": "hartree per cell (results); eV per formula unit (fit)",
"volume": "A^3 per formula unit",
"pressure": "GPa",
"bulk_modulus": "GPa",
}, # fmt: skip
convergence=_convergence(spec),
formula="E(V) fitted with third-order Birch-Murnaghan and Vinet forms",
assumptions=assumptions,
warnings=warnings,
references=[REFERENCES["birch"], REFERENCES["vinet"], REFERENCES["monkhorst"]],
)
driver = _driver(f"{structure.id}-volume-scan", points)
files.append(driver)
plan.files = [f.name for f in files]
return plan, InputBundle("vibeqc", structure.id, tuple(files))
def _cartesian(structure: PeriodicStructure) -> np.ndarray:
return np.array([structure.cartesian(s) for s in structure.sites], dtype=float)
def _images(structure: PeriodicStructure) -> np.ndarray:
ranges = [range(-1, 2) if p else range(0, 1) for p in structure.pbc]
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
return np.array([np.array([i, j, k]) @ lattice for i in ranges[0] for j in ranges[1]
for k in ranges[2]]) # fmt: skip
def _nearest(delta: np.ndarray, images: np.ndarray) -> np.ndarray:
candidates = delta[None, :] + images
result: np.ndarray = candidates[int(np.argmin(np.linalg.norm(candidates, axis=1)))]
return result
def _min_contact(structure: PeriodicStructure) -> float:
xyz = _cartesian(structure)
images = _images(structure)
best = math.inf
for i in range(len(xyz)):
delta = xyz[None, i, :] - xyz[:, :] # (n, 3)
d = np.linalg.norm(delta[:, None, :] + images[None, :, :], axis=2)
d[i, np.all(images == 0, axis=1)] = math.inf
best = min(best, float(d.min()))
return best
[docs]
def measure(structure: PeriodicStructure, coordinate: str, sites: list[str]) -> float:
"""The minimum-image distance (A) or angle (degrees) between named sites."""
index = {s.id: i for i, s in enumerate(structure.sites)}
missing = [s for s in sites if s not in index]
if missing:
raise ValueError(f"sites not in the structure: {', '.join(missing)}")
xyz = _cartesian(structure)
images = _images(structure)
if coordinate == "distance":
if len(sites) != 2:
raise ValueError("a distance names two sites")
return float(np.linalg.norm(_nearest(xyz[index[sites[1]]] - xyz[index[sites[0]]], images)))
if len(sites) != 3:
raise ValueError("an angle names three sites, the vertex in the middle")
u = _nearest(xyz[index[sites[0]]] - xyz[index[sites[1]]], images)
w = _nearest(xyz[index[sites[2]]] - xyz[index[sites[1]]], images)
cosine = float(u @ w / (np.linalg.norm(u) * np.linalg.norm(w)))
return math.degrees(math.acos(max(-1.0, min(1.0, cosine))))
def _set_coordinate(
structure: PeriodicStructure, recipe: CoordinateScanRecipe, value: float, label: str
) -> PeriodicStructure:
index = {s.id: i for i, s in enumerate(structure.sites)}
moving = recipe.moving or [recipe.sites[-1]]
anchors = recipe.sites[:1] if recipe.coordinate == "distance" else recipe.sites[:2]
if set(moving) & set(anchors):
raise ValueError(f"the moving sites cannot include {', '.join(sorted(set(anchors)))}")
unknown = [s for s in [*recipe.sites, *moving] if s not in index]
if unknown:
raise ValueError(f"sites not in the structure: {', '.join(sorted(set(unknown)))}")
if recipe.sites[-1] not in moving:
raise ValueError(f"the moving sites must include {recipe.sites[-1]}")
xyz = _cartesian(structure)
images = _images(structure)
new = xyz.copy()
if recipe.coordinate == "distance":
if value <= 0:
raise ValueError("a target distance must be positive")
a = xyz[index[recipe.sites[0]]]
vector = _nearest(xyz[index[recipe.sites[1]]] - a, images)
length = float(np.linalg.norm(vector))
if length < 1e-8:
raise ValueError("the two sites coincide")
shift = vector / length * (value - length)
for m in moving:
new[index[m]] = xyz[index[m]] + shift
else:
if not 0 < value < 180:
raise ValueError("a target angle must be between 0 and 180 degrees")
vertex = xyz[index[recipe.sites[1]]]
u = _nearest(xyz[index[recipe.sites[0]]] - vertex, images)
w = _nearest(xyz[index[recipe.sites[2]]] - vertex, images)
axis = np.cross(u, w)
if np.linalg.norm(axis) < 1e-8 * np.linalg.norm(u) * np.linalg.norm(w):
raise ValueError("the three sites are collinear; the rotation plane is undefined")
axis = axis / np.linalg.norm(axis)
current = measure(structure, "angle", recipe.sites)
theta = math.radians(value - current)
# Rodrigues rotation about the axis through the vertex (sites moved together).
k = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]])
rotation = np.eye(3) + math.sin(theta) * k + (1 - math.cos(theta)) * (k @ k)
for m in moving:
relative = _nearest(xyz[index[m]] - vertex, images)
new[index[m]] = vertex + rotation @ relative
inverse = np.linalg.inv(np.asarray(structure.lattice_angstrom, dtype=float))
sites = [
PeriodicSite.model_validate(
{**site.model_dump(), "fractional": tuple(float(x) for x in new[i] @ inverse)}
) # fmt: skip
for i, site in enumerate(structure.sites)
]
return structure.model_copy(update={"id": label, "sites": sites})
[docs]
def plan_coordinate_scan(
document: Document, recipe: CoordinateScanRecipe
) -> tuple[RecipePlan, InputBundle]:
"""One input per target distance or angle, rigid or with the defining atoms frozen."""
structure = _structure(document, recipe.structure)
if len(structure.sites) > MAX_SCAN_SITES:
raise RecipeRefused(f"coordinate scans are limited to {MAX_SCAN_SITES} sites")
expected = 2 if recipe.coordinate == "distance" else 3
if len(recipe.sites) != expected:
raise RecipeRefused(f"a {recipe.coordinate} scan names {expected} sites")
spec, rows = _scan_spec(
structure, recipe.spec, recipe.relax, recipe.sites if recipe.relax != "none" else []
)
start = measure(structure, recipe.coordinate, recipe.sites)
unit = "angstrom" if recipe.coordinate == "distance" else "degree"
files: list[InputFile] = []
points: list[dict[str, Any]] = []
for n, value in enumerate(recipe.values):
label = _point_id(structure.id, f"-s{n:02d}")
try:
point = PeriodicStructure.model_validate(
_set_coordinate(structure, recipe, value, label).model_dump()
)
except ValueError as error:
raise RecipeRefused(str(error)) from None
reached = measure(point, recipe.coordinate, recipe.sites)
tolerance = 1e-6 if recipe.coordinate == "distance" else 1e-4
if abs(reached - value) > tolerance:
raise RecipeRefused(
f"point {n}: the minimum-image {recipe.coordinate} became {reached:.6f}, not "
f"{value:g} (the moved site found a nearer image); scan a smaller range"
)
contact = _min_contact(point)
if contact < recipe.min_contact_angstrom:
raise RecipeRefused(
f"point {n} ({value:g} {unit}) brings two atoms to {contact:.3f} A, closer "
f"than {recipe.min_contact_angstrom:g} A"
)
file = _point_input(point, spec, label)
files.append(file)
points.append({"label": label, "value": value, "unit": unit, "reached": reached,
"closest_contact_angstrom": contact, "input": file.name,
"record": f"{label}.energy.json"}) # fmt: skip
plan = RecipePlan(
kind="coordinate_scan",
structure=structure.id,
status="ready",
engine=dict(caps.ENGINE),
capabilities=[r.model_dump(mode="json") for r in rows],
spec=spec.model_dump(mode="json"),
recipe=recipe.model_dump(mode="json"),
points=points,
normalisation={"per": "cell", "start_value": start},
units={"energy": "hartree per cell", "coordinate": unit},
convergence=_convergence(spec),
formula=f"E({recipe.coordinate} {'-'.join(recipe.sites)}) at fixed cell",
assumptions=[
"minimum-image coordinate; the cell is fixed",
"rigid points: only the moving sites change"
if recipe.relax == "none"
else "relaxed points: the defining sites are frozen, every other atom relaxes",
f"moving sites: {', '.join(recipe.moving or [recipe.sites[-1]])}",
], # fmt: skip
warnings=["unconverged forces are not reported per point; check each point's .out"]
if recipe.relax != "none"
else [], # fmt: skip
)
files.append(_driver(f"{structure.id}-{recipe.coordinate}-scan", points))
plan.files = [f.name for f in files]
return plan, InputBundle("vibeqc", structure.id, tuple(files))
[docs]
def standard_mass(symbol: str) -> float:
"""The standard atomic weight in amu (RDKit's IUPAC table)."""
from rdkit import Chem
return float(Chem.GetPeriodicTable().GetAtomicWeight(symbol))
[docs]
def plan_phonons(document: Document, recipe: PhononRecipe) -> tuple[RecipePlan, InputBundle]:
"""A finite-displacement supercell plan; execution refused while the engine lacks it."""
structure = _structure(document, recipe.structure)
dim = _dim(structure)
if recipe.hessian_source == "molecular-gamma":
raise RecipeRefused(
"a Gamma-only Hessian of the unit cell computed as a molecule is not a phonon "
"spectrum: it has no periodic images, no q-dispersion and no acoustic sum rule of "
"the crystal. Plan periodic-supercell force constants instead"
)
for axis in range(3):
if not structure.pbc[axis] and (recipe.supercell[axis] != 1 or recipe.q_mesh[axis] != 1):
raise RecipeRefused("supercell and q-mesh must be 1 along nonperiodic directions")
unknown = sorted(set(recipe.masses) - {s.symbol for s in structure.sites})
if unknown:
raise RecipeRefused(f"mass overrides for elements not in the cell: {', '.join(unknown)}")
n = len(structure.sites)
cells = int(np.prod(recipe.supercell))
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
super_lengths = [float(np.linalg.norm(lattice[i]) * recipe.supercell[i]) for i in range(3)
if structure.pbc[i]] # fmt: skip
displacements = [
{"site": site.id, "axis": "xyz"[axis], "sign": sign,
"amplitude_angstrom": recipe.displacement_angstrom}
for site in structure.sites for axis in range(3) for sign in (1, -1)
] # fmt: skip
masses = {
symbol: {"amu": recipe.masses.get(symbol, standard_mass(symbol)),
"source": "override" if symbol in recipe.masses
else "standard atomic weight (IUPAC, RDKit table)"}
for symbol in sorted({s.symbol for s in structure.sites})
} # fmt: skip
warnings: list[str] = []
if cells == 1:
warnings.append(
"a 1x1x1 supercell gives exact force constants only at Gamma; every other q of "
"the mesh would be an uncontrolled interpolation"
)
if super_lengths and min(super_lengths) < 10.0:
warnings.append(
f"the shortest supercell vector is {min(super_lengths):.2f} A; force constants "
"usually need 10 A or more"
)
if recipe.q_mesh == (1, 1, 1):
warnings.append("Gamma-only q sampling: zone-centre modes only, no dispersion")
report = caps.refusal("phonons", recipe.spec.model, dim)
plan = RecipePlan(
kind="phonons",
structure=structure.id,
status="refused",
engine=dict(caps.ENGINE),
capabilities=report["rows"],
spec=recipe.spec.model_dump(mode="json"),
recipe=recipe.model_dump(mode="json"),
points=displacements,
normalisation={
"atoms_per_cell": n,
"supercell": list(recipe.supercell),
"cells_in_supercell": cells,
"atoms_per_supercell": n * cells,
"commensurate_q_points": cells,
"displacements": len(displacements),
"single_points": len(displacements) + 1,
"supercell_lengths_angstrom": super_lengths,
"masses": masses,
},
units={
"displacement": "angstrom",
"mass": "amu",
"frequency": "cm^-1",
"q_mesh": "reciprocal-lattice divisions",
}, # fmt: skip
convergence={
**_convergence(recipe.spec),
"q_mesh": list(recipe.q_mesh),
"displacement_amplitude_angstrom": recipe.displacement_angstrom,
"acoustic_sum_rule": recipe.acoustic_sum_rule,
"symmetry_reduction": "none: every atom along +-x, +-y, +-z",
}, # fmt: skip
formula="Phi_ij = -[F_j(+u_i) - F_j(-u_i)] / (2 u); D(q) = sum_R Phi(0, R) "
"exp(i q R) / sqrt(M_i M_j)",
assumptions=[
"harmonic force constants from central differences of the forces",
"fixed cell; the supercell is the input cell repeated along its lattice vectors",
],
warnings=warnings,
refusal=report,
references=[REFERENCES["parlinski"], REFERENCES["togo"]],
)
return plan, InputBundle("vibeqc", structure.id, ())
OMITTED_TERMS: dict[str, list[dict[str, str]]] = {
"harmonic": [
{"term": "thermal expansion", "why": "the volume is fixed; F(T) at V_input only"},
{"term": "anharmonic phonon-phonon coupling", "why": "harmonic force constants"},
{"term": "electronic thermal excitation", "why": "T = 0 electronic energy (no "
"Mermin entropy); matters for metals and small-gap systems"},
{"term": "configurational entropy", "why": "one ordered structure; no disorder, "
"defect or site-mixing entropy"},
{"term": "magnetic entropy", "why": "one spin configuration"},
{"term": "pV", "why": "Helmholtz energy at fixed volume; no pressure term"},
],
"quasi-harmonic": [
{"term": "explicit anharmonicity", "why": "phonons are harmonic at each volume; "
"only their volume dependence is kept"},
{"term": "electronic thermal excitation", "why": "T = 0 electronic energy at each "
"volume (no Mermin entropy)"},
{"term": "configurational entropy", "why": "one ordered structure"},
{"term": "magnetic entropy", "why": "one spin configuration"},
{"term": "anisotropic thermal strain", "why": "isotropic volume grid; the cell "
"shape does not relax with temperature"},
],
} # fmt: skip
[docs]
def plan_free_energy(
document: Document, recipe: FreeEnergyRecipe
) -> tuple[RecipePlan, InputBundle]:
"""A harmonic or quasi-harmonic free-energy recipe, gated with the phonons."""
structure = _structure(document, recipe.structure)
phonons = recipe.phonons or PhononRecipe(structure=recipe.structure, spec=recipe.spec)
if phonons.structure != recipe.structure:
raise RecipeRefused("the phonon recipe must name the same structure")
if recipe.approximation == "quasi-harmonic":
if _dim(structure) != 3:
raise RecipeRefused("a quasi-harmonic F(V, T) needs a three-dimensional cell")
VolumeScanRecipe(structure=recipe.structure, volume_fractions=recipe.volume_fractions)
elif recipe.pressures_gpa != [0.0]:
raise RecipeRefused("pressures belong to the quasi-harmonic G(T, p)")
phonon_plan, _ = plan_phonons(document, phonons)
formula_text, z = formula_units(structure)
report = caps.refusal("free_energy", recipe.spec.model, _dim(structure))
report["reasons"] = [*report["reasons"], *phonon_plan.refusal["reasons"]] if (
phonon_plan.refusal) else report["reasons"] # fmt: skip
if recipe.approximation == "harmonic":
formula = ("F(T) = E_el + sum_q,nu w_q [hbar omega / 2 + k_B T ln(1 - exp(-hbar omega "
"/ k_B T))]") # fmt: skip
else:
formula = ("G(T, p) = min_V [E_el(V) + F_vib(V, T) + p V], F_vib per volume as in the "
"harmonic form; the minimum from an EOS fit of F(V) at each T") # fmt: skip
plan = RecipePlan(
kind="free_energy",
structure=structure.id,
status="refused",
engine=dict(caps.ENGINE),
capabilities=report["rows"],
spec=recipe.spec.model_dump(mode="json"),
recipe=recipe.model_dump(mode="json"),
points=[{"volume_fraction": f} for f in recipe.volume_fractions]
if recipe.approximation == "quasi-harmonic"
else [{"volume_fraction": 1.0}],
normalisation={
"formula": formula_text,
"formula_units": z,
"per": "formula unit",
"phonons": phonon_plan.normalisation,
}, # fmt: skip
units={
"energy": "eV per formula unit",
"temperature": "K",
"pressure": "GPa",
"entropy": "eV/K per formula unit",
}, # fmt: skip
convergence={
**phonon_plan.convergence,
"temperatures_k": recipe.temperatures_k,
"pressures_gpa": recipe.pressures_gpa,
}, # fmt: skip
formula=formula,
assumptions=[
"zero-point energy is included in F_vib",
"the three acoustic modes at Gamma are excluded (zero frequency)",
"any imaginary mode invalidates the free energy; it is refused, not dropped",
],
warnings=phonon_plan.warnings,
omitted_terms=OMITTED_TERMS[recipe.approximation],
refusal=report,
references=[REFERENCES["togo"], REFERENCES["parlinski"]]
+ (
[REFERENCES["birch"], REFERENCES["vinet"]]
if recipe.approximation == "quasi-harmonic"
else []
), # fmt: skip
)
return plan, InputBundle("vibeqc", structure.id, ())
[docs]
def harmonic_free_energy(
frequencies_cm1: list[float],
temperature_k: float,
weights: list[float] | None = None,
*,
zero_tolerance_cm1: float = 1e-3,
imaginary_tolerance_cm1: float = 1e-3,
) -> dict[str, Any]:
"""Harmonic vibrational F, ZPE, S and C_V from explicit frequencies (Togo and Tanaka 2015).
Frequencies are in cm^-1 with q-point weights (normalised to sum 1); an
imaginary mode (given as a negative frequency) is refused, zero modes are
counted and excluded. The energies are per cell of the frequencies.
"""
omega = np.asarray(frequencies_cm1, dtype=float)
w = np.ones_like(omega) if weights is None else np.asarray(weights, dtype=float)
if omega.shape != w.shape or omega.ndim != 1 or omega.size == 0:
raise ValueError("give one weight per frequency")
if not (np.all(np.isfinite(omega)) and np.all(np.isfinite(w)) and np.all(w >= 0)):
raise ValueError("frequencies and weights must be finite, weights non-negative")
if temperature_k < 0 or not math.isfinite(temperature_k):
raise ValueError("the temperature must be finite and non-negative")
imaginary = omega[omega < -imaginary_tolerance_cm1]
if imaginary.size:
raise ValueError(
f"{imaginary.size} imaginary mode(s) (lowest {imaginary.min():.2f} cm^-1): the "
"structure is not a minimum and has no harmonic free energy"
)
if weights is not None:
total = float(w.sum())
if total <= 0:
raise ValueError("weights must not all be zero")
modes_per_q = None
else:
total = 1.0
modes_per_q = omega.size
keep = omega > zero_tolerance_cm1
energy = omega[keep] / EV_TO_CM1 # eV
weight = w[keep] / total
zpe = float(np.sum(weight * energy) / 2)
if temperature_k == 0:
free = zpe
entropy = 0.0
heat = 0.0
else:
x = energy / (KB_EV * temperature_k)
free = zpe + float(np.sum(weight * KB_EV * temperature_k * np.log1p(-np.exp(-x))))
entropy = float(np.sum(weight * KB_EV * (x / np.expm1(x) - np.log1p(-np.exp(-x)))))
heat = float(np.sum(weight * KB_EV * x**2 * np.exp(x) / np.expm1(x) ** 2))
return {
"temperature_k": temperature_k,
"zero_point_energy_ev": zpe,
"free_energy_ev": free,
"entropy_ev_per_k": entropy,
"heat_capacity_ev_per_k": heat,
"modes_used": int(keep.sum()),
"zero_modes_excluded": int((~keep).sum()),
"modes_per_q": modes_per_q,
}
[docs]
def plan(document: Document, recipe: Recipe) -> tuple[RecipePlan, InputBundle]:
"""Dispatch a recipe to its planner."""
if isinstance(recipe, VolumeScanRecipe):
return plan_volume_scan(document, recipe)
if isinstance(recipe, CoordinateScanRecipe):
return plan_coordinate_scan(document, recipe)
if isinstance(recipe, PhononRecipe):
return plan_phonons(document, recipe)
return plan_free_energy(document, recipe)
[docs]
def plan_or_refusal(document: Document, data: dict[str, Any]) -> dict[str, Any]:
"""Plan a recipe dictionary; a refusal comes back as data, not an exception."""
try:
recipe = parse_recipe(data)
made, bundle = plan(document, recipe)
except WriterRefusal as error:
return {"status": "refused", "reasons": list(error.reasons), "report": None}
except RecipeRefused as error:
return {"status": "refused", "reasons": [str(error)], "report": error.report or None}
return {
"status": made.status,
"plan": made.model_dump(mode="json", by_alias=True),
"files": [{"name": f.name, "content": f.content, "media_type": f.media_type}
for f in bundle.files],
} # fmt: skip
[docs]
def eos_table(
plan_: RecipePlan,
results: dict[str, Any] | None = None,
qvfs: dict[str, bytes] | None = None,
*,
drop_unconverged: bool = False,
) -> Any:
"""An :class:`~vibesketcher.document.eos.EosTable` from a volume-scan plan and its results.
``results`` is a ``scan-results.json`` written by the plan's driver;
``qvfs`` maps point labels to result QVFs. Every planned point needs one.
"""
from vibesketcher.document.eos import EosPoint, EosTable
if plan_.kind != "volume_scan":
raise ValueError("an EOS table comes from a volume_scan plan")
found: dict[str, dict[str, Any]] = {}
if results is not None:
if results.get("schema") != "vibe-scan-results/1":
raise ValueError("not a vibe-scan-results/1 file")
for entry in results.get("points", []):
if not isinstance(entry, dict) or "label" not in entry:
continue
if "energy_hartree" not in entry:
raise ValueError(
f"point {entry['label']} has no energy (return code "
f"{entry.get('returncode')}); see its .log"
)
found[str(entry["label"])] = {
"energy_hartree": float(entry["energy_hartree"]),
"converged": entry.get("converged"),
"vibeqc_version": entry.get("vibeqc_version"),
}
if qvfs:
from vibesketcher.document.solid_energetics import _read_result
composition = plan_.normalisation.get("composition")
for label, data in qvfs.items():
result = _read_result(data)
if result["formula"] is not None and composition and result["formula"] != composition:
raise ValueError(
f"the {label} result is {result['formula']}, not the planned {composition}"
)
found[label] = {
"energy_hartree": result["energy_hartree"],
"converged": True,
"vibeqc_version": result["vibeqc"].get("version"),
}
missing = [p["label"] for p in plan_.points if p["label"] not in found]
if missing:
raise ValueError(f"results missing for {', '.join(missing)}")
settings = {
"model": plan_.spec.get("model"),
"method": plan_.spec.get("method"),
"basis": plan_.spec.get("basis"),
"kpoints": json.dumps(plan_.spec.get("kpoints"), sort_keys=True),
}
points = [
EosPoint(
volume_angstrom3=float(p["volume_angstrom3"]),
energy_hartree=found[p["label"]]["energy_hartree"],
converged=found[p["label"]]["converged"],
label=p["label"],
settings={**settings, "vibeqc_version": found[p["label"]]["vibeqc_version"]},
)
for p in plan_.points
]
return EosTable(
formula=str(plan_.normalisation.get("formula")),
formula_units=int(plan_.normalisation.get("formula_units", 1)),
points=points,
drop_unconverged=drop_unconverged,
)