-
Notifications
You must be signed in to change notification settings - Fork 867
/
lattice.py
2035 lines (1780 loc) · 75.3 KB
/
lattice.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
"""Defines the classes relating to 3D lattices."""
from __future__ import annotations
import collections
import itertools
import math
import warnings
from fractions import Fraction
from functools import reduce
from typing import TYPE_CHECKING, Iterator, Sequence
import numpy as np
from monty.dev import deprecated
from monty.json import MSONable
from numpy import dot, pi, transpose
from numpy.linalg import inv
from pymatgen.util.coord import pbc_shortest_vectors
from pymatgen.util.due import Doi, due
from pymatgen.util.num import abs_cap
if TYPE_CHECKING:
from numpy.typing import ArrayLike
__author__ = "Shyue Ping Ong, Michael Kocher"
__copyright__ = "Copyright 2011, The Materials Project"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
class Lattice(MSONable):
"""
A lattice object. Essentially a matrix with conversion matrices. In
general, it is assumed that length units are in Angstroms and angles are in
degrees unless otherwise stated.
"""
# Properties lazily generated for efficiency.
def __init__(self, matrix: ArrayLike, pbc: tuple[bool, bool, bool] = (True, True, True)):
"""
Create a lattice from any sequence of 9 numbers. Note that the sequence
is assumed to be read one row at a time. Each row represents one
lattice vector.
Args:
matrix: Sequence of numbers in any form. Examples of acceptable
input.
i) An actual numpy array.
ii) [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
iii) [1, 0, 0 , 0, 1, 0, 0, 0, 1]
iv) (1, 0, 0, 0, 1, 0, 0, 0, 1)
Each row should correspond to a lattice vector.
E.g., [[10, 0, 0], [20, 10, 0], [0, 0, 30]] specifies a lattice
with lattice vectors [10, 0, 0], [20, 10, 0] and [0, 0, 30].
pbc: a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
"""
m = np.array(matrix, dtype=np.float64).reshape((3, 3))
m.setflags(write=False)
self._matrix: np.ndarray = m
self._inv_matrix: np.ndarray | None = None
self._diags = None
self._lll_matrix_mappings: dict[float, tuple[np.ndarray, np.ndarray]] = {}
self._lll_inverse = None
self._pbc = tuple(pbc)
@property
def lengths(self) -> tuple[float, float, float]:
"""
Lattice lengths.
:return: The lengths (a, b, c) of the lattice.
"""
return tuple(np.sqrt(np.sum(self._matrix**2, axis=1)).tolist()) # type: ignore
@property
def angles(self) -> tuple[float, float, float]:
"""
Lattice angles.
:return: The angles (alpha, beta, gamma) of the lattice.
"""
m = self._matrix
lengths = self.lengths
angles = np.zeros(3)
for i in range(3):
j = (i + 1) % 3
k = (i + 2) % 3
angles[i] = abs_cap(np.dot(m[j], m[k]) / (lengths[j] * lengths[k]))
angles = np.arccos(angles) * 180.0 / pi
return tuple(angles.tolist()) # type: ignore
@property
def is_orthogonal(self) -> bool:
""":return: Whether all angles are 90 degrees."""
return all(abs(a - 90) < 1e-5 for a in self.angles)
def __format__(self, fmt_spec: str = ""):
"""
Support format printing.
Supported fmt_spec (str) are:
1. "l" for a list format that can be easily copied and pasted, e.g.,
".3fl" prints something like
"[[10.000, 0.000, 0.000], [0.000, 10.000, 0.000], [0.000, 0.000, 10.000]]"
2. "p" for lattice parameters ".1fp" prints something like
"{10.0, 10.0, 10.0, 90.0, 90.0, 90.0}"
3. Default will simply print a 3x3 matrix form. E.g.,
10.000 0.000 0.000
0.000 10.000 0.000
0.000 0.000 10.000
"""
m = self._matrix.tolist()
if fmt_spec.endswith("l"):
fmt = "[[{}, {}, {}], [{}, {}, {}], [{}, {}, {}]]"
fmt_spec = fmt_spec[:-1]
elif fmt_spec.endswith("p"):
fmt = "{{{}, {}, {}, {}, {}, {}}}"
fmt_spec = fmt_spec[:-1]
m = (self.lengths, self.angles)
else:
fmt = "{} {} {}\n{} {} {}\n{} {} {}"
return fmt.format(*(format(c, fmt_spec) for row in m for c in row))
def copy(self):
"""Deep copy of self."""
return self.__class__(self.matrix.copy(), pbc=self.pbc)
@property
def matrix(self) -> np.ndarray:
"""Copy of matrix representing the Lattice."""
return self._matrix
@property
def pbc(self) -> tuple[bool, bool, bool]:
"""Tuple defining the periodicity of the Lattice."""
return self._pbc # type: ignore
@property
def is_3d_periodic(self) -> bool:
"""True if the Lattice is periodic in all directions."""
return all(self._pbc)
@property
def inv_matrix(self) -> np.ndarray:
"""Inverse of lattice matrix."""
if self._inv_matrix is None:
self._inv_matrix = inv(self._matrix)
self._inv_matrix.setflags(write=False)
return self._inv_matrix
@property
def metric_tensor(self) -> np.ndarray:
"""The metric tensor of the lattice."""
return np.dot(self._matrix, self._matrix.T)
def get_cartesian_coords(self, fractional_coords: ArrayLike) -> np.ndarray:
"""
Returns the Cartesian coordinates given fractional coordinates.
Args:
fractional_coords (3x1 array): Fractional coords.
Returns:
Cartesian coordinates
"""
return np.dot(fractional_coords, self._matrix)
def get_fractional_coords(self, cart_coords: ArrayLike) -> np.ndarray:
"""
Returns the fractional coordinates given Cartesian coordinates.
Args:
cart_coords (3x1 array): Cartesian coords.
Returns:
Fractional coordinates.
"""
return np.dot(cart_coords, self.inv_matrix)
def get_vector_along_lattice_directions(self, cart_coords: ArrayLike) -> np.ndarray:
"""
Returns the coordinates along lattice directions given Cartesian coordinates.
Note, this is different than a projection of the Cartesian vector along the
lattice parameters. It is simply the fractional coordinates multiplied by the
lattice vector magnitudes.
For example, this method is helpful when analyzing the dipole moment (in
units of electron Angstroms) of a ferroelectric crystal. See the `Polarization`
class in `pymatgen.analysis.ferroelectricity.polarization`.
Args:
cart_coords (3x1 array): Cartesian coords.
Returns:
Lattice coordinates.
"""
return self.lengths * self.get_fractional_coords(cart_coords) # type: ignore
def d_hkl(self, miller_index: ArrayLike) -> float:
"""
Returns the distance between the hkl plane and the origin.
Args:
miller_index ([h,k,l]): Miller index of plane
Returns:
d_hkl (float)
"""
gstar = self.reciprocal_lattice_crystallographic.metric_tensor
hkl = np.array(miller_index)
return 1 / ((np.dot(np.dot(hkl, gstar), hkl.T)) ** (1 / 2))
@staticmethod
def cubic(a: float, pbc: tuple[bool, bool, bool] = (True, True, True)) -> Lattice:
"""
Convenience constructor for a cubic lattice.
Args:
a (float): The *a* lattice parameter of the cubic cell.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Cubic lattice of dimensions a x a x a.
"""
return Lattice([[a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a]], pbc)
@staticmethod
def tetragonal(a: float, c: float, pbc: tuple[bool, bool, bool] = (True, True, True)) -> Lattice:
"""
Convenience constructor for a tetragonal lattice.
Args:
a (float): *a* lattice parameter of the tetragonal cell.
c (float): *c* lattice parameter of the tetragonal cell.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Tetragonal lattice of dimensions a x a x c.
"""
return Lattice.from_parameters(a, a, c, 90, 90, 90, pbc=pbc)
@staticmethod
def orthorhombic(a: float, b: float, c: float, pbc: tuple[bool, bool, bool] = (True, True, True)) -> Lattice:
"""
Convenience constructor for an orthorhombic lattice.
Args:
a (float): *a* lattice parameter of the orthorhombic cell.
b (float): *b* lattice parameter of the orthorhombic cell.
c (float): *c* lattice parameter of the orthorhombic cell.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Orthorhombic lattice of dimensions a x b x c.
"""
return Lattice.from_parameters(a, b, c, 90, 90, 90, pbc=pbc)
@staticmethod
def monoclinic(
a: float, b: float, c: float, beta: float, pbc: tuple[bool, bool, bool] = (True, True, True)
) -> Lattice:
"""
Convenience constructor for a monoclinic lattice.
Args:
a (float): *a* lattice parameter of the monoclinc cell.
b (float): *b* lattice parameter of the monoclinc cell.
c (float): *c* lattice parameter of the monoclinc cell.
beta (float): *beta* angle between lattice vectors b and c in
degrees.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Monoclinic lattice of dimensions a x b x c with non right-angle
beta between lattice vectors a and c.
"""
return Lattice.from_parameters(a, b, c, 90, beta, 90, pbc=pbc)
@staticmethod
def hexagonal(a: float, c: float, pbc: tuple[bool, bool, bool] = (True, True, True)) -> Lattice:
"""
Convenience constructor for a hexagonal lattice.
Args:
a (float): *a* lattice parameter of the hexagonal cell.
c (float): *c* lattice parameter of the hexagonal cell.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Hexagonal lattice of dimensions a x a x c.
"""
return Lattice.from_parameters(a, a, c, 90, 90, 120, pbc=pbc)
@staticmethod
def rhombohedral(a: float, alpha: float, pbc: tuple[bool, bool, bool] = (True, True, True)) -> Lattice:
"""
Convenience constructor for a rhombohedral lattice.
Args:
a (float): *a* lattice parameter of the rhombohedral cell.
alpha (float): Angle for the rhombohedral lattice in degrees.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Rhombohedral lattice of dimensions a x a x a.
"""
return Lattice.from_parameters(a, a, a, alpha, alpha, alpha, pbc=pbc)
@classmethod
def from_parameters(
cls,
a: float,
b: float,
c: float,
alpha: float,
beta: float,
gamma: float,
vesta: bool = False,
pbc: tuple[bool, bool, bool] = (True, True, True),
):
"""
Create a Lattice using unit cell lengths (in Angstrom) and angles (in degrees).
Args:
a (float): *a* lattice parameter.
b (float): *b* lattice parameter.
c (float): *c* lattice parameter.
alpha (float): *alpha* angle in degrees.
beta (float): *beta* angle in degrees.
gamma (float): *gamma* angle in degrees.
vesta: True if you import Cartesian coordinates from VESTA.
pbc (tuple): a tuple defining the periodic boundary conditions along the three
axis of the lattice. If None periodic in all directions.
Returns:
Lattice with the specified lattice parameters.
"""
angles_r = np.radians([alpha, beta, gamma])
cos_alpha, cos_beta, cos_gamma = np.cos(angles_r)
sin_alpha, sin_beta, sin_gamma = np.sin(angles_r)
if vesta:
c1 = c * cos_beta
c2 = (c * (cos_alpha - (cos_beta * cos_gamma))) / sin_gamma
vector_a = [float(a), 0.0, 0.0]
vector_b = [b * cos_gamma, b * sin_gamma, 0]
vector_c = [c1, c2, math.sqrt(c**2 - c1**2 - c2**2)]
else:
val = (cos_alpha * cos_beta - cos_gamma) / (sin_alpha * sin_beta)
# Sometimes rounding errors result in values slightly > 1.
val = abs_cap(val)
gamma_star = np.arccos(val)
vector_a = [a * sin_beta, 0.0, a * cos_beta]
vector_b = [
-b * sin_alpha * np.cos(gamma_star),
b * sin_alpha * np.sin(gamma_star),
b * cos_alpha,
]
vector_c = [0.0, 0.0, float(c)]
return Lattice([vector_a, vector_b, vector_c], pbc)
@classmethod
def from_dict(cls, d: dict, fmt: str | None = None, **kwargs):
"""
Create a Lattice from a dictionary containing the a, b, c, alpha, beta,
and gamma parameters if fmt is None.
If fmt == "abivars", the function build a `Lattice` object from a
dictionary with the Abinit variables `acell` and `rprim` in Bohr.
If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr
Example:
Lattice.from_dict(fmt="abivars", acell=3*[10], rprim=np.eye(3))
"""
if fmt == "abivars":
# pylint: disable=C0415
from pymatgen.io.abinit.abiobjects import lattice_from_abivars
kwargs.update(d)
return lattice_from_abivars(cls=cls, **kwargs)
pbc = d.get("pbc", (True, True, True))
if "matrix" in d:
return cls(d["matrix"], pbc=pbc)
return cls.from_parameters(d["a"], d["b"], d["c"], d["alpha"], d["beta"], d["gamma"], pbc=pbc)
@property
def a(self) -> float:
"""*a* lattice parameter."""
return self.lengths[0]
@property
def b(self) -> float:
"""*b* lattice parameter."""
return self.lengths[1]
@property
def c(self) -> float:
"""*c* lattice parameter."""
return self.lengths[2]
@property
def abc(self) -> tuple[float, float, float]:
"""Lengths of the lattice vectors, i.e. (a, b, c)."""
return self.lengths
@property
def alpha(self) -> float:
"""Angle alpha of lattice in degrees."""
return self.angles[0]
@property
def beta(self) -> float:
"""Angle beta of lattice in degrees."""
return self.angles[1]
@property
def gamma(self) -> float:
"""Angle gamma of lattice in degrees."""
return self.angles[2]
@property
def volume(self) -> float:
"""Volume of the unit cell in Angstrom^3."""
matrix = self._matrix
return float(abs(np.dot(np.cross(matrix[0], matrix[1]), matrix[2])))
@property
def parameters(self) -> tuple[float, float, float, float, float, float]:
"""Returns: (a, b, c, alpha, beta, gamma)."""
return (*self.lengths, *self.angles)
@property
def reciprocal_lattice(self) -> Lattice:
"""
Return the reciprocal lattice. Note that this is the standard
reciprocal lattice used for solid state physics with a factor of 2 *
pi. If you are looking for the crystallographic reciprocal lattice,
use the reciprocal_lattice_crystallographic property.
The property is lazily generated for efficiency.
"""
v = np.linalg.inv(self._matrix).T
return Lattice(v * 2 * np.pi)
@property
def reciprocal_lattice_crystallographic(self) -> Lattice:
"""
Returns the *crystallographic* reciprocal lattice, i.e., no factor of
2 * pi.
"""
return Lattice(self.reciprocal_lattice.matrix / (2 * np.pi))
@property
def lll_matrix(self) -> np.ndarray:
""":return: The matrix for LLL reduction"""
if 0.75 not in self._lll_matrix_mappings:
self._lll_matrix_mappings[0.75] = self._calculate_lll()
return self._lll_matrix_mappings[0.75][0]
@property
def lll_mapping(self) -> np.ndarray:
"""
:return: The mapping between the LLL reduced lattice and the original
lattice.
"""
if 0.75 not in self._lll_matrix_mappings:
self._lll_matrix_mappings[0.75] = self._calculate_lll()
return self._lll_matrix_mappings[0.75][1]
@property
def lll_inverse(self) -> np.ndarray:
""":return: Inverse of self.lll_mapping."""
return np.linalg.inv(self.lll_mapping)
@property
def selling_vector(self) -> np.ndarray:
"""Returns the (1,6) array of Selling Scalars."""
a, b, c = self.matrix
d = -(a + b + c)
tol = 1e-10
selling_vector = np.array(
[
np.dot(b, c),
np.dot(a, c),
np.dot(a, b),
np.dot(a, d),
np.dot(b, d),
np.dot(c, d),
]
)
selling_vector = np.array([s if abs(s) > tol else 0 for s in selling_vector])
reduction_matrices = np.array(
[
np.array(
[
[-1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0],
[-1, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 1],
]
),
np.array(
[
[1, 1, 0, 0, 0, 0],
[0, -1, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, -1, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1],
]
),
np.array(
[
[1, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, -1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, -1, 0, 0, 1],
]
),
np.array(
[
[1, 0, 0, -1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 0, 0, -1, 0, 0],
[0, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 0, 1],
]
),
np.array(
[
[0, 0, 1, 0, 1, 0],
[0, 1, 0, 0, -1, 0],
[1, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, -1, 0],
[0, 0, 0, 0, 1, 1],
]
),
np.array(
[
[0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, -1],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, -1],
]
),
]
)
while np.greater(np.max(selling_vector), 0):
max_index = selling_vector.argmax()
selling_vector = np.dot(reduction_matrices[max_index], selling_vector)
return selling_vector
def selling_dist(self, other):
"""Returns the minimum Selling distance between two lattices."""
vcp_matrices = [
np.array(
[
[-1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, -1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, -1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, -1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, -1, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, -1],
]
),
]
reflection_matrices = [
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
]
),
np.array(
[
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
]
),
np.array(
[
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
]
),
np.array(
[
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
]
),
np.array(
[
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
]
),
np.array(
[
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
]
),
np.array(
[
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
]
),
np.array(
[
[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
]
),
np.array(
[
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
]
),
np.array(
[
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
]
),
np.array(
[
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
]
),
np.array(
[
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
]
),
]
selling1 = self.selling_vector
selling2 = other.selling_vector
vcps = np.dot(selling1, vcp_matrices)[0]
all_reflections = []
for vcp in vcps:
for reflection_matrix in reflection_matrices:
all_reflections.append(np.dot(vcp, reflection_matrix))
for reflection_matrix in reflection_matrices:
all_reflections.append(np.dot(selling1, reflection_matrix))
return min(np.linalg.norm(reflection - selling2) for reflection in all_reflections)
def __repr__(self):
outs = [
"Lattice",
" abc : " + " ".join(map(repr, self.lengths)),
" angles : " + " ".join(map(repr, self.angles)),
" volume : " + repr(self.volume),
" A : " + " ".join(map(repr, self._matrix[0])),
" B : " + " ".join(map(repr, self._matrix[1])),
" C : " + " ".join(map(repr, self._matrix[2])),
" pbc : " + " ".join(map(repr, self._pbc)),
]
return "\n".join(outs)
def __eq__(self, other: object) -> bool:
"""
A lattice is considered to be equal to another if the internal matrix
representation satisfies np.allclose(matrix1, matrix2) to be True and
share the same periodicity.
"""
if not hasattr(other, "matrix") or not hasattr(other, "pbc"):
return NotImplemented
# shortcut the np.allclose if the memory addresses are the same
# (very common in Structure.from_sites)
if self is other:
return True
return np.allclose(self.matrix, other.matrix) and self.pbc == other.pbc # type: ignore
def __hash__(self):
return 7
def __str__(self):
return "\n".join(" ".join([f"{i:.6f}" for i in row]) for row in self._matrix)
def as_dict(self, verbosity: int = 0) -> dict:
"""
Json-serialization dict representation of the Lattice.
Args:
verbosity (int): Verbosity level. Default of 0 only includes the
matrix representation. Set to 1 for more details.
"""
dct = {
"@module": type(self).__module__,
"@class": type(self).__name__,
"matrix": self._matrix.tolist(),
"pbc": self._pbc,
}
if verbosity > 0:
keys = ["a", "b", "c", "alpha", "beta", "gamma", "volume"]
dct.update(dict(zip(keys, [*self.parameters, self.volume])))
return dct
def find_all_mappings(
self,
other_lattice: Lattice,
ltol: float = 1e-5,
atol: float = 1,
skip_rotation_matrix: bool = False,
) -> Iterator[tuple[Lattice, np.ndarray | None, np.ndarray]]:
"""
Finds all mappings between current lattice and another lattice.
Args:
other_lattice (Lattice): Another lattice that is equivalent to
this one.
ltol (float): Tolerance for matching lengths. Defaults to 1e-5.
atol (float): Tolerance for matching angles. Defaults to 1.
skip_rotation_matrix (bool): Whether to skip calculation of the
rotation matrix
Yields:
(aligned_lattice, rotation_matrix, scale_matrix) if a mapping is
found. aligned_lattice is a rotated version of other_lattice that
has the same lattice parameters, but which is aligned in the
coordinate system of this lattice so that translational points
match up in 3D. rotation_matrix is the rotation that has to be
applied to other_lattice to obtain aligned_lattice, i.e.,
aligned_matrix = np.inner(other_lattice, rotation_matrix) and
op = SymmOp.from_rotation_and_translation(rotation_matrix)
aligned_matrix = op.operate_multi(latt.matrix)
Finally, scale_matrix is the integer matrix that expresses
aligned_matrix as a linear combination of this
lattice, i.e., aligned_matrix = np.dot(scale_matrix, self.matrix)
None is returned if no matches are found.
"""
lengths = other_lattice.lengths
(alpha, beta, gamma) = other_lattice.angles
frac, dist, _, _ = self.get_points_in_sphere(
[[0, 0, 0]], [0, 0, 0], max(lengths) * (1 + ltol), zip_results=False
)
cart = self.get_cartesian_coords(frac) # type: ignore
# this can't be broadcast because they're different lengths
inds = [np.logical_and(dist / len < 1 + ltol, dist / len > 1 / (1 + ltol)) for len in lengths] # type: ignore
c_a, c_b, c_c = (cart[i] for i in inds)
f_a, f_b, f_c = (frac[i] for i in inds) # type: ignore
l_a, l_b, l_c = (np.sum(c**2, axis=-1) ** 0.5 for c in (c_a, c_b, c_c))