-
Notifications
You must be signed in to change notification settings - Fork 873
/
materials.py
394 lines (340 loc) · 15.2 KB
/
materials.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
"""This module provides various representations of transformed structures. A
TransformedStructure is a structure that has been modified by undergoing a
series of transformations.
"""
from __future__ import annotations
import json
import re
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from warnings import warn
from monty.json import MSONable, jsanitize
from pymatgen.core.structure import Structure
from pymatgen.io.cif import CifParser
from pymatgen.io.vasp.inputs import Poscar
from pymatgen.io.vasp.sets import MPRelaxSet, VaspInputSet
from pymatgen.transformations.transformation_abc import AbstractTransformation
from pymatgen.util.provenance import StructureNL
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any
from typing_extensions import Self
from pymatgen.alchemy.filters import AbstractStructureFilter
class TransformedStructure(MSONable):
"""Container for new structures that include history of transformations.
Each transformed structure is made up of a sequence of structures with
associated transformation history.
"""
def __init__(
self,
structure: Structure,
transformations: AbstractTransformation | Sequence[AbstractTransformation] | None = None,
history: list[AbstractTransformation | dict[str, Any]] | None = None,
other_parameters: dict[str, Any] | None = None,
) -> None:
"""Initialize a transformed structure from a structure.
Args:
structure (Structure): Input structure
transformations (list[Transformation]): List of transformations to apply.
history (list[Transformation]): Previous history.
other_parameters (dict): Additional parameters to be added.
"""
self.final_structure = structure
self.history = history or []
self.other_parameters = other_parameters or {}
self._undone: list[tuple[AbstractTransformation | dict[str, Any], Structure]] = []
if isinstance(transformations, AbstractTransformation):
transformations = [transformations]
transformations = transformations or []
for trafo in transformations:
self.append_transformation(trafo)
def undo_last_change(self) -> None:
"""Undo the last change in the TransformedStructure.
Raises:
IndexError: If already at the oldest change.
"""
if len(self.history) == 0:
raise IndexError("No more changes to undo")
if "input_structure" not in self.history[-1]:
raise IndexError("Can't undo. Latest history has no input_structure")
h = self.history.pop()
self._undone.append((h, self.final_structure))
struct = h["input_structure"]
if isinstance(struct, dict):
struct = Structure.from_dict(struct)
self.final_structure = struct
def redo_next_change(self) -> None:
"""Redo the last undone change in the TransformedStructure.
Raises:
IndexError: If already at the latest change.
"""
if len(self._undone) == 0:
raise IndexError("No more changes to redo")
hist, struct = self._undone.pop()
self.history.append(hist)
self.final_structure = struct
def __getattr__(self, name: str) -> Any:
# Don't use getattr(self.final_structure, name) here to avoid infinite recursion if name = "final_structure"
struct = self.__getattribute__("final_structure")
return getattr(struct, name)
def __len__(self) -> int:
return len(self.history)
def append_transformation(
self, transformation, return_alternatives: bool = False, clear_redo: bool = True
) -> list[TransformedStructure] | None:
"""Append a transformation to the TransformedStructure.
Args:
transformation: Transformation to append
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a number, which stipulates the
total number of structures to return.
clear_redo: Boolean indicating whether to clear the redo list.
By default, this is True, meaning any appends clears the
history of undoing. However, when using append_transformation
to do a redo, the redo list should not be cleared to allow
multiple redos.
"""
if clear_redo:
self._undone = []
if return_alternatives and transformation.is_one_to_many:
ranked_list = transformation.apply_transformation(
self.final_structure, return_ranked_list=return_alternatives
)
input_structure = self.final_structure.as_dict()
alts = []
for x in ranked_list[1:]:
struct = x.pop("structure")
actual_transformation = x.pop("transformation", transformation)
h_dict = actual_transformation.as_dict()
h_dict["input_structure"] = input_structure
h_dict["output_parameters"] = x
self.final_structure = struct
dct = self.as_dict()
dct["history"].append(h_dict)
dct["final_structure"] = struct.as_dict()
alts.append(TransformedStructure.from_dict(dct))
x = ranked_list[0]
struct = x.pop("structure")
actual_transformation = x.pop("transformation", transformation)
h_dict = actual_transformation.as_dict()
h_dict["input_structure"] = self.final_structure.as_dict()
h_dict["output_parameters"] = x
self.history.append(h_dict)
self.final_structure = struct
return alts
struct = transformation.apply_transformation(self.final_structure)
h_dict = transformation.as_dict()
h_dict["input_structure"] = self.final_structure.as_dict()
h_dict["output_parameters"] = {}
self.history.append(h_dict)
self.final_structure = struct
return None
def append_filter(self, structure_filter: AbstractStructureFilter) -> None:
"""Add a filter.
Args:
structure_filter (StructureFilter): A filter implementing the
AbstractStructureFilter API. Tells transmuter what structures to retain.
"""
h_dict = structure_filter.as_dict()
h_dict["input_structure"] = self.final_structure.as_dict()
self.history.append(h_dict)
def extend_transformations(
self,
transformations: list[AbstractTransformation],
return_alternatives: bool = False,
) -> None:
"""Extend a sequence of transformations to the TransformedStructure.
Args:
transformations: Sequence of Transformations
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a number, which stipulates the
total number of structures to return.
"""
for trafo in transformations:
self.append_transformation(trafo, return_alternatives=return_alternatives)
def get_vasp_input(self, vasp_input_set: type[VaspInputSet] = MPRelaxSet, **kwargs) -> dict[str, Any]:
"""Get VASP input as a dict of VASP objects.
Args:
vasp_input_set (VaspInputSet): input set
to create VASP input files from structures
**kwargs: All keyword args supported by the VASP input set.
"""
dct = vasp_input_set(self.final_structure, **kwargs).get_vasp_input()
dct["transformations.json"] = json.dumps(self.as_dict())
return dct
def write_vasp_input(
self,
vasp_input_set: type[VaspInputSet] = MPRelaxSet,
output_dir: str = ".",
create_directory: bool = True,
**kwargs,
) -> None:
"""Write VASP input to an output_dir.
Args:
vasp_input_set: pymatgen.io.vasp.sets.VaspInputSet like object that creates vasp input files from
structures.
output_dir: Directory to output files
create_directory: Create the directory if not present. Defaults to
True.
**kwargs: All keyword args supported by the VASP input set.
"""
vasp_input_set(self.final_structure, **kwargs).write_input(output_dir, make_dir_if_not_present=create_directory)
with open(f"{output_dir}/transformations.json", mode="w", encoding="utf-8") as file:
json.dump(self.as_dict(), file)
def __str__(self) -> str:
output = [
"Current structure",
"------------",
str(self.final_structure),
"\nHistory",
"------------",
]
for hist in self.history:
hist.pop("input_structure", None)
output.append(str(hist))
output += ("\nOther parameters", "------------", str(self.other_parameters))
return "\n".join(output)
def set_parameter(self, key: str, value: Any) -> TransformedStructure:
"""Set a parameter.
Args:
key (str): The string key.
value (Any): The value.
Returns:
TransformedStructure
"""
self.other_parameters[key] = value
return self
@property
def was_modified(self) -> bool:
"""Boolean describing whether the last transformation on the structure
made any alterations to it one example of when this would return false
is in the case of performing a substitution transformation on the
structure when the specie to replace isn't in the structure.
"""
return self.final_structure != self.structures[-2]
@property
def structures(self) -> list[Structure]:
"""Copy of all structures in the TransformedStructure. A
structure is stored after every single transformation.
"""
h_structs = [Structure.from_dict(s["input_structure"]) for s in self.history if "input_structure" in s]
return [*h_structs, self.final_structure]
@classmethod
def from_cif_str(
cls,
cif_string: str,
transformations: list[AbstractTransformation] | None = None,
primitive: bool = True,
occupancy_tolerance: float = 1.0,
) -> Self:
"""Generate TransformedStructure from a CIF string.
Args:
cif_string (str): Input CIF string. Should contain only one
structure. For CIFs containing multiple structures, please use
CifTransmuter.
transformations (list[Transformation]): Sequence of transformations
to be applied to the input structure.
primitive (bool): Option to set if the primitive cell should be
extracted. Defaults to True. However, there are certain
instances where you might want to use a non-primitive cell,
e.g. if you are trying to generate all possible orderings of
partial removals or order a disordered structure. Defaults to True.
occupancy_tolerance (float): If total occupancy of a site is
between 1 and occupancy_tolerance, the occupancies will be
scaled down to 1.
Returns:
TransformedStructure
"""
parser = CifParser.from_str(cif_string, occupancy_tolerance=occupancy_tolerance)
raw_str = re.sub(r"'", '"', cif_string)
cif_dict = parser.as_dict()
cif_keys = list(cif_dict)
struct = parser.parse_structures(primitive=primitive)[0]
partial_cif = cif_dict[cif_keys[0]]
if "_database_code_ICSD" in partial_cif:
source = partial_cif["_database_code_ICSD"] + "-ICSD"
else:
source = "uploaded cif"
source_info = {
"source": source,
"datetime": str(datetime.now(tz=timezone.utc)),
"original_file": raw_str,
"cif_data": cif_dict[cif_keys[0]],
}
return cls(struct, transformations, history=[source_info])
@classmethod
def from_poscar_str(
cls,
poscar_string: str,
transformations: list[AbstractTransformation] | None = None,
) -> Self:
"""Generate TransformedStructure from a poscar string.
Args:
poscar_string (str): Input POSCAR string.
transformations (list[Transformation]): Sequence of transformations
to be applied to the input structure.
"""
poscar = Poscar.from_str(poscar_string)
if not poscar.true_names:
raise ValueError(
"Transformation can be created only from POSCAR strings with proper VASP5 element symbols."
)
raw_str = re.sub(r"'", '"', poscar_string)
struct = poscar.structure
source_info = {
"source": "POSCAR",
"datetime": str(datetime.now(tz=timezone.utc)),
"original_file": raw_str,
}
return cls(struct, transformations, history=[source_info])
def as_dict(self) -> dict[str, Any]:
"""Dict representation of the TransformedStructure."""
dct = self.final_structure.as_dict()
dct["@module"] = type(self).__module__
dct["@class"] = type(self).__name__
dct["history"] = jsanitize(self.history)
dct["last_modified"] = str(datetime.now(timezone.utc))
dct["other_parameters"] = jsanitize(self.other_parameters)
return dct
@classmethod
def from_dict(cls, dct: dict) -> Self:
"""Create a TransformedStructure from a dict."""
struct = Structure.from_dict(dct)
return cls(struct, history=dct["history"], other_parameters=dct.get("other_parameters"))
def to_snl(self, authors: list[str], **kwargs) -> StructureNL:
"""Generate a StructureNL from TransformedStructure.
Args:
authors (List[str]): List of authors contributing to the generated StructureNL.
**kwargs (Any): All kwargs supported by StructureNL.
Returns:
StructureNL: The generated StructureNL object.
"""
if self.other_parameters:
warn("Data in TransformedStructure.other_parameters discarded during type conversion to SNL")
history = []
for hist in self.history:
snl_metadata = hist.pop("_snl", {})
history += [
{
"name": snl_metadata.pop("name", "pymatgen"),
"url": snl_metadata.pop("url", "http://pypi.python.org/pypi/pymatgen"),
"description": hist,
}
]
return StructureNL(self.final_structure, authors, history=history, **kwargs)
@classmethod
def from_snl(cls, snl: StructureNL) -> Self:
"""Create TransformedStructure from SNL.
Args:
snl (StructureNL): Starting snl
Returns:
TransformedStructure
"""
history: list[dict] = []
for hist in snl.history:
dct = hist.description
dct["_snl"] = {"url": hist.url, "name": hist.name}
history.append(dct)
return cls(snl.structure, history=history)