-
Notifications
You must be signed in to change notification settings - Fork 875
/
Copy pathmatproj_legacy.py
1664 lines (1439 loc) · 69.3 KB
/
matproj_legacy.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module provides classes to interface with the Materials Project REST
API v1 to enable the creation of data structures and pymatgen objects using
Materials Project data.
"""
from __future__ import annotations
import itertools
import json
import logging
import math
import os
import platform
import re
import sys
import warnings
from enum import Enum, unique
from time import sleep
from typing import TYPE_CHECKING
import requests
from monty.json import MontyDecoder, MontyEncoder
from ruamel.yaml import YAML
from tqdm import tqdm
from pymatgen.core import SETTINGS, Composition, Element, Structure
from pymatgen.core import __version__ as PMG_VERSION
from pymatgen.core.surface import get_symmetrically_equivalent_miller_indices
from pymatgen.entries.compatibility import MaterialsProject2020Compatibility
from pymatgen.entries.computed_entries import ComputedEntry, ComputedStructureEntry
from pymatgen.entries.exp_entries import ExpEntry
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.util.due import Doi, due
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, Literal
from typing_extensions import Self
from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine
from pymatgen.phonon.dos import CompletePhononDos
logger = logging.getLogger(__name__)
MP_LOG_FILE = os.path.join(os.path.expanduser("~"), ".mprester.log.yaml")
@unique
class TaskType(Enum):
"""task types available in legacy MP data."""
GGA_OPT = "GGA Structure Optimization"
GGAU_OPT = "GGA+U Structure Optimization"
SCAN_OPT = "SCAN Structure Optimization"
GGA_LINE = "GGA NSCF Line"
GGAU_LINE = "GGA+U NSCF Line"
GGA_UNIFORM = "GGA NSCF Uniform"
GGAU_UNIFORM = "GGA+U NSCF Uniform"
GGA_STATIC = "GGA Static"
GGAU_STATIC = "GGA+U Static"
GGA_STATIC_DIEL = "GGA Static Dielectric"
GGAU_STATIC_DIEL = "GGA+U Static Dielectric"
GGA_DEF = "GGA Deformation"
GGAU_DEF = "GGA+U Deformation"
LDA_STATIC_DIEL = "LDA Static Dielectric"
class _MPResterLegacy:
"""A class to conveniently interface with the Materials Project REST interface.
The recommended way to use MPRester is with the "with" context manager to ensure
sessions are properly closed after usage.
with MPRester("API_KEY") as mpr:
mpr.some_method()
MPRester uses the "requests" package, which provides for HTTP connection
pooling. All connections are made via https for security.
For more advanced uses of the legacy Materials API, please consult the API
documentation at https://github.com/materialsproject/mapidoc.
Note that this class is for the *legacy* API. Upcoming changes to the
Materials Project api are described at https://materialsproject.org/api.
"""
supported_properties = (
"energy",
"energy_per_atom",
"volume",
"formation_energy_per_atom",
"nsites",
"unit_cell_formula",
"pretty_formula",
"is_hubbard",
"elements",
"nelements",
"e_above_hull",
"hubbards",
"is_compatible",
"spacegroup",
"task_ids",
"band_gap",
"density",
"icsd_id",
"icsd_ids",
"cif",
"total_magnetization",
"material_id",
"oxide_type",
"tags",
"elasticity",
)
supported_task_properties = (
"energy",
"energy_per_atom",
"volume",
"formation_energy_per_atom",
"nsites",
"unit_cell_formula",
"pretty_formula",
"is_hubbard",
"elements",
"nelements",
"e_above_hull",
"hubbards",
"is_compatible",
"spacegroup",
"band_gap",
"density",
"icsd_id",
"cif",
)
def __init__(
self,
api_key: str | None = None,
endpoint: str | None = None,
notify_db_version: bool = True,
include_user_agent: bool = True,
) -> None:
"""
Args:
api_key (str): A String API key for accessing the MaterialsProject
REST interface. Please obtain your API key at
https://materialsproject.org/dashboard. If this is None,
the code will check if there is a "PMG_MAPI_KEY" setting.
If so, it will use that environment variable. This makes
easier for heavy users to simply add this environment variable to
their setups and MPRester can then be called without any arguments.
endpoint (str): Url of endpoint to access the MaterialsProject REST
interface. Defaults to the standard Materials Project REST
address at "https://legacy.materialsproject.org/rest/v2", but
can be changed to other urls implementing a similar interface.
notify_db_version (bool): If True, the current MP database version will
be retrieved and logged locally in the ~/.pmgrc.yaml. If the database
version changes, you will be notified. The current database version is
also printed on instantiation. These local logs are not sent to
materialsproject.org and are not associated with your API key, so be
aware that a notification may not be presented if you run MPRester
from multiple computing environments.
include_user_agent (bool): If True, will include a user agent with the
HTTP request including information on pymatgen and system version
making the API request. This helps MP support pymatgen users, and
is similar to what most web browsers send with each page request.
Set to False to disable the user agent.
"""
warnings.warn(
"You are using the legacy MPRester. This version of the MPRester will no longer be updated. "
"To access the latest data with the new MPRester, obtain a new API key from "
"https://materialsproject.org/api and consult the docs at https://docs.materialsproject.org/ "
"for more information."
)
if api_key is not None:
self.api_key = api_key
else:
self.api_key = SETTINGS.get("PMG_MAPI_KEY", "")
if endpoint is not None:
self.preamble = endpoint
else:
self.preamble = SETTINGS.get("PMG_MAPI_ENDPOINT", "https://legacy.materialsproject.org/rest/v2")
if self.preamble != "https://legacy.materialsproject.org/rest/v2":
warnings.warn(f"Non-default endpoint used: {self.preamble}")
self.session = requests.Session()
self.session.headers = {"x-api-key": self.api_key}
if include_user_agent:
pymatgen_info = f"pymatgen/{PMG_VERSION}"
python_info = f"Python/{sys.version.split()[0]}"
platform_info = f"{platform.system()}/{platform.release()}"
self.session.headers["user-agent"] = f"{pymatgen_info} ({python_info} {platform_info})"
if notify_db_version:
yaml = YAML()
db_version = self.get_database_version()
logger.debug(f"Connection established to Materials Project database, version {db_version}.")
try:
with open(MP_LOG_FILE) as file:
dct = dict(yaml.load(file)) or {}
except (OSError, TypeError):
# TypeError: 'NoneType' object is not iterable occurs if MP_LOG_FILE exists but is empty
dct = {}
if "MAPI_DB_VERSION" not in dct:
dct["MAPI_DB_VERSION"] = {"LOG": {}, "LAST_ACCESSED": None}
else:
# ensure data is parsed as dict, rather than ordered dict,
# due to change in YAML parsing behavior
dct["MAPI_DB_VERSION"] = dict(dct["MAPI_DB_VERSION"])
if "LOG" in dct["MAPI_DB_VERSION"]:
dct["MAPI_DB_VERSION"]["LOG"] = dict(dct["MAPI_DB_VERSION"]["LOG"])
# store a log of what database versions are being connected to
if db_version not in dct["MAPI_DB_VERSION"]["LOG"]:
dct["MAPI_DB_VERSION"]["LOG"][db_version] = 1
else:
dct["MAPI_DB_VERSION"]["LOG"][db_version] += 1
# alert user if db version changed
last_accessed = dct["MAPI_DB_VERSION"]["LAST_ACCESSED"]
if last_accessed and last_accessed != db_version:
print(
f"This database version has changed from the database last accessed ({last_accessed}).\n"
f"Please see release notes on materialsproject.org for information about what has changed."
)
dct["MAPI_DB_VERSION"]["LAST_ACCESSED"] = db_version
# write out new database log if possible
# base Exception is not ideal (perhaps a PermissionError, etc.) but this is not critical
# and should be allowed to fail regardless of reason
try:
with open(MP_LOG_FILE, mode="w") as file:
yaml.dump(dct, file)
except Exception:
pass
def __enter__(self) -> Self:
"""Support for "with" context."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Support for "with" context."""
self.session.close()
def _make_request(
self,
sub_url: str,
payload: Any = None,
method: Literal["GET", "POST", "PUT", "DELETE"] = "GET",
mp_decode: bool = True,
) -> Any:
response = None
url = f"{self.preamble}{sub_url}"
try:
if method == "POST":
response = self.session.post(url, data=payload, verify=True)
else:
response = self.session.get(url, params=payload, verify=True)
if response.status_code in [200, 400]:
data = json.loads(response.text, cls=MontyDecoder) if mp_decode else json.loads(response.text)
if data["valid_response"]:
if data.get("warning"):
warnings.warn(data["warning"])
return data["response"]
raise MPRestError(data["error"])
raise MPRestError(f"REST query returned with error status code {response.status_code}")
except Exception as exc:
msg = f"{exc}. Content: {getattr(response, 'content', str(exc))}"
raise MPRestError(msg)
def get_database_version(self) -> str:
"""The Materials Project database is periodically updated and has a
database version associated with it. When the database is updated,
consolidated data (information about "a material") may and does
change, while calculation data about a specific calculation task
remains unchanged and available for querying via its task_id.
The database version is set as a date in the format YYYY-MM-DD,
where "-DD" may be optional. An additional numerical suffix
might be added if multiple releases happen on the same day.
Returns:
str: database version
"""
dct = self._make_request("/api_check")
return dct["version"]["db"]
def get_materials_id_from_task_id(self, task_id) -> str:
"""Get a new MP materials id from a task id (which can be
equivalent to an old materials id).
Args:
task_id (str): A task id.
Returns:
str: An MP material id.
"""
return self._make_request(f"/materials/mid_from_tid/{task_id}")
def get_materials_id_references(self, material_id):
"""Get all references for a materials id.
Args:
material_id (str): A material id.
Returns:
str: A BibTeX formatted string.
"""
return self._make_request(f"/materials/{material_id}/refs")
def get_data(self, chemsys_formula_id, data_type="vasp", prop=""):
"""Flexible method to get any data using the Materials Project REST
interface. Generally used by other methods for more specific queries.
Format of REST return is *always* a list of dict (regardless of the
number of pieces of data returned. The general format is as follows:
[{"material_id": material_id, "property_name" : value}, ...]
This is generally a call to
https://materialsproject.org/rest/v2/materials/vasp/<prop>.
See https://github.com/materialsproject/mapidoc for details.
Args:
chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O),
or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234).
data_type (str): Type of data to return. Currently can either be
"vasp" or "exp".
prop (str): Property to be obtained. Should be one of the
MPRester.supported_task_properties. Leave as empty string for a
general list of useful properties.
"""
sub_url = f"/materials/{chemsys_formula_id}/{data_type}"
if prop:
sub_url += "/" + prop
return self._make_request(sub_url)
def get_materials_ids(self, chemsys_formula):
"""Get all materials ids for a formula or chemsys.
Args:
chemsys_formula (str): A chemical system (e.g., Li-Fe-O),
or formula (e.g., Fe2O3).
Returns:
list[str]: all materials ids.
"""
return self._make_request(f"/materials/{chemsys_formula}/mids", mp_decode=False)
# For backwards compatibility.
get_material_id = get_materials_ids
def get_doc(self, materials_id):
"""Get the entire data document for one materials id. Use this judiciously.
REST Endpoint: https://materialsproject.org/materials/<mp-id>/doc.
Args:
materials_id (str): e.g. mp-1143 for Al2O3
Returns:
Dict of JSON document of all data that is displayed on a materials
details page.
"""
return self._make_request(f"/materials/{materials_id}/doc", mp_decode=False)
def get_xas_data(self, material_id, absorbing_element):
"""Get X-ray absorption spectroscopy data for absorbing element in the
structure corresponding to a material_id. Only X-ray Absorption Near Edge
Structure (XANES) for K-edge is supported.
REST Endpoint:
https://materialsproject.org/materials/<mp-id>/xas/<absorbing_element>.
Args:
material_id (str): e.g. mp-1143 for Al2O3
absorbing_element (str): The absorbing element in the corresponding
structure. e.g. Al in Al2O3
"""
element_list = self.get_data(material_id, prop="elements")[0]["elements"]
if absorbing_element not in element_list:
raise ValueError(
f"{absorbing_element} element not contained in corresponding structure with mp_id: {material_id}"
)
data = self._make_request(
f"/materials/{material_id}/xas/{absorbing_element}",
mp_decode=False,
)
return data[0]
def get_task_data(self, chemsys_formula_id, prop=""):
"""Flexible method to get any data using the Materials Project REST
interface. Generally used by other methods for more specific queries.
Unlike the :func:`get_data`_, this method queries the task collection
for specific run information.
Format of REST return is *always* a list of dict (regardless of the
number of pieces of data returned. The general format is as follows:
[{"material_id": material_id, "property_name" : value}, ...]
Args:
chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O),
or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234).
prop (str): Property to be obtained. Should be one of the
MPRester.supported_properties. Leave as empty string for a
general list of useful properties.
"""
sub_url = f"/tasks/{chemsys_formula_id}"
if prop:
sub_url += "/" + prop
return self._make_request(sub_url)
def get_structures(self, chemsys_formula_id, final=True):
"""Get a list of Structures corresponding to a chemical system, formula,
or materials_id.
Args:
chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O),
or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234).
final (bool): Whether to get the final structure, or the initial
(pre-relaxation) structure. Defaults to True.
Returns:
List of Structure objects.
"""
prop = "final_structure" if final else "initial_structure"
data = self.get_data(chemsys_formula_id, prop=prop)
return [d[prop] for d in data]
def find_structure(self, filename_or_structure):
"""Find matching structures on the Materials Project site.
Args:
filename_or_structure: filename or Structure object
Returns:
A list of matching materials project ids for structure.
Raises:
MPRestError
"""
if isinstance(filename_or_structure, str):
struct = Structure.from_file(filename_or_structure)
elif isinstance(filename_or_structure, Structure):
struct = filename_or_structure
else:
raise MPRestError("Provide filename or Structure object.")
payload = {"structure": json.dumps(struct.as_dict(), cls=MontyEncoder)}
response = self.session.post(f"{self.preamble}/find_structure", data=payload)
if response.status_code in [200, 400]:
response = json.loads(response.text, cls=MontyDecoder)
if response["valid_response"]:
return response["response"]
raise MPRestError(response["error"])
raise MPRestError(f"REST error with status code {response.status_code} and error {response.text}")
def get_entries(
self,
chemsys_formula_id_criteria: str | dict[str, Any],
compatible_only: bool = True,
inc_structure: bool | Literal["initial"] | None = None,
property_data: list[str] | None = None,
conventional_unit_cell: bool = False,
sort_by_e_above_hull: bool = False,
) -> list[ComputedEntry]:
"""Get a list of ComputedEntries or ComputedStructureEntries corresponding
to a chemical system, formula, or materials_id or full criteria.
Args:
chemsys_formula_id_criteria (str/dict): A chemical system
(e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id
(e.g., mp-1234) or full Mongo-style dict criteria.
compatible_only (bool): Whether to return only "compatible"
entries. Compatible entries are entries that have been
processed using the MaterialsProject2020Compatibility class,
which performs adjustments to allow mixing of GGA and GGA+U
calculations for more accurate phase diagrams and reaction
energies.
inc_structure (str): If None, entries returned are
ComputedEntries. If inc_structure="initial",
ComputedStructureEntries with initial structures are returned.
Otherwise, ComputedStructureEntries with final structures
are returned.
property_data (list): Specify additional properties to include in
entry.data. If None, no data. Should be a subset of
supported_properties.
conventional_unit_cell (bool): Whether to get the standard
conventional unit cell
sort_by_e_above_hull (bool): Whether to sort the list of entries by
e_above_hull (will query e_above_hull as a property_data if True).
Returns:
List of ComputedEntry or ComputedStructureEntry objects.
"""
# TODO: This is a very hackish way of doing this. It should be fixed
# on the REST end.
params = [
"run_type",
"is_hubbard",
"pseudo_potential",
"hubbards",
"potcar_symbols",
"oxide_type",
]
props = ["energy", "unit_cell_formula", "task_id", *params]
if sort_by_e_above_hull:
if property_data and "e_above_hull" not in property_data:
property_data.append("e_above_hull")
elif not property_data:
property_data = ["e_above_hull"]
if property_data:
props += property_data
if inc_structure:
if inc_structure == "initial":
props.append("initial_structure")
else:
props.append("structure")
if not isinstance(chemsys_formula_id_criteria, dict):
criteria = _MPResterLegacy.parse_criteria(chemsys_formula_id_criteria)
else:
criteria = chemsys_formula_id_criteria
data = self.query(criteria, props)
entries: list[ComputedEntry] = []
for d in data:
d["potcar_symbols"] = [
f"{d['pseudo_potential']['functional']} {label}" for label in d["pseudo_potential"]["labels"]
]
data = {"oxide_type": d["oxide_type"]}
if property_data:
data |= {k: d[k] for k in property_data}
if not inc_structure:
e = ComputedEntry(
d["unit_cell_formula"],
d["energy"],
parameters={k: d[k] for k in params},
data=data,
entry_id=d["task_id"],
)
else:
prim = d["initial_structure"] if inc_structure == "initial" else d["structure"]
if conventional_unit_cell:
struct = SpacegroupAnalyzer(prim).get_conventional_standard_structure()
energy = d["energy"] * (len(struct) / len(prim))
else:
struct = prim.copy()
energy = d["energy"]
e = ComputedStructureEntry(
struct,
energy,
parameters={k: d[k] for k in params},
data=data,
entry_id=d["task_id"],
)
entries.append(e)
if compatible_only:
# suppress the warning about missing oxidation states
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="Failed to guess oxidation states.*")
entries = MaterialsProject2020Compatibility().process_entries(entries, clean=True)
if sort_by_e_above_hull:
entries = sorted(entries, key=lambda entry: entry.data["e_above_hull"])
return entries
def get_pourbaix_entries(self, chemsys, solid_compat="MaterialsProject2020Compatibility"):
"""A helper function to get all entries necessary to generate
a Pourbaix diagram from the rest interface.
Args:
chemsys (str | list[str]): Chemical system string comprising element
symbols separated by dashes, e.g. "Li-Fe-O" or List of element
symbols, e.g. ["Li", "Fe", "O"].
solid_compat: Compatibility scheme used to pre-process solid DFT energies prior to applying aqueous
energy adjustments. May be passed as a class (e.g. MaterialsProject2020Compatibility) or an instance
(e.g., MaterialsProject2020Compatibility()). If None, solid DFT energies are used as-is.
Default: MaterialsProject2020Compatibility
"""
# imports are not top-level due to expense
from pymatgen.analysis.phase_diagram import PhaseDiagram
from pymatgen.analysis.pourbaix_diagram import IonEntry, PourbaixEntry
from pymatgen.core.ion import Ion
from pymatgen.entries.compatibility import (
Compatibility,
MaterialsProject2020Compatibility,
MaterialsProjectAqueousCompatibility,
MaterialsProjectCompatibility,
)
if solid_compat == "MaterialsProjectCompatibility":
self.solid_compat = MaterialsProjectCompatibility()
elif solid_compat == "MaterialsProject2020Compatibility":
self.solid_compat = MaterialsProject2020Compatibility()
elif isinstance(solid_compat, Compatibility):
self.solid_compat = solid_compat
else:
raise ValueError(
"Solid compatibility can only be 'MaterialsProjectCompatibility', "
"'MaterialsProject2020Compatibility', or an instance of a Compatibility class"
)
pbx_entries = []
if isinstance(chemsys, str):
chemsys = chemsys.split("-")
# Get ion entries first, because certain ions have reference
# solids that aren't necessarily in the chemsys (Na2SO4)
url = "/pourbaix_diagram/reference_data/" + "-".join(chemsys)
ion_data = self._make_request(url)
ion_ref_comps = [Composition(d["Reference Solid"]) for d in ion_data]
ion_ref_elts = list(itertools.chain.from_iterable(i.elements for i in ion_ref_comps))
ion_ref_entries = self.get_entries_in_chemsys(
list(set([str(e) for e in ion_ref_elts] + ["O", "H"])),
property_data=["e_above_hull"],
compatible_only=False,
)
# suppress the warning about supplying the required energies; they will be calculated from the
# entries we get from MPRester
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="You did not provide the required O2 and H2O energies.",
)
compat = MaterialsProjectAqueousCompatibility(solid_compat=self.solid_compat)
# suppress the warning about missing oxidation states
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="Failed to guess oxidation states.*")
ion_ref_entries = compat.process_entries(ion_ref_entries)
ion_ref_pd = PhaseDiagram(ion_ref_entries)
# position the ion energies relative to most stable reference state
for n, i_d in enumerate(ion_data):
ion = Ion.from_formula(i_d["Name"])
refs = [e for e in ion_ref_entries if e.reduced_formula == i_d["Reference Solid"]]
if not refs:
raise ValueError("Reference solid not contained in entry list")
stable_ref = min(refs, key=lambda x: x.data["e_above_hull"])
rf = stable_ref.composition.get_reduced_composition_and_factor()[1]
solid_diff = ion_ref_pd.get_form_energy(stable_ref) - i_d["Reference solid energy"] * rf
elt = i_d["Major_Elements"][0]
correction_factor = ion.composition[elt] / stable_ref.composition[elt]
energy = i_d["Energy"] + solid_diff * correction_factor
ion_entry = IonEntry(ion, energy)
pbx_entries.append(PourbaixEntry(ion_entry, f"ion-{n}"))
# Construct the solid Pourbaix entries from filtered ion_ref entries
extra_elts = set(ion_ref_elts) - {Element(s) for s in chemsys} - {Element("H"), Element("O")}
for entry in ion_ref_entries:
entry_elts = set(entry.elements)
# Ensure no OH chemsys or extraneous elements from ion references
if not (entry_elts <= {Element("H"), Element("O")} or extra_elts.intersection(entry_elts)):
# Create new computed entry
form_e = ion_ref_pd.get_form_energy(entry)
new_entry = ComputedEntry(entry.composition, form_e, entry_id=entry.entry_id)
pbx_entry = PourbaixEntry(new_entry)
pbx_entries.append(pbx_entry)
return pbx_entries
def get_structure_by_material_id(
self, material_id: str, final: bool = True, conventional_unit_cell: bool = False
) -> Structure:
"""Get a Structure corresponding to a material_id.
Args:
material_id (str): Materials Project ID (e.g. mp-1234).
final (bool): Whether to get the final structure, or the initial
(pre-relaxation) structure. Defaults to True.
conventional_unit_cell (bool): Whether to get the standard conventional unit cell
Returns:
Structure object.
"""
prop = "final_structure" if final else "initial_structure"
data = self.get_data(material_id, prop=prop)
if not data:
try:
new_material_id = self.get_materials_id_from_task_id(material_id)
if new_material_id:
warnings.warn(
f"The calculation task {material_id} is mapped to canonical mp-id {new_material_id}, "
f"so structure for {new_material_id} returned. This is not an error, see "
f"documentation. If original task data for {material_id} is required, use "
"get_task_data(). To find the canonical mp-id from a task id use "
"get_materials_id_from_task_id()."
)
return self.get_structure_by_material_id(new_material_id)
except MPRestError:
raise MPRestError(
f"{material_id=} unknown, if this seems like an error "
"please let us know at matsci.org/materials-project"
)
structure = data[0][prop]
if conventional_unit_cell:
structure = SpacegroupAnalyzer(structure).get_conventional_standard_structure()
return structure
def get_entry_by_material_id(
self,
material_id: str,
compatible_only: bool = True,
inc_structure: bool | Literal["initial"] | None = None,
property_data: list[str] | None = None,
conventional_unit_cell: bool = False,
) -> ComputedEntry | ComputedStructureEntry:
"""Get a ComputedEntry corresponding to a material_id.
Args:
material_id (str): Materials Project material_id (a string,
e.g. mp-1234).
compatible_only (bool): Whether to return only "compatible"
entries. Compatible entries are entries that have been
processed using the MaterialsProject2020Compatibility class,
which performs adjustments to allow mixing of GGA and GGA+U
calculations for more accurate phase diagrams and reaction
energies.
inc_structure (str): If None, entries returned are
ComputedEntries. If inc_structure="initial",
ComputedStructureEntries with initial structures are returned.
Otherwise, ComputedStructureEntries with final structures
are returned.
property_data (list): Specify additional properties to include in
entry.data. If None, no data. Should be a subset of
supported_properties.
conventional_unit_cell (bool): Whether to get the standard
conventional unit cell
Raises:
MPRestError if no data for given material_id is found.
Returns:
ComputedEntry or ComputedStructureEntry object.
"""
data = self.get_entries(
material_id,
compatible_only=compatible_only,
inc_structure=inc_structure,
property_data=property_data,
conventional_unit_cell=conventional_unit_cell,
)
if len(data) == 0:
raise MPRestError(f"{material_id = } does not exist")
return data[0]
def get_dos_by_material_id(self, material_id):
"""Get a Dos corresponding to a material_id.
REST Endpoint: https://materialsproject.org/rest/v2/materials/<mp-id>/vasp/dos
Args:
material_id (str): Materials Project material_id (a string,
e.g. mp-1234).
Returns:
A Dos object.
"""
data = self.get_data(material_id, prop="dos")
return data[0]["dos"]
def get_bandstructure_by_material_id(self, material_id, line_mode=True):
"""Get a BandStructure corresponding to a material_id.
REST Endpoint: https://materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or
https://materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure_uniform
Args:
material_id (str): Materials Project material_id.
line_mode (bool): If True, fetch a BandStructureSymmLine object
(default). If False, return the uniform band structure.
Returns:
BandStructure
"""
prop = "bandstructure" if line_mode else "bandstructure_uniform"
data = self.get_data(material_id, prop=prop)
return data[0][prop]
def get_phonon_dos_by_material_id(self, material_id: str) -> CompletePhononDos:
"""Get phonon density of states data corresponding to a material_id.
Args:
material_id (str): Materials Project material_id.
Returns:
CompletePhononDos: A phonon DOS object.
"""
return self._make_request(f"/materials/{material_id}/phonondos")
def get_phonon_bandstructure_by_material_id(self, material_id: str) -> PhononBandStructureSymmLine:
"""Get phonon dispersion data corresponding to a material_id.
Args:
material_id (str): Materials Project material_id.
Returns:
PhononBandStructureSymmLine: A phonon band structure.
"""
return self._make_request(f"/materials/{material_id}/phononbs")
def get_phonon_ddb_by_material_id(self, material_id: str) -> str:
"""Get ABINIT Derivative Data Base (DDB) output for phonon calculations.
Args:
material_id (str): Materials Project material_id.
Returns:
str: ABINIT DDB file as a string.
"""
return self._make_request(f"/materials/{material_id}/abinit_ddb")
def get_entries_in_chemsys(
self,
elements,
compatible_only=True,
inc_structure=None,
property_data=None,
conventional_unit_cell=False,
additional_criteria=None,
):
"""Helper method to get a list of ComputedEntries in a chemical system.
For example, elements = ["Li", "Fe", "O"] will return a list of all entries in the
Li-Fe-O chemical system, i.e., all LixOy, FexOy, LixFey, LixFeyOz, Li, Fe and O
phases. Extremely useful for creating phase diagrams of entire chemical systems.
Args:
elements (str | list[str]): Chemical system string comprising element
symbols separated by dashes, e.g. "Li-Fe-O" or List of element
symbols, e.g. ["Li", "Fe", "O"].
compatible_only (bool): Whether to return only "compatible"
entries. Compatible entries are entries that have been
processed using the MaterialsProject2020Compatibility class,
which performs adjustments to allow mixing of GGA and GGA+U
calculations for more accurate phase diagrams and reaction
energies.
inc_structure (str): If None, entries returned are
ComputedEntries. If inc_structure="initial",
ComputedStructureEntries with initial structures are returned.
Otherwise, ComputedStructureEntries with final structures
are returned.
property_data (list): Specify additional properties to include in
entry.data. If None, no data. Should be a subset of
supported_properties.
conventional_unit_cell (bool): Whether to get the standard
conventional unit cell
additional_criteria (dict): Any additional criteria to pass. For instance, if you are only interested in
stable entries, you can pass {"e_above_hull": {"$lte": 0.001}}.
Returns:
List of ComputedEntries.
"""
if isinstance(elements, str):
elements = elements.split("-")
all_chemsyses = []
for i in range(len(elements)):
for els in itertools.combinations(elements, i + 1):
all_chemsyses.append("-".join(sorted(els)))
criteria = {"chemsys": {"$in": all_chemsyses}}
if additional_criteria:
criteria.update(additional_criteria)
return self.get_entries(
criteria,
compatible_only=compatible_only,
inc_structure=inc_structure,
property_data=property_data,
conventional_unit_cell=conventional_unit_cell,
)
def get_exp_thermo_data(self, formula):
"""Get a list of ThermoData objects associated with a formula using the
Materials Project REST interface.
Args:
formula (str): A formula to search for.
Returns:
List of ThermoData objects.
"""
return self.get_data(formula, data_type="exp")
def get_exp_entry(self, formula):
"""Get an ExpEntry object, which is the experimental equivalent of a
ComputedEntry and can be used for analyses using experimental data.
Args:
formula (str): A formula to search for.
Returns:
An ExpEntry object.
"""
return ExpEntry(Composition(formula), self.get_exp_thermo_data(formula))
def query(
self,
criteria,
properties,
chunk_size: int = 500,
max_tries_per_chunk: int = 5,
mp_decode: bool = True,
show_progress_bar: bool = True,
):
r"""Perform an advanced query using MongoDB-like syntax for directly
querying the Materials Project database. This allows one to perform
queries which are otherwise too cumbersome to perform using the standard
convenience methods.
Please consult the Materials API documentation at
https://github.com/materialsproject/mapidoc, which provides a
comprehensive explanation of the document schema used in the Materials
Project (supported criteria and properties) and guidance on how best to
query for the relevant information you need.
For queries that request data on more than CHUNK_SIZE materials at once,
this method will chunk a query by first retrieving a list of material
IDs that satisfy CRITERIA, and then merging the criteria with a
restriction to one chunk of materials at a time of size CHUNK_SIZE. You
can opt out of this behavior by setting CHUNK_SIZE=0. To guard against
intermittent server errors in the case of many chunks per query,
possibly-transient server errors will result in re-trying a give chunk
up to MAX_TRIES_PER_CHUNK times.
Args:
criteria (str/dict): Criteria of the query as a string or
mongo-style dict.
If string, it supports a powerful but simple string criteria.
e.g. "Fe2O3" means search for materials with reduced_formula
Fe2O3. Wild cards are also supported. e.g. "\\*2O" means get
all materials whose formula can be formed as \\*2O, e.g.
Li2O, K2O, etc.
Other syntax examples:
mp-1234: Interpreted as a Materials ID.
Fe2O3 or *2O3: Interpreted as reduced formulas.
Li-Fe-O or *-Fe-O: Interpreted as chemical systems.
You can mix and match with spaces, which are interpreted as
"OR". E.g. "mp-1234 FeO" means query for all compounds with
reduced formula FeO or with materials_id mp-1234.
Using a full dict syntax, even more powerful queries can be
constructed. For example, {"elements":{"$in":["Li",
"Na", "K"], "$all": ["O"]}, "nelements":2} selects all Li, Na
and K oxides. {"band_gap": {"$gt": 1}} selects all materials
with band gaps greater than 1 eV.
properties (list): Properties to request for as a list. For
example, ["formula", "formation_energy_per_atom"] returns
the formula and formation energy per atom.
chunk_size (int): Number of materials for which to fetch data at a
time. More data-intensive properties may require smaller chunk
sizes. Use chunk_size=0 to force no chunking -- this is useful
when fetching only properties such as 'material_id'.
max_tries_per_chunk (int): How many times to re-try fetching a given
chunk when the server gives a 5xx error (e.g. a timeout error).
mp_decode (bool): Whether to do a decoding to a Pymatgen object
where possible. In some cases, it might be useful to just get
the raw python dict, i.e., set to False.
show_progress_bar (bool): Whether to show a progress bar for large queries.
Defaults to True. Set to False to reduce visual noise.
Returns:
List of results. e.g.
[{u'formula': {u'O': 1, u'Li': 2.0}},
{u'formula': {u'Na': 2.0, u'O': 2.0}},
{u'formula': {u'K': 1, u'O': 3.0}},
...]
"""
if not isinstance(criteria, dict):
criteria = self.parse_criteria(criteria)
payload = {
"criteria": json.dumps(criteria),
"properties": json.dumps(properties),
}
if chunk_size == 0:
return self._make_request("/query", payload=payload, method="POST", mp_decode=mp_decode)
count_payload = payload.copy()
count_payload["options"] = json.dumps({"count_only": True})
num_results = self._make_request("/query", payload=count_payload, method="POST")
if num_results <= chunk_size:
return self._make_request("/query", payload=payload, method="POST", mp_decode=mp_decode)
data = []
mids = [dct["material_id"] for dct in self.query(criteria, ["material_id"], chunk_size=0)]
chunks = get_chunks(mids, size=chunk_size)