vibe-sketcherDocumentation
Source code for vibesketcher.document.core_potentials
"""Explicit heavy-element basis, core-potential and scalar-relativistic contracts (#242).
A job specification states, per element, the orbital basis set and either a
named effective core potential (ECP) with the number of core electrons it
replaces, or an all-electron treatment, together with one Hamiltonian for
the molecule: ``nonrelativistic`` (scalar relativity, if any, carried by the
ECPs) or a scalar-relativistic all-electron Hamiltonian, ``zora`` or
``dkh2``. Nothing here infers a core potential from an element label: the
tables only decide whether a stated choice is consistent, and refuse it,
with the reason, when it is not or when the table does not know it.
Sources of the tables:
- def2-ECP core sizes and per-element sources: Weigend and Ahlrichs,
Phys. Chem. Chem. Phys. 7, 3297 (2005), doi:10.1039/B508541A, section 2:
ECP-28 for Rb-Xe, ECP-46 for Cs, Ba, La and ECP-60 for Hf-Rn; the
lanthanides Ce-Lu are excluded there and are not admitted here. Y-Cd
and Hf-Hg use Andrae et al., Theor. Chim. Acta 77, 123 (1990),
doi:10.1007/BF01114537; In-Sb and Tl-Bi use Metz, Stoll and Dolg,
J. Chem. Phys. 113, 2563 (2000), doi:10.1063/1.1305880.
- ZORA: van Lenthe, Baerends and Snijders, J. Chem. Phys. 99, 4597 (1993),
doi:10.1063/1.466059. DKH2: Hess, Phys. Rev. A 33, 3742 (1986),
doi:10.1103/PhysRevA.33.3742.
- SARC all-electron scalar-relativistic basis sets: Pantazis, Chen, Landis
and Neese, J. Chem. Theory Comput. 4, 908 (2008), doi:10.1021/ct800047t
(Hf-Hg, and the ZORA/DKH recontractions of def2 for H-Kr); Pantazis and
Neese, Theor. Chem. Acc. 131, 1292 (2012), doi:10.1007/s00214-012-1292-x
(Tl-Rn).
The module is standard library only, so the document model can use it.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Final, Literal
from vibesketcher.document.model import JobSpec, Species
from vibesketcher.elements import ATOMIC_NUMBER, SYMBOLS
__all__ = [
"HEAVY_ELEMENT_Z",
"EcpData",
"atom_treatments",
"contract_active",
"contract_record",
"contract_refusals",
"core_potential_table",
"ecp_data",
"electron_accounting",
"recorded_core_refusals",
"stale_entries",
]
#: Elements beyond this atomic number (Kr) need an explicit contract in recipes.
HEAVY_ELEMENT_Z: Final = 36
BasisKind = Literal["nonrelativistic", "def2-valence", "zora", "dkh2"]
[docs]
@dataclass(frozen=True)
class EcpData:
"""One named ECP family: the core it replaces per element, and its sources."""
name: str
cores: dict[int, int]
references: dict[int, str]
pairs_with: str
[docs]
def record(self, z: int) -> dict[str, Any]:
return {
"name": self.name,
"core_electrons": self.cores[z],
"reference": self.references[z],
"table": "Weigend and Ahlrichs (2005), doi:10.1039/B508541A, section 2",
}
def _span(first: str, last: str) -> range:
return range(ATOMIC_NUMBER[first], ATOMIC_NUMBER[last] + 1)
_WA2005 = "Weigend and Ahlrichs (2005), doi:10.1039/B508541A"
_ANDRAE = "Andrae et al. (1990), doi:10.1007/BF01114537"
_METZ = "Metz, Stoll and Dolg (2000), doi:10.1063/1.1305880"
def _def2_ecp() -> EcpData:
cores: dict[int, int] = {}
references: dict[int, str] = {}
for z in [*_span("Rb", "Xe"), *_span("Cs", "La"), *_span("Hf", "Rn")]:
cores[z] = 28 if z <= ATOMIC_NUMBER["Xe"] else 46 if z <= ATOMIC_NUMBER["La"] else 60
references[z] = _WA2005
for z in [*_span("Y", "Cd"), *_span("Hf", "Hg")]:
references[z] = _ANDRAE
for z in [*_span("In", "Sb"), *_span("Tl", "Bi")]:
references[z] = _METZ
return EcpData("def2-ECP", cores, references, "def2")
#: ECPs by lower-case name.
_ECPS: Final[dict[str, EcpData]] = {"def2-ecp": _def2_ecp()}
_DEF2 = re.compile(r"^def2-(sv\(p\)|svpd?|tzvpp?d?|qzvpp?d?)$")
_RECONTRACTED = re.compile(r"^(zora|dkh)-def2-(svp|tzvpp?|qzvpp?)$")
_SARC = re.compile(r"^sarc-(zora|dkh)-(svp|tzvpp?)$")
#: All-electron nonrelativistic sets for H-Kr (their names, lower case).
_LIGHT_ALL_ELECTRON = re.compile(
r"^(sto-[36]g|3-21g|6-31\+{0,2}g(\*{1,2}|\(d(,p)?\))?|6-311\+{0,2}g(\*{1,2}|\(d(,p)?\)|\(2d,p\))?"
r"|(aug-)?cc-p(w?c)?v[dtq56]z|(aug-)?pc(seg)?-[0-4])$"
)
_SARC_ELEMENTS: Final = frozenset(_span("Hf", "Rn"))
_RELATIVITY_REFERENCES: Final = {
"zora": "van Lenthe, Baerends and Snijders (1993), doi:10.1063/1.466059",
"dkh2": "Hess (1986), doi:10.1103/PhysRevA.33.3742",
}
_SARC_REFERENCES: Final = {
"5d": "Pantazis et al. (2008), doi:10.1021/ct800047t",
"6p": "Pantazis and Neese (2012), doi:10.1007/s00214-012-1292-x",
}
[docs]
def ecp_data(name: str) -> EcpData | None:
"""The table entry for an ECP name (case-insensitive), or ``None``."""
return _ECPS.get(name.lower())
def basis_kind(basis: str, z: int) -> BasisKind | None:
"""What ``basis`` is on element ``z``, or ``None`` when the table does not know.
``def2-valence`` is a def2 set on Rb-Rn, valence-only and paired with the
def2-ECP; ``zora``/``dkh2`` are all-electron sets contracted for that
Hamiltonian.
"""
name = basis.lower()
heavy = z > HEAVY_ELEMENT_Z
if _DEF2.match(name):
if not heavy:
return "nonrelativistic"
return "def2-valence" if z in _ECPS["def2-ecp"].cores else None
if match := _RECONTRACTED.match(name):
return None if heavy else ("zora" if match.group(1) == "zora" else "dkh2")
if match := _SARC.match(name):
if z not in _SARC_ELEMENTS:
return None
return "zora" if match.group(1) == "zora" else "dkh2"
if not heavy and _LIGHT_ALL_ELECTRON.match(name):
return "nonrelativistic"
return None
[docs]
def contract_active(spec: JobSpec) -> bool:
"""Whether the specification states a basis/core/Hamiltonian contract."""
return spec.relativity is not None or bool(spec.element_basis)
def _elements(species: Species) -> list[str]:
if not species.conformers:
return []
return sorted(set(species.conformers[0].symbols), key=ATOMIC_NUMBER.__getitem__)
[docs]
def atom_treatments(species: Species, spec: JobSpec) -> dict[str, dict[str, Any]]:
"""Per element of the species: its basis and ECP as the specification states them."""
entries = {e.element: e for e in spec.element_basis or []}
treatments: dict[str, dict[str, Any]] = {}
for symbol in _elements(species):
entry = entries.get(symbol)
basis = entry.basis if entry is not None else spec.basis
ecp = entry.ecp if entry is not None else None
treatments[symbol] = {
"explicit": entry is not None,
"basis": basis,
"ecp": None if ecp is None else ecp.model_dump(exclude_none=True),
}
return treatments
[docs]
def contract_refusals(species: Species, spec: JobSpec, *, require: bool = False) -> list[str]:
"""Why the stated contract is inconsistent for ``species``; empty if it holds.
``require`` (recipes) demands the contract, with an explicit entry for
every element beyond Kr, instead of leaving an absent one to the writer.
"""
elements = _elements(species)
heavy = [s for s in elements if ATOMIC_NUMBER[s] > HEAVY_ELEMENT_Z]
if not contract_active(spec):
if require and heavy:
return [
f"{', '.join(heavy)} need an explicit ECP/relativistic contract: state "
"relativity and an element_basis entry (basis and ecp or all-electron) for "
"each element beyond Kr; refusing this model rather than assuming one"
]
return []
reasons: list[str] = []
relativity = spec.relativity
if relativity is None:
return ["element_basis needs an explicit relativity choice"]
entries = {e.element: e for e in spec.element_basis or []}
missing = [s for s in heavy if s not in entries]
if missing:
reasons.append(
f"{', '.join(missing)}: elements beyond Kr need an explicit element_basis entry "
"(basis and ecp or all-electron); none is inferred from the element"
)
treatments = atom_treatments(species, spec)
for symbol in elements:
z = ATOMIC_NUMBER[symbol]
treatment = treatments[symbol]
basis = treatment["basis"]
if basis is None:
reasons.append(f"{symbol} has no basis set: set basis or an element_basis entry")
continue
kind = basis_kind(basis, z)
ecp = entries[symbol].ecp if symbol in entries else None
if kind is None:
reasons.append(
f"vibe-sketcher's core-potential table does not know {basis!r} on {symbol}; "
"it cannot tell whether that basis is all-electron or valence-only"
)
continue
if ecp is not None:
data = ecp_data(ecp.name)
if data is None:
known = ", ".join(e.name for e in _ECPS.values())
reasons.append(f"{symbol}: unknown ECP {ecp.name!r}; known: {known}")
elif z not in data.cores:
reasons.append(f"{symbol}: {data.name} defines no potential for {symbol}")
elif ecp.core_electrons != data.cores[z]:
reasons.append(
f"{symbol}: {data.name} replaces {data.cores[z]} core electrons, not "
f"{ecp.core_electrons}"
)
elif kind != "def2-valence" or data.pairs_with != "def2":
reasons.append(f"{symbol}: {data.name} does not pair with basis {basis!r}")
elif kind == "def2-valence":
reasons.append(
f"{symbol}: {basis} is valence-only on {symbol} and needs its def2-ECP "
f"({_ECPS['def2-ecp'].cores[z]} core electrons); an all-electron run in a "
"valence basis is refused"
)
if kind in ("zora", "dkh2") and kind != relativity:
reasons.append(
f"{symbol}: {basis} is contracted for {kind.upper()}, not a "
f"{relativity} Hamiltonian"
)
if relativity in ("zora", "dkh2") and kind != relativity:
reasons.append(
f"{symbol}: a {relativity.upper()} calculation needs a {relativity.upper()}-"
f"contracted all-electron basis on every element, not {basis!r}"
)
accounting = electron_accounting(species, spec)
if accounting is not None and accounting["valence_electrons"] < 1:
reasons.append(f"{species.id}: the core potentials leave no explicit electrons")
return reasons
[docs]
def stale_entries(spec: JobSpec, species: list[Species]) -> list[str]:
"""Elements ``element_basis`` names that none of ``species`` contains."""
present = {s for entry in species for s in _elements(entry)}
return [e.element for e in spec.element_basis or [] if e.element not in present]
[docs]
def electron_accounting(species: Species, spec: JobSpec) -> dict[str, Any] | None:
"""Nuclear charge, electrons, ECP core electrons and explicit electrons of a species."""
if not species.conformers:
return None
symbols = species.conformers[0].symbols
entries = {e.element: e for e in spec.element_basis or []}
core = 0
for symbol in symbols:
entry = entries.get(symbol)
if entry is not None and entry.ecp is not None:
core += entry.ecp.core_electrons
nuclear = sum(ATOMIC_NUMBER[s] for s in symbols)
electrons = nuclear - species.charge
return {
"species": species.id,
"nuclear_charge": nuclear,
"charge": species.charge,
"multiplicity": species.multiplicity,
"electrons": electrons,
"ecp_core_electrons": core,
"valence_electrons": electrons - core,
"effective_nuclear_charge": nuclear - core,
}
[docs]
def contract_record(spec: JobSpec, species: list[Species]) -> dict[str, Any] | None:
"""The provenance of a stated contract, for reports; ``None`` if none is stated."""
if not contract_active(spec):
return None
elements: dict[str, dict[str, Any]] = {}
for entry in species:
for symbol, treatment in atom_treatments(entry, spec).items():
z = ATOMIC_NUMBER[symbol]
row: dict[str, Any] = {"element": symbol, "z": z, **treatment}
if treatment["ecp"] is not None:
data = ecp_data(treatment["ecp"]["name"])
assert data is not None # refusals ran first
row["ecp"] = {**treatment["ecp"], **data.record(z)}
row["treatment"] = "ecp"
else:
row["treatment"] = "all-electron"
kind = basis_kind(row["basis"] or "", z)
if kind in ("zora", "dkh2") and z in _SARC_ELEMENTS:
shell = "5d" if z <= ATOMIC_NUMBER["Hg"] else "6p"
row["basis_reference"] = _SARC_REFERENCES[shell]
elements[symbol] = row
relativity = spec.relativity
return {
"relativity": relativity,
"relativity_reference": _RELATIVITY_REFERENCES.get(relativity or ""),
"elements": [elements[s] for s in sorted(elements, key=ATOMIC_NUMBER.__getitem__)],
"electrons": [a for a in (electron_accounting(s, spec) for s in species) if a],
"spin_orbit": "not included",
}
#: Electrons a summed occupation may differ from an integer count by (QVF § 5.3 allows 1e-6).
_OCCUPATION_SLACK: Final = 1e-6
[docs]
def recorded_core_refusals(
species: Species,
spec: JobSpec,
*,
physical_electrons: int | None,
explicit_electrons: list[float],
centres: list[dict[int, int]],
) -> list[str]:
"""Why the cores a result records disagree with the stated contract; empty if they agree.
The evidence is what a QVF result can record (QVF spec § 5.3,
``wavefunction.gto``): ``physical_electrons``, all of the species'
electrons before any core is removed (``provenance.n_electrons``);
``explicit_electrons``, the electrons each canonical wavefunction
describes (its basis ``n_electrons``, or its summed occupations); and
``centres``, per wavefunction with a basis ``ecp`` list, the replaced core
electrons by 0-based atom index. The difference between the first two is
the total the core potentials replaced. A result with neither kind of
evidence is refused: the contract could not be checked.
"""
accounting = electron_accounting(species, spec)
if accounting is None:
return [f"{species.id} has no geometry to count electrons on"]
reasons: list[str] = []
electrons, core = accounting["electrons"], accounting["ecp_core_electrons"]
if physical_electrons is not None and physical_electrons != electrons:
reasons.append(
f"the result counts {physical_electrons} electrons before core removal; "
f"{species.id} has {electrons}"
)
if not explicit_electrons and not centres:
reasons.append(
"the result records neither its core potentials (QVF basis ecp) nor its "
"orbital occupations, so the stated core-potential contract cannot be checked"
)
for described in explicit_electrons:
if abs(described - accounting["valence_electrons"]) > _OCCUPATION_SLACK:
reasons.append(
f"the result's wavefunction describes {described:g} of {electrons} electrons, "
f"so its core potentials replaced {electrons - described:g}; the contract "
f"replaces {core} and leaves {accounting['valence_electrons']}"
)
cores = {e.element: e.ecp.core_electrons for e in spec.element_basis or [] if e.ecp}
symbols = species.conformers[0].symbols
stated = [cores.get(s, 0) for s in symbols]
for recorded in centres:
outside = sorted(i for i in recorded if not 0 <= i < len(symbols))
if outside:
reasons.append(f"the result puts core potentials on atoms it does not have: {outside}")
for i, (symbol, want) in enumerate(zip(symbols, stated, strict=True)):
got = recorded.get(i, 0)
if got != want:
states = f"{want} core electrons" if want else "an all-electron treatment"
reasons.append(
f"atom {i + 1} ({symbol}): the result's core potential replaces {got} "
f"electrons; the contract states {states}"
)
return list(dict.fromkeys(reasons))
[docs]
def core_potential_table() -> dict[str, Any]:
"""The ECPs, basis families and Hamiltonians the contract admits, for review."""
return {
"ecps": [
{
"name": data.name,
"pairs_with": f"{data.pairs_with} orbital basis sets",
"cores": {SYMBOLS[z - 1]: n for z, n in sorted(data.cores.items())},
"references": sorted(set(data.references.values())),
}
for data in _ECPS.values()
],
"relativity": {
"nonrelativistic": "no relativistic Hamiltonian; scalar relativity through ECPs",
**_RELATIVITY_REFERENCES,
},
"basis_families": {
"def2-*": "all-electron H-Kr; valence-only Rb-Xe, Cs-La, Hf-Rn with def2-ECP",
"ZORA-def2-*, DKH-def2-*": "all-electron H-Kr for that Hamiltonian",
"SARC-ZORA-*, SARC-DKH-*": "all-electron Hf-Rn for that Hamiltonian",
},
"heavy_element_z": HEAVY_ELEMENT_Z,
"not_included": ["spin-orbit coupling", "lanthanide def2-ECP", "per-atom overrides"],
}