Debian Codegraph @

test/data/testGeoOpt.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 """Test geometry optimization logfiles in cclib"""
9
10 import os
11 import unittest
12
13 import numpy
14
15 from common import get_minimum_carbon_separation
16
17 from skip import skipForParser
18
19 __filedir__ = os.path.realpath(os.path.dirname(__file__))
20
21
22 class GenericGeoOptTest(unittest.TestCase):
23 """Generic geometry optimization unittest"""
24
25 # In STO-3G, H has 1, C has 3.
26 nbasisdict = {1:1, 6:5}
27
28 # Some programs print surplus atom coordinates by default.
29 extracoords = 0
30
31 # Some programs do surplus SCF cycles by default.
32 extrascfs = 0
33
34 # Approximate B3LYP energy of dvb after SCF in STO-3G.
35 b3lyp_energy = -10365
36 b3lyp_tolerance = 40
37
38 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
39 @skipForParser('MOPAC', 'The success status is not parsed yet')
40 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
41 def test_success(self):
42 self.assertTrue(self.data.metadata['success'])
43
44 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
45 def testnatom(self):
46 """Is the number of atoms equal to 20?"""
47 self.assertEqual(self.data.natom, 20)
48
49 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
50 def testatomnos(self):
51 """Are the atomnos correct?"""
52 # This will work only for numpy
53 #self.assertEqual(self.data.atomnos.dtype.char, 'i')
54
55 atomnos_types = [numpy.issubdtype(atomno, numpy.signedinteger)
56 for atomno in self.data.atomnos]
57 self.assertTrue(numpy.alltrue(atomnos_types))
58
59 self.assertEqual(self.data.atomnos.shape, (20,) )
60
61 count_C = sum(self.data.atomnos == 6)
62 count_H = sum(self.data.atomnos == 1)
63 self.assertEqual(count_C + count_H, 20)
64
65 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
66 def testatomcoords(self):
67 """Are atomcoords consistent with natom and Angstroms?"""
68 natom = len(self.data.atomcoords[0])
69 ref = self.data.natom
70 msg = "natom is %d but len(atomcoords[0]) is %d" % (ref, natom)
71 self.assertEqual(natom, ref, msg)
72
73 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
74 def testatomcoords_units(self):
75 """Are atomcoords consistent with Angstroms?"""
76 min_carbon_dist = get_minimum_carbon_separation(self.data)
77 dev = abs(min_carbon_dist - 1.34)
78 self.assertTrue(dev < 0.15, "Minimum carbon dist is %.2f (not 1.34)" % min_carbon_dist)
79
80 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
81 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
82 def testcharge_and_mult(self):
83 """Are the charge and multiplicity correct?"""
84 self.assertEqual(self.data.charge, 0)
85 self.assertEqual(self.data.mult, 1)
86
87 @skipForParser('MOPAC', 'Not implemented.')
88 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
89 def testnbasis(self):
90 """Is the number of basis set functions correct?"""
91 count = sum([self.nbasisdict[n] for n in self.data.atomnos])
92 self.assertEqual(self.data.nbasis, count)
93
94 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
95 def testcoreelectrons(self):
96 """Are the coreelectrons all 0?"""
97 ans = numpy.zeros(self.data.natom, 'i')
98 numpy.testing.assert_array_equal(self.data.coreelectrons, ans)
99
100 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
101 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
102 def testnormalisesym(self):
103 """Did this subclass overwrite normalisesym?"""
104 # https://stackoverflow.com/a/8747890
105 self.logfile.normalisesym("A")
106
107 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
108 @skipForParser('MOPAC', 'Not implemented.')
109 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
110 def testhomos(self):
111 """Is the index of the HOMO equal to 34?"""
112 ref = numpy.array([34], "i")
113 msg = "%s != array([34], 'i')" % numpy.array_repr(self.data.homos)
114 numpy.testing.assert_array_equal(self.data.homos, ref, msg)
115
116 @skipForParser('MOPAC', 'The scfvalues attribute is not parsed yet')
117 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
118 def testscfvaluetype(self):
119 """Are scfvalues and its elements the right type?"""
120 self.assertEqual(type(self.data.scfvalues),type([]))
121 self.assertEqual(type(self.data.scfvalues[0]),type(numpy.array([])))
122
123 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
124 def testscfenergy(self):
125 """Is the SCF energy close to target?"""
126 scf = self.data.scfenergies[-1]
127 ref = self.b3lyp_energy
128 tol = self.b3lyp_tolerance
129 msg = "Final SCF energy: %f not %i +- %ieV" %(scf, ref, tol)
130 self.assertAlmostEqual(scf, ref, delta=40, msg=msg)
131
132 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
133 def testscfenergydim(self):
134 """Is the number of SCF energies consistent with atomcoords?"""
135 count_scfenergies = self.data.scfenergies.shape[0] - self.extrascfs
136 count_atomcoords = self.data.atomcoords.shape[0] - self.extracoords
137 self.assertEqual(count_scfenergies, count_atomcoords)
138
139 @skipForParser('MOPAC', 'The scftargets attribute is not parsed yet')
140 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
141 def testscftargetdim(self):
142 """Do the scf targets have the right dimensions?"""
143 dim_scftargets = self.data.scftargets.shape
144 dim_scfvalues = (len(self.data.scfvalues),len(self.data.scfvalues[0][0]))
145 self.assertEqual(dim_scftargets, dim_scfvalues)
146
147 @skipForParser('MOPAC', 'Not implemented.')
148 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
149 def testgeovalues_atomcoords(self):
150 """Are atomcoords consistent with geovalues?"""
151 count_geovalues = len(self.data.geovalues)
152 count_coords = len(self.data.atomcoords) - self.extracoords
153 msg = "len(atomcoords) is %d but len(geovalues) is %d" % (count_coords, count_geovalues)
154 self.assertEqual(count_geovalues, count_coords, msg)
155
156 @skipForParser('MOPAC', 'Not implemented.')
157 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
158 def testgeovalues_scfvalues(self):
159 """Are scfvalues consistent with geovalues?"""
160 count_scfvalues = len(self.data.scfvalues) - self.extrascfs
161 count_geovalues = len(self.data.geovalues)
162 self.assertEqual(count_scfvalues, count_geovalues)
163
164 @skipForParser('MOPAC', 'Not implemented.')
165 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
166 def testgeotargets(self):
167 """Do the geo targets have the right dimensions?"""
168 dim_geotargets = self.data.geotargets.shape
169 dim_geovalues = (len(self.data.geovalues[0]), )
170 self.assertEqual(dim_geotargets, dim_geovalues)
171
172 @skipForParser('MOPAC', 'Not implemented.')
173 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
174 def testoptdone(self):
175 """Has the geometry converged and set optdone to True?"""
176 self.assertTrue(self.data.optdone)
177 self.assertTrue(numpy.all(numpy.abs(self.data.geovalues[-1]) <= self.data.geotargets))
178
179 @skipForParser("ADF", "Not implemented.")
180 @skipForParser("DALTON", "Not implemented.")
181 @skipForParser("GAMESS", "Not implemented.")
182 @skipForParser("GAMESSUK", "Not implemented.")
183 @skipForParser("Jaguar", "Not implemented.")
184 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
185 @skipForParser("Molpro", "Not implemented.")
186 @skipForParser("MOPAC", "Not implemented.")
187 @skipForParser("NWChem", "Not implemented.")
188 @skipForParser("ORCA", "Not implemented.")
189 @skipForParser("QChem", "Not implemented.")
190 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
191 def testoptstatus(self):
192 """Is optstatus consistent with geovalues and reasonable?"""
193 self.assertEqual(len(self.data.optstatus), len(self.data.geovalues))
194 self.assertEqual(self.data.optstatus[0], self.data.OPT_NEW)
195 for i in range(1, len(self.data.optstatus)-1):
196 self.assertEqual(self.data.optstatus[i], self.data.OPT_UNKNOWN)
197 self.assertEqual(self.data.optstatus[-1], self.data.OPT_DONE)
198
199 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
200 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
201 def testmoenergies(self):
202 """Are only the final MOs parsed?"""
203 self.assertEqual(len(self.data.moenergies), 1)
204 if hasattr(self.data, "mocoeffs"):
205 self.assertEqual(len(self.data.mocoeffs), 1)
206
207 @skipForParser('ADF', 'Not implemented.')
208 @skipForParser('DALTON', 'Not implemented.')
209 @skipForParser('GAMESS', 'Not implemented.')
210 @skipForParser('GAMESSUK', 'Not implemented.')
211 @skipForParser('Jaguar', 'Not implemented.')
212 @skipForParser('Molcas', 'The parser is still being developed so we skip this test')
213 @skipForParser('MOPAC', 'Not implemented.')
214 @skipForParser('NWChem', 'Not implemented.')
215 @skipForParser('Turbomole', 'The parser is still being developed so we skip this test')
216 def testgradsdim(self):
217 """Do the grads have the right dimensions?"""
218 self.assertEqual(self.data.grads.shape,(len(self.data.geovalues),self.data.natom,3))
219
220
221 class ADFGeoOptTest(GenericGeoOptTest):
222 """Customized geometry optimization unittest"""
223
224 extracoords = 1
225 extrascfs = 1
226
227 b3lyp_energy = -140
228 b3lyp_tolerance = 1
229
230
231 class DALTONGeoOptTest(GenericGeoOptTest):
232 """Customzed geometry optimziation unittest"""
233
234 # DALTON will normally print the geometry several extra times as the "final geometry"
235 # when an optimziation converges. We don't parse those coordinates, but the parser
236 # does catch the geometry printed in the final static property calculation when
237 # that is done for the final geometry (presumably always).
238 extracoords = 1
239
240 # Although DALTON generally has three criteria for convergence, it normally only
241 # requires two of them to end a geometry optimization. This is printed in the output
242 # and can probably be tweaked in the input, but we don't parsed that in cclib.
243 def testoptdone(self):
244 """Has the geometry converged and set optdone to True?"""
245 self.assertTrue(self.data.optdone)
246 convergence = numpy.abs(self.data.geovalues[-1]) <= self.data.geotargets
247 self.assertTrue(sum(convergence) >= 2)
248
249
250 class MolcasGeoOptTest(GenericGeoOptTest):
251 """Customized restricted single point HF unittest"""
252
253 # Molcas prints the input coordinates and performs the &scf job
254 # once before entering the optimization part where the coordinates and
255 # scf section are printed for each iteration. Hence we have an extra set of
256 # coordinates and extra set of SCF attributes (scfenergies, scftargets & scfvalues).
257 extracoords = 1
258 extrascfs = 1
259
260
261 class MolproGeoOptTest(GenericGeoOptTest):
262 """Customized geometry optimization unittest"""
263
264 # Note that these extra coordinates and energies will be available only
265 # if the appropriate output is parsed, and Molpro often saves the initial
266 # SCF run and subsequent geometry optimization to separate files, which
267 # both need to be given to the cclib parser (as a list).
268 extracoords = 1
269 extrascfs = 2
270
271 # Here is what the manual has to say about convergence:
272 # The standard MOLPRO convergency criterion requires the maximum component of the gradient
273 # to be less then $3 \cdot 10^{-4}$ [a.u.] and the maximum energy change to be less than
274 # $1 \cdot 10^{-6}$ [H] or the maximum component of the gradient to be less then
275 # $3 \cdot 10^{-4}$ [a.u.] and the maximum component of the step to be less then
276 # $3 \cdot 10^{-4}$ [a.u.].
277 #
278 # It is also possible to use the convergency criterion of (...)
279 #
280 # Source: https://www.molpro.net/info/2012.1/doc/manual/node592.html
281 def testoptdone(self):
282 """Has the geometry converged and set optdone to True?"""
283 self.assertTrue(self.data.optdone)
284 target_e, target_g, target_s = self.data.geotargets
285 value_e, value_g, value_s = self.data.geovalues[-1]
286 converged = (value_e < target_e and value_g < target_g) or (value_g < target_g and value_s < target_s)
287 self.assertTrue(converged)
288
289
290 class MOPACGeoOptTest(GenericGeoOptTest):
291 """Customized geometry optimization unittest for MOPAC."""
292
293 # The geometry optimization unit test logfile uses a PM7 Hamiltonian.
294 b3lyp_energy = 2.22
295 b3lyp_tolerance = 0.01
296
297
298 class NWChemGeoOptTest(GenericGeoOptTest):
299 """Customized restricted single point HF unittest"""
300
301 # NWChem typically prints the coordinates in the input module, at the
302 # beginning of each geometry optimization step, and then again after
303 # the optimziation is finished, so the first and last coordinates
304 # are repeated. On the other hand, each optimization step often
305 # involves a line search which we don't parse (see parse code for details).
306 extracoords = 2
307 extrascfs = 0
308
309
310 class OrcaGeoOptTest(GenericGeoOptTest):
311 """Customized geometry optimization unittest"""
312
313 extracoords = 1
314 extrascfs = 1
315
316 # Besides all the geovalues being below their tolerances, ORCA also considers
317 # an optimization finished in some extra cases. These are:
318 # 1) everything converged except the energy (within 25 x tolerance)
319 # 2) gradient is overachieved and displacement is reasonable (3 x tolerance)
320 # 3) displacement is overachieved and gradient is reasonable (3 x tolerance)
321 # 4) energy, gradients and angles are converged (displacements not considered)
322 # All these exceptions are signaleld in the output with some comments, and here
323 # we include the first three exceptions for the pruposes of the unit test.
324 def testoptdone(self):
325 """Has the geometry converged and set optdone to True?"""
326
327 self.assertTrue(self.data.optdone)
328
329 targets = self.data.geotargets
330 values = numpy.abs(self.data.geovalues[-1])
331
332 target_e = targets[0]
333 target_g = targets[1:3]
334 target_x = targets[3:]
335 value_e = values[0]
336 value_g = values[1:3]
337 value_x = values[3:]
338
339 conv_all = all(values < targets)
340 conv_e = value_e < 25*target_e and all(value_g < target_g) and all(value_x < target_x)
341 conv_g = value_e < target_e and all(value_g < target_g/3.0) and all(value_x < target_x*3.0)
342 conv_x = value_e < target_e and all(value_g < target_g*3.0) and all(value_x < target_x/3.0)
343 converged = conv_all or conv_e or conv_g or conv_x
344 self.assertTrue(converged)
345
346
347 class Psi4GeoOptTest(GenericGeoOptTest):
348 """Customized geometry optimization unittest"""
349
350 # Psi has a number of different convergence strategies to choose from, as described here:
351 # http://sirius.chem.vt.edu/psi4manual/latest/optking.html
352 # and the default is to check that the max. force is converged and if the max energy change
353 # or dispalcement is converged. This is in fact what is tested below.
354 def testoptdone(self):
355 """Has the geometry converged and set optdone to True?"""
356
357 self.assertTrue(self.data.optdone)
358
359 targets = self.data.geotargets
360 values = numpy.abs(self.data.geovalues[-1])
361
362 # Since the other criteria are not used and are not printed in this case, they should
363 # be parsed as numpy.inf, for which we can check.
364 self.assertTrue(numpy.isinf(targets[2]))
365 self.assertTrue(numpy.isinf(targets[4]))
366
367 conv = values[1] < targets[1] and (values[0] < targets[0] or values[3] < targets[3])
368 self.assertTrue(conv)
369
370
371 if __name__=="__main__":
372
373 import sys
374 sys.path.insert(1, os.path.join(__filedir__, ".."))
375
376 from test_data import DataSuite
377 suite = DataSuite(['GeoOpt'])
378 suite.testall()