Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 109 additions & 9 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -263,15 +263,115 @@ to skip it under ``torch.compile`` (also with ``fullgraph=True``), give
.. code:: python

param = {"a1": a1, "a2": a2, "s8": s8, "s9": 0.0} # no three-body term
energy = torch.compile(d3.dftd3)(numbers, positions, param)
energy = torch.compile(d3.dftd3)(structure, param)

The parameter loader in ``tad_dftd3.param`` returns tensors, so overwrite
``param["s9"]`` with a Python number (or delete it) to get the same effect.


Periodic systems
----------------

Give the ``Structure`` lattice vectors (as rows, in Bohr) to treat the system
as a periodic cell. The coordination number and the two-body energy then sum over all
periodic images within their cutoffs, as in s-dftd3. ``periodic`` (default: all
three axes) selects the periodic axes of a slab or chain, and atoms need not
lie inside the cell. Forces and the stress follow from one backward pass:

.. code:: python

import torch
import tad_dftd3 as d3
import tad_mctc as mctc

# diamond, conventional cubic cell
numbers = mctc.convert.symbol_to_number(symbols=8 * ["C"])
fractional = torch.tensor(
[
[0.00, 0.00, 0.00],
[0.00, 0.50, 0.50],
[0.50, 0.00, 0.50],
[0.50, 0.50, 0.00],
[0.25, 0.25, 0.25],
[0.25, 0.75, 0.75],
[0.75, 0.25, 0.75],
[0.75, 0.75, 0.25],
],
dtype=torch.double,
)
lattice = 6.7406 * torch.eye(3, dtype=torch.double)
positions = (fractional @ lattice).requires_grad_(True)
lattice.requires_grad_(True)
param = { # PBE-D3(BJ)
"a1": torch.tensor(0.4289, dtype=torch.double),
"s8": torch.tensor(0.7875, dtype=torch.double),
"a2": torch.tensor(4.4407, dtype=torch.double),
}

structure = mctc.Structure(numbers=numbers, positions=positions, lattice=lattice)
energy = d3.dftd3(structure, param)
print(f"{energy.sum():.10f}")
# -0.0562022045

grad_pos, grad_lat = torch.autograd.grad(energy.sum(), (positions, lattice))
virial = positions.mT @ grad_pos + lattice.mT @ grad_lat
stress = virial / torch.linalg.det(lattice)

Which images lie within a cutoff depends on the values of the lattice, so by
default the image shifts are built anew on each call. Under ``torch.compile``
(``fullgraph=True``), ``vmap`` over cells, or ``jacrev``/``jacfwd`` with
respect to the lattice, build them once beforehand, at the larger of the
coordination-number and two-body cutoffs, and pass them as ``shifts``:

.. code:: python

from tad_mctc.neighbor.images import build_periodic_shifts

cutoff = d3.Cutoff()
shifts = build_periodic_shifts(
structure.lattice.detach(), structure.periodic, max(cutoff.cn, cutoff.disp2)
)

def total(pos, lat):
cell = structure.replace(positions=pos, lattice=lat)
return d3.dftd3(cell, param, shifts=shifts).sum()

compiled = torch.compile(total, fullgraph=True)
grad_lat = torch.func.jacrev(total, argnums=1)(positions, lattice)

For a batch of cells, build one table from the stacked lattices; it covers
every cell of the batch. Under ``vmap`` over a batched ``Structure``, every
field is split per system, so give each system its own lattice and periodic
mask (e.g. ``lattice.expand(nbatch, 3, 3)``), not one shared by the batch. Whether a table covers the lattice is only checked in
eager mode, not under ``torch.compile``, ``vmap`` or ``jacrev``, where a table
built for a larger cell silently misses images. If the cell shrinks (cell
relaxation, NPT), rebuild the table, or call
``shifts.check_compatible(structure, cutoff)`` once eagerly beforehand.

The evaluation is dense: every atom is paired with every image of every atom,
which takes memory proportional to ``n_atoms**2 * n_images``. The three-body
term has no periodic evaluation, so for a cell ``s9`` must be left out or set to
the Python number ``0.0``.


Migrating from 0.7.0
--------------------

- **Structure.** ``dftd3``, ``dispersion``, ``dispersion2``, ``dispersion3``
and ``damping.dispersion_atm`` take a ``tad_mctc.Structure`` instead of
``numbers`` and ``positions``. A periodic cell is a ``Structure`` with a
``lattice``. Passing ``numbers`` and ``positions`` raises a ``TypeError``.
To differentiate with ``torch.func``, replace the positions (or the
lattice) inside the function with ``structure.replace(positions=...)``.

