-
Notifications
You must be signed in to change notification settings - Fork 62
/
thermo.py
303 lines (252 loc) · 11.5 KB
/
thermo.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
from collections import defaultdict
from datetime import datetime
from itertools import chain
from typing import Dict, Iterator, List, Optional, Set, Tuple
from icecream import ic
from maggma.core import Builder, Store
from monty.json import MontyDecoder
from pymatgen import Structure
from pymatgen.analysis.phase_diagram import PhaseDiagram, PhaseDiagramError
from pymatgen.analysis.structure_analyzer import oxide_type
from pymatgen.entries.compatibility import MaterialsProjectCompatibility
from pymatgen.entries.computed_entries import ComputedEntry, ComputedStructureEntry
from emmet.core.utils import jsanitize
from emmet.builders.utils import (
chemsys_permutations,
maximal_spanning_non_intersecting_subsets,
)
from emmet.core.thermo import ThermoDoc
from emmet.core.vasp.calc_types import run_type
class Thermo(Builder):
def __init__(
self,
materials: Store,
thermo: Store,
query: Optional[Dict] = None,
use_statics: bool = False,
compatibility=None,
**kwargs,
):
"""
Calculates thermodynamic quantities for materials from phase
diagram constructions
Args:
materials (Store): Store of materials documents
thermo (Store): Store of thermodynamic data such as formation
energy and decomposition pathway
query (dict): dictionary to limit materials to be analyzed
use_statics: Use the statics to compute thermodynamic information
compatibility (PymatgenCompatability): Compatability module
to ensure energies are compatible
"""
self.materials = materials
self.thermo = thermo
self.query = query if query else {}
self.compatibility = (
compatibility
if compatibility
else MaterialsProjectCompatibility("Advanced")
)
self._completed_tasks = set()
self._entries_cache = defaultdict(list)
super().__init__(sources=[materials], targets=[thermo], **kwargs)
def ensure_indexes(self):
"""
Ensures indicies on the tasks and materials collections
"""
# Search index for materials
self.materials.ensure_index("material_id")
self.materials.ensure_index("sandboxes")
self.materials.ensure_index("last_updated")
# Search index for thermo
self.thermo.ensure_index("material_id")
self.thermo.ensure_index("last_updated")
def get_items(self) -> Iterator[List[Dict]]:
"""
Gets whole chemical systems of entries to process
"""
self.logger.info("Thermo Builder Started")
self.logger.info("Setting indexes")
self.ensure_indexes()
updated_chemsys = self.get_updated_chemsys()
new_chemsys = self.get_new_chemsys()
affected_chemsys = self.get_affected_chemsys(updated_chemsys | new_chemsys)
# Remove overlapping chemical systems
to_process_chemsys = set()
for chemsys in updated_chemsys | new_chemsys | affected_chemsys:
if chemsys not in to_process_chemsys:
to_process_chemsys |= chemsys_permutations(chemsys)
self.logger.info(
f"Found {len(to_process_chemsys)} chemical systems with new/updated materials to process"
)
self.total = len(to_process_chemsys)
# Yield the chemical systems in order of increasing size
# Will build them in a similar manner to fast Pourbaix
for chemsys in sorted(to_process_chemsys, key=lambda x: len(x.split("-"))):
entries = self.get_entries(chemsys)
yield entries
# # build sandbox sets: ["a"] , ["a","b"], ["core","a","b"]
# sandbox_sets = set(
# [frozenset(entry.data.get("sandboxes", {})) for entry in entries]
# )
# sandbox_sets = maximal_spanning_non_intersecting_subsets(sandbox_sets)
# self.logger.debug(f"Found {len(sandbox_sets)}: {sandbox_sets}")
#
# for sandboxes in sandbox_sets:
# # only yield maximal subsets so that we can process a equivalent sandbox combinations at a time
# sandbox_entries = [
# entry
# for entry in entries
# if all(
# sandbox in entry.data.get("_sbxn", []) for sandbox in sandboxes
# )
# ]
#
# yield sandboxes, sandbox_entries
def process_item(self, item: Tuple[List[str], List[ComputedEntry]]):
entries = item
entries = [ComputedStructureEntry.from_dict(entry) for entry in entries]
# determine chemsys
elements = sorted(
set([el.symbol for e in entries for el in e.composition.elements])
)
chemsys = "-".join(elements)
self.logger.debug(f"Procesing {len(entries)} entries for {chemsys}")
material_entries = defaultdict(lambda: defaultdict(list))
pd_entries = []
for entry in entries:
material_entries[entry.entry_id][entry.data["run_type"]].append(entry)
# TODO: How to make this general and controllable via SETTINGS?
for material_id in material_entries:
if "GGA+U" in material_entries[material_id]:
pd_entries.extend(material_entries[material_id]["GGA+U"])
elif "GGA" in material_entries[material_id]:
pd_entries.extend(material_entries[material_id]["GGA"])
pd_entries = self.compatibility.process_entries(pd_entries)
try:
docs = ThermoDoc.from_entries(pd_entries)
for doc in docs:
doc.entries = material_entries[doc.material_id]
doc.entry_types = list(material_entries[doc.material_id].keys())
except PhaseDiagramError as p:
elsyms = []
for e in entries:
elsyms.extend([el.symbol for el in e.composition.elements])
self.logger.warning(
f"Phase diagram errorin chemsys {'-'.join(sorted(set(elsyms)))}: {p}"
)
return []
except Exception as e:
self.logger.error(f"Got unexpected error: {e}")
return []
return [d.dict() for d in docs]
def update_targets(self, items):
"""
Inserts the thermo docs into the thermo collection
Args:
items ([[dict]]): a list of list of thermo dictionaries to update
"""
# flatten out lists
items = list(filter(None, chain.from_iterable(items)))
# check for duplicates within this set
# items = list(
# {(v[self.thermo.key], frozenset(v["sandboxes"])): v for v in items}.values()
# )
# Check if already updated this run
items = [i for i in items if i[self.thermo.key] not in self._completed_tasks]
self._completed_tasks |= {i[self.thermo.key] for i in items}
for item in items:
if isinstance(item["last_updated"], dict):
item["last_updated"] = MontyDecoder().process_decoded(
item["last_updated"]
)
if len(items) > 0:
self.logger.info(f"Updating {len(items)} thermo documents")
self.thermo.update(docs=jsanitize(items), key=[self.thermo.key])
else:
self.logger.info("No items to update")
def get_entries(self, chemsys: str) -> List[Dict]:
"""
Gets a entries from the tasks collection for the corresponding chemical systems
Args:
chemsys(str): a chemical system represented by string elements seperated by a dash (-)
Returns:
set(ComputedEntry): a set of entries for this system
"""
self.logger.info(f"Getting entries for: {chemsys}")
# First check the cache
all_chemsys = chemsys_permutations(chemsys)
cached_chemsys = all_chemsys & set(self._entries_cache.keys())
query_chemsys = all_chemsys - cached_chemsys
all_entries = list(
chain.from_iterable(self._entries_cache[c] for c in cached_chemsys)
)
self.logger.debug(
f"Getting {len(cached_chemsys)} sub-chemsys from cache for {chemsys}"
)
self.logger.debug(
f"Getting {len(query_chemsys)} sub-chemsys from DB for {chemsys}"
)
# Second grab the materials docs
new_q = dict(self.query)
new_q["chemsys"] = {"$in": list(query_chemsys)}
new_q["deprecated"] = False
materials_docs = list(
self.materials.query(
criteria=new_q, properties=[self.materials.key, "entries", "structure"]
)
)
self.logger.debug(
f"Got {len(materials_docs)} entries from DB for {len(query_chemsys)} sub-chemsys for {chemsys}"
)
# Convert the entries into ComputedEntries and store
for doc in materials_docs:
for r_type, entry_dict in doc.get("entries", {}).items():
entry_dict["data"]["run_type"] = r_type
elsyms = sorted(set([el for el in entry_dict["composition"]]))
self._entries_cache["-".join(elsyms)].append(entry_dict)
all_entries.append(entry_dict)
self.logger.info(f"Total entries in {chemsys} : {len(all_entries)}")
return all_entries
def get_updated_chemsys(
self,
) -> Set:
""" Gets updated chemical system as defined by the updating of an existing material """
updated_mats = self.thermo.newer_in(self.materials, criteria=self.query)
updated_chemsys = set(
self.materials.distinct(
"chemsys", {self.materials.key: {"$in": list(updated_mats)}}
)
)
self.logger.debug(f"Found {len(updated_chemsys)} updated chemical systems")
return updated_chemsys
def get_new_chemsys(self) -> Set:
""" Gets newer chemical system as defined by introduction of a new material """
# All materials that are not present in the thermo collection
thermo_mat_ids = self.thermo.distinct(self.thermo.key)
mat_ids = self.materials.distinct(self.materials.key, self.query)
dif_task_ids = list(set(mat_ids) - set(thermo_mat_ids))
q = {"task_id": {"$in": dif_task_ids}}
new_mat_chemsys = set(self.materials.distinct("chemsys", q))
self.logger.debug(f"Found {len(new_mat_chemsys)} new chemical systems")
return new_mat_chemsys
def get_affected_chemsys(self, chemical_systems: Set) -> Set:
""" Gets chemical systems affected by changes in the supplied chemical systems """
# First get all chemsys with any of the elements we've marked
affected_chemsys = set()
affected_els = list({el for c in chemical_systems for el in c.split("-")})
possible_affected_chemsys = self.materials.distinct(
"chemsys", {"elements": {"$in": affected_els}}
)
sub_chemsys = defaultdict(list)
# Build a dictionary mapping sub_chemsys to all super_chemsys
for chemsys in possible_affected_chemsys:
for permutation in chemsys_permutations(chemsys):
sub_chemsys[permutation].append(chemsys)
# Select and merge distinct super chemsys from sub_chemsys
for chemsys in chemical_systems:
affected_chemsys |= set(sub_chemsys[chemsys])
self.logger.debug(
f"Found {len(affected_chemsys)} chemical systems affected by this build"
)
return affected_chemsys