TB2J 0.9.0.3__py3-none-any.whl → 0.9.0.4__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.
@@ -0,0 +1,433 @@
1
+ import os
2
+ from TB2J.myTB import MyTB, merge_tbmodels_spin
3
+ import numpy as np
4
+ from TB2J.exchange import ExchangeNCL
5
+ from TB2J.exchangeCL2 import ExchangeCL2
6
+ from TB2J.exchange_qspace import ExchangeCLQspace
7
+ from TB2J.utils import read_basis, auto_assign_basis_name
8
+ from ase.io import read
9
+ from TB2J.sisl_wrapper import SislWrapper
10
+ from TB2J.gpaw_wrapper import GPAWWrapper
11
+ from TB2J.wannier import parse_atoms
12
+
13
+
14
+ def gen_exchange(
15
+ path,
16
+ colinear=True,
17
+ groupby="spin",
18
+ posfile=None,
19
+ prefix_up="wannier90.up",
20
+ prefix_dn="wannier90.dn",
21
+ prefix_SOC="wannier90",
22
+ min_hopping_norm=1e-4,
23
+ max_distance=None,
24
+ efermi=0,
25
+ magnetic_elements=[],
26
+ kmesh=[4, 4, 4],
27
+ emin=-12.0,
28
+ emax=0.0,
29
+ nz=100,
30
+ exclude_orbs=[],
31
+ Rcut=None,
32
+ ne=None,
33
+ use_cache=False,
34
+ np=1,
35
+ output_path="TB2J_results",
36
+ wannier_type="wannier90",
37
+ qspace=False,
38
+ orb_decomposition=False,
39
+ write_density_matrix=False,
40
+ description="",
41
+ ):
42
+ try:
43
+ fname = os.path.join(path, posfile)
44
+ print(f"Reading atomic structure from file {fname}.")
45
+ atoms = read(os.path.join(path, posfile))
46
+ except Exception:
47
+ print(
48
+ f"Cannot read atomic structure from file {fname}. Trying to read from Wannier input."
49
+ )
50
+ if colinear:
51
+ fname = os.path.join(path, f"{prefix_up}.win")
52
+ else:
53
+ fname = os.path.join(path, f"{prefix_SOC}.win")
54
+
55
+ print(f"Reading atomic structure from file {fname}.")
56
+ atoms = parse_atoms(fname)
57
+
58
+ basis_fname = os.path.join(path, "basis.txt")
59
+ if colinear:
60
+ if wannier_type.lower() == "wannier90":
61
+ print("Reading Wannier90 hamiltonian: spin up.")
62
+ tbmodel_up = MyTB.read_from_wannier_dir(
63
+ path=path, prefix=prefix_up, atoms=atoms, nls=False
64
+ )
65
+ print("Reading Wannier90 hamiltonian: spin down.")
66
+ tbmodel_dn = MyTB.read_from_wannier_dir(
67
+ path=path, prefix=prefix_dn, atoms=atoms, nls=False
68
+ )
69
+ if os.path.exists(basis_fname):
70
+ basis = read_basis(basis_fname)
71
+ else:
72
+ basis, _ = auto_assign_basis_name(
73
+ tbmodel_up.xred,
74
+ atoms,
75
+ write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
76
+ )
77
+ elif wannier_type.lower() == "banddownfolder":
78
+ print("Reading Banddownfolder hamiltonian: spin up.")
79
+ tbmodel_up = MyTB.load_banddownfolder(
80
+ path=path, prefix=prefix_up, atoms=atoms, nls=False
81
+ )
82
+ print("Reading Banddownfolder hamiltonian: spin down.")
83
+ tbmodel_dn = MyTB.load_banddownfolder(
84
+ path=path, prefix=prefix_dn, atoms=atoms, nls=False
85
+ )
86
+
87
+ basis, _ = auto_assign_basis_name(
88
+ tbmodel_up.xred,
89
+ atoms,
90
+ write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
91
+ )
92
+ else:
93
+ raise ValueError("wannier_type should be Wannier90 or banddownfolder.")
94
+
95
+ print("Starting to calculate exchange.")
96
+ description = f""" Input from collinear Wannier90 data.
97
+ Tight binding data from {path}.
98
+ Prefix of wannier function files:{prefix_up} and {prefix_dn}.
99
+ Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
100
+ \n"""
101
+ if not qspace:
102
+ exchange = ExchangeCL2(
103
+ tbmodels=(tbmodel_up, tbmodel_dn),
104
+ atoms=atoms,
105
+ basis=basis,
106
+ efermi=efermi,
107
+ magnetic_elements=magnetic_elements,
108
+ kmesh=kmesh,
109
+ emin=emin,
110
+ emax=emax,
111
+ nz=nz,
112
+ exclude_orbs=exclude_orbs,
113
+ Rcut=Rcut,
114
+ ne=ne,
115
+ np=np,
116
+ use_cache=use_cache,
117
+ output_path=output_path,
118
+ write_density_matrix=write_density_matrix,
119
+ description=description,
120
+ )
121
+ else:
122
+ exchange = ExchangeCLQspace(
123
+ tbmodels=(tbmodel_up, tbmodel_dn),
124
+ atoms=atoms,
125
+ basis=basis,
126
+ efermi=efermi,
127
+ magnetic_elements=magnetic_elements,
128
+ kmesh=kmesh,
129
+ emin=emin,
130
+ emax=emax,
131
+ nz=nz,
132
+ exclude_orbs=exclude_orbs,
133
+ Rcut=Rcut,
134
+ ne=ne,
135
+ np=np,
136
+ use_cache=use_cache,
137
+ output_path=output_path,
138
+ write_density_matrix=write_density_matrix,
139
+ description=description,
140
+ )
141
+
142
+ exchange.run(path=output_path)
143
+ print("All calculation finsihed. The results are in TB2J_results directory.")
144
+
145
+ elif colinear and wannier_type.lower() == "banddownfolder":
146
+ print("Reading Wannier90 hamiltonian: spin up.")
147
+ tbmodel_up = MyTB.read_from_wannier_dir(
148
+ path=path, prefix=prefix_up, atoms=atoms, groupby=None, nls=False
149
+ )
150
+ print("Reading Wannier90 hamiltonian: spin down.")
151
+ tbmodel_dn = MyTB.read_from_wannier_dir(
152
+ path=path, prefix=prefix_dn, atoms=atoms, groupby=None, nls=False
153
+ )
154
+ tbmodel = merge_tbmodels_spin(tbmodel_up, tbmodel_dn)
155
+ basis, _ = auto_assign_basis_name(
156
+ tbmodel.xred,
157
+ atoms,
158
+ write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
159
+ )
160
+ description = f""" Input from collinear BandDownfolder data.
161
+ Tight binding data from {path}.
162
+ Prefix of wannier function files:{prefix_up} and {prefix_dn}.
163
+ Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
164
+ \n"""
165
+ print("Starting to calculate exchange.")
166
+ exchange = ExchangeCL2(
167
+ tbmodels=tbmodel,
168
+ atoms=atoms,
169
+ basis=basis,
170
+ efermi=efermi,
171
+ magnetic_elements=magnetic_elements,
172
+ kmesh=kmesh,
173
+ emin=emin,
174
+ emax=emax,
175
+ nz=nz,
176
+ exclude_orbs=exclude_orbs,
177
+ Rcut=Rcut,
178
+ ne=ne,
179
+ np=np,
180
+ use_cache=use_cache,
181
+ output_path=output_path,
182
+ write_density_matrix=write_density_matrix,
183
+ description=description,
184
+ )
185
+ exchange.run(path=output_path)
186
+ print("All calculation finsihed. The results are in TB2J_results directory.")
187
+ else:
188
+ print("Reading Wannier90 hamiltonian: non-colinear spin.")
189
+ groupby = groupby.lower().strip()
190
+ if groupby not in ["spin", "orbital"]:
191
+ raise ValueError("groupby can only be spin or orbital.")
192
+ tbmodel = MyTB.read_from_wannier_dir(
193
+ path=path, prefix=prefix_SOC, atoms=atoms, groupby=groupby, nls=True
194
+ )
195
+ if os.path.exists(basis_fname):
196
+ print("The use of basis file is deprecated. It will be ignored.")
197
+ # basis = read_basis(basis_fname)
198
+ else:
199
+ basis, _ = auto_assign_basis_name(
200
+ tbmodel.xred,
201
+ atoms,
202
+ write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
203
+ )
204
+ description = f""" Input from non-collinear Wannier90 data.
205
+ Tight binding data from {path}.
206
+ Prefix of wannier function files:{prefix_SOC}.
207
+ Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
208
+ The DMI component parallel to the spin orientation, the Jani which has the component of that orientation should be disregarded
209
+ e.g. if the spins are along z, the xz, yz, zz, zx, zy components and the z component of DMI.
210
+ If you need these component, try to do three calculations with spin along x, y, z, or use structure with z rotated to x, y and z. And then use TB2J_merge.py to get the full set of parameters.
211
+
212
+ \n"""
213
+ print("Starting to calculate exchange.")
214
+ exchange = ExchangeNCL(
215
+ tbmodels=tbmodel,
216
+ atoms=atoms,
217
+ basis=basis,
218
+ efermi=efermi,
219
+ magnetic_elements=magnetic_elements,
220
+ kmesh=kmesh,
221
+ emin=emin,
222
+ emax=emax,
223
+ nz=nz,
224
+ exclude_orbs=exclude_orbs,
225
+ Rcut=Rcut,
226
+ ne=ne,
227
+ np=np,
228
+ use_cache=use_cache,
229
+ description=description,
230
+ output_path=output_path,
231
+ write_density_matrix=write_density_matrix,
232
+ orb_decomposition=orb_decomposition,
233
+ )
234
+ print("\n")
235
+ exchange.run(path=output_path)
236
+ print(f"All calculation finsihed. The results are in {output_path} directory.")
237
+
238
+
239
+ def gen_exchange_siesta(
240
+ fdf_fname,
241
+ magnetic_elements=[],
242
+ include_orbs=None,
243
+ kmesh=[5, 5, 5],
244
+ emin=-12.0,
245
+ emax=0.0,
246
+ nz=100,
247
+ exclude_orbs=[],
248
+ Rcut=None,
249
+ ne=None,
250
+ np=1,
251
+ use_cache=False,
252
+ output_path="TB2J_results",
253
+ orb_decomposition=False,
254
+ description="",
255
+ ):
256
+ try:
257
+ import sisl
258
+ except:
259
+ raise ImportError("sisl cannot be imported. Please install sisl first.")
260
+
261
+ from packaging import version
262
+
263
+ if version.parse(sisl.__version__) <= version.parse("0.10.0"):
264
+ raise ImportError(
265
+ f"sisl version is {sisl.__version__}, but should be larger than 0.10.0."
266
+ )
267
+
268
+ include_orbs = {}
269
+ if isinstance(magnetic_elements, str):
270
+ magnetic_elements = [magnetic_elements]
271
+ for element in magnetic_elements:
272
+ if "_" in element:
273
+ elem = element.split("_")[0]
274
+ orb = element.split("_")[1:]
275
+ include_orbs[elem] = orb
276
+ else:
277
+ include_orbs[element] = None
278
+ magnetic_elements = list(include_orbs.keys())
279
+
280
+ fdf = sisl.get_sile(fdf_fname)
281
+ # geom = fdf.read_geometry()
282
+ H = fdf.read_hamiltonian()
283
+ geom = H.geometry
284
+ if H.spin.is_colinear:
285
+ print("Reading Siesta hamiltonian: colinear spin.")
286
+ tbmodel_up = SislWrapper(H, spin=0, geom=geom)
287
+ tbmodel_dn = SislWrapper(H, spin=1, geom=geom)
288
+ basis = dict(zip(tbmodel_up.orbs, list(range(tbmodel_up.norb))))
289
+ print("Starting to calculate exchange.")
290
+ description = f""" Input from collinear Siesta data.
291
+ working directory: {os.getcwd()}
292
+ fdf_fname: {fdf_fname}.
293
+ \n"""
294
+ exchange = ExchangeCL2(
295
+ tbmodels=(tbmodel_up, tbmodel_dn),
296
+ atoms=tbmodel_up.atoms,
297
+ basis=basis,
298
+ efermi=0.0,
299
+ magnetic_elements=magnetic_elements,
300
+ include_orbs=include_orbs,
301
+ kmesh=kmesh,
302
+ emin=emin,
303
+ emax=emax,
304
+ nz=nz,
305
+ exclude_orbs=exclude_orbs,
306
+ Rcut=Rcut,
307
+ ne=ne,
308
+ np=np,
309
+ use_cache=use_cache,
310
+ output_path=output_path,
311
+ description=description,
312
+ )
313
+ exchange.run(path=output_path)
314
+ print("\n")
315
+ print(f"All calculation finsihed. The results are in {output_path} directory.")
316
+
317
+ elif H.spin.is_colinear and False:
318
+ print(
319
+ "Reading Siesta hamiltonian: colinear spin. Treat as non-colinear. For testing only."
320
+ )
321
+ tbmodel = SislWrapper(H, spin="merge", geom=geom)
322
+ basis = dict(zip(tbmodel.orbs, list(range(tbmodel.nbasis))))
323
+ print("Starting to calculate exchange.")
324
+ description = f""" Input from collinear Siesta data.
325
+ working directory: {os.getcwd()}
326
+ fdf_fname: {fdf_fname}.
327
+ \n"""
328
+ exchange = ExchangeNCL(
329
+ tbmodels=tbmodel,
330
+ atoms=tbmodel.atoms,
331
+ basis=basis,
332
+ efermi=0.0,
333
+ magnetic_elements=magnetic_elements,
334
+ include_orbs=include_orbs,
335
+ kmesh=kmesh,
336
+ emin=emin,
337
+ emax=emax,
338
+ nz=nz,
339
+ exclude_orbs=exclude_orbs,
340
+ Rcut=Rcut,
341
+ ne=ne,
342
+ np=np,
343
+ use_cache=use_cache,
344
+ description=description,
345
+ output_path=output_path,
346
+ orb_decomposition=orb_decomposition,
347
+ )
348
+ exchange.run(path=output_path)
349
+ print("\n")
350
+ print(f"All calculation finsihed. The results are in {output_path} directory.")
351
+
352
+ elif H.spin.is_spinorbit or H.spin.is_noncolinear:
353
+ print("Reading Siesta hamiltonian: non-colinear spin.")
354
+ tbmodel = SislWrapper(H, spin=None, geom=geom)
355
+ basis = dict(zip(tbmodel.orbs, list(range(tbmodel.nbasis))))
356
+ print("Starting to calculate exchange.")
357
+ description = f""" Input from non-collinear Siesta data.
358
+ working directory: {os.getcwd()}
359
+ fdf_fname: {fdf_fname}.
360
+ Warning: The DMI component parallel to the spin orientation, the Jani which has the component of that orientation should be disregarded
361
+ e.g. if the spins are along z, the xz, yz, zz, zx, zy components and the z component of DMI.
362
+ If you need these component, try to do three calculations with spin along x, y, z, or use structure with z rotated to x, y and z. And then use TB2J_merge.py to get the full set of parameters.
363
+ \n"""
364
+ exchange = ExchangeNCL(
365
+ tbmodels=tbmodel,
366
+ atoms=tbmodel.atoms,
367
+ basis=basis,
368
+ efermi=0.0,
369
+ magnetic_elements=magnetic_elements,
370
+ include_orbs=include_orbs,
371
+ kmesh=kmesh,
372
+ emin=emin,
373
+ emax=emax,
374
+ nz=nz,
375
+ exclude_orbs=exclude_orbs,
376
+ Rcut=Rcut,
377
+ ne=ne,
378
+ np=np,
379
+ use_cache=use_cache,
380
+ description=description,
381
+ output_path=output_path,
382
+ orb_decomposition=orb_decomposition,
383
+ )
384
+ exchange.run(path=output_path)
385
+ print("\n")
386
+ print(f"All calculation finsihed. The results are in {output_path} directory.")
387
+
388
+
389
+ def gen_exchange_gpaw(
390
+ gpw_fname,
391
+ magnetic_elements=[],
392
+ kmesh=[3, 3, 3],
393
+ emin=-12.0,
394
+ emax=0.0,
395
+ nz=50,
396
+ exclude_orbs=[],
397
+ Rcut=None,
398
+ use_cache=False,
399
+ output_path="TB2J_results",
400
+ description="",
401
+ ):
402
+ print("Reading from GPAW data and calculate electronic structure.")
403
+ model = GPAWWrapper(gpw_fname=gpw_fname)
404
+ efermi = model.calc.get_fermi_level()
405
+ print(f"Fermi Energy: {efermi}")
406
+ poses = np.vstack([model.positions, model.positions])
407
+ basis, _ = auto_assign_basis_name(
408
+ poses,
409
+ model.atoms,
410
+ write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
411
+ )
412
+
413
+ if model.calc.get_spin_polarized():
414
+ print("Starting to calculate exchange.")
415
+ exchange = ExchangeNCL(
416
+ tbmodels=model,
417
+ atoms=model.atoms,
418
+ efermi=efermi,
419
+ basis=basis,
420
+ magnetic_elements=magnetic_elements,
421
+ kmesh=kmesh,
422
+ emin=emin,
423
+ emax=emax,
424
+ nz=nz,
425
+ exclude_orbs=exclude_orbs,
426
+ Rcut=Rcut,
427
+ use_cache=use_cache,
428
+ output_path=output_path,
429
+ description=description,
430
+ )
431
+ exchange.run(path=output_path)
432
+ print("\n")
433
+ print(f"All calculation finsihed. The results are in {output_path} directory.")
TB2J/manager.py CHANGED
@@ -9,6 +9,29 @@ from ase.io import read
9
9
  from TB2J.sisl_wrapper import SislWrapper
