Debian Codegraph @

cclib/parser/daltonparser.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 DALTON output files"""
9
10
11 from __future__ import print_function
12
13 import re
14
15 import numpy
16
17 from cclib.parser import logfileparser
18 from cclib.parser import utils
19
20
21 class DALTON(logfileparser.Logfile):
22 """A DALTON log file."""
23
24 def __init__(self, *args, **kwargs):
25
26 # Call the __init__ method of the superclass
27 super(DALTON, self).__init__(logname="DALTON", *args, **kwargs)
28
29 def __str__(self):
30 """Return a string representation of the object."""
31 return "DALTON log file %s" % (self.filename)
32
33 def __repr__(self):
34 """Return a representation of the object."""
35 return 'DALTON("%s")' % (self.filename)
36
37 def normalisesym(self, label):
38 """DALTON does not require normalizing symmetry labels."""
39 return label
40
41 def before_parsing(self):
42
43 # Used to decide whether to wipe the atomcoords clean.
44 self.firststdorient = True
45
46 # Use to track which section/program output we are parsing,
47 # since some programs print out the same headers, which we
48 # would like to use as triggers.
49 self.section = None
50
51 # If there is no symmetry, assume this.
52 self.symlabels = ['Ag']
53
54 # Is the basis set from a single library file? This is true
55 # when the first line is BASIS, false for INTGRL/ATOMBASIS.
56 self.basislibrary = True
57
58
59 def parse_geometry(self, lines):
60 """Parse DALTON geometry lines into an atomcoords array."""
61
62 coords = []
63 for lin in lines:
64
65 # Without symmetry there are simply four columns, and with symmetry
66 # an extra label is printed after the atom type.
67 cols = lin.split()
68 if cols[1][0] == "_":
69 xyz = cols[2:]
70 else:
71 xyz = cols[1:]
72
73 # The assumption is that DALTON always print in atomic units.
74 xyz = [utils.convertor(float(x), 'bohr', 'Angstrom') for x in xyz]
75 coords.append(xyz)
76
77 return coords
78
79 def extract(self, inputfile, line):
80 """Extract information from the file object inputfile."""
81
82 # Extract the version number and optionally the Git revision
83 # number.
84 #
85 # Example strings that at least the major version is parsed from:
86 #
87 # This is output from DALTON 2013.2
88 # 2013.4
89 # 2014.0
90 # 2014.alpha
91 # 2015.0
92 # 2016.alpha
93 # (Release 1.1, September 2000)
94 # Release 2011 (DEVELOPMENT VERSION)
95 # Release 2011 (Rev. 0, Dec. 2010)
96 # Release 2011 (Rev. 0, Mar. 2011)
97 # (Release 2.0 rev. 0, Mar. 2005)
98 # (Release Dalton2013 patch 0)
99 # release Dalton2017.alpha (2016)
100 # release Dalton2017.alpha (2017)
101 # release Dalton2018.0 (2018)
102 # release Dalton2018.0-rc (2018)
103 # release Dalton2018.alpha (2018)
104 # release Dalton2019.alpha (2018)
105 if line[4:30] == "This is output from DALTON":
106 rs = (r"from DALTON \(?(?:Release|release)?\s?(?:Dalton)?"
107 r"(\d+\.?[\w\d\-]*)"
108 r"(?:[\s,]\(?)?")
109 match = re.search(rs, line)
110 if match:
111 self.metadata["package_version"] = match.groups()[0]
112 # Don't add revision information to the main package version for now.
113 if "Last Git revision" in line:
114 revision = line.split()[4]
115
116 # Is the basis set from a single library file, or is it
117 # manually specified? See before_parsing().
118 if line[:6] == 'INTGRL'or line[:9] == 'ATOMBASIS':
119 self.basislibrary = False
120
121 # This section at the start of geometry optimization jobs gives us information
122 # about optimization targets (geotargets) and possibly other things as well.
123 # Notice how the number of criteria required to converge is set to 2 here,
124 # but this parameter can (probably) be tweaked in the input.
125 #
126 # Chosen parameters for *OPTIMI :
127 # -------------------------------
128 #
129 # Default 1st order method will be used: BFGS update.
130 # Optimization will be performed in redundant internal coordinates (by default).
131 # Model Hessian will be used as initial Hessian.
132 # The model Hessian parameters of Roland Lindh will be used.
133 #
134 #
135 # Trust region method will be used to control step (default).
136 #
137 # Convergence threshold for gradient set to : 1.00D-04
138 # Convergence threshold for energy set to : 1.00D-06
139 # Convergence threshold for step set to : 1.00D-04
140 # Number of convergence criteria set to : 2
141 #
142 if line.strip()[:25] == "Convergence threshold for":
143
144 if not hasattr(self, 'geotargets'):
145 self.geotargets = []
146 self.geotargets_names = []
147
148 target = self.float(line.split()[-1])
149 name = line.strip()[25:].split()[0]
150
151 self.geotargets.append(target)
152 self.geotargets_names.append(name)
153
154 # This is probably the first place where atomic symmetry labels are printed,
155 # somewhere afer the SYMGRP point group information section. We need to know
156 # which atom is in which symmetry, since this influences how some things are
157 # print later on. We can also get some generic attributes along the way.
158 #
159 # Isotopic Masses
160 # ---------------
161 #
162 # C _1 12.000000
163 # C _2 12.000000
164 # C _1 12.000000
165 # C _2 12.000000
166 # ...
167 #
168 # Note that when there is no symmetry there are only two columns here.
169 #
170 # It is also a good idea to keep in mind that DALTON, with symmetry on, operates
171 # in a specific point group, so symmetry atoms have no internal representation.
172 # Therefore only atoms marked as "_1" or "#1" in other places are actually
173 # represented in the model. The symmetry atoms (higher symmetry indices) are
174 # generated on the fly when writing the output. We will save the symmetry indices
175 # here for later use.
176 #
177 # Additional note: the symmetry labels are printed only for atoms that have
178 # symmetry images... so assume "_1" if a label is missing. For example, there will
179 # be no label for atoms on an axes, such as the oxygen in water in C2v:
180 #
181 # O 15.994915
182 # H _1 1.007825
183 # H _2 1.007825
184 #
185 if line.strip() == "Isotopic Masses":
186
187 self.skip_lines(inputfile, ['d', 'b'])
188
189 # Since some symmetry labels may be missing, read in all lines first.
190 lines = []
191 line = next(inputfile)
192 while line.strip():
193 lines.append(line)
194 line = next(inputfile)
195
196 # Split lines into columsn and dd any missing symmetry labels, if needed.
197 lines = [l.split() for l in lines]
198 if any([len(l) == 3 for l in lines]):
199 for il, l in enumerate(lines):
200 if len(l) == 2:
201 lines[il] = [l[0], "_1", l[1]]
202
203 atomnos = []
204 symmetry_atoms = []
205 atommasses = []
206 for cols in lines:
207 cols0 = ''.join([i for i in cols[0] if not i.isdigit()]) #remove numbers
208 atomnos.append(self.table.number[cols0])
209 if len(cols) == 3:
210 symmetry_atoms.append(int(cols[1][1]))
211 atommasses.append(float(cols[2]))
212 else:
213 atommasses.append(float(cols[1]))
214
215 self.set_attribute('atomnos', atomnos)
216 self.set_attribute('atommasses', atommasses)
217
218 self.set_attribute('natom', len(atomnos))
219 self.set_attribute('natom', len(atommasses))
220
221 # Save this for later if there were any labels.
222 self.symmetry_atoms = symmetry_atoms or None
223
224 # This section is close to the beginning of the file, and can be used
225 # to parse natom, nbasis and atomnos. We also construct atombasis here,
226 # although that is symmetry-dependent (see inline comments). Note that
227 # DALTON operates on the idea of atom type, which are not necessarily
228 # unique element-wise.
229 #
230 # Atoms and basis sets
231 # --------------------
232 #
233 # Number of atom types : 6
234 # Total number of atoms: 20
235 #
236 # Basis set used is "STO-3G" from the basis set library.
237 #
238 # label atoms charge prim cont basis
239 # ----------------------------------------------------------------------
240 # C 6 6.0000 15 5 [6s3p|2s1p]
241 # H 4 1.0000 3 1 [3s|1s]
242 # C 2 6.0000 15 5 [6s3p|2s1p]
243 # H 2 1.0000 3 1 [3s|1s]
244 # C 2 6.0000 15 5 [6s3p|2s1p]
245 # H 4 1.0000 3 1 [3s|1s]
246 # ----------------------------------------------------------------------
247 # total: 20 70.0000 180 60
248 # ----------------------------------------------------------------------
249 #
250 # Threshold for neglecting AO integrals: 1.00D-12
251 #
252 if line.strip() == "Atoms and basis sets":
253
254 self.skip_lines(inputfile, ['d', 'b'])
255
256 line = next(inputfile)
257 assert "Number of atom types" in line
258 self.ntypes = int(line.split()[-1])
259
260 line = next(inputfile)
261 assert "Total number of atoms:" in line
262 self.set_attribute("natom", int(line.split()[-1]))
263
264 # When using the INTGRL keyword and not pulling from the
265 # basis set library, the "Basis set used" line doesn't
266 # appear.
267 if not self.basislibrary:
268 self.skip_line(inputfile, 'b')
269 else:
270 #self.skip_lines(inputfile, ['b', 'basisname', 'b'])
271 line = next(inputfile)
272 line = next(inputfile)
273 self.metadata["basis_set"] = line.split()[4].strip('\"')
274 line = next(inputfile)
275
276 line = next(inputfile)
277 cols = line.split()
278
279 # Detecting which columns things are in will be somewhat more robust
280 # to formatting changes in the future.
281 iatoms = cols.index('atoms')
282 icharge = cols.index('charge')
283 icont = cols.index('cont')
284
285 self.skip_line(inputfile, 'dashes')
286
287 atomnos = []
288 atombasis = []
289 nbasis = 0
290 for itype in range(self.ntypes):
291
292 line = next(inputfile)
293 cols = line.split()
294
295 atoms = int(cols[iatoms])
296 charge = float(cols[icharge])
297 assert int(charge) == charge
298 charge = int(charge)
299 cont = int(cols[icont])
300
301 for at in range(atoms):
302
303 atomnos.append(charge)
304
305 # If symmetry atoms are present, these will have basis functions
306 # printed immediately after the one unique atom, so for all
307 # practical purposes cclib can assume the ordering in atombasis
308 # follows this out-of order scheme to match the output.
309 if self.symmetry_atoms:
310
311 # So we extend atombasis only for the unique atoms (with a
312 # symmetry index of 1), interleaving the basis functions
313 # for this atoms with basis functions for all symmetry atoms.
314 if self.symmetry_atoms[at] == 1:
315 nsyms = 1
316 while (at + nsyms < self.natom) and self.symmetry_atoms[at + nsyms] == nsyms + 1:
317 nsyms += 1
318 for isym in range(nsyms):
319 istart = nbasis + isym
320 iend = nbasis + cont*nsyms + isym
321 atombasis.append(list(range(istart, iend, nsyms)))
322 nbasis += cont*nsyms
323
324 else:
325 atombasis.append(list(range(nbasis, nbasis + cont)))
326 nbasis += cont
327
328 self.set_attribute('atomnos', atomnos)
329 self.set_attribute('atombasis', atombasis)
330 self.set_attribute('nbasis', nbasis)
331
332 self.skip_line(inputfile, 'dashes')
333
334 line = next(inputfile)
335 self.set_attribute('natom', int(line.split()[iatoms]))
336 self.set_attribute('nbasis', int(line.split()[icont]))
337
338 self.skip_line(inputfile, 'dashes')
339
340 # The Gaussian exponents and contraction coefficients are printed for each primitive
341 # and then the contraction information is printed separately (see below) Both segmented
342 # and general contractions are used, but we can parse them the same way since zeros are
343 # inserted for primitives that are not used. However, no atom index is printed here
344 # so we don't really know when a new atom is started without using information
345 # from other section (we should already have atombasis parsed at this point).
346 #
347 # Orbital exponents and contraction coefficients
348 # ----------------------------------------------
349 #
350 #
351 # C #1 1s 1 71.616837 0.1543 0.0000
352 # seg. cont. 2 13.045096 0.5353 0.0000
353 # 3 3.530512 0.4446 0.0000
354 # 4 2.941249 0.0000 -0.1000
355 # ...
356 #
357 # Here is a corresponding fragment for general contractions:
358 #
359 # C 1s 1 33980.000000 0.0001 -0.0000 0.0000 0.0000 0.0000
360 # 0.0000 0.0000 0.0000 0.0000
361 # gen. cont. 2 5089.000000 0.0007 -0.0002 0.0000 0.0000 0.0000
362 # 0.0000 0.0000 0.0000 0.0000
363 # 3 1157.000000 0.0037 -0.0008 0.0000 0.0000 0.0000
364 # 0.0000 0.0000 0.0000 0.0000
365 # 4 326.600000 0.0154 -0.0033 0.0000 0.0000 0.0000
366 # ...
367 #
368 if line.strip() == "Orbital exponents and contraction coefficients":
369
370 self.skip_lines(inputfile, ['d', 'b', 'b'])
371
372 # Here we simply want to save the numbers defining each primitive for later use,
373 # where the first number is the exponent, and the rest are coefficients which
374 # should be zero if the primitive is not used in a contraction. This list is
375 # symmetry agnostic, although primitives/contractions are not generally.
376 self.primitives = []
377
378 prims = []
379 line = next(inputfile)
380 while line.strip():
381
382 # Each contraction/section is separated by a blank line, and at the very
383 # end there is an extra blank line.
384 while line.strip():
385
386 # For generalized contraction it is typical to see the coefficients wrapped
387 # to new lines, so we must collect them until we are sure a primitive starts.
388 if line[:30].strip():
389 if prims:
390 self.primitives.append(prims)
391 prims = []
392
393 prims += [float(x) for x in line[20:].split()]
394
395 line = next(inputfile)
396
397 line = next(inputfile)
398
399 # At the end we have the final primitive to save.
400 self.primitives.append(prims)
401
402 # This is the corresponding section to the primitive definitions parsed above, so we
403 # assume those numbers are available in the variable 'primitives'. Here we read in the
404 # indicies of primitives, which we use to construct gbasis.
405 #
406 # Contracted Orbitals
407 # -------------------
408 #
409 # 1 C 1s 1 2 3 4 5 6 7 8 9 10 11 12
410 # 2 C 1s 1 2 3 4 5 6 7 8 9 10 11 12
411 # 3 C 1s 10
412 # 4 C 1s 11
413 # ...
414 #
415 # Here is an fragment with symmetry labels:
416 #
417 # ...
418 # 1 C #1 1s 1 2 3
419 # 2 C #2 1s 7 8 9
420 # 3 C #1 1s 4 5 6
421 # ...
422 #
423 if line.strip() == "Contracted Orbitals":
424
425 self.skip_lines(inputfile, ['d', 'b'])
426
427 # This is the reverse of atombasis, so that we can easily map from a basis functions
428 # to the corresponding atom for use in the loop below.
429 basisatoms = [None for i in range(self.nbasis)]
430 for iatom in range(self.natom):
431 for ibasis in self.atombasis[iatom]:
432 basisatoms[ibasis] = iatom
433
434 # Since contractions are not generally given in order (when there is symmetry),
435 # start with an empty list for gbasis.
436 gbasis = [[] for i in range(self.natom)]
437
438 # This will hold the number of contractions already printed for each orbital,
439 # counting symmetry orbitals separately.
440 orbitalcount = {}
441
442 for ibasis in range(self.nbasis):
443
444 line = next(inputfile)
445 cols = line.split()
446
447 # The first columns is always the basis function index, which we can assert.
448 assert int(cols[0]) == ibasis + 1
449
450 # The number of columns is differnet when symmetry is used. If there are further
451 # complications, it may be necessary to use exact slicing, since the formatting
452 # of this section seems to be fixed (although columns can be missing). Notice how
453 # We subtract one from the primitive indices here already to match cclib's
454 # way of counting from zero in atombasis.
455 if '#' in line:
456 sym = cols[2]
457 orbital = cols[3]
458 prims = [int(i) - 1 for i in cols[4:]]
459 else:
460 sym = None
461 orbital = cols[2]
462 prims = [int(i) - 1 for i in cols[3:]]
463
464 shell = orbital[0]
465 subshell = orbital[1].upper()
466
467 iatom = basisatoms[ibasis]
468
469 # We want to count the number of contractiong already parsed for each orbital,
470 # but need to make sure to differentiate between atoms and symmetry atoms.
471 orblabel = str(iatom) + '.' + orbital + (sym or "")
472 orbitalcount[orblabel] = orbitalcount.get(orblabel, 0) + 1
473
474 # Here construct the actual primitives for gbasis, which should be a list
475 # of 2-tuples containing an exponent an coefficient. Note how we are indexing
476 # self.primitives from zero although the printed numbering starts from one.
477 primitives = []
478 for ip in prims:
479 p = self.primitives[ip]
480 exponent = p[0]
481 coefficient = p[orbitalcount[orblabel]]
482 primitives.append((exponent, coefficient))
483
484 contraction = (subshell, primitives)
485 if contraction not in gbasis[iatom]:
486 gbasis[iatom].append(contraction)
487
488 self.skip_line(inputfile, 'blank')
489
490 self.set_attribute('gbasis', gbasis)
491
492 # Since DALTON sometimes uses symmetry labels (Ag, Au, etc.) and sometimes
493 # just the symmetry group index, we need to parse and keep a mapping between
494 # these two for later use.
495 #
496 # Symmetry Orbitals
497 # -----------------
498 #
499 # Number of orbitals in each symmetry: 25 5 25 5
500 #
501 #
502 # Symmetry Ag ( 1)
503 #
504 # 1 C 1s 1 + 2
505 # 2 C 1s 3 + 4
506 # ...
507 #
508 if line.strip() == "Symmetry Orbitals":
509
510 self.skip_lines(inputfile, ['d', 'b'])
511
512 line = inputfile.next()
513 self.symcounts = [int(c) for c in line.split(':')[1].split()]
514
515 self.symlabels = []
516 for sc in self.symcounts:
517
518 self.skip_lines(inputfile, ['b', 'b'])
519
520 # If the number of orbitals for a symmetry is zero, the printout
521 # is different (see MP2 unittest logfile for an example).
522 line = inputfile.next()
523
524 if sc == 0:
525 assert "No orbitals in symmetry" in line
526 else:
527 assert line.split()[0] == "Symmetry"
528 self.symlabels.append(line.split()[1])
529 self.skip_line(inputfile, 'blank')
530 for i in range(sc):
531 orbital = inputfile.next()
532
533 if "Starting in Wave Function Section (SIRIUS)" in line:
534 self.section = "SIRIUS"
535
536 # Orbital specifications
537 # ======================
538 # Abelian symmetry species All | 1 2 3 4
539 # | Ag Au Bu Bg
540 # --- | --- --- --- ---
541 # Total number of orbitals 60 | 25 5 25 5
542 # Number of basis functions 60 | 25 5 25 5
543 #
544 # ** Automatic occupation of RKS orbitals **
545 #
546 # -- Initial occupation of symmetries is determined from extended Huckel guess.
547 # -- Initial occupation of symmetries is :
548 # @ Occupied SCF orbitals 35 | 15 2 15 3
549 #
550 # Maximum number of Fock iterations 0
551 # Maximum number of DIIS iterations 60
552 # Maximum number of QC-SCF iterations 60
553 # Threshold for SCF convergence 1.00D-05
554 # This is a DFT calculation of type: B3LYP
555 # ...
556 #
557 if "Total number of orbitals" in line:
558 # DALTON 2015 adds a @ in front of number of orbitals
559 chomp = line.split()
560 index = 4
561 if "@" in chomp:
562 index = 5
563 self.set_attribute("nbasis", int(chomp[index]))
564 self.nmo_per_symmetry = list(map(int, chomp[index+2:]))
565 assert self.nbasis == sum(self.nmo_per_symmetry)
566 if "Threshold for SCF convergence" in line:
567 if not hasattr(self, "scftargets"):
568 self.scftargets = []
569 scftarget = self.float(line.split()[-1])
570 self.scftargets.append([scftarget])
571
572 # Wave function specification
573 # ============================
574 # @ Wave function type >>> KS-DFT <<<
575 # @ Number of closed shell electrons 70
576 # @ Number of electrons in active shells 0
577 # @ Total charge of the molecule 0
578 #
579 # @ Spin multiplicity and 2 M_S 1 0
580 # @ Total number of symmetries 4 (point group: C2h)
581 # @ Reference state symmetry 1 (irrep name : Ag )
582 #
583 # This is a DFT calculation of type: B3LYP
584 # ...
585 #
586 if line.strip() == "Wave function specification":
587 self.skip_line(inputfile, 'e')
588 line = next(inputfile)
589 # Must be a coupled cluster calculation.
590 if line.strip() == '':
591 self.skip_lines(inputfile, ['b', 'Coupled Cluster', 'b'])
592 else:
593 assert "wave function" in line.lower()
594 line = next(inputfile)
595 assert "Number of closed shell electrons" in line
596 self.paired_electrons = int(line.split()[-1])
597 line = next(inputfile)
598 assert "Number of electrons in active shells" in line
599 self.unpaired_electrons = int(line.split()[-1])
600 line = next(inputfile)
601 assert "Total charge of the molecule" in line
602 self.set_attribute("charge", int(line.split()[-1]))
603 self.skip_line(inputfile, 'b')
604 line = next(inputfile)
605 assert "Spin multiplicity and 2 M_S" in line
606 self.set_attribute("mult", int(line.split()[-2]))
607 # Dalton only has ROHF, no UHF
608 if self.mult != 1:
609 self.metadata["unrestricted"] = True
610
611 if not hasattr(self, 'homos'):
612 self.set_attribute('homos', [(self.paired_electrons // 2) - 1])
613 if self.unpaired_electrons > 0:
614 self.homos.append(self.homos[0])
615 self.homos[0] += self.unpaired_electrons
616
617 # *********************************************
618 # ***** DIIS optimization of Hartree-Fock *****
619 # *********************************************
620 #
621 # C1-DIIS algorithm; max error vectors = 8
622 #
623 # Automatic occupation of symmetries with 70 electrons.
624 #
625 # Iter Total energy Error norm Delta(E) SCF occupation
626 # -----------------------------------------------------------------------------
627 # K-S energy, electrons, error : -46.547567739269 69.9999799123 -2.01D-05
628 # @ 1 -381.645762476 4.00D+00 -3.82D+02 15 2 15 3
629 # Virial theorem: -V/T = 2.008993
630 # @ MULPOP C _1 0.15; C _2 0.15; C _1 0.12; C _2 0.12; C _1 0.11; C _2 0.11; H _1 -0.15; H _2 -0.15; H _1 -0.14; H _2 -0.14;
631 # @ C _1 0.23; C _2 0.23; H _1 -0.15; H _2 -0.15; C _1 0.08; C _2 0.08; H _1 -0.12; H _2 -0.12; H _1 -0.13; H _2 -0.13;
632 # -----------------------------------------------------------------------------
633 # K-S energy, electrons, error : -46.647668038900 69.9999810430 -1.90D-05
634 # @ 2 -381.949410128 1.05D+00 -3.04D-01 15 2 15 3
635 # Virial theorem: -V/T = 2.013393
636 # ...
637 #
638 # With and without symmetry, the "Total energy" line is shifted a little.
639 if self.section == "SIRIUS" and "Iter" in line and "Total energy" in line:
640
641 iteration = 0
642 converged = False
643 values = []
644 if not hasattr(self, "scfvalues"):
645 self.scfvalues = []
646
647 while not converged:
648
649 try:
650 line = next(inputfile)
651 except StopIteration:
652 self.logger.warning('File terminated before end of last SCF!')
653 break
654
655 # each iteration is bracketed by "-------------"
656 if "-------------------" in line:
657 iteration += 1
658 continue
659
660 # the first hit of @ n where n is the current iteration
661 strcompare = "@{0:>3d}".format(iteration)
662 if strcompare in line:
663 temp = line.split()
664 error_norm = self.float(temp[3])
665 values.append([error_norm])
666
667 if line[0] == "@" and "converged in" in line:
668 converged = True
669
670 # It seems DALTON does change the SCF convergence criteria during a
671 # geometry optimization, but also does not print them. So, assume they
672 # are unchanged and copy the initial values after the first step. However,
673 # it would be good to check up on this - perhaps it is possible to print.
674 self.scfvalues.append(values)
675 if len(self.scfvalues) > 1:
676 self.scftargets.append(self.scftargets[-1])
677
678 # DALTON organizes the energies by symmetry, so we need to parse first,
679 # and then sort the energies (and labels) before we store them.
680 #
681 # The formatting varies depending on RHF/DFT and/or version. Here is
682 # an example from a DFT job:
683 #
684 # *** SCF orbital energy analysis ***
685 #
686 # Only the five lowest virtual orbital energies printed in each symmetry.
687 #
688 # Number of electrons : 70
689 # Orbital occupations : 15 2 15 3
690 #
691 # Sym Kohn-Sham orbital energies
692 #
693 # 1 Ag -10.01616533 -10.00394288 -10.00288640 -10.00209612 -9.98818062
694 # -0.80583154 -0.71422407 -0.58487249 -0.55551093 -0.50630125
695 # ...
696 #
697 # Here is an example from an RHF job that only has symmetry group indices:
698 #
699 # *** SCF orbital energy analysis ***
700 #
701 # Only the five lowest virtual orbital energies printed in each symmetry.
702 #
703 # Number of electrons : 70
704 # Orbital occupations : 15 2 15 3
705 #
706 # Sym Hartree-Fock orbital energies
707 #
708 # 1 -11.04052518 -11.03158921 -11.02882211 -11.02858563 -11.01747921
709 # -1.09029777 -0.97492511 -0.79988247 -0.76282547 -0.69677619
710 # ...
711 #
712 if self.section == "SIRIUS" and "*** SCF orbital energy analysis ***" in line:
713
714 # to get ALL orbital energies, the .PRINTLEVELS keyword needs
715 # to be at least 0,10 (up from 0,5). I know, obvious, right?
716 # this, however, will conflict with the scfvalues output that
717 # changes into some weird form of DIIS debug output.
718
719 mosyms = []
720 moenergies = []
721
722 self.skip_line(inputfile, 'blank')
723 line = next(inputfile)
724
725 # There is some extra text between the section header and
726 # the number of electrons for open-shell calculations.
727 while "Number of electrons" not in line:
728 line = next(inputfile)
729 nelectrons = int(line.split()[-1])
730
731 line = next(inputfile)
732 occupations = [int(o) for o in line.split()[3:]]
733 nsym = len(occupations)
734
735 self.skip_lines(inputfile, ['b', 'header', 'b'])
736
737 # now parse nsym symmetries
738 for isym in range(nsym):
739
740 # For unoccupied symmetries, nothing is printed here.
741 if occupations[isym] == 0:
742 continue
743
744 # When there are exactly five energies printed (on just one line), it seems
745 # an extra blank line is printed after a block.
746 line = next(inputfile)
747 if not line.strip():
748 line = next(inputfile)
749 cols = line.split()
750
751 # The first line has the orbital symmetry information, but sometimes
752 # it's the label and sometimes it's the index. There are always five
753 # energies per line, though, so we can deduce if we have the labels or
754 # not just the index. In the latter case, we depend on the labels
755 # being read earlier into the list `symlabels`. Finally, if no symlabels
756 # were read that implies there is only one symmetry, namely Ag.
757 if 'A' in cols[1] or 'B' in cols[1]:
758 sym = self.normalisesym(cols[1])
759 energies = [float(t) for t in cols[2:]]
760 else:
761 if hasattr(self, 'symlabels'):
762 sym = self.normalisesym(self.symlabels[int(cols[0]) - 1])
763 else:
764 assert cols[0] == '1'
765 sym = "Ag"
766 energies = [float(t) for t in cols[1:]]
767
768 while len(energies) > 0:
769 moenergies.extend(energies)
770 mosyms.extend(len(energies)*[sym])
771 line = next(inputfile)
772 energies = [float(col) for col in line.split()]
773
774 # now sort the data about energies and symmetries. see the following post for the magic
775 # http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip
776 sdata = sorted(zip(moenergies, mosyms), key=lambda x: x[0])
777 moenergies, mosyms = zip(*sdata)
778
779 self.moenergies = [[]]
780 self.moenergies[0] = [utils.convertor(moenergy, 'hartree', 'eV') for moenergy in moenergies]
781 self.mosyms = [[]]
782 self.mosyms[0] = mosyms
783
784 if not hasattr(self, "nmo"):
785 self.nmo = self.nbasis
786 if len(self.moenergies[0]) != self.nmo:
787 self.set_attribute('nmo', len(self.moenergies[0]))
788
789 # .-----------------------------------.
790 # | >>> Final results from SIRIUS <<< |
791 # `-----------------------------------'
792 #
793 #
794 # @ Spin multiplicity: 1
795 # @ Spatial symmetry: 1 ( irrep Ag in C2h )
796 # @ Total charge of molecule: 0
797 #
798 # @ Final DFT energy: -382.050716652387
799 # @ Nuclear repulsion: 445.936979976608
800 # @ Electronic energy: -827.987696628995
801 #
802 # @ Final gradient norm: 0.000003746706
803 # ...
804 #
805 if "Final HF energy" in line and not (hasattr(self, "mpenergies") or hasattr(self, "ccenergies")):
806 self.metadata["methods"].append("HF")
807 if "Final DFT energy" in line:
808 self.metadata["methods"].append("DFT")
809 if "This is a DFT calculation of type" in line:
810 self.metadata["functional"] = line.split()[-1]
811
812 if "Final DFT energy" in line or "Final HF energy" in line:
813 if not hasattr(self, "scfenergies"):
814 self.scfenergies = []
815 temp = line.split()
816 self.scfenergies.append(utils.convertor(float(temp[-1]), "hartree", "eV"))
817
818 if "@ = MP2 second order energy" in line:
819 self.metadata["methods"].append("MP2")
820 energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')
821 if not hasattr(self, "mpenergies"):
822 self.mpenergies = []
823 self.mpenergies.append([])
824 self.mpenergies[-1].append(energ)
825
826 if "Total CCSD energy:" in line:
827 self.metadata["methods"].append("CCSD")
828 energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')
829 if not hasattr(self, "ccenergies"):
830 self.ccenergies = []
831 self.ccenergies.append(energ)
832
833 if "Total energy CCSD(T)" in line:
834 self.metadata["methods"].append("CCSD(T)")
835 energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')
836 if not hasattr(self, "ccenergies"):
837 self.ccenergies = []
838 self.ccenergies.append(energ)
839
840 # The molecular geometry requires the use of .RUN PROPERTIES in the input.
841 # Note that the second column is not the nuclear charge, but the atom type
842 # index used internally by DALTON.
843 #
844 # Molecular geometry (au)
845 # -----------------------
846 #
847 # C _1 1.3498778652 2.3494125195 0.0000000000
848 # C _2 -1.3498778652 -2.3494125195 0.0000000000
849 # C _1 2.6543517307 0.0000000000 0.0000000000
850 # ...
851 #
852 if "Molecular geometry (au)" in line:
853
854 if not hasattr(self, "atomcoords"):
855 self.atomcoords = []
856
857 if self.firststdorient:
858 self.firststdorient = False
859
860 self.skip_lines(inputfile, ['d', 'b'])
861
862 lines = [next(inputfile) for i in range(self.natom)]
863 atomcoords = self.parse_geometry(lines)
864 self.atomcoords.append(atomcoords)
865
866 if "Optimization Control Center" in line:
867 self.section = "OPT"
868 assert set(next(inputfile).strip()) == set(":")
869
870 # During geometry optimizations the geometry is printed in the section
871 # that is titles "Optimization Control Center". Note that after an optimizations
872 # finishes, DALTON normally runs another "static property section (ABACUS)",
873 # so the final geometry will be repeated in atomcoords.
874 #
875 # Next geometry (au)
876 # ------------------
877 #
878 # C _1 1.3203201560 2.3174808341 0.0000000000
879 # C _2 -1.3203201560 -2.3174808341 0.0000000000
880 # ...
881 if self.section == "OPT" and line.strip() == "Next geometry (au)":
882
883 self.skip_lines(inputfile, ['d', 'b'])
884
885 lines = [next(inputfile) for i in range(self.natom)]
886 coords = self.parse_geometry(lines)
887 self.atomcoords.append(coords)
888
889 # This section contains data for optdone and geovalues, although we could use
890 # it to double check some atttributes that were parsed before.
891 #
892 # Optimization information
893 # ------------------------
894 #
895 # Iteration number : 4
896 # End of optimization : T
897 # Energy at this geometry is : -379.777956
898 # Energy change from last geom. : -0.000000
899 # Predicted change : -0.000000
900 # Ratio, actual/predicted change : 0.952994
901 # Norm of gradient : 0.000058
902 # Norm of step : 0.000643
903 # Updated trust radius : 0.714097
904 # Total Hessian index : 0
905 #
906 if self.section == "OPT" and line.strip() == "Optimization information":
907
908 self.skip_lines(inputfile, ['d', 'b'])
909
910 line = next(inputfile)
911 assert 'Iteration number' in line
912 iteration = int(line.split()[-1])
913 line = next(inputfile)
914 assert 'End of optimization' in line
915 if not hasattr(self, 'optdone'):
916 self.optdone = []
917 self.optdone.append(line.split()[-1] == 'T')
918
919 # We need a way to map between lines here and the targets stated at the
920 # beginning of the file in 'Chosen parameters for *OPTIMI (see above),
921 # and this dictionary facilitates that. The keys are target names parsed
922 # in that initial section after input processing, and the values are
923 # substrings that should appear in the lines in this section. Make an
924 # exception for the energy at iteration zero where there is no gradient,
925 # and take the total energy for geovalues.
926 targets_labels = {
927 'gradient': 'Norm of gradient',
928 'energy': 'Energy change from last',
929 'step': 'Norm of step',
930 }
931 values = [numpy.nan] * len(self.geotargets)
932 while line.strip():
933 if iteration == 0 and "Energy at this geometry" in line:
934 index = self.geotargets_names.index('energy')
935 values[index] = self.float(line.split()[-1])
936 for tgt, lbl in targets_labels.items():
937 if lbl in line and tgt in self.geotargets_names:
938 index = self.geotargets_names.index(tgt)
939 values[index] = self.float(line.split()[-1])
940 line = next(inputfile)
941
942 # If we're missing something above, throw away the partial geovalues since
943 # we don't want artificial NaNs getting into cclib. Instead, fix the dictionary
944 # to make things work.
945 if not numpy.nan in values:
946 if not hasattr(self, 'geovalues'):
947 self.geovalues = []
948 self.geovalues.append(values)
949
950 # -------------------------------------------------
951 # extract the center of mass line
952 if "Center-of-mass coordinates (a.u.):" in line:
953 temp = line.split()
954 reference = [utils.convertor(float(temp[i]), "bohr", "Angstrom") for i in [3, 4, 5]]
955 if not hasattr(self, 'moments'):
956 self.moments = [reference]
957
958 # -------------------------------------------------
959 # Extract the dipole moment
960 if "Dipole moment components" in line:
961 dipole = numpy.zeros(3)
962 line = next(inputfile)
963 line = next(inputfile)
964 line = next(inputfile)
965 if not "zero by symmetry" in line:
966 line = next(inputfile)
967
968 line = next(inputfile)
969 temp = line.split()
970 for i in range(3):
971 dipole[i] = float(temp[2]) # store the Debye value
972 if hasattr(self, 'moments'):
973 self.moments.append(dipole)
974
975 ## 'vibfreqs', 'vibirs', and 'vibsyms' appear in ABACUS.
976 # Vibrational Frequencies and IR Intensities
977 # ------------------------------------------
978 #
979 # mode irrep frequency IR intensity
980 # ============================================================
981 # cm-1 hartrees km/mol (D/A)**2/amu
982 # ------------------------------------------------------------
983 # 1 A 3546.72 0.016160 0.000 0.0000
984 # 2 A 3546.67 0.016160 0.024 0.0006
985 # ...
986 if "Vibrational Frequencies and IR Intensities" in line:
987
988 self.skip_lines(inputfile, ['dashes', 'blank'])
989 line = next(inputfile)
990 assert line.strip() == "mode irrep frequency IR intensity"
991 self.skip_line(inputfile, 'equals')
992 line = next(inputfile)
993 assert line.strip() == "cm-1 hartrees km/mol (D/A)**2/amu"
994 self.skip_line(inputfile, 'dashes')
995 line = next(inputfile)
996
997 # The normal modes are in order of decreasing IR
998 # frequency, so they can't be added directly to
999 # attributes; they must be grouped together first, sorted
1000 # in order of increasing frequency, then added to their
1001 # respective attributes.
1002
1003 vibdata = []
1004
1005 while line.strip():
1006 sline = line.split()
1007 vibsym = sline[1]
1008 vibfreq = float(sline[2])
1009 vibir = float(sline[4])
1010 vibdata.append((vibfreq, vibir, vibsym))
1011 line = next(inputfile)
1012
1013 vibdata.sort(key=lambda normalmode: normalmode[0])
1014
1015 self.vibfreqs = [normalmode[0] for normalmode in vibdata]
1016 self.vibirs = [normalmode[1] for normalmode in vibdata]
1017 self.vibsyms = [normalmode[2] for normalmode in vibdata]
1018
1019 # Now extract the normal mode displacements.
1020 self.skip_lines(inputfile, ['b', 'b'])
1021 line = next(inputfile)
1022 assert line.strip() == "Normal Coordinates (bohrs*amu**(1/2)):"
1023
1024 # Normal Coordinates (bohrs*amu**(1/2)):
1025 # --------------------------------------
1026 #
1027 #
1028 # 1 3547 2 3547 3 3474 4 3471 5 3451
1029 # ----------------------------------------------------------------------
1030 #
1031 # C x -0.000319 -0.000314 0.002038 0.000003 -0.001599
1032 # C y -0.000158 -0.000150 -0.001446 0.003719 -0.002576
1033 # C z 0.000000 -0.000000 -0.000000 0.000000 -0.000000
1034 #
1035 # C x 0.000319 -0.000315 -0.002038 0.000003 0.001600
1036 # C y 0.000157 -0.000150 0.001448 0.003717 0.002577
1037 # ...
1038 self.skip_line(inputfile, 'd')
1039 line = next(inputfile)
1040
1041 vibdisps = numpy.empty(shape=(len(self.vibirs), self.natom, 3))
1042
1043 ndisps = 0
1044 while ndisps < len(self.vibirs):
1045 # Skip two blank lines.
1046 line = next(inputfile)
1047 line = next(inputfile)
1048 # Use the header with the normal mode indices and
1049 # frequencies to update where we are.
1050 ndisps_block = (len(line.split()) // 2)
1051 mode_min, mode_max = ndisps, ndisps + ndisps_block
1052 # Skip a line of dashes and a blank line.
1053 line = next(inputfile)
1054 line = next(inputfile)
1055 for w in range(self.natom):
1056 for coord in range(3):
1057 line = next(inputfile)
1058 vibdisps[mode_min:mode_max, w, coord] = [float(i) for i in line.split()[2:]]
1059 # Skip a blank line.
1060 line = next(inputfile)
1061 ndisps += ndisps_block
1062
1063 # The vibrational displacements are in the wrong order;
1064 # reverse them.
1065 self.vibdisps = vibdisps[::-1, :, :]
1066
1067 ## 'vibramans'
1068 # Raman related properties for freq. 0.000000 au = Infinity nm
1069 # ---------------------------------------------------------------
1070 #
1071 # Mode Freq. Alpha**2 Beta(a)**2 Pol.Int. Depol.Int. Dep. Ratio
1072 #
1073 # 1 3546.72 0.379364 16.900089 84.671721 50.700268 0.598786
1074 # 2 3546.67 0.000000 0.000000 0.000000 0.000000 0.599550
1075 if "Raman related properties for freq." in line:
1076
1077 self.skip_lines(inputfile, ['d', 'b'])
1078 line = next(inputfile)
1079 assert line[1:76] == "Mode Freq. Alpha**2 Beta(a)**2 Pol.Int. Depol.Int. Dep. Ratio"
1080 self.skip_line(inputfile, 'b')
1081 line = next(inputfile)
1082
1083 vibramans = []
1084
1085 # The Raman intensities appear under the "Pol.Int."
1086 # (polarization intensity) column.
1087 for m in range(len(self.vibfreqs)):
1088 vibramans.append(float(line.split()[4]))
1089 line = next(inputfile)
1090
1091 # All vibrational properties in DALTON appear in reverse
1092 # order.
1093 self.vibramans = vibramans[::-1]
1094
1095 # Static polarizability from **PROPERTIES/.POLARI.
1096 if line.strip() == "Static polarizabilities (au)":
1097 if not hasattr(self, 'polarizabilities'):
1098 self.polarizabilities = []
1099 polarizability = []
1100 self.skip_lines(inputfile, ['d', 'b', 'directions', 'b'])
1101 for _ in range(3):
1102 line = next(inputfile)
1103 # Separate possibly unspaced huge negative polarizability tensor
1104 # element and the left adjacent column from each other.
1105 line = line.replace('-', ' -')
1106 polarizability.append(line.split()[1:])
1107 self.polarizabilities.append(numpy.array(polarizability))
1108
1109 # Static and dynamic polarizability from **PROPERTIES/.ALPHA/*ABALNR.
1110 if "Polarizability tensor for frequency" in line:
1111 if not hasattr(self, 'polarizabilities'):
1112 self.polarizabilities = []
1113 polarizability = []
1114 self.skip_lines(inputfile, ['d', 'directions', 'b'])
1115 for _ in range(3):
1116 line = next(inputfile)
1117 polarizability.append(line.split()[1:])
1118 self.polarizabilities.append(numpy.array(polarizability))
1119
1120 if "Starting in Dynamic Property Section (RESPONS)" in line:
1121 self.section = "RESPONSE"
1122
1123 # Static and dynamic polarizability from **RESPONSE/*LINEAR.
1124 # This section is *very* general and will need to be expanded later.
1125 # For now, only form the matrix from dipole (length gauge) values.
1126 if "@ FREQUENCY INDEPENDENT SECOND ORDER PROPERTIES" in line:
1127
1128 coord_to_idx = {'X': 0, 'Y': 1, 'Z': 2}
1129
1130 self.skip_line(inputfile, 'b')
1131 line = next(inputfile)
1132
1133 polarizability_diplen = numpy.empty(shape=(3, 3)) * numpy.nan
1134 while "Time used in linear response calculation is" not in line:
1135 tokens = line.split()
1136 if line.count("DIPLEN") == 2:
1137 assert len(tokens) == 8
1138 if not hasattr(self, 'polarizabilities'):
1139 self.polarizabilities = []
1140 i, j = coord_to_idx[tokens[2][0]], coord_to_idx[tokens[4][0]]
1141 polarizability_diplen[i, j] = self.float(tokens[7])
1142 line = next(inputfile)
1143
1144 polarizability_diplen = utils.symmetrize(polarizability_diplen, use_triangle='upper')
1145 if hasattr(self, 'polarizabilities'):
1146 self.polarizabilities.append(polarizability_diplen)
1147
1148 ## Electronic excitations: single residues of the linear response
1149 ## equations.
1150 #
1151 #
1152 # @ Excited state no: 1 in symmetry 3 ( Bu )
1153 # ----------------------------------------------
1154 #
1155 # @ Excitation energy : 0.19609400 au
1156 # @ 5.3359892 eV; 43037.658 cm-1; 514.84472 kJ / mol
1157 #
1158 # @ Total energy : -381.85462 au
1159 #
1160 # @ Operator type: XDIPLEN
1161 # @ Oscillator strength (LENGTH) : 8.93558787E-03 (Transition moment : 0.26144181 )
1162 #
1163 # @ Operator type: YDIPLEN
1164 # @ Oscillator strength (LENGTH) : 0.15204812 (Transition moment : 1.0784599 )
1165 #
1166 # Eigenvector for state no. 1
1167 #
1168 # Response orbital operator symmetry = 3
1169 # (only scaled elements abs greater than 10.00 % of max abs value)
1170 #
1171 # Index(r,s) r s (r s) operator (s r) operator (r s) scaled (s r) scaled
1172 # ---------- ----- ----- -------------- -------------- -------------- --------------
1173 # 308 57(4) 28(2) 0.4829593728 -0.0024872024 0.6830076950 -0.0035174354
1174 # ...
1175 if "Linear Response single residue calculation" in line:
1176
1177 etsyms = []
1178 etenergies = []
1179 etsecs = []
1180 etoscs = dict()
1181 etoscs_keys = set()
1182
1183 symmap = {"T": "Triplet", "F": "Singlet"}
1184
1185 while "End of Dynamic Property Section (RESPONS)" not in line:
1186
1187 line = next(inputfile)
1188
1189 if "Operator symmetry" in line:
1190 do_triplet = line[-2]
1191
1192 # @ Excited state no: 4 in symmetry 2 ( Au )
1193 if line.startswith(" @ Excited state no:"):
1194 tokens = line.split()
1195 excited_state_num_in_sym = int(tokens[4])
1196 sym_num = int(tokens[7])
1197 etosc_key = (sym_num, excited_state_num_in_sym)
1198 etoscs_keys.add(etosc_key)
1199 etsym = tokens[9]
1200 etsyms.append(symmap[do_triplet] + "-" + etsym)
1201 self.skip_lines(inputfile, ["d", "b", "Excitation energy in a.u."])
1202 line = next(inputfile)
1203 etenergies.append(self.float(line.split()[3]))
1204 self.skip_lines(inputfile, ["b", "@ Total energy", "b"])
1205
1206 if line.startswith("@ Operator type:"):
1207 line = next(inputfile)
1208 assert line.startswith("@ Oscillator strength")
1209 if etosc_key not in etoscs:
1210 etoscs[etosc_key] = 0.0
1211 etoscs[etosc_key] += self.float(line.split()[5])
1212 self.skip_line(inputfile, "b")
1213
1214 # To understand why the "PBHT MO Overlap Diagnostic" section
1215 # cannot be used, see
1216 # `test/regression.py/testDALTON_DALTON_2013_dvb_td_normalprint_out`.
1217 if "Eigenvector for state no." in line:
1218 assert int(line.split()[4]) == excited_state_num_in_sym
1219 self.skip_lines(inputfile, [
1220 "b",
1221 "Response orbital operator symmetry",
1222 "only scaled elements",
1223 "b",
1224 "Index(r,s)",
1225 "d"
1226 ])
1227 line = next(inputfile)
1228 etsec = []
1229 while line.strip():
1230 tokens = line.split()
1231 startidx = int(tokens[1].split("(")[0]) - 1
1232 endidx = int(tokens[2].split("(")[0]) - 1
1233 # `(r s) scaled`; to handle anything other than
1234 # CIS/TDA properly, the deexcitation coefficient `(s
1235 # r) scaled` should also be considered, but this
1236 # requires a rework of the attribute structure.
1237 contrib = float(tokens[5])
1238 # Since DALTON is restricted open-shell only, there is
1239 # no distinction between alpha and beta spin.
1240 etsec.append([(startidx, 0), (endidx, 0), contrib])
1241 line = next(inputfile)
1242 etsecs.append(etsec)
1243
1244 self.set_attribute("etsyms", etsyms)
1245 self.set_attribute("etenergies", etenergies)
1246 if etsecs:
1247 self.set_attribute("etsecs", etsecs)
1248 if etoscs:
1249 for k in etoscs_keys:
1250 # If the oscillator strength of a transition is known to
1251 # be zero for symmetry reasons, it isn't printed, however
1252 # we need it for consistency; if it wasn't found, add it.
1253 if k not in etoscs:
1254 etoscs[k] = 0.0
1255 # `.keys()` is not strictly necessary, but make it obvious
1256 # that this is being sorted in order of excitation and
1257 # symmetry, not oscillator strength.
1258 self.set_attribute("etoscs", [etoscs[k] for k in sorted(etoscs.keys())])
1259
1260 if line[:37] == ' >>>> Total wall time used in DALTON:':
1261 self.metadata['success'] = True
1262
1263 # TODO:
1264 # aonames
1265 # aooverlaps
1266 # atomcharges
1267 # atomspins
1268 # coreelectrons
1269 # enthalpy
1270 # entropy
1271 # etrotats
1272 # freeenergy
1273 # grads
1274 # hessian
1275 # mocoeffs
1276 # nocoeffs
1277 # nooccnos
1278 # scancoords
1279 # scanenergies
1280 # scannames
1281 # scanparm
1282 # temperature
1283 # vibanharms
1284
1285 # N/A:
1286 # fonames
1287 # fooverlaps
1288 # fragnames
1289 # frags