Debian Codegraph @

cclib/parser/molproparser.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2019, the cclib development team
4 #
5 # This file is part of cclib (http://cclib.github.io) and is distributed under
6 # the terms of the BSD 3-Clause License.
7
8 """Parser for Molpro output files"""
9
10
11 import itertools
12
13 import numpy
14
15 from cclib.parser import logfileparser
16 from cclib.parser import utils
17
18
19 def create_atomic_orbital_names(orbitals):
20 """Generate all atomic orbital names that could be used by Molpro.
21
22 The names are returned in a dictionary, organized by subshell (S, P, D and so on).
23 """
24
25 # We can write out the first two manually, since there are not that many.
26 atomic_orbital_names = {
27 'S': ['s', '1s'],
28 'P': ['x', 'y', 'z', '2px', '2py', '2pz'],
29 }
30
31 # Although we could write out all names for the other subshells, it is better
32 # to generate them if we need to expand further, since the number of functions quickly
33 # grows and there are both Cartesian and spherical variants to consider.
34 # For D orbitals, the Cartesian functions are xx, yy, zz, xy, xz and yz, and the
35 # spherical ones are called 3d0, 3d1-, 3d1+, 3d2- and 3d2+. For F orbitals, the Cartesians
36 # are xxx, xxy, xxz, xyy, ... and the sphericals are 4f0, 4f1-, 4f+ and so on.
37 for i, orb in enumerate(orbitals):
38
39 # Cartesian can be generated directly by combinations.
40 cartesian = list(map(''.join, list(itertools.combinations_with_replacement(['x', 'y', 'z'], i+2))))
41
42 # For spherical functions, we need to construct the names.
43 pre = str(i+3) + orb.lower()
44 spherical = [pre + '0'] + [pre + str(j) + s for j in range(1, i+3) for s in ['-', '+']]
45 atomic_orbital_names[orb] = cartesian + spherical
46
47 return atomic_orbital_names
48
49
50 class Molpro(logfileparser.Logfile):
51 """Molpro file parser"""
52
53 atomic_orbital_names = create_atomic_orbital_names(['D', 'F', 'G'])
54
55 def __init__(self, *args, **kwargs):
56 # Call the __init__ method of the superclass
57 super(Molpro, self).__init__(logname="Molpro", *args, **kwargs)
58
59 def __str__(self):
60 """Return a string representation of the object."""
61 return "Molpro log file %s" % (self.filename)
62
63 def __repr__(self):
64 """Return a representation of the object."""
65 return 'Molpro("%s")' % (self.filename)
66
67 def normalisesym(self, label):
68 """Normalise the symmetries used by Molpro."""
69 ans = label.replace("`", "'").replace("``", "''")
70 return ans
71
72 def before_parsing(self):
73
74 self.electronorbitals = ""
75 self.insidescf = False
76
77 def after_parsing(self):
78
79 # If optimization thresholds are default, they are normally not printed and we need
80 # to set them to the default after parsing. Make sure to set them in the same order that
81 # they appear in the in the geometry optimization progress printed in the output,
82 # namely: energy difference, maximum gradient, maximum step.
83 if not hasattr(self, "geotargets"):
84 self.geotargets = []
85 # Default THRENERG (required accuracy of the optimized energy).
86 self.geotargets.append(1E-6)
87 # Default THRGRAD (required accuracy of the optimized gradient).
88 self.geotargets.append(3E-4)
89 # Default THRSTEP (convergence threshold for the geometry optimization step).
90 self.geotargets.append(3E-4)
91
92 def _parse_orbitals(self, inputfile, line):
93 # From this block aonames, atombasis, moenergies and mocoeffs can be parsed. The data is
94 # flipped compared to most programs (GAMESS, Gaussian), since the MOs are in rows. Also, Molpro
95 # does not cut the table into parts, rather each MO row has as many lines as it takes ro print
96 # all of the MO coefficients. Each row normally has 10 coefficients, although this can be less
97 # for the last row and when symmetry is used (each irrep has its own block).
98 #
99 # ELECTRON ORBITALS
100 # =================
101 #
102 #
103 # Orb Occ Energy Couls-En Coefficients
104 #
105 # 1 1s 1 1s 1 2px 1 2py 1 2pz 2 1s (...)
106 # 3 1s 3 1s 3 2px 3 2py 3 2pz 4 1s (...)
107 # (...)
108 #
109 # 1.1 2 -11.0351 -43.4915 0.701460 0.025696 -0.000365 -0.000006 0.000000 0.006922 (...)
110 # -0.006450 0.004742 -0.001028 -0.002955 0.000000 -0.701460 (...)
111 # (...)
112 #
113 # If an MCSCF calculation was performed, the natural orbitals
114 # (coefficients and occupation numbers) are printed in a
115 # format nearly identical to the ELECTRON ORBITALS section.
116 #
117 # NATURAL ORBITALS (state averaged)
118 # =================================
119 #
120 # Orb Occ Energy Coefficients
121 #
122 # 1 s 1 s 1 s 1 z 1 z 1 xx 1 yy 1 zz 2 s 2 s
123 # 2 s 2 z 2 z 2 xx 2 yy 2 zz 3 s 3 s 3 z 3 y
124 #
125 # 1.1 2.00000 -20.678730 0.000141 -0.000057 0.001631 -0.001377 0.001117 0.000029 0.000293 -0.000852 1.000748 0.001746
126 # -0.002552 -0.002005 0.001658 -0.001266 -0.001274 -0.001001 0.000215 -0.000131 -0.000242 -0.000126
127 #
128 # 2.1 2.00000 -11.322823 1.000682 0.004626 -0.000485 0.006634 -0.002096 -0.003072 -0.003282 -0.001724 -0.000181 0.006734
129 # -0.002398 -0.000527 0.001335 0.000091 0.000058 0.000396 -0.003219 0.000981 0.000250 -0.000191
130 # (...)
131
132 # The assigment of final cclib attributes is different for
133 # canonical/natural orbitals.
134 self.naturalorbitals = (line[1:17] == "NATURAL ORBITALS")
135 # Make sure we didn't get here by mistake.
136 assert line[1:18] == "ELECTRON ORBITALS" or self.electronorbitals or self.naturalorbitals
137
138 # For unrestricted calculations, ELECTRON ORBITALS is followed on the same line
139 # by FOR POSITIVE SPIN or FOR NEGATIVE SPIN as appropriate.
140 spin = (line[19:36] == "FOR NEGATIVE SPIN") or (self.electronorbitals[19:36] == "FOR NEGATIVE SPIN")
141
142 if self.naturalorbitals:
143 self.skip_lines(inputfile, ['equals', 'b', 'headers', 'b'])
144 else:
145 if not self.electronorbitals:
146 self.skip_line(inputfile, 'equals')
147 self.skip_lines(inputfile, ['b', 'b', 'headers', 'b'])
148
149 aonames = []
150 atombasis = [[] for i in range(self.natom)]
151 moenergies = []
152 # Use for both canonical and natural orbital coefficients.
153 mocoeffs = []
154 occnos = []
155 line = next(inputfile)
156
157 # Besides a double blank line, stop when the next orbitals are encountered for unrestricted jobs
158 # or if there are stars on the line which always signifies the end of the block.
159 while line.strip() and (not "ORBITALS" in line) and (not set(line.strip()) == {'*'}):
160
161 # The function names are normally printed just once, but if symmetry is used then each irrep
162 # has its own mocoeff block with a preceding list of names.
163 is_aonames = line[:25].strip() == ""
164 if is_aonames:
165
166 # We need to save this offset for parsing the coefficients later.
167 offset = len(aonames)
168
169 aonum = len(aonames)
170 while line.strip():
171 for s in line.split():
172 if s.isdigit():
173 atomno = int(s)
174 atombasis[atomno-1].append(aonum)
175 aonum += 1
176 else:
177 functype = s
178 element = self.table.element[self.atomnos[atomno-1]]
179 aoname = "%s%i_%s" % (element, atomno, functype)
180 aonames.append(aoname)
181 line = next(inputfile)
182
183 # Now there can be one or two blank lines.
184 while not line.strip():
185 line = next(inputfile)
186
187 # Newer versions of Molpro (for example, 2012 test files) will print some
188 # more things here, such as HOMO and LUMO, but these have less than 10 columns.
189 if "HOMO" in line or "LUMO" in line:
190 break
191
192 # End of the NATURAL ORBITALS section.
193 if "Natural orbital dump" in line:
194 break
195
196 # Now parse the MO coefficients, padding the list with an appropriate amount of zeros.
197 coeffs = [0.0 for i in range(offset)]
198 while line.strip() != "":
199 if line[:31].rstrip():
200 tokens = line.split()
201 moenergy = float(tokens[2])
202 moenergy = utils.convertor(moenergy, "hartree", "eV")
203 moenergies.append(moenergy)
204 if self.naturalorbitals:
205 occno = float(tokens[1])
206 occnos.append(occno)
207
208 # Coefficients are in 10.6f format and splitting does not work since there are not
209 # always spaces between them. If the numbers are very large, there will be stars.
210 str_coeffs = line[31:]
211 ncoeffs = len(str_coeffs) // 10
212 coeff = []
213 for ic in range(ncoeffs):
214 p = str_coeffs[ic*10:(ic+1)*10]
215 try:
216 c = float(p)
217 except ValueError as detail:
218 self.logger.warn("setting coeff element to zero: %s" % detail)
219 c = 0.0
220 coeff.append(c)
221 coeffs.extend(coeff)
222 line = next(inputfile)
223 mocoeffs.append(coeffs)
224
225 # The loop should keep going until there is a double blank line, and there is
226 # a single line between each coefficient block.
227 line = next(inputfile)
228 if not line.strip():
229 line = next(inputfile)
230
231 # If symmetry was used (offset was needed) then we will need to pad all MO vectors
232 # up to nbasis for all irreps before the last one.
233 if offset > 0:
234 for im, m in enumerate(mocoeffs):
235 if len(m) < self.nbasis:
236 mocoeffs[im] = m + [0.0 for i in range(self.nbasis - len(m))]
237
238 self.set_attribute('atombasis', atombasis)
239 self.set_attribute('aonames', aonames)
240
241 if self.naturalorbitals:
242 # Consistent with current cclib conventions, keep only the
243 # last possible set of natural orbital coefficients and
244 # occupation numbers.
245 self.nocoeffs = mocoeffs
246 self.nooccnos = occnos
247 else:
248 # Consistent with current cclib conventions, reset moenergies/mocoeffs if they have been
249 # previously parsed, since we want to produce only the final values.
250 if not hasattr(self, "moenergies") or spin == 0:
251 self.mocoeffs = []
252 self.moenergies = []
253 self.moenergies.append(moenergies)
254 self.mocoeffs.append(mocoeffs)
255
256 # Check if last line begins the next ELECTRON ORBITALS section, because we already used
257 # this line and need to know when this method is called next time.
258 if line[1:18] == "ELECTRON ORBITALS":
259 self.electronorbitals = line
260 else:
261 self.electronorbitals = ""
262
263 return
264
265 def extract(self, inputfile, line):
266 """Extract information from the file object inputfile."""
267
268 # Extract the package version number.
269 if "Version" in line:
270 self.metadata["package_version"] = line.split()[1]
271
272 if line[1:19] == "ATOMIC COORDINATES":
273
274 if not hasattr(self, "atomcoords"):
275 self.atomcoords = []
276
277 atomcoords = []
278 atomnos = []
279
280 self.skip_lines(inputfile, ['line', 'line', 'line'])
281
282 line = next(inputfile)
283 while line.strip():
284 temp = line.strip().split()
285 atomcoords.append([utils.convertor(float(x), "bohr", "Angstrom") for x in temp[3:6]]) # bohrs to angs
286 atomnos.append(int(round(float(temp[2]))))
287 line = next(inputfile)
288
289 self.atomcoords.append(atomcoords)
290
291 self.set_attribute('atomnos', atomnos)
292 self.set_attribute('natom', len(self.atomnos))
293
294 # Use BASIS DATA to parse input for gbasis, aonames and atombasis. If symmetry is used,
295 # the function number starts from 1 for each irrep (the irrep index comes after the dot).
296 #
297 # BASIS DATA
298 #
299 # Nr Sym Nuc Type Exponents Contraction coefficients
300 #
301 # 1.1 A 1 1s 71.616837 0.154329
302 # 13.045096 0.535328
303 # 3.530512 0.444635
304 # 2.1 A 1 1s 2.941249 -0.099967
305 # 0.683483 0.399513
306 # ...
307 #
308 if line[1:11] == "BASIS DATA":
309
310 # We can do a sanity check with the header.
311 self.skip_line(inputfile, 'blank')
312 header = next(inputfile)
313 assert header.split() == ["Nr", "Sym", "Nuc", "Type", "Exponents", "Contraction", "coefficients"]
314 self.skip_line(inputfile, 'blank')
315
316 aonames = []
317 atombasis = [[] for i in range(self.natom)]
318 gbasis = [[] for i in range(self.natom)]
319 while line.strip():
320
321 # We need to read the line at the start of the loop here, because the last function
322 # will be added when a blank line signalling the end of the block is encountered.
323 line = next(inputfile)
324
325 # The formatting here can exhibit subtle differences, including the number of spaces
326 # or indentation size. However, we will rely on explicit slices since not all components
327 # are always available. In fact, components not being there has some meaning (see below).
328 line_nr = line[1:6].strip()
329 line_sym = line[7:9].strip()
330 line_nuc = line[11:15].strip()
331 line_type = line[16:22].strip()
332 line_exp = line[25:38].strip()
333 line_coeffs = line[38:].strip()
334
335 # If a new function type is printed or the BASIS DATA block ends with a blank line,
336 # then add the previous function to gbasis, except for the first function since
337 # there was no preceeding one. When translating the Molpro function name to gbasis,
338 # note that Molpro prints all components, but we want it only once, with the proper
339 # shell type (S,P,D,F,G). Molpro names also differ between Cartesian/spherical representations.
340 if (line_type and aonames) or line.strip() == "":
341
342 # All the possible AO names are created with the class. The function should always
343 # find a match in that dictionary, so we can check for that here and will need to
344 # update the dict if something unexpected comes up.
345 funcbasis = None
346 for fb, names in self.atomic_orbital_names.items():
347 if functype in names:
348 funcbasis = fb
349 assert funcbasis
350
351 # There is a separate basis function for each column of contraction coefficients. Since all
352 # atomic orbitals for a subshell will have the same parameters, we can simply check if
353 # the function tuple is already in gbasis[i] before adding it.
354 for i in range(len(coefficients[0])):
355
356 func = (funcbasis, [])
357 for j in range(len(exponents)):
358 func[1].append((exponents[j], coefficients[j][i]))
359 if func not in gbasis[funcatom-1]:
360 gbasis[funcatom-1].append(func)
361
362 # If it is a new type, set up the variables for the next shell(s). An exception is symmetry functions,
363 # which we want to copy from the previous function and don't have a new number on the line. For them,
364 # we just want to update the nuclear index.
365 if line_type:
366 if line_nr:
367 exponents = []
368 coefficients = []
369 functype = line_type
370 funcatom = int(line_nuc)
371
372 # Add any exponents and coefficients to lists.
373 if line_exp and line_coeffs:
374 funcexp = float(line_exp)
375 funccoeffs = [float(s) for s in line_coeffs.split()]
376 exponents.append(funcexp)
377 coefficients.append(funccoeffs)
378
379 # If the function number is present then add to atombasis and aonames, which is different from
380 # adding to gbasis since it enumerates AOs rather than basis functions. The number counts functions
381 # in each irrep from 1 and we could add up the functions for each irrep to get the global count,
382 # but it is simpler to just see how many aonames we have already parsed. Any symmetry functions
383 # are also printed, but they don't get numbers so they are nor parsed.
384 if line_nr:
385 element = self.table.element[self.atomnos[funcatom-1]]
386 aoname = "%s%i_%s" % (element, funcatom, functype)
387 aonames.append(aoname)
388 funcnr = len(aonames)
389 atombasis[funcatom-1].append(funcnr-1)
390
391 self.set_attribute('aonames', aonames)
392 self.set_attribute('atombasis', atombasis)
393 self.set_attribute('gbasis', gbasis)
394
395 if line[1:23] == "NUMBER OF CONTRACTIONS":
396 nbasis = int(line.split()[3])
397 self.set_attribute('nbasis', nbasis)
398
399 # Basis set name
400 if line[1:8] == "Library":
401 self.metadata["basis_set"] = line.split()[4]
402
403 # This is used to signalize whether we are inside an SCF calculation.
404 if line[1:8] == "PROGRAM" and line[14:18] == "-SCF":
405
406 self.insidescf = True
407 self.metadata["methods"].append("HF")
408
409 # Use this information instead of 'SETTING ...', in case the defaults are standard.
410 # Note that this is sometimes printed in each geometry optimization step.
411 if line[1:20] == "NUMBER OF ELECTRONS":
412
413 spinup = int(line.split()[3][:-1])
414 spindown = int(line.split()[4][:-1])
415 # Nuclear charges (atomnos) should be parsed by now.
416 nuclear = numpy.sum(self.atomnos)
417
418 charge = nuclear - spinup - spindown
419 self.set_attribute('charge', charge)
420
421 mult = spinup - spindown + 1
422 self.set_attribute('mult', mult)
423
424 # Convergenve thresholds for SCF cycle, should be contained in a line such as:
425 # CONVERGENCE THRESHOLDS: 1.00E-05 (Density) 1.40E-07 (Energy)
426 if self.insidescf and line[1:24] == "CONVERGENCE THRESHOLDS:":
427
428 if not hasattr(self, "scftargets"):
429 self.scftargets = []
430
431 scftargets = list(map(float, line.split()[2::2]))
432 self.scftargets.append(scftargets)
433 # Usually two criteria, but save the names this just in case.
434 self.scftargetnames = line.split()[3::2]
435
436 # Read in the print out of the SCF cycle - for scfvalues. For RHF looks like:
437 # ITERATION DDIFF GRAD ENERGY 2-EL.EN. DIPOLE MOMENTS DIIS
438 # 1 0.000D+00 0.000D+00 -379.71523700 1159.621171 0.000000 0.000000 0.000000 0
439 # 2 0.000D+00 0.898D-02 -379.74469736 1162.389787 0.000000 0.000000 0.000000 1
440 # 3 0.817D-02 0.144D-02 -379.74635529 1162.041033 0.000000 0.000000 0.000000 2
441 # 4 0.213D-02 0.571D-03 -379.74658063 1162.159929 0.000000 0.000000 0.000000 3
442 # 5 0.799D-03 0.166D-03 -379.74660889 1162.144256 0.000000 0.000000 0.000000 4
443 if self.insidescf and line[1:10] == "ITERATION":
444
445 if not hasattr(self, "scfvalues"):
446 self.scfvalues = []
447
448 line = next(inputfile)
449 energy = 0.0
450 scfvalues = []
451 while line.strip() != "":
452 chomp = line.split()
453 if chomp[0].isdigit():
454
455 ddiff = float(chomp[1].replace('D', 'E'))
456 grad = float(chomp[2].replace('D', 'E'))
457 newenergy = float(chomp[3])
458 ediff = newenergy - energy
459 energy = newenergy
460
461 # The convergence thresholds must have been read above.
462 # Presently, we recognize MAX DENSITY and MAX ENERGY thresholds.
463 numtargets = len(self.scftargetnames)
464 values = [numpy.nan]*numtargets
465 for n, name in zip(list(range(numtargets)), self.scftargetnames):
466 if "ENERGY" in name.upper():
467 values[n] = ediff
468 elif "DENSITY" in name.upper():
469 values[n] = ddiff
470 scfvalues.append(values)
471
472 try:
473 line = next(inputfile)
474 except StopIteration:
475 self.logger.warning('File terminated before end of last SCF! Last gradient: {}'.format(grad))
476 break
477 self.scfvalues.append(numpy.array(scfvalues))
478
479 # SCF result - RHF/UHF and DFT (RKS) energies.
480 if (line[1:5] in ["!RHF", "!UHF", "!RKS"] and line[16:22].lower() == "energy"):
481
482 if not hasattr(self, "scfenergies"):
483 self.scfenergies = []
484 scfenergy = float(line.split()[4])
485 self.scfenergies.append(utils.convertor(scfenergy, "hartree", "eV"))
486
487 # We are now done with SCF cycle (after a few lines).
488 self.insidescf = False
489
490 # MP2 energies.
491 if line[1:5] == "!MP2":
492
493 self.metadata["methods"].append("MP2")
494
495 if not hasattr(self, 'mpenergies'):
496 self.mpenergies = []
497 mp2energy = float(line.split()[-1])
498 mp2energy = utils.convertor(mp2energy, "hartree", "eV")
499 self.mpenergies.append([mp2energy])
500
501 # MP2 energies if MP3 or MP4 is also calculated.
502 if line[1:5] == "MP2:":
503
504 self.metadata["methods"].append("MP2")
505 if not hasattr(self, 'mpenergies'):
506 self.mpenergies = []
507 mp2energy = float(line.split()[2])
508 mp2energy = utils.convertor(mp2energy, "hartree", "eV")
509 self.mpenergies.append([mp2energy])
510
511 # MP3 (D) and MP4 (DQ or SDQ) energies.
512 if line[1:8] == "MP3(D):":
513
514 self.metadata["methods"].append("MP3")
515 mp3energy = float(line.split()[2])
516 mp2energy = utils.convertor(mp3energy, "hartree", "eV")
517 line = next(inputfile)
518 self.mpenergies[-1].append(mp2energy)
519 if line[1:9] == "MP4(DQ):":
520 self.metadata["methods"].append("MP4")
521 mp4energy = float(line.split()[2])
522 line = next(inputfile)
523 if line[1:10] == "MP4(SDQ):":
524 self.metadata["methods"].append("MP4")
525 mp4energy = float(line.split()[2])
526 mp4energy = utils.convertor(mp4energy, "hartree", "eV")
527 self.mpenergies[-1].append(mp4energy)
528
529 # The CCSD program operates all closed-shel coupled cluster runs.
530 if line[1:15] == "PROGRAM * CCSD":
531
532 self.metadata["methods"].append("CCSD")
533 if not hasattr(self, "ccenergies"):
534 self.ccenergies = []
535 while line[1:20] != "Program statistics:":
536 # The last energy (most exact) will be read last and thus saved.
537 if line[1:5] == "!CCD" or line[1:6] == "!CCSD" or line[1:9] == "!CCSD(T)":
538 ccenergy = float(line.split()[-1])
539 ccenergy = utils.convertor(ccenergy, "hartree", "eV")
540 line = next(inputfile)
541 self.ccenergies.append(ccenergy)
542
543 # Read the occupancy (index of HOMO s).
544 # For restricted calculations, there is one line here. For unrestricted, two:
545 # Final alpha occupancy: ...
546 # Final beta occupancy: ...
547 if line[1:17] == "Final occupancy:":
548 self.homos = [int(line.split()[-1])-1]
549 if line[1:23] == "Final alpha occupancy:":
550 self.homos = [int(line.split()[-1])-1]
551 line = next(inputfile)
552 self.homos.append(int(line.split()[-1])-1)
553
554 # Dipole is always printed on one line after the final RHF energy, and by default
555 # it seems Molpro uses the origin as the reference point.
556 if line.strip()[:13] == "Dipole moment":
557
558 assert line.split()[2] == "/Debye"
559
560 reference = [0.0, 0.0, 0.0]
561 dipole = [float(d) for d in line.split()[-3:]]
562
563 if not hasattr(self, 'moments'):
564 self.moments = [reference, dipole]
565 else:
566 self.moments[1] == dipole
567
568 # Static dipole polarizability.
569 if line.strip() == "SCF dipole polarizabilities":
570 if not hasattr(self, "polarizabilities"):
571 self.polarizabilities = []
572 polarizability = []
573 self.skip_lines(inputfile, ['b', 'directions'])
574 for _ in range(3):
575 line = next(inputfile)
576 polarizability.append(line.split()[1:])
577 self.polarizabilities.append(numpy.array(polarizability))
578
579 # Check for ELECTRON ORBITALS (canonical molecular orbitals).
580 if line[1:18] == "ELECTRON ORBITALS" or self.electronorbitals:
581 self._parse_orbitals(inputfile, line)
582
583
584 # If the MATROP program was called appropriately,
585 # the atomic obital overlap matrix S is printed.
586 # The matrix is printed straight-out, ten elements in each row, both halves.
587 # Note that is the entire matrix is not printed, then aooverlaps
588 # will not have dimensions nbasis x nbasis.
589 if line[1:9] == "MATRIX S":
590
591 if not hasattr(self, "aooverlaps"):
592 self.aooverlaps = [[]]
593
594 self.skip_lines(inputfile, ['b', 'symblocklabel'])
595
596 line = next(inputfile)
597 while line.strip() != "":
598 elements = [float(s) for s in line.split()]
599 if len(self.aooverlaps[-1]) + len(elements) <= self.nbasis:
600 self.aooverlaps[-1] += elements
601 else:
602 n = len(self.aooverlaps[-1]) + len(elements) - self.nbasis
603 self.aooverlaps[-1] += elements[:-n]
604 self.aooverlaps.append([])
605 self.aooverlaps[-1] += elements[-n:]
606 line = next(inputfile)
607
608 # Check for MCSCF natural orbitals.
609 if line[1:17] == "NATURAL ORBITALS":
610 self._parse_orbitals(inputfile, line)
611
612 # Thresholds are printed only if the defaults are changed with GTHRESH.
613 # In that case, we can fill geotargets with non-default values.
614 # The block should look like this as of Molpro 2006.1:
615 # THRESHOLDS:
616
617 # ZERO = 1.00D-12 ONEINT = 1.00D-12 TWOINT = 1.00D-11 PREFAC = 1.00D-14 LOCALI = 1.00D-09 EORDER = 1.00D-04
618 # ENERGY = 0.00D+00 ETEST = 0.00D+00 EDENS = 0.00D+00 THRDEDEF= 1.00D-06 GRADIENT= 1.00D-02 STEP = 1.00D-03
619 # ORBITAL = 1.00D-05 CIVEC = 1.00D-05 COEFF = 1.00D-04 PRINTCI = 5.00D-02 PUNCHCI = 9.90D+01 OPTGRAD = 3.00D-04
620 # OPTENERG= 1.00D-06 OPTSTEP = 3.00D-04 THRGRAD = 2.00D-04 COMPRESS= 1.00D-11 VARMIN = 1.00D-07 VARMAX = 1.00D-03
621 # THRDOUB = 0.00D+00 THRDIV = 1.00D-05 THRRED = 1.00D-07 THRPSP = 1.00D+00 THRDC = 1.00D-10 THRCS = 1.00D-10
622 # THRNRM = 1.00D-08 THREQ = 0.00D+00 THRDE = 1.00D+00 THRREF = 1.00D-05 SPARFAC = 1.00D+00 THRDLP = 1.00D-07
623 # THRDIA = 1.00D-10 THRDLS = 1.00D-07 THRGPS = 0.00D+00 THRKEX = 0.00D+00 THRDIS = 2.00D-01 THRVAR = 1.00D-10
624 # THRLOC = 1.00D-06 THRGAP = 1.00D-06 THRLOCT = -1.00D+00 THRGAPT = -1.00D+00 THRORB = 1.00D-06 THRMLTP = 0.00D+00
625 # THRCPQCI= 1.00D-10 KEXTA = 0.00D+00 THRCOARS= 0.00D+00 SYMTOL = 1.00D-06 GRADTOL = 1.00D-06 THROVL = 1.00D-08
626 # THRORTH = 1.00D-08 GRID = 1.00D-06 GRIDMAX = 1.00D-03 DTMAX = 0.00D+00
627 if line[1:12] == "THRESHOLDS":
628
629 self.skip_line(input, 'blank')
630
631 line = next(inputfile)
632 while line.strip():
633
634 if "OPTENERG" in line:
635 start = line.find("OPTENERG")
636 optenerg = line[start+10:start+20]
637 if "OPTGRAD" in line:
638 start = line.find("OPTGRAD")
639 optgrad = line[start+10:start+20]
640 if "OPTSTEP" in line:
641 start = line.find("OPTSTEP")
642 optstep = line[start+10:start+20]
643 line = next(inputfile)
644
645 self.geotargets = [optenerg, optgrad, optstep]
646
647 # The optimization history is the source for geovlues:
648 #
649 # END OF GEOMETRY OPTIMIZATION. TOTAL CPU: 246.9 SEC
650 #
651 # ITER. ENERGY(OLD) ENERGY(NEW) DE GRADMAX GRADNORM GRADRMS STEPMAX STEPLEN STEPRMS
652 # 1 -382.02936898 -382.04914450 -0.01977552 0.11354875 0.20127947 0.01183997 0.12972761 0.20171740 0.01186573
653 # 2 -382.04914450 -382.05059234 -0.00144784 0.03299860 0.03963339 0.00233138 0.05577169 0.06687650 0.00393391
654 # 3 -382.05059234 -382.05069136 -0.00009902 0.00694359 0.01069889 0.00062935 0.01654549 0.02016307 0.00118606
655 # ...
656 #
657 # The above is an exerpt from Molpro 2006, but it is a little bit different
658 # for Molpro 2012, namely the 'END OF GEOMETRY OPTIMIZATION occurs after the
659 # actual history list. It seems there is a another consistent line before the
660 # history, but this might not be always true -- so this is a potential weak link.
661 if line[1:30] == "END OF GEOMETRY OPTIMIZATION." or line.strip() == "Quadratic Steepest Descent - Minimum Search":
662
663 # I think this is the trigger for convergence, and it shows up at the top in Molpro 2006.
664 geometry_converged = line[1:30] == "END OF GEOMETRY OPTIMIZATION."
665
666 self.skip_line(inputfile, 'blank')
667
668 # Newer version of Molpro (at least for 2012) print and additional column
669 # with the timing information for each step. Otherwise, the history looks the same.
670 headers = next(inputfile).split()
671 if not len(headers) in (10, 11):
672 return
673
674 # Although criteria can be changed, the printed format should not change.
675 # In case it does, retrieve the columns for each parameter.
676 index_ITER = headers.index('ITER.')
677 index_THRENERG = headers.index('DE')
678 index_THRGRAD = headers.index('GRADMAX')
679 index_THRSTEP = headers.index('STEPMAX')
680
681 line = next(inputfile)
682 self.geovalues = []
683 while line.strip():
684
685 line = line.split()
686 istep = int(line[index_ITER])
687
688 geovalues = []
689 geovalues.append(float(line[index_THRENERG]))
690 geovalues.append(float(line[index_THRGRAD]))
691 geovalues.append(float(line[index_THRSTEP]))
692 self.geovalues.append(geovalues)
693 line = next(inputfile)
694 if line.strip() == "Freezing grid":
695 line = next(inputfile)
696
697 # The convergence trigger shows up somewhere at the bottom in Molpro 2012,
698 # before the final stars. If convergence is not reached, there is an additional
699 # line that can be checked for. This is a little tricky, though, since it is
700 # not the last line... so bail out of the loop if convergence failure is detected.
701 while "*****" not in line:
702 line = next(inputfile)
703 if line.strip() == "END OF GEOMETRY OPTIMIZATION.":
704 geometry_converged = True
705 if "No convergence" in line:
706 geometry_converged = False
707 break
708
709 # Finally, deal with optdone, append the last step to it only if we had convergence.
710 if not hasattr(self, 'optdone'):
711 self.optdone = []
712 if geometry_converged:
713 self.optdone.append(istep-1)
714
715 # This block should look like this:
716 # Normal Modes
717 #
718 # 1 Au 2 Bu 3 Ag 4 Bg 5 Ag
719 # Wavenumbers [cm-1] 151.81 190.88 271.17 299.59 407.86
720 # Intensities [km/mol] 0.33 0.28 0.00 0.00 0.00
721 # Intensities [relative] 0.34 0.28 0.00 0.00 0.00
722 # CX1 0.00000 -0.01009 0.02577 0.00000 0.06008
723 # CY1 0.00000 -0.05723 -0.06696 0.00000 0.06349
724 # CZ1 -0.02021 0.00000 0.00000 0.11848 0.00000
725 # CX2 0.00000 -0.01344 0.05582 0.00000 -0.02513
726 # CY2 0.00000 -0.06288 -0.03618 0.00000 0.00349
727 # CZ2 -0.05565 0.00000 0.00000 0.07815 0.00000
728 # ...
729 # Molpro prints low frequency modes in a subsequent section with the same format,
730 # which also contains zero frequency modes, with the title:
731 # Normal Modes of low/zero frequencies
732 if line[1:13] == "Normal Modes":
733
734 islow = (line[1:37] == "Normal Modes of low/zero frequencies")
735
736 self.skip_line(inputfile, 'blank')
737
738 # Each portion of five modes is followed by a single blank line.
739 # The whole block is followed by an additional blank line.
740 line = next(inputfile)
741 while line.strip():
742
743 if line[1:25].isspace():
744 if not islow: # vibsyms not printed for low freq modes
745 numbers = list(map(int, line.split()[::2]))
746 vibsyms = line.split()[1::2]
747 else:
748 # give low freq modes an empty str as vibsym
749 # note there could be other possibilities..
750 numbers = list(map(int, line.split()))
751 vibsyms = ['']*len(numbers)
752
753 if line[1:12] == "Wavenumbers":
754 vibfreqs = list(map(float, line.strip().split()[2:]))
755
756 if line[1:21] == "Intensities [km/mol]":
757 vibirs = list(map(float, line.strip().split()[2:]))
758
759 # There should always by 3xnatom displacement rows.
760 if line[1:11].isspace() and line[13:25].strip().isdigit():
761
762 # There are a maximum of 5 modes per line.
763 nmodes = len(line.split())-1
764
765 vibdisps = []
766 for i in range(nmodes):
767 vibdisps.append([])
768 for n in range(self.natom):
769 vibdisps[i].append([])
770 for i in range(nmodes):
771 disp = float(line.split()[i+1])
772 vibdisps[i][0].append(disp)
773 for i in range(self.natom*3 - 1):
774 line = next(inputfile)
775 iatom = (i+1)//3
776 for i in range(nmodes):
777 disp = float(line.split()[i+1])
778 vibdisps[i][iatom].append(disp)
779
780 line = next(inputfile)
781 if not line.strip():
782
783 if not hasattr(self, "vibfreqs"):
784 self.vibfreqs = []
785 if not hasattr(self, "vibsyms"):
786 self.vibsyms = []
787 if not hasattr(self, "vibirs") and "vibirs" in dir():
788 self.vibirs = []
789 if not hasattr(self, "vibdisps") and "vibdisps" in dir():
790 self.vibdisps = []
791
792 if not islow:
793 self.vibfreqs.extend(vibfreqs)
794 self.vibsyms.extend(vibsyms)
795 if "vibirs" in dir():
796 self.vibirs.extend(vibirs)
797 if "vibdisps" in dir():
798 self.vibdisps.extend(vibdisps)
799 else:
800 nonzero = [f > 0 for f in vibfreqs]
801 vibfreqs = [f for f in vibfreqs if f > 0]
802 self.vibfreqs = vibfreqs + self.vibfreqs
803 vibsyms = [vibsyms[i] for i in range(len(vibsyms)) if nonzero[i]]
804 self.vibsyms = vibsyms + self.vibsyms
805 if "vibirs" in dir():
806 vibirs = [vibirs[i] for i in range(len(vibirs)) if nonzero[i]]
807 self.vibirs = vibirs + self.vibirs
808 if "vibdisps" in dir():
809 vibdisps = [vibdisps[i] for i in range(len(vibdisps)) if nonzero[i]]
810 self.vibdisps = vibdisps + self.vibdisps
811
812 line = next(inputfile)
813
814 if line[1:16] == "Force Constants":
815
816 hessian = []
817 line = next(inputfile)
818 hess = []
819 tmp = []
820
821 while line.strip():
822 try:
823 list(map(float, line.strip().split()[2:]))
824 except:
825 line = next(inputfile)
826 line.strip().split()[1:]
827 hess.extend([list(map(float, line.strip().split()[1:]))])
828 line = next(inputfile)
829 lig = 0
830
831 while (lig == 0) or (len(hess[0]) > 1):
832 tmp.append(hess.pop(0))
833 lig += 1
834 k = 5
835
836 while len(hess) != 0:
837 tmp[k] += hess.pop(0)
838 k += 1
839 if (len(tmp[k-1]) == lig):
840 break
841 if k >= lig:
842 k = len(tmp[-1])
843 for l in tmp:
844 hessian += l
845
846 self.set_attribute("hessian", hessian)
847
848 if line[1:14] == "Atomic Masses" and hasattr(self, "hessian"):
849
850 line = next(inputfile)
851 self.amass = list(map(float, line.strip().split()[2:]))
852
853 while line.strip():
854 line = next(inputfile)
855 self.amass += list(map(float, line.strip().split()[2:]))
856
857 #1PROGRAM * POP (Mulliken population analysis)
858 #
859 #
860 # Density matrix read from record 2100.2 Type=RHF/CHARGE (state 1.1)
861 #
862 # Population analysis by basis function type
863 #
864 # Unique atom s p d f g Total Charge
865 # 2 C 3.11797 2.88497 0.00000 0.00000 0.00000 6.00294 - 0.00294
866 # 3 C 3.14091 2.91892 0.00000 0.00000 0.00000 6.05984 - 0.05984
867 # ...
868 if line.strip() == "1PROGRAM * POP (Mulliken population analysis)":
869
870 self.skip_lines(inputfile, ['b', 'b', 'density_source', 'b', 'func_type', 'b'])
871
872 header = next(inputfile)
873 icharge = header.split().index('Charge')
874
875 charges = []
876 line = next(inputfile)
877 while line.strip():
878 cols = line.split()
879 charges.append(float(cols[icharge]+cols[icharge+1]))
880 line = next(inputfile)
881
882 if not hasattr(self, "atomcharges"):
883 self.atomcharges = {}
884 self.atomcharges['mulliken'] = charges
885
886 if 'GRADIENT FOR STATE' in line:
887 for _ in range(3):
888 next(inputfile)
889 grad = []
890 lines_read = 0
891 while lines_read < self.natom:
892 line = next(inputfile)
893 # Because molpro inserts an empty line every 50th atom.
894 if line:
895 grad.append([float(x) for x in line.split()[1:]])
896 lines_read += 1
897 if not hasattr(self, 'grads'):
898 self.grads = []
899 self.grads.append(grad)
900
901 if line[:25] == ' Variable memory released':
902 self.metadata['success'] = True