Debian Codegraph @

cclib/io/moldenwriter.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2017, the cclib development team
4 #
5 # This file is part of cclib (http://cclib.github.io) and is distributed under
6 # the terms of the BSD 3-Clause License.
7
8 """A writer for MOLDEN format files."""
9
10 import os.path
11 import math
12 import decimal
13
14 from cclib.parser import utils
15 from cclib.io import filewriter
16
17
18 def round_molden(num, p=6):
19 """Molden style number rounding in [Atoms] section."""
20 # Digit at pth position after dot.
21 p_digit = math.floor(abs(num) * 10 ** p) % 10
22 # If the 6th digit after dot is greater than 5, but is not 7,
23 # round the number upto 6th place.
24 # Else truncate at 6th digit after dot.
25 if p_digit > 5 and p_digit != 7:
26 return round(num, p)
27 if num >= 0:
28 return math.floor(num * 10 ** p) / 10 ** p
29 else:
30 return math.ceil(num * 10 ** p) / 10 ** p
31
32
33 class MOLDEN(filewriter.Writer):
34 """A writer for MOLDEN files."""
35
36 required_attrs = ('atomcoords', 'atomnos', 'natom')
37
38 def _title(self, path):
39 """Return filename without extension to be used as title."""
40 title = os.path.basename(os.path.splitext(path)[0])
41 return title
42
43 def _coords_from_ccdata(self, index):
44 """Create [Atoms] section using geometry at the given index."""
45 elements = [self.pt.element[Z] for Z in self.ccdata.atomnos]
46 if self.ghost is not None:
47 elements = [self.ghost if e is None else e for e in elements]
48 elif None in elements:
49 raise ValueError('It seems that there is at least one ghost atom ' +
50 'in these elements. Please use the ghost flag to'+
51 ' specify a label for the ghost atoms.')
52 atomcoords = self.ccdata.atomcoords[index]
53 atomnos = self.ccdata.atomnos
54 nos = range(self.ccdata.natom)
55
56 # element_name number atomic_number x y z
57 atom_template = '{:2s} {:5d} {:2d} {:12.6f} {:12.6f} {:12.6f}'
58 lines = []
59 for element, no, atomno, coord in zip(elements, nos, atomnos,
60 atomcoords):
61 x, y, z = map(round_molden, coord)
62 lines.append(atom_template.format(element, no + 1, atomno,
63 x, y, z))
64
65 return lines
66
67 def _gto_from_ccdata(self):
68 """Create [GTO] section using gbasis.
69
70 atom_sequence_number1 0
71 shell_label number_of_primitives 1.00
72 exponent_primitive_1 contraction_coeff_1 (contraction_coeff_1)
73 ...
74 empty line
75 atom_sequence__number2 0
76 """
77
78 gbasis = self.ccdata.gbasis
79 label_template = '{:s} {:5d} 1.00'
80 basis_template = '{:15.9e} {:15.9e}'
81 lines = []
82
83 for no, basis in enumerate(gbasis):
84 lines.append('{:3d} 0'.format(no + 1))
85 for prims in basis:
86 lines.append(label_template.format(prims[0].lower(),
87 len(prims[1])))
88 for prim in prims[1]:
89 lines.append(basis_template.format(prim[0], prim[1]))
90 lines.append('')
91 lines.append('')
92 return lines
93
94 def _scfconv_from_ccdata(self):
95 """Create [SCFCONV] section using gbasis.
96
97 scf-first 1 THROUGH 12
98 -672.634394
99 ...
100 -673.590571
101 -673.590571
102 """
103
104 lines = ["scf-first 1 THROUGH %d" % len(self.ccdata.scfenergies)]
105
106 for scfenergy in self.ccdata.scfenergies:
107 lines.append('{:15.6f}'.format(scfenergy))
108
109 return lines
110
111 def _rearrange_mocoeffs(self, mocoeffs):
112 """Rearrange cartesian F functions in mocoeffs.
113
114 Molden's order:
115 xxx, yyy, zzz, xyy, xxy, xxz, xzz, yzz, yyz, xyz
116 cclib's order:
117 XXX, YYY, ZZZ, XXY, XXZ, YYX, YYZ, ZZX, ZZY, XYZ
118 cclib's order can be converted by:
119 moving YYX two indexes ahead, and
120 moving YYZ two indexes back.
121 """
122 aonames = self.ccdata.aonames
123 mocoeffs = mocoeffs.tolist()
124
125 pos_yyx = [key for key, val in enumerate(aonames) if '_YYX' in val]
126 pos_yyz = [key for key, val in enumerate(aonames) if '_YYZ' in val]
127
128 if pos_yyx:
129 for pos in pos_yyx:
130 mocoeffs.insert(pos-2, mocoeffs.pop(pos))
131 if pos_yyz:
132 for pos in pos_yyz:
133 mocoeffs.insert(pos+2, mocoeffs.pop(pos))
134
135 return mocoeffs
136
137
138 def _mo_from_ccdata(self):
139 """Create [MO] section.
140
141 Sym= symmetry_label_1
142 Ene= mo_energy_1
143 Spin= (Alpha|Beta)
144 Occup= mo_occupation_number_1
145 ao_number_1 mo_coefficient_1
146 ...
147 ao_number_n mo_coefficient_n
148 ...
149 """
150
151 moenergies = self.ccdata.moenergies
152 mocoeffs = self.ccdata.mocoeffs
153 homos = self.ccdata.homos
154 mult = self.ccdata.mult
155
156 has_syms = False
157 lines = []
158
159 # Sym attribute is optional in [MO] section.
160 if hasattr(self.ccdata, 'mosyms'):
161 has_syms = True
162 syms = self.ccdata.mosyms
163
164 spin = 'Alpha'
165 for i in range(mult):
166 for j in range(len(moenergies[i])):
167 if has_syms:
168 lines.append(' Sym= %s' % syms[i][j])
169 moenergy = utils.convertor(moenergies[i][j], 'eV', 'hartree')
170 lines.append(' Ene= {:10.4f}'.format(moenergy))
171 lines.append(' Spin= %s' % spin)
172 if j <= homos[i]:
173 lines.append(' Occup= {:10.6f}'.format(2.0 / mult))
174 else:
175 lines.append(' Occup= {:10.6f}'.format(0.0))
176 # Rearrange mocoeffs according to Molden's lexicographical order.
177 mocoeffs[i][j] = self._rearrange_mocoeffs(mocoeffs[i][j])
178 for k, mocoeff in enumerate(mocoeffs[i][j]):
179 lines.append('{:4d} {:10.6f}'.format(k + 1, mocoeff))
180
181 spin = 'Beta'
182
183 return lines
184
185 def generate_repr(self):
186 """Generate the MOLDEN representation of the logfile data."""
187
188 molden_lines = ['[Molden Format]']
189
190 # Title of file.
191 if self.jobfilename is not None:
192 molden_lines.append('[Title]')
193 molden_lines.append(self._title(self.jobfilename))
194
195 # Coordinates for the Electron Density/Molecular orbitals.
196 # [Atoms] (Angs|AU)
197 unit = "Angs"
198 molden_lines.append('[Atoms] %s' % unit)
199 # Last set of coordinates for geometry optimization runs.
200 index = -1
201 molden_lines.extend(self._coords_from_ccdata(index))
202
203 # Either both [GTO] and [MO] should be present or none of them.
204 if hasattr(self.ccdata, 'gbasis') and hasattr(self.ccdata, 'mocoeffs')\
205 and hasattr(self.ccdata, 'moenergies'):
206
207 molden_lines.append('[GTO]')
208 molden_lines.extend(self._gto_from_ccdata())
209
210 molden_lines.append('[MO]')
211 molden_lines.extend(self._mo_from_ccdata())
212
213 # Omitting until issue #390 is resolved.
214 # https://github.com/cclib/cclib/issues/390
215 # if hasattr(self.ccdata, 'scfenergies'):
216 # if len(self.ccdata.scfenergies) > 1:
217 # molden_lines.append('[SCFCONV]')
218 # molden_lines.extend(self._scfconv_from_ccdata())
219
220 # molden_lines.append('')
221
222 return '\n'.join(molden_lines)
223
224
225 class MoldenReformatter(object):
226 """Reformat Molden output files."""
227
228 def __init__(self, filestring):
229 self.filestring = filestring
230
231 def scinotation(self, num):
232 """Convert Molden style number formatting to scientific notation.
233 0.9910616900D+02 --> 9.910617e+01
234 """
235 num = num.replace('D', 'e')
236 return str('%.9e' % decimal.Decimal(num))
237
238 def reformat(self):
239 """Reformat Molden output file to:
240 - use scientific notation,
241 - split sp molecular orbitals to s and p, and
242 - replace multiple spaces with single."""
243 filelines = iter(self.filestring.split("\n"))
244 lines = []
245
246 for line in filelines:
247 line = line.replace('\n', '')
248 # Replace multiple spaces with single spaces.
249 line = ' '.join(line.split())
250
251 # Check for [Title] section.
252 if '[title]' in line.lower():
253 # skip the title
254 line = next(filelines)
255 line = next(filelines)
256
257 # Exclude SCFCONV section until issue #390 is resolved.
258 # https://github.com/cclib/cclib/issues/390
259 if '[scfconv]' in line.lower():
260 break
261
262 # Although Molden format specifies Sym in [MO] section,
263 # the Molden program does not print it.
264 if 'sym' in line.lower():
265 continue
266
267 # Convert D notation to scientific notation.
268 if 'D' in line:
269 vals = line.split()
270 vals = [self.scinotation(i) for i in vals]
271 lines.append(' '.join(vals))
272
273 # Convert sp to s and p orbitals.
274 elif 'sp' in line:
275 n_prim = int(line.split()[1])
276 new_s = ['s ' + str(n_prim) + ' 1.00']
277 new_p = ['p ' + str(n_prim) + ' 1.00']
278 while n_prim > 0:
279 n_prim -= 1
280 line = next(filelines).split()
281 new_s.append(self.scinotation(line[0]) + ' '
282 + self.scinotation(line[1]))
283 new_p.append(self.scinotation(line[0]) + ' '
284 + self.scinotation(line[2]))
285 lines.extend(new_s)
286 lines.extend(new_p)
287 else:
288 lines.append(line)
289
290 return '\n'.join(lines)