10
10
  from TB2J.gpaw_wrapper import GPAWWrapper
11
11
  from TB2J.wannier import parse_atoms
12
+ from dataclasses import dataclass
13
+
14
+
15
+ @dataclass
16
+ class TB2JParams:
17
+ colinear: bool = True
18
+ efermi: float = 0
19
+ magnetic_elements = []
20
+ kmesh = [4, 4, 4]
21
+ emin: float = -12.0
22
+ emax: float = 0.0
23
+ nz: int = 100
24
+ exclude_orbs = []
25
+ Rcut: float = None
26
+ ne: int = None
27
+ use_cache: bool = False
28
+ np: int = 1
29
+ output_path: str = "TB2J_results"
30
+ wannier_type: str = "wannier90"
31
+ qspace: bool = False
32
+ orb_decomposition: bool = False
33
+ write_density_matrix: bool = False
34
+ description: str = ""
12
35
 
13
36
 
14
37
  def gen_exchange(
@@ -94,7 +117,7 @@ def gen_exchange(
94
117
 
95
118
  print("Starting to calculate exchange.")
96
119
  description = f""" Input from collinear Wannier90 data.
97
- Tight binding data from {path}.
120
+ Tight binding data from {path}.
98
121
  Prefix of wannier function files:{prefix_up} and {prefix_dn}.
99
122
  Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
100
123
  \n"""
@@ -158,7 +181,7 @@ Warning: Please check if the noise level of Wannier function Hamiltonian to make
158
181
  write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
159
182
  )
160
183
  description = f""" Input from collinear BandDownfolder data.
161
- Tight binding data from {path}.
184
+ Tight binding data from {path}.
162
185
  Prefix of wannier function files:{prefix_up} and {prefix_dn}.
163
186
  Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
164
187
  \n"""
@@ -202,7 +225,7 @@ Warning: Please check if the noise level of Wannier function Hamiltonian to make
202
225
  write_basis_file=os.path.join(output_path, "assigned_basis.txt"),
203
226
  )
