/
sets.py
595 lines (518 loc) · 19.9 KB
/
sets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines the FeffInputSet abstract base class and a concrete
implementation for the Materials Project. The basic concept behind an input
set is to specify a scheme to generate a consistent set of Feff inputs from a
structure without further user intervention. This ensures comparability across
runs.
"""
from __future__ import annotations
import abc
import logging
import os
import sys
from copy import deepcopy
import numpy as np
from monty.json import MSONable
from monty.os.path import zpath
from monty.serialization import loadfn
from pymatgen.io.feff.inputs import Atoms, Header, Potential, Tags
__author__ = "Kiran Mathew"
__credits__ = "Alan Dozier, Anubhav Jain, Shyue Ping Ong"
__version__ = "1.1"
__maintainer__ = "Kiran Mathew"
__email__ = "kmathew@lbl.gov"
__date__ = "Sept 10, 2016"
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s: %(levelname)s: %(name)s: %(message)s")
sh = logging.StreamHandler(stream=sys.stdout)
sh.setFormatter(formatter)
logger.addHandler(sh)
class AbstractFeffInputSet(MSONable, metaclass=abc.ABCMeta):
"""
Abstract base class representing a set of Feff input parameters.
The idea is that using a FeffInputSet, a complete set of input files
(feffPOT, feffXANES, feffEXAFS, ATOMS, feff.inp)set_
can be generated in an automated fashion for any structure.
"""
@abc.abstractmethod
def header(self):
"""
Returns header to be used in feff.inp file from a pymatgen structure
"""
@property
@abc.abstractmethod
def atoms(self):
"""
Returns Atoms string from a structure that goes in feff.inp file.
Returns:
Atoms object.
"""
@property
@abc.abstractmethod
def tags(self):
"""
Returns standard calculation parameters.
"""
return
@property
@abc.abstractmethod
def potential(self):
"""
Returns POTENTIAL section used in feff.inp from a structure.
"""
def all_input(self):
"""
Returns all input files as a dict of {filename: feffio object}
"""
d = {"HEADER": self.header(), "PARAMETERS": self.tags}
if "RECIPROCAL" not in self.tags:
d.update({"POTENTIALS": self.potential, "ATOMS": self.atoms})
return d
def write_input(self, output_dir=".", make_dir_if_not_present=True):
"""
Writes a set of FEFF input to a directory.
Args:
output_dir: Directory to output the FEFF input files
make_dir_if_not_present: Set to True if you want the directory (
and the whole path) to be created if it is not present.
"""
if make_dir_if_not_present and not os.path.exists(output_dir):
os.makedirs(output_dir)
feff = self.all_input()
feff_input = "\n\n".join(str(feff[k]) for k in ["HEADER", "PARAMETERS", "POTENTIALS", "ATOMS"] if k in feff)
for k, v in feff.items():
with open(os.path.join(output_dir, k), "w") as f:
f.write(str(v))
with open(os.path.join(output_dir, "feff.inp"), "w") as f:
f.write(feff_input)
# write the structure to cif file
if "ATOMS" not in feff:
self.atoms.struct.to(fmt="cif", filename=os.path.join(output_dir, feff["PARAMETERS"]["CIF"]))
class FEFFDictSet(AbstractFeffInputSet):
"""
Standard implementation of FeffInputSet, which can be extended by specific
implementations.
"""
def __init__(
self,
absorbing_atom: str | int,
structure,
radius: float,
config_dict: dict,
edge: str = "K",
spectrum: str = "EXAFS",
nkpts=1000,
user_tag_settings: dict | None = None,
spacegroup_analyzer_settings: dict | None = None,
):
"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input structure
radius (float): cluster radius
config_dict (dict): control tag settings dict
edge (str): absorption edge
spectrum (str): type of spectrum to calculate, available options :
EXAFS, XANES, DANES, XMCD, ELNES, EXELFS, FPRIME, NRIXS, XES.
The default is EXAFS.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings. To delete
tags, set the key '_del' in the user_tag_settings.
eg: user_tag_settings={"_del": ["COREHOLE", "EXCHANGE"]}
spacegroup_analyzer_settings (dict): parameters passed to SpacegroupAnalyzer.
E.g., {"symprec": 0.01, "angle_tolerance": 4}
"""
self.absorbing_atom = absorbing_atom
self.structure = structure
self.radius = radius
self.config_dict = deepcopy(config_dict)
self.edge = edge
self.spectrum = spectrum
self.nkpts = nkpts
self.user_tag_settings = user_tag_settings or {}
self.config_dict["EDGE"] = self.edge
self.config_dict.update(self.user_tag_settings)
if "_del" in self.user_tag_settings:
for tag in self.user_tag_settings["_del"]:
if tag in self.config_dict:
del self.config_dict[tag]
del self.config_dict["_del"]
# k-space feff only for small systems. The hardcoded system size in
# feff is around 14 atoms.
self.small_system = len(self.structure) < 14 and "EXAFS" not in self.config_dict
self.spacegroup_analyzer_settings = spacegroup_analyzer_settings or {}
def header(self, source: str = "", comment: str = ""):
"""
Creates header string from structure object
Args:
source: Source identifier used to create structure, can be defined
however user wants to organize structures, calculations, etc.
example would be Materials Project material ID number.
comment: comment to include in header
Returns:
Header
"""
return Header(self.structure, source, comment, spacegroup_analyzer_settings=self.spacegroup_analyzer_settings)
@property
def tags(self) -> Tags:
"""
FEFF job parameters.
Returns:
Tags
"""
if "RECIPROCAL" in self.config_dict:
if self.small_system:
self.config_dict["CIF"] = f"{self.structure.formula.replace(' ', '')}.cif"
self.config_dict["TARGET"] = self.atoms.center_index + 1
self.config_dict["COREHOLE"] = "RPA"
logger.warning("Setting COREHOLE = RPA for K-space calculation")
if not self.config_dict.get("KMESH", None):
abc = self.structure.lattice.abc
mult = (self.nkpts * abc[0] * abc[1] * abc[2]) ** (1 / 3)
self.config_dict["KMESH"] = [int(round(mult / l)) for l in abc]
else:
logger.warning(
"Large system(>=14 atoms) or EXAFS calculation, \
removing K-space settings"
)
del self.config_dict["RECIPROCAL"]
self.config_dict.pop("CIF", None)
self.config_dict.pop("TARGET", None)
self.config_dict.pop("KMESH", None)
self.config_dict.pop("STRFAC", None)
return Tags(self.config_dict)
@property
def potential(self) -> Potential:
"""
FEFF potential
Returns:
Potential
"""
return Potential(self.structure, self.absorbing_atom)
@property
def atoms(self) -> Atoms:
"""
absorber + the rest
Returns:
Atoms
"""
return Atoms(self.structure, self.absorbing_atom, self.radius)
def __str__(self):
output = [self.spectrum]
output.extend([f"{k} = {v}" for k, v in self.config_dict.items()])
output.append("")
return "\n".join(output)
@staticmethod
def from_directory(input_dir):
"""
Read in a set of FEFF input files from a directory, which is
useful when existing FEFF input needs some adjustment.
"""
sub_d = {}
for fname, ftype in [("HEADER", Header), ("PARAMETERS", Tags)]:
fullzpath = zpath(os.path.join(input_dir, fname))
sub_d[fname.lower()] = ftype.from_file(fullzpath)
# Generation of FEFFDict set requires absorbing atom, need to search
# the index of absorption atom in the structure according to the
# distance matrix and shell species information contained in feff.inp
absorber_index = []
radius = None
feffinp = zpath(os.path.join(input_dir, "feff.inp"))
if "RECIPROCAL" not in sub_d["parameters"]:
input_atoms = Atoms.cluster_from_file(feffinp)
shell_species = np.array([x.species_string for x in input_atoms])
# First row of distance matrix represents the distance from the absorber to
# the rest atoms
distance_matrix = input_atoms.distance_matrix[0, :]
# Get radius value
from math import ceil
radius = int(
ceil(
input_atoms.get_distance(
input_atoms.index(input_atoms[0]),
input_atoms.index(input_atoms[-1]),
)
)
)
for site_index, site in enumerate(sub_d["header"].struct):
if site.specie == input_atoms[0].specie:
site_atoms = Atoms(sub_d["header"].struct, absorbing_atom=site_index, radius=radius)
site_distance = np.array(site_atoms.get_lines())[:, 5].astype(np.float64)
site_shell_species = np.array(site_atoms.get_lines())[:, 4]
shell_overlap = min(shell_species.shape[0], site_shell_species.shape[0])
if np.allclose(distance_matrix[:shell_overlap], site_distance[:shell_overlap]) and np.all(
site_shell_species[:shell_overlap] == shell_species[:shell_overlap]
):
absorber_index.append(site_index)
if "RECIPROCAL" in sub_d["parameters"]:
absorber_index = sub_d["parameters"]["TARGET"]
absorber_index[0] = int(absorber_index[0]) - 1
# Generate the input set
if "XANES" in sub_d["parameters"]:
CONFIG = loadfn(os.path.join(MODULE_DIR, "MPXANESSet.yaml"))
if radius is None:
radius = 10
return FEFFDictSet(
absorber_index[0],
sub_d["header"].struct,
radius=radius,
config_dict=CONFIG,
edge=sub_d["parameters"]["EDGE"],
nkpts=1000,
user_tag_settings=sub_d["parameters"],
)
raise ValueError("Bad input directory.")
class MPXANESSet(FEFFDictSet):
"""
FeffDictSet for XANES spectroscopy.
"""
CONFIG = loadfn(os.path.join(MODULE_DIR, "MPXANESSet.yaml"))
def __init__(
self,
absorbing_atom,
structure,
edge: str = "K",
radius: float = 10.0,
nkpts: int = 1000,
user_tag_settings: dict | None = None,
**kwargs,
):
r"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input
edge (str): absorption edge
radius (float): cluster radius in Angstroms.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings
**kwargs: Passthrough to FEFFDictSet
"""
super().__init__(
absorbing_atom,
structure,
radius,
MPXANESSet.CONFIG,
edge=edge,
spectrum="XANES",
nkpts=nkpts,
user_tag_settings=user_tag_settings,
**kwargs,
)
class MPEXAFSSet(FEFFDictSet):
"""
FeffDictSet for EXAFS spectroscopy.
"""
CONFIG = loadfn(os.path.join(MODULE_DIR, "MPEXAFSSet.yaml"))
def __init__(
self,
absorbing_atom,
structure,
edge: str = "K",
radius: float = 10.0,
nkpts: int = 1000,
user_tag_settings: dict | None = None,
**kwargs,
):
r"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input structure
edge (str): absorption edge
radius (float): cluster radius in Angstroms.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings
**kwargs: Passthrough to FEFFDictSet
"""
super().__init__(
absorbing_atom,
structure,
radius,
MPEXAFSSet.CONFIG,
edge=edge,
spectrum="EXAFS",
nkpts=nkpts,
user_tag_settings=user_tag_settings,
**kwargs,
)
class MPEELSDictSet(FEFFDictSet):
"""
FeffDictSet for ELNES spectroscopy.
"""
def __init__(
self,
absorbing_atom,
structure,
edge,
spectrum,
radius,
beam_energy,
beam_direction,
collection_angle,
convergence_angle,
config_dict,
user_eels_settings=None,
nkpts: int = 1000,
user_tag_settings: dict | None = None,
**kwargs,
):
"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input structure
edge (str): absorption edge
spectrum (str): ELNES or EXELFS
radius (float): cluster radius in Angstroms.
beam_energy (float): Incident beam energy in keV
beam_direction (list): Incident beam direction. If None, the
cross section will be averaged.
collection_angle (float): Detector collection angle in mrad.
convergence_angle (float): Beam convergence angle in mrad.
user_eels_settings (dict): override default EELS config.
See MPELNESSet.yaml for supported keys.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings
**kwargs: Passthrough to FEFFDictSet
"""
self.beam_energy = beam_energy
self.beam_direction = beam_direction
self.collection_angle = collection_angle
self.convergence_angle = convergence_angle
self.user_eels_settings = user_eels_settings
eels_config_dict = deepcopy(config_dict)
if beam_direction:
beam_energy_list = [beam_energy, 0, 1, 1]
eels_config_dict[spectrum]["BEAM_DIRECTION"] = beam_direction
else:
beam_energy_list = [beam_energy, 1, 0, 1]
del eels_config_dict[spectrum]["BEAM_DIRECTION"]
eels_config_dict[spectrum]["BEAM_ENERGY"] = beam_energy_list
eels_config_dict[spectrum]["ANGLES"] = [collection_angle, convergence_angle]
if user_eels_settings:
eels_config_dict[spectrum].update(user_eels_settings)
super().__init__(
absorbing_atom,
structure,
radius,
eels_config_dict,
edge=edge,
spectrum=spectrum,
nkpts=nkpts,
user_tag_settings=user_tag_settings,
**kwargs,
)
class MPELNESSet(MPEELSDictSet):
"""
FeffDictSet for ELNES spectroscopy.
"""
CONFIG = loadfn(os.path.join(MODULE_DIR, "MPELNESSet.yaml"))
def __init__(
self,
absorbing_atom,
structure,
edge: str = "K",
radius: float = 10.0,
beam_energy: float = 100,
beam_direction=None,
collection_angle: float = 1,
convergence_angle: float = 1,
user_eels_settings=None,
nkpts: int = 1000,
user_tag_settings: dict | None = None,
**kwargs,
):
r"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input structure
edge (str): absorption edge
radius (float): cluster radius in Angstroms.
beam_energy (float): Incident beam energy in keV
beam_direction (list): Incident beam direction. If None, the
cross section will be averaged.
collection_angle (float): Detector collection angle in mrad.
convergence_angle (float): Beam convergence angle in mrad.
user_eels_settings (dict): override default EELS config.
See MPELNESSet.yaml for supported keys.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings
**kwargs: Passthrough to FEFFDictSet
"""
super().__init__(
absorbing_atom,
structure,
edge,
"ELNES",
radius,
beam_energy,
beam_direction,
collection_angle,
convergence_angle,
MPELNESSet.CONFIG,
user_eels_settings=user_eels_settings,
nkpts=nkpts,
user_tag_settings=user_tag_settings,
**kwargs,
)
class MPEXELFSSet(MPEELSDictSet):
"""
FeffDictSet for EXELFS spectroscopy.
"""
CONFIG = loadfn(os.path.join(MODULE_DIR, "MPEXELFSSet.yaml"))
def __init__(
self,
absorbing_atom,
structure,
edge="K",
radius: float = 10.0,
beam_energy: float = 100,
beam_direction=None,
collection_angle: float = 1,
convergence_angle: float = 1,
user_eels_settings=None,
nkpts: int = 1000,
user_tag_settings: dict | None = None,
**kwargs,
):
r"""
Args:
absorbing_atom (str/int): absorbing atom symbol or site index
structure (Structure): input structure
edge (str): absorption edge
radius (float): cluster radius in Angstroms.
beam_energy (float): Incident beam energy in keV
beam_direction (list): Incident beam direction. If None, the
cross section will be averaged.
collection_angle (float): Detector collection angle in mrad.
convergence_angle (float): Beam convergence angle in mrad.
user_eels_settings (dict): override default EELS config.
See MPEXELFSSet.yaml for supported keys.
nkpts (int): Total number of kpoints in the brillouin zone. Used
only when feff is run in the reciprocal space mode.
user_tag_settings (dict): override default tag settings
**kwargs: Passthrough to FEFFDictSet
"""
super().__init__(
absorbing_atom,
structure,
edge,
"EXELFS",
radius,
beam_energy,
beam_direction,
collection_angle,
convergence_angle,
MPEXELFSSet.CONFIG,
user_eels_settings=user_eels_settings,
nkpts=nkpts,
user_tag_settings=user_tag_settings,
**kwargs,
)