forked from liq07lzucn/FluenceMapOpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFluenceMapOpt.m
1312 lines (1194 loc) · 48.4 KB
/
FluenceMapOpt.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
classdef FluenceMapOpt < handle
% FLUENCEMAPOPT Fluence map optimization with dose-volume constraints.
%
% Problem statement:
%
% min_(x,w)
% sum(i in I) weight_i/(2*nVoxels_i)*||A_i*x - d_i||_2^2
% + sum(j in J) weight_j/(2*nVoxels_j)*||w_j - (A_j*x - d_j)||_2^2
% + lambda/2*||x||_2^2
% s.t.
% x >= 0
% ||max(0,w_j)||_0 <= nVoxels_j*percent_j/100 for all j in J
% where
% I = set of uniform dose targets
% J = set of dose-volume constraints
%
% For each body structure included in the treatment plan, create a
% structure with the following fields:
%
% name: string used in data files
% terms: cell containing organ constraint terms
%
% Each term should have the following fields:
%
% type: string 'unif', 'ldvc', or 'udvc'
% weight: coefficient of the term in the objective function
% dose: dose in Gy
% percent: include if type is 'ldvc' or 'udvc':
% * 'ldvc': No more than p% receives less than d Gy
% * 'udvc': No more than p% receives more than d Gy
%
% Written to work with the CORT prostate tumor dataset, but could be
% modified to work with other datasets.
properties (SetAccess = private)
structs % Body structures
angles = 0:52:358; % Gantry angles
overlap = false; % Allow overlaps in structures
lambda = 1e-8; % L2 regularization coefficient
nnls = 'minConf_TMP'; % Method to compute NNLS problem
nStructs % Number of body structures
nDVC % Number of dose-volume constraints
nAngles % Number of angles
nBeamlets % Number of beamlets
end
properties (Access = private)
D % Full beamlet-to-voxel matrix
A % Stacked beamlet-to-voxel matrix
H % Stacked beamlet-to-voxel Hessian
Au % Stacked beamlet-to-voxel matrix for uniform target terms
Hu % Stacked beamlet to voxel Hessian for uniform target terms
du % Stacked dose vector for uniform target terms
As % Stacked beamlet-to-voxel matrix for model with slack
Hs % Stacked beamlet-to-voxel Hessian for model with slack
lb % Lower bound for beamlets
ub % Upper bound for beamlets
lbs % Lower bound for beamlets and slack
ubs % Upper bound for beamlets and slack
names % Body structure names
mask % Body structure contours for plotting
end
properties
x0 % Initial beamlet intensities
x % Final beamlet intensities
obj % Objective function values
wDiff % Convergence criteria
nIter % Number of iterations used
time % Time to compute solution (seconds)
tol = 1e-3; % Stopping tolerance
maxIter = 1000; % Maximum number of iterations
end
methods
function prob = FluenceMapOpt(structs,varargin)
% FLUENCEMAPOPT Initialize problem.
%
% prob = FluenceMapOpt(structs)
% Initialize problem with default parameters.
%
% prob = FluenceMapOpt(structs,ProbSpec)
% Initialize problem with optional arguments.
%
% Example:
% prob = FluenceMapOpt(structs,...
% 'angles',0:52:358,...
% 'overlap',false,...
% 'lambda',1e-8,...
% 'nnls','minConf_TMP',...
% 'x0',zeros(986,1),...
% 'tol',1e-3,...
% 'maxIter',1000);
% Set input variables
if nargin == 0
error('Not enough input arguments.')
end
if ~iscell(structs)
error('Invalid input for `structs`.')
end
prob.setInputVars(varargin);
prob.nStructs = length(structs);
prob.nAngles = length(prob.angles);
% Comput internal variables
[prob.D,prob.nBeamlets] = FluenceMapOpt.getD(prob.angles);
[prob.structs,prob.nDVC] = FluenceMapOpt.getStructVars(structs,...
prob.nStructs,prob.overlap,prob.D);
prob.names = FluenceMapOpt.getNames(prob.structs,prob.nStructs);
prob.mask = FluenceMapOpt.getMaskStruct(prob.names,prob.overlap);
[prob.A,prob.H,prob.lb,prob.ub] = prob.getA('full');
[prob.Au,prob.Hu,~,~] = prob.getA('unif');
prob.du = prob.getd('unif');
% Compute initial beamlets
if isempty(prob.x0)
prob.x0 = prob.projX('unif');
end
prob.x = prob.x0;
end
function calcBeams(prob,print)
% CALCBEAMLETS Calculate beamlet intensities.
if nargin == 1
print = true;
end
% Fluence map optimization
tic;
prob.initProb(print);
for kk = 1:prob.maxIter
% Update x and w vectors
prob.x = prob.projX('full');
wDiffSum = 0;
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
wDiffSum = wDiffSum + prob.updateW(ii,jj);
end
end
end
wDiffSum = wDiffSum/prob.nDVC;
% Calculate objective
prob.nIter = kk;
prob.calcObj(kk,print);
prob.wDiff(kk) = wDiffSum;
if print
fprintf(', wDiff: %7.4e\n',wDiffSum);
end
% Check convergence
if wDiffSum <= prob.tol
prob.obj = prob.obj(1:prob.nIter+1);
prob.wDiff = prob.wDiff(1:prob.nIter);
break
end
end
prob.x = prob.projX('full');
prob.time = toc;
end
function calcBeamsConvex(prob,print)
% CONVRELAX Approach inspired by Fu paper.
if nargin == 1
print = true;
end
% Get number of dose-volume constraint terms
numA = 0;
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
numA = numA + 1;
end
end
end
% Fluence map optimization
tic;
if print
cvx_begin
else
cvx_begin quiet
end
variables xRelax(prob.nBeamlets) a(numA)
minimize(sum_square(prob.Au*xRelax - prob.du))
subject to
prob.lb <= xRelax;
zeros(numA,1) <= a;
idxA = 1;
for ii = 1:prob.nStructs
At = prob.structs{ii}.A;
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
d = prob.structs{ii}.terms{jj}.d;
k = prob.structs{ii}.terms{jj}.k;
s = strcmp(prob.structs{ii}.terms{jj}.type,'ldvc');
res = (At*xRelax - d);
termSum = sum(pos(a(idxA) + (-1)^s*res));
termSum <= a(idxA)*k;
idxA = idxA + 1;
end
end
end
cvx_end
prob.x = xRelax;
prob.time = toc;
end
function calcBeamsIter(prob,print)
% ITERDOSE Approach inspired by Llacer paper.
%
% NOTE: Lower dose-volume constraints not implemented.
if nargin == 1
print = true;
end
% Fluence map optimization
tic;
prob.x = prob.x0;
step = size(prob.Au,1) - prob.nBeamlets;
for ii = 1:prob.maxIter
xOld = prob.x;
grad = prob.getIterGrad(prob.x);
prob.x = prob.x - step*grad;
prob.x(prob.x < 0) = 0;
xDiff = norm(xOld - prob.x)/prob.nBeamlets;
% Calculate objective
prob.nIter = ii;
if print
obj = prob.getIterObj(prob.x);
fprintf('iter: %d, obj: %7.4e, xDiff: %7.4e\n',...
ii,obj,xDiff);
end
% Check convergence
if xDiff <= prob.tol
break
end
end
prob.time = toc;
end
function calcBeamsSlack(prob,print)
% CALCBEAMSLACK Approach inspired by Zhang paper.
if nargin == 1
print = true;
end
if isempty(prob.As)
[prob.As,prob.Hs,prob.lbs,prob.ubs] = prob.getA('slack');
end
% Fluence map optimization
tic;
prob.initU();
y = zeros(size(prob.As,2),1);
for kk = 1:prob.maxIter
% Update x and u vectors
y = prob.projX('slack',y);
prob.x = y(1:prob.nBeamlets);
uDiffSum = 0;
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
uDiffSum = uDiffSum + prob.updateU(ii,jj);
end
end
end
uDiffSum = uDiffSum/prob.nDVC;
% Calculate objective
prob.nIter = kk;
if print
ds = prob.getd('slack');
obj = norm(prob.As*y - ds)^2/2;
fprintf('iter: %d, obj: %7.4e, uDiff: %7.4e\n',...
kk,obj,uDiffSum);
end
% Check convergence
if uDiffSum <= prob.tol
break
end
end
y = prob.projX('slack',y);
prob.x = y(1:prob.nBeamlets);
prob.time = toc;
end
function calcBeamsPolish(prob,x,print)
% CALCBEAMSPOLISH Approach inspired by Saberian paper.
%
% Display options:
% * 'off', 'none', 'final', 'iter'
% * 'iter-detailed', 'final-detailed'
if nargin == 2
print = 'iter';
else
if ~print
print = 'off';
end
end
tic;
f = -prob.Au'*prob.du;
[Ac,dc] = prob.getConstraints(x);
options = optimoptions(@quadprog,'Display',print);
prob.x = quadprog(prob.Hu,f,Ac,dc,[],[],prob.lb,prob.ub,[],options);
prob.time = toc;
end
function plotObj(prob)
% PLOTOBJ Plot objective function values.
% Objective function
figure()
subplot(1,2,1)
plot(0:prob.nIter,prob.obj,'LineWidth',2)
xlabel('Iteration (k)')
ylabel('Objective Value')
% Convergence of proxy variables
subplot(1,2,2)
plot(1:prob.nIter,prob.wDiff,'LineWidth',2)
xlabel('Iteration (k)')
ylabel('Convergence Criteria')
end
function plotDVH(prob,legendNames)
% PLOTDVH Plot dose-volume histograms for initial and final dose.
if nargin == 1
legendNames = prob.names;
end
% Compute curves and initialize
[doses,dvhInit] = prob.calcDVH(prob.x0);
[~,dvhFinal] = prob.calcDVH(prob.x);
myLines = lines;
legendHandles = [];
figure(), hold on
% Plot dose-volume histograms
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
% Plot targets/constraints
prob.plotConstraints(ii,jj);
end
% Plot dvh curves
plot(doses,dvhInit(ii,:),'--','Color',myLines(ii,:),...
'LineWidth',2)
dvhHandle = plot(doses,dvhFinal(ii,:),...
'Color',myLines(ii,:),'LineWidth',2);
legendHandles = [legendHandles dvhHandle];
end
% Annotations
legend(legendHandles,legendNames,'Location','northeastoutside')
xlabel('Dose (Gy)')
ylabel('Relative Volume (%)')
ax = gca;
ax.XLim = [0 doses(end)];
ax.YLim = [0 100];
box on
axis square
end
function plotDVHPaper(prob,xMat,unif)
% PLOTDVHPAPER Plot dose-volume histogram of solution.
if nargin == 2
unif = true;
end
nX = size(xMat,2);
% Compute curves and initialize
dvhMat = [];
for ii = 1:nX
[doses,dvh] = prob.calcDVH(xMat(:,ii));
dvhMat = cat(3,dvhMat,dvh);
end
myColors = lines;
if nX == 2
myLines = {'--','-'}';
else
myLines = {'--','-',':'};
end
% Plot dose-volume histograms
for ii = 1:prob.nStructs
figure(), hold on
% Plot targets/constraints
for jj = 1:length(prob.structs{ii}.terms)
if unif || ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
prob.plotConstraints(ii,jj);
end
end
% Plot dvh curves
for kk = 1:nX
if jj == prob.structs{ii}.nTerms
plot(doses,dvhMat(ii,:,kk),myLines{kk},...
'Color',myColors(1,:),'LineWidth',2);
end
end
% Annotations
ax = gca;
ax.XLim = [0 doses(end)];
ax.YLim = [0 100];
ax.XTick = 0:20:100;
ax.YTick = 0:20:100;
ax.XTickLabel = {};
ax.YTickLabel = {};
ax.LineWidth = 2;
box on
axis square
end
end
function compareDVH(prob,xMat,legendNames)
% COMPAREDVH Plot dose-volume histograms for multiple solutions.
nX = size(xMat,2);
if nargin == 2
legendNames = cell(1,nX);
for ii = 1:nX
legendNames{ii} = sprintf('x%d',ii);
end
end
% Compute curves and initialize
dvhMat = [];
for ii = 1:nX
[doses,dvh] = prob.calcDVH(xMat(:,ii));
dvhMat = cat(3,dvhMat,dvh);
end
myLines = lines;
legendHandles = [];
figure(), hold on
% Plot dose-volume histograms
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
% Plot targets/constraints
prob.plotConstraints(ii,jj);
% Plot dvh curves
for kk = 1:nX
if ii == 1 && jj == 1
dvhHandle = plot(doses,dvhMat(ii,:,kk),...
'Color',myLines(kk,:),'LineWidth',2);
legendHandles = [legendHandles dvhHandle];
else
plot(doses,dvhMat(ii,:,kk),...
'Color',myLines(kk,:),'LineWidth',2)
end
end
end
end
% Annotations
legend(legendHandles,legendNames,'Location','northeastoutside')
xlabel('Dose (Gy)')
ylabel('Relative Volume (%)')
ax = gca;
ax.XLim = [0 doses(end)];
ax.YLim = [0 100];
box on
axis square
end
function plotBeams(prob)
%PLOTBEAMS Plot beamlet intensities.
figure()
xRemain = prob.x;
for ii = 1:prob.nAngles
% Get beamlet intensities
[idx,nX,nY] = FluenceMapOpt.getBeamCoords(prob.angles(ii));
xCurrent = xRemain(1:length(idx));
xRemain = xRemain(length(idx)+1:end);
beam = zeros(nX,nY);
beam(idx) = xCurrent;
beam = beam';
% Plot beamlet intensities
subplot(1,prob.nAngles,ii)
imagesc(beam), colormap gray
beamAngle = sprintf('%d^\\circ',prob.angles(ii));
title(beamAngle,'Interpreter','tex')
caxis([0 max(prob.x)])
axis square
end
% Add colorbar
pos = get(subplot(1,prob.nAngles,ii),'Position');
cb = colorbar;
cb.Label.String = 'Beamlet Intensity (MU)';
set(subplot(1,prob.nAngles,ii),'Position',pos);
end
function plotBeamsPaper(prob)
% PLOTBEAMSPAPER
figure()
xRemain = prob.x;
for ii = 1:4
% Get beamlet intensities
[idx,nX,nY] = FluenceMapOpt.getBeamCoords(prob.angles(ii));
xCurrent = xRemain(1:length(idx));
xRemain = xRemain(length(idx)+1:end);
beam = zeros(nX,nY);
beam(idx) = xCurrent;
beam = beam';
% Plot beamlet intensities
subplot(2,2,ii)
imagesc(beam), colormap gray
set(gca,'YDir','normal','XTick',[],'YTick',[])
caxis([0 max(prob.x)])
axis square
end
% Positioning
h = gcf;
pos = h.Position;
h.Position = [pos(1) pos(2) pos(3) pos(3)];
a = subplot(2,2,1);
a.Position = [0.1 0.5 0.3 0.3];
b = subplot(2,2,2);
b.Position = [0.45 0.5 0.3 0.3];
c = subplot(2,2,3);
c.Position = [0.1 0.15 0.3 0.3];
d = subplot(2,2,4);
d.Position = [0.45 0.15 0.3 0.3];
% Colorbar
e = colorbar('southoutside','Ticks',0:1000:3000,...
'TickLabels',{},'LineWidth',2);
e.Position = [0.1 0.077 0.65 0.02700];
end
function plotDose(prob,threshold)
% PLOTDOSE Plot dose with slider for z position.
figure()
warning('off','MATLAB:contour:ConstantData');
hax = axes('Units','pixels');
% Plot dose at z = 50
z = 50;
dose = reshape(prob.D*prob.x,184,184,90);
if nargin > 1
idxZero = dose(:,:,:) == 0;
dose = 2.0*(dose > threshold) - 1;
dose(idxZero) = 0;
end
imagesc(dose(:,:,z),'AlphaData',dose(:,:,z)~=0), hold on
% Plot body structure outlines
for ii = 1:length(prob.mask)
contour(prob.mask{ii}(:,:,z),1,'k');
end
% Annotations
title(sprintf('z = %d',z))
if nargin == 1
caxis([min(dose(:)) max(dose(:))]);
cb = colorbar;
cb.Label.String = 'Dose (Gy)';
threshold = false;
end
axis equal
axis off
hold off
% Add slider
uicontrol('Style','slider',...
'Min',1,'Max',90,'Value',z,...
'Position',[200 20 120 20],...
'Callback',{@prob.updateZ,hax,dose,threshold});
end
function plotDosePaper(prob)
% PLOTDOSEPAPER Plot dose at z = 50.
figure()
idx1 = 40:126;
idx2 = 23:152;
% Get CT slice
ct = dicomread('Prostate_Dicom/CT.2.16.840.1.113662.2.12.0.3173.1271873797.276');
ct = double(imresize(ct,[184,184]));
ct50 = ct(idx1,idx2);
ctShift = ct50 - min(ct50(:));
ctShiftScale = ctShift/max(ctShift(:));
CT50 = repmat(ctShiftScale,[1 1 3]);
% Get Dose
Dose = reshape(prob.D*prob.x,184,184,90);
Dose50 = Dose(idx1,idx2,50);
% Plot CT
body50 = prob.mask{end}(idx1,idx2,50);
imagesc(CT50), hold on
% Plot dose
imagesc(Dose50,'AlphaData',0.3*(body50~=0))
contour(Dose50,0:10:100,'LineWidth',2);
% Plot organ contours
for i = 1:length(prob.mask)-1
contour(prob.mask{i}(idx1,idx2,50),1,'k','LineWidth',2);
end
% Annotations
caxis([min(Dose50(:)) max(Dose50(:))]);
axis equal
axis off
% Colorbar
colorbar('southoutside','Ticks',0:20:100,'TickLabels',{},...
'LineWidth',2)
end
function plotObjPaper(prob)
% PLOTOBJPAPER Plot objective function values.
% Objective function
figure(1)
subplot(3,1,1)
plot(0:prob.nIter,prob.obj(1:prob.nIter+1),'LineWidth',2)
FluenceMapOpt.adjustAxis(gca)
% Objective terms
for ii = 1:prob.nStructs
for jj = 1:length(prob.structs{ii}.terms)
figure(1)
subplot(3,1,ii+1)
plot(0:prob.nIter,...
prob.structs{ii}.terms{jj}.obj(1:prob.nIter+1),...
'LineWidth',2);
FluenceMapOpt.adjustAxis(gca)
% Voxels under or over dose constraints
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
figure(2), hold on
subplot(2,1,2)
plot(0:prob.nIter,...
prob.structs{ii}.terms{jj}.dPos(1:prob.nIter+1),...
'LineWidth',2);
FluenceMapOpt.adjustAxis(gca)
set(gca,'YTick',52:2:56);
end
end
end
figure(2)
subplot(2,1,1)
plot(1:prob.nIter,prob.wDiff(1:prob.nIter),'LineWidth',2)
FluenceMapOpt.adjustAxis(gca);
end
function saveResults(prob,fileName)
% SAVERESULTS current state and results.
results = struct('structs',prob.structs,...
'angles',prob.angles,...
'lambda',prob.lambda,...
'overlap',prob.overlap,...
'x0',prob.x0,...
'x',prob.x,...
'obj',prob.obj,...
'wDiff',prob.wDiff,...
'nIter',prob.nIter,...
'time',prob.time,...
'tol',prob.tol,...
'maxIter',prob.maxIter);
save(fileName,'results');
end
end
methods (Hidden)
function setInputVars(prob,args)
% SETINPUTVARS Set input variables.
for ii = 1:length(args)/2
prob.(args{2*ii-1}) = args{2*ii};
end
end
function [A,H,lb,ub] = getA(prob,type)
% GETA Get stacked beamlet-to-voxel matrix, Hessian, and
% beamlet lower and upper bounds.
%
% Get output for structures and terms specified by type:
% * 'full': All structures and terms
% * 'unif': Structures and terms with uniform targets
% * 'slack': Columns added for slack variables
matFull = strcmp(type,'full');
matUnif = strcmp(type,'unif');
matSlack = strcmp(type,'slack');
% Add terms
A = [];
for ii = 1:prob.nStructs
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
termUnif = strcmp(prob.structs{ii}.terms{jj}.type,'unif');
if (matFull || matSlack) || (matUnif && termUnif)
weight = prob.structs{ii}.terms{jj}.weight;
temp = sqrt(weight/nVoxels)*prob.structs{ii}.A;
A = [A; temp];
end
end
end
% Add regularization
if prob.lambda > 0
A = [A; sqrt(prob.lambda)*eye(prob.nBeamlets)];
end
% Add columns for slack variables
if matSlack
prevVoxels = 1;
for ii = 1:prob.nStructs
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
weight = prob.structs{ii}.terms{jj}.weight;
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
newCol = zeros(size(A,1) ,nVoxels);
eyeTerm = sqrt(weight/nVoxels)*eye(nVoxels);
newCol(prevVoxels:prevVoxels+nVoxels-1,:) = eyeTerm;
A = [A newCol];
end
prevVoxels = prevVoxels + nVoxels;
end
end
end
% Create Hessian and beamlet bounds
H = A'*A;
lb = zeros(size(A,2),1);
ub = inf(size(A,2),1);
end
function d = getd(prob,type)
% GETD Get stacked dose vector.
%
% Get output for structurs and terms specified by type:
% * 'full': All structures and terms
% * 'unif': Structures and terms with uniform targets
% * 'slack': Use u vectors rather than d vectors for dvcs
vecFull = strcmp(type,'full');
vecUnif = strcmp(type,'unif');
vecSlack = strcmp(type,'slack');
% Add terms
d = [];
for ii = 1:prob.nStructs
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
termUnif = strcmp(prob.structs{ii}.terms{jj}.type,'unif');
if (vecFull || vecSlack) || (vecUnif && termUnif)
weight = prob.structs{ii}.terms{jj}.weight;
termD = prob.structs{ii}.terms{jj}.d;
temp = sqrt(weight/nVoxels)*termD;
if ~termUnif
if vecSlack
termU = prob.structs{ii}.terms{jj}.u;
temp = sqrt(weight/nVoxels)*termU;
else
termW = prob.structs{ii}.terms{jj}.w;
temp = temp + sqrt(weight/nVoxels)*termW;
end
end
d = [d; temp];
end
end
end
% Add regularization
if prob.lambda > 0
d = [d; zeros(prob.nBeamlets,1)];
end
end
function x = projX(prob,type,y0)
% PROJX Solve non-negative least-squares problem for beamlets.
%
% Solve nnls problem specified by type:
% * 'full': Full problem
% * 'unif': Initialization problem
% * 'slack': Problem with slack variables
if strcmp(type,'slack')
A = prob.As;
H = prob.Hs;
d = prob.getd('slack');
x0 = y0;
lb = prob.lbs;
ub = prob.ubs;
else
if strcmp(type,'full')
A = prob.A;
H = prob.H;
d = prob.getd('full');
x0 = prob.x;
elseif strcmp(type,'unif')
A = prob.Au;
H = prob.Hu;
d = prob.du;
x0 = zeros(prob.nBeamlets,1);
end
lb = prob.lb;
ub = prob.ub;
end
f = -A'*d;
if strcmp(prob.nnls,'quadprog')
options = optimoptions(@quadprog,'Display','off');
x = quadprog(H,f,[],[],[],[],lb,ub,[],options);
else
func = @(x)FluenceMapOpt.quadObj(x,H,f);
options.verbose = 0;
options.method = 'newton';
x = minConf_TMP(func,x0,lb,ub,options);
end
end
function initProb(prob,print)
% INITPROB Initialize x, w, and objective values.
prob.x = prob.x0;
prob.initW();
prob.initObj();
prob.calcObj(0,print);
end
function initW(prob)
% INITW Initialize w vectors for dose-volume constraint terms.
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
% PTV initialization
s = strcmp(prob.structs{ii}.terms{jj}.type,'ldvc');
initDose = prob.structs{ii}.A*prob.x0;
res = (-1)^s*(initDose - prob.structs{ii}.terms{jj}.d);
k = prob.structs{ii}.terms{jj}.k;
w = FluenceMapOpt.projW(res,k);
prob.structs{ii}.terms{jj}.w = w;
% DVC paper initialization
% d = prob.structs{ii}.terms{jj}.d;
% prob.structs{ii}.terms{jj}.w = zeros(size(d));
% OAR initialization (x0 = 0)
% d = prob.structs{ii}.terms{jj}.d;
% prob.structs{ii}.terms{jj}.w = -d;
end
end
end
end
function initU(prob)
% INITU Initialize u vectors for dose-volume constraint terms.
for ii = 1:prob.nStructs
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
% PTV initialization
% initDose = prob.structs{ii}.A*prob.x0;
% u = FluenceMapOpt.projU(0*initDose,initDose,ii,jj);
% prob.structs{ii}.terms{jj}.u = u;
% DVC initialization
d = prob.structs{ii}.terms{jj}.d;
prob.structs{ii}.terms{jj}.u = d;
% OAR initialization
% d = prob.structs{ii}.terms{jj}.d;
% prob.structs{ii}.terms{jj}.u = zeros(size(d));
end
end
end
end
function initObj(prob)
% INITOBJ Initialize objective function values
zeroVec = zeros(1,prob.maxIter+1);
prob.obj = zeroVec;
prob.wDiff = zeroVec(1:end-1);
for ii = 1:prob.nStructs
for jj = prob.structs{ii}.nTerms
prob.structs{ii}.terms{jj}.obj = zeroVec;
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
prob.structs{ii}.terms{jj}.resPos = zeroVec;
prob.structs{ii}.terms{jj}.wPos = zeroVec;
end
end
end
end
function calcObj(prob,iter,print)
% CALCOBJ Calculate and print objective function values.
for ii = 1:prob.nStructs
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
weight = prob.structs{ii}.terms{jj}.weight;
dose = prob.structs{ii}.A*prob.x;
res = dose - prob.structs{ii}.terms{jj}.d;
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
s = strcmp(prob.structs{ii}.terms{jj}.type,'ldvc');
resPos = 100*sum((-1)^s*res > 0)/nVoxels;
prob.structs{ii}.terms{jj}.dPos(iter+1) = resPos;
wPos = 100*sum(prob.structs{ii}.terms{jj}.w > 0)/nVoxels;
prob.structs{ii}.terms{jj}.wPos(iter+1) = wPos;
res = res - prob.structs{ii}.terms{jj}.w;
end
termObj = weight*norm(res)^2/(2*nVoxels);
prob.structs{ii}.terms{jj}.obj(iter+1) = termObj;
prob.obj(iter+1) = prob.obj(iter+1) + termObj;
end
end
prob.obj(iter+1) = prob.obj(iter+1) + prob.lambda*norm(prob.x)^2/2;
if print
fprintf('iter: %d, obj: %7.4e',iter,prob.obj(iter+1));
if iter == 0
fprintf('\n');
end
end
end
function obj = getObj(prob,type)
% GETOBJ Get objective value.
if nargin == 1
type = 'full';
end
if strcmp(type,'full')
d = prob.getd('full');
obj = 1/2*norm(prob.A*prob.x - d)^2;
elseif strcmp(type,'unif')
obj = 1/2*norm(prob.Au*prob.x - prob.du)^2;
elseif strcmp(type,'dvc')
obj = 0;
for ii = 1:prob.nStructs
nVoxels = prob.structs{ii}.nVoxels;
for jj = 1:prob.structs{ii}.nTerms
if ~strcmp(prob.structs{ii}.terms{jj}.type,'unif')
weight = prob.structs{ii}.terms{jj}.weight;
objTerm = prob.getOarDiff(ii,jj);
obj = obj + weight*objTerm^2/(2*nVoxels);
end
end
end
else
disp('Invalid objective type.');
obj = -1;
end
end
function diff = getOarDiff(prob,ii,jj,type)
% GETOARDIFF Get OAR term ||w - (Ax - d)||_2.
if nargin == 3
type = 2;
end
Ax = prob.structs{ii}.A*prob.x;
w = prob.structs{ii}.terms{jj}.w;
d = prob.structs{ii}.terms{jj}.d;
diff = norm(w - (Ax - d),type);
end
function wDiff = updateW(prob,ii,jj)
% UPDATEW Update proxy variable.
% Grab variables
s = strcmp(prob.structs{ii}.terms{jj}.type,'ldvc');
k = prob.structs{ii}.terms{jj}.k;
step = prob.structs{ii}.terms{jj}.step;
weight = prob.structs{ii}.terms{jj}.weight;
nVoxels = prob.structs{ii}.nVoxels;
coeff = step*weight/nVoxels;
% Calculate gradient step
dose = prob.structs{ii}.A*prob.x;
res = (-1)^s*(dose - prob.structs{ii}.terms{jj}.d);
wPrev = prob.structs{ii}.terms{jj}.w;
wStep = wPrev + coeff*(res - wPrev);
% Project onto set ||(w)_+||_0 <= k
wProj = FluenceMapOpt.projW(wStep,k);
wDiff = norm(wProj - wPrev)/step;
prob.structs{ii}.terms{jj}.w = wProj;
end
function uDiff = updateU(prob,ii,jj)
% UPDATE U Update dose variables.
dose = prob.structs{ii}.A*prob.x;
uPrev = prob.structs{ii}.terms{jj}.u;
d = prob.structs{ii}.terms{jj}.d(1);
n = prob.structs{ii}.nVoxels - prob.structs{ii}.terms{jj}.k;
uProj = FluenceMapOpt.projU(uPrev,max(uPrev,dose),d,n);
step = prob.structs{ii}.terms{jj}.step;
uDiff = norm(uPrev - uProj)/step;
prob.structs{ii}.terms{jj}.u = uProj;
end
function [Ac,dc] = getConstraints(prob,x)
% GETCONSTRAINTS Get stacked dose-volume constraints.