|
| 1 | +"""Cross-platform DFT-D3 backend compatibility.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +from importlib import import_module |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +from pyscf import gto |
| 9 | + |
| 10 | +_USE_PYSCF_DISPERSION = sys.platform == "linux" |
| 11 | +_backend_module = import_module( |
| 12 | + "pyscf.dispersion.dftd3" if _USE_PYSCF_DISPERSION else "dftd3.pyscf" |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class DFTD3Dispersion: |
| 17 | + """Normalize the DFT-D3 APIs available on supported platforms.""" |
| 18 | + |
| 19 | + def __init__(self, mol: gto.Mole, xc: str): |
| 20 | + self._xc = xc |
| 21 | + self._backend: Any = _backend_module.DFTD3Dispersion(mol, xc) |
| 22 | + |
| 23 | + def get_energy(self) -> float: |
| 24 | + """Return the dispersion energy as a Python scalar.""" |
| 25 | + if _USE_PYSCF_DISPERSION: |
| 26 | + energy = self._backend.get_dispersion()["energy"] |
| 27 | + else: |
| 28 | + energy = self._backend.kernel()[0] |
| 29 | + return float(np.asarray(energy).item()) |
| 30 | + |
| 31 | + def get_gradient(self) -> np.ndarray: |
| 32 | + """Return the dispersion nuclear gradient.""" |
| 33 | + if _USE_PYSCF_DISPERSION: |
| 34 | + gradient = self._backend.get_dispersion(grad=True)["gradient"] |
| 35 | + else: |
| 36 | + gradient = self._backend.kernel()[1] |
| 37 | + return np.asarray(gradient) |
| 38 | + |
| 39 | + def reset(self, mol: gto.Mole) -> "DFTD3Dispersion": |
| 40 | + """Reset the backend for a new molecular geometry.""" |
| 41 | + self._backend = _backend_module.DFTD3Dispersion(mol, self._xc) |
| 42 | + return self |
0 commit comments