-
Notifications
You must be signed in to change notification settings - Fork 874
/
surface_analysis.py
1904 lines (1677 loc) · 79.3 KB
/
surface_analysis.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 defines tools to analyze surface and adsorption related
quantities as well as related plots. If you use this module, please
consider citing the following works:
R. Tran, Z. Xu, B. Radhakrishnan, D. Winston, W. Sun, K. A. Persson,
S. P. Ong, "Surface Energies of Elemental Crystals", Scientific
Data, 2016, 3:160080, doi: 10.1038/sdata.2016.80.
and
Kang, S., Mo, Y., Ong, S. P., & Ceder, G. (2014). Nanoscale
stabilization of sodium oxides: Implications for Na-O2 batteries.
Nano Letters, 14(2), 1016-1020. https://doi.org/10.1021/nl404557w
and
Montoya, J. H., & Persson, K. A. (2017). A high-throughput framework
for determining adsorption energies on solid surfaces. Npj
Computational Materials, 3(1), 14.
https://doi.org/10.1038/s41524-017-0017-z
Todo:
- Still assumes individual elements have their own chempots
in a molecular adsorbate instead of considering a single
chempot for a single molecular adsorbate. E.g. for an OH
adsorbate, the surface energy is a function of delu_O and
delu_H instead of delu_OH
- Need a method to automatically get chempot range when
dealing with non-stoichiometric slabs
- Simplify the input for SurfaceEnergyPlotter such that the
user does not need to generate a dict
"""
from __future__ import annotations
import copy
import itertools
import warnings
from typing import TYPE_CHECKING
import matplotlib.pyplot as plt
import numpy as np
from sympy import Symbol
from sympy.solvers import linsolve, solve
from pymatgen.analysis.wulff import WulffShape
from pymatgen.core import Structure
from pymatgen.core.composition import Composition
from pymatgen.core.surface import get_slab_regions
from pymatgen.entries.computed_entries import ComputedStructureEntry
from pymatgen.io.vasp.outputs import Locpot, Outcar
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.util.due import Doi, due
from pymatgen.util.plotting import pretty_plot
if TYPE_CHECKING:
from typing_extensions import Self
from pymatgen.util.typing import Tuple3Ints
EV_PER_ANG2_TO_JOULES_PER_M2 = 16.0217656
__author__ = "Richard Tran"
__credits__ = "Joseph Montoya, Xianguo Li"
class SlabEntry(ComputedStructureEntry):
"""
A ComputedStructureEntry object encompassing all data relevant to a
slab for analyzing surface thermodynamics.
Attributes:
miller_index (tuple): Miller index of plane parallel to surface.
label (str): Brief description for this slab.
adsorbates (list): List of ComputedStructureEntry for the types of adsorbates.
clean_entry (SlabEntry): SlabEntry for the corresponding clean slab for an adsorbed slab.
ads_entries_dict (dict): Dictionary where the key is the reduced composition of the
adsorbate entry and value is the entry itself.
"""
def __init__(
self,
structure,
energy,
miller_index,
correction=0.0,
parameters=None,
data=None,
entry_id=None,
label=None,
adsorbates=None,
clean_entry=None,
marker=None,
color=None,
):
"""
Make a SlabEntry containing all relevant surface thermodynamics data.
Args:
structure (Slab): The primary slab associated with this entry.
energy (float): Energy from total energy calculation
miller_index (tuple(h, k, l)): Miller index of plane parallel
to surface
correction (float): See ComputedSlabEntry
parameters (dict): See ComputedSlabEntry
data (dict): See ComputedSlabEntry
entry_id (obj): See ComputedSlabEntry
data (dict): See ComputedSlabEntry
entry_id (str): See ComputedSlabEntry
label (str): Any particular label for this slab, e.g. "Tasker 2",
"non-stoichiometric", "reconstructed"
adsorbates ([ComputedStructureEntry]): List of reference entries
for the adsorbates on the slab, can be an isolated molecule
(e.g. O2 for O or O2 adsorption), a bulk structure (eg. fcc
Cu for Cu adsorption) or anything.
clean_entry (ComputedStructureEntry): If the SlabEntry is for an
adsorbed slab, this is the corresponding SlabEntry for the
clean slab
marker (str): Custom marker for gamma plots ("--" and "-" are typical)
color (str or rgba): Custom color for gamma plots
"""
self.miller_index = miller_index
self.label = label
self.adsorbates = adsorbates or []
self.clean_entry = clean_entry
self.ads_entries_dict = {str(next(iter(ads.composition.as_dict()))): ads for ads in self.adsorbates}
self.mark = marker
self.color = color
super().__init__(
structure,
energy,
correction=correction,
parameters=parameters,
data=data,
entry_id=entry_id,
)
def as_dict(self):
"""Get dict which contains Slab Entry data."""
dct = {"@module": type(self).__module__, "@class": type(self).__name__}
dct["structure"] = self.structure
dct["energy"] = self.energy
dct["miller_index"] = self.miller_index
dct["label"] = self.label
dct["adsorbates"] = self.adsorbates
dct["clean_entry"] = self.clean_entry
return dct
def gibbs_binding_energy(self, eads=False):
"""Get the adsorption energy or Gibbs binding energy of an adsorbate on a surface.
Args:
eads (bool): Whether to calculate the adsorption energy
(True) or the binding energy (False) which is just
adsorption energy normalized by number of adsorbates.
"""
surface_area = self.get_unit_primitive_area
n_ads = self.Nads_in_slab
BE = (self.energy - surface_area * self.clean_entry.energy) / n_ads - sum(
ads.energy_per_atom for ads in self.adsorbates
)
return BE * n_ads if eads else BE
def surface_energy(self, ucell_entry, ref_entries=None):
"""
Calculates the surface energy of this SlabEntry.
Args:
ucell_entry (entry): An entry object for the bulk
ref_entries (list: [entry]): A list of entries for each type
of element to be used as a reservoir for non-stoichiometric
systems. The length of this list MUST be n-1 where n is the
number of different elements in the bulk entry. The chempot
of the element ref_entry that is not in the list will be
treated as a variable.
Returns:
float: The surface energy of the slab.
"""
# Set up
ref_entries = ref_entries or []
# Check if appropriate ref_entries are present if the slab is non-stoichiometric
# TODO: There should be a way to identify which specific species are
# non-stoichiometric relative to the others in systems with more than 2 species
slab_comp = self.composition.as_dict()
ucell_entry_comp = ucell_entry.composition.reduced_composition.as_dict()
slab_clean_comp = Composition({el: slab_comp[el] for el in ucell_entry_comp})
if slab_clean_comp.reduced_composition != ucell_entry.composition.reduced_composition:
list_els = [next(iter(entry.composition.as_dict())) for entry in ref_entries]
if not any(el in list_els for el in ucell_entry.composition.as_dict()):
warnings.warn("Elemental references missing for the non-dopant species.")
gamma = (Symbol("E_surf") - Symbol("Ebulk")) / (2 * Symbol("A"))
ucell_comp = ucell_entry.composition
ucell_reduced_comp = ucell_comp.reduced_composition
ref_entries_dict = {str(next(iter(ref.composition.as_dict()))): ref for ref in ref_entries}
ref_entries_dict.update(self.ads_entries_dict)
# Calculate Gibbs free energy of the bulk per unit formula
gibbs_bulk = ucell_entry.energy / ucell_comp.get_integer_formula_and_factor()[1]
# First we get the contribution to the bulk energy
# from each element with an existing ref_entry.
bulk_energy, gbulk_eqn = 0, 0
for el, ref in ref_entries_dict.items():
N, delu = self.composition.as_dict()[el], Symbol(f"delu_{el}")
if el in ucell_comp.as_dict():
gbulk_eqn += ucell_reduced_comp[el] * (delu + ref.energy_per_atom)
bulk_energy += N * (Symbol("delu_" + el) + ref.energy_per_atom)
# Next, we add the contribution to the bulk energy from
# the variable element (the element without a ref_entry),
# as a function of the other elements
ref_el = None
for ref_el in ucell_comp.as_dict():
if str(ref_el) not in ref_entries_dict:
break
ref_e_per_a = (gibbs_bulk - gbulk_eqn) / ucell_reduced_comp.as_dict()[ref_el]
bulk_energy += self.composition.as_dict()[ref_el] * ref_e_per_a
se = gamma.subs(
{
Symbol("E_surf"): self.energy,
Symbol("Ebulk"): bulk_energy,
Symbol("A"): self.surface_area,
}
)
return float(se) if type(se).__name__ == "Float" else se
@property
def get_unit_primitive_area(self):
"""The surface area of the adsorbed system per unit area of the primitive slab system."""
A_ads = self.surface_area
A_clean = self.clean_entry.surface_area
return A_ads / A_clean
@property
def get_monolayer(self):
"""The primitive unit surface area density of the adsorbate."""
unit_a = self.get_unit_primitive_area
n_surfs = self.Nsurfs_ads_in_slab
n_ads = self.Nads_in_slab
return n_ads / (unit_a * n_surfs)
@property
def Nads_in_slab(self):
"""The TOTAL number of adsorbates in the slab on BOTH sides."""
return sum(self.composition.as_dict()[a] for a in self.ads_entries_dict)
@property
def Nsurfs_ads_in_slab(self):
"""The TOTAL number of adsorbed surfaces in the slab."""
struct = self.structure
weights = [s.species.weight for s in struct]
center_of_mass = np.average(struct.frac_coords, weights=weights, axis=0)
n_surfs = 0
# Are there adsorbates on top surface?
if any(
site.species_string in self.ads_entries_dict for site in struct if site.frac_coords[2] > center_of_mass[2]
):
n_surfs += 1
# Are there adsorbates on bottom surface?
if any(
site.species_string in self.ads_entries_dict for site in struct if site.frac_coords[2] < center_of_mass[2]
):
n_surfs += 1
return n_surfs
@classmethod
def from_dict(cls, dct: dict) -> Self:
"""Get a SlabEntry by reading in an dictionary."""
structure = SlabEntry.from_dict(dct["structure"])
energy = SlabEntry.from_dict(dct["energy"])
miller_index = dct["miller_index"]
label = dct["label"]
adsorbates = dct["adsorbates"]
clean_entry = dct["clean_entry"]
return cls(
structure,
energy,
miller_index,
label=label,
adsorbates=adsorbates,
clean_entry=clean_entry,
)
@property
def surface_area(self):
"""Calculate the surface area of the slab."""
matrix = self.structure.lattice.matrix
return np.linalg.norm(np.cross(matrix[0], matrix[1]))
@property
def cleaned_up_slab(self):
"""A slab with the adsorbates removed."""
ads_strs = list(self.ads_entries_dict)
cleaned = self.structure.copy()
cleaned.remove_species(ads_strs)
return cleaned
@property
def create_slab_label(self):
"""A label (str) for this particular slab based on composition, coverage and Miller index."""
if "label" in self.data:
return self.data["label"]
label = str(self.miller_index)
ads_strs = list(self.ads_entries_dict)
cleaned = self.cleaned_up_slab
label += f" {cleaned.composition.reduced_composition}"
if self.adsorbates:
for ads in ads_strs:
label += f"+{ads}"
label += f", {self.get_monolayer:.3f} ML"
return label
@classmethod
def from_computed_structure_entry(
cls, entry, miller_index, label=None, adsorbates=None, clean_entry=None, **kwargs
) -> Self:
"""Get SlabEntry from a ComputedStructureEntry."""
return cls(
entry.structure,
entry.energy,
miller_index,
label=label,
adsorbates=adsorbates,
clean_entry=clean_entry,
**kwargs,
)
class SurfaceEnergyPlotter:
"""
A class used for generating plots to analyze the thermodynamics of surfaces
of a material. Produces stability maps of different slab configurations,
phases diagrams of two parameters to determine stability of configurations
(future release), and Wulff shapes.
Attributes:
all_slab_entries (dict | list): Either a list of SlabEntry objects (note for a list, the
SlabEntry must have the adsorbates and clean_entry parameter plugged in) or a Nested
dictionary containing a list of entries for slab calculations as
items and the corresponding Miller index of the slab as the key.
To account for adsorption, each value is a sub-dictionary with the
entry of a clean slab calculation as the sub-key and a list of
entries for adsorption calculations as the sub-value. The sub-value
can contain different adsorption configurations such as a different
site or a different coverage, however, ordinarily only the most stable
configuration for a particular coverage will be considered as the
function of the adsorbed surface energy has an intercept dependent on
the adsorption energy (ie an adsorption site with a higher adsorption
energy will always provide a higher surface energy than a site with a
lower adsorption energy). An example parameter is provided:
{(h1,k1,l1): {clean_entry1: [ads_entry1, ads_entry2, ...], clean_entry2: [...], ...}, (h2,k2,l2): {...}}
where clean_entry1 can be a pristine surface and clean_entry2 can be a
reconstructed surface while ads_entry1 can be adsorption at site 1 with
a 2x2 coverage while ads_entry2 can have a 3x3 coverage. If adsorption
entries are present (i.e. if all_slab_entries[(h,k,l)][clean_entry1]), we
consider adsorption in all plots and analysis for this particular facet.
color_dict (dict): Dictionary of colors (r,g,b,a) when plotting surface energy stability.
The keys are individual surface entries where clean surfaces have a solid color while
the corresponding adsorbed surface will be transparent.
ucell_entry (ComputedStructureEntry): ComputedStructureEntry of the bulk reference for
this particular material.
ref_entries (list): List of ComputedStructureEntries to be used for calculating chemical potential.
facet_color_dict (dict): Randomly generated dictionary of colors associated with each facet.
"""
def __init__(self, all_slab_entries, ucell_entry, ref_entries=None):
"""
Object for plotting surface energy in different ways for clean and
adsorbed surfaces.
Args:
all_slab_entries (dict or list): Dictionary or list containing
all entries for slab calculations. See attributes.
ucell_entry (ComputedStructureEntry): ComputedStructureEntry
of the bulk reference for this particular material.
ref_entries ([ComputedStructureEntries]): A list of entries for
each type of element to be used as a reservoir for
non-stoichiometric systems. The length of this list MUST be
n-1 where n is the number of different elements in the bulk
entry. The bulk energy term in the grand surface potential can
be defined by a summation of the chemical potentials for each
element in the system. As the bulk energy is already provided,
one can solve for one of the chemical potentials as a function
of the other chemical potentials and bulk energy. i.e. there
are n-1 variables (chempots). e.g. if your ucell_entry is for
LiFePO4 than your ref_entries should have an entry for Li, Fe,
and P if you want to use the chempot of O as the variable.
"""
self.ucell_entry = ucell_entry
self.ref_entries = ref_entries
self.all_slab_entries = (
all_slab_entries if type(all_slab_entries).__name__ == "dict" else entry_dict_from_list(all_slab_entries)
)
self.color_dict = self.color_palette_dict()
se_dict, as_coeffs_dict = {}, {}
for hkl in self.all_slab_entries:
for clean in self.all_slab_entries[hkl]:
se = clean.surface_energy(self.ucell_entry, ref_entries=self.ref_entries)
if type(se).__name__ == "float":
se_dict[clean] = se
as_coeffs_dict[clean] = {1: se}
else:
se_dict[clean] = se
as_coeffs_dict[clean] = se.as_coefficients_dict()
for dope in self.all_slab_entries[hkl][clean]:
se = dope.surface_energy(self.ucell_entry, ref_entries=self.ref_entries)
if type(se).__name__ == "float":
se_dict[dope] = se
as_coeffs_dict[dope] = {1: se}
else:
se_dict[dope] = se
as_coeffs_dict[dope] = se.as_coefficients_dict()
self.surfe_dict = se_dict
self.as_coeffs_dict = as_coeffs_dict
list_of_chempots = []
for v in self.as_coeffs_dict.values():
if type(v).__name__ == "float":
continue
for du in v:
if du not in list_of_chempots:
list_of_chempots.append(du)
self.list_of_chempots = list_of_chempots
def get_stable_entry_at_u(
self,
miller_index,
delu_dict=None,
delu_default=0,
no_doped=False,
no_clean=False,
) -> tuple[SlabEntry, float]:
"""Get the entry corresponding to the most stable slab for a particular
facet at a specific chempot. We assume that surface energy is constant
so all free variables must be set with delu_dict, otherwise they are
assumed to be equal to delu_default.
Args:
miller_index ((h,k,l)): The facet to find the most stable slab in
delu_dict (dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
delu_default (float): Default value for all unset chemical potentials
no_doped (bool): Consider stability of clean slabs only.
no_clean (bool): Consider stability of doped slabs only.
Returns:
tuple[SlabEntry, float]: The most stable slab entry and its surface energy.
"""
all_delu_dict = self.set_all_variables(delu_dict, delu_default)
def get_coeffs(e):
coeffs = []
for du in all_delu_dict:
if type(self.as_coeffs_dict[e]).__name__ == "float":
coeffs.append(self.as_coeffs_dict[e])
elif du in self.as_coeffs_dict[e]:
coeffs.append(self.as_coeffs_dict[e][du])
else:
coeffs.append(0)
return np.array(coeffs)
all_entries, all_coeffs = [], []
for entry in self.all_slab_entries[miller_index]:
if not no_clean:
all_entries.append(entry)
all_coeffs.append(get_coeffs(entry))
if not no_doped:
for ads_entry in self.all_slab_entries[miller_index][entry]:
all_entries.append(ads_entry)
all_coeffs.append(get_coeffs(ads_entry))
du_vals = np.array(list(all_delu_dict.values()))
all_gamma = list(np.dot(all_coeffs, du_vals.T))
return all_entries[all_gamma.index(min(all_gamma))], float(min(all_gamma))
def wulff_from_chempot(
self,
delu_dict=None,
delu_default=0,
symprec=1e-5,
no_clean=False,
no_doped=False,
) -> WulffShape:
"""
Method to get the Wulff shape at a specific chemical potential.
Args:
delu_dict (dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
delu_default (float): Default value for all unset chemical potentials
symprec (float): See WulffShape.
no_doped (bool): Consider stability of clean slabs only.
no_clean (bool): Consider stability of doped slabs only.
Returns:
WulffShape: The WulffShape at u_ref and u_ads.
"""
lattice = SpacegroupAnalyzer(self.ucell_entry.structure).get_conventional_standard_structure().lattice
miller_list = list(self.all_slab_entries)
e_surf_list = []
for hkl in miller_list:
# For all configurations, calculate surface energy as a
# function of u. Use the lowest surface energy (corresponds
# to the most stable slab termination at that particular u)
gamma = self.get_stable_entry_at_u(
hkl,
delu_dict=delu_dict,
delu_default=delu_default,
no_clean=no_clean,
no_doped=no_doped,
)[1]
e_surf_list.append(gamma)
return WulffShape(lattice, miller_list, e_surf_list, symprec=symprec)
def area_frac_vs_chempot_plot(
self,
ref_delu: Symbol,
chempot_range: list[float],
delu_dict: dict[Symbol, float] | None = None,
delu_default: float = 0,
increments: int = 10,
no_clean: bool = False,
no_doped: bool = False,
) -> plt.Axes:
"""
1D plot. Plots the change in the area contribution
of each facet as a function of chemical potential.
Args:
ref_delu (Symbol): The free variable chempot with the format:
Symbol("delu_el") where el is the name of the element.
chempot_range (list[float]): Min/max range of chemical potential to plot along.
delu_dict (dict[Symbol, float]): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
delu_default (float): Default value for all unset chemical potentials.
increments (int): Number of data points between min/max or point
of intersection. Defaults to 10 points.
no_clean (bool): Some parameter, description missing.
no_doped (bool): Some parameter, description missing.
Returns:
plt.Axes: Plot of area frac on the Wulff shape for each facet vs chemical potential.
"""
delu_dict = delu_dict or {}
chempot_range = sorted(chempot_range)
all_chempots = np.linspace(min(chempot_range), max(chempot_range), increments)
# initialize a dictionary of lists of fractional areas for each hkl
hkl_area_dict: dict[Tuple3Ints, list[float]] = {}
for hkl in self.all_slab_entries:
hkl_area_dict[hkl] = []
# Get plot points for each Miller index
for u in all_chempots:
delu_dict[ref_delu] = u
wulff_shape = self.wulff_from_chempot(
delu_dict=delu_dict,
no_clean=no_clean,
no_doped=no_doped,
delu_default=delu_default,
)
for hkl in wulff_shape.area_fraction_dict:
hkl_area_dict[hkl].append(wulff_shape.area_fraction_dict[hkl])
# Plot the area fraction vs chemical potential for each facet
ax = pretty_plot(width=8, height=7)
for hkl in self.all_slab_entries:
clean_entry = next(iter(self.all_slab_entries[hkl]))
# Ignore any facets that never show up on the
# Wulff shape regardless of chemical potential
if all(a == 0 for a in hkl_area_dict[hkl]):
continue
plt.plot(
all_chempots,
hkl_area_dict[hkl],
"--",
color=self.color_dict[clean_entry],
label=str(hkl),
)
# Make the figure look nice
ax.set(ylabel=r"Fractional area $A^{Wulff}_{hkl}/A^{Wulff}$")
self.chempot_plot_addons(
ax,
chempot_range,
str(ref_delu).split("_")[1],
rect=[-0.0, 0, 0.95, 1],
pad=5,
ylim=[0, 1],
)
return ax
def get_surface_equilibrium(self, slab_entries, delu_dict=None):
"""
Takes in a list of SlabEntries and calculates the chemical potentials
at which all slabs in the list coexists simultaneously. Useful for
building surface phase diagrams. Note that to solve for x equations
(x slab_entries), there must be x free variables (chemical potentials).
Adjust delu_dict as need be to get the correct number of free variables.
Args:
slab_entries (array): The coefficients of the first equation
delu_dict (dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
Returns:
array: Array containing a solution to x equations with x
variables (x-1 chemical potential and 1 surface energy)
"""
# Generate all possible coefficients
all_parameters = []
all_eqns = []
for slab_entry in slab_entries:
se = self.surfe_dict[slab_entry]
# remove the free chempots we wish to keep constant and
# set the equation to 0 (subtract gamma from both sides)
if type(se).__name__ == "float":
all_eqns.append(se - Symbol("gamma"))
else:
se = sub_chempots(se, delu_dict) if delu_dict else se
all_eqns.append(se - Symbol("gamma"))
all_parameters.extend([p for p in list(se.free_symbols) if p not in all_parameters])
all_parameters.append(Symbol("gamma"))
# Now solve the system of linear eqns to find the chempot
# where the slabs are at equilibrium with each other
solution = linsolve(all_eqns, all_parameters)
if not solution:
warnings.warn("No solution")
return solution
return {param: next(iter(solution))[idx] for idx, param in enumerate(all_parameters)}
def stable_u_range_dict(
self,
chempot_range,
ref_delu,
no_doped=True,
no_clean=False,
delu_dict=None,
miller_index=(),
dmu_at_0=False,
return_se_dict=False,
):
"""
Creates a dictionary where each entry is a key pointing to a
chemical potential range where the surface of that entry is stable.
Does so by enumerating through all possible solutions (intersect)
for surface energies of a specific facet.
Args:
chempot_range ([max_chempot, min_chempot]): Range to consider the
stability of the slabs.
ref_delu (sympy Symbol): The range stability of each slab is based
on the chempot range of this chempot. Should be a sympy Symbol
object of the format: Symbol("delu_el") where el is the name of
the element
no_doped (bool): Consider stability of clean slabs only.
no_clean (bool): Consider stability of doped slabs only.
delu_dict (dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
miller_index (list): Miller index for a specific facet to get a
dictionary for.
dmu_at_0 (bool): If True, if the surface energies corresponding to
the chemical potential range is between a negative and positive
value, the value is a list of three chemical potentials with the
one in the center corresponding a surface energy of 0. Uselful
in identifying unphysical ranges of surface energies and their
chemical potential range.
return_se_dict (bool): Whether or not to return the corresponding
dictionary of surface energies
"""
if delu_dict is None:
delu_dict = {}
chempot_range = sorted(chempot_range)
stable_urange_dict, se_dict = {}, {}
# Get all entries for a specific facet
for hkl in self.all_slab_entries:
entries_in_hkl = []
# Skip this facet if this is not the facet we want
if miller_index and hkl != tuple(miller_index):
continue
if not no_clean:
entries_in_hkl.extend(self.all_slab_entries[hkl])
if not no_doped:
for entry in self.all_slab_entries[hkl]:
entries_in_hkl.extend(self.all_slab_entries[hkl][entry])
for entry in entries_in_hkl:
stable_urange_dict[entry] = []
se_dict[entry] = []
# if there is only one entry for this facet, then just give it the
# default urange, you can't make combinations with just 1 item
if len(entries_in_hkl) == 1:
stable_urange_dict[entries_in_hkl[0]] = chempot_range
u1, u2 = delu_dict.copy(), delu_dict.copy()
u1[ref_delu], u2[ref_delu] = chempot_range[0], chempot_range[1]
se = self.as_coeffs_dict[entries_in_hkl[0]]
se_dict[entries_in_hkl[0]] = [
sub_chempots(se, u1),
sub_chempots(se, u2),
]
continue
for pair in itertools.combinations(entries_in_hkl, 2):
# I'm assuming ref_delu was not set in delu_dict,
# so the solution should be for ref_delu
solution = self.get_surface_equilibrium(pair, delu_dict=delu_dict)
# Check if this solution is stable
if not solution:
continue
new_delu_dict = delu_dict.copy()
new_delu_dict[ref_delu] = solution[ref_delu]
stable_entry, gamma = self.get_stable_entry_at_u(
hkl, new_delu_dict, no_doped=no_doped, no_clean=no_clean
)
if stable_entry not in pair:
continue
# Now check if the solution is within the chempot range
if not chempot_range[0] <= solution[ref_delu] <= chempot_range[1]:
continue
for entry in pair:
stable_urange_dict[entry].append(solution[ref_delu])
se_dict[entry].append(gamma)
# Now check if all entries have 2 chempot values. If only
# one, we need to set the other value as either the upper
# limit or lower limit of the user provided chempot_range
new_delu_dict = delu_dict.copy()
for u in chempot_range:
new_delu_dict[ref_delu] = u
entry, gamma = self.get_stable_entry_at_u(
hkl, delu_dict=new_delu_dict, no_doped=no_doped, no_clean=no_clean
)
stable_urange_dict[entry].append(u)
se_dict[entry].append(gamma)
if dmu_at_0:
for entry, v in se_dict.items():
# if se are of opposite sign, determine chempot when se=0.
# Useful for finding a chempot range where se is unphysical
if not stable_urange_dict[entry]:
continue
if v[0] * v[1] < 0:
# solve for gamma=0
se = self.as_coeffs_dict[entry]
v.append(0)
stable_urange_dict[entry].append(solve(sub_chempots(se, delu_dict), ref_delu)[0])
# sort the chempot ranges for each facet
for entry, v in stable_urange_dict.items():
se_dict[entry] = [se for idx, se in sorted(zip(v, se_dict[entry], strict=True))]
stable_urange_dict[entry] = sorted(v)
if return_se_dict:
return stable_urange_dict, se_dict
return stable_urange_dict
def color_palette_dict(self, alpha=0.35):
"""
Helper function to assign each facet a unique color using a dictionary.
Args:
alpha (float): Degree of transparency
return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The keys are individual surface entries where
clean surfaces have a solid color while the corresponding adsorbed
surface will be transparent.
"""
color_dict = {}
rng = np.random.default_rng()
for hkl in self.all_slab_entries:
rgb_indices = [0, 1, 2]
color = [0, 0, 0, 1]
rng.shuffle(rgb_indices)
for idx, ind in enumerate(rgb_indices):
if idx == 2:
break
color[ind] = rng.uniform(0, 1)
# Get the clean (solid) colors first
clean_list = np.linspace(0, 1, len(self.all_slab_entries[hkl]))
for idx, clean in enumerate(self.all_slab_entries[hkl]):
c = copy.copy(color)
c[rgb_indices[2]] = clean_list[idx]
color_dict[clean] = c
# Now get the adsorbed (transparent) colors
for ads_entry in self.all_slab_entries[hkl][clean]:
c_ads = copy.copy(c)
c_ads[3] = alpha
color_dict[ads_entry] = c_ads
return color_dict
def chempot_vs_gamma_plot_one(
self,
ax: plt.Axes,
entry: SlabEntry,
ref_delu: Symbol,
chempot_range: list[float],
delu_dict: dict[Symbol, float] | None = None,
delu_default: float = 0,
label: str = "",
JPERM2: bool = False,
) -> plt.Axes:
"""
Helper function to help plot the surface energy of a
single SlabEntry as a function of chemical potential.
Args:
ax (plt.Axes): Matplotlib Axes instance for plotting.
entry: Entry of the slab whose surface energy we want
to plot. (Add appropriate description for type)
ref_delu (Symbol): The range stability of each slab is based
on the chempot range of this chempot.
chempot_range (list[float]): Range to consider the stability of the slabs.
delu_dict (dict[Symbol, float]): Dictionary of the chemical potentials.
delu_default (float): Default value for all unset chemical potentials.
label (str): Label of the slab for the legend.
JPERM2 (bool): Whether to plot surface energy in /m^2 (True) or
eV/A^2 (False).
Returns:
plt.Axes: Plot of surface energy vs chemical potential for one entry.
"""
delu_dict = delu_dict or {}
chempot_range = sorted(chempot_range)
ax = ax or plt.gca()
# use dashed lines for slabs that are not stoichiometric
# w.r.t. bulk. Label with formula if non-stoichiometric
ucell_comp = self.ucell_entry.composition.reduced_composition
if entry.adsorbates:
struct = entry.cleaned_up_slab
clean_comp = struct.composition.reduced_composition
else:
clean_comp = entry.composition.reduced_composition
mark = "--" if ucell_comp != clean_comp else "-"
delu_dict = self.set_all_variables(delu_dict, delu_default)
delu_dict[ref_delu] = chempot_range[0] # type: ignore[index]
gamma_min = self.as_coeffs_dict[entry]
gamma_min = gamma_min if type(gamma_min).__name__ == "float" else sub_chempots(gamma_min, delu_dict)
delu_dict[ref_delu] = chempot_range[1] # type: ignore[index]
gamma_max = self.as_coeffs_dict[entry]
gamma_max = gamma_max if type(gamma_max).__name__ == "float" else sub_chempots(gamma_max, delu_dict)
gamma_range = [gamma_min, gamma_max]
se_range = np.array(gamma_range) * EV_PER_ANG2_TO_JOULES_PER_M2 if JPERM2 else gamma_range
mark = entry.mark or mark
color = entry.color or self.color_dict[entry]
ax.plot(chempot_range, se_range, mark, color=color, label=label)
return ax
def chempot_vs_gamma(
self,
ref_delu,
chempot_range,
miller_index=(),
delu_dict=None,
delu_default=0,
JPERM2=False,
show_unstable=False,
ylim=None,
plt=None,
no_clean=False,
no_doped=False,
use_entry_labels=False,
no_label=False,
):
"""
Plots the surface energy as a function of chemical potential.
Each facet will be associated with its own distinct colors.
Dashed lines will represent stoichiometries different from that
of the mpid's compound. Transparent lines indicates adsorption.
Args:
ref_delu (sympy Symbol): The range stability of each slab is based
on the chempot range of this chempot. Should be a sympy Symbol
object of the format: Symbol("delu_el") where el is the name of
the element
chempot_range ([max_chempot, min_chempot]): Range to consider the
stability of the slabs.
miller_index (list): Miller index for a specific facet to get a
dictionary for.
delu_dict (dict): Dictionary of the chemical potentials to be set as
constant. Note the key should be a sympy Symbol object of the
format: Symbol("delu_el") where el is the name of the element.
delu_default (float): Default value for all unset chemical potentials
JPERM2 (bool): Whether to plot surface energy in /m^2 (True) or
eV/A^2 (False)
show_unstable (bool): Whether or not to show parts of the surface
energy plot outside the region of stability.
ylim ([ymax, ymin]): Range of y axis
no_doped (bool): Whether to plot for the clean slabs only.
no_clean (bool): Whether to plot for the doped slabs only.
use_entry_labels (bool): If True, will label each slab configuration
according to their given label in the SlabEntry object.
no_label (bool): Option to turn off labels.
Returns:
Plot: Plot of surface energy vs chempot for all entries.
"""
if delu_dict is None:
delu_dict = {}
chempot_range = sorted(chempot_range)
plt = plt or pretty_plot(width=8, height=7)
axes = plt.gca()
for hkl in self.all_slab_entries:
if miller_index and hkl != tuple(miller_index):
continue
# Get the chempot range of each surface if we only
# want to show the region where each slab is stable
if not show_unstable:
stable_u_range_dict = self.stable_u_range_dict(
chempot_range, ref_delu, no_doped=no_doped, delu_dict=delu_dict, miller_index=hkl
)
else:
stable_u_range_dict = {}
already_labelled = []
label = ""
for clean_entry in self.all_slab_entries[hkl]:
urange = stable_u_range_dict[clean_entry] if not show_unstable else chempot_range
# Don't plot if the slab is unstable, plot if it is.
if urange != []:
label = clean_entry.label
if label in already_labelled:
label = None
else:
already_labelled.append(label)
if not no_clean:
if use_entry_labels:
label = clean_entry.label
if no_label:
label = ""
plt = self.chempot_vs_gamma_plot_one(
plt,
clean_entry,
ref_delu,
urange,
delu_dict=delu_dict,
delu_default=delu_default,
label=label,
JPERM2=JPERM2,
)
if not no_doped:
for ads_entry in self.all_slab_entries[hkl][clean_entry]:
# Plot the adsorbed slabs
# Generate a label for the type of slab
urange = stable_u_range_dict[ads_entry] if not show_unstable else chempot_range
if urange != []:
if use_entry_labels:
label = ads_entry.label
if no_label:
label = ""
plt = self.chempot_vs_gamma_plot_one(
plt,
ads_entry,
ref_delu,
urange,
delu_dict=delu_dict,
delu_default=delu_default,