-
Notifications
You must be signed in to change notification settings - Fork 835
/
chemenv_strategies.py
3019 lines (2618 loc) · 115 KB
/
chemenv_strategies.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module provides so-called "strategies" to determine the coordination environments of an atom in a structure.
Some strategies can favour larger or smaller environments. Some strategies uniquely identifies the environments while
some others can identify the environment as a "mix" of several environments, each of which is assigned with a given
fraction. The choice of the strategy depends on the purpose of the user.
"""
from __future__ import annotations
import abc
import os
from typing import ClassVar
import numpy as np
from monty.json import MSONable
from scipy.stats import gmean
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 EquivalentSiteSearchError
from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import get_lower_and_upper_f
from pymatgen.analysis.chemenv.utils.defs_utils import AdditionalConditions
from pymatgen.analysis.chemenv.utils.func_utils import (
CSMFiniteRatioFunction,
CSMInfiniteRatioFunction,
DeltaCSMRatioFunction,
RatioFunction,
)
from pymatgen.core.operations import SymmOp
from pymatgen.core.sites import PeriodicSite
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
__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"
module_dir = os.path.dirname(os.path.abspath(__file__))
MPSYMBOL_TO_CN = AllCoordinationGeometries().get_symbol_cn_mapping()
ALLCG = AllCoordinationGeometries()
class StrategyOption(MSONable, metaclass=abc.ABCMeta):
"""Abstract class for the options of the chemenv strategies."""
allowed_values: str | None = None
@abc.abstractmethod
def as_dict(self):
"""A JSON-serializable dict representation of this strategy option."""
class DistanceCutoffFloat(float, StrategyOption):
"""Distance cutoff in a strategy."""
allowed_values = "Real number between 1 and +infinity"
def __new__(cls, cutoff):
"""Special float that should be between 1 and infinity.
:param cutoff: Distance cutoff.
"""
flt = float.__new__(cls, cutoff)
if flt < 1:
raise ValueError("Distance cutoff should be between 1 and +infinity")
return flt
def as_dict(self):
"""MSONable dict."""
return {
"@module": type(self).__module__,
"@class": type(self).__name__,
"value": self,
}
@classmethod
def from_dict(cls, d):
"""Initialize distance cutoff from dict.
:param d: Dict representation of the distance cutoff.
"""
return cls(d["value"])
class AngleCutoffFloat(float, StrategyOption):
"""Angle cutoff in a strategy."""
allowed_values = "Real number between 0 and 1"
def __new__(cls, cutoff):
"""Special float that should be between 0 and 1.
:param cutoff: Angle cutoff.
"""
flt = float.__new__(cls, cutoff)
if not 0 <= flt <= 1:
raise ValueError(f"Angle cutoff should be between 0 and 1, got {flt}")
return flt
def as_dict(self):
"""MSONable dict."""
return {
"@module": type(self).__module__,
"@class": type(self).__name__,
"value": self,
}
@classmethod
def from_dict(cls, d):
"""Initialize angle cutoff from dict.
:param d: Dict representation of the angle cutoff.
"""
return cls(d["value"])
class CSMFloat(float, StrategyOption):
"""Real number representing a Continuous Symmetry Measure."""
allowed_values = "Real number between 0 and 100"
def __new__(cls, cutoff):
"""Special float that should be between 0 and 100.
:param cutoff: CSM.
"""
flt = float.__new__(cls, cutoff)
if not 0 <= flt <= 100:
raise ValueError(f"Continuous symmetry measure limits should be between 0 and 100, got {flt}")
return flt
def as_dict(self):
"""MSONable dict."""
return {
"@module": type(self).__module__,
"@class": type(self).__name__,
"value": self,
}
@classmethod
def from_dict(cls, dct):
"""Initialize CSM from dict.
:param d: Dict representation of the CSM.
"""
return cls(dct["value"])
class AdditionalConditionInt(int, StrategyOption):
"""Integer representing an additional condition in a strategy."""
allowed_values = "Integer amongst :\n"
for integer, description in AdditionalConditions.CONDITION_DESCRIPTION.items():
allowed_values += f" - {integer} for {description!r}\n"
def __new__(cls, integer):
"""Special int representing additional conditions."""
if str(int(integer)) != str(integer):
raise ValueError(f"Additional condition {integer} is not an integer")
integer = int.__new__(cls, integer)
if integer not in AdditionalConditions.ALL:
raise ValueError(f"Additional condition {integer} is not allowed")
return integer
def as_dict(self):
"""MSONable dict."""
return {
"@module": type(self).__module__,
"@class": type(self).__name__,
"value": self,
}
@classmethod
def from_dict(cls, dct):
"""Initialize additional condition from dict.
:param d: Dict representation of the additional condition.
"""
return cls(dct["value"])
class AbstractChemenvStrategy(MSONable, metaclass=abc.ABCMeta):
"""
Class used to define a Chemenv strategy for the neighbors and coordination environment to be applied to a
StructureEnvironments object.
"""
AC = AdditionalConditions()
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict()
STRATEGY_DESCRIPTION: str | None = None
STRATEGY_INFO_FIELDS: ClassVar[list] = []
DEFAULT_SYMMETRY_MEASURE_TYPE = "csm_wcs_ctwcc"
def __init__(
self,
structure_environments=None,
symmetry_measure_type=DEFAULT_SYMMETRY_MEASURE_TYPE,
):
"""
Abstract constructor for the all chemenv strategies.
:param structure_environments: StructureEnvironments object containing all the information on the
coordination of the sites in a structure.
"""
self.structure_environments = None
if structure_environments is not None:
self.set_structure_environments(structure_environments)
self._symmetry_measure_type = symmetry_measure_type
@property
def symmetry_measure_type(self):
"""Type of symmetry measure."""
return self._symmetry_measure_type
def set_structure_environments(self, structure_environments):
"""Set the structure environments to this strategy.
:param structure_environments: StructureEnvironments object.
"""
self.structure_environments = structure_environments
if not isinstance(self.structure_environments.voronoi, DetailedVoronoiContainer):
raise ValueError('Voronoi Container not of type "DetailedVoronoiContainer"')
self.prepare_symmetries()
def prepare_symmetries(self):
"""Prepare the symmetries for the structure contained in the structure environments."""
try:
self.spg_analyzer = SpacegroupAnalyzer(self.structure_environments.structure)
self.symops = self.spg_analyzer.get_symmetry_operations()
except Exception:
self.symops = []
def equivalent_site_index_and_transform(self, psite):
"""Get the equivalent site and corresponding symmetry+translation transformations.
:param psite: Periodic site.
Returns:
Equivalent site in the unit cell, translations and symmetry transformation.
"""
# Get the index of the site in the unit cell of which the PeriodicSite psite is a replica.
try:
isite = self.structure_environments.structure.index(psite)
except ValueError:
try:
uc_psite = psite.to_unit_cell()
isite = self.structure_environments.structure.index(uc_psite)
except ValueError:
for isite2, site2 in enumerate(self.structure_environments.structure):
if psite.is_periodic_image(site2):
isite = isite2
break
# Get the translation between psite and its corresponding site in the unit cell (Translation I)
this_site = self.structure_environments.structure[isite]
dthis_site = psite.frac_coords - this_site.frac_coords
# Get the translation between the equivalent site for which the neighbors have been computed and the site in
# the unit cell that corresponds to psite (Translation II)
equiv_site = self.structure_environments.structure[self.structure_environments.sites_map[isite]].to_unit_cell()
# equivsite = self.structure_environments.structure[self.structure_environments.sites_map[isite]]
dequivsite = (
self.structure_environments.structure[self.structure_environments.sites_map[isite]].frac_coords
- equiv_site.frac_coords
)
found = False
# Find the symmetry that applies the site in the unit cell to the equivalent site, as well as the translation
# that gets back the site to the unit cell (Translation III)
# TODO: check that these tolerances are needed, now that the structures are refined before analyzing envs
tolerances = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4]
for tolerance in tolerances:
for sym_op in self.symops:
new_site = PeriodicSite(
equiv_site._species,
sym_op.operate(equiv_site.frac_coords),
equiv_site._lattice,
)
if new_site.is_periodic_image(this_site, tolerance=tolerance):
sym_trafo = sym_op
d_this_site2 = this_site.frac_coords - new_site.frac_coords
found = True
break
if not found:
sym_ops = [SymmOp.from_rotation_and_translation()]
for sym_op in sym_ops:
new_site = PeriodicSite(
equiv_site._species,
sym_op.operate(equiv_site.frac_coords),
equiv_site._lattice,
)
# if new_site.is_periodic_image(this_site):
if new_site.is_periodic_image(this_site, tolerance=tolerance):
sym_trafo = sym_op
d_this_site2 = this_site.frac_coords - new_site.frac_coords
found = True
break
if found:
break
if not found:
raise EquivalentSiteSearchError(psite)
return self.structure_environments.sites_map[isite], dequivsite, dthis_site + d_this_site2, sym_trafo
@abc.abstractmethod
def get_site_neighbors(self, site):
"""
Applies the strategy to the structure_environments object in order to get the neighbors of a given site.
:param site: Site for which the neighbors are looked for
:param structure_environments: StructureEnvironments object containing all the information needed to get the
neighbors of the site
Returns:
The list of neighbors of the site. For complex strategies, where one allows multiple solutions, this
can return a list of list of neighbors.
"""
raise NotImplementedError
@property
def uniquely_determines_coordination_environments(self):
"""Returns True if the strategy leads to a unique coordination environment."""
raise NotImplementedError
@abc.abstractmethod
def get_site_coordination_environment(self, site):
"""
Applies the strategy to the structure_environments object in order to define the coordination environment of
a given site.
:param site: Site for which the coordination environment is looked for
Returns:
The coordination environment of the site. For complex strategies, where one allows multiple
solutions, this can return a list of coordination environments for the site.
"""
raise NotImplementedError
@abc.abstractmethod
def get_site_coordination_environments(self, site):
"""
Applies the strategy to the structure_environments object in order to define the coordination environment of
a given site.
:param site: Site for which the coordination environment is looked for
Returns:
The coordination environment of the site. For complex strategies, where one allows multiple
solutions, this can return a list of coordination environments for the site.
"""
raise NotImplementedError
@abc.abstractmethod
def get_site_coordination_environments_fractions(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
ordered=True,
min_fraction=0,
return_maps=True,
return_strategy_dict_info=False,
):
"""
Applies the strategy to the structure_environments object in order to define the coordination environment of
a given site.
:param site: Site for which the coordination environment is looked for
Returns:
The coordination environment of the site. For complex strategies, where one allows multiple
solutions, this can return a list of coordination environments for the site.
"""
raise NotImplementedError
def get_site_ce_fractions_and_neighbors(self, site, full_ce_info=False, strategy_info=False):
"""
Applies the strategy to the structure_environments object in order to get coordination environments, their
fraction, csm, geometry_info, and neighbors
:param site: Site for which the above information is sought
Returns:
The list of neighbors of the site. For complex strategies, where one allows multiple solutions, this
can return a list of list of neighbors.
"""
isite, dequivsite, dthissite, mysym = self.equivalent_site_index_and_transform(site)
geoms_and_maps_list = self.get_site_coordination_environments_fractions(
site=site,
isite=isite,
dequivsite=dequivsite,
dthissite=dthissite,
mysym=mysym,
return_maps=True,
return_strategy_dict_info=True,
)
if geoms_and_maps_list is None:
return None
site_nbs_sets = self.structure_environments.neighbors_sets[isite]
ce_and_neighbors = []
for fractions_dict in geoms_and_maps_list:
ce_map = fractions_dict["ce_map"]
ce_nb_set = site_nbs_sets[ce_map[0]][ce_map[1]]
neighbors = [
{"site": nb_site_and_index["site"], "index": nb_site_and_index["index"]}
for nb_site_and_index in ce_nb_set.neighb_sites_and_indices
]
fractions_dict["neighbors"] = neighbors
ce_and_neighbors.append(fractions_dict)
return ce_and_neighbors
def set_option(self, option_name, option_value):
"""Set up a given option for this strategy.
:param option_name: Name of the option.
:param option_value: Value for this option.
"""
setattr(self, option_name, option_value)
def setup_options(self, all_options_dict):
"""Set up options for this strategy based on a dict.
:param all_options_dict: Dict of option_name->option_value.
"""
for option_name, option_value in all_options_dict.items():
self.set_option(option_name, option_value)
@abc.abstractmethod
def __eq__(self, other: object) -> bool:
"""
Equality method that should be implemented for any strategy
:param other: strategy to be compared with the current one
"""
raise NotImplementedError
def __str__(self):
out = f" Chemenv Strategy {type(self).__name__!r}\n"
out += f" {'=' * (19 + len(type(self).__name__))}\n\n"
out += f" Description :\n {'-' * 13}\n"
out += self.STRATEGY_DESCRIPTION
out += "\n\n"
out += f" Options :\n {'-' * 9}\n"
for option_name in self.STRATEGY_OPTIONS:
out += f" - {option_name} : {getattr(self, option_name)}\n"
return out
@abc.abstractmethod
def as_dict(self):
"""
Bson-serializable dict representation of the SimplestChemenvStrategy object.
Returns:
Bson-serializable dict representation of the SimplestChemenvStrategy object.
"""
raise NotImplementedError
@classmethod
def from_dict(cls, dct) -> AbstractChemenvStrategy:
"""
Reconstructs the SimpleAbundanceChemenvStrategy object from a dict representation of the
SimpleAbundanceChemenvStrategy object created using the as_dict method.
:param dct: dict representation of the SimpleAbundanceChemenvStrategy object
Returns:
StructureEnvironments object.
"""
raise NotImplementedError
class SimplestChemenvStrategy(AbstractChemenvStrategy):
"""
Simplest ChemenvStrategy using fixed angle and distance parameters for the definition of neighbors in the
Voronoi approach. The coordination environment is then given as the one with the lowest continuous symmetry measure.
"""
# Default values for the distance and angle cutoffs
DEFAULT_DISTANCE_CUTOFF = 1.4
DEFAULT_ANGLE_CUTOFF = 0.3
DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFF = 10
DEFAULT_ADDITIONAL_CONDITION = AbstractChemenvStrategy.AC.ONLY_ACB
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict( # type: ignore
distance_cutoff=dict(
type=DistanceCutoffFloat,
internal="_distance_cutoff",
default=DEFAULT_DISTANCE_CUTOFF,
),
angle_cutoff=dict(
type=AngleCutoffFloat,
internal="_angle_cutoff",
default=DEFAULT_ANGLE_CUTOFF,
),
additional_condition=dict(
type=AdditionalConditionInt,
internal="_additional_condition",
default=DEFAULT_ADDITIONAL_CONDITION,
),
continuous_symmetry_measure_cutoff=dict(
type=CSMFloat,
internal="_continuous_symmetry_measure_cutoff",
default=DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFF,
),
)
STRATEGY_DESCRIPTION = (
" Simplest ChemenvStrategy using fixed angle and distance parameters \n"
" for the definition of neighbors in the Voronoi approach. \n"
" The coordination environment is then given as the one with the \n"
" lowest continuous symmetry measure."
)
def __init__(
self,
structure_environments=None,
distance_cutoff=DEFAULT_DISTANCE_CUTOFF,
angle_cutoff=DEFAULT_ANGLE_CUTOFF,
additional_condition=DEFAULT_ADDITIONAL_CONDITION,
continuous_symmetry_measure_cutoff=DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFF,
symmetry_measure_type=AbstractChemenvStrategy.DEFAULT_SYMMETRY_MEASURE_TYPE,
):
"""
Constructor for this SimplestChemenvStrategy.
:param distance_cutoff: Distance cutoff used
:param angle_cutoff: Angle cutoff used.
"""
AbstractChemenvStrategy.__init__(self, structure_environments, symmetry_measure_type=symmetry_measure_type)
self.distance_cutoff = distance_cutoff
self.angle_cutoff = angle_cutoff
self.additional_condition = additional_condition
self.continuous_symmetry_measure_cutoff = continuous_symmetry_measure_cutoff
@property
def uniquely_determines_coordination_environments(self):
"""Whether this strategy uniquely determines coordination environments."""
return True
@property
def distance_cutoff(self):
"""Distance cutoff used."""
return self._distance_cutoff
@distance_cutoff.setter
def distance_cutoff(self, distance_cutoff):
"""Set the distance cutoff for this strategy.
:param distance_cutoff: Distance cutoff.
"""
self._distance_cutoff = DistanceCutoffFloat(distance_cutoff)
@property
def angle_cutoff(self):
"""Angle cutoff used."""
return self._angle_cutoff
@angle_cutoff.setter
def angle_cutoff(self, angle_cutoff):
"""Set the angle cutoff for this strategy.
:param angle_cutoff: Angle cutoff.
"""
self._angle_cutoff = AngleCutoffFloat(angle_cutoff)
@property
def additional_condition(self):
"""Additional condition for this strategy."""
return self._additional_condition
@additional_condition.setter
def additional_condition(self, additional_condition):
"""Set the additional condition for this strategy.
:param additional_condition: Additional condition.
"""
self._additional_condition = AdditionalConditionInt(additional_condition)
@property
def continuous_symmetry_measure_cutoff(self):
"""CSM cutoff used."""
return self._continuous_symmetry_measure_cutoff
@continuous_symmetry_measure_cutoff.setter
def continuous_symmetry_measure_cutoff(self, continuous_symmetry_measure_cutoff):
"""Set the CSM cutoff for this strategy.
:param continuous_symmetry_measure_cutoff: CSM cutoff
"""
self._continuous_symmetry_measure_cutoff = CSMFloat(continuous_symmetry_measure_cutoff)
def get_site_neighbors(self, site, isite=None, dequivsite=None, dthissite=None, mysym=None):
"""Get the neighbors of a given site.
:param site: Site for which neighbors are needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
Returns:
List of coordinated neighbors of site.
"""
if isite is None:
isite, dequivsite, dthissite, mysym = self.equivalent_site_index_and_transform(site)
_ce, cn_map = self.get_site_coordination_environment(
site=site,
isite=isite,
dequivsite=dequivsite,
dthissite=dthissite,
mysym=mysym,
return_map=True,
)
nb_set = self.structure_environments.neighbors_sets[isite][cn_map[0]][cn_map[1]]
eq_site_ps = nb_set.neighb_sites
coordinated_neighbors = []
for ps in eq_site_ps:
coords = mysym.operate(ps.frac_coords + dequivsite) + dthissite
ps_site = PeriodicSite(ps._species, coords, ps._lattice)
coordinated_neighbors.append(ps_site)
return coordinated_neighbors
def get_site_coordination_environment(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
return_map=False,
):
"""Get the coordination environment of a given site.
:param site: Site for which coordination environment is needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
:param return_map: Whether to return cn_map (identifies the NeighborsSet used).
Returns:
Coordination environment of site.
"""
if isite is None:
isite, *_ = self.equivalent_site_index_and_transform(site)
neighbors_normalized_distances = self.structure_environments.voronoi.neighbors_normalized_distances[isite]
neighbors_normalized_angles = self.structure_environments.voronoi.neighbors_normalized_angles[isite]
i_dist = None
for iwd, wd in enumerate(neighbors_normalized_distances):
if self.distance_cutoff >= wd["min"]:
i_dist = iwd
else:
break
i_ang = None
for iwa, wa in enumerate(neighbors_normalized_angles):
if self.angle_cutoff <= wa["max"]:
i_ang = iwa
else:
break
if i_dist is None or i_ang is None:
raise ValueError("Distance or angle parameter not found ...")
my_cn = my_inb_set = None
found = False
for cn, nb_sets in self.structure_environments.neighbors_sets[isite].items():
for inb_set, nb_set in enumerate(nb_sets):
sources = [
src
for src in nb_set.sources
if src["origin"] == "dist_ang_ac_voronoi" and src["ac"] == self.additional_condition
]
for src in sources:
if src["idp"] == i_dist and src["iap"] == i_ang:
my_cn = cn
my_inb_set = inb_set
found = True
break
if found:
break
if found:
break
if not found:
return None
cn_map = (my_cn, my_inb_set)
ce = self.structure_environments.ce_list[self.structure_environments.sites_map[isite]][cn_map[0]][cn_map[1]]
if ce is None:
return None
coord_geoms = ce.coord_geoms
if return_map:
if coord_geoms is None:
return cn_map[0], cn_map
return (
ce.minimum_geometry(symmetry_measure_type=self._symmetry_measure_type),
cn_map,
)
if coord_geoms is None:
return cn_map[0]
return ce.minimum_geometry(symmetry_measure_type=self._symmetry_measure_type)
def get_site_coordination_environments_fractions(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
ordered=True,
min_fraction=0,
return_maps=True,
return_strategy_dict_info=False,
):
"""Get the coordination environments of a given site and additional information.
:param site: Site for which coordination environment is needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
:param ordered: Whether to order the list by fractions.
:param min_fraction: Minimum fraction to include in the list
:param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used).
:param return_strategy_dict_info: Whether to add the info about the strategy used.
Returns:
List of Dict with coordination environment, fraction and additional info.
"""
if isite is None or dequivsite is None or dthissite is None or mysym is None:
isite, dequivsite, dthissite, mysym = self.equivalent_site_index_and_transform(site)
site_nb_sets = self.structure_environments.neighbors_sets[isite]
if site_nb_sets is None:
return None
ce_and_map = self.get_site_coordination_environment(
site=site,
isite=isite,
dequivsite=dequivsite,
dthissite=dthissite,
mysym=mysym,
return_map=True,
)
if ce_and_map is None:
return None
ce, ce_map = ce_and_map
if ce is None:
ce_dict = {
"ce_symbol": f"UNKNOWN:{ce_map[0]}",
"ce_dict": None,
"ce_fraction": 1,
}
else:
ce_dict = {"ce_symbol": ce[0], "ce_dict": ce[1], "ce_fraction": 1}
if return_maps:
ce_dict["ce_map"] = ce_map
if return_strategy_dict_info:
ce_dict["strategy_info"] = {}
return [ce_dict]
def get_site_coordination_environments(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
return_maps=False,
):
"""Get the coordination environments of a given site.
:param site: Site for which coordination environment is needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
:param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used).
Returns:
List of coordination environment.
"""
env = self.get_site_coordination_environment(
site=site, isite=isite, dequivsite=dequivsite, dthissite=dthissite, mysym=mysym, return_map=return_maps
)
return [env]
def add_strategy_visualization_to_subplot(self, subplot, visualization_options=None, plot_type=None):
"""Add a visual of the strategy on a distance-angle plot.
:param subplot: Axes object onto the visual should be added.
:param visualization_options: Options for the visual.
:param plot_type: Type of distance-angle plot.
"""
subplot.plot(
self._distance_cutoff, self._angle_cutoff, "o", markeredgecolor=None, markerfacecolor="w", markersize=12
)
subplot.plot(self._distance_cutoff, self._angle_cutoff, "x", linewidth=2, markersize=12)
def __eq__(self, other: object) -> bool:
if not isinstance(other, type(self)):
return NotImplemented
return (
self._distance_cutoff == other._distance_cutoff
and self._angle_cutoff == other._angle_cutoff
and self._additional_condition == other._additional_condition
and self._continuous_symmetry_measure_cutoff == other._continuous_symmetry_measure_cutoff
and self.symmetry_measure_type == other.symmetry_measure_type
)
def as_dict(self):
"""
Bson-serializable dict representation of the SimplestChemenvStrategy object.
Returns:
Bson-serializable dict representation of the SimplestChemenvStrategy object.
"""
return {
"@module": type(self).__module__,
"@class": type(self).__name__,
"distance_cutoff": float(self._distance_cutoff),
"angle_cutoff": float(self._angle_cutoff),
"additional_condition": int(self._additional_condition),
"continuous_symmetry_measure_cutoff": float(self._continuous_symmetry_measure_cutoff),
"symmetry_measure_type": self._symmetry_measure_type,
}
@classmethod
def from_dict(cls, dct: dict) -> SimplestChemenvStrategy:
"""
Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as_dict method.
:param dct: dict representation of the SimplestChemenvStrategy object
Returns:
StructureEnvironments object.
"""
return cls(
distance_cutoff=dct["distance_cutoff"],
angle_cutoff=dct["angle_cutoff"],
additional_condition=dct["additional_condition"],
continuous_symmetry_measure_cutoff=dct["continuous_symmetry_measure_cutoff"],
symmetry_measure_type=dct["symmetry_measure_type"],
)
class SimpleAbundanceChemenvStrategy(AbstractChemenvStrategy):
"""
Simple ChemenvStrategy using the neighbors that are the most "abundant" in the grid of angle and distance
parameters for the definition of neighbors in the Voronoi approach.
The coordination environment is then given as the one with the lowest continuous symmetry measure.
"""
DEFAULT_MAX_DIST = 2.0
DEFAULT_ADDITIONAL_CONDITION = AbstractChemenvStrategy.AC.ONLY_ACB
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict( # type: ignore
surface_calculation_type={},
additional_condition=dict(
type=AdditionalConditionInt,
internal="_additional_condition",
default=DEFAULT_ADDITIONAL_CONDITION,
),
)
STRATEGY_DESCRIPTION = (
' Simple Abundance ChemenvStrategy using the most "abundant" neighbors map \n'
" for the definition of neighbors in the Voronoi approach. \n"
" The coordination environment is then given as the one with the \n"
" lowest continuous symmetry measure."
)
def __init__(
self,
structure_environments=None,
additional_condition=AbstractChemenvStrategy.AC.ONLY_ACB,
symmetry_measure_type=AbstractChemenvStrategy.DEFAULT_SYMMETRY_MEASURE_TYPE,
):
"""
Constructor for the SimpleAbundanceChemenvStrategy.
:param structure_environments: StructureEnvironments object containing all the information on the
coordination of the sites in a structure.
"""
raise NotImplementedError("SimpleAbundanceChemenvStrategy not yet implemented")
AbstractChemenvStrategy.__init__(self, structure_environments, symmetry_measure_type=symmetry_measure_type)
self._additional_condition = additional_condition
@property
def uniquely_determines_coordination_environments(self):
"""Whether this strategy uniquely determines coordination environments."""
return True
def get_site_neighbors(self, site):
"""Get the neighbors of a given site with this strategy.
:param site: Periodic site.
Returns:
List of neighbors of site.
"""
isite, dequivsite, dthissite, mysym = self.equivalent_site_index_and_transform(site)
cn_map = self._get_map(isite)
eqsite_ps = self.structure_environments.unique_coordinated_neighbors(isite, cn_map=cn_map)
coordinated_neighbors = []
for ps in eqsite_ps:
coords = mysym.operate(ps.frac_coords + dequivsite) + dthissite
ps_site = PeriodicSite(ps._species, coords, ps._lattice)
coordinated_neighbors.append(ps_site)
return coordinated_neighbors
def get_site_coordination_environment(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
return_map=False,
):
"""Get the coordination environment of a given site.
:param site: Site for which coordination environment is needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
:param return_map: Whether to return cn_map (identifies the NeighborsSet used).
Returns:
Coordination environment of site.
"""
if isite is None:
isite, *_ = self.equivalent_site_index_and_transform(site)
cn_map = self._get_map(isite)
if cn_map is None:
return None
coord_geoms = self.structure_environments.ce_list[self.structure_environments.sites_map[isite]][cn_map[0]][
cn_map[1]
]
if return_map:
if coord_geoms is None:
return cn_map[0], cn_map
return (
coord_geoms.minimum_geometry(symmetry_measure_type=self._symmetry_measure_type),
cn_map,
)
if coord_geoms is None:
return cn_map[0]
return coord_geoms.minimum_geometry(symmetry_measure_type=self._symmetry_measure_type)
def get_site_coordination_environments(
self,
site,
isite=None,
dequivsite=None,
dthissite=None,
mysym=None,
return_maps=False,
):
"""Get the coordination environments of a given site.
:param site: Site for which coordination environment is needed.
:param isite: Index of the site.
:param dequivsite: Translation of the equivalent site.
:param dthissite: Translation of this site.
:param mysym: Symmetry to be applied.
:param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used).
Returns:
List of coordination environment.
"""
return [
self.get_site_coordination_environment(
site=site,
isite=isite,
dequivsite=dequivsite,
dthissite=dthissite,
mysym=mysym,
return_map=return_maps,
)
]
def _get_map(self, isite):
maps_and_surfaces = self._get_maps_surfaces(isite)
if maps_and_surfaces is None:
return None
surface_max = 0
imax = -1
for ii, map_and_surface in enumerate(maps_and_surfaces):
all_additional_conditions = [ac[2] for ac in map_and_surface["parameters_indices"]]
if self._additional_condition in all_additional_conditions and map_and_surface["surface"] > surface_max:
surface_max = map_and_surface["surface"]
imax = ii
return maps_and_surfaces[imax]["map"]
def _get_maps_surfaces(self, isite, surface_calculation_type=None):
if surface_calculation_type is None:
surface_calculation_type = {
"distance_parameter": ("initial_normalized", None),
"angle_parameter": ("initial_normalized", None),
}
return self.structure_environments.voronoi.maps_and_surfaces(
isite=isite,
surface_calculation_type=surface_calculation_type,
max_dist=self.DEFAULT_MAX_DIST,
)
def __eq__(self, other: object) -> bool: