TB2J 0.9.0__py3-none-any.whl → 0.9.0.2__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.
Files changed (33) hide show
  1. TB2J/Jdownfolder.py +110 -24
  2. TB2J/Jtensor.py +1 -1
  3. TB2J/MAE.py +188 -0
  4. TB2J/__init__.py +1 -1
  5. TB2J/abacus/MAE.py +320 -0
  6. TB2J/abacus/abacus_wrapper.py +20 -2
  7. TB2J/abacus/occupations.py +278 -0
  8. TB2J/abacus/test_density_matrix.py +38 -0
  9. TB2J/exchange.py +1 -1
  10. TB2J/green.py +2 -13
  11. TB2J/mathutils/__init__.py +1 -0
  12. TB2J/mathutils/fermi.py +22 -0
  13. TB2J/mathutils/kR_convert.py +90 -0
  14. TB2J/mathutils/lowdin.py +12 -0
  15. TB2J/mathutils/rotate_spin.py +35 -0
  16. TB2J/patch.py +50 -0
  17. TB2J/pauli.py +17 -0
  18. TB2J/utils.py +82 -1
  19. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_downfold.py +8 -0
  20. {TB2J-0.9.0.dist-info → TB2J-0.9.0.2.dist-info}/METADATA +6 -9
  21. {TB2J-0.9.0.dist-info → TB2J-0.9.0.2.dist-info}/RECORD +33 -23
  22. {TB2J-0.9.0.dist-info → TB2J-0.9.0.2.dist-info}/WHEEL +1 -1
  23. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_eigen.py +0 -0
  24. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_magnon.py +0 -0
  25. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_magnon_dos.py +0 -0
  26. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_merge.py +0 -0
  27. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_rotate.py +0 -0
  28. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/TB2J_rotateDM.py +0 -0
  29. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/abacus2J.py +0 -0
  30. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/siesta2J.py +0 -0
  31. {TB2J-0.9.0.data → TB2J-0.9.0.2.data}/scripts/wann2J.py +0 -0
  32. {TB2J-0.9.0.dist-info → TB2J-0.9.0.2.dist-info}/LICENSE +0 -0
  33. {TB2J-0.9.0.dist-info → TB2J-0.9.0.2.dist-info}/top_level.txt +0 -0
TB2J/Jdownfolder.py CHANGED
@@ -17,9 +17,23 @@ def ind_to_indn(ind, n=3):
17
17
  return indn
18
18
 
19
19
 
20
+ class JR_model:
21
+ def __init__(self, JR, Rlist):
22
+ self.JR = JR
23
+ self.Rlist = Rlist
24
+ self.nR = len(Rlist)
25
+
26
+ def get_Jq(self, q):
27
+ Jq = np.zeros(self.JR[0].shape, dtype=complex)
28
+ for iR, R in enumerate(self.Rlist):
29
+ phase = np.exp(2.0j * np.pi * np.dot(q, R))
30
+ Jq += self.JR[iR] * phase
31
+ return Jq
32
+
33
+
20
34
  class JDownfolder:
21
35
  def __init__(self, JR, Rlist, iM, iL, qmesh, iso_only=False):
22
- self.JR = JR
36
+ self.model = JR_model(JR, Rlist)
23
37
  self.Rlist = Rlist
24
38
  self.nR = len(Rlist)
25
39
  self.nM = len(iM)
@@ -34,25 +48,18 @@ class JDownfolder:
34
48
  self.nLn = self.nL * 3
35
49
  self.iso_only = iso_only
36
50
 
37
- def get_Jq(self, q):
38
- Jq = np.zeros(self.JR[0].shape, dtype=complex)
39
- for iR, R in enumerate(self.Rlist):
40
- phase = np.exp(2.0j * np.pi * np.dot(q, R))
41
- Jq += self.JR[iR] * phase
42
- return Jq
43
-
44
51
  def get_JR(self):
45
52
  JR_downfolded = np.zeros((self.nR, self.nMn, self.nMn), dtype=float)
46
53
  Jq_downfolded = np.zeros((self.nqpt, self.nMn, self.nMn), dtype=complex)
47
54
  self.iMn = ind_to_indn(self.iM, n=3)
48
55
  self.iLn = ind_to_indn(self.iL, n=3)
49
56
  for iq, q in enumerate(self.qpts):
