-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathseg3D.m
More file actions
2394 lines (2281 loc) · 106 KB
/
seg3D.m
File metadata and controls
2394 lines (2281 loc) · 106 KB
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
classdef seg3D
%SEG3D is a class containing methods for reconstructing surface
%coordinates and analyzing surface curvatures of droplets starting from
%tiff stacks. SEG3D can handle a single channel tiff z-stack as well as
%a single channel tiff z-stack timelapse.
%
% Created on September 5, 2019 by Elijah Shelton
% Last Modified February 22 2021 by Elijah
% * Supports radial analysis option
% Last Modified February 19 2021 by Elijah
% * Generates all directories for python analysis
% * Checks for python install, modules
% * Only plots surface points on first and last sequence
% Last Modified February 17 2021 by Elijah
% * Now checks for existence of destination folder 'Outputs'
% * Updated dialog for FILTER, FIDELITY, and ALPHA inputs
% * Removed some old warning messages
% Last Modified February 09 2021 by Elijah
% *fixed issues with timestamp changing for timeseries analysis
% *added functionality of specifying refactoring parameters
% *labeled axes and colorbars on final figures
% Last Modified February 05 2021 by Elijah
% *exports Input_Dict.mat file for use with subsequent analysis in python
% *exports just coordinate and curvature arrays as variables
% Modified October 21 2020 by Elijah
% *creates folder with tif name and timestamp, useful when
% different tifs are in the same directory*
% Modified September 14, 2020 by Elijah Shelton
% Modified July 30, 2020 by Elijah Shelton
% Modified April 25, 2020 by Elijah Shelton
% Fixed typo in getXYZfromVolume(); radiu -> radius; May 22, 2020 (E.S.)
%
% This work expands upon code written for and ideas presented in the
% 2017 Journal of Microscopy paper by Elijah Shelton, Friedhelm
% Serwane, & Otger Campas (https://doi.org/10.1111/jmi.12624).
properties (Constant)
DisplayOversampling = 1;
PatchRadiusForMedianFilter = 0; % size of median filter applied to curvature measurements at the end
PatchRadiusForIQRFilter = 0; % used to screen out coordinates during reconstruction using IQR filter applied to neighbor distances & errors in fitting parameters
modelShape = 'Ellipsoid'; % 'Sphere' or 'Ellipsoid'
MinNumPerPatch = 18; % For F(x,y) poly2 fitting, N = 3 times num of fit params
NumberOfIterations = 3; % number of iterations of patch fitting, testing sugests convergence at ~3
SmallPatchLengthScale = 1; % recommend 1 or 2;
FeatureKernelSize = 4; % This determines width of the kernel used to sample the feature channel
SurfDens = 1; % Intended number of points per square pixel
testing = 0; % Set to 1 if you would like to see graphic outputs from segmentation during run
end
properties
alpha_percentile % Percentile excluded from upper and lower ends of distribution in python analysis
ComputationTime % Time to run
CoordErrors % Error in Coordinate Edge Fit
Coordinates % Coordinates, in pixels (xy)
CurrentIteration % Current iteration of patch fittings
Curvatures % Mean Curvatures, in inverse pixel dimensions (1/xy)
Distances % Distances to nearest neighbors
Ellipsoidals % structured variable containing information about ellipsoidal segmentation
Features % Feature channel intensity from selected TIF
FilterSize % size of gaussian filter applied to image
FirstFrame
fluorescence % 'Fluorescent Surface' or 'Fluorescent Interior'
Indices % Indices of nearest neighbors
IFT_milliNewtons_per_meter % Interfacial tension, in mN/m. Used in pythom analysis.
k1 % 1st principal curvatures
k2 % 2nd principal curvatures
LastFrame
minRp % Smallest patch radius permitted
NumCoords % Number of coordinates
Normals % Surface normals, calculated on last surface fitting.
NS_kd % KD-tree model for neighbor searching
PatchRadii % The radius of patch used in surface fitting
Path2InputDictMat % Path to Input_Dict.mat file; Used to run python analysis
Path2Mat % Path to matlab results file
Path2MatDir % Path to directory containing matlab results file
Path2Tif % User specificied path to tiff stack containing drop image to analyze
Path2TifDir % Path to directory containing tiff stack
Path2Feat % Path to tiff stack containing feature to analyze.
proj2Fit % If 1 coordinates are projected onto fitted surfaces in the final interations.
segmentMethod % 'Local Edge Fit' or 'Local Edge Fit - Parallelized'
ReferenceCoordinates % For adding location of spatial references, used in Python analysis
SurfaceArea
TifName
Timestamp_analysis % Tells you when the analysis was started.
Timestep %
vsx % voxel size in x (um)
vsz % voxel size in z (um)
deg_lbdv_fit % degree used for lebedev fit
MAX_lbdv_fit_PTS; % 0 or 1; 1 instructs python analysis to use maximum spatial resolution possible.
end
properties (Dependent)
end
methods (Static)
function [] = notes()
fprintf(...
['This version of seg3D requires the following add-ons:\n',...
'Curve Fitting Toolbox\n',...
'Image Processing Toolbox\n',...
'Optimization Toolbox\n',...
'Parallel Computing Toolbox\n',...
'Statistic and Machine Learning Toolbox\n']...
)
end
function [XYZ,ErrOut,FitParOut] = cleanUpXYZCoords(XYZ,boxLimits,ErrIn,FitParIn,patchRadius,edgeFit,parallelize)
if nargin == 6
parallelize = 0;
end
%% Check inside box
xMin = boxLimits(1,1);
xMax = boxLimits(2,1);
yMin = boxLimits(1,2);
yMax = boxLimits(2,2);
zMin = boxLimits(1,3);
zMax = boxLimits(2,3);
xGood = (XYZ(:,1)>xMin) & (XYZ(:,1)<xMax);
yGood = (XYZ(:,2)>yMin) & (XYZ(:,2)<yMax);
zGood = (XYZ(:,3)>zMin) & (XYZ(:,3)<zMax);
indInBox = xGood & yGood & zGood;
XYZ(~indInBox,:) = nan;
%% InterQuartileRange Filters
[indPatch] = seg3D.getNeighborIndices( XYZ(:,1), XYZ(:,2), XYZ(:,3),patchRadius,parallelize);
[numCoords,~] = size(XYZ);
numNeighbors = nan(numCoords,1);
for n = 1:numCoords
numNeighbors(n) = length(indPatch{n});
end
[~,indIQR_err] = seg3D.interQuartileRangeFilter(log(ErrIn),'Upper'); % The order of magnitude of the errors is a better predictor
[~,numFitPar] = size(FitParIn);
indIQR_fPar = cell(numFitPar,1);
for n=numFitPar
[~,indIQR_fPar{n}] = seg3D.interQuartileRangeFilter(FitParIn(:,n),'Both');
end
[~,indIQR_nn] = seg3D.interQuartileRangeFilter(numNeighbors,'Lower');
if edgeFit
ind_accept = indIQR_err&indIQR_nn&indInBox;
else
ind_accept = true(size(indIQR_err));
end
%ind_accept = ~isnan(XYZ(:,1));
x = XYZ(ind_accept,1);
y = XYZ(ind_accept,2);
z = XYZ(ind_accept,3);
ErrOut = ErrIn(ind_accept);
close all
scatter3(x,y,z,[],numNeighbors(ind_accept),'.');
hold on
x_reject = XYZ(~ind_accept,1);
y_reject = XYZ(~ind_accept,2);
z_reject = XYZ(~ind_accept,3);
scatter3(x_reject, y_reject, z_reject,'.r');
% Exclude Low density, high error coordinates;
%warning('Need to fix error filtering...')
indInclude = ind_accept;
%% ORIGINAL
ErrOut = ErrIn(indInclude);
FitParOut = FitParIn(indInclude,:);
x = XYZ(indInclude,1);
y = XYZ(indInclude,2);
z = XYZ(indInclude,3);
center = nanmean(XYZ);
xCntrd = x - center(1);
yCntrd = y - center(2);
zCntrd = z - center(3);
[azi,elv,R] = cart2pol(xCntrd,yCntrd,zCntrd);
% CONSIDER AN INTERPOLATED RESAMPLING STEP HERE...
R_out = R;
% N = length(x);
% R_out = nan(N,1);
% [indPatch] = seg3D.getNeighborIndices(xCntrd,yCntrd,zCntrd,patchRadius,parallelize);
% for n=1:N
% indNbrs = indPatch{n};
% R_patch = R(indNbrs);
% R_out(n) = median(R_patch);
% R_out(n) = R(n);
% end
[xCntrd,yCntrd,zCntrd] = pol2cart(azi,elv,R_out);
x = xCntrd + center(1);
y = yCntrd + center(2);
z = zCntrd + center(3);
XYZ = [x,y,z];
end
function [H,k1,k2] = curvFromPoly2Fit(theta,Xq)
%p00 = theta(1);
p10 = theta(2);
p01 = theta(3);
p11 = theta(4);
p20 = theta(5);
p02 = theta(6);
x = Xq(1);
y = Xq(2);
z = Xq(3);
x0 = 1;
x1 = x;
x2 = y;
%x3 = x.*y;
%x4 = x.*x;
%x5 = y.*y;
X = [x0, x1, x2];
tht_u = [p10; 2*p20; p11*y];
hu = X*tht_u;
tht_v = [p01; p11; 2*p02];
hv = X*tht_v;
tht_uu = [2*p20; 0; 0];
huu = X*tht_uu;
tht_vv = [2*p02; 0; 0];
hvv = X*tht_vv;
tht_uv = [p11; 0; 0];
huv = X*tht_uv;
% Weisstein, Eric W. "Mean Curvature." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/MeanCurvature.html
H = ((1+hv^2)*huu-2*hu*hv*huv+(1+hu^2)*hvv)./(2*(1+hu^2+hv^2)^(3/2));
k1 = 2*max([p02,p20]); % Strictly speaking, this is the first principal curvature at the centroid. Will provide poor approx if query point is far from center/
k2 = 2*min([p02,p20]); % Strictly speaking, this is the second principal curvature at the centroid. Will provide poor approx if query point is far from center
% if H < 0
% warning('Mean curvature is negative...check orientation')
% end
end
function [x,y] = ellipseCoords(a,b,orientation,N,center)
if nargin < 5
center = [0,0];
end
t = linspace(0,2*pi,N+1);
t = t(1:end-1);
% centered, level ellipse
x = a*cos(t);
y = b*sin(t);
% centered rotated ellipse
[x,y] = seg3D.rotateCoordsXYPlane(x,y,orientation);
% translated, rotated ellipse
x = x + center(1);
y = y + center(2);
end
function [XYZ,rotMatrix] = ellipsoidCoords(semiAxesLengths,numCoords,center,rotMethod,rotParameters)
% Generates a set of coordinates on the surface on an ellipsoid
% defined by 'semiAxesLengths', 'eulerAngles' and 'center'
%
% DEFINE LOCAL COORDINATES
z = linspace(1-1/numCoords,1/numCoords-1,numCoords);
radius=sqrt(1-z.^2);
goldenAngle = pi*(3-sqrt(5));
theta = goldenAngle*(1:numCoords);
XYZ_local = zeros(numCoords,3);
XYZ_local(:,1) = semiAxesLengths(1)*radius.*cos(theta);
XYZ_local(:,2) = semiAxesLengths(2)*radius.*sin(theta);
XYZ_local(:,3) = semiAxesLengths(3)*z;
% ROTATE COORDINATES
switch rotMethod
case 'Euler Angles'
eulerAngles = rotParameters;
c1 = cos(eulerAngles(1));
c2 = cos(eulerAngles(2));
c3 = cos(eulerAngles(3));
s1 = sin(eulerAngles(1));
s2 = sin(eulerAngles(2));
s3 = sin(eulerAngles(3));
% https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
rotMatrix = [ c2 -c3*s2 s2*s3;...
c1*s2 c1*c2*c3 - s1*s3 -c3*s1 - c1*c2*s3;...
s1*s2 c1*s3 + c2*c3*s1 c1*c3 - c2*s1*s3];
case 'Rotation Matrix'
rotMatrix = rotParameters;
otherwise
error('Unexpected value for ''rotMethod''.')
end
XYZ_rot = rotMatrix*XYZ_local';
% TRANSLATE COORDINATES
XYZ = XYZ_rot' + ones(numCoords,1)*center;
end
function [estCenter,estRadius] = estCenAndRad3D(V,X,Y,Z,fluorescence,testing)
if nargin == 5
testing = 0;
end
thresholdValue = 0.2*max(V(:));
V_bool = double(V > thresholdValue);
sumV = sum(V_bool(:));
xCOM = sum(X(:).*V_bool(:))/sumV;
yCOM = sum(Y(:).*V_bool(:))/sumV;
zCOM = sum(Z(:).*V_bool(:))/sumV;
XYZ = [X(:)-xCOM,Y(:)-yCOM,Z(:)-zCOM].*sqrt([V_bool(:),V_bool(:),V_bool(:)]); % intensity weighted centered coordinates
S = 1/(sumV)*(XYZ'*XYZ);
[rotMatrix,D] = eig(S);
switch fluorescence
case 'Fluorescent Interior'
R = sqrt(5*diag(D));
case 'Fluorescent Surface'
R = sqrt(3*diag(D));
otherwise
error('Unexpected value for ''fluorescence''')
end
a = R(1); % smallest semiaxis length
b = R(2); % median semiaxis length
c = R(3); % largest semiaxis length
estCenter = [xCOM,yCOM,zCOM];
estRadius = (a*b*c)^(1/3);
MIP = sum(V,3);
if testing
%% CIRCLE CHECK
%close all
%imshow(MIP,[]);
%hold on
%plot(yCOM,xCOM,'.r')
%N = 100;
%[x_ell,y_ell] = seg3D.ellipseCoords(estRadius,estRadius,0,N,estCenter);
%plot(y_ell,x_ell,'-r')
%% ELLIPSOID CHECK
N = 1000;
XYZ_ell = seg3D.ellipsoidCoords(R,N,estCenter,'Rotation Matrix',rotMatrix);
close all
[~,~,P] = size(V);
for p = 1:P
inPlane = (XYZ_ell(:,3) >= (p-1))&(XYZ_ell(:,3) < p);
XY = XYZ_ell(inPlane,1:2);
imshow(V(:,:,p),[]);
hold on
plot(XY(:,1),XY(:,2),'.r')
pause(0.1)
end
% %% SANDBOX
% R0 = [5 7 10];
% EA = [pi/4 pi/4 pi/4];
% N = 1000;
% C0 = [2 3 4];
% [XYZ_ea,~] = seg3D.ellipsoidCoords(R0,N,C0,'Euler Angles',EA);
%
% C1 = mean(XYZ);
% XYZ_c = XYZ - C1;
% S = (1/N)*(XYZ_c'*XYZ_c);
% [vec,D] = eig(S);
% R1 = sqrt(3*diag(D));
%
% [XYZ_rm,~] = seg3D.ellipsoidCoords(R1,N,C1,'Rotation Matrix',vec);
% close all
% scatter3(XYZ_ea(:,1),XYZ_ea(:,2),XYZ_ea(:,3),'.k');
% hold on
% scatter3(XYZ_rm(:,1),XYZ_rm(:,2),XYZ_rm(:,3),'or');
% axis equal
end
end
function [estCenter,semiAxesLengths,rotMatrix] = estEllipsoidFromVolume(V,X,Y,Z,fluorescence,testing)
if nargin == 5
testing = 0;
end
thresholdValue = 0.2*max(V(:));
V_bool = double(V > thresholdValue);
sumV = sum(V_bool(:));
xCOM = sum(X(:).*V_bool(:))/sumV;
yCOM = sum(Y(:).*V_bool(:))/sumV;
zCOM = sum(Z(:).*V_bool(:))/sumV;
XYZ = [X(:)-xCOM,Y(:)-yCOM,Z(:)-zCOM].*sqrt([V_bool(:),V_bool(:),V_bool(:)]); % intensity weighted centered coordinates
S = 1/(sumV)*(XYZ'*XYZ);
[rotMatrix,D] = eig(S);
switch fluorescence
case 'Fluorescent Interior'
semiAxesLengths = sqrt(5*diag(D));
case 'Fluorescent Surface'
semiAxesLengths = sqrt(3*diag(D));
otherwise
error('Unexpected value for ''fluorescence''')
end
estCenter = [xCOM,yCOM,zCOM];
if testing
%% CIRCLE CHECK
a = semiAxesLengths(1); % smallest semiaxis length
b = semiAxesLengths(2); % median semiaxis length
c = semiAxesLengths(3); % largest semiaxis length
estRadius = (a*b*c)^(1/3);
MIP = sum(V,3);
close all
imshow(MIP,[]);
hold on
plot(yCOM,xCOM,'.r')
N = 100;
[x_ell,y_ell] = seg3D.ellipseCoords(estRadius,estRadius,0,N,estCenter);
plot(y_ell,x_ell,'-r')
pause()
%% ELLIPSOID CHECK
N = 1000;
XYZ_ell = seg3D.ellipsoidCoords(semiAxesLengths,N,estCenter,'Rotation Matrix',rotMatrix);
close all
[~,~,P] = size(V);
for p = 1:P
inPlane = (XYZ_ell(:,3) >= (p-1))&(XYZ_ell(:,3) < p);
XY = XYZ_ell(inPlane,1:2);
imshow(V(:,:,p),[]);
hold on
plot(XY(:,1),XY(:,2),'.r')
pause(0.1)
end
end
end
function [estCenter,semiAxesLengths,rotMatrix] = estEllipsoidFromCoordinates(XYZ,parallelize)
if nargin == 1
parallelize = 0;
end
samplingDensity = seg3D.getSamplingDensity(XYZ,parallelize);
indKeep = ~isnan(XYZ(:,1))&isfinite(XYZ(:,1));
X = XYZ(indKeep,1);
Y = XYZ(indKeep,2);
Z = XYZ(indKeep,3);
samplingDensity = samplingDensity(indKeep);
W = 1./samplingDensity;
sumW = sum(W);
xCOM = sum(X.*W)/sumW;
yCOM = sum(Y.*W)/sumW;
zCOM = sum(Z.*W)/sumW;
XYZ = [X(:)-xCOM,Y(:)-yCOM,Z(:)-zCOM].*sqrt([W,W,W]); % weighted centered coordinates
S = 1/(sumW)*(XYZ'*XYZ);
[rotMatrix,D] = eig(S);
semiAxesLengths = sqrt(3*diag(D));
estCenter = [xCOM,yCOM,zCOM];
end
function [startP,x_trimmed,y_trimmed] = estFitParameters(X,Y,fluorescence,testing)
if nargin < 4
testing = 0; % testing should be off be default
end
switch fluorescence
case 'Fluorescent Interior'
% FIT MODEL
% h(x) = (amp+lambda*(x-mu))/(1 + exp(-k*(x-mu)) + offset
if length(X) < 5
warning('Too few points in trace (length(X) < 5)')
startP = nan(1,5);
x_trimmed = X;
y_trimmed = Y;
return
end
%% FIND X1
x1 = X(1);
y1 = Y(1);
X1 = [x1 y1];
%% FIND X3
dY = 0.5*diff([Y(1); Y]) + 0.5*diff([Y; Y(end)]);
[~,indX3] = max(abs(dY));
x3 = X(indX3);
y3 = Y(indX3);
X3 = [x3 y3];
%% FIND X5
x5 = X(end);
y5 = Y(end);
X5 = [x5 y5];
%% FIND X2 & X4
ddY = 0.5*diff([dY(1); dY]) + 0.5*diff([dY; dY(end)]);
magLddY = ddY;
magLddY(1) = nan;
magLddY(indX3:end) = nan;
[~, indX2] = max(magLddY);
x2 = X(indX2);
magRddY = ddY;
magRddY(end) = nan;
magRddY(1:indX3) = nan;
[~, indX4] = max(magRddY);
x4 = X(indX4);
fullWidth = x4 - x2;
halfWidth = fullWidth/2;
dX = X(2)-X(1);
indX2 = indX3 - round(halfWidth/dX); % REDEFINE indX2
if indX2 < 2 || indX2 > (length(X)-2)
indX2 = 2;
end
indX4 = indX3 + round(halfWidth/dX); % REDEFINE indX4
if indX4 < 3 || indX4 > (length(X)-1)
indX4 = length(X) - 1;
end
x2 = X(indX2);
y2 = Y(indX2);
x4 = X(indX4);
y4 = Y(indX4);
X2 = [x2 y2];
X4 = [x4 y4];
% ESTIMATE K
k = 4/(x4-x2);
if y4 > y2
k = -k;
end
width = abs(1/k);
% ESTIMATE CENTER
center = x3;
% ESTIMATE AMP
amp = 2*y3;
% ESTIMATE OFFSET & LAMBDA
if k > 0 % EXPECTED
offset = y5;
lambda = (y2 - y1)/(x2-x1);
else % UNUSUAL, BUT IT HAPPENS...
offset = y1;
lambda = (y5 - y4)/(x5-x4);
end
if ~isfinite(lambda)
error('lambda must be finite')
end
%% ESTIMATE STARTING FIT PARAMETERS
startP = [k center lambda amp offset];
%% TRIM COORDINATES
x_trimmed = X(indX2:indX4);
y_trimmed = Y(indX2:indX4);
if ~isfinite(sum(startP))
error('startP must contain 5 finite numbers')
end
if isnan(sum(startP))
error('startP must contain 5 finite numbers')
end
if length(startP)<5
error('startP must contain 5 finite numbers')
end
if testing
h = @(r) (r(4) + r(3)*(x_trimmed-r(2)))./(1+exp(r(1)*(x_trimmed-r(2)))) + r(5);
%h = @(r) (r(3))./(1+exp(-r(1)*(x_trimmed-r(2)))) + r(4);
yFit = h(startP);
close all
plot(X,Y,'ok')
hold on
plot(x_trimmed,yFit,'r')
plot([x1 x2 x3 x4 x5],[y1 y2 y3 y4 y5],'.');
end
case 'Fluorescent Interior Old'
% FIT MODEL
% h(x) = amp*exp(-(x-mu)^2/lambda^2)/(1 + exp((x-mu)/width)) + offset
% Double check that...^ :-/
gradientThresholdFactor = 0.4; % Consider increasing to 0.4...
%warning('gradientThresholdFactor may be in need of adjustment...')
% ESTIMATE CENTER (mu)
dX = X(2) - X(1);
dY = diff(Y); % Calculate differentials at each segment;
[minDY, minDYind] = min(dY); % Determine minimum differential index
centerIndex = minDYind;
center = X(centerIndex); % Use minimum differential index to estimate center
% ESTIMATE EDGE WIDTH (width)
width1 =std((find(dY<gradientThresholdFactor*minDY)))*dX;
ddY = diff(dY);
%[minddY, ind1] = min(ddY);
ddY_rhs = ddY(minDYind:end);
[maxddY, ind_width] = max(ddY_rhs);
if isempty(ind_width)
warning('Bad Trace')
startP = nan(1,5);
x_trimmed = [];
y_trimmed = [];
return
end
ind1 = minDYind - ind_width;
if isempty(ind1)
ind1 = 1;
elseif isnan(ind1) || ind1 < 1 || ind1 > length(X)
ind1 = 1;
end
width = ind_width*dX;
% TRIM COORDINATES
startTrim = floor(centerIndex - 3*width/dX);
if startTrim < 1 || startTrim > length(X) || isempty(startTrim) || isnan(startTrim)
startTrim = 1;
end
endTrim = ceil(centerIndex + 4*width/dX);
if endTrim < 1 || endTrim > length(X) || isempty(endTrim) || isnan(endTrim)
endTrim = length(X);
end
trimInd = startTrim:endTrim;
x_trimmed = X(trimInd);
y_trimmed = Y(trimInd);
% ESTIMATE OFFSET (offset)
offset = min(y_trimmed);
% ESTIMATE AMPLITUDE (amp)
amp1 = Y(ind1+1)-offset;
% ESTIMATE INTERNAL SIGNAL ATTENUATION LENGTH
depth = X(ind1+1) - x_trimmed(1);
attenuation = amp1/y_trimmed(1);
lambda = depth/sqrt(log(attenuation));
if ~isfinite(lambda)||~isreal(lambda)
lambda = 1000*length(Y);
end
% ESTIMATED FIT PARAMETERS
startP = [width, center, lambda, amp1, offset];
case 'Fluorescent Surface'
%startP: sigma mu amp offset of Gaussian
% ESTIMATE CENTER (mu)
if length(X) < 3
warning('X2 is too short; the ray is way too short.')
startP = NaN(1,4);
x_trimmed = NaN;
y_trimmed = NaN;
return
end
amp1=max(Y);
dX=(X(2)-X(1));
%calc mean, stdev of whole trace first guess of peak center and width
indCenter=round(mean(find(Y>0.4*amp1)));
indCenterStd=round(std(find(Y>0.1*amp1)));
if isempty(indCenter) ||isnan(indCenter)
startP=[nan nan nan nan];
else
center=X( indCenter);
centerStd=dX*indCenterStd;
%find coords with intens. values around the peak
indForCenter=find(abs(X-center)<1.5*centerStd);
indCenter=round(mean(find(Y(indForCenter)>0.4*amp1)));
if isnan(indCenter)
startP=[nan nan nan nan];
else
centerIndex = indForCenter(indCenter);
center=X( centerIndex );
width=std((find(Y>0.2*amp1)))*dX;
offset=0;
startP=[width center amp1 offset];
end
end
x_trimmed = X;
y_trimmed = Y;
%error('NEED TO ESTIMATE FIT PARAMETERS')
otherwise
error('Unexpected value for ''fluorescence''.')
end
if testing
% FLUORESCENT INTERIOR
h = @(r) (r(4) + r(3)*(x_trimmed-x_trimmed(1)))./(1+exp(r(1)*(x_trimmed-r(2)))) + r(5);
%h = @(r) (r(3))./(1+exp(-r(1)*(x_trimmed-r(2)))) + r(4);
yFit = h(startP);
close all
plot(X,Y,'ok')
hold on
plot(x_trimmed,yFit,'r')
pause()
end
end
function [path2CoordsAndCurves] = exportCoordsAndCurves(path2MatFile,pointCloudArray,meanCurvatureArray,data,timestamp)
pathDissassembled = regexp(path2MatFile,filesep,'split');
matFilename = pathDissassembled{end};
path2MatDir = strjoin(pathDissassembled(1:end-1),filesep);
CoordsAndCurvesSubFolder = ['CoordsAndCurves',timestamp];
path2CoordsAndCurvesDir = [path2MatDir,filesep,CoordsAndCurvesSubFolder];
if ~exist(path2CoordsAndCurvesDir,'dir')
mkdir(path2CoordsAndCurvesDir);
end
fileSuffix = [matFilename(3:6),'.mat'];
CoordsAndCurvesMatFilename = ['justCoordinatesAndCurvatures',fileSuffix];
path2CoordsAndCurves = [path2CoordsAndCurvesDir,filesep,CoordsAndCurvesMatFilename];
save(path2CoordsAndCurves,'meanCurvatureArray','pointCloudArray','data');
end
function [area] = findSurfaceArea(XYZ,displaySurface)
if nargin == 1
displaySurface = 0;
end
% To calculate surface area, we can represent the surface as a
% mesh of rectangles. The total surface area is calculated by
% summing the area of each of the rectangles.
k = floor(log((length(XYZ))^(1/2))/log(2));
n = 2^k-1;
[x,y,z,R] = seg3D.meshPointCloud(XYZ,n);
if displaySurface
close all
s = surf(x,y,z,R);
s.EdgeColor = 'none';
s.FaceLighting = 'gouraud';
axis square
end
[m,n] = size(z);
area = 0;
for i = 1:m-1
for j = 1:n-1
v0 = [x(i,j) y(i,j) z(i,j) ];
v1 = [x(i,j+1) y(i,j+1) z(i,j+1) ];
v2 = [x(i+1,j) y(i+1,j) z(i+1,j) ];
v3 = [x(i+1,j+1) y(i+1,j+1) z(i+1,j+1)];
a = v1 - v0;
b = v2 - v0;
c = v3 - v0;
A = 1/2*(norm(cross(a, c)) + norm(cross(b, c)));
area = area + sum(A);
end
end
end
function [fitPar,yFit,MSE,FVU] = fitBoundary(x,y,startPar,fluorescence)
% optimoptions and lsqnonlin are relatively slow
options = optimoptions(@lsqnonlin,'Algorithm','levenberg-marquardt','display','off','MaxFunctionEvaluations',1500);
switch fluorescence
case 'Fluorescent Interior'
% r = [k mu amp offset]
costFun = @(r) (r(4)+r(3)*(x-r(2)))./(1+exp(r(1)*(x-r(2)))) + r(5) - y;
h = @(r) (r(4)+r(3)*(x-r(2)))./(1+exp(r(1)*(x-r(2)))) + r(5);
case 'Fluorescent Interior Old'
% r = [sigma mu lambda amp offset]
costFun = @(r) (r(4)*exp(-(x-r(2)).*(x-r(2))./(r(3)*r(3))))./(1+exp((x-r(2))./r(1))) + r(5) - y;
h = @(r) (r(4)*exp(-(x-r(2)).*(x-r(2))./(r(3)*r(3))))./(1+exp((x-r(2))./r(1))) + r(5);
case 'Fluorescent Surface'
% r = [sigma mu amp offset];
costFun = @(r) (r(3)*exp(-(x-r(2)).*(x-r(2))./(r(1)*r(1)))) + r(4) - y;
h = @(r) (r(3)*exp(-(x-r(2)).*(x-r(2))./(r(1)*r(1)))) + r(4);
otherwise
error('Unexpected value for ''fluorescence''.')
end
try
fitPar = lsqnonlin(costFun,startPar,[],[], options);
catch
warning('You got problems...')
fitPar = nan(size(startPar));
end
if ~isfinite(sum(fitPar))
warning('Returning non-finite fit parameters. Model is poorly conditioned for data.')
fitPar = nan(size(startPar));
end
yFit = h(fitPar);
J = (yFit - y);
%rmsErr = sqrt(J'*J/length(J));
MSE = mean(J.^2); % Mean Square Error;
FVU = MSE/var(y); % Fraction Of Variance Unexplained (by fit)
end
function [theta,J,h] = fitPoly2(x,y,z)
%% fitPoly2
% INPUTS: x,y,z are all column vectors
% OUTPUTS: theta: fitting parameters, J: cost function
m = length(x);
x0 = ones(m,1);
x1 = x;
x2 = y;
x3 = x.*y;
x4 = x.*x;
x5 = y.*y;
X = [x0, x1, x2, x3, x4, x5];
Y = z;
A = X'*X;
theta = pinv(A)*X'*Y;
h = X*theta;
R2 = (h-Y)'*(h-Y);
J = (1/(2*m))*R2;
%% TEST FIT
% close all
% scatter3(x,y,z,'.');
% hold on
% scatter3(x,y,h,'o');
end
function [XYZ,Err,FitParams] = fitTraces(traceStarts,traceEnds,F,fluorescence,edgeFit,testing)
if nargin == 5
testing = 0; % Change to 1 to display plots
end
N = length(traceEnds);
XYZ = nan(N,3);
Err = nan(N,1);
if edgeFit
switch fluorescence
case 'Fluorescent Interior'
numFitPar = 5;
case 'Fluorescent Surface'
numFitPar = 4;
otherwise
error('Unexpected value for ''fluorescence''.')
end
else
numFitPar = 1;
end
FitParams = nan(N,numFitPar);
samplingLength = 1;
% This loop is relatively slow. Consider parallelizing.
for n = 1:N
rStart = traceStarts(n,:);
rEnd = traceEnds(n,:);
[traceCoords,sampVec] = ...
seg3D.generateLineCoords(rStart, rEnd, samplingLength);
[t,Int] = seg3D.getTraceToFit(traceCoords,F);
if edgeFit
[startP,t_trimmed,Int_trimmed] = seg3D.estFitParameters(t,Int,fluorescence,testing);
[fitPar,yFit,~,FVU] = seg3D.fitBoundary(t_trimmed,Int_trimmed,startP,fluorescence);
XYZ(n,:) = fitPar(2)*sampVec + rStart;
Err(n) = FVU;
FitParams(n,:) = fitPar;
else
switch fluorescence
case 'Fluorescent Interior'
dInt = abs(diff(Int));
dt = (t(2)-t(1));
fitPar = t(dInt==max(dInt))+0.5*dt;
case 'Fluorescent Surface'
fitPar = t(Int==max(Int));
otherwise
error('Unexpected value for ''fluorescence''.')
end
XYZ(n,:) = fitPar*sampVec + rStart;
Err(n) = 0;
FitParams(n,:) = fitPar;
end
if testing
close all
% MAY ONLY WORK FOR FLUORESCENT INTERIOR
plot(t_trimmed,Int_trimmed,'-b')
hold on
plot(t_trimmed,yFit,'-r')
plot(fitPar(2),max(yFit),'o')
xEdge = [1 1]*fitPar(2);
yEdge = [0 1]*fitPar(4);
plot(xEdge,yEdge,'-k')
pause()
end
%close all
%plot(XY(:,1),XY(:,2),'.')
end
end
function [path2InputDictMatFile] = generateInputDict(fullpath,INPUT_DICT)
% make Outputs directory, if it doesn't exist
reqDirs = {'Outputs','Pickled_LBDV_Files','Pickled_Data','Pickled_Sphere_Triangulations'};
for n = 1:numel(reqDirs)
if~exist(reqDirs{n},'dir')
mkdir(reqDirs{n});
end
end
foldersInPath = regexp(fullpath,filesep,'split');
SubFolder_We_Load_From = foldersInPath{end-1};
MatFile_filepath = strjoin(foldersInPath(1:end-1),filesep);
Tension_gamma_val = INPUT_DICT.IFT;
Pixel_Size_Microns = INPUT_DICT.Pixel_size_microns;
Use_PyCompadre = 0;
Plot_Vtu_Outputs = 1;
Output_Plot_Subfolder_Name = [ SubFolder_We_Load_From,'_OUTPUT'];
deg_lbdv_fit = INPUT_DICT.deg_lbdv_fit;
MAX_lbdv_fit_PTS = INPUT_DICT.MAX_lbdv_fit_PTS;
deg_lbdv_Vol_Int = INPUT_DICT.deg_lbdv_Vol_Int;
MAX_lbdv_vol_PTS = INPUT_DICT.MAX_lbdv_vol_PTS;
deg_fit_Ellipsoid_Deviation_Analysis = INPUT_DICT.deg_fit_Ellipsoid_Deviation_Analysis;
alpha_percentile_excl_AnisStress = INPUT_DICT.alpha_percentile_excl_AnisStress;
alpha_percentile_excl_AnisCellStress = INPUT_DICT.alpha_percentile_excl_AnisCellStress;
alpha_percentile_excl_AnisStressLocalMax_m_AnisStressLocalMin = INPUT_DICT.alpha_percentile_excl_AnisStressLocalMax_m_AnisStressLocalMin;
Corr_Start_Dist = 0;
drop_center_XYZ_um = INPUT_DICT.drop_center_XYZ_um;
EK_center_XYZ_um = INPUT_DICT.EK_center_XYZ_um;
if ~isempty(EK_center_XYZ_um) && ~isempty(drop_center_XYZ_um)
Neha_Radial_analysis = true;
else
Neha_Radial_analysis = false;
end
Calc_Spat_Temp_Corrs = 0;
smoothBSpline = 1;
path2InputDictMatFile = ['Input_Dict.mat'];
save(path2InputDictMatFile,...
'SubFolder_We_Load_From',...
'MatFile_filepath',...
'Tension_gamma_val',...
'Use_PyCompadre',...
'Plot_Vtu_Outputs',...
'Pixel_Size_Microns',...
'Output_Plot_Subfolder_Name',...
'deg_lbdv_fit',...
'MAX_lbdv_fit_PTS',...
'deg_lbdv_Vol_Int',...
'MAX_lbdv_vol_PTS',...
'deg_fit_Ellipsoid_Deviation_Analysis',...
'alpha_percentile_excl_AnisStress',...
'alpha_percentile_excl_AnisCellStress',...
'alpha_percentile_excl_AnisStressLocalMax_m_AnisStressLocalMin',...
'Corr_Start_Dist',...
'Neha_Radial_analysis',...
'drop_center_XYZ_um',...
'EK_center_XYZ_um',...
'Calc_Spat_Temp_Corrs',...
'smoothBSpline')
end
function [traceCoordinates,sampVec] = generateLineCoords(rStart,rV, samplingLength)
dispVec = rV-rStart;
lengthTrace = norm(dispVec);
NPoints = floor(lengthTrace/samplingLength) + 1;
sampVec = samplingLength*dispVec./norm(dispVec);
traceCoordinates = ones(NPoints,1)*rStart + (0:(NPoints-1))'*sampVec;
end
function [Indices,NumNearestNeighbors] = getNeighborIndices(x,y,z,patchRadius,parallelize)
if nargin == 4
parallelize = 0;
end
N = length(x);
patchRadii = patchRadius*ones(N,1);
queryPoints = [x,y,z];
Indices = cell(N,1);
NumNearestNeighbors = nan(N,1);
NS_kd = KDTreeSearcher(queryPoints);
if parallelize
parfor n = 1:N
[idx]=rangesearch(NS_kd,queryPoints(n,:),patchRadii(n));
Indices{n} = idx{1};
NumNearestNeighbors(n) = length(idx{1});
end
else
for n = 1:N
[idx]=rangesearch(NS_kd,queryPoints(n,:),patchRadii(n));
Indices{n} = idx{1};
NumNearestNeighbors(n) = length(idx{1});
end
end
end
function [startRefined,endRefined] = getNewTraceVectors3D(XYZ,samplingLength,traceLength,parallelize)
% Resample Surface
[XYZ_out] = seg3D.ResampleSurface(XYZ,samplingLength);
xNew = XYZ_out(:,1);
yNew = XYZ_out(:,2);
zNew = XYZ_out(:,3);
% Calculate new centers after interpolating for even sampling
xNew0 = mean(xNew);
yNew0 = mean(yNew);
zNew0 = mean(zNew);
xNewCntrd = xNew - xNew0;
yNewCntrd = yNew - yNew0;
zNewCntrd = zNew - zNew0;
% Calculate radial coordinates with newly centered coords.
%[~,~,R] = cart2sph(xNewCntrd,yNewCntrd,zNewCntrd);
patchRadius = 2;
normVec = seg3D.getLocalNormals3D(xNew,yNew,zNew,patchRadius,parallelize);
%% CHECK BELOW...
R = traceLength;
startRefined = [xNew,yNew,zNew] - normVec.*R/2; % Consider using fit parameters to size trace vectors...
endRefined = [xNew,yNew,zNew] + normVec.*R/2;
%VISUAL CHECK IF DESIRED...
%close all
%scatter3(startRefined(:,1),startRefined(:,2),startRefined(:,3),'.')
%axis equal
%hold on
%scatter3(endRefined(:,1),endRefined(:,2),endRefined(:,3),'.')
end
function [x,y,z] = getNormSpiralCoords(N)
z = linspace(1-1/N,1/N-1,N)';
radius=sqrt(1-z.^2);
goldenAngle = pi*(3-sqrt(5));
theta = goldenAngle*(1:N)';
x = radius.*cos(theta);
y = radius.*sin(theta);
end
function [normVec] = getLocalNormals3D(x,y,z,patchRadius,parallelize)
if nargin == 4
parallelize = 0;
end
tic
fprintf(' Finding normals for retrace...')
N = length(x); % Number of coordinates
normVec = nan(N,3);
indPatch = seg3D.getNeighborIndices(x,y,z,patchRadius,parallelize);
Xct = mean([x,y,z]);
patchCoords = cell(N,1);
for n = 1:N
xPatch = x(indPatch{n});
yPatch = y(indPatch{n});
zPatch = z(indPatch{n});
patchCoords{n} = [xPatch,yPatch,zPatch];
end
for n = 1:N
xPatch = patchCoords{n}(:,1);
yPatch = patchCoords{n}(:,2);
zPatch = patchCoords{n}(:,3);
Xq = [x(n),y(n),z(n)];
X = [xPatch-nanmean(xPatch),yPatch-nanmean(yPatch),zPatch-nanmean(zPatch)];
numInPatch = length(X);
S = 1/(numInPatch-1)*(X'*X);
[V,~] = eig(S);
OrientMatrix = [V(:,3),V(:,2),V(:,1)]; % reverse vector order so surface normal is in z
Xlq = Xq*OrientMatrix;
Xlct = Xct*OrientMatrix;
%Check that vector is pointing outward
if (Xlct(3) - Xlq(3)) > 0
FlipUpsideDown = [1 0 0; 0 -1 0; 0 0 -1]; % Rotates 180 deg about x-axis
OrientMatrix = OrientMatrix*FlipUpsideDown;
end
nV = OrientMatrix(:,3)';
normVec(n,:) = nV;
end
tNRT = toc;
fprintf('(%3.1f seconds)\n',tNRT)
end
function [samplingDensity] = getSamplingDensity(XYZ,parallelize)
if nargin == 1
parallelize = 0;
end
X = XYZ(:,1);
Y = XYZ(:,2);