test_ignite.py 1.95 KB
Newer Older
1
2
3
4
5
6
import sys

if sys.version_info.major >= 3:
    import os
    import unittest
    import torch
Gao, Xiang's avatar
Gao, Xiang committed
7
    from ignite.engine import create_supervised_trainer, \
8
        create_supervised_evaluator, Events
9
10
11
12
    import torchani
    import torchani.data

    path = os.path.dirname(os.path.realpath(__file__))
13
    path = os.path.join(path, '../dataset/ani_gdb_s01.h5')
14
    chunksize = 4
15
    threshold = 1e-5
16
17
18
19

    class TestIgnite(unittest.TestCase):

        def testIgnite(self):
20
21
            shift_energy = torchani.EnergyShifter()
            ds = torchani.data.ANIDataset(
22
                path, chunksize, transform=[shift_energy.dataset_subtract_sae])
23
24
            ds = torch.utils.data.Subset(ds, [0])
            loader = torchani.data.dataloader(ds, 1)
25
26
            aev_computer = torchani.SortedAEV()
            prepare = torchani.PrepareInput(aev_computer.species)
27
            nnp = torchani.models.NeuroChemNNP(aev_computer.species)
28
29

            class Flatten(torch.nn.Module):
30
31
                def forward(self, x):
                    return x.flatten()
32

33
34
            model = torch.nn.Sequential(prepare, aev_computer, nnp, Flatten())
            batch_nnp = torchani.models.BatchModel(model)
35
            container = torchani.ignite.Container({'energies': batch_nnp})
36
            optimizer = torch.optim.Adam(container.parameters())
Gao, Xiang's avatar
Gao, Xiang committed
37
38
            trainer = create_supervised_trainer(
                container, optimizer, torchani.ignite.energy_mse_loss)
Gao, Xiang's avatar
Gao, Xiang committed
39
            evaluator = create_supervised_evaluator(container, metrics={
Gao, Xiang's avatar
Gao, Xiang committed
40
                'RMSE': torchani.ignite.energy_rmse_metric
Gao, Xiang's avatar
Gao, Xiang committed
41
            })
42
43
44
45
46
47
48
49
50

            @trainer.on(Events.COMPLETED)
            def completes(trainer):
                evaluator.run(loader)
                metrics = evaluator.state.metrics
                self.assertLess(metrics['RMSE'], threshold)
                self.assertLess(trainer.state.output, threshold)

            trainer.run(loader, max_epochs=1000)
51
52
53

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