Debian Codegraph @

cclib/parser/data.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2019, the cclib development team
4 #
5 # This file is part of cclib (http://cclib.github.io) and is distributed under
6 # the terms of the BSD 3-Clause License.
7
8 """Classes and tools for storing and handling parsed data"""
9
10 import logging
11 from collections import namedtuple
12
13 import numpy
14
15 from cclib.method import Electrons
16 from cclib.method import orbitals
17
18
19 Attribute = namedtuple('Attribute', ['type', 'json_key', 'attribute_path'])
20
21
22 class ccData(object):
23 """Stores data extracted by cclib parsers
24
25 Description of cclib attributes:
26 aonames -- atomic orbital names (list of strings)
27 aooverlaps -- atomic orbital overlap matrix (array[2])
28 atombasis -- indices of atomic orbitals on each atom (list of lists)
29 atomcharges -- atomic partial charges (dict of arrays[1])
30 atomcoords -- atom coordinates (array[3], angstroms)
31 atommasses -- atom masses (array[1], daltons)
32 atomnos -- atomic numbers (array[1])
33 atomspins -- atomic spin densities (dict of arrays[1])
34 ccenergies -- molecular energies with Coupled-Cluster corrections (array[2], eV)
35 charge -- net charge of the system (integer)
36 coreelectrons -- number of core electrons in atom pseudopotentials (array[1])
37 enthalpy -- sum of electronic and thermal enthalpies (float, hartree/particle)
38 entropy -- entropy (float, hartree/particle)
39 etenergies -- energies of electronic transitions (array[1], 1/cm)
40 etoscs -- oscillator strengths of electronic transitions (array[1])
41 etrotats -- rotatory strengths of electronic transitions (array[1], ??)
42 etsecs -- singly-excited configurations for electronic transitions (list of lists)
43 etsyms -- symmetries of electronic transitions (list of string)
44 freeenergy -- sum of electronic and thermal free energies (float, hartree/particle)
45 fonames -- fragment orbital names (list of strings)
46 fooverlaps -- fragment orbital overlap matrix (array[2])
47 fragnames -- names of fragments (list of strings)
48 frags -- indices of atoms in a fragment (list of lists)
49 gbasis -- coefficients and exponents of Gaussian basis functions (PyQuante format)
50 geotargets -- targets for convergence of geometry optimization (array[1])
51 geovalues -- current values for convergence of geometry optmization (array[1])
52 grads -- current values of forces (gradients) in geometry optimization (array[3])
53 hessian -- elements of the force constant matrix (array[1])
54 homos -- molecular orbital indices of HOMO(s) (array[1])
55 metadata -- various metadata about the package and computation (dict)
56 mocoeffs -- molecular orbital coefficients (list of arrays[2])
57 moenergies -- molecular orbital energies (list of arrays[1], eV)
58 moments -- molecular multipole moments (list of arrays[], a.u.)
59 mosyms -- orbital symmetries (list of lists)
60 mpenergies -- molecular electronic energies with Møller-Plesset corrections (array[2], eV)
61 mult -- multiplicity of the system (integer)
62 natom -- number of atoms (integer)
63 nbasis -- number of basis functions (integer)
64 nmo -- number of molecular orbitals (integer)
65 nocoeffs -- natural orbital coefficients (array[2])
66 nooccnos -- natural orbital occupation numbers (array[1])
67 nsocoeffs -- natural spin orbital coefficients (list of array[2])
68 nsooccnos -- natural spin orbital occupation numbers (list of array[1])
69 optdone -- flags whether an optimization has converged (Boolean)
70 optstatus -- optimization status for each set of atomic coordinates (array[1])
71 polarizabilities -- (dipole) polarizabilities, static or dynamic (list of arrays[2])
72 pressure -- temperature used for Thermochemistry (float, atm)
73 scancoords -- geometries of each scan step (array[3], angstroms)
74 scanenergies -- energies of potential energy surface (list)
75 scannames -- names of varaibles scanned (list of strings)
76 scanparm -- values of parameters in potential energy surface (list of tuples)
77 scfenergies -- molecular electronic energies after SCF (Hartree-Fock, DFT) (array[1], eV)
78 scftargets -- targets for convergence of the SCF (array[2])
79 scfvalues -- current values for convergence of the SCF (list of arrays[2])
80 temperature -- temperature used for Thermochemistry (float, kelvin)
81 time -- time in molecular dynamics and other trajectories (array[1], fs)
82 transprop -- all absorption and emission spectra (dictionary {name:(etenergies, etoscs)})
83 WARNING: this attribute is not standardized and is liable to change in cclib 2.0
84 vibanharms -- vibrational anharmonicity constants (array[2], 1/cm)
85 vibdisps -- cartesian displacement vectors (array[3], delta angstrom)
86 vibfreqs -- vibrational frequencies (array[1], 1/cm)
87 vibirs -- IR intensities (array[1], km/mol)
88 vibramans -- Raman intensities (array[1], A^4/Da)
89 vibsyms -- symmetries of vibrations (list of strings)
90 (1) The term 'array' refers to a numpy array
91 (2) The number of dimensions of an array is given in square brackets
92 (3) Python indexes arrays/lists starting at zero, so if homos==[10], then
93 the 11th molecular orbital is the HOMO
94 """
95
96 # The expected types for all supported attributes.
97 # The json_key is the key name used for attributes in the CJSON/JSON format
98 # 'TBD' - To Be Decided are the key names of attributes which haven't been included in the cjson format
99 _attributes = {
100 "aonames": Attribute(list, 'names', 'atoms:orbitals'),
101 "aooverlaps": Attribute(numpy.ndarray, 'overlaps', 'properties:orbitals'),
102 "atombasis": Attribute(list, 'indices', 'atoms:orbitals'),
103 "atomcharges": Attribute(dict, 'partial charges', 'properties'),
104 "atomcoords": Attribute(numpy.ndarray, 'coords', 'atoms:coords:3d'),
105 "atommasses": Attribute(numpy.ndarray, 'mass', 'atoms'),
106 "atomnos": Attribute(numpy.ndarray, 'number', 'atoms:elements'),
107 "atomspins": Attribute(dict, 'spins', 'atoms'),
108 "ccenergies": Attribute(numpy.ndarray, 'coupled cluster', 'properties:energy'),
109 "charge": Attribute(int, 'charge', 'properties'),
110 "coreelectrons": Attribute(numpy.ndarray, 'core electrons', 'atoms'),
111 "enthalpy": Attribute(float, 'enthalpy', 'properties'),
112 "entropy": Attribute(float, 'entropy', 'properties'),
113 "etenergies": Attribute(numpy.ndarray, 'electronic transitions', 'transitions'),
114 "etoscs": Attribute(numpy.ndarray, 'oscillator strength', 'transitions'),
115 "etrotats": Attribute(numpy.ndarray, 'rotatory strength', 'transitions'),
116 "etsecs": Attribute(list, 'one excited config', 'transitions'),
117 "etsyms": Attribute(list, 'symmetry', 'transitions'),
118 "freeenergy": Attribute(float, 'free energy', 'properties:energy'),
119 "fonames": Attribute(list, 'orbital names', 'fragments'),
120 "fooverlaps": Attribute(numpy.ndarray, 'orbital overlap', 'fragments'),
121 "fragnames": Attribute(list, 'fragment names', 'fragments'),
122 "frags": Attribute(list, 'atom indices', 'fragments'),
123 "gbasis": Attribute(list, 'basis functions', 'atoms:orbitals'),
124 "geotargets": Attribute(numpy.ndarray, 'geometric targets', 'optimization'),
125 "geovalues": Attribute(numpy.ndarray, 'geometric values', 'optimization'),
126 "grads": Attribute(numpy.ndarray, 'TBD', 'N/A'),
127 "hessian": Attribute(numpy.ndarray, 'hessian matrix', 'vibrations'),
128 "homos": Attribute(numpy.ndarray, 'homos', 'properties:orbitals'),
129 "metadata": Attribute(dict, 'TBD', 'N/A'),
130 "mocoeffs": Attribute(list, 'coeffs', 'properties:orbitals'),
131 "moenergies": Attribute(list, 'energies', 'properties:orbitals'),
132 "moments": Attribute(list, 'total dipole moment', 'properties'),
133 "mosyms": Attribute(list, 'molecular orbital symmetry', 'properties:orbitals'),
134 "mpenergies": Attribute(numpy.ndarray, 'moller plesset', 'properties:energy'),
135 "mult": Attribute(int, 'multiplicity', 'properties'),
136 "natom": Attribute(int, 'number of atoms', 'properties'),
137 "nbasis": Attribute(int, 'basis number', 'properties:orbitals'),
138 "nmo": Attribute(int, 'MO number', 'properties:orbitals'),
139 "nocoeffs": Attribute(numpy.ndarray, 'TBD', 'N/A'),
140 "nooccnos": Attribute(numpy.ndarray, 'TBD', 'N/A'),
141 "nsocoeffs": Attribute(list, 'TBD', 'N/A'),
142 "nsooccnos": Attribute(list, 'TBD', 'N/A'),
143 "optdone": Attribute(list, 'done', 'optimization'),
144 "optstatus": Attribute(numpy.ndarray, 'status', 'optimization'),
145 "polarizabilities": Attribute(list, 'polarizabilities', 'N/A'),
146 "pressure": Attribute(float, 'pressure', 'properties'),
147 "scancoords": Attribute(numpy.ndarray, 'step geometry', 'optimization:scan'),
148 "scanenergies": Attribute(list, 'PES energies', 'optimization:scan'),
149 "scannames": Attribute(list, 'variable names', 'optimization:scan'),
150 "scanparm": Attribute(list, 'PES parameter values', 'optimization:scan'),
151 "scfenergies": Attribute(numpy.ndarray, 'scf energies', 'optimization:scf'),
152 "scftargets": Attribute(numpy.ndarray, 'targets', 'optimization:scf'),
153 "scfvalues": Attribute(list, 'values', 'optimization:scf'),
154 "temperature": Attribute(float, 'temperature', 'properties'),
155 "time": Attribute(numpy.ndarray, 'time', 'N/A'),
156 "transprop": Attribute(dict, 'electronic transitions', 'transitions'),
157 "vibanharms": Attribute(numpy.ndarray, 'anharmonicity constants', 'vibrations'),
158 "vibdisps": Attribute(numpy.ndarray, 'displacement', 'vibrations'),
159 "vibfreqs": Attribute(numpy.ndarray, 'frequencies', 'vibrations'),
160 "vibirs": Attribute(numpy.ndarray, 'IR', 'vibrations:intensities'),
161 "vibramans": Attribute(numpy.ndarray, 'raman', 'vibrations:intensities'),
162 "vibsyms": Attribute(list, 'vibration symmetry', 'vibrations')
163 }
164
165 # The name of all attributes can be generated from the dictionary above.
166 _attrlist = sorted(_attributes.keys())
167
168 # Arrays are double precision by default, but these will be integer arrays.
169 _intarrays = ['atomnos', 'coreelectrons', 'homos', 'optstatus']
170
171 # Attributes that should be lists of arrays (double precision).
172 _listsofarrays = ['mocoeffs', 'moenergies', 'moments', 'polarizabilities', 'scfvalues']
173
174 # Attributes that should be dictionaries of arrays (double precision).
175 _dictsofarrays = ["atomcharges", "atomspins"]
176
177 # Possible statuses for optimization steps.
178 # OPT_UNKNOWN is the default and means optimization is in progress.
179 # OPT_NEW is set for every new optimization (e.g. PES, IRCs, etc.)
180 # OPT_DONE is set for the last step of an optimisation that converged.
181 # OPT_UNCONVERGED is set for every unconverged step (e.g. should be mutually exclusive with OPT_DONE)
182 # bit value notation allows coding for multiple states: OPT_NEW and OPT_UNCONVERGED or OPT_NEW and OPT_DONE.
183 OPT_UNKNOWN = 0b000
184 OPT_NEW = 0b001
185 OPT_UNCONVERGED = 0b010
186 OPT_DONE = 0b100
187
188 def __init__(self, attributes={}):
189 """Initialize the cclibData object.
190
191 Normally called in the parse() method of a Logfile subclass.
192
193 Inputs:
194 attributes - optional dictionary of attributes to load as data
195 """
196
197 if attributes:
198 self.setattributes(attributes)
199
200 def listify(self):
201 """Converts all attributes that are arrays or lists/dicts of arrays to lists."""
202
203 attrlist = [k for k in self._attrlist if hasattr(self, k)]
204 for k in attrlist:
205 v = self._attributes[k].type
206 if v == numpy.ndarray:
207 setattr(self, k, getattr(self, k).tolist())
208 elif v == list and k in self._listsofarrays:
209 setattr(self, k, [x.tolist() for x in getattr(self, k)])
210 elif v == dict and k in self._dictsofarrays:
211 items = getattr(self, k).items()
212 pairs = [(key, val.tolist()) for key, val in items]
213 setattr(self, k, dict(pairs))
214
215 def arrayify(self):
216 """Converts appropriate attributes to arrays or lists/dicts of arrays."""
217
218 attrlist = [k for k in self._attrlist if hasattr(self, k)]
219 for k in attrlist:
220 v = self._attributes[k].type
221 precision = 'd'
222 if k in self._intarrays:
223 precision = 'i'
224 if v == numpy.ndarray:
225 setattr(self, k, numpy.array(getattr(self, k), precision))
226 elif v == list and k in self._listsofarrays:
227 setattr(self, k, [numpy.array(x, precision) for x in getattr(self, k)])
228 elif v == dict and k in self._dictsofarrays:
229 items = getattr(self, k).items()
230 pairs = [(key, numpy.array(val, precision)) for key, val in items]
231 setattr(self, k, dict(pairs))
232
233 def getattributes(self, tolists=False):
234 """Returns a dictionary of existing data attributes.
235
236 Inputs:
237 tolists - flag to convert attributes to lists where applicable
238 """
239
240 if tolists:
241 self.listify()
242 attributes = {}
243 for attr in self._attrlist:
244 if hasattr(self, attr):
245 attributes[attr] = getattr(self, attr)
246 if tolists:
247 self.arrayify()
248 return attributes
249
250 def setattributes(self, attributes):
251 """Sets data attributes given in a dictionary.
252
253 Inputs:
254 attributes - dictionary of attributes to set
255 Outputs:
256 invalid - list of attributes names that were not set, which
257 means they are not specified in self._attrlist
258 """
259
260 if type(attributes) is not dict:
261 raise TypeError("attributes must be in a dictionary")
262
263 valid = [a for a in attributes if a in self._attrlist]
264 invalid = [a for a in attributes if a not in self._attrlist]
265
266 for attr in valid:
267 setattr(self, attr, attributes[attr])
268
269 self.arrayify()
270 self.typecheck()
271
272 return invalid
273
274 def typecheck(self):
275 """Check the types of all attributes.
276
277 If an attribute does not match the expected type, then attempt to
278 convert; if that fails, only then raise a TypeError.
279 """
280
281 self.arrayify()
282 for attr in [a for a in self._attrlist if hasattr(self, a)]:
283
284 val = getattr(self, attr)
285 if type(val) == self._attributes[attr].type:
286 continue
287
288 try:
289 val = self._attributes[attr].type(val)
290 except ValueError:
291 args = (attr, type(val), self._attributes[attr].type)
292 raise TypeError("attribute %s is %s instead of %s and could not be converted" % args)
293
294 def check_values(self, logger=logging):
295 """Perform custom checks on the values of attributes."""
296 if hasattr(self, "etenergies") and any(e < 0 for e in self.etenergies):
297 negative_values = [e for e in self.etenergies if e < 0]
298 msg = ("At least one excitation energy is negative. "
299 "\nNegative values: %s\nFull etenergies: %s"
300 % (negative_values, self.etenergies))
301 logger.error(msg)
302
303 def write(self, filename=None, indices=None, *args, **kwargs):
304 """Write parsed attributes to a file.
305
306 Possible extensions:
307 .cjson or .json - output a chemical JSON file
308 .cml - output a chemical markup language (CML) file
309 .xyz - output a Cartesian XYZ file of the last coordinates available
310 """
311
312 from cclib.io import ccwrite
313 outputstr = ccwrite(self, outputdest=filename, indices=indices,
314 *args, **kwargs)
315 return outputstr
316
317 def writejson(self, filename=None, indices=None):
318 """Write parsed attributes to a JSON file."""
319 return self.write(filename=filename, indices=indices,
320 outputtype='cjson')
321
322 def writecml(self, filename=None, indices=None):
323 """Write parsed attributes to a CML file."""
324 return self.write(filename=filename, indices=indices,
325 outputtype='cml')
326
327 def writexyz(self, filename=None, indices=None):
328 """Write parsed attributes to an XML file."""
329 return self.write(filename=filename, indices=indices,
330 outputtype='xyz')
331
332 @property
333 def converged_geometries(self):
334 """
335 Return all converged geometries.
336
337 An array containing only the converged geometries, e.g.:
338 - For PES or IRCs, return all geometries for which optstatus matches OPT_DONE
339 - The converged geometry for simple optimisations
340 - The input geometry for single points
341 """
342 if hasattr(self, 'optstatus'):
343 converged_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_DONE > 0]
344 return self.atomcoords[converged_indexes]
345 else:
346 return self.atomcoords
347
348 @property
349 def new_geometries(self):
350 """
351 Return all starting geometries.
352
353 An array containing only the starting geometries, e.g.:
354 - For PES or IRCs, return all geometries for which optstatus matches OPT_NEW
355 - The input geometry for simple optimisations or single points
356 """
357 if hasattr(self, 'optstatus'):
358 new_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_NEW > 0]
359 return self.atomcoords[new_indexes]
360 else:
361 return self.atomcoords
362
363 @property
364 def unknown_geometries(self):
365 """
366 Return all OPT_UNKNOWN geometries.
367
368 An array containing only the starting geometries, e.g.:
369 - For PES or IRCs, return all geometries for which optstatus matches OPT_UNKNOWN
370 - The input geometry for simple optimisations or single points
371 """
372 if hasattr(self, 'optstatus'):
373 unknown_indexes = [x for x, y in enumerate(self.optstatus) if y == self.OPT_UNKNOWN]
374 return self.atomcoords[unknown_indexes]
375 else:
376 return self.atomcoords
377
378 @property
379 def unconverged_geometries(self):
380 """
381 Return all unconverged geometries.
382
383 An array containing only the starting geometries, e.g.:
384 - For PES or IRCs, return all geometries for which optstatus matches OPT_UNCONVERGED
385 - The input geometry for simple optimisations or single points
386 """
387 if hasattr(self, 'optstatus'):
388 unconverged_indexes = [x for x, y in enumerate(self.optstatus) if y & self.OPT_UNCONVERGED > 0]
389 return self.atomcoords[unconverged_indexes]
390 else:
391 return self.atomcoords
392
393 @property
394 def nelectrons(self):
395 return Electrons(self).count()
396
397 @property
398 def closed_shell(self):
399 return orbitals.Orbitals(self).closed_shell()
400
401
402 class ccData_optdone_bool(ccData):
403 """This is the version of ccData where optdone is a Boolean."""
404
405 def __init__(self, *args, **kwargs):
406
407 super(ccData_optdone_bool, self).__init__(*args, **kwargs)
408 self._attributes["optdone"] = Attribute(bool, 'done', 'optimization')
409
410 def setattributes(self, *args, **kwargs):
411 invalid = super(ccData_optdone_bool, self).setattributes(*args, **kwargs)
412
413 # Reduce optdone to a Boolean, because it will be parsed as a list. If this list has any element,
414 # it means that there was an optimized structure and optdone should be True.
415 if hasattr(self, 'optdone'):
416 self.optdone = len(self.optdone) > 0