-
Notifications
You must be signed in to change notification settings - Fork 835
/
local_env.py
4459 lines (3856 loc) · 177 KB
/
local_env.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module provides classes to perform analyses of
the local environments (e.g., finding near neighbors)
of single sites in molecules and structures.
"""
from __future__ import annotations
import json
import math
import os
import warnings
from bisect import bisect_left
from collections import defaultdict, namedtuple
from copy import deepcopy
from functools import lru_cache
from math import acos, asin, atan2, cos, exp, fabs, pi, pow, sin, sqrt
from typing import TYPE_CHECKING, Any, Literal, get_args
import numpy as np
from monty.dev import requires
from monty.serialization import loadfn
from ruamel.yaml import YAML
from scipy.spatial import Voronoi
from pymatgen.analysis.bond_valence import BV_PARAMS, BVAnalyzer
from pymatgen.analysis.graphs import MoleculeGraph, StructureGraph
from pymatgen.analysis.molecule_structure_comparator import CovalentRadius
from pymatgen.core import Element, IStructure, PeriodicNeighbor, PeriodicSite, Site, Species, Structure
try:
from openbabel import openbabel
except Exception:
openbabel = None
if TYPE_CHECKING:
from pymatgen.core.composition import SpeciesLike
__author__ = "Shyue Ping Ong, Geoffroy Hautier, Sai Jayaraman, "
__author__ += "Nils E. R. Zimmermann, Bharat Medasani, Evan Spotte-Smith"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Nils E. R. Zimmermann"
__email__ = "nils.e.r.zimmermann@gmail.com"
__status__ = "Production"
__date__ = "August 17, 2017"
module_dir = os.path.dirname(os.path.abspath(__file__))
yaml = YAML()
with open(f"{module_dir}/op_params.yaml") as file:
default_op_params = yaml.load(file)
with open(f"{module_dir}/cn_opt_params.yaml") as file:
cn_opt_params = yaml.load(file)
with open(f"{module_dir}/ionic_radii.json") as file:
_ion_radii = json.load(file)
class ValenceIonicRadiusEvaluator:
"""
Computes site valences and ionic radii for a structure using bond valence
analyzer.
"""
def __init__(self, structure: Structure) -> None:
"""
Args:
structure: pymatgen Structure.
"""
self._structure = structure.copy()
self._valences = self._get_valences()
self._ionic_radii = self._get_ionic_radii()
@property
def radii(self):
"""List of ionic radii of elements in the order of sites."""
elems = [site.species_string for site in self._structure]
return dict(zip(elems, self._ionic_radii))
@property
def valences(self):
"""List of oxidation states of elements in the order of sites."""
el = [site.species_string for site in self._structure]
return dict(zip(el, self._valences))
@property
def structure(self):
"""Returns oxidation state decorated structure."""
return self._structure.copy()
def _get_ionic_radii(self):
"""
Computes ionic radii of elements for all sites in the structure.
If valence is zero, atomic radius is used.
"""
radii = []
vnn = VoronoiNN()
def nearest_key(sorted_vals, skey):
n = bisect_left(sorted_vals, skey)
if n == len(sorted_vals):
return sorted_vals[-1]
if n == 0:
return sorted_vals[0]
before = sorted_vals[n - 1]
after = sorted_vals[n]
if after - skey < skey - before:
return after
return before
for i, site in enumerate(self._structure):
if isinstance(site.specie, Element):
radius = site.specie.atomic_radius
# Handle elements with no atomic_radius
# by using calculated values instead.
if radius is None:
radius = site.specie.atomic_radius_calculated
if radius is None:
raise ValueError(f"cannot assign radius to element {site.specie}")
radii.append(radius)
continue
el = site.specie.symbol
oxi_state = int(round(site.specie.oxi_state))
coord_no = int(round(vnn.get_cn(self._structure, i)))
try:
tab_oxi_states = sorted(map(int, _ion_radii[el]))
oxi_state = nearest_key(tab_oxi_states, oxi_state)
radius = _ion_radii[el][str(oxi_state)][str(coord_no)]
except KeyError:
new_coord_no = coord_no + 1 if vnn.get_cn(self._structure, i) - coord_no > 0 else coord_no - 1
try:
radius = _ion_radii[el][str(oxi_state)][str(new_coord_no)]
coord_no = new_coord_no
except Exception:
tab_coords = sorted(map(int, _ion_radii[el][str(oxi_state)]))
new_coord_no = nearest_key(tab_coords, coord_no)
i = 0
for val in tab_coords:
if val > coord_no:
break
i = i + 1
if i == len(tab_coords):
key = str(tab_coords[-1])
radius = _ion_radii[el][str(oxi_state)][key]
elif i == 0:
key = str(tab_coords[0])
radius = _ion_radii[el][str(oxi_state)][key]
else:
key = str(tab_coords[i - 1])
radius1 = _ion_radii[el][str(oxi_state)][key]
key = str(tab_coords[i])
radius2 = _ion_radii[el][str(oxi_state)][key]
radius = (radius1 + radius2) / 2
# implement complex checks later
radii.append(radius)
return radii
def _get_valences(self):
"""Computes ionic valences of elements for all sites in the structure."""
try:
bv = BVAnalyzer()
self._structure = bv.get_oxi_state_decorated_structure(self._structure)
valences = bv.get_valences(self._structure)
except Exception:
try:
bv = BVAnalyzer(symm_tol=0)
self._structure = bv.get_oxi_state_decorated_structure(self._structure)
valences = bv.get_valences(self._structure)
except Exception:
valences = []
for site in self._structure:
if len(site.specie.common_oxidation_states) > 0:
valences.append(site.specie.common_oxidation_states[0])
# Handle noble gas species
# which have no entries in common_oxidation_states.
else:
valences.append(0)
if sum(valences):
valences = [0] * len(self._structure)
else:
self._structure.add_oxidation_state_by_site(valences)
# raise
# el = [site.specie.symbol for site in self._structure]
# el = [site.species_string for site in self._structure]
# el = [site.specie for site in self._structure]
# valence_dict = dict(zip(el, valences))
return valences
on_disorder_options = Literal["take_majority_strict", "take_majority_drop", "take_max_species", "error"]
def _handle_disorder(structure: Structure, on_disorder: on_disorder_options):
"""What to do in bonding and coordination number analysis if a site is disordered."""
if all(site.is_ordered for site in structure):
return structure
if on_disorder == "error":
raise ValueError(
f"Generating StructureGraphs for disordered Structures is unsupported. Pass on_disorder='take "
"majority' | 'take_max_species' | 'error'. 'take_majority_strict' considers only the majority species from "
"each site in the bonding algorithm and raises ValueError in case there is no majority (e.g. as in {Fe: "
"0.4, O: 0.4, C: 0.2}) whereas 'take_majority_drop' just ignores the site altogether when computing bonds "
"as if it didn't exist. 'take_max_species' extracts the first max species on each site (Fe in prev. "
"example since Fe and O have equal occupancy and Fe comes first). 'error' raises an error in case "
f"of disordered structure. Offending {structure = }"
)
if on_disorder.startswith("take_"):
# disordered structures raise AttributeError when passed to NearNeighbors.get_cn()
# or NearNeighbors.get_bonded_structure() (and probably others too, see GH-2070).
# As a workaround, we create a new structure with majority species on each site.
structure = structure.copy() # make a copy so we don't mutate the original structure
for idx, site in enumerate(structure):
max_specie = max(site.species, key=site.species.get) # type: ignore
max_val = site.species[max_specie]
if max_val <= 0.5:
if on_disorder == "take_majority_strict":
raise ValueError(
f"Site {idx} has no majority species, the max species is {max_specie} with occupancy {max_val}"
)
if on_disorder == "take_majority_drop":
continue
# this is the take_max_species case
site.species = max_specie # set site species in copied structure to max specie
else:
raise ValueError(f"Unexpected {on_disorder = }, should be one of {get_args(on_disorder_options)}")
return structure
class NearNeighbors:
"""
Base class to determine near neighbors that typically include nearest
neighbors and others that are within some tolerable distance.
"""
def __eq__(self, other: object) -> bool:
if isinstance(other, type(self)):
return self.__dict__ == other.__dict__
return False
def __hash__(self) -> int:
return len(self.__dict__.items())
def __repr__(self) -> str:
return f"{type(self).__name__}()"
@property
def structures_allowed(self) -> bool:
"""
Boolean property: can this NearNeighbors class be used with Structure
objects?
"""
raise NotImplementedError("structures_allowed is not defined!")
@property
def molecules_allowed(self) -> bool:
"""
Boolean property: can this NearNeighbors class be used with Molecule
objects?
"""
raise NotImplementedError("molecules_allowed is not defined!")
@property
def extend_structure_molecules(self) -> bool:
"""
Boolean property: Do Molecules need to be converted to Structures to use
this NearNeighbors class? Note: this property is not defined for classes
for which molecules_allowed is False.
"""
raise NotImplementedError("extend_structures_molecule is not defined!")
def get_cn(
self,
structure: Structure,
n: int,
use_weights: bool = False,
on_disorder: on_disorder_options = "take_majority_strict",
) -> float:
"""
Get coordination number, CN, of site with index n in structure.
Args:
structure (Structure): input structure.
n (int): index of site for which to determine CN.
use_weights (bool): flag indicating whether (True) to use weights for computing the coordination
number or not (False, default: each coordinated site has equal weight).
on_disorder ('take_majority_strict' | 'take_majority_drop' | 'take_max_species' | 'error'):
What to do when encountering a disordered structure. 'error' will raise ValueError.
'take_majority_strict' will use the majority specie on each site and raise
ValueError if no majority exists. 'take_max_species' will use the first max specie
on each site. For {{Fe: 0.4, O: 0.4, C: 0.2}}, 'error' and 'take_majority_strict'
will raise ValueError, while 'take_majority_drop' ignores this site altogether and
'take_max_species' will use Fe as the site specie.
Returns:
cn (float): coordination number.
"""
structure = _handle_disorder(structure, on_disorder)
siw = self.get_nn_info(structure, n)
return sum(e["weight"] for e in siw) if use_weights else len(siw)
def get_cn_dict(self, structure: Structure, n: int, use_weights: bool = False):
"""
Get coordination number, CN, of each element bonded to site with index n in structure.
Args:
structure (Structure): input structure
n (int): index of site for which to determine CN.
use_weights (bool): flag indicating whether (True)
to use weights for computing the coordination number
or not (False, default: each coordinated site has equal
weight).
Returns:
cn (dict): dictionary of CN of each element bonded to site
"""
siw = self.get_nn_info(structure, n)
cn_dict = {}
for idx in siw:
site_element = idx["site"].species_string
if site_element not in cn_dict:
if use_weights:
cn_dict[site_element] = idx["weight"]
else:
cn_dict[site_element] = 1
elif use_weights:
cn_dict[site_element] += idx["weight"]
else:
cn_dict[site_element] += 1
return cn_dict
def get_nn(self, structure: Structure, n: int):
"""
Get near neighbors of site with index n in structure.
Args:
structure (Structure): input structure.
n (int): index of site in structure for which to determine
neighbors.
Returns:
sites (list of Site objects): near neighbors.
"""
return [e["site"] for e in self.get_nn_info(structure, n)]
def get_weights_of_nn_sites(self, structure: Structure, n: int):
"""
Get weight associated with each near neighbor of site with
index n in structure.
Args:
structure (Structure): input structure.
n (int): index of site for which to determine the weights.
Returns:
weights (list of floats): near-neighbor weights.
"""
return [e["weight"] for e in self.get_nn_info(structure, n)]
def get_nn_images(self, structure: Structure, n: int):
"""
Get image location of all near neighbors of site with index n in
structure.
Args:
structure (Structure): input structure.
n (int): index of site for which to determine the image
location of near neighbors.
Returns:
images (list of 3D integer array): image locations of
near neighbors.
"""
return [e["image"] for e in self.get_nn_info(structure, n)]
def get_nn_info(self, structure: Structure, n: int) -> list[dict]:
"""
Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n.
Args:
structure (Structure): input structure.
n (int): index of site for which to determine near-neighbor
information.
Returns:
siw (list[dict]): each dictionary provides information
about a single near neighbor, where key 'site' gives access to the
corresponding Site object, 'image' gives the image location, and
'weight' provides the weight that a given near-neighbor site contributes
to the coordination number (1 or smaller), 'site_index' gives index of
the corresponding site in the original structure.
"""
raise NotImplementedError("get_nn_info(structure, n) is not defined!")
def get_all_nn_info(self, structure: Structure):
"""Get a listing of all neighbors for all sites in a structure.
Args:
structure (Structure): Input structure
Return:
List of NN site information for each site in the structure. Each
entry has the same format as `get_nn_info`
"""
return [self.get_nn_info(structure, n) for n in range(len(structure))]
def get_nn_shell_info(self, structure: Structure, site_idx, shell):
"""Get a certain nearest neighbor shell for a certain site.
Determines all non-backtracking paths through the neighbor network
computed by `get_nn_info`. The weight is determined by multiplying
the weight of the neighbor at each hop through the network. For
example, a 2nd-nearest-neighbor that has a weight of 1 from its
1st-nearest-neighbor and weight 0.5 from the original site will
be assigned a weight of 0.5.
As this calculation may involve computing the nearest neighbors of
atoms multiple times, the calculation starts by computing all of the
neighbor info and then calling `_get_nn_shell_info`. If you are likely
to call this method for more than one site, consider calling `get_all_nn`
first and then calling this protected method yourself.
Args:
structure (Structure): Input structure
site_idx (int): index of site for which to determine neighbor
information.
shell (int): Which neighbor shell to retrieve (1 == 1st NN shell)
Returns:
list of dictionaries. Each entry in the list is information about
a certain neighbor in the structure, in the same format as
`get_nn_info`.
"""
all_nn_info = self.get_all_nn_info(structure)
sites = self._get_nn_shell_info(structure, all_nn_info, site_idx, shell)
# Now update the site positions. Did not do this during NN options because that can be slower.
output = []
for info in sites:
orig_site = structure[info["site_index"]]
info["site"] = PeriodicSite(
orig_site.species,
np.add(orig_site.frac_coords, info["image"]),
structure.lattice,
properties=orig_site.properties,
)
output.append(info)
return output
def _get_nn_shell_info(
self,
structure,
all_nn_info,
site_idx,
shell,
_previous_steps=frozenset(),
_cur_image=(0, 0, 0),
):
"""Private method for computing the neighbor shell information.
Args:
structure (Structure) - Structure being assessed
all_nn_info ([[dict]]) - Results from `get_all_nn_info`
site_idx (int) - index of site for which to determine neighbor
information.
shell (int) - Which neighbor shell to retrieve (1 == 1st NN shell)
_previous_steps ({(site_idx, image}) - Internal use only: Set of
sites that have already been traversed.
_cur_image (tuple) - Internal use only Image coordinates of current atom
Returns:
list of dictionaries. Each entry in the list is information about
a certain neighbor in the structure, in the same format as
`get_nn_info`. Does not update the site positions
"""
if shell <= 0:
raise ValueError("Shell must be positive")
# Append this site to the list of previously-visited sites
_previous_steps = _previous_steps | {(site_idx, _cur_image)}
# Get all the neighbors of this site
possible_steps = list(all_nn_info[site_idx])
for i, step in enumerate(possible_steps):
# Update the image information
# Note: We do not update the site position yet, as making a PeriodicSite
# for each intermediate step is too costly
step = dict(step)
step["image"] = tuple(np.add(step["image"], _cur_image).tolist())
possible_steps[i] = step
# Get only the non-backtracking steps
allowed_steps = [x for x in possible_steps if (x["site_index"], x["image"]) not in _previous_steps]
# If we are the last step (i.e., shell == 1), done!
if shell == 1:
# No further work needed, just package these results
return allowed_steps
# If not, Get the N-1 NNs of these allowed steps
terminal_neighbors = [
self._get_nn_shell_info(
structure,
all_nn_info,
x["site_index"],
shell - 1,
_previous_steps,
x["image"],
)
for x in allowed_steps
]
# Each allowed step results in many terminal neighbors
# And, different first steps might results in the same neighbor
# Now, we condense those neighbors into a single entry per neighbor
all_sites = {}
for first_site, term_sites in zip(allowed_steps, terminal_neighbors):
for term_site in term_sites:
key = (term_site["site_index"], tuple(term_site["image"]))
# The weight for this site is equal to the weight of the
# first step multiplied by the weight of the terminal neighbor
term_site["weight"] *= first_site["weight"]
# Check if this site is already known
value = all_sites.get(key)
if value is not None:
# If so, add to its weight
value["weight"] += term_site["weight"]
else:
# If not, prepare to add it
value = term_site
all_sites[key] = value
return list(all_sites.values())
@staticmethod
def _get_image(structure: Structure, site: Site) -> tuple[int, int, int]:
"""Private convenience method for get_nn_info,
gives lattice image from provided PeriodicSite and Structure.
Image is defined as displacement from original site in structure to a given site.
i.e. if structure has a site at (-0.1, 1.0, 0.3), then (0.9, 0, 2.3) -> jimage = (1, -1, 2).
Note that this method takes O(number of sites) due to searching an original site.
Args:
structure (Structure): Structure Object
site (Site): PeriodicSite Object
Returns:
tuple[int, int , int] Lattice image
"""
if isinstance(site, PeriodicNeighbor):
return site.image
original_site = structure[NearNeighbors._get_original_site(structure, site)]
image = np.around(np.subtract(site.frac_coords, original_site.frac_coords))
return tuple(image.astype(int))
@staticmethod
def _get_original_site(structure: Structure, site: Site) -> int:
"""Private convenience method for get_nn_info,
gives original site index from ProvidedPeriodicSite.
"""
if isinstance(site, PeriodicNeighbor):
return site.index
if isinstance(structure, (IStructure, Structure)):
for idx, struc_site in enumerate(structure):
if site.is_periodic_image(struc_site):
return idx
else:
for idx, struc_site in enumerate(structure):
if site == struc_site:
return idx
raise ValueError("Site not found in structure")
def get_bonded_structure(
self,
structure: Structure,
decorate: bool = False,
weights: bool = True,
edge_properties: bool = False,
on_disorder: on_disorder_options = "take_majority_strict",
) -> StructureGraph | MoleculeGraph:
"""
Obtain a StructureGraph object using this NearNeighbor
class. Requires the optional dependency networkx
(pip install networkx).
Args:
structure: Structure object.
decorate (bool): whether to annotate site properties with order parameters using neighbors
determined by this NearNeighbor class
weights (bool): whether to include edge weights from NearNeighbor class in StructureGraph
edge_properties (bool) whether to include further edge properties from NearNeighbor class in StructureGraph
on_disorder ('take_majority_strict' | 'take_majority_drop' | 'take_max_species' | 'error'):
What to do when encountering a disordered structure. 'error' will raise ValueError.
'take_majority_strict' will use the majority specie on each site and raise
ValueError if no majority exists. 'take_max_species' will use the first max specie
on each site. For {{Fe: 0.4, O: 0.4, C: 0.2}}, 'error' and 'take_majority_strict'
will raise ValueError, while 'take_majority_drop' ignores this site altogether and
'take_max_species' will use Fe as the site specie.
Returns:
StructureGraph: object from pymatgen.analysis.graphs
"""
structure = _handle_disorder(structure, on_disorder)
if decorate:
# Decorate all sites in the underlying structure
# with site properties that provides information on the
# coordination number and coordination pattern based
# on the (current) structure of this graph.
order_parameters = [self.get_local_order_parameters(structure, n) for n in range(len(structure))]
structure.add_site_property("order_parameters", order_parameters)
sg = StructureGraph.with_local_env_strategy(structure, self, weights=weights, edge_properties=edge_properties)
# sets the attributes
sg.set_node_attributes()
return sg
def get_local_order_parameters(self, structure: Structure, n: int):
"""
Calculate those local structure order parameters for
the given site whose ideal CN corresponds to the
underlying motif (e.g., CN=4, then calculate the
square planar, tetrahedral, see-saw-like,
rectangular see-saw-like order parameters).
Args:
structure: Structure object
n (int): site index.
Returns (dict[str, float]):
A dict of order parameters (values) and the
underlying motif type (keys; for example, tetrahedral).
"""
# code from @nisse3000, moved here from graphs to avoid circular
# import, also makes sense to have this as a general NN method
cn = self.get_cn(structure, n)
int_cn = [int(k_cn) for k_cn in cn_opt_params]
if cn in int_cn:
names = list(cn_opt_params[cn])
types = []
params = []
for name in names:
types.append(cn_opt_params[cn][name][0])
tmp = cn_opt_params[cn][name][1] if len(cn_opt_params[cn][name]) > 1 else None
params.append(tmp)
lostops = LocalStructOrderParams(types, parameters=params)
sites = [structure[n], *self.get_nn(structure, n)]
lostop_vals = lostops.get_order_parameters(sites, 0, indices_neighs=list(range(1, cn + 1))) # type: ignore
dct = {}
for i, lostop in enumerate(lostop_vals):
dct[names[i]] = lostop
return dct
return None
class VoronoiNN(NearNeighbors):
"""
Uses a Voronoi algorithm to determine near neighbors for each site in a
structure.
"""
def __init__(
self,
tol=0,
targets=None,
cutoff=13.0,
allow_pathological=False,
weight="solid_angle",
extra_nn_info=True,
compute_adj_neighbors=True,
):
"""
Args:
tol (float): tolerance parameter for near-neighbor finding. Faces that are
smaller than `tol` fraction of the largest face are not included in the
tessellation. (default: 0).
targets (Element or list of Elements): target element(s).
cutoff (float): cutoff radius in Angstrom to look for near-neighbor
atoms. Defaults to 13.0.
allow_pathological (bool): whether to allow infinite vertices in
determination of Voronoi coordination.
weight (string) - Statistic used to weigh neighbors (see the statistics
available in get_voronoi_polyhedra)
extra_nn_info (bool) - Add all polyhedron info to `get_nn_info`
compute_adj_neighbors (bool) - Whether to compute which neighbors are
adjacent. Turn off for faster performance.
"""
super().__init__()
self.tol = tol
self.cutoff = cutoff
self.allow_pathological = allow_pathological
self.targets = targets
self.weight = weight
self.extra_nn_info = extra_nn_info
self.compute_adj_neighbors = compute_adj_neighbors
@property
def structures_allowed(self) -> bool:
"""
Boolean property: can this NearNeighbors class be used with Structure
objects?
"""
return True
@property
def molecules_allowed(self) -> bool:
"""
Boolean property: can this NearNeighbors class be used with Molecule
objects?
"""
return False
def get_voronoi_polyhedra(self, structure: Structure, n: int):
"""
Gives a weighted polyhedra around a site.
See ref: A Proposed Rigorous Definition of Coordination Number,
M. O'Keeffe, Acta Cryst. (1979). A35, 772-775
Args:
structure (Structure): structure for which to evaluate the
coordination environment.
n (int): site index.
Returns:
A dict of sites sharing a common Voronoi facet with the site
n mapped to a directory containing statistics about the facet:
- solid_angle - Solid angle subtended by face
- angle_normalized - Solid angle normalized such that the
faces with the largest
- area - Area of the facet
- face_dist - Distance between site n and the facet
- volume - Volume of Voronoi cell for this face
- n_verts - Number of vertices on the facet
"""
# Assemble the list of neighbors used in the tessellation. Gets all atoms within a certain radius
targets = structure.elements if self.targets is None else self.targets
center = structure[n]
# max cutoff is the longest diagonal of the cell + room for noise
corners = [[1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1]]
d_corners = [np.linalg.norm(structure.lattice.get_cartesian_coords(c)) for c in corners]
max_cutoff = max(d_corners) + 0.01
while True:
try:
neighbors = structure.get_sites_in_sphere(center.coords, self.cutoff)
neighbors = [ngbr[0] for ngbr in sorted(neighbors, key=lambda s: s[1])]
# Run the Voronoi tessellation
qvoronoi_input = [site.coords for site in neighbors]
voro = Voronoi(qvoronoi_input) # can give seg fault if cutoff is too small
# Extract data about the site in question
cell_info = self._extract_cell_info(0, neighbors, targets, voro, self.compute_adj_neighbors)
break
except RuntimeError as exc:
if self.cutoff >= max_cutoff:
if exc.args and "vertex" in exc.args[0]:
# pass through the error raised by _extract_cell_info
raise exc
raise RuntimeError("Error in Voronoi neighbor finding; max cutoff exceeded")
self.cutoff = min(self.cutoff * 2, max_cutoff + 0.001)
return cell_info
def get_all_voronoi_polyhedra(self, structure: Structure):
"""Get the Voronoi polyhedra for all site in a simulation cell.
Args:
structure (Structure): Structure to be evaluated
Returns:
A dict of sites sharing a common Voronoi facet with the site
n mapped to a directory containing statistics about the facet:
- solid_angle - Solid angle subtended by face
- angle_normalized - Solid angle normalized such that the
faces with the largest
- area - Area of the facet
- face_dist - Distance between site n and the facet
- volume - Volume of Voronoi cell for this face
- n_verts - Number of vertices on the facet
"""
# Special case: For atoms with 1 site, the atom in the root image is not
# included in the get_all_neighbors output. Rather than creating logic to add
# that atom to the neighbor list, which requires detecting whether it will be
# translated to reside within the unit cell before neighbor detection, it is
# less complex to just call the one-by-one operation
if len(structure) == 1:
return [self.get_voronoi_polyhedra(structure, 0)]
# Assemble the list of neighbors used in the tessellation
targets = structure.elements if self.targets is None else self.targets
# Initialize the list of sites with the atoms in the origin unit cell
# The `get_all_neighbors` function returns neighbors for each site's image in
# the original unit cell. We start off with these central atoms to ensure they
# are included in the tessellation
sites = [x.to_unit_cell() for x in structure]
indices = [(i, 0, 0, 0) for i, _ in enumerate(structure)]
# Get all neighbors within a certain cutoff. Record both the list of these neighbors and the site indices.
all_neighs = structure.get_all_neighbors(self.cutoff, include_index=True, include_image=True)
for neighs in all_neighs:
sites.extend([x[0] for x in neighs])
indices.extend([(x[2],) + x[3] for x in neighs])
# Get the non-duplicates (using the site indices for numerical stability)
indices = np.array(indices, dtype=int) # type: ignore
indices, uniq_inds = np.unique(indices, return_index=True, axis=0) # type: ignore[assignment]
sites = [sites[idx] for idx in uniq_inds]
# Sort array such that atoms in the root image are first
# Exploit the fact that the array is sorted by the unique operation such that
# the images associated with atom 0 are first, followed by atom 1, etc.
(root_images,) = np.nonzero(np.abs(indices[:, 1:]).max(axis=1) == 0) # type: ignore
del indices # Save memory (tessellations can be costly)
# Run the tessellation
qvoronoi_input = [s.coords for s in sites]
voro = Voronoi(qvoronoi_input)
# Get the information for each neighbor
return [
self._extract_cell_info(idx, sites, targets, voro, self.compute_adj_neighbors)
for idx in root_images.tolist()
]
def _extract_cell_info(self, site_idx, sites, targets, voro, compute_adj_neighbors=False):
"""Get the information about a certain atom from the results of a tessellation.
Args:
site_idx (int) - Index of the atom in question
sites ([Site]) - List of all sites in the tessellation
targets ([Element]) - Target elements
voro - Output of qvoronoi
compute_adj_neighbors (boolean) - Whether to compute which neighbors are adjacent
Returns:
A dict of sites sharing a common Voronoi facet. Key is facet id
(not useful) and values are dictionaries containing statistics
about the facet:
- site: Pymatgen site
- solid_angle - Solid angle subtended by face
- angle_normalized - Solid angle normalized such that the
faces with the largest
- area - Area of the facet
- face_dist - Distance between site n and the facet
- volume - Volume of Voronoi cell for this face
- n_verts - Number of vertices on the facet
- adj_neighbors - Facet id's for the adjacent neighbors
"""
# Get the coordinates of every vertex
all_vertices = voro.vertices
# Get the coordinates of the central site
center_coords = sites[site_idx].coords
# Iterate through all the faces in the tessellation
results = {}
for nn, vind in voro.ridge_dict.items():
# Get only those that include the site in question
if site_idx in nn:
other_site = nn[0] if nn[1] == site_idx else nn[1]
if -1 in vind:
# -1 indices correspond to the Voronoi cell
# missing a face
if self.allow_pathological:
continue
raise RuntimeError("This structure is pathological, infinite vertex in the Voronoi construction")
# Get the solid angle of the face
facets = [all_vertices[idx] for idx in vind]
angle = solid_angle(center_coords, facets)
# Compute the volume of associated with this face
volume = 0
# qvoronoi returns vertices in CCW order, so I can break
# the face up in to segments (0,1,2), (0,2,3), ... to compute
# its area where each number is a vertex size
for j, k in zip(vind[1:], vind[2:]):
volume += vol_tetra(
center_coords,
all_vertices[vind[0]],
all_vertices[j],
all_vertices[k],
)
# Compute the distance of the site to the face
face_dist = np.linalg.norm(center_coords - sites[other_site].coords) / 2
# Compute the area of the face (knowing V=Ad/3)
face_area = 3 * volume / face_dist
# Compute the normal of the facet
normal = np.subtract(sites[other_site].coords, center_coords)
normal /= np.linalg.norm(normal)
# Store by face index
results[other_site] = {
"site": sites[other_site],
"normal": normal,
"solid_angle": angle,
"volume": volume,
"face_dist": face_dist,
"area": face_area,
"n_verts": len(vind),
}
# If we are computing which neighbors are adjacent, store the vertices
if compute_adj_neighbors:
results[other_site]["verts"] = vind
# all sites should have at least two connected ridges in periodic system
if len(results) == 0:
raise ValueError("No Voronoi neighbors found for site - try increasing cutoff")
# Get only target elements
result_weighted = {}
for nn_index, nn_stats in results.items():
# Check if this is a target site
nn = nn_stats["site"]
if nn.is_ordered:
if nn.specie in targets:
result_weighted[nn_index] = nn_stats
else: # if nn site is disordered
for disordered_sp in nn.species:
if disordered_sp in targets:
result_weighted[nn_index] = nn_stats
# If desired, determine which neighbors are adjacent
if compute_adj_neighbors:
# Initialize storage for the adjacent neighbors
adj_neighbors = {idx: [] for idx in result_weighted}
# Find the neighbors that are adjacent by finding those
# that contain exactly two vertices
for a_ind, a_nn_info in result_weighted.items():
# Get the indices for this site
a_verts = set(a_nn_info["verts"])
# Loop over all neighbors that have an index lower that this one
# The goal here is to exploit the fact that neighbor adjacency is
# symmetric (if A is adj to B, B is adj to A)
for b_ind, b_nninfo in result_weighted.items():
if b_ind > a_ind:
continue
if len(a_verts.intersection(b_nninfo["verts"])) == 2:
adj_neighbors[a_ind].append(b_ind)
adj_neighbors[b_ind].append(a_ind)
# Store the results in the nn_info
for key, neighbors in adj_neighbors.items():
result_weighted[key]["adj_neighbors"] = neighbors
return result_weighted
def get_nn_info(self, structure: Structure, n: int):
"""
Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n in structure
using Voronoi decomposition.
Args:
structure (Structure): input structure.
n (int): index of site for which to determine near-neighbor sites.
Returns:
siw (list of tuples (Site, array, float)): tuples, each one
of which represents a coordinated site, its image location,
and its weight.
"""
# Run the tessellation
nns = self.get_voronoi_polyhedra(structure, n)
# Extract the NN info
return self._extract_nn_info(structure, nns)
def get_all_nn_info(self, structure: Structure):
"""
Args:
structure (Structure): input structure.