50
- Jq = self.get_Jq(q)
57
+ Jq = self.model.get_Jq(q)
51
58
  Jq_downfolded[iq] = self.downfold_oneq(Jq)
52
59
  for iR, R in enumerate(self.Rlist):
53
60
  phase = np.exp(-2.0j * np.pi * np.dot(q, R))
54
61
  JR_downfolded[iR] += np.real(Jq_downfolded[iq] * phase / self.nqpt)
55
- return JR_downfolded
62
+ return JR_downfolded, self.Rlist
56
63
 
57
64
  def downfold_oneq(self, J):
58
65
  JMM = J[np.ix_(self.iMn, self.iMn)]
@@ -63,17 +70,80 @@ class JDownfolder:
63
70
  return Jn
64
71
 
65
72
 
73
+ class PWFDownfolder:
74
+ def __init__(self, JR, Rlist, iM, iL, qmesh, atoms=None, iso_only=False, **kwargs):
75
+ from lawaf.interfaces.magnon.magnon_downfolder import (
76
+ MagnonWrapper,
77
+ MagnonDownfolder,
78
+ )
79
+
80
+ model = MagnonWrapper(JR, Rlist, atoms)
81
+ wann = MagnonDownfolder(model)
82
+ # Downfold the band structure.
83
+ index_basis = []
84
+ for i in iM:
85
+ index_basis += list(range(i * 3, i * 3 + 3))
86
+ params = dict(
87
+ method="projected",
88
+ # method="maxprojected",
89
+ kmesh=qmesh,
90
+ nwann=len(index_basis),
91
+ selected_basis=index_basis,
92
+ # anchors={(0, 0, 0): (-1, -2, -3, -4)},
93
+ # anchors={(0, 0, 0): ()},
94
+ # use_proj=True,
95
+ enhance_Amn=2.0,
96
+ )
97
+ params.update(kwargs)
98
+ wann.set_parameters(**params)
99
+ print("begin downfold")
100
+ ewf = wann.downfold()
101
+ ewf.save_hr_pickle("downfolded_JR.pickle")
102
+
103
+ # Plot the band structure.
104
+ wann.plot_band_fitting(
105
+ # kvectors=np.array([[0, 0, 0], [0.5, 0, 0],
106
+ # [0.5, 0.5, 0], [0, 0, 0],
107
+ # [.5, .5, .5]]),
108
+ # knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
109
+ cell=model.atoms.cell,
110
+ supercell_matrix=None,
111
+ npoints=100,
112
+ efermi=None,
113
+ erange=None,
114
+ fullband_color="blue",
115
+ downfolded_band_color="green",
116
+ marker="o",
117
+ ax=None,
118
+ savefig="downfold_band.png",
119
+ show=True,
120
+ )
121
+ self.JR_downfolded = ewf.HwannR
122
+ self.Rlist = ewf.Rlist
123
+
124
+ def get_JR(self):
125
+ return self.JR_downfolded, self.Rlist
126
+
127
+
66
128
  class JDownfolder_pickle:
67
129
  def __init__(
68
- self, inpath, metals, ligands, outpath, qmesh=[7, 7, 7], iso_only=False
130
+ self,
131
+ inpath,
132
+ metals,
133
+ ligands,
134
+ outpath,
135
+ qmesh=[7, 7, 7],
136
+ iso_only=False,
137
+ method="pwf",
138
+ **kwargs
69
139
  ):
70
140
  self.exc = SpinIO.load_pickle(path=inpath, fname="TB2J.pickle")
71
141
 
72
142
  self.iso_only = (self.exc.dmi_ddict is None) or iso_only
73
-
74
143
  self.metals = metals
75
144
  self.ligands = ligands
76
145
  self.outpath = outpath
146
+ self.method = method
77
147
 
78
148
  # read atomic structure
79
149
  self.atoms = self.exc.atoms
@@ -83,7 +153,8 @@ class JDownfolder_pickle:
83
153
  self.Rcut = None
84
154
  self._build_atom_index()
85
155
  self._prepare_distance()
86
- self._downfold()
156
+ Jd, Rlist = self._downfold(**kwargs)
157
+ self._Jd_to_exchange(Jd, Rlist)
87
158
 
88
159
  def _build_atom_index(self):
89
160
  self.magnetic_elements = self.metals