204
227
  description = f""" Input from non-collinear Wannier90 data.
205
- Tight binding data from {path}.
228
+ Tight binding data from {path}.
206
229
  Prefix of wannier function files:{prefix_SOC}.
207
230
  Warning: Please check if the noise level of Wannier function Hamiltonian to make sure it is much smaller than the exchange values.
208
231
  The DMI component parallel to the spin orientation, the Jani which has the component of that orientation should be disregarded
TB2J/patch.py ADDED
@@ -0,0 +1,50 @@
1
+ import types
2
+ from unittest import mock
3
+
4
+ class A(object):#but seems to work for old style objects too
5
+ def funcx(self,x):
6
+ print("x1=",x)
7
+ print("called from", self)
8
+
9
+ def method(self,x):
10
+ print("xmethod=",x)
11
+ print("called from", self)
12
+
13
+ def patch_me(target):
14
+ def method(target,x):
15
+ print("x=",x)
16
+ print("called from", target)
17
+ target.method = types.MethodType(method,target)
18
+
19
+ def method(self,x):
20
+ print("x=",x)
21
+ print("called from", self)
22
+
23
+ @mock.patch("__main__.A")
24
+ def funcx(self,x):
25
+ print("new x=",x)
26
+ print("called from", self)
27
+
28
+ A.method=method
29
+ #add more if needed
30
+ a = A()
31
+ print(A.__dict__)
32
+ print(a)
33
+ #out: <__main__.A object at 0x2b73ac88bfd0>
34
+
35
+ @mock.patch("__main__.a")
36
+ def funcx(self,x):
37
+ print("x=",x)
38
+ print("called from", self)
39
+
40
+ a.funcx(3)
41
+ patch_me(a) #patch instance
42
+ a.method=method
43
+ #a.method(5)
44
+ #out: x= 5
45
+ #out: called from <__main__.A object at 0x2b73ac88bfd0>
46
+ patch_me(A)
47
+
48
+ a.method(6) #can patch class too
49
+ #out: x= 6
50
+ #out: called from <class '__main__.A'>
@@ -0,0 +1,68 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import aiida
4
+ from aiida_tb2j.data import ExchangeData
5
+
6
+ def plot_dispersion(bands, kpoint_labels, color='blue', title=None):
7
+
8
+ fig, axs = plt.subplots(1, 1, constrained_layout=True)
9
+ fig.set_size_inches(6, 6/1.618)
10
+
11
+ '''
12
+ Plot the bands
13
+ '''
14
+ kpoints = np.arange(len(bands))
15
+ axs.plot(kpoints, bands, color=color, linewidth=1.5)
16
+
17
+ '''
18
+ Plot the symmetry points
19
+ '''
20
+ bmin = bands.min(); bmax = bands.max()
21
+ ymin = bmin - 0.05*np.abs(bmin-bmax); ymax = bmax + 0.05*np.abs(bmax-bmin);
22
+ axs.set_xticks(kpoint_labels[0], kpoint_labels[1], fontsize=10)
23
+ axs.vlines(x=kpoint_labels[0], ymin=ymin, ymax=ymax, color='black', linewidth=0.5)
24
+ axs.set_xlim([0, len(kpoints)])
25
+ axs.set_ylim([ymin, ymax])
26
+
27
+ if title is not None:
28
+ plt.title(title, fontsize=10)
29
+
30
+ plt.show()
31
+
32
+
33
+ if __name__ == "__main__":
34
+
35
+ from argparse import ArgumentParser
36
+
37
+ parser = ArgumentParser()
38
+ parser.add_argument('-f', '--pickle_filename', type=str, help="Path of the 'TB2J.pickle' file.", required=True)
39
+ args = parser.parse_args()
40
+
41
+ '''
42
+ Right now the implementation depends on AiiDA and so we must create and load an AiiDA profile,
43
+ even if we do not store any information on a data base.
44
+ '''
45
+ aiida.load_profile()
46
+ '''
47
+ Create an ExchangeData object with the informations from the TB2J.pickle file
48
+ '''
49
+ exchange = ExchangeData.load_tb2j(pickle_file=args.pickle_filename, isotropic=False, pbc=(True, True, True))
50
+ '''
51
+ Compute the magnon band structure along a high symmetry path generated with
52
+ the ASE package. The informations is stored in an AiiDA BandsData object.
53
+ Here tol is the symmetry tolerance to determine the space group of the system.
54
+ They are in units of eV
55
+ '''
56
+ magnon_data = exchange.get_magnon_bands(npoints=300, tol=1e-1, with_DMI=True, with_Jani=True)
57
+ magnon_bands = 1000*magnon_data.get_bands() # Convert to meV
58
+ raw_labels = [(k, '$\Gamma$') if s == 'GAMMA' else (k, s) for k, s in magnon_data.labels]
59
+ kpoint_labels = list( zip( *raw_labels ) )
60
+ plot_dispersion(magnon_bands, kpoint_labels, color='blue', title='Magnon Bands')
61
+ '''
62
+ We can also obtain the dynamical matrix h instead of the actual magnon bands. The result
63
+ is stored in a numpy array with shape (number of kpoints, 2*natoms, 2*natoms)
64
+ '''
65
+ kpoints = magnon_data.get_kpoints() # The shape of the kpoints must be (nkpoints, 3)
66
+ h_matrix = 1000*exchange._H_matrix(kpoints, with_DMI=True, with_Jani=True) # Convert to meV
67
+ h_dispersion = np.linalg.eigvalsh(h_matrix) # We can also get the eigenvectors with np.linalg.eigh
68
+ plot_dispersion(h_dispersion, kpoint_labels, color='red', title='h matrix dispersion')
@@ -0,0 +1,79 @@
1
+ import numpy as np
2
+ from aiida_tb2j.data import ExchangeData
3
+ from aiida_tb2j.data.exchange import get_rotation_arrays
4
+ from itertools import combinations_with_replacement
5
+
6
+ ux, uy, uz = np.eye(3).reshape((3, 1, 3))
7
+
8
+ def combine_arrays(u, v):
9
+
10
+ return np.concatenate([u*v, np.roll(u, -1, axis=-1)*v, np.roll(v, -1, axis=-1)*u], axis=-1)
11
+
12
+ def get_coefficients(magmoms, indices):
13
+
14
+ i, j = indices
15
+
16
+ U, V = zip(*[get_rotation_arrays(magmoms, u=u) for u in [ux, uy, uz]])
17
+ U = np.stack(U).swapaxes(0, 1)
18
+ V = np.stack(V).swapaxes(0, 1)
19
+
20
+ uc = combine_arrays(U[i], U[j].conj())
21
+ ur = combine_arrays(U[i], U[j])
22
+ uc2 = combine_arrays(U[i].conj(), U[j])
23
+ u = np.concatenate([uc, ur, uc2], axis=1)
24
+
25
+ return u, V
26
+
27
+ def get_C(H0, u, V):
28
+
29
+ n = int(H0.shape[-1]/2)
30
+ upi = np.triu_indices(n)
31
+ dig = np.diag_indices(n)
32
+
33
+ i, j = upi
34
+ AB0 = H0[:, [i, i, i+n], [j, j+n, j+n]]
35
+ AB0 = np.swapaxes(AB0, 0, 2).reshape(len(i), 9)
36
+ J0_flat = np.linalg.solve(u, AB0)
37
+
38
+ J0 = np.empty((n, n, 3, 3), dtype=complex)
39
+ J0[*upi] = J0_flat[:, [0, 6, 5, 3, 1, 7, 8, 4, 2]].reshape(-1, 3, 3)
40
+ J0 += J0.swapaxes(0, 1)
41
+ J0[*dig] = 0.0
42
+
43
+ C = np.array([np.diag(a) for a in np.einsum('imx,ijxy,jmy->mi', V, 2*J0, V)])
44
+
45
+ return C
46
+
47
+ def get_J(H, kpoints, exchange):
48
+
49
+ n = int(H.shape[-1]/2)
50
+ upi = np.triu_indices(n)
51
+ dig = np.diag_indices(n)
52
+ i, j = upi
53
+
54
+ magmoms = exchange.magmoms()[np.unique(exchange.pairs)]
55
+ magmoms /= np.linalg.norm(magmoms, axis=-1).reshape(-1, 1)
56
+ u, V = get_coefficients(magmoms, indices=upi)
57
+
58
+ H0 = np.stack([1000*exchange._H_matrix(kpoints=np.zeros((1, 3)), with_DMI=True, with_Jani=True, u=u) for u in [ux, uy, uz]])[:, 0, :, :]
59
+ C = get_C(H0, u, V)
60
+ H[:, :, :n, :n] += C.reshape(3, 1, n, n)
61
+ H[:, :, n:, n:] += C.reshape(3, 1, n, n)
62
+
63
+ AB = H[:, :, [i, i, i+n], [j, j+n, j+n]]
64
+ AB[:, :, 2, :] = AB[:, ::-1, 2, :]
65
+ AB = np.moveaxis(AB, [2, 3], [1, 0]).reshape(len(i), 9, -1)
66
+
67
+ vectors = exchange.get_vectors()
68
+ exp_summand = np.exp( -2j*np.pi*vectors @ kpoints.T )
69
+ nAB = np.einsum('nik,ndk->nid', AB, exp_summand) / len(kpoints)
70
+
71
+ ii = np.where(i == j)
72
+ i0 = np.where(np.linalg.norm(vectors, axis=-1) == 0.0)
73
+ J = np.linalg.solve(u, nAB).swapaxes(1, 2)
74
+ J = J[:, :, [0, 6, 5, 3, 1, 7, 8, 4, 2]].reshape(len(i), -1, 3, 3)
75
+ J *= -1
76
+ J[ii] *= 2
77
+ J[i0] *= 0
78
+
79
+ return J