nomad-parser-plugins-electronic 1.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.
Files changed (272) hide show
  1. electronicparsers/__init__.py +1162 -0
  2. electronicparsers/abacus/__init__.py +20 -0
  3. electronicparsers/abacus/__main__.py +32 -0
  4. electronicparsers/abacus/metainfo/__init__.py +19 -0
  5. electronicparsers/abacus/metainfo/abacus.py +836 -0
  6. electronicparsers/abacus/nomad_plugin.yaml +44 -0
  7. electronicparsers/abacus/parser.py +1975 -0
  8. electronicparsers/abinit/__init__.py +19 -0
  9. electronicparsers/abinit/__main__.py +31 -0
  10. electronicparsers/abinit/metainfo/__init__.py +20 -0
  11. electronicparsers/abinit/metainfo/abinit.py +871 -0
  12. electronicparsers/abinit/metainfo/abinit_autogenerated.py +6794 -0
  13. electronicparsers/abinit/nomad_plugin.yaml +43 -0
  14. electronicparsers/abinit/parser.py +1922 -0
  15. electronicparsers/ams/__init__.py +19 -0
  16. electronicparsers/ams/__main__.py +31 -0
  17. electronicparsers/ams/metainfo/__init__.py +19 -0
  18. electronicparsers/ams/metainfo/ams.py +769 -0
  19. electronicparsers/ams/nomad_plugin.yaml +19 -0
  20. electronicparsers/ams/parser.py +1849 -0
  21. electronicparsers/ams/rkf.py +620 -0
  22. electronicparsers/atk/__init__.py +19 -0
  23. electronicparsers/atk/__main__.py +31 -0
  24. electronicparsers/atk/metainfo/__init__.py +19 -0
  25. electronicparsers/atk/metainfo/atk.py +71 -0
  26. electronicparsers/atk/nomad_plugin.yaml +34 -0
  27. electronicparsers/atk/parser.py +388 -0
  28. electronicparsers/bigdft/__init__.py +19 -0
  29. electronicparsers/bigdft/__main__.py +31 -0
  30. electronicparsers/bigdft/metainfo/__init__.py +18 -0
  31. electronicparsers/bigdft/nomad_plugin.yaml +19 -0
  32. electronicparsers/bigdft/parser.py +372 -0
  33. electronicparsers/castep/__init__.py +19 -0
  34. electronicparsers/castep/__main__.py +31 -0
  35. electronicparsers/castep/metainfo/__init__.py +19 -0
  36. electronicparsers/castep/metainfo/castep.py +2481 -0
  37. electronicparsers/castep/nomad_plugin.yaml +28 -0
  38. electronicparsers/castep/parser.py +1680 -0
  39. electronicparsers/charmm/__init__.py +19 -0
  40. electronicparsers/charmm/__main__.py +31 -0
  41. electronicparsers/charmm/metainfo/__init__.py +19 -0
  42. electronicparsers/charmm/metainfo/charmm.py +1931 -0
  43. electronicparsers/charmm/nomad_plugin.yaml +18 -0
  44. electronicparsers/charmm/parser.py +61 -0
  45. electronicparsers/cp2k/__init__.py +19 -0
  46. electronicparsers/cp2k/__main__.py +31 -0
  47. electronicparsers/cp2k/metainfo/__init__.py +19 -0
  48. electronicparsers/cp2k/metainfo/cp2k.py +59185 -0
  49. electronicparsers/cp2k/metainfo/cp2k_general.py +1014 -0
  50. electronicparsers/cp2k/nomad_plugin.yaml +49 -0
  51. electronicparsers/cp2k/parser.py +2324 -0
  52. electronicparsers/cpmd/__init__.py +19 -0
  53. electronicparsers/cpmd/__main__.py +31 -0
  54. electronicparsers/cpmd/metainfo/__init__.py +19 -0
  55. electronicparsers/cpmd/metainfo/cpmd.py +10733 -0
  56. electronicparsers/cpmd/metainfo/cpmd_general.py +988 -0
  57. electronicparsers/cpmd/nomad_plugin.yaml +19 -0
  58. electronicparsers/cpmd/parser.py +680 -0
  59. electronicparsers/crystal/__init__.py +19 -0
  60. electronicparsers/crystal/__main__.py +31 -0
  61. electronicparsers/crystal/metainfo/__init__.py +19 -0
  62. electronicparsers/crystal/metainfo/crystal.py +619 -0
  63. electronicparsers/crystal/nomad_plugin.yaml +36 -0
  64. electronicparsers/crystal/parser.py +1745 -0
  65. electronicparsers/dmol3/__init__.py +19 -0
  66. electronicparsers/dmol3/__main__.py +31 -0
  67. electronicparsers/dmol3/metainfo/__init__.py +19 -0
  68. electronicparsers/dmol3/metainfo/dmol3.py +664 -0
  69. electronicparsers/dmol3/nomad_plugin.yaml +19 -0
  70. electronicparsers/dmol3/parser.py +750 -0
  71. electronicparsers/edmft/__init__.py +19 -0
  72. electronicparsers/edmft/__main__.py +31 -0
  73. electronicparsers/edmft/metainfo/__init__.py +19 -0
  74. electronicparsers/edmft/metainfo/edmft.py +96 -0
  75. electronicparsers/edmft/nomad_plugin.yaml +53 -0
  76. electronicparsers/edmft/parser.py +912 -0
  77. electronicparsers/elk/__init__.py +19 -0
  78. electronicparsers/elk/__main__.py +31 -0
  79. electronicparsers/elk/metainfo/__init__.py +19 -0
  80. electronicparsers/elk/metainfo/elk.py +775 -0
  81. electronicparsers/elk/nomad_plugin.yaml +19 -0
  82. electronicparsers/elk/parser.py +493 -0
  83. electronicparsers/exciting/__init__.py +19 -0
  84. electronicparsers/exciting/__main__.py +31 -0
  85. electronicparsers/exciting/metainfo/__init__.py +19 -0
  86. electronicparsers/exciting/metainfo/exciting.py +2942 -0
  87. electronicparsers/exciting/nomad_plugin.yaml +83 -0
  88. electronicparsers/exciting/parser.py +3398 -0
  89. electronicparsers/fhiaims/__init__.py +19 -0
  90. electronicparsers/fhiaims/__main__.py +31 -0
  91. electronicparsers/fhiaims/metainfo/__init__.py +19 -0
  92. electronicparsers/fhiaims/metainfo/fhi_aims.py +1565 -0
  93. electronicparsers/fhiaims/nomad_plugin.yaml +52 -0
  94. electronicparsers/fhiaims/parser.py +2582 -0
  95. electronicparsers/fleur/__init__.py +19 -0
  96. electronicparsers/fleur/__main__.py +31 -0
  97. electronicparsers/fleur/metainfo/__init__.py +19 -0
  98. electronicparsers/fleur/metainfo/fleur.py +623 -0
  99. electronicparsers/fleur/nomad_plugin.yaml +19 -0
  100. electronicparsers/fleur/parser.py +952 -0
  101. electronicparsers/fplo/__init__.py +19 -0
  102. electronicparsers/fplo/__main__.py +31 -0
  103. electronicparsers/fplo/metainfo/__init__.py +19 -0
  104. electronicparsers/fplo/metainfo/fplo.py +188 -0
  105. electronicparsers/fplo/metainfo/fplo_input_autogenerated.py +2744 -0
  106. electronicparsers/fplo/metainfo/fplo_temporaries.py +319 -0
  107. electronicparsers/fplo/nomad_plugin.yaml +19 -0
  108. electronicparsers/fplo/parser.py +42 -0
  109. electronicparsers/gamess/__init__.py +19 -0
  110. electronicparsers/gamess/__main__.py +31 -0
  111. electronicparsers/gamess/metainfo/__init__.py +19 -0
  112. electronicparsers/gamess/metainfo/gamess.py +837 -0
  113. electronicparsers/gamess/nomad_plugin.yaml +19 -0
  114. electronicparsers/gamess/parser.py +941 -0
  115. electronicparsers/gaussian/__init__.py +19 -0
  116. electronicparsers/gaussian/__main__.py +31 -0
  117. electronicparsers/gaussian/metainfo/__init__.py +19 -0
  118. electronicparsers/gaussian/metainfo/gaussian.py +1707 -0
  119. electronicparsers/gaussian/nomad_plugin.yaml +18 -0
  120. electronicparsers/gaussian/parser.py +1556 -0
  121. electronicparsers/gpaw/__init__.py +19 -0
  122. electronicparsers/gpaw/__main__.py +31 -0
  123. electronicparsers/gpaw/metainfo/__init__.py +19 -0
  124. electronicparsers/gpaw/metainfo/gpaw.py +214 -0
  125. electronicparsers/gpaw/nomad_plugin.yaml +19 -0
  126. electronicparsers/gpaw/parser.py +671 -0
  127. electronicparsers/magres/__init__.py +19 -0
  128. electronicparsers/magres/__main__.py +31 -0
  129. electronicparsers/magres/metainfo/__init__.py +19 -0
  130. electronicparsers/magres/metainfo/magres.py +110 -0
  131. electronicparsers/magres/nomad_plugin.yaml +18 -0
  132. electronicparsers/magres/parser.py +505 -0
  133. electronicparsers/molcas/__init__.py +19 -0
  134. electronicparsers/molcas/__main__.py +31 -0
  135. electronicparsers/molcas/metainfo/__init__.py +19 -0
  136. electronicparsers/molcas/metainfo/molcas.py +151 -0
  137. electronicparsers/molcas/nomad_plugin.yaml +19 -0
  138. electronicparsers/molcas/parser.py +59 -0
  139. electronicparsers/mopac/__init__.py +19 -0
  140. electronicparsers/mopac/__main__.py +31 -0
  141. electronicparsers/mopac/metainfo/__init__.py +19 -0
  142. electronicparsers/mopac/metainfo/mopac.py +79 -0
  143. electronicparsers/mopac/nomad_plugin.yaml +19 -0
  144. electronicparsers/mopac/parser.py +304 -0
  145. electronicparsers/nwchem/__init__.py +19 -0
  146. electronicparsers/nwchem/__main__.py +31 -0
  147. electronicparsers/nwchem/metainfo/__init__.py +19 -0
  148. electronicparsers/nwchem/metainfo/nwchem.py +487 -0
  149. electronicparsers/nwchem/nomad_plugin.yaml +19 -0
  150. electronicparsers/nwchem/parser.py +757 -0
  151. electronicparsers/ocean/__init__.py +19 -0
  152. electronicparsers/ocean/__main__.py +31 -0
  153. electronicparsers/ocean/metainfo/__init__.py +19 -0
  154. electronicparsers/ocean/metainfo/ocean.py +410 -0
  155. electronicparsers/ocean/nomad_plugin.yaml +37 -0
  156. electronicparsers/ocean/parser.py +344 -0
  157. electronicparsers/octopus/__init__.py +19 -0
  158. electronicparsers/octopus/__main__.py +31 -0
  159. electronicparsers/octopus/metainfo/__init__.py +19 -0
  160. electronicparsers/octopus/metainfo/octopus.py +71 -0
  161. electronicparsers/octopus/metainfo/octopus_autogenerated.py +11647 -0
  162. electronicparsers/octopus/nomad_plugin.yaml +41 -0
  163. electronicparsers/octopus/parser.py +1214 -0
  164. electronicparsers/onetep/__init__.py +19 -0
  165. electronicparsers/onetep/__main__.py +31 -0
  166. electronicparsers/onetep/metainfo/__init__.py +19 -0
  167. electronicparsers/onetep/metainfo/onetep.py +3443 -0
  168. electronicparsers/onetep/nomad_plugin.yaml +19 -0
  169. electronicparsers/onetep/parser.py +577 -0
  170. electronicparsers/openmx/__init__.py +19 -0
  171. electronicparsers/openmx/__main__.py +31 -0
  172. electronicparsers/openmx/metainfo/__init__.py +19 -0
  173. electronicparsers/openmx/metainfo/openmx.py +24 -0
  174. electronicparsers/openmx/nomad_plugin.yaml +25 -0
  175. electronicparsers/openmx/parser.py +918 -0
  176. electronicparsers/orca/__init__.py +19 -0
  177. electronicparsers/orca/__main__.py +31 -0
  178. electronicparsers/orca/metainfo/__init__.py +19 -0
  179. electronicparsers/orca/metainfo/orca.py +1448 -0
  180. electronicparsers/orca/nomad_plugin.yaml +19 -0
  181. electronicparsers/orca/parser.py +1371 -0
  182. electronicparsers/psi4/__init__.py +19 -0
  183. electronicparsers/psi4/__main__.py +31 -0
  184. electronicparsers/psi4/metainfo/__init__.py +19 -0
  185. electronicparsers/psi4/metainfo/psi4.py +372 -0
  186. electronicparsers/psi4/nomad_plugin.yaml +27 -0
  187. electronicparsers/psi4/parser.py +1362 -0
  188. electronicparsers/qball/__init__.py +19 -0
  189. electronicparsers/qball/__main__.py +31 -0
  190. electronicparsers/qball/metainfo/__init__.py +19 -0
  191. electronicparsers/qball/metainfo/qball.py +27 -0
  192. electronicparsers/qball/nomad_plugin.yaml +25 -0
  193. electronicparsers/qball/parser.py +152 -0
  194. electronicparsers/qbox/__init__.py +19 -0
  195. electronicparsers/qbox/__main__.py +31 -0
  196. electronicparsers/qbox/metainfo/__init__.py +19 -0
  197. electronicparsers/qbox/metainfo/qbox.py +490 -0
  198. electronicparsers/qbox/nomad_plugin.yaml +19 -0
  199. electronicparsers/qbox/parser.py +508 -0
  200. electronicparsers/quantumespresso/__init__.py +19 -0
  201. electronicparsers/quantumespresso/__main__.py +31 -0
  202. electronicparsers/quantumespresso/metainfo/__init__.py +19 -0
  203. electronicparsers/quantumespresso/metainfo/quantum_espresso.py +3296 -0
  204. electronicparsers/quantumespresso/nomad_plugin.yaml +31 -0
  205. electronicparsers/quantumespresso/parser.py +3594 -0
  206. electronicparsers/siesta/__init__.py +19 -0
  207. electronicparsers/siesta/__main__.py +31 -0
  208. electronicparsers/siesta/metainfo/__init__.py +19 -0
  209. electronicparsers/siesta/metainfo/siesta.py +141 -0
  210. electronicparsers/siesta/metainfo/siesta_autogenerated.py +3365 -0
  211. electronicparsers/siesta/nomad_plugin.yaml +19 -0
  212. electronicparsers/siesta/parser.py +607 -0
  213. electronicparsers/soliddmft/__init__.py +19 -0
  214. electronicparsers/soliddmft/__main__.py +31 -0
  215. electronicparsers/soliddmft/metainfo/__init__.py +19 -0
  216. electronicparsers/soliddmft/metainfo/soliddmft.py +274 -0
  217. electronicparsers/soliddmft/nomad_plugin.yaml +26 -0
  218. electronicparsers/soliddmft/parser.py +727 -0
  219. electronicparsers/tbstudio/__init__.py +19 -0
  220. electronicparsers/tbstudio/__main__.py +31 -0
  221. electronicparsers/tbstudio/metainfo/__init__.py +19 -0
  222. electronicparsers/tbstudio/metainfo/tbstudio.py +34 -0
  223. electronicparsers/tbstudio/nomad_plugin.yaml +24 -0
  224. electronicparsers/tbstudio/parser.py +412 -0
  225. electronicparsers/turbomole/__init__.py +19 -0
  226. electronicparsers/turbomole/__main__.py +31 -0
  227. electronicparsers/turbomole/metainfo/__init__.py +19 -0
  228. electronicparsers/turbomole/metainfo/turbomole.py +727 -0
  229. electronicparsers/turbomole/nomad_plugin.yaml +18 -0
  230. electronicparsers/turbomole/parser.py +1585 -0
  231. electronicparsers/utils/__init__.py +20 -0
  232. electronicparsers/utils/magres_workflow.py +61 -0
  233. electronicparsers/utils/utils.py +636 -0
  234. electronicparsers/vasp/__init__.py +19 -0
  235. electronicparsers/vasp/__main__.py +31 -0
  236. electronicparsers/vasp/metainfo/__init__.py +19 -0
  237. electronicparsers/vasp/metainfo/vasp.py +169 -0
  238. electronicparsers/vasp/metainfo/vasp_incars.py +3428 -0
  239. electronicparsers/vasp/metainfo/vasp_incarsOut.py +3428 -0
  240. electronicparsers/vasp/metainfo/vasp_incarsUnknown.py +86 -0
  241. electronicparsers/vasp/nomad_plugin.yaml +28 -0
  242. electronicparsers/vasp/parser.py +2340 -0
  243. electronicparsers/w2dynamics/__init__.py +19 -0
  244. electronicparsers/w2dynamics/__main__.py +31 -0
  245. electronicparsers/w2dynamics/metainfo/__init__.py +19 -0
  246. electronicparsers/w2dynamics/metainfo/w2dynamics.py +1270 -0
  247. electronicparsers/w2dynamics/nomad_plugin.yaml +36 -0
  248. electronicparsers/w2dynamics/parser.py +674 -0
  249. electronicparsers/wannier90/__init__.py +19 -0
  250. electronicparsers/wannier90/__main__.py +31 -0
  251. electronicparsers/wannier90/metainfo/__init__.py +19 -0
  252. electronicparsers/wannier90/metainfo/wannier90.py +56 -0
  253. electronicparsers/wannier90/nomad_plugin.yaml +34 -0
  254. electronicparsers/wannier90/parser.py +671 -0
  255. electronicparsers/wien2k/__init__.py +19 -0
  256. electronicparsers/wien2k/__main__.py +31 -0
  257. electronicparsers/wien2k/metainfo/__init__.py +19 -0
  258. electronicparsers/wien2k/metainfo/wien2k.py +783 -0
  259. electronicparsers/wien2k/nomad_plugin.yaml +18 -0
  260. electronicparsers/wien2k/parser.py +1133 -0
  261. electronicparsers/yambo/__init__.py +19 -0
  262. electronicparsers/yambo/__main__.py +31 -0
  263. electronicparsers/yambo/metainfo/__init__.py +19 -0
  264. electronicparsers/yambo/metainfo/yambo.py +577 -0
  265. electronicparsers/yambo/nomad_plugin.yaml +31 -0
  266. electronicparsers/yambo/parser.py +896 -0
  267. nomad_parser_plugins_electronic-1.0.dist-info/LICENSE +202 -0
  268. nomad_parser_plugins_electronic-1.0.dist-info/METADATA +360 -0
  269. nomad_parser_plugins_electronic-1.0.dist-info/RECORD +272 -0
  270. nomad_parser_plugins_electronic-1.0.dist-info/WHEEL +5 -0
  271. nomad_parser_plugins_electronic-1.0.dist-info/entry_points.txt +43 -0
  272. nomad_parser_plugins_electronic-1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1680 @@
