run_tests.py 35 KB
Newer Older
1
2
3
4
"""
This is a module for unit testing the CP2K parser. The unit tests are run with
a custom backend that outputs the results directly into native python object for
easier and faster analysis.
5
6
7
8
9
10
11

Each property that has an enumerable list of different possible options is
assigned a new test class, that should ideally test through all the options.

The properties that can have any value imaginable will be tested only for one
specific case inside a test class that is designed for a certain type of run
(MD, optimization, QM/MM, etc.)
12
13
14
15
16
17
18
19
"""
import os
import unittest
import logging
import numpy as np
from cp2kparser import CP2KParser
from nomadcore.unit_conversion.unit_conversion import convert_unit

20
# Setup the logger so that it doesn't spam messages during tests
21
22
23
24
25
26
27
28
29
30
logging.basicConfig(
    level=logging.DEBUG,
    format=(
        '%(filename)s: '
        '%(levelname)s: '
        '%(funcName)s(): '
        '%(lineno)d:\t'
        '%(message)s'
    )
)
31
32
logger = logging.getLogger("nomad")
logger.setLevel(logging.CRITICAL)
33
logging.getLogger("nomadcore.caching_backend").setLevel(logging.CRITICAL)
34

35
36

#===============================================================================
37
def get_results(folder, metainfo_to_keep=None):
38
39
40
41
42
43
    """Get the given result from the calculation in the given folder by using
    the Analyzer in the nomadtoolkit package. Tries to optimize the parsing by
    giving the metainfo_to_keep argument.

    Args:
        folder: The folder relative to the directory of this script where the
44
            parsed calculation resides.
45
46
47
        metaname: The quantity to extract.
    """
    dirname = os.path.dirname(__file__)
48
    filename = os.path.join(dirname, folder, "unittest.out")
49
    parser = CP2KParser(filename, None)
50
    results = parser.parse()
51
52
53
54
    return results


#===============================================================================
55
56
def get_result(folder, metaname, optimize=True):
    if optimize:
57
        results = get_results(folder, None)
58
59
    else:
        results = get_results(folder)
60
    result = results[metaname]
Lauri Himanen's avatar
Lauri Himanen committed
61
    return result
62
63


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#===============================================================================
class TestErrors(unittest.TestCase):
    """Test misc. error stuations which may occur during the parsing.
    """
    def test_no_file(self):
        self.assertRaises(IOError, get_result, "errors/no_file", "XC_functional")

    def test_invalid_file(self):
        self.assertRaises(RuntimeError, get_result, "errors/invalid_file", "XC_functional")

    def test_invalid_run_type(self):
        self.assertRaises(KeyError, get_result, "errors/invalid_run_type", "XC_functional")

    def test_unknown_version(self):
        get_result("errors/unknown_version", "XC_functional")

80
81
82
83
84
85
86
87
88
    def test_unknown_input_keyword(self):
        get_result("errors/unknown_input_keyword", "XC_functional")

    def test_unknown_input_section(self):
        get_result("errors/unknown_input_section", "XC_functional")

    def test_unknown_input_section_parameter(self):
        get_result("errors/unknown_input_section_parameter", "XC_functional")

89

90
91
#===============================================================================
class TestXCFunctional(unittest.TestCase):
92
93
    """Tests that the XC functionals can be properly parsed.
    """
94
95
96

    def test_pade(self):
        xc = get_result("XC_functional/pade", "XC_functional")
97
        self.assertEqual(xc, "1*LDA_XC_TETER93")
98
99
100

    def test_lda(self):
        xc = get_result("XC_functional/lda", "XC_functional")
101
        self.assertEqual(xc, "1*LDA_XC_TETER93")
102
103
104

    def test_blyp(self):
        xc = get_result("XC_functional/blyp", "XC_functional")
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        self.assertEqual(xc, "1*GGA_C_LYP+1*GGA_X_B88")

    def test_b3lyp(self):
        xc = get_result("XC_functional/b3lyp", "XC_functional")
        self.assertEqual(xc, "1*HYB_GGA_XC_B3LYP")

    def test_olyp(self):
        xc = get_result("XC_functional/olyp", "XC_functional")
        self.assertEqual(xc, "1*GGA_C_LYP+1*GGA_X_OPTX")

    def test_hcth120(self):
        xc = get_result("XC_functional/hcth120", "XC_functional")
        self.assertEqual(xc, "1*GGA_XC_HCTH_120")

    def test_pbe0(self):
        xc = get_result("XC_functional/pbe0", "XC_functional")
        self.assertEqual(xc, "1*HYB_GGA_XC_PBEH")

    def test_pbe(self):
        xc = get_result("XC_functional/pbe", "XC_functional")
        self.assertEqual(xc, "1*GGA_C_PBE+1*GGA_X_PBE")
