Debian Codegraph @

cclib/parser/psi4parser.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 Psi4 output files."""
9
10 from collections import namedtuple
11
12 import numpy
13
14 from cclib.parser import data
15 from cclib.parser import logfileparser
16 from cclib.parser import utils
17
18
19 class Psi4(logfileparser.Logfile):
20 """A Psi4 log file."""
21
22 def __init__(self, *args, **kwargs):
23
24 # Call the __init__ method of the superclass
25 super(Psi4, self).__init__(logname="Psi4", *args, **kwargs)
26
27 def __str__(self):
28 """Return a string representation of the object."""
29 return "Psi4 log file %s" % (self.filename)
30
31 def __repr__(self):
32 """Return a representation of the object."""
33 return 'Psi4("%s")' % (self.filename)
34
35 def before_parsing(self):
36
37 # Early beta versions of Psi4 normalize basis function
38 # coefficients when printing.
39 self.version_4_beta = False
40
41 # This is just used to track which part of the output we are in for Psi4,
42 # with changes triggered by ==> things like this <== (Psi3 does not have this)
43 self.section = None
44
45 def after_parsing(self):
46
47 # Newer versions of Psi4 don't explicitly print the number of atoms.
48 if not hasattr(self, 'natom'):
49 if hasattr(self, 'atomnos'):
50 self.set_attribute('natom', len(self.atomnos))
51
52 def normalisesym(self, label):
53 """Psi4 does not require normalizing symmetry labels."""
54 return label
55
56 # Match the number of skipped lines required based on the type of
57 # gradient present (determined from the header), as otherwise the
58 # parsing is identical.
59 GradientInfo = namedtuple('GradientInfo', ['gradient_type', 'header', 'skip_lines'])
60 GRADIENT_TYPES = {
61 'analytic': GradientInfo('analytic',
62 '-Total Gradient:',
63 ['header', 'dash header']),
64 'numerical': GradientInfo('numerical',
65 '## F-D gradient (Symmetry 0) ##',
66 ['Irrep num and total size', 'b', '123', 'b']),
67 }
68 GRADIENT_HEADERS = set([gradient_type.header
69 for gradient_type in GRADIENT_TYPES.values()])
70
71 def extract(self, inputfile, line):
72 """Extract information from the file object inputfile."""
73
74 # Extract the version number and the version control
75 # information, if it exists.
76 if "Driver" in line:
77 tokens = line.split()
78 package_version = tokens[1].split("-")[-1]
79 self.metadata["package_version"] = package_version
80 # Keep track of early versions of Psi4.
81 if "beta" in package_version:
82 self.version_4_beta = True
83 # Don't add revision information to the main package version for now.
84 if "Git:" in line:
85 tokens = line.split()
86 revision = '-'.join(tokens[2:])
87
88 # This will automatically change the section attribute for Psi4, when encountering
89 # a line that <== looks like this ==>, to whatever is in between.
90 if (line.strip()[:3] == "==>") and (line.strip()[-3:] == "<=="):
91 self.section = line.strip()[4:-4]
92 if self.section == "DFT Potential":
93 self.metadata["methods"].append("DFT")
94
95 # Determine whether or not the reference wavefunction is
96 # restricted, unrestricted, or restricted open-shell.
97 if line.strip() == "SCF":
98 self.skip_line(inputfile, 'author list')
99 line = next(inputfile)
100 self.reference = line.split()[0]
101 # Work with a complex reference as if it's real.
102 if self.reference[0] == 'C':
103 self.reference = self.reference[1:]
104
105 # Parse the XC density functional
106 # => Composite Functional: B3LYP <=
107 if self.section == "DFT Potential" and "composite functional" in line.lower():
108 chomp = line.split()
109 functional = chomp[-2]
110 self.metadata["functional"] = functional
111
112 # ==> Geometry <==
113 #
114 # Molecular point group: c2h
115 # Full point group: C2h
116 #
117 # Geometry (in Angstrom), charge = 0, multiplicity = 1:
118 #
119 # Center X Y Z
120 # ------------ ----------------- ----------------- -----------------
121 # C -1.415253322400 0.230221785400 0.000000000000
122 # C 1.415253322400 -0.230221785400 0.000000000000
123 # ...
124 #
125 if (self.section == "Geometry") and ("Geometry (in Angstrom), charge" in line):
126
127 assert line.split()[3] == "charge"
128 charge = int(line.split()[5].strip(','))
129 self.set_attribute('charge', charge)
130
131 assert line.split()[6] == "multiplicity"
132 mult = int(line.split()[8].strip(':'))
133 self.set_attribute('mult', mult)
134
135 self.skip_line(inputfile, "blank")
136 line = next(inputfile)
137
138 # Usually there is the header and dashes, but, for example, the coordinates
139 # printed when a geometry optimization finishes do not have it.
140 if line.split()[0] == "Center":
141 self.skip_line(inputfile, "dashes")
142 line = next(inputfile)
143
144 elements = []
145 coords = []
146 atommasses = []
147 while line.strip():
148 chomp = line.split()
149 el, x, y, z = chomp[:4]
150 if len(el) > 1:
151 el = el[0] + el[1:].lower()
152 elements.append(el)
153 coords.append([float(x), float(y), float(z)])
154 # Newer versions of Psi4 print atomic masses.
155 if len(chomp) == 5:
156 atommasses.append(float(chomp[4]))
157 line = next(inputfile)
158
159 # The 0 is to handle the presence of ghost atoms.
160 self.set_attribute('atomnos', [self.table.number.get(el, 0) for el in elements])
161
162 if not hasattr(self, 'atomcoords'):
163 self.atomcoords = []
164
165 # This condition discards any repeated coordinates that Psi print. For example,
166 # geometry optimizations will print the coordinates at the beginning of and SCF
167 # section and also at the start of the gradient calculation.
168 if len(self.atomcoords) == 0 \
169 or (self.atomcoords[-1] != coords and not hasattr(self, 'finite_difference')):
170 self.atomcoords.append(coords)
171
172 if len(atommasses) > 0:
173 if not hasattr(self, 'atommasses'):
174 self.atommasses = atommasses
175
176 # Psi4 repeats the charge and multiplicity after the geometry.
177 if (self.section == "Geometry") and (line[2:16].lower() == "charge ="):
178 charge = int(line.split()[-1])
179 self.set_attribute('charge', charge)
180 if (self.section == "Geometry") and (line[2:16].lower() == "multiplicity ="):
181 mult = int(line.split()[-1])
182 self.set_attribute('mult', mult)
183
184 # The printout for Psi4 has a more obvious trigger for the SCF parameter printout.
185 if (self.section == "Algorithm") and (line.strip() == "==> Algorithm <==") \
186 and not hasattr(self, 'finite_difference'):
187
188 self.skip_line(inputfile, 'blank')
189
190 line = next(inputfile)
191 while line.strip():
192 if "Energy threshold" in line:
193 etarget = float(line.split()[-1])
194 if "Density threshold" in line:
195 dtarget = float(line.split()[-1])
196 line = next(inputfile)
197
198 if not hasattr(self, "scftargets"):
199 self.scftargets = []
200 self.scftargets.append([etarget, dtarget])
201
202 # This section prints contraction information before the atomic basis set functions and
203 # is a good place to parse atombasis indices as well as atomnos. However, the section this line
204 # is in differs between HF and DFT outputs.
205 #
206 # -Contraction Scheme:
207 # Atom Type All Primitives // Shells:
208 # ------ ------ --------------------------
209 # 1 C 6s 3p // 2s 1p
210 # 2 C 6s 3p // 2s 1p
211 # 3 C 6s 3p // 2s 1p
212 # ...
213 if self.section == "Primary Basis":
214 if line[2:12] == "Basis Set:":
215 self.metadata["basis_set"] = line.split()[2]
216
217 if (self.section == "Primary Basis" or self.section == "DFT Potential") and line.strip() == "-Contraction Scheme:":
218
219 self.skip_lines(inputfile, ['headers', 'd'])
220
221 atomnos = []
222 atombasis = []
223 atombasis_pos = 0
224 line = next(inputfile)
225 while line.strip():
226
227 element = line.split()[1]
228 if len(element) > 1:
229 element = element[0] + element[1:].lower()
230 atomnos.append(self.table.number[element])
231
232 # To count the number of atomic orbitals for the atom, sum up the orbitals
233 # in each type of shell, times the numbers of shells. Currently, we assume
234 # the multiplier is a single digit and that there are only s and p shells,
235 # which will need to be extended later when considering larger basis sets,
236 # with corrections for the cartesian/spherical cases.
237 ao_count = 0
238 shells = line.split('//')[1].split()
239 for s in shells:
240 count, type = s
241 multiplier = 3*(type == 'p') or 1
242 ao_count += multiplier*int(count)
243
244 if len(atombasis) > 0:
245 atombasis_pos = atombasis[-1][-1] + 1
246 atombasis.append(list(range(atombasis_pos, atombasis_pos+ao_count)))
247
248 line = next(inputfile)
249
250 self.set_attribute('natom', len(atomnos))
251 self.set_attribute('atomnos', atomnos)
252 self.set_attribute('atombasis', atombasis)
253
254 # The atomic basis set is straightforward to parse, but there are some complications
255 # when symmetry is used, because in that case Psi4 only print the symmetry-unique atoms,
256 # and the list of symmetry-equivalent ones is not printed. Therefore, for simplicity here
257 # when an atomic is missing (atom indices are printed) assume the atomic orbitals of the
258 # last atom of the same element before it. This might not work if a mixture of basis sets
259 # is used somehow... but it should cover almost all cases for now.
260 #
261 # Note that Psi also print normalized coefficients (details below).
262 #
263 # ==> AO Basis Functions <==
264 #
265 # [ STO-3G ]
266 # spherical
267 # ****
268 # C 1
269 # S 3 1.00
270 # 71.61683700 2.70781445
271 # 13.04509600 2.61888016
272 # ...
273 if (self.section == "AO Basis Functions") and (line.strip() == "==> AO Basis Functions <=="):
274
275 def get_symmetry_atom_basis(gbasis):
276 """Get symmetry atom by replicating the last atom in gbasis of the same element."""
277
278 missing_index = len(gbasis)
279 missing_atomno = self.atomnos[missing_index]
280
281 ngbasis = len(gbasis)
282 last_same = ngbasis - self.atomnos[:ngbasis][::-1].index(missing_atomno) - 1
283 return gbasis[last_same]
284
285 dfact = lambda n: (n <= 0) or n * dfact(n-2)
286
287 # Early beta versions of Psi4 normalize basis function
288 # coefficients when printing.
289 if self.version_4_beta:
290 def get_normalization_factor(exp, lx, ly, lz):
291 norm_s = (2*exp/numpy.pi)**0.75
292 if lx + ly + lz > 0:
293 nom = (4*exp)**((lx+ly+lz)/2.0)
294 den = numpy.sqrt(dfact(2*lx-1) * dfact(2*ly-1) * dfact(2*lz-1))
295 return norm_s * nom / den
296 else:
297 return norm_s
298 else:
299 get_normalization_factor = lambda exp, lx, ly, lz: 1
300
301 self.skip_lines(inputfile, ['b', 'basisname'])
302
303 line = next(inputfile)
304 spherical = line.strip() == "spherical"
305 if hasattr(self, 'spherical_basis'):
306 assert self.spherical_basis == spherical
307 else:
308 self.spherical_basis = spherical
309
310 gbasis = []
311 self.skip_line(inputfile, 'stars')
312 line = next(inputfile)
313 while line.strip():
314
315 element, index = line.split()
316 if len(element) > 1:
317 element = element[0] + element[1:].lower()
318 index = int(index)
319
320 # This is the code that adds missing atoms when symmetry atoms are excluded
321 # from the basis set printout. Again, this will work only if all atoms of
322 # the same element use the same basis set.
323 while index > len(gbasis) + 1:
324 gbasis.append(get_symmetry_atom_basis(gbasis))
325
326 gbasis.append([])
327 line = next(inputfile)
328 while line.find("*") == -1:
329
330 # The shell type and primitive count is in the first line.
331 shell_type, nprimitives, _ = line.split()
332 nprimitives = int(nprimitives)
333
334 # Get the angular momentum for this shell type.
335 momentum = {'S': 0, 'P': 1, 'D': 2, 'F': 3, 'G': 4, 'H': 5, 'I': 6}[shell_type.upper()]
336
337 # Read in the primitives.
338 primitives_lines = [next(inputfile) for i in range(nprimitives)]
339 primitives = [list(map(float, pl.split())) for pl in primitives_lines]
340
341 # Un-normalize the coefficients. Psi prints the normalized coefficient
342 # of the highest polynomial, namely XX for D orbitals, XXX for F, and so on.
343 for iprim, prim in enumerate(primitives):
344 exp, coef = prim
345 coef = coef / get_normalization_factor(exp, momentum, 0, 0)
346 primitives[iprim] = [exp, coef]
347
348 primitives = [tuple(p) for p in primitives]
349 shell = [shell_type, primitives]
350 gbasis[-1].append(shell)
351
352 line = next(inputfile)
353
354 line = next(inputfile)
355
356 # We will also need to add symmetry atoms that are missing from the input
357 # at the end of this block, if the symmetry atoms are last.
358 while len(gbasis) < self.natom:
359 gbasis.append(get_symmetry_atom_basis(gbasis))
360
361 self.gbasis = gbasis
362
363 # A block called 'Calculation Information' prints these before starting the SCF.
364 if (self.section == "Pre-Iterations") and ("Number of atoms" in line):
365 natom = int(line.split()[-1])
366 self.set_attribute('natom', natom)
367 if (self.section == "Pre-Iterations") and ("Number of atomic orbitals" in line):
368 nbasis = int(line.split()[-1])
369 self.set_attribute('nbasis', nbasis)
370 if (self.section == "Pre-Iterations") and ("Total" in line):
371 chomp = line.split()
372 nbasis = int(chomp[1])
373 self.set_attribute('nbasis', nbasis)
374
375 # ==> Iterations <==
376
377 # Psi4 converges both the SCF energy and density elements and reports both in the
378 # iterations printout. However, the default convergence scheme involves a density-fitted
379 # algorithm for efficiency, and this is often followed by a something with exact electron
380 # repulsion integrals. In that case, there are actually two convergence cycles performed,
381 # one for the density-fitted algorithm and one for the exact one, and the iterations are
382 # printed in two blocks separated by some set-up information.
383 if (self.section == "Iterations") and (line.strip() == "==> Iterations <==") \
384 and not hasattr(self, 'finite_difference'):
385
386 if not hasattr(self, 'scfvalues'):
387 self.scfvalues = []
388 scfvals = []
389
390 self.skip_lines(inputfile, ['b', 'header', 'b'])
391 line = next(inputfile)
392 # Read each SCF iteration.
393 while line.strip() != "==> Post-Iterations <==":
394 if line.strip() and line.split()[0][0] == '@':
395 denergy = float(line.split()[4])
396 ddensity = float(line.split()[5])
397 scfvals.append([denergy, ddensity])
398 try:
399 line = next(inputfile)
400 except StopIteration:
401 self.logger.warning('File terminated before end of last SCF! Last density err: {}'.format(ddensity))
402 break
403 self.section = "Post-Iterations"
404 self.scfvalues.append(scfvals)
405
406 # This section, from which we parse molecular orbital symmetries and
407 # orbital energies, is quite similar for both Psi3 and Psi4, and in fact
408 # the format for orbtials is the same, although the headers and spacers
409 # are a bit different. Let's try to get both parsed with one code block.
410 #
411 # Here is how the block looks like for Psi4:
412 #
413 # Orbital Energies (a.u.)
414 # -----------------------
415 #
416 # Doubly Occupied:
417 #
418 # 1Bu -11.040586 1Ag -11.040524 2Bu -11.031589
419 # 2Ag -11.031589 3Bu -11.028950 3Ag -11.028820
420 # (...)
421 # 15Ag -0.415620 1Bg -0.376962 2Au -0.315126
422 # 2Bg -0.278361 3Bg -0.222189
423 #
424 # Virtual:
425 #
426 # 3Au 0.198995 4Au 0.268517 4Bg 0.308826
427 # 5Au 0.397078 5Bg 0.521759 16Ag 0.565017
428 # (...)
429 # 24Ag 0.990287 24Bu 1.027266 25Ag 1.107702
430 # 25Bu 1.124938
431 #
432 # The case is different in the trigger string.
433 if ("orbital energies (a.u.)" in line.lower() or "orbital energies [eh]" in line.lower()) \
434 and not hasattr(self, 'finite_difference'):
435
436 # If this is Psi4, we will be in the appropriate section.
437 assert self.section == "Post-Iterations"
438
439 self.moenergies = [[]]
440 self.mosyms = [[]]
441
442 # Psi4 has dashes under the trigger line, but Psi3 did not.
443 self.skip_line(inputfile, 'dashes')
444 self.skip_line(inputfile, 'blank')
445
446 # Both versions have this case-insensitive substring.
447 occupied = next(inputfile)
448 if self.reference[0:2] == 'RO' or self.reference[0:1] == 'R':
449 assert 'doubly occupied' in occupied.lower()
450 elif self.reference[0:1] == 'U':
451 assert 'alpha occupied' in occupied.lower()
452
453 self.skip_line(inputfile, 'blank')
454
455 # Parse the occupied MO symmetries and energies.
456 self._parse_mosyms_moenergies(inputfile, 0)
457
458 # The last orbital energy here represents the HOMO.
459 self.homos = [len(self.moenergies[0])-1]
460 # For a restricted open-shell calculation, this is the
461 # beta HOMO, and we assume the singly-occupied orbitals
462 # are all alpha, which are handled next.
463 if self.reference[0:2] == 'RO':
464 self.homos.append(self.homos[0])
465
466 unoccupied = next(inputfile)
467 if self.reference[0:2] == 'RO':
468 assert unoccupied.strip() == 'Singly Occupied:'
469 elif self.reference[0:1] == 'R':
470 assert unoccupied.strip() == 'Virtual:'
471 elif self.reference[0:1] == 'U':
472 assert unoccupied.strip() == 'Alpha Virtual:'
473
474 # Psi4 now has a blank line, Psi3 does not.
475 self.skip_line(inputfile, 'blank')
476
477 # Parse the unoccupied MO symmetries and energies.
478 self._parse_mosyms_moenergies(inputfile, 0)
479
480 # Here is where we handle the Beta or Singly occupied orbitals.
481 if self.reference[0:1] == 'U':
482 self.mosyms.append([])
483 self.moenergies.append([])
484 line = next(inputfile)
485 assert line.strip() == 'Beta Occupied:'
486 self.skip_line(inputfile, 'blank')
487 self._parse_mosyms_moenergies(inputfile, 1)
488 self.homos.append(len(self.moenergies[1])-1)
489 line = next(inputfile)
490 assert line.strip() == 'Beta Virtual:'
491 self.skip_line(inputfile, 'blank')
492 self._parse_mosyms_moenergies(inputfile, 1)
493 elif self.reference[0:2] == 'RO':
494 line = next(inputfile)
495 assert line.strip() == 'Virtual:'
496 self.skip_line(inputfile, 'blank')
497 self._parse_mosyms_moenergies(inputfile, 0)
498
499 line = next(inputfile)
500 assert line.strip() == 'Final Occupation by Irrep:'
501 line = next(inputfile)
502 irreps = line.split()
503 line = next(inputfile)
504 tokens = line.split()
505 assert tokens[0] == 'DOCC'
506 docc = sum([int(x.replace(',', '')) for x in tokens[2:-1]])
507 line = next(inputfile)
508 if line.strip():
509 tokens = line.split()
510 assert tokens[0] in ('SOCC', 'NA')
511 socc = sum([int(x.replace(',', '')) for x in tokens[2:-1]])
512 # Fix up the restricted open-shell alpha HOMO.
513 if self.reference[0:2] == 'RO':
514 self.homos[0] += socc
515
516 # Both Psi3 and Psi4 print the final SCF energy right after the orbital energies,
517 # but the label is different. Psi4 also does DFT, and the label is also different in that case.
518 if self.section == "Post-Iterations" and "Final Energy:" in line \
519 and not hasattr(self, 'finite_difference'):
520 e = float(line.split()[3])
521 if not hasattr(self, 'scfenergies'):
522 self.scfenergies = []
523 self.scfenergies.append(utils.convertor(e, 'hartree', 'eV'))
524
525 # ==> Molecular Orbitals <==
526 #
527 # 1 2 3 4 5
528 #
529 # 1 H1 s0 0.1610392 0.1040990 0.0453848 0.0978665 1.0863246
530 # 2 H1 s0 0.3066996 0.0742959 0.8227318 1.3460922 -1.6429494
531 # 3 H1 s0 0.1669296 1.5494169 -0.8885631 -1.8689490 1.0473633
532 # 4 H2 s0 0.1610392 -0.1040990 0.0453848 -0.0978665 -1.0863246
533 # 5 H2 s0 0.3066996 -0.0742959 0.8227318 -1.3460922 1.6429494
534 # 6 H2 s0 0.1669296 -1.5494169 -0.8885631 1.8689490 -1.0473633
535 #
536 # Ene -0.5279195 0.1235556 0.3277474 0.5523654 2.5371710
537 # Sym Ag B3u Ag B3u B3u
538 # Occ 2 0 0 0 0
539 #
540 #
541 # 6
542 #
543 # 1 H1 s0 1.1331221
544 # 2 H1 s0 -1.2163107
545 # 3 H1 s0 0.4695317
546 # 4 H2 s0 1.1331221
547 # 5 H2 s0 -1.2163107
548 # 6 H2 s0 0.4695317
549 #
550 # Ene 2.6515637
551 # Sym Ag
552 # Occ 0
553
554 if (self.section) and ("Molecular Orbitals" in self.section) \
555 and ("Molecular Orbitals" in line) and not hasattr(self, 'finite_difference'):
556
557 self.skip_line(inputfile, 'blank')
558
559 mocoeffs = []
560 indices = next(inputfile)
561 while indices.strip():
562
563 if indices[:3] == '***':
564 break
565
566 indices = [int(i) for i in indices.split()]
567
568 if len(mocoeffs) < indices[-1]:
569 for i in range(len(indices)):
570 mocoeffs.append([])
571 else:
572 assert len(mocoeffs) == indices[-1]
573
574 self.skip_line(inputfile, 'blank')
575
576 n = len(indices)
577 line = next(inputfile)
578 while line.strip():
579 chomp = line.split()
580 m = len(chomp)
581 iao = int(chomp[0])
582 coeffs = [float(c) for c in chomp[m - n:]]
583 for i, c in enumerate(coeffs):
584 mocoeffs[indices[i]-1].append(c)
585 line = next(inputfile)
586
587 energies = next(inputfile)
588 symmetries = next(inputfile)
589 occupancies = next(inputfile)
590
591 self.skip_lines(inputfile, ['b', 'b'])
592 indices = next(inputfile)
593
594 if not hasattr(self, 'mocoeffs'):
595 self.mocoeffs = []
596 self.mocoeffs.append(mocoeffs)
597
598 # The formats for Mulliken and Lowdin atomic charges are the same, just with
599 # the name changes, so use the same code for both.
600 #
601 # Properties computed using the SCF density density matrix
602 # Mulliken Charges: (a.u.)
603 # Center Symbol Alpha Beta Spin Total
604 # 1 C 2.99909 2.99909 0.00000 0.00182
605 # 2 C 2.99909 2.99909 0.00000 0.00182
606 # ...
607 for pop_type in ["Mulliken", "Lowdin"]:
608 if line.strip() == "%s Charges: (a.u.)" % pop_type:
609 if not hasattr(self, 'atomcharges'):
610 self.atomcharges = {}
611 header = next(inputfile)
612
613 line = next(inputfile)
614 while not line.strip():
615 line = next(inputfile)
616
617 charges = []
618 while line.strip():
619 ch = float(line.split()[-1])
620 charges.append(ch)
621 line = next(inputfile)
622 self.atomcharges[pop_type.lower()] = charges
623
624 # This is for the older conventional MP2 code in 4.0b5.
625 mp_trigger = "MP2 Total Energy (a.u.)"
626 if line.strip()[:len(mp_trigger)] == mp_trigger:
627 self.metadata["methods"].append("MP2")
628 mpenergy = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')
629 if not hasattr(self, 'mpenergies'):
630 self.mpenergies = []
631 self.mpenergies.append([mpenergy])
632 # This is for the newer DF-MP2 code in 4.0.
633 if 'DF-MP2 Energies' in line:
634 self.metadata["methods"].append("DF-MP2")
635 while 'Total Energy' not in line:
636 line = next(inputfile)
637 mpenergy = utils.convertor(float(line.split()[3]), 'hartree', 'eV')
638 if not hasattr(self, 'mpenergies'):
639 self.mpenergies = []
640 self.mpenergies.append([mpenergy])
641
642 # Note this is just a start and needs to be modified for CCSD(T), etc.
643 ccsd_trigger = "* CCSD total energy"
644 if line.strip()[:len(ccsd_trigger)] == ccsd_trigger:
645 self.metadata["methods"].append("CCSD")
646 ccsd_energy = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')
647 if not hasattr(self, "ccenergis"):
648 self.ccenergies = []
649 self.ccenergies.append(ccsd_energy)
650
651 # The geometry convergence targets and values are printed in a table, with the legends
652 # describing the convergence annotation. Probably exact slicing of the line needs
653 # to be done in order to extract the numbers correctly. If there are no values for
654 # a paritcular target it means they are not used (marked also with an 'o'), and in this case
655 # we will set a value of numpy.inf so that any value will be smaller.
656 #
657 # ==> Convergence Check <==
658 #
659 # Measures of convergence in internal coordinates in au.
660 # Criteria marked as inactive (o), active & met (*), and active & unmet ( ).
661 # ---------------------------------------------------------------------------------------------
662 # Step Total Energy Delta E MAX Force RMS Force MAX Disp RMS Disp
663 # ---------------------------------------------------------------------------------------------
664 # Convergence Criteria 1.00e-06 * 3.00e-04 * o 1.20e-03 * o
665 # ---------------------------------------------------------------------------------------------
666 # 2 -379.77675264 -7.79e-03 1.88e-02 4.37e-03 o 2.29e-02 6.76e-03 o ~
667 # ---------------------------------------------------------------------------------------------
668 #
669 if (self.section == "Convergence Check") and line.strip() == "==> Convergence Check <==" \
670 and not hasattr(self, 'finite_difference'):
671
672 if not hasattr(self, "optstatus"):
673 self.optstatus = []
674 self.optstatus.append(data.ccData.OPT_UNKNOWN)
675
676 self.skip_lines(inputfile, ['b', 'units', 'comment', 'dash+tilde', 'header', 'dash+tilde'])
677
678 # These are the position in the line at which numbers should start.
679 starts = [27, 41, 55, 69, 83]
680
681 criteria = next(inputfile)
682 geotargets = []
683 for istart in starts:
684 if criteria[istart:istart+9].strip():
685 geotargets.append(float(criteria[istart:istart+9]))
686 else:
687 geotargets.append(numpy.inf)
688
689 self.skip_line(inputfile, 'dashes')
690
691 values = next(inputfile)
692 step = int(values.split()[0])
693 geovalues = []
694 for istart in starts:
695 if values[istart:istart+9].strip():
696 geovalues.append(float(values[istart:istart+9]))
697
698 if step == 1:
699 self.optstatus[-1] += data.ccData.OPT_NEW
700
701 # This assertion may be too restrictive, but we haven't seen the geotargets change.
702 # If such an example comes up, update the value since we're interested in the last ones.
703 if not hasattr(self, 'geotargets'):
704 self.geotargets = geotargets
705 else:
706 assert self.geotargets == geotargets
707
708 if not hasattr(self, 'geovalues'):
709 self.geovalues = []
710 self.geovalues.append(geovalues)
711
712 # This message signals a converged optimization, in which case we want
713 # to append the index for this step to optdone, which should be equal
714 # to the number of geovalues gathered so far.
715 if "Optimization is complete!" in line:
716
717 # This is a workaround for Psi4.0/sample_opt-irc-2.out;
718 # IRC calculations currently aren't parsed properly for
719 # optimization parameters.
720 if hasattr(self, 'geovalues'):
721
722 if not hasattr(self, 'optdone'):
723 self.optdone = []
724 self.optdone.append(len(self.geovalues))
725
726 assert hasattr(self, "optstatus") and len(self.optstatus) > 0
727 self.optstatus[-1] += data.ccData.OPT_DONE
728
729 # This message means that optimization has stopped for some reason, but we
730 # still want optdone to exist in this case, although it will be an empty list.
731 if line.strip() == "Optimizer: Did not converge!":
732 if not hasattr(self, 'optdone'):
733 self.optdone = []
734
735 assert hasattr(self, "optstatus") and len(self.optstatus) > 0
736 self.optstatus[-1] += data.ccData.OPT_UNCONVERGED
737
738 # The reference point at which properties are evaluated in Psi4 is explicitely stated,
739 # so we can save it for later. It is not, however, a part of the Properties section,
740 # but it appears before it and also in other places where properies that might depend
741 # on it are printed.
742 #
743 # Properties will be evaluated at 0.000000, 0.000000, 0.000000 Bohr
744 #
745 # OR
746 #
747 # Properties will be evaluated at 0.000000, 0.000000, 0.000000 [a0]
748 #
749 if "Properties will be evaluated at" in line.strip():
750 self.origin = numpy.array([float(x.strip(',')) for x in line.split()[-4:-1]])
751 assert line.split()[-1] in ["Bohr", "[a0]"]
752 self.origin = utils.convertor(self.origin, 'bohr', 'Angstrom')
753
754 # The properties section print the molecular dipole moment:
755 #
756 # ==> Properties <==
757 #
758 #
759 #Properties computed using the SCF density density matrix
760 # Nuclear Dipole Moment: (a.u.)
761 # X: 0.0000 Y: 0.0000 Z: 0.0000
762 #
763 # Electronic Dipole Moment: (a.u.)
764 # X: 0.0000 Y: 0.0000 Z: 0.0000
765 #
766 # Dipole Moment: (a.u.)
767 # X: 0.0000 Y: 0.0000 Z: 0.0000 Total: 0.0000
768 #
769 if (self.section == "Properties") and line.strip() == "Dipole Moment: (a.u.)":
770
771 line = next(inputfile)
772 dipole = numpy.array([float(line.split()[1]), float(line.split()[3]), float(line.split()[5])])
773 dipole = utils.convertor(dipole, "ebohr", "Debye")
774
775 if not hasattr(self, 'moments'):
776 # Old versions of Psi4 don't print the origin; assume
777 # it's at zero.
778 if not hasattr(self, 'origin'):
779 self.origin = numpy.array([0.0, 0.0, 0.0])
780 self.moments = [self.origin, dipole]
781 else:
782 try:
783 assert numpy.all(self.moments[1] == dipole)
784 except AssertionError:
785 self.logger.warning('Overwriting previous multipole moments with new values')
786 self.logger.warning('This could be from post-HF properties or geometry optimization')
787 self.moments = [self.origin, dipole]
788
789 # Higher multipole moments are printed separately, on demand, in lexicographical order.
790 #
791 # Multipole Moments:
792 #
793 # ------------------------------------------------------------------------------------
794 # Multipole Electric (a.u.) Nuclear (a.u.) Total (a.u.)
795 # ------------------------------------------------------------------------------------
796 #
797 # L = 1. Multiply by 2.5417462300 to convert to Debye
798 # Dipole X : 0.0000000 0.0000000 0.0000000
799 # Dipole Y : 0.0000000 0.0000000 0.0000000
800 # Dipole Z : 0.0000000 0.0000000 0.0000000
801 #
802 # L = 2. Multiply by 1.3450341749 to convert to Debye.ang
803 # Quadrupole XX : -1535.8888701 1496.8839996 -39.0048704
804 # Quadrupole XY : -11.5262958 11.4580038 -0.0682920
805 # ...
806 #
807 if line.strip() == "Multipole Moments:":
808
809 self.skip_lines(inputfile, ['b', 'd', 'header', 'd', 'b'])
810
811 # The reference used here should have been printed somewhere
812 # before the properties and parsed above.
813 moments = [self.origin]
814
815 line = next(inputfile)
816 while "----------" not in line.strip():
817
818 rank = int(line.split()[2].strip('.'))
819
820 multipole = []
821 line = next(inputfile)
822 while line.strip():
823
824 value = float(line.split()[-1])
825 fromunits = "ebohr" + (rank > 1)*("%i" % rank)
826 tounits = "Debye" + (rank > 1)*".ang" + (rank > 2)*("%i" % (rank-1))
827 value = utils.convertor(value, fromunits, tounits)
828 multipole.append(value)
829
830 line = next(inputfile)
831
832 multipole = numpy.array(multipole)
833 moments.append(multipole)
834 line = next(inputfile)
835
836 if not hasattr(self, 'moments'):
837 self.moments = moments
838 else:
839 for im, m in enumerate(moments):
840 if len(self.moments) <= im:
841 self.moments.append(m)
842 else:
843 assert numpy.allclose(self.moments[im], m, atol=1.0e4)
844
845 ## Analytic Gradient
846 # -Total Gradient:
847 # Atom X Y Z
848 # ------ ----------------- ----------------- -----------------
849 # 1 -0.000000000000 0.000000000000 -0.064527252292
850 # 2 0.000000000000 -0.028380539652 0.032263626146
851 # 3 -0.000000000000 0.028380539652 0.032263626146
852
853 ## Finite Differences Gradient
854 # -------------------------------------------------------------
855 # ## F-D gradient (Symmetry 0) ##
856 # Irrep: 1 Size: 3 x 3
857 #
858 # 1 2 3
859 #
860 # 1 0.00000000000000 0.00000000000000 -0.02921303282515
861 # 2 0.00000000000000 -0.00979709321487 0.01460651641258
862 # 3 0.00000000000000 0.00979709321487 0.01460651641258
863 if line.strip() in Psi4.GRADIENT_HEADERS:
864
865 # Handle the different header lines between analytic and
866 # numerical gradients.
867 gradient_skip_lines = [
868 info.skip_lines
869 for info in Psi4.GRADIENT_TYPES.values()
870 if info.header == line.strip()
871 ][0]
872 gradient = self.parse_gradient(inputfile, gradient_skip_lines)
873
874 if not hasattr(self, 'grads'):
875 self.grads = []
876 self.grads.append(gradient)
877
878 # OLD Normal mode output parser (PSI4 < 1)
879
880 ## Harmonic frequencies.
881
882 # -------------------------------------------------------------
883
884 # Computing second-derivative from gradients using projected,
885 # symmetry-adapted, cartesian coordinates (fd_freq_1).
886
887 # 74 gradients passed in, including the reference geometry.
888 # Generating complete list of displacements from unique ones.
889
890 # Operation 2 takes plus displacements of irrep Bg to minus ones.
891 # Operation 3 takes plus displacements of irrep Au to minus ones.
892 # Operation 2 takes plus displacements of irrep Bu to minus ones.
893
894 # Irrep Harmonic Frequency
895 # (cm-1)
896 # -----------------------------------------------
897 # Au 137.2883
898 if line.strip() == 'Irrep Harmonic Frequency':
899
900 vibsyms = []
901 vibfreqs = []
902
903 self.skip_lines(inputfile, ['(cm-1)', 'dashes'])
904
905 ## The first section contains the symmetry of each normal
906 ## mode and its frequency.
907 line = next(inputfile)
908 while '---' not in line:
909 chomp = line.split()
910 vibsym = chomp[0]
911 vibfreq = Psi4.parse_vibfreq(chomp[1])
912 vibsyms.append(vibsym)
913 vibfreqs.append(vibfreq)
914 line = next(inputfile)
915
916 self.set_attribute('vibsyms', vibsyms)
917 self.set_attribute('vibfreqs', vibfreqs)
918
919 line = next(inputfile)
920 assert line.strip() == ''
921 line = next(inputfile)
922 assert 'Normal Modes' in line
923 line = next(inputfile)
924 assert 'Molecular mass is' in line
925 if hasattr(self, 'atommasses'):
926 assert abs(float(line.split()[3]) - sum(self.atommasses)) < 1.0e-4
927 line = next(inputfile)
928 assert line.strip() == 'Frequencies in cm^-1; force constants in au.'
929 line = next(inputfile)
930 assert line.strip() == ''
931 line = next(inputfile)
932
933 ## The second section contains the frequency, force
934 ## constant, and displacement for each normal mode, along
935 ## with the atomic masses.
936
937 # Normal Modes (non-mass-weighted).
938 # Molecular mass is 130.07825 amu.
939 # Frequencies in cm^-1; force constants in au.
940
941 # Frequency: 137.29
942 # Force constant: 0.0007
943 # X Y Z mass
944 # C 0.000 0.000 0.050 12.000000
945 # C 0.000 0.000 0.050 12.000000
946 for vibfreq in self.vibfreqs:
947 _vibfreq = Psi4.parse_vibfreq(line[13:].strip())
948 assert abs(vibfreq - _vibfreq) < 1.0e-2
949 line = next(inputfile)
950 # Can't do anything with this for now.
951 assert 'Force constant:' in line
952 line = next(inputfile)
953 assert 'X Y Z mass' in line
954 line = next(inputfile)
955 if not hasattr(self, 'vibdisps'):
956 self.vibdisps = []
957 normal_mode_disps = []
958 # for k in range(self.natom):
959 while line.strip():
960 chomp = line.split()
961 # Do nothing with this for now.
962 atomsym = chomp[0]
963 atomcoords = [float(x) for x in chomp[1:4]]
964 # Do nothing with this for now.
965 atommass = float(chomp[4])
966 normal_mode_disps.append(atomcoords)
967 line = next(inputfile)
968 self.vibdisps.append(normal_mode_disps)
969 line = next(inputfile)
970
971 # NEW Normal mode output parser (PSI4 >= 1)
972
973 # ==> Harmonic Vibrational Analysis <==
974 # ...
975 # Vibration 7 8 9
976 # ...
977 #
978 # Vibration 10 11 12
979 # ...
980
981 if line.strip() == '==> Harmonic Vibrational Analysis <==':
982
983 vibsyms = []
984 vibfreqs = []
985 vibdisps = []
986
987 # Skip lines till the first Vibration block
988 while not line.strip().startswith('Vibration'):
989 line = next(inputfile)
990
991 n_modes = 0
992 # Parse all the Vibration blocks
993 while line.strip().startswith('Vibration'):
994 n = len(line.split()) - 1
995 n_modes += n
996 vibfreqs_, vibsyms_, vibdisps_ = self.parse_vibration(n, inputfile)
997 vibfreqs.extend(vibfreqs_)
998 vibsyms.extend(vibsyms_)
999 vibdisps.extend(vibdisps_)
1000 line = next(inputfile)
1001
1002 # It looks like the symmetry of the normal mode may be missing
1003 # from some / most. Only include them if they are there for all
1004
1005 if len(vibfreqs) == n_modes:
1006 self.set_attribute('vibfreqs', vibfreqs)
1007
1008 if len(vibsyms) == n_modes:
1009 self.set_attribute('vibsyms', vibsyms)
1010
1011 if len(vibdisps) == n_modes:
1012 self.set_attribute('vibdisps', vibdisps)
1013
1014 # If finite difference is used to compute forces (i.e. by displacing
1015 # slightly all the atoms), a series of additional scf calculations is
1016 # performed. Orbitals, geometries, energies, etc. for these shouln't be
1017 # included in the parsed data.
1018
1019 if line.strip().startswith('Using finite-differences of gradients'):
1020 self.set_attribute('finite_difference', True)
1021
1022 if line[:54] == '*** Psi4 exiting successfully. Buy a developer a beer!'\
1023 or line[:54] == '*** PSI4 exiting successfully. Buy a developer a beer!':
1024 self.metadata['success'] = True
1025
1026 def _parse_mosyms_moenergies(self, inputfile, spinidx):
1027 """Parse molecular orbital symmetries and energies from the
1028 'Post-Iterations' section.
1029 """
1030 line = next(inputfile)
1031 while line.strip():
1032 for i in range(len(line.split()) // 2):
1033 self.mosyms[spinidx].append(line.split()[i*2][-2:])
1034 moenergy = utils.convertor(float(line.split()[i*2+1]), "hartree", "eV")
1035 self.moenergies[spinidx].append(moenergy)
1036 line = next(inputfile)
1037 return
1038
1039 def parse_gradient(self, inputfile, skip_lines):
1040 """Parse the nuclear gradient section into a list of lists with shape
1041 [natom, 3].
1042 """
1043 self.skip_lines(inputfile, skip_lines)
1044 line = next(inputfile)
1045 gradient = []
1046
1047 while line.strip():
1048 idx, x, y, z = line.split()
1049 gradient.append((float(x), float(y), float(z)))
1050 line = next(inputfile)
1051 return gradient
1052
1053 @staticmethod
1054 def parse_vibration(n, inputfile):
1055
1056 # Freq [cm^-1] 1501.9533 1501.9533 1501.9533
1057 # Irrep
1058 # Reduced mass [u] 1.1820 1.1820 1.1820
1059 # Force const [mDyne/A] 1.5710 1.5710 1.5710
1060 # Turning point v=0 [a0] 0.2604 0.2604 0.2604
1061 # RMS dev v=0 [a0 u^1/2] 0.2002 0.2002 0.2002
1062 # Char temp [K] 2160.9731 2160.9731 2160.9731
1063 # ----------------------------------------------------------------------------------
1064 # 1 C -0.00 0.01 0.13 -0.00 -0.13 0.01 -0.13 0.00 -0.00
1065 # 2 H 0.33 -0.03 -0.38 0.02 0.60 -0.02 0.14 -0.01 -0.32
1066 # 3 H -0.32 -0.03 -0.37 -0.01 0.60 -0.01 0.15 -0.01 0.33
1067 # 4 H 0.02 0.32 -0.36 0.01 0.16 -0.34 0.60 -0.01 0.01
1068 # 5 H 0.02 -0.33 -0.39 0.01 0.13 0.31 0.60 0.01 0.01
1069
1070 line = next(inputfile)
1071 assert 'Freq' in line
1072 chomp = line.split()
1073 vibfreqs = [Psi4.parse_vibfreq(x) for x in chomp[-n:]]
1074
1075 line = next(inputfile)
1076 assert 'Irrep' in line
1077 chomp = line.split()
1078 vibsyms = [irrep for irrep in chomp[1:]]
1079
1080 line = next(inputfile)
1081 assert 'Reduced mass' in line
1082
1083 line = next(inputfile)
1084 assert 'Force const' in line
1085
1086 line = next(inputfile)
1087 assert 'Turning point' in line
1088
1089 line = next(inputfile)
1090 assert 'RMS dev' in line
1091
1092 line = next(inputfile)
1093 assert 'Char temp' in line
1094
1095 line = next(inputfile)
1096 assert '---' in line
1097
1098 line = next(inputfile)
1099 vibdisps = [ [] for i in range(n)]
1100 while len(line.strip()) > 0:
1101 chomp = line.split()
1102 for i in range(n):
1103 start = len(chomp) - (n - i) * 3
1104 stop = start + 3
1105 mode_disps = [float(c) for c in chomp[start:stop]]
1106 vibdisps[i].append(mode_disps)
1107
1108 line = next(inputfile)
1109
1110 return vibfreqs, vibsyms, vibdisps
1111
1112 @staticmethod
1113 def parse_vibfreq(vibfreq):
1114 """Imaginary frequencies are printed as '12.34i', rather than
1115 '-12.34'.
1116 """
1117 is_imag = vibfreq[-1] == 'i'
1118 if is_imag:
1119 return -float(vibfreq[:-1])
1120 else:
1121 return float(vibfreq)