/
vector3d.py
1572 lines (1388 loc) · 52.3 KB
/
vector3d.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
# -*- coding: utf-8 -*-
# Copyright 2018-2024 the orix developers
#
# This file is part of orix.
#
# orix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orix. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
from copy import deepcopy
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import dask.array as da
from dask.diagnostics import ProgressBar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
from orix._base import Object3d
class Vector3d(Object3d):
r"""Three-dimensional vectors.
Vectors :math:`\mathbf{v} = (x, y, z)` support the following
mathematical operations:
* Unary negation.
* Addition to other vectors, numbers, and compatible array-like
objects.
* Subtraction to and from the above.
* Multiplication to numbers and compatible array-like objects.
* Division by the same as multiplication. Division by a vector is
not defined in general.
Examples
--------
>>> from orix.vector import Vector3d
>>> v = Vector3d([1, 2, 3])
>>> w = Vector3d([[1, 0, 0], [0, 1, 1]])
>>> w.x
array([1, 0])
>>> v.unit
Vector3d (1,)
[[0.2673 0.5345 0.8018]]
>>> -v
Vector3d (1,)
[[-1 -2 -3]]
>>> v + w
Vector3d (2,)
[[2 2 3]
[1 3 4]]
>>> w - (2, -3)
Vector3d (2,)
[[-1 -2 -2]
[ 3 4 4]]
>>> 3 * v
Vector3d (1,)
[[3 6 9]]
>>> v / 2
Vector3d (1,)
[[0.5 1. 1.5]]
>>> v / (2, -2)
Vector3d (2,)
[[ 0.5 1. 1.5]
[-0.5 -1. -1.5]]
Vectors can be rotated by quaternion-like objects (which are
interpreted as basis transformations)
>>> from orix.quaternion import Rotation
>>> R = Rotation.from_axes_angles([0, 0, 1], -45, degrees=True)
>>> v2 = Vector3d([1, 1, 1.])
>>> v3 = R * v2
>>> v3
Vector3d (1,)
[[ 1.4142 -0. 1. ]]
>>> v3_np = np.dot(R.to_matrix().squeeze(), v2.data.squeeze())
>>> np.allclose(v3.data, v3_np)
True
"""
dim = 3
# -------------------------- Properties -------------------------- #
@property
def x(self) -> np.ndarray:
"""Return or set the x coordinates.
Parameters
----------
value : np.ndarray
The new x coordinates.
"""
return self.data[..., 0]
@x.setter
def x(self, value: np.ndarray):
"""Set the x coordinates."""
self.data[..., 0] = value
@property
def y(self) -> np.ndarray:
"""Return or set the y coordinates.
Parameters
----------
value : np.ndarray
The new y coordinates.
"""
return self.data[..., 1]
@y.setter
def y(self, value: np.ndarray):
"""Set the y coordinates."""
self.data[..., 1] = value
@property
def z(self) -> np.ndarray:
"""Return or set the z coordinate.
Parameters
----------
value : np.ndarray
The new z coordinate.
"""
return self.data[..., 2]
@z.setter
def z(self, value: np.ndarray):
"""Set the z coordinates."""
self.data[..., 2] = value
@property
def xyz(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return the coordinates as three arrays, useful for
plotting.
"""
return self.x, self.y, self.z
@property
def _tuples(self) -> Set:
"""Return the set of comparable vectors."""
s = self.flatten()
tuples = set([tuple(d) for d in s.data])
return tuples
@property
def perpendicular(self) -> Vector3d:
"""Return the perpendicular vectors."""
if np.any(self.x == 0) and np.any(self.y == 0):
if np.any(self.z == 0):
raise ValueError("No vectors are perpendicular")
return Vector3d.xvector()
x = -self.y
y = self.x
z = np.zeros_like(x)
return Vector3d(np.stack((x, y, z), axis=-1))
@property
def radial(self) -> np.ndarray:
"""Return the radial spherical coordinate, i.e. the distance
from a point on the sphere to the origin, according to the
ISO 31-11 standard :cite:`weisstein2005spherical`.
Returns
-------
radial
Radial spherical coordinate.
"""
return np.sqrt(
self.data[..., 0] ** 2 + self.data[..., 1] ** 2 + self.data[..., 2] ** 2
)
@property
def azimuth(self) -> np.ndarray:
r"""Azimuth spherical coordinate, i.e. the angle
:math:`\phi \in [0, 2\pi]` from the positive z-axis to a point
on the sphere, according to the ISO 31-11 standard
:cite:`weisstein2005spherical`.
Returns
-------
azimuth
"""
x, y = self.data[..., 0], self.data[..., 1]
# avoid rounding errors
x[np.isclose(x, 0)] = 0
y[np.isclose(y, 0)] = 0
azimuth = np.arctan2(y, x)
azimuth += (azimuth < 0) * 2 * np.pi
return azimuth
@property
def polar(self) -> np.ndarray:
r"""Polar spherical coordinate, i.e. the angle
:math:`\theta \in [0, \pi]` from the positive z-axis to a point
on the sphere, according to the ISO 31-11 standard
:cite:`weisstein2005spherical`.
Returns
-------
polar
"""
return np.arccos(self.data[..., 2] / self.radial.data)
# ------------------------ Dunder methods ------------------------ #
def __neg__(self) -> Vector3d:
return self.__class__(-self.data)
def __add__(
self, other: Union[int, float, List, Tuple, np.ndarray, Vector3d]
) -> Vector3d:
if isinstance(other, Vector3d):
return self.__class__(self.data + other.data)
elif isinstance(other, (int, float)):
return self.__class__(self.data + other)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(self.data + other[..., np.newaxis])
return NotImplemented
def __radd__(self, other: Union[int, float, List, Tuple, np.ndarray]) -> Vector3d:
if isinstance(other, (int, float)):
return self.__class__(other + self.data)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(other[..., np.newaxis] + self.data)
return NotImplemented
def __sub__(
self, other: Union[int, float, List, Tuple, np.ndarray, Vector3d]
) -> Vector3d:
if isinstance(other, Vector3d):
return self.__class__(self.data - other.data)
elif isinstance(other, (int, float)):
return self.__class__(self.data - other)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(self.data - other[..., np.newaxis])
return NotImplemented
def __rsub__(self, other: Union[int, float, List, Tuple, np.ndarray]) -> Vector3d:
if isinstance(other, (int, float)):
return self.__class__(other - self.data)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(other[..., np.newaxis] - self.data)
return NotImplemented
def __mul__(
self, other: Union[int, float, List, Tuple, np.ndarray, Vector3d]
) -> Vector3d:
if isinstance(other, Vector3d):
raise ValueError(
"Multiplying one vector with another is ambiguous. "
"Try `.dot` or `.cross` instead."
)
elif isinstance(other, (int, float)):
return self.__class__(self.data * other)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(self.data * other[..., np.newaxis])
return NotImplemented
def __rmul__(self, other: Union[int, float, List, Tuple, np.ndarray]) -> Vector3d:
if isinstance(other, (int, float)):
return self.__class__(other * self.data)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(other[..., np.newaxis] * self.data)
return NotImplemented
def __truediv__(
self, other: Union[int, float, List, Tuple, np.ndarray, Vector3d]
) -> Vector3d:
if isinstance(other, Vector3d):
raise ValueError("Dividing vectors is undefined")
elif isinstance(other, (int, float)):
return self.__class__(self.data / other)
elif isinstance(other, (list, tuple)):
other = np.array(other)
if isinstance(other, np.ndarray):
return self.__class__(self.data / other[..., np.newaxis])
return NotImplemented
def __rtruediv__(self, other: Any):
raise ValueError("Division by a vector is undefined")
# ------------------------ Class methods ------------------------- #
@classmethod
def from_polar(
cls,
azimuth: Union[np.ndarray, list, tuple, float],
polar: Union[np.ndarray, list, tuple, float],
radial: float = 1.0,
degrees: bool = False,
) -> Vector3d:
"""Initialize from spherical coordinates according to the ISO
31-11 standard :cite:`weisstein2005spherical`.
Parameters
----------
azimuth
Azimuth angle(s) in radians (``degrees=False``) or degrees
(``degrees=True``).
polar
Polar angle(s) in radians (``degrees=False``) or degrees
(``degrees=True``).
radial
Radial distance. Defaults to 1 to produce unit vectors.
degrees
If ``True``, the angles are assumed to be in degrees.
Default is ``False``.
Returns
-------
vec
"""
azimuth = np.atleast_1d(azimuth)
polar = np.atleast_1d(polar)
if degrees:
azimuth = np.deg2rad(azimuth)
polar = np.deg2rad(polar)
sin_polar = np.sin(polar)
x = np.cos(azimuth) * sin_polar
y = np.sin(azimuth) * sin_polar
z = np.cos(polar)
return radial * cls(np.stack((x, y, z), axis=-1))
@classmethod
def zero(cls, shape: Tuple[int] = (1,)) -> Vector3d:
"""Return zero vectors in the specified shape.
Parameters
----------
shape
Output vectors' shape.
Returns
-------
vec
Zero vectors.
"""
return cls(np.zeros(shape + (cls.dim,)))
@classmethod
def xvector(cls) -> Vector3d:
"""Return a unit vector in the x-direction."""
return cls((1, 0, 0))
@classmethod
def yvector(cls) -> Vector3d:
"""Return a unit vector in the y-direction."""
return cls((0, 1, 0))
@classmethod
def zvector(cls) -> Vector3d:
"""Return a unit vector in the z-direction."""
return cls((0, 0, 1))
@classmethod
def from_path_ends(
cls,
vectors: Union[list, tuple, Vector3d],
close: bool = False,
steps: int = 100,
) -> Vector3d:
r"""Return vectors along the shortest path on the sphere between
two or more consectutive vectors.
Parameters
----------
vectors
Two or more vectors to get paths between.
close
Whether to append the first to the end of ``vectors`` in
order to close the paths when more than two vectors are
passed. Default is False.
steps
Number of vectors in the great circle about the normal
vector between each two vectors *before* restricting the
circle to the path between the two. Default is 100. More
steps give a smoother path on the sphere.
Returns
-------
paths
Vectors along the shortest path(s) between given vectors.
Notes
-----
The vectors along the shortest path on the sphere between two
vectors :math:`v_1` and :math:`v_2` are found by first getting
the vectors :math:`v_i` along the great circle about the vector
normal to these two vectors, and then only keeping the part of
the circle between the two vectors. Vectors within this part
satisfy these two conditions
.. math::
(v_1 \times v_i) \cdot (v_1 \times v_2) \geq 0,
(v_2 \times v_i) \cdot (v_2 \times v_1) \geq 0.
"""
v = Vector3d(vectors).flatten()
if close:
v = Vector3d(np.concatenate((v.data, v[0].data)))
paths_list = []
n = v.size - 1
for i in range(n):
v1, v2 = v[i : i + 2]
v_normal = v1.cross(v2)
v_circle = v_normal.get_circle(steps=steps)
cond1 = v1.cross(v_circle).dot(v1.cross(v2)) >= 0
cond2 = v2.cross(v_circle).dot(v2.cross(v1)) >= 0
v_path = v_circle[cond1 & cond2]
to_concatenate = (v1.data, v_path.data)
if i == n - 1:
to_concatenate += (v2.data,)
paths_list.append(np.concatenate(to_concatenate, axis=0))
paths_data = np.concatenate(paths_list, axis=0)
paths = Vector3d(paths_data)
return paths
# --------------------- Other public methods --------------------- #
def dot(self, other: Vector3d) -> np.ndarray:
"""Return the dot products of the vectors and the other vectors.
Parameters
----------
other
Other vectors with a compatible shape.
Returns
-------
dot_products
Dot products.
Examples
--------
>>> from orix.vector import Vector3d
>>> v = Vector3d((0, 0, 1.0))
>>> w = Vector3d(((0, 0, 0.5), (0.4, 0.6, 0)))
>>> v.dot(w)
array([0.5, 0. ])
>>> w.dot(v)
array([0.5, 0. ])
"""
if not isinstance(other, Vector3d):
raise ValueError("{} is not a vector!".format(other))
return np.sum(self.data * other.data, axis=-1)
def dot_outer(
self,
other: Vector3d,
lazy: bool = False,
chunk_size: int = 20,
progressbar: bool = False,
) -> np.ndarray:
"""Return the outer dot products of all vectors and all the
other vectors.
Parameters
----------
other
Compute the outer dot product with these vectors.
lazy
Whether to perform the computation lazily with Dask. Default
is ``False``.
chunk_size
Number of orientations per axis to include in each iteration
of the computation. Default is 20. Only applies when
``lazy`` is ``True``.
progressbar
Whether to show a progressbar during computation if ``lazy``
is ``True``. Default is ``True``.
Returns
-------
dot_products
Dot products.
Examples
--------
>>> from orix.vector import Vector3d
>>> v = Vector3d(((0.0, 0.0, 1.0), (1.0, 0.0, 0.0))) # shape = (2, )
>>> w = Vector3d(((0.0, 0.0, 0.5), (0.4, 0.6, 0.0), (0.5, 0.5, 0.5))) # shape = (3, )
>>> v.dot_outer(w)
array([[0.5, 0. , 0.5],
[0. , 0.4, 0.5]])
>>> w.dot_outer(v) # shape = (3, 2)
array([[0.5, 0. ],
[0. , 0.4],
[0.5, 0.5]])
"""
if lazy:
dots = np.empty(self.shape + other.shape)
dp = self._dot_outer_dask(other, chunk_size)
if progressbar:
with ProgressBar():
da.store(sources=dp, targets=dots)
else:
da.store(sources=dp, targets=dots)
else:
dots = np.tensordot(self.data, other.data, axes=(-1, -1))
return dots
def cross(self, other: Vector3d) -> Vector3d:
"""Return the cross product of a vector with another vector.
Vectors must have compatible shape for broadcasting to work.
Returns
-------
vec
The class of ``other`` is preserved.
Examples
--------
>>> from orix.vector import Vector3d
>>> v = Vector3d(((1, 0, 0), (-1, 0, 0)))
>>> w = Vector3d((0, 1, 0))
>>> v.cross(w)
Vector3d (2,)
[[ 0 0 1]
[ 0 0 -1]]
"""
return other.__class__(np.cross(self.data, other.data))
def angle_with(self, other: Vector3d, degrees: bool = False) -> np.ndarray:
"""Return the angles between these vectors in other vectors.
Vectors must have compatible shapes for broadcasting to work.
Parameters
----------
other
Another vector.
degrees
If ``True``, the given angles are returned in degrees.
Default is ``False``.
Returns
-------
angles
Angles in radians (``degrees=False``) or degrees
(``degrees=True``).
"""
cosines = np.round(self.dot(other) / self.norm / other.norm, 10)
angles = np.arccos(cosines)
if degrees:
angles = np.rad2deg(angles)
return angles
def rotate(
self,
axis: Union[np.ndarray, Vector3d] = None,
angle: Union[List[float], float, np.np.ndarray] = 0,
) -> Vector3d:
"""Convenience function for rotating this vector.
Shapes of ``axis`` and ``angle`` must be compatible with shape
of ``self`` for broadcasting.
Parameters
----------
axis
The axis of rotation. Defaults to the z-vector.
angle
The angle of rotation, in radians.
Returns
-------
v
A new vector with entries rotated.
Examples
--------
>>> from orix.vector import Vector3d
>>> v = Vector3d.yvector()
>>> axis = Vector3d((0, 0, 1))
>>> angles = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4, np.pi]
>>> v.rotate(axis=axis, angle=angles)
Vector3d (5,)
[[ 0. 1. 0. ]
[-0.7071 0.7071 0. ]
[-1. 0. 0. ]
[-0.7071 -0.7071 0. ]
[-0. -1. 0. ]]
"""
# Import here to avoid circular import
from orix.quaternion import Rotation
axis = Vector3d.zvector() if axis is None else axis
angle = 0 if angle is None else angle
R = Rotation.from_axes_angles(axis, angle)
return R * self
def get_nearest(
self, x: Vector3d, inclusive: bool = False, tiebreak: bool = None
) -> Vector3d:
"""Return the vector in ``x`` with the smallest angle to this
vector.
Parameters
----------
x
Set of vectors in which to find the one with the smallest
angle to this vector.
inclusive
If ``False`` (default) vectors exactly parallel to this will
not be considered.
tiebreak
If multiple vectors are equally close to this one,
``tiebreak`` will be used as a secondary comparison. By
default equal to (0, 0, 1).
Returns
-------
v
Vector with the smallest angle to this vector.
Raises
------
ValueError
If this is not a single vector.
Examples
--------
>>> from orix.vector import Vector3d
>>> v1 = Vector3d([1, 0, 0])
>>> v1.get_nearest(Vector3d([[0.5, 0, 0], [0.6, 0, 0]]))
Vector3d (1,)
[[0.6 0. 0. ]]
"""
assert self.size == 1, "`get_nearest` only works for single vectors."
tiebreak = Vector3d.zvector() if tiebreak is None else tiebreak
eps = 1e-9 if inclusive else 0
cosines = x.dot(self)
mask = np.logical_and(-1 - eps < cosines, cosines < 1 + eps)
v = x[mask]
if v.size == 0:
return Vector3d.empty()
cosines = cosines[mask]
verticality = v.dot(tiebreak)
order = np.lexsort((cosines, verticality))
return v[order[-1]]
def mean(self) -> Vector3d:
"""Return the mean vector.
Returns
-------
v
The mean vector.
"""
axis = tuple(range(self.ndim))
return self.__class__(self.data.mean(axis=axis))
def to_polar(
self, degrees: bool = False
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
r"""Return the azimuth :math:`\phi`, polar :math:`\theta`, and
radial :math:`r` spherical coordinates defined as in the ISO
31-11 standard :cite:`weisstein2005spherical`.
Parameters
----------
degrees
If ``True``, the given angles are returned in degrees.
Default is ``False``.
Returns
-------
azimuth
Azimuth angles in radians (``degrees=False``) or degrees
(``degrees=True``).
polar
Polar angles in radians (``degrees=False``) or degrees
(``degrees=True``).
radial
Radial values.
"""
azimuth = self.azimuth
polar = self.polar
if degrees:
azimuth = np.rad2deg(azimuth)
polar = np.rad2deg(polar)
return azimuth, polar, self.radial
def in_fundamental_sector(self, symmetry: "Symmetry") -> Vector3d:
"""Project vectors to a symmetry's fundamental sector (inverse
pole figure).
This projection is taken from MTEX'
:code:`project2FundamentalRegion`.
Parameters
----------
symmetry
Symmetry with a fundamental sector.
Returns
-------
v
Vectors within the fundamental sector.
Examples
--------
>>> from orix.quaternion.symmetry import D6h, Oh
>>> from orix.vector import Vector3d
>>> v = Vector3d((-1, 1, 0))
>>> v.in_fundamental_sector(Oh)
Vector3d (1,)
[[1. 0. 1.]]
>>> v.in_fundamental_sector(D6h)
Vector3d (1,)
[[1.366 0.366 0. ]]
"""
fs = symmetry.fundamental_sector
v = deepcopy(self)
center = fs.center
if center.size == 0:
return v
if symmetry.name in ["321", "312", "32", "-4"]:
idx = v.z < 0
vv = symmetry[-1] * v[idx]
if vv.size != 0:
v[idx] = vv
S = symmetry[:3]
elif symmetry.name == "-3":
idx = v.z < 0
vv = symmetry[3] * v[idx]
if vv.size != 0:
v[idx] = vv
S = symmetry[:3]
else:
S = symmetry
rotated_centers = S * center
closeness = v.dot_outer(rotated_centers).round(12)
idx_max = np.argmax(closeness, axis=-1)
v2 = ~S[idx_max] * v
# Keep the ones already inside the sector
mask = v <= fs
v2[mask] = v[mask]
return v2
def get_circle(
self, opening_angle: Union[float, np.ndarray] = np.pi / 2, steps: int = 100
) -> Vector3d:
r"""Get vectors delineating great or small circle(s) with a
given ``opening_angle`` about each vector.
Used for plotting plane traces in stereographic projections.
Parameters
----------
opening_angle
Opening angle(s) around the vector(s). Default is
:math:`\pi/2`, giving a great circle. If an array is passed,
its size must be equal to the number of vectors.
steps
Number of vectors to describe each circle, default is 100.
Returns
-------
circles
Vectors delineating circles with the ``opening_angle`` about
the vectors.
Notes
-----
A set of ``steps`` number of vectors equal to each vector is
rotated twice to obtain a circle: (1) About a perpendicular
vector to the current vector at ``opening_angle`` and (2) about
the current vector in a full circle.
"""
circles = self.zero((self.size, steps))
full_circle = np.linspace(0, 2 * np.pi, num=steps)
opening_angles = np.ones(self.size) * opening_angle
for i, (v, oa) in enumerate(zip(self.flatten(), opening_angles)):
circles[i] = v.rotate(v.perpendicular, oa).rotate(v, full_circle)
return circles
def inverse_pole_density_function(
self,
resolution: float = 0.25,
sigma: float = 5,
log: bool = False,
colorbar: bool = True,
symmetry: Optional["Symmetry"] = None,
weights: Optional[np.ndarray] = None,
figure: Optional[Figure] = None,
hemisphere: Optional[str] = None,
show_hemisphere_label: Optional[bool] = None,
grid: Optional[bool] = None,
grid_resolution: Optional[Tuple[float, float]] = None,
figure_kwargs: Optional[Dict] = None,
text_kwargs: Optional[Dict] = None,
return_figure: bool = False,
**kwargs: Any,
) -> Optional[Figure]:
"""Plot the Inverse Pole Density Function (IPDF) within the
fundamental sector of a given point group symmetry in the
stereographic projection.
The IPDF is calculated in terms of Multiples of Random
Distribution (MRD), ie. multiples of the expected density if the
pole distribution was completely random, see
:cite:`rohrer2004distribution`.
Parameters
----------
resolution
The angular resolution of the sampling grid in degrees.
Default value is 0.25.
sigma
The angular resolution of the applied broadening in degrees.
Default value is 5.
log
If ``True`` the log(PDF) is calculated. Default is ``True``.
colorbar
If ``True`` a colorbar is shown alongside the IPDF plot.
Default is ``True``.
symmetry
The point group symmetry. Default is ``None``, in which case
``C1`` is used.
weights
The weights for the individual vectors. Default is ``None``,
in which case each vector is 1.
figure
Which figure to plot onto. Default is ``None``, which
creates a new figure.
hemisphere
Which hemisphere(s) to plot the vectors in, defaults to
``None``, which means ``"upper"`` if a new figure is
created, otherwise adds to the current figure's hemispheres.
Options are ``"upper"`` and ``"lower"``.
show_hemisphere_label
Whether to show hemisphere labels ``"upper"`` or
``"lower"``. Default is ``True`` if ``hemisphere`` is
``"both"``, otherwise ``False``.
grid
Whether to show the azimuth and polar grid. Default is
whatever ``axes.grid`` is set to in
:obj:`matplotlib.rcParams`.
grid_resolution
Azimuth and polar grid resolution in degrees, as a tuple.
Default is whatever is default in
:class:`~orix.plot.StereographicPlot.stereographic_grid`.
figure_kwargs
Dictionary of keyword arguments passed to
:func:`matplotlib.pyplot.subplots`.
text_kwargs
Dictionary of keyword arguments passed to
:meth:`~orix.plot.StereographicPlot.text`, which passes
these on to :meth:`matplotlib.axes.Axes.text`.
return_figure
Whether to return the figure (default is ``False``).
**kwargs
Keyword arguments passed to
:meth:`matplotlib.axes.Axes.pcolormesh`.
Returns
-------
fig
The created figure, returned if ``return_figure=True``.
See Also
--------
orix.measure.pole_density_function
orix.plot.InversePoleFigurePlot.pole_density_function
orix.plot.StereographicPlot.pole_density_function
"""
if hemisphere is None:
hemisphere = "upper"
if hemisphere not in ("upper", "lower", "both"):
raise ValueError('Hemisphere must be either "upper", "lower", or "both".')
# computation done in spherical coordinates
azimuth, polar, _ = self.unit.to_polar()
(
fig,
axes,
hemisphere,
show_hemisphere_label,
grid,
grid_resolution,
text_kwargs,
axes_labels,
) = self._setup_plot(
projection="ipf",
figure=figure,
hemisphere=hemisphere,
show_hemisphere_label=show_hemisphere_label,
symmetry=symmetry,
grid=grid,
grid_resolution=grid_resolution,
figure_kwargs=figure_kwargs,
text_kwargs=text_kwargs,
)
for i, ax in enumerate(axes):
# setup plot
ax.hemisphere = hemisphere[i]
ax.stereographic_grid(grid[i], grid_resolution[0], grid_resolution[1])
ax._stereographic_grid = grid[i]
if show_hemisphere_label:
ax.show_hemisphere_label()
ax.pole_density_function(
azimuth,
polar,
resolution=resolution,
sigma=sigma,
log=log,
colorbar=colorbar,
weights=weights,
**kwargs,
)
if return_figure:
return fig
def pole_density_function(
self,
resolution: float = 1,
sigma: float = 5,
log: bool = False,
colorbar: bool = True,
weights: Optional[np.ndarray] = None,
figure: Optional[Figure] = None,
axes_labels: Optional[List[str]] = None,
hemisphere: Optional[str] = None,
show_hemisphere_label: Optional[bool] = None,
grid: Optional[bool] = None,
grid_resolution: Optional[Tuple[float, float]] = None,
figure_kwargs: Optional[Dict] = None,
text_kwargs: Optional[Dict] = None,
return_figure: bool = False,
**kwargs: Any,
) -> Optional[Figure]:
"""Plot the Pole Density Function (PDF) on a given hemisphere
in the stereographic projection.
The PDF is calculated in terms of Multiples of Random
Distribution (MRD), ie. multiples of the expected density if the
pole distribution was completely random, see
:cite:`rohrer2004distribution`.
Parameters