126
127


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#===============================================================================
class TestSCFConvergence(unittest.TestCase):
    """Tests whether the convergence status and number of SCF step can be
    parsed correctly.
    """

    def test_converged(self):
        result = get_result("convergence/converged", "single_configuration_calculation_converged")
        self.assertTrue(result)

    def test_non_converged(self):
        result = get_result("convergence/non_converged", "single_configuration_calculation_converged")
        self.assertFalse(result)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#===============================================================================
class TestForceFiles(unittest.TestCase):
    """Tests that different force files that can be output, can actually be
    found and parsed.
    """

    def test_single_point(self):

        result = get_result("force_file/single_point", "atom_forces")
        expected_result = convert_unit(
            np.array([
                [0.00000000, 0.00000000, 0.00000000],
                [0.00000000, 0.00000001, 0.00000001],
                [0.00000001, 0.00000001, 0.00000000],
                [0.00000001, 0.00000000, 0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
            ]),
            "forceAu"
        )
        self.assertTrue(np.array_equal(result, expected_result))


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#===============================================================================
class TestSelfInteractionCorrectionMethod(unittest.TestCase):
    """Tests that the self-interaction correction can be properly parsed.
    """

    def test_no(self):
        sic = get_result("sic/no", "self_interaction_correction_method")
        self.assertEqual(sic, "")

    def test_ad(self):
        sic = get_result("sic/ad", "self_interaction_correction_method")
        self.assertEqual(sic, "SIC_AD")

    def test_explicit_orbitals(self):
        sic = get_result("sic/explicit_orbitals", "self_interaction_correction_method")
        self.assertEqual(sic, "SIC_EXPLICIT_ORBITALS")

    def test_mauri_spz(self):
        sic = get_result("sic/mauri_spz", "self_interaction_correction_method")
        self.assertEqual(sic, "SIC_MAURI_SPZ")

    def test_mauri_us(self):
        sic = get_result("sic/mauri_us", "self_interaction_correction_method")
        self.assertEqual(sic, "SIC_MAURI_US")


194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#===============================================================================
class TestStressTensorMethods(unittest.TestCase):
    """Tests that the stress tensor can be properly parsed for different
    calculation methods.
    """
    def test_none(self):
        get_results("stress_tensor/none", "section_stress_tensor")

    def test_analytical(self):
        results = get_results("stress_tensor/analytical", ["stress_tensor_method", "stress_tensor"])
        method = results["stress_tensor_method"]
        results["stress_tensor"]
        self.assertEqual(method, "Analytical")

    def test_numerical(self):
        results = get_results("stress_tensor/numerical", ["stress_tensor_method", "stress_tensor"])
        method = results["stress_tensor_method"]
        results["stress_tensor"]
        self.assertEqual(method, "Numerical")

    def test_diagonal_analytical(self):
        results = get_results("stress_tensor/diagonal_analytical", ["stress_tensor_method", "stress_tensor"])
        method = results["stress_tensor_method"]
        results["stress_tensor"]
        self.assertEqual(method, "Diagonal analytical")

    def test_diagonal_numerical(self):
        results = get_results("stress_tensor/diagonal_numerical", ["stress_tensor_method", "stress_tensor"])
        method = results["stress_tensor_method"]
        results["stress_tensor"]
        self.assertEqual(method, "Diagonal numerical")


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#===============================================================================
class TestConfigurationPeriodicDimensions(unittest.TestCase):
    """Tests that the self-interaction correction can be properly parsed.
    """

    def test_default(self):
        result = get_result("configuration_periodic_dimensions/default", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((True, True, True))))

    def test_none(self):
        result = get_result("configuration_periodic_dimensions/none", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((False, False, False))))

    def test_x(self):
        result = get_result("configuration_periodic_dimensions/x", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((True, False, False))))

    def test_y(self):
        result = get_result("configuration_periodic_dimensions/y", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((False, True, False))))

    def test_z(self):
        result = get_result("configuration_periodic_dimensions/z", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((False, False, True))))

    def test_xy(self):
        result = get_result("configuration_periodic_dimensions/xy", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((True, True, False))))

    def test_xyz(self):
        result = get_result("configuration_periodic_dimensions/xyz", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((True, True, True))))

    def test_xz(self):
        result = get_result("configuration_periodic_dimensions/xz", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((True, False, True))))

    def test_yz(self):
        result = get_result("configuration_periodic_dimensions/yz", "configuration_periodic_dimensions")
        self.assertTrue(np.array_equal(result, np.array((False, True, True))))


