arrayff 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- arrayff/__init__.py +29 -0
- arrayff/electrostatics/__init__.py +20 -0
- arrayff/electrostatics/calculator.py +18 -0
- arrayff/electrostatics/placeholders.py +23 -0
- arrayff/electrostatics/qeq.py +498 -0
- arrayff/neighbors/__init__.py +9 -0
- arrayff/neighbors/_list.py +649 -0
- arrayff/neighbors/_table.py +388 -0
- arrayff/potentials/__init__.py +76 -0
- arrayff/potentials/_torch.py +44 -0
- arrayff/potentials/base.py +720 -0
- arrayff/potentials/calculator.py +146 -0
- arrayff/potentials/composite.py +142 -0
- arrayff/potentials/eam/__init__.py +1 -0
- arrayff/potentials/eam/_torch.py +31 -0
- arrayff/potentials/eam/calculator.py +20 -0
- arrayff/potentials/eam/eam.py +233 -0
- arrayff/potentials/eam/io/__init__.py +8 -0
- arrayff/potentials/eam/io/eam.py +115 -0
- arrayff/potentials/emt/__init__.py +1 -0
- arrayff/potentials/emt/_torch.py +38 -0
- arrayff/potentials/emt/calculator.py +18 -0
- arrayff/potentials/emt/emt.py +353 -0
- arrayff/potentials/pairwise/__init__.py +21 -0
- arrayff/potentials/pairwise/_pairs.py +36 -0
- arrayff/potentials/pairwise/_torch.py +181 -0
- arrayff/potentials/pairwise/base.py +346 -0
- arrayff/potentials/pairwise/calculator.py +43 -0
- arrayff/potentials/pairwise/forms.py +147 -0
- arrayff/potentials/pairwise/lj.py +134 -0
- arrayff/potentials/pairwise/lj93.py +85 -0
- arrayff/potentials/pairwise/lj_kim.py +138 -0
- arrayff/potentials/pairwise/morse.py +100 -0
- arrayff/potentials/pairwise/params.py +50 -0
- arrayff/potentials/placeholders.py +37 -0
- arrayff/potentials/registry.py +49 -0
- arrayff/py.typed +0 -0
- arrayff/utils/__init__.py +50 -0
- arrayff/utils/ad.py +272 -0
- arrayff/utils/ase.py +68 -0
- arrayff/utils/backend.py +101 -0
- arrayff/utils/dispatch.py +118 -0
- arrayff/utils/exceptions.py +19 -0
- arrayff/utils/interp.py +77 -0
- arrayff/utils/jit.py +51 -0
- arrayff/utils/optional.py +38 -0
- arrayff-0.0.1.dist-info/METADATA +142 -0
- arrayff-0.0.1.dist-info/RECORD +50 -0
- arrayff-0.0.1.dist-info/WHEEL +4 -0
- arrayff-0.0.1.dist-info/licenses/src/LICENSE +674 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Generic ASE calculator adapter.
|
|
2
|
+
|
|
3
|
+
Every potential can be driven through :class:`ase.Calculator`, so
|
|
4
|
+
``Atoms.get_potential_energy()`` / ``get_forces()`` (and MD, optimizers,
|
|
5
|
+
NEB, ...) work unchanged. Charge models additionally expose
|
|
6
|
+
``results["charges"]``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import inspect
|
|
12
|
+
from collections.abc import Iterable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from ase.calculators.calculator import Calculator, all_changes
|
|
17
|
+
from ase.stress import full_3x3_to_voigt_6_stress
|
|
18
|
+
|
|
19
|
+
__all__ = ["ArrayFFCalculator", "split_kwargs"]
|
|
20
|
+
|
|
21
|
+
#: Keywords consumed by :class:`ase.calculators.calculator.Calculator`.
|
|
22
|
+
_CALCULATOR_PARAMETERS = {
|
|
23
|
+
"label",
|
|
24
|
+
"directory",
|
|
25
|
+
"restart",
|
|
26
|
+
"discard",
|
|
27
|
+
"logfile",
|
|
28
|
+
"use_cache",
|
|
29
|
+
"txt",
|
|
30
|
+
"communicator",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def split_kwargs(
|
|
35
|
+
kwargs: dict[str, Any],
|
|
36
|
+
potential_cls: type,
|
|
37
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
38
|
+
"""Split ``kwargs`` into potential arguments and ASE calculator options.
|
|
39
|
+
|
|
40
|
+
Potential classes have explicit signatures; anything else that ASE's
|
|
41
|
+
``Calculator`` recognises (or unknown keys) is forwarded to it, so new
|
|
42
|
+
potential options such as ``jit``/``method`` are not silently dropped.
|
|
43
|
+
"""
|
|
44
|
+
parameters = inspect.signature(potential_cls.__init__).parameters
|
|
45
|
+
potential_kwargs: dict[str, Any] = {}
|
|
46
|
+
calculator_kwargs: dict[str, Any] = {}
|
|
47
|
+
for key, value in kwargs.items():
|
|
48
|
+
if key in parameters and key not in _CALCULATOR_PARAMETERS:
|
|
49
|
+
potential_kwargs[key] = value
|
|
50
|
+
else:
|
|
51
|
+
calculator_kwargs[key] = value
|
|
52
|
+
return potential_kwargs, calculator_kwargs
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ArrayFFCalculator(Calculator):
|
|
56
|
+
"""Wrap any arrayff potential as an ASE calculator."""
|
|
57
|
+
|
|
58
|
+
implemented_properties = ["energy", "forces", "stress"]
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
potential: Any,
|
|
63
|
+
*,
|
|
64
|
+
method: str | None = None,
|
|
65
|
+
**kwargs: Any,
|
|
66
|
+
) -> None:
|
|
67
|
+
super().__init__(**kwargs)
|
|
68
|
+
self.potential = potential
|
|
69
|
+
self.method = method
|
|
70
|
+
supported = ["energy", "forces", "stress"]
|
|
71
|
+
if getattr(potential, "supports_charges", False):
|
|
72
|
+
supported.append("charges")
|
|
73
|
+
# ASE reads this attribute per instance.
|
|
74
|
+
self.implemented_properties = supported
|
|
75
|
+
|
|
76
|
+
def get_stress(self, atoms: Any = None) -> Any:
|
|
77
|
+
"""Return a zero Voigt stress vector for non-periodic systems.
|
|
78
|
+
|
|
79
|
+
ASE always exposes an ``Atoms.cell`` object, even for molecules.
|
|
80
|
+
Asking for stress there is not meaningful; return zeros instead of
|
|
81
|
+
raising, and do not add a ``stress`` entry to ``results``.
|
|
82
|
+
"""
|
|
83
|
+
if atoms is None:
|
|
84
|
+
atoms = self.atoms
|
|
85
|
+
if atoms is None or atoms.cell.rank != 3:
|
|
86
|
+
# Non-periodic stress is undefined; return a zero Voigt vector
|
|
87
|
+
# without adding a ``stress`` entry to ``results`` (reference
|
|
88
|
+
# data stores no periodic stress for these systems).
|
|
89
|
+
return np.zeros(6)
|
|
90
|
+
return super().get_stress(atoms)
|
|
91
|
+
|
|
92
|
+
def calculate(
|
|
93
|
+
self,
|
|
94
|
+
atoms: Any = None,
|
|
95
|
+
properties: Iterable[str] = ("energy",),
|
|
96
|
+
system_changes: list[str] = all_changes,
|
|
97
|
+
) -> None:
|
|
98
|
+
super().calculate(atoms, properties, system_changes)
|
|
99
|
+
requested = set(properties)
|
|
100
|
+
if (
|
|
101
|
+
"stress" in requested
|
|
102
|
+
and self.atoms is not None
|
|
103
|
+
and self.atoms.cell is not None
|
|
104
|
+
and self.atoms.cell.rank != 3
|
|
105
|
+
):
|
|
106
|
+
requested.discard("stress")
|
|
107
|
+
wanted = ["energy"]
|
|
108
|
+
if "forces" in requested:
|
|
109
|
+
wanted.append("forces")
|
|
110
|
+
if "stress" in requested:
|
|
111
|
+
wanted.append("stress")
|
|
112
|
+
if getattr(self.potential, "supports_charges", False):
|
|
113
|
+
# Preserve the historical behaviour: a charge model always
|
|
114
|
+
# exposes its charges after a calculation, even for an
|
|
115
|
+
# energy-only request.
|
|
116
|
+
wanted.append("charges")
|
|
117
|
+
|
|
118
|
+
if hasattr(self.potential, "evaluate"):
|
|
119
|
+
result = self.potential.evaluate(
|
|
120
|
+
self.atoms, properties=tuple(wanted), method=self.method
|
|
121
|
+
)
|
|
122
|
+
energy = result["energy"]
|
|
123
|
+
forces = result.get("forces")
|
|
124
|
+
stress = result.get("stress")
|
|
125
|
+
charges = result.get("charges")
|
|
126
|
+
else: # backward compatibility for non-PotentialBase objects
|
|
127
|
+
energy, forces = self.potential.energy_and_forces(self.atoms)
|
|
128
|
+
stress = (
|
|
129
|
+
self.potential.stress(self.atoms)
|
|
130
|
+
if "stress" in requested
|
|
131
|
+
else None
|
|
132
|
+
)
|
|
133
|
+
charges = (
|
|
134
|
+
self.potential.charges(self.atoms)
|
|
135
|
+
if "charges" in requested
|
|
136
|
+
else None
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
self.results["energy"] = energy
|
|
140
|
+
self.results["free_energy"] = energy
|
|
141
|
+
if forces is not None:
|
|
142
|
+
self.results["forces"] = forces
|
|
143
|
+
if stress is not None:
|
|
144
|
+
self.results["stress"] = full_3x3_to_voigt_6_stress(stress)
|
|
145
|
+
if charges is not None:
|
|
146
|
+
self.results["charges"] = charges
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Additive composite potentials.
|
|
2
|
+
|
|
3
|
+
``LJ(...) + QEq(...)`` returns a :class:`CompositePotential` whose energy,
|
|
4
|
+
forces and stress are the sum of its components. Each component keeps its
|
|
5
|
+
own neighbour table, backend and evaluation method; a composite is never
|
|
6
|
+
compiled as a whole (set ``jit=True`` on the components instead).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from ase import Atoms
|
|
15
|
+
|
|
16
|
+
from arrayff.potentials.base import PotentialBase
|
|
17
|
+
from arrayff.utils.exceptions import ScopeError
|
|
18
|
+
|
|
19
|
+
__all__ = ["CompositePotential"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CompositePotential(PotentialBase):
|
|
23
|
+
"""Sum of two or more potentials / charge models."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
components: tuple[PotentialBase, ...] | list[PotentialBase],
|
|
28
|
+
) -> None:
|
|
29
|
+
flattened: list[PotentialBase] = []
|
|
30
|
+
for component in components:
|
|
31
|
+
if isinstance(component, CompositePotential):
|
|
32
|
+
flattened.extend(component.components)
|
|
33
|
+
else:
|
|
34
|
+
flattened.append(component)
|
|
35
|
+
if not flattened:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
"CompositePotential requires at least one component"
|
|
38
|
+
)
|
|
39
|
+
for component in flattened:
|
|
40
|
+
if not isinstance(component, PotentialBase):
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"CompositePotential components must be PotentialBase "
|
|
43
|
+
f"instances, got {type(component).__name__}"
|
|
44
|
+
)
|
|
45
|
+
backends = {component.backend for component in flattened}
|
|
46
|
+
if len(backends) != 1:
|
|
47
|
+
raise TypeError(
|
|
48
|
+
"All composite components must use the same backend, got "
|
|
49
|
+
f"{sorted(backends)}"
|
|
50
|
+
)
|
|
51
|
+
dtypes = {
|
|
52
|
+
component.dtype
|
|
53
|
+
for component in flattened
|
|
54
|
+
if component.dtype is not None
|
|
55
|
+
}
|
|
56
|
+
if len(dtypes) > 1:
|
|
57
|
+
raise TypeError(
|
|
58
|
+
"All composite components must use the same dtype, got "
|
|
59
|
+
f"{dtypes}"
|
|
60
|
+
)
|
|
61
|
+
charge_components = [
|
|
62
|
+
component
|
|
63
|
+
for component in flattened
|
|
64
|
+
if getattr(component, "supports_charges", False)
|
|
65
|
+
]
|
|
66
|
+
if len(charge_components) > 1:
|
|
67
|
+
raise ValueError(
|
|
68
|
+
"A composite may contain at most one charge model "
|
|
69
|
+
f"({[type(c).__name__ for c in charge_components]})"
|
|
70
|
+
)
|
|
71
|
+
super().__init__(
|
|
72
|
+
backend=next(iter(backends)),
|
|
73
|
+
dtype=next(iter(dtypes), None),
|
|
74
|
+
jit=False,
|
|
75
|
+
method="analytic",
|
|
76
|
+
)
|
|
77
|
+
self.components = tuple(flattened)
|
|
78
|
+
self.supports_charges = bool(charge_components)
|
|
79
|
+
self._charge_component = (
|
|
80
|
+
charge_components[0] if charge_components else None
|
|
81
|
+
)
|
|
82
|
+
self.name = "+".join(
|
|
83
|
+
getattr(component, "name", type(component).__name__)
|
|
84
|
+
for component in self.components
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def __len__(self) -> int:
|
|
88
|
+
return len(self.components)
|
|
89
|
+
|
|
90
|
+
def __iter__(self):
|
|
91
|
+
return iter(self.components)
|
|
92
|
+
|
|
93
|
+
def __repr__(self) -> str:
|
|
94
|
+
return f"CompositePotential({self.name})"
|
|
95
|
+
|
|
96
|
+
def evaluate(
|
|
97
|
+
self,
|
|
98
|
+
atoms: Atoms,
|
|
99
|
+
*,
|
|
100
|
+
properties: tuple[str, ...] = ("energy",),
|
|
101
|
+
method: str | None = None,
|
|
102
|
+
) -> dict[str, Any]:
|
|
103
|
+
props = tuple(properties)
|
|
104
|
+
unknown = set(props) - {"energy", "forces", "stress", "charges"}
|
|
105
|
+
if unknown:
|
|
106
|
+
raise ScopeError(
|
|
107
|
+
f"Unsupported properties for composite: {sorted(unknown)}"
|
|
108
|
+
)
|
|
109
|
+
component_props = tuple(
|
|
110
|
+
dict.fromkeys(("energy", *(p for p in props if p != "charges")))
|
|
111
|
+
)
|
|
112
|
+
results = [
|
|
113
|
+
component.evaluate(
|
|
114
|
+
atoms, properties=component_props, method=method
|
|
115
|
+
)
|
|
116
|
+
for component in self.components
|
|
117
|
+
]
|
|
118
|
+
out: dict[str, Any] = {
|
|
119
|
+
"energy": float(sum(result["energy"] for result in results))
|
|
120
|
+
}
|
|
121
|
+
if "forces" in props:
|
|
122
|
+
out["forces"] = np.sum(
|
|
123
|
+
[result["forces"] for result in results], axis=0
|
|
124
|
+
)
|
|
125
|
+
if "stress" in props:
|
|
126
|
+
out["stress"] = np.sum(
|
|
127
|
+
[result["stress"] for result in results], axis=0
|
|
128
|
+
)
|
|
129
|
+
if "charges" in props:
|
|
130
|
+
if self._charge_component is None:
|
|
131
|
+
raise ScopeError("This composite has no charge model")
|
|
132
|
+
out["charges"] = self._charge_component.charges(atoms)
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
def charges(self, atoms: Atoms) -> np.ndarray:
|
|
136
|
+
if self._charge_component is None:
|
|
137
|
+
raise ScopeError("This composite has no charge model")
|
|
138
|
+
return self._charge_component.charges(atoms)
|
|
139
|
+
|
|
140
|
+
def clear_cache(self) -> None:
|
|
141
|
+
for component in self.components:
|
|
142
|
+
component.clear_cache()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""EAM potential."""
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Optional torch wrapper for tabulated EAM potentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch import nn
|
|
7
|
+
|
|
8
|
+
from arrayff.potentials._torch import TorchPotential
|
|
9
|
+
from arrayff.potentials.eam.eam import EAM
|
|
10
|
+
|
|
11
|
+
__all__ = ["EAMTorch"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class EAMTorch(EAM, TorchPotential):
|
|
15
|
+
"""Torch module version of :class:`arrayff.potentials.EAM`."""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
potential: str,
|
|
20
|
+
*,
|
|
21
|
+
max_neighbors: int | None = None,
|
|
22
|
+
dtype: torch.dtype = torch.float64,
|
|
23
|
+
) -> None:
|
|
24
|
+
nn.Module.__init__(self)
|
|
25
|
+
EAM.__init__(
|
|
26
|
+
self,
|
|
27
|
+
potential,
|
|
28
|
+
backend="torch",
|
|
29
|
+
dtype=dtype,
|
|
30
|
+
max_neighbors=max_neighbors,
|
|
31
|
+
)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""ASE calculator for tabulated EAM potentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from arrayff.potentials.calculator import ArrayFFCalculator, split_kwargs
|
|
8
|
+
from arrayff.potentials.eam.eam import EAM
|
|
9
|
+
|
|
10
|
+
__all__ = ["EAMCalculator"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EAMCalculator(ArrayFFCalculator):
|
|
14
|
+
"""EAM calculator reading a ``setfl`` file."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, potential: str, **kwargs: Any) -> None:
|
|
17
|
+
potential_kwargs, calculator_kwargs = split_kwargs(kwargs, EAM)
|
|
18
|
+
super().__init__(
|
|
19
|
+
EAM(potential, **potential_kwargs), **calculator_kwargs
|
|
20
|
+
)
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Embedded atom method (EAM) potential.
|
|
2
|
+
|
|
3
|
+
Follows ``ase.calculators.eam``::
|
|
4
|
+
|
|
5
|
+
E = sum_i F_i(rho_i) + 1/2 sum_{i,j} phi_{a_i,a_j}(r_ij)
|
|
6
|
+
rho_i = sum_{j != i} rho_{a_j}(r_ij)
|
|
7
|
+
|
|
8
|
+
All three functions are tabulated on uniform grids and evaluated through
|
|
9
|
+
:func:`arrayff.utils.interp.interp_rows`, so the kernel stays vectorised and
|
|
10
|
+
differentiable on every backend.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from arrayff.potentials.eam.io.eam import EAMTable, read_setfl
|
|
20
|
+
from arrayff.utils.interp import interp_rows, interp_rows_with_slope
|
|
21
|
+
from arrayff.potentials.pairwise._pairs import pair_distances, pair_vectors
|
|
22
|
+
from arrayff.potentials.base import Potential
|
|
23
|
+
from arrayff.potentials.registry import register_potential
|
|
24
|
+
from arrayff.utils.dispatch import do, to_backend
|
|
25
|
+
from arrayff.neighbors._table import NeighborPaddedTable
|
|
26
|
+
|
|
27
|
+
__all__ = ["EAM"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@register_potential("eam")
|
|
31
|
+
class EAM(Potential):
|
|
32
|
+
"""Tabulated EAM potential read from an ``setfl`` file."""
|
|
33
|
+
|
|
34
|
+
name = "eam"
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
potential: str,
|
|
39
|
+
cutoff: float | None = None,
|
|
40
|
+
*,
|
|
41
|
+
backend: str = "numpy",
|
|
42
|
+
dtype: Any = None,
|
|
43
|
+
max_neighbors: int | None = None,
|
|
44
|
+
builder: str = "sklearn",
|
|
45
|
+
skin: float = 0.0,
|
|
46
|
+
jit: bool = False,
|
|
47
|
+
method: str = "analytic",
|
|
48
|
+
) -> None:
|
|
49
|
+
self.table: EAMTable = read_setfl(potential)
|
|
50
|
+
self._param_cache: dict[tuple[int, ...], dict[str, Any]] = {}
|
|
51
|
+
super().__init__(
|
|
52
|
+
cutoff or self.table.cutoff,
|
|
53
|
+
backend=backend,
|
|
54
|
+
dtype=dtype,
|
|
55
|
+
max_neighbors=max_neighbors,
|
|
56
|
+
builder=builder,
|
|
57
|
+
skin=skin,
|
|
58
|
+
jit=jit,
|
|
59
|
+
method=method,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def element_parameters(self, elements: np.ndarray) -> dict[str, Any]:
|
|
63
|
+
key = tuple(int(z) for z in elements)
|
|
64
|
+
cached = self._param_cache.get(key)
|
|
65
|
+
if cached is not None:
|
|
66
|
+
return cached
|
|
67
|
+
index = np.array([self.table.index_of(int(z)) for z in elements])
|
|
68
|
+
size = len(elements)
|
|
69
|
+
rphi = self.table.rphi[np.ix_(index, index)].reshape(size * size, -1)
|
|
70
|
+
result = {
|
|
71
|
+
"size": size,
|
|
72
|
+
"embedded": to_backend(self.table.embedded[index], self.backend),
|
|
73
|
+
"density": to_backend(self.table.density[index], self.backend),
|
|
74
|
+
"rphi": to_backend(rphi, self.backend),
|
|
75
|
+
"nr": self.table.nr,
|
|
76
|
+
"dr": self.table.dr,
|
|
77
|
+
"nrho": self.table.nrho,
|
|
78
|
+
"drho": self.table.drho,
|
|
79
|
+
}
|
|
80
|
+
self._param_cache[key] = result
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
def energy_arrays(
|
|
84
|
+
self,
|
|
85
|
+
positions: Any,
|
|
86
|
+
species: Any,
|
|
87
|
+
table: NeighborPaddedTable,
|
|
88
|
+
cell: Any,
|
|
89
|
+
pbc: Any,
|
|
90
|
+
params: dict[str, Any],
|
|
91
|
+
) -> Any:
|
|
92
|
+
if table.index.shape[1] == 0:
|
|
93
|
+
return do("sum", positions * 0.0)
|
|
94
|
+
|
|
95
|
+
index = table.index
|
|
96
|
+
mask = table.mask
|
|
97
|
+
size = params["size"]
|
|
98
|
+
|
|
99
|
+
species_j = species[index]
|
|
100
|
+
centre = species[:, None]
|
|
101
|
+
distance = pair_distances(positions, table, cell)
|
|
102
|
+
distance = do("where", mask, distance, 1.0)
|
|
103
|
+
|
|
104
|
+
# phi_a,b(r) = (r * phi)(r) / r
|
|
105
|
+
inside = do("logical_and", mask, distance < self.cutoff)
|
|
106
|
+
pair_rows = centre * size + species_j
|
|
107
|
+
rphi = interp_rows(
|
|
108
|
+
params["rphi"], pair_rows, distance, 0.0, params["dr"]
|
|
109
|
+
)
|
|
110
|
+
pair_energy = do("sum", do("where", inside, rphi / distance, 0.0))
|
|
111
|
+
pair_energy = 0.5 * pair_energy
|
|
112
|
+
|
|
113
|
+
# rho_i = sum_j rho_{a_j}(r_ij)
|
|
114
|
+
density = interp_rows(
|
|
115
|
+
params["density"], species_j, distance, 0.0, params["dr"]
|
|
116
|
+
)
|
|
117
|
+
density = do("sum", do("where", inside, density, 0.0), axis=-1)
|
|
118
|
+
|
|
119
|
+
embedding = interp_rows(
|
|
120
|
+
params["embedded"], species, density, 0.0, params["drho"]
|
|
121
|
+
)
|
|
122
|
+
return pair_energy + do("sum", embedding)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _eam_derivative_terms(
|
|
126
|
+
self,
|
|
127
|
+
positions: Any,
|
|
128
|
+
species: Any,
|
|
129
|
+
table: NeighborPaddedTable,
|
|
130
|
+
cell: Any,
|
|
131
|
+
params: dict[str, Any],
|
|
132
|
+
) -> tuple[Any, Any]:
|
|
133
|
+
if table.index.shape[1] == 0:
|
|
134
|
+
zeros = do("zeros_like", positions)
|
|
135
|
+
return zeros, do("zeros", (3, 3), like=positions)
|
|
136
|
+
|
|
137
|
+
index = table.index
|
|
138
|
+
mask = table.mask
|
|
139
|
+
size = params["size"]
|
|
140
|
+
species_j = species[index]
|
|
141
|
+
centre = species[:, None]
|
|
142
|
+
distance = pair_distances(positions, table, cell)
|
|
143
|
+
distance = do("where", mask, distance, 1.0)
|
|
144
|
+
inside = do(
|
|
145
|
+
"logical_and",
|
|
146
|
+
mask,
|
|
147
|
+
do("logical_and", distance < self.cutoff, distance > 0.0),
|
|
148
|
+
)
|
|
149
|
+
r_safe = do("where", inside, distance, self.cutoff)
|
|
150
|
+
|
|
151
|
+
pair_rows = centre * size + species_j
|
|
152
|
+
rphi, drphi = interp_rows_with_slope(
|
|
153
|
+
params["rphi"], pair_rows, r_safe, 0.0, params["dr"]
|
|
154
|
+
)
|
|
155
|
+
dphi = drphi / r_safe - rphi / (r_safe * r_safe)
|
|
156
|
+
|
|
157
|
+
density_value, density_slope = interp_rows_with_slope(
|
|
158
|
+
params["density"], species_j, r_safe, 0.0, params["dr"]
|
|
159
|
+
)
|
|
160
|
+
density = do("sum", do("where", inside, density_value, 0.0), axis=-1)
|
|
161
|
+
embedded, d_embedded = interp_rows_with_slope(
|
|
162
|
+
params["embedded"], species, density, 0.0, params["drho"]
|
|
163
|
+
)
|
|
164
|
+
_ = embedded
|
|
165
|
+
d_embedded_j = d_embedded[index]
|
|
166
|
+
dE_dr = do("where", inside, dphi, 0.0)
|
|
167
|
+
dE_dr = dE_dr + do(
|
|
168
|
+
"where", inside, d_embedded[:, None] * density_slope, 0.0
|
|
169
|
+
)
|
|
170
|
+
dE_dr = dE_dr + do(
|
|
171
|
+
"where", inside, d_embedded_j * density_slope, 0.0
|
|
172
|
+
)
|
|
173
|
+
coefficient = do("where", inside, dE_dr / r_safe, 0.0)
|
|
174
|
+
vectors = pair_vectors(positions, table, cell)
|
|
175
|
+
forces = do("sum", coefficient[:, :, None] * vectors, axis=1)
|
|
176
|
+
virial = 0.5 * do(
|
|
177
|
+
"einsum", "nm,nmi,nmj->ij", coefficient, vectors, vectors
|
|
178
|
+
)
|
|
179
|
+
volume = do("abs", do("linalg.det", cell))
|
|
180
|
+
stress = virial / volume
|
|
181
|
+
return forces, stress
|
|
182
|
+
|
|
183
|
+
def evaluate_arrays( # type: ignore[override]
|
|
184
|
+
self,
|
|
185
|
+
positions: Any,
|
|
186
|
+
species: Any,
|
|
187
|
+
table: NeighborPaddedTable,
|
|
188
|
+
cell: Any,
|
|
189
|
+
pbc: Any,
|
|
190
|
+
params: dict[str, Any],
|
|
191
|
+
*,
|
|
192
|
+
want: tuple[str, ...] = ("energy", "forces", "stress"),
|
|
193
|
+
) -> dict[str, Any]:
|
|
194
|
+
out: dict[str, Any] = {}
|
|
195
|
+
if "energy" in want:
|
|
196
|
+
out["energy"] = self.energy_arrays(
|
|
197
|
+
positions, species, table, cell, pbc, params
|
|
198
|
+
)
|
|
199
|
+
if "forces" in want or "stress" in want:
|
|
200
|
+
forces, stress = self._eam_derivative_terms(
|
|
201
|
+
positions, species, table, cell, params
|
|
202
|
+
)
|
|
203
|
+
if "forces" in want:
|
|
204
|
+
out["forces"] = forces
|
|
205
|
+
if "stress" in want:
|
|
206
|
+
out["stress"] = stress
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
def forces_arrays( # type: ignore[override]
|
|
210
|
+
self,
|
|
211
|
+
positions: Any,
|
|
212
|
+
species: Any,
|
|
213
|
+
table: NeighborPaddedTable,
|
|
214
|
+
cell: Any,
|
|
215
|
+
pbc: Any,
|
|
216
|
+
params: dict[str, Any],
|
|
217
|
+
) -> Any:
|
|
218
|
+
return self.evaluate_arrays(
|
|
219
|
+
positions, species, table, cell, pbc, params, want=("forces",)
|
|
220
|
+
)["forces"]
|
|
221
|
+
|
|
222
|
+
def stress_arrays( # type: ignore[override]
|
|
223
|
+
self,
|
|
224
|
+
positions: Any,
|
|
225
|
+
species: Any,
|
|
226
|
+
table: NeighborPaddedTable,
|
|
227
|
+
cell: Any,
|
|
228
|
+
pbc: Any,
|
|
229
|
+
params: dict[str, Any],
|
|
230
|
+
) -> Any:
|
|
231
|
+
return self.evaluate_arrays(
|
|
232
|
+
positions, species, table, cell, pbc, params, want=("stress",)
|
|
233
|
+
)["stress"]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Reader for the EAM ``setfl`` (alloy) format.
|
|
2
|
+
|
|
3
|
+
The layout follows LAMMPS / ``ase.calculators.eam``:
|
|
4
|
+
|
|
5
|
+
* three header lines,
|
|
6
|
+
* ``nelements``, element names, ``nrho drho nr dr cutoff``,
|
|
7
|
+
* per element: ``Z mass a lattice`` + ``nrho`` embedding values + ``nr``
|
|
8
|
+
density values,
|
|
9
|
+
* ``nr`` values of ``r * phi`` for every ``i >= j`` pair.
|
|
10
|
+
|
|
11
|
+
Tabulated functions are stored as plain arrays so any backend can evaluate
|
|
12
|
+
them; interpolation happens in :mod:`arrayff.utils.interp`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import pathlib
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
__all__ = ["EAMTable", "read_setfl"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class EAMTable:
|
|
27
|
+
"""Tabulated EAM functions on uniform grids."""
|
|
28
|
+
|
|
29
|
+
elements: tuple[int, ...]
|
|
30
|
+
z: np.ndarray
|
|
31
|
+
nrho: int
|
|
32
|
+
drho: float
|
|
33
|
+
nr: int
|
|
34
|
+
dr: float
|
|
35
|
+
cutoff: float
|
|
36
|
+
embedded: np.ndarray # (S, nrho)
|
|
37
|
+
density: np.ndarray # (S, nr)
|
|
38
|
+
rphi: np.ndarray # (S, S, nr), symmetric
|
|
39
|
+
|
|
40
|
+
def index_of(self, atomic_number: int) -> int:
|
|
41
|
+
matches = np.flatnonzero(self.z == int(atomic_number))
|
|
42
|
+
if len(matches) == 0:
|
|
43
|
+
raise KeyError(
|
|
44
|
+
f"Element Z={atomic_number} is not present in the EAM table "
|
|
45
|
+
f"({list(self.z)})"
|
|
46
|
+
)
|
|
47
|
+
return int(matches[0])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def read_setfl(path: str | pathlib.Path) -> EAMTable:
|
|
51
|
+
"""Read an EAM ``setfl`` file."""
|
|
52
|
+
with open(path, encoding="utf-8", errors="replace") as handle:
|
|
53
|
+
lines = handle.readlines()
|
|
54
|
+
data: list[str] = []
|
|
55
|
+
for line in lines[3:]:
|
|
56
|
+
data.extend(line.split())
|
|
57
|
+
|
|
58
|
+
if not data:
|
|
59
|
+
raise ValueError(f"{path}: empty EAM setfl file")
|
|
60
|
+
nelements = int(data[0])
|
|
61
|
+
if nelements <= 0:
|
|
62
|
+
raise ValueError(f"{path}: nelements must be positive")
|
|
63
|
+
cursor = 1
|
|
64
|
+
cursor += nelements # element names (the atomic numbers follow later)
|
|
65
|
+
nrho = int(data[cursor])
|
|
66
|
+
drho = float(data[cursor + 1])
|
|
67
|
+
nr = int(data[cursor + 2])
|
|
68
|
+
dr = float(data[cursor + 3])
|
|
69
|
+
cutoff = float(data[cursor + 4])
|
|
70
|
+
cursor += 5
|
|
71
|
+
if nrho <= 0 or nr <= 0:
|
|
72
|
+
raise ValueError(f"{path}: nrho and nr must be positive")
|
|
73
|
+
expected = (
|
|
74
|
+
cursor
|
|
75
|
+
+ nelements * (4 + nrho + nr)
|
|
76
|
+
+ nr * nelements * (nelements + 1) // 2
|
|
77
|
+
)
|
|
78
|
+
if len(data) < expected:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"{path}: truncated EAM setfl file "
|
|
81
|
+
f"(expected at least {expected} values, got {len(data)})"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
embedded = np.zeros((nelements, nrho))
|
|
85
|
+
density = np.zeros((nelements, nr))
|
|
86
|
+
z = np.zeros(nelements, dtype=int)
|
|
87
|
+
for element in range(nelements):
|
|
88
|
+
z[element] = int(data[cursor])
|
|
89
|
+
cursor += 4 # Z, mass, lattice constant, lattice type name
|
|
90
|
+
embedded[element] = np.asarray(
|
|
91
|
+
data[cursor : cursor + nrho], dtype=float
|
|
92
|
+
)
|
|
93
|
+
cursor += nrho
|
|
94
|
+
density[element] = np.asarray(data[cursor : cursor + nr], dtype=float)
|
|
95
|
+
cursor += nr
|
|
96
|
+
|
|
97
|
+
rphi = np.zeros((nelements, nelements, nr))
|
|
98
|
+
for i in range(nelements):
|
|
99
|
+
for j in range(i + 1):
|
|
100
|
+
rphi[j, i] = np.asarray(data[cursor : cursor + nr], dtype=float)
|
|
101
|
+
rphi[i, j] = rphi[j, i]
|
|
102
|
+
cursor += nr
|
|
103
|
+
|
|
104
|
+
return EAMTable(
|
|
105
|
+
elements=tuple(int(x) for x in z),
|
|
106
|
+
z=z,
|
|
107
|
+
nrho=nrho,
|
|
108
|
+
drho=drho,
|
|
109
|
+
nr=nr,
|
|
110
|
+
dr=dr,
|
|
111
|
+
cutoff=cutoff,
|
|
112
|
+
embedded=embedded,
|
|
113
|
+
density=density,
|
|
114
|
+
rphi=rphi,
|
|
115
|
+
)
|