1def test_mixingcalc():
2    """This test checks the basic functionality of the MixingCalculators.
3    The example system is based on the SinglePointCalculator test case.
4    """
5    import numpy as np
6
7    from ase.build import fcc111
8    from ase.calculators.emt import EMT
9    from ase.calculators.mixing import SumCalculator, LinearCombinationCalculator, AverageCalculator, MixedCalculator
10    from ase.constraints import FixAtoms
11
12    # Calculate reference values:
13    atoms = fcc111('Cu', (2, 2, 1), vacuum=10.)
14    atoms[0].x += 0.2
15
16    # First run the test with EMT similarly to the test of the single point calculator.
17    calc = EMT()
18    atoms.calc = calc
19    forces = atoms.get_forces()
20
21    # SumCalculator: Alternative ways to associate a calculator with an atoms object.
22    atoms1 = atoms.copy()
23    calc1 = SumCalculator([EMT(), EMT()])
24    atoms1.calc = calc1
25
26    atoms2 = atoms.copy()
27    SumCalculator(calcs=[EMT(), EMT()], atoms=atoms2)
28
29    # Check the results.
30    assert np.isclose(2 * forces, atoms1.get_forces()).all()
31    assert np.isclose(2 * forces, atoms2.get_forces()).all()
32
33    # testing  step
34    atoms1[0].x += 0.2
35    assert not np.isclose(2 * forces, atoms1.get_forces()).all()
36
37    # Check constraints
38    atoms1.set_constraint(FixAtoms(indices=[atom.index for atom in atoms]))
39    assert np.isclose(0, atoms1.get_forces()).all()
40
41    # AverageCalculator:
42
43    atoms1 = atoms.copy()
44    calc1 = AverageCalculator([EMT(), EMT()])
45    atoms1.calc = calc1
46
47    # LinearCombinationCalculator:
48
49    atoms2 = atoms.copy()
50    LinearCombinationCalculator([EMT(), EMT()], weights=[.5, .5], atoms=atoms2)
51
52    # Check the results (it should be the same because it is tha average of the same values).
53    assert np.isclose(forces, atoms1.get_forces()).all()
54    assert np.isclose(forces, atoms2.get_forces()).all()
55
56    # testing  step
57    atoms1[0].x += 0.2
58    assert not np.isclose(2 * forces, atoms1.get_forces()).all()
59
60    try:
61        calc1 = LinearCombinationCalculator([], [])
62    except ValueError:
63        assert True
64
65    try:
66        calc1 = AverageCalculator([])
67    except ValueError:
68        assert True
69
70    # test  MixedCalculator and energy contributions
71    w1, w2 = 0.78, 0.22
72    atoms1 = atoms.copy()
73    atoms1.calc = EMT()
74    E_tot = atoms1.get_potential_energy()
75
76    calc1 = MixedCalculator(EMT(), EMT(), w1, w2)
77    E1, E2 = calc1.get_energy_contributions(atoms1)
78    assert np.isclose(E1, E_tot)
79    assert np.isclose(E2, E_tot)
80