venuspython 1.0.5__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.
@@ -0,0 +1,358 @@
1
+ # This file is part of tblite.
2
+ # SPDX-Identifier: LGPL-3.0-or-later
3
+ #
4
+ # tblite is free software: you can redistribute it and/or modify it under
5
+ # the terms of the GNU Lesser General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # tblite is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU Lesser General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU Lesser General Public License
15
+ # along with tblite. If not, see <https://www.gnu.org/licenses/>.
16
+ """
17
+ The Python API of *tblite* natively support integration with the atomic simulation environment (`ASE`_).
18
+ By constructing a calculator most functionality of ASE is readily available.
19
+ For details on building the Python API checkout the :ref:`installation guide <python-build>`.
20
+
21
+ .. _ase: https://wiki.fysik.dtu.dk/ase/
22
+ """
23
+
24
+ try:
25
+ import ase
26
+ except ModuleNotFoundError:
27
+ raise ModuleNotFoundError("This submodule requires ASE installed")
28
+
29
+
30
+ from typing import List, Optional
31
+
32
+ from tblite.interface import Calculator
33
+ import ase.calculators.calculator
34
+ from ase.atoms import Atoms
35
+ from ase.units import Hartree, Bohr, kB
36
+
37
+
38
+ class TBLite(ase.calculators.calculator.Calculator):
39
+ """
40
+ ASE calculator for using xTB Hamiltonians from the tblite library.
41
+ Supported properties by this calculator are:
42
+
43
+ - energy (free_energy)
44
+ - forces
45
+ - stress
46
+ - dipole
47
+ - charges
48
+
49
+ Supported keywords are
50
+
51
+ ======================== ================= ============================================
52
+ Keyword Default Description
53
+ ======================== ================= ============================================
54
+ method "GFN2-xTB" Underlying method for energy and forces
55
+ accuracy 1.0 Numerical accuracy of the calculation
56
+ electronic_temperature 300.0 Electronic temperatur in Kelvin
57
+ max_iterations 250 Iterations for self-consistent evaluation
58
+ cache_api True Reuse generate API objects (recommended)
59
+ verbosity 1 Set verbosity of printout
60
+ ======================== ================= ============================================
61
+
62
+ Example
63
+ -------
64
+
65
+ An ASE calculator can be constructed by using the *TBLite* class provided by the *tblite.ase* module.
66
+ For example to perform a single point calculation for a CO\ :sub:`2` crystal use
67
+
68
+ >>> from tblite.ase import TBLite
69
+ >>> from ase.atoms import Atoms
70
+ >>> import numpy as np
71
+ >>> atoms = Atoms(
72
+ ... symbols="C4O8",
73
+ ... positions=np.array(
74
+ ... [
75
+ ... [0.9441259872, 0.9437851680, 0.9543505632],
76
+ ... [3.7179966528, 0.9556570368, 3.7316862240],
77
+ ... [3.7159517376, 3.7149292800, 0.9692330016],
78
+ ... [0.9529872864, 3.7220864832, 3.7296981120],
79
+ ... [1.6213905408, 1.6190616096, 1.6313879040],
80
+ ... [0.2656685664, 0.2694175776, 0.2776540416],
81
+ ... [4.3914553920, 1.6346256864, 3.0545920000],
82
+ ... [3.0440834880, 0.2764611744, 4.4080419264],
83
+ ... [4.3910577696, 3.0416409504, 0.2881058304],
84
+ ... [3.0399936576, 4.3879335936, 1.6497353376],
85
+ ... [0.2741322432, 4.4003734944, 3.0573754368],
86
+ ... [1.6312174944, 3.0434586528, 4.4023048032],
87
+ ... ]
88
+ ... ),
89
+ ... cell=np.array([5.68032, 5.68032, 5.68032]),
90
+ ... pbc=np.array([True, True, True]),
91
+ ... )
92
+ >>> atoms.calc = TBLite(method="GFN1-xTB")
93
+ >>> atoms.get_potential_energy() # result in eV
94
+ -1257.0943962462964
95
+
96
+ The resulting calculator can be used like most ASE calculator, *e.g.* for optimizing geometries.
97
+ """
98
+
99
+ implemented_properties = [
100
+ "energy",
101
+ "forces",
102
+ "charges",
103
+ "dipole",
104
+ "stress",
105
+ ]
106
+
107
+ default_parameters = {
108
+ "method": "GFN2-xTB",
109
+ "accuracy": 0.10, # 1.0, # Kazuumi change
110
+ "max_iterations": 500, # 250, # Kazuumi change
111
+ "electronic_temperature": 10.0, # 300.0, # Kazuumi change
112
+ "cache_api": True,
113
+ "verbosity": 1,
114
+ }
115
+
116
+ _res = None
117
+ _xtb = None
118
+
119
+ def __init__(
120
+ self,
121
+ input_path,
122
+ atoms: Optional[Atoms] = None,
123
+ **kwargs,
124
+ ):
125
+ """
126
+ Construct the TBLite base calculator object.
127
+ """
128
+
129
+ ase.calculators.calculator.Calculator.__init__(self, atoms=atoms, **kwargs)
130
+
131
+ self.xtbmethod = 'GFN2-xTB' # The semiempirical library to use
132
+ self.charge = 0
133
+ self.multiplicity = 2 # 2s+1
134
+
135
+ # self.memory = 1500 # In MB
136
+ # self.scratchdir = "/tmp"
137
+
138
+ # Read in the psi4 input
139
+ with open(input_path, 'r') as f:
140
+ for line in f:
141
+ strippedline=" ".join(line.split())
142
+ entries = strippedline.split(" ")
143
+ if (entries[0] == "memory"): self.memory = int(entries[1])
144
+ if (entries[0] == "scratchdir"): self.scratchdir = str(entries[1])
145
+ if (entries[0] == "xtbmethod"): self.psi4method = str(entries[1])
146
+ if (entries[0] == "charge"): self.charge = int(entries[1])
147
+ if (entries[0] == "multiplicity"): self.multiplicity = int(entries[1])
148
+
149
+ self.Nunpaired = self.multiplicity - 1
150
+
151
+ # Keep track of the number of restarts due to SCF convergence issues
152
+ self.accuracy_flag = False
153
+
154
+
155
+ def set(self, **kwargs) -> dict:
156
+ """
157
+ Set new parameters to TBLite. Will automatically reconstruct the underlying
158
+ model in case critical parameters change.
159
+
160
+ Example
161
+ -------
162
+ >>> from ase.build import molecule
163
+ >>> from tblite.ase import TBLite
164
+ >>> atoms = molecule("H2O")
165
+ >>> atoms.calc = TBLite(method="GFN2-xTB")
166
+ >>> atoms.get_potential_energy()
167
+ -137.96777625229421
168
+ >>> atoms.calc.set(method="GFN1-xTB")
169
+ {'method': 'GFN1-xTB'}
170
+ >>> atoms.get_potential_energy()
171
+ -156.9675057724589
172
+ """
173
+
174
+ changed_parameters = ase.calculators.calculator.Calculator.set(self, **kwargs)
175
+
176
+ # Always reset the calculation if parameters change
177
+ if changed_parameters:
178
+ self.reset()
179
+
180
+ # If the method is changed, invalidate the cached calculator as well
181
+ if "method" in changed_parameters:
182
+ self._xtb = None
183
+ self._res = None
184
+
185
+ # Minor changes can be updated in the API calculator directly
186
+ if self._xtb is not None:
187
+ if "accuracy" in changed_parameters:
188
+ self._xtb.set("accuracy", self.parameters.accuracy)
189
+
190
+ if "electronic_temperature" in changed_parameters:
191
+ self._xtb.set(
192
+ "temperature", self.parameters.electronic_temperature * kB / Hartree
193
+ )
194
+
195
+ if "max_iterations" in changed_parameters:
196
+ self._xtb.set("max-iter", self.parameters.max_iterations)
197
+
198
+ return changed_parameters
199
+
200
+ def reset(self) -> None:
201
+ """
202
+ Clear all information from old calculation. This will only remove the cached
203
+ API objects in case the `cache_api` is set to False.
204
+ """
205
+ ase.calculators.calculator.Calculator.reset(self)
206
+
207
+ if not self.parameters.cache_api:
208
+ self._xtb = None
209
+ self._res = None
210
+
211
+ def _check_api_calculator(self, system_changes: List[str]) -> None:
212
+ """Check state of API calculator and reset if necessary"""
213
+
214
+ # Changes in positions and cell parameters can use a normal update
215
+ _reset = system_changes.copy()
216
+ if "positions" in _reset:
217
+ _reset.remove("positions")
218
+ if "cell" in _reset:
219
+ _reset.remove("cell")
220
+
221
+ # Invalidate cached calculator and results object
222
+ if _reset:
223
+ self._xtb = None
224
+ self._res = None
225
+ else:
226
+ if system_changes and self._xtb is not None:
227
+ try:
228
+ _cell = self.atoms.cell
229
+ self._xtb.update(
230
+ self.atoms.positions / Bohr,
231
+ _cell / Bohr,
232
+ )
233
+ # An exception in this part means the geometry is bad,
234
+ # still we will give a complete reset a try as well
235
+ except RuntimeError:
236
+ self._xtb = None
237
+ self._res = None
238
+
239
+ def _create_api_calculator(self) -> Calculator:
240
+ """Create a new API calculator object"""
241
+
242
+ try:
243
+ _cell = self.atoms.cell
244
+ _periodic = self.atoms.pbc
245
+
246
+ # Kazuumi change:
247
+ # _charge = self.atoms.get_initial_charges().sum()
248
+ # _uhf = int(self.atoms.get_initial_magnetic_moments().sum().round())
249
+ _charge = self.charge
250
+ _uhf = self.Nunpaired
251
+
252
+ calc = Calculator(
253
+ self.parameters.method,
254
+ self.atoms.numbers,
255
+ self.atoms.positions / Bohr,
256
+ _charge,
257
+ _uhf,
258
+ _cell / Bohr,
259
+ _periodic,
260
+ )
261
+ calc.set("accuracy", self.parameters.accuracy)
262
+ calc.set(
263
+ "temperature", self.parameters.electronic_temperature * kB / Hartree
264
+ )
265
+ calc.set("max-iter", self.parameters.max_iterations)
266
+ calc.set("verbosity", self.parameters.verbosity)
267
+
268
+ except RuntimeError:
269
+ raise ase.calculators.calculator.InputError(
270
+ "Cannot construct calculator for TBLite"
271
+ )
272
+
273
+ return calc
274
+
275
+ def calculate(
276
+ self,
277
+ atoms: Optional[Atoms] = None,
278
+ properties: List[str] = None,
279
+ system_changes: List[str] = ase.calculators.calculator.all_changes,
280
+ ) -> None:
281
+ """
282
+ Perform actual calculation with by calling the TBLite API
283
+
284
+ Example
285
+ -------
286
+
287
+ >>> from ase.build import molecule
288
+ >>> from tblite.ase import TBLite
289
+ >>> calc = TBLite(method="GFN2-xTB")
290
+ >>> calc.calculate(molecule("H2O"))
291
+ >>> calc.get_potential_energy()
292
+ -137.96777625229421
293
+ >>> calc.calculate(molecule("CH4"))
294
+ >>> calc.get_potential_energy()
295
+ -113.60956621093894
296
+
297
+ Raises
298
+ ------
299
+ ase.calculators.calculator.InputError
300
+ on invalid input passed to the interface module
301
+
302
+ ase.calculators.calculator.CalculationFailed
303
+ in case of an `RuntimeError` in the library
304
+ """
305
+
306
+ if not properties:
307
+ properties = ["energy"]
308
+ ase.calculators.calculator.Calculator.calculate(
309
+ self, atoms, properties, system_changes
310
+ )
311
+ self.atoms = atoms.copy()
312
+
313
+ for i in range(100):
314
+ if (i==10):
315
+ raise ase.calculators.calculator.CalculationFailed(
316
+ "TBLite SCF convergence failed too many times in a row!"
317
+ )
318
+ # "TBLite could not evaluate input"
319
+
320
+ self._check_api_calculator(system_changes)
321
+
322
+ if self._xtb is None:
323
+ self._xtb = self._create_api_calculator()
324
+
325
+ try:
326
+ self._res = self._xtb.singlepoint(self._res)
327
+ if (self.accuracy_flag):
328
+ self.parameters.accuracy = self.parameters.accuracy/3.0
329
+ if (self.parameters.accuracy <= self.default_parameters["accuracy"]):
330
+ self.parameters.accuracy = self.default_parameters["accuracy"]
331
+ self.accuracy_flag = False
332
+
333
+ print("TBLite SCF convergence finally succeeded... lowering convergence criteria by 3 (now: %.4f) ..." % (self.parameters.accuracy))
334
+ system_changes = self.set(accuracy=self.parameters.accuracy)
335
+ if (self.atoms is None):
336
+ self.atoms = atoms.copy()
337
+ break
338
+
339
+ except RuntimeError:
340
+ self.parameters.accuracy = self.parameters.accuracy*3.0
341
+ system_changes = self.set(accuracy=self.parameters.accuracy)
342
+ system_changes = self.set(guess=0)
343
+ self.accuracy_flag = True
344
+ print("TBLite SCF convergence failed... raising convergence criteria by 3 (now: %.4f) and restarting..." % (self.parameters.accuracy))
345
+
346
+ if (self.atoms is None):
347
+ self.atoms = atoms.copy()
348
+
349
+ # These properties are garanteed to exist for all implemented calculators
350
+ self.results["energy"] = self._res.get("energy") * Hartree
351
+ self.results["free_energy"] = self.results["energy"]
352
+ self.results["forces"] = -self._res.get("gradient") * Hartree / Bohr
353
+ self.results["charges"] = self._res.get("charges")
354
+ self.results["dipole"] = self._res.get("dipole") * Bohr
355
+ # stress tensor is only returned for periodic systems
356
+ if self.atoms.pbc.any():
357
+ _stress = self._res.get("virial") * Hartree / self.atoms.get_volume()
358
+ self.results["stress"] = _stress.flat[[0, 4, 8, 5, 2, 1]]