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.
Files changed (50) hide show
  1. arrayff/__init__.py +29 -0
  2. arrayff/electrostatics/__init__.py +20 -0
  3. arrayff/electrostatics/calculator.py +18 -0
  4. arrayff/electrostatics/placeholders.py +23 -0
  5. arrayff/electrostatics/qeq.py +498 -0
  6. arrayff/neighbors/__init__.py +9 -0
  7. arrayff/neighbors/_list.py +649 -0
  8. arrayff/neighbors/_table.py +388 -0
  9. arrayff/potentials/__init__.py +76 -0
  10. arrayff/potentials/_torch.py +44 -0
  11. arrayff/potentials/base.py +720 -0
  12. arrayff/potentials/calculator.py +146 -0
  13. arrayff/potentials/composite.py +142 -0
  14. arrayff/potentials/eam/__init__.py +1 -0
  15. arrayff/potentials/eam/_torch.py +31 -0
  16. arrayff/potentials/eam/calculator.py +20 -0
  17. arrayff/potentials/eam/eam.py +233 -0
  18. arrayff/potentials/eam/io/__init__.py +8 -0
  19. arrayff/potentials/eam/io/eam.py +115 -0
  20. arrayff/potentials/emt/__init__.py +1 -0
  21. arrayff/potentials/emt/_torch.py +38 -0
  22. arrayff/potentials/emt/calculator.py +18 -0
  23. arrayff/potentials/emt/emt.py +353 -0
  24. arrayff/potentials/pairwise/__init__.py +21 -0
  25. arrayff/potentials/pairwise/_pairs.py +36 -0
  26. arrayff/potentials/pairwise/_torch.py +181 -0
  27. arrayff/potentials/pairwise/base.py +346 -0
  28. arrayff/potentials/pairwise/calculator.py +43 -0
  29. arrayff/potentials/pairwise/forms.py +147 -0
  30. arrayff/potentials/pairwise/lj.py +134 -0
  31. arrayff/potentials/pairwise/lj93.py +85 -0
  32. arrayff/potentials/pairwise/lj_kim.py +138 -0
  33. arrayff/potentials/pairwise/morse.py +100 -0
  34. arrayff/potentials/pairwise/params.py +50 -0
  35. arrayff/potentials/placeholders.py +37 -0
  36. arrayff/potentials/registry.py +49 -0
  37. arrayff/py.typed +0 -0
  38. arrayff/utils/__init__.py +50 -0
  39. arrayff/utils/ad.py +272 -0
  40. arrayff/utils/ase.py +68 -0
  41. arrayff/utils/backend.py +101 -0
  42. arrayff/utils/dispatch.py +118 -0
  43. arrayff/utils/exceptions.py +19 -0
  44. arrayff/utils/interp.py +77 -0
  45. arrayff/utils/jit.py +51 -0
  46. arrayff/utils/optional.py +38 -0
  47. arrayff-0.0.1.dist-info/METADATA +142 -0
  48. arrayff-0.0.1.dist-info/RECORD +50 -0
  49. arrayff-0.0.1.dist-info/WHEEL +4 -0
  50. arrayff-0.0.1.dist-info/licenses/src/LICENSE +674 -0
