-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathebsd.py
executable file
·1917 lines (1550 loc) · 67 KB
/
ebsd.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 2023 Mechanics of Microstructures Group
# at The University of Manchester
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from skimage import morphology as mph
import networkx as nx
import copy
from warnings import warn
from defdap.utils import Datastore
from defdap.file_readers import EBSDDataLoader
from defdap.file_writers import EBSDDataWriter
from defdap.quat import Quat
from defdap import base
from defdap._accelerated import flood_fill
from defdap import defaults
from defdap.plotting import MapPlot
from defdap.utils import report_progress
class Map(base.Map):
"""
Class to encapsulate an EBSD map and useful analysis and plotting
methods.
Attributes
----------
step_size : float
Step size in micron.
phases : list of defdap.crystal.Phase
List of phases.
mis_ori : numpy.ndarray
Map of misorientation.
mis_ori_axis : list of numpy.ndarray
Map of misorientation axis components.
origin : tuple(int)
Map origin (x, y). Used by linker class where origin is a
homologue point of the maps.
data : defdap.utils.Datastore
Must contain after loading data (maps):
phase : numpy.ndarray
1-based, 0 is non-indexed points
euler_angle : numpy.ndarray
stored as (3, y_dim, x_dim) in radians
Generated data:
orientation : numpy.ndarray of defdap.quat.Quat
Quaterion for each point of map. Shape (y_dim, x_dim).
grain_boundaries : BoundarySet
phase_boundaries : BoundarySet
grains : numpy.ndarray of int
Map of grains. Grain numbers start at 1 here but everywhere else
grainID starts at 0. Regions that are smaller than the minimum
grain size are given value -2. Remnant boundary points are -1.
KAM : numpy.ndarray
Kernal average misorientaion map.
GND : numpy.ndarray
GND scalar map.
Nye_tensor : numpy.ndarray
3x3 Nye tensor at each point.
Derived data:
grain_data_to_map : numpy.ndarray
Grain list data to map data from all grains
"""
MAPNAME = 'ebsd'
def __init__(self, *args, **kwargs):
"""
Initialise class and load EBSD data.
Parameters
----------
*args, **kwarg
Passed to base constructor
"""
# Initialise variables
self.step_size = None
self.phases = []
# Call base class constructor
super(Map, self).__init__(*args, **kwargs)
self.mis_ori = None
self.mis_ori_axis = None
self.origin = (0, 0)
# Phase used for the maps crystal structure and c_over_a. So old
# functions still work for the 'main' phase in the map. 0-based
self.primary_phase_id = 0
# Use euler map for defining homologous points
self.plot_default = self.plot_euler_map
self.homog_map_name = 'band_contrast'
self.highlight_alpha = 1
self.data.add_generator(
'orientation', self.calc_quat_array, unit='', type='map',
order=0, default_component='IPF_x',
)
self.data.add_generator(
('phase_boundaries', 'grain_boundaries'), self.find_boundaries,
type='boundaries',
)
self.data.add_generator(
'grains', self.find_grains, unit='', type='map', order=0
)
self.data.add_generator(
'KAM', self.calc_kam, unit='rad', type='map', order=0,
plot_params={
'plot_colour_bar': True,
'clabel': 'KAM',
}
)
self.data.add_generator(
('GND', 'Nye_tensor'), self.calc_nye,
unit='', type='map',
metadatas=({
'order': 0,
'plot_params': {
'plot_colour_bar': True,
'clabel': 'GND content',
}
}, {
'order': 2,
'save': False,
'default_component': (0, 0),
'plot_params': {
'plot_colour_bar': True,
'clabel': 'Nye tensor',
}
})
)
@report_progress("loading EBSD data")
def load_data(self, file_name, data_type=None):
"""Load in EBSD data from file.
Parameters
----------
file_name : pathlib.Path
Path to EBSD file
data_type : str, {'OxfordBinary', 'OxfordText', 'EdaxAng', 'PythonDict'}
Format of EBSD data file.
"""
data_loader = EBSDDataLoader.get_loader(data_type, file_name)
data_loader.load(file_name)
metadata_dict = data_loader.loaded_metadata
self.shape = metadata_dict['shape']
self.step_size = metadata_dict['step_size']
self.phases = metadata_dict['phases']
self.data.update(data_loader.loaded_data)
# write final status
yield (f"Loaded EBSD data (dimensions: {self.x_dim} x {self.y_dim} "
f"pixels, step size: {self.step_size} um)")
def save(self, file_name, data_type=None, file_dir=""):
"""Save EBSD map to file.
Parameters
----------
file_name : str
Name of file to save to, it must not already exist.
data_type : str, {'OxfordText'}
Format of EBSD data file to save.
file_dir : str
Directory to save the file to.
"""
data_writer = EBSDDataWriter.get_writer(data_type)
data_writer.metadata['shape'] = self.shape
data_writer.metadata['step_size'] = self.step_size
data_writer.metadata['phases'] = self.phases
data_writer.data['phase'] = self.data.phase
data_writer.data['quat'] = self.data.orientation
data_writer.data['band_contrast'] = self.data.band_contrast
data_writer.write(file_name, file_dir=file_dir)
@property
def crystal_sym(self):
"""Crystal symmetry of the primary phase.
Returns
-------
str
Crystal symmetry
"""
return self.primary_phase.crystal_structure.name
@property
def c_over_a(self):
"""C over A ratio of the primary phase
Returns
-------
float or None
C over A ratio if hexagonal crystal structure otherwise None
"""
return self.primary_phase.c_over_a
@property
def num_phases(self):
return len(self.phases) or None
@property
def primary_phase(self):
"""Primary phase of the EBSD map.
Returns
-------
defdap.crystal.Phase
Primary phase
"""
return self.phases[self.primary_phase_id]
@property
def scale(self):
return self.step_size
@report_progress("rotating EBSD data")
def rotate_data(self):
"""Rotate map by 180 degrees and transform quats accordingly.
"""
self.data.euler_angle = self.data.euler_angle[:, ::-1, ::-1]
self.data.band_contrast = self.data.band_contrast[::-1, ::-1]
self.data.band_slope = self.data.band_slope[::-1, ::-1]
self.data.phase = self.data.phase[::-1, ::-1]
self.calc_quat_array()
# Rotation from old coord system to new
transform_quat = Quat.from_axis_angle(np.array([0, 0, 1]), np.pi).conjugate
# Perform vectorised multiplication
quats = Quat.multiply_many_quats(self.data.orientation.flatten(), transform_quat)
self.data.orientation = np.array(quats).reshape(self.shape)
yield 1.
def calc_euler_colour(self, map_data, phases=None, bg_colour=None):
if phases is None:
phases = self.phases
phase_ids = range(len(phases))
else:
phase_ids = phases
phases = [self.phases[i] for i in phase_ids]
if bg_colour is None:
bg_colour = np.array([0., 0., 0.])
map_colours = np.tile(bg_colour, self.shape + (1,))
for phase, phase_id in zip(phases, phase_ids):
if phase.crystal_structure.name == 'cubic':
norm = np.array([2 * np.pi, np.pi / 2, np.pi / 2])
elif phase.crystal_structure.name == 'hexagonal':
norm = np.array([np.pi, np.pi, np.pi / 3])
else:
ValueError("Only hexagonal and cubic symGroup supported")
# Apply normalisation for each phase
phase_mask = self.data.phase == phase_id + 1
map_colours[phase_mask] = map_data[:, phase_mask].T / norm
return map_colours
def calc_ipf_colour(self, map_data, direction, phases=None,
bg_colour=None):
if phases is None:
phases = self.phases
phase_ids = range(len(phases))
else:
phase_ids = phases
phases = [self.phases[i] for i in phase_ids]
if bg_colour is None:
bg_colour = np.array([0., 0., 0.])
map_colours = np.tile(bg_colour, self.shape + (1,))
for phase, phase_id in zip(phases, phase_ids):
# calculate IPF colours for phase
phase_mask = self.data.phase == phase_id + 1
map_colours[phase_mask] = Quat.calc_ipf_colours(
map_data[phase_mask], direction, phase.crystal_structure.name
).T
return map_colours
def plot_euler_map(self, phases=None, bg_colour=None, **kwargs):
"""Plot an orientation map in Euler colouring
Parameters
----------
phases : list of int
Which phases to plot for
kwargs
All arguments are passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {}
plot_params.update(kwargs)
map_colours = self.calc_euler_colour(
self.data.euler_angle, phases=phases, bg_colour=bg_colour
)
return MapPlot.create(self, map_colours, **plot_params)
def plot_ipf_map(self, direction, phases=None, bg_colour=None, **kwargs):
"""
Plot a map with points coloured in IPF colouring,
with respect to a given sample direction.
Parameters
----------
direction : np.array len 3
Sample direction.
phases : list of int
Which phases to plot IPF data for.
bg_colour : np.array len 3
Colour of background (i.e. for phases not plotted).
kwargs
Other arguments passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {}
plot_params.update(kwargs)
map_colours = self.calc_ipf_colour(
self.data.orientation, direction, phases=phases,
bg_colour=bg_colour
)
return MapPlot.create(self, map_colours, **plot_params)
def plot_phase_map(self, **kwargs):
"""Plot a phase map.
Parameters
----------
kwargs
All arguments passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {
'vmin': 0,
'vmax': self.num_phases
}
plot_params.update(kwargs)
plot = MapPlot.create(self, self.data.phase, **plot_params)
# add a legend to the plot
phase_ids = list(range(0, self.num_phases + 1))
phase_names = ["Non-indexed"] + [phase.name for phase in self.phases]
plot.add_legend(phase_ids, phase_names, loc=2, borderaxespad=0.)
return plot
@report_progress("calculating KAM")
def calc_kam(self):
"""
Calculates Kernel Average Misorientaion (KAM) for the EBSD map,
based on a 3x3 kernel. Crystal symmetric equivalences are not
considered. Stores result as `KAM`.
"""
quat_comps = np.empty((4, ) + self.shape)
for i, row in enumerate(self.data.orientation):
for j, quat in enumerate(row):
quat_comps[:, i, j] = quat.quat_coef
kam = np.empty(self.shape)
# Start with rows. Calculate misorientation with neighbouring rows.
# First and last row only in one direction
kam[0] = abs(np.einsum("ij,ij->j",
quat_comps[:, 0], quat_comps[:, 1]))
kam[-1] = abs(np.einsum("ij,ij->j",
quat_comps[:, -1], quat_comps[:, -2]))
for i in range(1, self.y_dim - 1):
kam[i] = (abs(np.einsum("ij,ij->j",
quat_comps[:, i], quat_comps[:, i + 1])) +
abs(np.einsum("ij,ij->j",
quat_comps[:, i], quat_comps[:, i - 1]))
) / 2
kam[kam > 1] = 1
# Do the same for columns
kam[:, 0] += abs(np.einsum("ij,ij->j",
quat_comps[:, :, 0], quat_comps[:, :, 1]))
kam[:, -1] += abs(np.einsum("ij,ij->j",
quat_comps[:, :, -1], quat_comps[:, :, -2]))
for i in range(1, self.x_dim - 1):
kam[:, i] += (abs(np.einsum("ij,ij->j",
quat_comps[:, :, i],
quat_comps[:, :, i + 1])) +
abs(np.einsum("ij,ij->j",
quat_comps[:, :, i],
quat_comps[:, :, i - 1]))
) / 2
kam /= 2
kam[kam > 1] = 1
yield 1.
return 2 * np.arccos(kam)
@report_progress("calculating Nye tensor")
def calc_nye(self):
"""
Calculates Nye tensor and related GND density for the EBSD map.
Stores result as `Nye_tensor` and `GND`. Uses the crystal
symmetry of the primary phase.
"""
syms = self.primary_phase.crystal_structure.symmetries
num_syms = len(syms)
# array to store quat components of initial and symmetric equivalents
quat_comps = np.empty((num_syms, 4) + self.shape)
# populate with initial quat components
for i, row in enumerate(self.data.orientation):
for j, quat in enumerate(row):
quat_comps[0, :, i, j] = quat.quat_coef
# loop of over symmetries and apply to initial quat components
# (excluding first symmetry as this is the identity transformation)
for i, sym in enumerate(syms[1:], start=1):
# sym[i] * quat for all points (* is quaternion product)
quat_comps[i, 0] = (quat_comps[0, 0] * sym[0] - quat_comps[0, 1] * sym[1] -
quat_comps[0, 2] * sym[2] - quat_comps[0, 3] * sym[3])
quat_comps[i, 1] = (quat_comps[0, 0] * sym[1] + quat_comps[0, 1] * sym[0] -
quat_comps[0, 2] * sym[3] + quat_comps[0, 3] * sym[2])
quat_comps[i, 2] = (quat_comps[0, 0] * sym[2] + quat_comps[0, 2] * sym[0] -
quat_comps[0, 3] * sym[1] + quat_comps[0, 1] * sym[3])
quat_comps[i, 3] = (quat_comps[0, 0] * sym[3] + quat_comps[0, 3] * sym[0] -
quat_comps[0, 1] * sym[2] + quat_comps[0, 2] * sym[1])
# swap into positive hemisphere if required
quat_comps[i, :, quat_comps[i, 0] < 0] *= -1
# Arrays to store neighbour misorientation in positive x and y direction
mis_ori_x = np.zeros((num_syms,) + self.shape)
mis_ori_y = np.zeros((num_syms, ) + self.shape)
# loop over symmetries calculating misorientation to initial
for i in range(num_syms):
for j in range(self.x_dim - 1):
mis_ori_x[i, :, j] = abs(np.einsum("ij,ij->j", quat_comps[0, :, :, j], quat_comps[i, :, :, j + 1]))
for j in range(self.y_dim - 1):
mis_ori_y[i, j, :] = abs(np.einsum("ij,ij->j", quat_comps[0, :, j, :], quat_comps[i, :, j + 1, :]))
mis_ori_x[mis_ori_x > 1] = 1
mis_ori_y[mis_ori_y > 1] = 1
# find min misorientation (max here as misorientaion is cos of this)
arg_mis_ori_x = np.argmax(mis_ori_x, axis=0)
arg_mis_ori_y = np.argmax(mis_ori_y, axis=0)
mis_ori_x = np.max(mis_ori_x, axis=0)
mis_ori_y = np.max(mis_ori_y, axis=0)
# convert to misorientation in degrees
mis_ori_x = 360 * np.arccos(mis_ori_x) / np.pi
mis_ori_y = 360 * np.arccos(mis_ori_y) / np.pi
# calculate relative elastic distortion tensors at each point in the two directions
betaderx = np.zeros((3, 3) + self.shape)
betadery = betaderx
for i in range(self.x_dim - 1):
for j in range(self.y_dim - 1):
q0x = Quat(quat_comps[0, 0, j, i], quat_comps[0, 1, j, i],
quat_comps[0, 2, j, i], quat_comps[0, 3, j, i])
qix = Quat(quat_comps[arg_mis_ori_x[j, i], 0, j, i + 1],
quat_comps[arg_mis_ori_x[j, i], 1, j, i + 1],
quat_comps[arg_mis_ori_x[j, i], 2, j, i + 1],
quat_comps[arg_mis_ori_x[j, i], 3, j, i + 1])
misoquatx = qix.conjugate * q0x
# change stepsize to meters
betaderx[:, :, j, i] = (Quat.rot_matrix(misoquatx) - np.eye(3)) / self.step_size / 1e-6
q0y = Quat(quat_comps[0, 0, j, i], quat_comps[0, 1, j, i],
quat_comps[0, 2, j, i], quat_comps[0, 3, j, i])
qiy = Quat(quat_comps[arg_mis_ori_y[j, i], 0, j + 1, i],
quat_comps[arg_mis_ori_y[j, i], 1, j + 1, i],
quat_comps[arg_mis_ori_y[j, i], 2, j + 1, i],
quat_comps[arg_mis_ori_y[j, i], 3, j + 1, i])
misoquaty = qiy.conjugate * q0y
# change stepsize to meters
betadery[:, :, j, i] = (Quat.rot_matrix(misoquaty) - np.eye(3)) / self.step_size / 1e-6
# Calculate the Nye Tensor
alpha = np.empty((3, 3) + self.shape)
bavg = 1.4e-10 # Burgers vector
alpha[0, 2] = (betadery[0, 0] - betaderx[0, 1]) / bavg
alpha[1, 2] = (betadery[1, 0] - betaderx[1, 1]) / bavg
alpha[2, 2] = (betadery[2, 0] - betaderx[2, 1]) / bavg
alpha[:, 1] = betaderx[:, 2] / bavg
alpha[:, 0] = -1 * betadery[:, 2] / bavg
# Calculate 3 possible L1 norms of Nye tensor for total
# disloction density
alpha_total3 = np.empty(self.shape)
alpha_total5 = np.empty(self.shape)
alpha_total9 = np.empty(self.shape)
alpha_total3 = 30 / 10. * (
abs(alpha[0, 2]) + abs(alpha[1, 2]) + abs(alpha[2, 2])
)
alpha_total5 = 30 / 14. * (
abs(alpha[0, 2]) + abs(alpha[1, 2]) + abs(alpha[2, 2]) +
abs(alpha[1, 0]) + abs(alpha[0, 1])
)
alpha_total9 = 30 / 20. * (
abs(alpha[0, 2]) + abs(alpha[1, 2]) + abs(alpha[2, 2]) +
abs(alpha[0, 0]) + abs(alpha[1, 0]) + abs(alpha[2, 0]) +
abs(alpha[0, 1]) + abs(alpha[1, 1]) + abs(alpha[2, 1])
)
alpha_total3[abs(alpha_total3) < 1] = 1e12
alpha_total5[abs(alpha_total3) < 1] = 1e12
alpha_total9[abs(alpha_total3) < 1] = 1e12
# choose from the different alpha_totals according to preference;
# see Ruggles GND density paper
yield 1.
return alpha_total9, alpha
@report_progress("building quaternion array")
def calc_quat_array(self):
"""Build quaternion array
"""
# create the array of quat objects
quats = Quat.create_many_quats(self.data.euler_angle)
yield 1.
return quats
def filter_data(self, misori_tol=5):
# Kuwahara filter
print("8 quadrants")
misori_tol *= np.pi / 180
misori_tol = np.cos(misori_tol / 2)
# store quat components in array
quat_comps = np.empty((4,) + self.shape)
for idx in np.ndindex(self.shape):
quat_comps[(slice(None),) + idx] = self.data.orientation[idx].quat_coef
# misorientation in each quadrant surrounding a point
mis_oris = np.zeros((8,) + self.shape)
for i in range(2, self.shape[0] - 2):
for j in range(2, self.shape[1] - 2):
ref_quat = quat_comps[:, i, j]
quadrants = [
quat_comps[:, i - 2:i + 1, j - 2:j + 1], # UL
quat_comps[:, i - 2:i + 1, j - 1:j + 2], # UC
quat_comps[:, i - 2:i + 1, j:j + 3], # UR
quat_comps[:, i - 1:i + 2, j:j + 3], # MR
quat_comps[:, i:i + 3, j:j + 3], # LR
quat_comps[:, i:i + 3, j - 1:j + 2], # LC
quat_comps[:, i:i + 3, j - 2:j + 1], # LL
quat_comps[:, i - 1:i + 2, j - 2:j + 1] # ML
]
for k, quats in enumerate(quadrants):
mis_oris_quad = np.abs(
np.einsum("ijk,i->jk", quats, ref_quat)
)
mis_oris_quad = mis_oris_quad[mis_oris_quad > misori_tol]
mis_oris[k, i, j] = mis_oris_quad.mean()
min_mis_ori_quadrant = np.argmax(mis_oris, axis=0)
# minMisOris = np.max(mis_oris, axis=0)
# minMisOris[minMisOris > 1.] = 1.
# minMisOris = 2 * np.arccos(minMisOris)
quat_comps_new = np.copy(quat_comps)
for i in range(2, self.shape[0] - 2):
for j in range(2, self.shape[1] - 2):
# if minMisOris[i, j] < misOriTol:
# continue
ref_quat = quat_comps[:, i, j]
quadrants = [
quat_comps[:, i - 2:i + 1, j - 2:j + 1], # UL
quat_comps[:, i - 2:i + 1, j - 1:j + 2], # UC
quat_comps[:, i - 2:i + 1, j:j + 3], # UR
quat_comps[:, i - 1:i + 2, j:j + 3], # MR
quat_comps[:, i:i + 3, j:j + 3], # LR
quat_comps[:, i:i + 3, j - 1:j + 2], # LC
quat_comps[:, i:i + 3, j - 2:j + 1], # LL
quat_comps[:, i - 1:i + 2, j - 2:j + 1] # ML
]
quats = quadrants[min_mis_ori_quadrant[i, j]]
mis_oris_quad = np.abs(
np.einsum("ijk,i->jk", quats, ref_quat)
)
quats = quats[:, mis_oris_quad > misori_tol]
avOri = np.einsum("ij->i", quats)
# avOri /= np.sqrt(np.dot(avOri, avOri))
quat_comps_new[:, i, j] = avOri
quat_comps_new /= np.sqrt(np.einsum("ijk,ijk->jk", quat_comps_new, quat_comps_new))
quat_array_new = np.empty(self.shape, dtype=Quat)
for idx in np.ndindex(self.shape):
quat_array_new[idx] = Quat(quat_comps_new[(slice(None),) + idx])
self.data.orientation = quat_array_new
return quats
@report_progress("finding grain boundaries")
def find_boundaries(self, misori_tol=10):
"""Find grain and phase boundaries
Parameters
----------
misori_tol : float
Critical misorientation in degrees.
"""
# TODO: what happens with non-indexed points
# TODO: grain boundaries should be calculated per crystal structure
misori_tol *= np.pi / 180
syms = self.primary_phase.crystal_structure.symmetries
num_syms = len(syms)
# array to store quat components of initial and symmetric equivalents
quat_comps = np.empty((num_syms, 4) + self.shape)
# populate with initial quat components
for i, row in enumerate(self.data.orientation):
for j, quat in enumerate(row):
quat_comps[0, :, i, j] = quat.quat_coef
# loop of over symmetries and apply to initial quat components
# (excluding first symmetry as this is the identity transformation)
for i, sym in enumerate(syms[1:], start=1):
# sym[i] * quat for all points (* is quaternion product)
quat_comps[i, 0] = (
quat_comps[0, 0]*sym[0] - quat_comps[0, 1]*sym[1] -
quat_comps[0, 2]*sym[2] - quat_comps[0, 3]*sym[3]
)
quat_comps[i, 1] = (
quat_comps[0, 0]*sym[1] + quat_comps[0, 1]*sym[0] -
quat_comps[0, 2]*sym[3] + quat_comps[0, 3]*sym[2]
)
quat_comps[i, 2] = (
quat_comps[0, 0]*sym[2] + quat_comps[0, 2]*sym[0] -
quat_comps[0, 3]*sym[1] + quat_comps[0, 1]*sym[3]
)
quat_comps[i, 3] = (
quat_comps[0, 0]*sym[3] + quat_comps[0, 3]*sym[0] -
quat_comps[0, 1]*sym[2] + quat_comps[0, 2]*sym[1]
)
# swap into positive hemisphere if required
quat_comps[i, :, quat_comps[i, 0] < 0] *= -1
# Arrays to store neighbour misorientation in positive x and y
# directions
misori_x = np.ones((num_syms, ) + self.shape)
misori_y = np.ones((num_syms, ) + self.shape)
# loop over symmetries calculating misorientation to initial
for i in range(num_syms):
for j in range(self.shape[1] - 1):
misori_x[i, :, j] = abs(np.einsum(
"ij,ij->j", quat_comps[0, :, :, j], quat_comps[i, :, :, j+1]
))
for j in range(self.shape[0] - 1):
misori_y[i, j] = abs(np.einsum(
"ij,ij->j", quat_comps[0, :, j], quat_comps[i, :, j+1]
))
misori_x[misori_x > 1] = 1
misori_y[misori_y > 1] = 1
# find max dot product and then convert to misorientation angle
misori_x = 2 * np.arccos(np.max(misori_x, axis=0))
misori_y = 2 * np.arccos(np.max(misori_y, axis=0))
# PHASE boundary POINTS
phase_im = self.data.phase
pb_im_x = np.not_equal(phase_im, np.roll(phase_im, -1, axis=1))
pb_im_x[:, -1] = False
pb_im_y = np.not_equal(phase_im, np.roll(phase_im, -1, axis=0))
pb_im_y[-1] = False
phase_boundaries = BoundarySet.from_image(self, pb_im_x, pb_im_y)
grain_boundaries = BoundarySet.from_image(
self,
(misori_x > misori_tol) | pb_im_x,
(misori_y > misori_tol) | pb_im_y
)
yield 1.
return phase_boundaries, grain_boundaries
@report_progress("constructing neighbour network")
def build_neighbour_network(self):
# create network
nn = nx.Graph()
nn.add_nodes_from(self.grains)
points_x = self.data.grain_boundaries.points_x
points_y = self.data.grain_boundaries.points_y
total_points_x = len(points_x)
total_points = total_points_x + len(points_y)
for i, points in enumerate((points_x, points_y)):
for i_point, (x, y) in enumerate(points):
# report progress
yield (i_point + i * total_points_x) / total_points
if (x == 0 or y == 0 or x == self.shape[1] - 1 or
y == self.shape[0] - 1):
# exclude boundary pixels of map
continue
grain_id = self.data.grains[y, x] - 1
nei_grain_id = self.data.grains[y + i, x - i + 1] - 1
if nei_grain_id == grain_id:
# ignore if neighbour is same as grain
continue
if nei_grain_id < 0 or grain_id < 0:
# ignore if not a grain (boundary points -1 and
# points in small grains -2)
continue
grain = self[grain_id]
nei_grain = self[nei_grain_id]
try:
# look up boundary segment if it exists
b_seg = nn[grain][nei_grain]['boundary']
except KeyError:
# neighbour relation doesn't exist so add it
b_seg = BoundarySegment(self, grain, nei_grain)
nn.add_edge(grain, nei_grain, boundary=b_seg)
# add the boundary point
b_seg.addBoundaryPoint((x, y), i, grain)
self.neighbour_network = nn
def plot_phase_boundary_map(self, dilate=False, **kwargs):
"""Plot phase boundary map.
Parameters
----------
dilate : bool
If true, dilate boundary.
kwargs
All other arguments are passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {
'vmax': 1,
'plot_colour_bar': True,
'cmap': 'gray'
}
plot_params.update(kwargs)
boundaries_image = self.data.phase_boundaries.image.astype(int)
if dilate:
boundaries_image = mph.binary_dilation(boundaries_image)
plot = MapPlot.create(self, boundaries_image, **plot_params)
return plot
def plot_boundary_map(self, **kwargs):
"""Plot grain boundary map.
Parameters
----------
kwargs
All arguments are passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {
'plot_gbs': True,
'boundaryColour': 'black'
}
plot_params.update(kwargs)
plot = MapPlot.create(self, None, **plot_params)
return plot
@report_progress("finding grains")
def find_grains(self, min_grain_size=10):
"""Find grains and assign IDs.
Parameters
----------
min_grain_size : int
Minimum grain area in pixels.
"""
# Initialise the grain map
# TODO: Look at grain map compared to boundary map
grains = np.zeros(self.shape, dtype=int)
grain_list = []
boundary_im_x = self.data.grain_boundaries.image_x
boundary_im_y = self.data.grain_boundaries.image_y
# List of points where no grain has be set yet
points_left = self.data.phase != 0
total_points = points_left.sum()
found_point = 0
next_point = points_left.tobytes().find(b'\x01')
# Start counter for grains
grain_index = 1
group_id = Datastore.generate_id()
# Loop until all points (except boundaries) have been assigned
# to a grain or ignored
i = 0
coords_buffer = np.zeros((boundary_im_y.size, 2), dtype=np.intp)
while found_point >= 0:
# Flood fill first unknown point and return grain object
seed = np.unravel_index(next_point, self.shape)
grain = Grain(grain_index - 1, self, group_id)
grain.data.point = flood_fill(
(seed[1], seed[0]), grain_index, points_left, grains,
boundary_im_x, boundary_im_y, coords_buffer
)
coords_buffer = coords_buffer[len(grain.data.point):]
if len(grain) < min_grain_size:
# if grain size less than minimum, ignore grain and set
# values in grain map to -2
for point in grain.data.point:
grains[point[1], point[0]] = -2
else:
# add grain to list and increment grain index
grain_list.append(grain)
grain_index += 1
# find next search point
points_left_sub = points_left.reshape(-1)[next_point + 1:]
found_point = points_left_sub.tobytes().find(b'\x01')
next_point += found_point + 1
# report progress
i += 1
if i == defaults['find_grain_report_freq']:
yield 1. - points_left_sub.sum() / total_points
i = 0
# Assign phase to each grain
for grain in grain_list:
phase_vals = grain.grain_data(self.data.phase)
if np.max(phase_vals) != np.min(phase_vals):
warn(f"Grain {grain.grain_id} could not be assigned a "
f"phase, phase vals not constant.")
continue
phase_id = phase_vals[0] - 1
if not (0 <= phase_id < self.num_phases):
warn(f"Grain {grain.grain_id} could not be assigned a "
f"phase, invalid phase {phase_id}.")
continue
grain.phase_id = phase_id
grain.phase = self.phases[phase_id]
## TODO: this will get duplicated if find grains called again
self.data.add_derivative(
grain_list[0].data, self.grain_data_to_map, pass_ref=True,
in_props={
'type': 'list'
},
out_props={
'type': 'map'
}
)
self._grains = grain_list
return grains
def plot_grain_map(self, **kwargs):
"""Plot a map with grains coloured.
Parameters
----------
kwargs
All arguments are passed to :func:`defdap.plotting.MapPlot.create`.
Returns
-------
defdap.plotting.MapPlot
"""
# Set default plot parameters then update with any input
plot_params = {
'clabel': "Grain number"
}
plot_params.update(kwargs)
plot = MapPlot.create(self, self.data.grains, **plot_params)
return plot
@report_progress("calculating grain mean orientations")
def calc_grain_av_oris(self):
"""Calculate the average orientation of grains.
"""
numGrains = len(self)
for iGrain, grain in enumerate(self):
grain.calc_average_ori()
# report progress
yield (iGrain + 1) / numGrains
@report_progress("calculating grain misorientations")
def calc_grain_mis_ori(self, calc_axis=False):
"""Calculate the misorientation within grains.
Parameters
----------
calc_axis : bool
Calculate the misorientation axis if True.
"""
num_grains = len(self)
for i_grain, grain in enumerate(self):
grain.build_mis_ori_list(calc_axis=calc_axis)
# report progress
yield (i_grain + 1) / num_grains
def plot_mis_ori_map(self, component=0, **kwargs):
"""Plot misorientation map.