Coverage for gpaw/test/ext_potential/test_b_field.py: 97%

30 statements  

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

1import pytest 

2from ase import Atoms 

3 

4from gpaw import GPAW 

5from gpaw.bfield import BField 

6 

7 

8@pytest.mark.old_gpaw_only # use extension=[BField(...)] 

9@pytest.mark.serial 

10def test_b_field(gpaw_new): 

11 """Hydrogen atom in a magnetic field.""" 

12 L = 2.0 

13 atom = Atoms('H', magmoms=[1], cell=[L, L, L], pbc=True) 

14 atom.calc = GPAW(mode='pw') 

15 E1 = atom.get_potential_energy() 

16 a1, b1 = (atom.calc.get_eigenvalues(spin=s)[0] for s in [0, 1]) 

17 

18 B = 0.1 

19 

20 # Collinear: 

21 atom.calc = GPAW(mode='pw', 

22 external=BField((0, 0, B))) 

23 E2 = atom.get_potential_energy() 

24 a2, b2 = (atom.calc.get_eigenvalues(spin=s)[0] for s in [0, 1]) 

25 

26 assert E2 - E1 == pytest.approx(-B, abs=1e-6) 

27 assert a2 - a1 == pytest.approx(-B, abs=1e-6) 

28 assert b2 - b1 == pytest.approx(B, abs=1e-6) 

29 

30 # Non-collinear: 

31 params = ({'magmoms': [(0.5, 0.5, 0)]} 

32 if gpaw_new else 

33 {'experimental': {'magmoms': [(0.5, 0.5, 0)]}}) 

34 atom.calc = GPAW(mode='pw', 

35 symmetry='off', 

36 **params, 

37 external=BField([B, 0, 0])) 

38 E3 = atom.get_potential_energy() 

39 a3, b3 = atom.calc.get_eigenvalues() 

40 

41 assert E3 - E1 == pytest.approx(-B, abs=2e-5) 

42 assert a3 - a1 == pytest.approx(-B, abs=3e-5) 

43 

44 if gpaw_new: 

45 totmom_v, magmom_av = ( 

46 atom.calc.dft.density.calculate_magnetic_moments()) 

47 else: 

48 totmom_v, magmom_av = atom.calc.density.estimate_magnetic_moments() 

49 assert totmom_v == pytest.approx([1, 0, 0], abs=1e-5) 

50 assert magmom_av[0] == pytest.approx([0.176, 0, 0], abs=1e-3)