Coverage for gpaw/test/directopt/test_grad_numerically_lcao.py: 100%

28 statements  

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

1import pytest 

2import numpy as np 

3 

4from gpaw import GPAW 

5from gpaw.directmin.derivatives import Derivatives 

6 

7 

8@pytest.mark.do 

9def test_gradient_numerically_lcao(in_tmp_dir, gpw_files): 

10 """ 

11 test exponential transformation 

12 direct minimization method for KS-DFT in LCAO 

13 :param in_tmp_dir: 

14 :return: 

15 """ 

16 

17 calc = GPAW(gpw_files['h3_do_num_lcao']) 

18 atoms = calc.atoms 

19 atoms.calc = calc 

20 

21 params = [{'name': 'etdm-lcao', 

22 'representation': 'full', 

23 'matrix_exp': 'egdecomp'}, 

24 {'name': 'etdm-lcao', 

25 'representation': 'full', 

26 'matrix_exp': 'pade-approx'}, 

27 {'name': 'etdm-lcao', 

28 'representation': 'sparse', 

29 'matrix_exp': 'egdecomp'}, 

30 {'name': 'etdm-lcao', 

31 'representation': 'sparse', 

32 'matrix_exp': 'pade-approx'}, 

33 {'name': 'etdm-lcao', 

34 'representation': 'u-invar', 

35 'matrix_exp': 'egdecomp'}, 

36 {'name': 'etdm-lcao', 

37 'representation': 'u-invar', 

38 'matrix_exp': 'egdecomp-u-invar'}] 

39 

40 for eigsolver in params: 

41 print('IN PROGRESS: ', eigsolver) 

42 

43 calc = calc.new(eigensolver=eigsolver) 

44 atoms.calc = calc 

45 if eigsolver['representation'] == 'u-invar': 

46 with pytest.warns(UserWarning, 

47 match="Use representation == 'sparse'"): 

48 atoms.get_potential_energy() 

49 else: 

50 atoms.get_potential_energy() 

51 ham = calc.hamiltonian 

52 wfs = calc.wfs 

53 dens = calc.density 

54 

55 # Do we get consistent results regardless of randomization? 

56 rngs = [False, 

57 np.random.default_rng(123456)] 

58 num_ders = [Derivatives(wfs.eigensolver, 

59 wfs, 

60 random_amat=rng, 

61 update_c_ref=True) 

62 for rng in rngs] 

63 

64 analytical_results = [ 

65 der.get_analytical_derivatives( 

66 wfs.eigensolver, ham, wfs, dens)[0] 

67 for der in num_ders] 

68 numerical_results = [ 

69 der.get_numerical_derivatives( 

70 wfs.eigensolver, ham, wfs, dens)[0] 

71 for der in num_ders] 

72 for x, *ys in zip(*analytical_results, *numerical_results): 

73 assert np.array(ys).real == pytest.approx(x.real, abs=1.0e-2) 

74 assert np.array(ys).imag == pytest.approx(x.imag, abs=1.0e-2)