arrayff 0.0.2__py3-none-any.whl → 0.2.0__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 +41 -8
- arrayff/_compat.py +73 -0
- arrayff/cli/__init__.py +172 -0
- arrayff/cli/config.py +141 -0
- arrayff/cli/training.py +582 -0
- arrayff/{utils → core}/__init__.py +5 -5
- arrayff/{utils → core}/ad.py +40 -32
- arrayff/{utils/ase.py → core/atoms.py} +8 -15
- arrayff/{utils → core}/backend.py +32 -9
- arrayff/core/bspline.py +173 -0
- arrayff/core/dispatch.py +516 -0
- arrayff/{utils → core}/exceptions.py +4 -0
- arrayff/core/interp.py +132 -0
- arrayff/core/jit.py +96 -0
- arrayff/{utils → core}/optional.py +1 -1
- arrayff/core/stress.py +110 -0
- arrayff/core/switching.py +70 -0
- arrayff/core/system.py +177 -0
- arrayff/core/tree.py +179 -0
- arrayff/engine/__init__.py +7 -0
- arrayff/engine/evaluator.py +624 -0
- arrayff/interfaces/__init__.py +0 -0
- arrayff/interfaces/ase.py +210 -0
- arrayff/interfaces/torch.py +429 -0
- arrayff/io/__init__.py +0 -0
- arrayff/{potentials/eam/io/eam.py → io/eam_setfl.py} +1 -1
- arrayff/io/export.py +306 -0
- arrayff/io/meam_library.py +234 -0
- arrayff/io/reaxff_ffield.py +333 -0
- arrayff/io/uf3.py +268 -0
- arrayff/mc/__init__.py +44 -0
- arrayff/mc/force_bias.py +193 -0
- arrayff/mc/local.py +357 -0
- arrayff/mc/moves.py +231 -0
- arrayff/mc/observables.py +75 -0
- arrayff/mc/samplers.py +466 -0
- arrayff/models/__init__.py +92 -0
- arrayff/models/_torch.py +82 -0
- arrayff/models/base.py +479 -0
- arrayff/models/composite.py +273 -0
- arrayff/{potentials → models}/eam/_torch.py +15 -3
- arrayff/models/eam/calculator.py +7 -0
- arrayff/models/eam/eam.py +180 -0
- arrayff/models/electrostatics/__init__.py +80 -0
- arrayff/models/electrostatics/_torch.py +603 -0
- arrayff/models/electrostatics/calculator.py +7 -0
- arrayff/models/electrostatics/charges/__init__.py +9 -0
- arrayff/models/electrostatics/charges/base.py +66 -0
- arrayff/models/electrostatics/charges/eem.py +37 -0
- arrayff/models/electrostatics/charges/qeq.py +33 -0
- arrayff/models/electrostatics/eem.py +85 -0
- arrayff/models/electrostatics/ewald.py +14 -0
- arrayff/models/electrostatics/kernels.py +276 -0
- arrayff/models/electrostatics/model.py +408 -0
- arrayff/models/electrostatics/placeholders.py +5 -0
- arrayff/models/electrostatics/pqeq.py +1314 -0
- arrayff/models/electrostatics/qeq.py +103 -0
- arrayff/models/electrostatics/solvers/__init__.py +25 -0
- arrayff/models/electrostatics/solvers/base.py +115 -0
- arrayff/models/electrostatics/solvers/direct.py +37 -0
- arrayff/models/electrostatics/solvers/ewald.py +208 -0
- arrayff/models/emt/_torch.py +129 -0
- arrayff/models/emt/calculator.py +7 -0
- arrayff/models/emt/emt.py +371 -0
- arrayff/models/meam/__init__.py +13 -0
- arrayff/models/meam/_torch.py +197 -0
- arrayff/models/meam/meam.py +841 -0
- arrayff/models/pairwise/__init__.py +21 -0
- arrayff/{potentials → models}/pairwise/_torch.py +76 -42
- arrayff/models/pairwise/base.py +155 -0
- arrayff/models/pairwise/calculator.py +7 -0
- arrayff/{potentials → models}/pairwise/forms.py +2 -2
- arrayff/{potentials → models}/pairwise/lj.py +25 -12
- arrayff/{potentials → models}/pairwise/lj93.py +10 -11
- arrayff/{potentials → models}/pairwise/morse.py +9 -10
- arrayff/{potentials → models}/pairwise/params.py +5 -4
- arrayff/models/placeholders.py +3 -0
- arrayff/models/reaxff/__init__.py +20 -0
- arrayff/models/reaxff/_torch.py +502 -0
- arrayff/models/reaxff/bond_order.py +411 -0
- arrayff/models/reaxff/model.py +598 -0
- arrayff/models/reaxff/params.py +253 -0
- arrayff/models/reaxff/terms/__init__.py +26 -0
- arrayff/models/reaxff/terms/angles.py +343 -0
- arrayff/models/reaxff/terms/atoms.py +127 -0
- arrayff/models/reaxff/terms/bonds.py +74 -0
- arrayff/models/reaxff/terms/hbonds.py +71 -0
- arrayff/models/reaxff/terms/nonbonded.py +203 -0
- arrayff/models/reaxff/terms/torsions.py +271 -0
- arrayff/models/reaxff/topology.py +157 -0
- arrayff/models/registry.py +281 -0
- arrayff/models/uf/__init__.py +26 -0
- arrayff/models/uf/_terms.py +155 -0
- arrayff/models/uf/_torch.py +104 -0
- arrayff/models/uf/fit.py +400 -0
- arrayff/models/uf/uf3.py +333 -0
- arrayff/neighbors/_list.py +88 -60
- arrayff/neighbors/_manybody.py +265 -0
- arrayff/neighbors/_table.py +61 -74
- arrayff/neighbors/cache.py +217 -0
- arrayff/neighbors/container.py +165 -0
- arrayff/neighbors/pairs.py +135 -0
- arrayff/optimize/__init__.py +9 -1
- arrayff/optimize/_dimer.py +21 -12
- arrayff/optimize/_helper.py +94 -43
- arrayff/optimize/_neb.py +63 -39
- arrayff-0.2.0.dist-info/METADATA +695 -0
- arrayff-0.2.0.dist-info/RECORD +116 -0
- {arrayff-0.0.2.dist-info → arrayff-0.2.0.dist-info}/WHEEL +1 -1
- arrayff-0.2.0.dist-info/entry_points.txt +3 -0
- arrayff/electrostatics/__init__.py +0 -20
- arrayff/electrostatics/calculator.py +0 -18
- arrayff/electrostatics/placeholders.py +0 -23
- arrayff/electrostatics/qeq.py +0 -498
- arrayff/potentials/__init__.py +0 -76
- arrayff/potentials/_torch.py +0 -44
- arrayff/potentials/base.py +0 -720
- arrayff/potentials/calculator.py +0 -146
- arrayff/potentials/composite.py +0 -142
- arrayff/potentials/eam/calculator.py +0 -20
- arrayff/potentials/eam/eam.py +0 -233
- arrayff/potentials/eam/io/__init__.py +0 -8
- arrayff/potentials/emt/_torch.py +0 -38
- arrayff/potentials/emt/calculator.py +0 -18
- arrayff/potentials/emt/emt.py +0 -353
- arrayff/potentials/pairwise/__init__.py +0 -21
- arrayff/potentials/pairwise/_pairs.py +0 -36
- arrayff/potentials/pairwise/base.py +0 -346
- arrayff/potentials/pairwise/calculator.py +0 -43
- arrayff/potentials/placeholders.py +0 -37
- arrayff/potentials/registry.py +0 -49
- arrayff/utils/dispatch.py +0 -118
- arrayff/utils/interp.py +0 -77
- arrayff/utils/jit.py +0 -51
- arrayff-0.0.2.dist-info/METADATA +0 -147
- arrayff-0.0.2.dist-info/RECORD +0 -54
- /arrayff/{potentials → models}/eam/__init__.py +0 -0
- /arrayff/{potentials → models}/emt/__init__.py +0 -0
- /arrayff/{potentials → models}/pairwise/lj_kim.py +0 -0
- {arrayff-0.0.2.dist-info → arrayff-0.2.0.dist-info}/licenses/src/LICENSE +0 -0
arrayff/__init__.py
CHANGED
|
@@ -1,29 +1,62 @@
|
|
|
1
1
|
"""ArrayFF: force fields on multiple array backends.
|
|
2
2
|
|
|
3
|
-
The package is organised as a thin dispatch layer (:mod:`arrayff.
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
The package is organised as a thin dispatch layer (:mod:`arrayff.core`),
|
|
4
|
+
neighbour tables (:mod:`arrayff.neighbors`), array level models
|
|
5
|
+
(:mod:`arrayff.models`), file formats (:mod:`arrayff.io`) and adapters to
|
|
6
|
+
other libraries (:mod:`arrayff.interfaces`). Numerical kernels never import a
|
|
7
|
+
concrete array library.
|
|
6
8
|
"""
|
|
7
9
|
|
|
8
10
|
from __future__ import annotations
|
|
9
11
|
|
|
10
|
-
|
|
11
|
-
from
|
|
12
|
-
from
|
|
12
|
+
import importlib
|
|
13
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from arrayff import _compat
|
|
17
|
+
|
|
18
|
+
_compat.install()
|
|
19
|
+
|
|
20
|
+
from arrayff import core # noqa: E402
|
|
21
|
+
from arrayff.models import ( # noqa: E402
|
|
13
22
|
CompositePotential,
|
|
14
23
|
LennardJones,
|
|
15
24
|
available_potentials,
|
|
25
|
+
build_potential,
|
|
16
26
|
get_potential,
|
|
17
27
|
)
|
|
28
|
+
from arrayff.models.electrostatics import QEq # noqa: E402
|
|
18
29
|
|
|
19
|
-
|
|
30
|
+
try:
|
|
31
|
+
__version__ = version("arrayff")
|
|
32
|
+
except PackageNotFoundError: # pragma: no cover - source tree without install
|
|
33
|
+
__version__ = "0.0.0+unknown"
|
|
20
34
|
|
|
21
35
|
__all__ = [
|
|
36
|
+
"ArrayFFCalculator",
|
|
22
37
|
"CompositePotential",
|
|
23
38
|
"LennardJones",
|
|
24
39
|
"QEq",
|
|
40
|
+
"TorchModel",
|
|
25
41
|
"__version__",
|
|
26
42
|
"available_potentials",
|
|
43
|
+
"build_potential",
|
|
44
|
+
"core",
|
|
27
45
|
"get_potential",
|
|
28
|
-
"utils",
|
|
29
46
|
]
|
|
47
|
+
|
|
48
|
+
_LEGACY_PACKAGES = ("utils", "potentials", "electrostatics")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def __getattr__(name: str) -> Any:
|
|
52
|
+
if name == "ArrayFFCalculator":
|
|
53
|
+
from arrayff.interfaces.ase import ArrayFFCalculator
|
|
54
|
+
|
|
55
|
+
return ArrayFFCalculator
|
|
56
|
+
if name == "TorchModel":
|
|
57
|
+
from arrayff.interfaces.torch import TorchModel
|
|
58
|
+
|
|
59
|
+
return TorchModel
|
|
60
|
+
if name in _LEGACY_PACKAGES:
|
|
61
|
+
return importlib.import_module(f"arrayff.{name}")
|
|
62
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
arrayff/_compat.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Import aliases for the pre-0.2 package layout.
|
|
2
|
+
|
|
3
|
+
``arrayff.utils``, ``arrayff.potentials`` and ``arrayff.electrostatics`` moved
|
|
4
|
+
to :mod:`arrayff.core`, :mod:`arrayff.models` and
|
|
5
|
+
:mod:`arrayff.models.electrostatics`. The finder below maps every old module
|
|
6
|
+
name onto the new module object on first import, so ``from
|
|
7
|
+
arrayff.potentials.pairwise.lj import LennardJones`` keeps working (and stays
|
|
8
|
+
lazy: nothing is imported before it is asked for).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import importlib
|
|
14
|
+
import importlib.abc
|
|
15
|
+
import importlib.machinery
|
|
16
|
+
import importlib.util
|
|
17
|
+
import sys
|
|
18
|
+
import warnings
|
|
19
|
+
from types import ModuleType
|
|
20
|
+
|
|
21
|
+
__all__ = ["install", "translate"]
|
|
22
|
+
|
|
23
|
+
#: Longest prefix first; the first match wins.
|
|
24
|
+
_PREFIXES: tuple[tuple[str, str], ...] = (
|
|
25
|
+
("arrayff.utils.ase", "arrayff.core.atoms"),
|
|
26
|
+
("arrayff.utils", "arrayff.core"),
|
|
27
|
+
("arrayff.potentials.eam.io.eam", "arrayff.io.eam_setfl"),
|
|
28
|
+
("arrayff.potentials.eam.io", "arrayff.io"),
|
|
29
|
+
("arrayff.potentials.calculator", "arrayff.interfaces.ase"),
|
|
30
|
+
("arrayff.potentials", "arrayff.models"),
|
|
31
|
+
("arrayff.electrostatics", "arrayff.models.electrostatics"),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
_WARNED: set[str] = set()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def translate(name: str) -> str | None:
|
|
38
|
+
"""Return the new module name for a legacy ``name`` (or ``None``)."""
|
|
39
|
+
for old, new in _PREFIXES:
|
|
40
|
+
if name == old or name.startswith(old + "."):
|
|
41
|
+
return new + name[len(old) :]
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _AliasFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader):
|
|
46
|
+
def find_spec(self, fullname, path=None, target=None):
|
|
47
|
+
target_name = translate(fullname)
|
|
48
|
+
if target_name is None:
|
|
49
|
+
return None
|
|
50
|
+
if importlib.util.find_spec(target_name) is None:
|
|
51
|
+
return None
|
|
52
|
+
return importlib.machinery.ModuleSpec(fullname, self)
|
|
53
|
+
|
|
54
|
+
def create_module(self, spec) -> ModuleType:
|
|
55
|
+
legacy = spec.name.split(".")[1]
|
|
56
|
+
if legacy not in _WARNED:
|
|
57
|
+
_WARNED.add(legacy)
|
|
58
|
+
warnings.warn(
|
|
59
|
+
f"arrayff.{legacy} is deprecated; import from "
|
|
60
|
+
f"{translate('arrayff.' + legacy)} instead",
|
|
61
|
+
DeprecationWarning,
|
|
62
|
+
stacklevel=2,
|
|
63
|
+
)
|
|
64
|
+
return importlib.import_module(translate(spec.name)) # type: ignore
|
|
65
|
+
|
|
66
|
+
def exec_module(self, module: ModuleType) -> None:
|
|
67
|
+
"""The aliased module is already executed."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def install() -> None:
|
|
71
|
+
"""Register the alias finder once (idempotent)."""
|
|
72
|
+
if not any(isinstance(f, _AliasFinder) for f in sys.meta_path):
|
|
73
|
+
sys.meta_path.insert(0, _AliasFinder())
|
arrayff/cli/__init__.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""``arrayff`` command line: ``train``, ``eval`` and ``export``.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
arrayff train config.toml --set train.epochs=200 --set train.lr=1e-3
|
|
6
|
+
arrayff train --spec lj --data train.extxyz --epochs 50
|
|
7
|
+
arrayff eval run/best.pt --data test.extxyz
|
|
8
|
+
arrayff export run/best.pt --out trained.json
|
|
9
|
+
|
|
10
|
+
PyTorch is imported only when a command runs; without it the commands
|
|
11
|
+
raise :class:`~arrayff.core.exceptions.MissingBackendError`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from arrayff.core.exceptions import ArrayFFError, MissingBackendError
|
|
23
|
+
from arrayff.core.optional import is_available
|
|
24
|
+
|
|
25
|
+
__all__ = ["main"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _require_torch() -> None:
|
|
29
|
+
if not is_available("torch"):
|
|
30
|
+
raise MissingBackendError(
|
|
31
|
+
"arrayff train/eval/export need PyTorch; install it with "
|
|
32
|
+
"`pip install arrayff[torch]`"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parser() -> argparse.ArgumentParser:
|
|
37
|
+
parser = argparse.ArgumentParser(
|
|
38
|
+
prog="arrayff", description="Train and export arrayff force fields."
|
|
39
|
+
)
|
|
40
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
41
|
+
|
|
42
|
+
train = commands.add_parser("train", help="fit a model to reference data")
|
|
43
|
+
train.add_argument("config", nargs="?", help="TOML configuration file")
|
|
44
|
+
train.add_argument("--spec", help="model spec, e.g. lj or reaxff+qeq")
|
|
45
|
+
train.add_argument("--species", help="atomic numbers, e.g. 1,6,8")
|
|
46
|
+
train.add_argument("--data", help="training structures (ase.io.read)")
|
|
47
|
+
train.add_argument("--valid", help="validation structures")
|
|
48
|
+
train.add_argument("--epochs", type=int)
|
|
49
|
+
train.add_argument("--lr", type=float)
|
|
50
|
+
train.add_argument("--batch-size", type=int)
|
|
51
|
+
train.add_argument("--optimizer", choices=("adam", "lbfgs"))
|
|
52
|
+
train.add_argument("--device")
|
|
53
|
+
train.add_argument("--out", help="output directory (default: run)")
|
|
54
|
+
train.add_argument(
|
|
55
|
+
"--export",
|
|
56
|
+
help="file or directory written from best.pt at the end",
|
|
57
|
+
)
|
|
58
|
+
train.add_argument("--resume", help="checkpoint to continue from")
|
|
59
|
+
train.add_argument(
|
|
60
|
+
"--set",
|
|
61
|
+
action="append",
|
|
62
|
+
default=[],
|
|
63
|
+
metavar="KEY=VALUE",
|
|
64
|
+
help="override any field, e.g. --set loss.forces=5",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
evaluate = commands.add_parser("eval", help="metrics of a checkpoint")
|
|
68
|
+
evaluate.add_argument("checkpoint")
|
|
69
|
+
evaluate.add_argument("--data", required=True)
|
|
70
|
+
evaluate.add_argument("--batch-size", type=int)
|
|
71
|
+
evaluate.add_argument("--json", help="also write the metrics to this file")
|
|
72
|
+
|
|
73
|
+
export = commands.add_parser("export", help="write trained parameters")
|
|
74
|
+
export.add_argument("checkpoint")
|
|
75
|
+
export.add_argument(
|
|
76
|
+
"--out",
|
|
77
|
+
required=True,
|
|
78
|
+
action="append",
|
|
79
|
+
help=(
|
|
80
|
+
"file (.ffield, .meam, .uf3 or .json), directory (one file per "
|
|
81
|
+
"trainable component), or COMPONENT=FILE (repeatable)"
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
return parser
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _export_path(values: list[str]) -> Any:
|
|
88
|
+
"""``--out`` values as one path or a ``{component: file}`` dict."""
|
|
89
|
+
pairs = [v.partition("=") for v in values]
|
|
90
|
+
if len(values) == 1 and not pairs[0][1]:
|
|
91
|
+
return values[0]
|
|
92
|
+
if not all(sep and name and path for name, sep, path in pairs):
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"several --out values must all be COMPONENT=FILE, got "
|
|
95
|
+
f"{values}"
|
|
96
|
+
)
|
|
97
|
+
return {name.strip(): path for name, _, path in pairs}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _species(text: str | None) -> list[int] | None:
|
|
101
|
+
if text is None:
|
|
102
|
+
return None
|
|
103
|
+
return [int(part) for part in text.replace(" ", "").split(",") if part]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _train(args: argparse.Namespace) -> int:
|
|
107
|
+
from arrayff.cli.config import build_config
|
|
108
|
+
from arrayff.cli.training import train
|
|
109
|
+
|
|
110
|
+
flags: dict[str, Any] = {
|
|
111
|
+
"model.spec": args.spec,
|
|
112
|
+
"model.species": _species(args.species),
|
|
113
|
+
"data.train": args.data,
|
|
114
|
+
"data.valid": args.valid,
|
|
115
|
+
"train.epochs": args.epochs,
|
|
116
|
+
"train.lr": args.lr,
|
|
117
|
+
"train.batch_size": args.batch_size,
|
|
118
|
+
"train.optimizer": args.optimizer,
|
|
119
|
+
"train.device": args.device,
|
|
120
|
+
"output.dir": args.out,
|
|
121
|
+
"output.export": args.export,
|
|
122
|
+
}
|
|
123
|
+
config = build_config(args.config, flags=flags, overrides=args.set)
|
|
124
|
+
summary = train(config, resume=args.resume)
|
|
125
|
+
print(json.dumps(summary, indent=1))
|
|
126
|
+
return 0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _evaluate(args: argparse.Namespace) -> int:
|
|
130
|
+
from arrayff.cli.training import (
|
|
131
|
+
evaluate_model,
|
|
132
|
+
load_structures,
|
|
133
|
+
model_from_checkpoint,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
model, checkpoint = model_from_checkpoint(args.checkpoint)
|
|
137
|
+
config = checkpoint["config"]
|
|
138
|
+
structures = load_structures(args.data, config["data"])
|
|
139
|
+
size = args.batch_size or int(config["train"]["batch_size"])
|
|
140
|
+
metrics = evaluate_model(model, structures, config["loss"], size)
|
|
141
|
+
text = json.dumps(metrics, indent=1)
|
|
142
|
+
print(text)
|
|
143
|
+
if args.json:
|
|
144
|
+
with open(args.json, "w") as handle:
|
|
145
|
+
handle.write(text + "\n")
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _export(args: argparse.Namespace) -> int:
|
|
150
|
+
from arrayff.cli.training import model_from_checkpoint
|
|
151
|
+
from arrayff.io.export import export
|
|
152
|
+
|
|
153
|
+
model, _ = model_from_checkpoint(args.checkpoint)
|
|
154
|
+
for path in export(model, _export_path(args.out)):
|
|
155
|
+
print(path)
|
|
156
|
+
return 0
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
160
|
+
"""Run the command line; returns the exit status."""
|
|
161
|
+
args = _parser().parse_args(argv)
|
|
162
|
+
commands = {"train": _train, "eval": _evaluate, "export": _export}
|
|
163
|
+
try:
|
|
164
|
+
_require_torch()
|
|
165
|
+
return commands[args.command](args)
|
|
166
|
+
except (ArrayFFError, ValueError, KeyError, FileNotFoundError) as exc:
|
|
167
|
+
print(f"arrayff {args.command}: error: {exc}", file=sys.stderr)
|
|
168
|
+
return 2
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
if __name__ == "__main__": # pragma: no cover
|
|
172
|
+
raise SystemExit(main())
|
arrayff/cli/config.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Configuration of ``arrayff train``: defaults, TOML file, overrides.
|
|
2
|
+
|
|
3
|
+
Precedence, lowest first: :data:`DEFAULTS`, the TOML file, the dedicated
|
|
4
|
+
command-line flags (``--spec``, ``--epochs``, ...), then ``--set a.b=v``.
|
|
5
|
+
Paths are used as given (relative to the working directory).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import pathlib
|
|
12
|
+
import tomllib
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from arrayff.core.exceptions import ArrayFFError
|
|
16
|
+
|
|
17
|
+
__all__ = ["DEFAULTS", "ConfigError", "build_config", "parse_value"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConfigError(ArrayFFError, ValueError):
|
|
21
|
+
"""The training configuration is incomplete or inconsistent."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
#: Every section and key ``arrayff train`` reads.
|
|
25
|
+
DEFAULTS: dict[str, Any] = {
|
|
26
|
+
"model": {"spec": None, "species": None, "frozen": []},
|
|
27
|
+
"data": {
|
|
28
|
+
"train": None,
|
|
29
|
+
"valid": None,
|
|
30
|
+
"valid_fraction": 0.0,
|
|
31
|
+
"energy_key": "energy",
|
|
32
|
+
"forces_key": "forces",
|
|
33
|
+
"stress_key": "stress",
|
|
34
|
+
},
|
|
35
|
+
"loss": {"energy": 1.0, "forces": 10.0, "stress": 0.0},
|
|
36
|
+
"train": {
|
|
37
|
+
"optimizer": "adam",
|
|
38
|
+
"lr": 1e-3,
|
|
39
|
+
"epochs": 100,
|
|
40
|
+
"batch_size": 8,
|
|
41
|
+
"patience": 20,
|
|
42
|
+
"seed": 0,
|
|
43
|
+
"device": "cpu",
|
|
44
|
+
"lbfgs_max_iter": 20,
|
|
45
|
+
},
|
|
46
|
+
"output": {"dir": "run", "export": None},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_OPTIMIZERS = ("adam", "lbfgs")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_value(text: str) -> Any:
|
|
53
|
+
"""A TOML value (``3``, ``1e-3``, ``true``, ``[1, 8]``) or a string."""
|
|
54
|
+
try:
|
|
55
|
+
return tomllib.loads(f"value = {text}")["value"]
|
|
56
|
+
except tomllib.TOMLDecodeError:
|
|
57
|
+
return text
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _merge(base: dict[str, Any], update: dict[str, Any]) -> None:
|
|
61
|
+
for key, value in update.items():
|
|
62
|
+
if isinstance(value, dict) and isinstance(base.get(key), dict):
|
|
63
|
+
_merge(base[key], value)
|
|
64
|
+
else:
|
|
65
|
+
base[key] = copy.deepcopy(value)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _assign(config: dict[str, Any], dotted: str, value: Any) -> None:
|
|
69
|
+
keys = dotted.split(".")
|
|
70
|
+
if len(keys) < 2 or not all(keys):
|
|
71
|
+
raise ConfigError(f"--set needs section.key=value, got {dotted!r}")
|
|
72
|
+
node = config
|
|
73
|
+
for key in keys[:-1]:
|
|
74
|
+
child = node.setdefault(key, {})
|
|
75
|
+
if not isinstance(child, dict):
|
|
76
|
+
raise ConfigError(f"{dotted!r}: {key!r} is not a table")
|
|
77
|
+
node = child
|
|
78
|
+
node[keys[-1]] = value
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def build_config(
|
|
82
|
+
path: str | pathlib.Path | None = None,
|
|
83
|
+
*,
|
|
84
|
+
flags: dict[str, Any] | None = None,
|
|
85
|
+
overrides: list[str] | tuple[str, ...] = (),
|
|
86
|
+
) -> dict[str, Any]:
|
|
87
|
+
"""Merge defaults, the TOML file, ``flags`` and ``--set`` overrides.
|
|
88
|
+
|
|
89
|
+
``flags`` maps dotted keys (``"train.epochs"``) to values; ``None``
|
|
90
|
+
values are skipped.
|
|
91
|
+
"""
|
|
92
|
+
config = copy.deepcopy(DEFAULTS)
|
|
93
|
+
if path is not None:
|
|
94
|
+
text = pathlib.Path(path).read_text()
|
|
95
|
+
try:
|
|
96
|
+
_merge(config, tomllib.loads(text))
|
|
97
|
+
except tomllib.TOMLDecodeError as exc:
|
|
98
|
+
raise ConfigError(f"{path}: {exc}") from None
|
|
99
|
+
for dotted, value in (flags or {}).items():
|
|
100
|
+
if value is not None:
|
|
101
|
+
_assign(config, dotted, value)
|
|
102
|
+
for item in overrides:
|
|
103
|
+
if "=" not in item:
|
|
104
|
+
raise ConfigError(f"--set needs section.key=value, got {item!r}")
|
|
105
|
+
dotted, text = item.split("=", 1)
|
|
106
|
+
_assign(config, dotted.strip(), parse_value(text.strip()))
|
|
107
|
+
_validate(config)
|
|
108
|
+
return config
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _validate(config: dict[str, Any]) -> None:
|
|
112
|
+
unknown = sorted(set(config) - set(DEFAULTS))
|
|
113
|
+
if unknown:
|
|
114
|
+
raise ConfigError(f"unknown config sections {unknown}")
|
|
115
|
+
for section in ("data", "loss", "train", "output"):
|
|
116
|
+
extra = sorted(set(config[section]) - set(DEFAULTS[section]))
|
|
117
|
+
if extra:
|
|
118
|
+
raise ConfigError(f"unknown keys in [{section}]: {extra}")
|
|
119
|
+
if not config["model"].get("spec"):
|
|
120
|
+
raise ConfigError("model.spec is required (e.g. --spec lj)")
|
|
121
|
+
if not config["data"].get("train"):
|
|
122
|
+
raise ConfigError("data.train is required (e.g. --data train.xyz)")
|
|
123
|
+
train = config["train"]
|
|
124
|
+
if train["optimizer"] not in _OPTIMIZERS:
|
|
125
|
+
raise ConfigError(
|
|
126
|
+
f"train.optimizer must be one of {_OPTIMIZERS}, got "
|
|
127
|
+
f"{train['optimizer']!r}"
|
|
128
|
+
)
|
|
129
|
+
for key in ("epochs", "batch_size", "patience", "lbfgs_max_iter"):
|
|
130
|
+
if int(train[key]) < 1:
|
|
131
|
+
raise ConfigError(f"train.{key} must be at least 1")
|
|
132
|
+
fraction = float(config["data"]["valid_fraction"])
|
|
133
|
+
if not 0.0 <= fraction < 1.0:
|
|
134
|
+
raise ConfigError("data.valid_fraction must be in [0, 1)")
|
|
135
|
+
if fraction and config["data"]["valid"]:
|
|
136
|
+
raise ConfigError("set data.valid or data.valid_fraction, not both")
|
|
137
|
+
weights = config["loss"]
|
|
138
|
+
if any(float(weights[k]) < 0.0 for k in ("energy", "forces", "stress")):
|
|
139
|
+
raise ConfigError("loss weights must be non-negative")
|
|
140
|
+
if not any(float(weights[k]) > 0.0 for k in ("energy", "forces", "stress")):
|
|
141
|
+
raise ConfigError("at least one loss weight must be positive")
|