-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathcalcfunctions.m
4120 lines (3612 loc) · 124 KB
/
calcfunctions.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
function varargout = calcfunctions(varargin)
% CALCFUNCTIONS
% Functions for doing calculations
% Moved out from segment_main by Nisse Lundahl
%Invoke subfunction
macro_helper(varargin{:}); %future macro recording use
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
%---------------------
function segmentationintersection_helper(panel,t)
%-----------------------
%This is updates segmentation intersections for selected panel and timeframe.
global DATA
[DATA.endointersectionx{panel}{t},DATA.endointersectiony{panel}{t}] = ...
calcfunctions('calcsegmentationintersections',panel,'epi',t,DATA.ViewPanelsType{panel});
[DATA.epiintersectionx{panel}{t},DATA.epiintersectiony{panel}{t}] = ...
calcfunctions('calcsegmentationintersections',panel,'epi',t,DATA.ViewPanelsType{panel});
%----------------------------------------------
function [x,y] = resamplecurve(x,y,numpoints) %#ok<DEFNU>
%----------------------------------------------
%Calculate total length and remove duplicate points
global DATA
if nargin==2
numpoints = DATA.NumPoints;
end
if length(x)>1
len = sqrt(...
conv2(x',[1 -1],'valid').^2+...
conv2(y',[1 -1],'valid').^2);
len = [0;len(:)]; %Add zero first
len = cumsum(len);
tempind = find(conv2(len,[1;-1],'valid')~=0); %Remove doublets
len = [len(1);len(tempind+1)]; %used in interpolation later
x = [x(1); x(tempind+1)];
y = [y(1); y(tempind+1)];
totallength = len(end);%used in interpolation later
%Resample
x = interp1(len,x,linspace(0,totallength,numpoints),'pchip');
y = interp1(len,y,linspace(0,totallength,numpoints),'pchip');
%assert correct clockwise order
[x,y] = mypoly2cw(x,y);
xr = y;
yr = x;
mx = mean(xr);
my = mean(yr);
[~,inda] = min(angle(complex(mx-xr,my-yr)));
x(1:(numpoints-inda)) = yr(inda+1:end);
y(1:(numpoints-inda)) = xr(inda+1:end);
x((numpoints+1-inda):end) = yr(1:inda);
y((numpoints+1-inda):end) = xr(1:inda);
end
%---------------------
function preallocatesegmentationintersections(panels) %#ok<DEFNU>
%-----------------------
%This is the preallocation of segmentation intersections Not doing the
%calculation within image rendering should be a large speed up.
global DATA SET
%If no panels supplied these are the panels that needs calculation. A panel can be empty thats
%why this is needed.
if nargin == 0
panels = find(DATA.ViewPanels(DATA.ViewPanels>0));
end
if length(DATA.endointersectionx)~=length(DATA.ViewPanels)
DATA.endointersectionx = cell(1,length(DATA.ViewPanels));
DATA.endointersectiony = cell(1,length(DATA.ViewPanels));
DATA.epiintersectionx = cell(1,length(DATA.ViewPanels));
DATA.epiintersectiony = cell(1,length(DATA.ViewPanels));
%if the number of panels has changed we need to update all panel
%intersections. This overrides the input panels
panels = find(DATA.ViewPanels(DATA.ViewPanels>0));
end
for i = panels
DATA.endointersectionx{i} = cell(1,SET(DATA.ViewPanels(i)).TSize);
DATA.endointersectiony{i} = cell(1,SET(DATA.ViewPanels(i)).TSize);
DATA.epiintersectionx{i} = cell(1,SET(DATA.ViewPanels(i)).TSize);
DATA.epiintersectiony{i} = cell(1,SET(DATA.ViewPanels(i)).TSize);
end
for i = panels
%Contour intersection
for t = 1:SET(DATA.ViewPanels(i)).TSize
segmentationintersection_helper(i,t)
end
end
%------------------------------------------
function [edmax, MaxdiameterPoint, Zslice_no] = maxsaxdiameter(no,tf,type) %#ok<DEFNU>
%------------------------------------------
%Get maximum endocardial diameter in short-axis cine stack
% Input: no - no of stack,
% tf - time frame,
% type - 'RV', 'LV'
% Output: edmax - max LV/RV diameter
% MaxdiameterPoint - points with the largest distance in form [x,y]
% Zslice_no - slice number with largest LV/RV diameter
%
global SET
xres = SET(no).ResolutionX;
yres = SET(no).ResolutionY;
switch type
case 'LV'
edxall = squeeze(SET(no).EndoX(:,tf,:));
edyall = squeeze(SET(no).EndoY(:,tf,:));
edmax = 0;
edmax_temp = 0;
MaxdiameterPoint = [];
Zslice_no=[];
for z = 1:SET(no).ZSize
edx = edxall(:,z);
if ~isnan(edx(1))
edy = edyall(:,z);
edxmat = repmat(edx,1,length(edx));
edymat = repmat(edy,1,length(edy));
eddist = sqrt((xres*(edxmat'-edxmat)).^2+ ...
(yres*(edymat'-edymat)).^2);
% edmax = max(edmax,max(eddist(:)));
edmax_temp=max(eddist(:));
if edmax_temp>edmax
edmax=edmax_temp;
[row, col] = find(ismember(eddist, edmax));
MaxdiameterPoint(1,:)=[edx(row(1)),edy(row(1))];
MaxdiameterPoint(2,:)=[edx(col(1)),edy(col(1))];
Zslice_no=z; % #slice number
end
end
end
% In case of RV max diameter, first we find center point of LV based on EPI contour
% Then we finiding septum, and calculate the middle point of septum
% The last part is to find the intersection between line (center LV and center septum) with RV endo contur.
% This intersecton defines our maximal RV dimater.
case 'RV'
edmax = 0;
edmax_temp = 0;
MaxdiameterPoint=[];
Zslice_no=[];
edxall = squeeze(SET(no).RVEndoX(:,tf,:));
edyall = squeeze(SET(no).RVEndoY(:,tf,:));
epxLVall = squeeze(SET(no).EpiX(:,tf,:));
epyLVall = squeeze(SET(no).EpiY(:,tf,:));
%Center of Epi LV ROI for each slice
xLVcen=mean(epxLVall);
yLVcen=mean(epyLVall);
% Convhull RV roi
for z = 1:SET(no).ZSize
edx = edxall(:,z);
edxLV=epxLVall(:,z);
if isnan(edxLV(1))
continue
end
if ~isnan(edx(1))
edy = edyall(:,z);
k=convhull(edx,edy);
xhull=edx(k);
yhull=edy(k);
len=diff(xhull).^2+diff(yhull).^2;
%maximum length line segment is made out of the septum points. An addition
%to make this more robust is to pick out the n largest line segments and check the area of the concavity the maximum area concavity should be the LV.
[~,ind]=max(len);
a=[xhull(ind),yhull(ind)];
b=[xhull(ind+1),yhull(ind+1)];
%find closest points on RV contour
[~,ind_a]=min((edx-a(1)).^2+(edy-a(2)).^2);
[~,ind_b]=min((edx-b(1)).^2+(edy-b(2)).^2);
%number of poinst between A and B
if (edx(ind_a) < edx(ind_a+1))&&(edx(ind_b) < edx(ind_b+1))
noABx=[edx(1:ind_a-1); edx(ind_b+1:end)];
else
noABx=edx(ind_a+1:ind_b-1);
end
% point which is in the middle between A and B
ind_midAB=ceil(length(noABx)/2);
% middle point
if ind_a <= ind_midAB
midRVab=[edx(end-(ind_midAB-ind_a)), edy(end-(ind_midAB-ind_a))];
else
midRVab=[edx(ind_a-ind_midAB), edy(ind_a-ind_midAB)];
end
% line between center LV and centre of septal RV
x=[xLVcen(z), midRVab(1)];
y=[yLVcen(z), midRVab(2)];
p = polyfit(x,y,1);
% calculate line
x_space=linspace(min(edx), max(edx),100);
y_space=p(1)*x_space+p(2);
% Intersection between the line LV - septal centre and RV segmentation
[xi,yi] = polyxpoly(edx,edy,x_space,y_space);
% Max RV diameter
edmax_temp=sqrt((xres*diff(xi)).^2+(yres*diff(yi)).^2);
if edmax_temp>edmax
edmax=edmax_temp;
MaxdiameterPoint(1,:)=[xi(1),yi(1)];
MaxdiameterPoint(2,:)=[xi(2),yi(2)];
Zslice_no=z; % #slice number
end
end
end
end
%----------------------------------------
function [N,xc,yc,zc] = lsplanefit(x,y,z) %#ok<DEFNU>, used by makecut
%---------------------------------------
%This function calculates the plane least squares fit to the points given by the
%x,y,z coordinates. It uses the null space of a matrix formulation of the .
%An idea is to subtract the first point this will force the plane to lie on
%the first point.
%x=rand(1,10),y=rand(1,10),z=rand(1,10)
xc = mean(x);
yc = mean(y);
zc = mean(z);
x= x - xc;
y= y - yc;
z= z - zc;
% %using leastsquares
% Sxx = x*x';
% Sxy = x*y';
% Syy = y*y';
% Sxz = x*z';
% Syz = y*z';
%
% %using that there is no problem with fixating one param in the equation and
% %that the point cloud is zero centered i.e sum(x)=0 etc we get that it is
% %sufficient to solve the below system
% A = [Sxx,Sxy;Sxy,Syy];
% B = -[Sxz;Syz];
%
% params = A\B;
% N = [params;1];
%using svd
A=[x;y;z];
[U,~,~] = svd(A,'econ');
N = cross(U(:,1),U(:,2));
% point = [0,0,0];
% normal = N';
% a plane is a*x+b*y+c*z+d=0
% [a,b,c] is the normal. Thus, we have to calculate
% d and we're set
% d = -point*normal'; %'# dot product for less typing
% % create x,y
% [xx,yy]=ndgrid(linspace(-1,1,10),linspace(-1,1,10));
%
% % calculate corresponding z
% zz = (-normal(1)*xx - normal(2)*yy - d)/normal(3);
% plot the surface
% figure
% surf(xx,yy,zz)
% hold on
% plot3(x',y',z','k*')
%----------------------
function calcvolume(no) %#ok<DEFNU>
%----------------------
%Calculate volume of segmentation and updates. Updates both
%lv and rv segmentation. Calls subfunctions to do the work.
calclvvolume(no);
calcrvvolume(no);
volume_helper(no); %Find peak ejection rate, and empty volumes etc.
%-------------------------------------------
function varargout = calclvvolume(no,docomp)
%-------------------------------------------
%Calculate LV volume. Docomp if to use longaxis motion, see below.
%Uses area*(thickness+slicedist)
%NOTE: the exported LVM do NOT include Papillary volume (PV)
global DATA SET
if nargin<2
docomp=true;
elseif SET(no).Longaxis > 1%SET(NO).Longaxis > 1
docomp = true;
end
if SET(no).Rotated
calclvvolumepolar(no);
return;
end
% needtodo = false;
% if ~isempty(SET(no).EndoX)
% needtodo = true;
% end
% if ~isempty(SET(no).EpiX)
% needtodo = true;
% end
ind = (findfunctions('findslicewithendo',no))|(findfunctions('findslicewithepi',no)); %Accepts empty endo and epi if exist
if ~any(ind)
SET(no).LVV = nan(1,SET(no).TSize);
SET(no).EPV = SET(no).LVV;
SET(no).LVM = SET(no).LVV;
SET(no).PV = zeros(size(SET(no).LVV));
SET(no).PFR = 0;
SET(no).PER = 0;
SET(no).PFRT = 1;
SET(no).PERT = 1;
SET(no).ESV = 0;
SET(no).EDV = 0;
SET(no).EF = 0;
SET(no).SV = 0;
if nargout>0
varargout = cell(1,1);
varargout{1} = [];
end
if nargout>1
varargout{2} = [];
end
return;
end
%Find what slices to do
if SET(no).ZSize>1
pos = find(ind);
else
pos = 1;
end
% LVVall = zeros(length(pos),SET(no).TSize);
% EPVall = zeros(length(pos),SET(no).TSize);
% if isempty(SET(no).EndoX)
% %This far then create
% SET(no).EndoX = nan(DATA.NumPoints,SET(no).TSize,SET(no).ZSize);
% SET(no).EndoY = nan(DATA.NumPoints,SET(no).TSize,SET(no).ZSize);
% end
%
% if isempty(SET(no).EpiX)
% %This far then create
% SET(no).EpiX = nan(DATA.NumPoints,SET(no).TSize,SET(no).ZSize);
% SET(no).EpiY = nan(DATA.NumPoints,SET(no).TSize,SET(no).ZSize);
% end
%Loop over all segmented slices
if ~isempty(SET(no).EndoX)
LVVall = squeeze(polyarea(SET(no).ResolutionY*SET(no).EndoY(1:end-1,:,pos),...
SET(no).ResolutionX*SET(no).EndoX(1:end-1,:,pos))*(SET(no).SliceThickness+SET(no).SliceGap)/1000);
if length(pos)>1
LVVall = nansum(LVVall');
end
else
LVVall = zeros(1,SET(no).TSize);
end
if ~isempty(SET(no).EpiX)
EPVall = squeeze(polyarea(SET(no).ResolutionY*SET(no).EpiY(1:end-1,:,pos),...
SET(no).ResolutionX*SET(no).EpiX(1:end-1,:,pos))*(SET(no).SliceThickness+SET(no).SliceGap)/1000);
if length(pos)>1
EPVall = nansum(EPVall');
end
else
EPVall = zeros(1,SET(no).TSize);
end
% for sloop=1:length(pos)
% for tloop=1:SET(no).TSize
% if ~isempty(SET(no).EndoX)&&~isnan(SET(no).EndoX(1,tloop,pos(sloop)))
% A = stablepolyarea(...
% SET(no).ResolutionY*SET(no).EndoY(1:end-1,tloop,pos(sloop)),...
% SET(no).ResolutionX*SET(no).EndoX(1:end-1,tloop,pos(sloop)));
% LVVall(sloop,tloop)=A*(SET(no).SliceThickness+SET(no).SliceGap)/1000; %to cm3
% end
% if ~isempty(SET(no).EpiX)&&~isnan(SET(no).EpiX(1,tloop,pos(sloop)))
% A = stablepolyarea(...
% SET(no).ResolutionY*SET(no).EpiY(1:end-1,tloop,pos(sloop)),...
% SET(no).ResolutionX*SET(no).EpiX(1:end-1,tloop,pos(sloop)));
% EPVall(sloop,tloop)=A*(SET(no).SliceThickness+SET(no).SliceGap)/1000; %to cm3
% end
% end
% end
%Sum to get total volume
% if length(pos)>1
% SET(no).LVV = sum(LVVall');
% SET(no).EPV = sum(EPVall');
% else
SET(no).LVV = LVVall;
SET(no).EPV = EPVall;
% end
SET(no).LVM = SET(no).EPV-SET(no).LVV+SET(no).PV;
if nargout>0
varargout = cell(1,1);
varargout{1} = LVVall;
end
if nargout>1
varargout{2} = EPVall;
end
if nargout>2
varargout{3} = 1.05*(EPVall-LVVall); %LVM in g, NOTE not include Papillary volume (PV)
end
%Update EDV,ESV
SET(no).EDV = SET(no).LVV(SET(no).EDT);
if ~isequal(SET(no).EDT,SET(no).EST)
SET(no).ESV = SET(no).LVV(SET(no).EST);
else
SET(no).ESV = NaN;
end
if (SET(no).ZSize>2)&&docomp
LVVnocomp = SET(no).LVV;
EPVnocomp = SET(no).EPV;
for rloop=1:1 %Converges very quickly
%Calculate compensation mechanism
if (SET(no).LVV(SET(no).EDT)-SET(no).LVV(SET(no).EST)~=0)
pp = SET(no).LVV;
pp = pp-SET(no).LVV(SET(no).EST);
pp = pp./(SET(no).LVV(SET(no).EDT)-SET(no).LVV(SET(no).EST));
pp = 1-pp;
pp = min(max(pp,0),1);
else
pp = ones(size(SET(no).LVV));
end
err = zeros(1,20);
%Compensate
%pp = pp.*pp;
%Check if autodetect
if SET(no).AutoLongaxis
for loop=1:20
%Calculate slices
slices = (loop-1); %Convert to mm
slices = slices/(SET(no).SliceThickness+SET(no).SliceGap); %Convert to slices
sloop=1;
SET(no).LVV = LVVnocomp; %Restore
SET(no).EPV = EPVnocomp;
while (slices>0)&&(sloop<size(LVVall,1))
%Remove whole slice or fraction of it.
SET(no).LVV = SET(no).LVV-min(slices,1)*LVVall(sloop,:).*pp;
SET(no).EPV = SET(no).EPV-min(slices,1)*EPVall(sloop,:).*pp;
slices = slices-1;
sloop = sloop+1;
end
%Calculate error
err(loop) = max(SET(no).EPV-SET(no).LVV+SET(no).PV)-min(SET(no).EPV-SET(no).LVV+SET(no).PV);
end %loop
[~,inde] = min(err);
SET(no).Longaxis = inde;
end %autodetect
%Convert to slices => 1mm between, first is zero
slices = (SET(no).Longaxis-1);
if isempty(slices)
slices = 0;
end
slices = slices/(SET(no).SliceThickness+SET(no).SliceGap);
%Compensate the last time, now store it!
sloop=1;
SET(no).LVV = LVVnocomp; %Restore
SET(no).EPV = EPVnocomp;
%Check if need to fix with outline
if ~isempty(SET(no).EndoX)
zloop = find(not(isnan(SET(no).EndoX(1,SET(no).CurrentTimeFrame,:))));
elseif ~isempty(SET(no).EpiX)
zloop = find(not(isnan(SET(no).EpiX(1,SET(no).CurrentTimeFrame,:))));
else
zloop = [];
end
if isempty(zloop)
slices = 0;
zloop = SET(no).CurrentSlice;
else
zloop = zloop(1);
end
while (slices>0)&&(sloop<=size(LVVall,1))
%Remove whole slice or fraction of it.
SET(no).LVV = SET(no).LVV-min(slices,1)*LVVall(sloop,:).*pp;
SET(no).EPV = SET(no).EPV-min(slices,1)*EPVall(sloop,:).*pp;
zloop = zloop+1;
slices = slices-1;
sloop = sloop+1;
end
end %rloop
if DATA.Silent
return;
end
end %If docompensation
%-----------------------------
function calclvvolumepolar(no)
%-----------------------------
%Calculate volume of lv when rotated image stacks.
%no is the imsage stack. The LV volume calculation includes
%longaxis compensation taken from the setting in the GUI and
%stored in the SET structure.
global SET
ind = (findfunctions('findslicewithendo',no))|(findfunctions('findslicewithepi',no));
if ~any(ind)
SET(no).LVV = nan(1,SET(no).TSize);
SET(no).EPV = SET(no).LVV;
SET(no).LVM = SET(no).LVV;
SET(no).PV = zeros(size(SET(no).LVV));
SET(no).PFR = 0;
SET(no).PER = 0;
SET(no).PFRT = 1;
SET(no).PERT = 1;
SET(no).ESV = 0;
SET(no).EDV = 0;
SET(no).EF = 0;
SET(no).SV = 0;
return;
end
%Find rotation axis, rotation around x-axis
my = SET(no).RotationCenter;
%'Angle' increment
alphapart = 1/(2*SET(no).ZSize);
%--- Calc endo volume
if ~isempty(SET(no).EndoX) && ~all(isnan(SET(no).EndoX(:)))
%Calc dx/ds
temp = double(SET(no).ResolutionX)*double(cat(1,SET(no).EndoX(:,:,ind),SET(no).EndoX(1,:,ind)))/10; %cm
if ndims(temp)==2
dxds = conv2(temp,[1;-1],'same');
dxds = dxds(1:(end-1),:,:); %Remove "outside" data
else
dxds = econv3(temp,[-1;1]);
dxds = dxds(2:end,:,:); %Different convolves have different "outside"
end
y = double(SET(no).ResolutionY)*double((SET(no).EndoY(:,:,ind)-my))/10; %cm
vol = pi*alphapart*y.^2.*sign(y).*dxds;
vol = nansum(nansum(vol,1),3);
SET(no).LVV = vol; %Store
else
SET(no).LVV = zeros(1,SET(no).TSize);
end
%--- Calc epi volume
if ~isempty(SET(no).EpiX) && ~all(isnan(SET(no).EpiX(:)))
temp = double(SET(no).ResolutionX)*double(cat(1,SET(no).EpiX(:,:,ind),SET(no).EpiX(1,:,ind)))/10; %cm
if ndims(temp)==2
dxds = conv2(temp,[1;-1],'same');
dxds = dxds(1:(end-1),:,:); %Remove "outside" data
else
dxds = econv3(temp,[-1;1]);
dxds = dxds(2:end,:,:); %Different convolves have different "outside"
end
y = double(SET(no).ResolutionY)*double(SET(no).EpiY(:,:,ind)-my)/10; %cm
vol = pi*alphapart*y.^2.*sign(y).*dxds;
vol = nansum(nansum(vol,1),3);
SET(no).EPV = vol; %Store
else
SET(no).EPV = zeros(1,SET(no).TSize);
end
%------------------------------------
function [varargout] = calcrvvolume(no)
%------------------------------------
%Calculate RV volume. no is the image stack.
%The RV volume calculation does not involve any longaxis
%compensation.
global SET
needtodo = false;
if ~isempty(SET(no).RVEndoX)
needtodo = true;
end
if ~isempty(SET(no).RVEpiX)
needtodo = true;
end
if SET(no).Rotated
calcrvvolumepolar(no);
return;
end
if ~needtodo
SET(no).RVV = zeros(1,SET(no).TSize);
SET(no).RVEPV = zeros(1,SET(no).TSize);
SET(no).RVEDV = 0;
SET(no).RVESV = 0;
SET(no).RVSV = 0;
SET(no).RVEF = 0;
SET(no).RVM = 0;
varargout = cell(1,nargout);
return;
end
ind = (findfunctions('findslicewithrvendo',no))|(findfunctions('findslicewithrvepi',no)); %Accepts empty endo and epi if exist
%Find what slices to do
if SET(no).ZSize>1
pos = find(ind);
else
pos = 1;
end
RVVall = zeros(length(pos),SET(no).TSize);
EPVall = zeros(length(pos),SET(no).TSize);
%Loop over all segmented slices
SET(no).RVV = zeros(1,SET(no).TSize);
if ~isempty(SET(no).RVEndoX)
for sloop=1:length(pos)
for tloop=1:SET(no).TSize
if ~isnan(SET(no).RVEndoX(1,tloop,pos(sloop)))
A = stablepolyarea(...
SET(no).ResolutionY*SET(no).RVEndoY(1:end-1,tloop,pos(sloop)),...
SET(no).ResolutionX*SET(no).RVEndoX(1:end-1,tloop,pos(sloop)));
RVVall(sloop,tloop)=A*(SET(no).SliceThickness+SET(no).SliceGap)/1000;
end
end
end
end
SET(no).RVV=nansum(RVVall,1); %Buggfix for RV calculation. Addded ,1 EH:
SET(no).RVEDV = SET(no).RVV(SET(no).EDT);
SET(no).RVESV = SET(no).RVV(SET(no).EST);
SET(no).RVEPV = zeros(1,SET(no).TSize);
if ~isempty(SET(no).RVEpiX)
for sloop=1:length(pos)
for tloop=1:SET(no).TSize
if ~isnan(SET(no).RVEpiX(1,tloop,pos(sloop)))
A = stablepolyarea(...
SET(no).ResolutionY*SET(no).RVEpiY(1:end-1,tloop,pos(sloop)),...
SET(no).ResolutionX*SET(no).RVEpiX(1:end-1,tloop,pos(sloop)));
EPVall(sloop,tloop)=A*(SET(no).SliceThickness+SET(no).SliceGap)/1000;
end
end
end
end
SET(no).RVEPV=nansum(EPVall,1); %Buggfix for RV calculation. Addded ,1 EH:
if nargout>0
varargout = cell(1,1);
varargout{1} = RVVall;
end
if nargout>1
varargout{2} = EPVall;
end
%-----------------------------
function calcrvvolumepolar(no)
%-----------------------------
%Calculate RV volume when rotated image stacks.
global SET
ind = (findfunctions('findslicewithrvendo',no))|(findfunctions('findslicewithrvepi',no));
if ~any(ind)
SET(no).RVV = nan(1,SET(no).TSize);
SET(no).RVEPV = SET(no).RVV;
SET(no).RVM = SET(no).RVV;
SET(no).RVESV = 0;
SET(no).RVEDV = 0;
SET(no).RVEF = 0;
SET(no).RVSV = 0;
return;
end
%Find rotation axis, rotation around x-axis
my = SET(no).RotationCenter;
%'Angle' increment
alphapart = 1/(2*SET(no).ZSize);
%--- Calc endo volume
if ~isempty(SET(no).RVEndoX)
%Calc dx/ds
temp = SET(no).ResolutionX*cat(1,SET(no).RVEndoX(:,:,ind),SET(no).RVEndoX(1,:,ind))/10; %cm
if ismatrix(temp)
dxds = conv2(temp,[1;-1],'same');
dxds = dxds(1:(end-1),:,:); %Remove "outside" data
else
dxds = econv3(temp,[-1;1]);
dxds = dxds(2:end,:,:); %Different convolves have different "outside"
end
y = SET(no).ResolutionY*(SET(no).RVEndoY(:,:,ind)-my)/10; %cm
vol = pi*alphapart*y.^2.*sign(y).*dxds;
vol = nansum(nansum(vol,1),3);
SET(no).RVV = vol; %Store
else
SET(no).RVV = zeros(1,SET(no).TSize);
end
%--- Calc epi volume
if ~isempty(SET(no).RVEpiX)
temp = SET(no).ResolutionX*cat(1,SET(no).RVEpiX(:,:,ind),SET(no).RVEpiX(1,:,ind))/10; %cm
if ndims(temp)==2
dxds = conv2(temp,[1;-1],'same');
dxds = dxds(1:(end-1),:,:); %Remove "outside" data
else
dxds = econv3(temp,[-1;1]);
dxds = dxds(2:end,:,:); %Different convolves have different "outside"
end
y = SET(no).ResolutionY*(SET(no).RVEpiY(:,:,ind)-my)/10; %cm
vol = pi*alphapart*y.^2.*sign(y).*dxds;
vol = nansum(nansum(vol,1),3);
SET(no).RVEPV = vol; %Store
else
SET(no).RVEPV = zeros(1,SET(no).TSize);
end
%-------------------------
function volume_helper(no)
%-------------------------
%Helper to find peak ejection, and empty volumes etc.
%Lots of checks to prevent NaN or Inf to be presented
%when some of the data are missing.
global SET
%Find zeros in volume
SET(no).LVV(SET(no).LVV==0) = NaN;
SET(no).EPV(SET(no).EPV==0) = NaN;
SET(no).RVV(SET(no).RVV==0) = NaN;
SET(no).RVEPV(SET(no).RVEPV==0) = NaN;
SET(no).LVM = SET(no).EPV-SET(no).LVV+SET(no).PV;
SET(no).RVM = SET(no).RVEPV-SET(no).RVV;
%Prevent that when endo is empty that epi may be viewed
if not(isnan(SET(no).EPV(1)))&&(isnan(SET(no).LVV(1)))
SET(no).LVV = zeros(size(SET(no).LVV));
end
%Find peak ejection rate, peak filling rate
if SET(no).TSize>2
%dLVV = conv2(SET(no).LVV,[1 -1]/SET(no).TIncr,'valid');
dLVV = diff(SET(no).LVV)./diff(SET(no).TimeVector);
[SET(no).PFR,SET(no).PFRT] = max(dLVV); %Peak filling rate
[SET(no).PER,SET(no).PERT] = min(dLVV); %Peak ejection rate
SET(no).PER = -SET(no).PER;
dRVV = diff(SET(no).RVV)./diff(SET(no).TimeVector);
[SET(no).RVPFR,SET(no).RVPFRT] = max(dRVV); %Peak filling rate
[SET(no).RVPER,SET(no).RVPERT] = min(dRVV); %Peak ejection rate
SET(no).RVPER = -SET(no).RVPER;
else
SET(no).PFR = 0;
SET(no).PER = 0;
SET(no).PFRT = 1;
SET(no).PERT = 1;
SET(no).RVPFR = 0;
SET(no).RVPER = 0;
SET(no).RVPFRT = 1;
SET(no).RVPERT = 1;
end
%Store LV-EDV,ESV,SV
SET(no).EDV = SET(no).LVV(SET(no).EDT)-SET(no).PV(SET(no).EDT);
if ~isequal(SET(no).EDT,SET(no).EST)
SET(no).ESV = SET(no).LVV(SET(no).EST)-SET(no).PV(SET(no).EST);
SET(no).SV = SET(no).EDV-SET(no).ESV; %Stroke volume
else
SET(no).ESV=NaN;
SET(no).SV=NaN;
end
%LV-EF
if SET(no).EDV>0
SET(no).EF = SET(no).SV/SET(no).EDV; %Ejection fraction
else
SET(no).EF = NaN;
end
if ~isempty(SET(no).RVEndoX)
%Store RV-EDV,ESV,SV
SET(no).RVEDV = SET(no).RVV(SET(no).EDT);
SET(no).RVESV = SET(no).RVV(SET(no).EST);
SET(no).RVSV = SET(no).RVEDV-SET(no).RVESV; %Stroke volume
%RV-EF
if SET(no).RVEDV==0 || isnan(SET(no).RVEDV) || isempty(SET(no).RVEDV)
SET(no).RVEF = 0;
else
SET(no).RVEF = SET(no).RVSV/SET(no).RVEDV; %Ejection fraction
end
end
if isnan(SET(no).RVEDV)
SET(no).RVEDV = 0;
end
if isnan(SET(no).RVESV)
SET(no).RVESV = 0;
end
if isnan(SET(no).RVSV)
SET(no).RVSV = 0;
end
if isnan(SET(no).RVEF)
SET(no).RVEF = 0;
end
if isequal(SET(no).EDT,SET(no).EST)
SET(no).RVESV=NaN;
SET(no).RVSV=NaN;
SET(no).RVEF=NaN;
end
%-------------------------------------
function age = calcageyearfraction(age,ageunit) %#ok<DEFNU>
%-------------------------------------
%Calculates age as fraction of the year
denominator = 372; %corresponds to the 12month*31days for easier calculations
switch lower(ageunit)
case 'm' %months
numerator = 31;
case 'd' %days
numerator = 1;
case 'w' %weeks
numerator = 7; % to calculate into corresponding number of days
case 'y' % years
return; % no calculation necessary
end
age = age*numerator/denominator;
%-------------------------------------
function [age,ageunit] = calcagewithunits(age) %#ok<DEFNU>
%-------------------------------------
%Calculates age that is given as fraction of the year into "normal"
denominator = 372; %corresponds to the 12month*31days for easier calculations
numdaysinmonth = 31;
if not(isempty(age))
if age >= 1 % corresponds to years
if age < 2
ageunit = dprintf('year');
else
ageunit = dprintf('years');
end
else
newage = age*denominator;
if newage < numdaysinmonth % corresponds to days
age = newage;
if age < 2
ageunit = dprintf('day');
else
ageunit = dprintf('days');
end
else %corresponds to months
age = newage/numdaysinmonth;
if age < 2
ageunit = dprintf('month');
else
ageunit = dprintf('months');
end
end
end
else
ageunit = '';
end
%-------------------------------------
function [agedigits,ageunit] = calcagefrombirthdate(birthdate, acqusitiondate) %#ok<DEFNU>
%-------------------------------------
%Calculates age as difference between birthdate and acquisition date
switch length(birthdate)
case 4
birthinputformat = 'yyyy';
case 8
birthinputformat = 'yyyyMMdd';
otherwise
agedigits = [];
ageunit = '';
return;
end
try
datedifference = between(datetime(birthdate,'InputFormat',birthinputformat),...
datetime(acqusitiondate,'InputFormat','yyyyMMdd'),...
{'years','months','days'});
catch me
mydispexception(me)
agedigits = [];
ageunit = '';
return
end
% split into number of years/moths/days
[numyears,nummonths,numdays] = split(datedifference,{'years','months','days'});
% set up digits and units
if numyears > 0 % years digit
agedigits = numyears;
ageunit = 'y';
else
if nummonths > 0
agedigits = nummonths;
ageunit = 'm';
else
agedigits = numdays;
ageunit = 'd';
end
end
%-------------------------------------
function bsa = calcbsa(weight,height) %#ok<DEFNU>
%-------------------------------------
%Calculates BSA. Formula based on Mosteller
%weight in kilo and height in cm.
%This code is duplicated in segdicomtags to avoid compiler leak of
%segmentserversorter
bsa = sqrt(weight*height/3600);
%-----------------------------------
function ticks = calcticks(num,res) %#ok<DEFNU>
%-----------------------------------
%Helper fcn to calculate length of ticks in volumegraph
totlength = floor(num*res/10-1e-4); %length in cm
ticks = 10*(1:totlength); %ticks i mm
ticks = ticks/res; %ticks i pixels
%--------------------------
function im = truedata2im(z,no) %#ok<DEFNU>
%--------------------------
%Inverse of calctruedata
global SET NO
if nargin<2
no = NO;
end
if not(isa(z,'int16')) && ~isempty(SET(no).IntensityOffset)
%z = im*SET(no).IntensityScaling+SET(no).IntensityOffset;
im = (z-SET(no).IntensityOffset)/SET(no).IntensityScaling;
else
im = z;
end
%-------------------------------
function z = calctruedata(im,no)
%-------------------------------
%Calculate true image intensities (as before Segment internal
%normalization). Uses IntensityScaling and IntensityOffset stored
%in SET structure. im is input image, and no is image stack,
%where to take the scaling from.
global SET NO
if nargin<2
no = NO;
end
if isequal(SET(no).IntensityScaling,1) && isequal(SET(no).IntensityOffset,0)