.. code:: python

# 0.7.0
energy = d3.dftd3(numbers, positions, param)
# now
structure = mctc.Structure(numbers=numbers, positions=positions)
energy = d3.dftd3(structure, param)

- **Element parameters.** Up to 0.7.0, ``rcov``, ``rvdw`` and ``r4r2`` took
per-atom (or per-pair) values, i.e. ``table[numbers]``. They are now
per-element tables, passed as ``rcov_table``, ``rvdw_table`` and
Expand All @@ -283,7 +383,7 @@ Migrating from 0.7.0
# 0.7.0
d3.dftd3(numbers, positions, param, r4r2=d3.data.R4R2()[numbers])
# now
d3.dftd3(numbers, positions, param, r4r2_table=d3.data.R4R2())
d3.dftd3(structure, param, r4r2_table=d3.data.R4R2())

- **Keyword-only arguments.** All arguments of ``dispersion``,
``dispersion2`` and ``dispersion3`` after ``c6``, and of
Expand Down Expand Up @@ -356,7 +456,8 @@ The following example shows how to calculate the DFT-D3 dispersion energy for a
"a2": torch.tensor(5.73083694),
}

energy = d3.dftd3(numbers, positions, param)
structure = mctc.Structure(numbers=numbers, positions=positions)
energy = d3.dftd3(structure, param)

torch.set_printoptions(precision=10)
print(energy)
Expand Down Expand Up @@ -445,8 +546,7 @@ The next example shows the calculation of dispersion energies for a batch of str
weights = d3.model.weight_references(numbers, cn, ref, d3.model.gaussian_weight)
c6 = d3.model.atomic_c6(numbers, weights, ref)
energy = d3.disp.dispersion(
numbers,
positions,
structure,
param,
c6,
rvdw_table=rvdw,
Expand Down Expand Up @@ -493,7 +593,8 @@ obtained from a simple backward pass.
"a2": torch.tensor(5.73083694),
}

energy = d3.dftd3(numbers, positions, param)
structure = mctc.Structure(numbers=numbers, positions=positions)
energy = d3.dftd3(structure, param)

(grad,) = torch.autograd.grad(energy.sum(), positions)
forces = -grad
Expand All @@ -508,9 +609,8 @@ applying reverse-mode automatic differentiation twice (see
Limitations
-----------

The current implementation only works for molecular structures.
Periodic boundary conditions are **not** implemented, i.e., no stress tensor or
lattice gradient is available.
The three-body (ATM) term is only implemented for molecules (see
`Periodic systems`_).

The code is fully vectorized for maximum efficiency.
Therefore, all quantities are stored as full tensors, which makes calculations rather **memory intensive**.
Expand Down
3 changes: 1 addition & 2 deletions examples/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@
}

