Debian Codegraph @

cclib/parser/nwchemparser.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2017, 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 """Parser for NWChem output files"""
9
10
11 import itertools
12 import re
13
14 import numpy
15
16 from cclib.parser import logfileparser
17 from cclib.parser import utils
18
19
20 class NWChem(logfileparser.Logfile):
21 """An NWChem log file."""
22
23 def __init__(self, *args, **kwargs):
24
25 # Call the __init__ method of the superclass
26 super(NWChem, self).__init__(logname="NWChem", *args, **kwargs)
27
28 def __str__(self):
29 """Return a string representation of the object."""
30 return "NWChem log file %s" % (self.filename)
31
32 def __repr__(self):
33 """Return a representation of the object."""
34 return 'NWChem("%s")' % (self.filename)
35
36 def normalisesym(self, label):
37 """NWChem does not require normalizing symmetry labels."""
38 return label
39
40 name2element = lambda self, lbl: "".join(itertools.takewhile(str.isalpha, str(lbl)))
41
42 def extract(self, inputfile, line):
43 """Extract information from the file object inputfile."""
44
45 # Extract the version number.
46 if "nwchem branch" in line:
47 self.metadata["package_version"] = line.split()[3]
48 # Don't add revision information to the main package version for now.
49 if "nwchem revision" in line:
50 revision = line.split()[3]
51
52 # This is printed in the input module, so should always be the first coordinates,
53 # and contains some basic information we want to parse as well. However, this is not
54 # the only place where the coordinates are printed during geometry optimization,
55 # since the gradients module has a separate coordinate printout, which happens
56 # alongside the coordinate gradients. This geometry printout happens at the
57 # beginning of each optimization step only.
58 if line.strip() == 'Geometry "geometry" -> ""' or line.strip() == 'Geometry "geometry" -> "geometry"':
59
60 self.skip_lines(inputfile, ['dashes', 'blank', 'units', 'blank', 'header', 'dashes'])
61
62 if not hasattr(self, 'atomcoords'):
63 self.atomcoords = []
64
65 line = next(inputfile)
66 coords = []
67 atomnos = []
68 while line.strip():
69 # The column labeled 'tag' is usually empty, but I'm not sure whether it can have spaces,
70 # so for now assume that it can and that there will be seven columns in that case.
71 if len(line.split()) == 6:
72 index, atomname, nuclear, x, y, z = line.split()
73 else:
74 index, atomname, tag, nuclear, x, y, z = line.split()
75 coords.append(list(map(float, [x, y, z])))
76 atomnos.append(int(float(nuclear)))
77 line = next(inputfile)
78
79 self.atomcoords.append(coords)
80
81 self.set_attribute('atomnos', atomnos)
82
83 # If the geometry is printed in XYZ format, it will have the number of atoms.
84 if line[12:31] == "XYZ format geometry":
85
86 self.skip_line(inputfile, 'dashes')
87 natom = int(next(inputfile).strip())
88 self.set_attribute('natom', natom)
89
90 if line.strip() == "NWChem Geometry Optimization":
91 self.skip_lines(inputfile, ['d', 'b', 'b', 'b', 'b', 'title', 'b', 'b'])
92 line = next(inputfile)
93 while line.strip():
94 if "maximum gradient threshold" in line:
95 gmax = float(line.split()[-1])
96 if "rms gradient threshold" in line:
97 grms = float(line.split()[-1])
98 if "maximum cartesian step threshold" in line:
99 xmax = float(line.split()[-1])
100 if "rms cartesian step threshold" in line:
101 xrms = float(line.split()[-1])
102 line = next(inputfile)
103
104 self.set_attribute('geotargets', [gmax, grms, xmax, xrms])
105
106 # NWChem does not normally print the basis set for each atom, but rather
107 # chooses the concise option of printing Gaussian coefficients for each
108 # atom type/element only once. Therefore, we need to first parse those
109 # coefficients and afterwards build the appropriate gbasis attribute based
110 # on that and atom types/elements already parsed (atomnos). However, if atom
111 # are given different names (number after element, like H1 and H2), then NWChem
112 # generally prints the gaussian parameters for all unique names, like this:
113 #
114 # Basis "ao basis" -> "ao basis" (cartesian)
115 # -----
116 # O (Oxygen)
117 # ----------
118 # Exponent Coefficients
119 # -------------- ---------------------------------------------------------
120 # 1 S 1.30709320E+02 0.154329
121 # 1 S 2.38088610E+01 0.535328
122 # (...)
123 #
124 # H1 (Hydrogen)
125 # -------------
126 # Exponent Coefficients
127 # -------------- ---------------------------------------------------------
128 # 1 S 3.42525091E+00 0.154329
129 # (...)
130 #
131 # H2 (Hydrogen)
132 # -------------
133 # Exponent Coefficients
134 # -------------- ---------------------------------------------------------
135 # 1 S 3.42525091E+00 0.154329
136 # (...)
137 #
138 # This current parsing code below assumes all atoms of the same element
139 # use the same basis set, but that might not be true, and this will probably
140 # need to be considered in the future when such a logfile appears.
141 if line.strip() == """Basis "ao basis" -> "ao basis" (cartesian)""":
142 self.skip_line(inputfile, 'dashes')
143 gbasis_dict = {}
144 line = next(inputfile)
145 while line.strip():
146 atomname = line.split()[0]
147 atomelement = self.name2element(atomname)
148 gbasis_dict[atomelement] = []
149 self.skip_lines(inputfile, ['d', 'labels', 'd'])
150 shells = []
151 line = next(inputfile)
152 while line.strip() and line.split()[0].isdigit():
153 shell = None
154 while line.strip():
155 nshell, type, exp, coeff = line.split()
156 nshell = int(nshell)
157 assert len(shells) == nshell - 1
158 if not shell:
159 shell = (type, [])
160 else:
161 assert shell[0] == type
162 exp = float(exp)
163 coeff = float(coeff)
164 shell[1].append((exp, coeff))
165 line = next(inputfile)
166 shells.append(shell)
167 line = next(inputfile)
168 gbasis_dict[atomelement].extend(shells)
169
170 gbasis = []
171 for i in range(self.natom):
172 atomtype = self.table.element[self.atomnos[i]]
173 gbasis.append(gbasis_dict[atomtype])
174
175 self.set_attribute('gbasis', gbasis)
176
177 # Normally the indexes of AOs assigned to specific atoms are also not printed,
178 # so we need to infer that. We could do that from the previous section,
179 # it might be worthwhile to take numbers from two different places, hence
180 # the code below, which builds atombasis based on the number of functions
181 # listed in this summary of the AO basis. Similar to previous section, here
182 # we assume all atoms of the same element have the same basis sets, but
183 # this will probably need to be revised later.
184
185 # The section we can glean info about aonmaes looks like:
186 #
187 # Summary of "ao basis" -> "ao basis" (cartesian)
188 # ------------------------------------------------------------------------------
189 # Tag Description Shells Functions and Types
190 # ---------------- ------------------------------ ------ ---------------------
191 # C sto-3g 3 5 2s1p
192 # H sto-3g 1 1 1s
193 #
194 # However, we need to make sure not to match the following entry lines:
195 #
196 # * Summary of "ao basis" -> "" (cartesian)
197 # * Summary of allocated global arrays
198 #
199 # Unfortantely, "ao basis" isn't unique because it can be renamed to anything for
200 # later reference: http://www.nwchem-sw.org/index.php/Basis
201 # It also appears that we have to handle cartesian vs. spherical
202
203 if line[1:11] == "Summary of":
204 match = re.match(' Summary of "([^\"]*)" -> "([^\"]*)" \((.+)\)', line)
205
206 if match and match.group(1) == match.group(2):
207
208 self.skip_lines(inputfile, ['d', 'title', 'd'])
209
210 self.shells = {}
211 self.shells["type"] = match.group(3)
212
213 atombasis_dict = {}
214
215 line = next(inputfile)
216 while line.strip():
217 atomname, desc, shells, funcs, types = line.split()
218 atomelement = self.name2element(atomname)
219 self.metadata["basis_set"] = desc
220
221 self.shells[atomname] = types
222 atombasis_dict[atomelement] = int(funcs)
223 line = next(inputfile)
224
225 last = 0
226 atombasis = []
227 for atom in self.atomnos:
228 atomelement = self.table.element[atom]
229 nfuncs = atombasis_dict[atomelement]
230 atombasis.append(list(range(last, last+nfuncs)))
231 last = atombasis[-1][-1] + 1
232
233 self.set_attribute('atombasis', atombasis)
234
235 # This section contains general parameters for Hartree-Fock calculations,
236 # which do not contain the 'General Information' section like most jobs.
237 if line.strip() == "NWChem SCF Module":
238 # If the calculation doesn't have a title specified, there
239 # aren't as many lines to skip here.
240 self.skip_lines(inputfile, ['d', 'b', 'b'])
241 line = next(inputfile)
242 if line.strip():
243 self.skip_lines(inputfile, ['b', 'b', 'b'])
244 line = next(inputfile)
245 while line.strip():
246 if line[2:8] == "charge":
247 charge = int(float(line.split()[-1]))
248 self.set_attribute('charge', charge)
249 if line[2:13] == "open shells":
250 unpaired = int(line.split()[-1])
251 self.set_attribute('mult', 2*unpaired + 1)
252 if line[2:7] == "atoms":
253 natom = int(line.split()[-1])
254 self.set_attribute('natom', natom)
255 if line[2:11] == "functions":
256 nfuncs = int(line.split()[-1])
257 self.set_attribute("nbasis", nfuncs)
258 line = next(inputfile)
259
260 # This section contains general parameters for DFT calculations, as well as
261 # for the many-electron theory module.
262 if line.strip() == "General Information":
263
264 if hasattr(self, 'linesearch') and self.linesearch:
265 return
266
267 while line.strip():
268
269 if "No. of atoms" in line:
270 self.set_attribute('natom', int(line.split()[-1]))
271 if "Charge" in line:
272 self.set_attribute('charge', int(line.split()[-1]))
273 if "Spin multiplicity" in line:
274 mult = line.split()[-1]
275 if mult == "singlet":
276 mult = 1
277 self.set_attribute('mult', int(mult))
278 if "AO basis - number of function" in line:
279 nfuncs = int(line.split()[-1])
280 self.set_attribute('nbasis', nfuncs)
281
282 # These will be present only in the DFT module.
283 if "Convergence on energy requested" in line:
284 target_energy = self.float(line.split()[-1])
285 if "Convergence on density requested" in line:
286 target_density = self.float(line.split()[-1])
287 if "Convergence on gradient requested" in line:
288 target_gradient = self.float(line.split()[-1])
289
290 line = next(inputfile)
291
292 # Pretty nasty temporary hack to set scftargets only in the SCF module.
293 if "target_energy" in dir() and "target_density" in dir() and "target_gradient" in dir():
294 if not hasattr(self, 'scftargets'):
295 self.scftargets = []
296 self.scftargets.append([target_energy, target_density, target_gradient])
297
298 #DFT functional information
299 if "XC Information" in line:
300 line = next(inputfile)
301 line = next(inputfile)
302 self.metadata["functional"] = line.split()[0]
303
304 # If the full overlap matrix is printed, it looks like this:
305 #
306 # global array: Temp Over[1:60,1:60], handle: -996
307 #
308 # 1 2 3 4 5 6
309 # ----------- ----------- ----------- ----------- ----------- -----------
310 # 1 1.00000 0.24836 -0.00000 -0.00000 0.00000 0.00000
311 # 2 0.24836 1.00000 0.00000 -0.00000 0.00000 0.00030
312 # 3 -0.00000 0.00000 1.00000 0.00000 0.00000 -0.00014
313 # ...
314 if "global array: Temp Over[" in line:
315
316 self.set_attribute('nbasis', int(line.split('[')[1].split(',')[0].split(':')[1]))
317 self.set_attribute('nmo', int(line.split(']')[0].split(',')[1].split(':')[1]))
318
319 aooverlaps = []
320 while len(aooverlaps) < self.nbasis:
321
322 self.skip_line(inputfile, 'blank')
323
324 indices = [int(i) for i in inputfile.next().split()]
325 assert indices[0] == len(aooverlaps) + 1
326
327 self.skip_line(inputfile, "dashes")
328 data = [inputfile.next().split() for i in range(self.nbasis)]
329 indices = [int(d[0]) for d in data]
330 assert indices == list(range(1, self.nbasis+1))
331
332 for i in range(1, len(data[0])):
333 vector = [float(d[i]) for d in data]
334 aooverlaps.append(vector)
335
336 self.set_attribute('aooverlaps', aooverlaps)
337
338 if line.strip() in ("The SCF is already converged", "The DFT is already converged"):
339 if self.linesearch:
340 return
341 if hasattr(self, 'scftargets'):
342 self.scftargets.append(self.scftargets[-1])
343 if hasattr(self, 'scfvalues'):
344 self.scfvalues.append(self.scfvalues[-1])
345
346 # The default (only?) SCF algorithm for Hartree-Fock is a preconditioned conjugate
347 # gradient method that apparently "always" converges, so this header should reliably
348 # signal a start of the SCF cycle. The convergence targets are also printed here.
349 if line.strip() == "Quadratically convergent ROHF":
350
351 if hasattr(self, 'linesearch') and self.linesearch:
352 return
353
354 while not "Final" in line:
355
356 # Only the norm of the orbital gradient is used to test convergence.
357 if line[:22] == " Convergence threshold":
358 target = float(line.split()[-1])
359 if not hasattr(self, "scftargets"):
360 self.scftargets = []
361 self.scftargets.append([target])
362
363 # This is critical for the stop condition of the section,
364 # because the 'Final Fock-matrix accuracy' is along the way.
365 # It would be prudent to find a more robust stop condition.
366 while list(set(line.strip())) != ["-"]:
367 line = next(inputfile)
368
369 if line.split() == ['iter', 'energy', 'gnorm', 'gmax', 'time']:
370 values = []
371 self.skip_line(inputfile, 'dashes')
372 line = next(inputfile)
373 while line.strip():
374 it, energy, gnorm, gmax, time = line.split()
375 gnorm = self.float(gnorm)
376 values.append([gnorm])
377 try:
378 line = next(inputfile)
379 # Is this the end of the file for some reason?
380 except StopIteration:
381 self.logger.warning('File terminated before end of last SCF! Last gradient norm: {}'.format(gnorm))
382 break
383 if not hasattr(self, 'scfvalues'):
384 self.scfvalues = []
385 self.scfvalues.append(values)
386
387 try:
388 line = next(inputfile)
389 except StopIteration:
390 self.logger.warning('File terminated?')
391 break
392
393 # The SCF for DFT does not use the same algorithm as Hartree-Fock, but always
394 # seems to use the following format to report SCF convergence:
395 # convergence iter energy DeltaE RMS-Dens Diis-err time
396 # ---------------- ----- ----------------- --------- --------- --------- ------
397 # d= 0,ls=0.0,diis 1 -382.2544324446 -8.28D+02 1.42D-02 3.78D-01 23.2
398 # d= 0,ls=0.0,diis 2 -382.3017298534 -4.73D-02 6.99D-03 3.82D-02 39.3
399 # d= 0,ls=0.0,diis 3 -382.2954343173 6.30D-03 4.21D-03 7.95D-02 55.3
400 # ...
401 if line.split() == ['convergence', 'iter', 'energy', 'DeltaE', 'RMS-Dens', 'Diis-err', 'time']:
402
403 if hasattr(self, 'linesearch') and self.linesearch:
404 return
405
406 self.skip_line(inputfile, 'dashes')
407 line = next(inputfile)
408 values = []
409 while line.strip():
410
411 # Sometimes there are things in between iterations with fewer columns,
412 # and we want to skip those lines, most probably. An exception might
413 # unrestricted calcualtions, which show extra RMS density and DIIS
414 # errors, although it is not clear yet whether these are for the
415 # beta orbitals or somethine else. The iterations look like this in that case:
416 # convergence iter energy DeltaE RMS-Dens Diis-err time
417 # ---------------- ----- ----------------- --------- --------- --------- ------
418 # d= 0,ls=0.0,diis 1 -382.0243202601 -8.28D+02 7.77D-03 1.04D-01 30.0
419 # 7.68D-03 1.02D-01
420 # d= 0,ls=0.0,diis 2 -382.0647539758 -4.04D-02 4.64D-03 1.95D-02 59.2
421 # 5.39D-03 2.36D-02
422 # ...
423 if len(line[17:].split()) == 6:
424 iter, energy, deltaE, dens, diis, time = line[17:].split()
425 val_energy = self.float(deltaE)
426 val_density = self.float(dens)
427 val_gradient = self.float(diis)
428 values.append([val_energy, val_density, val_gradient])
429
430 try:
431 line = next(inputfile)
432 # Is this the end of the file for some reason?
433 except StopIteration:
434 self.logger.warning('File terminated before end of last SCF! Last error: {}'.format(diis))
435 break
436
437 if not hasattr(self, 'scfvalues'):
438 self.scfvalues = []
439
440 self.scfvalues.append(values)
441
442 # These triggers are supposed to catch the current step in a geometry optimization search
443 # and determine whether we are currently in the main (initial) SCF cycle of that step
444 # or in the subsequent line search. The step is printed between dashes like this:
445 #
446 # --------
447 # Step 0
448 # --------
449 #
450 # and the summary lines that describe the main SCF cycle for the frsit step look like this:
451 #
452 #@ Step Energy Delta E Gmax Grms Xrms Xmax Walltime
453 #@ ---- ---------------- -------- -------- -------- -------- -------- --------
454 #@ 0 -379.76896249 0.0D+00 0.04567 0.01110 0.00000 0.00000 4.2
455 # ok ok
456 #
457 # However, for subsequent step the format is a bit different:
458 #
459 # Step Energy Delta E Gmax Grms Xrms Xmax Walltime
460 # ---- ---------------- -------- -------- -------- -------- -------- --------
461 #@ 2 -379.77794602 -7.4D-05 0.00118 0.00023 0.00440 0.01818 14.8
462 # ok
463 #
464 # There is also a summary of the line search (which we don't use now), like this:
465 #
466 # Line search:
467 # step= 1.00 grad=-1.8D-05 hess= 8.9D-06 energy= -379.777955 mode=accept
468 # new step= 1.00 predicted energy= -379.777955
469 #
470 if line[10:14] == "Step":
471 self.geostep = int(line.split()[-1])
472 self.skip_line(inputfile, 'dashes')
473 self.linesearch = False
474 if line[0] == "@" and line.split()[1] == "Step":
475 at_and_dashes = next(inputfile)
476 line = next(inputfile)
477 assert int(line.split()[1]) == self.geostep == 0
478 gmax = float(line.split()[4])
479 grms = float(line.split()[5])
480 xrms = float(line.split()[6])
481 xmax = float(line.split()[7])
482 if not hasattr(self, 'geovalues'):
483 self.geovalues = []
484 self.geovalues.append([gmax, grms, xmax, xrms])
485 self.linesearch = True
486 if line[2:6] == "Step":
487 self.skip_line(inputfile, 'dashes')
488 line = next(inputfile)
489 assert int(line.split()[1]) == self.geostep
490 if self.linesearch:
491 #print(line)
492 return
493 gmax = float(line.split()[4])
494 grms = float(line.split()[5])
495 xrms = float(line.split()[6])
496 xmax = float(line.split()[7])
497 if not hasattr(self, 'geovalues'):
498 self.geovalues = []
499 self.geovalues.append([gmax, grms, xmax, xrms])
500 self.linesearch = True
501
502 # There is a clear message when the geometry optimization has converged:
503 #
504 # ----------------------
505 # Optimization converged
506 # ----------------------
507 #
508 if line.strip() == "Optimization converged":
509 self.skip_line(inputfile, 'dashes')
510 if not hasattr(self, 'optdone'):
511 self.optdone = []
512 self.optdone.append(len(self.geovalues) - 1)
513
514 if "Failed to converge" in line and hasattr(self, 'geovalues'):
515 if not hasattr(self, 'optdone'):
516 self.optdone = []
517
518 # extract the theoretical method
519 if "Total SCF energy" in line:
520 self.metadata["methods"].append("HF")
521 if "Total DFT energy" in line:
522 self.metadata["methods"].append("DFT")
523
524 # The line containing the final SCF energy seems to be always identifiable like this.
525 if "Total SCF energy" in line or "Total DFT energy" in line:
526
527 # NWChem often does a line search during geometry optimization steps, reporting
528 # the SCF information but not the coordinates (which are not necessarily 'intermediate'
529 # since the step size can become smaller). We want to skip these SCF cycles,
530 # unless the coordinates can also be extracted (possibly from the gradients?).
531 if hasattr(self, 'linesearch') and self.linesearch:
532 return
533
534 if not hasattr(self, "scfenergies"):
535 self.scfenergies = []
536 energy = float(line.split()[-1])
537 energy = utils.convertor(energy, "hartree", "eV")
538 self.scfenergies.append(energy)
539
540 # The final MO orbitals are printed in a simple list, but apparently not for
541 # DFT calcs, and often this list does not contain all MOs, so make sure to
542 # parse them from the MO analysis below if possible. This section will be like this:
543 #
544 # Symmetry analysis of molecular orbitals - final
545 # -----------------------------------------------
546 #
547 # Numbering of irreducible representations:
548 #
549 # 1 ag 2 au 3 bg 4 bu
550 #
551 # Orbital symmetries:
552 #
553 # 1 bu 2 ag 3 bu 4 ag 5 bu
554 # 6 ag 7 bu 8 ag 9 bu 10 ag
555 # ...
556 if line.strip() == "Symmetry analysis of molecular orbitals - final":
557
558 self.skip_lines(inputfile, ['d', 'b', 'numbering', 'b', 'reps', 'b', 'syms', 'b'])
559
560 if not hasattr(self, 'mosyms'):
561 self.mosyms = [[None]*self.nbasis]
562 line = next(inputfile)
563 while line.strip():
564 ncols = len(line.split())
565 assert ncols % 2 == 0
566 for i in range(ncols//2):
567 index = int(line.split()[i*2]) - 1
568 sym = line.split()[i*2+1]
569 sym = sym[0].upper() + sym[1:]
570 if self.mosyms[0][index]:
571 if self.mosyms[0][index] != sym:
572 self.logger.warning("Symmetry of MO %i has changed" % (index+1))
573 self.mosyms[0][index] = sym
574 line = next(inputfile)
575
576 # The same format is used for HF and DFT molecular orbital analysis. We want to parse
577 # the MO energies from this section, although it is printed already before this with
578 # less precision (might be useful to parse that if this is not available). Also, this
579 # section contains coefficients for the leading AO contributions, so it might also
580 # be useful to parse and use those values if the full vectors are not printed.
581 #
582 # The block looks something like this (two separate alpha/beta blocks in the unrestricted case):
583 #
584 # ROHF Final Molecular Orbital Analysis
585 # -------------------------------------
586 #
587 # Vector 1 Occ=2.000000D+00 E=-1.104059D+01 Symmetry=bu
588 # MO Center= 1.4D-17, 0.0D+00, -6.5D-37, r^2= 2.1D+00
589 # Bfn. Coefficient Atom+Function Bfn. Coefficient Atom+Function
590 # ----- ------------ --------------- ----- ------------ ---------------
591 # 1 0.701483 1 C s 6 -0.701483 2 C s
592 #
593 # Vector 2 Occ=2.000000D+00 E=-1.104052D+01 Symmetry=ag
594 # ...
595 # Vector 12 Occ=2.000000D+00 E=-1.020253D+00 Symmetry=bu
596 # MO Center= -1.4D-17, -5.6D-17, 2.9D-34, r^2= 7.9D+00
597 # Bfn. Coefficient Atom+Function Bfn. Coefficient Atom+Function
598 # ----- ------------ --------------- ----- ------------ ---------------
599 # 36 -0.298699 11 C s 41 0.298699 12 C s
600 # 2 0.270804 1 C s 7 -0.270804 2 C s
601 # 48 -0.213655 15 C s 53 0.213655 16 C s
602 # ...
603 #
604 if "Final" in line and "Molecular Orbital Analysis" in line:
605
606 # Unrestricted jobs have two such blocks, for alpha and beta orbitals, and
607 # we need to keep track of which one we're parsing (always alpha in restricted case).
608 unrestricted = ("Alpha" in line) or ("Beta" in line)
609 alphabeta = int("Beta" in line)
610
611 self.skip_lines(inputfile, ['dashes', 'blank'])
612
613 nvectors = []
614 mooccnos = []
615 energies = []
616 symmetries = [None]*self.nbasis
617 line = next(inputfile)
618 while line[:7] == " Vector":
619
620 # Note: the vector count starts from 1 in NWChem.
621 nvector = int(line[7:12])
622 nvectors.append(nvector)
623
624 # A nonzero occupancy for SCF jobs means the orbital is occupied.
625 mooccno = int(self.float(line[18:30]))
626 mooccnos.append(mooccno)
627
628 # If the printout does not start from the first MO, assume None for all previous orbitals.
629 if len(energies) == 0 and nvector > 1:
630 for i in range(1, nvector):
631 energies.append(None)
632
633 energy = self.float(line[34:47])
634 energy = utils.convertor(energy, "hartree", "eV")
635 energies.append(energy)
636
637 # When symmetry is not used, this part of the line is missing.
638 if line[47:58].strip() == "Symmetry=":
639 sym = line[58:].strip()
640 sym = sym[0].upper() + sym[1:]
641 symmetries[nvector-1] = sym
642
643 line = next(inputfile)
644 if "MO Center" in line:
645 line = next(inputfile)
646 if "Bfn." in line:
647 line = next(inputfile)
648 if "-----" in line:
649 line = next(inputfile)
650 while line.strip():
651 line = next(inputfile)
652 line = next(inputfile)
653
654 self.set_attribute('nmo', nvector)
655
656 if not hasattr(self, 'moenergies') or (len(self.moenergies) > alphabeta):
657 self.moenergies = []
658 self.moenergies.append(energies)
659
660 if not hasattr(self, 'mosyms') or (len(self.mosyms) > alphabeta):
661 self.mosyms = []
662 self.mosyms.append(symmetries)
663
664 if not hasattr(self, 'homos') or (len(self.homos) > alphabeta):
665 self.homos = []
666 nvector_index = mooccnos.index(0) - 1
667 if nvector_index > -1:
668 self.homos.append(nvectors[nvector_index] - 1)
669 else:
670 self.homos.append(-1)
671 # If this was a restricted open-shell calculation, append
672 # to HOMOs twice since only one Molecular Orbital Analysis
673 # section is in the output file.
674 if (not unrestricted) and (1 in mooccnos):
675 nvector_index = mooccnos.index(1) - 1
676 if nvector_index > -1:
677 self.homos.append(nvectors[nvector_index] - 1)
678 else:
679 self.homos.append(-1)
680
681 # This is where the full MO vectors are printed, but a special
682 # directive is needed for it in the `scf` or `dft` block:
683 # print "final vectors" "final vectors analysis"
684 # which gives:
685 #
686 # Final MO vectors
687 # ----------------
688 #
689 #
690 # global array: alpha evecs[1:60,1:60], handle: -995
691 #
692 # 1 2 3 4 5 6
693 # ----------- ----------- ----------- ----------- ----------- -----------
694 # 1 -0.69930 -0.69930 -0.02746 -0.02769 -0.00313 -0.02871
695 # 2 -0.03156 -0.03135 0.00410 0.00406 0.00078 0.00816
696 # 3 0.00002 -0.00003 0.00067 0.00065 -0.00526 -0.00120
697 # ...
698 #
699 if line.strip() == "Final MO vectors":
700
701 if not hasattr(self, 'mocoeffs'):
702 self.mocoeffs = []
703
704 self.skip_lines(inputfile, ['d', 'b', 'b'])
705
706 # The columns are MOs, rows AOs, but that's and educated guess since no
707 # atom information is printed alongside the indices. This next line gives
708 # the dimensions, which we can check. if set before this. Also, this line
709 # specifies whether we are dealing with alpha or beta vectors.
710 array_info = next(inputfile)
711 while ("global array" in array_info):
712 alphabeta = int(line.split()[2] == "beta")
713 size = array_info.split('[')[1].split(']')[0]
714 nbasis = int(size.split(',')[0].split(':')[1])
715 nmo = int(size.split(',')[1].split(':')[1])
716 self.set_attribute('nbasis', nbasis)
717 self.set_attribute('nmo', nmo)
718
719 self.skip_line(inputfile, 'blank')
720 mocoeffs = []
721 while len(mocoeffs) < self.nmo:
722 nmos = list(map(int, next(inputfile).split()))
723 assert len(mocoeffs) == nmos[0] - 1
724 for n in nmos:
725 mocoeffs.append([])
726 self.skip_line(inputfile, 'dashes')
727 for nb in range(nbasis):
728 line = next(inputfile)
729 index = int(line.split()[0])
730 assert index == nb+1
731 coefficients = list(map(float, line.split()[1:]))
732 assert len(coefficients) == len(nmos)
733 for i, c in enumerate(coefficients):
734 mocoeffs[nmos[i]-1].append(c)
735 self.skip_line(inputfile, 'blank')
736 self.mocoeffs.append(mocoeffs)
737
738 array_info = next(inputfile)
739
740 # For Hartree-Fock, the atomic Mulliken charges are typically printed like this:
741 #
742 # Mulliken analysis of the total density
743 # --------------------------------------
744 #
745 # Atom Charge Shell Charges
746 # ----------- ------ -------------------------------------------------------
747 # 1 C 6 6.00 1.99 1.14 2.87
748 # 2 C 6 6.00 1.99 1.14 2.87
749 # ...
750 if line.strip() == "Mulliken analysis of the total density":
751
752 if not hasattr(self, "atomcharges"):
753 self.atomcharges = {}
754
755 self.skip_lines(inputfile, ['d', 'b', 'header', 'd'])
756
757 charges = []
758 line = next(inputfile)
759 while line.strip():
760 index, atomname, nuclear, atom = line.split()[:4]
761 shells = line.split()[4:]
762 charges.append(float(atom)-float(nuclear))
763 line = next(inputfile)
764 self.atomcharges['mulliken'] = charges
765
766 # Not the the 'overlap population' as printed in the Mulliken population analysis,
767 # is not the same thing as the 'overlap matrix'. In fact, it is the overlap matrix
768 # multiplied elementwise times the density matrix.
769 #
770 # ----------------------------
771 # Mulliken population analysis
772 # ----------------------------
773 #
774 # ----- Total overlap population -----
775 #
776 # 1 2 3 4 5 6 7
777 #
778 # 1 1 C s 2.0694818227 -0.0535883400 -0.0000000000 -0.0000000000 -0.0000000000 -0.0000000000 0.0000039991
779 # 2 1 C s -0.0535883400 0.8281341291 0.0000000000 -0.0000000000 0.0000000000 0.0000039991 -0.0009906747
780 # ...
781 #
782 # DFT does not seem to print the separate listing of Mulliken charges
783 # by default, but they are printed by this modules later on. They are also print
784 # for Hartree-Fock runs, though, so in that case make sure they are consistent.
785 if line.strip() == "Mulliken population analysis":
786
787 self.skip_lines(inputfile, ['d', 'b', 'total_overlap_population', 'b'])
788
789 overlaps = []
790 line = next(inputfile)
791 while all([c.isdigit() for c in line.split()]):
792
793 # There is always a line with the MO indices printed in thie block.
794 indices = [int(i)-1 for i in line.split()]
795 for i in indices:
796 overlaps.append([])
797
798 # There is usually a blank line after the MO indices, but
799 # there are exceptions, so check if line is blank first.
800 line = next(inputfile)
801 if not line.strip():
802 line = next(inputfile)
803
804 # Now we can iterate or atomic orbitals.
805 for nao in range(self.nbasis):
806 data = list(map(float, line.split()[4:]))
807 for i, d in enumerate(data):
808 overlaps[indices[i]].append(d)
809 line = next(inputfile)
810
811 line = next(inputfile)
812
813 # This header should be printed later, before the charges are print, which of course
814 # are just sums of the overlaps and could be calculated. But we just go ahead and
815 # parse them, make sure they're consistent with previously parsed values and
816 # use these since they are more precise (previous precision could have been just 0.01).
817 while "Total gross population on atoms" not in line:
818 line = next(inputfile)
819 self.skip_line(inputfile, 'blank')
820 charges = []
821 for i in range(self.natom):
822 line = next(inputfile)
823 iatom, element, ncharge, epop = line.split()
824 iatom = int(iatom)
825 ncharge = float(ncharge)
826 epop = float(epop)
827 assert iatom == (i+1)
828 charges.append(epop-ncharge)
829
830 if not hasattr(self, 'atomcharges'):
831 self.atomcharges = {}
832 if not "mulliken" in self.atomcharges:
833 self.atomcharges['mulliken'] = charges
834 else:
835 assert max(self.atomcharges['mulliken'] - numpy.array(charges)) < 0.01
836 self.atomcharges['mulliken'] = charges
837
838 # NWChem prints the dipole moment in atomic units first, and we could just fast forward
839 # to the values in Debye, which are also printed. But we can also just convert them
840 # right away and so parse a little bit less. Note how the reference point is print
841 # here within the block nicely, as it is for all moment later.
842 #
843 # -------------
844 # Dipole Moment
845 # -------------
846 #
847 # Center of charge (in au) is the expansion point
848 # X = 0.0000000 Y = 0.0000000 Z = 0.0000000
849 #
850 # Dipole moment 0.0000000000 Debye(s)
851 # DMX 0.0000000000 DMXEFC 0.0000000000
852 # DMY 0.0000000000 DMYEFC 0.0000000000
853 # DMZ -0.0000000000 DMZEFC 0.0000000000
854 #
855 # ...
856 #
857 if line.strip() == "Dipole Moment":
858
859 self.skip_lines(inputfile, ['d', 'b'])
860
861 reference_comment = next(inputfile)
862 assert "(in au)" in reference_comment
863 reference = next(inputfile).split()
864 self.reference = [reference[-7], reference[-4], reference[-1]]
865 self.reference = numpy.array([float(x) for x in self.reference])
866 self.reference = utils.convertor(self.reference, 'bohr', 'Angstrom')
867
868 self.skip_line(inputfile, 'blank')
869
870 magnitude = next(inputfile)
871 assert magnitude.split()[-1] == "A.U."
872
873 dipole = []
874 for i in range(3):
875 line = next(inputfile)
876 dipole.append(float(line.split()[1]))
877
878 dipole = utils.convertor(numpy.array(dipole), "ebohr", "Debye")
879
880 if not hasattr(self, 'moments'):
881 self.moments = [self.reference, dipole]
882 else:
883 self.moments[1] == dipole
884
885 # The quadrupole moment is pretty straightforward to parse. There are several
886 # blocks printed, and the first one called 'second moments' contains the raw
887 # moments, and later traceless values are printed. The moments, however, are
888 # not in lexicographical order, so we need to sort them. Also, the first block
889 # is in atomic units, so remember to convert to Buckinghams along the way.
890 #
891 # -----------------
892 # Quadrupole Moment
893 # -----------------
894 #
895 # Center of charge (in au) is the expansion point
896 # X = 0.0000000 Y = 0.0000000 Z = 0.0000000
897 #
898 # < R**2 > = ********** a.u. ( 1 a.u. = 0.280023 10**(-16) cm**2 )
899 # ( also called diamagnetic susceptibility )
900 #
901 # Second moments in atomic units
902 #
903 # Component Electronic+nuclear Point charges Total
904 # --------------------------------------------------------------------------
905 # XX -38.3608511210 0.0000000000 -38.3608511210
906 # YY -39.0055467347 0.0000000000 -39.0055467347
907 # ...
908 #
909 if line.strip() == "Quadrupole Moment":
910
911 self.skip_lines(inputfile, ['d', 'b'])
912
913 reference_comment = next(inputfile)
914 assert "(in au)" in reference_comment
915 reference = next(inputfile).split()
916 self.reference = [reference[-7], reference[-4], reference[-1]]
917 self.reference = numpy.array([float(x) for x in self.reference])
918 self.reference = utils.convertor(self.reference, 'bohr', 'Angstrom')
919
920 self.skip_lines(inputfile, ['b', 'units', 'susc', 'b'])
921
922 line = next(inputfile)
923 assert line.strip() == "Second moments in atomic units"
924
925 self.skip_lines(inputfile, ['b', 'header', 'd'])
926
927 # Parse into a dictionary and then sort by the component key.
928 quadrupole = {}
929 for i in range(6):
930 line = next(inputfile)
931 quadrupole[line.split()[0]] = float(line.split()[-1])
932 lex = sorted(quadrupole.keys())
933 quadrupole = [quadrupole[key] for key in lex]
934
935 quadrupole = utils.convertor(numpy.array(quadrupole), "ebohr2", "Buckingham")
936
937 # The checking of potential previous values if a bit more involved here,
938 # because it turns out NWChem has separate keywords for dipole, quadrupole
939 # and octupole output. So, it is perfectly possible to print the quadrupole
940 # and not the dipole... if that is the case set the former to None and
941 # issue a warning. Also, a regression has been added to cover this case.
942 if not hasattr(self, 'moments') or len(self.moments) < 2:
943 self.logger.warning("Found quadrupole moments but no previous dipole")
944 self.moments = [self.reference, None, quadrupole]
945 else:
946 if len(self.moments) == 2:
947 self.moments.append(quadrupole)
948 else:
949 assert self.moments[2] == quadrupole
950
951 # The octupole moment is analogous to the quadrupole, but there are more components
952 # and the checking of previously parsed dipole and quadrupole moments is more involved,
953 # with a corresponding test also added to regressions.
954 #
955 # ---------------
956 # Octupole Moment
957 # ---------------
958 #
959 # Center of charge (in au) is the expansion point
960 # X = 0.0000000 Y = 0.0000000 Z = 0.0000000
961 #
962 # Third moments in atomic units
963 #
964 # Component Electronic+nuclear Point charges Total
965 # --------------------------------------------------------------------------
966 # XXX -0.0000000000 0.0000000000 -0.0000000000
967 # YYY -0.0000000000 0.0000000000 -0.0000000000
968 # ...
969 #
970 if line.strip() == "Octupole Moment":
971
972 self.skip_lines(inputfile, ['d', 'b'])
973
974 reference_comment = next(inputfile)
975 assert "(in au)" in reference_comment
976 reference = next(inputfile).split()
977 self.reference = [reference[-7], reference[-4], reference[-1]]
978 self.reference = numpy.array([float(x) for x in self.reference])
979 self.reference = utils.convertor(self.reference, 'bohr', 'Angstrom')
980
981 self.skip_line(inputfile, 'blank')
982
983 line = next(inputfile)
984 assert line.strip() == "Third moments in atomic units"
985
986 self.skip_lines(inputfile, ['b', 'header', 'd'])
987
988 octupole = {}
989 for i in range(10):
990 line = next(inputfile)
991 octupole[line.split()[0]] = float(line.split()[-1])
992 lex = sorted(octupole.keys())
993 octupole = [octupole[key] for key in lex]
994
995 octupole = utils.convertor(numpy.array(octupole), "ebohr3", "Debye.ang2")
996
997 if not hasattr(self, 'moments') or len(self.moments) < 2:
998 self.logger.warning("Found octupole moments but no previous dipole or quadrupole moments")
999 self.moments = [self.reference, None, None, octupole]
1000 elif len(self.moments) == 2:
1001 self.logger.warning("Found octupole moments but no previous quadrupole moments")
1002 self.moments.append(None)
1003 self.moments.append(octupole)
1004 else:
1005 if len(self.moments) == 3:
1006 self.moments.append(octupole)
1007 else:
1008 assert self.moments[3] == octupole
1009
1010 if "Total MP2 energy" in line:
1011 self.metadata["methods"].append("MP2")
1012 mpenerg = float(line.split()[-1])
1013 if not hasattr(self, "mpenergies"):
1014 self.mpenergies = []
1015 self.mpenergies.append([])
1016 self.mpenergies[-1].append(utils.convertor(mpenerg, "hartree", "eV"))
1017
1018 if "CCSD total energy / hartree" in line or "total CCSD energy:" in line:
1019 self.metadata["methods"].append("CCSD")
1020 ccenerg = float(line.split()[-1])
1021 if not hasattr(self, "ccenergies"):
1022 self.ccenergies = []
1023 self.ccenergies.append([])
1024 self.ccenergies[-1].append(utils.convertor(ccenerg, "hartree", "eV"))
1025
1026 if "CCSD(T) total energy / hartree" in line:
1027 self.metadata["methods"].append("CCSD(T)")
1028 ccenerg = float(line.split()[-1])
1029 if not hasattr(self, "ccenergies"):
1030 self.ccenergies = []
1031 self.ccenergies.append([])
1032 self.ccenergies[-1].append(utils.convertor(ccenerg, "hartree", "eV"))
1033
1034 # Static and dynamic polarizability.
1035 if "Linear Response polarizability / au" in line:
1036 if not hasattr(self, "polarizabilities"):
1037 self.polarizabilities = []
1038 polarizability = []
1039 line = next(inputfile)
1040 assert line.split()[0] == "Frequency"
1041 line = next(inputfile)
1042 assert line.split()[0] == "Wavelength"
1043 self.skip_lines(inputfile, ['coordinates', 'd'])
1044 for _ in range(3):
1045 line = next(inputfile)
1046 polarizability.append(line.split()[1:])
1047 self.polarizabilities.append(numpy.array(polarizability))
1048
1049 if line[:18] == ' Total times cpu:':
1050 self.metadata['success'] = True
1051
1052 if line.strip() == "NWChem QMD Module":
1053 self.is_BOMD = True
1054
1055 # Born-Oppenheimer molecular dynamics (BOMD): time.
1056 if "QMD Run Information" in line:
1057 self.skip_line(inputfile, 'd')
1058 line = next(inputfile)
1059 assert "Time elapsed (fs)" in line
1060 time = float(line.split()[4])
1061 self.append_attribute('time', time)
1062
1063 # BOMD: geometry coordinates when `print low`.
1064 if line.strip() == "DFT ENERGY GRADIENTS":
1065 if self.is_BOMD:
1066 self.skip_lines(inputfile, ['b', 'atom coordinates gradient', 'xyzxyz'])
1067 line = next(inputfile)
1068 atomcoords_step = []
1069 while line.strip():
1070 tokens = line.split()
1071 assert len(tokens) == 8
1072 atomcoords_step.append([float(c) for c in tokens[2:5]])
1073 line = next(inputfile)
1074 self.atomcoords.append(atomcoords_step)
1075
1076 def before_parsing(self):
1077 """NWChem-specific routines performed before parsing a file.
1078 """
1079
1080 # The only reason we need this identifier is if `print low` is
1081 # set in the input file, which we assume is likely for a BOMD
1082 # trajectory. This will enable parsing coordinates from the
1083 # 'DFT ENERGY GRADIENTS' section.
1084 self.is_BOMD = False
1085
1086 def after_parsing(self):
1087 """NWChem-specific routines for after parsing a file.
1088
1089 Currently, expands self.shells() into self.aonames.
1090 """
1091
1092 # setup a few necessary things, including a regular expression
1093 # for matching the shells
1094 table = utils.PeriodicTable()
1095 elements = [table.element[x] for x in self.atomnos]
1096 pattern = re.compile("(\ds)+(\dp)*(\dd)*(\df)*(\dg)*")
1097
1098 labels = {}
1099 labels['s'] = ["%iS"]
1100 labels['p'] = ["%iPX", "%iPY", "%iPZ"]
1101 if self.shells['type'] == 'spherical':
1102 labels['d'] = ['%iD-2', '%iD-1', '%iD0', '%iD1', '%iD2']
1103 labels['f'] = ['%iF-3', '%iF-2', '%iF-1', '%iF0',
1104 '%iF1', '%iF2', '%iF3']
1105 labels['g'] = ['%iG-4', '%iG-3', '%iG-2', '%iG-1', '%iG0',
1106 '%iG1', '%iG2', '%iG3', '%iG4']
1107 elif self.shells['type'] == 'cartesian':
1108 labels['d'] = ['%iDXX', '%iDXY', '%iDXZ',
1109 '%iDYY', '%iDYZ',
1110 '%iDZZ']
1111 labels['f'] = ['%iFXXX', '%iFXXY', '%iFXXZ',
1112 '%iFXYY', '%iFXYZ', '%iFXZZ',
1113 '%iFYYY', '%iFYYZ', '%iFYZZ',
1114 '%iFZZZ']
1115 labels['g'] = ['%iGXXXX', '%iGXXXY', '%iGXXXZ',
1116 '%iGXXYY', '%iGXXYZ', '%iGXXZZ',
1117 '%iGXYYY', '%iGXYYZ', '%iGXYZZ',
1118 '%iGXZZZ', '%iGYYYY', '%iGYYYZ',
1119 '%iGYYZZ', '%iGYZZZ', '%iGZZZZ']
1120 else:
1121 self.logger.warning("Found a non-standard aoname representation type.")
1122 return
1123
1124 # now actually build aonames
1125 # involves expanding 2s1p into appropriate types
1126
1127 self.aonames = []
1128 for i, element in enumerate(elements):
1129 try:
1130 shell_text = self.shells[element]
1131 except KeyError:
1132 del self.aonames
1133 msg = "Cannot determine aonames for at least one atom."
1134 self.logger.warning(msg)
1135 break
1136
1137 prefix = "%s%i_" % (element, i + 1) # (e.g. C1_)
1138
1139 matches = pattern.match(shell_text)
1140 for j, group in enumerate(matches.groups()):
1141 if group is None:
1142 continue
1143
1144 count = int(group[:-1])
1145 label = group[-1]
1146
1147 for k in range(count):
1148 temp = [x % (j + k + 1) for x in labels[label]]
1149 self.aonames.extend([prefix + x for x in temp])
1150
1151 # If we parsed a BOMD trajectory, the first two parsed
1152 # geometries are identical, and all from the second onward are
1153 # in Bohr. Delete the first one and perform the unit
1154 # conversion.
1155 if self.is_BOMD:
1156 self.atomcoords = utils.convertor(numpy.asarray(self.atomcoords)[1:, ...],
1157 'bohr', 'Angstrom')