Beispiel #1
0
def test():
    """Gaussian/Neural numeric-analytic consistency."""
    images = generate_data()
    regressor = Regressor(optimizer='BFGS')

    _G = make_symmetry_functions(type='G2',
                                 etas=[0.05, 5.],
                                 elements=['Cu', 'Pt'])
    _G += make_symmetry_functions(type='G4',
                                  etas=[0.005],
                                  zetas=[1., 4.],
                                  gammas=[1.],
                                  elements=['Cu', 'Pt'])
    Gs = {'Cu': _G, 'Pt': _G}
    calc = Amp(descriptor=Gaussian(Gs=Gs),
               model=NeuralNetwork(
                   hiddenlayers=(2, 1),
                   regressor=regressor,
                   randomseed=42,
               ),
               cores=1)

    step = 0
    for d in [None, 0.00001]:
        for fortran in [True, False]:
            for cores in [1, 2]:
                step += 1
                label = \
                    'numeric_analytic_test/analytic-%s-%i' % (fortran, cores) \
                    if d is None \
                    else 'numeric_analytic_test/numeric-%s-%i' \
                    % (fortran, cores)
                print(label)

                loss = LossFunction(convergence={
                    'energy_rmse': 10**10,
                    'force_rmse': 10**10
                },
                                    d=d)
                calc.set_label(label)
                calc.dblabel = 'numeric_analytic_test/analytic-True-1'
                calc.model.lossfunction = loss
                calc.descriptor.fortran = fortran
                calc.model.fortran = fortran
                calc.cores = cores

                calc.train(images=images, )

                if step == 1:
                    ref_energies = []
                    ref_forces = []
                    for image in images:
                        ref_energies += [calc.get_potential_energy(image)]
                        ref_forces += [calc.get_forces(image)]
                        ref_dloss_dparameters = \
                            calc.model.lossfunction.dloss_dparameters
                else:
                    energies = []
                    forces = []
                    for image in images:
                        energies += [calc.get_potential_energy(image)]
                        forces += [calc.get_forces(image)]
                        dloss_dparameters = \
                            calc.model.lossfunction.dloss_dparameters

                    for image_no in range(2):

                        diff = abs(energies[image_no] - ref_energies[image_no])
                        assert (diff < 10.**(-13.)), \
                            'The calculated value of energy of image %i is ' \
                            'wrong!' % (image_no + 1)

                        for atom_no in range(len(images[0])):
                            for i in range(3):
                                diff = abs(forces[image_no][atom_no][i] -
                                           ref_forces[image_no][atom_no][i])
                                assert (diff < 10.**(-10.)), \
                                    'The calculated %i force of atom %i of ' \
                                    'image %i is wrong!' \
                                    % (i, atom_no, image_no + 1)
                        # Checks analytical and numerical dloss_dparameters
                        for _ in range(len(ref_dloss_dparameters)):
                            diff = abs(dloss_dparameters[_] -
                                       ref_dloss_dparameters[_])
                            assert(diff < 10 ** (-10.)), \
                                'The calculated value of loss function ' \
                                'derivative is wrong!'
    # Checks analytical and numerical forces
    forces = []
    for image in images:
        image.set_calculator(calc)
        forces += [calc.calculate_numerical_forces(image, d=d)]
    for atom_no in range(len(images[0])):
        for i in range(3):
            diff = abs(forces[image_no][atom_no][i] -
                       ref_forces[image_no][atom_no][i])
            print('{:3d} {:1d} {:7.1e}'.format(atom_no, i, diff))
            assert (diff < 10.**(-6.)), \
                'The calculated %i force of atom %i of ' \
                'image %i is wrong! (Diff = %f)' \
                % (i, atom_no, image_no + 1, diff)
