-
Notifications
You must be signed in to change notification settings - Fork 3
/
diffLabDCTsim_poly_3Dmesh_comp_exp_v3_abs_DQE.m
1564 lines (1503 loc) · 80.7 KB
/
diffLabDCTsim_poly_3Dmesh_comp_exp_v3_abs_DQE.m
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
% diffLabDCTsim_poly_3Dmesh script simulates the diffraction pattern of polycrystal
% created by Haixing Fang, first established in March 2019
% updated dynamically
% The present code generates reflections for any space group. If structural
% information is given it can calculate the structure factors. The
% diffraction pattern simulated from a polycrystal either with random orientations or
% orientations input by the user.
%%%% This simulation applies for the polychromatic X-ray generated by W
%%%% anode
%%%% 3D meshing on grains
%%% by default the X-ray spectrum profile corresponds to the X-ray source operating at an electron accelerating voltage of 140 kV
% Input of grain structures need to be created first using input_main.m
% When first time to run it, simulating only one projection is strongly recommended for testing
% Particularly, this applies to the comparison between simulation and experimental projection
% Modified on Oct 31, 2019
% updates March 16, 2020
% Using anisotropic Gaussian filter for spot shape
% add calculation of the spot and bg intensities for both simu and exp
% improved the segmentation of simu and exp spots
% record the intensity pair
% changed the 'DA' to 'DA_cmp' and 'TFT' to 'TFT_cmp'
% updates June 22, 2020
% corrected Lorentz factor
% add sample attenuation and detective quantum efficiency
% Haixing Fang, hfang@mek.dtu.dk, haixingfang868@gmail.com
% % load measuremnt parameters of the projection images
clear all;
% close all;
%%% load dipimage, mpt3 and mtex toolbox
load_diplib;
load_mpt3; % see documentation, type 'mptdoc'
load_mtex;
load(fullfile(strcat(pwd,'\Examples'),'Input_8grains_MeshNr15.mat')); % an experimental LabDCT characterized sample
exp_parameters; % always better to check the experimental parameters such as Lss, Lsd, detector dimensions and pixel size etc.
% check DA_cmp and TFT_cmp folders exist
if ~exist('TFT_cmp', 'dir')
mkdir('TFT_cmp'); % TFT_cmp folder is to store each output projection
direc = 'TFT_cmp'; % save frames in this directory
else
direc = 'TFT_cmp';
end
if ~exist('DA_cmp', 'dir')
mkdir('DA_cmp'); % DA_cmp folder is to store data record for each projection
end
% % change to Fe
% input_fe;
% if readhkl == 0
% sg = sglib(space_group_IT_number); % get sysconditions for specific element from the sglib.m
% sysconditions=sg.sysconditions;
% end
% Last modified by Haixing Fang, March 2019
tthetamax = acos(dot([Lsam2det 0 0]./norm([Lsam2det 0 0]), ...
[Lsam2det 0.5*detysize*pixelysize 0.5*detzsize*pixelzsize]./norm([Lsam2det 0.5*detysize*pixelysize 0.5*detzsize*pixelzsize])));
tthetamax = tthetamax*180/pi; % two-theta [deg]
thetamax=tthetamax/2;
lambda_max = 12.39818746/min(Energy); % [Angstrom]
lambda_min = 12.39818746/max(Energy); % [Angstrom]
Kmax = 1/lambda_min;
Kmin = 1/lambda_max;
lambda = 12.398./Energy;
sintlmax = sin(thetamax*pi/180)/(12.398/Energy(find(I0E==max(I0E)))); % sin(theta)/lambda [A^-1], consider the characteristic wavelength which corresponds to highest flux
Ki_max = [-2*pi/lambda_min 0 0];
Klen_max = -Ki_max(1);
Ki_min = [-2*pi/lambda_max 0 0];
Klen_min = -Ki_min(1);
L = Lsam2det+Lsam2sou; % source-to-detector distance [mm]
% S = Ang_Axis_g(90,[0 0 1]);
% S = [1 0 0; 0 1 0; 0 0 1]; % Sample orientation - normally this will be the indentity
B = FormB(cell);
V = cellvolume(cell); % [Angs^3]
emass =9.1093826e-31;
echarge = 1.60217653e-19;
pi4eps0 = 1.11265e-10;
c = 299792458 ;
K1 = (echarge^2/(pi4eps0*emass*c*c)*1000)^2; % square of Thomson scattering length r0^2, [mm^2]
% Calc the rotation matrix for the detector
if tilt_x ~= 0 || tilt_y ~= 0 || tilt_z ~= 0
Rx =[1 0 0; 0 cos(tilt_x) -sin(tilt_x); 0 sin(tilt_x) cos(tilt_x)];
Ry =[cos(tilt_y) 0 sin(tilt_y); 0 1 0; -sin(tilt_y) 0 cos(tilt_y)];
Rz =[cos(tilt_z) -sin(tilt_z) 0; sin(tilt_z) cos(tilt_z) 0; 0 0 1];
R = Rx*Ry*Rz;
end
if readhkl == 0
% Generate Miller indices for reflections within a certain resolution
% only compute the first several hkl families
Ahkl0 = genhkl(cell,sysconditions,1.5*sintlmax);
hkl_square=Ahkl0(:,1).^2+Ahkl0(:,2).^2+Ahkl0(:,3).^2;
hkl_square=sortrows(unique(hkl_square));
Ahkl=[];
hklnumber=4; % maximum is 10, recommended be at least >= 4
if length(hkl_square(:,1))>=hklnumber
hkl2_max=hkl_square(hklnumber);
else
hkl2_max=hkl_square(end);
end
for i=1:length(Ahkl0(:,1))
if (Ahkl0(i,1).^2+Ahkl0(i,2).^2+Ahkl0(i,3).^2)<=hkl2_max
Ahkl=[Ahkl;Ahkl0(i,:)];
end
end
% Initialize Ahkl
nrhkl = size(Ahkl,1);
if structfact == 1
disp('Calculating Structure factors');
atomlib;
hkl = [0 0 0];
for i=1:nrhkl
hkl2 = [Ahkl(i,1) Ahkl(i,2) Ahkl(i,3)];
if all(hkl2 == -1*hkl) %Only calculate F^2 if not Friedel mate
hkl = hkl2;
else
hkl = hkl2;
[Freal Fimg] = structure_factor(hkl,cell,atomparam,sg,atom);
int = Freal^2 + Fimg^2;
end
Ahkl(i,5) = int;
end
%disp('Finished Calculating Structure factors'); disp(' ')
else
for i=1:nrhkl
Ahkl(i,5) = 32768; % half of 2^16
end
end
else
disp('Please set readhkl as 0 for automatic generation of hkl reflections ');
end
% save([direc,'/Ahkl.mat'],'Ahkl','-MAT')
% read transmission data and CsI scintillator data, add on June 22, 2020
atomparam_atomno=atomparam.atomno;
[Transmission rou]=ReadTransData(atomparam_atomno); % [(-), g/cm^3]
[CsI Swank]=ReadCsI();
if ~exist('Lx','var')
L_xy=[];
for i=1:length(SubGrain)
L_xy=[L_xy;max(abs(SubGrain{i}(:,2))) max(abs(SubGrain{i}(:,3)))];
end
Rsample=sqrt(max(L_xy(:,1))^2+max(L_xy(:,2))^2); %[mm]
% Rsample=max([max(L_xy(:,1)) max(L_xy(:,2))]);
Lx=Rsample*2e3; % [um]
SampleCylinderFlag=0;
else
Rsample=0.5*Lx*1e-3; % [mm]
SampleCylinderFlag=1;
end
rot_number=1; % recording number of rotations
rot_start=-180;
rot_end=180;
rot_step=2;
frame_number=rot_start:(rot_end-rot_start)/5:rot_end; % frame number to display
frame_showno=1;
% parpool;
% delete(gcp);
SpotsPair=[];
IntPair=[];
% for rot =rot_start:rot_step:rot_end % rotation angle, a full dataset
% for rot =rot_start:2*rot_step:0 % rotation angle, every 2*rot_step projs
for rot = [-146] % rotation angle
% experimental LabDCT projections, starting from _0001 for -180 deg
ImageFolder=strcat(pwd,'\Examples\ExpProjections');
name1='proj';
name3='.tiff';
ProjectNo=(rot-rot_start)/rot_step+1;
if ProjectNo<10
name2=['000',num2str(ProjectNo)];
else if ProjectNo<100
name2=['00',num2str(ProjectNo)];
else if ProjectNo<1000
name2=['0',num2str(ProjectNo)];
else
name2=[num2str(ProjectNo)];
end
end
end
ImageName=[name1 name2 name3];
ImageName = fullfile(ImageFolder, ImageName);
imdata=imread(ImageName); % grey image with beam stop
if strcmp(name3,'.tiff')
imdata=flipud(imdata);
end
if size(imdata,3)==3
imdata=rgb2gray(imdata);
end
imdata=dip_image(imdata,'uint16');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
AllSpotsNr(rot_number)=0; % number of all spots
SpotOverlapNr(rot_number)=0; % number of overlapped spots
rotation_angle(rot_number)=rot;
S=[1 0 0;0 -1 0;0 0 1];
Sw=S;
Ss=S;
omega=rot*pi/180; % [rad]
Omega=[cos(omega) -sin(omega) 0;sin(omega) cos(omega) 0;0 0 1];
graininfo = zeros(abs(grains),16);
A=[];
% Generate orientations of the grains and loop over all grains
% for grainno = 1:abs(grains)
for grainno = [4 5 6 7 8]
% NewProj{rot_number,grainno}=newim(detysize,detzsize);
% NewProj_bin{rot_number,grainno}=newim(detysize,detzsize);
if rot_number==1
ImStack_exp_seg{grainno}=newim(detysize,detzsize);
ImStack_exp_raw{grainno}=newim(detysize,detzsize);
ImStack_simu{grainno}=newim(detysize,detzsize);
ImStack_simu_cl{grainno}=newcolorim([detysize detzsize],'RGB','uint8');
ImStack_simu_cl_mask{grainno}=newcolorim([detysize detzsize],'RGB','uint8');
hkl_color=[255 0 0;0 255 0;0 0 255;255 255 0;0 255 255;255 0 255;0 128 0;128 0 128;0 0 128;255 140 0];
% hkl color: red, green, blue, yellow, cyan, magenta, olive,
% purple, navy, dark orange
hklnumber_max(grainno)=hklnumber;
SpotNr_ideal(grainno)=0; % theoritical spot number hit on the detector
SpotNr_simu(grainno)=0; % simulated spot number after segmentation on the detector
SpotNr_obs(grainno)=0; % experimentally observed spot number
if hklnumber>=5
if grainsize(grainno)>=200
hklnumber_max(grainno)=hklnumber;
elseif grainsize(grainno)>=150 && grainsize(grainno)<200
hklnumber_max(grainno)=min([hklnumber 8]);
elseif grainsize(grainno)>=120 && grainsize(grainno)<150
hklnumber_max(grainno)=min([hklnumber 6]);
else
hklnumber_max(grainno)=4;
end
end
end
A_gr=[];
phi1 = euler_grains(grainno,1)*pi/180;
Phi = euler_grains(grainno,2)*pi/180;
phi2 = euler_grains(grainno,3)*pi/180;
U = euler2u(phi1,Phi,phi2);
if exist('Su','var')==1
U=Su{grainno}*U; % for transformation of gr_esrf19_4grains
end
if exist('Suu','var')==1
U=Suu*U; % for transformation of two different LabDCT reconstructions
end
graininfo(grainno,1:6) = [grainno grainsize(grainno) grainvolume(grainno) phi1*180/pi Phi*180/pi phi2*180/pi];
graininfo(grainno,7:15) = [U(1,1) U(1,2) U(1,3) U(2,1) U(2,2) U(2,3) U(3,1) U(3,2) U(3,3)];
graininfo(grainno,16)=length(SubGrain{grainno}(:,1)); % number of 3D cells for calculation
reshape(graininfo(grainno,7:15),3,3)';
nr = 1;
nrefl = 1;
% Calculate matrix A with (1:totalnr, 2:grain, 3:refno, 4-6:h,k,l, 7:F^2, 8:phi1, 9:PHI, 10:phi2,
% 11-13:Gw(1),Gw(2),Gw(3), 14:omega, 15:2theta, 16:eta, 17:dety, 18:detz, 19:Lorentz, 20:Polarization, 21:Int)
% Gw is the G-vector in the omega-system (w=0)
% Gt is the G-vector in the tilted system (identical to the lab-system except for the tilt of sample stage)
% All angles in A are in degrees
SubA{grainno}=[];
for subgrainno=1:length(SubGrain{grainno}(:,1))
%diffraction center
SubGrain_pos=[SubGrain{grainno}(subgrainno,2) SubGrain{grainno}(subgrainno,3) SubGrain{grainno}(subgrainno,4)];
if exist('Suu','var')==1
SubGrain_pos=(Suu*(SubGrain_pos-shift)'+shift')'; % for registering the volume
end
SubGrain_posW=Omega*Ss*SubGrain_pos';
center = [L, SubGrain_posW(2)*L/(Lsam2sou+SubGrain_posW(1)), ...
SubGrain_posW(3)*L/(Lsam2sou+SubGrain_posW(1))]; % sample center projected to the position of the detector
center0 = [L, SubGrain_pos(2)*L/(Lsam2sou+SubGrain_pos(1)), ...
SubGrain_pos(3)*L/(Lsam2sou+SubGrain_pos(1))];
alpha = atan(sqrt(SubGrain_posW(2)^2+SubGrain_posW(3)^2)/(Lsam2sou+SubGrain_posW(1)));
grainpos = [Lsam2sou+SubGrain_posW(1) SubGrain_posW(2) SubGrain_posW(3)];
% K_in = [Lsam2sou+SubGrain_posW(1) SubGrain_posW(2) SubGrain_posW(3)];
for j=1:nrhkl
% for j=find(Ahkl(:,1)==1 & Ahkl(:,2)==1 & Ahkl(:,3)==5)
if (Ahkl(j,1)^2+Ahkl(j,2)^2+Ahkl(j,3)^2)<=hkl_square(hklnumber_max(grainno))
hkl = [Ahkl(j,1) Ahkl(j,2) Ahkl(j,3)]';
Gw = Sw*U*B*hkl;
Gt=Omega*Gw;
v1 = [0 Gt(2) Gt(3)];
Glen = (Gt(1)^2 + Gt(2)^2 + Gt(3)^2)^0.5;
beta = acos(dot(grainpos/norm(grainpos),Gt/Glen)); % [rad]
if beta > pi/2 && beta < (90+thetamax*4)/180*pi % why 130/180*pi?
theta = beta-pi/2;
sintth = sin(2*theta);
costth = cos(2*theta);
d = 1/Glen*2*pi;
lambdahkl = 2 * d *sin(theta);
Energy_hkl=12.398/lambdahkl; % [keV]
if lambdahkl > lambda_min && lambdahkl < lambda_max
phix = acos(dot(v1/norm(v1),center/norm(center)));
phiy = phix-2*theta;
L2 = (Lsam2det-SubGrain_posW(1))/cos(alpha);
diffvec = L2*sintth/sin(phiy); % [mm]
Kd = Ki_max + Gt';
shkl = norm(Kd)-Klen_max;
if shkl == 0.0
ds = 1;
else
ds = (sin(pi*shkl)/(pi*shkl))^2;
end
SubA{grainno}(nr,1) = nr;
SubA{grainno}(nr,2) = grainno;
SubA{grainno}(nr,3) = nrefl;
SubA{grainno}(nr,4:6) = hkl';
SubA{grainno}(nr,7) = Ahkl(j,5);
SubA{grainno}(nr,8) = phi1*180/pi;
SubA{grainno}(nr,9) = Phi*180/pi;
SubA{grainno}(nr,10) = phi2*180/pi;
SubA{grainno}(nr,11:13) = Gt';
SubA{grainno}(nr,14) = rot;% omega [deg]
SubA{grainno}(nr,15)= 2*theta*180/pi;
eta=atan2(Gt(3),-Gt(2)); % [0, -pi] and [0, pi]
if eta>0
eta=eta-pi/2;
if eta<0
eta=eta+2*pi;
end
else
eta=eta+3/2*pi;
end
SubA{grainno}(nr,16) = eta*180/pi;% [0 360] eta [deg]
% angle between PQ vector and the vertical
% axis, modified on Feb 26, 2020
eta=acos(dot([0 Gt(2) Gt(3)]/norm([0 Gt(2) Gt(3)]),[0 0 1]/norm([0 0 1])));
SubA{grainno}(nr,16) = eta*180/pi;% [0 360] eta [deg]
SubA{grainno}(nr,23) = subgrainno;
konst = norm([0 Gt(2) Gt(3)]);
dety22 = (center(2)+ (diffvec*Gt(2)/konst)); % dety [mm]
detz22 = (center(3)+ (diffvec*Gt(3)/konst)); % detz [mm]
dety2=dety0+dety22/pixelysize;
detz2=detz0+detz22/pixelzsize;
SubA{grainno}(nr,17) = dety2;
SubA{grainno}(nr,18) = detz2;
%%%%%% Lorentz factor
% tests show single crystal monochromatic beam best suits LabDCT
% Lorentz=1./(sin(theta).^2.*cos(theta)); % for powder diffraction monochromatic beam
Lorentz=1./(sin(2*theta)); % for single crystal monochromatic beam
% Lorentz=1./(sin(theta^2)); % for polychromatic Laue diffraction, J. Lange 1995
SubA{grainno}(nr,19)=Lorentz;
%%%%%% Polarisation
% P=1; % for synchrontron source, polarization is normally perpendicular to plane of scattering
P=(1+costth^2)/2; % for lab X-ray producing unpolarized X-ray beam
SubA{grainno}(nr,20)=P;
%Diffracted intensity
SubA{grainno}(nr,21)=0;
ee=min(find(Energy>(Energy_hkl-(Energy(2)-Energy(1))) & Energy<(Energy_hkl+(Energy(2)-Energy(1)))));
[A_Ehkl L_total]=beam_attenuation(SubGrain_posW,Lsam2sou,Lsam2det,dety22,detz22, ...
atomparam,Transmission,rou,Energy_hkl,Rsample); % attenuation intensity factor, June 22, 2020
[DQE_Ehkl]=Detector_efficiency(CsI,Swank,Energy_hkl); % DQE, June 22, 2020
if SubGrain{grainno}(subgrainno,6)==Inf % few cases the grain volume is Inf due to meshing
SubGrain{grainno}(subgrainno,6)=mean(setdiff(SubGrain{grainno}(:,6),Inf,'rows'));
end
if SubGrain{grainno}(subgrainno,6)>1 && SubGrain{grainno}(subgrainno,6)<400 % identify unit as um
K2(ee) = lambda(ee)^3*SubGrain{grainno}(subgrainno,5)*10^12/V^2; % [dimensionless]
else
K2(ee) = lambda(ee)^3*SubGrain{grainno}(subgrainno,5)*10^21/V^2; % [dimensionless] % identify unit as mm
end
K2(ee) = A_Ehkl*DQE_Ehkl*K2(ee); % consider attenuation and detector efficiency
SubA{grainno}(nr,21) = SubA{grainno}(nr,21)+K1*K2(ee)*abs(I0E(ee))*Lorentz*P*Ahkl(j,5)*ExpTime; % intensity [photons]
if Lorentz==1
SubA{grainno}(nr,21)=SubA{grainno}(nr,21)*2e3; % a factor, no physical meaning
else
SubA{grainno}(nr,21)=SubA{grainno}(nr,21); % a factor, no physical meaning
end
SubA{grainno}(nr,22) = Energy_hkl;
end % Loop over Omega solutions
end
end
nr = nr+1;
nrefl = nrefl+1;
end % Loop over reflections
end % Loop over subgrains
SubA_eff{grainno}=[];
if ~isempty(SubA{grainno})
for kk=1:length(SubA{grainno}(:,1))
if (~(all(SubA{grainno}(kk,:))==0) || SubA{grainno}(kk,21)>0) ...
&& (SubA{grainno}(kk,17)>=1 && SubA{grainno}(kk,17)<detysize ...
&& SubA{grainno}(kk,18)>=1 && SubA{grainno}(kk,18)<detzsize)
SubA_eff{grainno}=[SubA_eff{grainno};SubA{grainno}(kk,:)]; % select the data contributing to the intensity on the detector
end
end
end
A_gr=[A_gr;SubA_eff{grainno}];
bgint_gen; % generate background noise, move to here on March 25,2020
% thres1=bgint+sqrt(bgint);
thres1=bgint+1;
thres1=ceil(thres1);
if ~isempty(A_gr)
SpotNr_ideal(grainno)=SpotNr_ideal(grainno)+size(unique(A_gr(:,[2 4 5 6]),'rows'),1);
% theoritical spots hit on the detector, however containing multiple reflections need to be revised out of the loop
makeimage_poly_3Dmesh_v3_SingleGrain;
if exist('GrainIndex','var')
for mm=1:length(GrainIndex_unique(:,1))
Im_Simu=newim(detysize,detzsize);
A_gr_spot=A_gr(find(A_gr(:,2)==GrainIndex_unique(mm,3) & A_gr(:,4)==GrainIndex_unique(mm,4) & ...
A_gr(:,5)==GrainIndex_unique(mm,5) & A_gr(:,6)==GrainIndex_unique(mm,6) & ...
abs(A_gr(:,17)-A_gr(find(A_gr(:,1)==GrainIndex_unique(mm,8)),17))<=GrainIndex_unique(mm,2) & ...
abs(A_gr(:,18)-A_gr(find(A_gr(:,1)==GrainIndex_unique(mm,8)),18))<=GrainIndex_unique(mm,2)),:);
hklno=find(hkl_square==(A_gr_spot(1,4)^2+A_gr_spot(1,5)^2+A_gr_spot(1,6)^2));
SpotNr_simu(grainno)=SpotNr_simu(grainno)+1;
CropBox(1,1)=round(min(A_gr_spot(:,18)))-20;
CropBox(1,2)=round(max(A_gr_spot(:,18)))+20;
CropBox(2,1)=round(min(A_gr_spot(:,17)))-20;
CropBox(2,2)=round(max(A_gr_spot(:,17)))+20;
% CropBox(1,1)=round(min(A_gr_spot(:,18)))-min([20 fix((round(max(A_gr_spot(:,18)))-round(min(A_gr_spot(:,18))))/2)]);
% CropBox(1,2)=round(max(A_gr_spot(:,18)))+min([20 fix((round(max(A_gr_spot(:,18)))-round(min(A_gr_spot(:,18))))/2)]);
% CropBox(2,1)=round(min(A_gr_spot(:,17)))-min([20 fix((round(max(A_gr_spot(:,17)))-round(min(A_gr_spot(:,17))))/2)]);
% CropBox(2,2)=round(max(A_gr_spot(:,17)))+min([20 fix((round(max(A_gr_spot(:,17)))-round(min(A_gr_spot(:,17))))/2)]);
if CropBox(1,2)-CropBox(1,1)>=2 && CropBox(2,2)-CropBox(2,1)>=2
% [xmin ymin width height]
CropRec(1)=detysize-CropBox(2,2);
CropRec(2)=detzsize-CropBox(1,2);
if CropRec(1)<1
CropRec(1)=1;
end
if CropRec(2)<1
CropRec(2)=1;
end
CropRec(3)=CropBox(2,2)-CropBox(2,1);
CropRec(4)=CropBox(1,2)-CropBox(1,1);
if CropRec(1)+CropRec(3)>=detysize
CropRec(3)=detysize-CropRec(1);
end
if CropRec(2)+CropRec(4)>=detzsize
CropRec(4)=detzsize-CropRec(2);
end
im_gr=cut(frame_image_BeamStop,CropRec(3:4),CropRec(1:2));
% im_gr_bin=im_gr>bgint+sqrt(bgint);
% im_gr_bin=im_gr>thres1;
% same segmentation as in makeimage_poly_3Dmesh_v3_SingleGrain.m March 16, 2020
if sum(sum(im_gr==0))>0 || sum(sum(im_gr==mean(mean(im_gr))))/numel(im_gr)
im_gr_bin=im_gr>1.1*thres1; % in touch with the beam stop
im_gr_bin2=im_gr_bin;
else
% if max(max(im_gr))<=thres1*1.5
[im_gr_bin1,im_gr_bg1] = threshold(im_gr,'otsu',Inf);
% else
[im_gr_bin2,im_gr_bg2] = threshold(im_gr,'background',Inf);
% end
im_gr_bg=im_gr_bg1*1/2+im_gr_bg2*1/2;
if im_gr_bg<thres1
im_gr_bg=thres1;
end
im_gr_bin=im_gr>im_gr_bg;
end
if sum(im_gr_bin)~=0
im_gr_seg=im_gr*im_gr_bin;
im_gr_label = label(im_gr_bin,2,0,size(im_gr_bin,1)*size(im_gr_bin,2));
im_gr_measure = measure(im_gr_label,im_gr,{'dimension','DimensionsEllipsoid','gravity','size','feret'});
im_gr_COM=[im_gr_measure(find(im_gr_measure.Size==max(im_gr_measure.Size))).Gravity(1) ...
im_gr_measure(find(im_gr_measure.Size==max(im_gr_measure.Size))).Gravity(2)];
im_gr_ca=im_gr_measure(find(im_gr_measure.Size==max(im_gr_measure.Size))).DimensionsEllipsoid(1) ...
/im_gr_measure(find(im_gr_measure.Size==max(im_gr_measure.Size))).DimensionsEllipsoid(2); % ellipsoid shape: c/a ratio
imdata_gr=cut(imdata,CropRec(3:4),CropRec(1:2)-1);
im_bg=double(im_gr-im_gr_seg);
% im_bg_int(1)=mean(im_bg(im_bg>0),'all'); % average bg intensity
% im_bg_int(2)=std(im_bg(im_bg>0),0,'all'); % standard deviation of bg intensity
im_bg_int(1)=mean(im_bg(im_bg>0)); % average bg intensity
im_bg_int(2)=std(im_bg(im_bg>0)); % standard deviation of bg intensity
im_spot=double(im_gr_seg);
% im_spot_int(1)=mean(im_spot(im_spot>0),'all'); % average spot intensity
% im_spot_int(2)=std(im_spot(im_spot>0),0,'all'); % standard deviation of spot intensity
im_spot_int(1)=mean(im_spot(im_spot>0)); % average spot intensity
im_spot_int(2)=std(im_spot(im_spot>0)); % standard deviation of spot intensity
% %%% get bg intensity
% im1=smooth(imdata_gr,1);
% im1=laplace(im1,2);
% im1=smooth(im1,1);
% im2=im1<-0.5;
% im3=bdilation(im2,2,-1,0);
% im_label=label(im3,1,0);
% im4=imdata_gr>median(imdata_gr);
% im5=im3+im4; % combined filter
% im5=im5>0;
% imdata_bg=imdata_gr-imdata_gr*im5;
% im6=double(imdata_bg);
% % imdata_bg_int(1)=mean(im6(im6>0),'all'); % average bg intensity
% % imdata_bg_int(2)=std(im6(im6>0),0,'all'); % standard deviation of bg intensity
% imdata_bg_int(1)=mean(im6(im6>0)); % average bg intensity
% imdata_bg_int(2)=std(im6(im6>0)); % standard deviation of bg intensity
imdata_gr=smooth(imdata_gr,1);
imdata_gr_value=[mean(mean(imdata_gr)) min(min(imdata_gr)) max(max(imdata_gr))];
thres_gr=imdata_gr_value(1)+sqrt(imdata_gr_value(1))*2/3;
% thres_gr=imdata_gr_value(1)+5;
imdata_gr_bin=imdata_gr>thres_gr;
% % [imdata_gr_bin,thres_gr] = threshold(imdata_gr,'background',Inf);
% [imdata_gr_bin,thres_gr] = threshold(imdata_gr,'otsu',Inf);
% if max(im_label)<=0 % essentially mute this option
imdata_mask=bdilation(im_gr_bin2,3,-1,0); % mask from simulation segmented by symmetry background, April 3, 2020
% imdata_mask=bdilation(im_gr_bin,3,-1,0); % mask from simulation
% else
% imdata_simu_mask=bdilation(im_gr_bin,3,-1,0); % mask from simulation
% imdata_seg_mask=double(im_label*imdata_simu_mask);
% labelID=mode(nonzeros(imdata_seg_mask),'all'); % the most frequent value is the ID of the right object
% imdata_mask=bdilation((im_label==labelID),1,-1,0); % get rid of the spot overlap
% end
% out_shift=findshift(imdata_mask,imdata_gr,'integer',0,0);
% imdata_mask=shift(imdata_mask,[-out_shift(1) -out_shift(2)],1);
imdata_gr_bin=imdata_gr_bin*imdata_mask;
im_out=overlay(imdata_gr,imdata_mask,[255 0 0;0 255 0;0 0 255;255 255 0; ...
0 255 255;255 0 255;255 85 0;170 255 0;0 170 255;85 0 255;255 0 170; ...
255 170 0;0 255 128;0 85 255;170 0 255;255 0 85]);
imdata_gr_seg=imdata_gr*imdata_gr_bin;
imdata_gr_label = label(imdata_gr_bin,2,0,size(imdata_gr_bin,1)*size(imdata_gr_bin,2));
if sum(imdata_gr_label)~=0
imdata_gr_measure = measure(imdata_gr_label,imdata_gr,{'dimension','DimensionsEllipsoid','gravity','size','feret'});
imdata_gr_COM=[imdata_gr_measure(min(find(imdata_gr_measure.Size==max(imdata_gr_measure.Size)))).Gravity(1) ...
imdata_gr_measure(min(find(imdata_gr_measure.Size==max(imdata_gr_measure.Size)))).Gravity(2)];
imdata_gr_ca=imdata_gr_measure(min(find(imdata_gr_measure.Size==max(imdata_gr_measure.Size)))).DimensionsEllipsoid(1) ...
/imdata_gr_measure(min(find(imdata_gr_measure.Size==max(imdata_gr_measure.Size)))).DimensionsEllipsoid(2); % ellipsoid shape: c/a ratio
imdata_gr_select=imdata_gr_label==min(find(imdata_gr_measure.Size==max(imdata_gr_measure.Size)));
imdata_gr_select=bclosing(imdata_gr_select,1,1,0);
imdata_gr_seg=imdata_gr_seg*imdata_gr_select;
imdata_gr_bin=imdata_gr_seg>0;
im6=double(imdata_gr_seg);
% imdata_spot_int(1)=mean(im6(im6>0),'all'); % average bg intensity
% imdata_spot_int(2)=std(im6(im6>0),0,'all'); % standard deviation of bg intensity
imdata_spot_int(1)=mean(im6(im6>0)); % average bg intensity
imdata_spot_int(2)=std(im6(im6>0)); % standard deviation of bg intensity
imdata_bg=imdata_gr-imdata_gr_bin*imdata_gr;
im6=double(imdata_bg);
imdata_bg_int(1)=mean(im6(im6>0)); % average bg intensity
imdata_bg_int(2)=std(im6(im6>0)); % standard deviation of bg intensity
if max(imdata_gr_measure.Size)./sum(im_gr_bin)>0.2 && imdata_spot_int(1)>(imdata_bg_int(1)+1.5*imdata_bg_int(2))
visibility_flag=1;
SpotNr_obs(grainno)=SpotNr_obs(grainno)+1;
else
visibility_flag=0;
end
else
imdata_gr_COM=[NaN NaN];
imdata_gr_ca=NaN;
visibility_flag=0;
imdata_spot_int=[NaN NaN];
imdata_bg_int=[NaN NaN];
end
% imdata_gr_spot=imdata_gr_bin.*imdata_gr;
imdata_gr_spot=imdata_gr_bin.*cut(imdata,CropRec(3:4),CropRec(1:2)-1);
COM_shift=sqrt((im_gr_COM(1)-imdata_gr_COM(1))^2+(im_gr_COM(2)-imdata_gr_COM(2))^2);
% COM_shift=COM_shift/mean(CropRec(3:4)); % <0.2
% COM_shift=COM_shift/max(im_gr_measure.DimensionsEllipsoid(1)); % <0.4
% SpotsPair=[SpotsPair;GrainIndex_unique(mm,:) ...
% sum(sum(imdata_gr_bin)) sum(sum(imdata_gr_spot))./sum(sum(imdata_gr_bin)) ...
% COM_shift rot im_gr_COM(1)+CropRec(1) im_gr_COM(2)+CropRec(2) im_gr_ca ...
% imdata_gr_ca hklno thres_gr visibility_flag A_gr_spot(find(A_gr_spot(:,1)==GrainIndex_unique(mm,8)),22)];
% % [1-9 ExpSpotSize ExpAveInt]
SpotsPair=[SpotsPair;GrainIndex_unique(mm,1:7) GrainIndex_unique(mm,10) sum(sum(imdata_gr_spot))-thres_gr.*sum(imdata_gr_bin) ...
sum(sum(imdata_gr_bin)) sum(sum(imdata_gr_spot))./sum(sum(imdata_gr_bin)) ...
COM_shift rot im_gr_COM(1)+CropRec(1) im_gr_COM(2)+CropRec(2) im_gr_ca ...
imdata_gr_ca hklno thres_gr visibility_flag A_gr_spot(find(A_gr_spot(:,1)==GrainIndex_unique(mm,8)),22)];
% [1-9 ExpSpotSize ExpAveInt] col8 and 9 change to IntIntSimu and IntIntExp, March 28, 2020
IntPair=[IntPair;GrainIndex_unique(mm,10) im_spot_int(1) im_spot_int(2) im_bg_int(1) im_bg_int(2) ...
sum(sum(imdata_gr_spot))-thres_gr.*sum(imdata_gr_bin) imdata_spot_int(1) imdata_spot_int(2) imdata_bg_int(1) imdata_bg_int(2) ...
(imdata_spot_int(1)-imdata_bg_int(1))/imdata_bg_int(2) ...
(imdata_spot_int(1)-imdata_bg_int(1))/sqrt(imdata_spot_int(2)^2+imdata_bg_int(2)^2)];
%%%%% [spot_intint spot_mean spot_sd bg_mean bg_sd SNR1_exp SNR2_exp] for simuand exp
im_overlay=overlay(imdata_gr,im_gr_bin,[255 0 0;0 255 0;0 0 255;255 255 0; ...
0 255 255;255 0 255;255 85 0;170 255 0;0 170 255;85 0 255;255 0 170; ...
255 170 0;0 255 128;0 85 255;170 0 255;255 0 85]);
if sum(ImStack_exp_seg{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1))==0
ImStack_exp_seg{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=imdata_gr_seg;
ImStack_exp_raw{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=imdata_gr;
else
ImStack_exp_seg{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=imdata_gr_seg+ ...
ImStack_exp_seg{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1);
ImStack_exp_raw{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=imdata_gr+ ...
ImStack_exp_raw{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1);
end
% NewProj{rot_number,grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=imdata_gr;
% NewProj_bin{rot_number,grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=closing(imdata_gr_bin,2,'elliptic');
% if sum(ImStack_simu{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1))==0
ImStack_simu{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=im_gr_seg+ ...
ImStack_simu{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1);
% end
%%%%%%%%%%% stack the simulated spots colored by hkl
%%%%%%%%%%% red green blue yellow cyan magenta olive
% im_gr_bin_edge=dgg(im_gr_bin,1);
% im_gr_bin_edge=im_gr_bin_edge~=0;
% im_gr_bin_edge=berosion(im_gr_bin_edge,3,-2,1);
im1 = countneighbours(im_gr_bin,1,Inf,0);
im2=im1>=8;
im_gr_bin_edge=im_gr_bin-im2;
% im_gr_bin_edge=bclosing(im_gr_bin_edge,2,-1,0);
im_gr_bin_edge=bdilation(im_gr_bin_edge,1,-1,0);
Im_Simu=colorspace(im_gr_bin_edge,'RGB');
% Im_Simu_mask=~Im_Simu;
Im_Simu_mask_bin=ImStack_simu{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)>0;
im1 = countneighbours(Im_Simu_mask_bin,1,Inf,0);
im2=im1>=8;
Im_Simu_mask=Im_Simu_mask_bin-im2;
Im_Simu_mask=~Im_Simu_mask;
% Im_Simu_mask=bclosing(Im_Simu_mask,2,-1,0);
Im_Simu_mask=bdilation(Im_Simu_mask,1,-1,0);
Im_Simu_mask=colorspace(Im_Simu_mask,'RGB');
Im_Simu=dip_array(Im_Simu,'double');
redChannel = Im_Simu(:, :, 1)*hkl_color(hklno,1);
greenChannel = Im_Simu(:, :, 2)*hkl_color(hklno,2);
blueChannel = Im_Simu(:, :, 3)*hkl_color(hklno,3);
Im_Simu=joinchannels('RGB',redChannel, greenChannel, blueChannel);
ImStack_simu_cl{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=Im_Simu+ ...
ImStack_simu_cl{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1);
% if sum(sum(sum(ImStack_simu_cl{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1))))==0
ImStack_simu_cl_mask{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=Im_Simu_mask+ ...
ImStack_simu_cl_mask{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1);
% else
% ImStack_simu_cl_mask{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)=Im_Simu_mask.* ...
% ImStack_simu_cl_mask{grainno}(CropRec(1):CropRec(1)+CropRec(3)-1,CropRec(2):CropRec(2)+CropRec(4)-1)+Im_Simu_mask;
% end
imdata_gr_cl=colorspace(imdata_gr,'RGB');
im_gr_overlay=imdata_gr_cl.*Im_Simu_mask+Im_Simu;
end
end
end
end
end
A=[A;SubA_eff{grainno}];
grainno;
end % loop over grains
%Make diffraction images
if makeframes == 1
peakshape=1; % recommended to employ Gaussian point spread
makeimage_poly_3Dmesh_v3;
else
disp('Diffraction images are not formed ... Set makeframes equal to 1 for generating images.')
end
A_rot{rot_number}=A;
header_A_rot = ['ReflectionNo.' ' ' 'GrainNo.' ' ' 'NumberOfReflection' ' ' 'h' ' ' 'k' ' ' 'l' ' ' 'F^2' ' ' ...
'phi1' ' ' 'Phi' ' ' 'phi2' ' ' 'Gw(1)' ' ' 'Gw(2)' ' ' 'Gw(3)' ' ' 'Omega' ' ' '2-theta' ' ' ...
'eta' ' ' 'det_y' ' ' 'det_z' ' ' 'LorentzFactor' ' ' 'PolarizationFactor' ' ' 'IntegratedIntensity' ...
' ' 'EnergyHKL' ' ' 'Subgrainno'];
if ~isempty(A_rot{rot_number})
fid=fopen(strcat('DA_cmp\',strcat(num2str(rot_number-1),'A_rot.txt')),'wt');
fprintf(fid, [header_A_rot '\n']);
for pp=1:length(A_rot{rot_number}(:,1))
fprintf(fid, '%d %d %d %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %d\n', A_rot{rot_number}(pp,:));
end
fclose(fid);
end
if exist('GrainIndex','var')
A_GrainIndex{rot_number}=GrainIndex;
header_A_GrainIndex = ['SpotID' ' ' 'SpotSize' ' ' 'GrainID' ' ' 'h' ' ' 'k' ' ' 'l' ' ' 'AverageIntensiy' ' ' 'ReflectionNo' ' ' 'OverlapFraction' ' ' 'IntInt'];
if ~isempty(A_GrainIndex{rot_number})
fid=fopen(strcat('DA_cmp\',strcat(num2str(rot_number-1),'GrainIndex.txt')),'wt');
fprintf(fid, [header_A_GrainIndex '\n']);
for pp=1:length(A_GrainIndex{rot_number}(:,1))
fprintf(fid, '%d %d %d %d %d %d %f %d %d %f\n', A_GrainIndex{rot_number}(pp,:));
end
fclose(fid);
end
A_GrainIndex_unique{rot_number}=GrainIndex_unique;
if ~isempty(A_GrainIndex_unique{rot_number})
fid=fopen(strcat('DA_cmp\',strcat(num2str(rot_number-1),'GrainIndex_unique.txt')),'wt');
fprintf(fid, [header_A_GrainIndex '\n']);
for pp=1:length(A_GrainIndex_unique{rot_number}(:,1))
fprintf(fid, '%d %d %d %d %d %d %f %d %d %f\n', A_GrainIndex_unique{rot_number}(pp,:));
end
fclose(fid);
end
end
%%%% compare the size difference for
frame0=frame_image_BeamStop>thres1;
% [frame0,frame0_bg] = threshold(frame_image_BeamStop,'otsu',Inf);
% [frame0,frame0_bg] = threshold(frame_image_BeamStop,'background',Inf);
% frame0=dgg(frame0,1);
% frame0=frame0~=0;
% frame0=berosion(frame0,3,-2,1);
im1 = countneighbours(frame0,1,Inf,0);
im2=im1>=8;
frame0=frame0-im2;
frame0=bdilation(frame0,1,-1,0);
frame1 = label(frame0,1,0,detzsize*detysize);
%% intersection area / investigated area
thres2=mean(imdata)+sqrt(mean(imdata));
im=imdata>thres2;
im_intersection=frame0*im;
ProjectNo=1;
AreaRatio(ProjectNo)=sum(im_intersection)./sum(dip_image(frame0,'bin'));
% % visualize the difference
% OutOverlay{ProjectNo} = overlay(imdata,frame1,[255 0 0;0 255 0;0 0 255;255 255 0; ...
% 0 255 255;255 0 255;255 85 0;170 255 0;0 170 255;85 0 255;255 0 170; ...
% 255 170 0;0 255 128;0 85 255;170 0 255;255 0 85]);
% colored with hkl
imdata_cl=colorspace(imdata,'RGB');
OutOverlay1{ProjectNo}=imdata_cl.*ImStack_frame_cl_mask+ImStack_frame_cl;
rot_number=rot_number+1;
rot
end % loop over rotations
% dipshow(frame_image);
dipshow(frame_image_BeamStop);
% imdata;
dipshow(OutOverlay1{ProjectNo});
if exist('frame_label_annot','var')
dipshow(frame_label_annot);
end
% dipshow(ImStack_exp_seg{grainno});
% dipshow(ImStack_exp_raw{grainno});
% dipshow(ImStack_simu{grainno});
write_newproj=0;
if write_newproj==1
% check folders exist
if ~exist('NewProj', 'dir')
mkdir('NewProj');
end
if ~exist('NewProj_bin', 'dir')
mkdir('NewProj_bin');
end
% write out new projections corresponding to one particular grain
grainno=7; % [6, 7]
if exist('NewProj','var')
for rot_number=1:length(rotation_angle)
if sum(NewProj{rot_number,grainno})==0
NewProj{rot_number,grainno}(detysize/2,detzsize/2)=1;
end
filename = sprintf('%s/%s%0.4d.tif','NewProj',prefix,rot_number-1); % Generate FILENAME of frame
imwrite(double(NewProj{rot_number,grainno}),filename,'tif'); % Write out tiff file
end
end
if exist('NewProj_bin','var')
for rot_number=1:length(rotation_angle)
if sum(NewProj_bin{rot_number,grainno})==0
NewProj_bin{rot_number,grainno}(detysize/2,detzsize/2)=1;
end
filename = sprintf('%s/%s%0.4d.tif','NewProj_bin',prefix,rot_number-1); % Generate FILENAME of frame
imwrite(double(NewProj_bin{rot_number,grainno}),filename,'tif'); % Write out tiff file
end
end
% if exist('NewProj_bin','var')
% for rot_number=1:length(rotation_angle)
% NewProj_im=NewProj_bin{rot_number,6}+NewProj_bin{rot_number,7};
% if NewProj_im==0
% NewProj_im(detysize/2,detzsize/2)=1;
% end
% filename = sprintf('%s/%s%0.4d.tif','NewProj_bin',prefix,rot_number-1); % Generate FILENAME of frame
% imwrite(double(NewProj_im),filename,'tif'); % Write out tiff file
% end
% end
end
%%%% overlay the stack
for i=1:length(ImStack_exp_seg)
if ~isempty(ImStack_exp_seg{i}) && ~isempty(ImStack_simu{i})
% ImStack_simu_bin=ImStack_simu{i}>0;
% % ImStack_simu_bin=dgg(ImStack_simu_bin,1);
% % ImStack_simu_bin=ImStack_simu_bin~=0;
% % ImStack_simu_bin=berosion(ImStack_simu_bin,3,-2,1);
% im1 = countneighbours(ImStack_simu_bin,1,Inf,0);
% im2=im1>=8;
% ImStack_simu_bin=ImStack_simu_bin-im2;
% ImStack_simu_label = label(ImStack_simu_bin,1,0,detzsize*detysize);
% ImStackOverlay0{i} = overlay(ImStack_exp_seg{i},ImStack_simu_label,[255 0 0;0 255 0;0 0 255;255 255 0; ...
% 0 255 255;255 0 255;255 85 0;170 255 0;0 170 255;85 0 255;255 0 170; ...
% 255 170 0;0 255 128;0 85 255;170 0 255;255 0 85]);
% ImStackOverlay1{i} = overlay(ImStack_exp_raw{i},ImStack_simu_label,[255 0 0;0 255 0;0 0 255;255 255 0; ...
% 0 255 255;255 0 255;255 85 0;170 255 0;0 170 255;85 0 255;255 0 170; ...
% 255 170 0;0 255 128;0 85 255;170 0 255;255 0 85]);
ImStack_simu_bin=ImStack_simu{i}>0;
im1 = countneighbours(ImStack_simu_bin,1,Inf,0);
im2=im1>=8;
ImStack_simu_mask=ImStack_simu_bin-im2;
ImStack_simu_mask=~ImStack_simu_mask;
% ImStack_simu_mask=bclosing(ImStack_simu_mask,2,-1,0);
ImStack_simu_mask=bdilation(ImStack_simu_mask,1,-1,0);
ImStack_simu_mask=colorspace(ImStack_simu_mask,'RGB');
ImStack_exp_raw_cl=colorspace(ImStack_exp_seg{i},'RGB');
% ImStackOverlay0{i}=ImStack_exp_raw_cl.*ImStack_simu_cl_mask{i}+ImStack_simu_cl{i};
ImStackOverlay0{i}=ImStack_exp_raw_cl.*ImStack_simu_mask+ImStack_simu_cl{i};
ImStack_exp_raw_cl=colorspace(ImStack_exp_raw{i},'RGB');
% ImStackOverlay1{i}=ImStack_exp_raw_cl.*ImStack_simu_cl_mask{i}+ImStack_simu_cl{i};
ImStackOverlay1{i}=ImStack_exp_raw_cl.*ImStack_simu_mask+ImStack_simu_cl{i};
end
end
dipshow(ImStackOverlay1{i});
hklReflection_all=SpotsPair(:,4:6);
hklReflection_all=abs(hklReflection_all);
hklReflection_all=sort(hklReflection_all,2);
[hklReflection,ia,ic] = unique(hklReflection_all,'rows');
hklReflection(:,4)=hklReflection(:,1).^2+hklReflection(:,2).^2+hklReflection(:,3).^2;
hklReflection = sortrows(hklReflection,4);
hklReflection=hklReflection(:,1:3);
GrainID=unique(SpotsPair(:,3));
% count the ideal spot number for each hkl
Spots=[];
for i=1:length(A_rot)
if ~isempty(A_rot{i})
[A_rot_unique,ia,ic] = unique(A_rot{i}(:,[2 4 5 6]),'rows');
Spots=[Spots;A_rot{i}(ia,:)];
end
i
end
for ii=1:length(GrainID)
i=GrainID(ii);
SpotsID{i}=Spots(find(Spots(:,2)==i),:);
for j=1:length(hklReflection(:,1))
SpotNr_ideal_hkl(i,j)=0;
for k=1:length(SpotsID{i}(:,1))
if (sum(sort(abs(SpotsID{i}(k,4:6)),2)==hklReflection(j,:))==3 && ...
~(SpotsID{i}(k,18)>BeamStopY(1) && SpotsID{i}(k,18)<BeamStopY(2) && ...
SpotsID{i}(k,17)>BeamStopZ(1) && SpotsID{i}(k,17)<BeamStopZ(2)))
SpotNr_ideal_hkl(i,j)=SpotNr_ideal_hkl(i,j)+1;
end
end
end
end
% statistics
% finding the maximum mean intensity of all the non-overlapped spots for
% each grain is the key to get things right
statistics_flag=0;
if statistics_flag==1
clear SpotsPair_all SpotsPair_all_eff SpotsPair_all_bad SpotsPair_gr;
clear SpotsPair_gr_eff SpotsPair_gr_hkl SpotsPair_gr_hkl_eff SpotsPair_all_eff_gr;
clear SpotsPair_gr_max1 SpotsPair_gr_max2 SpotsPair_gr_max3;
clear Int_max Int_max_gr Int_max_exp Int_max_ratio;
for ii=1:length(GrainID)
i=GrainID(ii);
for j=1:length(hklReflection(:,1))
SpotsPair_gr_hkl{i,j}=[];
for k=1:length(SpotsPair(:,1))
if sum(sort(abs(SpotsPair(k,4:6)),2)==hklReflection(j,:))==3 && GrainID(ii)==SpotsPair(k,3)
SpotsPair_gr_hkl{i,j}=[SpotsPair_gr_hkl{i,j};SpotsPair(k,:) grainsize(GrainID(ii))]; % + grainsize
end
end
end
SpotsPair_gr{i}=SpotsPair(find(SpotsPair(:,3)==GrainID(ii)),:);
% IntPair_gr{i}=IntPair(find(SpotsPair(:,3)==GrainID(ii)),:);
hkl_2=SpotsPair_gr{i}(:,4).^2+SpotsPair_gr{i}(:,5).^2+SpotsPair_gr{i}(:,6).^2;
hkl_min_index=find(hkl_2==min(hkl_2));
SpotsPair_gr_max1=SpotsPair_gr{i};
% Int_index=find(SpotsPair_gr_max1(:,20)==1 & SpotsPair_gr_max1(:,12)./sqrt(SpotsPair_gr_max1(:,2))<=0.8 & ...
% SpotsPair_gr_max1(:,16)./SpotsPair_gr_max1(:,17)<=1.67 & SpotsPair_gr_max1(:,16)./SpotsPair_gr_max1(:,17)>=0.6);
Int_index=find(SpotsPair_gr_max1(:,20)==1);
Int_exp=SpotsPair_gr_max1(Int_index,10).*SpotsPair_gr_max1(Int_index,11);
IntA_exp=SpotsPair_gr_max1(Int_index,11);
% IntA_exp_diff=IntPair_gr{i}(Int_index,7)-IntPair_gr{i}(Int_index,9); % Ispot-Ibg
Int_gr=SpotsPair_gr_max1(Int_index,2).*SpotsPair_gr_max1(Int_index,7);
IntA_gr=SpotsPair_gr_max1(Int_index,7);
Int_ratio=[Int_gr./max(Int_gr) Int_exp./max(Int_exp)];
Int_ratio(:,3)=Int_ratio(:,2)./Int_ratio(:,1);
IntA_ratio=[IntA_gr./max(IntA_gr) IntA_exp./max(IntA_exp)];
IntA_ratio(:,3)=IntA_ratio(:,2)./IntA_ratio(:,1);
% figure;subplot(2,2,1);plot(Int_gr,Int_exp,'ro');
% subplot(2,2,2);plot(IntA_gr,IntA_exp,'ro');
% subplot(2,2,3);plot(Int_ratio(:,1),Int_ratio(:,2),'ro');
% subplot(2,2,4);plot(IntA_ratio(:,1),IntA_ratio(:,2),'ro');
% % Int_max_ratio_index=find(Int_max_ratio(:,3)<=nanmean(Int_max_ratio(:,3))+0.5*nanstd(Int_max_ratio(:,3)) ...
% % & Int_max_ratio(:,3)>=nanmean(Int_max_ratio(:,3))-0.5*nanstd(Int_max_ratio(:,3)) ...
% % & Int_max_ratio(:,1)>0.75 & IntA_max_ratio(:,1)>0.75 ...
% % & IntA_max_ratio(:,3)<=nanmean(IntA_max_ratio(:,3))+0.5*nanstd(IntA_max_ratio(:,3)) ...
% % & IntA_max_ratio(:,3)>=nanmean(IntA_max_ratio(:,3))-0.5*nanstd(IntA_max_ratio(:,3)));
% Int_max_ratio_index=find(Int_max_ratio(:,3)<=1.67 ...
% & Int_max_ratio(:,3)>=0.3 ...
% & Int_max_ratio(:,1)>0.75 & IntA_max_ratio(:,1)>0.75);
% Int_max(i,1)=max(SpotsPair_gr_max1(Int_max_gr_index(Int_max_ratio_index),7));
% Int_max(i,2)=max(SpotsPair_gr_max1(Int_max_gr_index(Int_max_ratio_index),11));
[TF_outlier,L_outlier,U_outlier,C_outlier]=isoutlier(IntA_exp,'movmedian',round(length(IntA_exp)/3));
if length(GrainID)<=6
figure;plot(IntA_gr,IntA_exp,'ro',IntA_gr(TF_outlier),IntA_exp(TF_outlier),'bx');
end
Int_max(i,2)=max(IntA_exp(intersect(find(TF_outlier~=1),find(IntA_ratio(:,1)>0.4))));
Int_max(i,1)=IntA_gr(find(IntA_exp==Int_max(i,2)));
Int_max(i,4)=max(Int_exp(intersect(find(TF_outlier~=1),find(IntA_ratio(:,1)>0.4))));
Int_max(i,3)=Int_gr(find(Int_exp==Int_max(i,4)));
% % note sometimes it is needed to manually select the max intensity
% if i==4
% Int_max(i,2)=IntA_exp(29); % 181projs: 361.1833 [29 29]; 91 projs: 340.7 [5 6]
% elseif i==5
% Int_max(i,2)=IntA_exp(106); % 181projs: 259.2478 [106 92];91 projs: 232.8 [42 48]
% elseif i==6
% Int_max(i,2)=IntA_exp(136); % 181projs: 154.4732 [136 133]; 91 projs: 149.1 [51 49]
% elseif i==7
% Int_max(i,2)=IntA_exp(127); % 181projs: 184.3817 [105 169]; 91 projs: 167.8 [48]
% elseif i==8
% Int_max(i,2)=IntA_exp(435); % 181projs: 306.1031 [435 282]; 91 projs: 311.2 [73]
% end
%%%%%%%%%%%%%%%%%%
SpotsPair_gr{i}(:,length(SpotsPair_gr{i}(1,:))+1)=(SpotsPair_gr{i}(:,7))./Int_max(i,1); % normalized simu intensities
SpotsPair_gr{i}(:,length(SpotsPair_gr{i}(1,:))+1)=(SpotsPair_gr{i}(:,11))./Int_max(i,2); % normalized exp intensities
% SpotsPair_gr{i}(:,length(SpotsPair_gr{i}(1,:))+1)=(SpotsPair_gr{i}(:,2)).*(SpotsPair_gr{i}(:,7))./Int_max(i,3); % normalized simu intensities
% SpotsPair_gr{i}(:,length(SpotsPair_gr{i}(1,:))+1)=(SpotsPair_gr{i}(:,10)).*(SpotsPair_gr{i}(:,11))./Int_max(i,4); % normalized exp intensities
Invisible_Index=find(SpotsPair_gr{i}(:,20)==0);
if ~isempty(Invisible_Index)
Invisible_int_max(i,:)=[max(SpotsPair_gr{i}(Invisible_Index,7)) max(SpotsPair_gr{i}(Invisible_Index,11))];
else
Invisible_int_max(i,:)=[0 0];
end
end
for ii=1:length(GrainID)
i=GrainID(ii);
SpotsPair_gr_eff{i}=[];
% SpotsPair_gr_obs{i}=SpotsPair_gr{i}(SpotsPair_gr{i}(:,20)==1,:);
% SpotsPair_gr_obs{i}=SpotsPair_gr{i}(find(SpotsPair_gr{i}(:,20)==1 & ...
% SpotsPair_gr{i}(:,11)>nanmedian(IntPair(:,9))+sqrt(nanmedian(IntPair(:,9)))),:);
% SpotsPair_gr_obs{i}=SpotsPair_gr{i}(find(SpotsPair_gr{i}(:,20)==1 & ...
% SpotsPair_gr{i}(:,11)>nanmedian(IntPair(:,9))),:);
SpotsPair_gr_obs{i}=SpotsPair_gr{i}(find(SpotsPair_gr{i}(:,20)==1 & ...
SpotsPair_gr{i}(:,11)>107),:);
% [TF_outlier,L_outlier,U_outlier,C_outlier]=isoutlier(SpotsPair_gr_obs{i}(:,23),'movmedian',round(length(SpotsPair_gr_obs{i}(:,1))/3));
% if length(GrainID)<=6
% figure;plot(SpotsPair_gr_obs{i}(:,22),SpotsPair_gr_obs{i}(:,23),'ro', ...
% SpotsPair_gr_obs{i}(TF_outlier,22),SpotsPair_gr_obs{i}(TF_outlier,23),'bx');
% end
if length(GrainID)<=6
figure;
subplot(2,2,1);
plot(sqrt(SpotsPair_gr_obs{i}(:,2)),SpotsPair_gr_obs{i}(:,12)./sqrt(SpotsPair_gr_obs{i}(:,2)),'ro');
xlabel('sqrt(A) (pixel)');ylabel('COMshift/sqrt(A) (pixel)');axis square;
subplot(2,2,2);
plot(SpotsPair_gr_obs{i}(:,2),SpotsPair_gr_obs{i}(:,10),'ro');
xlabel('Simu spot size');ylabel('Exp spot size');axis square;
subplot(2,2,3);
plot(SpotsPair_gr_obs{i}(:,16),SpotsPair_gr_obs{i}(:,17),'ro');
xlabel('Simu c/a');ylabel('Exp c/a');axis square;
% subplot(2,2,4);
% plot(SpotsPair_gr_obs{i}(:,22),SpotsPair_gr_obs{i}(:,23),'ro');
% xlabel('Simu spot relative int');ylabel('Exp spot relative int');axis square;
subplot(2,2,4);
plot(SpotsPair_gr_obs{i}(:,18),SpotsPair_gr_obs{i}(:,23),'ro');
xlabel('hkl order');ylabel('Exp spot relative int');axis square;
end
for j=1:length(SpotsPair_gr_obs{i}(:,1))
if SpotsPair_gr_obs{i}(j,18)==min(SpotsPair_gr_obs{i}(:,18)) || SpotsPair_gr_obs{i}(j,18)==min(SpotsPair_gr_obs{i}(:,18))+1
int_thre(1)=1;
int_thre(2)=nanmedian(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)) ...
+3*(-1/(sqrt(2)*erfcinv(3/2))*median(abs(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)- ...
median(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23))))); % more than three scaled MAD from the median
int_thre_sd=[0.05 0.05];
elseif SpotsPair_gr_obs{i}(j,18)==max(SpotsPair_gr_obs{i}(:,18))
int_thre(1)=nanmedian(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)<SpotsPair_gr_obs{i}(j,18)),23)); % compare to lower order hkl
int_thre(2)=nanmedian(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)) ...
+3*(-1/(sqrt(2)*erfcinv(3/2))*median(abs(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)- ...
median(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)))));
int_thre_sd=[nanstd(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)<SpotsPair_gr_obs{i}(j,18)),23)) 0.05];
else
int_thre(1)=nanmedian(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)<SpotsPair_gr_obs{i}(j,18)),23));
int_thre(2)=nanmedian(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)) ...
+3*(-1/(sqrt(2)*erfcinv(3/2))*median(abs(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)- ...
median(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)),23)))));
int_thre_sd(1)=nanstd(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)<SpotsPair_gr_obs{i}(j,18)),23));
int_thre_sd(2)=nanstd(SpotsPair_gr_obs{i}(find(SpotsPair_gr_obs{i}(:,18)==SpotsPair_gr_obs{i}(j,18)+1),23));
end
% COM shift; intensity; size; shape
% if (SpotsPair_gr_obs{i}(j,12)/sqrt(SpotsPair_gr_obs{i}(j,2))<=0.8 && ...
% SpotsPair_gr_obs{i}(j,11)>0 && (SpotsPair_gr_obs{i}(j,23)<int_thre(1) || SpotsPair_gr_obs{i}(j,23)==1) && ...
% SpotsPair_gr_obs{i}(j,23)>int_thre(2) && ...
% SpotsPair_gr_obs{i}(j,10)>25 && ...
% SpotsPair_gr_obs{i}(j,17)>0 && ...
% (SpotsPair_gr_obs{i}(j,17)/SpotsPair_gr_obs{i}(j,16)>=0.6 && SpotsPair_gr_obs{i}(j,17)/SpotsPair_gr_obs{i}(j,16)<=1.67) && ...
% SpotsPair_gr_obs{i}(j,22)/SpotsPair_gr_obs{i}(j,23)>=0.6 && SpotsPair_gr_obs{i}(j,22)/SpotsPair_gr_obs{i}(j,23)<=1.67)
% if (SpotsPair_gr_obs{i}(j,10)>50 && SpotsPair_gr_obs{i}(j,12)/sqrt(SpotsPair_gr_obs{i}(j,2))<=0.8 && ...
% SpotsPair_gr_obs{i}(j,20)==1 && SpotsPair_gr_obs{i}(j,17)>0 && SpotsPair_gr_obs{i}(j,17)~=Inf && ...
% SpotsPair_gr_obs{i}(j,16)>0 && SpotsPair_gr_obs{i}(j,16)~=Inf && ...
% SpotsPair_gr_obs{i}(j,11)>0 && SpotsPair_gr_obs{i}(j,19)>mean(SpotsPair(:,19))*0.8 && ...
% (SpotsPair_gr_obs{i}(j,23)<int_thre(1) || SpotsPair_gr_obs{i}(j,23)==1) && ...
% SpotsPair_gr_obs{i}(j,23)>int_thre(2))
% if (SpotsPair_gr_obs{i}(j,10)>50 && SpotsPair_gr_obs{i}(j,20)==1 && SpotsPair_gr_obs{i}(j,17)>0 && SpotsPair_gr_obs{i}(j,17)~=Inf && ...
% SpotsPair_gr_obs{i}(j,16)>0 && SpotsPair_gr_obs{i}(j,16)~=Inf && SpotsPair_gr_obs{i}(j,23)<=1.2 && ...
% SpotsPair_gr_obs{i}(j,11)>100 && ...
% (SpotsPair_gr_obs{i}(j,17)/SpotsPair_gr_obs{i}(j,16)>=0.1 && SpotsPair_gr_obs{i}(j,17)/SpotsPair_gr_obs{i}(j,16)<=2) && ...
% SpotsPair_gr_obs{i}(j,12)/sqrt(SpotsPair_gr_obs{i}(j,2))<=0.8)
% if (SpotsPair_gr_obs{i}(j,20)==1 && SpotsPair_gr_obs{i}(j,17)>0 && SpotsPair_gr_obs{i}(j,17)~=Inf && ...
% SpotsPair_gr_obs{i}(j,16)>0 && SpotsPair_gr_obs{i}(j,16)~=Inf && SpotsPair_gr_obs{i}(j,23)<=1.05 && ...
% SpotsPair_gr_obs{i}(j,11)>100 && ...