Examples by application
Each example below includes its Python source code, a download link
and a link to module documentation. The examples come directly from
src/ase2sprkkr/examples/ so the displayed code follows the source.
For a first calculation, follow First calculation: aluminium SCF and DOS. They demonstrate API use rather than numerically converged reference calculations. Some require additional programs or optional Python packages. Review numerical parameters before using them in production. For scientific assumptions and parameter convergence, consult the SPR-KKR manual.
The command-line interface can list, show and copy the same examples:
ase2sprkkr example
ase2sprkkr example --regex 'Fe|DOS'
ase2sprkkr example 1
ase2sprkkr example 1 --copy ./my-example
A01_Fe_scf_simple
Simple SCF calculation for bcc Fe.
Copy the example:
ase2sprkkr example 1 --copy ./my-example
1"""
2Simple SCF calculation for bcc Fe.
3"""
4
5
6def main():
7 from ase.build import bulk
8 from ase2sprkkr.sprkkr.calculator import SPRKKR
9
10 # Create structure
11 atoms = bulk("Fe")
12
13 # choose sprkkr calculator
14 calculator = SPRKKR(atoms=atoms, mpi=["mpirun", "-np", "4"])
15
16 # perform scf calculations
17 out = calculator.calculate()
18 # out object includes results
19 print(out.energy)
20 print(len(out.iterations))
21 print(out.iterations[-1]["error"]())
22 print(out.last_iteration["moment"])
23
24
25# Just run the script only when directly called from command line
26
27if __name__ == "__main__":
28 main()
A02_Fe_scf_input_modifications
Demonstration how to chage input SPRKKR file.
Copy the example:
ase2sprkkr example 2 --copy ./my-example
1"""
2Demonstration how to chage input SPRKKR file.
3"""
4
5
6def main():
7 from ase.build import bulk
8 from ase2sprkkr.sprkkr.calculator import SPRKKR
9
10 atoms = bulk("Fe")
11
12 calculator = SPRKKR(atoms=atoms, mpi=["mpirun", "-np", "4"])
13 # print out input parameters. This will be used when calling
14 # calculator to create corresponding input file. Please note
15 # that potential filename will be set by method calculate
16 print("ORIGINAL INPUT PARAMETERS==================")
17 print(calculator.input_parameters.to_dict())
18 print("===========================================")
19 # There are several way to modify parameters
20 # Lets modify l-expanstion (this will nodify first occurence of NL)
21 calculator.input_parameters.set(NL=3)
22 calculator.input_parameters.set(NE=32)
23 # Lest also change mixing
24 calculator.input_parameters.SCF.MIX = 0.20
25 calculator.input_parameters.ENERGY.ImE = 0.0
26 # calculator.input_parameters.ENERGY.GRID=[5,3]
27 print("NEW INPUT PARAMETERS=======================")
28 print(calculator.input_parameters.to_dict())
29 print("===========================================")
30 out = calculator.calculate()
31 print(out.energy)
32 print(len(out.iterations))
33 print(out.iterations[-1]["error"])
34 print(out.last_iteration["moment"])
35
36
37# Just run the script only when directly called from command line
38
39if __name__ == "__main__":
40 main()
A03_Fe_dos
SCF calculation for Fe using kkrscf and consequent DOS by kkrgen.
Copy the example:
ase2sprkkr example 3 --copy ./my-example
1"""
2SCF calculation for Fe using kkrscf and consequent DOS by kkrgen.
3"""
4
5
6def main():
7 from ase.build import bulk
8 from ase2sprkkr.sprkkr.calculator import SPRKKR
9
10 atoms = bulk("Fe")
11
12 print("FIRST STEP: SELF CONSISTENT CALCULATIONS====")
13 calculator = SPRKKR(atoms=atoms, mpi=True)
14 calculator.input_parameters.set(NL=3)
15 calculator.input_parameters.SCF.MIX = 0.20
16 calculator.input_parameters.ENERGY.ImE = 0.0
17 calculator.input_parameters.ENERGY.GRID = [5, 3]
18 calculator.input_parameters.set(NE=32)
19 out = calculator.calculate(options={"NITER": 1})
20
21 print(out.energy)
22 print(len(out.iterations))
23 print(out.iterations[-1]["error"]())
24 print(out.last_iteration["moment"].to_dict())
25 print("SECOND (OPTIONAL) STEP: CALCULATION OF BSF============")
26 calculator = out.calculator
27 calculator.input_parameters = "bsfek"
28 calculator.input_parameters.ENERGY.EMAX = 0.2
29 calculator.input_parameters.TASK.KPATH = 1
30 calculator.calculate()
31
32 print("THIRD STEP: CALCULATION OF DOS============")
33 # Lets now calculate DOS
34 # First we need to change task (there are several input data tabulated for
35 # various tasks to help user.
36 calculator.input_parameters = "DOS"
37 print("INPUT PARAMETERS HAVE BEEN REPLACED =======")
38 print(calculator.input_parameters.to_dict())
39 print("===========================================")
40
41 calculator.input_parameters.set(NE=300)
42 calculator.input_parameters.set(NL=3)
43
44 # Pass a newly converged potential to the DOS calculation
45 out = calculator.calculate(potential=out.potential_filename)
46 out.dos.plot()
47
48 # For the processing of the results of the DOS task use xband
49 # calculator.run_xband()
50
51
52# Just run the script only when directly called from command line
53
54if __name__ == "__main__":
55 main()
A04_CPA_Example
Ni Doped SrTiO3 as calculated by the CPA method. This example demonstrate partial occupations.
Copy the example:
ase2sprkkr example 4 --copy ./my-example
1"""
2Ni Doped SrTiO3 as calculated by the CPA method. This example demonstrate partial occupations.
3"""
4
5
6def main():
7 from ase.lattice.tetragonal import SimpleTetragonalFactory
8 from ase2sprkkr.sprkkr.calculator import SPRKKR
9 from ase2sprkkr.sprkkr.sprkkr_atoms import SPRKKRAtoms
10
11 # Define a Perovskite Factory class
12 class PerovskiteFactory(SimpleTetragonalFactory):
13 bravais_basis = [[0, 0, 0.0], [0.5, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0], [0.5, 0.0, 0.5]]
14 element_basis = (0, 1, 2, 2, 2)
15
16 Perovskite = PerovskiteFactory()
17
18 # Generate the base STO cell
19 a0 = 3.905
20 STO = Perovskite(("Sr", "Ti", "O"), latticeconstant={"a": a0, "c/a": 1.0}, size=(1, 1, 1))
21
22 # First we create new child of the atoms object which includes occupations
23 atoms = SPRKKRAtoms.promote_ase_atoms(STO)
24 atoms.sites[1].occupation.set({"Ti": 0.99, "Ni": 0.01})
25
26 calculator = SPRKKR(atoms=atoms, mpi=["mpirun", "-np", "4"])
27 calculator.input_parameters.set(NKTAB=50)
28 calculator.input_parameters.set(NL=3)
29 calculator.input_parameters.set(NE=32)
30 calculator.input_parameters.set(NITER=20)
31 calculator.input_parameters.SCF.MIX = 0.01
32 calculator.input_parameters.ENERGY.ImE = 0.0
33 calculator.input_parameters.ENERGY.GRID = 5
34 out = calculator.calculate()
35 print(out.energy)
36 print(len(out.iterations))
37 print(out.iterations[-1]["error"])
38 print(out.last_iteration["moment"])
39
40
41# Just run the script only when directly called from command line
42
43if __name__ == "__main__":
44 main()
A05_Al_EOS
Total energy SCF calculations as a function of Volume and corresponding equation of state fiting.
Copy the example:
ase2sprkkr example 5 --copy ./my-example
1"""Total energy SCF calculations as a function of Volume and corresponding
2equation of state fiting."""
3
4def main():
5
6 from ase.build import bulk
7 from ase2sprkkr.sprkkr.calculator import SPRKKR
8 from ase.io.trajectory import Trajectory
9 import numpy as np
10 from ase.io import read
11 from ase.units import kJ
12 from ase.eos import EquationOfState
13
14
15 al = bulk("Al", "fcc", a=4.0)
16 cell = al.get_cell()
17 traj = Trajectory("Al.traj", "w")
18
19 # run calculation
20 calc = SPRKKR(atoms=al, mpi=True)
21 calc.input_parameters.set(NL=3)
22 calc.input_parameters.set(NE=32)
23 calc.input_parameters.SCF.MIX = 0.20
24 calc.input_parameters.ENERGY.ImE = 0.0
25 calc.input_parameters.ENERGY.GRID = 5
26 calc.input_parameters.SCF.FULLPOT = True
27 calc.input_parameters.MODE.MODE = "SREL"
28
29 al.set_calculator(calc)
30
31 for x in np.linspace(0.80, 1.20, 10):
32 al.set_cell(cell * x, scale_atoms=True)
33 al.get_potential_energy()
34 traj.write(al)
35
36 # Now lets plot the result and fit EOS
37 configs = read("Al.traj@0:") # read 5 configurations
38 # Extract volumes and energies:
39 volumes = [al.get_volume() for al in configs]
40 energies = [al.get_potential_energy() for al in configs]
41 eos = EquationOfState(volumes, energies)
42 v0, e0, B = eos.fit()
43 print(B / kJ * 1.0e24, "GPa")
44 eos.plot("Al-eos.png")
45
46
47# Just run the script only when directly called from command line
48
49if __name__ == "__main__":
50 main()
A06_Cu_MSSPEC
Simple SCF calculations for fcc Cu in combination with msspec code to generate photoelectron diffraction.
Copy the example:
ase2sprkkr example 6 --copy ./my-example
1#!/usr/bin/env python
2"""
3Simple SCF calculations for fcc Cu in combination with msspec code to generate
4photoelectron diffraction.
5
6Call with ``msspec`` and/or ``sprkkr`` commandline argument.
7"""
8
9import glob
10import sys
11from ase2sprkkr.sprkkr.calculator import SPRKKR
12from ase.build import bulk
13
14
15def main(args):
16 # Create a copper cell
17 Cu = bulk("Cu")
18
19 # ########## SPRKKR part
20 if "sprkkr" in args:
21 # create a SPRKKR calculator
22 calc = SPRKKR(atoms=Cu, mpi=True)
23
24 # launch kkrscf
25 calc.input_parameters.set(NL=3)
26 calc.input_parameters.SCF.MIX = 0.20
27 calc.input_parameters.ENERGY.ImE = 0.0
28 calc.input_parameters.ENERGY.GRID = [5, 3]
29 calc.input_parameters.set(NE=32)
30 out_scf = calc.calculate()
31 #
32 # EXPORT POTENTIAL FOR PHAGEN
33 #
34
35 # Now use the calculator with the newly converged potential
36 calc = out_scf.calculator
37 calc.input_parameters = "PHAGEN"
38 calc.input_parameters.SCF.MIX = 0.20
39 calc.input_parameters.ENERGY.ImE = 0.0
40 calc.input_parameters.ENERGY.GRID = [5, 3]
41 calc.input_parameters.set(NE=32)
42 calc.calculate(potential=out_scf.potential_filename)
43
44 # ######### MsSpec part
45 if "msspec" in args:
46 from msspec.calculator import MSSPEC
47 from msspec.utils import get_atom_index, hemispherical_cluster, SPRKKRPotential
48
49 pot = SPRKKRPotential(Cu, "Cu_scf.pot_new", *glob.glob("*PHAGEN.pot"))
50
51 nplanes = 3
52 cluster = hemispherical_cluster(Cu, planes=nplanes, emitter_plane=nplanes - 1)
53 cluster.absorber = get_atom_index(cluster, 0, 0, 0)
54
55 calc = MSSPEC(folder="calc")
56 calc.set_atoms(cluster)
57 calc.tmatrix_parameters.potential = pot
58
59 data = calc.get_theta_scan(level="2p3/2")
60 data.view()
61
62 if len(args) <= 1:
63 print("Please specify either 'sprkkr', 'msspec' keywords or both of them on the command line")
64
65
66# Just run the script only when directly called from command line
67
68if __name__ == "__main__":
69 main(sys.argv)
A07_SrTiO3_MSSPEC
SCF calculations for SrTiO3 in combination with msspec code to generate photoelectron diffraction.
Copy the example:
ase2sprkkr example 7 --copy ./my-example
1"""
2SCF calculations for SrTiO3 in combination with msspec code to generate
3photoelectron diffraction.
4
5Call with ``msspec`` and/or ``sprkkr`` commandline argument.
6"""
7
8
9def main():
10
11 from ase.lattice.tetragonal import SimpleTetragonalFactory
12 from ase.visualize import view
13 from ase2sprkkr import SPRKKR
14 import numpy as np
15 import sys
16 import glob
17
18 args = sys.argv
19
20 # Define a Perovskite Factory class
21 class PerovskiteFactory(SimpleTetragonalFactory):
22 bravais_basis = [[0, 0, 0.0], [0.5, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0], [0.5, 0.0, 0.5]]
23 element_basis = (0, 1, 2, 2, 2)
24
25 Perovskite = PerovskiteFactory()
26
27 # Generate the base STO cell
28 a0 = 3.905
29 STO = Perovskite(("Sr", "Ti", "O"), latticeconstant={"a": a0, "c/a": 1.0}, size=(1, 1, 1))
30 if "view" in args:
31 view(STO)
32
33 # ########## SPRKKR part
34 if "sprkkr" in args:
35 calc = SPRKKR(atoms=STO, mpi=["mpirun", "-np", "16"])
36 calc.input_parameters.set(NL=3)
37 calc.input_parameters.SCF.MIX = 0.01
38 calc.input_parameters.SCF.NITER = 1000
39 calc.input_parameters.CONTROL.add("NOSYM", True)
40
41 out_scf = calc.calculate()
42 calc.input_parameters = "PHAGEN"
43 calc.calculate(potential=out_scf.potential_filename)
44
45 # ######### MsSpec part
46 if "msspec" in args:
47 from msspec.calculator import MSSPEC
48 from msspec.utils import SPRKKRPotential, hemispherical_cluster, get_atom_index
49
50 ###########################################################################
51 # Build the SrTiO3 cluster #
52 ###########################################################################
53 # We start by loading the potential since it updates info in the STO cell
54 pot = SPRKKRPotential(STO, "SrTiO3_scf.pot_new", *glob.glob("*PHAGEN.pot"))
55
56 # tag each atom in the STO object to easily set the emitter in the
57 # hemispherical_cluster function
58 [atom.set("tag", ("Sr", "Ti", "O").index(atom.symbol)) for atom in STO]
59
60 # Create a hemispherical cluster centered on a Ti emitter from the
61 # STO primitive cell used in the SPRKKR step.
62 # For this example we use 4 planes and the Ti emitter (tag #1) is
63 # located in the 2nd plane (numbering starts at 0)
64 cluster = hemispherical_cluster(STO, planes=4, emitter_plane=1, emitter_tag=1)
65
66 # The created cluster is centered on the emitter atom, so defining
67 # the absorber attribute is straightforward:
68 cluster.absorber = get_atom_index(cluster, 0, 0, 0)
69
70 ###########################################################################
71 # Set up the PhotoElectron Diffraction calculator #
72 ###########################################################################
73 # Create the calculator
74 calc = MSSPEC(spectroscopy="PED", algorithm="expansion", folder="PED")
75
76 # minimalistic set of parameter for XPD scan
77 calc.set_atoms(cluster)
78 calc.calculation_parameters.scattering_order = 2
79 # We need to impose a maximum number of tl to use because there is still
80 # a memory bug that I need to investigate. Anyway, usually 25 is not that
81 # bad for the kind of atoms and the photon energy of lab sources...
82 calc.tmatrix_parameters.lmax_mode = "imposed"
83 calc.tmatrix_parameters.lmaxt = 25
84
85 data = None
86 for source_energy in np.arange(500.0, 1501.0, 100.0):
87 calc.source_parameters.energy = source_energy
88 # Run a polar scan with the default MuffinTin potential for Ti(2p3/2)
89 calc.tmatrix_parameters.potential = "muffin_tin"
90 data = calc.get_theta_scan(level="2p3/2", data=data)
91
92 # Now we use the previously generated SPRKKR potential and run the same
93 # calculation
94 calc.tmatrix_parameters.potential = pot
95 data = calc.get_theta_scan(level="2p3/2", data=data)
96
97 # To better see the differences, plot the normalized signal on the
98 # same graph
99 # add a new dataset for storing normalized values
100 dset = data.add_dset(f"comparison at {source_energy} eV")
101 # make a copy of previous scans values
102 theta, muffintin_cs, sprkkr_cs = (
103 data[-3].theta.copy(),
104 data[-3].cross_section.copy(),
105 data[-2].cross_section.copy(),
106 )
107 # divide by the max
108 sprkkr_cs /= sprkkr_cs.max()
109 muffintin_cs /= muffintin_cs.max()
110 # add a new dataset with those values
111 dset.add_columns(theta=theta, sprkkr=sprkkr_cs, muffintin=muffintin_cs)
112 # add a view for this dataset
113 dview = dset.add_view(
114 "Comparison",
115 title=(
116 "Comparison of XPD polar scans for "
117 r"Ti(2p3/2) at $h\nu$ = {:.0f} eV".format(source_energy)
118 ),
119 xlabel=r"$\Theta (\degree$)",
120 ylabel="Normalized Signal (a.u.)",
121 )
122 dview.select("theta", "sprkkr", legend="With SPRKKR potential")
123 dview.select("theta", "muffintin", legend="With internal MT potential")
124 dview.set_plot_options(autoscale=True)
125
126 # Pop up the final result
127 data.view()
128
129 if len(args) <= 1:
130 print("Please specify either 'sprkkr', 'msspec' keywords or both of them on the command line")
131
132
133# Just run the script only when directly called from command line
134
135if __name__ == "__main__":
136 main()
A08_ARPES_and_plotting
Example of an ARPES calculation and plotting its results.
Copy the example:
ase2sprkkr example 8 --copy ./my-example
1"""Example of an ARPES calculation and plotting its results."""
2
3
4def main():
5
6 import numpy as np
7 from ase.atoms import Atoms
8 from ase2sprkkr import SPRKKR
9
10 a = Atoms(symbols="H", cell=np.array([(1.0, 0, 0), (0, 1, 0), (0, 0, 1)]))
11 a.pbc = True
12 xx = SPRKKR(atoms=a)
13 out = xx.calculate(options={"NITER": 2})
14 calc = out.calculator
15
16 # running ARPES TASK
17 calc.change_task("arpes")
18 calc.set("NE", 10)
19 calc.set("NKTAB", 30)
20 calc.set("NKTAB2D", 30)
21 calc.set("NKTAB3D", 30)
22 out = out.calculator.calculate()
23 print(out.spc.ENERGY())
24 # plotting
25 out.spc.plot()
26 out.spc.TOTAL.plot(filename="out.png")
27
28 # Direct reading of earlier calculated result files
29 from ase2sprkkr import ResultFile
30
31 of2 = ResultFile.from_file("H_ARPES_ARPES_data.spc")
32 of2.ENERGY()
33
34 # One can do calculations with SPC files
35 print((out.spc).ENERGY())
36 print((of2 + out.spc).ENERGY())
37 print((of2 - out.spc).TOTAL())
38 (of2 - out.spc).plot()
39
40
41if __name__ == "__main__":
42 main()
A09_EmptySpheres
Add empty spheres to open diamond Si for an atomic-sphere calculation.
Copy the example:
ase2sprkkr example 9 --copy ./my-example
1"""Add empty spheres to open diamond Si for an atomic-sphere calculation."""
2
3
4def main():
5 from ase.build import bulk
6 from ase2sprkkr import SPRKKR
7
8 # Diamond Si has large interstitial voids. It is therefore a natural
9 # example of a structure whose ASA basis benefits from empty spheres.
10 silicon = bulk("Si", "diamond", a=5.43)
11 calculator = SPRKKR(atoms=silicon)
12
13 # The simplest form asks ASE2SPRKKR to choose all settings automatically:
14 # calculator.save_input(potential_file="Si.pot", empty_spheres=True)
15
16 # A two-item tuple limits the permitted empty-sphere radii:
17 # calculator.save_input(
18 # potential_file="Si.pot",
19 # empty_spheres=(0.2, 2.0),
20 # )
21
22 # A dictionary exposes the complete set of useful tuning parameters. This
23 # example only writes the input, so no SPR-KKR executable is launched.
24 calculator.save_input(
25 potential_file="Si.pot",
26 empty_spheres={
27 "min_radius": 0.2,
28 "max_radius": 2.0,
29 "max_spheres": 300,
30 "verbose": True,
31 },
32 )
33
34
35if __name__ == "__main__":
36 main()
A10_DLM
Script demonstrating how to set up a disordered local moment (DLM) calculation using bcc Fe as the test case.
Copy the example:
ase2sprkkr example 10 --copy ./my-example
1r"""
2Script demonstrating how to set up a disordered local moment (DLM) calculation using bcc Fe as the test case.
3
4Such calculations are used to describe the paramagnetic state of materials,
5where local magnetic moments on atoms persist, but where the net magnetisation
6of the material is zero on account of thermally induced spin fluctuations. The
7CPA is used to average over possible orientations of magnetic moment. Above the Curie
8temperature, all orientations of magnetic moment are equally probably, and the
9probability distribution of orientations of magnetic moments is uniform on the sphere.
10In the absence of spin-orbit coupling, the CPA condition for a full average (using
11an angular integral) over the sphere with uniform probability distribution can be shown
12to be mathematically equivalent to the CPA condition for a 50:50 Ising 'alloy' of 'up'
13and 'down' magnetic moments. (Note that this equality does not strictly hold in the
14case where spin-orbit effects are present, as in a fully relativistic calculation.)
15
16A DLM calculation should be iterated to self-consistency to check whether the local
17moments 'collapse' (as frequently happens for elements like Cr, Ni) or whether they
18are self-sustaining (as is typical for Fe, Co).
19
20Once you have run this script and iterated to self-consistency, if you run
21`tail Fe.pot_new`
22you should find that, although the net magnetisation of the calculation is zero,
23the two Fe atoms have equal and opposite magnetic moments, each of magnitude
24approximately 2.16 \mu_B. This confirms that the local moments are self-sustaining,
25and that bcc Fe is a 'good' local moment system.
26
27Some appropriate references for the disordered local moment (DLM) picture are:
28 - A. J. Pindor et al., J. Phys. F: Met. Phys. 13, 979 (1983)
29 - J. B. Staunton et al., J. Magn. Magn. Mater. 45, 15-22 (1984)
30 - B. L. Gyorffy et al., J. Phys. F: Met. Phys. 15, 1337 (1985)
31
32Author: Christopher D. Woodgate, University of Bristol, 2025
33
34Email: christopher.woodgate@bristol.ac.uk
35"""
36
37
38def main():
39
40 from ase.build import bulk
41 from ase2sprkkr.sprkkr.calculator import SPRKKR
42 from ase2sprkkr.sprkkr.sprkkr_atoms import SPRKKRAtoms
43
44 # BCC Fe has a_lat = 2.87 \AA
45 a_lat = 2.87
46 atom = bulk("Fe", "bcc", a=a_lat)
47
48 # Now set up the 'alloy'
49 atoms = SPRKKRAtoms.promote_ase_atoms(atom)
50
51 # We cannot use a Python dictionary here, as we need an alloy of two elements
52 # with the same chemical symbol and this behaviour is not permitted in a Python dictionary
53 # Instead, we use a list.
54 atoms.sites[0].occupation.set([("Fe", 0.5), ("Fe", 0.5)])
55
56 # Now we set up the ASE calculator
57 calculator = SPRKKR(atoms=atoms, mpi=["mpirun", "-np", "4"])
58
59 # NOTE: we need to specify initial magnetic moments, up and down, on the two Fe atoms
60 # NOTE: These are in units of \mu_B
61 calculator.input_parameters.SCF.MSPIN = [2.3, -2.3]
62
63 # And other necessary parameters
64 calculator.input_parameters.set(NKTAB=500) # Control k-point sampling
65 calculator.input_parameters.set(VXC="VWN") # VWN LDA XC functional
66 calculator.input_parameters.set(MODE="SP-SREL") # Scalar relativistic mode for the DLM physics
67 calculator.input_parameters.set(NL=4) # l_max=3 means 4 l-channels
68 calculator.input_parameters.set(NE=32) # 32-point semicircular energy contour
69 calculator.input_parameters.ENERGY.GRID = 5 # Semicircular energy contour
70 calculator.input_parameters.SCF.MIX = 0.05 # Gentle mixing paramter to ensure convergence
71 calculator.input_parameters.SCF.TOL = 1e-7 # Tight tolerance on SCF cycle
72 calculator.input_parameters.SCF.NITER = 1000 # Allow for lots of iterations if needed
73 calculator.input_parameters.ENERGY.ImE = 0.00 # Distance of closest approach to real axis
74 calculator.input_parameters.CPA.NITER = 100 # Allow for a lot of CPA iterations if needed
75 calculator.input_parameters.CPA.TOL = 1e-8 # Tight CPA tol to go with tight SCF tol
76 calculator.input_parameters.SCF.USEVMATT = True # I like to use the Mattheiss construction for the potential
77
78 # Run the calculator
79 out = calculator.calculate()
80
81 print(out.energy)
82 print(out.last_iteration["energy"]["EF"].to_dict())
83 print(out.iterations[-1]["error"]())
84 print(out.last_iteration["moment"].to_dict())
85
86
87# If we run this script, execute 'main'
88if __name__ == "__main__":
89 main()
A11_Torque
Magnetic torque calculations.
Copy the example:
ase2sprkkr example 11 --copy ./my-example
1"""Magnetic torque calculations."""
2
3
4def main():
5 from ase2sprkkr.sprkkr.calculator import SPRKKR
6 import os
7
8 print("Starting SPRKKR calculation...")
9
10 # Get the directory where this script is located
11 script_dir = os.path.dirname(os.path.abspath(__file__))
12
13 # Set the working directory to the script's directory
14 os.chdir(script_dir)
15 print(f"Working directory set to: {os.getcwd()}")
16
17 # Initialize calculator
18 calculator = SPRKKR()
19
20 # Set input parameters
21 print("Setting up input parameters...")
22 calculator.input_parameters = "torque"
23 calculator.input_parameters.CONTROL.DATASET = "Fe"
24 calculator.input_parameters.MODE.MDIR = [1.0, 0.0, 0.0] # Using floats instead of integers
25 calculator.input_parameters.MODE.MALF = 0.0
26 calculator.input_parameters.MODE.MBET = 45.0
27 calculator.input_parameters.MODE.MGAM = 0.0
28
29 # Define potential file path relative to the script location
30 potential_file = os.path.abspath("Fe.pot_new")
31
32 # Check if potential file exists
33 if not os.path.exists(potential_file):
34 print(f"\nError: Potential file not found at {potential_file}")
35 print("Please ensure the potential file 'Fe.pot_new' is in the same directory as this script.")
36 return 1
37
38 print(f"Using potential file: {potential_file}")
39 print(f"File exists: {os.path.exists(potential_file)}")
40 print(f"File size: {os.path.getsize(potential_file) / 1024:.2f} KB")
41
42 # Run calculation with explicit path to kkrgen and save output to file
43 print("Starting calculation...")
44 output_file = os.path.abspath("torque_calculation.out")
45
46 try:
47 calculator.calculate(
48 potential=potential_file,
49 directory=script_dir, # Set the working directory for the calculation
50 print_output=True,
51 output_file=output_file,
52 )
53 print(f"Calculation completed! Output saved to {output_file}")
54
55 except Exception as e:
56 print(f"Error during calculation: {str(e)}")
57 # If there was an error but the output file exists, show its contents
58 if os.path.exists(output_file):
59 print("\n=== Output file contents ===")
60 with open(output_file, "r") as f:
61 print(f.read())
62 print("===========================")
63 raise
64
65 return 0
66
67
68if __name__ == "__main__":
69 main()
A12_JXC
Calculates the exchange coupling parameters Jij of the Heisenberg model and Dzyaloshinskii-Moriya interaction.
Copy the example:
ase2sprkkr example 12 --copy ./my-example
1"""Calculates the exchange coupling parameters Jij of the Heisenberg model and
2Dzyaloshinskii-Moriya interaction."""
3
4
5def main():
6 from ase2sprkkr.sprkkr.calculator import SPRKKR
7 import os
8
9 print("Starting SPRKKR calculation...")
10
11 # Initialize calculator
12 calculator = SPRKKR()
13
14 # Set input parameters
15 print("Setting up input parameters...")
16 calculator.input_parameters = "jxc"
17 calculator.input_parameters.TASK.add("DMI", True)
18
19 calculator.input_parameters.CONTROL.DATASET = "Fe"
20 # calculator.input_parameters.MODE.MDIR = [1.0, 0.0, 0.0] # Using floats instead of integers
21 # calculator.input_parameters.MODE.MALF = 0.0
22 # calculator.input_parameters.MODE.MBET = 45.0
23 # calculator.input_parameters.MODE.MGAM = 0.0
24
25 try:
26 potential_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Fe.pot_new")
27 result = calculator.calculate( # noqa F841
28 potential=potential_file,
29 print_output=True,
30 output_file=os.path.join(os.path.dirname(os.path.abspath(__file__)), "Fe_jxc.out"),
31 )
32
33 except Exception as e:
34 print(f"Error during calculation: {str(e)}")
35 raise
36
37 return 0
38
39
40if __name__ == "__main__":
41 main()
A13_XAS
Calculate and plot Ni L2,3 XAS and XMCD spectra of Ni2FeGa.
Copy the example:
ase2sprkkr example 13 --copy ./my-example
1"""Calculate and plot Ni L2,3 XAS and XMCD spectra of Ni2FeGa."""
2
3
4def make_ni2fega():
5 """Return the ordered primitive Ni2FeGa Heusler cell."""
6 import numpy as np
7 from ase2sprkkr import SPRKKRAtoms
8
9 cell = 5.748 * np.array(
10 [[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]
11 )
12 return SPRKKRAtoms(
13 symbols=["Ni", "Ni", "Fe", "Ga"],
14 scaled_positions=[
15 [0.25, 0.25, 0.25],
16 [0.75, 0.75, 0.75],
17 [0.50, 0.50, 0.50],
18 [0.00, 0.00, 0.00],
19 ],
20 cell=cell,
21 pbc=True,
22 )
23
24
25def main():
26 from glob import glob
27 from ase2sprkkr import ResultFile, SPRKKR
28
29 # XAS is a post-SCF task, so first obtain a converged potential. Keeping
30 # this step here makes the example independent of every other example.
31 calculator = SPRKKR(atoms=make_ni2fega())
32 scf_result = calculator.calculate()
33
34 # IT=1 selects Ni and CL='2p' selects the spin-orbit split L2,3 edge.
35 xas_options = {
36 "CONTROL.DATASET": "Ni2FeGa",
37 "TAU.NKTAB": 500,
38 "TASK.IT": 1,
39 "TASK.CL": "2p",
40 "TASK.FRAMETET": 0,
41 "TASK.FRAMEPHI": 0,
42 "ENERGY.NE": 180,
43 "ENERGY.GRID": 6,
44 "ENERGY.EMAX": 40.0,
45 }
46 calculator.calculate(
47 potential=scf_result.potential_filename,
48 input_parameters="xas",
49 options=xas_options,
50 )
51
52 # SPR-KKR writes one RAT file for each selected absorbing edge.
53 rat_files = glob("Ni2FeGa_XAS_*.rat")
54 if len(rat_files) != 1:
55 raise RuntimeError(f"Expected one XAS RAT file, found {rat_files}")
56 ResultFile.from_file(rat_files[0]).plot()
57
58
59if __name__ == "__main__":
60 main()
A14_Semiinfinite
Calculate the Bloch spectral function of a semi-infinite Au(111) surface.
Copy the example:
ase2sprkkr example 14 --copy ./my-example
1"""Calculate the Bloch spectral function of a semi-infinite Au(111) surface."""
2
3
4def main():
5 from ase.build import fcc111
6 from ase2sprkkr import SPRKKR
7 from ase2sprkkr.sprkkr.build import semiinfinite_system
8
9 # Build a central interaction zone between bulk Au and vacuum.
10 bulk_slab = fcc111("Au", size=(1, 1, 3), periodic=True)
11 surface = semiinfinite_system(
12 atoms=bulk_slab, repeat=[3, 3], atoms2=None, axis=2
13 )
14
15 bulk_options = {
16 "CONTROL.KRMT": 2,
17 "SITES.NL": 4,
18 "TAU.KKRMODE": "TB",
19 "TAU.NKTAB3D": 1000,
20 "TAU.NKTAB2D": 100,
21 "TAU.CLURAD": 2.7,
22 "SCF.VXC": "VWN",
23 "SCF.NITER": 500,
24 "SCF.MIX": 0.1,
25 "SCF.TOL": 1e-5,
26 }
27 calculator = SPRKKR(atoms=surface, options=bulk_options)
28 bulk_result = calculator.calculate()
29
30 # The surface SCF starts from the converged bulk potential and uses gentler
31 # mixing because convergence of the interaction zone is more demanding.
32 surface_options = {
33 **bulk_options,
34 "TAU.NKTAB2D": 71,
35 "SCF.NITER": 2000,
36 "SCF.MIX": 0.01,
37 }
38 surface_calculator = SPRKKR(
39 potential=bulk_result.potential_filename, options=surface_options
40 )
41 surface_result = surface_calculator.calculate()
42
43 # Evaluate the energy-dependent BSF along a path through the surface BZ.
44 bsf_options = {
45 "TAU.NKTAB3D": 1000,
46 "TAU.NKTAB2D": 71,
47 "TAU.CLURAD": 2.7,
48 "ENERGY.ImE": 0.002,
49 "ENERGY.EMINEV": -4.0,
50 "ENERGY.EMAXEV": 2.0,
51 "ENERGY.NE": 400,
52 "TASK.NK": 300,
53 "TASK.KA": [[-0.66667, 0.0, 0.0], [0.0, 0.0, 0.0]],
54 "TASK.KE": [[0.0, 0.0, 0.0], [0.66667, 0.0, 0.0]],
55 }
56 result = surface_calculator.calculate(
57 potential=surface_result.potential_filename,
58 input_parameters="bsfek",
59 options=bsf_options,
60 )
61 result.bsf.plot(IQ=[0, 1, 2, 10, 11, 12])
62
63
64if __name__ == "__main__":
65 main()
A15_Ni2FeGa_CPA_scan
Scan Fe/Co substitution in Ni2FeGa with the coherent potential approximation.
Copy the example:
ase2sprkkr example 15 --copy ./my-example
1"""Scan Fe/Co substitution in Ni2FeGa with the coherent potential approximation."""
2
3
4def make_ni2fega():
5 """Build the ordered primitive cell used as the scan template."""
6 import numpy as np
7 from ase2sprkkr import SPRKKRAtoms
8
9 cell = 5.748 * np.array(
10 [[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]
11 )
12 return SPRKKRAtoms(
13 symbols=["Ni", "Ni", "Fe", "Ga"],
14 scaled_positions=[
15 [0.25, 0.25, 0.25],
16 [0.75, 0.75, 0.75],
17 [0.50, 0.50, 0.50],
18 [0.00, 0.00, 0.00],
19 ],
20 cell=cell,
21 pbc=True,
22 )
23
24
25def main():
26 import numpy as np
27 from ase2sprkkr import SPRKKR
28
29 template = make_ni2fega()
30 results = []
31
32 # CPA represents substitutional disorder in the primitive cell, avoiding
33 # a separate large supercell for every concentration.
34 for fe_fraction in np.linspace(0.0, 1.0, 21):
35 atoms = template.copy()
36 atoms.sites[2].site_type.occupation.set(
37 {"Fe": fe_fraction, "Co": 1.0 - fe_fraction}
38 )
39 result = SPRKKR(atoms=atoms).calculate()
40 results.append((fe_fraction, result.energy))
41
42 for fe_fraction, energy in results:
43 print(f"Fe fraction={fe_fraction:5.2f}, total energy={energy}")
44
45
46if __name__ == "__main__":
47 main()
A16_GPAW_to_SPRKKR_ARPES
Relax MoSe2 with GPAW and reuse the ASE structure for SPR-KKR ARPES.
Copy the example:
ase2sprkkr example 16 --copy ./my-example
1"""Relax MoSe2 with GPAW and reuse the ASE structure for SPR-KKR ARPES."""
2
3
4def main():
5 from ase.filters import FrechetCellFilter
6 from ase.optimize import BFGS
7 from ase.spacegroup import crystal
8 from ase2sprkkr import SPRKKR
9 from gpaw import FermiDirac, GPAW, PW
10
11 # GPAW is an optional dependency. The relaxed object remains an ordinary
12 # ASE Atoms instance and can therefore be passed directly to ASE2SPRKKR.
13 atoms = crystal(
14 symbols=["Mo", "Se"],
15 basis=[(1 / 3, 2 / 3, 1 / 4), (1 / 3, 2 / 3, 0.621)],
16 spacegroup=194,
17 cellpar=[3.288, 3.288, 12.900, 90, 90, 120],
18 )
19 atoms.calc = GPAW(
20 mode=PW(650),
21 xc="PBE",
22 kpts={"size": (8, 8, 4), "gamma": True},
23 occupations=FermiDirac(0.05),
24 txt="mose2_bulk_relax.txt",
25 )
26 optimizer = BFGS(
27 FrechetCellFilter(atoms),
28 trajectory="mose2.traj",
29 logfile="mose2.log",
30 )
31 optimizer.run(fmax=0.02)
32 atoms.write("mose2_relaxed.cif")
33
34 # First converge the SPR-KKR potential, then reuse it by changing the task
35 # on the same calculator object.
36 calculator = SPRKKR(atoms=atoms)
37 calculator.calculate()
38 calculator.change_task("arpes")
39 result = calculator.calculate()
40 result.spc.plot()
41
42
43if __name__ == "__main__":
44 main()
A17_Au_ARPES
Calculate Au bulk DOS, angle-resolved photoemission and a Fermi map.
Copy the example:
ase2sprkkr example 17 --copy ./my-example
1"""Calculate Au bulk DOS, angle-resolved photoemission and a Fermi map."""
2
3
4def main():
5 from ase.build import bulk
6 from ase2sprkkr import SPRKKR
7
8 # The SCF step produces the converged potential required by all subsequent
9 # spectroscopy tasks in this self-contained workflow.
10 gold = bulk("Au", "fcc", a=4.08)
11 scf_options = {
12 "CONTROL.KRMT": 4,
13 "TAU.NKTAB3D": 1000,
14 "SCF.VXC": "VWN",
15 "SCF.FULLPOT": False,
16 "SCF.NITER": 2000,
17 "SCF.MIX": 0.1,
18 "SCF.TOL": 1e-5,
19 }
20 calculator = SPRKKR(atoms=gold, options=scf_options)
21 calculator.calculate()
22
23 # A DOS calculation is a useful check of the converged bulk potential.
24 dos_result = calculator.calculate(
25 input_parameters="dos",
26 options={
27 "ENERGY.ImE": 0.001,
28 "ENERGY.EMINEV": -12.0,
29 "ENERGY.EMAXEV": 7.0,
30 "ENERGY.NE": 1000,
31 "TAU.NKTAB": 2500,
32 },
33 )
34 dos_result.dos.plot()
35
36 # One-step ARPES includes photon geometry, the surface orientation and the
37 # detector scan in a single calculation.
38 arpes_options = {
39 "TAU.NKTAB": 500,
40 "ENERGY.EMINEV": -4.0,
41 "ENERGY.EMAXEV": 2.0,
42 "ENERGY.EWORK_EV": 5.0,
43 "ENERGY.NE": 300,
44 "ENERGY.IMV_INI_EV": 0.02,
45 "ENERGY.IMV_FIN_EV": 2.0,
46 "TASK.MILLER_HKL": [1, 1, 1],
47 "SPEC_PH.THETA": 45,
48 "SPEC_PH.PHI": 90,
49 "SPEC_PH.EPHOT": 50,
50 "SPEC_STR.N_LAYDBL": [12, 12],
51 "SPEC_STR.N_LAYER": 30,
52 "SPEC_EL.THETA": [-20, 20],
53 "SPEC_EL.NT": 200,
54 "SPEC_EL.SPOL": 4,
55 }
56 arpes_result = calculator.calculate(
57 input_parameters="arpes", options=arpes_options
58 )
59 arpes_result.spc.plot()
60
61 # Reuse the same experimental geometry on a two-dimensional k grid at EF.
62 fermi_options = {
63 **arpes_options,
64 "ENERGY.EMINEV": 0.0,
65 "ENERGY.EMAXEV": 0.0,
66 "ENERGY.NE": 1,
67 "SPEC_EL.KA": [-0.5, -0.5],
68 "SPEC_EL.K1": [1, 0],
69 "SPEC_EL.K2": [0, 1],
70 "SPEC_EL.NK1": 120,
71 "SPEC_EL.NK2": 120,
72 "SPEC_EL.PSPIN": [0, 0, 1],
73 }
74 fermi_result = calculator.calculate(
75 input_parameters="arpes", options=fermi_options
76 )
77 fermi_result.spc.plot()
78
79
80if __name__ == "__main__":
81 main()
A18_Ni2FeGa_JXC
Calculate Ni2FeGa exchange couplings and export them for UppASD.
Copy the example:
ase2sprkkr example 18 --copy ./my-example
1"""Calculate Ni2FeGa exchange couplings and export them for UppASD."""
2
3
4def make_ni2fega():
5 """Return the ordered primitive Ni2FeGa Heusler cell."""
6 import numpy as np
7 from ase2sprkkr import SPRKKRAtoms
8
9 cell = 5.748 * np.array(
10 [[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]
11 )
12 return SPRKKRAtoms(
13 symbols=["Ni", "Ni", "Fe", "Ga"],
14 scaled_positions=[
15 [0.25, 0.25, 0.25],
16 [0.75, 0.75, 0.75],
17 [0.50, 0.50, 0.50],
18 [0.00, 0.00, 0.00],
19 ],
20 cell=cell,
21 pbc=True,
22 )
23
24
25def main():
26 from ase2sprkkr import SPRKKR
27
28 # Exchange parameters require a converged magnetic potential. Performing
29 # SCF here keeps the example independent of the CPA and XAS examples.
30 calculator = SPRKKR(atoms=make_ni2fega())
31 scf_result = calculator.calculate()
32
33 jxc_options = {
34 "CONTROL.DATASET": "Ni2FeGa",
35 "TAU.NKTAB": 1000,
36 "MODE.LLOYD": False,
37 "TASK.CLURAD": 4.5,
38 "SITES.NL": 4,
39 "MODE": "SP-SREL",
40 "ENERGY.NE": 32,
41 }
42 result = calculator.calculate(
43 potential=scf_result.potential_filename,
44 input_parameters="jxc",
45 options=jxc_options,
46 )
47
48 # Inspect all three exchange-tensor components, report SPR-KKR's mean-field
49 # Curie temperature and create jfile/posfile/momfile/inpsd for UppASD.
50 result.jxc.plot(layout=(1, 3))
51 print("Mean-field Curie temperature:", result.mean_field_curie_temperature)
52 result.write_uppasd_files()
53
54
55if __name__ == "__main__":
56 main()