Coverage for gpaw/test/wannier/test_asewannier.py: 100%

44 statements  

« prev     ^ index     » next       coverage.py v7.7.1, created at 2025-07-19 00:19 +0000

1"""Test of ase wannier using gpaw.""" 

2import numpy as np 

3import pytest 

4from ase.build import molecule 

5from ase.dft.wannier import Wannier 

6 

7from gpaw.mpi import world 

8from gpaw import GPAW 

9 

10pytestmark = pytest.mark.skipif(world.size > 1, 

11 reason='world.size > 1') 

12 

13 

14@pytest.mark.wannier 

15def test_ase_features_asewannier(in_tmp_dir): 

16 calc = GPAW(mode='fd', gpts=(32, 32, 32), nbands=4) 

17 atoms = molecule('H2', calculator=calc) 

18 atoms.center(vacuum=3.) 

19 e = atoms.get_potential_energy() 

20 

21 pos = atoms.positions + np.array([[0, 0, .2339], [0, 0, -.2339]]) 

22 com = atoms.get_center_of_mass() 

23 

24 wan = Wannier(nwannier=2, calc=calc, initialwannier='bloch') 

25 assert wan.get_functional_value() == pytest.approx(2.964, abs=1e-3) 

26 assert np.linalg.norm(wan.get_centers() - [com, com]) == pytest.approx( 

27 0, abs=1e-4) 

28 

29 wan = Wannier(nwannier=2, calc=calc, initialwannier='projectors') 

30 assert wan.get_functional_value() == pytest.approx(3.100, abs=2e-3) 

31 assert np.linalg.norm(wan.get_centers() - pos) == pytest.approx( 

32 0, abs=1e-3) 

33 

34 wan = Wannier(nwannier=2, 

35 calc=calc, 

36 initialwannier=[[0, 0, .5], [1, 0, .5]]) 

37 assert wan.get_functional_value() == pytest.approx(3.100, abs=2e-3) 

38 assert np.linalg.norm(wan.get_centers() - pos) == pytest.approx( 

39 0, abs=1e-3) 

40 

41 wan.localize() 

42 assert wan.get_functional_value() == pytest.approx(3.100, abs=2e-3) 

43 assert np.linalg.norm(wan.get_centers() - pos) == pytest.approx( 

44 0, abs=1e-3) 

45 assert np.linalg.norm(wan.get_radii() - 1.2393) == pytest.approx( 

46 0, abs=2e-3) 

47 eig = np.sort(np.linalg.eigvals(wan.get_hamiltonian(k=0).real)) 

48 assert np.linalg.norm(eig - calc.get_eigenvalues()[:2]) == pytest.approx( 

49 0, abs=1e-4) 

50 

51 wan.write_cube(0, 'H2.cube') 

52 

53 energy_tolerance = 0.002 

54 assert e == pytest.approx(-6.652, abs=energy_tolerance) 

55 

56 

57@pytest.mark.flaky 

58@pytest.mark.wannier 

59def test_wannier_pw(in_tmp_dir, gpw_files, needs_ase_master): 

60 calc = GPAW(gpw_files['fancy_si_pw_nosym']) 

61 wan = Wannier(nwannier=4, calc=calc, fixedstates=4, 

62 initialwannier='orbitals') 

63 wan.localize() 

64 wan.translate_all_to_cell(cell=(0, 0, 0)) 

65 assert wan.get_functional_value() == pytest.approx(9.853, abs=2e-3) 

66 

67 # test that one of the Wannier functions is localized between the 

68 # two Si atoms in the unit cell, as it should be 

69 center = calc.atoms.positions.mean(axis=0) 

70 min_dist_to_center = np.min(np.linalg.norm(wan.get_centers() 

71 - center, axis=1)) 

72 assert min_dist_to_center < 1e-3