-
Notifications
You must be signed in to change notification settings - Fork 51
/
sparse_calc.jl
412 lines (365 loc) · 16.9 KB
/
sparse_calc.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using DelimitedFiles, LinearAlgebra, JSON
using HDF5
using ArgParse
using SparseArrays
using Pardiso, Arpack, LinearMaps
using JLD
# BLAS.set_num_threads(1)
const ev2Hartree = 0.036749324533634074
const Bohr2Ang = 0.529177249
const default_dtype = Complex{Float64}
function parse_commandline()
s = ArgParseSettings()
@add_arg_table! s begin
"--input_dir", "-i"
help = "path of rlat.dat, orbital_types.dat, site_positions.dat, hamiltonians_pred.h5, and overlaps.h5"
arg_type = String
default = "./"
"--output_dir", "-o"
help = "path of output openmx.Band"
arg_type = String
default = "./"
"--config"
help = "config file in the format of JSON"
arg_type = String
"--ill_project"
help = "projects out the eigenvectors of the overlap matrix that correspond to eigenvalues smaller than ill_threshold"
arg_type = Bool
default = true
"--ill_threshold"
help = "threshold for ill_project"
arg_type = Float64
default = 5e-4
end
return parse_args(s)
end
function _create_dict_h5(filename::String)
fid = h5open(filename, "r")
T = eltype(fid[keys(fid)[1]])
d_out = Dict{Array{Int64,1}, Array{T, 2}}()
for key in keys(fid)
data = read(fid[key])
nk = map(x -> parse(Int64, convert(String, x)), split(key[2 : length(key) - 1], ','))
d_out[nk] = permutedims(data)
end
close(fid)
return d_out
end
# The function construct_linear_map below is come from https://discourse.julialang.org/t/smallest-magnitude-eigenvalues-of-the-generalized-eigenvalue-equation-for-a-large-sparse-matrix/75485/11
function construct_linear_map(H, S)
ps = MKLPardisoSolver()
set_matrixtype!(ps, Pardiso.COMPLEX_HERM_INDEF)
pardisoinit(ps)
fix_iparm!(ps, :N)
H_pardiso = get_matrix(ps, H, :N)
b = rand(ComplexF64, size(H, 1))
set_phase!(ps, Pardiso.ANALYSIS)
pardiso(ps, H_pardiso, b)
set_phase!(ps, Pardiso.NUM_FACT)
pardiso(ps, H_pardiso, b)
return (
LinearMap{ComplexF64}(
(y, x) -> begin
set_phase!(ps, Pardiso.SOLVE_ITERATIVE_REFINE)
pardiso(ps, y, H_pardiso, S * x)
end,
size(H, 1);
ismutating=true
),
ps
)
end
function genlist(x)
return collect(range(x[1], stop = x[2], length = Int64(x[3])))
end
function k_data2num_ks(kdata::AbstractString)
return parse(Int64,split(kdata)[1])
end
function k_data2kpath(kdata::AbstractString)
return map(x->parse(Float64,x), split(kdata)[2:7])
end
function std_out_array(a::AbstractArray)
return string(map(x->string(x," "),a)...)
end
function constructmeshkpts(nkmesh::Vector{Int64}; offset::Vector{Float64}=[0.0, 0.0, 0.0],
k1::Vector{Float64}=[0.0, 0.0, 0.0], k2::Vector{Float64}=[1.0, 1.0, 1.0])
length(nkmesh) == 3 || throw(ArgumentError("nkmesh in wrong size."))
nkpts = prod(nkmesh)
kpts = zeros(3, nkpts)
ik = 1
for ikx in 1:nkmesh[1], iky in 1:nkmesh[2], ikz in 1:nkmesh[3]
kpts[:, ik] = [
(ikx-1)/nkmesh[1]*(k2[1]-k1[1])+k1[1],
(iky-1)/nkmesh[2]*(k2[2]-k1[2])+k1[2],
(ikz-1)/nkmesh[3]*(k2[3]-k1[3])+k1[3]
]
ik += 1
end
return kpts.+offset
end
function main()
parsed_args = parse_commandline()
println(parsed_args["config"])
config = JSON.parsefile(parsed_args["config"])
calc_job = config["calc_job"]
ill_project = parsed_args["ill_project"]
ill_threshold = parsed_args["ill_threshold"]
if isfile(joinpath(parsed_args["input_dir"],"info.json"))
spinful = JSON.parsefile(joinpath(parsed_args["input_dir"],"info.json"))["isspinful"]
else
spinful = false
end
site_positions = readdlm(joinpath(parsed_args["input_dir"], "site_positions.dat"))
nsites = size(site_positions, 2)
orbital_types_f = open(joinpath(parsed_args["input_dir"], "orbital_types.dat"), "r")
site_norbits = zeros(nsites)
orbital_types = Vector{Vector{Int64}}()
for index_site = 1:nsites
orbital_type = parse.(Int64, split(readline(orbital_types_f)))
push!(orbital_types, orbital_type)
end
site_norbits = (x->sum(x .* 2 .+ 1)).(orbital_types) * (1 + spinful)
norbits = sum(site_norbits)
site_norbits_cumsum = cumsum(site_norbits)
rlat = readdlm(joinpath(parsed_args["input_dir"], "rlat.dat"))
if isfile(joinpath(parsed_args["input_dir"], "sparse_matrix.jld"))
@info string("read sparse matrix from ", parsed_args["input_dir"], "/sparse_matrix.jld")
H_R = load(joinpath(parsed_args["input_dir"], "sparse_matrix.jld"), "H_R")
S_R = load(joinpath(parsed_args["input_dir"], "sparse_matrix.jld"), "S_R")
else
@info "read h5"
begin_time = time()
hamiltonians_pred = _create_dict_h5(joinpath(parsed_args["input_dir"], "hamiltonians_pred.h5"))
overlaps = _create_dict_h5(joinpath(parsed_args["input_dir"], "overlaps.h5"))
println("Time for reading h5: ", time() - begin_time, "s")
I_R = Dict{Vector{Int64}, Vector{Int64}}()
J_R = Dict{Vector{Int64}, Vector{Int64}}()
H_V_R = Dict{Vector{Int64}, Vector{default_dtype}}()
S_V_R = Dict{Vector{Int64}, Vector{default_dtype}}()
@info "construct sparse matrix in the format of COO"
begin_time = time()
for key in collect(keys(hamiltonians_pred))
hamiltonian_pred = hamiltonians_pred[key]
if (key ∈ keys(overlaps))
overlap = overlaps[key]
if spinful
overlap = vcat(hcat(overlap,zeros(size(overlap))),hcat(zeros(size(overlap)),overlap)) # the readout overlap matrix only contains the upper-left block # TODO maybe drop the zeros?
end
else
# continue
overlap = zero(hamiltonian_pred)
end
R = key[1:3]; atom_i=key[4]; atom_j=key[5]
@assert (site_norbits[atom_i], site_norbits[atom_j]) == size(hamiltonian_pred)
@assert (site_norbits[atom_i], site_norbits[atom_j]) == size(overlap)
if !(R ∈ keys(I_R))
I_R[R] = Vector{Int64}()
J_R[R] = Vector{Int64}()
H_V_R[R] = Vector{default_dtype}()
S_V_R[R] = Vector{default_dtype}()
end
for block_matrix_i in 1:site_norbits[atom_i]
for block_matrix_j in 1:site_norbits[atom_j]
coo_i = site_norbits_cumsum[atom_i] - site_norbits[atom_i] + block_matrix_i
coo_j = site_norbits_cumsum[atom_j] - site_norbits[atom_j] + block_matrix_j
push!(I_R[R], coo_i)
push!(J_R[R], coo_j)
push!(H_V_R[R], hamiltonian_pred[block_matrix_i, block_matrix_j])
push!(S_V_R[R], overlap[block_matrix_i, block_matrix_j])
end
end
end
println("Time for constructing sparse matrix in the format of COO: ", time() - begin_time, "s")
@info "convert sparse matrix to the format of CSC"
begin_time = time()
H_R = Dict{Vector{Int64}, SparseMatrixCSC{default_dtype, Int64}}()
S_R = Dict{Vector{Int64}, SparseMatrixCSC{default_dtype, Int64}}()
for R in keys(I_R)
H_R[R] = sparse(I_R[R], J_R[R], H_V_R[R], norbits, norbits)
S_R[R] = sparse(I_R[R], J_R[R], S_V_R[R], norbits, norbits)
end
println("Time for converting to the format of CSC: ", time() - begin_time, "s")
save(joinpath(parsed_args["input_dir"], "sparse_matrix.jld"), "H_R", H_R, "S_R", S_R)
end
if calc_job == "band"
which_k = config["which_k"] # which k point to calculate, start counting from 1, 0 for all k points
fermi_level = config["fermi_level"]
max_iter = config["max_iter"]
num_band = config["num_band"]
k_data = config["k_data"]
@info "calculate bands"
num_ks = k_data2num_ks.(k_data)
kpaths = k_data2kpath.(k_data)
egvals = zeros(Float64, num_band, sum(num_ks)[1])
begin_time = time()
idx_k = 1
for i = 1:size(kpaths, 1)
kpath = kpaths[i]
pnkpts = num_ks[i]
kxs = LinRange(kpath[1], kpath[4], pnkpts)
kys = LinRange(kpath[2], kpath[5], pnkpts)
kzs = LinRange(kpath[3], kpath[6], pnkpts)
for (kx, ky, kz) in zip(kxs, kys, kzs)
if which_k == 0 || which_k == idx_k
H_k = spzeros(default_dtype, norbits, norbits)
S_k = spzeros(default_dtype, norbits, norbits)
for R in keys(H_R)
H_k += H_R[R] * exp(im*2π*([kx, ky, kz]⋅R))
S_k += S_R[R] * exp(im*2π*([kx, ky, kz]⋅R))
end
S_k = (S_k + S_k') / 2
H_k = (H_k + H_k') / 2
if ill_project
lm, ps = construct_linear_map(Hermitian(H_k) - (fermi_level) * Hermitian(S_k), Hermitian(S_k))
println("Time for No.$idx_k matrix factorization: ", time() - begin_time, "s")
egval_sub_inv, egvec_sub = eigs(lm, nev=num_band, which=:LM, ritzvec=true, maxiter=max_iter)
set_phase!(ps, Pardiso.RELEASE_ALL)
pardiso(ps)
egval_sub = real(1 ./ egval_sub_inv) .+ (fermi_level)
# orthogonalize the eigenvectors
egvec_sub_qr = qr(egvec_sub)
egvec_sub = convert(Matrix{default_dtype}, egvec_sub_qr.Q)
S_k_sub = egvec_sub' * S_k * egvec_sub
(egval_S, egvec_S) = eigen(Hermitian(S_k_sub))
# egvec_S: shape (num_basis, num_bands)
project_index = abs.(egval_S) .> ill_threshold
if sum(project_index) != length(project_index)
H_k_sub = egvec_sub' * H_k * egvec_sub
egvec_S = egvec_S[:, project_index]
@warn "ill-conditioned eigenvalues detected, projected out $(length(project_index) - sum(project_index)) eigenvalues"
H_k_sub = egvec_S' * H_k_sub * egvec_S
S_k_sub = egvec_S' * S_k_sub * egvec_S
(egval, egvec) = eigen(Hermitian(H_k_sub), Hermitian(S_k_sub))
egval = vcat(egval, fill(1e4, length(project_index) - sum(project_index)))
egvec = egvec_S * egvec
egvec = egvec_sub * egvec
else
egval = egval_sub
end
else
lm, ps = construct_linear_map(Hermitian(H_k) - (fermi_level) * Hermitian(S_k), Hermitian(S_k))
println("Time for No.$idx_k matrix factorization: ", time() - begin_time, "s")
egval_inv, egvec = eigs(lm, nev=num_band, which=:LM, ritzvec=false, maxiter=max_iter)
set_phase!(ps, Pardiso.RELEASE_ALL)
pardiso(ps)
egval = real(1 ./ egval_inv) .+ (fermi_level)
# egval = real(eigs(H_k, S_k, nev=num_band, sigma=(fermi_level + lowest_band), which=:LR, ritzvec=false, maxiter=max_iter)[1])
end
egvals[:, idx_k] = egval
if which_k == 0
# println(egval .- fermi_level)
else
open(joinpath(parsed_args["output_dir"], "kpoint.dat"), "w") do f
writedlm(f, [kx, ky, kz])
end
open(joinpath(parsed_args["output_dir"], "egval.dat"), "w") do f
writedlm(f, egval)
end
end
egvals[:, idx_k] = egval
println("Time for solving No.$idx_k eigenvalues at k = ", [kx, ky, kz], ": ", time() - begin_time, "s")
end
idx_k += 1
end
end
# output in openmx band format
f = open(joinpath(parsed_args["output_dir"], "openmx.Band"),"w")
println(f, num_band, " ", 0, " ", ev2Hartree * fermi_level)
openmx_rlat = reshape((rlat .* Bohr2Ang), 1, :)
println(f, std_out_array(openmx_rlat))
println(f, length(k_data))
for line in k_data
println(f,line)
end
idx_k = 1
for i = 1:size(kpaths, 1)
pnkpts = num_ks[i]
kstart = kpaths[i][1:3]
kend = kpaths[i][4:6]
k_list = zeros(Float64,pnkpts,3)
for alpha = 1:3
k_list[:,alpha] = genlist([kstart[alpha],kend[alpha],pnkpts])
end
for j = 1:pnkpts
kvec = k_list[j,:]
println(f, num_band, " ", std_out_array(kvec))
println(f, std_out_array(ev2Hartree * egvals[:, idx_k]))
idx_k += 1
end
end
close(f)
elseif calc_job == "dos"
fermi_level = config["fermi_level"]
max_iter = config["max_iter"]
num_band = config["num_band"]
nkmesh = convert(Array{Int64,1}, config["kmesh"])
ks = constructmeshkpts(nkmesh)
nks = size(ks, 2)
egvals = zeros(Float64, num_band, nks)
begin_time = time()
for idx_k in 1:nks
kx, ky, kz = ks[:, idx_k]
H_k = spzeros(default_dtype, norbits, norbits)
S_k = spzeros(default_dtype, norbits, norbits)
for R in keys(H_R)
H_k += H_R[R] * exp(im*2π*([kx, ky, kz]⋅R))
S_k += S_R[R] * exp(im*2π*([kx, ky, kz]⋅R))
end
S_k = (S_k + S_k') / 2
H_k = (H_k + H_k') / 2
if ill_project
lm, ps = construct_linear_map(Hermitian(H_k) - (fermi_level) * Hermitian(S_k), Hermitian(S_k))
println("Time for No.$idx_k matrix factorization: ", time() - begin_time, "s")
egval_sub_inv, egvec_sub = eigs(lm, nev=num_band, which=:LM, ritzvec=true, maxiter=max_iter)
set_phase!(ps, Pardiso.RELEASE_ALL)
pardiso(ps)
egval_sub = real(1 ./ egval_sub_inv) .+ (fermi_level)
# orthogonalize the eigenvectors
egvec_sub_qr = qr(egvec_sub)
egvec_sub = convert(Matrix{default_dtype}, egvec_sub_qr.Q)
S_k_sub = egvec_sub' * S_k * egvec_sub
(egval_S, egvec_S) = eigen(Hermitian(S_k_sub))
# egvec_S: shape (num_basis, num_bands)
project_index = abs.(egval_S) .> ill_threshold
if sum(project_index) != length(project_index)
H_k_sub = egvec_sub' * H_k * egvec_sub
egvec_S = egvec_S[:, project_index]
@warn "ill-conditioned eigenvalues detected, projected out $(length(project_index) - sum(project_index)) eigenvalues"
H_k_sub = egvec_S' * H_k_sub * egvec_S
S_k_sub = egvec_S' * S_k_sub * egvec_S
(egval, egvec) = eigen(Hermitian(H_k_sub), Hermitian(S_k_sub))
egval = vcat(egval, fill(1e4, length(project_index) - sum(project_index)))
egvec = egvec_S * egvec
egvec = egvec_sub * egvec
else
egval = egval_sub
end
else
lm, ps = construct_linear_map(Hermitian(H_k) - (fermi_level) * Hermitian(S_k), Hermitian(S_k))
println("Time for No.$idx_k matrix factorization: ", time() - begin_time, "s")
egval_inv, egvec = eigs(lm, nev=num_band, which=:LM, ritzvec=false, maxiter=max_iter)
set_phase!(ps, Pardiso.RELEASE_ALL)
pardiso(ps)
egval = real(1 ./ egval_inv) .+ (fermi_level)
# egval = real(eigs(H_k, S_k, nev=num_band, sigma=(fermi_level + lowest_band), which=:LR, ritzvec=false, maxiter=max_iter)[1])
end
egvals[:, idx_k] = egval
println("Time for solving No.$idx_k eigenvalues at k = ", [kx, ky, kz], ": ", time() - begin_time, "s")
end
open(joinpath(parsed_args["output_dir"], "egvals.dat"), "w") do f
writedlm(f, egvals)
end
ϵ = config["epsilon"]
ωs = genlist(config["omegas"])
nωs = length(ωs)
dos = zeros(nωs)
factor = 1/((2π)^3*ϵ*√π)
for idx_k in 1:nks, idx_band in 1:num_band, (idx_ω, ω) in enumerate(ωs)
dos[idx_ω] += exp(-(egvals[idx_band, idx_k] - ω - fermi_level) ^ 2 / ϵ ^ 2) * factor
end
open(joinpath(parsed_args["output_dir"], "dos.dat"), "w") do f
writedlm(f, [ωs dos])
end
end
end
main()