Debian Codegraph @

cclib/parser/qchemparser.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 Q-Chem output files"""
9
10 from __future__ import division
11 from __future__ import print_function
12
13 import itertools
14 import re
15
16 import numpy
17
18 from cclib.parser import logfileparser
19 from cclib.parser import utils
20
21
22 class QChem(logfileparser.Logfile):
23 """A Q-Chem log file."""
24
25 def __init__(self, *args, **kwargs):
26
27 # Call the __init__ method of the superclass
28 super(QChem, self).__init__(logname="QChem", *args, **kwargs)
29
30 def __str__(self):
31 """Return a string representation of the object."""
32 return "QChem log file %s" % (self.filename)
33
34 def __repr__(self):
35 """Return a representation of the object."""
36 return 'QChem("%s")' % (self.filename)
37
38 def normalisesym(self, label):
39 """Q-Chem does not require normalizing symmetry labels."""
40 return label
41
42 def before_parsing(self):
43
44 # Keep track of whether or not we're performing an
45 # (un)restricted calculation.
46 self.unrestricted = False
47 self.is_rohf = False
48
49 # Keep track of whether or not this is a fragment calculation,
50 # so that only the supersystem is parsed.
51 self.is_fragment_section = False
52 # These headers identify when a fragment section is
53 # entered/exited.
54 self.fragment_section_headers = (
55 'Guess MOs from converged MOs on fragments',
56 'CP correction for fragment',
57 )
58 self.supersystem_section_headers = (
59 'Done with SCF on isolated fragments',
60 'Done with counterpoise correction on fragments',
61 )
62
63 # Compile the dashes-and-or-spaces-only regex.
64 self.re_dashes_and_spaces = re.compile('^[\s-]+$')
65
66 # Compile the regex for extracting the atomic index from an
67 # aoname.
68 self.re_atomindex = re.compile('(\d+)_')
69
70 # A maximum of 6 columns per block when printing matrices. The
71 # Fock matrix is 4.
72 self.ncolsblock = 6
73
74 # By default, when asked to print orbitals via
75 # `scf_print`/`scf_final_print` and/or `print_orbitals`,
76 # Q-Chem will print all occupieds and the first 5 virtuals.
77 #
78 # When the number is set for `print_orbitals`, that section of
79 # the output will display (NOcc + that many virtual) MOs, but
80 # any other sections present due to
81 # `scf_print`/`scf_final_print` will still only display (NOcc
82 # + 5) MOs. It is the `print_orbitals` section that `aonames`
83 # is parsed from.
84 #
85 # Note that the (AO basis) density matrix is always (NBasis *
86 # NBasis)!
87 self.norbdisp_alpha = self.norbdisp_beta = 5
88 self.norbdisp_alpha_aonames = self.norbdisp_beta_aonames = 5
89 self.norbdisp_set = False
90
91 self.alpha_mo_coefficient_headers = (
92 'RESTRICTED (RHF) MOLECULAR ORBITAL COEFFICIENTS',
93 'ALPHA MOLECULAR ORBITAL COEFFICIENTS'
94 )
95
96 self.gradient_headers = (
97 'Full Analytical Gradient',
98 'Gradient of SCF Energy',
99 'Gradient of MP2 Energy',
100 )
101
102 self.hessian_headers = (
103 'Hessian of the SCF Energy',
104 'Final Hessian.',
105 )
106
107 self.wfn_method = [
108 'HF',
109 'MP2', 'RI-MP2', 'LOCAL_MP2', 'MP4',
110 'CCD', 'CCSD', 'CCSD(T)',
111 'QCISD', 'QCISD(T)'
112 ]
113
114 def after_parsing(self):
115
116 # If parsing a fragment job, each of the geometries appended to
117 # `atomcoords` may be of different lengths, which will prevent
118 # conversion from a list to NumPy array.
119 # Take the length of the first geometry as correct, and remove
120 # all others with different lengths.
121 if len(self.atomcoords) > 1:
122 correctlen = len(self.atomcoords[0])
123 self.atomcoords[:] = [coords for coords in self.atomcoords
124 if len(coords) == correctlen]
125 # At the moment, there is no similar correction for other properties!
126
127 # QChem does not print all MO coefficients by default, but rather
128 # up to HOMO+5. So, fill up the missing values with NaNs. If there are
129 # other cases where coefficient are missing, but different ones, this
130 # general afterthought might not be appropriate and the fix will
131 # need to be done while parsing.
132 if hasattr(self, 'mocoeffs'):
133 for im in range(len(self.mocoeffs)):
134 _nmo, _nbasis = self.mocoeffs[im].shape
135 if (_nmo, _nbasis) != (self.nmo, self.nbasis):
136 coeffs = numpy.empty((self.nmo, self.nbasis))
137 coeffs[:] = numpy.nan
138 coeffs[0:_nmo, 0:_nbasis] = self.mocoeffs[im]
139 self.mocoeffs[im] = coeffs
140
141 # When parsing the 'MOLECULAR ORBITAL COEFFICIENTS' block for
142 # `aonames`, Q-Chem doesn't print the principal quantum number
143 # for each shell; this needs to be added.
144 if hasattr(self, 'aonames') and hasattr(self, 'atombasis'):
145 angmom = ('', 'S', 'P', 'D', 'F', 'G', 'H', 'I')
146 for atom in self.atombasis:
147 bfcounts = dict()
148 for bfindex in atom:
149 atomname, bfname = self.aonames[bfindex].split('_')
150 # Keep track of how many times each shell type has
151 # appeared.
152 if bfname in bfcounts:
153 bfcounts[bfname] += 1
154 else:
155 # Make sure the starting number for type of
156 # angular momentum begins at the appropriate
157 # principal quantum number (1S, 2P, 3D, 4F,
158 # ...).
159 bfcounts[bfname] = angmom.index(bfname[0])
160 newbfname = '{}{}'.format(bfcounts[bfname], bfname)
161 self.aonames[bfindex] = '_'.join([atomname, newbfname])
162
163 # Assign the number of core electrons replaced by ECPs.
164 if hasattr(self, 'user_input') and self.user_input.get('rem') is not None:
165 if self.user_input['rem'].get('ecp') is not None:
166 ecp_is_gen = (self.user_input['rem']['ecp'] == 'gen')
167 if ecp_is_gen:
168 assert 'ecp' in self.user_input
169 has_iprint = hasattr(self, 'possible_ecps')
170
171 if not ecp_is_gen and not has_iprint:
172 msg = """ECPs are present, but the number of core \
173 electrons isn't printed at all. Rerun with "iprint >= 100" to get \
174 coreelectrons."""
175 self.logger.warning(msg)
176 self.incorrect_coreelectrons = True
177 elif ecp_is_gen and not has_iprint:
178 nmissing = sum(ncore == 0
179 for (_, _, ncore) in self.user_input['ecp'])
180 if nmissing > 1:
181 msg = """ECPs are present, but coreelectrons can only \
182 be guessed for one element at most. Rerun with "iprint >= 100" to get \
183 coreelectrons."""
184 self.logger.warning(msg)
185 self.incorrect_coreelectrons = True
186 elif self.user_input['molecule'].get('charge') is None:
187 msg = """ECPs are present, but the total charge \
188 cannot be determined. Rerun without `$molecule read`."""
189 self.logger.warning(msg)
190 self.incorrect_coreelectrons = True
191 else:
192 user_charge = self.user_input['molecule']['charge']
193 # First, assign the entries given
194 # explicitly.
195 for entry in self.user_input['ecp']:
196 element, _, ncore = entry
197 if ncore > 0:
198 self._assign_coreelectrons_to_element(element, ncore)
199 # Because of how the charge is calculated
200 # during extract(), this is the number of
201 # remaining core electrons that need to be
202 # assigned ECP centers. Filter out the
203 # remaining entries, of which there should
204 # only be one.
205 core_sum = self.coreelectrons.sum() if hasattr(self, 'coreelectrons') else 0
206 remainder = self.charge - user_charge - core_sum
207 entries = [entry
208 for entry in self.user_input['ecp']
209 if entry[2] == 0]
210 if len(entries) != 0:
211 assert len(entries) == 1
212 element, _, ncore = entries[0]
213 assert ncore == 0
214 self._assign_coreelectrons_to_element(
215 element, remainder, ncore_is_total_count=True)
216 elif not ecp_is_gen and has_iprint:
217 atomsymbols = [self.table.element[atomno] for atomno in self.atomnos]
218 for i in range(self.natom):
219 if atomsymbols[i] in self.possible_ecps:
220 self.coreelectrons[i] = self.possible_ecps[atomsymbols[i]]
221 else:
222 assert ecp_is_gen and has_iprint
223 for entry in self.user_input['ecp']:
224 element, _, ncore = entry
225 # If ncore is non-zero, then it must be
226 # user-defined, and we take that
227 # value. Otherwise, look it up.
228 if ncore == 0:
229 ncore = self.possible_ecps[element]
230 self._assign_coreelectrons_to_element(element, ncore)
231
232 # Check to see if the charge is consistent with the input
233 # section. It may not be if using an ECP.
234 if hasattr(self, 'user_input'):
235 if self.user_input.get('molecule') is not None:
236 user_charge = self.user_input['molecule'].get('charge')
237 if user_charge is not None:
238 self.set_attribute('charge', user_charge)
239
240 def parse_charge_section(self, inputfile, chargetype):
241 """Parse the population analysis charge block."""
242 self.skip_line(inputfile, 'blank')
243 line = next(inputfile)
244 has_spins = False
245 if 'Spin' in line:
246 if not hasattr(self, 'atomspins'):
247 self.atomspins = dict()
248 has_spins = True
249 spins = []
250 self.skip_line(inputfile, 'dashes')
251 if not hasattr(self, 'atomcharges'):
252 self.atomcharges = dict()
253 charges = []
254 line = next(inputfile)
255
256 while list(set(line.strip())) != ['-']:
257 elements = line.split()
258 charge = self.float(elements[2])
259 charges.append(charge)
260 if has_spins:
261 spin = self.float(elements[3])
262 spins.append(spin)
263 line = next(inputfile)
264
265 self.atomcharges[chargetype] = numpy.array(charges)
266 if has_spins:
267 self.atomspins[chargetype] = numpy.array(spins)
268
269 @staticmethod
270 def parse_matrix(inputfile, nrows, ncols, ncolsblock):
271 """Q-Chem prints most matrices in a standard format; parse the matrix
272 into a NumPy array of the appropriate shape.
273 """
274 nparray = numpy.empty(shape=(nrows, ncols))
275 line = next(inputfile)
276 assert len(line.split()) == min(ncolsblock, ncols)
277 colcounter = 0
278 while colcounter < ncols:
279 # If the line is just the column header (indices)...
280 if line[:5].strip() == '':
281 line = next(inputfile)
282 rowcounter = 0
283 while rowcounter < nrows:
284 row = list(map(float, line.split()[1:]))
285 assert len(row) == min(ncolsblock, (ncols - colcounter))
286 nparray[rowcounter][colcounter:colcounter + ncolsblock] = row
287 line = next(inputfile)
288 rowcounter += 1
289 colcounter += ncolsblock
290 return nparray
291
292 def parse_matrix_aonames(self, inputfile, nrows, ncols):
293 """Q-Chem prints most matrices in a standard format; parse the matrix
294 into a preallocated NumPy array of the appropriate shape.
295
296 Rather than have one routine for parsing all general matrices
297 and the 'MOLECULAR ORBITAL COEFFICIENTS' block, use a second
298 which handles `aonames`.
299 """
300 bigmom = ('d', 'f', 'g', 'h')
301 nparray = numpy.empty(shape=(nrows, ncols))
302 line = next(inputfile)
303 assert len(line.split()) == min(self.ncolsblock, ncols)
304 colcounter = 0
305 split_fixed = utils.WidthSplitter((4, 3, 5, 6, 10, 10, 10, 10, 10, 10))
306 while colcounter < ncols:
307 # If the line is just the column header (indices)...
308 if line[:5].strip() == '':
309 line = next(inputfile)
310 # Do nothing for now.
311 if 'eigenvalues' in line:
312 line = next(inputfile)
313 rowcounter = 0
314 while rowcounter < nrows:
315 row = split_fixed.split(line)
316 # Only take the AO names on the first time through.
317 if colcounter == 0:
318 if len(self.aonames) != self.nbasis:
319 # Apply the offset for rows where there is
320 # more than one atom of any element in the
321 # molecule.
322 offset = 1
323 if row[2] != '':
324 name = self.atommap.get(row[1] + str(row[2]))
325 else:
326 name = self.atommap.get(row[1] + '1')
327 # For l > 1, there is a space between l and
328 # m_l when using spherical functions.
329 shell = row[2 + offset]
330 if shell in bigmom:
331 shell = ''.join([shell, row[3 + offset]])
332 aoname = ''.join([name, '_', shell.upper()])
333 self.aonames.append(aoname)
334 row = list(map(float, row[-min(self.ncolsblock, (ncols - colcounter)):]))
335 nparray[rowcounter][colcounter:colcounter + self.ncolsblock] = row
336 line = next(inputfile)
337 rowcounter += 1
338 colcounter += self.ncolsblock
339 return nparray
340
341 def parse_orbital_energies_and_symmetries(self, inputfile):
342 """Parse the 'Orbital Energies (a.u.)' block appearing after SCF converges,
343 which optionally includes MO symmetries. Based upon the
344 Occupied/Virtual labeling, the HOMO is also parsed.
345 """
346 energies = []
347 symbols = []
348
349 line = next(inputfile)
350 # Sometimes Q-Chem gets a little confused...
351 while "MOs" not in line:
352 line = next(inputfile)
353 line = next(inputfile)
354
355 # The end of the block is either a blank line or only dashes.
356 while not self.re_dashes_and_spaces.search(line) \
357 and not 'Warning : Irrep of orbital' in line:
358 if 'Occupied' in line or 'Virtual' in line:
359 # A nice trick to find where the HOMO is.
360 if 'Virtual' in line:
361 homo = len(energies) - 1
362 line = next(inputfile)
363 tokens = line.split()
364 # If the line contains letters, it must be the MO
365 # symmetries. Otherwise, it's the energies.
366 if re.search("[a-zA-Z]", line):
367 symbols.extend(tokens[1::2])
368 else:
369 for e in tokens:
370 try:
371 energy = utils.convertor(self.float(e), 'hartree', 'eV')
372 except ValueError:
373 energy = numpy.nan
374 energies.append(energy)
375 line = next(inputfile)
376
377 # MO symmetries are either not present or there is one for each MO
378 # (energy).
379 assert len(symbols) in (0, len(energies))
380
381 return energies, symbols, homo
382
383
384 def generate_atom_map(self):
385 """Generate the map to go from Q-Chem atom numbering:
386 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'H1', 'H2', 'H3', 'H4', 'C7', ...
387 to cclib atom numbering:
388 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'H7', 'H8', 'H9', 'H10', 'C11', ...
389 for later use.
390 """
391
392 # Generate the desired order.
393 order_proper = [element + str(num)
394 for element, num in zip(self.atomelements,
395 itertools.count(start=1))]
396 # We need separate counters for each element.
397 element_counters = {element: itertools.count(start=1)
398 for element in set(self.atomelements)}
399 # Generate the Q-Chem printed order.
400 order_qchem = [element + str(next(element_counters[element]))
401 for element in self.atomelements]
402 # Combine the orders into a mapping.
403 atommap = {k: v for k, v, in zip(order_qchem, order_proper)}
404 return atommap
405
406 def generate_formula_histogram(self):
407 """From the atomnos, generate a histogram that represents the
408 molecular formula.
409 """
410
411 histogram = dict()
412 for element in self.atomelements:
413 if element in histogram.keys():
414 histogram[element] += 1
415 else:
416 histogram[element] = 1
417 return histogram
418
419 def extract(self, inputfile, line):
420 """Extract information from the file object inputfile."""
421
422 # Extract the version number and optionally the version
423 # control info.
424 if "Q-Chem" in line:
425 match = re.search(r"Q-Chem\s([0-9\.]*)\sfor", line)
426 if match:
427 self.metadata["package_version"] = match.groups()[0]
428 # Don't add revision information to the main package version for now.
429 if "SVN revision" in line:
430 revision = line.split()[3]
431
432 # Disable/enable parsing for fragment sections.
433 if any(message in line for message in self.fragment_section_headers):
434 self.is_fragment_section = True
435 if any(message in line for message in self.supersystem_section_headers):
436 self.is_fragment_section = False
437
438 if not self.is_fragment_section:
439
440 # If the input section is repeated back, parse the $rem and
441 # $molecule sections.
442 if line[0:11] == 'User input:':
443 self.user_input = dict()
444 self.skip_line(inputfile, 'd')
445 while list(set(line.strip())) != ['-']:
446
447 if line.strip().lower() == '$rem':
448
449 self.user_input['rem'] = dict()
450
451 while line.strip().lower() != '$end':
452
453 line = next(inputfile).lower()
454 if line.strip() == '$end':
455 break
456 # Apparently calculations can run without
457 # a matching $end...this terminates the
458 # user input section no matter what.
459 if line.strip() == ('-' * 62):
460 break
461
462 tokens = line.split()
463 # Allow blank lines.
464 if len(tokens) == 0:
465 continue
466 # Entries may be separated by an equals
467 # sign, and can have comments, for example:
468 # ecp gen
469 # ecp = gen
470 # ecp gen ! only on first chlorine
471 # ecp = gen only on first chlorine
472 assert len(tokens) >= 2
473 keyword = tokens[0]
474 if tokens[1] == '=':
475 option = tokens[2]
476 else:
477 option = tokens[1]
478 self.user_input['rem'][keyword] = option
479
480 if keyword == 'method':
481 method = option.upper()
482 if method in self.wfn_method:
483 self.metadata["methods"].append(method)
484 else:
485 self.metadata["methods"].append('DFT')
486 self.metadata["functional"] = method
487
488 if keyword == 'exchange':
489 self.metadata["methods"].append('DFT')
490 self.metadata["functional"] = option
491
492 if keyword == 'print_orbitals':
493 # Stay with the default value if a number isn't
494 # specified.
495 if option in ('true', 'false'):
496 continue
497 else:
498 norbdisp_aonames = int(option)
499 self.norbdisp_alpha_aonames = norbdisp_aonames
500 self.norbdisp_beta_aonames = norbdisp_aonames
501 self.norbdisp_set = True
502
503 if line.strip().lower() == '$ecp':
504
505 self.user_input['ecp'] = []
506 line = next(inputfile)
507
508 while line.strip().lower() != '$end':
509
510 while list(set(line.strip())) != ['*']:
511
512 # Parse the element for this ECP
513 # entry. If only the element is on
514 # this line, or the 2nd token is 0, it
515 # applies to all atoms; if it's > 0,
516 # then it indexes (1-based) that
517 # specific atom in the whole molecule.
518 tokens = line.split()
519 assert len(tokens) > 0
520 element = tokens[0][0].upper() + tokens[0][1:].lower()
521 assert element in self.table.element
522 if len(tokens) > 1:
523 assert len(tokens) == 2
524 index = int(tokens[1]) - 1
525 else:
526 index = -1
527 line = next(inputfile)
528
529 # Next comes the ECP definition. If
530 # the line contains only a single
531 # item, it's a built-in ECP, otherwise
532 # it's a full definition.
533 tokens = line.split()
534 if len(tokens) == 1:
535 ncore = 0
536 line = next(inputfile)
537 else:
538 assert len(tokens) == 3
539 ncore = int(tokens[2])
540 # Don't parse the remainder of the
541 # ECP definition.
542 while list(set(line.strip())) != ['*']:
543 line = next(inputfile)
544
545 entry = (element, index, ncore)
546 self.user_input['ecp'].append(entry)
547
548 line = next(inputfile)
549
550 if line.strip().lower() == '$end':
551 break
552
553 if line.strip().lower() == '$molecule':
554
555 self.user_input['molecule'] = dict()
556 line = next(inputfile)
557
558 # Don't read the molecule, only the
559 # supersystem charge and multiplicity.
560 if line.split()[0].lower() == 'read':
561 pass
562 else:
563 charge, mult = [int(x) for x in line.split()]
564 self.user_input['molecule']['charge'] = charge
565 self.user_input['molecule']['mult'] = mult
566
567 line = next(inputfile).lower()
568
569 # Parse the basis set name
570 if 'Requested basis set' in line:
571 self.metadata["basis_set"] = line.split()[-1]
572
573 # Parse the general basis for `gbasis`, in the style used by
574 # Gaussian.
575 if 'Basis set in general basis input format:' in line:
576 self.skip_lines(inputfile, ['d', '$basis'])
577 line = next(inputfile)
578 if not hasattr(self, 'gbasis'):
579 self.gbasis = []
580 # The end of the general basis block.
581 while '$end' not in line:
582 atom = []
583 # 1. Contains element symbol and atomic index of
584 # basis functions; if 0, applies to all atoms of
585 # same element.
586 assert len(line.split()) == 2
587 line = next(inputfile)
588 # The end of each atomic block.
589 while '****' not in line:
590 # 2. Contains the type of basis function {S, SP,
591 # P, D, F, G, H, ...}, the number of primitives,
592 # and the weight of the final contracted function.
593 bfsplitline = line.split()
594 assert len(bfsplitline) == 3
595 bftype = bfsplitline[0]
596 nprim = int(bfsplitline[1])
597 line = next(inputfile)
598 # 3. The primitive basis functions that compose
599 # the contracted basis function; there are `nprim`
600 # of them. The first value is the exponent, and
601 # the second value is the contraction
602 # coefficient. If `bftype == 'SP'`, the primitives
603 # are for both S- and P-type basis functions but
604 # with separate contraction coefficients,
605 # resulting in three columns.
606 if bftype == 'SP':
607 primitives_S = []
608 primitives_P = []
609 else:
610 primitives = []
611 # For each primitive in the contracted basis
612 # function...
613 for iprim in range(nprim):
614 primsplitline = line.split()
615 exponent = float(primsplitline[0])
616 if bftype == 'SP':
617 assert len(primsplitline) == 3
618 coefficient_S = float(primsplitline[1])
619 coefficient_P = float(primsplitline[2])
620 primitives_S.append((exponent, coefficient_S))
621 primitives_P.append((exponent, coefficient_P))
622 else:
623 assert len(primsplitline) == 2
624 coefficient = float(primsplitline[1])
625 primitives.append((exponent, coefficient))
626 line = next(inputfile)
627 if bftype == 'SP':
628 bf_S = ('S', primitives_S)
629 bf_P = ('P', primitives_P)
630 atom.append(bf_S)
631 atom.append(bf_P)
632 else:
633 bf = (bftype, primitives)
634 atom.append(bf)
635 # Move to the next contracted basis function
636 # as long as we don't hit the '****' atom
637 # delimiter.
638 self.gbasis.append(atom)
639 line = next(inputfile)
640
641 if line.strip() == 'The following effective core potentials will be applied':
642
643 # Keep track of all elements that may have an ECP on
644 # them. *Which* centers have an ECP can't be
645 # determined here, so just take the number of valence
646 # electrons, then later later figure out the centers
647 # and do core = Z - valence.
648 self.possible_ecps = dict()
649 # This will fail if an element has more than one kind
650 # of ECP.
651
652 split_fixed = utils.WidthSplitter((4, 13, 20, 2, 14, 14))
653
654 self.skip_lines(inputfile, ['d', 'header', 'header', 'd'])
655 line = next(inputfile)
656 while list(set(line.strip())) != ['-']:
657 tokens = split_fixed.split(line)
658 if tokens[0] != '':
659 element = tokens[0]
660 valence = int(tokens[1])
661 ncore = self.table.number[element] - valence
662 self.possible_ecps[element] = ncore
663 line = next(inputfile)
664
665 if 'TIME STEP #' in line:
666 tokens = line.split()
667 self.append_attribute('time', float(tokens[8]))
668
669 # Extract the atomic numbers and coordinates of the atoms.
670 if 'Standard Nuclear Orientation (Angstroms)' in line:
671 if not hasattr(self, 'atomcoords'):
672 self.atomcoords = []
673 self.skip_lines(inputfile, ['cols', 'dashes'])
674 atomelements = []
675 atomcoords = []
676 line = next(inputfile)
677 while list(set(line.strip())) != ['-']:
678 entry = line.split()
679 atomelements.append(entry[1])
680 atomcoords.append(list(map(float, entry[2:])))
681 line = next(inputfile)
682
683 self.atomcoords.append(atomcoords)
684
685 # We calculate and handle atomnos no matter what, since in
686 # the case of fragment calculations the atoms may change,
687 # along with the charge and spin multiplicity.
688 self.atomnos = []
689 self.atomelements = []
690 for atomelement in atomelements:
691 self.atomelements.append(atomelement)
692 if atomelement == 'GH':
693 self.atomnos.append(0)
694 else:
695 self.atomnos.append(self.table.number[atomelement])
696 self.natom = len(self.atomnos)
697 self.atommap = self.generate_atom_map()
698 self.formula_histogram = self.generate_formula_histogram()
699
700 # Number of electrons.
701 # Useful for determining the number of occupied/virtual orbitals.
702 if 'Nuclear Repulsion Energy' in line:
703 line = next(inputfile)
704 nelec_re_string = 'There are(\s+[0-9]+) alpha and(\s+[0-9]+) beta electrons'
705 match = re.findall(nelec_re_string, line.strip())
706 self.set_attribute('nalpha', int(match[0][0].strip()))
707 self.set_attribute('nbeta', int(match[0][1].strip()))
708 self.norbdisp_alpha += self.nalpha
709 self.norbdisp_alpha_aonames += self.nalpha
710 self.norbdisp_beta += self.nbeta
711 self.norbdisp_beta_aonames += self.nbeta
712 # Calculate the spin multiplicity (2S + 1), where S is the
713 # total spin of the system.
714 S = (self.nalpha - self.nbeta) / 2
715 mult = int(2 * S + 1)
716 self.set_attribute('mult', mult)
717 # Calculate the molecular charge as the difference between
718 # the atomic numbers and the number of electrons.
719 if hasattr(self, 'atomnos'):
720 charge = sum(self.atomnos) - (self.nalpha + self.nbeta)
721 self.set_attribute('charge', charge)
722
723 # Number of basis functions.
724 if 'basis functions' in line:
725 if not hasattr(self, 'nbasis'):
726 self.set_attribute('nbasis', int(line.split()[-3]))
727 # In the case that there are fewer basis functions
728 # (and therefore MOs) than default number of MOs
729 # displayed, reset the display values.
730 self.norbdisp_alpha = min(self.norbdisp_alpha, self.nbasis)
731 self.norbdisp_alpha_aonames = min(self.norbdisp_alpha_aonames, self.nbasis)
732 self.norbdisp_beta = min(self.norbdisp_beta, self.nbasis)
733 self.norbdisp_beta_aonames = min(self.norbdisp_beta_aonames, self.nbasis)
734
735 # Check for whether or not we're peforming an
736 # (un)restricted calculation.
737 if 'calculation will be' in line:
738 if ' restricted' in line:
739 self.unrestricted = False
740 if 'unrestricted' in line:
741 self.unrestricted = True
742 if hasattr(self, 'nalpha') and hasattr(self, 'nbeta'):
743 if self.nalpha != self.nbeta:
744 self.unrestricted = True
745 self.is_rohf = True
746
747 # Section with SCF iterations goes like this:
748 #
749 # SCF converges when DIIS error is below 1.0E-05
750 # ---------------------------------------
751 # Cycle Energy DIIS Error
752 # ---------------------------------------
753 # 1 -381.9238072190 1.39E-01
754 # 2 -382.2937212775 3.10E-03
755 # 3 -382.2939780242 3.37E-03
756 # ...
757 #
758 scf_success_messages = (
759 'Convergence criterion met',
760 'corrected energy'
761 )
762 scf_failure_messages = (
763 'SCF failed to converge',
764 'Convergence failure'
765 )
766 if 'SCF converges when ' in line:
767 if not hasattr(self, 'scftargets'):
768 self.scftargets = []
769 target = float(line.split()[-1])
770 self.scftargets.append([target])
771
772 # We should have the header between dashes now,
773 # but sometimes there are lines before the first dashes.
774 while not 'Cycle Energy' in line:
775 line = next(inputfile)
776 self.skip_line(inputfile, 'd')
777
778 values = []
779 iter_counter = 1
780 line = next(inputfile)
781 while not any(message in line for message in scf_success_messages):
782
783 # Some trickery to avoid a lot of printing that can occur
784 # between each SCF iteration.
785 entry = line.split()
786 if len(entry) > 0:
787 if entry[0] == str(iter_counter):
788 # Q-Chem only outputs one error metric.
789 error = float(entry[2])
790 values.append([error])
791 iter_counter += 1
792
793 try:
794 line = next(inputfile)
795 # Is this the end of the file for some reason?
796 except StopIteration:
797 self.logger.warning('File terminated before end of last SCF! Last error: {}'.format(error))
798 break
799
800 # We've converged, but still need the last iteration.
801 if any(message in line for message in scf_success_messages):
802 entry = line.split()
803 error = float(entry[2])
804 values.append([error])
805 iter_counter += 1
806
807 # This is printed in regression QChem4.2/dvb_sp_unconverged.out
808 # so use it to bail out when convergence fails.
809 if any(message in line for message in scf_failure_messages):
810 break
811
812 if not hasattr(self, 'scfvalues'):
813 self.scfvalues = []
814 self.scfvalues.append(numpy.array(values))
815
816 # Molecular orbital coefficients.
817
818 # Try parsing them from this block (which comes from
819 # `scf_final_print = 2``) rather than the combined
820 # aonames/mocoeffs/moenergies block (which comes from
821 # `print_orbitals = true`).
822 if 'Final Alpha MO Coefficients' in line:
823 if not hasattr(self, 'mocoeffs'):
824 self.mocoeffs = []
825 mocoeffs = QChem.parse_matrix(inputfile, self.nbasis, self.norbdisp_alpha, self.ncolsblock)
826 self.mocoeffs.append(mocoeffs.transpose())
827
828 if 'Final Beta MO Coefficients' in line:
829 mocoeffs = QChem.parse_matrix(inputfile, self.nbasis, self.norbdisp_beta, self.ncolsblock)
830 self.mocoeffs.append(mocoeffs.transpose())
831
832 if 'Total energy in the final basis set' in line:
833 if not hasattr(self, 'scfenergies'):
834 self.scfenergies = []
835 scfenergy = float(line.split()[-1])
836 self.scfenergies.append(utils.convertor(scfenergy, 'hartree', 'eV'))
837
838 # Geometry optimization.
839
840 if 'Maximum Tolerance Cnvgd?' in line:
841 line_g = next(inputfile).split()[1:3]
842 line_d = next(inputfile).split()[1:3]
843 line_e = next(inputfile).split()[2:4]
844
845 if not hasattr(self, 'geotargets'):
846 self.geotargets = [line_g[1], line_d[1], self.float(line_e[1])]
847 if not hasattr(self, 'geovalues'):
848 self.geovalues = []
849 maxg = self.float(line_g[0])
850 maxd = self.float(line_d[0])
851 ediff = self.float(line_e[0])
852 geovalues = [maxg, maxd, ediff]
853 self.geovalues.append(geovalues)
854
855 if '** OPTIMIZATION CONVERGED **' in line:
856 if not hasattr(self, 'optdone'):
857 self.optdone = []
858 self.optdone.append(len(self.atomcoords))
859
860 if '** MAXIMUM OPTIMIZATION CYCLES REACHED **' in line:
861 if not hasattr(self, 'optdone'):
862 self.optdone = []
863
864 # Moller-Plesset corrections.
865
866 # There are multiple modules in Q-Chem for calculating MPn energies:
867 # cdman, ccman, and ccman2, all with different output.
868 #
869 # MP2, RI-MP2, and local MP2 all default to cdman, which has a simple
870 # block of output after the regular SCF iterations.
871 #
872 # MP3 is handled by ccman2.
873 #
874 # MP4 and variants are handled by ccman.
875
876 # This is the MP2/cdman case.
877 if 'MP2 total energy' in line:
878 if not hasattr(self, 'mpenergies'):
879 self.mpenergies = []
880 mp2energy = float(line.split()[4])
881 mp2energy = utils.convertor(mp2energy, 'hartree', 'eV')
882 self.mpenergies.append([mp2energy])
883
884 # This is the MP3/ccman2 case.
885 if line[1:11] == 'MP2 energy' and line[12:19] != 'read as':
886 if not hasattr(self, 'mpenergies'):
887 self.mpenergies = []
888 mpenergies = []
889 mp2energy = float(line.split()[3])
890 mpenergies.append(mp2energy)
891 line = next(inputfile)
892 line = next(inputfile)
893 # Just a safe check.
894 if 'MP3 energy' in line:
895 mp3energy = float(line.split()[3])
896 mpenergies.append(mp3energy)
897 mpenergies = [utils.convertor(mpe, 'hartree', 'eV')
898 for mpe in mpenergies]
899 self.mpenergies.append(mpenergies)
900
901 # This is the MP4/ccman case.
902 if 'EHF' in line:
903 if not hasattr(self, 'mpenergies'):
904 self.mpenergies = []
905 mpenergies = []
906
907 while list(set(line.strip())) != ['-']:
908
909 if 'EMP2' in line:
910 mp2energy = float(line.split()[2])
911 mpenergies.append(mp2energy)
912 if 'EMP3' in line:
913 mp3energy = float(line.split()[2])
914 mpenergies.append(mp3energy)
915 if 'EMP4SDQ' in line:
916 mp4sdqenergy = float(line.split()[2])
917 mpenergies.append(mp4sdqenergy)
918 # This is really MP4SD(T)Q.
919 if 'EMP4 ' in line:
920 mp4sdtqenergy = float(line.split()[2])
921 mpenergies.append(mp4sdtqenergy)
922
923 line = next(inputfile)
924
925 mpenergies = [utils.convertor(mpe, 'hartree', 'eV')
926 for mpe in mpenergies]
927 self.mpenergies.append(mpenergies)
928
929 # Coupled cluster corrections.
930 # Hopefully we only have to deal with ccman2 here.
931
932 if 'CCD total energy' in line:
933 if not hasattr(self, 'ccenergies'):
934 self.ccenergies = []
935 ccdenergy = float(line.split()[-1])
936 ccdenergy = utils.convertor(ccdenergy, 'hartree', 'eV')
937 self.ccenergies.append(ccdenergy)
938 if 'CCSD total energy' in line:
939 has_triples = False
940 if not hasattr(self, 'ccenergies'):
941 self.ccenergies = []
942 ccsdenergy = float(line.split()[-1])
943 # Make sure we aren't actually doing CCSD(T).
944 line = next(inputfile)
945 line = next(inputfile)
946 if 'CCSD(T) total energy' in line:
947 has_triples = True
948 ccsdtenergy = float(line.split()[-1])
949 ccsdtenergy = utils.convertor(ccsdtenergy, 'hartree', 'eV')
950 self.ccenergies.append(ccsdtenergy)
951 if not has_triples:
952 ccsdenergy = utils.convertor(ccsdenergy, 'hartree', 'eV')
953 self.ccenergies.append(ccsdenergy)
954
955 # Electronic transitions. Works for both CIS and TDDFT.
956 if 'Excitation Energies' in line:
957
958 # Restricted:
959 # ---------------------------------------------------
960 # TDDFT/TDA Excitation Energies
961 # ---------------------------------------------------
962 #
963 # Excited state 1: excitation energy (eV) = 3.6052
964 # Total energy for state 1: -382.167872200685
965 # Multiplicity: Triplet
966 # Trans. Mom.: 0.0000 X 0.0000 Y 0.0000 Z
967 # Strength : 0.0000
968 # D( 33) --> V( 3) amplitude = 0.2618
969 # D( 34) --> V( 2) amplitude = 0.2125
970 # D( 35) --> V( 1) amplitude = 0.9266
971 #
972 # Unrestricted:
973 # Excited state 2: excitation energy (eV) = 2.3156
974 # Total energy for state 2: -381.980177630969
975 # <S**2> : 0.7674
976 # Trans. Mom.: -2.7680 X -0.1089 Y 0.0000 Z
977 # Strength : 0.4353
978 # S( 1) --> V( 1) amplitude = -0.3105 alpha
979 # D( 34) --> S( 1) amplitude = 0.9322 beta
980
981 self.skip_lines(inputfile, ['dashes', 'blank'])
982 line = next(inputfile)
983
984 etenergies = []
985 etsyms = []
986 etoscs = []
987 etsecs = []
988 spinmap = {'alpha': 0, 'beta': 1}
989
990 while list(set(line.strip())) != ['-']:
991
992 # Take the total energy for the state and subtract from the
993 # ground state energy, rather than just the EE;
994 # this will be more accurate.
995 if 'Total energy for state' in line:
996 energy = utils.convertor(float(line.split()[5]), 'hartree', 'wavenumber')
997 etenergy = energy - utils.convertor(self.scfenergies[-1], 'eV', 'wavenumber')
998 etenergies.append(etenergy)
999 # if 'excitation energy' in line:
1000 # etenergy = utils.convertor(float(line.split()[-1]), 'eV', 'wavenumber')
1001 # etenergies.append(etenergy)
1002 if 'Multiplicity' in line:
1003 etsym = line.split()[1]
1004 etsyms.append(etsym)
1005 if 'Strength' in line:
1006 strength = float(line.split()[-1])
1007 etoscs.append(strength)
1008
1009 # This is the list of transitions.
1010 if 'amplitude' in line:
1011 sec = []
1012 while line.strip() != '':
1013 if self.unrestricted:
1014 spin = spinmap[line[42:47].strip()]
1015 else:
1016 spin = 0
1017
1018 # There is a subtle difference between TDA and RPA calcs,
1019 # because in the latter case each transition line is
1020 # preceeded by the type of vector: X or Y, name excitation
1021 # or deexcitation (see #154 for details). For deexcitations,
1022 # we will need to reverse the MO indices. Note also that Q-Chem
1023 # starts reindexing virtual orbitals at 1.
1024 if line[5] == '(':
1025 ttype = 'X'
1026 startidx = int(line[6:9]) - 1
1027 endidx = int(line[17:20]) - 1 + self.nalpha
1028 contrib = float(line[34:41].strip())
1029 else:
1030 assert line[5] == ":"
1031 ttype = line[4]
1032 startidx = int(line[9:12]) - 1
1033 endidx = int(line[20:23]) - 1 + self.nalpha
1034 contrib = float(line[37:44].strip())
1035
1036 start = (startidx, spin)
1037 end = (endidx, spin)
1038 if ttype == 'X':
1039 sec.append([start, end, contrib])
1040 elif ttype == 'Y':
1041 sec.append([end, start, contrib])
1042 else:
1043 raise ValueError('Unknown transition type: %s' % ttype)
1044 line = next(inputfile)
1045 etsecs.append(sec)
1046
1047 line = next(inputfile)
1048
1049 self.set_attribute('etenergies', etenergies)
1050 self.set_attribute('etsyms', etsyms)
1051 self.set_attribute('etoscs', etoscs)
1052 self.set_attribute('etsecs', etsecs)
1053
1054 # Static and dynamic polarizability from mopropman.
1055 if 'Polarizability (a.u.)' in line:
1056 if not hasattr(self, 'polarizabilities'):
1057 self.polarizabilities = []
1058 while 'Full Tensor' not in line:
1059 line = next(inputfile)
1060 self.skip_line(inputfile, 'blank')
1061 polarizability = [next(inputfile).split() for _ in range(3)]
1062 self.polarizabilities.append(numpy.array(polarizability))
1063
1064 # Static polarizability from finite difference or
1065 # responseman.
1066 if line.strip() in ('Static polarizability tensor [a.u.]',
1067 'Polarizability tensor [a.u.]'):
1068 if not hasattr(self, 'polarizabilities'):
1069 self.polarizabilities = []
1070 polarizability = [next(inputfile).split() for _ in range(3)]
1071 self.polarizabilities.append(numpy.array(polarizability))
1072
1073 # Molecular orbital energies and symmetries.
1074 if line.strip() == 'Orbital Energies (a.u.) and Symmetries':
1075
1076 # --------------------------------------------------------------
1077 # Orbital Energies (a.u.) and Symmetries
1078 # --------------------------------------------------------------
1079 #
1080 # Alpha MOs, Restricted
1081 # -- Occupied --
1082 # -10.018 -10.018 -10.008 -10.008 -10.007 -10.007 -10.006 -10.005
1083 # 1 Bu 1 Ag 2 Bu 2 Ag 3 Bu 3 Ag 4 Bu 4 Ag
1084 # -9.992 -9.992 -0.818 -0.755 -0.721 -0.704 -0.670 -0.585
1085 # 5 Ag 5 Bu 6 Ag 6 Bu 7 Ag 7 Bu 8 Bu 8 Ag
1086 # -0.561 -0.532 -0.512 -0.462 -0.439 -0.410 -0.400 -0.397
1087 # 9 Ag 9 Bu 10 Ag 11 Ag 10 Bu 11 Bu 12 Bu 12 Ag
1088 # -0.376 -0.358 -0.349 -0.330 -0.305 -0.295 -0.281 -0.263
1089 # 13 Bu 14 Bu 13 Ag 1 Au 15 Bu 14 Ag 15 Ag 1 Bg
1090 # -0.216 -0.198 -0.160
1091 # 2 Au 2 Bg 3 Bg
1092 # -- Virtual --
1093 # 0.050 0.091 0.116 0.181 0.280 0.319 0.330 0.365
1094 # 3 Au 4 Au 4 Bg 5 Au 5 Bg 16 Ag 16 Bu 17 Bu
1095 # 0.370 0.413 0.416 0.422 0.446 0.469 0.496 0.539
1096 # 17 Ag 18 Bu 18 Ag 19 Bu 19 Ag 20 Bu 20 Ag 21 Ag
1097 # 0.571 0.587 0.610 0.627 0.646 0.693 0.743 0.806
1098 # 21 Bu 22 Ag 22 Bu 23 Bu 23 Ag 24 Ag 24 Bu 25 Ag
1099 # 0.816
1100 # 25 Bu
1101 #
1102 # Beta MOs, Restricted
1103 # -- Occupied --
1104 # -10.018 -10.018 -10.008 -10.008 -10.007 -10.007 -10.006 -10.005
1105 # 1 Bu 1 Ag 2 Bu 2 Ag 3 Bu 3 Ag 4 Bu 4 Ag
1106 # -9.992 -9.992 -0.818 -0.755 -0.721 -0.704 -0.670 -0.585
1107 # 5 Ag 5 Bu 6 Ag 6 Bu 7 Ag 7 Bu 8 Bu 8 Ag
1108 # -0.561 -0.532 -0.512 -0.462 -0.439 -0.410 -0.400 -0.397
1109 # 9 Ag 9 Bu 10 Ag 11 Ag 10 Bu 11 Bu 12 Bu 12 Ag
1110 # -0.376 -0.358 -0.349 -0.330 -0.305 -0.295 -0.281 -0.263
1111 # 13 Bu 14 Bu 13 Ag 1 Au 15 Bu 14 Ag 15 Ag 1 Bg
1112 # -0.216 -0.198 -0.160
1113 # 2 Au 2 Bg 3 Bg
1114 # -- Virtual --
1115 # 0.050 0.091 0.116 0.181 0.280 0.319 0.330 0.365
1116 # 3 Au 4 Au 4 Bg 5 Au 5 Bg 16 Ag 16 Bu 17 Bu
1117 # 0.370 0.413 0.416 0.422 0.446 0.469 0.496 0.539
1118 # 17 Ag 18 Bu 18 Ag 19 Bu 19 Ag 20 Bu 20 Ag 21 Ag
1119 # 0.571 0.587 0.610 0.627 0.646 0.693 0.743 0.806
1120 # 21 Bu 22 Ag 22 Bu 23 Bu 23 Ag 24 Ag 24 Bu 25 Ag
1121 # 0.816
1122 # 25 Bu
1123 # --------------------------------------------------------------
1124
1125 self.skip_line(inputfile, 'dashes')
1126 line = next(inputfile)
1127 energies_alpha, symbols_alpha, homo_alpha = self.parse_orbital_energies_and_symmetries(inputfile)
1128 # Only look at the second block if doing an unrestricted calculation.
1129 # This might be a problem for ROHF/ROKS.
1130 if self.unrestricted:
1131 energies_beta, symbols_beta, homo_beta = self.parse_orbital_energies_and_symmetries(inputfile)
1132
1133 # For now, only keep the last set of MO energies, even though it is
1134 # printed at every step of geometry optimizations and fragment jobs.
1135 self.set_attribute('moenergies', [numpy.array(energies_alpha)])
1136 self.set_attribute('homos', [homo_alpha])
1137 self.set_attribute('mosyms', [symbols_alpha])
1138 if self.unrestricted:
1139 self.moenergies.append(numpy.array(energies_beta))
1140 self.homos.append(homo_beta)
1141 self.mosyms.append(symbols_beta)
1142
1143 self.set_attribute('nmo', len(self.moenergies[0]))
1144
1145 # Molecular orbital energies, no symmetries.
1146 if line.strip() == 'Orbital Energies (a.u.)':
1147
1148 # In the case of no orbital symmetries, the beta spin block is not
1149 # present for restricted calculations.
1150
1151 # --------------------------------------------------------------
1152 # Orbital Energies (a.u.)
1153 # --------------------------------------------------------------
1154 #
1155 # Alpha MOs
1156 # -- Occupied --
1157 # ******* -38.595 -34.580 -34.579 -34.578 -19.372 -19.372 -19.364
1158 # -19.363 -19.362 -19.362 -4.738 -3.252 -3.250 -3.250 -1.379
1159 # -1.371 -1.369 -1.365 -1.364 -1.362 -0.859 -0.855 -0.849
1160 # -0.846 -0.840 -0.836 -0.810 -0.759 -0.732 -0.729 -0.704
1161 # -0.701 -0.621 -0.610 -0.595 -0.587 -0.584 -0.578 -0.411
1162 # -0.403 -0.355 -0.354 -0.352
1163 # -- Virtual --
1164 # -0.201 -0.117 -0.099 -0.086 0.020 0.031 0.055 0.067
1165 # 0.075 0.082 0.086 0.092 0.096 0.105 0.114 0.148
1166 #
1167 # Beta MOs
1168 # -- Occupied --
1169 # ******* -38.561 -34.550 -34.549 -34.549 -19.375 -19.375 -19.367
1170 # -19.367 -19.365 -19.365 -4.605 -3.105 -3.103 -3.102 -1.385
1171 # -1.376 -1.376 -1.371 -1.370 -1.368 -0.863 -0.858 -0.853
1172 # -0.849 -0.843 -0.839 -0.818 -0.765 -0.738 -0.737 -0.706
1173 # -0.702 -0.624 -0.613 -0.600 -0.591 -0.588 -0.585 -0.291
1174 # -0.291 -0.288 -0.275
1175 # -- Virtual --
1176 # -0.139 -0.122 -0.103 0.003 0.014 0.049 0.049 0.059
1177 # 0.061 0.070 0.076 0.081 0.086 0.090 0.098 0.106
1178 # 0.138
1179 # --------------------------------------------------------------
1180
1181 self.skip_line(inputfile, 'dashes')
1182 line = next(inputfile)
1183 energies_alpha, _, homo_alpha = self.parse_orbital_energies_and_symmetries(inputfile)
1184 # Only look at the second block if doing an unrestricted calculation.
1185 # This might be a problem for ROHF/ROKS.
1186 if self.unrestricted:
1187 energies_beta, _, homo_beta = self.parse_orbital_energies_and_symmetries(inputfile)
1188
1189 # For now, only keep the last set of MO energies, even though it is
1190 # printed at every step of geometry optimizations and fragment jobs.
1191 self.set_attribute('moenergies', [numpy.array(energies_alpha)])
1192 self.set_attribute('homos', [homo_alpha])
1193 if self.unrestricted:
1194 self.moenergies.append(numpy.array(energies_beta))
1195 self.homos.append(homo_beta)
1196
1197 self.set_attribute('nmo', len(self.moenergies[0]))
1198
1199 # Molecular orbital coefficients.
1200
1201 # This block comes from `print_orbitals = true/{int}`. Less
1202 # precision than `scf_final_print >= 2` for `mocoeffs`, but
1203 # important for `aonames` and `atombasis`.
1204
1205 if any(header in line
1206 for header in self.alpha_mo_coefficient_headers):
1207
1208 # If we've asked to display more virtual orbitals than
1209 # there are MOs present in the molecule, fix that now.
1210 if hasattr(self, 'nmo') and hasattr(self, 'nalpha') and hasattr(self, 'nbeta'):
1211 self.norbdisp_alpha_aonames = min(self.norbdisp_alpha_aonames, self.nmo)
1212 self.norbdisp_beta_aonames = min(self.norbdisp_beta_aonames, self.nmo)
1213
1214 if not hasattr(self, 'mocoeffs'):
1215 self.mocoeffs = []
1216 if not hasattr(self, 'atombasis'):
1217 self.atombasis = []
1218 for n in range(self.natom):
1219 self.atombasis.append([])
1220 if not hasattr(self, 'aonames'):
1221 self.aonames = []
1222 # We could also attempt to parse `moenergies` here, but
1223 # nothing is gained by it.
1224
1225 mocoeffs = self.parse_matrix_aonames(inputfile, self.nbasis, self.norbdisp_alpha_aonames)
1226 # Only use these MO coefficients if we don't have them
1227 # from `scf_final_print`.
1228 if len(self.mocoeffs) == 0:
1229 self.mocoeffs.append(mocoeffs.transpose())
1230
1231 # Go back through `aonames` to create `atombasis`.
1232 assert len(self.aonames) == self.nbasis
1233 for aoindex, aoname in enumerate(self.aonames):
1234 atomindex = int(self.re_atomindex.search(aoname).groups()[0]) - 1
1235 self.atombasis[atomindex].append(aoindex)
1236 assert len(self.atombasis) == len(self.atomnos)
1237
1238 if 'BETA MOLECULAR ORBITAL COEFFICIENTS' in line:
1239
1240 mocoeffs = self.parse_matrix_aonames(inputfile, self.nbasis, self.norbdisp_beta_aonames)
1241 if len(self.mocoeffs) == 1:
1242 self.mocoeffs.append(mocoeffs.transpose())
1243
1244 # Population analysis.
1245
1246 if 'Ground-State Mulliken Net Atomic Charges' in line:
1247 self.parse_charge_section(inputfile, 'mulliken')
1248 if 'Hirshfeld Atomic Charges' in line:
1249 self.parse_charge_section(inputfile, 'hirshfeld')
1250 if 'Ground-State ChElPG Net Atomic Charges' in line:
1251 self.parse_charge_section(inputfile, 'chelpg')
1252
1253 # Multipole moments are not printed in lexicographical order,
1254 # so we need to parse and sort them. The units seem OK, but there
1255 # is some uncertainty about the reference point and whether it
1256 # can be changed.
1257 #
1258 # Notice how the letter/coordinate labels change to coordinate ranks
1259 # after hexadecapole moments, and need to be translated. Additionally,
1260 # after 9-th order moments the ranks are not necessarily single digits
1261 # and so there are spaces between them.
1262 #
1263 # -----------------------------------------------------------------
1264 # Cartesian Multipole Moments
1265 # LMN = < X^L Y^M Z^N >
1266 # -----------------------------------------------------------------
1267 # Charge (ESU x 10^10)
1268 # 0.0000
1269 # Dipole Moment (Debye)
1270 # X 0.0000 Y 0.0000 Z 0.0000
1271 # Tot 0.0000
1272 # Quadrupole Moments (Debye-Ang)
1273 # XX -50.9647 XY -0.1100 YY -50.1441
1274 # XZ 0.0000 YZ 0.0000 ZZ -58.5742
1275 # ...
1276 # 5th-Order Moments (Debye-Ang^4)
1277 # 500 0.0159 410 -0.0010 320 0.0005
1278 # 230 0.0000 140 0.0005 050 0.0012
1279 # ...
1280 # -----------------------------------------------------------------
1281 #
1282 if "Cartesian Multipole Moments" in line:
1283
1284 # This line appears not by default, but only when
1285 # `multipole_order` > 4:
1286 line = inputfile.next()
1287 if 'LMN = < X^L Y^M Z^N >' in line:
1288 line = inputfile.next()
1289
1290 # The reference point is always the origin, although normally the molecule
1291 # is moved so that the center of charge is at the origin.
1292 self.reference = [0.0, 0.0, 0.0]
1293 self.moments = [self.reference]
1294
1295 # Watch out! This charge is in statcoulombs without the exponent!
1296 # We should expect very good agreement, however Q-Chem prints
1297 # the charge only with 5 digits, so expect 1e-4 accuracy.
1298 charge_header = inputfile.next()
1299 assert charge_header.split()[0] == "Charge"
1300 charge = float(inputfile.next().strip())
1301 charge = utils.convertor(charge, 'statcoulomb', 'e') * 1e-10
1302 # Allow this to change until fragment jobs are properly implemented.
1303 # assert abs(charge - self.charge) < 1e-4
1304
1305 # This will make sure Debyes are used (not sure if it can be changed).
1306 line = inputfile.next()
1307 assert line.strip() == "Dipole Moment (Debye)"
1308
1309 while "-----" not in line:
1310
1311 # The current multipole element will be gathered here.
1312 multipole = []
1313
1314 line = inputfile.next()
1315 while ("-----" not in line) and ("Moment" not in line):
1316
1317 cols = line.split()
1318
1319 # The total (norm) is printed for dipole but not other multipoles.
1320 if cols[0] == 'Tot':
1321 line = inputfile.next()
1322 continue
1323
1324 # Find and replace any 'stars' with NaN before moving on.
1325 for i in range(len(cols)):
1326 if '***' in cols[i]:
1327 cols[i] = numpy.nan
1328
1329 # The moments come in pairs (label followed by value) up to the 9-th order,
1330 # although above hexadecapoles the labels are digits representing the rank
1331 # in each coordinate. Above the 9-th order, ranks are not always single digits,
1332 # so there are spaces between them, which means moments come in quartets.
1333 if len(self.moments) < 5:
1334 for i in range(len(cols)//2):
1335 lbl = cols[2*i]
1336 m = cols[2*i + 1]
1337 multipole.append([lbl, m])
1338 elif len(self.moments) < 10:
1339 for i in range(len(cols)//2):
1340 lbl = cols[2*i]
1341 lbl = 'X'*int(lbl[0]) + 'Y'*int(lbl[1]) + 'Z'*int(lbl[2])
1342 m = cols[2*i + 1]
1343 multipole.append([lbl, m])
1344 else:
1345 for i in range(len(cols)//4):
1346 lbl = 'X'*int(cols[4*i]) + 'Y'*int(cols[4*i + 1]) + 'Z'*int(cols[4*i + 2])
1347 m = cols[4*i + 3]
1348 multipole.append([lbl, m])
1349
1350 line = inputfile.next()
1351
1352 # Sort should use the first element when sorting lists,
1353 # so this should simply work, and afterwards we just need
1354 # to extract the second element in each list (the actual moment).
1355 multipole.sort()
1356 multipole = [m[1] for m in multipole]
1357 self.moments.append(multipole)
1358
1359 # For `method = force` or geometry optimizations,
1360 # the gradient is printed.
1361 if any(header in line for header in self.gradient_headers):
1362 if not hasattr(self, 'grads'):
1363 self.grads = []
1364 if 'SCF' in line:
1365 ncolsblock = self.ncolsblock
1366 else:
1367 ncolsblock = 5
1368 grad = QChem.parse_matrix(inputfile, 3, self.natom, ncolsblock)
1369 self.grads.append(grad.T)
1370
1371 # (Static) polarizability from frequency calculations.
1372 if 'Polarizability Matrix (a.u.)' in line:
1373 if not hasattr(self, 'polarizabilities'):
1374 self.polarizabilities = []
1375 polarizability = []
1376 self.skip_line(inputfile, 'index header')
1377 for _ in range(3):
1378 line = next(inputfile)
1379 ss = line.strip()[1:]
1380 polarizability.append([ss[0:12], ss[13:24], ss[25:36]])
1381 # For some reason the sign is inverted.
1382 self.polarizabilities.append(-numpy.array(polarizability, dtype=float))
1383
1384 # For IR-related jobs, the Hessian is printed (dim: 3*natom, 3*natom).
1385 # Note that this is *not* the mass-weighted Hessian.
1386 if any(header in line for header in self.hessian_headers):
1387 if not hasattr(self, 'hessian'):
1388 dim = 3*self.natom
1389 self.hessian = QChem.parse_matrix(inputfile, dim, dim, self.ncolsblock)
1390
1391 # Start of the IR/Raman frequency section.
1392 if 'VIBRATIONAL ANALYSIS' in line:
1393
1394 while 'STANDARD THERMODYNAMIC QUANTITIES' not in line:
1395 ## IR, optional Raman:
1396 #
1397 # **********************************************************************
1398 # ** **
1399 # ** VIBRATIONAL ANALYSIS **
1400 # ** -------------------- **
1401 # ** **
1402 # ** VIBRATIONAL FREQUENCIES (CM**-1) AND NORMAL MODES **
1403 # ** FORCE CONSTANTS (mDYN/ANGSTROM) AND REDUCED MASSES (AMU) **
1404 # ** INFRARED INTENSITIES (KM/MOL) **
1405 ##** RAMAN SCATTERING ACTIVITIES (A**4/AMU) AND DEPOLARIZATION RATIOS **
1406 # ** **
1407 # **********************************************************************
1408 #
1409 #
1410 # Mode: 1 2 3
1411 # Frequency: -106.88 -102.91 161.77
1412 # Force Cnst: 0.0185 0.0178 0.0380
1413 # Red. Mass: 2.7502 2.8542 2.4660
1414 # IR Active: NO YES YES
1415 # IR Intens: 0.000 0.000 0.419
1416 # Raman Active: YES NO NO
1417 ##Raman Intens: 2.048 0.000 0.000
1418 ##Depolar: 0.750 0.000 0.000
1419 # X Y Z X Y Z X Y Z
1420 # C 0.000 0.000 -0.100 -0.000 0.000 -0.070 -0.000 -0.000 -0.027
1421 # C 0.000 0.000 0.045 -0.000 0.000 -0.074 0.000 -0.000 -0.109
1422 # C 0.000 0.000 0.148 -0.000 -0.000 -0.074 0.000 0.000 -0.121
1423 # (...)
1424 # H -0.000 -0.000 0.422 -0.000 -0.000 0.499 0.000 0.000 -0.285
1425 # TransDip 0.000 -0.000 -0.000 0.000 -0.000 -0.000 -0.000 0.000 0.021
1426 #
1427 # Mode: 4 5 6
1428 # ...
1429 #
1430 # There isn't any symmetry information for normal modes present
1431 # in Q-Chem.
1432 # if not hasattr(self, 'vibsyms'):
1433 # self.vibsyms = []
1434 if 'Frequency:' in line:
1435 if not hasattr(self, 'vibfreqs'):
1436 self.vibfreqs = []
1437 vibfreqs = map(float, line.split()[1:])
1438 self.vibfreqs.extend(vibfreqs)
1439
1440 if 'IR Intens:' in line:
1441 if not hasattr(self, 'vibirs'):
1442 self.vibirs = []
1443 vibirs = map(float, line.split()[2:])
1444 self.vibirs.extend(vibirs)
1445
1446 if 'Raman Intens:' in line:
1447 if not hasattr(self, 'vibramans'):
1448 self.vibramans = []
1449 vibramans = map(float, line.split()[2:])
1450 self.vibramans.extend(vibramans)
1451
1452 # This is the start of the displacement block.
1453 if line.split()[0:3] == ['X', 'Y', 'Z']:
1454 if not hasattr(self, 'vibdisps'):
1455 self.vibdisps = []
1456 disps = []
1457 for k in range(self.natom):
1458 line = next(inputfile)
1459 numbers = list(map(float, line.split()[1:]))
1460 N = len(numbers) // 3
1461 if not disps:
1462 for n in range(N):
1463 disps.append([])
1464 for n in range(N):
1465 disps[n].append(numbers[3*n:(3*n)+3])
1466 self.vibdisps.extend(disps)
1467
1468 line = next(inputfile)
1469
1470 # Anharmonic vibrational analysis.
1471 # Q-Chem includes 3 theories: VPT2, TOSH, and VCI.
1472 # For now, just take the VPT2 results.
1473
1474 # if 'VIBRATIONAL ANHARMONIC ANALYSIS' in line:
1475
1476 # while list(set(line.strip())) != ['=']:
1477 # if 'VPT2' in line:
1478 # if not hasattr(self, 'vibanharms'):
1479 # self.vibanharms = []
1480 # self.vibanharms.append(float(line.split()[-1]))
1481 # line = next(inputfile)
1482
1483 if 'STANDARD THERMODYNAMIC QUANTITIES AT' in line:
1484
1485 if not hasattr(self, 'temperature'):
1486 self.temperature = float(line.split()[4])
1487 # Not supported yet.
1488 if not hasattr(self, 'pressure'):
1489 self.pressure = float(line.split()[7])
1490 self.skip_line(inputfile, 'blank')
1491
1492 line = next(inputfile)
1493 if self.natom == 1:
1494 assert 'Translational Enthalpy' in line
1495 else:
1496 assert 'Imaginary Frequencies' in line
1497 line = next(inputfile)
1498 # Not supported yet.
1499 assert 'Zero point vibrational energy' in line
1500 if not hasattr(self, 'zpe'):
1501 # Convert from kcal/mol to Hartree/particle.
1502 self.zpe = utils.convertor(float(line.split()[4]),
1503 'kcal/mol', 'hartree')
1504 atommasses = []
1505 while 'Translational Enthalpy' not in line:
1506 if 'Has Mass' in line:
1507 atommass = float(line.split()[6])
1508 atommasses.append(atommass)
1509 line = next(inputfile)
1510 if not hasattr(self, 'atommasses'):
1511 self.atommasses = numpy.array(atommasses)
1512
1513 while line.strip():
1514 line = next(inputfile)
1515
1516 line = next(inputfile)
1517 assert 'Total Enthalpy' in line
1518 if not hasattr(self, 'enthalpy'):
1519 enthalpy = float(line.split()[2])
1520 self.enthalpy = utils.convertor(enthalpy,
1521 'kcal/mol', 'hartree')
1522 line = next(inputfile)
1523 assert 'Total Entropy' in line
1524 if not hasattr(self, 'entropy'):
1525 entropy = float(line.split()[2]) * self.temperature / 1000
1526 # This is the *temperature dependent* entropy.
1527 self.entropy = utils.convertor(entropy,
1528 'kcal/mol', 'hartree')
1529 if not hasattr(self, 'freeenergy'):
1530 self.freeenergy = self.enthalpy - self.entropy
1531
1532 if line[:16] == ' Total job time:':
1533 self.metadata['success'] = True
1534
1535 # TODO:
1536 # 'enthalpy' (incorrect)
1537 # 'entropy' (incorrect)
1538 # 'freeenergy' (incorrect)
1539 # 'nocoeffs'
1540 # 'nooccnos'
1541 # 'vibanharms'