energy = d3.dftd3(
numbers,
positions,
mctc.Structure(numbers=numbers, positions=positions),
param,
ref=ref,
rcov_table=rcov,
Expand Down
10 changes: 7 additions & 3 deletions examples/forces.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
#######################

pos = positions.clone().requires_grad_(True)
energy = d3.dftd3(numbers, pos, param)
energy = d3.dftd3(mctc.Structure(numbers=numbers, positions=pos), param)

(grad,) = torch.autograd.grad(energy.sum(), pos)

Expand All @@ -64,10 +64,14 @@
for i in range(numbers.shape[-1]):
for j in range(3):
positions[i, j] += step
e1 = d3.dftd3(numbers, positions, param).sum()
e1 = d3.dftd3(
mctc.Structure(numbers=numbers, positions=positions), param
).sum()

positions[i, j] -= 2 * step
e2 = d3.dftd3(numbers, positions, param).sum()
e2 = d3.dftd3(
mctc.Structure(numbers=numbers, positions=positions), param
).sum()

positions[i, j] += step
num_grad[i, j] = (e1 - e2) / (2 * step)
Expand Down
4 changes: 3 additions & 1 deletion examples/hessian.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ def _energy(numbers: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
Returns the energy as a scalar, which is required for Hessian computation
to obtain the correct shape of ``(..., nat, 3, nat, 3)``.
"""
return d3.dftd3(numbers, positions, param).sum(-1)
return d3.dftd3(
mctc.Structure(numbers=numbers, positions=positions), param
).sum(-1)


def hessian(
Expand Down
2 changes: 1 addition & 1 deletion examples/single.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"a2": torch.tensor(5.73083694),
}

energy = d3.dftd3(numbers, positions, param)
energy = d3.dftd3(mctc.Structure(numbers=numbers, positions=positions), param)

torch.set_printoptions(precision=10)
print(energy)
Expand Down
3 changes: 2 additions & 1 deletion src/tad_dftd3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@
... s8=torch.tensor(0.3908),
... a2=torch.tensor(3.1280),
... )
>>> energy = torch.sum(d3.dftd3(numbers, positions, param), -1)
>>> structure = mctc.Structure(numbers=numbers, positions=positions)
>>> energy = torch.sum(d3.dftd3(structure, param), -1)
>>> print([f"{e:.7f}" for e in energy.tolist()]) # Energies in Hartree
['-0.0124292', '-0.0045002']
>>> print(f"{energy[0] - 2*energy[1]:.7f}")
Expand Down
72 changes: 72 additions & 0 deletions src/tad_dftd3/_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# This file is part of tad-dftd3.
# SPDX-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Argument checks shared by the public functions that take a
:class:`~tad_mctc.io.structure.Structure`.

They only look at Python types and at whether a field is set, never at
tensor values, so they are safe under ``vmap`` and ``torch.compile``.
"""

from __future__ import annotations

import functools
from collections.abc import Callable
from typing import Any, TypeVar

from tad_mctc.io.structure import Structure

__all__ = ["require_molecule", "takes_structure"]


F = TypeVar("F", bound=Callable[..., Any])


def takes_structure(func: F) -> F:
"""
Reject a first argument that is not a ``Structure``.

Up to 0.7.0, the public functions took ``numbers`` and ``positions`` as
their first two arguments. Such a call would otherwise fail with an
unhelpful message about the number of positional arguments, or not at
all for functions whose next argument also takes a tensor.
"""

@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
structure = args[0] if args else kwargs.get("structure")
if not isinstance(structure, Structure):
raise TypeError(
f"'{func.__name__}' takes a 'tad_mctc.Structure' as its "
f"first argument, not '{type(structure).__name__}'. Up to "
"0.7.0 it took 'numbers' and 'positions'; pass "
"'Structure(numbers=numbers, positions=positions)' instead."
)
return func(*args, **kwargs)

return wrapper # type: ignore[return-value]


def require_molecule(structure: Structure, term: str) -> None:
"""
Raise if `structure` is a periodic cell, for a `term` that has no
periodic evaluation. Evaluating the molecular one instead would
silently ignore the periodic images.
"""
if structure.lattice is not None:
raise ValueError(
f"The {term} has no periodic evaluation, but 'structure' has a "
"'lattice'."
)
24 changes: 18 additions & 6 deletions src/tad_dftd3/damping/atm.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,20 @@
from tad_mctc import storch
from tad_mctc.batch import real_pairs, real_triples
from tad_mctc.convert import any_to_tensor
from tad_mctc.io.structure import Structure
from tad_mctc.typing import DD, TableFunction, Tensor

from .. import defaults
from .._checks import require_molecule, takes_structure
from ..data.table import element_table, reject_renamed_tables

__all__ = ["dispersion_atm"]


@reject_renamed_tables
@takes_structure
def dispersion_atm(
numbers: Tensor,
positions: Tensor,
structure: Structure,
c6: Tensor,
*,
rvdw_table: Tensor | TableFunction | None = None,
Expand All @@ -62,10 +64,9 @@ def dispersion_atm(

Parameters
----------
numbers : Tensor
Atomic numbers of the atoms in the system.
positions : Tensor
Cartesian coordinates of the atoms in the system.
structure : Structure
The system, a molecule: atomic numbers and Cartesian coordinates,
single or batched (see :func:`tad_dftd3.disp.dftd3`).
c6 : Tensor
Atomic C6 dispersion coefficients.
rvdw_table : Tensor | TableFunction | None, optional
Expand All @@ -86,7 +87,18 @@ def dispersion_atm(
-------
Tensor
Atom-resolved ATM dispersion energy.

Raises
------
ValueError
If `structure` is a periodic cell, for which the ATM term has no
evaluation.
TypeError
If `structure` is not a ``Structure``.
"""
require_molecule(structure, "three-body (ATM) term")

numbers, positions = structure.numbers, structure.positions
dd: DD = {"device": positions.device, "dtype": positions.dtype}

s9 = any_to_tensor(defaults.S9 if s9 is None else s9, **dd)
Expand Down
Loading
Loading