test_forces.py 1.42 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
import torch
import torchani
import unittest
import os
import pickle

path = os.path.dirname(os.path.realpath(__file__))
N = 97


class TestForce(unittest.TestCase):

13
    def setUp(self):
14
        self.tolerance = 1e-5
15
16
        aev_computer = torchani.SortedAEV()
        prepare = torchani.PrepareInput(aev_computer.species)
17
18
        nnp = torchani.models.NeuroChemNNP(aev_computer.species)
        self.model = torch.nn.Sequential(prepare, aev_computer, nnp)
19
20

    def _test_molecule(self, coordinates, species, forces):
Gao, Xiang's avatar
Gao, Xiang committed
21
22
23
24
25
26
27
        # generate a random permute
        atoms = len(species)
        randperm = torch.randperm(atoms)
        coordinates = coordinates.index_select(1, randperm)
        forces = forces.index_select(1, randperm)
        species = [species[i] for i in randperm.tolist()]

Gao, Xiang's avatar
Gao, Xiang committed
28
        coordinates = torch.tensor(coordinates, requires_grad=True)
29
        _, energies = self.model((species, coordinates))
Gao, Xiang's avatar
Gao, Xiang committed
30
        derivative = torch.autograd.grad(energies.sum(), coordinates)[0]
31
32
33
34
35
36
37
38
39
40
41
42
43
        max_diff = (forces + derivative).abs().max().item()
        self.assertLess(max_diff, self.tolerance)

    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, _, _, _, forces = pickle.load(f)
                self._test_molecule(coordinates, species, forces)


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