269
#===============================================================================
270
271
272
class TestEnergyForce(unittest.TestCase):
    """Tests for a CP2K calculation with RUN_TYPE ENERGY_FORCE.
    """
273

274
275
276
    @classmethod
    def setUpClass(cls):
        cls.results = get_results("energy_force", "section_run")
277
        # cls.results.print_summary()
278

279
    def test_energy_total_scf_iteration(self):
280
        result = self.results["energy_total_scf_iteration"]
281
        expected_result = convert_unit(np.array(-32.2320848878), "hartree")
282
        self.assertTrue(np.array_equal(result[0], expected_result))
283

284
285
286
287
288
289
290
291
292
293
    def test_energy_change_scf_iteration(self):
        energy_change = self.results["energy_change_scf_iteration"]
        expected_result = convert_unit(np.array(-3.22E+01), "hartree")
        self.assertTrue(np.array_equal(energy_change[0], expected_result))

    def test_energy_XC_scf_iteration(self):
        result = self.results["energy_XC_scf_iteration"]
        expected_result = convert_unit(np.array(-9.4555961214), "hartree")
        self.assertTrue(np.array_equal(result[0], expected_result))

294
    def test_energy_total(self):
295
        result = self.results["energy_total"]
296
        expected_result = convert_unit(np.array(-31.297885372811063), "hartree")
297
        self.assertTrue(np.array_equal(result, expected_result))
298

299
300
301
302
303
    def test_electronic_kinetic_energy(self):
        result = self.results["electronic_kinetic_energy"]
        expected_result = convert_unit(np.array(13.31525592466418), "hartree")
        self.assertTrue(np.array_equal(result, expected_result))

304
    def test_atom_forces(self):
305
        result = self.results["atom_forces"]
