test_ensemble.py 1.57 KB
Newer Older
1
2
3
4
5
6
7
import unittest
import pickle
import os
import torch
import torchani

path = os.path.dirname(os.path.realpath(__file__))
8
N = 10
9
10
11
12
13
14
15
16
17


class TestEnsemble(unittest.TestCase):

    def setUp(self):
        self.tol = 1e-5
        self.conformations = 20

    def _test_molecule(self, coordinates, species):
Gao, Xiang's avatar
Gao, Xiang committed
18
        coordinates = torch.tensor(coordinates, requires_grad=True)
19
        n = torchani.buildin_ensemble
20
21
        prefix = torchani.buildin_model_prefix
        aev = torchani.SortedAEV(device=torch.device('cpu'))
Gao, Xiang's avatar
Gao, Xiang committed
22
        ensemble = torchani.models.NeuroChemNNP(aev, ensemble=True)
23
        models = [torchani.models.
Gao, Xiang's avatar
Gao, Xiang committed
24
                  NeuroChemNNP(aev, ensemble=False,
25
26
                               from_=prefix + '{}/networks/'.format(i))
                  for i in range(n)]
27

Gao, Xiang's avatar
Gao, Xiang committed
28
29
30
        energy1 = ensemble(coordinates, species)
        force1 = torch.autograd.grad(energy1.sum(), coordinates)[0]
        energy2 = [m(coordinates, species) for m in models]
31
        energy2 = sum(energy2) / n
Gao, Xiang's avatar
Gao, Xiang committed
32
        force2 = torch.autograd.grad(energy2.sum(), coordinates)[0]
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
        energy_diff = (energy1 - energy2).abs().max().item()
        force_diff = (force1 - force2).abs().max().item()
        self.assertLess(energy_diff, self.tol)
        self.assertLess(force_diff, self.tol)

    def testGDB(self):
        for i in range(N):
            datafile = os.path.join(path, 'test_data/{}'.format(i))
            with open(datafile, 'rb') as f:
                coordinates, species, _, _, _, _ = pickle.load(f)
                self._test_molecule(coordinates, species)


if __name__ == '__main__':
    unittest.main()