/
tripletvote.py
1607 lines (1357 loc) · 57.2 KB
/
tripletvote.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
# This software was developed by employees of the US Naval Research Laboratory (NRL), an
# agency of the Federal Government. Pursuant to title 17 section 105 of the United States
# Code, works of NRL employees are not subject to copyright protection, and this software
# is in the public domain. PyEBSDIndex is an experimental system. NRL assumes no
# responsibility whatsoever for its use by other parties, and makes no guarantees,
# expressed or implied, about its quality, reliability, or any other characteristic. We
# would appreciate acknowledgment if the software is used. To the extent that NRL may hold
# copyright in countries other than the United States, you are hereby granted the
# non-exclusive irrevocable and unconditional right to print, publish, prepare derivative
# works and distribute this software, in any medium, or authorize others to do so on your
# behalf, on a royalty-free basis throughout the world. You may improve, modify, and
# create derivative works of the software or any portion of the software, and you may copy
# and distribute such modifications or works. Modified works should carry a notice stating
# that you changed the software and should note the date and nature of any such change.
# Please explicitly acknowledge the US Naval Research Laboratory as the original source.
# This software can be redistributed and/or modified freely provided that any derivative
# works bear some notice that they are derived from it, and any modified versions bear
# some notice that they have been modified.
#
# Author: David Rowenhorst;
# The US Naval Research Laboratory Date: 21 Aug 2020
"""Creation of look-up tables from phase information for band
indexing.
"""
from os import environ
from pathlib import PurePath
import platform
import tempfile
from timeit import default_timer as timer
import numpy as np
import numba
from pyebsdindex import crystal_sym, rotlib, crystallometry
__all__ = ["addphase", "BandIndexer"]
RADEG = 180.0/np.pi
tempdir = PurePath("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
tempdir = tempdir.joinpath('numba')
environ["NUMBA_CACHE_DIR"] = str(tempdir)
def addphase(libtype=None, phasename=None,
spacegroup=None,
latticeparameter=None,
polefamilies=None, nband_earlyexit = 10):
"""Return a band indexer for a phase.
Parameters
----------
libtype : str, optional
Shorthand definition of a phase. Options are FCC, BCC, or HCP.
phasename : str, optional
Phase name.
spacegroup : int, optional
Space group of the phase.
latticeparameter : np.ndarray, tuple, or list, optional
Lattice parameters (a, b, c, alpha, beta, gamma).
polefamilies : np.ndarray, tuple, or list, optional
Reflector families to use in indexing.
nband_earlyexit : int, optional
If this phase is first in a list of phases used in indexing, and
if this many bands are matched, the remaining phases in the list
will not be checked. Default is 10, unless ``libtype`` is
passed, in which case it is 8.
Returns
-------
BandIndexer
Band indexer for this phase.
"""
if libtype is not None:
#set up generic FCC
if str(libtype).upper() == 'FCC':
nband_earlyexit=8
if phasename is None:
phasename = 'FCC'
if spacegroup is None:
spacegroup = 225
if latticeparameter is None:
latticeparameter = np.array([1.0, 1.0, 1.0, 90.0, 90.0, 90.0])
else:
latticeparameter = np.array(latticeparameter)
if polefamilies is None:
polefamilies = np.array([[0, 0, 2], [1, 1, 1], [0, 2, 2], [1, 1, 3]]).astype(np.int32)
else:
polefamilies = np.atleast_2d(np.array(polefamilies))
# Set up a generic BCC
if str(libtype).upper() == 'BCC':
nband_earlyexit=8
if phasename is None:
phasename = 'BCC'
if spacegroup is None:
spacegroup = 229
if latticeparameter is None:
latticeparameter = np.array([1.0, 1.0, 1.0, 90.0, 90.0, 90.0])
else:
latticeparameter = np.array(latticeparameter)
if polefamilies is None:
polefamilies = np.array([[0, 1, 1], [0, 0, 2], [1, 1, 2], [0, 1, 3]]).astype(np.int32)
else:
polefamilies = np.atleast_2d(np.array(polefamilies))
# Set up a generic HCP
if str(libtype).upper() == 'HCP':
if phasename is None:
phasename = 'HCP'
if spacegroup is None:
spacegroup = 194
if latticeparameter is None:
latticeparameter = np.array([1.0, 1.0, 1.63, 90.0, 90.0, 120.0])
else:
latticeparameter = np.array(latticeparameter)
if polefamilies is None:
polefamilies = np.array([ [1, 0, -1, 0], [0, 0, 0, 2],[1, 0, -1, 1], [1, 0, -1, 2], [1, 1, -2, 0],
[1, 0, -1, 3], [1, 1,-2, 2], [2,0,-2,1]]).astype(np.int32)
else:
polefamilies = np.atleast_2d(np.array(polefamilies))
else:
if spacegroup is None:
return addphase(libtype='FCC', latticeparameter=latticeparameter, polefamilies=polefamilies, phasename = phasename)
if latticeparameter is None:
latticeparameter = np.array([1.0, 1.0, 1.0, 90.0, 90.0, 90.0])
if polefamilies is None:
polefamilies = np.array([[0, 0, 2], [1, 1, 1], [0, 2, 2], [1, 1, 3]]).astype(np.int32)
triplib = BandIndexer(phasename=phasename,
spacegroup=spacegroup,
latticeparameter=latticeparameter,
polefamilies=np.atleast_2d(polefamilies),
nband_earlyexit=nband_earlyexit)
triplib.build_trip_lib()
return triplib
class BandIndexer():
#def __init__(self, libType='FCC', phaseName=None, laticeParameter = None):
def __init__(self,
phasename=None,
spacegroup = None,
latticeparameter=None,
polefamilies = None,
angTol=2.0,
nband_earlyexit = 8):
self.phaseName = None # User provided name of the phase.
self.spacegroup = None # space group id 1-230
self.latticeparameter = None # 6 element array for the lattice parameter.
self.polefamilies = None # array of integer pole normals that should have reflections
self.npolefamilies = None # number of unique reflector families
self.crystalmats = None # store the four crystal matrices useful for angle/cartisian conversions.
self.lauecode = None # Laue code for the space group (following DREAM.3D notation.
self.qsymops = None # array of quaternions that represent proper symmetry operations for the laue group
self.pointgroup = ' ' # point group nomenclature
self.pointgroupid = None
self.angTol = angTol
self.nband_earlyexit = nband_earlyexit
self.high_fidelity = True
# many objects to hold the information about the reflecting poles, angles between them ...
self.angpairs = None # dictionary that will store the possible unique angles between all pole families.
self.angtriplets = None # dictionary that will store all possible angle triplets within the pole family.
self.completelib = None # dictionary that will hold all possible angles (non-unique) between the families and
# all possible poles
# these Look Up Tables are used in the sorting/unsorting of angle triplets.
luta = np.array([[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]])
lutb = np.array([[0, 1, 2], [1, 0, 2], [0, 2, 1], [2, 0, 1], [1, 2, 0], [2, 1, 0]])
lut = np.zeros((3, 3, 3, 3), dtype=np.int64)
for i in range(6):
lut[:, luta[i, 0], luta[i, 1], luta[i, 2]] = lutb[i, :]
self.lut = np.asarray(lut).copy()
if phasename is None:
self.phasename = ' '
else:
self.phasename = str(phasename)
if latticeparameter is not None:
self.setlatticeparameter(latticeparameter)
if spacegroup is not None:
self.setspacegroup(spacegroup)
if polefamilies is not None:
self.setpolefamilies(polefamilies)
def setlatticeparameter(self, latticeparameter):
self.latticeparameter = np.array(latticeparameter)
self.crystalmats = crystallometry.Crystal(self.phaseName,
self.latticeparameter[0],
self.latticeparameter[1],
self.latticeparameter[2],
self.latticeparameter[3],
self.latticeparameter[4],
self.latticeparameter[5])
def setspacegroup(self, spacegroup = 225):
self.spacegroup = spacegroup
self.lauecode = crystal_sym.spacegroup2lauenumber(self.spacegroup)
self.qsymops = crystal_sym.laueid2symops(self.lauecode)
def setpolefamilies(self, reflectors):
# check if any of the poles are length 0
poles = np.atleast_2d(np.array(reflectors)).astype(float)
mx = np.max(np.abs(poles), axis=1)
wh = np.nonzero(mx > 1e-6)[0]
if wh.size == 0:
return
poles = poles[wh, :]
# check for inversion redundancy
npoles = poles / (np.sqrt((poles ** 2).sum(-1))[..., np.newaxis])
npoles = np.atleast_2d(npoles)
keep = np.ones(npoles.shape[0], dtype = int)
dot = np.abs(npoles.dot(npoles.T))
for i in range(npoles.shape[0]):
wh = np.nonzero(dot[i, i+1:] > 0.99999)[0]
if len(wh) > 0:
keep[i+1+wh] = 0
whk = np.nonzero(keep)
poles = poles[whk,:]
self.polefamilies = np.rint(poles * (1.+ 1e-6)).astype(int)
# def build_fcc(self):
# if self.phaseName is None:
# self.phaseName = 'FCC'
# self.pointgroup = "Cubic m3m"
# self.pointgroupid = 131
# self.spacegroup = 225
# self.lauecode = crystal_sym.spacegroup2lauenumber(self.spacegroup)
# self.qsymops = crystal_sym.laueid2symops(self.lauecode)
# poles = np.array([[0,0,2], [1,1,1], [0,2,2], [1,1,3]])
# self.build_trip_lib(poles)
#
# def build_dc(self):
# if self.phaseName is None:
# self.phaseName = 'Diamond Cubic'
# self.pointgroup = "Cubic m3m"
# self.pointgroupid = 131
# self.spacegroup = 227
# self.lauecode = crystal_sym.spacegroup2lauenumber(self.spacegroup)
# self.qsymops = crystal_sym.laueid2symops(self.lauecode)
# poles = np.array([[1, 1, 1], [0, 2, 2], [0, 0, 4], [1, 1, 3], [2, 2, 4], [1, 3, 3]])
# self.build_trip_lib(poles)
#
# def build_bcc(self):
# if self.phaseName is None:
# self.phaseName = 'BCC'
# self.pointgroup = "Cubic m3m"
# self.pointgroupid = 131
# self.spacegroup = 229
# self.lauecode = crystal_sym.spacegroup2lauenumber(self.spacegroup)
# self.qsymops = crystal_sym.laueid2symops(self.lauecode)
# poles = np.array([[0,1,1],[0,0,2],[1,1,2],[0,1,3]])
# self.build_trip_lib(poles)
# def build_hcp(self):
# if self.phaseName is None:
# self.phaseName = 'HCP'
# self.pointgroup = "Hexagonal 6/mmm"
# self.spacegroup = 194
# self.lauecode = crystal_sym.spacegroup2lauenumber(self.spacegroup)
# self.qsymops = crystal_sym.laueid2symops(self.lauecode)
# poles4 = np.array([[1,0, -1, 0], [1, 0, -1, 1], [0,0, 0, 2], [1, 0, -1, 3], [1,1,-2,0], [1,0,-1,2]])
# self.build_hex_trip_lib(poles4)
#
# def build_hex_trip_lib(self, poles4):
# poles3 = crystal_sym.hex4poles2hex3poles(poles4)
# self.build_trip_lib(poles3)
# p3temp = self.polefamilies
# p4temp = crystal_sym.hex3poles2hex4poles(p3temp)
# self.polefamilies = p4temp
def build_trip_lib(self):
if self.spacegroup is None:
print('No Space Group ID is set')
return
if self.latticeparameter is None:
print('No lattice parameter is set')
return
if self.polefamilies is None:
print('No pole familes are set')
return
crystalmats = self.crystalmats
poles = np.array(self.polefamilies)
if (self.lauecode == 62) or (self.lauecode == 6):
if self.polefamilies.shape[-1] == 4:
poles = crystal_sym.hex4poles2hex3poles(np.array(self.polefamilies))
poles = poles.reshape((-1, 3))
npoles = poles.shape[0]
sympoles = [] # list of all HKL variants which does not count the invariant pole as unique.
sympolesComplete = [] # list of all HKL variants with no duplicates
nFamComplete = np.zeros(npoles, dtype = np.int32) # number of
nFamily = np.zeros(npoles, dtype = np.int32)
polesFlt = np.array(poles, dtype=np.float32) # convert the input poles to floating point (but still HKL int values)
for i in range(npoles):
family = self._symrotpoles(polesFlt[i, :], crystalmats) #rotlib.quat_vector(symmetry,polesFlt[i,:])
uniqHKL = self._hkl_unique(family, reduceInversion=False)
uniqHKL = np.flip(uniqHKL, axis=0)
sympolesComplete.append(uniqHKL)
nFamComplete[i] = np.reshape(sympolesComplete[-1],(-1,3)).shape[0] #np.int32((sympolesComplete[-1]).size/3)
uniqHKL2 = self._hkl_unique(family, reduceInversion=True, rMT = crystalmats.reciprocalMetricTensor)
nFamily[i] = np.reshape(uniqHKL2,(-1,3)).shape[0] #np.int32(uniqHKL2.size/3)
sign = np.squeeze(self._calc_pole_dot_int(uniqHKL2, polesFlt[i, :], rMetricTensor=crystalmats.reciprocalMetricTensor))
sign = np.atleast_1d(sign)
whmx = (np.abs(sign)).argmax()
sign = np.round(sign[whmx])
uniqHKL2 *= sign
sympoles.append(np.round(uniqHKL2))
#sympolesN.append(self.xstalPlane2cart(family))
sympolesComplete = np.concatenate(sympolesComplete)
#print(sympolesComplete)
famindx = np.concatenate( ([0],np.cumsum(nFamComplete)) )
angs = []
familyID = []
polePairs = []
for i in range(npoles):
for j in range(i, npoles):
fampoles = sympolesComplete[famindx[j]:famindx[j+1], :].astype(np.float32)
#print('______', i,j)
#print(np.round(fampoles).astype(int))
ang = self._calc_pole_dot_int(polesFlt[i, :], fampoles, rMetricTensor=crystalmats.reciprocalMetricTensor) # for each input pole, calculate
ang = np.squeeze(ang)
ang = np.clip(ang, -1.0, 1.0)
#sign = (ang >= 0).astype(np.float32) - (ang < 0).astype(np.float32)
#sign = np.atleast_1d(sign)
ang = np.round(np.arccos(np.abs(ang))*RADEG*100).astype(np.int32) # get the unique angles between the input
ang = np.atleast_1d(ang)
# pole, and the family poles. Angles within 0.01 deg are taken as the same.
unqang, argunq = np.unique(ang, return_index=True)
unqang = unqang/100.0 # revert back to the actual angle in degrees.
wh = np.nonzero(unqang > 1.0)[0]
nwh = wh.size
if nwh > 0:
#sign = sign[wh]
#sign = sign.reshape(nwh,1)
temp = np.zeros((nwh, 2, 3))
temp[:,0,:] = np.broadcast_to(poles[i,:], (nwh, 3))
temp[:,1,:] = np.broadcast_to(fampoles[argunq[wh],:], (nwh, 3))
for k in range(nwh):
angs.append(unqang[wh[k]])
familyID.append([i,j])
polePairs.append(temp[k,:,:])
angs = np.atleast_1d(np.squeeze(np.array(angs)))
nangs = angs.size
familyID = np.array(familyID)
polePairs = np.array(polePairs)
nFamilyID = np.bincount(np.squeeze(familyID[:,0]).astype(int), minlength=int(npoles))
#stuff, nFamilyID = np.unique(familyID[:,0], return_counts=True)
indx0FID = (np.concatenate( ([0],np.cumsum(nFamilyID)) ))[0:npoles]
#print(familyID)
#print(nFamilyID)
#print(indx0FID)
#This completely over previsions the arrays, this is essentially
#N Choose K with N = number of angles and K = 3
nlib = npoles*np.prod(np.arange(3, dtype=np.int64)+(nangs-2+1))/np.compat.long(np.math.factorial(3))
nlib = nlib.astype(int)
libANG = np.zeros((nlib, 3))
libID = np.zeros((nlib, 3), dtype=int)
counter = 0
# now actually catalog all the triplet angles.
for i in range(npoles):
if nFamilyID[i] <= 0:
continue
id0 = familyID[indx0FID[i], 0]
for j in range(0,nFamilyID[i]):
ang0 = angs[j + indx0FID[i]]
id1 = familyID[j + indx0FID[i], 1]
for k in range(j, nFamilyID[i]):
ang1 = angs[k + indx0FID[i]]
id2 = familyID[k + indx0FID[i], 1]
whjk = np.nonzero( np.logical_and( familyID[:,0] == id1, familyID[:,1] == id2 ))[0]
for q in range(whjk.size):
ang2 = angs[whjk[q]]
libANG[counter, :] = np.array([ang0, ang1, ang2])
libID[counter, :] = np.array([id0, id1, id2])
counter += 1
libANG = libANG[0:counter, :]
libID = libID[0:counter, :]
libANG, libID = self._sortlib_id(libANG, libID, findDups = True) # sorts each row of the library to make sure
# the triplets are in increasing order.
#print(libANG)
#print(libANG.shape)
# now make a table of the angle between all the poles (allowing inversino)
angTable = self._calc_pole_dot_int(sympolesComplete, sympolesComplete, rMetricTensor=crystalmats.reciprocalMetricTensor)
angTable = np.arccos(angTable)*RADEG
famindx0 = ((np.concatenate( ([0],np.cumsum(nFamComplete)) ))[0:-1]).astype(dtype=np.int64)
cartPoles = self._xstalplane2cart(sympolesComplete, rStructMatrix=crystalmats.reciprocalStructureMatrix)
cartPoles /= np.linalg.norm(cartPoles, axis = 1).reshape(np.int64(cartPoles.size/3),1)
completePoleFamId = np.zeros(sympolesComplete.shape[0], dtype=np.int32)
for i in range(npoles):
for j in range(nFamComplete[i]):
completePoleFamId[j+famindx0[i]] = i
self.completelib = {
'poles' : sympolesComplete,
'polesCart': cartPoles,
'familyid': completePoleFamId,
'angTable' : angTable,
'nFamily' : nFamComplete,
'famIndex' : famindx0
}
self.angpairs = {
'familyid': familyID,
'polepairs':polePairs,
'angles':angs
}
self.angtriplets = {
'angles': libANG,
'familyid': libID
}
if (self.lauecode == 62) or (self.lauecode == 6):
poles = crystal_sym.hex3poles2hex4poles(poles)
self.polefamilies = poles
self.npolefamilies = npoles
#self.angles = angs
#self.polePairs = polePairs
#self.angleFamilyID = familyID
#self.tripAngles = libANG
#self.tripID = libID
def bandindex(self, band_norms, band_intensity = None, band_widths=None, verbose=0):
tic0 = timer()
nfam = self.polefamilies.shape[0]
bandnorms = np.squeeze(band_norms)
n_bands = np.reshape(bandnorms, (-1,3)).shape[0] #np.int64(bandnorms.size/3)
if band_intensity is None:
band_intensity = np.ones((n_bands))
tic = timer()
bandangs = np.abs(bandnorms.dot(bandnorms.T))
bandangs = np.clip(bandangs, -1.0, 1.0)
bandangs = np.arccos(bandangs)*RADEG
tripangs = self.angtriplets['angles']
tripid = self.angtriplets['familyid']
pairangs = self.angpairs['angles']
pairfam = self.angpairs['familyid']
accumulator, bandFam, bandRank, band_cm, accumulator_nw = self._tripvote_numba(bandangs, self.lut, self.angTol, tripangs, tripid, nfam, n_bands)
#accumulator, bandFam, bandRank, band_cm = self._pairvote_numba(bandangs, self.angTol, pairangs, pairfam,
# nfam, n_bands)
if verbose > 2:
print('band Vote time:',timer() - tic)
if verbose > 3:
with np.printoptions(precision=2, suppress=True):
print('___Accumulator___')
print(accumulator)
print('___Band Rank___')
print(bandRank)
print('___Band Family ID___')
print(bandFam)
tic = timer()
sumaccum = np.sum(accumulator)
bandRank_arg = np.argsort(bandRank).astype(np.int64) # n_bands - np.arange(n_bands, dtype=np.int64) #
test = 0
fit = 1000.0
nMatch = -1
avequat = np.zeros(4, dtype=np.float32)
avequat[0] = 1.0
polematch = np.zeros([n_bands], dtype = int)-1
whGood = -1
angTable = self.completelib['angTable']
sztable = angTable.shape
famIndx = self.completelib['famIndex']
nFam = self.completelib['nFamily']
polesCart = self.completelib['polesCart']
angTol = self.angTol
n_band_early = np.int64(self.nband_earlyexit)
# this will check the vote, and return the exact band matching to specific poles of the best fitting solution.
fit, polematch, nMatch, whGood, ij, R, fitb = \
self._assign_bands_nb(polesCart, bandRank_arg, bandFam, famIndx, nFam, angTable, bandnorms, angTol, n_band_early)
if verbose > 3:
#print(rotlib.om2qu(R))
#print(polematch)
#print(whGood)
#print(fitb)
print('___Assigned Band___')
print(self.completelib['familyid'][polematch])
acc_correct = np.sum( np.array(self.completelib['familyid'][polematch] == bandFam).astype(int)).astype(int)
if verbose > 2:
#print(polematch)
#print(fit, fitb, fitb[whGood])
print('band index: ',timer() - tic)
tic = timer()
cm2 = 0.0
if nMatch >=2:
if self.high_fidelity == True:
score = accumulator[[self.completelib['familyid'][polematch[whGood]]], [whGood]]
score /= accumulator_nw[[self.completelib['familyid'][polematch[whGood]]], [whGood]] + 1.0e-6
score = np.squeeze(score)
srt = np.flip(np.argsort(score))
#print(srt+1)
#print(score[srt])
#print(band_intensity[whGood[srt]])
#srt = np.flip(np.argsort(band_intensity[whGood]))
whgood6 = whGood[srt[0:np.min([6, whGood.shape[0]])]]
#if verbose > 2:
# print("Good bands:", whGood+1)
# print("Fit Bands: ", whgood6+1)
#weights6 = score[srt[0:np.min([6, whGood.shape[0]])]]
weights6 = band_intensity[whgood6]
weights6 -= weights6.min()
weights6 *= 1/weights6.max()
#weights6 += 1
weights6 = np.exp(weights6**2)
#weights6 = np.exp(weights6)
pflt6 = (np.asarray(polesCart[polematch[whgood6], :], dtype=np.float64))
bndnorm6 = (np.asarray(bandnorms[whgood6, :], dtype=np.float64))
avequat, fit = self._refine_orientation_quest(bndnorm6, pflt6, weights=weights6)
#fitfull = self._fitcheck(avequat,
# np.asarray(bandnorms[whGood, :]), np.asarray(polesCart[polematch[whGood], :] ))
fit = np.arccos(np.clip(fit, -1.0, 1.0))*RADEG
else:
avequat = rotlib.om2qu(R)
whmatch = np.nonzero(polematch >= 0)[0]
cm = np.mean(band_cm[whmatch])
whfam = self.completelib['familyid'][polematch[whmatch]]
cm2 = np.sum(accumulator[[whfam], [whmatch]]).astype(np.float32)
cm2 /= np.sum(accumulator.clip(1))
if verbose > 2:
print('refinement: ', timer() - tic)
print('all: ',timer() - tic0)
return avequat, fit, cm2, polematch, nMatch, ij, acc_correct #sumaccum
def _symrotpoles(self, pole, crystalmats):
polecart = np.matmul(crystalmats.reciprocalStructureMatrix, np.array(pole).T)
sympolescart = rotlib.quat_vector(self.qsymops, polecart)
return np.transpose(np.matmul(crystalmats.invReciprocalStructureMatrix, sympolescart.T))
def _symrotdir(self, pole, crystalmats):
polecart = np.matmul(crystalmats.directStructureMatrix, np.array(pole).T)
sympolescart = rotlib.quat_vector(self.qsymops, polecart)
return np.transpose(np.matmul(crystalmats.invDirectStructureMatrix, sympolescart.T))
def _hkl_unique(self, poles, reduceInversion=True, rMT=np.identity(3)):
"""When given a list of integer HKL poles (plane normals), will
return only the unique HKL variants.
Parameters
----------
poles : np.ndarray
(n, 3) in HKL integer form.
reduceInversion : bool, optional
If True, then any inverted crystal pole will also be removed
from the unique list.
rMT : np.ndarray
Reciprocol metric tensor. Needed to calculated the angle between
poles.
Returns
-------
np.ndarray
(n, 3) in HKL integer form of the unique poles.
"""
polesout = poles.reshape((-1, 3))
intPoles = polesout.round().astype(np.int32)
mn = intPoles.min()
intPoles -= mn
basis = intPoles.max()+1
basis3 = np.array([1,basis, basis**2])
test = intPoles.dot(basis3)
if polesout.shape[0] > 1:
_, unq = np.unique(test, return_index=True)
polesout = polesout[unq]
if reduceInversion:
family = polesout
nf = family.shape[0]
test = self._calc_pole_dot_int(family, family, rMetricTensor = rMT)
testSum = np.sum( (test < -0.99999).astype(np.int32)*np.arange(nf).reshape(1,nf), axis = 1)
whpos = np.nonzero( np.logical_or(testSum < np.arange(nf), (testSum == 0)))[0]
polesout = polesout[whpos, :]
return polesout
def _calc_pole_dot_int(self, poles1, poles2, rMetricTensor = np.identity(3)):
p1 = poles1.reshape(-1, 3)
p2 = poles2.reshape(-1, 3)
n1 = p1.shape[0]
n2 = p2.shape[0]
t1 = p1.dot(rMetricTensor)
t2 = rMetricTensor.dot(p2.T)
dot = t1.dot(p2.T)
dotnum = np.sqrt(np.diag(t1.dot(p1.T)))
dotnum = dotnum.reshape(n1,1)
dotnum2 = np.sqrt(np.diag(p2.dot(t2)))
dotnum2 = dotnum2.reshape(1,n2)
dotnum = dotnum.dot(dotnum2)
dot /= dotnum
dot = np.clip(dot, -1.0, 1.0)
return dot
def _xstalplane2cart(self, poles, rStructMatrix = np.identity(3)):
polesout = rStructMatrix.dot(poles.T)
return np.transpose(polesout)
def _sortlib_id(self, libANG, libID, findDups = False):
# will make sure that triplets are ordered from lowest to highest
# and maintain the pole family id
# optionally will locate any duplicates in the triplet list.
# LUTA = np.array([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]])
# LUTB = np.array([[0,1,2],[1,0,2],[0,2,1],[2,0,1],[1,2,0],[2,1,0]])
#
# LUT = np.zeros((3,3,3,3), dtype=np.int64)
# for i in range(6):
# LUT[:, LUTA[i,0], LUTA[i,1], LUTA[i,2]] = LUTB[i,:]
lut = self.lut
ntrips = np.int64(libANG.size / 3)
for i in range(ntrips):
temp = np.squeeze(libANG[i,:])
srt = np.argsort(temp)
libANG[i,:] = temp[srt]
srt2 = np.squeeze(lut[:,srt[0], srt[1], srt[2]])
temp2 = np.squeeze(libID[i,:])
temp2 = temp2[srt2]
libID[i,:] = temp2
if findDups == True:
angID = np.sum(np.round(libANG*100), axis = 1).astype(np.longlong)
basis = np.longlong(libID.max() + 1)
libID_ID = libID.dot(np.array([1,basis, basis**2]))
UID = np.ceil(np.log10(libID_ID.max()))
UID = np.where(UID > 2, UID, 2)
UID = (angID * 10**UID) + libID_ID
stuff, unq = np.unique(UID, return_index=True)
libANG = libANG[unq, :]
libID = libID[unq,:]
libID_ID = libID_ID[unq]
srt = np.argsort(libID_ID)
libANG = libANG[srt, :]
libID = libID[srt, :]
return (libANG, libID)
# def band_index(self,bandnorms,bnd1,bnd2,familyLabel,angTol=3.0, verbose = 0):
#
# #nBands = np.int32(bandnorms.size/3)
# angTable = self.tripLib.completelib['angTable']
# sztable = angTable.shape
# #whGood = -1
# famIndx = self.tripLib.completelib['famIndex']
# nFam = self.tripLib.completelib['nFamily']
# poles = self.tripLib.completelib['polesCart']
# #ang01 = 0.0
# # need to check that the two selected bands are not parallel.
# #v0 = bandnorms[bnd1, :]
# #f0 = familyLabel[bnd1]
# #v1 = bandnorms[bnd2, :]
# #f1 = familyLabel[bnd2]
# #ang01 = np.clip(np.dot(v0, v1), -1.0, 1.0)
# #ang01 = np.arccos(ang01)*RADEG
# #if ang01 < angTol: # the two poles are parallel, send in another two poles if available.
# # return 360.0, 0, whGood, -1
#
# #wh01 = np.nonzero(np.abs(angTable[famIndx[f0], famIndx[f1]:np.int(famIndx[f1]+nFam[f1])] - ang01) < angTol)[0]
#
# #n01 = wh01.size
# #if n01 == 0:
# # return 360.0, 0, whGood, -1
#
# #wh01 += famIndx[f1]
# #p0 = poles[famIndx[f0], :]
# #print('pre first loop: ',timer() - tic)
# #tic = timer()
# # place numba code here ...
#
#
#
# #fit, polematch, R, nGood, whGood = self.band_vote_refine_loops1(poles,v0,v1, p0, wh01, bandnorms, angTol)
# fit,polematch,R,nGood,whGood = self.band_vote_refine_loops1(poles, bnd1, bnd2, familyLabel, famIndx, nFam, angTable, bandnorms, angTol)
#
# #print('numba first loops',timer() - tic)
# #whGood = np.nonzero(angFit < angTol)[0]
# #nGood = np.int64(whGood.size)
# #if nGood < 3:
# # return 360.0, -1, -1, -1
#
# #fit = np.mean(angFit[whGood])
# #print('all bindexed time', timer()-tic0)
# return fit, nGood, whGood, polematch
def _refine_orientation(self, bandnorms, whGood, polematch):
tic = timer()
poles = self.tripLib.completelib['polesCart']
nGood = whGood.size
n2Fit = np.int64(np.product(np.arange(2)+(nGood-2+1))/np.int64(2))
whGood = np.asarray(whGood,dtype=np.int64)
#AB, ABgood = self.orientation_refine_loops_am(nGood,whGood,poles,bandnorms,polematch,n2Fit)
# tic = timer()
# quats = rotlib.om2quL(AB[ABgood.nonzero()[0], :, :])
# print("om2qu", timer() - tic)
# tic = timer()
# avequat = rotlib.quatave(quats)
AB, weights = self._orientation_refine_loops_am(nGood, whGood, poles, bandnorms, polematch, n2Fit)
wh_weight = np.nonzero(weights < 359.0)[0]
quats = rotlib.om2quL(AB[wh_weight, :, :])
expw = weights[wh_weight]
rng = expw.max()-expw.min()
#print(rng, len(wh_weight))
if rng > 1e-6:
expw -= expw.min()
#print(np.arccos(1.0 - expw)*RADEG)
expw = np.exp(-expw/(0.5*(rng)))
expw /= np.sum(expw)
#print(quats)
#print(expw)
#print(expw*len(wh_weight))
avequat = rotlib.quatave(quats * np.expand_dims(expw, axis=-1))
#print(avequat)
else:
avequat = rotlib.quatave(quats)
test = rotlib.quat_vectorL(avequat,bandnorms[whGood,:])
tic = timer()
test = np.sum(test * poles[polematch[whGood], :], axis = 1)
test = np.arccos(np.clip(test, -1.0, 1.0))*RADEG
fit = np.mean(test)
#print('fitting: ',timer() - tic)
return avequat, fit
def _refine_orientation_quest(self, bandnorms, polecartmatch, weights = None):
tic = timer()
if weights is None:
weights = np.ones((bandnorms.shape[0]), dtype=np.float64)
weightsn = np.asarray(weights, dtype=np.float64)
weightsn /= np.sum(weightsn)
#print(weightsn)
pflt = np.asarray(polecartmatch, dtype=np.float64)
bndnorm = np.asarray(bandnorms, dtype=np.float64)
avequat, fit = self._orientation_quest_nb(pflt, bndnorm, weightsn)
return avequat, fit
@staticmethod
@numba.jit(nopython=True, cache=True, fastmath=True, parallel=False)
def _orientation_quest_nb(polescart, bandnorms, weights):
# this uses the Quaternion Estimator AKA quest algorithm.
pflt = np.asarray(polescart, dtype=np.float64)
bndnorm = np.asarray(bandnorms, dtype=np.float64)
npoles = pflt.shape[0]
wn = (np.asarray(weights, dtype=np.float64)).reshape(npoles, 1)
# wn = np.ones((nGood,1), dtype=np.float32)/np.float32(nGood) #(weights[whGood]).reshape(nGood,1)
wn /= np.sum(wn)
I = np.zeros((3, 3), dtype=np.float64)
I[0, 0] = 1.0;
I[1, 1] = 1.0;
I[2, 2] = 1.0
q = np.zeros((4), dtype=np.float64)
B = (wn * bndnorm).T @ pflt
S = B + B.T
z = np.asarray(np.sum(wn * np.cross(bndnorm, pflt), axis=0), dtype=np.float64)
S2 = S @ S
det = np.linalg.det(S)
k = (S[1, 1] * S[2, 2] - S[1, 2] * S[2, 1]) + (S[0, 0] * S[2, 2] - S[0, 2] * S[2, 0]) + (
S[0, 0] * S[1, 1] - S[1, 0] * S[0, 1])
sig = 0.5 * (S[0, 0] + S[1, 1] + S[2, 2])
sig2 = sig * sig
d = z.T @ S2 @ z
c = det + (z.T @ S @ z)
b = sig2 + (z.T @ z)
a = sig2 - k
lam = 1.0
tol = 1.0e-12
iter = 0
dlam = 1e6
# for i in range(10):
while (dlam > tol) and (iter < 10):
lam0 = lam
lam = lam - (lam ** 4 - (a + b) * lam ** 2 - c * lam + (a * b + c * sig - d)) / (
4 * lam ** 3 - 2 * (a + b) * lam - c)
dlam = np.fabs(lam0 - lam)
iter += 1
beta = lam - sig
alpha = lam ** 2 - sig2 + k
gamma = (lam + sig) * alpha - det
X = np.asarray((alpha * I + beta * S + S2), dtype=np.float64) @ z
qn = np.float64(0.0)
qn += gamma ** 2 + X[0] ** 2 + X[1] ** 2 + X[2] ** 2
qn = np.sqrt(qn)
q[0] = gamma
q[1:4] = X[0:3]
q /= qn
if (np.sign(gamma) < 0):
q *= -1.0
# polesrot = rotlib.quat_vectorL1N(q, pflt, npoles, np.float64, p=1)
# pdot = np.sum(polesrot*bndnorm, axis = 1, dtype=np.float64)
return q, lam # , pdot
@staticmethod
@numba.jit(nopython=True, cache=True,fastmath=True,parallel=False)
def _tripvote_numba(bandangs, LUT, angTol, tripAngles, tripID, nfam, n_bands):
LUTTemp = np.asarray(LUT).copy()
accumulator = np.zeros((nfam, n_bands), dtype=np.float32)
accumulatorW = np.zeros((nfam, n_bands), dtype=np.float32)
tshape = np.shape(tripAngles)
ntrip = int(tshape[0])
#count = 0.0
#angTest2 = np.zeros(ntrip, dtype=numba.boolean)
#angTest2 = np.empty(ntrip,dtype=numba.boolean)
angTest0 = np.zeros((3), dtype=np.float32)
for i in range(n_bands):
for j in range(i + 1,n_bands):
for k in range(j + 1,n_bands):
angtri = np.array([bandangs[i,j],bandangs[i,k],bandangs[j,k]], dtype=np.float32)
srt = angtri.argsort(kind='quicksort') #np.array(np.argsort(angtri), dtype=numba.int64)
srt2 = np.asarray(LUTTemp[:,srt[0],srt[1],srt[2]], dtype=np.int64).copy()
unsrtFID = np.argsort(srt2,kind='quicksort').astype(np.int64)
angtriSRT = np.asarray(angtri[srt])
#angTest0 = (np.abs(tripAngles - angtriSRT)).astype(np.float32)
#print(angTest0.shape)
#angTest = (angTest0 <= angTol)#.astype(np.int)
for q in range(ntrip):
#print('____')
#print(tripAngles[q,:], angtriSRT)
test1 = np.abs(tripAngles[q,0] - angtriSRT[0])
if test1 > angTol:
continue
else:
angTest0[0] = test1
test2 = np.abs(tripAngles[q, 1] - angtriSRT[1])
if test2 > angTol:
continue
else:
angTest0[1] = test2
test3 = np.abs(tripAngles[q, 2] - angtriSRT[2])
if test3 > angTol:
continue
else:
angTest0[2] = test3
#print('here')
#angTest2 = (angTest[q,0] + angTest[q,1] + angTest[q,2]) == 3
#if angTest2:
f = tripID[q,:]
f = f[unsrtFID]
#print(angTest0[q,:])
w1 = ( angTol - 0.5*(angTest0[0] + angTest0[1]) )
w2 = ( angTol - 0.5*(angTest0[0] + angTest0[2]) )
w3 = ( angTol - 0.5*(angTest0[1] + angTest0[2]) )
#print(w1, w2, w3)
accumulatorW[f[0],i] += w1
accumulatorW[f[1],j] += w2
accumulatorW[f[2],k] += w3
accumulator[f[0], i] += 1
accumulator[f[1], j] += 1
accumulator[f[2], k] += 1
t1 = False
t2 = False
t3 = False
if np.abs(angtriSRT[0] - angtriSRT[1]) < angTol:
accumulatorW[f[0],j] += w1
accumulatorW[f[1],i] += w2
accumulatorW[f[2],k] += w3
accumulator[f[0], j] += 1
accumulator[f[1], i] += 1
accumulator[f[2], k] += 1
t1 = True
if np.abs(angtriSRT[1] - angtriSRT[2]) < angTol:
accumulatorW[f[0],i] += w1
accumulatorW[f[1],k] += w2
accumulatorW[f[2],j] += w3
accumulator[f[0], i] += 1
accumulator[f[1], k] += 1
accumulator[f[2], j] += 1
t2 = True
if np.abs(angtriSRT[2] - angtriSRT[0]) < angTol:
accumulatorW[f[0],k] += w1
accumulatorW[f[1],j] += w2
accumulatorW[f[2],i] += w3
accumulator[f[0], k] += 1
accumulator[f[1], j] += 1
accumulator[f[2], i] += 1
t3 = True
if (t1 and t2 and t3):
accumulatorW[f[0],k] += w1
accumulatorW[f[1],i] += w2
accumulatorW[f[2],j] += w3
accumulatorW[f[0], j] += w1
accumulatorW[f[1], k] += w2
accumulatorW[f[2], i] += w3
accumulator[f[0], k] += 1
accumulator[f[1], i] += 1
accumulator[f[2], j] += 1
accumulator[f[0], j] += 1
accumulator[f[1], k] += 1
accumulator[f[2], i] += 1
mxvote = np.zeros(n_bands, dtype=np.int32)
tvotes = np.zeros(n_bands, dtype=np.int32)
band_cm = np.zeros(n_bands, dtype=np.float32)
for q in range(n_bands):
mxvote[q] = np.amax(accumulatorW[:,q])
tvotes[q] = np.sum(accumulatorW[:,q])
for i in range(n_bands):
if tvotes[i] < 1:
band_cm[i] = 0.0
else:
srt = np.argsort(accumulatorW[:,i])
band_cm[i] = (accumulatorW[srt[-1],i] - accumulatorW[srt[-2],i]) / tvotes[i]