Debian Codegraph @

cclib/parser/adfparser.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 ADF output files"""
9
10 from __future__ import print_function
11
12 import itertools
13 import re
14
15 import numpy
16
17 from cclib.parser import logfileparser
18 from cclib.parser import utils
19
20
21 class ADF(logfileparser.Logfile):
22 """An ADF log file"""
23
24 def __init__(self, *args, **kwargs):
25
26 # Call the __init__ method of the superclass
27 super(ADF, self).__init__(logname="ADF", *args, **kwargs)
28
29 def __str__(self):
30 """Return a string representation of the object."""
31 return "ADF log file %s" % (self.filename)
32
33 def __repr__(self):
34 """Return a representation of the object."""
35 return 'ADF("%s")' % (self.filename)
36
37 def normalisesym(self, label):
38 """Use standard symmetry labels instead of ADF labels.
39
40 To normalise:
41 (1) any periods are removed (except in the case of greek letters)
42 (2) XXX is replaced by X, and a " added.
43 (3) XX is replaced by X, and a ' added.
44 (4) The greek letters Sigma, Pi, Delta and Phi are replaced by
45 their lowercase equivalent.
46 """
47 greeks = ['Sigma', 'Pi', 'Delta', 'Phi']
48 for greek in greeks:
49 if label.startswith(greek):
50 return label.lower()
51
52 ans = label.replace(".", "")
53 if ans[1:3] == "''":
54 temp = ans[0] + '"'
55 ans = temp
56
57 l = len(ans)
58 if l > 1 and ans[0] == ans[1]: # Python only tests the second condition if the first is true
59 if l > 2 and ans[1] == ans[2]:
60 ans = ans.replace(ans[0]*3, ans[0]) + '"'
61 else:
62 ans = ans.replace(ans[0]*2, ans[0]) + "'"
63 return ans
64
65 def normalisedegenerates(self, label, num, ndict=None):
66 """Generate a string used for matching degenerate orbital labels
67
68 To normalise:
69 (1) if label is E or T, return label:num
70 (2) if label is P or D, look up in dict, and return answer
71 """
72
73 if not ndict:
74 ndict = {
75 'P': {0: "P:x", 1: "P:y", 2: "P:z"},
76 'D': {0: "D:z2", 1: "D:x2-y2", 2: "D:xy", 3: "D:xz", 4: "D:yz"}
77 }
78
79 if label in ndict:
80 if num in ndict[label]:
81 return ndict[label][num]
82 else:
83 return "%s:%i" % (label, num+1)
84 else:
85 return "%s:%i" % (label, num+1)
86
87 def before_parsing(self):
88
89 # Used to avoid extracting the final geometry twice in a GeoOpt
90 self.NOTFOUND, self.GETLAST, self.NOMORE = list(range(3))
91 self.finalgeometry = self.NOTFOUND
92
93 # Used for calculating the scftarget (variables names taken from the ADF manual)
94 self.accint = self.SCFconv = self.sconv2 = None
95
96 # keep track of nosym and unrestricted case to parse Energies since it doens't have an all Irreps section
97 self.nosymflag = False
98 self.unrestrictedflag = False
99
100 SCFCNV, SCFCNV2 = list(range(2)) # used to index self.scftargets[]
101 maxelem, norm = list(range(2)) # used to index scf.values
102
103 def extract(self, inputfile, line):
104 """Extract information from the file object inputfile."""
105
106 # If a file contains multiple calculations, currently we want to print a warning
107 # and skip to the end of the file, since cclib parses only the main system, which
108 # is usually the largest. Here we test this by checking if scftargets has already
109 # been parsed when another INPUT FILE segment is found, although this might
110 # not always be the best indicator.
111 if line.strip() == "(INPUT FILE)" and hasattr(self, "scftargets"):
112 self.logger.warning("Skipping remaining calculations")
113 inputfile.seek(0, 2)
114 return
115
116 # We also want to check to make sure we aren't parsing "Create" jobs,
117 # which normally come before the calculation we actually want to parse.
118 if line.strip() == "(INPUT FILE)":
119 while True:
120 self.updateprogress(inputfile, "Unsupported Information", self.fupdate)
121 line = next(inputfile) if line.strip() == "(INPUT FILE)" else None
122 if line and not line[:6] in ("Create", "create"):
123 break
124 line = next(inputfile)
125
126 version_searchstr = "Amsterdam Density Functional (ADF)"
127 if version_searchstr in line:
128 startidx = line.index(version_searchstr) + len(version_searchstr)
129 trimmed_line = line[startidx:].strip()[:-1]
130 # The package version is normally a year with revision
131 # number (such as 2013.01), but it may also be a random
132 # string (such as a version control branch name).
133 match = re.search(r"([\d\.]{4,7})", trimmed_line)
134 if match:
135 package_version = match.groups()[0]
136 self.metadata["package_version"] = package_version
137 else:
138 # This isn't as well-defined, but the field shouldn't
139 # be left empty.
140 self.metadata["package_version"] = trimmed_line.strip()
141
142 # In ADF 2014.01, there are (INPUT FILE) messages, so we need to use just
143 # the lines that start with 'Create' and run until the title or something
144 # else we are sure is is the calculation proper. It would be good to combine
145 # this with the previous block, if possible.
146 if line[:6] == "Create":
147 while line[:5] != "title" and "NO TITLE" not in line:
148 line = inputfile.next()
149
150 if line[1:10] == "Symmetry:":
151 info = line.split()
152 if info[1] == "NOSYM":
153 self.nosymflag = True
154
155 # Use this to read the subspecies of irreducible representations.
156 # It will be a list, with each element representing one irrep.
157 if line.strip() == "Irreducible Representations, including subspecies":
158
159 self.skip_line(inputfile, 'dashes')
160
161 self.irreps = []
162 line = next(inputfile)
163 while line.strip() != "":
164 self.irreps.append(line.split())
165 line = next(inputfile)
166
167 if line[4:13] == 'Molecule:':
168 info = line.split()
169 if info[1] == 'UNrestricted':
170 self.unrestrictedflag = True
171
172 if line[1:6] == "ATOMS":
173 # Find the number of atoms and their atomic numbers
174 # Also extract the starting coordinates (for a GeoOpt anyway)
175 # and the atommasses (previously called vibmasses)
176 self.updateprogress(inputfile, "Attributes", self.cupdate)
177
178 self.atomcoords = []
179
180 self.skip_lines(inputfile, ['header1', 'header2', 'header3'])
181
182 atomnos = []
183 atommasses = []
184 atomcoords = []
185 coreelectrons = []
186 line = next(inputfile)
187 while len(line) > 2: # ensure that we are reading no blank lines
188 info = line.split()
189 element = info[1].split('.')[0]
190 atomnos.append(self.table.number[element])
191 atomcoords.append(list(map(float, info[2:5])))
192 coreelectrons.append(int(float(info[5]) - float(info[6])))
193 atommasses.append(float(info[7]))
194 line = next(inputfile)
195 self.atomcoords.append(atomcoords)
196
197 self.set_attribute('natom', len(atomnos))
198 self.set_attribute('atomnos', atomnos)
199 self.set_attribute('atommasses', atommasses)
200 self.set_attribute('coreelectrons', coreelectrons)
201
202 if line[1:10] == "FRAGMENTS":
203 header = next(inputfile)
204
205 self.frags = []
206 self.fragnames = []
207
208 line = next(inputfile)
209 while len(line) > 2: # ensure that we are reading no blank lines
210 info = line.split()
211
212 if len(info) == 7: # fragment name is listed here
213 self.fragnames.append("%s_%s" % (info[1], info[0]))
214 self.frags.append([])
215 self.frags[-1].append(int(info[2]) - 1)
216
217 elif len(info) == 5: # add atoms into last fragment
218 self.frags[-1].append(int(info[0]) - 1)
219
220 line = next(inputfile)
221
222 # Extract charge
223 if line[1:11] == "Net Charge":
224
225 charge = int(line.split()[2])
226 self.set_attribute('charge', charge)
227
228 line = next(inputfile)
229 if len(line.strip()):
230 # Spin polar: 1 (Spin_A minus Spin_B electrons)
231 # (Not sure about this for higher multiplicities)
232 mult = int(line.split()[2]) + 1
233 else:
234 mult = 1
235 self.set_attribute('mult', mult)
236
237 if line[1:22] == "S C F U P D A T E S":
238 # find targets for SCF convergence
239
240 if not hasattr(self, "scftargets"):
241 self.scftargets = []
242
243 self.skip_lines(inputfile, ['e', 'b', 'numbers'])
244
245 line = next(inputfile)
246 self.SCFconv = float(line.split()[-1])
247 line = next(inputfile)
248 self.sconv2 = float(line.split()[-1])
249
250 # In ADF 2013, the default numerical integration method is fuzzy cells,
251 # although it used to be Voronoi polyhedra. Both methods apparently set
252 # the accint parameter, although the latter does so indirectly, based on
253 # a 'grid quality' setting. This is translated into accint using a
254 # dictionary with values taken from the documentation.
255 if "Numerical Integration : Voronoi Polyhedra (Te Velde)" in line:
256 self.integration_method = "voronoi_polyhedra"
257 if line[1:27] == 'General Accuracy Parameter':
258 # Need to know the accuracy of the integration grid to
259 # calculate the scftarget...note that it changes with time
260 self.accint = float(line.split()[-1])
261 if "Numerical Integration : Fuzzy Cells (Becke)" in line:
262 self.integration_method = 'fuzzy_cells'
263 if line[1:19] == "Becke grid quality":
264 self.grid_quality = line.split()[-1]
265 quality2accint = {
266 'BASIC': 2.0,
267 'NORMAL': 4.0,
268 'GOOD': 6.0,
269 'VERYGOOD': 8.0,
270 'EXCELLENT': 10.0,
271 }
272 self.accint = quality2accint[self.grid_quality]
273
274 # Half of the atomic orbital overlap matrix is printed since it is symmetric,
275 # but this requires "PRINT Smat" to be in the input. There are extra blank lines
276 # at the end of the block, which are used to terminate the parsing.
277 #
278 # ====== smat
279 #
280 # column 1 2 3 4
281 # row
282 # 1 1.00000000000000E+00
283 # 2 2.43370854175315E-01 1.00000000000000E+00
284 # 3 0.00000000000000E+00 0.00000000000000E+00 1.00000000000000E+00
285 # ...
286 #
287 if "====== smat" in line:
288
289 # Initialize the matrix with Nones so we can easily check all has been parsed.
290 overlaps = [[None] * self.nbasis for i in range(self.nbasis)]
291
292 self.skip_line(inputfile, 'blank')
293
294 line = inputfile.next()
295 while line.strip():
296
297 colline = line
298 assert colline.split()[0] == "column"
299 columns = [int(i) for i in colline.split()[1:]]
300
301 rowline = inputfile.next()
302 assert rowline.strip() == "row"
303
304 line = inputfile.next()
305 while line.strip():
306
307 i = int(line.split()[0])
308 vals = [float(col) for col in line.split()[1:]]
309 for j, o in enumerate(vals):
310 k = columns[j]
311 overlaps[k-1][i-1] = o
312 overlaps[i-1][k-1] = o
313
314 line = inputfile.next()
315
316 line = inputfile.next()
317
318 # Now all values should be parsed, and so no Nones remaining.
319 assert all([all([x is not None for x in ao]) for ao in overlaps])
320
321 self.set_attribute('aooverlaps', overlaps)
322
323 if line[1:11] == "CYCLE 1":
324
325 self.updateprogress(inputfile, "QM convergence", self.fupdate)
326
327 newlist = []
328 line = next(inputfile)
329
330 if not hasattr(self, "geovalues"):
331 # This is the first SCF cycle
332 self.scftargets.append([self.sconv2*10, self.sconv2])
333 elif self.finalgeometry in [self.GETLAST, self.NOMORE]:
334 # This is the final SCF cycle
335 self.scftargets.append([self.SCFconv*10, self.SCFconv])
336 else:
337 # This is an intermediate SCF cycle in a geometry optimization,
338 # in which case the SCF convergence target needs to be derived
339 # from the accint parameter. For Voronoi polyhedra integration,
340 # accint is printed and parsed. For fuzzy cells, it can be inferred
341 # from the grid quality setting, as is done somewhere above.
342 if self.accint:
343 oldscftst = self.scftargets[-1][1]
344 grdmax = self.geovalues[-1][1]
345 scftst = max(self.SCFconv, min(oldscftst, grdmax/30, 10**(-self.accint)))
346 self.scftargets.append([scftst*10, scftst])
347
348 while line.find("SCF CONVERGED") == -1 and line.find("SCF not fully converged, result acceptable") == -1 and line.find("SCF NOT CONVERGED") == -1:
349 if line[4:12] == "SCF test":
350 if not hasattr(self, "scfvalues"):
351 self.scfvalues = []
352
353 info = line.split()
354 newlist.append([float(info[4]), abs(float(info[6]))])
355 try:
356 line = next(inputfile)
357 except StopIteration: # EOF reached?
358 self.logger.warning("SCF did not converge, so attributes may be missing")
359 break
360
361 if line.find("SCF not fully converged, result acceptable") > 0:
362 self.logger.warning("SCF not fully converged, results acceptable")
363
364 if line.find("SCF NOT CONVERGED") > 0:
365 self.logger.warning("SCF did not converge! moenergies and mocoeffs are unreliable")
366
367 if hasattr(self, "scfvalues"):
368 self.scfvalues.append(newlist)
369
370 # Parse SCF energy for SP calcs from bonding energy decomposition section.
371 # It seems ADF does not print it earlier for SP calculations.
372 # Geometry optimization runs also print this, and we want to parse it
373 # for them, too, even if it repeats the last "Geometry Convergence Tests"
374 # section (but it's usually a bit different).
375 if line[:21] == "Total Bonding Energy:":
376
377 if not hasattr(self, "scfenergies"):
378 self.scfenergies = []
379
380 energy = utils.convertor(float(line.split()[3]), "hartree", "eV")
381 self.scfenergies.append(energy)
382
383 if line[51:65] == "Final Geometry":
384 self.finalgeometry = self.GETLAST
385
386 # Get the coordinates from each step of the GeoOpt.
387 if line[1:24] == "Coordinates (Cartesian)" and self.finalgeometry in [self.NOTFOUND, self.GETLAST]:
388
389 self.skip_lines(inputfile, ['e', 'b', 'title', 'title', 'd'])
390
391 atomcoords = []
392 line = next(inputfile)
393 while list(set(line.strip())) != ['-']:
394 atomcoords.append(list(map(float, line.split()[5:8])))
395 line = next(inputfile)
396
397 if not hasattr(self, "atomcoords"):
398 self.atomcoords = []
399 self.atomcoords.append(atomcoords)
400
401 # Don't get any more coordinates in this case.
402 # KML: I think we could combine this with optdone (see below).
403 if self.finalgeometry == self.GETLAST:
404 self.finalgeometry = self.NOMORE
405
406 # There have been some changes in the format of the geometry convergence information,
407 # and this is how it is printed in older versions (2007.01 unit tests).
408 #
409 # ==========================
410 # Geometry Convergence Tests
411 # ==========================
412 #
413 # Energy old : -5.14170647
414 # new : -5.15951374
415 #
416 # Convergence tests:
417 # (Energies in hartree, Gradients in hartree/angstr or radian, Lengths in angstrom, Angles in degrees)
418 #
419 # Item Value Criterion Conv. Ratio
420 # -------------------------------------------------------------------------
421 # change in energy -0.01780727 0.00100000 NO 0.00346330
422 # gradient max 0.03219530 0.01000000 NO 0.30402650
423 # gradient rms 0.00858685 0.00666667 NO 0.27221261
424 # cart. step max 0.07674971 0.01000000 NO 0.75559435
425 # cart. step rms 0.02132310 0.00666667 NO 0.55335378
426 #
427 if line[1:27] == 'Geometry Convergence Tests':
428
429 if not hasattr(self, "geotargets"):
430 self.geovalues = []
431 self.geotargets = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0], "d")
432
433 if not hasattr(self, "scfenergies"):
434 self.scfenergies = []
435
436 self.skip_lines(inputfile, ['e', 'b'])
437
438 energies_old = next(inputfile)
439 energies_new = next(inputfile)
440 self.scfenergies.append(utils.convertor(float(energies_new.split()[-1]), "hartree", "eV"))
441
442 self.skip_lines(inputfile, ['b', 'convergence', 'units', 'b', 'header', 'd'])
443
444 values = []
445 for i in range(5):
446 temp = next(inputfile).split()
447 self.geotargets[i] = float(temp[-3])
448 values.append(float(temp[-4]))
449
450 self.geovalues.append(values)
451
452 # This is to make geometry optimization always have the optdone attribute,
453 # even if it is to be empty for unconverged runs.
454 if not hasattr(self, 'optdone'):
455 self.optdone = []
456
457 # After the test, there is a message if the search is converged:
458 #
459 # ***************************************************************************************************
460 # Geometry CONVERGED
461 # ***************************************************************************************************
462 #
463 if line.strip() == "Geometry CONVERGED":
464 self.skip_line(inputfile, 'stars')
465 self.optdone.append(len(self.geovalues) - 1)
466
467 # Here is the corresponding geometry convergence info from the 2013.01 unit test.
468 # Note that the step number is given, which it will be prudent to use in an assertion.
469 #
470 #----------------------------------------------------------------------
471 #Geometry Convergence after Step 3 (Hartree/Angstrom,Angstrom)
472 #----------------------------------------------------------------------
473 #current energy -5.16274478 Hartree
474 #energy change -0.00237544 0.00100000 F
475 #constrained gradient max 0.00884999 0.00100000 F
476 #constrained gradient rms 0.00249569 0.00066667 F
477 #gradient max 0.00884999
478 #gradient rms 0.00249569
479 #cart. step max 0.03331296 0.01000000 F
480 #cart. step rms 0.00844037 0.00666667 F
481 if line[:31] == "Geometry Convergence after Step":
482
483 stepno = int(line.split()[4])
484
485 # This is to make geometry optimization always have the optdone attribute,
486 # even if it is to be empty for unconverged runs.
487 if not hasattr(self, 'optdone'):
488 self.optdone = []
489
490 # The convergence message is inline in this block, not later as it was before.
491 if "** CONVERGED **" in line:
492 if not hasattr(self, 'optdone'):
493 self.optdone = []
494 self.optdone.append(len(self.geovalues) - 1)
495
496 self.skip_line(inputfile, 'dashes')
497
498 current_energy = next(inputfile)
499 energy_change = next(inputfile)
500 constrained_gradient_max = next(inputfile)
501 constrained_gradient_rms = next(inputfile)
502 gradient_max = next(inputfile)
503 gradient_rms = next(inputfile)
504 cart_step_max = next(inputfile)
505 cart_step_rms = next(inputfile)
506
507 if not hasattr(self, "scfenergies"):
508 self.scfenergies = []
509
510 energy = utils.convertor(float(current_energy.split()[-2]), "hartree", "eV")
511 self.scfenergies.append(energy)
512
513 if not hasattr(self, "geotargets"):
514 self.geotargets = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0], "d")
515
516 self.geotargets[0] = float(energy_change.split()[-2])
517 self.geotargets[1] = float(constrained_gradient_max.split()[-2])
518 self.geotargets[2] = float(constrained_gradient_rms.split()[-2])
519 self.geotargets[3] = float(cart_step_max.split()[-2])
520 self.geotargets[4] = float(cart_step_rms.split()[-2])
521
522 if not hasattr(self, "geovalues"):
523 self.geovalues = []
524
525 self.geovalues.append([])
526 self.geovalues[-1].append(float(energy_change.split()[-3]))
527 self.geovalues[-1].append(float(constrained_gradient_max.split()[-3]))
528 self.geovalues[-1].append(float(constrained_gradient_rms.split()[-3]))
529 self.geovalues[-1].append(float(cart_step_max.split()[-3]))
530 self.geovalues[-1].append(float(cart_step_rms.split()[-3]))
531
532 if line.find('Orbital Energies, per Irrep and Spin') > 0 and not hasattr(self, "mosyms") and self.nosymflag and not self.unrestrictedflag:
533 #Extracting orbital symmetries and energies, homos for nosym case
534 #Should only be for restricted case because there is a better text block for unrestricted and nosym
535
536 self.mosyms = [[]]
537
538 self.moenergies = [[]]
539
540 self.skip_lines(inputfile, ['e', 'header', 'd', 'label'])
541
542 line = next(inputfile)
543 info = line.split()
544
545 if not info[0] == '1':
546 self.logger.warning("MO info up to #%s is missing" % info[0])
547
548 #handle case where MO information up to a certain orbital are missing
549 while int(info[0]) - 1 != len(self.moenergies[0]):
550 self.moenergies[0].append(99999)
551 self.mosyms[0].append('A')
552
553 homoA = None
554
555 while len(line) > 10:
556 info = line.split()
557 self.mosyms[0].append('A')
558 self.moenergies[0].append(utils.convertor(float(info[2]), 'hartree', 'eV'))
559 if info[1] == '0.000' and not hasattr(self, 'homos'):
560 self.set_attribute('homos', [len(self.moenergies[0]) - 2])
561 line = next(inputfile)
562
563 self.moenergies = [numpy.array(self.moenergies[0], "d")]
564
565 if line[1:29] == 'Orbital Energies, both Spins' and not hasattr(self, "mosyms") and self.nosymflag and self.unrestrictedflag:
566 #Extracting orbital symmetries and energies, homos for nosym case
567 #should only be here if unrestricted and nosym
568
569 self.mosyms = [[], []]
570 moenergies = [[], []]
571
572 self.skip_lines(inputfile, ['d', 'b', 'header', 'd'])
573
574 homoa = 0
575 homob = None
576
577 line = next(inputfile)
578 while len(line) > 5:
579 info = line.split()
580 if info[2] == 'A':
581 self.mosyms[0].append('A')
582 moenergies[0].append(utils.convertor(float(info[4]), 'hartree', 'eV'))
583 if info[3] != '0.00':
584 homoa = len(moenergies[0]) - 1
585 elif info[2] == 'B':
586 self.mosyms[1].append('A')
587 moenergies[1].append(utils.convertor(float(info[4]), 'hartree', 'eV'))
588 if info[3] != '0.00':
589 homob = len(moenergies[1]) - 1
590 else:
591 print(("Error reading line: %s" % line))
592
593 line = next(inputfile)
594
595 self.moenergies = [numpy.array(x, "d") for x in moenergies]
596
597 self.set_attribute('homos', [homoa, homob])
598
599 # Extracting orbital symmetries and energies, homos.
600 if line[1:29] == 'Orbital Energies, all Irreps' and not hasattr(self, "mosyms"):
601
602 self.symlist = {}
603 self.mosyms = [[]]
604 self.moenergies = [[]]
605
606 self.skip_lines(inputfile, ['e', 'b', 'header', 'd'])
607
608 homoa = None
609 homob = None
610
611 #multiple = {'E':2, 'T':3, 'P':3, 'D':5}
612 # The above is set if there are no special irreps
613 names = [irrep[0].split(':')[0] for irrep in self.irreps]
614 counts = [len(irrep) for irrep in self.irreps]
615 multiple = dict(list(zip(names, counts)))
616 irrepspecies = {}
617 for n in range(len(names)):
618 indices = list(range(counts[n]))
619 subspecies = self.irreps[n]
620 irrepspecies[names[n]] = dict(list(zip(indices, subspecies)))
621
622 line = next(inputfile)
623 while line.strip():
624 info = line.split()
625 if len(info) == 5: # this is restricted
626 #count = multiple.get(info[0][0],1)
627 count = multiple.get(info[0], 1)
628 for repeat in range(count): # i.e. add E's twice, T's thrice
629 self.mosyms[0].append(self.normalisesym(info[0]))
630 self.moenergies[0].append(utils.convertor(float(info[3]), 'hartree', 'eV'))
631
632 sym = info[0]
633 if count > 1: # add additional sym label
634 sym = self.normalisedegenerates(info[0], repeat, ndict=irrepspecies)
635
636 try:
637 self.symlist[sym][0].append(len(self.moenergies[0])-1)
638 except KeyError:
639 self.symlist[sym] = [[]]
640 self.symlist[sym][0].append(len(self.moenergies[0])-1)
641
642 if info[2] == '0.00' and not hasattr(self, 'homos'):
643 self.homos = [len(self.moenergies[0]) - (count + 1)] # count, because need to handle degenerate cases
644 line = next(inputfile)
645 elif len(info) == 6: # this is unrestricted
646 if len(self.moenergies) < 2: # if we don't have space, create it
647 self.moenergies.append([])
648 self.mosyms.append([])
649 # count = multiple.get(info[0][0], 1)
650 count = multiple.get(info[0], 1)
651 if info[2] == 'A':
652 for repeat in range(count): # i.e. add E's twice, T's thrice
653 self.mosyms[0].append(self.normalisesym(info[0]))
654 self.moenergies[0].append(utils.convertor(float(info[4]), 'hartree', 'eV'))
655
656 sym = info[0]
657 if count > 1: # add additional sym label
658 sym = self.normalisedegenerates(info[0], repeat)
659
660 try:
661 self.symlist[sym][0].append(len(self.moenergies[0])-1)
662 except KeyError:
663 self.symlist[sym] = [[], []]
664 self.symlist[sym][0].append(len(self.moenergies[0])-1)
665
666 if info[3] == '0.00' and homoa is None:
667 homoa = len(self.moenergies[0]) - (count + 1) # count because degenerate cases need to be handled
668
669 if info[2] == 'B':
670 for repeat in range(count): # i.e. add E's twice, T's thrice
671 self.mosyms[1].append(self.normalisesym(info[0]))
672 self.moenergies[1].append(utils.convertor(float(info[4]), 'hartree', 'eV'))
673
674 sym = info[0]
675 if count > 1: # add additional sym label
676 sym = self.normalisedegenerates(info[0], repeat)
677
678 try:
679 self.symlist[sym][1].append(len(self.moenergies[1])-1)
680 except KeyError:
681 self.symlist[sym] = [[], []]
682 self.symlist[sym][1].append(len(self.moenergies[1])-1)
683
684 if info[3] == '0.00' and homob is None:
685 homob = len(self.moenergies[1]) - (count + 1)
686
687 line = next(inputfile)
688
689 else: # different number of lines
690 print(("Error", info))
691
692 if len(info) == 6: # still unrestricted, despite being out of loop
693 self.set_attribute('homos', [homoa, homob])
694
695 self.moenergies = [numpy.array(x, "d") for x in self.moenergies]
696
697 # Section on extracting vibdisps
698 # Also contains vibfreqs, but these are extracted in the
699 # following section (see below)
700 if line[1:28] == "Vibrations and Normal Modes":
701
702 self.vibdisps = []
703
704 self.skip_lines(inputfile, ['e', 'b', 'header', 'header', 'b', 'b'])
705
706 freqs = next(inputfile)
707 while freqs.strip() != "":
708 minus = next(inputfile)
709 p = [[], [], []]
710 for i in range(len(self.atomnos)):
711 broken = list(map(float, next(inputfile).split()[1:]))
712 for j in range(0, len(broken), 3):
713 p[j//3].append(broken[j:j+3])
714 self.vibdisps.extend(p[:(len(broken)//3)])
715 self.skip_lines(inputfile, ['b', 'b'])
716 freqs = next(inputfile)
717 self.vibdisps = numpy.array(self.vibdisps, "d")
718
719 if line[1:24] == "List of All Frequencies":
720 # Start of the IR/Raman frequency section
721 self.updateprogress(inputfile, "Frequency information", self.fupdate)
722
723 # self.vibsyms = [] # Need to look into this a bit more
724 self.vibirs = []
725 self.vibfreqs = []
726 for i in range(8):
727 line = next(inputfile)
728 line = next(inputfile).strip()
729 while line:
730 temp = line.split()
731 self.vibfreqs.append(float(temp[0]))
732 self.vibirs.append(float(temp[2])) # or is it temp[1]?
733 line = next(inputfile).strip()
734 self.vibfreqs = numpy.array(self.vibfreqs, "d")
735 self.vibirs = numpy.array(self.vibirs, "d")
736 if hasattr(self, "vibramans"):
737 self.vibramans = numpy.array(self.vibramans, "d")
738
739 #******************************************************************************************************************8
740 #delete this after new implementation using smat, eigvec print,eprint?
741 # Extract the number of basis sets
742 if line[1:49] == "Total nr. of (C)SFOs (summation over all irreps)":
743 nbasis = int(line.split(":")[1].split()[0])
744 self.set_attribute('nbasis', nbasis)
745
746 # now that we're here, let's extract aonames
747
748 self.fonames = []
749 self.start_indeces = {}
750 self.atombasis = [[] for frag in self.frags] # parse atombasis in the case of trivial SFOs
751
752 self.skip_line(inputfile, 'blank')
753
754 note = next(inputfile)
755 symoffset = 0
756
757 self.skip_line(inputfile, 'blank')
758 line = next(inputfile)
759 if len(line) > 2: # fix for ADF2006.01 as it has another note
760 self.skip_line(inputfile, 'blank')
761 line = next(inputfile)
762 self.skip_line(inputfile, 'blank')
763
764 self.nosymreps = []
765 while len(self.fonames) < self.nbasis:
766
767 symline = next(inputfile)
768 sym = symline.split()[1]
769 line = next(inputfile)
770 num = int(line.split(':')[1].split()[0])
771 self.nosymreps.append(num)
772
773 #read until line "--------..." is found
774 while line.find('-----') < 0:
775 line = next(inputfile)
776
777 line = next(inputfile) # the start of the first SFO
778
779 while len(self.fonames) < symoffset + num:
780 info = line.split()
781
782 #index0 index1 occ2 energy3/4 fragname5 coeff6 orbnum7 orbname8 fragname9
783 if not sym in list(self.start_indeces.keys()):
784 #have we already set the start index for this symmetry?
785 self.start_indeces[sym] = int(info[1])
786
787 orbname = info[8]
788 orbital = info[7] + orbname.replace(":", "")
789
790 fragname = info[5]
791 frag = fragname + info[9]
792
793 coeff = float(info[6])
794
795 # parse atombasis only in the case that all coefficients are 1
796 # and delete it otherwise
797 if hasattr(self, 'atombasis'):
798 if coeff == 1.:
799 ibas = int(info[0]) - 1
800 ifrag = int(info[9]) - 1
801 iat = self.frags[ifrag][0]
802 self.atombasis[iat].append(ibas)
803 else:
804 del self.atombasis
805
806 line = next(inputfile)
807 while line.strip() and not line[:7].strip(): # while it's the same SFO
808 # i.e. while not completely blank, but blank at the start
809 info = line[43:].split()
810 if len(info) > 0: # len(info)==0 for the second line of dvb_ir.adfout
811 frag += "+" + fragname + info[-1]
812 coeff = float(info[-4])
813 if coeff < 0:
814 orbital += '-' + info[-3] + info[-2].replace(":", "")
815 else:
816 orbital += '+' + info[-3] + info[-2].replace(":", "")
817 line = next(inputfile)
818 # At this point, we are either at the start of the next SFO or at
819 # a blank line...the end
820
821 self.fonames.append("%s_%s" % (frag, orbital))
822 symoffset += num
823
824 # blankline blankline
825 next(inputfile)
826 next(inputfile)
827
828 if line[1:32] == "S F O P O P U L A T I O N S ,":
829 #Extract overlap matrix
830
831 # self.fooverlaps = numpy.zeros((self.nbasis, self.nbasis), "d")
832
833 symoffset = 0
834
835 for nosymrep in self.nosymreps:
836
837 line = next(inputfile)
838 while line.find('===') < 10: # look for the symmetry labels
839 line = next(inputfile)
840
841 self.skip_lines(inputfile, ['b', 'b'])
842
843 text = next(inputfile)
844 if text[13:20] != "Overlap": # verify this has overlap info
845 break
846
847 self.skip_lines(inputfile, ['b', 'col', 'row'])
848
849 if not hasattr(self, "fooverlaps"): # make sure there is a matrix to store this
850 self.fooverlaps = numpy.zeros((self.nbasis, self.nbasis), "d")
851
852 base = 0
853 while base < nosymrep: # have we read all the columns?
854
855 for i in range(nosymrep - base):
856
857 self.updateprogress(inputfile, "Overlap", self.fupdate)
858 line = next(inputfile)
859 parts = line.split()[1:]
860 for j in range(len(parts)):
861 k = float(parts[j])
862 self.fooverlaps[base + symoffset + j, base + symoffset + i] = k
863 self.fooverlaps[base + symoffset + i, base + symoffset + j] = k
864
865 #blank, blank, column
866 for i in range(3):
867 next(inputfile)
868
869 base += 4
870
871 symoffset += nosymrep
872 base = 0
873
874 # The commented code below makes the atombasis attribute based on the BAS function in ADF,
875 # but this is probably not so useful, since SFOs are used to build MOs in ADF.
876 # if line[1:54] == "BAS: List of all Elementary Cartesian Basis Functions":
877 #
878 # self.atombasis = []
879 #
880 # # There will be some text, followed by a line:
881 # # (power of) X Y Z R Alpha on Atom
882 # while not line[1:11] == "(power of)":
883 # line = inputfile.next()
884 # dashes = inputfile.next()
885 # blank = inputfile.next()
886 # line = inputfile.next()
887 # # There will be two blank lines when there are no more atom types.
888 # while line.strip() != "":
889 # atoms = [int(i)-1 for i in line.split()[1:]]
890 # for n in range(len(atoms)):
891 # self.atombasis.append([])
892 # dashes = inputfile.next()
893 # line = inputfile.next()
894 # while line.strip() != "":
895 # indices = [int(i)-1 for i in line.split()[5:]]
896 # for i in range(len(indices)):
897 # self.atombasis[atoms[i]].append(indices[i])
898 # line = inputfile.next()
899 # line = inputfile.next()
900
901 if line[48:67] == "SFO MO coefficients":
902
903 self.mocoeffs = [numpy.zeros((self.nbasis, self.nbasis), "d")]
904 spin = 0
905 symoffset = 0
906 lastrow = 0
907
908 # Section ends with "1" at beggining of a line.
909 while line[0] != "1":
910 line = next(inputfile)
911
912 # If spin is specified, then there will be two coefficient matrices.
913 if line.strip() == "***** SPIN 1 *****":
914 self.mocoeffs = [numpy.zeros((self.nbasis, self.nbasis), "d"),
915 numpy.zeros((self.nbasis, self.nbasis), "d")]
916
917 # Bump up the spin.
918 if line.strip() == "***** SPIN 2 *****":
919 spin = 1
920 symoffset = 0
921 lastrow = 0
922
923 # Next symmetry.
924 if line.strip()[:4] == "=== ":
925 sym = line.split()[1]
926 if self.nosymflag:
927 aolist = list(range(self.nbasis))
928 else:
929 aolist = self.symlist[sym][spin]
930 # Add to the symmetry offset of AO ordering.
931 symoffset += lastrow
932
933 # Blocks with coefficient always start with "MOs :".
934 if line[1:6] == "MOs :":
935 # Next line has the MO index contributed to.
936 monumbers = [int(n) for n in line[6:].split()]
937
938 self.skip_lines(inputfile, ['occup', 'label'])
939
940 # The table can end with a blank line or "1".
941 row = 0
942 line = next(inputfile)
943 while not line.strip() in ["", "1"]:
944 info = line.split()
945
946 if int(info[0]) < self.start_indeces[sym]:
947 #check to make sure we aren't parsing CFs
948 line = next(inputfile)
949 continue
950
951 self.updateprogress(inputfile, "Coefficients", self.fupdate)
952 row += 1
953 coeffs = [float(x) for x in info[1:]]
954 moindices = [aolist[n-1] for n in monumbers]
955 # The AO index is 1 less than the row.
956 aoindex = symoffset + row - 1
957 for i in range(len(monumbers)):
958 self.mocoeffs[spin][moindices[i], aoindex] = coeffs[i]
959 line = next(inputfile)
960 lastrow = row
961
962 # **************************************************************************
963 # * *
964 # * Final excitation energies from Davidson algorithm *
965 # * *
966 # **************************************************************************
967 #
968 # Number of loops in Davidson routine = 20
969 # Number of matrix-vector multiplications = 24
970 # Type of excitations = SINGLET-SINGLET
971 #
972 # Symmetry B.u
973 #
974 # ... several blocks ...
975 #
976 # Normal termination of EXCITATION program part
977 if line[4:53] == "Final excitation energies from Davidson algorithm":
978
979 while line[1:9] != "Symmetry" and "Normal termination" not in line:
980 line = next(inputfile)
981 symm = self.normalisesym(line.split()[1])
982
983 # Excitation energies E in a.u. and eV, dE wrt prev. cycle,
984 # oscillator strengths f in a.u.
985 #
986 # no. E/a.u. E/eV f dE/a.u.
987 # -----------------------------------------------------
988 # 1 0.17084 4.6488 0.16526E-01 0.28E-08
989 # ...
990 while line.split() != ['no.', 'E/a.u.', 'E/eV', 'f', 'dE/a.u.'] and "Normal termination" not in line:
991 line = next(inputfile)
992
993 self.skip_line(inputfile, 'dashes')
994
995 etenergies = []
996 etoscs = []
997 etsyms = []
998 line = next(inputfile)
999 while len(line) > 2:
1000 info = line.split()
1001 etenergies.append(utils.convertor(float(info[2]), "eV", "wavenumber"))
1002 etoscs.append(float(info[3]))
1003 etsyms.append(symm)
1004 line = next(inputfile)
1005
1006 # There is another section before this, with transition dipole moments,
1007 # but this should just skip past it.
1008 while line[1:53] != "Major MO -> MO transitions for the above excitations":
1009 line = next(inputfile)
1010
1011 # Note that here, and later, the number of blank lines can vary between
1012 # version of ADF (extra lines are seen in 2013.01 unit tests, for example).
1013 self.skip_line(inputfile, 'blank')
1014 excitation_occupied = next(inputfile)
1015 header = next(inputfile)
1016 while not header.strip():
1017 header = next(inputfile)
1018 header2 = next(inputfile)
1019 x_y_z = next(inputfile)
1020 line = next(inputfile)
1021 while not line.strip():
1022 line = next(inputfile)
1023
1024 # Before we start handeling transitions, we need to create mosyms
1025 # with indices; only restricted calcs are possible in ADF.
1026 counts = {}
1027 syms = []
1028 for mosym in self.mosyms[0]:
1029 if list(counts.keys()).count(mosym) == 0:
1030 counts[mosym] = 1
1031 else:
1032 counts[mosym] += 1
1033 syms.append(str(counts[mosym]) + mosym)
1034
1035 etsecs = []
1036 printed_warning = False
1037 for i in range(len(etenergies)):
1038
1039 etsec = []
1040 info = line.split()
1041 while len(info) > 0:
1042
1043 match = re.search('[^0-9]', info[1])
1044 index1 = int(info[1][:match.start(0)])
1045 text = info[1][match.start(0):]
1046 symtext = text[0].upper() + text[1:]
1047 sym1 = str(index1) + self.normalisesym(symtext)
1048
1049 match = re.search('[^0-9]', info[3])
1050 index2 = int(info[3][:match.start(0)])
1051 text = info[3][match.start(0):]
1052 symtext = text[0].upper() + text[1:]
1053 sym2 = str(index2) + self.normalisesym(symtext)
1054
1055 try:
1056 index1 = syms.index(sym1)
1057 except ValueError:
1058 if not printed_warning:
1059 self.logger.warning("Etsecs are not accurate!")
1060 printed_warning = True
1061
1062 try:
1063 index2 = syms.index(sym2)
1064 except ValueError:
1065 if not printed_warning:
1066 self.logger.warning("Etsecs are not accurate!")
1067 printed_warning = True
1068
1069 etsec.append([(index1, 0), (index2, 0), float(info[4])])
1070
1071 line = next(inputfile)
1072 info = line.split()
1073
1074 etsecs.append(etsec)
1075
1076 # Again, the number of blank lines between transition can vary.
1077 line = next(inputfile)
1078 while not line.strip():
1079 line = next(inputfile)
1080
1081 if not hasattr(self, "etenergies"):
1082 self.etenergies = etenergies
1083 else:
1084 self.etenergies += etenergies
1085
1086 if not hasattr(self, "etoscs"):
1087 self.etoscs = etoscs
1088 else:
1089 self.etoscs += etoscs
1090
1091 if not hasattr(self, "etsyms"):
1092 self.etsyms = etsyms
1093 else:
1094 self.etsyms += etsyms
1095
1096 if not hasattr(self, "etsecs"):
1097 self.etsecs = etsecs
1098 else:
1099 self.etsecs += etsecs
1100
1101 if "M U L L I K E N P O P U L A T I O N S" in line:
1102 if not hasattr(self, "atomcharges"):
1103 self.atomcharges = {}
1104 while line[1:5] != "Atom":
1105 line = next(inputfile)
1106 self.skip_line(inputfile, 'dashes')
1107 mulliken = []
1108 line = next(inputfile)
1109 while line.strip():
1110 mulliken.append(float(line.split()[2]))
1111 line = next(inputfile)
1112 self.atomcharges["mulliken"] = mulliken
1113
1114 # Dipole moment is always printed after a point calculation,
1115 # and the reference point for this is always the origin (0,0,0)
1116 # and not necessarily the center of mass, as explained on the
1117 # ADF user mailing list (see cclib/cclib#113 for details).
1118 #
1119 # =============
1120 # Dipole Moment *** (Debye) ***
1121 # =============
1122 #
1123 # Vector : 0.00000000 0.00000000 0.00000000
1124 # Magnitude: 0.00000000
1125 #
1126 if line.strip()[:13] == "Dipole Moment":
1127
1128 self.skip_line(inputfile, 'equals')
1129
1130 # There is not always a blank line here, for example when the dipole and quadrupole
1131 # moments are printed after the multipole derived atomic charges. Still, to the best
1132 # of my knowledge (KML) the values are still in Debye.
1133 line = next(inputfile)
1134 if not line.strip():
1135 line = next(inputfile)
1136
1137 assert line.split()[0] == "Vector"
1138 dipole = [float(d) for d in line.split()[-3:]]
1139
1140 reference = [0.0, 0.0, 0.0]
1141 if not hasattr(self, 'moments'):
1142 self.moments = [reference, dipole]
1143 else:
1144 try:
1145 assert self.moments[1] == dipole
1146 except AssertionError:
1147 self.logger.warning('Overwriting previous multipole moments with new values')
1148 self.moments = [reference, dipole]
1149
1150 # Molecular response properties.
1151 if line.strip()[1:-1].strip() == "RESPONSE program part":
1152
1153 while line.strip() != "Normal termination of RESPONSE program part":
1154
1155 if "THE DIPOLE-DIPOLE POLARIZABILITY TENSOR:" in line:
1156 if not hasattr(self, 'polarizabilities'):
1157 self.polarizabilities = []
1158 polarizability = numpy.empty(shape=(3, 3))
1159 self.skip_lines(inputfile, ['b', 'FREQUENCY', 'coordinates'])
1160 # Ordering of rows/columns is Y, Z, X.
1161 ordering = [1, 2, 0]
1162 indices = list(itertools.product(ordering, ordering))
1163 for i in range(3):
1164 tokens = next(inputfile).split()
1165 for j in range(3):
1166 polarizability[indices[(i*3)+j]] = tokens[j]
1167 self.polarizabilities.append(polarizability)
1168
1169 line = next(inputfile)
1170
1171 if line[:24] == ' Buffered I/O statistics':
1172 self.metadata['success'] = True