1
+ #
2
+ # Copyright The NOMAD Authors.
3
+ #
4
+ # This file is part of NOMAD.
5
+ # See https://nomad-lab.eu for further info.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ #
19
+ import os
20
+ import numpy as np
21
+ import logging
22
+ import re
23
+ from datetime import datetime
24
+
25
+ from nomad.units import ureg
26
+ from nomad.parsing.file_parser import TextParser, Quantity
27
+ from runschema.run import Run, Program, TimeRun
28
+ from runschema.method import (
29
+ Functional,
30
+ Method,
31
+ DFT,
32
+ Electronic,
33
+ XCFunctional,
34
+ Smearing,
35
+ BasisSetContainer,
36
+ BasisSet,
37
+ AtomParameters,
38
+ )
39
+ from runschema.system import System, Atoms
40
+ from runschema.calculation import (
41
+ Calculation,
42
+ Energy,
43
+ EnergyEntry,
44
+ Forces,
45
+ ForcesEntry,
46
+ Thermodynamics,
47
+ Stress,
48
+ StressEntry,
49
+ Charges,
50
+ ChargesValue,
51
+ ScfIteration,
52
+ BandStructure,
53
+ BandEnergies,
54
+ VibrationalFrequencies,
55
+ VibrationalFrequenciesValues,
56
+ )
57
+ from simulationworkflowschema import (
58
+ GeometryOptimization,
59
+ GeometryOptimizationMethod,
60
+ MolecularDynamics,
61
+ MolecularDynamicsMethod,
62
+ SinglePoint,
63
+ Phonon,
64
+ )
65
+
66
+ from .metainfo.castep import (
67
+ x_castep_section_phonons,
68
+ x_castep_section_scf_parameters,
69
+ x_castep_section_density_mixing_parameters,
70
+ x_castep_section_population_analysis_parameters,
71
+ x_castep_section_core_parameters,
72
+ x_castep_section_band_parameters,
73
+ x_castep_section_ts_parameters,
74
+ x_castep_section_optics_parameters,
75
+ x_castep_section_electronic_spectroscpy_parameters,
76
+ x_castep_section_tddft_parameters,
77
+ x_castep_section_atom_positions,
78
+ x_castep_section_vibrational_frequencies,
79
+ x_castep_section_tddft,
80
+ x_castep_section_DFT_SEDC,
81
+ x_castep_section_van_der_Waals_parameters,
82
+ x_castep_section_time,
83
+ x_castep_section_raman_tensor,
84
+ )
85
+
86
+ from ..utils import get_files
87
+
88
+ # TODO map all castep units
89
+ units_map = {
90
+ 'A': ureg.angstrom,
91
+ 'amu': ureg.amu,
92
+ 'ps': ureg.ps,
93
+ 'e': ureg.e,
94
+ 'eV': ureg.eV,
95
+ 'K': ureg.K,
96
+ 'GPa': ureg.GPa,
97
+ 'hbar': ureg.hbar,
98
+ 'cm': ureg.cm,
99
+ 'D': ureg.D,
100
+ 'mol': ureg.mol,
101
+ 'J': ureg.J,
102
+ 'atom': 1,
103
+ 'steps': 1,
104
+ 'iterations': 1,
105
+ }
106
+
107
+
108
+ def resolve_unit(unit_str, parts=[]):
109
+ unit_str = unit_str.replace(' ', '')
110
+ parts = list(parts)
111
+
112
+ if unit_str in units_map:
113
+ return units_map[unit_str]
114
+
115
+ try:
116
+ return float(unit_str)
117
+ except Exception:
118
+ pass
119
+
120
+ if unit_str == '':
121
+ return 1
122
+
123
+ open_p = unit_str.rfind('(')
124
+ if open_p > -1:
125
+ n_groups = unit_str.count('(')
126
+ if n_groups != unit_str.count(')'):
127
+ return unit_str
128
+ for n in range(n_groups):
129
+ part = unit_str[open_p + 1 :]
130
+ part = part[: part.find(')')]
131
+ parts.append(resolve_unit(part, parts))
132
+ unit_str = unit_str.replace('(%s)' % part, '[%d]' % n)
133
+ open_p = unit_str.rfind('(')
134
+ return resolve_unit(unit_str, parts)
135
+
136
+ vals = unit_str.split('/')
137
+ if len(vals) > 1:
138
+ vals = [resolve_unit(v, parts) for v in vals]
139
+ val = vals[0]
140
+ for v in vals[1:]:
141
+ val /= v
142
+ return val
143
+
144
+ vals = unit_str.split('**')
145
+ if len(vals) > 1:
146
+ vals = [resolve_unit(v, parts) for v in vals]
147
+ val = vals[0]
148
+ for v in reversed(vals[1:]):
149
+ val = val**v
150
+ return val
151
+
152
+ vals = unit_str.split('*')
153
+ if len(vals) > 1:
154
+ vals = [resolve_unit(v, parts) for v in vals]
155
+ unit = 1
156
+ for v in vals:
157
+ unit *= v
158
+ return unit
159
+
160
+ vals = unit_str.split('-1')
161
+ if len(vals) == 2:
162
+ return 1 / resolve_unit(vals[0], parts)
163
+
164
+ vals = re.match(r'\[(\d+)\]', unit_str)
165
+ if vals:
166
+ return parts[int(vals.group(1))]
167
+
168
+
169
+ class CellParser(TextParser):
170
+ def __init__(self):
171
+ super().__init__()
172
+
173
+ def init_quantities(self):
174
+ def str_to_block(val_in):
175
+ val = val_in.split('\n')
176
+ key = val[0].strip().lower()
177
+ return key, [v.split() for v in val[1:] if v and v[0] not in ('#', '!')]
178
+
179
+ def str_to_value(val_in):
180
+ key, val = val_in.split(' ', 1)
181
+ return key.strip().lower(), val
182
+
183
+ self._quantities = [
184
+ Quantity(
185
+ 'block',
186
+ r'\s\%(?:block|BLOCK)\s*([\s\S]+?)\%(?:endblock|ENDBLOCK)',
187
+ str_operation=str_to_block,
188
+ repeats=True,
189
+ ),
190
+ Quantity(
191
+ 'value',
192
+ r'\s(\w.+?)\s*:\s*([^\n]+)',
193
+ str_operation=str_to_value,
194
+ repeats=True,
195
+ ),
196
+ ]
197
+
198
+ def get_value(self, key, default=None):
199
+ for source in ['value', 'block']:
200
+ for val in self.get(source, []):
201
+ if val[0] == key:
202
+ return val[1]
203
+ return default
204
+
205
+
206
+ class BandsParser(TextParser):
207
+ def __init__(self):
208
+ super().__init__()
209
+
210
+ def init_quantities(self):
211
+ def str_to_kpt_energies(val_in):
212
+ val = [v.split() for v in val_in.split('\n')]
213
+ kpt = np.array(val[0][:3], dtype=np.dtype(np.float64))
214
+ energies = np.array(
215
+ [v[0] for v in val if len(v) == 1], dtype=np.dtype(np.float64)
216
+ )
217
+ return kpt, energies
218
+
219
+ self._quantities = [
220
+ Quantity('n_kpoints', r'Number of k-points\s*(\d+)', dtype=np.int32),
221
+ Quantity('n_spins', r'Number of spin components\s*(\d+)', dtype=np.int32),
222
+ Quantity(
223
+ 'n_electrons', r'Number of electrons\s*([\d\. ]+)', dtype=np.float64
224
+ ),
225
+ Quantity(
226
+ 'n_eigenvalues', r'Number of eigenvalues\s*([\d\. ]+)', dtype=np.float64
227
+ ),
228
+ Quantity(
229
+ 'fermi_energies',
230
+ r'Fermi energies \(in atomic units\)\s*([\d\.\- ]+)',
231
+ dtype=np.float64,
232
+ units=ureg.hartree,
233
+ ),
234
+ Quantity(
235
+ 'kpt_energies',
236
+ r'point\s*\d+\s*([\s\S]+?)(?:K\-|\Z)',
237
+ repeats=True,
238
+ str_operation=str_to_kpt_energies,
239
+ convert=False,
240
+ ),
241
+ ]
242
+
243
+
244
+ class OutParser(TextParser):
245
+ def __init__(self):
246
+ super().__init__()
247
+
248
+ def init_quantities(self):
249
+ re_float = r'[\d\.\-\+Ee]+'
250
+
251
+ def str_to_title(val_in):
252
+ def add_unit(val):
253
+ val_unit = val.rsplit(' ', 1)
254
+ if len(val_unit) == 2:
255
+ try:
256
+ val_str = val_unit[1].strip()
257
+ unit = resolve_unit(val_str)
258
+ units_map[val_str] = unit
259
+ val = float(val_unit[0]) * unit
260
+ except Exception:
261
+ pass
262
+ return val
263
+
264
+ re_section = re.compile(r' *\*+ *(.+?) *\*+ *')
265
+ re_value = re.compile(r' *(.+?)\s*:\s*(.+)')
266
+ title = dict()
267
+ # necessary to cache last quantity for multi-line values such as custom xc func
268
+ last_parameter = []
269
+ for line in val_in.split('\n'):
270
+ section = re_section.match(line)
271
+ if section:
272
+ key = section.group(1).lower()
273
+ title[key] = dict()
274
+ continue
275
+ value = re_value.match(line)
276
+ if value:
277
+ sub_key = value.group(1).strip().lower()
278
+ if sub_key not in title[key]:
279
+ title[key][sub_key] = []
280
+ val = (
281
+ value.group(2).strip().strip(':')
282
+ ) # misformattig of custom xc func
283
+ if not val:
284
+ last_parameter = [sub_key, []]
285
+ continue
286
+ title[key][sub_key].append(add_unit(val))
287
+ if last_parameter:
288
+ title[key][last_parameter[0]].extend(last_parameter[1])
289
+ last_parameter = []
290
+ elif line and last_parameter:
291
+ last_parameter[1].append(add_unit(line.strip()))
292
+
293
+ for key in title.keys():
294
+ for sub_key, val in title[key].items():
295
+ title[key][sub_key] = val[0] if len(val) == 1 else val
296
+
297
+ return title
298
+
299
+ def str_to_lattice_vectors(val_in):
300
+ val = val_in.strip().split('\n')
301
+ val = np.array([v.split() for v in val[1:]], dtype=np.dtype(np.float64)).T
302
+ return [val[0:3].T, val[3:6].T]
303
+
304
+ def str_to_lattice_parameters(val_in):
305
+ re_parameter = rf'(\w+)\s*=\s*({re_float})'
306
+ parameters = {p[0]: float(p[1]) for p in re.findall(re_parameter, val_in)}
307
+ return parameters
308
+
309
+ def str_to_array(val_in):
310
+ val = [v.strip().strip('x').strip('*').split() for v in val_in.split('\n')]
311
+ val = np.transpose(
312
+ [[vi.split('(')[0] for vi in v] for v in val if len(v) == 5]
313
+ )
314
+ array = np.array(val[-3:], dtype=np.dtype(np.float64)).T
315
+ return val[0], array
316
+
317
+ def str_to_kpt_energies(val_in):
318
+ spin = re.search(r'Spin=(\d+)', val_in)
319
+ spin = int(spin.group(1)) if spin else 1
320
+ kpt = re.search(r'kpt=\s*\d+\s*\(([\d\.\- ]+)\)', val_in)
321
+ kpt = (
322
+ np.array(kpt.group(1).split(), dtype=np.dtype(np.float64))
323
+ if kpt
324
+ else [0.0, 0.0, 0.0]
325
+ )
326
+ re_energies = re.compile(rf'\+\s*\d+\s*({re_float})\s*\+')
327
+ energies = re.findall(re_energies, val_in)
328
+ if energies:
329
+ energies = np.array(energies, dtype=np.dtype(np.float64))
330
+ return spin, kpt, energies
331
+
332
+ def str_to_scf(val_in):
333
+ result = []
334
+ for val in val_in.strip().split('\n'):
335
+ val = val.split()
336
+ if not val:
337
+ continue
338
+ if val[0].isdecimal() or val[0] == 'Initial':
339
+ val = val[:-2]
340
+ if val[0] == 'Initial':
341
+ val.insert(-1, 0.0)
342
+ result.append(val[1:])
343
+ return np.array(result, dtype=np.dtype(np.float64))
344
+
345
+ def str_to_md_data(val_in):
346
+ re_data = re.compile(rf'x\s*(.+?):\s*({re_float})\s*(\w+)')
347
+ data = dict()
348
+ for val in val_in.split('\n'):
349
+ val = re_data.search(val)
350
+ if val:
351
+ data[val.group(1).strip()] = float(val.group(2)) * units_map.get(
352
+ val.group(3), 1
353
+ )
354
+ return data
355
+
356
+ def str_to_energy(val_in):
357
+ key, val = val_in.split('=', 1)
358
+ val = val.split()
359
+ try:
360
+ unit = resolve_unit(val[1])
361
+ units_map[val[1]] = unit
362
+ unit = unit if unit else 1
363
+ except Exception:
364
+ unit = 1
365
+ return key.strip(), float(val[0]) * unit
366
+
367
+ def str_to_mulliken(val_in):
368
+ val = [v.split() for v in val_in.split('\n')]
369
+ keys = [v for v in val[0] if not v.startswith('(')]
370
+ return {
371
+ key: [v[n] for v in val[1:] if len(v) == len(keys)]
372
+ for n, key in enumerate(keys)
373
+ }
374
+
375
+ def str_to_vibrational_frequencies(val_in):
376
+ # replace keys to fit length of values
377
+ val_in = re.sub(
378
+ r'ir\s*intensity\s*active', 'ir_intensity ir_active', val_in
379
+ )
380
+ val_in = re.sub(
381
+ r'raman\s*activity\s*active', 'raman_activity raman_active', val_in
382
+ )
383
+ val_in = re.sub(r'raman\s*active', 'raman_active', val_in)
384
+ val_in = re.sub(r'Frequency', 'vibrational_frequencies', val_in)
385
+ val = [v.strip(' +').split() for v in val_in.split('\n')]
386
+ return {
387
+ key: [v[n] for v in val[1:] if len(v) == len(val[0])]
388
+ for n, key in enumerate(val[0])
389
+ }
390
+
391
+ system_quantities = [
392
+ Quantity(
393
+ 'unit_cell',
394
+ r'Unit Cell\s*\s*\-+([\s\S]+?)\-{20}',
395
+ sub_parser=TextParser(
396
+ quantities=[
397
+ Quantity(
398
+ 'lattice_vectors',
399
+ r'(Real.+\s*[\d\.\-\s]+)',
400
+ str_operation=str_to_lattice_vectors,
401
+ convert=False,
402
+ ),
403
+ Quantity(
404
+ 'lattice_parameters',
405
+ r'(Lattice parameters.+[\s\S]+?\n *\n)',
406
+ str_operation=str_to_lattice_parameters,
407
+ convert=False,
408
+ ),
409
+ Quantity(
410
+ 'cell_volume', rf'Current cell volume\s*=\s*({re_float})'
411
+ ),
412
+ ]
413
+ ),
414
+ ),
415
+ Quantity(
416
+ 'cell_contents',
417
+ r'Cell Contents\s*\-+([\s\S]+?)\n *\n *\-{20}',
418
+ sub_parser=TextParser(
419
+ quantities=[
420
+ Quantity(
421
+ 'positions',
422
+ r'u\s*v\s*w\s*x([\s\S]+?)x{50}',
423
+ str_operation=str_to_array,
424
+ convert=False,
425
+ ),
426
+ Quantity(
427
+ 'velocities',
428
+ r'Vx\s*Vy\s*Vz\s*x([\s\S]+?)x{50}',
429
+ str_operation=str_to_array,
430
+ convert=False,
431
+ ),
432
+ ]
433
+ ),
434
+ ),
435
+ Quantity(
436
+ 'species',
437
+ r'Details of Species\s*\-+([\s\S]+?)\-{20}',
438
+ sub_parser=TextParser(
439
+ quantities=[
440
+ Quantity(
441
+ 'mass',
442
+ r'Mass of species in AMU\s*([\s\S]+?)\n *\n',
443
+ str_operation=lambda x: [
444
+ v.split() for v in x.strip().split('\n')
445
+ ],
446
+ )
447
+ ]
448
+ ),
449
+ ),
450
+ Quantity(
451
+ 'dft_d',
452
+ r'(Dispersion-correction scheme[\s\S]+?)\n *\n *\n',
453
+ sub_parser=TextParser(
454
+ quantities=[
455
+ Quantity(
456
+ 'method', r'Dispersion\-correction scheme\s*\:\s*(\w+)'
457
+ ),
458
+ Quantity(
459
+ 'parameter',
460
+ rf'Parameter\s*(\w+)\s*\:\s*({re_float})',
461
+ repeats=True,
462
+ ),
463
+ ]
464
+ ),
465
+ ),
466
+ ]
467
+
468
+ basic_quantities = [
469
+ Quantity(
470
+ 'scf',
471
+ r'(SCF loop.+\s*.+\s*\-+ \<\-\- SCF[\s\S]+?)\-{70}\s*\<\-\- SCF',
472
+ str_operation=str_to_scf,
473
+ convert=False,
474
+ ),
475
+ Quantity(
476
+ 'energy',
477
+ rf'(.+?energy.+?\s*=\s*{re_float}\s*.+)\n',
478
+ repeats=True,
479
+ str_operation=str_to_energy,
480
+ convert=False,
481
+ ),
482
+ Quantity(
483
+ 'energy_total', rf'Final Total Energy\s*({re_float})', dtype=float
484
+ ),
485
+ Quantity(
486
+ 'enthalpy',
487
+ rf'(Final Enthalpy\s*=\s*{re_float}\s*.+)',
488
+ str_operation=str_to_energy,
489
+ convert=False,
490
+ ),
491
+ Quantity(
492
+ 'frequency',
493
+ rf'(Final \<frequency\>\s*=\s*{re_float}\s*.+)',
494
+ str_operation=str_to_energy,
495
+ convert=False,
496
+ ),
497
+ Quantity(
498
+ 'forces',
499
+ r'Forces \*+\s*([\s\S]+?)\*{20}',
500
+ str_operation=str_to_array,
501
+ convert=False,
502
+ ),
503
+ Quantity(
504
+ 'stress_tensor',
505
+ r'Stress Tensor \*+\s*([\s\S]+?)\*{20}',
506
+ sub_parser=TextParser(
507
+ quantities=[
508
+ Quantity(
509
+ 'stress_tensor',
510
+ rf'\*\s*(?:x|y|z)\s*({re_float})\s*({re_float})\s*({re_float})',
511
+ repeats=True,
512
+ dtype=np.dtype(np.float64),
513
+ ),
514
+ Quantity(
515
+ 'pressure',
516
+ rf'\*\s*Pressure:\s*({re_float})',
517
+ dtype=np.float64,
518
+ ),
519
+ ]
520
+ ),
521
+ ),
522
+ Quantity(
523
+ 'mulliken',
524
+ r'Atomic Populations \(Mulliken\)\s*\-+\s*([\s\S]+?)\n *\n',
525
+ str_operation=str_to_mulliken,
526
+ ),
527
+ Quantity(
528
+ 'tddft',
529
+ r'Time-Dependent DFT Calculation([\s\S]+?TDDFT calculation time.+)',
530
+ sub_parser=TextParser(
531
+ quantities=[
532
+ Quantity(
533
+ 'iteration',
534
+ r'TDDFT iteration\:\s*(\d+).+?Time\:\s*([\d\.]+)',
535
+ repeats=True,
536
+ ),
537
+ Quantity(
538
+ 'energies',
539
+ rf'(\d+)\s*({re_float})\s*({re_float})\s*\w+',
540
+ repeats=True,
541
+ dtype=np.dtype(np.float64),
542
+ ),
543
+ Quantity('time', r'TDDFT calculation time\:\s*([\d\.]+)'),
544
+ ]
545
+ ),
546
+ ),
547
+ Quantity(
548
+ 'interaction_energy',
549
+ r'SEDC PBC Interaction Energy([\s\S]+?NB dispersion corrected est.+)',
550
+ sub_parser=TextParser(
551
+ quantities=[
552
+ Quantity(
553
+ 'energy',
554
+ rf'\%\s*(.+?=\s*{re_float}\s*)\[(.+)\]',
555
+ repeats=True,
556
+ str_operation=str_to_energy,
557
+ convert=False,
558
+ ),
559
+ Quantity(
560
+ 'shell',
561
+ rf'\%\s*(\d+\s+{re_float}\s+{re_float}\s+{re_float})',
562
+ repeats=True,
563
+ ),
564
+ ]
565
+ ),
566
+ ),
567
+ ]
568
+
569
+ bandstructure_quantities = [
570
+ Quantity(
571
+ 'fermi_energy',
572
+ rf'Fermi energy for spin\s*(?:up|down)\s*electrons is:\s*({re_float})',
573
+ repeats=True,
574
+ dtype=np.float64,
575
+ ),
576
+ Quantity(
577
+ 'fermi_energy',
578
+ rf'Fermi energy for spin-degenerate system:\s*({re_float})',
579
+ repeats=True,
580
+ dtype=np.float64,
581
+ ),
582
+ Quantity(
583
+ 'kpt_energies',
584
+ r'(Spin=\d+ kpt=.+\s*\+ *\-+ *\+[\s\S]+?)(?:\-{50}|\Z)',
585
+ repeats=True,
586
+ str_operation=str_to_kpt_energies,
587
+ ),
588
+ ]
589
+
590
+ basis_set_correction_quantities = [
591
+ Quantity(
592
+ 'iteration',
593
+ r'(ulating total energy[\s\S]+?)(?:Calc|\Z)',
594
+ repeats=True,
595
+ sub_parser=TextParser(
596
+ quantities=basic_quantities
597
+ + [
598
+ Quantity(
599
+ 'cutoff',
600
+ rf'Calculating total energy with cut-off of\s*([\d\.]+)',
601
+ dtype=np.float64,
602
+ )
603
+ ]
604
+ ),
605
+ )
606
+ ]
607
+
608
+ md_quantities = basic_quantities + [
609
+ Quantity(
610
+ 'md_data',
611
+ r'MD Data:\s*x([\s\S]+?)x{50}',
612
+ str_operation=str_to_md_data,
613
+ convert=False,
614
+ ),
615
+ Quantity(
616
+ 'iteration',
617
+ r'(Starting MD iteration\s*\d+[\s\S]+?)finished',
618
+ repeats=True,
619
+ sub_parser=TextParser(quantities=basic_quantities + system_quantities),
620
+ ),
621
+ ]
622
+
623
+ dmd_quantities = basic_quantities + [
624
+ Quantity(
625
+ 'iteration',
626
+ r'(Starting DMD iteration\s*\d+[\s\S]+?)finished',
627
+ repeats=True,
628
+ sub_parser=TextParser(quantities=basic_quantities + system_quantities),
629
+ )
630
+ ]
631
+
632
+ di_quantities = basic_quantities + [
633
+ Quantity(
634
+ 'iteration',
635
+ r'(Starting DI iteration\s*\d+[\s\S]+?)finished',
636
+ repeats=True,
637
+ sub_parser=TextParser(quantities=basic_quantities + system_quantities),
638
+ )
639
+ ]
640
+
641
+ tss_quantities = basic_quantities + [
642
+ Quantity(
643
+ 'iteration',
644
+ r'(SCF loop\s*Energy[\s\S]+?Energy\:.+)',
645
+ repeats=True,
646
+ sub_parser=TextParser(quantities=basic_quantities),
647
+ )
648
+ ]
649
+
650
+ cg_refinement_quantities = basic_quantities + [
651
+ Quantity(
652
+ 'iteration',
653
+ r'(SCF loop\s*Energy[\s\S]+?NB est\. 0K energy.+)',
654
+ repeats=True,
655
+ sub_parser=TextParser(quantities=basic_quantities),
656
+ )
657
+ ]
658
+
659
+ bfgs_iteration_quantities = (
660
+ basic_quantities
661
+ + system_quantities
662
+ + [Quantity('spin_density', rf'Integrated Spin Density\s*=\s*({re_float})')]
663
+ )
664
+
665
+ bfgs_quantities = basic_quantities + [
666
+ Quantity(
667
+ 'iteration',
668
+ r'(Starting BFGS iteration\s*\d+.+\s*\=+[\s\S]+?)\={70}',
669
+ repeats=True,
670
+ sub_parser=TextParser(
671
+ quantities=[
672
+ Quantity(
673
+ 'iteration',
674
+ r'((?:starting|improving) iteration[\s\S]+?)BFGS:',
675
+ repeats=True,
676
+ sub_parser=TextParser(quantities=bfgs_iteration_quantities),
677
+ )
678
+ ]
679
+ ),
680
+ )
681
+ ]
682
+
683
+ self._quantities = system_quantities + [
684
+ Quantity(
685
+ 'program_version',
686
+ r'Welcome to (?:Academic Release|Materials Studio)\s*(\w*) version (\S+)',
687
+ ),
688
+ Quantity(
689
+ 'program_compilation',
690
+ r'Compiled for (\S+) on \w+,\s*([\w :]+)',
691
+ flatten=False,
692
+ ),
693
+ Quantity('compiler', r'Compiler:\s*(.+)\n', flatten=False),
694
+ Quantity('maths_library', r'MATHLIBS\s*:\s*(.+)\n', flatten=False),
695
+ Quantity('fft_library', r'FFT Lib\s*:\s*(.+)\n', flatten=False),
696
+ Quantity(
697
+ 'constants_reference',
698
+ r'Fundamental constants values\s*:\s*(.+)\n',
699
+ flatten=False,
700
+ ),
701
+ Quantity('run_start', r'Run started\: \w+,\s*([\w :]+)', flatten=False),
702
+ Quantity(
703
+ 'title', r'Title\s*\*+\s*([\s\S]+?)\*{75}', str_operation=str_to_title
704
+ ),
705
+ # TODO verify this, I cannot find an example
706
+ Quantity('dft_u', r'Units for (\w+) U values are'),
707
+ Quantity(
708
+ 'calculation',
709
+ r'(MEMORY AND SCRATCH DISK ESTIMATES PER[\s\S]+?(?:A BibTeX formatted|\Z))',
710
+ sub_parser=TextParser(
711
+ quantities=basic_quantities
712
+ + [
713
+ Quantity(
714
+ 'vibrational_frequencies',
715
+ r'\+\s*(N\s*Frequency\s*irrep[\s\S]+?)(?:\s*\+\s*\.{70}|\Z)',
716
+ repeats=True,
717
+ str_operation=str_to_vibrational_frequencies,
718
+ ),
719
+ Quantity(
720
+ 'raman_tensor',
721
+ rf'Mode number\:\s*\d+ Raman tensor\s*Depolarisation Ratio.+'
722
+ rf'\s*\+\s*({re_float}\s*{re_float}\s*{re_float}).+'
723
+ rf'\s*\+\s*({re_float}\s*{re_float}\s*{re_float}).+'
724
+ rf'\s*\+\s*({re_float}\s*{re_float}\s*{re_float}).+',
725
+ repeats=True,
726
+ str_operation=lambda x: np.reshape(
727
+ np.array(x.split(), dtype=np.dtype(np.float64)), (3, 3)
728
+ ),
729
+ ),
730
+ Quantity(
731
+ 'bandstructure',
732
+ r'(Fermi energy for spin[\s\S]+?Spin\=1[\s\S]+?)\=\=',
733
+ sub_parser=TextParser(quantities=bandstructure_quantities),
734
+ ),
735
+ Quantity(
736
+ 'basis_set_correction',
737
+ r'(Calculating finite basis set correction with[\s\S]+?)'
738
+ r'(Total energy corrected for finite basis set.+)',
739
+ sub_parser=TextParser(
740
+ quantities=basis_set_correction_quantities
741
+ ),
742
+ ),
743
+ Quantity(
744
+ 'tss',
745
+ r'Starting Transition State Search([\s\S]+?[LQ]ST Maximum Found[\s\S]+?\+{10})',
746
+ sub_parser=TextParser(quantities=tss_quantities),
747
+ ),
748
+ Quantity(
749
+ 'cg_refinement',
750
+ r'Commencing conjugate gradient refinement([\s\S]+?)(?:Writing model|\Z)',
751
+ sub_parser=TextParser(quantities=cg_refinement_quantities),
752
+ ),
753
+ Quantity(
754
+ 'md',
755
+ r'Starting MD([\s\S]+?)(?:Finished MD|\Z)',
756
+ sub_parser=TextParser(quantities=md_quantities),
757
+ ),
758
+ Quantity(
759
+ 'dmd',
760
+ r'Starting DMD([\s\S]+?)(?:Finished DMD|\Z)',
761
+ sub_parser=TextParser(quantities=dmd_quantities),
762
+ ),
763
+ # TODO verify this cannot find an example
764
+ Quantity(
765
+ 'di',
766
+ r'Starting DI([\s\S]+?)(?:Finished DI|\Z)',
767
+ sub_parser=TextParser(quantities=di_quantities),
768
+ ),
769
+ Quantity(
770
+ 'bfgs',
771
+ r'(BFGS:[\s\S]+?)(?:BFGS: Geometry optimization|\Z)',
772
+ sub_parser=TextParser(quantities=bfgs_quantities),
773
+ ),
774
+ Quantity(
775
+ 'final',
776
+ r'Final Configuration([\s\S]+?)(?:Writing model to|\Z)',
777
+ sub_parser=TextParser(
778
+ quantities=system_quantities + basic_quantities
779
+ ),
780
+ ),
781
+ ]
782
+ ),
783
+ ),
784
+ Quantity(
785
+ 'time',
786
+ r'([A-Z]\w+) time\s+\=\s*([\d\.]+) s',
787
+ dtype=np.float64,
788
+ repeats=True,
789
+ ),
790
+ Quantity(
791
+ 'nmr_flag',
792
+ r'\|\s*Welcome to Materials Studio CASTEP\-([A-Z]+)\s*\|',
793
+ repeats=False,
794
+ ),
795
+ ]
796
+
797
+
798
+ class CastepParser:
799
+ def __init__(self):
800
+ self.out_parser = OutParser()
801
+ self.cell_parser = CellParser()
802
+ self.bands_parser = BandsParser()
803
+
804
+ self._xc_functional_map = {
805
+ 'Perdew Burke Ernzerhof': ['GGA_X_PBE', 'GGA_C_PBE'],
806
+ 'Local Density Approximation': ['LDA_C_PZ', 'LDA_X_PZ'],
807
+ 'Perdew Wang (1991)': ['GGA_X_PW91', 'GGA_C_PW91'],
808
+ 'revised Perdew Burke Ernzerhof': ['GGA_X_RPBE'],
809
+ 'PBE for solids (2008)': ['GGA_X_PBE_SOL'],
810
+ 'hybrid B3LYP': ['HYB_GGA_XC_B3LYP5'],
811
+ 'Hartree-Fock': ['HF_X'],
812
+ 'Hartree-Fock + Local Density Approximation': ['HF_X_LDA_C_PW'],
813
+ 'hybrid HSE03': ['HYB_GGA_XC_HSE03'],
814
+ 'hybrid HSE06': ['HYB_GGA_XC_HSE06'],
815
+ 'hybrid PBE0': ['HYB_GGA_XC_PBEH'],
816
+ 'PBE with Wu-Cohen exchange': ['GGA_C_PBE_GGA_X_WC'],
817
+ 'LDA-X': ['LDA_X_PZ'],
818
+ 'LDA-C': ['LDA_C_PZ'],
819
+ 'Optimised Effective Potential': ['OEP_EXX'],
820
+ 'PBE': ['GGA_X_PBE', 'GGA_C_PBE'],
821
+ 'PW91': ['GGA_X_PW91', 'GGA_C_PW91'],
822
+ 'RPBE': 'GGA_X_RPBE',
823
+ 'PBEsol': ['GGA_X_RPBE'],
824
+ 'HF': ['HF_X'],
825
+ 'HF-LDA': ['HF_X_LDA_C_PW'],
826
+ 'HSE03': ['HYB_GGA_XC_HSE03'],
827
+ 'HSE06': ['HYB_GGA_XC_HSE06'],
828
+ 'PBE0': ['HYB_GGA_XC_PBEH'],
829
+ 'WC': ['GGA_C_PBE_GGA_X_WC'],
830
+ 'LDA': ['LDA_X_PZ', 'LDA_C_PZ'],
831
+ 'b3lyp': ['HYB_GGA_XC_B3LYP5'],
832
+ }
833
+
834
+ self._relativistic_map = {'Koelling-Harmon': 'scalar_relativistic'}
835
+
836
+ self._sampling_method_map = {
837
+ 'single point energy': 'single_point',
838
+ 'geometry optimization': 'geometry_optimization',
839
+ 'molecular dynamics': 'molecular_dynamics',
840
+ 'phonon calculation': 'phonon',
841
+ 'transition state search': 'geometry_optimization',
842
+ 'band structure': 'single_point',
843
+ 'Core level spectra (ELNES etc)': 'single_point',
844
+ }
845
+
846
+ self._metainfo_map = {
847
+ 'Final energy': 'energy_total',
848
+ 'Final energy, E': 'energy_total',
849
+ 'Total energy corrected for finite basis set': 'x_castep_total_energy_corrected_for_finite_basis',
850
+ 'Final free energy (E-TS)': 'energy_free',
851
+ 'Dispersion corrected final energy*': 'x_castep_total_dispersion_corrected_energy',
852
+ 'NB est. 0K energy (E-0.5TS)': 'energy_total_t0',
853
+ "'TS'/PBE structure energy corr.'": 'x_castep_structure_energy_corr',
854
+ "'TS'/PBE PBC image interaction corr.": 'x_castep_PBC_image_inter_corr',
855
+ "'TS'/PBE total energy correction": 'x_castep_total_energy_correction',
856
+ "'TS'/PBE correction |F|max": 'x_castep_total_fmax_correction',
857
+ 'Dispersion corrected final energy*, Ecor': 'x_castep_total_dispersion_corrected_energy',
858
+ 'Dispersion corrected final free energy* (Ecor-TS)': 'x_castep_total_dispersion_corrected_free_energy',
859
+ 'NB dispersion corrected est. 0K energy* (Ecor-0.5TS)': 'x_castep_disp_corrected_energy_total_T0',
860
+ 'basis set parameters': {
861
+ 'basis set accuracy': 'native_tier', # https://www.tcm.phy.cam.ac.uk/castep/documentation/WebHelp/content/modules/castep/keywords/k_basis_precision_castep.htm
862
+ 'size of standard grid': 'x_castep_size_std_grid',
863
+ 'size of fine gmax': 'x_castep_size_fine_grid',
864
+ },
865
+ 'phonon parameters': {
866
+ 'phonon calculation method': 'x_castep_phonon_method',
867
+ 'phonon convergence tolerance': 'x_castep_phonon_tolerance',
868
+ 'max. number of phonon cycles': 'x_castep_phonon_cycles',
869
+ 'dfpt solver method': 'x_castep_DFPT_solver_method',
870
+ 'band convergence tolerance': 'x_castep_band_tolerance',
871
+ },
872
+ 'geometry optimization parameters': {
873
+ 'optimization method': 'method',
874
+ 'total energy convergence tolerance': 'convergence_tolerance_energy_difference',
875
+ 'max. number of steps': 'x_castep_max_number_of_steps',
876
+ 'max ionic |force| tolerance': 'convergence_tolerance_force_maximum',
877
+ 'max ionic |displacement| tolerance': 'convergence_tolerance_displacement_maximum',
878
+ 'max |stress component| tolerance': 'x_castep_geometry_stress_com_tolerance',
879
+ },
880
+ 'electronic parameters': {
881
+ 'number of electrons': 'x_castep_number_of_electrons',
882
+ 'net charge of system': 'x_castep_net_charge',
883
+ 'number of bands': 'x_castep_number_of_bands',
884
+ },
885
+ 'electronic minimization parameters': {
886
+ 'total energy / atom convergence tol.': 'x_castep_energy_threshold',
887
+ 'max. number of scf cycles': 'x_castep_max_iter',
888
+ 'smearing scheme': 'x_castep_smearing_kind',
889
+ 'smearing width': 'x_castep_smearing_width',
890
+ },
891
+ 'density mixing parameters': {
892
+ 'density-mixing scheme': 'x_castep_density_mixing_scheme',
893
+ 'max. length of mixing history': 'x_castep_density_mixing_length',
894
+ 'charge density mixing amplitude': 'x_castep_charge_density_mixing_amplitude',
895
+ 'cut-off energy for mixing': 'x_castep_cut_off_energy_for_mixing',
896
+ },
897
+ 'population analysis parameters': {
898
+ 'population analysis with cutoff': 'x_castep_population_analysis_cutoff'
899
+ },
900
+ 'core level spectra parameters': {
901
+ 'number of bands': 'x_castep_core_spectra_n_bands',
902
+ 'band convergence tolerance': 'x_castep_core_spectra_conv_tolerance',
903
+ },
904
+ 'band structure parameters': {
905
+ 'max. number of iterations': 'x_castep_band_n_iterations',
906
+ 'max. cg steps in bs calc': 'x_castep_band_max_cg',
907
+ 'number of bands / k-point': 'x_castep_band_n_bands',
908
+ 'band convergence tolerance': 'x_castep_band_conv_tolerance',
909
+ },
910
+ 'molecular dynamics parameters': {
911
+ 'ensemble': 'ensemble_type',
912
+ 'temperature': 'x_castep_thermostat_target_temperature',
913
+ 'pressure': 'x_castep_frame_pressure',
914
+ 'using': ['x_castep_barostat_type', 'x_castep_thermostat_type'],
915
+ 'with characteristic cell time': 'x_castep_barostat_tau',
916
+ 'with characteristic ionic time': 'x_castep_thermostat_tau',
917
+ 'time step': 'x_castep_integrator_dt',
918
+ 'number of md steps': 'x_castep_number_of_steps_requested',
919
+ 'md scf energy / atom convergence tol.': 'x_castep_frame_energy_tolerance',
920
+ 'md scf eigenenergies tolerance': 'x_castep_frame_eigen_tolerance',
921
+ },
922
+ 'transition state search parameters': {
923
+ 'search method': 'x_castep_ts_method',
924
+ 'lstqst protocol': 'x_castep_ts_protocol',
925
+ 'max. number of qst iterations': 'x_castep_ts_number_qst',
926
+ 'max. number of cg iterations': 'x_castep_ts_number_cg',
927
+ 'max. ionic |force| tolerance': 'x_castep_ts_force_tolerance',
928
+ 'max. ionic |displacement| tolerance': 'x_castep_ts_displacement_tolerance',
929
+ },
930
+ 'optics parameters': {
931
+ 'search method': 'x_castep_optics_n_bands',
932
+ 'band convergence tolerance': 'x_castep_optics_tolerance',
933
+ },
934
+ 'electronic spectroscopy parameters': {
935
+ 'electronic spectroscopy with theory level': 'x_castep_theory_level',
936
+ 'spectroscopy calculation': 'x_castep_spectroscopy_calculation',
937
+ 'max. number of iterations': 'x_castep_spec_max_iter',
938
+ 'max. steps per iteration': 'x_castep_spec_max_steps',
939
+ 'number of bands / k-point': 'x_castep_spec_max_bands',
940
+ 'band convergence tolerance': 'x_castep_spec_tolerance',
941
+ },
942
+ 'time-dependent dft parameters': {
943
+ 'number of excited states': 'x_castep_tddft_n_excited_states',
944
+ 'state selected for calculation of forces': 'x_castep_tddft_n_states_forces',
945
+ 'state convergence tolerance': 'x_castep_tddft_state_tolerance',
946
+ 'convergence tolerance window': 'x_castep_tddft_state_tolerance_window',
947
+ 'max. number of iterations': 'x_castep_tddft_max_iter',
948
+ 'no. of extra (convergence indifferent) states': 'x_castep_tddft_extra_states',
949
+ 'using tddft functional': 'x_castep_tddft_functional',
950
+ 'time-dependent dft method': 'x_castep_tddft_method',
951
+ 'matrix eigenvalue method': 'x_castep_tddft_eigenmethod',
952
+ 'time-Dependent dft approximation': 'x_castep_tddft_approximation',
953
+ 'time-Dependent dft position operator': 'x_castep_tddft_position_op',
954
+ },
955
+ }
956
+
957
+ self._units = None
958
+ self._nspin = None
959
+
960
+ def init_parser(self):
961
+ self.out_parser.mainfile = self.filepath
962
+ self.out_parser.logger = self.logger
963
+ self._units = None
964
+ self._nspin = None
965
+
966
+ @property
967
+ def units(self):
968
+ if self._units is None:
969
+ self._units = dict()
970
+ re_unit = re.compile(r'output\s*([\w ]+) unit')
971
+ parameters = self.out_parser.get('title', {}).get('general parameters', {})
972
+ for key, val in parameters.items():
973
+ name = re_unit.match(key)
974
+ if name:
975
+ try:
976
+ self._units[name.group(1)] = resolve_unit(val)
977
+ except Exception:
978
+ pass
979
+ return self._units
980
+
981
+ @property
982
+ def n_spin_channels(self):
983
+ if self._nspin is None:
984
+ self._nspin = (
985
+ 1
986
+ if self.out_parser.get('title', {})
987
+ .get('electronic parameters', {})
988
+ .get('number of down spins')
989
+ is None
990
+ else 2
991
+ )
992
+ return self._nspin
993
+
994
+ def get_castep_file(self, ext):
995
+ paths = [p for p in os.listdir(self.maindir) if p.endswith(ext)]
996
+ if not paths:
997
+ return
998
+ elif len(paths) == 1:
999
+ return os.path.join(self.maindir, paths[0])
1000
+ else:
1001
+ prefix = os.path.basename(self.filepath).rsplit('.', 1)[0]
1002
+ for path in paths:
1003
+ if path.startswith(prefix):
1004
+ return os.path.join(self.maindir, path)
1005
+
1006
+ def parse_method(self):
1007
+ sec_run = self.archive.run[-1]
1008
+ sec_method = Method()
1009
+ sec_run.method.append(sec_method)
1010
+ title = self.out_parser.get('title', {})
1011
+
1012
+ # basis set
1013
+ basis_parameters = self.out_parser.get('title', {}).get(
1014
+ 'basis set parameters', {}
1015
+ )
1016
+ sec_method.electrons_representation.append(
1017
+ BasisSetContainer(
1018
+ native_tier=basis_parameters.get('basis set accuracy', 'FINE'),
1019
+ type='plane waves',
1020
+ scope=['wavefunction'],
1021
+ basis_set=[
1022
+ BasisSet(
1023
+ scope=['valence'],
1024
+ type='plane waves',
1025
+ cutoff=basis_parameters.get('plane wave basis set cut-off'),
1026
+ )
1027
+ ],
1028
+ )
1029
+ )
1030
+
1031
+ # DFT
1032
+ sec_dft = DFT()
1033
+ sec_method.dft = sec_dft
1034
+ method = 'DFT+U' if self.out_parser.get('dft_u') is not None else 'DFT'
1035
+ sec_method.electronic = Electronic(
1036
+ method=method, n_spin_channels=self.n_spin_channels
1037
+ )
1038
+
1039
+ xc_parameters = title.get('exchange-correlation parameters', {})
1040
+
1041
+ # xc functional
1042
+ xc_functionals = xc_parameters.get('using functional')
1043
+ if xc_functionals is None:
1044
+ xc_functionals = xc_parameters.get(
1045
+ 'using custom xc functional definition', []
1046
+ )
1047
+ xc_functionals = (
1048
+ xc_functionals if isinstance(xc_functionals, list) else [xc_functionals]
1049
+ )
1050
+
1051
+ sec_xc_functional = XCFunctional()
1052
+ sec_dft.xc_functional = sec_xc_functional
1053
+ for xc_functional in xc_functionals:
1054
+ # when custom, a weight is attached
1055
+ xc_weight = None
1056
+ if xc_parameters.get('using custom xc functional definition') is not None:
1057
+ xc_functional, xc_weight = xc_functional.rsplit(' ', 1)
1058
+ for functional in self._xc_functional_map.get(xc_functional, []):
1059
+ sec_functional = Functional(name=functional)
1060
+ if xc_weight is not None:
1061
+ sec_functional.weight = float(xc_weight)
1062
+ if '_X_' in functional or functional.endswith('_X'):
1063
+ sec_xc_functional.exchange.append(sec_functional)
1064
+ elif '_C_' in functional or functional.endswith('_C'):
1065
+ sec_xc_functional.correlation.append(sec_functional)
1066
+ elif 'HYB' in functional:
1067
+ sec_xc_functional.hybrid.append(sec_functional)
1068
+ else:
1069
+ sec_xc_functional.contributions.append(sec_functional)
1070
+
1071
+ # relativistic treatment
1072
+ relativistic = self._relativistic_map.get(
1073
+ xc_parameters.get('relativistic treatment')
1074
+ )
1075
+ if relativistic is not None:
1076
+ sec_method.electronic.relativity_method = relativistic
1077
+
1078
+ # dispersion correction
1079
+ dispersion = xc_parameters.get('sedc with')
1080
+ if dispersion is not None:
1081
+ sec_method.electronic.van_der_waals_method = dispersion.split()[0]
1082
+
1083
+ # smearing scheme
1084
+ electronic_parameters = title.get('electronic minimization parameters', {})
1085
+ smearing = electronic_parameters.get('smearing scheme')
1086
+ if smearing is not None:
1087
+ sec_smearing = Smearing()
1088
+ sec_method.electronic.smearing = sec_smearing
1089
+ sec_smearing.kind = smearing.lower()
1090
+ width = electronic_parameters.get('smearing width')
1091
+ if width is not None:
1092
+ sec_smearing.width = width.to('joule').magnitude
1093
+
1094
+ species = self.out_parser.get('species')
1095
+ if species is None:
1096
+ return
1097
+
1098
+ for name, mass in species.get('mass', []):
1099
+ sec_atom_parameters = AtomParameters()
1100
+ sec_method.atom_parameters.append(sec_atom_parameters)
1101
+ sec_atom_parameters.label = name
1102
+ sec_atom_parameters.mass = mass
1103
+
1104
+ # Setting up NMR label and code-specific flag for workflow DFT+NMR recognition
1105
+ nmr_flag = self.out_parser.get('nmr_flag', '') == 'NMR'
1106
+ if nmr_flag:
1107
+ self.logger.info('NMR flag found in the main output file.')
1108
+ sec_method.label = 'NMR'
1109
+
1110
+ def parse_workflow(self):
1111
+ workflow = None
1112
+
1113
+ title = self.out_parser.get('title', {})
1114
+
1115
+ method = title.get('general parameters', {}).get(
1116
+ 'type of calculation', 'single point'
1117
+ )
1118
+ method = self._sampling_method_map.get(method)
1119
+ if method is None:
1120
+ self.logger.warning('Sampling method cannot be resolved.')
1121
+ method = 'single_point'
1122
+
1123
+ if method == 'geometry_optimization':
1124
+ parameters = title.get('geometry optimization parameters', {})
1125
+ key_map = self._metainfo_map.get('geometry optimization parameters')
1126
+ workflow = GeometryOptimization(method=GeometryOptimizationMethod())
1127
+ for key, val in parameters.items():
1128
+ key = key_map.get(key)
1129
+ if key is None or val is None:
1130
+ continue
1131
+ setattr(workflow.method, key, val)
1132
+ workflow.method.convergence_tolerance_displacement_maximum = parameters.get(
1133
+ 'max ionic |displacement| tolerance'
1134
+ )
1135
+ workflow.method.convergence_tolerance_energy_difference = parameters.get(
1136
+ 'total energy convergence tolerance'
1137
+ )
1138
+ workflow.method.convergence_tolerance_force_maximum = parameters.get(
1139
+ 'max ionic |force| tolerance'
1140
+ )
1141
+ elif method == 'molecular_dynamics':
1142
+ parameters = title.get('molecular dynamics parameters', {})
1143
+ workflow = MolecularDynamics(method=MolecularDynamicsMethod())
1144
+ for key, val in parameters.items():
1145
+ key = self._metainfo_map.get('molecular dynamics parameters').get(key)
1146
+ if key is None or val is None:
1147
+ continue
1148
+ if isinstance(key, list):
1149
+ for i, key_i in enumerate(key):
1150
+ setattr(workflow.method, key_i, val[i])
1151
+ else:
1152
+ setattr(workflow.method, key, val)
1153
+ workflow.method.thermodynamic_ensemble = parameters.get('ensemble')
1154
+ elif method == 'single_point':
1155
+ workflow = SinglePoint()
1156
+
1157
+ elif method == 'phonon':
1158
+ workflow = Phonon()
1159
+
1160
+ self.archive.workflow2 = workflow
1161
+
1162
+ def parse_configurations(self):
1163
+ calculation = self.out_parser.get('calculation')
1164
+ if calculation is None:
1165
+ return
1166
+
1167
+ sec_run = self.archive.run[0]
1168
+
1169
+ def parse_eigenvalues(source):
1170
+ sec_scc = sec_run.calculation[-1]
1171
+
1172
+ energy_unit = self.units.get('energy', 1)
1173
+ bandstructure = source.get('bandstructure')
1174
+ kpts, band_energies = [], []
1175
+ if bandstructure is not None:
1176
+ for spin, kpt, energies in bandstructure.get('kpt_energies', []):
1177
+ if spin == 1:
1178
+ kpts.append(kpt)
1179
+ band_energies.append(energies)
1180
+ band_energies = (
1181
+ np.reshape(band_energies, (spin, len(kpts), len(band_energies[0])))
1182
+ * energy_unit
1183
+ )
1184
+
1185
+ else:
1186
+ self.bands_parser.mainfile = self.get_castep_file('bands')
1187
+ for kpt, energies in self.bands_parser.get('kpt_energies', []):
1188
+ kpts.append(kpt)
1189
+ band_energies.append(energies)
1190
+ if len(band_energies) == 0:
1191
+ return
1192
+
1193
+ n_spin = self.bands_parser.get('n_spins', 1)
1194
+ band_energies = np.reshape(
1195
+ band_energies, (len(kpts), n_spin, len(band_energies[0]) // n_spin)
1196
+ )
1197
+ band_energies = (
1198
+ np.transpose(band_energies, axes=(1, 0, 2)) * energy_unit
1199
+ )
1200
+
1201
+ # get path segment nodes from .cell
1202
+ self.cell_parser.mainfile = self.get_castep_file('cell')
1203
+ kpoint_path = self.cell_parser.get_value('bs_kpoint_path', [])
1204
+
1205
+ if len(kpoint_path) == 0:
1206
+ # write energies to eigenvalues
1207
+ sec_eigenvalues = BandEnergies()
1208
+ sec_scc.eigenvalues.append(sec_eigenvalues)
1209
+ sec_eigenvalues.n_kpoints = len(kpts)
1210
+ sec_eigenvalues.kpoints = kpts
1211
+ sec_eigenvalues.energies = band_energies
1212
+ else:
1213
+ # write band energies on segments
1214
+ nodes = np.array(
1215
+ [path[:3] for path in kpoint_path], dtype=np.dtype(np.float64)
1216
+ )
1217
+ labels = [
1218
+ '\u0393' if path[-1].lower() == 'gamma' else path[-1]
1219
+ for path in kpoint_path
1220
+ ]
1221
+ sec_bandstructure = BandStructure()
1222
+ sec_scc.band_structure_electronic.append(sec_bandstructure)
1223
+ start = 0
1224
+ for n, node in enumerate(nodes[1:]):
1225
+ node_index = np.where(kpts == node)[0]
1226
+ for index in node_index:
1227
+ if np.count_nonzero(node_index == index) == 3 and index > start:
1228
+ break
1229
+ sec_band_segment = BandEnergies()
1230
+ sec_bandstructure.segment.append(sec_band_segment)
1231
+ sec_band_segment.n_bands = len(band_energies[0][start])
1232
+ sec_band_segment.n_kpoints = int(index + 1 - start)
1233
+ sec_band_segment.kpoints = kpts[start : index + 1]
1234
+ # assign labels at nodes
1235
+ sec_band_segment.endpoints_labels = [labels[n], labels[n + 1]]
1236
+ sec_band_segment.energies = band_energies[:, start : index + 1, :]
1237
+ start = index
1238
+
1239
+ def parse_scc(source):
1240
+ sec_scc = Calculation()
1241
+ sec_run.calculation.append(sec_scc)
1242
+ energy_unit = self.units.get('energy', 1)
1243
+
1244
+ sec_energy = Energy()
1245
+ sec_scc.energy = sec_energy
1246
+ if source.get('energy_total') is not None:
1247
+ sec_energy.total = EnergyEntry(
1248
+ value=source.get('energy_total') * energy_unit
1249
+ )
1250
+
1251
+ # energies
1252
+ for key, val in source.get('energy', []):
1253
+ name = self._metainfo_map.get(key)
1254
+ if name is not None:
1255
+ if name.startswith('x_castep_'):
1256
+ sec_energy.m_add_sub_section(
1257
+ Energy.contributions,
1258
+ EnergyEntry(kind=name.replace('x_castep_', ''), value=val),
1259
+ )
1260
+ setattr(sec_scc, name, val.to('joule').magnitude)
1261
+ else:
1262
+ sec_energy.m_add_sub_section(
1263
+ getattr(Energy, name.replace('energy_', '')),
1264
+ EnergyEntry(value=val),
1265
+ )
1266
+
1267
+ # forces
1268
+ forces = source.get('forces')
1269
+ if forces is not None:
1270
+ sec_forces = Forces()
1271
+ sec_scc.forces = sec_forces
1272
+ sec_forces.total = ForcesEntry(
1273
+ value=forces[1] * self.units.get('force', 1)
1274
+ )
1275
+
1276
+ sec_thermo = Thermodynamics()
1277
+ sec_scc.thermodynamics.append(sec_thermo)
1278
+ # stress tensor
1279
+ stress_tensor = source.get('stress_tensor')
1280
+ if stress_tensor is not None:
1281
+ if stress_tensor.get('stress_tensor') is not None:
1282
+ sec_stress = Stress()
1283
+ sec_scc.stress = sec_stress
1284
+ sec_stress.total = StressEntry(
1285
+ value=stress_tensor.get('stress_tensor')
1286
+ * self.units.get('pressure', 1)
1287
+ )
1288
+ if stress_tensor.get('pressure') is not None:
1289
+ sec_thermo.pressure = stress_tensor.get(
1290
+ 'pressure'
1291
+ ) * self.units.get('pressure', 1)
1292
+
1293
+ # other properties
1294
+ enthalpy = source.get('enthalpy')
1295
+ if enthalpy is not None:
1296
+ sec_thermo.enthalpy = enthalpy[1]
1297
+
1298
+ freq = source.get('frequency')
1299
+ if freq is not None:
1300
+ sec_scc.x_castep_frequency = freq[1].magnitude
1301
+
1302
+ # eigenvalues
1303
+ parse_eigenvalues(source)
1304
+
1305
+ # mulliken population analysis
1306
+ mulliken = source.get('mulliken')
1307
+ if mulliken is not None:
1308
+ species = mulliken.get('Species', [])
1309
+ sec_charges = Charges()
1310
+ sec_scc.charges.append(sec_charges)
1311
+ sec_charges.analysis_method = 'mulliken'
1312
+ orbitals = [o for o in 'spdf' if mulliken.get(o) is not None]
1313
+ sec_charges.n_charges_orbitals = len(orbitals)
1314
+ sec_charges.n_charges_atoms = len(species)
1315
+ sec_charges.value = mulliken['Total']
1316
+ for n, specie in enumerate(species):
1317
+ for orbital in orbitals:
1318
+ sec_charges_value = ChargesValue()
1319
+ sec_charges.orbital_projected.append(sec_charges_value)
1320
+ sec_charges_value.orbital = orbital
1321
+ sec_charges_value.atom_index = n
1322
+ sec_charges_value.atom_label = specie
1323
+ sec_charges_value.value = mulliken[orbital][n]
1324
+
1325
+ # vibrational frequencies
1326
+ # why are vibrational frequencies section under section_run?
1327
+ for vibrational_frequencies in source.get('vibrational_frequencies', []):
1328
+ sec_frequencies = x_castep_section_vibrational_frequencies()
1329
+ sec_run.x_castep_section_vibrational_frequencies.append(sec_frequencies)
1330
+ sec_vibrations = VibrationalFrequencies()
1331
+ sec_scc.vibrational_frequencies.append(sec_vibrations)
1332
+ for key, val in vibrational_frequencies.items():
1333
+ if key == 'vibrational_frequencies':
1334
+ sec_vibrations.value = val * (1 / ureg.cm)
1335
+ elif key == 'ir_intensity':
1336
+ sec_ir = VibrationalFrequenciesValues()
1337
+ sec_vibrations.infrared = sec_ir
1338
+ sec_ir.intensity = val
1339
+ if vibrational_frequencies.get('ir_active') is not None:
1340
+ sec_ir.activity = vibrational_frequencies.get('ir_active')
1341
+ elif key == 'raman_activity':
1342
+ sec_raman = VibrationalFrequenciesValues()
1343
+ sec_vibrations.raman = sec_raman
1344
+ sec_raman.intensity = val
1345
+ if vibrational_frequencies.get('raman_active') is not None:
1346
+ sec_raman.activity = vibrational_frequencies.get(
1347
+ 'raman_active'
1348
+ )
1349
+ setattr(sec_frequencies, 'x_castep_%s' % key, val)
1350
+
1351
+ # raman tensors
1352
+ for raman_tensor in source.get('raman_tensor', []):
1353
+ sec_raman = x_castep_section_raman_tensor()
1354
+ sec_run.x_castep_section_raman_tensor.append(sec_raman)
1355
+ unit = (
1356
+ self.units.get('length', ureg.angstrom)
1357
+ / self.units.get('mass', ureg.amu)
1358
+ ) * 0.5
1359
+ sec_raman.x_castep_raman_tensor = raman_tensor * unit
1360
+
1361
+ # interaction energy
1362
+ interaction = source.get('interaction_energy')
1363
+ if interaction is not None:
1364
+ for shell in interaction.get('shell', []):
1365
+ sec_sedc = x_castep_section_DFT_SEDC()
1366
+ sec_scc.x_castep_section_DFT_SEDC.append(sec_sedc)
1367
+ sec_sedc.x_castep_shell = shell[0]
1368
+ sec_sedc.x_castep_correction_energy = (
1369
+ (shell[1] * energy_unit).to('J').magnitude
1370
+ )
1371
+ sec_sedc.x_castep_de_atom = (
1372
+ (shell[2] * energy_unit).to('J').magnitude
1373
+ )
1374
+ sec_sedc.x_castep_dfmax_atom = (
1375
+ (shell[3] * self.units.get('force')).to('J/m').magnitude
1376
+ )
1377
+
1378
+ for key, val in interaction.get('energy', []):
1379
+ name = self._metainfo_map.get(key)
1380
+ if name is None:
1381
+ continue
1382
+ val = val.to('J') if val.units == ureg.eV else val.to('J/m')
1383
+ setattr(sec_sedc, name, val.magnitude)
1384
+
1385
+ # add the dispersion energies
1386
+ for key, val in source.get('energy', []):
1387
+ name = self._metainfo_map.get(key, '')
1388
+ if '_disp' in name:
1389
+ setattr(sec_sedc, name, val.to('joule').magnitude)
1390
+
1391
+ # scf iteration
1392
+ for n, scf in enumerate(source.get('scf', [])):
1393
+ sec_scf = ScfIteration()
1394
+ sec_scc.scf_iteration.append(sec_scf)
1395
+ sec_scf_energy = Energy()
1396
+ sec_scf.energy = sec_scf_energy
1397
+ sec_scf.energy.total = EnergyEntry(value=scf[0] * energy_unit)
1398
+ if len(scf) == 4:
1399
+ sec_scf_energy.fermi = scf[1] * energy_unit
1400
+ sec_scf_energy.change = scf[-2] * energy_unit
1401
+ sec_scf.time_physical = scf[-1] * ureg.s
1402
+ if n:
1403
+ time_start = source.scf[n - 1][-1] * ureg.s
1404
+ else:
1405
+ time_start = (
1406
+ sec_run.calculation[-2].time_physical
1407
+ if len(sec_run.calculation) > 1
1408
+ else 0 * ureg.s
1409
+ )
1410
+ sec_scf.time_calculation = sec_scf.time_physical - time_start
1411
+
1412
+ if sec_scc.scf_iteration:
1413
+ sec_scc.time_physical = sec_scc.scf_iteration[-1].time_physical
1414
+ sec_scc.time_calculation = sum(
1415
+ [scf.time_calculation for scf in sec_scc.scf_iteration]
1416
+ )
1417
+
1418
+ return sec_scc
1419
+
1420
+ def parse_system(source):
1421
+ sec_system = System()
1422
+ sec_run.system.append(sec_system)
1423
+ sec_atoms = Atoms()
1424
+ sec_system.atoms = sec_atoms
1425
+ length_unit = self.units.get('length', 1)
1426
+
1427
+ unit_cell = source.get('unit_cell', self.out_parser.get('unit_cell', {}))
1428
+ if unit_cell.get('lattice_vectors') is not None:
1429
+ sec_atoms.lattice_vectors = (
1430
+ unit_cell.get('lattice_vectors')[0] * length_unit
1431
+ )
1432
+ sec_atoms.periodic = [True, True, True]
1433
+
1434
+ cell_contents = source.get(
1435
+ 'cell_contents', self.out_parser.get('cell_contents', {})
1436
+ )
1437
+ if cell_contents.get('positions') is not None:
1438
+ sec_atoms.labels = cell_contents.get('positions')[0]
1439
+ sec_atoms.positions = np.dot(
1440
+ cell_contents.get('positions')[1], sec_system.atoms.lattice_vectors
1441
+ )
1442
+ if cell_contents.get('velocities') is not None:
1443
+ sec_atoms.velocities = cell_contents.get('velocities')[1] * (
1444
+ length_unit / self.units.get('time', 1)
1445
+ )
1446
+
1447
+ # miscellaneous quantities
1448
+ cell_volume = unit_cell.get('cell_volume')
1449
+ if cell_volume is not None:
1450
+ cell_volume *= length_unit**3
1451
+ sec_system.x_castep_cell_volume = cell_volume.to('m**3').magnitude
1452
+
1453
+ lattice_parameters = unit_cell.get('lattice_parameters')
1454
+ if lattice_parameters is not None:
1455
+ sec_positions = x_castep_section_atom_positions()
1456
+ sec_system.x_castep_section_atom_positions.append(sec_positions)
1457
+ for key, val in lattice_parameters.items():
1458
+ if key in ('a', 'b', 'c'):
1459
+ val *= length_unit
1460
+ setattr(
1461
+ sec_positions,
1462
+ 'x_castep_cell_length_%s' % key,
1463
+ val.to('m').magnitude,
1464
+ )
1465
+ elif key in ('alpha', 'beta', 'gamma'):
1466
+ setattr(sec_positions, 'x_castep_cell_angle_%s' % key, val)
1467
+
1468
+ # tddft
1469
+ # why are tddft results here?, adapted from old parser
1470
+ tddft = source.get('tddft')
1471
+ if tddft is not None:
1472
+ for energies in tddft.get('energies', []):
1473
+ sec_tddft = x_castep_section_tddft()
1474
+ sec_system.x_castep_section_tddft.append(sec_tddft)
1475
+ energies = energies * self.units.get('energy', ureg.eV)
1476
+ sec_tddft.x_castep_state_energy = energies[1].to('J').magnitude
1477
+ sec_tddft.x_castep_state_energy_error = (
1478
+ energies[2].to('J').magnitude
1479
+ )
1480
+ sec_tddft.x_castep_state_number = energies[0].magnitude
1481
+ sec_tddft.x_castep_tddft_calculation_time = tddft.get('time', 0.0)
1482
+ sec_tddft.x_castep_tddft_iteration = tddft.get('iteration', [0, 0])[-1][
1483
+ 0
1484
+ ]
1485
+
1486
+ # add miscellaneos stuff to first instance
1487
+ if len(sec_run.system) == 1:
1488
+ for key, val in (
1489
+ self.out_parser.get('title', {})
1490
+ .get('electronic parameters', {})
1491
+ .items()
1492
+ ):
1493
+ key = self._metainfo_map.get('electronic parameters', {}).get(key)
1494
+ if key is None:
1495
+ continue
1496
+ setattr(sec_system, key, val)
1497
+
1498
+ return sec_system
1499
+
1500
+ def parse_calculation(source):
1501
+ if source is None:
1502
+ return
1503
+ sec_scc = parse_scc(source)
1504
+ sec_system = parse_system(source)
1505
+ sec_scc.system_ref = sec_system
1506
+ sec_scc.method_ref = sec_run.method[-1]
1507
+
1508
+ # basis set correction
1509
+ # TODO determine if there is a need to add this
1510
+ basis_set_correction = calculation.get('basis_set_correction')
1511
+ if basis_set_correction is not None:
1512
+ for iteration in basis_set_correction.get('iteration', []):
1513
+ parse_calculation(iteration)
1514
+
1515
+ # transition state search
1516
+ tss = calculation.get('tss')
1517
+ if tss is not None:
1518
+ for iteration in tss.get('iteration', []):
1519
+ parse_calculation(iteration)
1520
+
1521
+ cg_refinement = calculation.get('cg_refinement')
1522
+ if cg_refinement is not None:
1523
+ for iteration in cg_refinement.get('iteration', []):
1524
+ parse_calculation(iteration)
1525
+
1526
+ # molecular dyanamics
1527
+ # because of basis set correction number of frames may not correspond to number
1528
+ # of iterations
1529
+ md = calculation.get('md')
1530
+ if md is not None:
1531
+ # TODO add more quantities, read from md file
1532
+ for iteration in md.get('iteration', []):
1533
+ parse_calculation(iteration)
1534
+
1535
+ # dmd optimization
1536
+ dmd = calculation.get('dmd')
1537
+ if dmd is not None:
1538
+ for iteration in dmd.get('iteration', []):
1539
+ parse_calculation(iteration)
1540
+
1541
+ # di optimization
1542
+ di = calculation.get('di')
1543
+ if di is not None:
1544
+ for iteration in di.get('iteration', []):
1545
+ parse_calculation(iteration)
1546
+
1547
+ # bfgs optimization
1548
+ bfgs = calculation.get('bfgs')
1549
+ if bfgs is not None:
1550
+ for iteration in bfgs.get('iteration', []):
1551
+ # an iteration can both have a pre-conditioning stage which we skip
1552
+ if iteration.get('iteration'):
1553
+ parse_calculation(iteration.get('iteration')[-1])
1554
+
1555
+ # final configuration
1556
+ if calculation.get('final') is not None:
1557
+ parse_calculation(calculation.get('final'))
1558
+
1559
+ if self.archive.workflow2.m_def.name in ['SinglePoint', 'Phonon']:
1560
+ # single point calculation
1561
+ parse_calculation(calculation)
1562
+
1563
+ def parse_parameters(self):
1564
+ section_map = {
1565
+ 'phonon parameters': x_castep_section_phonons,
1566
+ 'electronic minimization parameters': x_castep_section_scf_parameters,
1567
+ 'density mixing parameters': x_castep_section_density_mixing_parameters,
1568
+ 'population analysis parameters': x_castep_section_population_analysis_parameters,
1569
+ 'core level spectra parameters': x_castep_section_core_parameters,
1570
+ 'band structure parameters': x_castep_section_band_parameters,
1571
+ 'transition state search parameters': x_castep_section_ts_parameters,
1572
+ 'optics parameters': x_castep_section_optics_parameters,
1573
+ 'electronic spectroscopy parameters': x_castep_section_electronic_spectroscpy_parameters,
1574
+ 'time-dependent dft parameters': x_castep_section_tddft_parameters,
1575
+ }
1576
+
1577
+ # TODO map all castep parameters
1578
+ sec_run = self.archive.run[0]
1579
+ title = self.out_parser.get('title', {})
1580
+
1581
+ def create_section(definition):
1582
+ if definition is None:
1583
+ return
1584
+
1585
+ create = True
1586
+ section = None
1587
+ for section in sec_run.m_contents():
1588
+ if section.m_def == definition.m_def:
1589
+ create = False
1590
+ break
1591
+ if create:
1592
+ section = definition()
1593
+ sub_section_def = sec_run.m_def.all_sub_sections_by_section.get(
1594
+ definition.m_def
1595
+ )[0]
1596
+ sec_run.m_add_sub_section(sub_section_def, section)
1597
+ return section
1598
+
1599
+ for key in title.keys():
1600
+ section = create_section(section_map.get(key))
1601
+ if section is None:
1602
+ continue
1603
+ for sub_key, val in title[key].items():
1604
+ sub_key = self._metainfo_map.get(key, {}).get(sub_key)
1605
+ if val is not None and sub_key is not None:
1606
+ val = val.magnitude if hasattr(val, 'magnitude') else val
1607
+ setattr(section, sub_key, val)
1608
+
1609
+ # van der Waals
1610
+ dft_d = self.out_parser.get('dft_d')
1611
+ if dft_d is not None:
1612
+ sec_vdW = x_castep_section_van_der_Waals_parameters()
1613
+ sec_run.x_castep_section_van_der_Waals_parameters.append(sec_vdW)
1614
+ if dft_d.get('method') is not None:
1615
+ sec_vdW.x_castep_disp_method_name = dft_d.get('method')
1616
+ for parameter in dft_d.get('parameter', []):
1617
+ key = parameter[0].upper() if parameter[0] == 'lambda' else parameter[0]
1618
+ setattr(sec_vdW, 'x_castep_Parameter_%s' % key, float(parameter[1]))
1619
+
1620
+ def parse(self, filepath, archive, logger):
1621
+ self.filepath = os.path.abspath(filepath)
1622
+ self.archive = archive
1623
+ self.maindir = os.path.dirname(self.filepath)
1624
+ self.mainfile = os.path.basename(self.filepath)
1625
+ self.logger = logger if logger is not None else logging.getLogger(__name__)
1626
+
1627
+ self.init_parser()
1628
+
1629
+ sec_run = Run()
1630
+ self.archive.run.append(sec_run)
1631
+ version = self.out_parser.get('program_version', ['CASTEP', ''])
1632
+ sec_run.program = Program(name=version[0])
1633
+ if version[1]:
1634
+ sec_run.program.version = str(version[1])
1635
+
1636
+ compilation = (
1637
+ self.out_parser.get('program_compilation', '').strip().split(' ', 1)
1638
+ )
1639
+ if len(compilation) == 2:
1640
+ sec_run.program.compilation_host = compilation[0]
1641
+ date, time = compilation[1].rsplit(' ', 1)
1642
+ sec_run.x_castep_program_compilation_date = date
1643
+ sec_run.x_castep_program_compilation_time = time
1644
+
1645
+ for key in ['compiler', 'maths_library', 'fft_library', 'constants_reference']:
1646
+ val = self.out_parser.get(key)
1647
+ if val is not None:
1648
+ setattr(sec_run, 'x_castep_%s' % key, val)
1649
+
1650
+ date_start = self.out_parser.get('run_start')
1651
+ if date_start is not None:
1652
+ date_start = datetime.strptime(date_start.strip(), '%d %b %Y %H:%M:%S')
1653
+ sec_run.time_run = TimeRun(
1654
+ date_start=(date_start - datetime(1970, 1, 1)).total_seconds()
1655
+ )
1656
+
1657
+ self.parse_method()
1658
+
1659
+ self.parse_workflow()
1660
+
1661
+ self.parse_configurations()
1662
+
1663
+ self.parse_parameters()
1664
+
1665
+ # times
1666
+ time = self.out_parser.get('time')
1667
+ if time is not None:
1668
+ total_time = None
1669
+ sec_time = x_castep_section_time()
1670
+ sec_run.x_castep_section_time.append(sec_time)
1671
+ for key, val in time:
1672
+ if key == 'Total':
1673
+ total_time = val
1674
+ setattr(sec_time, 'x_castep_%s_time' % key.lower(), val)
1675
+ if total_time is not None and len(sec_run.calculation) > 2:
1676
+ sec_scc = sec_run.calculation[-1]
1677
+ sec_scc.time_physical = total_time * ureg.s
1678
+ sec_scc.time_calculation = (
1679
+ sec_scc.time_physical - sec_run.calculation[-2].time_physical
1680
+ )