-
Notifications
You must be signed in to change notification settings - Fork 835
/
structure_environments.py
2378 lines (2148 loc) · 100 KB
/
structure_environments.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 contains objects that are used to describe the environments in a structure. The most detailed object
(StructureEnvironments) contains a very thorough analysis of the environments of a given atom but is difficult to
used as such. The LightStructureEnvironments object is a lighter version that is obtained by applying a "strategy"
on the StructureEnvironments object. Basically, the LightStructureEnvironments provides the coordination environment(s)
and possibly some fraction corresponding to these.
"""
from __future__ import annotations
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from matplotlib.colors import Normalize
from matplotlib.gridspec import GridSpec
from matplotlib.patches import Polygon
from monty.json import MontyDecoder, MSONable, jsanitize
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import AllCoordinationGeometries
from pymatgen.analysis.chemenv.coordination_environments.voronoi import DetailedVoronoiContainer
from pymatgen.analysis.chemenv.utils.chemenv_errors import ChemenvError
from pymatgen.analysis.chemenv.utils.defs_utils import AdditionalConditions
from pymatgen.core import Element, PeriodicNeighbor, PeriodicSite, Species, Structure
__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Geoffroy Hautier"
__version__ = "2.0"
__maintainer__ = "David Waroquiers"
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"
all_cg = AllCoordinationGeometries()
symbol_cn_mapping = all_cg.get_symbol_cn_mapping()
class StructureEnvironments(MSONable):
"""Class used to store the chemical environments of a given structure."""
AC = AdditionalConditions()
class NeighborsSet:
"""Class used to store a given set of neighbors of a given site (based on the detailed_voronoi)."""
def __init__(self, structure: Structure, isite, detailed_voronoi, site_voronoi_indices, sources=None):
"""Constructor for NeighborsSet.
Args:
structure: Structure object.
isite: Index of the site for which neighbors are stored in this NeighborsSet.
detailed_voronoi: Corresponding DetailedVoronoiContainer object containing all the possible
neighbors of the give site.
site_voronoi_indices: Indices of the voronoi sites in the DetailedVoronoiContainer object that
make up this NeighborsSet.
sources: Sources for this NeighborsSet, i.e. how this NeighborsSet was generated.
"""
self.structure = structure
self.isite = isite
self.detailed_voronoi = detailed_voronoi
self.voronoi = detailed_voronoi.voronoi_list2[isite]
if n_dupes := (len(set(site_voronoi_indices)) - len(site_voronoi_indices)):
raise ValueError(f"Set of neighbors contains {n_dupes} duplicates!")
self.site_voronoi_indices = sorted(site_voronoi_indices)
if sources is None:
self.sources = [{"origin": "UNKNOWN"}]
elif isinstance(sources, list):
self.sources = sources
else:
self.sources = [sources]
def get_neighb_voronoi_indices(self, permutation):
"""Get indices in the detailed_voronoi corresponding to the current permutation.
Args:
permutation: Current permutation for which the indices in the detailed_voronoi are needed.
Returns:
list[int]: indices in the detailed_voronoi.
"""
return [self.site_voronoi_indices[ii] for ii in permutation]
@property
def neighb_coords(self):
"""Coordinates of neighbors for this NeighborsSet."""
return [self.voronoi[inb]["site"].coords for inb in self.site_voronoi_indices]
@property
def neighb_coordsOpt(self):
"""Optimized access to the coordinates of neighbors for this NeighborsSet."""
return self.detailed_voronoi.voronoi_list_coords[self.isite].take(self.site_voronoi_indices, axis=0)
@property
def neighb_sites(self):
"""Neighbors for this NeighborsSet as pymatgen Sites."""
return [self.voronoi[inb]["site"] for inb in self.site_voronoi_indices]
@property
def neighb_sites_and_indices(self):
"""List of neighbors for this NeighborsSet as pymatgen Sites and their index in the original structure."""
return [
{"site": self.voronoi[inb]["site"], "index": self.voronoi[inb]["index"]}
for inb in self.site_voronoi_indices
]
@property
def coords(self):
"""Coordinates of the current central atom and its neighbors for this NeighborsSet."""
coords = [self.structure[self.isite].coords]
coords.extend(self.neighb_coords)
return coords
@property
def normalized_distances(self):
"""Normalized distances to each neighbor in this NeighborsSet."""
return [self.voronoi[inb]["normalized_distance"] for inb in self.site_voronoi_indices]
@property
def normalized_angles(self):
"""Normalized angles for each neighbor in this NeighborsSet."""
return [self.voronoi[inb]["normalized_angle"] for inb in self.site_voronoi_indices]
@property
def distances(self):
"""Distances to each neighbor in this NeighborsSet."""
return [self.voronoi[inb]["distance"] for inb in self.site_voronoi_indices]
@property
def angles(self):
"""Angles for each neighbor in this NeighborsSet."""
return [self.voronoi[inb]["angle"] for inb in self.site_voronoi_indices]
# @property
# def sphere_fraction_angles(self):
# return [0.25 * self.voronoi[inb]['angle'] / np.pi for inb in self.site_voronoi_indices]
@property
def info(self):
"""Summarized information about this NeighborsSet."""
was = self.normalized_angles
wds = self.normalized_distances
angles = self.angles
distances = self.distances
return {
"normalized_angles": was,
"normalized_distances": wds,
"normalized_angles_sum": np.sum(was),
"normalized_angles_mean": np.mean(was),
"normalized_angles_std": np.std(was),
"normalized_angles_min": np.min(was),
"normalized_angles_max": np.max(was),
"normalized_distances_mean": np.mean(wds),
"normalized_distances_std": np.std(wds),
"normalized_distances_min": np.min(wds),
"normalized_distances_max": np.max(wds),
"angles": angles,
"distances": distances,
"angles_sum": np.sum(angles),
"angles_mean": np.mean(angles),
"angles_std": np.std(angles),
"angles_min": np.min(angles),
"angles_max": np.max(angles),
"distances_mean": np.mean(distances),
"distances_std": np.std(distances),
"distances_min": np.min(distances),
"distances_max": np.max(distances),
}
def distance_plateau(self):
"""Returns the distances plateau's for this NeighborsSet."""
all_nbs_normalized_distances_sorted = sorted(
(nb["normalized_distance"] for nb in self.voronoi), reverse=True
)
maxdist = np.max(self.normalized_distances)
plateau = None
for idist, dist in enumerate(all_nbs_normalized_distances_sorted):
if np.isclose(
dist,
maxdist,
rtol=0.0,
atol=self.detailed_voronoi.normalized_distance_tolerance,
):
plateau = np.inf if idist == 0 else all_nbs_normalized_distances_sorted[idist - 1] - maxdist
break
if plateau is None:
raise ValueError("Plateau not found ...")
return plateau
def angle_plateau(self):
"""Returns the angles plateau's for this NeighborsSet."""
all_nbs_normalized_angles_sorted = sorted(nb["normalized_angle"] for nb in self.voronoi)
minang = np.min(self.normalized_angles)
for nb in self.voronoi:
print(nb)
plateau = None
for iang, ang in enumerate(all_nbs_normalized_angles_sorted):
if np.isclose(
ang,
minang,
rtol=0.0,
atol=self.detailed_voronoi.normalized_angle_tolerance,
):
plateau = minang if iang == 0 else minang - all_nbs_normalized_angles_sorted[iang - 1]
break
if plateau is None:
raise ValueError("Plateau not found ...")
return plateau
def voronoi_grid_surface_points(self, additional_condition=1, other_origins="DO_NOTHING"):
"""
Get the surface points in the Voronoi grid for this neighbor from the sources.
The general shape of the points should look like a staircase such as in the following figure :
^
0.0|
|
| B----C
| | |
| | |
a | k D-------E
n | | |
g | | |
l | | |
e | j F----n---------G
| | |
| | |
| A----g-------h----i---------H
|
|
1.0+------------------------------------------------->
1.0 distance 2.0 ->+Inf
Args:
additional_condition: Additional condition for the neighbors.
other_origins: What to do with sources that do not come from the Voronoi grid (e.g. "from hints").
"""
src_list = []
for src in self.sources:
if src["origin"] == "dist_ang_ac_voronoi":
if src["ac"] != additional_condition:
continue
src_list.append(src)
else:
if other_origins == "DO_NOTHING":
continue
raise NotImplementedError("Nothing implemented for other sources ...")
if len(src_list) == 0:
return None
dists = [src["dp_dict"]["min"] for src in src_list]
angles = [src["ap_dict"]["max"] for src in src_list]
next_dists = [src["dp_dict"]["next"] for src in src_list]
next_angles = [src["ap_dict"]["next"] for src in src_list]
points_dict = {}
p_dists = []
pangs = []
for idx in range(len(src_list)):
if not any(np.isclose(p_dists, dists[idx])):
p_dists.append(dists[idx])
if not any(np.isclose(p_dists, next_dists[idx])):
p_dists.append(next_dists[idx])
if not any(np.isclose(pangs, angles[idx])):
pangs.append(angles[idx])
if not any(np.isclose(pangs, next_angles[idx])):
pangs.append(next_angles[idx])
d1_indices = np.argwhere(np.isclose(p_dists, dists[idx])).flatten()
if len(d1_indices) != 1:
raise ValueError("Distance parameter not found ...")
d2_indices = np.argwhere(np.isclose(p_dists, next_dists[idx])).flatten()
if len(d2_indices) != 1:
raise ValueError("Distance parameter not found ...")
a1_indices = np.argwhere(np.isclose(pangs, angles[idx])).flatten()
if len(a1_indices) != 1:
raise ValueError("Angle parameter not found ...")
a2_indices = np.argwhere(np.isclose(pangs, next_angles[idx])).flatten()
if len(a2_indices) != 1:
raise ValueError("Angle parameter not found ...")
id1 = d1_indices[0]
id2 = d2_indices[0]
ia1 = a1_indices[0]
ia2 = a2_indices[0]
for id_ia in [(id1, ia1), (id1, ia2), (id2, ia1), (id2, ia2)]:
points_dict.setdefault(id_ia, 0)
points_dict[id_ia] += 1
new_pts = []
for pt, pt_nb in points_dict.items():
if pt_nb % 2 == 1:
new_pts.append(pt)
sorted_points = [(0, 0)]
move_ap_index = True
while True:
last_pt = sorted_points[-1]
if move_ap_index: # "Move" the angle parameter
idp = last_pt[0]
iap = None
for pt in new_pts:
if pt[0] == idp and pt != last_pt:
iap = pt[1]
break
else: # "Move" the distance parameter
idp = None
iap = last_pt[1]
for pt in new_pts:
if pt[1] == iap and pt != last_pt:
idp = pt[0]
break
if (idp, iap) == (0, 0):
break
if (idp, iap) in sorted_points:
raise ValueError("Error sorting points ...")
sorted_points.append((idp, iap))
move_ap_index = not move_ap_index
return [(p_dists[idp], pangs[iap]) for (idp, iap) in sorted_points]
@property
def source(self):
"""
Returns the source of this NeighborsSet (how it was generated, e.g. from which Voronoi
cutoffs, or from hints).
"""
if len(self.sources) != 1:
raise RuntimeError("Number of sources different from 1 !")
return self.sources[0]
def add_source(self, source):
"""
Add a source to this NeighborsSet.
Args:
source: Information about the generation of this NeighborsSet.
"""
if source not in self.sources:
self.sources.append(source)
def __len__(self):
return len(self.site_voronoi_indices)
def __hash__(self) -> int:
return len(self.site_voronoi_indices)
def __eq__(self, other: object) -> bool:
needed_attrs = ("isite", "site_voronoi_indices")
if not all(hasattr(other, attr) for attr in needed_attrs):
return NotImplemented
return all(getattr(self, attr) == getattr(other, attr) for attr in needed_attrs)
def __str__(self):
out = f"Neighbors Set for site #{self.isite} :\n"
out += f" - Coordination number : {len(self)}\n"
voro_indices = ", ".join(f"{site_voronoi_index}" for site_voronoi_index in self.site_voronoi_indices)
out += f" - Voronoi indices : {voro_indices}\n"
return out
def as_dict(self):
"""A JSON-serializable dict representation of the NeighborsSet."""
return {
"isite": self.isite,
"site_voronoi_indices": self.site_voronoi_indices,
"sources": self.sources,
}
@classmethod
def from_dict(cls, dct, structure: Structure, detailed_voronoi):
"""
Reconstructs the NeighborsSet algorithm from its JSON-serializable dict representation, together with
the structure and the DetailedVoronoiContainer.
As an inner (nested) class, the NeighborsSet is not supposed to be used anywhere else that inside the
StructureEnvironments. The from_dict method is thus using the structure and detailed_voronoi when
reconstructing itself. These two are both in the StructureEnvironments object.
Args:
dct: a JSON-serializable dict representation of a NeighborsSet.
structure: The structure.
detailed_voronoi: The Voronoi object containing all the neighboring atoms from which the subset of
neighbors for this NeighborsSet is extracted.
Returns:
NeighborsSet
"""
return cls(
structure=structure,
isite=dct["isite"],
detailed_voronoi=detailed_voronoi,
site_voronoi_indices=dct["site_voronoi_indices"],
sources=dct["sources"],
)
def __init__(
self,
voronoi,
valences,
sites_map,
equivalent_sites,
ce_list,
structure,
neighbors_sets=None,
info=None,
):
"""
Constructor for the StructureEnvironments object.
Args:
voronoi: VoronoiContainer object for the structure.
valences: Valences provided.
sites_map: Mapping of equivalent sites to the nonequivalent sites that have been computed.
equivalent_sites: List of list of equivalent sites of the structure.
ce_list: List of chemical environments.
structure: Structure object.
neighbors_sets: List of neighbors sets.
info: Additional information for this StructureEnvironments object.
"""
self.voronoi = voronoi
self.valences = valences
self.sites_map = sites_map
self.equivalent_sites = equivalent_sites
# self.struct_sites_to_irreducible_site_list_map = struct_sites_to_irreducible_site_list_map
self.ce_list = ce_list
self.structure = structure
if neighbors_sets is None:
self.neighbors_sets = [None] * len(self.structure)
else:
self.neighbors_sets = neighbors_sets
self.info = info
def init_neighbors_sets(self, isite, additional_conditions=None, valences=None):
"""
Initialize the list of neighbors sets for the current site.
Args:
isite: Index of the site under consideration.
additional_conditions: Additional conditions to be used for the initialization of the list of
neighbors sets, e.g. "Only anion-cation bonds", ...
valences: List of valences for each site in the structure (needed if an additional condition based on the
valence is used, e.g. only anion-cation bonds).
"""
site_voronoi = self.voronoi.voronoi_list2[isite]
if site_voronoi is None:
return
if additional_conditions is None:
additional_conditions = self.AC.ALL
if (self.AC.ONLY_ACB in additional_conditions or self.AC.ONLY_ACB_AND_NO_E2SEB) and valences is None:
raise ChemenvError(
"StructureEnvironments",
"init_neighbors_sets",
"Valences are not given while only_anion_cation_bonds are allowed. Cannot continue",
)
site_distance_parameters = self.voronoi.neighbors_normalized_distances[isite]
site_angle_parameters = self.voronoi.neighbors_normalized_angles[isite]
# Precompute distance conditions
distance_conditions = []
for idp, dp_dict in enumerate(site_distance_parameters):
distance_conditions.append([])
for inb in range(len(site_voronoi)):
cond = inb in dp_dict["nb_indices"]
distance_conditions[idp].append(cond)
# Precompute angle conditions
angle_conditions = []
for iap, ap_dict in enumerate(site_angle_parameters):
angle_conditions.append([])
for inb in range(len(site_voronoi)):
cond = inb in ap_dict["nb_indices"]
angle_conditions[iap].append(cond)
# Precompute additional conditions
precomputed_additional_conditions = {ac: [] for ac in additional_conditions}
for voro_nb_dict in site_voronoi:
for ac in additional_conditions:
cond = self.AC.check_condition(
condition=ac,
structure=self.structure,
parameters={
"valences": valences,
"neighbor_index": voro_nb_dict["index"],
"site_index": isite,
},
)
precomputed_additional_conditions[ac].append(cond)
# Add the neighbors sets based on the distance/angle/additional parameters
for idp, dp_dict in enumerate(site_distance_parameters):
for iap, ap_dict in enumerate(site_angle_parameters):
for iac, ac in enumerate(additional_conditions):
src = {
"origin": "dist_ang_ac_voronoi",
"idp": idp,
"iap": iap,
"dp_dict": dp_dict,
"ap_dict": ap_dict,
"iac": iac,
"ac": ac,
"ac_name": self.AC.CONDITION_DESCRIPTION[ac],
}
site_voronoi_indices = [
inb
for inb, voro_nb_dict in enumerate(site_voronoi)
if (
distance_conditions[idp][inb]
and angle_conditions[iap][inb]
and precomputed_additional_conditions[ac][inb]
)
]
nb_set = self.NeighborsSet(
structure=self.structure,
isite=isite,
detailed_voronoi=self.voronoi,
site_voronoi_indices=site_voronoi_indices,
sources=src,
)
self.add_neighbors_set(isite=isite, nb_set=nb_set)
def add_neighbors_set(self, isite, nb_set):
"""
Adds a neighbor set to the list of neighbors sets for this site.
Args:
isite: Index of the site under consideration.
nb_set: NeighborsSet to be added.
"""
if self.neighbors_sets[isite] is None:
self.neighbors_sets[isite] = {}
self.ce_list[isite] = {}
cn = len(nb_set)
if cn not in self.neighbors_sets[isite]:
self.neighbors_sets[isite][cn] = []
self.ce_list[isite][cn] = []
try:
nb_set_index = self.neighbors_sets[isite][cn].index(nb_set)
self.neighbors_sets[isite][cn][nb_set_index].add_source(nb_set.source)
except ValueError:
self.neighbors_sets[isite][cn].append(nb_set)
self.ce_list[isite][cn].append(None)
def update_coordination_environments(self, isite, cn, nb_set, ce):
"""
Updates the coordination environment for this site, coordination and neighbor set.
Args:
isite: Index of the site to be updated.
cn: Coordination to be updated.
nb_set: Neighbors set to be updated.
ce: ChemicalEnvironments object for this neighbors set.
"""
if self.ce_list[isite] is None:
self.ce_list[isite] = {}
if cn not in self.ce_list[isite]:
self.ce_list[isite][cn] = []
try:
nb_set_index = self.neighbors_sets[isite][cn].index(nb_set)
except ValueError:
raise ValueError("Neighbors set not found in the structure environments")
if nb_set_index == len(self.ce_list[isite][cn]):
self.ce_list[isite][cn].append(ce)
elif nb_set_index < len(self.ce_list[isite][cn]):
self.ce_list[isite][cn][nb_set_index] = ce
else:
raise ValueError("Neighbors set not yet in ce_list !")
def update_site_info(self, isite, info_dict):
"""
Update information about this site.
Args:
isite: Index of the site for which info has to be updated.
info_dict: Dictionary of information to be added for this site.
"""
if "sites_info" not in self.info:
self.info["sites_info"] = [{} for _ in range(len(self.structure))]
self.info["sites_info"][isite].update(info_dict)
def get_coordination_environments(self, isite, cn, nb_set):
"""
Get the ChemicalEnvironments for a given site, coordination and neighbors set.
Args:
isite: Index of the site for which the ChemicalEnvironments is looked for.
cn: Coordination for which the ChemicalEnvironments is looked for.
nb_set: Neighbors set for which the ChemicalEnvironments is looked for.
Returns:
ChemicalEnvironments
"""
if self.ce_list[isite] is None:
return None
if cn not in self.ce_list[isite]:
return None
try:
nb_set_index = self.neighbors_sets[isite][cn].index(nb_set)
except ValueError:
return None
return self.ce_list[isite][cn][nb_set_index]
def get_csm(self, isite, mp_symbol):
"""
Get the continuous symmetry measure for a given site in the given coordination environment.
Args:
isite: Index of the site.
mp_symbol: Symbol of the coordination environment for which we want the continuous symmetry measure.
Returns:
Continuous symmetry measure of the given site in the given environment.
"""
csms = self.get_csms(isite, mp_symbol)
if len(csms) != 1:
raise ChemenvError(
"StructureEnvironments",
"get_csm",
f"Number of csms for site #{isite} with mp_symbol {mp_symbol!r} = {len(csms)}",
)
return csms[0]
def get_csms(self, isite, mp_symbol) -> list:
"""
Returns the continuous symmetry measure(s) of site with index isite with respect to the
perfect coordination environment with mp_symbol. For some environments, a given mp_symbol might not
be available (if there is no voronoi parameters leading to a number of neighbors corresponding to
the coordination number of environment mp_symbol). For some environments, a given mp_symbol might
lead to more than one csm (when two or more different voronoi parameters lead to different neighbors
but with same number of neighbors).
Args:
isite: Index of the site.
mp_symbol: MP symbol of the perfect environment for which the csm has to be given.
Returns:
list[CSM]: for site isite with respect to geometry mp_symbol
"""
cn = symbol_cn_mapping[mp_symbol]
if cn not in self.ce_list[isite]:
return []
return [envs[mp_symbol] for envs in self.ce_list[isite][cn]]
def plot_csm_and_maps(self, isite, max_csm=8.0):
"""
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the
chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure
as the value for the color of that distfactor/angfactor set.
Args:
isite: Index of the site for which the plot has to be done
max_csm: Maximum continuous symmetry measure to be shown.
"""
fig = self.get_csm_and_maps(isite=isite, max_csm=max_csm)
if fig is None:
return
plt.show()
return
def get_csm_and_maps(
self, isite, max_csm=8.0, figsize=None, symmetry_measure_type=None
) -> tuple[plt.Figure, plt.Axes] | None:
"""
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the
chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure
as the value for the color of that distfactor/angfactor set.
Args:
isite: Index of the site for which the plot has to be done.
max_csm: Maximum continuous symmetry measure to be shown.
figsize: Size of the figure.
symmetry_measure_type: Type of continuous symmetry measure to be used.
Returns:
Matplotlib figure and axes representing the CSM and maps.
"""
if symmetry_measure_type is None:
symmetry_measure_type = "csm_wcs_ctwcc"
# Initializes the figure
fig = plt.figure() if figsize is None else plt.figure(figsize=figsize)
gs = GridSpec(2, 1, hspace=0.0, wspace=0.0)
ax = fig.add_subplot(gs[:])
ax_distang = ax.twinx()
idx = 0
cn_maps = []
all_wds = []
all_was = []
max_wd = 0.0
for cn, nb_sets in self.neighbors_sets[isite].items():
for inb_set, nb_set in enumerate(nb_sets):
ce = self.ce_list[isite][cn][inb_set]
if ce is None:
continue
min_geoms = ce.minimum_geometries(max_csm=max_csm)
if len(min_geoms) == 0:
continue
wds = nb_set.normalized_distances
max_wd = max(max_wd, *wds)
all_wds.append(wds)
all_was.append(nb_set.normalized_angles)
for mp_symbol, cg_dict in min_geoms:
csm = cg_dict["other_symmetry_measures"][symmetry_measure_type]
ax.plot(idx, csm, "ob")
ax.annotate(mp_symbol, xy=(idx, csm))
cn_maps.append((cn, inb_set))
idx += 1
if max_wd < 1.225:
ymax_wd = 1.25
yticks_wd = np.linspace(1.0, ymax_wd, 6)
elif max_wd < 1.36:
ymax_wd = 1.4
yticks_wd = np.linspace(1.0, ymax_wd, 5)
elif max_wd < 1.45:
ymax_wd = 1.5
yticks_wd = np.linspace(1.0, ymax_wd, 6)
elif max_wd < 1.55:
ymax_wd = 1.6
yticks_wd = np.linspace(1.0, ymax_wd, 7)
elif max_wd < 1.75:
ymax_wd = 1.8
yticks_wd = np.linspace(1.0, ymax_wd, 5)
elif max_wd < 1.95:
ymax_wd = 2.0
yticks_wd = np.linspace(1.0, ymax_wd, 6)
elif max_wd < 2.35:
ymax_wd = 2.5
yticks_wd = np.linspace(1.0, ymax_wd, 7)
else:
ymax_wd = np.ceil(1.1 * max_wd)
yticks_wd = np.linspace(1.0, ymax_wd, 6)
yticks_wa = np.linspace(0.0, 1.0, 6)
frac_bottom = 0.05
frac_top = 0.05
frac_middle = 0.1
yamin = frac_bottom
yamax = 0.5 - frac_middle / 2
ydmin = 0.5 + frac_middle / 2
ydmax = 1.0 - frac_top
def yang(wa):
return (yamax - yamin) * np.array(wa) + yamin
def ydist(wd):
return (np.array(wd) - 1.0) / (ymax_wd - 1.0) * (ydmax - ydmin) + ydmin
for idx, was in enumerate(all_was):
ax_distang.plot(0.2 + idx * np.ones_like(was), yang(was), "<g")
alpha = 0.3 if np.mod(idx, 2) == 0 else 0.1
ax_distang.fill_between(
[-0.5 + idx, 0.5 + idx],
[1.0, 1.0],
0.0,
facecolor="k",
alpha=alpha,
zorder=-1000,
)
for idx, wds in enumerate(all_wds):
ax_distang.plot(0.2 + idx * np.ones_like(wds), ydist(wds), "sm")
ax_distang.plot([-0.5, len(cn_maps)], [0.5, 0.5], "k--", alpha=0.5)
yticks = yang(yticks_wa).tolist()
yticks.extend(ydist(yticks_wd).tolist())
yticklabels = yticks_wa.tolist()
yticklabels.extend(yticks_wd.tolist())
ax_distang.set_yticks(yticks)
ax_distang.set_yticklabels(yticklabels)
fake_subplot_ang = fig.add_subplot(gs[1], frame_on=False)
fake_subplot_dist = fig.add_subplot(gs[0], frame_on=False)
fake_subplot_ang.set_yticks([])
fake_subplot_dist.set_yticks([])
fake_subplot_ang.set_xticks([])
fake_subplot_dist.set_xticks([])
fake_subplot_ang.set_ylabel("Angle parameter", labelpad=45, rotation=-90)
fake_subplot_dist.set_ylabel("Distance parameter", labelpad=45, rotation=-90)
fake_subplot_ang.yaxis.set_label_position("right")
fake_subplot_dist.yaxis.set_label_position("right")
ax_distang.set_ylim([0.0, 1.0])
ax.set_xticks(range(len(cn_maps)))
ax.set_ylabel("Continuous symmetry measure")
ax.set_xlim([-0.5, len(cn_maps) - 0.5])
ax_distang.set_xlim([-0.5, len(cn_maps) - 0.5])
ax.set_xticklabels([str(cn_map) for cn_map in cn_maps])
return fig, ax
def get_environments_figure(
self,
isite,
plot_type=None,
title="Coordination numbers",
max_dist=2.0,
colormap=None,
figsize=None,
strategy=None,
):
"""
Plotting of the coordination environments of a given site for all the distfactor/angfactor regions. The
chemical environments with the lowest continuous symmetry measure is shown for each distfactor/angfactor
region as the value for the color of that distfactor/angfactor region (using a colormap).
Args:
isite: Index of the site for which the plot has to be done.
plot_type: How to plot the coordinations.
title: Title for the figure.
max_dist: Maximum distance to be plotted when the plotting of the distance is set to 'initial_normalized'
or 'initial_real' (Warning: this is not the same meaning in both cases! In the first case, the
closest atom lies at a "normalized" distance of 1.0 so that 2.0 means refers to this normalized
distance while in the second case, the real distance is used).
colormap: Color map to be used for the continuous symmetry measure.
figsize: Size of the figure.
strategy: Whether to plot information about one of the Chemenv Strategies.
Returns:
tuple[plt.Figure, plt.Axes]: matplotlib figure and axes representing the environments.
"""
# Initializes the figure
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
# Initializes the distance and angle parameters
if plot_type is None:
plot_type = {
"distance_parameter": ("initial_normalized", None),
"angle_parameter": ("initial_normalized_inverted", None),
}
clr_map = cm.jet if colormap is None else colormap
clr_min = 0.0
clr_max = 10.0
norm = Normalize(vmin=clr_min, vmax=clr_max)
scalarmap = cm.ScalarMappable(norm=norm, cmap=clr_map)
dist_limits = [1.0, max_dist]
ang_limits = [0.0, 1.0]
if plot_type["distance_parameter"][0] == "one_minus_inverse_alpha_power_n":
if plot_type["distance_parameter"][1] is None:
exponent = 3
else:
exponent = plot_type["distance_parameter"][1]["exponent"]
xlabel = f"Distance parameter : $1.0-\\frac{{1.0}}{{\\alpha^{{{exponent}}}}}$"
def dp_func(dp):
return 1.0 - 1.0 / np.power(dp, exponent)
elif plot_type["distance_parameter"][0] == "initial_normalized":
xlabel = "Distance parameter : $\\alpha$"
def dp_func(dp):
return dp
else:
raise ValueError(f"Wrong value for distance parameter plot type \"{plot_type['distance_parameter'][0]}\"")
if plot_type["angle_parameter"][0] == "one_minus_gamma":
ylabel = "Angle parameter : $1.0-\\gamma$"
def ap_func(ap):
return 1.0 - ap
elif plot_type["angle_parameter"][0] in [
"initial_normalized_inverted",
"initial_normalized",
]:
ylabel = "Angle parameter : $\\gamma$"
def ap_func(ap):
return ap
else:
raise ValueError(f"Wrong value for angle parameter plot type \"{plot_type['angle_parameter'][0]}\"")
dist_limits = [dp_func(dp) for dp in dist_limits]
ang_limits = [ap_func(ap) for ap in ang_limits]
for cn, cn_nb_sets in self.neighbors_sets[isite].items():
for inb_set, nb_set in enumerate(cn_nb_sets):
nb_set_surface_pts = nb_set.voronoi_grid_surface_points()
if nb_set_surface_pts is None:
continue
ce = self.ce_list[isite][cn][inb_set]
if ce is None:
color = "w"
inv_color = "k"
text = f"{cn}"
else:
mingeom = ce.minimum_geometry()
if mingeom is not None:
mp_symbol = mingeom[0]
csm = mingeom[1]["symmetry_measure"]
color = scalarmap.to_rgba(csm)
inv_color = [
1.0 - color[0],
1.0 - color[1],
1.0 - color[2],
1.0,
]
text = f"{mp_symbol}"
else:
color = "w"
inv_color = "k"
text = f"{cn}"
nb_set_surface_pts = [(dp_func(pt[0]), ap_func(pt[1])) for pt in nb_set_surface_pts]
polygon = Polygon(
nb_set_surface_pts,
closed=True,
edgecolor="k",
facecolor=color,
linewidth=1.2,
)
ax.add_patch(polygon)
ipt = len(nb_set_surface_pts) / 2
if ipt != int(ipt):
raise RuntimeError("Uneven number of surface points")
ipt = int(ipt)
patch_center = (
(nb_set_surface_pts[0][0] + min(nb_set_surface_pts[ipt][0], dist_limits[1])) / 2,
(nb_set_surface_pts[0][1] + nb_set_surface_pts[ipt][1]) / 2,
)
if (
np.abs(nb_set_surface_pts[-1][1] - nb_set_surface_pts[-2][1]) > 0.06
and np.abs(min(nb_set_surface_pts[-1][0], dist_limits[1]) - nb_set_surface_pts[0][0]) > 0.125
):
xytext = (
(min(nb_set_surface_pts[-1][0], dist_limits[1]) + nb_set_surface_pts[0][0]) / 2,
(nb_set_surface_pts[-1][1] + nb_set_surface_pts[-2][1]) / 2,
)
ax.annotate(
text,
xy=xytext,
ha="center",
va="center",
color=inv_color,
fontsize="x-small",
)
elif (
np.abs(nb_set_surface_pts[ipt][1] - nb_set_surface_pts[0][1]) > 0.1
and np.abs(min(nb_set_surface_pts[ipt][0], dist_limits[1]) - nb_set_surface_pts[0][0]) > 0.125
):
xytext = patch_center
ax.annotate(
text,
xy=xytext,
ha="center",
va="center",
color=inv_color,
fontsize="x-small",
)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
dist_limits.sort()
ang_limits.sort()
ax.set_xlim(dist_limits)
ax.set_ylim(ang_limits)
if strategy is not None:
try:
strategy.add_strategy_visualization_to_subplot(subplot=ax)
except Exception:
pass
if plot_type["angle_parameter"][0] == "initial_normalized_inverted":
ax.axes.invert_yaxis()
scalarmap.set_array([clr_min, clr_max])
cb = fig.colorbar(scalarmap, ax=ax, extend="max")
cb.set_label("Continuous symmetry measure")
return fig, ax
def plot_environments(
self,
isite,
plot_type=None,
title="Coordination numbers",
max_dist=2.0,
figsize=None,
strategy=None,
):
"""
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the
chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure
as the value for the color of that distfactor/angfactor set.
Args:
isite: Index of the site for which the plot has to be done.
plot_type: How to plot the coordinations.
title: Title for the figure.
max_dist: Maximum distance to be plotted when the plotting of the distance is set to 'initial_normalized'
or 'initial_real' (Warning: this is not the same meaning in both cases! In the first case, the
closest atom lies at a "normalized" distance of 1.0 so that 2.0 means refers to this normalized
distance while in the second case, the real distance is used).
figsize: Size of the figure.
strategy: Whether to plot information about one of the Chemenv Strategies.
"""
fig, _ax = self.get_environments_figure(
isite=isite,
plot_type=plot_type,
title=title,
max_dist=max_dist,
figsize=figsize,