Debian Codegraph @

cclib/parser/gamessparser.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2018, 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 GAMESS(US) output files"""
9
10
11 from __future__ import print_function
12 import re
13
14 import numpy
15
16
17 from cclib.parser import logfileparser
18 from cclib.parser import utils
19
20
21 class GAMESS(logfileparser.Logfile):
22 """A GAMESS/Firefly log file."""
23
24 # Used to index self.scftargets[].
25 SCFRMS, SCFMAX, SCFENERGY = list(range(3))
26
27 # Used to extact Dunning basis set names.
28 dunningbas = {'CCD': 'cc-pVDZ', \
29 'CCT': 'cc-pVTZ', \
30 'CCQ': 'cc-pVQZ', \
31 'CC5': 'cc-pV5Z', \
32 'CC6': 'cc-pV6Z', \
33 'ACCD': 'aug-cc-pVDZ', \
34 'ACCT': 'aug-cc-pVTZ', \
35 'ACCQ': 'aug-cc-pVQZ', \
36 'ACC5': 'aug-cc-pV5Z', \
37 'ACC6': 'aug-cc-pV6Z', \
38 'CCDC': 'cc-pCVDZ', \
39 'CCTC': 'cc-pCVTZ', \
40 'CCQC': 'cc-pCVQZ', \
41 'CC5C': 'cc-pCV5Z', \
42 'CC6C': 'cc-pCV6Z', \
43 'ACCDC': 'aug-cc-pCVDZ', \
44 'ACCTC': 'aug-cc-pCVTZ', \
45 'ACCQC': 'aug-cc-pCVQZ', \
46 'ACC5C': 'aug-cc-pCV5Z', \
47 'ACC6C': 'aug-cc-pCV6Z'}
48
49 def __init__(self, *args, **kwargs):
50
51 # Call the __init__ method of the superclass
52 super(GAMESS, self).__init__(logname="GAMESS", *args, **kwargs)
53
54 def __str__(self):
55 """Return a string representation of the object."""
56 return "GAMESS log file %s" % (self.filename)
57
58 def __repr__(self):
59 """Return a representation of the object."""
60 return 'GAMESS("%s")' % (self.filename)
61
62 def normalisesym(self, label):
63 """Normalise the symmetries used by GAMESS.
64
65 To normalise, two rules need to be applied:
66 (1) Occurences of U/G in the 2/3 position of the label
67 must be lower-cased
68 (2) Two single quotation marks must be replaced by a double
69 """
70
71 if label[1:] == "''":
72 end = '"'
73 else:
74 end = label[1:].replace("U", "u").replace("G", "g")
75 return label[0] + end
76
77 def before_parsing(self):
78
79 self.firststdorient = True # Used to decide whether to wipe the atomcoords clean
80 self.cihamtyp = "none" # Type of CI Hamiltonian: saps or dets.
81 self.scftype = "none" # Type of SCF calculation: BLYP, RHF, ROHF, etc.
82
83 def extract(self, inputfile, line):
84 """Extract information from the file object inputfile."""
85
86 # Extract the version number. If the calculation is from
87 # Firefly, its version number comes before a line that looks
88 # like the normal GAMESS version number...
89 if "Firefly version" in line:
90 match = re.search(r"Firefly version\s([\d.]*)\D*(\d*)\s*\*", line)
91 if match:
92 version, build = match.groups()
93 package_version = "{}.b{}".format(version, build)
94 self.metadata["package_version"] = package_version
95 if "GAMESS VERSION" in line:
96 # ...so avoid overwriting it if Firefly already set this field.
97 if "package_version" not in self.metadata:
98 tokens = line.split()
99 self.metadata["package_version"] = ' '.join(tokens[4:-1])
100
101 if line[1:12] == "INPUT CARD>":
102 return
103
104 # extract the methods
105 if line[1:7] == "SCFTYP":
106 method = line.split()[0][7:]
107 if len(self.metadata["methods"]) == 0:
108 self.metadata["methods"].append(method)
109
110 # extract the basis set name
111 if line[5:11] == "GBASIS":
112 basnm1 = line.split()[0][7:]
113 if basnm1 in self.dunningbas:
114 self.metadata["basis_set"] = self.dunningbas[basnm1]
115 else:
116 if basnm1 == "PM3" or basnm1 == "AM1":
117 self.metadata["methods"].append(basnm1)
118 if basnm1 == "STO" :
119 if line.split()[2] == "2":
120 self.metadata["basis_set"] = "STO-2G"
121 elif line.split()[2] == "3":
122 self.metadata["basis_set"] = "STO-3G"
123 elif line.split()[2] == "4":
124 self.metadata["basis_set"] = "STO-4G"
125 elif line.split()[2] == "5":
126 self.metadata["basis_set"] = "STO-5G"
127 if basnm1 == "N21" :
128 if line.split()[2] == "3" and line.split()[3] == "POLAR=COMMON":
129 self.metadata["basis_set"] = "3-21G*"
130 if line.split()[2] == "3" and line.split()[3] == "POLAR=NONE":
131 self.metadata["basis_set"] = "3-21G"
132 if line.split()[2] == "4" and line.split()[3] == "POLAR=NONE":
133 self.metadata["basis_set"] = "4-21G"
134 if line.split()[2] == "6" and line.split()[3] == "POLAR=NONE":
135 self.metadata["basis_set"] = "6-21G"
136 if basnm1 == "N31" :
137 if line.split()[2] == "6" and (line.split()[3] == "POLAR=POPN31" \
138 or line.split()[3] == "POLAR=POPLE"):
139 self.metadata["basis_set"] = "6-31G*"
140 line = next(inputfile)
141 if line.split()[-1] == "T":
142 self.metadata["basis_set"] = "6-31+G*"
143 line = next(inputfile)
144 if line.split()[1] == "0" and line.split()[3] == "T":
145 self.metadata["basis_set"] = "6-31++G*"
146 if line.split()[1] == "1" and line.split()[3] == "T":
147 self.metadata["basis_set"] = "6-31++G**"
148 else:
149 line = next(inputfile)
150 if line.split()[1] == "1": #NPFUNC = 1
151 self.metadata["basis_set"] = "6-31G**"
152 if line.split()[2] == "6" and line.split()[3] == "POLAR=NONE":
153 self.metadata["basis_set"] = "6-31G"
154 if line.split()[2] == "4" and line.split()[3] == "POLAR=NONE":
155 self.metadata["basis_set"] = "4-31G"
156 if line.split()[2] == "4" and line.split()[3] == "POLAR=POPN31":
157 self.metadata["basis_set"] = "4-31G*"
158 if basnm1 == "N311" :
159 if line.split()[2] == "6" and line.split()[3] == "POLAR=POPN311":
160 self.metadata["basis_set"] = "6-311G*"
161 line = next(inputfile)
162 if line.split()[-1] == "T":
163 self.metadata["basis_set"] = "6-311+G*"
164 line = next(inputfile)
165 if line.split()[1] == "0" and line.split()[3] == "T":
166 self.metadata["basis_set"] = "6-311++G*"
167 if line.split()[1] == "1" and line.split()[3] == "T":
168 self.metadata["basis_set"] = "6-311++G**"
169 else:
170 line = next(inputfile)
171 if line.split()[1] == "1": #NPFUNC = 1
172 self.metadata["basis_set"] = "6-311G**"
173 if line.split()[2] == "6" and line.split()[3] == "POLAR=NONE":
174 self.metadata["basis_set"] = "6-311G"
175
176 # We are looking for this line:
177 # PARAMETERS CONTROLLING GEOMETRY SEARCH ARE
178 # ...
179 # OPTTOL = 1.000E-04 RMIN = 1.500E-03
180 if line[10:18] == "OPTTOL =":
181 if not hasattr(self, "geotargets"):
182 opttol = float(line.split()[2])
183 self.geotargets = numpy.array([opttol, 3. / opttol], "d")
184
185 # Has to deal with such lines as:
186 # FINAL R-B3LYP ENERGY IS -382.0507446475 AFTER 10 ITERATIONS
187 # FINAL ENERGY IS -379.7594673378 AFTER 9 ITERATIONS
188 # ...so take the number after the "IS"
189 if line.find("FINAL") == 1:
190 if not hasattr(self, "scfenergies"):
191 self.scfenergies = []
192 temp = line.split()
193 self.scfenergies.append(utils.convertor(float(temp[temp.index("IS") + 1]), "hartree", "eV"))
194
195 # For total energies after Moller-Plesset corrections, the output looks something like this:
196 #
197 # RESULTS OF MOLLER-PLESSET 2ND ORDER CORRECTION ARE
198 # E(0)= -285.7568061536
199 # E(1)= 0.0
200 # E(2)= -0.9679419329
201 # E(MP2)= -286.7247480864
202 # where E(MP2) = E(0) + E(2)
203 #
204 # With GAMESS-US 12 Jan 2009 (R3), the preceding text is different:
205 # DIRECT 4-INDEX TRANSFORMATION
206 # SCHWARZ INEQUALITY TEST SKIPPED 0 INTEGRAL BLOCKS
207 # E(SCF)= -76.0088477471
208 # E(2)= -0.1403745370
209 # E(MP2)= -76.1492222841
210 #
211 # With GAMESS-US 20 APR 2017 (R1), the following block may be present:
212 # SCHWARZ INEQUALITY TEST SKIPPED 0 INTEGRAL BLOCKS
213 # ... END OF INTEGRAL TRANSFORMATION ...
214
215 if line.find("RESULTS OF MOLLER-PLESSET") >= 0 or line[6:37] == "SCHWARZ INEQUALITY TEST SKIPPED":
216
217 if not hasattr(self, "mpenergies"):
218 self.mpenergies = []
219
220 line = next(inputfile)
221 # Each iteration has a new print-out
222 if "END OF INTEGRAL TRANSFORMATION" not in line:
223 self.mpenergies.append([])
224
225 # GAMESS-US presently supports only second order corrections (MP2)
226 # PC GAMESS also has higher levels (3rd and 4th), with different output
227 # Only the highest level MP4 energy is gathered (SDQ or SDTQ)
228 # Loop breaks when substring "DONE WITH MPn ENERGY" is encountered,
229 # where n=2, 3 or 4.
230 while "DONE WITH MP" not in line:
231
232 if len(line.split()) > 0:
233 # Only up to MP2 correction
234 if line.split()[0] == "E(MP2)=":
235 self.metadata["methods"].append("MP2")
236 mp2energy = float(line.split()[1])
237 self.mpenergies[-1].append(utils.convertor(mp2energy, "hartree", "eV"))
238 # MP2 before higher order calculations
239 if line.split()[0] == "E(MP2)":
240 mp2energy = float(line.split()[2])
241 self.mpenergies[-1].append(utils.convertor(mp2energy, "hartree", "eV"))
242 if line.split()[0] == "E(MP3)":
243 self.metadata["methods"].append("MP3")
244 mp3energy = float(line.split()[2])
245 self.mpenergies[-1].append(utils.convertor(mp3energy, "hartree", "eV"))
246 if line.split()[0] in ["E(MP4-SDQ)", "E(MP4-SDTQ)"]:
247 self.metadata["methods"].append("MP4")
248 mp4energy = float(line.split()[2])
249 self.mpenergies[-1].append(utils.convertor(mp4energy, "hartree", "eV"))
250 line = next(inputfile)
251
252 # Total energies after Coupled Cluster calculations
253 # Only the highest Coupled Cluster level result is gathered
254 if line[12:23] == "CCD ENERGY:":
255 self.metadata["methods"].append("CCD")
256 if not hasattr(self, "ccenergies"):
257 self.ccenergies = []
258 ccenergy = float(line.split()[2])
259 self.ccenergies.append(utils.convertor(ccenergy, "hartree", "eV"))
260 if line.find("CCSD") >= 0 and line.split()[0:2] == ["CCSD", "ENERGY:"]:
261 self.metadata["methods"].append("CCSD")
262 if not hasattr(self, "ccenergies"):
263 self.ccenergies = []
264 ccenergy = float(line.split()[2])
265 line = next(inputfile)
266 if line[8:23] == "CCSD[T] ENERGY:":
267 self.metadata["methods"].append("CCSD[T]")
268 ccenergy = float(line.split()[2])
269 line = next(inputfile)
270 if line[8:23] == "CCSD(T) ENERGY:":
271 self.metadata["methods"].append("CCSD(T)")
272 ccenergy = float(line.split()[2])
273 self.ccenergies.append(utils.convertor(ccenergy, "hartree", "eV"))
274
275 # Also collect MP2 energies, which are always calculated before CC
276 if line[8:23] == "MBPT(2) ENERGY:":
277 if not hasattr(self, "mpenergies"):
278 self.mpenergies = []
279 self.mpenergies.append([])
280 mp2energy = float(line.split()[2])
281 self.mpenergies[-1].append(utils.convertor(mp2energy, "hartree", "eV"))
282
283 # Extract charge and multiplicity
284 if line[1:19] == "CHARGE OF MOLECULE":
285
286 charge = int(round(float(line.split()[-1])))
287 self.set_attribute('charge', charge)
288
289 line = next(inputfile)
290 mult = int(line.split()[-1])
291 self.set_attribute('mult', mult)
292
293 # Electronic transitions (etenergies) for CIS runs and TD-DFT, which
294 # have very similar outputs. The outputs EOM look very differentm, though.
295 #
296 # ---------------------------------------------------------------------
297 # CI-SINGLES EXCITATION ENERGIES
298 # STATE HARTREE EV KCAL/MOL CM-1 NM
299 # ---------------------------------------------------------------------
300 # 1A'' 0.1677341781 4.5643 105.2548 36813.40 271.64
301 # ...
302 if re.match("(CI-SINGLES|TDDFT) EXCITATION ENERGIES", line.strip()):
303
304 if not hasattr(self, "etenergies"):
305 self.etenergies = []
306
307 get_etosc = False
308 header = next(inputfile).rstrip()
309 if header.endswith("OSC. STR."):
310 # water_cis_dets.out does not have the oscillator strength
311 # in this table...it is extracted from a different section below
312 get_etosc = True
313 self.etoscs = []
314
315 self.skip_line(inputfile, 'dashes')
316
317 line = next(inputfile)
318 broken = line.split()
319 while len(broken) > 0:
320
321 # Take hartree value with more numbers, and convert.
322 # Note that the values listed after this are also less exact!
323 etenergy = float(broken[1])
324 self.etenergies.append(utils.convertor(etenergy, "hartree", "wavenumber"))
325 if get_etosc:
326 etosc = float(broken[-1])
327 self.etoscs.append(etosc)
328 broken = next(inputfile).split()
329
330 # Detect the CI hamiltonian type, if applicable.
331 # Should always be detected if CIS is done.
332 if line[8:64] == "RESULTS FROM SPIN-ADAPTED ANTISYMMETRIZED PRODUCT (SAPS)":
333 self.cihamtyp = "saps"
334 if line[8:64] == "RESULTS FROM DETERMINANT BASED ATOMIC ORBITAL CI-SINGLES":
335 self.cihamtyp = "dets"
336
337 # etsecs (used only for CIS runs for now)
338 if line[1:14] == "EXCITED STATE":
339 if not hasattr(self, 'etsecs'):
340 self.etsecs = []
341 if not hasattr(self, 'etsyms'):
342 self.etsyms = []
343 statenumber = int(line.split()[2])
344 spin = int(float(line.split()[7]))
345 if spin == 0:
346 sym = "Singlet"
347 if spin == 1:
348 sym = "Triplet"
349 sym += '-' + line.split()[-1]
350 self.etsyms.append(sym)
351 # skip 5 lines
352 for i in range(5):
353 line = next(inputfile)
354 line = next(inputfile)
355 CIScontribs = []
356 while line.strip()[0] != "-":
357 MOtype = 0
358 # alpha/beta are specified for hamtyp=dets
359 if self.cihamtyp == "dets":
360 if line.split()[0] == "BETA":
361 MOtype = 1
362 fromMO = int(line.split()[-3])-1
363 toMO = int(line.split()[-2])-1
364 coeff = float(line.split()[-1])
365 # With the SAPS hamiltonian, the coefficients are multiplied
366 # by sqrt(2) so that they normalize to 1.
367 # With DETS, both alpha and beta excitations are printed.
368 # if self.cihamtyp == "saps":
369 # coeff /= numpy.sqrt(2.0)
370 CIScontribs.append([(fromMO, MOtype), (toMO, MOtype), coeff])
371 line = next(inputfile)
372 self.etsecs.append(CIScontribs)
373
374 # etoscs (used only for CIS runs now)
375 if line[1:50] == "TRANSITION FROM THE GROUND STATE TO EXCITED STATE":
376 if not hasattr(self, "etoscs"):
377 self.etoscs = []
378
379 # This was the suggested as a fix in issue #61, and it does allow
380 # the parser to finish without crashing. However, it seems that
381 # etoscs is shorter in this case than the other transition attributes,
382 # so that should be somehow corrected and tested for.
383 if "OPTICALLY" in line:
384 pass
385 else:
386 statenumber = int(line.split()[-1])
387 # skip 7 lines
388 for i in range(8):
389 line = next(inputfile)
390 strength = float(line.split()[3])
391 self.etoscs.append(strength)
392
393 # TD-DFT for GAMESS-US.
394 # The format for excitations has changed a bit between 2007 and 2012.
395 # Original format parser was written for:
396 #
397 # -------------------
398 # TRIPLET EXCITATIONS
399 # -------------------
400 #
401 # STATE # 1 ENERGY = 3.027228 EV
402 # OSCILLATOR STRENGTH = 0.000000
403 # DRF COEF OCC VIR
404 # --- ---- --- ---
405 # 35 -1.105383 35 -> 36
406 # 69 -0.389181 34 -> 37
407 # 103 -0.405078 33 -> 38
408 # 137 0.252485 32 -> 39
409 # 168 -0.158406 28 -> 40
410 #
411 # STATE # 2 ENERGY = 4.227763 EV
412 # ...
413 #
414 # Here is the corresponding 2012 version:
415 #
416 # -------------------
417 # TRIPLET EXCITATIONS
418 # -------------------
419 #
420 # STATE # 1 ENERGY = 3.027297 EV
421 # OSCILLATOR STRENGTH = 0.000000
422 # LAMBDA DIAGNOSTIC = 0.925 (RYDBERG/CHARGE TRANSFER CHARACTER)
423 # SYMMETRY OF STATE = A
424 # EXCITATION DE-EXCITATION
425 # OCC VIR AMPLITUDE AMPLITUDE
426 # I A X(I->A) Y(A->I)
427 # --- --- -------- --------
428 # 35 36 -0.929190 -0.176167
429 # 34 37 -0.279823 -0.109414
430 # ...
431 #
432 # We discern these two by the presence of the arrow in the old version.
433 #
434 # The "LET EXCITATIONS" pattern used below catches both
435 # singlet and triplet excitations output.
436 if line[14:29] == "LET EXCITATIONS":
437
438 self.etenergies = []
439 self.etoscs = []
440 self.etsecs = []
441 etsyms = []
442
443 self.skip_lines(inputfile, ['d', 'b'])
444
445 # Loop while states are still being printed.
446 line = next(inputfile)
447 while line[1:6] == "STATE":
448
449 self.updateprogress(inputfile, "Excited States")
450
451 etenergy = utils.convertor(float(line.split()[-2]), "eV", "wavenumber")
452 etoscs = float(next(inputfile).split()[-1])
453 self.etenergies.append(etenergy)
454 self.etoscs.append(etoscs)
455
456 # Symmetry is not always present, especially in old versions.
457 # Newer versions, on the other hand, can also provide a line
458 # with lambda diagnostic and some extra headers.
459 line = next(inputfile)
460 if "LAMBDA DIAGNOSTIC" in line:
461 line = next(inputfile)
462 if "SYMMETRY" in line:
463 etsyms.append(line.split()[-1])
464 line = next(inputfile)
465 if "EXCITATION" in line and "DE-EXCITATION" in line:
466 line = next(inputfile)
467 if line.count("AMPLITUDE") == 2:
468 line = next(inputfile)
469
470 self.skip_line(inputfile, 'dashes')
471
472 CIScontribs = []
473 line = next(inputfile)
474 while line.strip():
475 cols = line.split()
476 if "->" in line:
477 i_occ_vir = [2, 4]
478 i_coeff = 1
479
480 else:
481 i_occ_vir = [0, 1]
482 i_coeff = 2
483 fromMO, toMO = [int(cols[i]) - 1 for i in i_occ_vir]
484 coeff = float(cols[i_coeff])
485 CIScontribs.append([(fromMO, 0), (toMO, 0), coeff])
486 line = next(inputfile)
487 self.etsecs.append(CIScontribs)
488 line = next(inputfile)
489
490 # The symmetries are not always present.
491 if etsyms:
492 self.etsyms = etsyms
493
494 # Maximum and RMS gradients.
495 if "MAXIMUM GRADIENT" in line or "RMS GRADIENT" in line:
496
497 parts = line.split()
498
499 # Avoid parsing the following...
500
501 ## YOU SHOULD RESTART "OPTIMIZE" RUNS WITH THE COORDINATES
502 ## WHOSE ENERGY IS LOWEST. RESTART "SADPOINT" RUNS WITH THE
503 ## COORDINATES WHOSE RMS GRADIENT IS SMALLEST. THESE ARE NOT
504 ## ALWAYS THE LAST POINT COMPUTED!
505
506 if parts[0] not in ["MAXIMUM", "RMS", "(1)"]:
507 return
508
509 if not hasattr(self, "geovalues"):
510 self.geovalues = []
511
512 # Newer versions (around 2006) have both maximum and RMS on one line:
513 # MAXIMUM GRADIENT = 0.0531540 RMS GRADIENT = 0.0189223
514 if len(parts) == 8:
515 maximum = float(parts[3])
516 rms = float(parts[7])
517
518 # In older versions of GAMESS, this spanned two lines, like this:
519 # MAXIMUM GRADIENT = 0.057578167
520 # RMS GRADIENT = 0.027589766
521 if len(parts) == 4:
522 maximum = float(parts[3])
523 line = next(inputfile)
524 parts = line.split()
525 rms = float(parts[3])
526
527 # FMO also prints two final one- and two-body gradients (see exam37):
528 # (1) MAXIMUM GRADIENT = 0.0531540 RMS GRADIENT = 0.0189223
529 if len(parts) == 9:
530 maximum = float(parts[4])
531 rms = float(parts[8])
532
533 self.geovalues.append([maximum, rms])
534
535 # This is the input orientation, which is the only data available for
536 # SP calcs, but which should be overwritten by the standard orientation
537 # values, which is the only information available for all geoopt cycles.
538 if line[11:50] == "ATOMIC COORDINATES":
539
540 if not hasattr(self, "atomcoords"):
541 self.atomcoords = []
542
543 line = next(inputfile)
544 atomcoords = []
545 atomnos = []
546 line = next(inputfile)
547 while line.strip():
548 temp = line.strip().split()
549 atomcoords.append([utils.convertor(float(x), "bohr", "Angstrom") for x in temp[2:5]])
550 atomnos.append(int(round(float(temp[1])))) # Don't use the atom name as this is arbitary
551 line = next(inputfile)
552
553 self.set_attribute('atomnos', atomnos)
554 self.atomcoords.append(atomcoords)
555
556 if line[12:40] == "EQUILIBRIUM GEOMETRY LOCATED":
557 # Prevent extraction of the final geometry twice
558 if not hasattr(self, 'optdone'):
559 self.optdone = []
560 self.optdone.append(len(self.geovalues) - 1)
561
562 # Make sure we always have optdone for geomtry optimization, even if not converged.
563 if "GEOMETRY SEARCH IS NOT CONVERGED" in line:
564 if not hasattr(self, 'optdone'):
565 self.optdone = []
566
567 # This is the standard orientation, which is the only coordinate
568 # information available for all geometry optimisation cycles.
569 # The input orientation will be overwritten if this is a geometry optimisation
570 # We assume that a previous Input Orientation has been found and
571 # used to extract the atomnos
572 if line[1:29] == "COORDINATES OF ALL ATOMS ARE" and (not hasattr(self, "optdone") or self.optdone == []):
573
574 self.updateprogress(inputfile, "Coordinates")
575
576 if self.firststdorient:
577 self.firststdorient = False
578 # Wipes out the single input coordinate at the start of the file
579 self.atomcoords = []
580
581 self.skip_lines(inputfile, ['line', '-'])
582
583 atomcoords = []
584 line = next(inputfile)
585
586 for i in range(self.natom):
587 temp = line.strip().split()
588 atomcoords.append(list(map(float, temp[2:5])))
589 line = next(inputfile)
590 self.atomcoords.append(atomcoords)
591
592 # Section with SCF information.
593 #
594 # The space at the start of the search string is to differentiate from MCSCF.
595 # Everything before the search string is stored as the type of SCF.
596 # SCF types may include: BLYP, RHF, ROHF, UHF, etc.
597 #
598 # For example, in exam17 the section looks like this (note that this is GVB):
599 # ------------------------
600 # ROHF-GVB SCF CALCULATION
601 # ------------------------
602 # GVB STEP WILL USE 119875 WORDS OF MEMORY.
603 #
604 # MAXIT= 30 NPUNCH= 2 SQCDF TOL=1.0000E-05
605 # NUCLEAR ENERGY= 6.1597411978
606 # EXTRAP=T DAMP=F SHIFT=F RSTRCT=F DIIS=F SOSCF=F
607 #
608 # ITER EX TOTAL ENERGY E CHANGE SQCDF DIIS ERROR
609 # 0 0 -38.298939963 -38.298939963 0.131784454 0.000000000
610 # 1 1 -38.332044339 -0.033104376 0.026019716 0.000000000
611 # ... and will be terminated by a blank line.
612 if line.rstrip()[-16:] == " SCF CALCULATION":
613
614 # Remember the type of SCF.
615 self.scftype = line.strip()[:-16]
616
617 self.skip_line(inputfile, 'dashes')
618
619 while line[:5] != " ITER":
620
621 self.updateprogress(inputfile, "Attributes")
622
623 # GVB uses SQCDF for checking convergence (for example in exam17).
624 if "GVB" in self.scftype and "SQCDF TOL=" in line:
625 scftarget = float(line.split("=")[-1])
626
627 # Normally, however, the density is used as the convergence criterium.
628 # Deal with various versions:
629 # (GAMESS VERSION = 12 DEC 2003)
630 # DENSITY MATRIX CONV= 2.00E-05 DFT GRID SWITCH THRESHOLD= 3.00E-04
631 # (GAMESS VERSION = 22 FEB 2006)
632 # DENSITY MATRIX CONV= 1.00E-05
633 # (PC GAMESS version 6.2, Not DFT?)
634 # DENSITY CONV= 1.00E-05
635 elif "DENSITY CONV" in line or "DENSITY MATRIX CONV" in line:
636 scftarget = float(line.split()[-1])
637
638 line = next(inputfile)
639
640 if not hasattr(self, "scftargets"):
641 self.scftargets = []
642
643 self.scftargets.append([scftarget])
644
645 if not hasattr(self, "scfvalues"):
646 self.scfvalues = []
647
648 # Normally the iterations print in 6 columns.
649 # For ROHF, however, it is 5 columns, thus this extra parameter.
650 if "ROHF" in self.scftype:
651 self.scf_valcol = 4
652 else:
653 self.scf_valcol = 5
654
655 line = next(inputfile)
656
657 # SCF iterations are terminated by a blank line.
658 # The first four characters usually contains the step number.
659 # However, lines can also contain messages, including:
660 # * * * INITIATING DIIS PROCEDURE * * *
661 # CONVERGED TO SWOFF, SO DFT CALCULATION IS NOW SWITCHED ON
662 # DFT CODE IS SWITCHING BACK TO THE FINER GRID
663 values = []
664 while line.strip():
665 try:
666 temp = int(line[0:4])
667 except ValueError:
668 pass
669 else:
670 values.append([float(line.split()[self.scf_valcol])])
671 try:
672 line = next(inputfile)
673 except StopIteration:
674 self.logger.warning('File terminated before end of last SCF!')
675 break
676 self.scfvalues.append(values)
677
678 # Sometimes, only the first SCF cycle has the banner parsed for above,
679 # so we must identify them from the header before the SCF iterations.
680 # The example we have for this is the GeoOpt unittest for Firefly8.
681 if line[1:8] == "ITER EX":
682
683 # In this case, the convergence targets are not printed, so we assume
684 # they do not change.
685 self.scftargets.append(self.scftargets[-1])
686
687 values = []
688 line = next(inputfile)
689 while line.strip():
690 try:
691 temp = int(line[0:4])
692 except ValueError:
693 pass
694 else:
695 values.append([float(line.split()[self.scf_valcol])])
696 line = next(inputfile)
697 self.scfvalues.append(values)
698
699 # Extract normal coordinate analysis, including vibrational frequencies (vibfreq),
700 # IT intensities (vibirs) and displacements (vibdisps).
701 #
702 # This section typically looks like the following in GAMESS-US:
703 #
704 # MODES 1 TO 6 ARE TAKEN AS ROTATIONS AND TRANSLATIONS.
705 #
706 # FREQUENCIES IN CM**-1, IR INTENSITIES IN DEBYE**2/AMU-ANGSTROM**2,
707 # REDUCED MASSES IN AMU.
708 #
709 # 1 2 3 4 5
710 # FREQUENCY: 52.49 41.45 17.61 9.23 10.61
711 # REDUCED MASS: 3.92418 3.77048 5.43419 6.44636 5.50693
712 # IR INTENSITY: 0.00013 0.00001 0.00004 0.00000 0.00003
713 #
714 # ...or in the case of a numerical Hessian job...
715 #
716 # MODES 1 TO 5 ARE TAKEN AS ROTATIONS AND TRANSLATIONS.
717 #
718 # FREQUENCIES IN CM**-1, IR INTENSITIES IN DEBYE**2/AMU-ANGSTROM**2,
719 # REDUCED MASSES IN AMU.
720 #
721 # 1 2 3 4 5
722 # FREQUENCY: 0.05 0.03 0.03 30.89 30.94
723 # REDUCED MASS: 8.50125 8.50137 8.50136 1.06709 1.06709
724 #
725 # ...whereas PC-GAMESS has...
726 #
727 # MODES 1 TO 6 ARE TAKEN AS ROTATIONS AND TRANSLATIONS.
728 #
729 # FREQUENCIES IN CM**-1, IR INTENSITIES IN DEBYE**2/AMU-ANGSTROM**2
730 #
731 # 1 2 3 4 5
732 # FREQUENCY: 5.89 1.46 0.01 0.01 0.01
733 # IR INTENSITY: 0.00000 0.00000 0.00000 0.00000 0.00000
734 #
735 # If Raman is present we have (for PC-GAMESS)...
736 #
737 # MODES 1 TO 6 ARE TAKEN AS ROTATIONS AND TRANSLATIONS.
738 #
739 # FREQUENCIES IN CM**-1, IR INTENSITIES IN DEBYE**2/AMU-ANGSTROM**2
740 # RAMAN INTENSITIES IN ANGSTROM**4/AMU, DEPOLARIZATIONS ARE DIMENSIONLESS
741 #
742 # 1 2 3 4 5
743 # FREQUENCY: 5.89 1.46 0.04 0.03 0.01
744 # IR INTENSITY: 0.00000 0.00000 0.00000 0.00000 0.00000
745 # RAMAN INTENSITY: 12.675 1.828 0.000 0.000 0.000
746 # DEPOLARIZATION: 0.750 0.750 0.124 0.009 0.750
747 #
748 # If GAMESS-US or PC-GAMESS has not reached the stationary point we have
749 # and additional warning, repeated twice, like so (see n_water.log for an example):
750 #
751 # *******************************************************
752 # * THIS IS NOT A STATIONARY POINT ON THE MOLECULAR PES *
753 # * THE VIBRATIONAL ANALYSIS IS NOT VALID !!! *
754 # *******************************************************
755 #
756 # There can also be additional warnings about the selection of modes, for example:
757 #
758 # * * * WARNING, MODE 6 HAS BEEN CHOSEN AS A VIBRATION
759 # WHILE MODE12 IS ASSUMED TO BE A TRANSLATION/ROTATION.
760 # PLEASE VERIFY THE PROGRAM'S DECISION MANUALLY!
761 #
762 if "NORMAL COORDINATE ANALYSIS IN THE HARMONIC APPROXIMATION" in line:
763
764 self.vibfreqs = []
765 self.vibirs = []
766 self.vibdisps = []
767
768 # Need to get to the modes line, which is often preceeded by
769 # a list of atomic weights and some possible warnings.
770 # Pass the warnings to the logger if they are there.
771 while not "MODES" in line:
772 self.updateprogress(inputfile, "Frequency Information")
773
774 line = next(inputfile)
775
776 # Typical Atomic Masses section printed in GAMESS
777 # ATOMIC WEIGHTS (AMU)
778 #
779 # 1 O 15.99491
780 # 2 H 1.00782
781 # 3 H 1.00782
782 if "ATOMIC WEIGHTS" in line:
783 atommasses = []
784 self.skip_line(inputfile,['b'])
785 # There is a blank line after ATOMIC WEIGHTS
786 line = next(inputfile)
787 while line.strip():
788 temp = line.strip().split()
789 atommasses.append(float(temp[2]))
790 line = next(inputfile)
791 self.set_attribute('atommasses', atommasses)
792
793 if "THIS IS NOT A STATIONARY POINT" in line:
794 msg = "\n This is not a stationary point on the molecular PES"
795 msg += "\n The vibrational analysis is not valid!!!"
796 self.logger.warning(msg)
797 if "* * * WARNING, MODE" in line:
798 line1 = line.strip()
799 line2 = next(inputfile).strip()
800 line3 = next(inputfile).strip()
801 self.logger.warning("\n " + "\n ".join((line1, line2, line3)))
802
803 # In at least one case (regression zolm_dft3a.log) for older version of GAMESS-US,
804 # the header concerning the range of nodes is formatted wrong and can look like so:
805 # MODES 9 TO14 ARE TAKEN AS ROTATIONS AND TRANSLATIONS.
806 # ... although it's unclear whether this happens for all two-digit values.
807 startrot = int(line.split()[1])
808 if len(line.split()[2]) == 2:
809 endrot = int(line.split()[3])
810 else:
811 endrot = int(line.split()[2][2:])
812
813 self.skip_line(inputfile, 'blank')
814
815 # Continue down to the first frequencies
816 line = next(inputfile)
817 # With GAMESS-US 20 APR 2017 (R1), there are 28 blank spaces,
818 # in earlier versions there used to be 26.
819 while not line.strip() or not re.search(' {26,}1', line) is not None:
820 line = next(inputfile)
821
822 while not "SAYVETZ" in line:
823 self.updateprogress(inputfile, "Frequency Information")
824
825 # Note: there may be imaginary frequencies like this (which we make negative):
826 # FREQUENCY: 825.18 I 111.53 12.62 10.70 0.89
827 #
828 # A note for debuggers: some of these frequencies will be removed later,
829 # assumed to be translations or rotations (see startrot/endrot above).
830 for col in next(inputfile).split()[1:]:
831 if col == "I":
832 self.vibfreqs[-1] *= -1
833 else:
834 self.vibfreqs.append(float(col))
835
836 line = next(inputfile)
837
838 # Skip the symmetry (appears in newer versions), fixes bug #3476063.
839 if line.find("SYMMETRY") >= 0:
840 line = next(inputfile)
841
842 # Skip the reduced mass (not always present).
843 if line.find("REDUCED") >= 0:
844 line = next(inputfile)
845
846 # Not present in numerical Hessian calculations.
847 if line.find("IR INTENSITY") >= 0:
848 irIntensity = map(float, line.strip().split()[2:])
849 self.vibirs.extend([utils.convertor(x, "Debye^2/amu-Angstrom^2", "km/mol") for x in irIntensity])
850 line = next(inputfile)
851
852 # Read in Raman vibrational intensities if present.
853 if line.find("RAMAN") >= 0:
854 if not hasattr(self, "vibramans"):
855 self.vibramans = []
856 ramanIntensity = line.strip().split()
857 self.vibramans.extend(list(map(float, ramanIntensity[2:])))
858 depolar = next(inputfile)
859 line = next(inputfile)
860
861 # This line seems always to be blank.
862 assert line.strip() == ''
863
864 # Extract the Cartesian displacement vectors.
865 p = [[], [], [], [], []]
866 for j in range(self.natom):
867 q = [[], [], [], [], []]
868 for coord in "xyz":
869 line = next(inputfile)[21:]
870 cols = list(map(float, line.split()))
871 for i, val in enumerate(cols):
872 q[i].append(val)
873 for k in range(len(cols)):
874 p[k].append(q[k])
875 self.vibdisps.extend(p[:len(cols)])
876
877 # Skip the Sayvetz stuff at the end.
878 for j in range(10):
879 line = next(inputfile)
880
881 self.skip_line(inputfile, 'blank')
882 line = next(inputfile)
883
884 # Exclude rotations and translations.
885 self.vibfreqs = numpy.array(self.vibfreqs[:startrot-1]+self.vibfreqs[endrot:], "d")
886 self.vibirs = numpy.array(self.vibirs[:startrot-1]+self.vibirs[endrot:], "d")
887 self.vibdisps = numpy.array(self.vibdisps[:startrot-1]+self.vibdisps[endrot:], "d")
888 if hasattr(self, "vibramans"):
889 self.vibramans = numpy.array(self.vibramans[:startrot-1]+self.vibramans[endrot:], "d")
890
891 if line[5:21] == "ATOMIC BASIS SET":
892 self.gbasis = []
893 line = next(inputfile)
894 while line.find("SHELL") < 0:
895 line = next(inputfile)
896
897 self.skip_lines(inputfile, ['blank', 'atomname'])
898
899 # shellcounter stores the shell no of the last shell
900 # in the previous set of primitives
901 shellcounter = 1
902 while line.find("TOTAL NUMBER") < 0:
903
904 self.skip_line(inputfile, 'blank')
905
906 line = next(inputfile)
907 shellno = int(line.split()[0])
908 shellgap = shellno - shellcounter
909 gbasis = [] # Stores basis sets on one atom
910 shellsize = 0
911 while len(line.split()) != 1 and line.find("TOTAL NUMBER") < 0:
912 shellsize += 1
913 coeff = {}
914 # coefficients and symmetries for a block of rows
915 while line.strip():
916 temp = line.strip().split()
917 sym = temp[1]
918 assert sym in ['S', 'P', 'D', 'F', 'G', 'L']
919 if sym == "L": # L refers to SP
920 if len(temp) == 6: # GAMESS US
921 coeff.setdefault("S", []).append((float(temp[3]), float(temp[4])))
922 coeff.setdefault("P", []).append((float(temp[3]), float(temp[5])))
923 else: # PC GAMESS
924 assert temp[6][-1] == temp[9][-1] == ')'
925 coeff.setdefault("S", []).append((float(temp[3]), float(temp[6][:-1])))
926 coeff.setdefault("P", []).append((float(temp[3]), float(temp[9][:-1])))
927 else:
928 if len(temp) == 5: # GAMESS US
929 coeff.setdefault(sym, []).append((float(temp[3]), float(temp[4])))
930 else: # PC GAMESS
931 assert temp[6][-1] == ')'
932 coeff.setdefault(sym, []).append((float(temp[3]), float(temp[6][:-1])))
933 line = next(inputfile)
934 # either a blank or a continuation of the block
935 if sym == "L":
936 gbasis.append(('S', coeff['S']))
937 gbasis.append(('P', coeff['P']))
938 else:
939 gbasis.append((sym, coeff[sym]))
940 line = next(inputfile)
941 # either the start of the next block or the start of a new atom or
942 # the end of the basis function section
943
944 numtoadd = 1 + (shellgap // shellsize)
945 shellcounter = shellno + shellsize
946 for x in range(numtoadd):
947 self.gbasis.append(gbasis)
948
949 # The eigenvectors, which also include MO energies and symmetries, follow
950 # the *final* report of evalues and the last list of symmetries in the log file:
951 #
952 # ------------
953 # EIGENVECTORS
954 # ------------
955 #
956 # 1 2 3 4 5
957 # -10.0162 -10.0161 -10.0039 -10.0039 -10.0029
958 # BU AG BU AG AG
959 # 1 C 1 S 0.699293 0.699290 -0.027566 0.027799 0.002412
960 # 2 C 1 S 0.031569 0.031361 0.004097 -0.004054 -0.000605
961 # 3 C 1 X 0.000908 0.000632 -0.004163 0.004132 0.000619
962 # 4 C 1 Y -0.000019 0.000033 0.000668 -0.000651 0.005256
963 # 5 C 1 Z 0.000000 0.000000 0.000000 0.000000 0.000000
964 # 6 C 2 S -0.699293 0.699290 0.027566 0.027799 0.002412
965 # 7 C 2 S -0.031569 0.031361 -0.004097 -0.004054 -0.000605
966 # 8 C 2 X 0.000908 -0.000632 -0.004163 -0.004132 -0.000619
967 # 9 C 2 Y -0.000019 -0.000033 0.000668 0.000651 -0.005256
968 # 10 C 2 Z 0.000000 0.000000 0.000000 0.000000 0.000000
969 # 11 C 3 S -0.018967 -0.019439 0.011799 -0.014884 -0.452328
970 # 12 C 3 S -0.007748 -0.006932 0.000680 -0.000695 -0.024917
971 # 13 C 3 X 0.002628 0.002997 0.000018 0.000061 -0.003608
972 # ...
973 #
974 # There are blanks lines between each block.
975 #
976 # Warning! There are subtle differences between GAMESS-US and PC-GAMES
977 # in the formatting of the first four columns. In particular, for F orbitals,
978 # PC GAMESS:
979 # 19 C 1 YZ 0.000000 0.000000 0.000000 0.000000 0.000000
980 # 20 C XXX 0.000000 0.000000 0.000000 0.000000 0.002249
981 # 21 C YYY 0.000000 0.000000 -0.025555 0.000000 0.000000
982 # 22 C ZZZ 0.000000 0.000000 0.000000 0.002249 0.000000
983 # 23 C XXY 0.000000 0.000000 0.001343 0.000000 0.000000
984 # GAMESS US
985 # 55 C 1 XYZ 0.000000 0.000000 0.000000 0.000000 0.000000
986 # 56 C 1XXXX -0.000014 -0.000067 0.000000 0.000000 0.000000
987 #
988 if line.find("EIGENVECTORS") == 10 or line.find("MOLECULAR ORBITALS") == 10:
989
990 # This is the stuff that we can read from these blocks.
991 self.moenergies = [[]]
992 self.mosyms = [[]]
993
994 if not hasattr(self, "nmo"):
995 self.nmo = self.nbasis
996
997 self.mocoeffs = [numpy.zeros((self.nmo, self.nbasis), "d")]
998
999 readatombasis = False
1000 if not hasattr(self, "atombasis"):
1001 self.atombasis = []
1002 self.aonames = []
1003 for i in range(self.natom):
1004 self.atombasis.append([])
1005 self.aonames = []
1006 readatombasis = True
1007
1008 self.skip_line(inputfile, 'dashes')
1009
1010 for base in range(0, self.nmo, 5):
1011 self.updateprogress(inputfile, "Coefficients")
1012
1013 line = next(inputfile)
1014
1015 # This makes sure that this section does not end prematurely,
1016 # which happens in regression 2CO.ccsd.aug-cc-pVDZ.out.
1017 if line.strip() != "":
1018 break
1019
1020 numbers = next(inputfile) # Eigenvector numbers.
1021
1022 # This is for regression CdtetraM1B3LYP.
1023 if "ALPHA SET" in numbers:
1024 blank = next(inputfile)
1025 numbers = next(inputfile)
1026
1027 # If not all coefficients are printed, the logfile will go right to
1028 # the beta section if there is one, so break out in that case.
1029 if "BETA SET" in numbers:
1030 line = numbers
1031 break
1032
1033 # Sometimes there are some blank lines here.
1034 while not line.strip():
1035 line = next(inputfile)
1036
1037 # Geometry optimizations don't have END OF RHF/DFT
1038 # CALCULATION, they head right into the next section.
1039 if "--------" in line:
1040 break
1041
1042 # Eigenvalues for these orbitals (in hartrees).
1043 try:
1044 self.moenergies[0].extend([utils.convertor(float(x), "hartree", "eV") for x in line.split()])
1045 except:
1046 self.logger.warning('MO section found but could not be parsed!')
1047 break
1048
1049 # Orbital symmetries.
1050 line = next(inputfile)
1051 if line.strip():
1052 self.mosyms[0].extend(list(map(self.normalisesym, line.split())))
1053
1054 # Now we have nbasis lines. We will use the same method as in normalise_aonames() before.
1055 p = re.compile("(\d+)\s*([A-Z][A-Z]?)\s*(\d+)\s*([A-Z]+)")
1056 oldatom = '0'
1057 i_atom = 0 # counter to keep track of n_atoms > 99
1058 flag_w = True # flag necessary to keep from adding 100's at wrong time
1059
1060 for i in range(self.nbasis):
1061 line = next(inputfile)
1062
1063 # If line is empty, break (ex. for FMO in exam37 which is a regression).
1064 if not line.strip():
1065 break
1066
1067 # Fill atombasis and aonames only first time around
1068 if readatombasis and base == 0:
1069
1070 aonames = []
1071 start = line[:17].strip()
1072 m = p.search(start)
1073
1074 if m:
1075 g = m.groups()
1076 g2 = int(g[2]) # atom index in GAMESS file; changes to 0 after 99
1077
1078 # Check if we have moved to a hundred
1079 # if so, increment the counter and add it to the parsed value
1080 # There will be subsequent 0's as that atoms AO's are parsed
1081 # so wait until the next atom is parsed before resetting flag
1082 if g2 == 0 and flag_w:
1083 i_atom = i_atom + 100
1084 flag_w = False # handle subsequent AO's
1085 if g2 != 0:
1086 flag_w = True # reset flag
1087 g2 = g2 + i_atom
1088
1089 aoname = "%s%i_%s" % (g[1].capitalize(), g2, g[3])
1090 oldatom = str(g2)
1091 atomno = g2-1
1092 orbno = int(g[0])-1
1093 else: # For F orbitals, as shown above
1094 g = [x.strip() for x in line.split()]
1095 aoname = "%s%s_%s" % (g[1].capitalize(), oldatom, g[2])
1096 atomno = int(oldatom)-1
1097 orbno = int(g[0])-1
1098
1099 self.atombasis[atomno].append(orbno)
1100 self.aonames.append(aoname)
1101
1102 coeffs = line[15:] # Strip off the crud at the start.
1103 j = 0
1104 while j*11+4 < len(coeffs):
1105 self.mocoeffs[0][base+j, i] = float(coeffs[j * 11:(j + 1) * 11])
1106 j += 1
1107
1108 # If it's a restricted calc and no more properties, we have:
1109 #
1110 # ...... END OF RHF/DFT CALCULATION ......
1111 #
1112 # If there are more properties (such as the density matrix):
1113 # --------------
1114 #
1115 # If it's an unrestricted calculation, however, we now get the beta orbitals:
1116 #
1117 # ----- BETA SET -----
1118 #
1119 # ------------
1120 # EIGENVECTORS
1121 # ------------
1122 #
1123 # 1 2 3 4 5
1124 # ...
1125 #
1126 if "BETA SET" not in line:
1127 line = next(inputfile)
1128 line = next(inputfile)
1129
1130 # This can come in between the alpha and beta orbitals (see #130).
1131 if line.strip() == "LZ VALUE ANALYSIS FOR THE MOS":
1132 while line.strip():
1133 line = next(inputfile)
1134 line = next(inputfile)
1135
1136 # Covers label with both dashes and stars (like regression CdtetraM1B3LYP).
1137 if "BETA SET" in line:
1138 self.mocoeffs.append(numpy.zeros((self.nmo, self.nbasis), "d"))
1139 self.moenergies.append([])
1140 self.mosyms.append([])
1141 blank = next(inputfile)
1142 line = next(inputfile)
1143
1144 # Sometimes EIGENVECTORS is missing, so rely on dashes to signal it.
1145 if set(line.strip()) == {'-'}:
1146 self.skip_lines(inputfile, ['EIGENVECTORS', 'd', 'b'])
1147 line = next(inputfile)
1148
1149 for base in range(0, self.nmo, 5):
1150 self.updateprogress(inputfile, "Coefficients")
1151 if base != 0:
1152 line = next(inputfile)
1153 line = next(inputfile)
1154 line = next(inputfile)
1155 if "properties" in line.lower():
1156 break
1157 self.moenergies[1].extend([utils.convertor(float(x), "hartree", "eV") for x in line.split()])
1158 line = next(inputfile)
1159 self.mosyms[1].extend(list(map(self.normalisesym, line.split())))
1160 for i in range(self.nbasis):
1161 line = next(inputfile)
1162 temp = line[15:] # Strip off the crud at the start
1163 j = 0
1164 while j * 11 + 4 < len(temp):
1165 self.mocoeffs[1][base+j, i] = float(temp[j * 11:(j + 1) * 11])
1166 j += 1
1167 line = next(inputfile)
1168 self.moenergies = [numpy.array(x, "d") for x in self.moenergies]
1169
1170 # Natural orbital coefficients and occupation numbers, presently supported only
1171 # for CIS calculations. Looks the same as eigenvectors, without symmetry labels.
1172 #
1173 # --------------------
1174 # CIS NATURAL ORBITALS
1175 # --------------------
1176 #
1177 # 1 2 3 4 5
1178 #
1179 # 2.0158 2.0036 2.0000 2.0000 1.0000
1180 #
1181 # 1 O 1 S 0.000000 -0.157316 0.999428 0.164938 0.000000
1182 # 2 O 1 S 0.000000 0.754402 0.004472 -0.581970 0.000000
1183 # ...
1184 #
1185 if line[10:30] == "CIS NATURAL ORBITALS":
1186
1187 self.nocoeffs = numpy.zeros((self.nmo, self.nbasis), "d")
1188 self.nooccnos = []
1189
1190 self.skip_line(inputfile, 'dashes')
1191
1192 for base in range(0, self.nmo, 5):
1193
1194 self.skip_lines(inputfile, ['blank', 'numbers'])
1195
1196 # The eigenvalues that go along with these natural orbitals are
1197 # their occupation numbers. Sometimes there are blank lines before them.
1198 line = next(inputfile)
1199 while not line.strip():
1200 line = next(inputfile)
1201 eigenvalues = map(float, line.split())
1202 self.nooccnos.extend(eigenvalues)
1203
1204 # Orbital symemtry labels are normally here for MO coefficients.
1205 line = next(inputfile)
1206
1207 # Now we have nbasis lines with the coefficients.
1208 for i in range(self.nbasis):
1209
1210 line = next(inputfile)
1211 coeffs = line[15:]
1212 j = 0
1213 while j*11+4 < len(coeffs):
1214 self.nocoeffs[base+j, i] = float(coeffs[j * 11:(j + 1) * 11])
1215 j += 1
1216
1217 # We cannot trust this self.homos until we come to the phrase:
1218 # SYMMETRIES FOR INITAL GUESS ORBITALS FOLLOW
1219 # which either is followed by "ALPHA" or "BOTH" at which point we can say
1220 # for certain that it is an un/restricted calculations.
1221 # Note that MCSCF calcs also print this search string, so make sure
1222 # that self.homos does not exist yet.
1223 if line[1:28] == "NUMBER OF OCCUPIED ORBITALS" and not hasattr(self, 'homos'):
1224
1225 homos = [int(line.split()[-1])-1]
1226 line = next(inputfile)
1227 homos.append(int(line.split()[-1])-1)
1228
1229 self.set_attribute('homos', homos)
1230
1231 if line.find("SYMMETRIES FOR INITIAL GUESS ORBITALS FOLLOW") >= 0:
1232 # Not unrestricted, so lop off the second index.
1233 # In case the search string above was not used (ex. FMO in exam38),
1234 # we can try to use the next line which should also contain the
1235 # number of occupied orbitals.
1236 if line.find("BOTH SET(S)") >= 0:
1237 nextline = next(inputfile)
1238 if "ORBITALS ARE OCCUPIED" in nextline:
1239 homos = int(nextline.split()[0])-1
1240 if hasattr(self, "homos"):
1241 try:
1242 assert self.homos[0] == homos
1243 except AssertionError:
1244 self.logger.warning("Number of occupied orbitals not consistent. This is normal for ECP and FMO jobs.")
1245 else:
1246 self.homos = [homos]
1247 self.homos = numpy.resize(self.homos, [1])
1248
1249 # Set the total number of atoms, only once.
1250 # Normally GAMESS print TOTAL NUMBER OF ATOMS, however in some cases
1251 # this is slightly different (ex. lower case for FMO in exam37).
1252 if not hasattr(self, "natom") and "NUMBER OF ATOMS" in line.upper():
1253 natom = int(line.split()[-1])
1254 self.set_attribute('natom', natom)
1255
1256 # The first is from Julien's Example and the second is from Alexander's
1257 # I think it happens if you use a polar basis function instead of a cartesian one
1258 if line.find("NUMBER OF CARTESIAN GAUSSIAN BASIS") == 1 or line.find("TOTAL NUMBER OF BASIS FUNCTIONS") == 1:
1259 nbasis = int(line.strip().split()[-1])
1260 self.set_attribute('nbasis', nbasis)
1261
1262 elif line.find("TOTAL NUMBER OF CONTAMINANTS DROPPED") >= 0:
1263 nmos_dropped = int(line.split()[-1])
1264 if hasattr(self, "nmo"):
1265 self.set_attribute('nmo', self.nmo - nmos_dropped)
1266 else:
1267 self.set_attribute('nmo', self.nbasis - nmos_dropped)
1268
1269 # Note that this line is present if ISPHER=1, e.g. for C_bigbasis
1270 elif line.find("SPHERICAL HARMONICS KEPT IN THE VARIATION SPACE") >= 0:
1271 nmo = int(line.strip().split()[-1])
1272 self.set_attribute('nmo', nmo)
1273
1274 # Note that this line is not always present, so by default
1275 # NBsUse is set equal to NBasis (see below).
1276 elif line.find("TOTAL NUMBER OF MOS IN VARIATION SPACE") == 1:
1277 nmo = int(line.split()[-1])
1278 self.set_attribute('nmo', nmo)
1279
1280 elif line.find("OVERLAP MATRIX") == 0 or line.find("OVERLAP MATRIX") == 1:
1281 # The first is for PC-GAMESS, the second for GAMESS
1282 # Read 1-electron overlap matrix
1283 if not hasattr(self, "aooverlaps"):
1284 self.aooverlaps = numpy.zeros((self.nbasis, self.nbasis), "d")
1285 else:
1286 self.logger.info("Reading additional aooverlaps...")
1287 base = 0
1288 while base < self.nbasis:
1289 self.updateprogress(inputfile, "Overlap")
1290
1291 self.skip_lines(inputfile, ['b', 'basis_fn_number', 'b'])
1292
1293 for i in range(self.nbasis - base): # Fewer lines each time
1294 line = next(inputfile)
1295 temp = line.split()
1296 for j in range(4, len(temp)):
1297 self.aooverlaps[base+j-4, i+base] = float(temp[j])
1298 self.aooverlaps[i+base, base+j-4] = float(temp[j])
1299 base += 5
1300
1301 # ECP Pseudopotential information
1302 if "ECP POTENTIALS" in line:
1303 if not hasattr(self, "coreelectrons"):
1304 self.coreelectrons = [0]*self.natom
1305
1306 self.skip_lines(inputfile, ['d', 'b'])
1307
1308 header = next(inputfile)
1309 while header.split()[0] == "PARAMETERS":
1310 name = header[17:25]
1311 atomnum = int(header[34:40])
1312 # The pseudopotnetial is given explicitely
1313 if header[40:50] == "WITH ZCORE":
1314 zcore = int(header[50:55])
1315 lmax = int(header[63:67])
1316 self.coreelectrons[atomnum-1] = zcore
1317 # The pseudopotnetial is copied from another atom
1318 if header[40:55] == "ARE THE SAME AS":
1319 atomcopy = int(header[60:])
1320 self.coreelectrons[atomnum-1] = self.coreelectrons[atomcopy-1]
1321 line = next(inputfile)
1322 while line.split() != []:
1323 line = next(inputfile)
1324 header = next(inputfile)
1325
1326 # This was used before refactoring the parser, geotargets was set here after parsing.
1327 #if not hasattr(self, "geotargets"):
1328 # opttol = 1e-4
1329 # self.geotargets = numpy.array([opttol, 3. / opttol], "d")
1330 #if hasattr(self,"geovalues"): self.geovalues = numpy.array(self.geovalues, "d")
1331
1332 # This is quite simple to parse, but some files seem to print certain lines twice,
1333 # repeating the populations without charges, but not in proper order.
1334 # The unrestricted calculations are a bit tricky, since GAMESS-US prints populations
1335 # for both alpha and beta orbitals in the same format and with the same title,
1336 # but it still prints the charges only at the very end.
1337 if "TOTAL MULLIKEN AND LOWDIN ATOMIC POPULATIONS" in line:
1338
1339 if not hasattr(self, "atomcharges"):
1340 self.atomcharges = {}
1341
1342 header = next(inputfile)
1343 line = next(inputfile)
1344
1345 # It seems that when population are printed twice (without charges),
1346 # there is a blank line along the way (after the first header),
1347 # so let's get a flag out of that circumstance.
1348 doubles_printed = line.strip() == ""
1349 if doubles_printed:
1350 title = next(inputfile)
1351 header = next(inputfile)
1352 line = next(inputfile)
1353
1354 # Only go further if the header had five columns, which should
1355 # be the case when both populations and charges are printed.
1356 # This is pertinent for both double printing and unrestricted output.
1357 if not len(header.split()) == 5:
1358 return
1359 mulliken, lowdin = [], []
1360 while line.strip():
1361 if line.strip() and doubles_printed:
1362 line = next(inputfile)
1363 mulliken.append(float(line.split()[3]))
1364 lowdin.append(float(line.split()[5]))
1365 line = next(inputfile)
1366 self.atomcharges["mulliken"] = mulliken
1367 self.atomcharges["lowdin"] = lowdin
1368
1369 # ---------------------
1370 # ELECTROSTATIC MOMENTS
1371 # ---------------------
1372 #
1373 # POINT 1 X Y Z (BOHR) CHARGE
1374 # -0.000000 0.000000 0.000000 -0.00 (A.U.)
1375 # DX DY DZ /D/ (DEBYE)
1376 # 0.000000 -0.000000 0.000000 0.000000
1377 #
1378 if line.strip() == "ELECTROSTATIC MOMENTS":
1379
1380 self.skip_lines(inputfile, ['d', 'b'])
1381 line = next(inputfile)
1382
1383 # The old PC-GAMESS prints memory assignment information here.
1384 if "MEMORY ASSIGNMENT" in line:
1385 memory_assignment = next(inputfile)
1386 line = next(inputfile)
1387
1388 # If something else ever comes up, we should get a signal from this assert.
1389 assert line.split()[0] == "POINT"
1390
1391 # We can get the reference point from here, as well as
1392 # check here that the net charge of the molecule is correct.
1393 coords_and_charge = next(inputfile)
1394 assert coords_and_charge.split()[-1] == '(A.U.)'
1395 reference = numpy.array([float(x) for x in coords_and_charge.split()[:3]])
1396 reference = utils.convertor(reference, 'bohr', 'Angstrom')
1397 charge = int(round(float(coords_and_charge.split()[-2])))
1398 self.set_attribute('charge', charge)
1399
1400 dipoleheader = next(inputfile)
1401 assert dipoleheader.split()[:3] == ['DX', 'DY', 'DZ']
1402 assert dipoleheader.split()[-1] == "(DEBYE)"
1403
1404 dipoleline = next(inputfile)
1405 dipole = [float(d) for d in dipoleline.split()[:3]]
1406
1407 # The dipole is always the first multipole moment to be printed,
1408 # so if it already exists, we will overwrite all moments since we want
1409 # to leave just the last printed value (could change in the future).
1410 if not hasattr(self, 'moments'):
1411 self.moments = [reference, dipole]
1412 else:
1413 try:
1414 assert self.moments[1] == dipole
1415 except AssertionError:
1416 self.logger.warning('Overwriting previous multipole moments with new values')
1417 self.logger.warning('This could be from post-HF properties or geometry optimization')
1418 self.moments = [reference, dipole]
1419
1420 # Static polarizability from a harmonic frequency calculation
1421 # with $CPHF/POLAR=.TRUE.
1422 if line.strip() == 'ALPHA POLARIZABILITY TENSOR (ANGSTROMS**3)':
1423 if not hasattr(self, 'polarizabilities'):
1424 self.polarizabilities = []
1425 polarizability = numpy.zeros(shape=(3, 3))
1426 self.skip_lines(inputfile, ['d', 'b', 'directions'])
1427 for i in range(3):
1428 line = next(inputfile)
1429 polarizability[i, :i+1] = [float(x) for x in line.split()[1:]]
1430 polarizability = utils.symmetrize(polarizability, use_triangle='lower')
1431 # Convert from Angstrom**3 to bohr**3 (a.u.**3).
1432 volume_convert = numpy.vectorize(lambda x: x * utils.convertor(1, 'Angstrom', 'bohr') ** 3)
1433 polarizability = volume_convert(polarizability)
1434 self.polarizabilities.append(polarizability)
1435
1436 # Static and dynamic polarizability from RUNTYP=TDHF.
1437 if line.strip() == 'TIME-DEPENDENT HARTREE-FOCK NLO PROPERTIES':
1438 if not hasattr(self, 'polarizabilities'):
1439 self.polarizabilities = []
1440 polarizability = numpy.empty(shape=(3, 3))
1441 coord_to_idx = {'X': 0, 'Y': 1, 'Z': 2}
1442 self.skip_lines(inputfile, ['d', 'b', 'dots'])
1443 line = next(inputfile)
1444 assert 'ALPHA AT' in line
1445 self.skip_lines(inputfile, ['dots', 'b'])
1446 for a in range(3):
1447 for b in range(3):
1448 line = next(inputfile)
1449 tokens = line.split()
1450 i, j = coord_to_idx[tokens[1][0]], coord_to_idx[tokens[1][1]]
1451 polarizability[i, j] = tokens[3]
1452 self.polarizabilities.append(polarizability)
1453
1454 if line[:30] == ' ddikick.x: exited gracefully.'\
1455 or line[:41] == ' EXECUTION OF FIREFLY TERMINATED NORMALLY'\
1456 or line[:40] == ' EXECUTION OF GAMESS TERMINATED NORMALLY':
1457 self.metadata['success'] = True