-
Notifications
You must be signed in to change notification settings - Fork 4
/
MatSurv.m
1133 lines (999 loc) · 41 KB
/
MatSurv.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] = MatSurv(TimeVar, EventVar, GroupVar, varargin)
% USAGE:
% MatSurv(TimeVar, EventVar, GroupVar,'param', value, ...) creates a Kaplan-Meier plot,
% a risk table and calculates a log rank p-value
%
% [p] = MatSurv( ... ) returns the log rank p-value
% [p, fh] = MatSurv( ... ) returns both p-value and figure handle
% [p, fh, stats] = MatSurv( ... ) returns additions stats from log rank test
% [p, fh, stats] = MatSurv([], [], [], ... ) loads test dataset
%
% INPUTS:
% * 'TimeVar' is a vector with numeric time to event, either observed or
% censored. Values less than zero will be removed by default
%
% * 'EventVar' is a vector or cell array defining events or censored
% observation. Events are defined with a 1 and censored point with a 0. By
% default 'Dead', 'Deceased', 'Relapsed', 'Yes', 'Event' 'Progression' &
% 'Progressed' are considered as events.
% 'Alive', 'Living', 'Not Relapsed', 'DiseaseFree', 'No' 'NoEvent'
% 'Censored' 'NoProgression' are considers as censored
% 'EventDefinition' can be used to define other types of events
%
% * 'GroupVar' is a vector or cell array defining the different groups.
% If it is a continues variable median cut will be used as a default.
%
% OUTPUTS:
% * p : log rank p-value
% * fh : figure handle to KM-plot figure
% * stats : Additional statistics from the log rank test
%
% stats =
% struct with fields:
%
% GroupNames: Cell with group names
% p_MC: log rank p-value (Mantel-Cox)
% Chi2_MC: Chi square (Mantel-Cox)
% HR_logrank: Hazard Ratio (log rank)
% HR_95_CI_logrank: 95% Confidence intervals [lower upper]
% HR_logrank_Inv: Inverted Hazard Ratio (log rank)
% HR_95_CI_logrank_Inv: Inverted 95% Confidence intervals [lower upper]
% HR_MH: Hazard Ratio (Mantel-Haenszel)
% HR_95_CI_MH: 95% Confidence intervals [lower upper]
% HR_MH_Inv: Inverted Hazard Ratio (Mantel-Haenszel)
% HR_95_CI_MH_Inv: Inverted 95% Confidence intervals [lower upper]
% MedianSurvivalTime: Median survival time for each group
%
%
% OTHER PARAMETERS (passed as parameter-value pairs)
% * 'NoPlot': A true/false value which, if true, no figure is created
% (default: false)
%
% * 'NoRiskTable': A true/false value which, if true, no risk table is
% included in the KM-plot. (default: false)
%
% * 'CutPoint': Either a string or scalar/vector with cut points to be used
% for defining groups based on a continuous 'GroupVar' input variable
% Allowed names are: 'Median', 'Quartile' or 'Tertile'
% If a scalar or vector is given the groups will be defined based on the
% cut points. (default: 'Median')
%
% * 'GroupsToUse': Cell array defining what groups to use from the GroupVar
% variable. Works only if GroupVar is a cell array. (default: all groups are used)
%
% * 'GroupOrder': A cell array defining the group order to be used in the
% legend. (default: Groups are sorted alphabetically)
%
% * 'EventDefinition': Two element cell array where the first cell defines
% the event and the second censored values. Example {'Dead','Alive'}
%
% * 'TimeMin': Scalar defining minimum valid time point. Subjects with time
% values below this will be removed. (default: 0)
%
% * 'TimeMax': Scalar value defining righ censoring time. Subjects with
% TimeVar > TimeMax will be set to TimeMax and considered as censored.
% (default: [])
%
% * 'PairWiseP': A true/false for calculating pairwise log rank test
% between group pairs, useful if there is more than two groups. (default: false)
%
% * 'Print': A true/false value which, if true, survival statistics are
% printed in the command window(default: true)
%
% * 'NoWarnings': A true/false value which, if true, no warnings are printed
% if subjects are removed. (default: false)
%
% * 'MedianLess': By default 'x < median' is used for median cut, but if false
% 'x > median' is used instead, only affect the results when there
% is an odd number of samples (default: true)
%
%
% KM plot options
%
% * 'LineColor': Either a matrix of size numLevels-by-3 representing the
% colormap to be used or a string for a MATLAB colormap (lines, parula,
% cool, prism) or 'JCO' 'nejm' 'Lancet' 'Science' 'Nature','lines' for a
% set of Journal dependent palettes or my default 'aeb01' (default:'aeb01')
%
% * 'FlipGroupOrder': Flips the order of the groups in the legend.
% (default: false)
%
% * 'FlipColorOrder': Flips the color order of the groups.
% (default: false)
%
% * 'KM_position': Vector defining the KM axes for the KM plot
% (default: [0.3 0.4 0.68 0.45])
%
% * 'RT_position': Vector defining the Risk Table axes for the KM plot
% (default: [0.3 0.05 0.68 0.20])
%
% * 'TimeUnit': String defining time unit displayd on the x-axis.
% (default: 'Months')
%
% * 'BaseFontSize': Base font size for all text in the plot
% (default: 16)
%
% * 'DispP': A true/false value which, if true, log rank test p-value
% is displayed on the KM-plot. (default: true)
%
% * 'DispHR': A true/false value which, if true, Hazard ration (HR)
% is displayed on the KM-plot. (default: true)
%
% * 'Use_HR_MH': A true/false value which, if true, Mantel-Haenszel HR
% is displayed instead of the logrank HR. (default: true)
%
% * 'InvHR': A true/false value which, if true, the inverted HR value
% is displayed on the KM-plot. (default: false)
%
% * 'DrawMSL': A true/false value which, if true, a line for the median
% survival time is drawn in the KM-plot. (default: false)
%
% * 'XLim': Vector defining the XLim. Do not affect the log rank test
% (default: automatic)
%
% * 'LineWidth': Scalar defining the line width used in the KM-plot
% (Default: 2)
%
% * 'LineStyle': Cell array defining the linestyle for the KM-plot.
% If an array is given each group will have different linestyle, for example
% 'LineStyle',{'-','--',':','-.'}
% (Default: {'-'})
%
% * 'CensorLineWidth': Scalar defining the linewith of the censored ticks
% (default: 2)
%
% * 'CensorLineLength': Scalar defining the length of the censored ticks
% (Default: 0.02)
%
% * 'CensorLineColor': Text string defining color of censor ticks. 'same'
% gives the same colors as the lines while 'k' would make them all black
% (Default: 'same')
%
% * 'Xstep': Scalar defining the X tick step length.
% (defaut: automatic)
%
% * 'XTicks': Vector defining the position of the X-tick marks
% (Default: automatic)
%
% * 'XMinorTick': Scalar defining the number of minor ticks between major X
% ticks (Default: 1)
%
% * 'Xlabel': Text string for X-label (Default: 'Time (Months)' )
%
% * 'XlabelOptions': MATLAB Name-value pair arguments for xlabel (Default: '')
%
% * 'XLabelFontSize': Scalar describing Xlabel font size change compared
% to base font size (Default: 0)
%
% * 'XTickFontSize': Scalar describing Xtick font size change compared
% to base font size (Default: -2)
%
% * 'YTicks': Vector defining the position of the X-tick marks
% (Default: [0:0.2:1])
%
% * 'YMinorTick': Scalar defining the number of minor ticks between major Y
% ticks (Default: 1)
%
% * 'Ylabel': Text string for Y-label (Default: 'Survival Probability' )
%
% * 'YlabelOptions': MATLAB Name-value pair arguments for ylabel (Default: '')
%
% * 'YLabelFontSize': Scalar describing Ylabel font size change compared
% to base font size (Default: 0)
%
% * 'YTickFontSize': Scalar describing Ytick font size change compared
% to base font size (Default: -2)
%
% * 'Title': Text string for Title (Default: '' )
%
% * 'TitleOptions': MATLAB Name-value pair arguments for Title (Default: '')
%
% * 'LegendFontSize': Scalar describing Legend font size change compared
% to base font size (Default: -2)
%
% * 'PvalFontSize': Scalar describing p-value font size change compared
% to base font size (Default: 0)
%
% Risk table plot options
% * 'RT_FontSize': Scalar describing Risk Table font size change compared
% to base font size (Default: 0)
%
% * 'RT_Color': Text string defining color of Risk table text. 'same'
% gives the same colors as the groups in the KM plot while 'k' would make
% them all black (Default: 'same')
%
% * 'RT_Title': Text string for Risk Table Title (Default: '' )
%
% * 'RT_TitleOptions': MATLAB Name-value pair arguments for Risk Table Titel (Default: '')
%
% * 'RT_YLabel': True/False for displaying the group names on the Risk table
% Y-axis (Default: True )
%
% EXAMPLES:
% [p,fh,stats] = MatSurv([], [], [],'Xstep',4,'Title','MatSurv KM-Plot','FlipColor',1,'XMinorTick',3);
%
%
% MatSurv do NOT use any toolboxes
%
% More examples can be found at: https://github.com/aebergl/MatSurv
%
% *** Anders Berglund ***
% Check TimeVar, EventVar, GroupVar variables
if nargin < 3
error('MatSurv requires at least 3 input argument');
end
% Load test data
if isempty(TimeVar) && isempty(EventVar) && isempty(GroupVar)
[TimeVar, EventVar, GroupVar] = MatSurvLoadTestData;
varargin =[varargin,{'TimeUnit','Weeks'}];
end
% Check that they are all vectors
if min(size(TimeVar)) ~= 1 || min(size(EventVar)) ~= 1 || min(size(GroupVar)) ~= 1
error('TimeVar, EventVar, GroupVar must all be vectors or cell arrays');
end
% Check that they all are equal length
if (length(TimeVar) ~= length(EventVar)) || (length(TimeVar) ~= length(GroupVar)) || (length(EventVar) ~= length(GroupVar))
error('TimeVar, EventVar & GroupVar must all have equal length');
end
% Check for MATLAB version, currently MatSurv only work with 9.1 (2016b) and later
if verLessThan('matlab','9.1')
error('MatSurv do not work with this version of MATLAB');
end
%Parse input and set default values
options = MatSurvParseInput(varargin{:});
% Check input and clean input data
[TimeVar, EventVar, GroupVar] = MatSurvCleanData(TimeVar, EventVar, GroupVar, options);
% Define events 1=event, 0=no event but it also checks for dead/alive etc use
% EventDefinition parameter for full control
[EventVarBin] = MatSurvDefineEventVar(EventVar, options);
% Censor data if TimeMax is given
if ~isempty(options.TimeMax)
[TimeVar, EventVarBin] = MatSurvCensorTimeMax(TimeVar, EventVarBin, options);
end
% CreatGroups based on GroupVar and create DATA structure
[DATA,options] = MatSurvCreateGroups(TimeVar, EventVarBin, GroupVar, options);
% Flip Group Ordering
if options.FlipGroupOrder
DATA.GROUPS = DATA.GROUPS(DATA.numGroups:-1:1);
end
% Creat Survival table for plotting
[DATA] = MatSurvCreateTable(DATA);
% Do log rank test
[p,stats] = MatSurvLogRank(DATA);
if options.PairWiseP
counter = 0;
stats.ParwiseName = cell(DATA.numGroups * (DATA.numGroups - 1) / 2,1);
for i = 1:DATA.numGroups - 1
for j = i+1:DATA.numGroups
counter = counter + 1;
DATA_tmp.numGroups = 2;
DATA_tmp.GROUPS(1) = DATA.GROUPS(i);
DATA_tmp.GROUPS(2) = DATA.GROUPS(j);
[~,stats.ParwiseStats(counter)] = MatSurvLogRank(DATA_tmp);
stats.ParwiseName{counter} = sprintf('%s vs. %s',DATA.GROUPS(i).GroupName{1},DATA.GROUPS(j).GroupName{1});
end
end
end
% Calculate median survival time if no plot is created
if options.NoPlot
% Create stairs
stats.MedianSurvivalTime = nan(DATA.numGroups,1);
stats.WithinGroupMedianSurvivalTime = nan(DATA.numGroups,1);
stats.AUC = zeros(DATA.numGroups,1);
for i = 1:DATA.numGroups
[xb,yb] = stairs(DATA.GROUPS(i).KM_ALL(:,1),DATA.GROUPS(i).KM_ALL(:,2));
% Calculate Median Survival time:
indx_MST = find((yb <= 0.5),1);
if ~isempty(indx_MST)
stats.MedianSurvivalTime(i) = xb(indx_MST);
end
% Calculate Within-Group Median Survival Time
wmedy = (1 - yb(end))/2 + yb(end);
idx_wmst = find(yb <= wmedy, 1);
if ~isempty(idx_wmst)
stats.WithinGroupMedianSurvivalTime(i) = xb(idx_wmst);
end
stats.XDATA = xb;
stats.YDATA = yb;
stats.YDATA(isnan(stats.YDATA)) = 0;
npoints = length(xb);
for z = 1:(npoints-1)
stats.AUC(i) = stats.AUC(i) + (stats.XDATA(z+1) - stats.XDATA(z))*stats.YDATA(z);
end
end
fh = [];
else % Creat KM-Plot
% Create Figure Window
fh = figure('Position',[0 0 500 500],'Name','MatSurv KM-Plot','Color','w','Tag','MatSurv KM-Plot figure');
%Create Axes
if options.NoRiskTable
axh_KM = axes(fh,'NextPlot','add','tag','KM-Plot');
else
axh_KM = axes(fh,'Position',options.KM_position,'NextPlot','add','tag','KM-Plot');
axh_RT = axes(fh,'Position',options.RT_position,'tag','Risk Table');
% No axis for the Risk Table
axh_RT.XAxis.Visible='off';
axh_RT.YAxis.Visible='off';
end
% Adjust Colors for user input
if ischar(options.LineColor)
if any(strcmpi(options.LineColor,{'JCO','nejm','Lancet','Science','Nature','aeb01',...
'Metastasis','Prostate','Lung','Breast','Colon','Prostate3','BreastSubtype',...
'Breast3','NPC'}))
cMAP = GetMatSurvColorPalette(options.LineColor);
else
cMAP = feval(options.LineColor, DATA.numGroups);
end
elseif ismatrix(options.LineColor)
cMAP = options.LineColor;
cMAP = cMAP(1:DATA.numGroups,:);
else
cMAP = GetMatSurvColorPalette;
end
if options.FlipColorOrder
cMAP = flipud(cMAP);
end
% Adjust line style
if ischar(options.LineStyle)
LineStyles = cell(DATA.numGroups,1);
LineStyles(:) = {options.LineStyle};
elseif numel(options.LineStyle) == 1
LineStyles = cell(DATA.numGroups,1);
LineStyles(:) = options.LineStyle;
elseif iscell(options.LineStyle)
LineStyles = options.LineStyle;
end
% Adjust censoring markers
if ischar(options.CensorLineColor) && strcmpi('same',options.CensorLineColor)
cMAPCensor = cMAP;
elseif ismatrix(options.CensorLineColor)
cMAPCensor = options.CensorLineColor;
end
% Create stairs
S = gobjects(DATA.numGroups,1);
stats.MedianSurvivalTime = nan(DATA.numGroups,1);
stats.AUC = zeros(DATA.numGroups,1);
for i = 1:DATA.numGroups
S(i) = stairs(...
axh_KM,...
DATA.GROUPS(i).KM_ALL(:,1),...
DATA.GROUPS(i).KM_ALL(:,2),...
'Color',cMAP(i,:),...
'Linewidth',options.LineWidth,...
'LineStyle',LineStyles{i});
%S(i).Marker = 'o';
stats.XDATA = S(i).XData;
stats.YDATA = S(i).YData;
stats.YDATA(isnan(stats.YDATA)) = 0;
npoints = length(S(i).XData);
for z = 1:(npoints-1)
stats.AUC(i) = stats.AUC(i) + (stats.XDATA(z+1) - stats.XDATA(z))*stats.YDATA(z);
end
% Calculate Median Survival time:
indx_MST = find((S(i).YData <= 0.5),1);
if ~isempty(indx_MST)
stats.MedianSurvivalTime(i) = S(i).XData(indx_MST);
if options.DrawMSL
line(axh_KM,[stats.MedianSurvivalTime(i) stats.MedianSurvivalTime(i)], [0.5 0],'LineStyle','--','Linewidth',1.5,'Color','k');
line(axh_KM,[0 stats.MedianSurvivalTime(i)], [0.5 0.5],'LineStyle','--','Linewidth',1.5,'Color','k');
end
end
% Draw marks for censored points
if ~isempty(DATA.GROUPS(i).Censored_Points)
line(axh_KM,[DATA.GROUPS(i).Censored_Points(:,1)'; DATA.GROUPS(i).Censored_Points(:,1)'],...
[DATA.GROUPS(i).Censored_Points(:,2)'-options.CensorLineLength ; DATA.GROUPS(i).Censored_Points(:,2)'+options.CensorLineLength],...
'Color',cMAPCensor(i,:),'Linewidth',options.CensorLineWidth);
end
end
%Fix Y-Axis
% Limit range from 0 to 1
axh_KM.YLim = [0 1];
axh_KM.YTick = options.YTick;
YMinorStep = (options.YTick(2) - options.YTick(1) ) / (1+options.YMinorTick);
axh_KM.YAxis.MinorTickValues = YMinorStep:YMinorStep:1;
axh_KM.YAxis.MinorTick = 'off';
axh_KM.YAxis.TickDirection = 'out';
axis square
% Y label
axh_KM.YAxis.FontSize=options.BaseFontSize + options.YTickFontSize;
ylabel(axh_KM,options.Ylabel,'FontSize',options.BaseFontSize + options.YLabelFontSize,options.YlabelOptions{:});
% X label
axh_KM.XAxis.FontSize=options.BaseFontSize + options.XTickFontSize;
if isempty(options.Xlabel)
xlabel_str = sprintf('Time (%s)',options.TimeUnit);
else
xlabel_str = options.Xlabel;
end
xlabel(axh_KM,xlabel_str,'FontSize',options.BaseFontSize + options.XLabelFontSize,options.XlabelOptions{:});
axh_KM.XAxis.TickDirection = 'out';
% Title
if ~isempty(options.Title)
title(axh_KM,options.Title,'FontSize',18,options.TitleOptions{:});
end
% Set legend
h_LE=legend(S,[DATA.GROUPS(:).GroupName]);
h_LE.Box='off';
title(h_LE,DATA.GroupType);
h_LE.FontSize=options.BaseFontSize + options.LegendFontSize;
% Get Xticks
if ~isempty(options.XLim)
axh_KM.XLim = [0 options.XLim];
end
max_X = axh_KM.XLim(2);
Nudge_X = max_X / 50;
if ~isempty(options.Xstep)
axh_KM.XTick = 0:options.Xstep:max_X;
end
if ~isempty(options.XTicks)
axh_KM.XTick = options.XTicks;
end
axh_KM.XAxis.MinorTick = 'off';
XMinorStep = (axh_KM.XTick(2) - axh_KM.XTick(1) ) / (1+options.XMinorTick);
axh_KM.XAxis.MinorTickValues = XMinorStep:XMinorStep:axh_KM.XTick(end);
axh_KM.LineWidth = 2;
set(gca,'TickLength',[0.02 0.02],'fontsize',20,'linewidth',1.5)
if options.DispP
txt_str(1) = {sprintf('p = %.3g',p)};
if options.DispHR
if ~options.Use_HR_MH
if options.InvHR
txt_str(2) = {sprintf('HR = %.3g (%.3g - %.3g)',stats.HR_logrank_Inv, stats.HR_95_CI_logrank_Inv(1), stats.HR_95_CI_logrank_Inv(2))};
else
txt_str(2) = {sprintf('HR = %.3g (%.3g - %.3g)',stats.HR_logrank, stats.HR_95_CI_logrank(1), stats.HR_95_CI_logrank(2))};
end
else
if options.InvHR
txt_str(2) = {sprintf('HR = %.3g (%.3g - %.3g)',stats.HR_MH_Inv, stats.HR_95_CI_MH_Inv(1), stats.HR_95_CI_MH_Inv(2))};
else
txt_str(2) = {sprintf('HR = %.3g (%.3g - %.3g)',stats.HR_MH, stats.HR_95_CI_MH(1), stats.HR_95_CI_MH(2))};
end
end
end
text(axh_KM,Nudge_X,0.1,txt_str,'FontSize',options.BaseFontSize + options.PvalFontSize,'tag','p-value')
end
% And now to the Risk table
if ~options.NoRiskTable
axh_RT.XTick=axh_KM.XTick;
% Get number of samples for each time point
RT_X = zeros(length(axh_KM.XTick),DATA.numGroups);
for i = 1:length(axh_KM.XTick)
for j = 1:DATA.numGroups
%RT_X(i,j) = sum(DATA.GROUPS(j).TimeVar > axh_KM.XTick(i) & DATA.GROUPS(j).EventVar == 1) + sum(DATA.GROUPS(j).TimeVar >= axh_KM.XTick(i) & DATA.GROUPS(j).EventVar == 0);
RT_X(i,j) = sum(DATA.GROUPS(j).TimeVar >= axh_KM.XTick(i));
end
end
axh_RT.YLim = [0.5 DATA.numGroups + 0.5];
axh_RT.YTick = 1:DATA.numGroups;
linkaxes([axh_RT,axh_KM],'x')
% Color OptionsFor Risk Table
if ischar(options.RT_Color) && strcmpi('same',options.RT_Color)
cMAP_RT = cMAP;
elseif ismatrix(options.RT_Color)
cMAP_RT = options.RT_Color;
cMAP_RT = repmat(cMAP_RT,DATA.numGroups,1);
end
for i = 1:length(axh_KM.XTick)
for j = 1:DATA.numGroups
%sprintf('%u',RT_X(i,j))
text(axh_RT,axh_RT.XTick(i),axh_RT.YTick(end-j+1),sprintf('%u',RT_X(i,j)),...
'HorizontalAlignment','center','VerticalAlignment','middle',...
'FontSize',options.BaseFontSize + options.RT_FontSize,'Color',cMAP_RT(j,:))
end
end
% Create Line
%Get position for all text objects
txt_pos = [axh_RT.Children(2:end).Extent];
%get the second element for all text objects
left_pos = min(txt_pos(1:4:end));
nudge_x = abs(axh_RT.XLim(2) - axh_RT.XLim(1))/100;
line(axh_RT,[left_pos-nudge_x left_pos-nudge_x],[axh_RT.YTick(1)-0.5 axh_RT.YTick(end)+0.5],'color','k','clipping','off','LineWidth',1.25)
%Set Y label for risk table
if options.RT_YLabel
for j = 1:DATA.numGroups
text(axh_RT,left_pos-(nudge_x*2),axh_RT.YTick(end-j+1),DATA.GROUPS(j).GroupName,...
'HorizontalAlignment','right','VerticalAlignment','middle',...
'FontSize',options.BaseFontSize + options.RT_FontSize,'Color',cMAP_RT(j,:),'FontWeight','bold')
end
end
% Title
if ~isempty(options.RT_Title)
ht = title(axh_RT,options.RT_Title,'FontSize',14,options.TitleOptions{:});
ht.VerticalAlignment='middle';
end
end
end
if options.Print
fprintf('\n')
fprintf('p = %.3g\n',stats.p_MC)
if options.CalcHR
if options.InvHR
fprintf('HR = %.3g (%.3g - %.3g)\n',stats.HR_logrank_Inv, stats.HR_95_CI_logrank_Inv(1), stats.HR_95_CI_logrank_Inv(2));
else
fprintf('HR = %.3g (%.3g - %.3g)\n',stats.HR_logrank, stats.HR_95_CI_logrank(1), stats.HR_95_CI_logrank(2));
end
end
for i = 1: DATA.numGroups
fprintf('Median Survival Time: (%s) = %g\n',stats.GroupNames{i},stats.MedianSurvivalTime(i))
end
fprintf('\n')
end
% Define output variables dependent of varargout
if nargout > 0
varargout{1} = p;
end
if nargout > 1
varargout{2} = fh;
end
if nargout > 2
varargout{3} = stats;
end
end
function params = MatSurvParseInput(varargin)
%Parse input and set defualt values
p = inputParser;
p.addParameter('NoPlot',false);
p.addParameter('NoRiskTable',false);
p.addParameter('CutPoint','Median');
p.addParameter('GroupOrder',[]);
p.addParameter('GroupsToUse',[]);
p.addParameter('EventDefinition',[]);
p.addParameter('TimeMin',0, @(x)isnumeric(x) && isscalar(x));
p.addParameter('TimeMax',[], @(x)isnumeric(x) && isscalar(x));
p.addParameter('FlipGroupOrder',0);
p.addParameter('FlipColorOrder',0);
p.addParameter('NoWarnings',false);
p.addParameter('TimeUnit','Months');
p.addParameter('PairWiseP',0);
p.addParameter('Print',1);
p.addParameter('MedianLess',1);
% Figure Options
p.addParameter('KM_position',[0.25 0.4 0.70 0.45]);
p.addParameter('RT_position',[0.25 0.05 0.70 0.20]);
p.addParameter('BaseFontSize',16);
% KM plot options
p.addParameter('DispP',1);
p.addParameter('DispHR',1);
p.addParameter('Use_HR_MH',0);
p.addParameter('DrawMSL',0);
p.addParameter('InvHR',0);
p.addParameter('Xstep',[], @(x)isnumeric(x) && isscalar(x));
p.addParameter('XTicks',[], @(x)isnumeric(x) && isvector(x));
p.addParameter('XMinorTick',1, @(x)isnumeric(x) && isscalar(x));
p.addParameter('XLim',[], @(x)isnumeric(x) && isscalar(x));
p.addParameter('LineColor','aeb01');
p.addParameter('LineWidth',2);
p.addParameter('LineStyle','-');
p.addParameter('CensorLineWidth',2);
p.addParameter('CensorLineLength',0.01);
p.addParameter('CensorLineColor','same');
p.addParameter('Xlabel',[]);
p.addParameter('XlabelOptions',cell(0,0));
p.addParameter('XLabelFontSize',0);
p.addParameter('XTickFontSize',-2);
p.addParameter('Ylabel','Survival Probability');
p.addParameter('YlabelOptions',cell(0,0));
p.addParameter('YLabelFontSize',0);
p.addParameter('YTickFontSize',-2);
p.addParameter('YTick',0:0.2:1);
p.addParameter('YMinorTick',1);
p.addParameter('Title',[]);
p.addParameter('TitleOptions',cell(0,0));
p.addParameter('LegendFontSize',-2);
p.addParameter('PvalFontSize',-2);
% Risk table plot options
p.addParameter('RT_FontSize',0);
p.addParameter('RT_Color','same');
p.addParameter('RT_YLabel',1);
p.addParameter('RT_Title',[]);
p.addParameter('RT_TitleOptions',cell(0,0));
%Others
p.addParameter('CalcHR',1);
parse(p,varargin{:});
params = p.Results;
end
function [p,stats] = MatSurvLogRank(DATA)
% Merge tables from all groups
KM_ALL = vertcat(DATA.GROUPS.KM_Events);
% Get all time points with events
tf = KM_ALL(:,1);
tf = unique(tf);
% allocate matrices
n = length(tf);
mf = zeros(n,DATA.numGroups); % Observed failures
nf = zeros(n,DATA.numGroups); % Number at risk
ef = zeros(n,DATA.numGroups); % Expected number of failures
% Assign values
for i = 1:DATA.numGroups
% Need to add censored time entries for group i
tf_in = unique([tf;DATA.GROUPS(i).TimeVar]);
[KM_Events, ~, ~] = MatSurvCalculateTables(tf_in,DATA.GROUPS(i).TimeVar,DATA.GROUPS(i).EventVar,tf);
nf(:,i) = KM_Events(:,2);
mf(:,i) = KM_Events(:,3);
end
% Calculate sums over all groups
nf_sum = sum(nf,2);
mf_sum = sum(mf,2);
% Calculated expected values
for i = 1:DATA.numGroups
ef(:,i) = (nf(:,i) ./ nf_sum) .* mf_sum;
end
%[tf mf nf ef]
d = sum(mf(:,1:end-1)-ef(:,1:end-1))';
%Calculate Variance
Var_OE=zeros(n,DATA.numGroups-1);
for i = 1:DATA.numGroups-1
Var_OE(:,i) = (nf(:,i) .* (nf_sum - nf(:,i)) .* mf_sum .*(nf_sum - mf_sum)) ./ (nf_sum.^2 .* (nf_sum - 1));
end
Var_OE(isnan(Var_OE)) = 0;
Var_OE_sum = sum(Var_OE);
%Calculate covariance
Cov_OE = zeros(n,(DATA.numGroups-1)*(DATA.numGroups-2)/2);
if DATA.numGroups > 2 % If there are more than 2 groups
counter = 0;
for i = 1:DATA.numGroups-2
for j = i+1:DATA.numGroups-1
counter = counter + 1;
Cov_OE(:,counter) = ( -nf(:,i) .* nf(:,j) .* mf_sum .* (nf_sum - mf_sum)) ./ (nf_sum.^2 .* (nf_sum -1));
end
end
Cov_OE(isnan(Cov_OE)) = 0;
Cov_OE_sum = sum(Cov_OE);
V = zeros(DATA.numGroups-1);
V(tril(true(DATA.numGroups-1),-1))=Cov_OE_sum;
V(~tril(true(DATA.numGroups-1),0))=Cov_OE_sum;
V(1:size(V,1)+1:end) = Var_OE_sum;
else % Special case for 2 groups
V = Var_OE_sum;
end
% Mantel Cox
% Calculate Chi2
Chi2 = d'/V*d;
% p = 1 - gammainc(stats.Chi2/2,(DATA.numGroups-1)/2);
p = gammainc(Chi2/2,(DATA.numGroups-1)/2,'upper');
% Create stats output
stats.GroupNames = [DATA.GROUPS.GroupName]';
stats.p_MC = p;
stats.Chi2_MC = Chi2';
% Caclulate Hazard Ratio
if DATA.numGroups == 2
stats.HR_logrank = (sum(mf(:,1)) / sum(ef(:,1))) / (sum(mf(:,2)) / sum(ef(:,2)));
stats.HR_95_CI_logrank = [exp((log(stats.HR_logrank) - 1.96 * sqrt(1/sum(ef(:,1)) + 1/sum(ef(:,2))))), exp((log(stats.HR_logrank) + 1.96 * sqrt(1/sum(ef(:,1)) + 1/sum(ef(:,2)))))];
stats.HR_logrank_Inv = 1/stats.HR_logrank;
stats.HR_95_CI_logrank_Inv = flip(1 ./ stats.HR_95_CI_logrank);
L = (sum(mf(:,1)) - sum(ef(:,1))) / Var_OE_sum;
stats.HR_MH = exp(L);
stats.HR_95_CI_MH = [exp(L - 1.96/sqrt(Var_OE_sum)), exp(L + 1.96/sqrt(Var_OE_sum))];
stats.HR_MH_Inv = 1 / stats.HR_MH;
stats.HR_95_CI_MH_Inv = flip(1 ./ stats.HR_95_CI_MH);
end
end
function [DATA] = MatSurvCreateTable(DATA)
for i=1:DATA.numGroups
% Get unique time points including censored and add a leading 0
tf = [0; unique(DATA.GROUPS(i).TimeVar)];
[KM_Events, KM_ALL, Censored_Points] = MatSurvCalculateTables(tf,DATA.GROUPS(i).TimeVar,DATA.GROUPS(i).EventVar,[]);
DATA.GROUPS(i).KM_Events=KM_Events;
DATA.GROUPS(i).KM_ALL=KM_ALL;
DATA.GROUPS(i).Censored_Points=Censored_Points;
end
end
function [KM_Events, KM_ALL, Censored_Points] = MatSurvCalculateTables(tf,TimeVar,EventVar,tf_out)
% Calculate number of samples for each time point including censored
% Thanks to ashrafinia for identifying and fixing bug if there is only one group member
mf = sum(repmat(TimeVar,1,length(tf)) == repmat(tf',length(TimeVar),1),1)';
%Calculate number of samples left at each time point
mf_cumsum = cumsum(mf);
nf = ones(length(tf),1) * length(TimeVar);
nf(2:end) = nf(2:end) - mf_cumsum(1:end-1);
% Find censored points
indx_censor = (EventVar == 0);
tfq = unique(TimeVar(indx_censor));
mfq = sum(repmat(TimeVar(indx_censor),1,length(tfq)) == repmat(tfq',length(TimeVar(indx_censor)),1),1)';
% Find time points where there are censored data
[~,tf_indx,~]=intersect(tf,tfq,'stable');
%Adjust counts for censored data, a 0 will mean that only censored data
%was observed at that time
mf_true = mf;
mf_true(tf_indx) = mf((tf_indx)) - mfq;
% Calculate fraction alive
S = cumprod(1-(mf_true./nf));
% get index of censored samples for plotting
indx_censored = ((mf_true - mf) < 0);
%
if isempty(tf_out) % function called for plotting
indx_observed = (mf_true ~= 0);
else % fynction called for log rank test
[~,~,indx_observed] = intersect(tf_out,tf);
end
KM_Events = [tf(indx_observed) nf(indx_observed) mf_true(indx_observed)];
KM_ALL = [tf S nf];
Censored_Points=[tf(indx_censored) S(indx_censored)];
end
function [DATA,options] = MatSurvCreateGroups(TimeVar, EventVarBin, GroupVar, options)
% Create Group structure
DATA.numGroups = 0;
DATA.GROUPS = struct('GroupName',{},'TimeVar',[],'EventVar',[]);
% Define set of Groups to use
if ~isempty(options.GroupsToUse) % User defined Groups to use
DATA.numGroups = numel(options.GroupsToUse);
DATA.GroupType = 'Groups';
for i = 1:DATA.numGroups
if iscell(GroupVar)
indx_group = strcmp(options.GroupsToUse(i),GroupVar);
DATA.GROUPS(i).GroupName = options.GroupsToUse(i);
elseif isnumeric(GroupVar)
indx_group = (options.GroupsToUse(i) == GroupVar);
DATA.GROUPS(i).GroupName = {num2str(options.GroupsToUse(i))};
end
DATA.GROUPS(i).TimeVar = TimeVar(indx_group);
DATA.GROUPS(i).EventVar = EventVarBin(indx_group);
end
% If the Groupvariable is a cell vector
elseif iscell(GroupVar)
Unique_Groups = unique(GroupVar);
DATA.numGroups = length(Unique_Groups);
DATA.GroupType = 'Groups';
for i = 1:DATA.numGroups
indx_group = strcmp(Unique_Groups(i),GroupVar);
DATA.GROUPS(i).GroupName = Unique_Groups(i);
DATA.GROUPS(i).TimeVar = TimeVar(indx_group);
DATA.GROUPS(i).EventVar = EventVarBin(indx_group);
end
% If the Groupvariable is a numerical vector
elseif (strcmpi('Median',options.CutPoint) || isscalar(options.CutPoint)) && isnumeric(GroupVar)
if strcmpi('Median',options.CutPoint)
Cut_Val = median(GroupVar);
DATA.GroupType = 'Median';
elseif isscalar(options.CutPoint)
Cut_Val = options.CutPoint;
DATA.GroupType = 'Fixed value';
end
DATA.numGroups = 2;
if options.MedianLess
indx_Below = (GroupVar < Cut_Val);
indx_Above = ~indx_Below;
DATA.GROUPS(1).GroupName = {sprintf('x >= %g',Cut_Val)};
DATA.GROUPS(2).GroupName = {sprintf('x < %g',Cut_Val)};
else
indx_Above = (GroupVar > Cut_Val);
indx_Below = ~indx_Above;
DATA.GROUPS(1).GroupName = {sprintf('x > %g',Cut_Val)};
DATA.GROUPS(2).GroupName = {sprintf('x <= %g',Cut_Val)};
end
DATA.GROUPS(1).TimeVar = TimeVar(indx_Above);
DATA.GROUPS(1).EventVar = EventVarBin(indx_Above);
DATA.GROUPS(2).TimeVar = TimeVar(indx_Below);
DATA.GROUPS(2).EventVar = EventVarBin(indx_Below);
elseif strcmpi('Quartile',options.CutPoint) && isnumeric(GroupVar)
Cut_Val = prctile(GroupVar,[25 75]);
DATA.GroupType = 'Quartile';
indx_Below = (GroupVar < Cut_Val(1));
indx_Above = (GroupVar > Cut_Val(2));
DATA.numGroups = 2;
DATA.GROUPS(1).GroupName = {sprintf('x > %g',Cut_Val(2))};
DATA.GROUPS(1).TimeVar = TimeVar(indx_Above);
DATA.GROUPS(1).EventVar = EventVarBin(indx_Above);
DATA.GROUPS(2).GroupName = {sprintf('x < %g',Cut_Val(1))};
DATA.GROUPS(2).TimeVar = TimeVar(indx_Below);
DATA.GROUPS(2).EventVar = EventVarBin(indx_Below);
elseif strcmpi('Tertile',options.CutPoint) && isnumeric(GroupVar)
Cut_Val = prctile(GroupVar,[100/3 100/1.5]);
DATA.GroupType = 'Tertile';
indx_Below = (GroupVar < Cut_Val(1));
indx_Above = (GroupVar > Cut_Val(2));
indx_Between = ~(indx_Below | indx_Above);
DATA.numGroups = 3;
%High
DATA.GROUPS(1).GroupName = {sprintf('x > %g',Cut_Val(2))};
DATA.GROUPS(1).TimeVar = TimeVar(indx_Above);
DATA.GROUPS(1).EventVar = EventVarBin(indx_Above);
%Medium
DATA.GROUPS(2).GroupName = {sprintf('%g < x < %g',Cut_Val(1),Cut_Val(2))};
DATA.GROUPS(2).TimeVar = TimeVar(indx_Between);
DATA.GROUPS(2).EventVar = EventVarBin(indx_Between);
%Low
DATA.GROUPS(3).GroupName = {sprintf('x < %g',Cut_Val(1))};
DATA.GROUPS(3).TimeVar = TimeVar(indx_Below);
DATA.GROUPS(3).EventVar = EventVarBin(indx_Below);
% Vector with several cut pints
elseif (isvector(options.CutPoint)) && isnumeric(GroupVar)
CutPointSorted = sort(options.CutPoint,'descend');
DATA.numGroups = length(CutPointSorted) + 1;
DATA.GroupType = 'Cut Points';
% For samples above
indx_Above = (GroupVar > CutPointSorted(1));
DATA.GROUPS(1).GroupName = {sprintf('x > %g',CutPointSorted(1))};
DATA.GROUPS(1).TimeVar = TimeVar(indx_Above);
DATA.GROUPS(1).EventVar = EventVarBin(indx_Above);
% For samples inbetween cut points
for i = 1:length(CutPointSorted) - 1
indx = (GroupVar > CutPointSorted(i+1) & GroupVar <= CutPointSorted(i));
DATA.GROUPS(i+1).GroupName = {sprintf('%g < x <= %g',CutPointSorted(i+1),CutPointSorted(i))};
DATA.GROUPS(i+1).TimeVar = TimeVar(indx);
DATA.GROUPS(i+1).EventVar = EventVarBin(indx);
end
%For samples below
i = i + 1;
indx = (GroupVar <= CutPointSorted(i));
DATA.GROUPS(i+1).GroupName = {sprintf('x <= %g',CutPointSorted(i))};
DATA.GROUPS(i+1).TimeVar = TimeVar(indx);
DATA.GROUPS(i+1).EventVar = EventVarBin(indx);
end
% Hazard ration can only be calculated if there is two groups
if DATA.numGroups ~= 2
options.DispHR = 0;
options.CalcHR = 0;
end
end
function [TimeVar, EventVarBin] = MatSurvCensorTimeMax(TimeVar, EventVarBin, options)
indx_TimeMax = (TimeVar > options.TimeMax);
TimeVar(indx_TimeMax) = options.TimeMax;
EventVarBin(indx_TimeMax) = 0;
end
function [EventVarBin] = MatSurvDefineEventVar(EventVar, options)
% Set all entries to zeros
EventVarBin = zeros(size(EventVar));
if islogical(EventVar) % Set TRUE to 1
EventVarBin(EventVar) = 1;
elseif isnumeric(EventVar) % set ones to 1
EventVarBin(EventVar == 1) = 1;
elseif iscell(EventVar)
if ~isempty(options.EventDefinition) % Set values based on user input
indx_Event = strcmp(options.EventDefinition{1},EventVar);
indx_NoEvent = strcmp(options.EventDefinition{2},EventVar);
if sum(indx_Event) + sum(indx_NoEvent) == length(EventVar)
EventVarBin(indx_Event) = 1;
EventVarBin(indx_NoEvent) = 0;
else
error('Event variable do not match event type defined in options.EventDefinition')
end
else % Set values based on common event types such as dead/alive
indx_Event = strcmpi('Dead',EventVar) | strcmpi('Deceased',EventVar) | strcmpi('Relapsed',EventVar)...
| strcmpi('Yes',EventVar) | strcmpi('Event',EventVar) | strcmpi('Progression',EventVar)...
| strcmpi('Progressed',EventVar);
indx_NoEvent = strcmpi('Alive',EventVar) | strcmpi('Living',EventVar) | strcmpi('NotRelapsed',EventVar)...
| strcmpi('DiseaseFree',EventVar) | strcmpi('No',EventVar) | strcmpi('Censored',EventVar)...
| strcmpi('NoProgression',EventVar) | strcmpi('NoEvent',EventVar);
if sum(indx_Event) + sum(indx_NoEvent) == length(EventVar)
EventVarBin(indx_Event) = 1;
EventVarBin(indx_NoEvent) = 0;
else
error('Event variable has non recognazed type. Please check EventVar')
end
end
else
error('Non supported Event variable input')
end
end
function [TimeVar, EventVar, GroupVar] = MatSurvCleanData(TimeVar, EventVar, GroupVar, options)
% Functions to check and cleanup inout data
% Make sure that TimeVar, EventVar, GroupVar are all column vectors
% and not row vectors
if size(TimeVar,1) == 1
TimeVar = TimeVar';
end
if size(EventVar,1) == 1
EventVar = EventVar';
end
if size(GroupVar,1) == 1
GroupVar = GroupVar';
end
% Check time variable for missing data and timepoints < TimeMin
rem_indx_time = ( isnan(TimeVar) | (TimeVar < options.TimeMin) );