@@ -101,18 +172,33 @@ class JDownfolder_pickle:
101
172
  self.nL = len(self.iL)
102
173
  self.nsite = self.nM + self.nL
103
174
 
104
- def _downfold(self):
175
+ def _downfold(self, **kwargs):
105
176
  JR2 = self.exc.get_full_Jtensor_for_Rlist(asr=True)
106
- d = JDownfolder(
107
- JR2,
108
- self.exc.Rlist,
109
- iM=self.iM,
110
- iL=self.iL,
111
- qmesh=self.qmesh,
112
- iso_only=self.iso_only,
113
- )
114
- Jd = d.get_JR()
177
+ if self.method == "lowdin":
178
+ d = JDownfolder(
179
+ JR2,
180
+ self.exc.Rlist,
181
+ iM=self.iM,
182
+ iL=self.iL,
183
+ qmesh=self.qmesh,
184
+ iso_only=self.iso_only,
185
+ )
186
+ Jd, Rlist = d.get_JR()
187
+ else:
188
+ d = PWFDownfolder(
189
+ JR2,
190
+ self.exc.Rlist,
191
+ iM=self.iM,
192
+ iL=self.iL,
193
+ qmesh=self.qmesh,
194
+ atoms=self.atoms,
195
+ iso_only=self.iso_only,
196
+ **kwargs
197
+ )
198
+ Jd, Rlist = d.get_JR()
199
+ return Jd, Rlist
115
200
 
201
+ def _Jd_to_exchange(self, Jd, Rlist):
116
202
  self._prepare_distance()
117
203
  self._prepare_index_spin()
118
204
  self.Jdict = {}
@@ -123,7 +209,7 @@ class JDownfolder_pickle:
123
209
  self.DMIdict = {}
124
210
  self.Janidict = {}
125
211
 
126
- for iR, R in enumerate(d.Rlist):
212
+ for iR, R in enumerate(Rlist):
127
213
  for i, ispin in enumerate(self.index_spin):
128
214
  for j, jspin in enumerate(self.index_spin):
129
215
  if ispin >= 0 and jspin >= 0:
