forked from JuliaMolSim/DFTK.jl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stress-forwarddiff-generic.jl
51 lines (42 loc) · 1.61 KB
/
stress-forwarddiff-generic.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Hellmann-Feynman stress
# via ForwardDiff & generic arithmetic (FourierTransforms.jl)
# (disregarding performance)
using DFTK
# for generic FourierTransforms.jl (TODO replace by FFTW later)
using DoubleFloats
using GenericLinearAlgebra
function make_basis(a)
lattice = a / 2 * [[0 1 1.];
[1 0 1.];
[1 1 0.]]
Si = ElementPsp(:Si, psp=load_psp("hgh/lda/Si-q4"))
atoms = [Si => [ones(3)/8, -ones(3)/8]]
terms = [
Kinetic(),
AtomicLocal(),
# AtomicNonlocal(), # gives NaN ForwardDiff
Ewald(),
PspCorrection(),
Entropy()
]
model = Model(lattice; atoms=atoms, terms=terms, symmetries=false)
kgrid = [1, 1, 1] # k-point grid (Regular Monkhorst-Pack grid)
Ecut = 15 # kinetic energy cutoff in Hartree
PlaneWaveBasis(model, Ecut; kgrid=kgrid, fft_size=[32, 32, 32])
end
a = 10.26
basis = make_basis(a)
# scfres = self_consistent_field(basis, tol=1e-8) # LoadError: Unable to find non-fractional occupations that have the correct number of electrons. You should add a temperature.
# try a high tolerance for debugging
scfres = self_consistent_field(basis, tol=1e-4)
function compute_energy(scfres_ref, a)
basis = make_basis(a)
energies, H = energy_hamiltonian(basis, scfres_ref.ψ, scfres_ref.occupation; ρ=scfres_ref.ρ)
energies.total
end
compute_energy(a) = compute_energy(scfres, a)
compute_energy(10.26)
import FiniteDiff
FiniteDiff.finite_difference_derivative(compute_energy, 10.26) # -11.115631567324957
using ForwardDiff
ForwardDiff.derivative(compute_energy, 10.26) # -11.115631566795612