def test():
    images = generate_data(2)
    regressor = Regressor(optimizer='BFGS')

    calc = Amp(descriptor=Gaussian(),
               model=NeuralNetwork(hiddenlayers=(3, 3),
                                   regressor=regressor,),
               cores=1)

    step = 0
    for d in [None, 0.00001]:
        for fortran in [True, False]:
            for cores in [1, 2]:
                step += 1
                label = \
                    'numeric_analytic_test/analytic-%s-%i' % (fortran, cores) \
                    if d is None \
                    else 'numeric_analytic_test/numeric-%s-%i' \
                    % (fortran, cores)
                print(label)

                loss = LossFunction(convergence={'energy_rmse': 10 ** 10,
                                                 'force_rmse': 10 ** 10},
                                    d=d)
                calc.set_label(label)
                calc.dblabel = 'numeric_analytic_test/analytic-True-1'
                calc.model.lossfunction = loss
                calc.descriptor.fortran = fortran
                calc.model.fortran = fortran
                calc.cores = cores

                calc.train(images=images,)

                if step == 1:
                    ref_energies = []
                    ref_forces = []
                    for image in images:
                        ref_energies += [calc.get_potential_energy(image)]
                        ref_forces += [calc.get_forces(image)]
                        ref_dloss_dparameters = \
                            calc.model.lossfunction.dloss_dparameters
                else:
                    energies = []
                    forces = []
                    for image in images:
                        energies += [calc.get_potential_energy(image)]
                        forces += [calc.get_forces(image)]
                        dloss_dparameters = \
                            calc.model.lossfunction.dloss_dparameters

                    for image_no in range(2):

                        diff = abs(energies[image_no] - ref_energies[image_no])
                        assert (diff < 10.**(-13.)), \
                            'The calculated value of energy of image %i is ' \
                            'wrong!' % (image_no + 1)

                        for atom_no in range(6):
                            for i in range(3):
                                diff = abs(forces[image_no][atom_no][i] -
                                           ref_forces[image_no][atom_no][i])
                                assert (diff < 10.**(-10.)), \
                                    'The calculated %i force of atom %i of ' \
                                    'image %i is wrong!' \
                                    % (i, atom_no, image_no + 1)
                        # Checks analytical and numerical dloss_dparameters
                        for _ in range(len(ref_dloss_dparameters)):
                            diff = abs(dloss_dparameters[_] -
                                       ref_dloss_dparameters[_])
                            assert(diff < 10 ** (-10.)), \
                                'The calculated value of loss function ' \
                                'derivative is wrong!'
    # Checks analytical and numerical forces
    forces = []
    for image in images:
        image.set_calculator(calc)
        forces += [calc.calculate_numerical_forces(image, d=d)]
    for atom_no in range(6):
        for i in range(3):
            diff = abs(forces[image_no][atom_no][i] -
                       ref_forces[image_no][atom_no][i])
            assert (diff < 10.**(-9.)), \
                'The calculated %i force of atom %i of ' \
                'image %i is wrong!' % (i, atom_no, image_no + 1)
Beispiel #3
0
def test():

    images = make_training_images()

    for descriptor in [None, Gaussian()]:
        for global_search in [
                None, SimulatedAnnealing(temperature=10, steps=5)
        ]:
            for data_format in ['json', 'db']:
                for save_memory in [
                        False,
                ]:
                    for fortran in [False, True]:
                        for cores in range(1, 4):

                            print(descriptor, global_search, data_format,
                                  save_memory, fortran, cores)

                            pwd = os.getcwd()
                            testdir = 'read_write_test'
                            os.mkdir(testdir)
                            os.chdir(testdir)

                            regression = NeuralNetwork(hiddenlayers=(
                                5,
                                5,
                            ))

                            calc = Amp(
                                label='calc',
                                descriptor=descriptor,
                                regression=regression,
                                fortran=fortran,
                            )

                            # Should start with new variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                cores=cores,
                            )

                            # Test that we cannot overwrite. (Strange code
                            # here because we *want* it to raise an
                            # exception...)
                            try:
                                calc.train(
                                    images,
                                    energy_goal=0.01,
                                    force_goal=10.,
                                    global_search=global_search,
                                    extend_variables=True,
                                    data_format=data_format,
                                    save_memory=save_memory,
                                    cores=cores,
                                )
                            except IOError:
                                pass
                            else:
                                raise RuntimeError(
                                    'Code allowed to overwrite!')

                            # Test that we can manually overwrite.
                            # Should start with existing variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                overwrite=True,
                                cores=cores,
                            )

                            label = 'testdir'
                            if not os.path.exists(label):
                                os.mkdir(label)

                            # New directory calculator.
                            calc = Amp(
                                label='testdir/calc',
                                descriptor=descriptor,
                                regression=regression,
                                fortran=fortran,
                            )

                            # Should start with new variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                cores=cores,
                            )

                            # Open existing, save under new name.
                            calc = Amp(
                                load='calc',
                                label='calc2',
                                descriptor=descriptor,
                                regression=regression,
                                fortran=fortran,
                            )

                            # Should start with existing variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                cores=cores,
                            )

                            label = 'calc_new'
                            if not os.path.exists(label):
                                os.mkdir(label)

                            # Change label and re-train
                            calc.set_label('calc_new/calc')
                            # Should start with existing variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                cores=cores,
                            )

                            # Open existing without specifying new name.
                            calc = Amp(
                                load='calc',
                                descriptor=descriptor,
                                regression=regression,
                                fortran=fortran,
                            )

                            # Should start with existing variables
                            calc.train(
                                images,
                                energy_goal=0.01,
                                force_goal=10.,
                                global_search=global_search,
                                extend_variables=True,
                                data_format=data_format,
                                save_memory=save_memory,
                                cores=cores,
                            )

                            os.chdir(pwd)
                            shutil.rmtree(testdir, ignore_errors=True)
                            del calc, regression