-
Notifications
You must be signed in to change notification settings - Fork 842
/
phase_diagram.py
3026 lines (2593 loc) · 115 KB
/
phase_diagram.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
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines tools to generate and analyze phase diagrams.
"""
import collections
import itertools
import json
import logging
import math
import os
import re
from functools import lru_cache
import numpy as np
import plotly.graph_objs as go
from monty.json import MontyDecoder, MSONable
from scipy.optimize import minimize
from scipy.spatial import ConvexHull
from pymatgen.analysis.reaction_calculator import Reaction, ReactionError
from pymatgen.core.composition import Composition
from pymatgen.core.periodic_table import DummySpecies, Element, get_el_sp
from pymatgen.entries import Entry
from pymatgen.util.coord import Simplex, in_coord_list
from pymatgen.util.plotting import pretty_plot
from pymatgen.util.string import latexify
logger = logging.getLogger(__name__)
with open(os.path.join(os.path.dirname(__file__), "..", "util", "plotly_pd_layouts.json")) as f:
plotly_layouts = json.load(f)
class PDEntry(Entry):
"""
An object encompassing all relevant data for phase diagrams.
Attributes:
composition (Composition): The composition associated with the PDEntry.
energy (float): The energy associated with the entry.
name (str): A name for the entry. This is the string shown in the phase diagrams.
By default, this is the reduced formula for the composition, but can be
set to some other string for display purposes.
attribute (MSONable): A arbitrary attribute. Can be used to specify that the
entry is a newly found compound, or to specify a particular label for
the entry, etc. An attribute can be anything but must be MSONable.
"""
def __init__(
self,
composition: Composition,
energy: float,
name: str = None,
attribute: object = None,
):
"""
Args:
composition (Composition): Composition
energy (float): Energy for composition.
name (str): Optional parameter to name the entry. Defaults
to the reduced chemical formula.
attribute: Optional attribute of the entry. Must be MSONable.
"""
super().__init__(composition, energy)
self.name = name if name else self.composition.reduced_formula
self.attribute = attribute
@property
def energy(self) -> float:
"""
:return: the energy of the entry.
"""
return self._energy
def as_dict(self):
"""
:return: MSONable dict.
"""
return_dict = super().as_dict()
return_dict.update({"name": self.name, "attribute": self.attribute})
return return_dict
@classmethod
def from_dict(cls, d):
"""
:param d: Dict representation
:return: PDEntry
"""
return cls(
Composition(d["composition"]),
d["energy"],
d["name"] if "name" in d else None,
d["attribute"] if "attribute" in d else None,
)
class GrandPotPDEntry(PDEntry):
"""
A grand potential pd entry object encompassing all relevant data for phase
diagrams. Chemical potentials are given as a element-chemical potential
dict.
"""
def __init__(self, entry, chempots, name=None):
"""
Args:
entry: A PDEntry-like object.
chempots: Chemical potential specification as {Element: float}.
name: Optional parameter to name the entry. Defaults to the reduced
chemical formula of the original entry.
"""
super().__init__(
entry.composition,
entry.energy,
name if name else entry.name,
entry.attribute if hasattr(entry, "attribute") else None,
)
# NOTE if we init GrandPotPDEntry from ComputedEntry _energy is the
# corrected energy of the ComputedEntry hence the need to keep
# the original entry to not lose data.
self.original_entry = entry
self.original_comp = self._composition
self.chempots = chempots
@property
def composition(self) -> Composition:
"""The composition after removing free species
Returns:
Composition
"""
return Composition({el: self._composition[el] for el in self._composition.elements if el not in self.chempots})
@property
def chemical_energy(self):
"""The chemical energy term mu*N in the grand potential
Returns:
The chemical energy term mu*N in the grand potential
"""
return sum([self._composition[el] * pot for el, pot in self.chempots.items()])
@property
def energy(self):
"""
Returns:
The grand potential energy
"""
return self._energy - self.chemical_energy
def __repr__(self):
chempot_str = " ".join(["mu_%s = %.4f" % (el, mu) for el, mu in self.chempots.items()])
return "GrandPotPDEntry with original composition " + "{}, energy = {:.4f}, {}".format(
self.original_entry.composition, self.original_entry.energy, chempot_str
)
def as_dict(self):
"""
:return: MSONAble dict
"""
return {
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"entry": self.original_entry.as_dict(),
"chempots": {el.symbol: u for el, u in self.chempots.items()},
"name": self.name,
}
@classmethod
def from_dict(cls, d):
"""
:param d: Dict representation
:return: PDStructureEntry
"""
chempots = {Element(symbol): u for symbol, u in d["chempots"].items()}
entry = MontyDecoder().process_decoded(d["entry"])
return cls(entry, chempots, d["name"])
class TransformedPDEntry(PDEntry):
"""
This class repesents a TransformedPDEntry, which allows for a PDEntry to be
transformed to a different composition coordinate space. It is used in the
construction of phase diagrams that do not have elements as the terminal
compositions.
"""
# Tolerance for determining if amount of a composition is positive.
amount_tol = 1e-5
def __init__(self, entry, sp_mapping, name=None):
"""
Args:
entry (PDEntry): Original entry to be transformed.
sp_mapping ({Composition: DummySpecies}): dictionary
mapping Terminal Compositions to Dummy Species
"""
super().__init__(
entry.composition,
entry.energy,
name if name else entry.name,
entry.attribute if hasattr(entry, "attribute") else None,
)
self.original_entry = entry
self.sp_mapping = sp_mapping
self.rxn = Reaction(list(self.sp_mapping.keys()), [self._composition])
self.rxn.normalize_to(self.original_entry.composition)
# NOTE We only allow reactions that have positive amounts of reactants.
if not all(self.rxn.get_coeff(comp) <= TransformedPDEntry.amount_tol for comp in self.sp_mapping.keys()):
raise TransformedPDEntryError("Only reactions with positive amounts of reactants allowed")
@property
def composition(self) -> Composition:
"""The composition in the dummy species space
Returns:
Composition
"""
# NOTE this is not infallable as the original entry is mutable and an
# end user could choose to normalize or change the original entry.
# However, the risk of this seems low.
factor = self._composition.num_atoms / self.original_entry.composition.num_atoms
trans_comp = {self.sp_mapping[comp]: -self.rxn.get_coeff(comp) for comp in self.sp_mapping}
trans_comp = {k: v * factor for k, v in trans_comp.items() if v > TransformedPDEntry.amount_tol}
return Composition(trans_comp)
def __repr__(self):
output = [
"TransformedPDEntry {}".format(self.composition),
" with original composition {}".format(self.original_entry.composition),
", E = {:.4f}".format(self.original_entry.energy),
]
return "".join(output)
def as_dict(self):
"""
:return: MSONable dict
"""
d = {
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"sp_mapping": self.sp_mapping,
}
d.update(self.original_entry.as_dict())
return d
@classmethod
def from_dict(cls, d):
"""
:param d: Dict representation
:return: TransformedPDEntry
"""
sp_mapping = d["sp_mapping"]
del d["sp_mapping"]
entry = MontyDecoder().process_decoded(d)
return cls(entry, sp_mapping)
class TransformedPDEntryError(Exception):
"""
An exception class for TransformedPDEntry.
"""
pass
class BasePhaseDiagram(MSONable):
"""
BasePhaseDiagram is not intended to be used directly, and PhaseDiagram should be preferred.
When constructing a PhaseDiagram, a lot of heavy processing is performed to calculate the
phase diagram information such as facets, simplexes, etc. The BasePhaseDiagram offers a way to
store this information so that a phase diagram can be re-constructed without doing this heavy
processing. It is primarily intended for database applications.
"""
# Tolerance for determining if formation energy is positive.
formation_energy_tol = 1e-11
numerical_tol = 1e-8
def __init__(
self,
facets,
simplexes,
all_entries,
qhull_data,
dim,
el_refs,
elements,
qhull_entries,
):
"""
This class uses casting to bypass the init, so this constructor should only be
called by as_dict and from_dict functions. Prefer the PhaseDiagram class for
typical use cases.
"""
self.facets = facets
self.simplexes = simplexes
self.all_entries = all_entries
self.qhull_data = qhull_data
self.dim = dim
self.el_refs = el_refs
self.elements = elements
self.qhull_entries = qhull_entries
self._stable_entries = set(self.qhull_entries[i] for i in set(itertools.chain(*self.facets)))
@classmethod
def from_entries(cls, entries, elements=None):
"""
Construct the PhaseDiagram object and recast it as a BasePhaseDiagram
Args:
entries ([PDEntry]): A list of PDEntry-like objects having an
energy, energy_per_atom and composition.
elements ([Element]): Optional list of elements in the phase
diagram. If set to None, the elements are determined from
the the entries themselves and are sorted alphabetically.
If specified, element ordering (e.g. for pd coordinates)
is preserved.
"""
return cls(**cls._kwargs_from_entries(entries, elements))
@classmethod
def _kwargs_from_entries(cls, entries, elements):
if elements is None:
elements = sorted({els for e in entries for els in e.composition.elements})
elements = list(elements)
dim = len(elements)
entries = sorted(entries, key=lambda e: e.composition.reduced_composition)
el_refs = {}
min_entries = []
all_entries = []
for c, g in itertools.groupby(entries, key=lambda e: e.composition.reduced_composition):
g = list(g)
min_entry = min(g, key=lambda e: e.energy_per_atom)
if c.is_element:
el_refs[c.elements[0]] = min_entry
min_entries.append(min_entry)
all_entries.extend(g)
if len(el_refs) != dim:
missing = set(elements).difference(el_refs.keys())
raise ValueError(f"There are no entries for the terminal elements: {missing}")
data = np.array(
[[e.composition.get_atomic_fraction(el) for el in elements] + [e.energy_per_atom] for e in min_entries]
)
# Use only entries with negative formation energy
vec = [el_refs[el].energy_per_atom for el in elements] + [-1]
form_e = -np.dot(data, vec)
inds = np.where(form_e < -cls.formation_energy_tol)[0].tolist()
# Add the elemental references
inds.extend([min_entries.index(el) for el in el_refs.values()])
qhull_entries = [min_entries[i] for i in inds]
qhull_data = data[inds][:, 1:]
# Add an extra point to enforce full dimensionality.
# This point will be present in all upper hull facets.
extra_point = np.zeros(dim) + 1 / dim
extra_point[-1] = np.max(qhull_data) + 1
qhull_data = np.concatenate([qhull_data, [extra_point]], axis=0)
if dim == 1:
facets = [qhull_data.argmin(axis=0)]
else:
facets = get_facets(qhull_data)
final_facets = []
for facet in facets:
# Skip facets that include the extra point
if max(facet) == len(qhull_data) - 1:
continue
m = qhull_data[facet]
m[:, -1] = 1
if abs(np.linalg.det(m)) > 1e-14:
final_facets.append(facet)
facets = final_facets
simplexes = [Simplex(qhull_data[f, :-1]) for f in facets]
return dict(
facets=facets,
simplexes=simplexes,
all_entries=all_entries,
qhull_data=qhull_data,
dim=dim,
el_refs=el_refs,
elements=elements,
qhull_entries=qhull_entries,
)
def pd_coords(self, comp):
"""
The phase diagram is generated in a reduced dimensional space
(n_elements - 1). This function returns the coordinates in that space.
These coordinates are compatible with the stored simplex objects.
Args:
comp (Composition): A composition
Returns:
The coordinates for a given composition in the PhaseDiagram's basis
"""
if set(comp.elements).difference(self.elements):
raise ValueError("{} has elements not in the phase diagram {}" "".format(comp, self.elements))
return np.array([comp.get_atomic_fraction(el) for el in self.elements[1:]])
@property
def all_entries_hulldata(self):
"""
:return: The actual ndarray used to construct the convex hull.
"""
data = []
for entry in self.all_entries:
comp = entry.composition
row = [comp.get_atomic_fraction(el) for el in self.elements]
row.append(entry.energy_per_atom)
data.append(row)
return np.array(data)[:, 1:]
@property
def unstable_entries(self):
"""
Returns a list of Entries that are unstable in the phase diagram.
Includes positive formation energy entries.
"""
return [e for e in self.all_entries if e not in self.stable_entries]
@property
def stable_entries(self):
"""
Returns the set of stable entries in the phase diagram.
"""
return self._stable_entries
def get_form_energy(self, entry):
"""
Returns the formation energy for an entry (NOT normalized) from the
elemental references.
Args:
entry (PDEntry): A PDEntry-like object.
Returns:
Formation energy from the elemental references.
"""
c = entry.composition
return entry.energy - sum([c[el] * self.el_refs[el].energy_per_atom for el in c.elements])
def get_form_energy_per_atom(self, entry):
"""
Returns the formation energy per atom for an entry from the
elemental references.
Args:
entry (PDEntry): An PDEntry-like object
Returns:
Formation energy **per atom** from the elemental references.
"""
return self.get_form_energy(entry) / entry.composition.num_atoms
def __repr__(self):
symbols = [el.symbol for el in self.elements]
output = [
"{} phase diagram".format("-".join(symbols)),
"{} stable phases: ".format(len(self.stable_entries)),
", ".join([entry.name for entry in self.stable_entries]),
]
return "\n".join(output)
@lru_cache(1)
def _get_facet_and_simplex(self, comp):
"""
Get any facet that a composition falls into. Cached so successive
calls at same composition are fast.
Args:
comp (Composition): A composition
"""
c = self.pd_coords(comp)
for f, s in zip(self.facets, self.simplexes):
if s.in_simplex(c, PhaseDiagram.numerical_tol / 10):
return f, s
raise RuntimeError("No facet found for comp = {}".format(comp))
def _get_facet_chempots(self, facet):
"""
Calculates the chemical potentials for each element within a facet.
Args:
facet: Facet of the phase diagram.
Returns:
{element: chempot} for all elements in the phase diagram.
"""
complist = [self.qhull_entries[i].composition for i in facet]
energylist = [self.qhull_entries[i].energy_per_atom for i in facet]
m = [[c.get_atomic_fraction(e) for e in self.elements] for c in complist]
chempots = np.linalg.solve(m, energylist)
return dict(zip(self.elements, chempots))
def get_decomposition(self, comp):
"""
Provides the decomposition at a particular composition.
Args:
comp (Composition): A composition
Returns:
Decomposition as a dict of {PDEntry: amount} where amount
is the amount of the fractional composition.
"""
facet, simplex = self._get_facet_and_simplex(comp)
decomp_amts = simplex.bary_coords(self.pd_coords(comp))
return {
self.qhull_entries[f]: amt for f, amt in zip(facet, decomp_amts) if abs(amt) > PhaseDiagram.numerical_tol
}
def get_hull_energy(self, comp):
"""
Args:
comp (Composition): Input composition
Returns:
Energy of lowest energy equilibrium at desired composition. Not
normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O)
"""
decomp = self.get_decomposition(comp)
return comp.num_atoms * sum([e.energy_per_atom * n for e, n in decomp.items()])
def get_decomp_and_e_above_hull(self, entry, allow_negative=False):
"""
Provides the decomposition and energy above convex hull for an entry.
Due to caching, can be much faster if entries with the same composition
are processed together.
Args:
entry (PDEntry): A PDEntry like object
allow_negative (bool): Whether to allow negative e_above_hulls. Used to
calculate equilibrium reaction energies. Defaults to False.
Returns:
(decomp, energy_above_hull). The decomposition is provided
as a dict of {PDEntry: amount} where amount is the amount of the
fractional composition. Stable entries should have energy above
convex hull of 0. The energy is given per atom.
"""
# Avoid computation for stable_entries.
# NOTE scaled duplicates of stable_entries will not be caught.
if entry in list(self.stable_entries):
return {entry: 1}, 0
decomp = self.get_decomposition(entry.composition)
e_above_hull = entry.energy_per_atom - sum([e.energy_per_atom * n for e, n in decomp.items()])
if allow_negative or e_above_hull >= -PhaseDiagram.numerical_tol:
return decomp, e_above_hull
raise ValueError("No valid decomp found for {}! (e {})".format(entry, e_above_hull))
def get_e_above_hull(self, entry, **kwargs):
"""
Provides the energy above convex hull for an entry
Args:
entry (PDEntry): A PDEntry like object
Returns:
Energy above convex hull of entry. Stable entries should have
energy above hull of 0. The energy is given per atom.
"""
return self.get_decomp_and_e_above_hull(entry, **kwargs)[1]
def get_equilibrium_reaction_energy(self, entry):
"""
Provides the reaction energy of a stable entry from the neighboring
equilibrium stable entries (also known as the inverse distance to
hull).
Args:
entry (PDEntry): A PDEntry like object
Returns:
Equilibrium reaction energy of entry. Stable entries should have
equilibrium reaction energy <= 0. The energy is given per atom.
"""
# NOTE scaled duplicates of stable_entries will not be caught.
if entry not in self.stable_entries:
raise ValueError(
"{} is unstable, the equilibrium reaction energy is" "available only for stable entries.".format(entry)
)
if entry.is_element:
return 0
entries = [e for e in self.stable_entries if e != entry]
modpd = PhaseDiagram(entries, self.elements)
return modpd.get_decomp_and_e_above_hull(entry, allow_negative=True)[1]
def get_decomp_and_phase_separation_energy(
self, entry, space_limit=200, stable_only=False, tol=1e-10, maxiter=1000
):
"""
Provides the combination of entries in the PhaseDiagram that gives the
lowest formation enthalpy with the same composition as the given entry
excluding entries with the same composition and the energy difference
per atom between the given entry and the energy of the combination found.
For unstable entries that are not polymorphs of stable entries (or completely
novel entries) this is simply the energy above (or below) the convex hull.
For entries with the same composition as one of the stable entries in the
phase diagram setting `stable_only` to `False` (Default) allows for entries
not previously on the convex hull to be considered in the combination.
In this case the energy returned is what is referred to as the decomposition
enthalpy in:
1. Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from
machine-learned formation energies, npj Computational Materials 6, 97 (2020)
For stable entries setting `stable_only` to `True` returns the same energy
as `get_equilibrium_reaction_energy`. This function is based on a constrained
optimisation rather than recalculation of the convex hull making it
algorithmically cheaper. However, if `tol` is too loose there is potential
for this algorithm to converge to a different solution.
Args:
entry (PDEntry): A PDEntry like object.
space_limit (int): The maximum number of competing entries to consider
before calculating a second convex hull to reducing the complexity
of the optimization.
stable_only (bool): Only use stable materials as competing entries.
tol (float): The tolerence for convergence of the SLSQP optimization
when finding the equilibrium reaction.
maxiter (int): The maximum number of iterations of the SLSQP optimizer
when finding the equilibrium reaction.
Returns:
(decomp, energy). The decompostion is given as a dict of {PDEntry, amount}
for all entries in the decomp reaction where amount is the amount of the
fractional composition. The phase separation energy is given per atom.
"""
# For unstable or novel materials use simplex approach
if entry.composition.fractional_composition not in [
e.composition.fractional_composition for e in self.stable_entries
]:
return self.get_decomp_and_e_above_hull(entry, allow_negative=True)
# Handle elemental materials
if entry.is_element:
return self.get_decomp_and_e_above_hull(entry, allow_negative=True)
# Select space to compare against
if stable_only:
compare_entries = self.stable_entries
else:
compare_entries = self.qhull_entries
# take entries with negative formation enthalpies as competing entries
competing_entries = [
c
for c in compare_entries
if (c.composition.fractional_composition != entry.composition.fractional_composition)
if set(c.composition.elements).issubset(entry.composition.elements)
]
# NOTE SLSQP optimizer doesn't scale well for > 300 competing entries. As a
# result in phase diagrams where we have too many competing entries we can
# reduce the number by looking at the first and second convex hulls. This
# requires computing the convex hull of a second (hopefully smallish) space
# and so is not done by default
if len(competing_entries) > space_limit and not stable_only:
inner_hull = PhaseDiagram(
list(
set.intersection(
set(competing_entries), # same chemical space
set(self.qhull_entries), # negative E_f
set(self.unstable_entries), # not already on hull
)
)
+ list(self.el_refs.values())
) # terminal points
competing_entries = list(self.stable_entries.union(inner_hull.stable_entries))
competing_entries = [c for c in competing_entries if c != entry]
solution = _get_slsqp_decomp(entry, competing_entries, tol, maxiter)
if solution.success:
decomp_amts = solution.x
decomp = {c: amt for c, amt in zip(competing_entries, decomp_amts) if amt > PhaseDiagram.numerical_tol}
# find the minimum alternative formation energy for the decomposition
decomp_enthalpy = np.sum([c.energy_per_atom * amt for c, amt in decomp.items()])
decomp_enthalpy = entry.energy_per_atom - decomp_enthalpy
return decomp, decomp_enthalpy
raise ValueError("No valid decomp found for {}!".format(entry))
def get_phase_separation_energy(self, entry, **kwargs):
"""
Provides the energy to the convex hull for the given entry. For stable entries
already in the phase diagram the algorithm provides the phase separation energy
which is refered to as the decomposition enthalpy in:
1. Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from
machine-learned formation energies, npj Computational Materials 6, 97 (2020)
Args:
entry (PDEntry): A PDEntry like object
**kwargs: Keyword args passed to `get_decomp_and_decomp_energy`
space_limit (int): The maximum number of competing entries to consider.
stable_only (bool): Only use stable materials as competing entries
tol (float): The tolerence for convergence of the SLSQP optimization
when finding the equilibrium reaction.
maxiter (int): The maximum number of iterations of the SLSQP optimizer
when finding the equilibrium reaction.
Returns:
phase separation energy per atom of entry. Stable entries should have
energies <= 0, Stable elemental entries should have energies = 0 and
unstable entries should have energies > 0. Entries that have the same
composition as a stable energy may have postive or negative phase
separation energies depending on their own energy.
"""
return self.get_decomp_and_phase_separation_energy(entry, **kwargs)[1]
def get_composition_chempots(self, comp):
"""
Get the chemical potentials for all elements at a given composition.
:param comp: Composition
:return: Dict of chemical potentials.
"""
facet = self._get_facet_and_simplex(comp)[0]
return self._get_facet_chempots(facet)
def get_all_chempots(self, comp):
"""
Get chemical potentials at a given compositon.
:param comp: Composition
:return: Chemical potentials.
"""
# NOTE the top part takes from format of _get_facet_and_simplex,
# but wants to return all facets rather than the first one that
# meets this criteria
c = self.pd_coords(comp)
all_facets = []
for f, s in zip(self.facets, self.simplexes):
if s.in_simplex(c, PhaseDiagram.numerical_tol / 10):
all_facets.append(f)
if not len(all_facets):
raise RuntimeError("No facets found for comp = {}".format(comp))
chempots = {}
for facet in all_facets:
facet_name = "-".join([self.qhull_entries[j].name for j in facet])
chempots[facet_name] = self._get_facet_chempots(facet)
return chempots
def get_transition_chempots(self, element):
"""
Get the critical chemical potentials for an element in the Phase
Diagram.
Args:
element: An element. Has to be in the PD in the first place.
Returns:
A sorted sequence of critical chemical potentials, from less
negative to more negative.
"""
if element not in self.elements:
raise ValueError("get_transition_chempots can only be called with elements in the phase diagram.")
critical_chempots = []
for facet in self.facets:
chempots = self._get_facet_chempots(facet)
critical_chempots.append(chempots[element])
clean_pots = []
for c in sorted(critical_chempots):
if len(clean_pots) == 0:
clean_pots.append(c)
else:
if abs(c - clean_pots[-1]) > PhaseDiagram.numerical_tol:
clean_pots.append(c)
clean_pots.reverse()
return tuple(clean_pots)
def get_critical_compositions(self, comp1, comp2):
"""
Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition): compositions that define the tieline
Returns:
[(Composition)]: list of critical compositions. All are of
the form x * comp1 + (1-x) * comp2
"""
n1 = comp1.num_atoms
n2 = comp2.num_atoms
pd_els = self.elements
# the reduced dimensionality Simplexes don't use the
# first element in the PD
c1 = self.pd_coords(comp1)
c2 = self.pd_coords(comp2)
# none of the projections work if c1 == c2, so just return *copies*
# of the inputs
if np.all(c1 == c2):
return [comp1.copy(), comp2.copy()]
intersections = [c1, c2]
for sc in self.simplexes:
intersections.extend(sc.line_intersection(c1, c2))
intersections = np.array(intersections)
# find position along line
l = c2 - c1
l /= np.sum(l ** 2) ** 0.5
proj = np.dot(intersections - c1, l)
# only take compositions between endpoints
proj = proj[
np.logical_and(proj > -self.numerical_tol, proj < proj[1] + self.numerical_tol) # proj[1] is |c2-c1|
]
proj.sort()
# only unique compositions
valid = np.ones(len(proj), dtype=np.bool)
valid[1:] = proj[1:] > proj[:-1] + self.numerical_tol
proj = proj[valid]
ints = c1 + l * proj[:, None]
# reconstruct full-dimensional composition array
cs = np.concatenate([np.array([1 - np.sum(ints, axis=-1)]).T, ints], axis=-1)
# mixing fraction when compositions are normalized
x = proj / np.dot(c2 - c1, l)
# mixing fraction when compositions are not normalized
x_unnormalized = x * n1 / (n2 + x * (n1 - n2))
num_atoms = n1 + (n2 - n1) * x_unnormalized
cs *= num_atoms[:, None]
return [Composition((c, v) for c, v in zip(pd_els, m)) for m in cs]
def get_element_profile(self, element, comp, comp_tol=1e-5):
"""
Provides the element evolution data for a composition.
For example, can be used to analyze Li conversion voltages by varying
uLi and looking at the phases formed. Also can be used to analyze O2
evolution by varying uO2.
Args:
element: An element. Must be in the phase diagram.
comp: A Composition
comp_tol: The tolerance to use when calculating decompositions.
Phases with amounts less than this tolerance are excluded.
Defaults to 1e-5.
Returns:
Evolution data as a list of dictionaries of the following format:
[ {'chempot': -10.487582010000001, 'evolution': -2.0,
'reaction': Reaction Object], ...]
"""
element = get_el_sp(element)
if element not in self.elements:
raise ValueError("get_transition_chempots can only be called with" " elements in the phase diagram.")
gccomp = Composition({el: amt for el, amt in comp.items() if el != element})
elref = self.el_refs[element]
elcomp = Composition(element.symbol)
evolution = []
for cc in self.get_critical_compositions(elcomp, gccomp)[1:]:
decomp_entries = self.get_decomposition(cc).keys()
decomp = [k.composition for k in decomp_entries]
rxn = Reaction([comp], decomp + [elcomp])
rxn.normalize_to(comp)
c = self.get_composition_chempots(cc + elcomp * 1e-5)[element]
amt = -rxn.coeffs[rxn.all_comp.index(elcomp)]
evolution.append(
{
"chempot": c,
"evolution": amt,
"element_reference": elref,
"reaction": rxn,
"entries": decomp_entries,
}
)
return evolution
def get_chempot_range_map(self, elements, referenced=True, joggle=True):
"""
Returns a chemical potential range map for each stable entry.
Args:
elements: Sequence of elements to be considered as independent
variables. E.g., if you want to show the stability ranges
of all Li-Co-O phases wrt to uLi and uO, you will supply
[Element("Li"), Element("O")]
referenced: If True, gives the results with a reference being the
energy of the elemental phase. If False, gives absolute values.
joggle (boolean): Whether to joggle the input to avoid precision
errors.
Returns:
Returns a dict of the form {entry: [simplices]}. The list of
simplices are the sides of the N-1 dim polytope bounding the
allowable chemical potential range of each entry.
"""
all_chempots = []
for facet in self.facets:
chempots = self._get_facet_chempots(facet)
all_chempots.append([chempots[el] for el in self.elements])
inds = [self.elements.index(el) for el in elements]
if referenced:
el_energies = {el: self.el_refs[el].energy_per_atom for el in elements}
else:
el_energies = {el: 0.0 for el in elements}
chempot_ranges = collections.defaultdict(list)
vertices = [list(range(len(self.elements)))]
if len(all_chempots) > len(self.elements):
vertices = get_facets(all_chempots, joggle=joggle)
for ufacet in vertices:
for combi in itertools.combinations(ufacet, 2):
data1 = self.facets[combi[0]]
data2 = self.facets[combi[1]]
common_ent_ind = set(data1).intersection(set(data2))
if len(common_ent_ind) == len(elements):
common_entries = [self.qhull_entries[i] for i in common_ent_ind]
data = np.array([[all_chempots[i][j] - el_energies[self.elements[j]] for j in inds] for i in combi])
sim = Simplex(data)
for entry in common_entries:
chempot_ranges[entry].append(sim)
return chempot_ranges
def getmu_vertices_stability_phase(self, target_comp, dep_elt, tol_en=1e-2):
"""
returns a set of chemical potentials corresponding to the vertices of
the simplex in the chemical potential phase diagram.
The simplex is built using all elements in the target_composition
except dep_elt.
The chemical potential of dep_elt is computed from the target
composition energy.
This method is useful to get the limiting conditions for
defects computations for instance.
Args:
target_comp: A Composition object
dep_elt: the element for which the chemical potential is computed
from the energy of the stable phase at the target composition
tol_en: a tolerance on the energy to set
Returns:
[{Element:mu}]: An array of conditions on simplex vertices for
which each element has a chemical potential set to a given
value. "absolute" values (i.e., not referenced to element energies)
"""
muref = np.array([self.el_refs[e].energy_per_atom for e in self.elements if e != dep_elt])
chempot_ranges = self.get_chempot_range_map([e for e in self.elements if e != dep_elt])
for e in self.elements:
if e not in target_comp.elements:
target_comp = target_comp + Composition({e: 0.0})
coeff = [-target_comp[e] for e in self.elements if e != dep_elt]
for e in chempot_ranges.keys():
if e.composition.reduced_composition == target_comp.reduced_composition:
multiplicator = e.composition[dep_elt] / target_comp[dep_elt]
ef = e.energy / multiplicator
all_coords = []
for s in chempot_ranges[e]: