/
_refinement.py
1329 lines (1161 loc) · 43.4 KB
/
_refinement.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
# Copyright 2019-2023 The kikuchipy developers
#
# This file is part of kikuchipy.
#
# kikuchipy 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.
#
# kikuchipy 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 kikuchipy. If not, see <http://www.gnu.org/licenses/>.
"""Setup of refinement refinement of crystal orientations and projection
centers by optimizing the similarity between experimental and simulated
patterns.
"""
import sys
from time import time
from typing import Callable, Optional, Tuple, Union
from dask.diagnostics import ProgressBar
import dask.array as da
import numpy as np
from orix.crystal_map import create_coordinate_arrays, CrystalMap, Phase, PhaseList
from orix.quaternion import Rotation
import scipy.optimize
from kikuchipy.indexing._refinement._solvers import (
_refine_orientation_solver_nlopt,
_refine_orientation_solver_scipy,
_refine_orientation_pc_solver_nlopt,
_refine_orientation_pc_solver_scipy,
_refine_pc_solver_nlopt,
_refine_pc_solver_scipy,
)
from kikuchipy.indexing._refinement import SUPPORTED_OPTIMIZATION_METHODS
from kikuchipy.pattern import rescale_intensity
from kikuchipy.signals.util._crystal_map import _get_indexed_points_in_data_in_xmap
from kikuchipy.signals.util._master_pattern import (
_get_direction_cosines_from_detector,
)
def compute_refine_orientation_results(
results: da.Array,
xmap: CrystalMap,
master_pattern: "EBSDMasterPattern",
navigation_mask: Optional[np.ndarray] = None,
pseudo_symmetry_checked: bool = False,
) -> CrystalMap:
"""Compute the results from
:meth:`~kikuchipy.signals.EBSD.refine_orientation` and return the
:class:`~orix.crystal_map.CrystalMap`.
Parameters
----------
results
Dask array returned from ``refine_orientation()``.
xmap
Crystal map passed to ``refine_orientation()`` to obtain
``results``.
master_pattern
Master pattern passed to ``refine_orientation()`` to obtain
``results``.
navigation_mask
Navigation mask passed to ``refine_orientation()`` to obtain
``results``. If not given, it is assumed that it was not given
to ``refine_orientation()`` either.
pseudo_symmetry_checked
Whether pseudo-symmetry operators were passed to
``refine_orientation()``. Default is ``False``.
Returns
-------
xmap_refined
Crystal map with refined orientations, scores, the number of
function evaluations and the pseudo-symmetry index if
``pseudo_symmetry_checked=True``. See the docstring of
``refine_orientation()`` for details.
"""
points_to_refine, is_in_data, phase_id, _ = _get_indexed_points_in_data_in_xmap(
xmap, navigation_mask
)
nav_size = points_to_refine.size
nav_size_in_data = points_to_refine.sum()
xmap_kw = _get_crystal_map_parameters(
xmap, nav_size, master_pattern.phase, phase_id, pseudo_symmetry_checked
)
xmap_kw["phase_id"][points_to_refine] = phase_id
is_indexed = np.zeros_like(is_in_data)
is_indexed[xmap.is_in_data] = xmap.is_indexed
xmap_kw["phase_id"][~is_indexed] = -1
print(f"Refining {nav_size_in_data} orientation(s):", file=sys.stdout)
time_start = time()
with ProgressBar():
res = results.compute()
total_time = time() - time_start
patterns_per_second = nav_size_in_data / total_time
print(f"Refinement speed: {patterns_per_second:.5f} patterns/s", file=sys.stdout)
# Extract data: n x (score, number of evaluations, phi1, Phi, phi2,
# [pseudo-symmetry index])
res = np.array(res)
xmap_kw["prop"]["scores"][points_to_refine] = res[:, 0]
xmap_kw["prop"]["num_evals"][points_to_refine] = res[:, 1]
xmap_kw["rotations"][points_to_refine] = Rotation.from_euler(res[:, 2:5]).data
if pseudo_symmetry_checked:
xmap_kw["prop"]["pseudo_symmetry_index"][points_to_refine] = res[:, 5]
xmap_refined = CrystalMap(is_in_data=is_in_data, **xmap_kw)
return xmap_refined
def compute_refine_projection_center_results(
results: da.Array,
detector: "EBSDDetector",
xmap: CrystalMap,
navigation_mask: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, "EBSDDetector", np.ndarray]:
"""Compute the results from
:meth:`~kikuchipy.signals.EBSD.refine_projection_center` and return
the score array, :class:`~kikuchipy.detectors.EBSDDetector` and
number of function evaluations per pattern.
Parameters
----------
results
Dask array returned from ``refine_projection_center()``.
detector
Detector passed to ``refine_projection_center()`` to obtain
``results``.
xmap
Crystal map passed to ``refine_projection_center()`` to obtain
``results``.
navigation_mask
Navigation mask passed to ``refine_projection_center()`` to
obtain ``results``. If not given, it is assumed that it was not
given to ``refine_projection_center()`` either.
Returns
-------
new_scores
Score array.
new_detector
EBSD detector with refined projection center parameters.
num_evals
Number of function evaluations per pattern.
"""
(points_to_refine, *_, mask_shape) = _get_indexed_points_in_data_in_xmap(
xmap, navigation_mask
)
nav_size_in_data = points_to_refine.sum()
new_detector = detector.deepcopy()
print(f"Refining {nav_size_in_data} projection center(s):", file=sys.stdout)
time_start = time()
with ProgressBar():
res = results.compute()
total_time = time() - time_start
patterns_per_second = nav_size_in_data / total_time
print(f"Refinement speed: {patterns_per_second:.5f} patterns/s", file=sys.stdout)
# Extract data: n x (score, number of evaluations, PCx, PCy, PCz)
res = np.array(res)
scores = res[:, 0]
num_evals = res[:, 1].astype(np.int32)
new_pc = res[:, 2:]
if mask_shape is not None:
scores = scores.reshape(mask_shape)
num_evals = num_evals.reshape(mask_shape)
new_pc = new_pc.reshape(mask_shape + (3,))
new_detector.pc = new_pc
return scores, new_detector, num_evals
def compute_refine_orientation_projection_center_results(
results: da.Array,
detector: "EBSDDetector",
xmap: CrystalMap,
master_pattern: "EBSDMasterPattern",
navigation_mask: Optional[np.ndarray] = None,
pseudo_symmetry_checked: bool = False,
) -> Tuple[CrystalMap, "EBSDDetector"]:
"""Compute the results from
:meth:`~kikuchipy.signals.EBSD.refine_orientation_projection_center`
and return the :class:`~orix.crystal_map.CrystalMap` and
:class:`~kikuchipy.detectors.EBSDDetector`.
Parameters
----------
results
Dask array returned from
``refine_orientation_projection_center()``.
detector
Detector passed to ``refine_orientation_projection_center()`` to
obtain ``results``.
xmap
Crystal map passed to ``refine_orientation_projection_center()``
to obtain ``results``.
master_pattern
Master pattern passed to
``refine_orientation_projection_center()`` to obtain
``results``.
navigation_mask
Navigation mask passed to
``refine_orientation_projection_center()`` to obtain
``results``. If not given, it is assumed that it was not given
to ``refine_orientation_projection_center()`` either.
pseudo_symmetry_checked
Whether pseudo-symmetry operators were passed to
``refine_orientation_projection_center()``. Default is
``False``.
Returns
-------
xmap_refined
Crystal map with refined orientations, scores, the number of
function evaluations and the pseudo-symmetry index if
``pseudo_symmetry_checked=True``. See the docstring of
``refine_orientation_projection_center()`` for details.
new_detector
EBSD detector with refined projection center parameters.
See Also
--------
kikuchipy.signals.EBSD.refine_orientation_projection_center
"""
(
points_to_refine,
is_in_data,
phase_id,
mask_shape,
) = _get_indexed_points_in_data_in_xmap(xmap, navigation_mask)
nav_size = points_to_refine.size
nav_size_in_data = points_to_refine.sum()
xmap_kw = _get_crystal_map_parameters(
xmap, nav_size, master_pattern.phase, phase_id, pseudo_symmetry_checked
)
xmap_kw["phase_id"][points_to_refine] = phase_id
is_indexed = np.zeros_like(is_in_data)
is_indexed[xmap.is_in_data] = xmap.is_indexed
xmap_kw["phase_id"][~is_indexed] = -1
new_detector = detector.deepcopy()
print(
f"Refining {nav_size_in_data} orientation(s) and projection center(s):",
file=sys.stdout,
)
time_start = time()
with ProgressBar():
res = results.compute()
total_time = time() - time_start
patterns_per_second = nav_size_in_data / total_time
print(f"Refinement speed: {patterns_per_second:.5f} patterns/s", file=sys.stdout)
# Extract data: n x (score, number of evaluations, phi1, Phi, phi2,
# PCx, PCy, PCz, [pseudo-symmetry index])
res = np.array(res)
xmap_kw["prop"]["scores"][points_to_refine] = res[:, 0]
xmap_kw["prop"]["num_evals"][points_to_refine] = res[:, 1]
xmap_kw["rotations"][points_to_refine] = Rotation.from_euler(res[:, 2:5]).data
if pseudo_symmetry_checked:
xmap_kw["prop"]["pseudo_symmetry_index"][points_to_refine] = res[:, 8]
xmap_refined = CrystalMap(is_in_data=is_in_data, **xmap_kw)
new_pc = res[:, 5:8]
if mask_shape is not None:
new_pc = new_pc.reshape(mask_shape + (3,))
new_detector.pc = new_pc
return xmap_refined, new_detector
def _get_crystal_map_parameters(
xmap: CrystalMap,
nav_size: int,
master_pattern_phase: Phase,
phase_id: int,
pseudo_symmetry_checked: bool = False,
) -> dict:
step_sizes = ()
for step_size in [xmap.dy, xmap.dx]:
if step_size != 0:
step_sizes += (step_size,)
xmap_dict, _ = create_coordinate_arrays(xmap.shape, step_sizes=step_sizes)
xmap_dict.update(
{
"rotations": Rotation.identity((nav_size,)),
"phase_id": np.zeros(nav_size, dtype=np.int32),
"phase_list": PhaseList(phases=master_pattern_phase, ids=phase_id),
"scan_unit": xmap.scan_unit,
"prop": {
"scores": np.zeros(nav_size, dtype=np.float64),
"num_evals": np.zeros(nav_size, dtype=np.int32),
},
}
)
if pseudo_symmetry_checked:
xmap_dict["prop"]["pseudo_symmetry_index"] = np.zeros(nav_size, dtype=np.int32)
if "not_indexed" in xmap.phases.names:
xmap_dict["phase_list"].add_not_indexed()
return xmap_dict
# -------------------------- Refine orientation ---------------------- #
def _refine_orientation(
xmap: CrystalMap,
detector,
master_pattern,
energy: Union[int, float],
patterns: Union[np.ndarray, da.Array],
points_to_refine: np.ndarray,
signal_mask: np.ndarray,
trust_region: Union[tuple, list, np.ndarray, None],
rtol: float,
pseudo_symmetry_ops: Optional[Rotation] = None,
method: Optional[str] = None,
method_kwargs: Optional[dict] = None,
initial_step: Optional[float] = None,
maxeval: Optional[int] = None,
compute: bool = True,
navigation_mask: Optional[np.ndarray] = None,
):
ref = _RefinementSetup(
mode="ori",
xmap=xmap,
detector=detector,
master_pattern=master_pattern,
energy=energy,
patterns=patterns,
rtol=rtol,
method=method,
method_kwargs=method_kwargs,
initial_step=initial_step,
maxeval=maxeval,
points_to_refine=points_to_refine,
signal_mask=signal_mask,
pseudo_symmetry_ops=pseudo_symmetry_ops,
)
# Get bounds on control variables. If a trust region is not passed,
# these arrays are all 0, and not used in the objective functions.
lower_bounds, upper_bounds = ref.get_bound_constraints(trust_region)
ref.solver_kwargs["trust_region_passed"] = trust_region is not None
if ref.unique_pc:
# Patterns have been indexed with varying PCs, so we re-compute
# the direction cosines for every pattern during refinement.
# Since we're iterating over (n patterns, x parameters, 1) in
# each Dask array, we need the PC arrays to stay 3D (hence the
# 'weird' slicing).
pc = ref.pc_array
pcx = pc[:, :, 0:1]
pcy = pc[:, :, 1:2]
pcz = pc[:, :, 2:3]
res = da.map_blocks(
ref.chunk_func,
patterns,
ref.rotations_array,
lower_bounds,
upper_bounds,
pcx,
pcy,
pcz,
nrows=detector.nrows,
ncols=detector.ncols,
tilt=detector.tilt,
azimuthal=detector.azimuthal,
sample_tilt=detector.sample_tilt,
signal_mask=signal_mask,
solver_kwargs=ref.solver_kwargs,
n_pseudo_symmetry_ops=ref.n_pseudo_symmetry_ops,
**ref.map_blocks_kwargs,
)
else:
# Patterns have been indexed with the same PC, so we use the
# same direction cosines during refinement of all patterns
dc = _get_direction_cosines_from_detector(detector, signal_mask)
res = da.map_blocks(
ref.chunk_func,
patterns,
ref.rotations_array,
lower_bounds,
upper_bounds,
direction_cosines=dc,
signal_mask=signal_mask,
solver_kwargs=ref.solver_kwargs,
n_pseudo_symmetry_ops=ref.n_pseudo_symmetry_ops,
**ref.map_blocks_kwargs,
)
msg = ref.get_info_message(trust_region)
print(msg)
if compute:
res = compute_refine_orientation_results(
results=res,
xmap=xmap,
master_pattern=master_pattern,
navigation_mask=navigation_mask,
pseudo_symmetry_checked=pseudo_symmetry_ops is not None,
)
return res
def _refine_orientation_chunk_scipy(
patterns: np.ndarray,
rotations: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
pcx: Optional[np.ndarray] = None,
pcy: Optional[np.ndarray] = None,
pcz: Optional[np.ndarray] = None,
signal_mask: Optional[np.ndarray] = None,
solver_kwargs: Optional[dict] = None,
direction_cosines: Optional[np.ndarray] = None,
nrows: Optional[int] = None,
ncols: Optional[int] = None,
tilt: Optional[float] = None,
azimuthal: Optional[float] = None,
sample_tilt: Optional[float] = None,
n_pseudo_symmetry_ops: int = 0,
):
"""Refine orientations from patterns in one dask array chunk using
*SciPy*.
Note that ``signal_mask`` and ``solver_kwargs`` are required. They
are set to ``None`` to enable use of this function in
:func:`~dask.array.Array.map_blocks`.
"""
nav_size = patterns.shape[0]
value_size = 5
if n_pseudo_symmetry_ops > 0:
value_size += 1
results = np.empty((nav_size, value_size), dtype=np.float64)
# SciPy requires a sequence of (min, max) for each control variable
bounds = np.stack((lower_bounds, upper_bounds), axis=lower_bounds.ndim)
if direction_cosines is None:
for i in range(nav_size):
results[i] = _refine_orientation_solver_scipy(
pattern=patterns[i, 0],
rotation=rotations[i],
bounds=bounds[i],
pcx=float(pcx[i, 0, 0]),
pcy=float(pcy[i, 0, 0]),
pcz=float(pcz[i, 0, 0]),
nrows=nrows,
ncols=ncols,
tilt=tilt,
azimuthal=azimuthal,
sample_tilt=sample_tilt,
signal_mask=signal_mask,
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
else:
for i in range(nav_size):
results[i] = _refine_orientation_solver_scipy(
pattern=patterns[i, 0],
rotation=rotations[i],
bounds=bounds[i],
direction_cosines=direction_cosines,
signal_mask=signal_mask,
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
return results
def _refine_orientation_chunk_nlopt(
patterns: np.ndarray,
rotations: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
pcx: Optional[np.ndarray] = None,
pcy: Optional[np.ndarray] = None,
pcz: Optional[np.ndarray] = None,
opt: "nlopt.opt" = None,
signal_mask: Optional[np.ndarray] = None,
solver_kwargs: Optional[dict] = None,
direction_cosines: Optional[np.ndarray] = None,
nrows: Optional[int] = None,
ncols: Optional[int] = None,
tilt: Optional[float] = None,
azimuthal: Optional[float] = None,
sample_tilt: Optional[float] = None,
n_pseudo_symmetry_ops: int = 0,
):
"""Refine orientations from patterns in one dask array chunk using
*NLopt*.
Note that ``signal_mask``, ``solver_kwargs`` and ``opt`` are
required. They are set to ``None`` to enable use of this function in
:func:`~dask.array.Array.map_blocks`.
"""
# Copy optimizer
import nlopt
opt = nlopt.opt(opt)
nav_size = patterns.shape[0]
value_size = 5
if n_pseudo_symmetry_ops > 0:
value_size += 1
results = np.empty((nav_size, value_size), dtype=np.float64)
if direction_cosines is None:
for i in range(nav_size):
results[i] = _refine_orientation_solver_nlopt(
opt=opt,
pattern=patterns[i, 0],
rotation=rotations[i],
lower_bounds=lower_bounds[i],
upper_bounds=upper_bounds[i],
signal_mask=signal_mask,
pcx=float(pcx[i, 0, 0]),
pcy=float(pcy[i, 0, 0]),
pcz=float(pcz[i, 0, 0]),
nrows=nrows,
ncols=ncols,
tilt=tilt,
azimuthal=azimuthal,
sample_tilt=sample_tilt,
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
else:
for i in range(nav_size):
results[i] = _refine_orientation_solver_nlopt(
opt=opt,
pattern=patterns[i, 0],
rotation=rotations[i],
lower_bounds=lower_bounds[i],
upper_bounds=upper_bounds[i],
signal_mask=signal_mask,
direction_cosines=direction_cosines,
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
return results
# ------------------------------ Refine PC --------------------------- #
def _refine_pc(
xmap: CrystalMap,
detector,
master_pattern,
energy: Union[int, float],
patterns: Union[np.ndarray, da.Array],
points_to_refine: np.ndarray,
signal_mask: np.ndarray,
trust_region: Union[tuple, list, np.ndarray, None],
rtol: float,
rotations_ps: Optional[Rotation] = None,
method: Optional[str] = None,
method_kwargs: Optional[dict] = None,
initial_step: Optional[float] = None,
maxeval: Optional[int] = None,
compute: bool = True,
navigation_mask: Optional[np.ndarray] = None,
):
ref = _RefinementSetup(
mode="pc",
xmap=xmap,
detector=detector,
master_pattern=master_pattern,
energy=energy,
patterns=patterns,
rtol=rtol,
method=method,
method_kwargs=method_kwargs,
initial_step=initial_step,
maxeval=maxeval,
points_to_refine=points_to_refine,
signal_mask=signal_mask,
pseudo_symmetry_ops=rotations_ps,
)
# Get bounds on control variables. If a trust region is not passed,
# these arrays are all 0, and not used in the objective functions.
lower_bounds, upper_bounds = ref.get_bound_constraints(trust_region)
ref.solver_kwargs["trust_region_passed"] = trust_region is not None
res = da.map_blocks(
ref.chunk_func,
patterns[:, 0, :],
ref.rotations_array[:, 0, :],
ref.pc_array[:, 0, :],
lower_bounds[:, 0, :],
upper_bounds[:, 0, :],
solver_kwargs=ref.solver_kwargs,
**ref.map_blocks_kwargs,
)
msg = ref.get_info_message(trust_region)
print(msg)
if compute:
res = compute_refine_projection_center_results(
results=res,
detector=detector,
xmap=xmap,
navigation_mask=navigation_mask,
)
return res
def _refine_pc_chunk_scipy(
patterns: np.ndarray,
rotations: np.ndarray,
pc: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
solver_kwargs: dict,
):
"""Refine projection centers using patterns in one dask array chunk."""
nav_size = patterns.shape[0]
results = np.empty((nav_size, 5), dtype=np.float64)
# SciPy requires a sequence of (min, max) for each control variable
bounds = np.stack((lower_bounds, upper_bounds), axis=lower_bounds.ndim)
for i in range(nav_size):
results[i] = _refine_pc_solver_scipy(
pattern=patterns[i],
rotation=rotations[i],
pc=pc[i],
bounds=bounds[i],
**solver_kwargs,
)
return results
def _refine_pc_chunk_nlopt(
patterns: np.ndarray,
rotations: np.ndarray,
pc: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
solver_kwargs: dict,
opt: "nlopt.opt" = None,
):
"""Refine projection centers using patterns in one dask array chunk."""
# Copy optimizer
import nlopt
opt = nlopt.opt(opt)
nav_size = patterns.shape[0]
results = np.empty((nav_size, 5), dtype=np.float64)
for i in range(nav_size):
results[i] = _refine_pc_solver_nlopt(
opt=opt,
pattern=patterns[i],
pc=pc[i],
rotation=rotations[i],
lower_bounds=lower_bounds[i],
upper_bounds=upper_bounds[i],
**solver_kwargs,
)
return results
# ---------------------- Refine orientation and PC ------------------- #
def _refine_orientation_pc(
xmap: CrystalMap,
detector,
master_pattern,
energy: Union[int, float],
patterns: Union[np.ndarray, da.Array],
points_to_refine: np.ndarray,
signal_mask: np.ndarray,
trust_region: Union[tuple, list, np.ndarray, None],
rtol: float,
pseudo_symmetry_ops: Optional[Rotation] = None,
method: Optional[str] = None,
method_kwargs: Optional[dict] = None,
initial_step: Union[tuple, list, np.ndarray, None] = None,
maxeval: Optional[int] = None,
compute: bool = True,
navigation_mask: Optional[np.ndarray] = None,
) -> tuple:
"""See the docstring of
:meth:`kikuchipy.signals.EBSD.refine_orientation_projection_center`.
"""
ref = _RefinementSetup(
mode="ori_pc",
xmap=xmap,
detector=detector,
master_pattern=master_pattern,
energy=energy,
patterns=patterns,
points_to_refine=points_to_refine,
rtol=rtol,
method=method,
method_kwargs=method_kwargs,
initial_step=initial_step,
maxeval=maxeval,
signal_mask=signal_mask,
pseudo_symmetry_ops=pseudo_symmetry_ops,
)
# Stack Euler angles and PC parameters into one array of shape:
# navigation shape + (6,)
rot_pc = ref.rotations_pc_array
# Get bounds on control variables. If a trust region is not passed,
# these arrays are all 0, and not used in the objective functions.
lower_bounds, upper_bounds = ref.get_bound_constraints(trust_region)
ref.solver_kwargs["trust_region_passed"] = trust_region is not None
res = da.map_blocks(
ref.chunk_func,
patterns,
rot_pc,
lower_bounds,
upper_bounds,
solver_kwargs=ref.solver_kwargs,
n_pseudo_symmetry_ops=ref.n_pseudo_symmetry_ops,
**ref.map_blocks_kwargs,
)
msg = ref.get_info_message(trust_region)
print(msg)
if compute:
res = compute_refine_orientation_projection_center_results(
results=res,
detector=detector,
xmap=xmap,
master_pattern=master_pattern,
navigation_mask=navigation_mask,
pseudo_symmetry_checked=pseudo_symmetry_ops is not None,
)
return res
def _refine_orientation_pc_chunk_scipy(
patterns: np.ndarray,
rot_pc: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
solver_kwargs: Optional[dict] = None,
n_pseudo_symmetry_ops: int = 0,
):
"""Refine orientations and projection centers using all patterns in
one dask array chunk using *SciPy*.
"""
nav_size = patterns.shape[0]
value_size = 8
if n_pseudo_symmetry_ops > 0:
value_size += 1
results = np.empty((nav_size, value_size), dtype=np.float64)
# SciPy requires a sequence of (min, max) for each control variable
bounds = np.stack((lower_bounds, upper_bounds), axis=lower_bounds.ndim)
for i in range(nav_size):
results[i] = _refine_orientation_pc_solver_scipy(
pattern=patterns[i, 0],
rot_pc=rot_pc[i],
bounds=bounds[i],
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
return results
def _refine_orientation_pc_chunk_nlopt(
patterns: np.ndarray,
rot_pc: np.ndarray,
lower_bounds: np.ndarray,
upper_bounds: np.ndarray,
solver_kwargs: Optional[dict] = None,
opt: "nlopt.opt" = None,
n_pseudo_symmetry_ops: int = 0,
):
"""Refine orientations and projection centers using all patterns in
one dask array chunk using *NLopt*.
"""
# Copy optimizer
import nlopt
opt = nlopt.opt(opt)
nav_size = patterns.shape[0]
value_size = 8
if n_pseudo_symmetry_ops > 0:
value_size += 1
results = np.empty((nav_size, value_size), dtype=np.float64)
for i in range(nav_size):
results[i] = _refine_orientation_pc_solver_nlopt(
opt,
pattern=patterns[i, 0],
rot_pc=rot_pc[i],
lower_bounds=lower_bounds[i],
upper_bounds=upper_bounds[i],
n_pseudo_symmetry_ops=n_pseudo_symmetry_ops,
**solver_kwargs,
)
return results
# ------------------------- Refinement setup ------------------------- #
class _RefinementSetup:
"""Set up EBSD refinement.
Parameters
----------
mode
Either ``"ori"``, ``"pc"`` or ``"ori_pc"``.
xmap
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
detector
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
master_pattern
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
energy
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
patterns
EBSD patterns in a 2D array with one navigation dimension and
one signal dimension.
points_to_refine
A 1D boolean array with points in the crystal map to refine. The
number of ``True`` values is equal to the length of the
pattern's navigation dimension.
rtol
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
method
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
method_kwargs
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
initial_step
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
maxeval
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
signal_mask
A 1D boolean array of equal size as the pattern signal
dimension, with values equal to ``True`` to use in refinement.
pseudo_symmetry_ops
See docstring of e.g.
:meth:`~kikuchipy.signals.EBSD.refine_orientation`.
"""
mode: str
# Data parameters
data_shape: tuple
nav_size: int
n_pseudo_symmetry_ops: int = 0
rotations_array: da.Array
rotations_pc_array: Optional[da.Array] = None
# Optimization parameters
initial_step: Optional[list] = None
maxeval: Optional[int] = None
method_name: str
optimization_type: str
package: str
supports_bounds: bool = False
# Fixed parameters
fixed_parameters: tuple
# Arguments to pass to Dask and to solver functions
chunk_func: Callable
map_blocks_kwargs: dict = {}
solver_kwargs: dict = {}
def __init__(
self,
mode: str,
xmap: CrystalMap,
detector: "EBSDDetector",
master_pattern: "EBSDMasterPattern",
energy: Union[int, float],
patterns: Union[np.ndarray, da.Array],
points_to_refine: np.ndarray,
rtol: float,
method: str,
method_kwargs: Optional[dict] = None,
initial_step: Optional[float] = None,
maxeval: Optional[int] = None,
signal_mask: Optional[np.ndarray] = None,
pseudo_symmetry_ops: Optional[Rotation] = None,
):
"""Set up EBSD refinement."""
self.mode = mode
self.set_optimization_parameters(
rtol=rtol,
method=method,
method_kwargs=method_kwargs,
initial_step=initial_step,
maxeval=maxeval,
)
self.set_fixed_parameters(
master_pattern=master_pattern,
energy=energy,
signal_mask=signal_mask,
detector=detector,
)
self.solver_kwargs["fixed_parameters"] = self.fixed_parameters
self.solver_kwargs["rescale"] = patterns.dtype == np.float32
# Chunks for navigation size, pseudo-symmetry operators and
# variables (e.g. detector pixels, control variables etc.)
self.chunks = (patterns.chunksize[0], -1, -1)
# Relevant rotations, potentially after applying pseudo-symmetry
# operators, as a Dask array of shape (navigation size,
# 1 + n pseudo-symmetry operators, n variables)
self.nav_size = points_to_refine.sum()
points_to_refine_in_data = points_to_refine[xmap.is_in_data]
if xmap.rotations_per_point > 1:
rot = xmap.rotations[points_to_refine_in_data, 0]
else:
rot = xmap.rotations[points_to_refine_in_data]
if pseudo_symmetry_ops is not None:
self.n_pseudo_symmetry_ops = pseudo_symmetry_ops.size
rot_ps_data = pseudo_symmetry_ops.flatten().outer(rot).data
rot_ps_data = rot_ps_data.transpose((1, 0, 2))
rot = Rotation(np.hstack((rot.data[:, np.newaxis], rot_ps_data)))
if self.mode == "pc":
rot_data = rot.data
else:
rot_data = rot.to_euler()
# Relevant projection centers as a Dask array of shape
# (navigation size, 1, n variables)
self.unique_pc = detector.navigation_size > 1
if self.unique_pc:
# Patterns have been initially indexed with varying PCs, so
# we use these as the starting point for every pattern
pc = detector.pc_flattened[points_to_refine]
else:
# Patterns have been initially indexed with the same PC, so
# we use this as the starting point for every pattern
pc = np.full((int(points_to_refine.sum()), 3), detector.pc[0])
pc = pc.astype(np.float64)
pc = np.expand_dims(pc, 1) # Pseudo-symmetry operator axis
self.pc_array = da.from_array(pc, chunks=self.chunks)
if pseudo_symmetry_ops is None:
rot_data = np.expand_dims(rot_data, 1)
else: