green-mbtools 0.2b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of green-mbtools might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from . import common_utils as cu
2
+ from . import integral_utils as iu
3
+ from .pyscf_init import pyscf_init
@@ -0,0 +1,607 @@
1
+ import argparse
2
+ import os
3
+
4
+ import h5py
5
+ import numpy as np
6
+ import pyscf.lib.chkfile as chk
7
+ from numba import jit
8
+ from pyscf import gto as mgto
9
+ from pyscf.pbc import tools, gto, df, scf, dft
10
+
11
+ from . import integral_utils as int_utils
12
+
13
+ def construct_rmesh(nkx, nky, nkz):
14
+ '''
15
+ Construct real space grid centered around (0,0,0)
16
+ '''
17
+ Lx, Ly, Lz = (nkx-1)//2, (nky-1)//2, (nkz-1)//2 # nk=6, L=2
18
+ leftx, lefty, leftz = (nkx-1)%2, (nky-1)%2, (nkz-1)%2 # left = 1
19
+
20
+ rx = np.linspace(-Lx, Lx+leftx, nkx, endpoint=True) # -2,-1,0,1,2,3
21
+ ry = np.linspace(-Ly, Ly+lefty, nky, endpoint=True)
22
+ rz = np.linspace(-Lz, Lz+leftz, nkz, endpoint=True)
23
+ RX, RY, RZ = np.meshgrid(rx, ry, rz)
24
+ rmesh = np.array([RX.flatten(), RY.flatten(), RZ.flatten()]).T
25
+
26
+ return rmesh
27
+
28
+ def extract_ase_data(a, atoms):
29
+ '''
30
+ For a given data in XYZ format generate parameters in ASE format
31
+
32
+ :param a: string containing lattice vectros in XYZ format
33
+ :param atoms: string containin atoms positions in XYZ format
34
+ '''
35
+ symbols = []
36
+ positions = []
37
+ lattice_vectors = []
38
+ for a_i in a.splitlines():
39
+ if len(a_i) == 0 or len(a_i.split(",")) != 3:
40
+ continue
41
+ lattice_vectors.append([float(x.strip()) for x in a_i.split(",")])
42
+ for atom in atoms.splitlines():
43
+ if len(atom) == 0 or len(atom.split()) != 4:
44
+ continue
45
+ atom = atom.strip()
46
+ symbol = atom.split()[0]
47
+ position = atom.split(symbol)[1].strip()
48
+ symbols.append(symbol)
49
+ position = [float(p) for p in position.split()]
50
+ positions.append(np.dot(np.linalg.inv(lattice_vectors), position).tolist())
51
+ return (np.array(lattice_vectors), symbols, positions)
52
+
53
+ def print_high_symmetry_points(cell, args):
54
+ '''
55
+ For a given unit cell and simulation parameters generate and print list of lattice special points
56
+ '''
57
+ import ase.spacegroup
58
+ lattice_vectors, symbols, positions = extract_ase_data(args.a, args.atom)
59
+ cc = ase.spacegroup.crystal(symbols, positions, cellpar=ase.geometry.cell_to_cellpar(lattice_vectors))
60
+ space_group = ase.spacegroup.get_spacegroup(cc)
61
+ lat = cc.cell.get_bravais_lattice()
62
+ special_points = lat.get_special_points()
63
+ print("List of special points: {}".format(special_points))
64
+
65
+ def check_high_symmetry_path(cell, args):
66
+ '''
67
+ Check that selected high-symmetry path is correct for the chosen simulation parameters
68
+
69
+ :param cell: unit cell object
70
+ :param args: simulation parameters
71
+ '''
72
+ if args.high_symmetry_path is None:
73
+ return
74
+ import ase.spacegroup
75
+ lattice_vectors, symbols, positions = extract_ase_data(args.a, args.atom)
76
+ print("parse:", lattice_vectors, symbols, positions)
77
+ cc = ase.spacegroup.crystal(symbols, positions, cellpar=ase.geometry.cell_to_cellpar(lattice_vectors))
78
+ space_group = ase.spacegroup.get_spacegroup(cc)
79
+ lat = cc.cell.get_bravais_lattice()
80
+ special_points = lat.get_special_points()
81
+ path = args.high_symmetry_path
82
+ for sp in special_points.keys():
83
+ path = path.replace(sp, "")
84
+ path = path.replace(",", "")
85
+ if path != "":
86
+ raise RuntimeError(("Chosen high symmetry path {} has invalid special points {}. Valid "
87
+ "special points are {} ").format(args.high_symmetry_path, path, special_points.keys()))
88
+
89
+ def high_symmetry_path(cell, args):
90
+ '''
91
+ Compute high-symmetry k-path
92
+
93
+ :param cell: unit-cell object
94
+ :param args: simulation parameters
95
+ :return: Points on the chosen high-symmetry path and corresponding non-interacting Hamiltonian and overlap matrix
96
+ '''
97
+ if args.high_symmetry_path is None:
98
+ return [None, None, None]
99
+ import ase
100
+ lattice_vectors, symbols, positions = extract_ase_data(args.a, args.atom)
101
+ path = args.high_symmetry_path
102
+ kpath = ase.dft.kpoints.bandpath(args.high_symmetry_path, lattice_vectors, npoints=args.high_symmetry_path_points)
103
+ kmesh = cell.get_abs_kpts(kpath.kpts)
104
+ new_mf = dft.KUKS(cell,kmesh).density_fit()
105
+ H0_hs = new_mf.get_hcore()
106
+ Sk_hs = new_mf.get_ovlp()
107
+ return [kmesh, H0_hs, Sk_hs]
108
+
109
+ def transform(Z, X, X_inv):
110
+ '''
111
+ Transform Z into X basis
112
+ :param Z: Object to be transformed
113
+ :param X: Transformation matrix
114
+ :param X_inv: Inverse transformation matrix
115
+ :return: Z in new basis
116
+ '''
117
+ Z_X = np.zeros(Z.shape, dtype=np.complex128)
118
+ maxdiff = -1
119
+ for ss in range(Z.shape[0]):
120
+ for ik in range(Z.shape[1]):
121
+ Z_X[ss,ik] = np.einsum('ij,jk...,kl->il...', X[ik], Z[ss, ik], X[ik].T.conj())
122
+
123
+ Z_restore = np.dot(X_inv[ik], np.dot(Z_X[ss, ik], X_inv[ik].conj().T))
124
+ diff = np.max(np.abs(Z[ss, ik] - Z_restore))
125
+ maxdiff = max(maxdiff, diff)
126
+
127
+ if not np.allclose(Z[ss, ik], Z_restore, atol=1e-12, rtol=1e-12) :
128
+ error = "Orthogonal transformation failed. Max difference between origin and restored quantity is {}".format(np.max(np.abs(Z[ss,ik] - Z_restore)))
129
+ raise RuntimeError(error)
130
+ print("Maximum difference between Z and Z_restore ", maxdiff)
131
+ return Z_X
132
+
133
+ def fold_back_to_1stBZ(kpts):
134
+ '''
135
+ Map each k-point from a given list of scaled k-points into the first Brillouin zone
136
+
137
+ :param kpts: list of k-points
138
+ '''
139
+ nkpts = len(kpts)
140
+ for i, ik in enumerate(kpts):
141
+ kpts[i] = np.array([wrap_1stBZ(kk) for kk in ik])
142
+ return kpts
143
+
144
+ def inversion_sym(kmesh_scaled):
145
+ '''
146
+ For a given list of the scaled k-point in the full Brillouin zone select k-points that are
147
+ equivalent by the time-reversal symmetry and return them and their corresponding weight and index
148
+ '''
149
+ ind = np.arange(np.shape(kmesh_scaled)[0])
150
+ weight = np.zeros(np.shape(kmesh_scaled)[0])
151
+ for i, ki in enumerate(kmesh_scaled):
152
+ ki = [wrap_1stBZ(l) for l in ki]
153
+ kmesh_scaled[i] = ki
154
+
155
+ # Time-reversal symmetry
156
+ Inv = (-1) * np.identity(3)
157
+ for i, ki in enumerate(kmesh_scaled):
158
+ ki = np.dot(Inv,ki)
159
+ ki = [wrap_1stBZ(l) for l in ki]
160
+ for l, kl in enumerate(kmesh_scaled[:i]):
161
+ if np.allclose(ki,kl):
162
+ ind[i] = l
163
+ break
164
+
165
+ uniq = np.unique(ind, return_counts=True)
166
+ for i, k in enumerate(uniq[0]):
167
+ weight[k] = uniq[1][i]
168
+ ir_list = uniq[0]
169
+
170
+ # Mark down time-reversal-reduced k-points
171
+ conj_list = np.zeros(len(kmesh_scaled))
172
+ for i, k in enumerate(ind):
173
+ if i != k:
174
+ conj_list[i] = 1
175
+
176
+ return ir_list, ind, weight, conj_list
177
+
178
+ def wrap_k(k):
179
+ while k < 0 :
180
+ k = 1 + k
181
+ while (k - 9.9999999999e-1) > 0.0 :
182
+ k = k - 1
183
+ return k
184
+
185
+ def parse_basis(basis_list):
186
+ '''
187
+ Parse information about chosen basis sets
188
+ '''
189
+ loggin.debug(basis_list, len(basis_list) % 2)
190
+ if len(basis_list) % 2 == 0:
191
+ b = {}
192
+ for atom_i in range(0, len(basis_list), 2):
193
+ bas_i = basis_list[atom_i + 1]
194
+ if os.path.exists(bas_i) :
195
+ with open(bas_i) as bfile:
196
+ bas = mgto.parse(bfile.read())
197
+ # if basis specified as a standard basis
198
+ else:
199
+ bas = bas_i
200
+ b[basis_list[atom_i]] = bas
201
+ return b
202
+ else:
203
+ return basis_list[0]
204
+
205
+ def parse_geometry(g):
206
+ '''
207
+ parse geometry of the system
208
+ '''
209
+ res = ""
210
+ if os.path.exists(g) :
211
+ with open(g) as gf:
212
+ res = gf.read()
213
+ else:
214
+ res = g
215
+ return res
216
+
217
+ def save_data(args, mycell, mf, kmesh, ind, weight, num_ik, ir_list, conj_list, Nk, nk, NQ, F, S, T, hf_dm,
218
+ Zs, last_ao):
219
+ '''
220
+ Save data in Green/WeakCoupling format into a hdf5 file
221
+ '''
222
+ kptij_idx, kij_conj, kij_trans, kpair_irre_list, num_kpair_stored, kptis, kptjs = int_utils.integrals_grid(mycell, kmesh)
223
+ print("number of reduced k-pairs: ", num_kpair_stored)
224
+ inp_data = h5py.File(args.output_path, "w")
225
+ inp_data["grid/k_mesh"] = kmesh
226
+ inp_data["grid/k_mesh_scaled"] = mycell.get_scaled_kpts(kmesh)
227
+ inp_data["grid/index"] = ind
228
+ inp_data["grid/weight"] = weight
229
+ inp_data["grid/ink"] = num_ik
230
+ inp_data["grid/nk"] = nk
231
+ inp_data["grid/ir_list"] = ir_list
232
+ inp_data["grid/conj_list"] = conj_list
233
+ inp_data["grid/conj_pairs_list"] = kij_conj
234
+ inp_data["grid/trans_pairs_list"] = kij_trans
235
+ inp_data["grid/kpair_irre_list"] = kpair_irre_list
236
+ inp_data["grid/kpair_idx"] = kptij_idx
237
+ inp_data["grid/num_kpair_stored"] = num_kpair_stored
238
+ inp_data["HF/Nk"] = Nk
239
+ inp_data["HF/nk"] = nk
240
+ inp_data["HF/Energy"] = mf.e_tot
241
+ inp_data["HF/Energy_nuc"] = mf.cell.energy_nuc()
242
+ inp_data["HF/Fock-k"] = F.view(np.float64).reshape(F.shape[0], F.shape[1], F.shape[2], F.shape[3], 2)
243
+ inp_data["HF/Fock-k"].attrs["__complex__"] = np.int8(1)
244
+ inp_data["HF/S-k"] = S.view(np.float64).reshape(S.shape[0], S.shape[1], S.shape[2], S.shape[3], 2)
245
+ inp_data["HF/S-k"].attrs["__complex__"] = np.int8(1)
246
+ inp_data["HF/H-k"] = T.view(np.float64).reshape(T.shape[0], T.shape[1], T.shape[2], T.shape[3], 2)
247
+ inp_data["HF/H-k"].attrs["__complex__"] = np.int8(1)
248
+ inp_data["HF/madelung"] = tools.pbc.madelung(mycell, kmesh)
249
+ inp_data["HF/mo_energy"] = mf.mo_energy
250
+ inp_data["HF/mo_coeff"] = mf.mo_coeff
251
+ inp_data["mulliken/Zs"] = Zs
252
+ inp_data["mulliken/last_ao"] = last_ao
253
+ inp_data["params/nao"] = S.shape[2]
254
+ inp_data["params/nso"] = S.shape[2]
255
+ inp_data["params/ns"] = S.shape[0]
256
+ inp_data["params/nel_cell"] = mycell.nelectron
257
+ inp_data["params/nk"] = kmesh.shape[0]
258
+ inp_data["params/NQ"] = NQ
259
+ inp_data.close()
260
+ chk.save(args.output_path, "Cell", mycell.dumps())
261
+ inp_data = h5py.File("dm.h5", "w")
262
+ inp_data["HF/dm-k"] = hf_dm.view(np.float64).reshape(hf_dm.shape[0], hf_dm.shape[1], hf_dm.shape[2], hf_dm.shape[3], 2)
263
+ inp_data["HF/dm-k"].attrs["__complex__"] = np.int8(1)
264
+ inp_data["dm_gamma"] = hf_dm[:, 0, :, :]
265
+ inp_data.close()
266
+
267
+
268
+ def orthogonalize(mydf, orth, X_k, X_inv_k, F, T, hf_dm, S):
269
+ '''
270
+ Transform Fock-matrix, non-interacting Hamiltonian, density matrix and overlap matrix into an orthogonal basis
271
+ '''
272
+ maxdiff = -1
273
+ old_shape = [-1, -1]
274
+ for ik, k in enumerate(mydf.kpts):
275
+ if orth == 0:
276
+ X_inv_k.append(np.eye(F.shape[2], dtype=np.complex128))
277
+ X_k.append(np.eye(F.shape[2], dtype=np.complex128))
278
+ continue
279
+
280
+ s_ev, s_eb = np.linalg.eigh(S[0, ik])
281
+
282
+ # Remove all eigenvalues < threshold
283
+ istart = s_ev.searchsorted(1e-9)
284
+ s_sqrtev = np.sqrt(s_ev[istart:])
285
+
286
+ x_pinv = s_eb[:, istart:] * s_sqrtev
287
+ x = (s_eb[:, istart:].conj() * 1 / s_sqrtev).T
288
+ n_ortho, n_nonortho = x.shape
289
+ if old_shape[0] >= 0 and n_ortho != old_shape[0] and n_nonortho != old_shape[1]:
290
+ raise RuntimeError("Error!!! Different k-point have different number of orthogonal basis.")
291
+
292
+ old_shape[0] = n_ortho
293
+ old_shape[1] = n_nonortho
294
+
295
+ X_inv_k.append(x_pinv.copy())
296
+ X_k.append(x.copy())
297
+
298
+ diff = np.eye(n_nonortho) - np.dot(x, x_pinv)
299
+ diff_max = np.max(np.abs(diff))
300
+ maxdiff = max(maxdiff, diff_max)
301
+ logging.info("max diff from identity ", maxdiff)
302
+ X_inv_k = np.asarray(X_inv_k).reshape(F.shape[1:])
303
+ X_k = np.asarray(X_k).reshape(F.shape[1:])
304
+ # Orthogonalization
305
+ if orth == 1:
306
+ F = transform(F, X_k, X_inv_k)
307
+ # S = transform(S, X_k, X_inv_k)
308
+ T = transform(T, X_k, X_inv_k)
309
+ hf_dm = transform(hf_dm, X_inv_k, X_k)
310
+
311
+ S = np.array([np.eye(F.shape[-1], dtype=np.complex128)] * F.shape[1])
312
+ S = np.array([S, S])
313
+
314
+ return X_k, X_inv_k, S, F, T, hf_dm
315
+
316
+ def add_common_params(parser):
317
+ '''
318
+ Define common command line arguments for Green python module
319
+ '''
320
+ parser.add_argument("--a", type=parse_geometry, help="lattice geometry", required=True)
321
+ parser.add_argument("--atom", type=parse_geometry, help="poistions of atoms", required=True)
322
+ parser.add_argument("--nk", type=int, help="number of k-points in each direction", required=True)
323
+ parser.add_argument("--symm", type=lambda x: (str(x).lower() in ['true','1', 'yes']), default='true', help="Use inversion symmetry")
324
+ parser.add_argument("--Nk", type=int, default=0, help="number of plane-waves in each direction for integral evaluation")
325
+ parser.add_argument("--basis", type=str, nargs="*", help="basis sets definition. First specify atom then basis for this atom", required=True)
326
+ parser.add_argument("--auxbasis", type=str, nargs="*", default=[None], help="auxiliary basis")
327
+ parser.add_argument("--ecp", type=str, nargs="*", default=[None], help="effective core potentials")
328
+ parser.add_argument("--pseudo", type=str, nargs="*", default=[None], help="pseudopotential")
329
+ parser.add_argument("--shift", type=float, nargs=3, default=[0.0, 0.0, 0.0], help="mesh shift")
330
+ parser.add_argument("--center", type=float, nargs=3, default=[0.0, 0.0, 0.0], help="mesh center")
331
+ parser.add_argument("--xc", type=str, nargs="*", default=[None], help="XC functional")
332
+ parser.add_argument("--dm0", type=str, default=None, help="initial guess for density matrix")
333
+ parser.add_argument("--df_int", type=int, default=1, help="prepare density fitting integrals or not")
334
+ parser.add_argument("--int_path", type=str, default="df_int", help="path to store ewald corrected integrals")
335
+ parser.add_argument("--hf_int_path", type=str, default="df_hf_int", help="path to store hf integrals")
336
+ parser.add_argument("--output_path", type=str, default="input.h5", help="output file with initial data")
337
+ parser.add_argument("--orth", type=int, default=0, help="Transform to orthogonal basis or not. 0 - no orthogonal transformation, 1 - data is in orthogonal basis.")
338
+ parser.add_argument("--beta", type=float, default=None, help="Emperical parameter for even-Gaussian auxiliary basis")
339
+ parser.add_argument("--active_space", type=int, nargs='+', default=None, help="active space orbitals")
340
+ parser.add_argument("--spin", type=int, default=0, help="Local spin")
341
+ parser.add_argument("--restricted", type=lambda x: (str(x).lower() in ['true','1', 'yes']), default='false', help="Spin restricted calculations.")
342
+ parser.add_argument("--print_high_symmetry_points", default=False, action='store_true', help="Print available high symmetry points for current system and exit.")
343
+ parser.add_argument("--high_symmetry_path", type=str, default=None, help="High symmetry path")
344
+ parser.add_argument("--high_symmetry_path_points", type=int, default=0, help="Number of points for high symmetry path")
345
+ parser.add_argument("--memory", type=int, default=700, help="Memory bound for integral chunk in MB")
346
+ parser.add_argument("--grid_only", type=lambda x: (str(x).lower() in ['true','1', 'yes']), default='false', help="Only recompute k-grid points")
347
+ parser.add_argument("--diffuse_cutoff", type=float, default=0.0, help="Remove the diffused Gaussians whose exponents are less than the cutoff")
348
+ parser.add_argument("--damping", type=float, default=0.0, help="Damping factor for mean-field iterations")
349
+ parser.add_argument("--max_iter", type=int, default=100, help="Maximum number of iterations in the SCF loop")
350
+ parser.add_argument("--keep_cderi", type=lambda x: (str(x).lower() in ['true','1', 'yes']), default='false', help="Keep generated cderi files.")
351
+ parser.add_argument("--job", choices=["init", "sym_path", "ewald_corr"], default="init")
352
+ parser.add_argument("--finite_size_kind", choices=["ewald", "gf2", "gw", "gw_s", "coarse_grained"], default="ewald", help="Two body finite-size correction. Be default computes the second set of integrals that include simple ewald correction.")
353
+
354
+ def init_pbc_params():
355
+ '''
356
+ Initialize argparse.ArgumentParser for Green/WeakCoupling python module and return a prased parameters map
357
+ '''
358
+ parser = argparse.ArgumentParser(description="Green/WeakCoupling initialization script")
359
+ add_common_params(parser)
360
+ args = parser.parse_args()
361
+ args.basis = parse_basis(args.basis)
362
+ args.auxbasis = parse_basis(args.auxbasis)
363
+ args.ecp = parse_basis(args.ecp)
364
+ args.pseudo = parse_basis(args.pseudo)
365
+ args.xc = parse_basis(args.xc)
366
+ if args.xc is not None:
367
+ args.mean_field = dft.KRKS if args.restricted else dft.KUKS
368
+ else:
369
+ args.mean_field = scf.KRHF if args.restricted else scf.KUHF
370
+ args.ns = 1 if args.restricted else 2
371
+ return args
372
+
373
+
374
+ def cell(args):
375
+ '''
376
+ Initialize PySCF unit cell object for a given system
377
+ '''
378
+ c = gto.M(
379
+ a = args.a,
380
+ atom = args.atom,
381
+ unit = 'A',
382
+ basis = args.basis,
383
+ ecp = args.ecp,
384
+ pseudo = args.pseudo,
385
+ verbose = 7,
386
+ spin = args.spin,
387
+ exp_to_discard = args.diffuse_cutoff
388
+ )
389
+ _a = c.lattice_vectors()
390
+ c.exp_to_discard = args.diffuse_cutoff
391
+ c.build()
392
+ if np.linalg.det(_a) < 0:
393
+ raise "Lattice are not in right-handed coordinate system. Please correct your lattice vectors"
394
+ return c
395
+
396
+ def wrap_1stBZ(k):
397
+ '''
398
+ wrap scaled k into [-0.5,0.5) range
399
+ :param k: value of k-point at some dimension
400
+ '''
401
+ while k < -0.5 :
402
+ k = k + 1
403
+ while (k - 4.9999999999e-1) > 0.0 :
404
+ k = k - 1
405
+ return k
406
+
407
+ def init_k_mesh(args, mycell):
408
+ '''
409
+ init k-points mesh for GDF
410
+
411
+ :param args: script arguments
412
+ :param mycell: unit cell for simulation
413
+ :return: kmesh, k_ibz, ir_list, conj_list, weight, ind, num_ik
414
+ '''
415
+ kmesh = mycell.make_kpts([args.nk, args.nk, args.nk], scaled_center=args.center)
416
+ for i, kk in enumerate(kmesh):
417
+ ki = kmesh[i]
418
+ ki = mycell.get_scaled_kpts(ki) + args.shift
419
+ ki = [wrap_k(l) for l in ki]
420
+ kmesh[i] = mycell.get_abs_kpts(ki)
421
+ for i, ki in enumerate(kmesh):
422
+ ki = mycell.get_scaled_kpts(ki)
423
+ ki = [wrap_k(l) for l in ki]
424
+ ki = mycell.get_abs_kpts(ki)
425
+ kmesh[i] = ki
426
+
427
+ logging.debug(kmesh)
428
+ logging.(mycell.get_scaled_kpts(kmesh))
429
+
430
+ if not args.symm :
431
+ nkpts = kmesh.shape[0]
432
+ weight = np.ones(nkpts)
433
+ ir_list = np.array(range(nkpts))
434
+ ind = np.array(range(nkpts))
435
+ conj_list = np.zeros(nkpts)
436
+ k_ibz = np.copy(kmesh)
437
+ num_ik = nkpts
438
+ return kmesh, k_ibz, ir_list, conj_list, weight, ind, num_ik
439
+
440
+ logging.info("Compute irreducible k-points")
441
+
442
+
443
+ k_ibz = mycell.make_kpts([args.nk,args.nk,args.nk], scaled_center=args.center)
444
+ ind = np.arange(np.shape(k_ibz)[0])
445
+ weight = np.zeros(np.shape(k_ibz)[0])
446
+ for i, ki in enumerate(k_ibz):
447
+ ki = mycell.get_scaled_kpts(ki)
448
+ ki = [wrap_1stBZ(l) for l in ki]
449
+ k_ibz[i] = ki
450
+
451
+ # Time-reversal symmetry
452
+ Inv = (-1) * np.identity(3)
453
+ for i, ki in enumerate(k_ibz):
454
+ ki = np.dot(Inv,ki)
455
+ ki = [wrap_1stBZ(l) for l in ki]
456
+ for l, kl in enumerate(k_ibz[:i]):
457
+ if np.allclose(ki,kl):
458
+ k_ibz[i] = kl
459
+ ind[i] = l
460
+ break
461
+
462
+ uniq = np.unique(ind, return_counts=True)
463
+ for i, k in enumerate(uniq[0]):
464
+ weight[k] = uniq[1][i]
465
+ ir_list = uniq[0]
466
+
467
+ # Mark down time-reversal-reduced k-points
468
+ conj_list = np.zeros(args.nk**3)
469
+ for i, k in enumerate(ind):
470
+ if i != k:
471
+ conj_list[i] = 1
472
+ num_ik = np.shape(uniq[0])[0]
473
+
474
+ return kmesh, k_ibz, ir_list, conj_list, weight, ind, num_ik
475
+
476
+
477
+
478
+ def read_dm(dm0, dm_file):
479
+ '''
480
+ Read density matrix from smaller kmesh
481
+ '''
482
+ nao = dm0.shape[-1]
483
+ nkpts = dm0.shape[1]
484
+ dm = np.zeros((2,nao,nao),dtype=np.complex128)
485
+ f = h5py.File(dm_file, 'r')
486
+ dm[:,:,:] = f['/dm_gamma'][:]
487
+ f.close()
488
+ dm_kpts = np.repeat(dm[:,None, :, :], nkpts, axis=1)
489
+ return dm_kpts
490
+
491
+ def solve_mean_field(args, mydf, mycell):
492
+ '''
493
+ Obtain pySCF mean-field solution for a given parameters, unit-cell object and density-fitting object
494
+ '''
495
+ logging.info("Solve LDA")
496
+ # prepare and solve DFT
497
+ mf = args.mean_field(mycell,mydf.kpts).density_fit() # if args.xc is not None else scf.KUHF(mycell,mydf.kpts).density_fit()
498
+ if args.xc is not None:
499
+ mf.xc = args.xc
500
+ #mf.max_memory = 10000
501
+ mydf._cderi = "cderi.h5"
502
+ mf.kpts = mydf.kpts
503
+ mf.with_df = mydf
504
+ mf.diis_space = 16
505
+ mf.damp = args.damping
506
+ mf.max_cycle = args.max_iter
507
+ mf.chkfile = 'tmp.chk'
508
+ if os.path.exists("tmp.chk"):
509
+ init_dm = mf.from_chk('tmp.chk')
510
+ mf.kernel(init_dm)
511
+ elif args.dm0 is not None:
512
+ init_dm = mf.get_init_guess()
513
+ init_dm = read_dm(init_dm, args.dm0)
514
+ mf.kernel(init_dm)
515
+ else:
516
+ mf.kernel()
517
+ mf.analyze()
518
+ return mf
519
+
520
+
521
+ def store_k_grid(args, mycell, kmesh, k_ibz, ir_list, conj_list, weight, ind, num_ik):
522
+ '''
523
+ Store reciprocal space information into a hdf5 file in Green'WeakCoupling format
524
+ '''
525
+ inp_data = h5py.File(args.output_path, "a")
526
+ nk = kmesh.shape[0]
527
+ ink = k_ibz.shape[0]
528
+ kptij_idx, kij_conj, kij_trans, kpair_irre_list, num_kpair_stored, kptis, kptjs = int_utils.integrals_grid(mycell, kmesh)
529
+ print("number of reduced k-pairs: ", num_kpair_stored)
530
+ if not "grid" in inp_data:
531
+ inp_data.create_group("grid")
532
+ grid_grp = inp_data["grid"]
533
+ data = [kmesh, mycell.get_scaled_kpts(kmesh), ind, weight, num_ik, nk, ir_list, conj_list,
534
+ kij_conj, kij_trans, kpair_irre_list, kptij_idx, num_kpair_stored]
535
+ names = ["k_mesh", "k_mesh_scaled", "index", "weight", "ink", "nk", "ir_list", "conj_list",
536
+ "conj_pairs_list", "trans_pairs_list", "kpair_irre_list", "kpair_idx", "num_kpair_stored" ]
537
+ for i, name in enumerate(names):
538
+ if name in grid_grp:
539
+ grid_grp[name][...] = data[i]
540
+ else:
541
+ grid_grp[name] = data[i]
542
+ inp_data.close()
543
+
544
+ def construct_gdf(args, mycell, kmesh=None):
545
+ '''
546
+ Construct Gaussian Density Fitting obejct for a given parameters and unit cell.
547
+ We make sure to disable range-separeting implementation
548
+ '''
549
+ # Use gaussian density fitting to get fitted densities
550
+ mydf = df.GDF(mycell)
551
+ if hasattr(mydf, "_prefer_ccdf"):
552
+ mydf._prefer_ccdf = True # Disable RS-GDF switch for new pyscf versions
553
+ if args.auxbasis is not None:
554
+ mydf.auxbasis = args.auxbasis
555
+ elif args.beta is not None:
556
+ mydf.auxbasis = df.aug_etb(mycell, beta=args.beta)
557
+ # Coulomb kernel mesh
558
+ if args.Nk > 0:
559
+ mydf.mesh = [args.Nk, args.Nk, args.Nk]
560
+ if kmesh is not None:
561
+ mydf.kpts = kmesh
562
+ return mydf
563
+
564
+ def compute_ewald_correction(args, cell, kmesh, filename):
565
+ # Use gaussian density fitting to get fitted densities
566
+ mydf = df.GDF(cell)
567
+ if args.auxbasis is not None:
568
+ mydf.auxbasis = args.auxbasis
569
+ elif args.beta is not None:
570
+ mydf.auxbasis = df.aug_etb(cell, beta=args.beta)
571
+ # Coulomb kernel mesh
572
+ if args.Nk > 0:
573
+ mydf.mesh = [args.Nk, args.Nk, args.Nk]
574
+ int_utils.compute_ewald_correction(args, mydf, kmesh, cell.nao_nr(), filename)
575
+
576
+ def compute_df_int_dca(args, mycell, kmesh, lattice_kmesh, nao, X_k):
577
+ '''
578
+ Generate density-fitting integrals for correlated methods using q-averaging over the super-lattice points to compensate finite-size error
579
+
580
+ :param args: simulation parameters
581
+ :param mycell: unit cell object
582
+ :param kmesh: reciprocal space grid
583
+ :param lattice_kmesh: super-lattice k-points
584
+ :param nao: number of atomic orbitals in the unit cell
585
+ :param X_k: trasformation matrix for projection onto an orthogonal space
586
+ '''
587
+
588
+ if not bool(args.df_int):
589
+ return
590
+ mydf = construct_gdf(args, mycell, kmesh)
591
+ # Use Ewald for divergence treatment
592
+ mydf.exxdiv = 'ewald'
593
+ weighted_coulG_old = df.GDF.weighted_coulG
594
+ df.GDF.weighted_coulG = int_utils.weighted_coulG_ewald
595
+ old_get_coulG = tools.get_coulG
596
+ tools.get_coulG = lambda cell, k=np.zeros(3), exx=False, mf=None, mesh=None, Gv=None, wrap_around=True, omega=None, **kwargs: int_utils.get_coarsegrained_coulG(lattice_kmesh, cell, k, exx, mf, mesh, Gv,
597
+ wrap_around, omega, **kwargs)
598
+
599
+ kij_conj, kij_trans, kpair_irre_list, kptij_idx, num_kpair_stored = int_utils.compute_integrals(mycell, mydf, kmesh, nao, X_k, args.int_path, "cderi_ewald_dca.h5", False)
600
+
601
+ mydf = None
602
+ mydf = construct_gdf(args, mycell, kmesh)
603
+ df.GDF.weighted_coulG = weighted_coulG_old
604
+ int_utils.compute_integrals(mycell, mydf, kmesh, nao, X_k, args.hf_int_path, "cderi_dca.h5", False)
605
+
606
+ tools.get_coulG = old_get_coulG
607
+