forked from deepmodeling/dpdata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.py
More file actions
256 lines (204 loc) · 6.28 KB
/
driver.py
File metadata and controls
256 lines (204 loc) · 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Driver plugin system."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Callable
from .plugin import Plugin
if TYPE_CHECKING:
import ase.calculators.calculator
class Driver(ABC):
"""The base class for a driver plugin. A driver can
label a pure System to generate the LabeledSystem.
See Also
--------
dpdata.plugins.deepmd.DPDriver : an example of Driver
"""
__DriverPlugin = Plugin()
@staticmethod
def register(key: str) -> Callable:
"""Register a driver plugin. Used as decorators.
Parameters
----------
key : str
key of the plugin.
Returns
-------
Callable
decorator of a class
Examples
--------
>>> @Driver.register("some_driver")
... class SomeDriver(Driver):
... pass
"""
return Driver.__DriverPlugin.register(key)
@staticmethod
def get_driver(key: str) -> type[Driver]:
"""Get a driver plugin.
Parameters
----------
key : str
key of the plugin.
Returns
-------
Driver
the specific driver class
Raises
------
RuntimeError
if the requested driver is not implemented
"""
try:
return Driver.__DriverPlugin.plugins[key]
except KeyError as e:
raise RuntimeError("Unknown driver: " + key) from e
@staticmethod
def get_drivers() -> dict:
"""Get all driver plugins.
Returns
-------
dict
dict for all driver plugisn
"""
return Driver.__DriverPlugin.plugins
def __init__(self, *args, **kwargs) -> None:
"""Setup the driver."""
@abstractmethod
def label(self, data: dict) -> dict:
"""Label a system data. Returns new data with energy, forces, and virials.
Parameters
----------
data : dict
data with coordinates and atom types
Returns
-------
dict
labeled data with energies and forces
"""
return NotImplemented
@property
def ase_calculator(self) -> ase.calculators.calculator.Calculator:
"""Returns an ase calculator based on this driver."""
from .ase_calculator import DPDataCalculator
return DPDataCalculator(self)
@Driver.register("hybrid")
class HybridDriver(Driver):
"""Hybrid driver, with mixed drivers.
Parameters
----------
drivers : list[dict, Driver]
list of drivers or drivers dict. For a dict, it should
contain `type` as the name of the driver, and others
are arguments of the driver.
Raises
------
TypeError
The value of `drivers` is not a dict or `Driver`.
Examples
--------
>>> driver = HybridDriver([
... {"type": "sqm", "qm_theory": "DFTB3"},
... {"type": "dp", "dp": "frozen_model.pb"},
... ])
This driver is the hybrid of SQM and DP.
"""
def __init__(self, drivers: list[dict | Driver]) -> None:
self.drivers = []
for driver in drivers:
if isinstance(driver, Driver):
self.drivers.append(driver)
elif isinstance(driver, dict):
type = driver["type"]
del driver["type"]
self.drivers.append(Driver.get_driver(type)(**driver))
else:
raise TypeError("driver should be Driver or dict")
def label(self, data: dict) -> dict:
"""Label a system data.
Energies and forces are the sum of those of each driver.
Parameters
----------
data : dict
data with coordinates and atom types
Returns
-------
dict
labeled data with energies and forces
"""
labeled_data = {}
for ii, driver in enumerate(self.drivers):
lb_data = driver.label(data.copy())
if ii == 0:
labeled_data = lb_data.copy()
else:
labeled_data["energies"] += lb_data["energies"]
if "forces" in labeled_data and "forces" in lb_data:
labeled_data["forces"] += lb_data["forces"]
if "virials" in labeled_data and "virials" in lb_data:
labeled_data["virials"] += lb_data["virials"]
return labeled_data
class Minimizer(ABC):
"""The base class for a minimizer plugin. A minimizer can
minimize geometry.
"""
__MinimizerPlugin = Plugin()
@staticmethod
def register(key: str) -> Callable:
"""Register a minimizer plugin. Used as decorators.
Parameters
----------
key : str
key of the plugin.
Returns
-------
Callable
decorator of a class
Examples
--------
>>> @Minimizer.register("some_minimizer")
... class SomeMinimizer(Minimizer):
... pass
"""
return Minimizer.__MinimizerPlugin.register(key)
@staticmethod
def get_minimizer(key: str) -> type[Minimizer]:
"""Get a minimizer plugin.
Parameters
----------
key : str
key of the plugin.
Returns
-------
Minimizer
the specific minimizer class
Raises
------
RuntimeError
if the requested minimizer is not implemented
"""
try:
return Minimizer.__MinimizerPlugin.plugins[key]
except KeyError as e:
raise RuntimeError("Unknown minimizer: " + key) from e
@staticmethod
def get_minimizers() -> dict:
"""Get all minimizer plugins.
Returns
-------
dict
dict for all minimizer plugisn
"""
return Minimizer.__MinimizerPlugin.plugins
def __init__(self, *args, **kwargs) -> None:
"""Setup the minimizer."""
@abstractmethod
def minimize(self, data: dict) -> dict:
"""Minimize the geometry.
Parameters
----------
data : dict
data with coordinates and atom types
Returns
-------
dict
labeled data with minimized coordinates, energies, and forces
"""