pycp2k 0.3.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.
cp2k/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """Direct Python access to CP2K, without starting a CP2K subprocess.
2
+
3
+ The native API uses atomic units (bohr, hartree). Importing this package does
4
+ not load libcp2k or initialize MPI. See :class:`CP2K` for runtime ownership.
5
+ """
6
+
7
+ # SPDX-License-Identifier: GPL-2.0-or-later
8
+
9
+ from .input import input_to_string
10
+ from .library import CP2K, CalculationResult, ForceEnvironment, SCFConvergenceError
11
+ from .remote import SocketEnvironment
12
+
13
+ __all__ = [
14
+ "CP2K",
15
+ "CalculationResult",
16
+ "ForceEnvironment",
17
+ "SocketEnvironment",
18
+ "SCFConvergenceError",
19
+ "input_to_string",
20
+ ]
21
+ __version__ = "0.3.0"
cp2k/_transport.py ADDED
@@ -0,0 +1,61 @@
1
+ """Bounded JSON framing; no pickle or native-library objects cross the socket."""
2
+
3
+ # SPDX-License-Identifier: GPL-2.0-or-later
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ import json
9
+ import socket
10
+ import struct
11
+ from typing import TYPE_CHECKING, Any, TypeVar, cast
12
+
13
+ if TYPE_CHECKING:
14
+ from mpi4py import MPI
15
+
16
+ _T = TypeVar("_T")
17
+
18
+ _MAX_MESSAGE = 64 * 1024 * 1024
19
+
20
+
21
+ def _read(sock: socket.socket, size: int) -> bytearray:
22
+ data = bytearray()
23
+ while len(data) < size:
24
+ chunk = sock.recv(min(size - len(data), 65536))
25
+ if not chunk:
26
+ raise ConnectionError("CP2K socket closed before a complete response")
27
+ data.extend(chunk)
28
+ return data
29
+
30
+
31
+ def receive(sock: socket.socket) -> dict[str, Any]:
32
+ size = struct.unpack("!I", _read(sock, 4))[0]
33
+ if not 0 < size <= _MAX_MESSAGE:
34
+ raise ValueError("Invalid CP2K message length")
35
+ value = json.loads(_read(sock, size))
36
+ if not isinstance(value, dict):
37
+ raise ValueError("CP2K messages must be JSON objects")
38
+ return value
39
+
40
+
41
+ def send(sock: socket.socket, value: dict[str, Any]) -> None:
42
+ data = json.dumps(value, allow_nan=False, separators=(",", ":")).encode()
43
+ if not 0 < len(data) <= _MAX_MESSAGE:
44
+ raise ValueError("CP2K message exceeds the 64 MiB limit")
45
+ sock.sendall(struct.pack("!I", len(data)) + data)
46
+
47
+
48
+ def root_call(comm: MPI.Intracomm | None, function: Callable[[], _T]) -> _T:
49
+ """Relay root-only I/O failures to all caller ranks before raising."""
50
+ reply: dict[str, Any] | None = None
51
+ if comm is None or comm.rank == 0:
52
+ try:
53
+ reply = {"value": function()}
54
+ except Exception as error:
55
+ reply = {"error": f"{type(error).__name__}: {error}"}
56
+ if comm is not None:
57
+ reply = comm.bcast(reply, root=0)
58
+ assert reply is not None
59
+ if "error" in reply:
60
+ raise RuntimeError(reply["error"])
61
+ return cast(_T, reply["value"])
cp2k/_units.py ADDED
@@ -0,0 +1,10 @@
1
+ """CP2K's CODATA-2006 conversions, matching src/common/physcon.F."""
2
+
3
+ # SPDX-License-Identifier: GPL-2.0-or-later
4
+
5
+ BOHR_TO_ANGSTROM = 0.52917720859
6
+ BOHR_TO_NM = BOHR_TO_ANGSTROM * 0.1
7
+ HARTREE_TO_JOULE = 2.0 * 10973731.568527 * 6.62606896e-34 * 299792458.0
8
+ HARTREE_TO_EV = HARTREE_TO_JOULE / 1.602176487e-19
9
+ HARTREE_TO_KJMOL = HARTREE_TO_JOULE * 6.02214179e23 * 0.001
10
+ HARTREE_TO_KCALMOL = HARTREE_TO_KJMOL / 4.184
cp2k/aiida.py ADDED
@@ -0,0 +1,107 @@
1
+ """Optional bridge to the existing AiiDA common CP2K relaxation workflow."""
2
+
3
+ # SPDX-License-Identifier: GPL-2.0-or-later
4
+
5
+ from copy import deepcopy
6
+ import math
7
+
8
+
9
+ def build_relax_builder(
10
+ structure,
11
+ *,
12
+ code,
13
+ options,
14
+ electronic_type,
15
+ protocol="moderate",
16
+ relax_type="positions",
17
+ spin_type="none",
18
+ magnetization_per_site=None,
19
+ threshold_forces=None,
20
+ threshold_stress=None,
21
+ reference_workchain=None,
22
+ ):
23
+ """Build, but do not submit, an AiiDA common CP2K relaxation workflow.
24
+
25
+ Load an AiiDA profile first. ``structure`` is a StructureData node, ``code``
26
+ a configured CP2K Code, and ``options`` its scheduler options. Electronic
27
+ type (``metal`` or ``insulator``) is an explicit physical choice. Relaxation
28
+ types are ``none``, ``positions`` and ``positions_cell``. Protocols and all
29
+ CP2K input generation belong to aiida-common-workflows, not this interface.
30
+ Thresholds are in eV/angstrom and eV/angstrom**3. This function neither
31
+ stores nor submits the builder, and never loads libcp2k in the AiiDA daemon.
32
+ The supplied common protocols describe neutral, fully periodic systems.
33
+ Use a custom cp2k.base builder for different boundary conditions/charge.
34
+ """
35
+ from aiida import orm
36
+ from aiida.plugins import WorkflowFactory
37
+ from aiida_common_workflows.common import ElectronicType, RelaxType, SpinType
38
+
39
+ if not isinstance(structure, orm.StructureData):
40
+ raise TypeError("structure must be an AiiDA StructureData node")
41
+ if not all(structure.pbc):
42
+ raise ValueError(
43
+ "The common CP2K protocols require fully periodic structures; for molecules "
44
+ "or slabs, use cp2k.base with explicit cell/Poisson boundary conditions"
45
+ )
46
+ if not isinstance(options, dict):
47
+ raise TypeError("options must be a scheduler-options dictionary")
48
+ relax_type = RelaxType(relax_type)
49
+ electronic_type = ElectronicType(electronic_type)
50
+ spin_type = SpinType(spin_type)
51
+ if magnetization_per_site is not None and spin_type != SpinType.COLLINEAR:
52
+ raise ValueError("magnetization_per_site requires collinear spin")
53
+ if magnetization_per_site is not None:
54
+ if len(magnetization_per_site) != len(structure.sites) or not all(
55
+ math.isfinite(value) for value in magnetization_per_site
56
+ ):
57
+ raise ValueError(
58
+ "magnetization_per_site must contain one finite value per site"
59
+ )
60
+ if threshold_forces is not None and relax_type == RelaxType.NONE:
61
+ raise ValueError("threshold_forces requires a relaxation")
62
+ if threshold_stress is not None and relax_type != RelaxType.POSITIONS_CELL:
63
+ raise ValueError("threshold_stress requires positions_cell relaxation")
64
+ for name, value in (
65
+ ("threshold_forces", threshold_forces),
66
+ ("threshold_stress", threshold_stress),
67
+ ):
68
+ if value is not None and (not math.isfinite(value) or value <= 0):
69
+ raise ValueError(f"{name} must be finite and positive")
70
+ kwargs = {
71
+ "structure": structure,
72
+ "engines": {"relax": {"code": code, "options": deepcopy(options)}},
73
+ "protocol": protocol,
74
+ "relax_type": relax_type,
75
+ "electronic_type": electronic_type,
76
+ "spin_type": spin_type,
77
+ }
78
+ for key, value in (
79
+ ("magnetization_per_site", magnetization_per_site),
80
+ ("threshold_forces", threshold_forces),
81
+ ("threshold_stress", threshold_stress),
82
+ ("reference_workchain", reference_workchain),
83
+ ):
84
+ if value is not None:
85
+ kwargs[key] = value
86
+ workflow = WorkflowFactory("common_workflows.relax.cp2k")
87
+ builder = workflow.get_input_generator().get_builder(**kwargs)
88
+ parameters = builder.cp2k.parameters.get_dict()
89
+ cell_opt = parameters.get("MOTION", {}).get("CELL_OPT", {})
90
+ if cell_opt.get("TYPE") == "DIRECT_CELL_OPT":
91
+ # Current CP2K always uses DIRECT_CELL_OPT and rejects the old TYPE
92
+ # keyword, including in the unused CELL_OPT section of a GEO_OPT run.
93
+ # Omitting this former default also preserves older CP2K semantics.
94
+ del cell_opt["TYPE"]
95
+ # aiida-cp2k's advanced parser reads XYZ, not the common protocol's DCD.
96
+ # Keep cells at the same cadence for a meaningful variable-cell trajectory.
97
+ printing = parameters.setdefault("MOTION", {}).setdefault("PRINT", {})
98
+ trajectory = printing.setdefault("TRAJECTORY", {})
99
+ trajectory["FORMAT"] = "XYZ"
100
+ trajectory["ADD_LAST"] = "NUMERIC"
101
+ printing["CELL"] = {
102
+ "_": "ON",
103
+ "ADD_LAST": "NUMERIC",
104
+ "EACH": deepcopy(trajectory.get("EACH", {})),
105
+ }
106
+ builder.cp2k.parameters = orm.Dict(dict=parameters)
107
+ return builder
cp2k/ase.py ADDED
@@ -0,0 +1,228 @@
1
+ """Optional ASE calculator using libcp2k in the Python process."""
2
+
3
+ # SPDX-License-Identifier: GPL-2.0-or-later
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Mapping, Sequence
8
+ from copy import deepcopy
9
+ import os
10
+ from pathlib import Path
11
+ from typing import Any, cast
12
+
13
+ import numpy as np
14
+ from ase import Atoms
15
+ from ase.calculators.calculator import CalculationFailed, Calculator, all_changes
16
+
17
+ from ._units import BOHR_TO_ANGSTROM as Bohr, HARTREE_TO_EV as Hartree
18
+ from .input import InputMapping, input_to_string
19
+ from .library import CP2K, ForceEnvironment, PathLike, SCFConvergenceError
20
+
21
+
22
+ def _uppercase(tree: InputMapping) -> dict[str, Any]:
23
+ if not isinstance(tree, Mapping):
24
+ raise TypeError("inp must be a CP2K input mapping")
25
+ result: dict[str, Any] = {}
26
+ for key, value in tree.items():
27
+ if not isinstance(key, str) or key.upper() in result:
28
+ raise ValueError(f"Invalid or duplicate input key: {key!r}")
29
+ if isinstance(value, Mapping):
30
+ value = _uppercase(value)
31
+ elif isinstance(value, (list, tuple)):
32
+ value = [
33
+ _uppercase(item) if isinstance(item, Mapping) else item
34
+ for item in value
35
+ ]
36
+ result[key.upper()] = deepcopy(value)
37
+ return result
38
+
39
+
40
+ class CP2KCalculator(Calculator):
41
+ """ASE energy/force calculator with no shell or output parsing.
42
+
43
+ ``runtime`` is an open :class:`cp2k.CP2K` session, owned by the caller.
44
+ ``inp`` specifies the method, DFT/force-field settings and SUBSYS/KINDs.
45
+ Geometry and periodicity come exclusively from ASE's Atoms. A finite,
46
+ right-handed cell is required even for nonperiodic systems. Positions and
47
+ cells are converted from angstrom, energy/forces back to eV and eV/angstrom.
48
+
49
+ Per-atom energies, shell models, topology files, and implicit use
50
+ of ASE initial charges/magnetic moments are not supported. Set charge and
51
+ spin explicitly in inp. Stress uses ASE's tensile-positive eV/angstrom**3
52
+ convention and enables cell optimization/NPT. Close before closing runtime.
53
+ """
54
+
55
+ implemented_properties = ["energy", "free_energy", "forces", "stress"]
56
+ default_parameters = {"inp": None}
57
+
58
+ def __init__(
59
+ self,
60
+ runtime: CP2K,
61
+ inp: InputMapping,
62
+ *,
63
+ output_file: PathLike | None = None,
64
+ **kwargs: Any,
65
+ ) -> None:
66
+ self._runtime = runtime
67
+ self._env: ForceEnvironment | None = None
68
+ self._stress_requested = False
69
+ self._closed = False
70
+ self._output_file = output_file
71
+ # ASE's base-class methods do not yet declare their argument types.
72
+ super().__init__(inp=deepcopy(inp), **kwargs) # type: ignore[no-untyped-call]
73
+
74
+ def set(self, **kwargs: Any) -> dict[str, Any]:
75
+ unknown = set(kwargs) - {"inp"}
76
+ if unknown:
77
+ raise TypeError(f"Unknown CP2K calculator parameters: {sorted(unknown)}")
78
+ if "inp" in kwargs:
79
+ # Validate without mutating caller-owned dictionaries.
80
+ kwargs["inp"] = _uppercase(kwargs["inp"])
81
+ input_to_string(kwargs["inp"])
82
+ changed = super().set(**kwargs) # type: ignore[no-untyped-call]
83
+ if changed:
84
+ self._discard_environment()
85
+ self.reset() # type: ignore[no-untyped-call]
86
+ return cast(dict[str, Any], changed)
87
+
88
+ def _discard_environment(self) -> None:
89
+ if self._env is not None:
90
+ self._env.close()
91
+ self._env = None
92
+ self._stress_requested = False
93
+
94
+ def _make_input(self, atoms: Atoms, *, stress: bool = False) -> dict[str, Any]:
95
+ tree: dict[str, Any] = deepcopy(self.parameters["inp"])
96
+ force_eval = tree.setdefault("FORCE_EVAL", {})
97
+ if not isinstance(force_eval, dict):
98
+ raise ValueError("ASE requires exactly one FORCE_EVAL section")
99
+ if stress:
100
+ force_eval.setdefault("STRESS_TENSOR", "ANALYTICAL")
101
+ subsys = force_eval.setdefault("SUBSYS", {})
102
+ if not isinstance(subsys, dict):
103
+ raise ValueError("SUBSYS must be a single section")
104
+ conflicting = {
105
+ "CELL",
106
+ "COORD",
107
+ "TOPOLOGY",
108
+ "VELOCITY",
109
+ "SHELL",
110
+ "CORE",
111
+ } & subsys.keys()
112
+ if conflicting:
113
+ raise ValueError(
114
+ f"ASE owns the geometry; remove SUBSYS {sorted(conflicting)}"
115
+ )
116
+ subsys["CELL"] = {
117
+ axis: row.tolist() for axis, row in zip("ABC", atoms.cell.array)
118
+ }
119
+ subsys["CELL"]["PERIODIC"] = (
120
+ "".join(axis for axis, periodic in zip("XYZ", atoms.pbc) if periodic)
121
+ or "NONE"
122
+ )
123
+ subsys["COORD"] = {
124
+ "_lines": [
125
+ f"{symbol} {x:.17g} {y:.17g} {z:.17g}"
126
+ for symbol, (x, y, z) in zip(
127
+ atoms.get_chemical_symbols(), atoms.positions
128
+ )
129
+ ]
130
+ }
131
+ glob = tree.setdefault("GLOBAL", {})
132
+ if not isinstance(glob, dict):
133
+ raise ValueError("GLOBAL must be a single section")
134
+ if "PROJECT" not in glob:
135
+ # GLOBAL/PROJECT is limited to 80 bytes in native CP2K. Avoid
136
+ # unnecessarily embedding a potentially long absolute cwd.
137
+ project = os.path.relpath(Path(self.directory) / (self.prefix or "cp2k"))
138
+ if '"' in project or len(os.fsencode(project)) > 80:
139
+ raise ValueError(
140
+ "Use a shorter calculator directory/label or set GLOBAL/PROJECT "
141
+ "explicitly; generated PROJECT must fit 80 bytes without quotes"
142
+ )
143
+ glob["PROJECT"] = f'"{project}"'
144
+ glob.setdefault("PRINT_LEVEL", "LOW")
145
+ return tree
146
+
147
+ def calculate(
148
+ self,
149
+ atoms: Atoms | None = None,
150
+ properties: Sequence[str] = ("energy",),
151
+ system_changes: Sequence[str] = all_changes,
152
+ ) -> None:
153
+ if self._closed:
154
+ raise RuntimeError("This CP2K calculator is closed")
155
+ self._runtime._check()
156
+ super().calculate(atoms, properties, system_changes) # type: ignore[no-untyped-call]
157
+ self.results = {}
158
+ assert self.atoms is not None
159
+ if len(self.atoms) == 0:
160
+ raise ValueError("CP2K requires at least one atom")
161
+ cell = self.atoms.cell.array
162
+ determinant = np.linalg.det(cell)
163
+ if (
164
+ not np.isfinite(cell).all()
165
+ or not np.isfinite(determinant)
166
+ or determinant <= 0
167
+ ):
168
+ raise ValueError("CP2K requires a finite, right-handed 3D cell")
169
+ if not np.isfinite(self.atoms.positions).all():
170
+ raise ValueError("Atomic positions must be finite")
171
+ if np.any(self.atoms.get_initial_charges()) or np.any(
172
+ self.atoms.get_initial_magnetic_moments()
173
+ ):
174
+ raise ValueError(
175
+ "Specify charge/spin in inp, not ASE initial charges/magmoms"
176
+ )
177
+ if set(system_changes) & {"numbers", "pbc"}:
178
+ self._discard_environment()
179
+ stress = "stress" in properties
180
+ # The native stress setting is fixed when the environment is created.
181
+ if (
182
+ self._env is not None
183
+ and stress != self._stress_requested
184
+ and "STRESS_TENSOR" not in self.parameters["inp"].get("FORCE_EVAL", {})
185
+ ):
186
+ self._discard_environment()
187
+ if self._env is None:
188
+ source = self._make_input(self.atoms, stress=stress)
189
+ output = self._output_file or str(
190
+ Path(self.directory) / f"{self.prefix or 'cp2k'}.out"
191
+ )
192
+ self._env = self._runtime.create_force_env(source, output_file=output)
193
+ self._stress_requested = stress
194
+ if self._env.natom != len(self.atoms) or self._env.nparticle != len(
195
+ self.atoms
196
+ ):
197
+ self._discard_environment()
198
+ raise ValueError("ASE requires exactly one CP2K particle per atom")
199
+ self._env.cell = cell / Bohr
200
+ self._env.positions = self.atoms.positions / Bohr
201
+ try:
202
+ result = self._env.calculate(stress=stress)
203
+ except SCFConvergenceError as error:
204
+ raise CalculationFailed(str(error)) from error
205
+ assert result.forces is not None
206
+ # As in ASE's shell calculator, use CP2K's variational total energy.
207
+ self.results = {
208
+ "energy": result.energy * Hartree,
209
+ "free_energy": result.energy * Hartree,
210
+ "forces": result.forces * (Hartree / Bohr),
211
+ }
212
+ if result.stress is not None:
213
+ tensor = -result.stress * Hartree / Bohr**3
214
+ self.results["stress"] = tensor.flat[[0, 4, 8, 5, 2, 1]]
215
+
216
+ def close(self) -> None:
217
+ if not self._closed:
218
+ self._discard_environment()
219
+ self.reset() # type: ignore[no-untyped-call]
220
+ self._closed = True
221
+
222
+ def __enter__(self) -> CP2KCalculator:
223
+ if self._closed:
224
+ raise RuntimeError("This CP2K calculator is closed")
225
+ return self
226
+
227
+ def __exit__(self, *exc: object) -> None:
228
+ self.close()
cp2k/input.py ADDED
@@ -0,0 +1,91 @@
1
+ """Small, schema-independent serializer for native CP2K input dictionaries."""
2
+
3
+ # SPDX-License-Identifier: GPL-2.0-or-later
4
+
5
+ from collections.abc import Mapping
6
+ import math
7
+ from numbers import Real
8
+ import re
9
+ from typing import Any, TypeAlias
10
+
11
+ # Native CP2K validates the schema; this serializer accepts heterogeneous trees.
12
+ InputMapping: TypeAlias = Mapping[str, Any]
13
+
14
+
15
+ def _value(value: object) -> str:
16
+ if isinstance(value, bool):
17
+ return ".TRUE." if value else ".FALSE."
18
+ if isinstance(value, str):
19
+ if any(c in value for c in "\n\r\0"):
20
+ raise ValueError("Input values must be single lines without NUL characters")
21
+ return value
22
+ if isinstance(value, Real) and math.isfinite(value):
23
+ return str(value)
24
+ raise TypeError(f"Unsupported CP2K input value: {value!r}")
25
+
26
+
27
+ def input_to_string(tree: InputMapping) -> str:
28
+ """Serialize a mapping to CP2K input (without selecting physical defaults).
29
+
30
+ A mapping is a section; a list of mappings repeats a section. ``_`` gives
31
+ section parameters (e.g. ``KIND: {_: H, ...}``), ``_lines`` holds unparsed
32
+ single lines (e.g. coordinates). A list/tuple of scalars gives keyword
33
+ arguments; a list of lists repeats a keyword. ``None`` is a bare keyword.
34
+ Keys are case insensitive. Semantic validation remains CP2K's job.
35
+ """
36
+ if not isinstance(tree, Mapping):
37
+ raise TypeError("CP2K input must be a mapping")
38
+
39
+ def contents(section: InputMapping, depth: int) -> list[str]:
40
+ lines = []
41
+ indent = " " * depth
42
+ seen = set()
43
+ for key, value in section.items():
44
+ if not isinstance(key, str):
45
+ raise TypeError("Input keys must be strings")
46
+ name = key.upper()
47
+ if name in seen:
48
+ raise ValueError(f"Duplicate input key: {key}")
49
+ seen.add(name)
50
+ if name == "_":
51
+ if depth == 0:
52
+ raise ValueError("Section parameters are not valid at the root")
53
+ continue
54
+ if name == "_LINES":
55
+ if not isinstance(value, (list, tuple)):
56
+ raise TypeError("_lines must be a list of single lines")
57
+ for line in value:
58
+ text = _value(line)
59
+ if text.lstrip().startswith(("&", "@")):
60
+ raise ValueError("Use mappings for sections, not _lines")
61
+ lines.append(indent + text)
62
+ continue
63
+ if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_+\-]*", key):
64
+ raise ValueError(f"Invalid CP2K input key: {key!r}")
65
+ sections = [value] if isinstance(value, Mapping) else value
66
+ if (
67
+ isinstance(sections, (list, tuple))
68
+ and sections
69
+ and all(isinstance(item, Mapping) for item in sections)
70
+ ):
71
+ for child in sections:
72
+ parameter = child.get("_")
73
+ suffix = " " + _value(parameter) if parameter is not None else ""
74
+ lines.append(f"{indent}&{name}{suffix}")
75
+ lines.extend(contents(child, depth + 1))
76
+ lines.append(f"{indent}&END {name}")
77
+ elif value is None:
78
+ lines.append(indent + name)
79
+ elif isinstance(value, (list, tuple)):
80
+ if not value:
81
+ raise ValueError(f"Empty value list for {name}")
82
+ entries = value if isinstance(value[0], (list, tuple)) else [value]
83
+ for entry in entries:
84
+ if not isinstance(entry, (list, tuple)) or not entry:
85
+ raise ValueError(f"Invalid repeated keyword {name}")
86
+ lines.append(indent + name + " " + " ".join(map(_value, entry)))
87
+ else:
88
+ lines.append(indent + name + " " + _value(value))
89
+ return lines
90
+
91
+ return "\n".join(contents(tree, 0)) + "\n"