Coverage for gpaw/test/fileio/test_restart_density.py: 97%

37 statements  

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

1import numpy as np 

2from gpaw import GPAW, restart 

3import pytest 

4from ase.io.ulm import ulmopen 

5 

6 

7def get_restart_test_values(calc, skip_forces): 

8 # XXX the forces must be evaluated first because a force evaluation 

9 # somehow affects (changes) both the energy and the wf when restarting 

10 # from a gpw file. An issue was created (#1051) documenting this unexpected 

11 # and rather bizarre behavior. 

12 

13 atoms = calc.get_atoms() 

14 if skip_forces: 

15 f = np.zeros((len(atoms), 3)) 

16 else: 

17 f = atoms.get_forces() 

18 e = atoms.get_potential_energy() 

19 m = atoms.get_magnetic_moments() 

20 

21 eig0 = calc.get_eigenvalues(spin=0) 

22 eig1 = calc.get_eigenvalues(spin=1) 

23 

24 return e, f, m, eig0, eig1 

25 

26 

27def test_fileio_restart_density(in_tmp_dir, gpw_files): 

28 calc = GPAW(gpw_files['na3_fd_density_restart']) 

29 

30 # We don't care about forces working for new GPAW reading old gpw-file 

31 skip_forces = (not calc.old and 

32 ulmopen(gpw_files['na3_fd_density_restart']).version < 4) 

33 e0, f0, m0, eig00, eig01 = get_restart_test_values(calc, skip_forces) 

34 

35 # Write the restart file 

36 calc.write('tmp.gpw') 

37 

38 # Try restarting from all the files 

39 atoms, calc = restart('tmp.gpw') 

40 e1, f1, m1, eig10, eig11 = get_restart_test_values(calc, skip_forces) 

41 

42 print(e0, e1) 

43 assert e0 == pytest.approx(e1, abs=2e-3) 

44 print(f0, f1) 

45 for ff0, ff1 in zip(f0, f1): 

46 err = np.linalg.norm(ff0 - ff1) 

47 # for forces, we use larger tolerance 

48 assert err == pytest.approx(0.0, abs=4e-2) 

49 print(m0, m1) 

50 for mm0, mm1 in zip(m0, m1): 

51 assert mm0 == pytest.approx(mm1, abs=2e-3) 

52 print('A', eig00, eig10) 

53 for eig0, eig1 in zip(eig00, eig10): 

54 assert eig0 == pytest.approx(eig1, abs=5e-3) 

55 print('B', eig01, eig11) 

56 for eig0, eig1 in zip(eig01, eig11): 

57 assert eig0 == pytest.approx(eig1, abs=2e-2) 

58 

59 # Check that after restart, everything is writable 

60 calc.write('tmp2.gpw')