306
307
308
309
310
311
312
313
314
315
316
        expected_result = convert_unit(
            np.array([
                [0.00000000, 0.00000000, 0.00000000],
                [0.00000000, 0.00000001, 0.00000001],
                [0.00000001, 0.00000001, 0.00000000],
                [0.00000001, 0.00000000, 0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
                [-0.00000001, -0.00000001, -0.00000001],
            ]),
317
            "forceAu"
318
        )
319
        self.assertTrue(np.array_equal(result, expected_result))
320

321
    def test_atom_label(self):
322
        atom_labels = self.results["atom_labels"]
Lauri Himanen's avatar
Lauri Himanen committed
323
324
325
326
        expected_labels = np.array(8*["Si"])
        self.assertTrue(np.array_equal(atom_labels, expected_labels))

    def test_simulation_cell(self):
Lauri Himanen's avatar
Lauri Himanen committed
327
        cell = self.results["simulation_cell"]
Lauri Himanen's avatar
Lauri Himanen committed
328
329
330
331
332
333
334
335
        n_vectors = cell.shape[0]
        n_dim = cell.shape[1]
        self.assertEqual(n_vectors, 3)
        self.assertEqual(n_dim, 3)
        expected_cell = convert_unit(np.array([[5.431, 0, 0], [0, 5.431, 0], [0, 0, 5.431]]), "angstrom")
        self.assertTrue(np.array_equal(cell, expected_cell))

    def test_number_of_atoms(self):
Lauri Himanen's avatar
Lauri Himanen committed
336
        n_atoms = self.results["number_of_atoms"]
Lauri Himanen's avatar
Lauri Himanen committed
337
338
339
        self.assertEqual(n_atoms, 8)

    def test_atom_position(self):
340
        atom_position = self.results["atom_positions"]
Lauri Himanen's avatar
Lauri Himanen committed
341
342
343
        expected_position = convert_unit(np.array([4.073023, 4.073023, 1.357674]), "angstrom")
        self.assertTrue(np.array_equal(atom_position[-1, :], expected_position))

344
    def test_x_cp2k_filenames(self):
345
        input_filename = self.results["x_cp2k_input_filename"]
346
347
348
        expected_input = "si_bulk8.inp"
        self.assertTrue(input_filename, expected_input)

349
        bs_filename = self.results["x_cp2k_basis_set_filename"]
350
351
352
        expected_bs = "../BASIS_SET"
        self.assertEqual(bs_filename, expected_bs)

353
        geminal_filename = self.results["x_cp2k_geminal_filename"]
354
355
356
        expected_geminal = "BASIS_GEMINAL"
        self.assertEqual(geminal_filename, expected_geminal)

357
        potential_filename = self.results["x_cp2k_potential_filename"]
358
359
360
        expected_potential = "../GTH_POTENTIALS"
        self.assertEqual(potential_filename, expected_potential)

361
        mm_potential_filename = self.results["x_cp2k_mm_potential_filename"]
362
363
364
        expected_mm_potential = "MM_POTENTIAL"
        self.assertEqual(mm_potential_filename, expected_mm_potential)

365
        coordinate_filename = self.results["x_cp2k_coordinate_filename"]
366
367
        expected_coordinate = "__STD_INPUT__"
        self.assertEqual(coordinate_filename, expected_coordinate)
368

369
    def test_target_multiplicity(self):
370
        multiplicity = self.results["spin_target_multiplicity"]
371
372
373
374
375
376
        self.assertEqual(multiplicity, 1)

    def test_total_charge(self):
        charge = self.results["total_charge"]
        self.assertEqual(charge, 0)

377
378
379
380
381
    def test_single_configuration_calculation_converged(self):
        result = self.results["single_configuration_calculation_converged"]
        self.assertTrue(result)

    def test_scf_dft_number_of_iterations(self):
382
        result = self.results["number_of_scf_iterations"]
383
384
385
386
387
388
389
        self.assertEqual(result, 10)

    def test_single_configuration_to_calculation_method_ref(self):
        result = self.results["single_configuration_to_calculation_method_ref"]
        self.assertEqual(result, 0)

    def test_single_configuration_calculation_to_system_description_ref(self):
390
        result = self.results["single_configuration_calculation_to_system_ref"]
391
392
        self.assertEqual(result, 0)

393
    def test_stress_tensor(self):
394
        result = self.results["stress_tensor"]
395
396
397
398
399
400
401
402
403
404
        expected_result = convert_unit(
            np.array([
                [7.77641684, -0.00000106, -0.00000106],
                [-0.00000106, 7.77641703, -0.00000106],
                [-0.00000106, -0.00000106, 7.77641703],
            ]),
            "GPa"
        )
        self.assertTrue(np.array_equal(result, expected_result))

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    def test_stress_tensor_eigenvalues(self):
        result = self.results["x_cp2k_stress_tensor_eigenvalues"]
        expected_result = convert_unit(np.array([7.77641809, 7.77641797, 7.77641485]), "GPa")
        self.assertTrue(np.array_equal(result, expected_result))

    def test_stress_tensor_eigenvectors(self):
        result = self.results["x_cp2k_stress_tensor_eigenvectors"]
        expected_result = np.array([
            [0.00094549, -0.79967815, 0.60042815],
            [-0.70749682, 0.42379757, 0.56554741],
            [0.70671590, 0.42533573, 0.56536905],
        ])
        self.assertTrue(np.array_equal(result, expected_result))

    def test_stress_tensor_determinant(self):
        result = self.results["x_cp2k_stress_tensor_determinant"]
        expected_result = convert_unit(4.70260626E+02, "GPa^3")
        self.assertTrue(np.array_equal(result, expected_result))

    def test_stress_tensor_one_third_of_trace(self):
        result = self.results["x_cp2k_stress_tensor_one_third_of_trace"]
        expected_result = convert_unit(7.77641697E+00, "GPa")
        self.assertTrue(np.array_equal(result, expected_result))

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
    def test_program_basis_set_type(self):
        result = self.results["program_basis_set_type"]
        self.assertEqual(result, "gaussian")


#===============================================================================
class TestPreprocessor(unittest.TestCase):

    def test_include(self):
        result = get_result("input_preprocessing/include", "x_cp2k_CP2K_INPUT.GLOBAL.PRINT_LEVEL", optimize=False)
        self.assertEqual(result, "LOW")

    def test_variable(self):
        result = get_result("input_preprocessing/variable", "x_cp2k_CP2K_INPUT.GLOBAL.PROJECT_NAME", optimize=False)
        self.assertEqual(result, "variable_test")

445
    def test_variable_multiple(self):
446
        result = get_result("input_preprocessing/variable_multiple", "x_cp2k_CP2K_INPUT.FORCE_EVAL.DFT.MGRID.CUTOFF", optimize=False)
447
        self.assertEqual(result, "50")
448

Lauri Himanen's avatar
Lauri Himanen committed
449
450
    def test_comments(self):
        result = get_result("input_preprocessing/comments", "x_cp2k_CP2K_INPUT.FORCE_EVAL.DFT.MGRID.CUTOFF", optimize=False)
451
        self.assertEqual(result, "120")
Lauri Himanen's avatar
Lauri Himanen committed
452

453
454
    def test_tabseparator(self):
        result = get_result("input_preprocessing/tabseparator", "x_cp2k_CP2K_INPUT.FORCE_EVAL.DFT.MGRID.CUTOFF", optimize=False)
455
        self.assertEqual(result, "120")
456

457

458
459
460
461
462
#===============================================================================
class TestGeoOpt(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
463
        cls.results = get_results("geo_opt/cg", "section_run")
464
465
466
467
468

    def test_geometry_optimization_converged(self):
        result = self.results["geometry_optimization_converged"]
        self.assertTrue(result)

469
    def test_number_of_frames_in_sequence(self):
470
        result = self.results["number_of_frames_in_sequence"]
471
472
        self.assertEqual(result, 7)

473
474
475
476
477
478
    def test_frame_sequence_to_sampling_ref(self):
        result = self.results["frame_sequence_to_sampling_ref"]
        self.assertEqual(result, 0)

    def test_frame_sequence_local_frames_ref(self):
        result = self.results["frame_sequence_local_frames_ref"]
479
        expected_result = np.array([0, 1, 2, 3, 4, 5, 6])
480
481
        self.assertTrue(np.array_equal(result, expected_result))

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    def test_sampling_method(self):
        result = self.results["sampling_method"]
        self.assertEqual(result, "geometry_optimization")

    def test_geometry_optimization_method(self):
        result = self.results["geometry_optimization_method"]
        self.assertEqual(result, "conjugate_gradient")

    def test_geometry_optimization_geometry_change(self):
        result = self.results["geometry_optimization_geometry_change"]
        expected_result = convert_unit(
            0.0010000000,
            "bohr"
        )
        self.assertEqual(result, expected_result)

    def test_geometry_optimization_threshold_force(self):
        result = self.results["geometry_optimization_threshold_force"]
        expected_result = convert_unit(
            0.0010000000,
            "bohr^-1*hartree"
        )
        self.assertEqual(result, expected_result)

    def test_frame_sequence_potential_energy(self):
        result = self.results["frame_sequence_potential_energy"]
        expected_result = convert_unit(
            np.array([
                -17.1534159246,
                -17.1941015290,
                -17.2092321965,
                -17.2097667733,
                -17.2097743028,
                -17.2097743229,
516
                -17.20977820662248,
517
518
519
520
521
            ]),
            "hartree"
        )
        self.assertTrue(np.array_equal(result, expected_result))

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
    def test_atom_positions(self):
        result = self.results["atom_positions"]
        expected_start = convert_unit(
            np.array([
                [12.2353220000, 1.3766420000, 10.8698800000],
                [12.4175775999, 2.2362362573, 11.2616216864],
                [11.9271436933, 1.5723516602, 10.0115134757],
            ]),
            "angstrom"
        )

        expected_end = convert_unit(
            np.array([
                [12.2353220000, 1.3766420000, 10.8698800000],
                [12.4958164689, 2.2307248873, 11.3354322515],
                [11.9975558616, 1.5748085240, 10.0062792262],
            ]),
            "angstrom"
        )
        result_start = result[0,:,:]
        result_end = result[-1,:,:]
        self.assertTrue(np.array_equal(result_start, expected_start))
        self.assertTrue(np.array_equal(result_end, expected_end))
545
546


547
548
549
550
# ===============================================================================
class TestGeoOptTrajFormats(unittest.TestCase):

    def test_xyz(self):
551

552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
        result = get_result("geo_opt/geometry_formats/xyz", "atom_positions", optimize=True)
        expected_start = convert_unit(
            np.array([
                [12.2353220000, 1.3766420000, 10.8698800000],
                [12.4175624065, 2.2362390825, 11.2616392180],
                [11.9271777126, 1.5723402996, 10.0115089094],
            ]),
            "angstrom"
        )
        expected_end = convert_unit(
            np.array([
                [12.2353220000, 1.3766420000, 10.8698800000],
                [12.4957995882, 2.2307218433, 11.3354453867],
                [11.9975764125, 1.5747996320, 10.0062529540],
            ]),
            "angstrom"
        )
        result_start = result[0,:,:]
        result_end = result[-1,:,:]
        self.assertTrue(np.array_equal(result_start, expected_start))
        self.assertTrue(np.array_equal(result_end, expected_end))

    def test_pdb(self):
        result = get_result("geo_opt/geometry_formats/pdb", "atom_positions", optimize=True)
        expected_start = convert_unit(
            np.array([
                [12.235, 1.377, 10.870],
                [12.418, 2.236, 11.262],
                [11.927, 1.572, 10.012],
            ]),
            "angstrom"
        )
        expected_end = convert_unit(
            np.array([
                [12.235, 1.377, 10.870],
                [12.496, 2.231, 11.335],
                [11.998, 1.575, 10.006],
            ]),
            "angstrom"
        )
        result_start = result[0,:,:]
        result_end = result[-1,:,:]
        self.assertTrue(np.array_equal(result_start, expected_start))
        self.assertTrue(np.array_equal(result_end, expected_end))

    def test_dcd(self):
        result = get_result("geo_opt/geometry_formats/dcd", "atom_positions", optimize=True)
        frames = result.shape[0]
        self.assertEqual(frames, 7)


603
604
605
606
607
608
609
610
611
612
613
#===============================================================================
class TestGeoOptOptimizers(unittest.TestCase):

    def test_bfgs(self):
        result = get_result("geo_opt/bfgs", "geometry_optimization_method")
        self.assertEqual(result, "bfgs")

    def test_lbfgs(self):
        result = get_result("geo_opt/lbfgs", "geometry_optimization_method")
        self.assertEqual(result, "bfgs")

614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680

#===============================================================================
class TestGeoOptTrajectory(unittest.TestCase):

    def test_each_and_add_last(self):
        """Test that the EACH and ADD_LAST settings affect the parsing
        correctly.
        """
        results = get_results("geo_opt/each")

        single_conf = results["section_single_configuration_calculation"]
        systems = results["section_system"]

        i_conf = 0
        for calc in single_conf.itervalues():
            system_index = calc["single_configuration_calculation_to_system_ref"][0]
            system = systems[system_index]
            pos = system["atom_positions"]

            if i_conf == 0 or i_conf == 2 or i_conf == 4:
                self.assertEqual(pos, None)
            else:
                pos = system["atom_positions"][0]
                if i_conf == 1:
                    expected_pos = convert_unit(
                        np.array([
                            [12.2353220000, 1.3766420000, 10.8698800000],
                            [12.4618486015, 2.2314871691, 11.3335607388],
                            [11.9990227122, 1.5776813026, 10.0384213366],
                        ]),
                        "angstrom"
                    )
                    self.assertTrue(np.array_equal(pos, expected_pos))
                if i_conf == 3:
                    expected_pos = convert_unit(
                        np.array([
                            [12.2353220000, 1.3766420000, 10.8698800000],
                            [12.4962705528, 2.2308411983, 11.3355758433],
                            [11.9975151486, 1.5746309898, 10.0054430868],
                        ]),
                        "angstrom"
                    )
                    self.assertTrue(np.array_equal(pos, expected_pos))
                if i_conf == 5:
                    expected_pos = convert_unit(
                        np.array([
                            [12.2353220000, 1.3766420000, 10.8698800000],
                            [12.4958168364, 2.2307249171, 11.3354322532],
                            [11.9975556812, 1.5748088251, 10.0062793864],
                        ]),
                        "angstrom"
                    )
                    self.assertTrue(np.array_equal(pos, expected_pos))

                if i_conf == 6:
                    expected_pos = convert_unit(
                        np.array([
                            [12.2353220000, 1.3766420000, 10.8698800000],
                            [12.4958164689, 2.2307248873, 11.3354322515],
                            [11.9975558616, 1.5748085240, 10.0062792262],
                        ]),
                        "angstrom"
                    )
                    self.assertTrue(np.array_equal(pos, expected_pos))

            i_conf += 1

Lauri Himanen's avatar
Lauri Himanen committed
681
682
683
684
685
686
687

#===============================================================================
class TestMD(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.results = get_results("md/nve", "section_run")
Lauri Himanen's avatar
Lauri Himanen committed
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
        cls.temp = convert_unit(
            np.array([
                300.000000000,
                275.075405378,
                235.091633019,
                202.752506973,
                192.266488819,
                201.629598676,
                218.299664775,
                230.324748558,
                232.691881533,
                226.146979313,
                213.165337396,
            ]),
            "K"
        )
        cls.cons = convert_unit(
            np.array([
                -34.323271136,
                -34.323245645,
                -34.323206964,
                -34.323183380,
                -34.323187747,
                -34.323208962,
                -34.323227533,
                -34.323233583,
                -34.323230715,
                -34.323227013,
                -34.323224123,
            ]),
            "hartree"
        )
        cls.pot = convert_unit(
            np.array([
                -34.330396471,
                -34.329778993,
                -34.328790653,
                -34.327998978,
                -34.327754290,
                -34.327997890,
                -34.328412394,
                -34.328704052,
                -34.328757407,
                -34.328598255,
                -34.328287038,
            ]),
            "hartree"
        )
        cls.kin = convert_unit(
            np.array([
                0.007125335,
                0.006533348,
                0.005583688,
                0.004815598,
                0.004566544,
                0.004788928,
                0.005184860,
                0.005470470,
                0.005526692,
                0.005371243,
                0.005062914,
            ]),
            "hartree"
        )
Lauri Himanen's avatar
Lauri Himanen committed
752
753

    def test_ensemble_type(self):
754
        result = self.results["ensemble_type"]
Lauri Himanen's avatar
Lauri Himanen committed
755
756
        self.assertEqual(result, "NVE")

757
758
759
760
    def test_sampling_method(self):
        result = self.results["sampling_method"]
        self.assertEqual(result, "molecular_dynamics")

Lauri Himanen's avatar
Lauri Himanen committed
761
762
763
764
    def test_number_of_frames_in_sequence(self):
        result = self.results["number_of_frames_in_sequence"]
        self.assertEqual(result, 11)

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    def test_atom_positions(self):
        result = self.results["atom_positions"]
        expected_start = convert_unit(
            np.array([
                [2.2803980000, 9.1465390000, 5.0886960000],
                [1.2517030000, 2.4062610000, 7.7699080000],
                [1.7620190000, 9.8204290000, 5.5284540000],
                [3.0959870000, 9.1070880000, 5.5881860000],
                [0.5541290000, 2.9826340000, 8.0820240000],
                [1.7712570000, 2.9547790000, 7.1821810000],
            ]),
            "angstrom"
        )
        expected_end = convert_unit(
            np.array([
                [2.2916014875, 9.1431763260, 5.0868100688],
                [1.2366834078, 2.4077552776, 7.7630044423],
                [1.6909790671, 9.8235337924, 5.5042564094],
                [3.1130341664, 9.0372111810, 5.6100739746],
                [0.5652070478, 3.0441761067, 8.1734257299],
                [1.8669280879, 2.9877213524, 7.2364955946],
            ]),
            "angstrom"
        )
        self.assertTrue(np.array_equal(result[0,:], expected_start))
        self.assertTrue(np.array_equal(result[-1,:], expected_end))

    def test_frame_sequence_potential_energy(self):
        result = self.results["frame_sequence_potential_energy"]
Lauri Himanen's avatar
Lauri Himanen committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        self.assertTrue(np.array_equal(result, self.pot))

    def test_frame_sequence_kinetic_energy(self):
        result = self.results["frame_sequence_kinetic_energy"]
        self.assertTrue(np.array_equal(result, self.kin))

    def test_frame_sequence_conserved_quantity(self):
        result = self.results["frame_sequence_conserved_quantity"]
        self.assertTrue(np.array_equal(result, self.cons))

    def test_frame_sequence_temperature(self):
        result = self.results["frame_sequence_temperature"]
        self.assertTrue(np.array_equal(result, self.temp))

    def test_frame_sequence_time(self):
        result = self.results["frame_sequence_time"]
810
811
        expected_result = convert_unit(
            np.array([
Lauri Himanen's avatar
Lauri Himanen committed
812
813
814
815
816
817
818
819
820
821
822
                0.000000,
                0.500000,
                1.000000,
                1.500000,
                2.000000,
                2.500000,
                3.000000,
                3.500000,
                4.000000,
                4.500000,
                5.000000,
823
            ]),
Lauri Himanen's avatar
Lauri Himanen committed
824
            "fs"
825
826
827
        )
        self.assertTrue(np.array_equal(result, expected_result))

Lauri Himanen's avatar
Lauri Himanen committed
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
    def test_frame_sequence_potential_energy_stats(self):
        result = self.results["frame_sequence_potential_energy_stats"]
        expected_result = np.array([self.pot.mean(), self.pot.std()])
        self.assertTrue(np.array_equal(result, expected_result))

    def test_frame_sequence_kinetic_energy_stats(self):
        result = self.results["frame_sequence_kinetic_energy_stats"]
        expected_result = np.array([self.kin.mean(), self.kin.std()])
        self.assertTrue(np.array_equal(result, expected_result))

    def test_frame_sequence_conserved_quantity_stats(self):
        result = self.results["frame_sequence_conserved_quantity_stats"]
        expected_result = np.array([self.cons.mean(), self.cons.std()])
        self.assertTrue(np.array_equal(result, expected_result))

    def test_frame_sequence_temperature_stats(self):
        result = self.results["frame_sequence_temperature_stats"]
        expected_result = np.array([self.temp.mean(), self.temp.std()])
        self.assertTrue(np.array_equal(result, expected_result))


#===============================================================================
class TestMDEnsembles(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.pressure = convert_unit(
855
            np.array([
Lauri Himanen's avatar
Lauri Himanen committed
856
857
858
859
860
861
862
863
864
865
866
                -0.192828092558E+04,
                -0.145371071469E+04,
                -0.210098903760E+03,
                0.167260570312E+04,
                0.395562042840E+04,
                0.630374855942E+04,
                0.836906136785E+04,
                0.983216022828E+04,
                0.104711540465E+05,
                0.102444821549E+05,
                0.931695792434E+04,
867
            ]),
Lauri Himanen's avatar
Lauri Himanen committed
868
            "bar"
869
        )
Lauri Himanen's avatar
Lauri Himanen committed
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886

    def test_nvt(self):
        results = get_results("md/nvt", "section_run")
        ensemble = results["ensemble_type"]
        self.assertEqual(ensemble, "NVT")

    def test_npt(self):
        results = get_results("md/npt", "section_run")
        ensemble = results["ensemble_type"]
        self.assertEqual(ensemble, "NPT")

        pressure = results["frame_sequence_pressure"]
        self.assertTrue(np.array_equal(pressure, self.pressure))

        pressure_stats = results["frame_sequence_pressure_stats"]
        expected_pressure_stats = np.array([self.pressure.mean(), self.pressure.std()])
        self.assertTrue(np.array_equal(pressure_stats, expected_pressure_stats))
Lauri Himanen's avatar
Lauri Himanen committed
887
888


889
890
891
892
893
894
#===============================================================================
if __name__ == '__main__':
    logger = logging.getLogger("cp2kparser")
    logger.setLevel(logging.ERROR)

    suites = []
895
896
897
898
899
900
901
902
903
904
905
906
907
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestErrors))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestXCFunctional))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestEnergyForce))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestStressTensorMethods))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestSelfInteractionCorrectionMethod))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestConfigurationPeriodicDimensions))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestSCFConvergence))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestForceFiles))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestPreprocessor))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestGeoOpt))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestGeoOptTrajFormats))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestGeoOptOptimizers))
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestGeoOptTrajectory))
Lauri Himanen's avatar
Lauri Himanen committed
908
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestMD))
Lauri Himanen's avatar
Lauri Himanen committed
909
    suites.append(unittest.TestLoader().loadTestsFromTestCase(TestMDEnsembles))
910
911
    alltests = unittest.TestSuite(suites)
    unittest.TextTestRunner(verbosity=0).run(alltests)