/
reciprocal_lattice_vector.py
1791 lines (1431 loc) · 53 KB
/
reciprocal_lattice_vector.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 2017-2023 The diffsims developers
#
# This file is part of diffsims.
#
# diffsims 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.
#
# diffsims 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 diffsims. If not, see <http://www.gnu.org/licenses/>.
from typing import Tuple
from collections import defaultdict
from copy import deepcopy
from diffpy.structure.symmetryutilities import expandPosition
from diffpy.structure import Structure
import numba as nb
import numpy as np
from orix.vector import Miller, Vector3d
from orix.vector.miller import (
_check_hkil,
_get_highest_hkl,
_get_indices_from_highest,
_hkil2hkl,
_hkl2hkil,
_transform_space,
)
from diffsims.structure_factor.atomic_scattering_parameters import (
_get_string_from_element_id,
)
from diffsims.structure_factor.structure_factor import (
get_refraction_corrected_wavelength,
)
from diffsims.utils.sim_utils import _get_kinematical_structure_factor
class ReciprocalLatticeVector(Vector3d):
r"""Reciprocal lattice vectors :math:`(hkl)` for use in electron
diffraction analysis and simulation.
All lengths are assumed to be given in Å or inverse Å.
This class extends :class:`orix.vector.Vector3d` to reciprocal
lattice vectors :math:`(hkl)` specifically for diffraction
experiments and simulations. It is thus different from
:class:`orix.vector.Miller`, which is a general class for Miller
indices both in reciprocal *and* direct space. It supports relevant
methods also supported in `Miller`, like obtaining a set of vectors
from a minimal interplanar spacing.
Create a set of reciprocal lattice vectors from :math:`(hkl)` or
:math:`(hkil)`.
The vectors are stored internally as cartesian coordinates in
:attr:`data`.
Parameters
----------
phase : orix.crystal_map.Phase
A phase with a crystal lattice and symmetry.
xyz : numpy.ndarray, list, or tuple, optional
Cartesian coordinates of indices of reciprocal lattice vector(s)
``hkl``. Default is ``None``. This, ``hkl``, or ``hkil`` is
required.
hkl : numpy.ndarray, list, or tuple, optional
Indices of reciprocal lattice vector(s). Default is ``None``.
This, ``xyz``, or ``hkil`` is required.
hkil : numpy.ndarray, list, or tuple, optional
Indices of reciprocal lattice vector(s), often preferred over
``hkl`` in trigonal and hexagonal lattices. Default is ``None``.
This, ``xyz``, or ``hkl`` is required.
Examples
--------
>>> from diffpy.structure import Atom, Lattice, Structure
>>> from orix.crystal_map import Phase
>>> from diffsims.crystallography import ReciprocalLatticeVector
>>> phase = Phase(
... "al",
... space_group=225,
... structure=Structure(
... lattice=Lattice(4.04, 4.04, 4.04, 90, 90, 90),
... atoms=[Atom("Al", [0, 0, 1])],
... ),
... )
>>> rlv = ReciprocalLatticeVector(phase, hkl=[[1, 1, 1], [2, 0, 0]])
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
"""
def __init__(self, phase, xyz=None, hkl=None, hkil=None):
self.phase = phase
self._raise_if_no_point_group()
if np.sum([i is not None for i in [xyz, hkl, hkil]]) != 1:
raise ValueError("Exactly one of `xyz`, `hkl`, or `hkil` must be passed")
elif xyz is not None:
xyz = np.asarray(xyz)
self._coordinate_format = "hkl"
elif hkil is not None:
hkil = np.asarray(hkil)
_check_hkil(hkil)
hkl = _hkil2hkl(hkil)
self._coordinate_format = "hkil"
xyz = _transform_space(hkl, "r", "c", phase.structure.lattice)
else:
hkl = np.asarray(hkl)
self._coordinate_format = "hkl"
xyz = _transform_space(hkl, "r", "c", phase.structure.lattice)
super().__init__(xyz)
self._theta = np.full(self.shape, np.nan)
self._structure_factor = np.full(self.shape, np.nan, dtype="complex128")
self._intensity = np.full(self.shape, np.nan)
def __getitem__(self, key):
new_data = self.data[key]
rlv_new = self.__class__(self.phase, xyz=new_data)
if np.isnan(self.structure_factor).all():
rlv_new._structure_factor = np.full(
rlv_new.shape, np.nan, dtype="complex128"
)
else:
rlv_new._structure_factor = self.structure_factor[key]
if np.isnan(self.theta).all():
rlv_new._theta = np.full(rlv_new.shape, np.nan)
else:
rlv_new._theta = self.theta[key]
if np.isnan(self.intensity).all():
rlv_new._intensity = np.full(rlv_new.shape, np.nan)
else:
slic = self.intensity[key]
if not hasattr(slic, "__len__"):
slic = np.array(
[
slic,
]
)
rlv_new._intensity = slic
return rlv_new
def __repr__(self):
"""String representation."""
name = self.__class__.__name__
shape = self.shape
symmetry = self.phase.point_group.name
data = np.array_str(self.coordinates, precision=0, suppress_small=True)
phase_name = self.phase.name
return f"{name} {shape}, {phase_name} ({symmetry})\n" f"{data}"
@property
def hkl(self):
"""Miller indices.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.hkl
array([[1., 1., 1.],
[2., 0., 0.]])
"""
return _transform_space(self.data, "c", "r", self.phase.structure.lattice)
@property
def hkil(self):
"""Miller-Bravais indices.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.hkil
array([[ 1., 1., -2., 1.],
[ 2., 0., -2., 0.]])
"""
return _hkl2hkil(self.hkl)
@property
def h(self):
"""First reciprocal lattice vector index.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.h
array([1., 2.])
"""
return self.hkl[..., 0]
@property
def k(self):
"""Second reciprocal lattice vector index.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.k
array([1., 0.])
"""
return self.hkl[..., 1]
@property
def i(self):
r"""Third reciprocal lattice vector index in 4-index
Miller-Bravais indices, equal to :math:`-(h + k)`.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.i
array([-2., -2.])
"""
return self.hkil[..., 2]
@property
def l(self):
"""Third reciprocal lattice vector index, or fourth index in
4-index Miller Bravais indices.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.l
array([1., 0.])
"""
return self.hkl[..., 2]
@property
def multiplicity(self):
"""Number of symmetrically equivalent directions per vector.
Returns
-------
mult : numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.multiplicity
array([8, 6])
"""
mult = self.symmetrise(return_multiplicity=True)[1]
return mult.reshape(self.shape)
@property
def has_hexagonal_lattice(self):
"""Whether the crystal lattice is hexagonal/trigonal.
Returns
-------
bool
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.has_hexagonal_lattice
False
"""
return self.phase.is_hexagonal
@property
def coordinate_format(self):
"""Vector coordinate format, either ``"hkl"`` or ``"hkil"``.
Returns
-------
str
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.coordinate_format
'hkl'
>>> rlv.coordinate_format = "hkil"
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[ 1. 1. -2. 1.]
[ 2. 0. -2. 0.]]
"""
return self._coordinate_format
@coordinate_format.setter
def coordinate_format(self, value):
"""Set the vector coordinate format, either ``"hkl"``, or
``"hkil"``.
"""
formats = ["hkl", "hkil"]
if value not in formats:
raise ValueError(f"Available coordinate formats are {formats}")
self._coordinate_format = value
@property
def coordinates(self):
"""Miller or Miller-Bravais indices.
Returns
-------
coordinates : numpy.ndarray
Miller indices if :attr:`coordiante_format` is ``"hkl"`` or
Miller-Bravais indices if it is ``"hkil"``.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.coordinates
array([[1., 1., 1.],
[2., 0., 0.]])
>>> rlv.coordinate_format = "hkil"
>>> rlv.coordinates
array([[ 1., 1., -2., 1.],
[ 2., 0., -2., 0.]])
"""
return self.__getattribute__(self.coordinate_format)
@property
def gspacing(self):
r"""Reciprocal lattice vector spacing :math:`g`.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
Lattice parameters are given in :math:`Å`
>>> rlv.phase.structure.lattice
Lattice(a=4.04, b=4.04, c=4.04, alpha=90, beta=90, gamma=90)
so :math:`g` is given in :math:`Å^-1`
>>> rlv.gspacing
array([0.42872545, 0.4950495 ])
"""
return self.phase.structure.lattice.rnorm(self.hkl)
@property
def dspacing(self):
r"""Direct lattice interplanar spacing :math:`d = 1 / g`.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
Lattice parameters are given in :math:`Å`
>>> rlv.phase.structure.lattice
Lattice(a=4.04, b=4.04, c=4.04, alpha=90, beta=90, gamma=90)
so :math:`d` is given in :math:`Å`
>>> rlv.dspacing
array([2.33249509, 2.02 ])
"""
return 1 / self.gspacing
@property
def scattering_parameter(self):
r"""Scattering parameter :math:`0.5 \cdot g`.
Returns
-------
numpy.ndarray
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
Lattice parameters are given in :math:`Å`
>>> rlv.phase.structure.lattice
Lattice(a=4.04, b=4.04, c=4.04, alpha=90, beta=90, gamma=90)
so the scattering parameters are given in :math:`Å^-1`
>>> rlv.scattering_parameter
array([0.21436272, 0.24752475])
"""
return 0.5 * self.gspacing
@property
def intensity(self):
return self._intensity
@intensity.setter
def intensity(self, value):
if not hasattr(value, "__len__"):
value = np.array(
[
value,
]
* self.size
)
if len(value) != self.size:
raise ValueError("Length of intensity array must match number of vectors")
self._intensity = np.array(value)
def rotate_from_matrix(self, rotation_matrix):
return ReciprocalLatticeVector(
phase=self.phase, xyz=np.matmul(rotation_matrix, self.data.T).T
)
@property
def structure_factor(self):
r"""Kinematical structure factors :math:`F`.
Returns
-------
structure_factor : numpy.ndarray
Complex array. Filled with ``None`` if
:meth:`calculate_structure_factor` hasn't been called yet.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
Kinematical structure factors are by default not calculated
>>> rlv.structure_factor
array([nan+0.j, nan+0.j])
A unit cell with all asymmetric atom positions is required to
calculate structure factors
>>> rlv.phase.structure
[Al 0.000000 0.000000 1.000000 1.0000]
>>> rlv.sanitise_phase()
>>> rlv.phase.structure
[Al 0.000000 0.000000 0.000000 1.0000,
Al 0.000000 0.500000 0.500000 1.0000,
Al 0.500000 0.000000 0.500000 1.0000,
Al 0.500000 0.500000 0.000000 1.0000]
>>> rlv.calculate_structure_factor()
>>> rlv.structure_factor # doctest: +SKIP
array([8.46881663-1.55569638e-15j, 7.04777513-8.63103525e-16j])
"""
return self._structure_factor
@property
def theta(self):
"""Twice the Bragg angle.
Returns
-------
theta : numpy.ndarray
Filled with ``None`` if :meth:`calculate_theta` hasn't been
called yet.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
Bragg angles are by default not calculated
>>> rlv.theta
array([nan, nan])
>>> rlv.calculate_theta(20e3)
>>> rlv.theta # doctest: +SKIP
array([0.0184036 , 0.02125105])
"""
return self._theta
@property
def allowed(self):
"""Return whether vectors diffract according to diffraction
selection rules assuming kinematic scattering theory.
Integer vectors are assumed.
Returns
-------
allowed : numpy.ndarray
Boolean array.
Examples
--------
>>> from diffpy.structure import Atom, Lattice, Structure
>>> from orix.crystal_map import Phase
>>> from diffsims.crystallography import ReciprocalLatticeVector
>>> phase = Phase(
... "al",
... space_group=225,
... structure=Structure(
... lattice=Lattice(4.04, 4.04, 4.04, 90, 90, 90),
... atoms=[Atom("Al", [0, 0, 1])],
... ),
... )
>>> rlv = ReciprocalLatticeVector(
... phase, hkl=[[1, 0, 0], [2, 0, 0]]
... )
>>> rlv.allowed
array([False, True])
"""
self._raise_if_no_space_group()
# Translational symmetry
centering = self.phase.space_group.short_name[0]
hkl = self.hkl.round().astype(int).reshape(-1, 3)
if centering == "A": # Centred on A faces only
return np.isclose(np.mod(hkl[:, 1] + hkl[:, 2], 2), 0)
elif centering == "B": # Centred on B faces only
return np.isclose(np.mod(hkl[:, 0] + hkl[:, 2], 2), 0)
elif centering == "C": # Centred on C faces only
return np.isclose(np.mod(hkl[:, 0] + hkl[:, 1], 2), 0)
elif centering == "F": # Face-centred, hkl all odd/even
selection = np.sum(np.mod(hkl, 2), axis=-1)
return np.array([i not in [1, 2] for i in selection], dtype=bool)
elif centering == "I": # Body-centred, h + k + l = 2n (even)
return np.isclose(np.mod(np.sum(hkl, axis=-1), 2), 0)
elif centering in ["R", "H"]: # Rhombohedral obverse
# Consider Rhombohedral reverse?
return np.isclose(np.mod(-hkl[:, 0] + hkl[:, 1] + hkl[:, 2], 3), 0)
elif centering == "P": # Primitive
if self.has_hexagonal_lattice:
# TODO: See rules in e.g.
# https://mcl1.ncifcrf.gov/dauter_pubs/284.pdf, Table 4
# http://xrayweb.chem.ou.edu/notes/symmetry.html, Systematic Absences
raise NotImplementedError
else: # Any hkl
return np.ones(self.shape, dtype=bool)
else:
raise ValueError(f"Unknown unit cell centering {centering}")
# ------------------------- Custom methods ----------------------- #
def calculate_structure_factor(self, scattering_params="xtables"):
r"""Populate :attr:`structure_factor` with the complex
kinematical structure factor :math:`F_{hkl}` for each vector.
Parameters
----------
scattering_params : str
Which atomic scattering factors to use, either ``"xtables"``
(default) or ``"lobato"``.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
A unit cell with all asymmetric atom positions is required to
calculate structure factors
>>> rlv.phase.structure
[Al 0.000000 0.000000 1.000000 1.0000]
>>> rlv.sanitise_phase()
>>> rlv.phase.structure
[Al 0.000000 0.000000 0.000000 1.0000,
Al 0.000000 0.500000 0.500000 1.0000,
Al 0.500000 0.000000 0.500000 1.0000,
Al 0.500000 0.500000 0.000000 1.0000]
>>> rlv.calculate_structure_factor()
>>> rlv.structure_factor # doctest: +SKIP
array([8.46881663-1.55569638e-15j, 7.04777513-8.63103525e-16j])
Default atomic scattering factors are from the International
Tables of Crystallography Vol. C Table 4.3.2.3. Alternative
scattering factors are available from Lobato and Van Dyck
Acta Cryst. (2014). A70, 636-649
https://doi.org/10.1107/S205327331401643X
>>> rlv.calculate_structure_factor("lobato")
>>> rlv.structure_factor # doctest: +SKIP
array([8.44934816-1.55212008e-15j, 7.0387957 -8.62003862e-16j])
"""
# Compute one structure factor per set {hkl}
hkl_sets = self.get_hkl_sets()
# For each set, get the indices of the first vector in the
# present vectors, accounting for potential multiple dimensions
# and avoding computing the unique vectors again
first_idx = []
for arr in list(hkl_sets.values()):
i = []
for arr_i in arr:
i.append(arr_i[0])
first_idx.append(i)
first_idx_arr = np.array(first_idx).T
# Get 2D array of unique vectors, one for each set
hkl_unique = self.hkl[tuple(first_idx_arr)]
structure_factor = _get_kinematical_structure_factor(
structure=self.phase.structure,
g_indices=hkl_unique,
g_hkls_array=self.phase.structure.lattice.rnorm(hkl_unique),
scattering_params=scattering_params,
)
# Set structure factors of all symmetrically equivalent vectors
for i, idx in enumerate(hkl_sets.values()):
self._structure_factor[idx] = structure_factor[i]
def calculate_theta(self, voltage):
r"""Populate :attr:`theta` with the Bragg angle :math:`theta_B`
in radians.
Assumes :attr:`phase.structure` lattice parameters and
Debye-Waller factors are expressed in Ångströms.
Parameters
----------
voltage : float
Beam energy in V.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.calculate_theta(20e3)
>>> rlv.theta
array([0.0184036 , 0.02125105])
>>> rlv.calculate_theta(200e3)
>>> rlv.theta
array([0.00537583, 0.00620749])
"""
wavelength = 10 * get_refraction_corrected_wavelength(self.phase, voltage)
self._theta = np.arcsin(0.5 * wavelength * self.gspacing)
def deepcopy(self):
"""Get a deepcopy of the vectors.
Returns
-------
ReciprocalLatticeVector
"""
return deepcopy(self)
def get_hkl_sets(self):
r"""Get unique sets of :math:`{hkl}` for the vectors and the
indices of vectors in each set.
Returns
-------
hkl_sets : defaultdict
Dictionary with (h, k, l) as keys and a tuple with
:class:`numpy.ndarray` with integers of the vectors
(possibly multi-dimensional) in each set. The keys (h, k, l)
are rounded to six decimals so that applying integer values
(h, k, l) as dictionary keys work.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> hkl_sets = rlv.get_hkl_sets()
>>> hkl_sets
defaultdict(<class 'tuple'>, {(2.0, 0.0, 0.0): (array([1]),), (1.0, 1.0, 1.0): (array([0]),)})
>>> hkl_sets[2, 0, 0]
(array([1]),)
>>> rlv[hkl_sets[2, 0, 0]]
ReciprocalLatticeVector (1,), al (m-3m)
[[2. 0. 0.]]
"""
# Determine the unique vectors {hkl} representing each set
rlv_unique = self.unique(use_symmetry=True)
# Generate all symmetrically equivalent vectors in each set
# {hkl}, used as a look-up-table for the present vectors
rlv_symmetrised, mult = rlv_unique.symmetrise(return_multiplicity=True)
# Find the set for each vector. A Numba function is called,
# requiring two 2D arrays and one 1D array of float64
hkl = self.hkl.reshape(-1, 3).astype(np.float64)
test_hkl = rlv_symmetrised.hkl.reshape(-1, 3).astype(np.float64)
mult = mult.astype(np.int64)
hkl_set_idx = _get_set_per_hkl(hkl, test_hkl, mult)
# Generate dictionary of {hkl} and the indices of vectors in
# each set
hkl_sets = defaultdict(tuple)
for i, hkl_i in enumerate(rlv_unique.hkl):
mask1d = np.where(hkl_set_idx == i)[0]
mask = np.unravel_index(mask1d, self.shape)
hkl_sets[tuple(hkl_i.round(6))] = mask
return hkl_sets
def print_table(self):
r"""Table with indices, structure factor values and multiplicity
of each set of :math:`{hkl}`.
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.print_table()
h k l d |F|_hkl |F|^2 |F|^2_rel Mult
1 1 1 2.332 nan nan nan 8
2 0 0 2.020 nan nan nan 6
>>> rlv.sanitise_phase()
>>> rlv.calculate_structure_factor()
>>> rlv.print_table()
h k l d |F|_hkl |F|^2 |F|^2_rel Mult
1 1 1 2.332 8.5 71.7 100.0 8
2 0 0 2.020 7.0 49.7 69.3 6
"""
# Column alignment
align = "^" # right ">", left "<", or centered "^"
# Column widths
width = 6
hkl_width = width + 2
d_width = width
f_hkl_width = width + 1
f2_hkl_width = width + 1
f2_hkl_rel_width = width + 2
mult_width = width
# Header (note the two-space spacing)
data = (
"{:{align}{width}} ".format(" h k l ", width=hkl_width, align=align)
+ "{:{align}{width}} ".format("d", width=d_width, align=align)
+ "{:{align}{width}} ".format("|F|_hkl", width=f_hkl_width, align=align)
+ "{:{align}{width}} ".format("|F|^2", width=f2_hkl_width, align=align)
+ "{:{align}{width}} ".format(
"|F|^2_rel", width=f2_hkl_rel_width, align=align
)
+ "{:{align}{width}}\n".format("Mult", width=mult_width, align=align)
)
v = self.unique(use_symmetry=True)
structure_factor = v.structure_factor
f_hkl = abs(structure_factor)
f2_hkl = abs(structure_factor * structure_factor.conjugate())
order = np.argsort(f2_hkl)
v = v[order][::-1]
f_hkl = f_hkl[order][::-1]
f2_hkl = f2_hkl[order][::-1]
size = v.size
hkl = np.round(v.coordinates).astype(int)
hkl_string = np.array_str(hkl).replace("[", "").replace("]", "").split("\n")
d = v.dspacing
f2_hkl_rel = (f2_hkl / f2_hkl[0]) * 100
mult = v.multiplicity
for i in range(size):
hkl_string_i = hkl_string[i].lstrip(" ")
data += (
f"{hkl_string_i:{align}{hkl_width}} "
+ f"{d[i]:{align}{d_width}.3f} "
+ f"{f_hkl[i]:{align}{f_hkl_width}.1f} "
+ f"{f2_hkl[i]:{align}{f2_hkl_width}.1f} "
+ f" {f2_hkl_rel[i]:{align}{f2_hkl_rel_width}.1f} "
+ f" {mult[i]:{align}{mult_width}}"
)
if i != size - 1:
data += "\n"
print(data)
def sanitise_phase(self):
"""Sanitise the :attr:`phase` inplace for calculation of
structure factors.
The phase is sanitised when it's
:attr:`~orix.crystal_map.Phase.structure` has an expanded unit
cell with all symmetrically atom positions filled, and the atoms
have their :attr:`~diffpy.structure.Atom.element` set to a
string, e.g. "Al".
Examples
--------
See :class:`ReciprocalLatticeVector` for the creation of ``rlv``
>>> rlv
ReciprocalLatticeVector (2,), al (m-3m)
[[1. 1. 1.]
[2. 0. 0.]]
>>> rlv.phase.structure
[Al 0.000000 0.000000 1.000000 1.0000]
>>> rlv.sanitise_phase()
>>> rlv.phase.structure
[Al 0.000000 0.000000 0.000000 1.0000,
Al 0.000000 0.500000 0.500000 1.0000,
Al 0.500000 0.000000 0.500000 1.0000,
Al 0.500000 0.500000 0.000000 1.0000]
"""
self._raise_if_no_space_group()
space_group = self.phase.space_group
structure = self.phase.structure
new_structure = _expand_unit_cell(space_group, structure)
for atom in new_structure:
if np.issubdtype(type(atom.element), np.integer):
atom.element = _get_string_from_element_id(atom.element)
self.phase.structure = new_structure
def symmetrise(self, return_multiplicity=False, return_index=False):
"""Unique vectors symmetrically equivalent to the vectors.
Parameters
----------
return_multiplicity : bool, optional
Whether to return the multiplicity of each vector. Default
is ``False``.
return_index : bool, optional
Whether to return the index into the vectors for the
returned symmetrically equivalent vectors. Default is
``False``.
Returns
-------
ReciprocalLatticeVector
Flattened symmetrically equivalent vectors.
multiplicity : numpy.ndarray
Multiplicity of each vector. Returned if
``return_multiplicity=True``.
idx : numpy.ndarray
Index into the vectors for the symmetrically equivalent
vectors. Returned if ``return_index=True``.