TB2J/Jtensor.py CHANGED
@@ -79,7 +79,7 @@ def combine_J_tensor(Jiso=0.0, D=np.zeros(3), Jani=np.zeros((3, 3), dtype=float)
79
79
  :param Jani: 3x3 matrix anisotropic exchange
80
80
  :returns: A 3x3 matrix, the exchange paraemter in tensor form.
81
81
  """
82
- Jtensor = np.zeros((3, 3), dtype=float)
82
+ Jtensor = np.zeros((3, 3), dtype=complex)
83
83
  if Jiso is not None:
84
84
  Jtensor += np.eye(3, dtype=float) * Jiso
85
85
  if Jani is not None:
TB2J/MAE.py ADDED
@@ -0,0 +1,188 @@
1
+ import numpy as np
2
+ from TB2J.abacus.abacus_wrapper import AbacusWrapper, AbacusParser
3
+ from TB2J.mathutils.rotate_spin import rotate_Matrix_from_z_to_axis
4
+ from TB2J.kpoints import monkhorst_pack
5
+ from TB2J.mathutils.fermi import fermi
6
+ from TB2J.mathutils.kR_convert import R_to_k
7
+ from scipy.linalg import eigh
8
+ from copy import deepcopy
9
+ from scipy.spatial.transform import Rotation
10
+ import matplotlib.pyplot as plt
11
+ from pathlib import Path
12
+ from TB2J.mathutils.rotate_spin import spherical_to_cartesian
13
+ from HamiltonIO.model.occupations import Occupations
14
+ #from TB2J.abacus.abacus_wrapper import AbacusSplitSOCParser
15
+ from HamiltonIO.abacus.abacus_wrapper import AbacusSplitSOCParser
16
+ from HamiltonIO.siesta import SislParser, SiestaHamiltonian
17
+ import tqdm
18
+
19
+
20
+ def get_occupation(evals, kweights, nel, width=0.1):
21
+ occ = Occupations(nel=nel, width=width, wk=kweights, nspin=2)
22
+ return occ.occupy(evals)
23
+
24
+
25
+ def get_density_matrix(evals=None, evecs=None, kweights=None, nel=None, width=0.1):
26
+ occ = get_occupation(evals, kweights, nel, width=width)
27
+ rho = np.einsum("kib, kb, kjb -> kij", evecs, occ, evecs.conj())
28
+ return rho
29
+
30
+
31
+ class MAE:
32
+ def __init__(self, model, kmesh, gamma=True, width=0.1, nel=None):
33
+ self.model = model
34
+ if nel is not None:
35
+ self.model.nel = nel
36
+ self.kpts = monkhorst_pack(kmesh, gamma_center=gamma)
37
+ self.kweights = np.ones(len(self.kpts), dtype=float) / len(self.kpts)
38
+ self.width = width
39
+
40
+ def get_band_energy(self):
41
+ evals, evecs = self.model.solve_all(self.kpts)
42
+ occ = get_occupation(evals, self.kweights, self.model.nel, width=self.width)
43
+ eband = np.sum(evals * occ * self.kweights[:, np.newaxis])
44
+ return eband
45
+
46
+ def calc_ref(self):
47
+ # calculate the Hk_ref, Sk_ref, Hk_soc_ref, and rho_ref
48
+ self.Sk_ref = R_to_k(self.kpts, self.model.Rlist, self.model.SR)
49
+ self.Hk_xc_ref = R_to_k(self.kpts, self.model.Rlist, self.model._HR_copy)
50
+ self.Hk_soc_ref = R_to_k(self.kpts, self.model.Rlist, self.model.HR_soc)
51
+ self.rho_ref = np.zeros(
52
+ (len(self.kpts), self.model.nbasis, self.model.nbasis), dtype=complex
53
+ )
54
+
55
+ evals = np.zeros((len(self.kpts), self.model.nbasis), dtype=float)
56
+ evecs = np.zeros(
57
+ (len(self.kpts), self.model.nbasis, self.model.nbasis), dtype=complex
58
+ )
59
+
60
+ for ik, kpt in enumerate(self.kpts):
61
+ # evals, evecs = eigh(self.Hk_xc_ref[ik]+self.Hk_soc_ref[ik], self.Sk_ref[ik])
62
+ evals[ik], evecs[ik] = eigh(self.Hk_xc_ref[ik], self.Sk_ref[ik])
63
+ occ = get_occupation(
64
+ evals, self.kweights, self.model.nel, width=self.model.width
65
+ )
66
+ # occ = fermi(evals, self.model.efermi, width=self.model.width)
67
+ self.rho_ref = np.einsum("kib, kb, kjb -> kij", evecs, occ, evecs.conj())
68
+
69
+ def get_band_energy_vs_angles(
70
+ self,
71
+ thetas,
72
+ phis,
73
+ ):
74
+ es = []
75
+ # es2 = []
76
+ # e,rho = self.model.get_band_energy(dm=True)
77
+ # self.calc_ref()
78
+ # thetas = np.linspace(*angle_range, npoints)
79
+ nangles = len(thetas)
80
+ for i in tqdm.trange(nangles):
81
+ theta = thetas[i]
82
+ phi = phis[i]
83
+ self.model.set_Hsoc_rotation_angle([theta, phi])
84
+ e = self.get_band_energy()
85
+ es.append(e)
86
+ # es2.append(e2)
87
+ return es
88
+
89
+
90
+ def get_model_energy(model, kmesh, gamma=True):
91
+ ham = MAE(model, kmesh, gamma=gamma)
92
+ return ham.get_band_energy()
93
+
94
+
95
+ def abacus_get_MAE(
96
+ path_nosoc, path_soc, kmesh, thetas, psis, gamma=True, outfile="MAE.txt", nel=None
97
+ ):
98
+ """Get MAE from Abacus with magnetic force theorem. Two calculations are needed. First we do an calculation with SOC but the soc_lambda is set to 0. Save the density. The next calculatin we start with the density from the first calculation and set the SOC prefactor to 1. With the information from the two calcualtions, we can get the band energy with magnetic moments in the direction, specified in two list, thetas, and phis."""
99
+ parser = AbacusSplitSOCParser(
100
+ outpath_nosoc=path_nosoc, outpath_soc=path_soc, binary=False
101
+ )
102
+ model = parser.parse()
103
+ ham = MAE(model, kmesh, gamma=gamma)
104
+ es = ham.get_band_energy_vs_angles(thetas, psis)
105
+ if outfile:
106
+ with open(outfile, "w") as f:
107
+ f.write("#theta, psi, energy\n")
108
+ for theta, psi, e in zip(thetas, psis, es):
109
+ f.write(f"{theta:5.3f}, {psi:5.3f}, {e:10.9f}\n")
110
+ return es
111
+
112
+
113
+ def siesta_get_MAE(fdf_fname, kmesh, thetas, phis, gamma=True, outfile="MAE.txt"):
114
+ """ """
115
+ model= SislParser(fdf_fname=fdf_fname, read_H_soc=True).get_model()
116
+ ham = MAE(model, kmesh, gamma=gamma)
117
+ es = ham.get_band_energy_vs_angles(thetas, phis)
118
+ if outfile:
119
+ with open(outfile, "w") as f:
120
+ f.write("#theta, psi, energy\n")
121
+ for theta, psi, e in zip(thetas, phis, es):
122
+ #f.write(f"{theta}, {psi}, {e}\n")
123
+ f.write(f"{theta:5.3f}, {psi:5.3f}, {e:10.9f}\n")
124
+ return es
125
+
126
+
127
+ def test_AbacusSplitSOCWrapper():
128
+ # path = Path("~/projects/2D_Fe").expanduser()
129
+ path = Path("~/projects/TB2Jflows/examples/2D_Fe/Fe_z").expanduser()
130
+ outpath_nosoc = f"{path}/soc0/OUT.ABACUS"
131
+ outpath_soc = f"{path}/soc1/OUT.ABACUS"
132
+ parser = AbacusSplitSOCParser(
133
+ outpath_nosoc=outpath_nosoc, outpath_soc=outpath_soc, binary=False
134
+ )
135
+ model = parser.parse()
136
+ kmesh = [6, 6, 1]
137
+
138
+ r = MAE(model, kmesh, gamma=True)
139
+ # thetas, es = r.get_band_energy_vs_theta(angle_range=(0, np.pi*2), rotation_axis="z", initial_direction=(1,0,0), npoints=21)
140
+ thetas, es, es2 = r.get_band_energy_vs_theta(
141
+ angle_range=(0, np.pi),
142
+ rotation_axis="y",
143
+ initial_direction=(0, 0, 1),
144
+ npoints=11,
145
+ )
146
+ # print the table of thetas and es, es2
147
+ for theta, e, e2 in zip(thetas, es, es2):
148
+ print(f"{theta=}, {e=}, {e2=}")
149
+
150
+ plt.plot(thetas / np.pi, es - es[0], marker="o")
151
+ plt.plot(thetas / np.pi, es2 - es2[0], marker=".")
152
+ plt.savefig("E_along_z_x_z.png")
153
+ plt.show()
154
+
155
+
156
+ def abacus_get_MAE_cli():
157
+ import argparse
158
+
159
+ parser = argparse.ArgumentParser(
160
+ description="Get MAE from Abacus with magnetic force theorem. Two calculations are needed. First we do an calculation with SOC but the soc_lambda is set to 0. Save the density. The next calculatin we start with the density from the first calculation and set the SOC prefactor to 1. With the information from the two calcualtions, we can get the band energy with magnetic moments in the direction, specified in two list, thetas, and phis. "
161
+ )
162
+ parser.add_argument("path_nosoc", type=str, help="Path to the calculation with ")
163
+ parser.add_argument("path_soc", type=str, help="Path to the SOC calculation")
164
+ parser.add_argument("thetas", type=float, nargs="+", help="Thetas")
165
+ parser.add_argument("psis", type=float, nargs="+", help="Phis")
166
+ parser.add_argument("kmesh", type=int, nargs=3, help="K-mesh")
167
+ parser.add_argument(
168
+ "--gamma", action="store_true", help="Use Gamma centered kpoints"
169
+ )
170
+ parser.add_argument(
171
+ "--outfile",
172
+ type=str,
173
+ help="The angles and the energey will be saved in this file.",
174
+ )
175
+ args = parser.parse_args()
176
+ abacus_get_MAE(
177
+ args.path_nosoc,
178
+ args.path_soc,
179
+ args.kmesh,
180
+ args.thetas,
181
+ args.psis,
182
+ gamma=args.gamma,
183
+ outfile=args.outfile,
184
+ )
185
+
186
+
187
+ if __name__ == "__main__":
188
+ abacus_get_MAE_cli()
TB2J/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.9.0"
1
+ __version__ = "0.9.0.1"