arrayff/utils/ad.py ADDED
@@ -0,0 +1,272 @@
1
+ """Backend agnostic automatic differentiation.
2
+
3
+ This module merges the former ``arrayff.ad`` package into a single file:
4
+ detach helpers, the autoray transform registry and the public transforms.
5
+ Importing it never imports torch/jax/autograd; registration happens when a
6
+ transform is first requested for a backend.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable, Sequence
12
+ from typing import Any
13
+
14
+ import autoray as ar
15
+
16
+ from arrayff.utils.backend import is_available, resolve_ad_backend
17
+ from arrayff.utils.dispatch import do
18
+
19
+ __all__ = [
20
+ "grad",
21
+ "jacrev",
22
+ "jvp",
23
+ "register_backend",
24
+ "registered_backends",
25
+ "stop_gradient",
26
+ "value_and_grad",
27
+ "vjp",
28
+ ]
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # detach
33
+ # ---------------------------------------------------------------------------
34
+ def stop_gradient(x: Any) -> Any:
35
+ """Return ``x`` with its gradient contribution removed.
36
+
37
+ Dispatches through autoray, so the same call works for numpy (identity),
38
+ torch (``.detach()``), JAX (``lax.stop_gradient``) and autograd.
39
+ """
40
+ return do("stop_gradient", x)
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # registry
45
+ # ---------------------------------------------------------------------------
46
+ _REGISTERED: set[str] = set()
47
+
48
+ #: Transform names exposed by arrayff and registered per backend.
49
+ TRANSFORM_NAMES = ("grad", "value_and_grad", "jacrev", "jvp", "vjp")
50
+
51
+
52
+ def _jvp_from_immediate(module: Any) -> Callable[[Callable], Callable]:
53
+ """Adapt ``module.jvp(f, primals, tangents)`` to ``f -> callable``."""
54
+
55
+ def factory(fn: Callable) -> Callable:
56
+ def transformed(primals: tuple, tangents: tuple) -> tuple:
57
+ return module.jvp(fn, primals, tangents)
58
+
59
+ return transformed
60
+
61
+ return factory
62
+
63
+
64
+ def _vjp_from_immediate(module: Any) -> Callable[[Callable], Callable]:
65
+ """Adapt ``module.vjp(f, primals)`` to ``f -> callable``."""
66
+
67
+ def factory(fn: Callable) -> Callable:
68
+ def transformed(primals: tuple) -> tuple:
69
+ return module.vjp(fn, *primals)
70
+
71
+ return transformed
72
+
73
+ return factory
74
+
75
+
76
+ def _register_jax() -> None:
77
+ import jax
78
+
79
+ ar.register_function("jax", "grad", jax.grad)
80
+ ar.register_function("jax", "value_and_grad", jax.value_and_grad)
81
+ ar.register_function("jax", "jacrev", jax.jacrev)
82
+ ar.register_function("jax", "jvp", _jvp_from_immediate(jax))
83
+ ar.register_function("jax", "vjp", _vjp_from_immediate(jax))
84
+
85
+
86
+ def _register_torch() -> None:
87
+ import torch.func as tf
88
+
89
+ def value_and_grad(fn: Callable) -> Callable:
90
+ # torch returns (grad, value); arrayff normalises to (value, grad).
91
+ def transformed(*primals: Any) -> tuple:
92
+ grad, value = tf.grad_and_value(fn)(*primals)
93
+ return value, grad
94
+
95
+ return transformed
96
+
97
+ ar.register_function("torch", "grad", tf.grad)
98
+ ar.register_function("torch", "value_and_grad", value_and_grad)
99
+ ar.register_function("torch", "jacrev", tf.jacrev)
100
+ ar.register_function("torch", "jvp", _jvp_from_immediate(tf))
101
+ ar.register_function("torch", "vjp", _vjp_from_immediate(tf))
102
+
103
+
104
+ def _register_autograd() -> None:
105
+ import autograd
106
+ import autograd.numpy as anp
107
+ from autograd.extend import defvjp, primitive
108
+
109
+ @primitive
110
+ def _stop_gradient(x):
111
+ return anp.asarray(x)
112
+
113
+ defvjp(
114
+ _stop_gradient,
115
+ lambda ans, x: lambda g: anp.zeros_like(x),
116
+ )
117
+
118
+ def jvp(fn: Callable) -> Callable:
119
+ transformed = autograd.make_jvp(fn)
120
+
121
+ def apply(primals: tuple, tangents: tuple) -> tuple:
122
+ return transformed(primals[0])(tangents[0])
123
+
124
+ return apply
125
+
126
+ def vjp(fn: Callable) -> Callable:
127
+ transformed = autograd.make_vjp(fn)
128
+
129
+ def apply(primals: tuple) -> tuple:
130
+ pullback, value = transformed(primals[0])
131
+ return value, pullback
132
+
133
+ return apply
134
+
135
+ ar.register_function("autograd", "grad", autograd.grad)
136
+ ar.register_function(
137
+ "autograd", "value_and_grad", autograd.value_and_grad
138
+ )
139
+ ar.register_function("autograd", "jacrev", autograd.jacobian)
140
+ ar.register_function("autograd", "jvp", jvp)
141
+ ar.register_function("autograd", "vjp", vjp)
142
+ ar.register_function("autograd", "stop_gradient", _stop_gradient)
143
+
144
+
145
+ def _register_numpy() -> None:
146
+ import numpy as np
147
+
148
+ # Plain numpy arrays carry no derivative information: detaching is a no-op.
149
+ ar.register_function("numpy", "stop_gradient", lambda x: np.asarray(x))
150
+
151
+
152
+ def _REGISTRARS() -> dict[str, Callable[[], None]]:
153
+ return {
154
+ "jax": _register_jax,
155
+ "torch": _register_torch,
156
+ "autograd": _register_autograd,
157
+ "numpy": _register_numpy,
158
+ }
159
+
160
+
161
+ def register_backend(backend: str) -> None:
162
+ """Register the AD transforms of ``backend`` (idempotent, lazy)."""
163
+ if backend in _REGISTERED:
164
+ return
165
+ registrar = _REGISTRARS().get(backend)
166
+ if registrar is None:
167
+ raise ValueError(f"No autodiff backend named {backend!r}")
168
+ if backend != "numpy" and not is_available(backend):
169
+ raise ImportError(
170
+ f"The {backend!r} backend is not installed; install its extra"
171
+ )
172
+ registrar()
173
+ _REGISTERED.add(backend)
174
+
175
+
176
+ def registered_backends() -> tuple[str, ...]:
177
+ """Return the backends whose transforms have been registered so far."""
178
+ return tuple(sorted(_REGISTERED))
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # public transforms
183
+ # ---------------------------------------------------------------------------
184
+ def _unary(f: Callable[..., Any], argnum: int, primals: tuple) -> Callable:
185
+ """Freeze every argument of ``f`` except ``primals[argnum]``."""
186
+
187
+ def g(x: Any) -> Any:
188
+ args = list(primals)
189
+ args[argnum] = x
190
+ return f(*args)
191
+
192
+ return g
193
+
194
+
195
+ def _factory(name: str, primals: tuple, argnum: int) -> Callable:
196
+ backend = resolve_ad_backend(primals[argnum])
197
+ register_backend(backend)
198
+ return ar.get_lib_fn(backend, name)
199
+
200
+
201
+ def grad(f: Callable[..., Any], argnum: int = 0) -> Callable[..., Any]:
202
+ """Return a function computing ``d f / d primals[argnum]``."""
203
+
204
+ def wrapped(*primals: Any) -> Any:
205
+ primals = tuple(primals)
206
+ factory = _factory("grad", primals, argnum)
207
+ return factory(_unary(f, argnum, primals))(primals[argnum])
208
+
209
+ return wrapped
210
+
211
+
212
+ def value_and_grad(
213
+ f: Callable[..., Any], argnum: int = 0
214
+ ) -> Callable[..., Any]:
215
+ """Return ``(value, gradient)`` when called."""
216
+
217
+ def wrapped(*primals: Any) -> tuple[Any, Any]:
218
+ primals = tuple(primals)
219
+ factory = _factory("value_and_grad", primals, argnum)
220
+ return factory(_unary(f, argnum, primals))(primals[argnum])
221
+
222
+ return wrapped
223
+
224
+
225
+ def jacrev(f: Callable[..., Any], argnum: int = 0) -> Callable[..., Any]:
226
+ """Return a function computing the Jacobian of ``f``."""
227
+
228
+ def wrapped(*primals: Any) -> Any:
229
+ primals = tuple(primals)
230
+ factory = _factory("jacrev", primals, argnum)
231
+ return factory(_unary(f, argnum, primals))(primals[argnum])
232
+
233
+ return wrapped
234
+
235
+
236
+ def _as_tuple(value: Any) -> tuple:
237
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
238
+ return tuple(value)
239
+ return (value,)
240
+
241
+
242
+ def jvp(f: Callable[..., Any], argnum: int = 0) -> Callable[..., Any]:
243
+ """Return ``f -> (primals, tangents) -> (value, jvp)``."""
244
+
245
+ def wrapped(primals: Any, tangents: Any) -> tuple[Any, Any]:
246
+ primals = _as_tuple(primals)
247
+ tangents = _as_tuple(tangents)
248
+ factory = _factory("jvp", primals, argnum)
249
+ anchor = primals[argnum]
250
+ tangents = (tangents[argnum] if len(tangents) > 1 else tangents[0],)
251
+ return factory(_unary(f, argnum, primals))((anchor,), tangents)
252
+
253
+ return wrapped
254
+
255
+
256
+ def vjp(f: Callable[..., Any], argnum: int = 0) -> Callable[..., Any]:
257
+ """Return ``f -> primals -> (value, pullback)``."""
258
+
259
+ def wrapped(primals: Any) -> tuple[Any, Callable]:
260
+ primals = _as_tuple(primals)
261
+ factory = _factory("vjp", primals, argnum)
262
+ value, pullback = factory(_unary(f, argnum, primals))(
263
+ (primals[argnum],)
264
+ )
265
+
266
+ def vjp_fn(cotangent: Any) -> tuple:
267
+ result = pullback(cotangent)
268
+ return result if isinstance(result, tuple) else (result,)
269
+
270
+ return value, vjp_fn
271
+
272
+ return wrapped
arrayff/utils/ase.py ADDED
@@ -0,0 +1,68 @@
1
+ """Conversion helpers between :class:`ase.Atoms` and backend arrays.
2
+
3
+ Arrayff uses :class:`~ase.Atoms` as its structural input/output type. This
4
+ module is the only place where an ``Atoms`` object is unpacked into arrays.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ from ase import Atoms
13
+
14
+ from arrayff.utils.dispatch import to_backend
15
+
16
+ __all__ = ["atoms_to_arrays", "element_numbers", "species_of"]
17
+
18
+
19
+ def atoms_to_arrays(
20
+ atoms: Atoms,
21
+ backend: str = "numpy",
22
+ dtype: Any = None,
23
+ ) -> tuple[Any, Any, Any, Any]:
24
+ """Return ``positions, numbers, cell, pbc`` arrays for ``atoms``.
25
+
26
+ ``positions`` is ``(N, 3)`` float, ``numbers`` is ``(N,)`` int, ``cell`` is
27
+ ``(3, 3)`` float (zeros when no cell is defined) and ``pbc`` is ``(3,)``
28
+ bool.
29
+ """
30
+ if not isinstance(atoms, Atoms):
31
+ raise TypeError(
32
+ f"Expected an ase.Atoms instance, got {type(atoms).__name__}"
33
+ )
34
+ positions = np.asarray(atoms.positions, dtype=np.float64)
35
+ numbers = np.asarray(atoms.numbers, dtype=np.int64)
36
+ cell = np.asarray(atoms.cell.array, dtype=np.float64)
37
+ pbc = np.asarray(atoms.pbc, dtype=bool)
38
+ positions_b = to_backend(positions, backend)
39
+ cell_b = to_backend(cell, backend)
40
+ if dtype is not None:
41
+ if backend == "torch":
42
+ positions_b = positions_b.to(dtype)
43
+ cell_b = cell_b.to(dtype)
44
+ else:
45
+ positions_b = positions_b.astype(dtype)
46
+ cell_b = cell_b.astype(dtype)
47
+ return (
48
+ positions_b,
49
+ to_backend(numbers, backend),
50
+ cell_b,
51
+ to_backend(pbc, backend),
52
+ )
53
+
54
+
55
+ def element_numbers(numbers: np.ndarray) -> np.ndarray:
56
+ """Return the sorted unique atomic numbers present in ``numbers``."""
57
+ return np.unique(np.asarray(numbers, dtype=np.int64))
58
+
59
+
60
+ def species_of(numbers: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
61
+ """Map atomic numbers to a compact ``0..S-1`` species index.
62
+
63
+ Returns ``(elements, species)`` where ``elements`` is the sorted array of
64
+ unique atomic numbers and ``species`` has the same shape as ``numbers``.
65
+ """
66
+ numbers = np.asarray(numbers, dtype=np.int64)
67
+ elements, species = np.unique(numbers, return_inverse=True)
68
+ return elements, species.astype(np.int64)
@@ -0,0 +1,101 @@
1
+ """Array backend detection and policy helpers.
2
+
3
+ Arrayff never branches on the backend inside numerical kernels: the backend
4
+ is inferred from the arrays themselves and ``autoray`` dispatches accordingly.
5
+ This module only collects the few places where a policy decision is needed
6
+ (e.g. which engine provides autodiff for ``numpy`` arrays).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib.util
12
+ from typing import Any
13
+
14
+ import autoray as ar
15
+
16
+ #: Backends whose arrays can flow through the kernels.
17
+ ARRAY_BACKENDS = ("numpy", "torch", "jax", "autograd")
18
+
19
+ #: Backends that provide native automatic differentiation.
20
+ AD_BACKENDS = ("torch", "jax", "autograd")
21
+
22
+ #: Backend used to differentiate plain ``numpy`` inputs.
23
+ NUMPY_AD_BACKEND = "autograd"
24
+
25
+
26
+ def infer_backend(*arrays: Any) -> str:
27
+ """Return the single backend shared by ``arrays``.
28
+
29
+ ``None`` entries are ignored so that optional arguments can be passed
30
+ straight through. Python scalars (``int``/``float``) are ignored too:
31
+ they are weak values that any backend accepts.
32
+ """
33
+ names: set[str] = set()
34
+ for array in arrays:
35
+ if array is None:
36
+ continue
37
+ name = ar.infer_backend(array)
38
+ if name in ("builtins", "dask"): # pragma: no cover - defensive
39
+ continue
40
+ names.add(name)
41
+ if not names:
42
+ raise TypeError(
43
+ "Cannot infer an array backend from the given arguments; "
44
+ "pass at least one array."
45
+ )
46
+ if len(names) > 1:
47
+ raise TypeError(
48
+ "Mixed array backends are not supported: "
49
+ f"{sorted(names)}. Convert the inputs to one backend first."
50
+ )
51
+ return names.pop()
52
+
53
+
54
+ def resolve_ad_backend(*primals: Any) -> str:
55
+ """Return the backend used to differentiate the given primals.
56
+
57
+ Plain ``numpy`` arrays are differentiated with :mod:`autograd`, which is
58
+ the designated NumPy automatic differentiation engine.
59
+ """
60
+ backend = infer_backend(*primals)
61
+ if backend == "numpy":
62
+ return NUMPY_AD_BACKEND
63
+ return backend
64
+
65
+
66
+ def default_dtype(backend: str) -> Any:
67
+ """Return the default floating point dtype for ``backend``."""
68
+ if backend == "numpy":
69
+ import numpy as np
70
+
71
+ return np.dtype("float64")
72
+ if backend == "torch":
73
+ import torch
74
+
75
+ return torch.float64
76
+ if backend == "jax":
77
+ import jax.numpy as jnp
78
+
79
+ return jnp.float64
80
+ if backend == "autograd":
81
+ import numpy as np
82
+
83
+ return np.dtype("float64")
84
+ raise ValueError(f"Unknown backend: {backend!r}")
85
+
86
+
87
+ def is_available(name: str) -> bool:
88
+ """Return whether the optional dependency ``name`` is importable."""
89
+ return importlib.util.find_spec(name) is not None
90
+
91
+
92
+ def available_backends() -> tuple[str, ...]:
93
+ """Return the array backends usable in the current environment."""
94
+ names = ["numpy"]
95
+ if is_available("torch"):
96
+ names.append("torch")
97
+ if is_available("jax"):
98
+ names.append("jax")
99
+ if is_available("autograd"):
100
+ names.append("autograd")
101
+ return tuple(names)
@@ -0,0 +1,118 @@
1
+ """Thin wrappers around :mod:`autoray` used by every numerical module.
2
+
3
+ ``arrayff`` talks to arrays exclusively through :func:`do`. The wrapper exists
4
+ so that (a) the ``autograd`` module alias is registered exactly once, before
5
+ any dispatch happens, and (b) error messages point at arrayff instead of
6
+ autoray.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ import autoray as ar
14
+ from autoray.autoray import register_module_alias
15
+
16
+ from arrayff.utils.backend import infer_backend
17
+
18
+ _AUTOGRAD_ALIAS_REGISTERED = False
19
+
20
+
21
+ def register_autograd_alias() -> None:
22
+ """Teach autoray how to dispatch on :mod:`autograd` traced arrays.
23
+
24
+ ``autoray`` infers the backend name ``"autograd"`` for HIPS autograd
25
+ ``ArrayBox`` objects. The module mapping is registered lazily and only
26
+ once; importing arrayff does not import autograd itself.
27
+ """
28
+ global _AUTOGRAD_ALIAS_REGISTERED
29
+ if _AUTOGRAD_ALIAS_REGISTERED:
30
+ return
31
+ register_module_alias("autograd", "autograd.numpy")
32
+ _AUTOGRAD_ALIAS_REGISTERED = True
33
+
34
+
35
+ def _contains_autograd(value: Any) -> bool:
36
+ """Return whether ``value`` (recursively) contains autograd boxes."""
37
+ if type(value).__module__.split(".")[0] == "autograd":
38
+ return True
39
+ if isinstance(value, (list, tuple)):
40
+ return any(_contains_autograd(item) for item in value)
41
+ if isinstance(value, dict):
42
+ return any(_contains_autograd(item) for item in value.values())
43
+ return False
44
+
45
+
46
+ def do(fn: str, *args: Any, like: str | None = None, **kwargs: Any) -> Any:
47
+ """Dispatch ``fn`` to the backend of the given arrays.
48
+
49
+ Parameters
50
+ ----------
51
+ fn:
52
+ Name of the operation, e.g. ``"sum"`` or ``"linalg.solve"``.
53
+ like:
54
+ Force a backend instead of inferring it from ``args``.
55
+ """
56
+ register_autograd_alias()
57
+ if like is None and _contains_autograd(args):
58
+ # Autograd table/index arrays are plain numpy arrays; force the
59
+ # dispatch backend when the first argument is one of those tables.
60
+ like = "autograd"
61
+ return ar.do(fn, *args, like=like, **kwargs)
62
+
63
+
64
+ def require_same_backend(*arrays: Any) -> str:
65
+ """Return the common backend of ``arrays`` or raise ``TypeError``."""
66
+ return infer_backend(*arrays)
67
+
68
+
69
+ def to_backend(array: Any, backend: str) -> Any:
70
+ """Convert ``array`` to ``backend`` while preserving autograd state."""
71
+ register_autograd_alias()
72
+ if backend == "numpy":
73
+ import numpy as np
74
+
75
+ return np.asarray(array)
76
+ if backend == "torch":
77
+ import numpy as np
78
+ import torch
79
+
80
+ if isinstance(array, torch.Tensor):
81
+ return array
82
+ # Go through numpy so Python floats keep float64 instead of torch's
83
+ # float32 default (important for scalar kernel parameters).
84
+ return torch.as_tensor(np.asarray(array))
85
+ if backend == "jax":
86
+ import jax.numpy as jnp
87
+
88
+ return jnp.asarray(array)
89
+ if backend == "autograd":
90
+ import autograd.numpy as anp
91
+
92
+ return anp.asarray(array)
93
+ raise ValueError(f"Unknown backend: {backend!r}")
94
+
95
+
96
+ def to_numpy(array: Any) -> Any:
97
+ """Convert a backend array to ``numpy`` (detaching any autograd graph)."""
98
+ register_autograd_alias()
99
+ import numpy as np
100
+
101
+ if isinstance(array, np.ndarray):
102
+ return array
103
+ backend = ar.infer_backend(array)
104
+ if backend == "torch":
105
+ return array.detach().cpu().numpy()
106
+ if backend == "jax":
107
+ return np.asarray(array)
108
+ if backend == "autograd":
109
+ return np.asarray(getattr(array, "_value", array))
110
+ return np.asarray(array)
111
+
112
+
113
+ def dtype_of(array: Any) -> Any:
114
+ """Return the dtype of ``array`` (untouched, backend object)."""
115
+ dtype = getattr(array, "dtype", None)
116
+ if dtype is None:
117
+ return "float64"
118
+ return dtype
@@ -0,0 +1,19 @@
1
+ """Exceptions raised by :mod:`arrayff`."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ArrayFFError(Exception):
7
+ """Base class for all arrayff specific errors."""
8
+
9
+
10
+ class MissingBackendError(ArrayFFError, ImportError):
11
+ """A requested array backend (or extra) is not installed."""
12
+
13
+
14
+ class ShapeError(ArrayFFError, ValueError):
15
+ """An array has an unexpected shape or dtype."""
16
+
17
+
18
+ class ScopeError(ArrayFFError, NotImplementedError):
19
+ """A feature is declared in the API but not implemented yet."""
@@ -0,0 +1,77 @@
1
+ """Differentiable table lookup.
2
+
3
+ EAM evaluates three tabulated functions (embedding, density, pair) on a
4
+ uniform radial grid. NumPy/autograd, torch and JAX all differentiate the
5
+ piecewise-linear lookup through plain advanced indexing; ``floor`` and
6
+ ``astype`` contribute zero derivative, so the local segment slope is the
7
+ correct gradient. No backend-specific primitive is needed.
8
+
9
+ ``interp_rows_with_slope`` returns the value and the analytic slope of the
10
+ piecewise-linear interpolant, for the EAM analytic force path (Q5=A).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+
19
+ from arrayff.utils.backend import infer_backend
20
+ from arrayff.utils.dispatch import do, to_backend
21
+
22
+ __all__ = ["interp_rows", "interp_rows_with_slope"]
23
+
24
+ def _prepare(table: np.ndarray, backend: str) -> np.ndarray:
25
+ if backend == "numpy":
26
+ return table
27
+ return to_backend(table, backend)
28
+
29
+
30
+ def _table_index(x: Any, table: np.ndarray, x0: float, dx: float):
31
+ u = (x - x0) / dx
32
+ last = table.shape[1] - 2
33
+ k = do("clip", do("astype", do("floor", u), "int32"), 0, last)
34
+ f = u - k
35
+ return k, f
36
+
37
+
38
+ def interp_rows(
39
+ table: np.ndarray,
40
+ rows: Any,
41
+ x: Any,
42
+ x0: float,
43
+ dx: float,
44
+ ) -> Any:
45
+ """Linearly interpolate ``table[rows]`` at ``x``.
46
+
47
+ ``table`` has shape ``(R, T)`` on a uniform grid ``r = x0 + i * dx``.
48
+ ``rows`` selects one row per element of ``x`` (same shape as ``x``).
49
+ """
50
+ if table.ndim != 2 or table.shape[1] < 2:
51
+ raise ValueError("interp_rows expects a (R, T>=2) table")
52
+ backend = infer_backend(x)
53
+ table = _prepare(table, backend)
54
+ k, f = _table_index(x, table, x0, dx)
55
+ low = table[rows, k]
56
+ high = table[rows, k + 1]
57
+ return low * (1.0 - f) + high * f
58
+
59
+
60
+ def interp_rows_with_slope(
61
+ table: np.ndarray,
62
+ rows: Any,
63
+ x: Any,
64
+ x0: float,
65
+ dx: float,
66
+ ) -> tuple[Any, Any]:
67
+ """Return ``(value, d value / d x)`` for the linear interpolant."""
68
+ if table.ndim != 2 or table.shape[1] < 2:
69
+ raise ValueError("interp_rows_with_slope expects a (R, T>=2) table")
70
+ backend = infer_backend(x)
71
+ table = _prepare(table, backend)
72
+ k, f = _table_index(x, table, x0, dx)
73
+ low = table[rows, k]
74
+ high = table[rows, k + 1]
75
+ value = low * (1.0 - f) + high * f
76
+ slope = (high - low) / dx
77
+ return value, slope