NLP_optimizer_v3.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. % paths.patient_dir
  2. % paths.Goal_dir (previously called DP_dir)
  3. % paths.patient
  4. % paths.goalsName
  5. % colorwash(Geometry.data, D_full, [500, 1500], [0,70])
  6. % orthoslice(D_full, [0,70])
  7. function [D_full, w_fin, Geometry, optGoal] = NLP_optimizer_v3(varargin)
  8. % This function performs the beamlet optimization
  9. % [D_full, w_fin, Geometry, optGoal] = NLP_beamlet_optimizer;
  10. %
  11. % Inputs:
  12. % () OR
  13. % (Pat_path, path2goal) OR
  14. % (Pat_path, path2goal, beamlet_weights)
  15. % Pat_path, path2goal = strings to patient folder and optimal goals
  16. % beamlet_weights = initial beamlet weights
  17. %
  18. % Outputs:
  19. % full dose image dose: [D_full, w_fin, Geometry, optGoal]
  20. %
  21. % Made by Peter Ferjancic 1. May 2018
  22. % Last updated: 1. April 2019
  23. if nargin<2
  24. load('WiscPlan_preferences.mat')
  25. [Pat_path] = uigetdir([WiscPlan_preferences.patientDataPath ], 'Select Patient folder');
  26. [Goal_file,Goal_path,indx] = uigetfile([Pat_path '\matlab_files\*.mat'], 'Select OptGoal file');
  27. path2geometry = [Pat_path, '\matlab_files\Geometry.mat'];
  28. path2goal = [Goal_path, Goal_file];
  29. else
  30. Pat_path = varargin{1};
  31. path2geometry = [Pat_path, '\matlab_files\Geometry.mat'];
  32. path2goal = varargin{2};
  33. [Goal_path,Goal_file,ext] = fileparts(path2goal);
  34. end
  35. str = inputdlg({'N of iterations for initial calc', 'N of iterations for full calc', ...
  36. 'Use pre-existing NLP_result to initiate? (y/n)'}, 'input', [1,35], {'100000', '500000', 'n'});
  37. N_fcallback1 = str2double(str{1}); % 100000 is a good guesstimate
  38. N_fcallback2 = str2double(str{2}); % 500000 is a good guesstimate
  39. pre_beamWeights = str{3};
  40. switch pre_beamWeights
  41. case 'y'
  42. [NLP_file,NLP_path,indx] = uigetfile([Pat_path '\matlab_files\*.mat'], 'Select NLP_result file');
  43. load([NLP_path, NLP_file])
  44. w_beamlets = NLP_result.weights;
  45. load([Pat_path, '\all_beams.mat'])
  46. if numel(all_beams) ~= numel(w_beamlets)
  47. error('Provided weight number does not match beamlet number!')
  48. end
  49. case 'n'
  50. disp('Initial beam weights will be calculated.')
  51. end
  52. %% PROGRAM STARTS HERE
  53. % - no tocar lo que hay debajo -
  54. fprintf('starting NLP optimization process... \n')
  55. % % -- LOAD GEOMETRY, GOALS, BEAMLETS --
  56. load(path2geometry)
  57. load(path2goal)
  58. [beamlets, numBeamlet] = get_beamlets(Geometry, Pat_path, OptGoals);
  59. % [beamlets, beamlets_joined, numBeamlet, numBeam, beam_i_list] = get_beam_lets(Geometry, Pat_path);
  60. %% -- OPTIMIZATION TARGETS --
  61. % -- make the optimization optGoal structure --
  62. for i_goal = 1:size(OptGoals.goals,1)
  63. if isfield(OptGoals.data{i_goal}, 'SupVox_num')
  64. SupVox_num = OptGoals.data{i_goal}.SupVox_num;
  65. else
  66. answer = inputdlg(['# of supervoxels for "' OptGoals.data{i_goal}.name '" with ' num2str(numel(OptGoals.data{i_goal}.ROI_idx)) ' vox: ("0" to skip)'])
  67. SupVox_num = str2double(answer{1})
  68. end
  69. switch SupVox_num
  70. case 0
  71. % if not supervoxel, just select provided ROI_idx
  72. optGoal{i_goal} = OptGoals.data{i_goal};
  73. optGoal{i_goal}.beamlets_pruned = sparse(beamlets(optGoal{i_goal}.ROI_idx, :));
  74. otherwise
  75. % -- if supervoxel, merge given columns
  76. % - make supervoxel map
  77. mask = zeros(OptGoals.data{i_goal}.imgDim);
  78. mask(OptGoals.data{i_goal}.ROI_idx) = 1;
  79. superMask = superpix_group(mask, SupVox_num);
  80. superVoxList = unique(superMask);
  81. superVoxList = superVoxList(superVoxList>0);
  82. optGoal{i_goal} = OptGoals.data{i_goal};
  83. optGoal{i_goal}.ROI_idx_old = optGoal{i_goal}.ROI_idx; % copy old index data
  84. optGoal{i_goal}.ROI_idx = zeros(numel(superVoxList), 1);
  85. optGoal{i_goal}.opt_weight = optGoal{i_goal}.opt_weight * numel(optGoal{i_goal}.ROI_idx_old)/numel(optGoal{i_goal}.ROI_idx);
  86. if isfield(OptGoals.data{i_goal}, 'wgt_map')
  87. tabula_wgtmap = zeros(size(superMask));
  88. tabula_wgtmap(OptGoals.data{i_goal}.ROI_idx) = OptGoals.data{i_goal}.wgt_map;
  89. end
  90. h_w1 = waitbar(0, 'merging superboxels');
  91. for i_supVox = 1:numel(superVoxList)
  92. waitbar(i_supVox/numel(superVoxList), h_w1)
  93. supVox_idx = superVoxList(i_supVox);
  94. idxList = find(superMask == supVox_idx);
  95. optGoal{i_goal}.beamlets_pruned(i_supVox,:) = sparse(mean(beamlets(idxList, :),1));
  96. if isfield(OptGoals.data{i_goal}, 'wgt_map')
  97. optGoal{i_goal}.vox_wgt(i_supVox) = sum(tabula_wgtmap(idxList));
  98. end
  99. % -- make new indeces
  100. optGoal{i_goal}.ROI_idx(i_supVox) = idxList(1);
  101. end
  102. close(h_w1)
  103. end
  104. end
  105. % -- make them robust --
  106. RO_params=0;
  107. optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  108. save([Goal_path, Goal_file '_robust.mat'], 'optGoal')
  109. % -- CALLBACK OPTIMIZATION FUNCTION --
  110. fun1 = @(x) get_penalty(x, optGoal_beam);
  111. fun2 = @(x) get_penalty(x, optGoal);
  112. % -- OPTIMIZATION PARAMETERS --
  113. % define optimization parameters
  114. A = [];
  115. b = [];
  116. Aeq = [];
  117. beq = [];
  118. lb = zeros(1, numBeamlet);
  119. % lb_beam = zeros(1, numBeam);
  120. ub = [];
  121. nonlcon = [];
  122. % define opt limits, and make it fmincon progress
  123. options = optimoptions('fmincon');
  124. options.MaxFunctionEvaluations = N_fcallback1;
  125. options.Display = 'iter';
  126. options.PlotFcn = 'optimplotfval';
  127. % options.UseParallel = true;
  128. options.UseParallel = false;
  129. % options.OptimalityTolerance = 1e-9;
  130. %% -- INITIALIZE BEAMLET WEIGHTS --
  131. switch pre_beamWeights
  132. case 'y'
  133. % should have been assigned previously.
  134. disp('Provided beamlet weights used for initial comparison')
  135. case 'n'
  136. % if initial beamlet weights are not provided, get quick estimate
  137. % fprintf('\n running initial optimizer:')
  138. % initialize beamlet weights, OR
  139. w0 = ones(numBeamlet,1);
  140. % w0 = mean(optGoal{1}.D_final(optGoal{1}.ROI_idx) ./ (optGoal{1}.beamlets_pruned*w0+0.1)) * w0; % old
  141. w0 = mean(optGoal{1}.D_final(:)) ./ mean(optGoal{1}.beamlets_pruned*w0+0.05) * w0;
  142. w_beamlets = double(w0);
  143. % -- GET BEAM WEIGHTS --
  144. % tic
  145. % w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb,ub,nonlcon,options);
  146. % fprintf(' done!:')
  147. % t=toc;
  148. % disp(['Optimization time for beams = ',num2str(t)]);
  149. %
  150. % w_beamlets = ones(numBeamlet,1);
  151. % numBeam=numel(unique(beam_i_list));
  152. % for beam_i = 1:numBeam % assign weights to beamlets
  153. % % beamlets from same beam get same initial weights
  154. % w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  155. % end
  156. end
  157. %% FULL OPTIMIZATION
  158. % -- GET FULL BEAMLET WEIGHTS --
  159. options.MaxFunctionEvaluations = N_fcallback2;
  160. tic
  161. fprintf('\n running full optimizer:')
  162. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  163. fprintf(' done!:')
  164. t=toc;
  165. disp(['Optimization time for beamlets = ',num2str(t)]);
  166. %% evaluate the results
  167. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  168. %% save outputs
  169. NLP_result.dose = D_full;
  170. NLP_result.weights = w_fin;
  171. save([Pat_path, '\matlab_files\NLP_result_' Goal_file '.mat'], 'NLP_result');
  172. plot_DVH(Geometry, D_full)
  173. colorwash(Geometry.data, D_full, [500, 1500], [0, 90]);
  174. end
  175. %% support functions
  176. % ---- PENALTY FUNCTION ----
  177. function penalty = get_penalty(x, optGoal)
  178. % this function gets called by the optimizer. It checks the penalty for
  179. % all the robust implementation and returns the worst result.
  180. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  181. fobj = zeros(NumScenarios,1);
  182. sc_i = 1;
  183. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  184. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  185. for rgs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  186. fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rgs_i);
  187. sc_i = sc_i + 1;
  188. end
  189. end
  190. end
  191. % take the worst case penalty of evaluated scenarios
  192. penalty=max(fobj);
  193. % take the median worst case (stochastic robust)
  194. % penalty=median(fobj);
  195. end
  196. % ------ supp: penalty for single scenario ------
  197. function penalty = eval_f(x, optGoal, nrs_i, sss_i, rgs_i)
  198. penalty = 0;
  199. % for each condition
  200. for goal_i = 1:numel(optGoal)
  201. switch optGoal{goal_i}.function
  202. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  203. case 'min'
  204. % penalize if achieved dose is lower than target dose
  205. d_penalty = 1.0e0 * sum(max(0, ...
  206. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  207. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)));
  208. case 'max'
  209. % penalize if achieved dose is higher than target dose
  210. d_penalty = 1.0e0 * sum(max(0, ...
  211. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  212. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target)));
  213. case 'min_sq'
  214. % penalize if achieved dose is lower than target dose
  215. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  216. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  217. d_penalty = 1.0e0 * sum(temp1.*temp1);
  218. case 'max_sq'
  219. % penalize if achieved dose is higher than target dose
  220. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  221. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  222. d_penalty = 1.0e0 * sum(temp1.*temp1);
  223. case 'min_exp'
  224. % penalize if achieved dose is lower than target dose
  225. temp1=-min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  226. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  227. d_penalty = 1.0e0 * sum(exp(temp1));
  228. case 'max_exp'
  229. % penalize if achieved dose is higher than target dose
  230. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  231. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  232. d_penalty = 1.0e0 * sum(exp(temp1));
  233. case 'LeastSquare'
  234. % penalize with sum of squares any deviation from target
  235. % dose
  236. temp1 = (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) - ...
  237. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target;
  238. d_penalty = 1.0e0* sum(temp1.^2);
  239. case 'min_perc_Volume'
  240. % penalize by amount of volume under threshold
  241. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  242. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) > 0)) ...
  243. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  244. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  245. case 'max_perc_Volume'
  246. % penalize by amount of volume under threshold
  247. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  248. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) < 0)) ...
  249. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  250. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  251. case 'min_sq_voxwgt'
  252. % penalize if achieved dose is lower than target dose
  253. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  254. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  255. d_penalty = 1.0e0 * sum(temp1.*temp1.* optGoal{goal_i}.vox_wgt');
  256. case 'max_sq_voxwgt'
  257. % penalize if achieved dose is lower than target dose
  258. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  259. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  260. d_penalty = 1.0e0 * sum(temp1.*temp1.* optGoal{goal_i}.vox_wgt');
  261. end
  262. penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  263. end
  264. %% add modulation penalty
  265. if true
  266. max_modulation = 5;
  267. mod_pen_weight = 1.0e10;
  268. % calc the penalty
  269. mod_excess = max(0, x-5*mean(x));
  270. mod_pen = mod_pen_weight*(sum(mod_excess) + numel(mod_excess)* any(mod_excess));
  271. penalty = penalty + mod_pen;
  272. end
  273. end
  274. % ---- MAKE ROI ROBUST ----
  275. function optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  276. % take regular optimal goal and translate it into several robust cases
  277. % RO_params - should have the information below
  278. % nrs - random scenarios
  279. % sss - system setup scenarios
  280. % rgs - random range scenarios
  281. % X - X>0 moves image right
  282. % Y - Y>0 moves image down
  283. % Z - in/out.
  284. shift_X = 2; % vox of shift
  285. shift_Y = 2; % vox of shift
  286. shift_Z = 1; % vox of shift
  287. nrs_scene_list={[0,0,0]};
  288. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  289. % sss_scene_list={[0,0,0]};
  290. sss_scene_list={[0,0,0], [-shift_Y,0,0], [shift_Y,0,0], [0,-shift_X,0], [0,shift_X,0], [0,0,-shift_Z], [0,0,shift_Z]};
  291. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0],...
  292. % [-shift_mag*2,0,0], [shift_mag*2,0,0], [0,-shift_mag*2,0], [0,shift_mag*2,0]};
  293. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  294. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  295. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom\Tomo_DP_target.nrrd');
  296. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  297. rgs_scene_list={[0,0,0]};
  298. for i = 1:numel(optGoal)
  299. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  300. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  301. optGoal{i}.NbrRangeScenarios =numel(rgs_scene_list);
  302. end
  303. for goal_i = 1:numel(optGoal)
  304. % get target
  305. idx=optGoal{goal_i}.ROI_idx;
  306. targetImg1=zeros(optGoal{goal_i}.imgDim);
  307. targetImg1(idx)=1;
  308. % get beamlets
  309. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  310. % modify target and beamlets
  311. targetImg2=targetImg1;
  312. % beamlets stay the same
  313. for sss_i = 1 :optGoal{goal_i}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  314. % modify target and beamlets
  315. [targetImg3 idxValid]=get_RO_sss(targetImg2, sss_scene_list{sss_i});
  316. % beamlets stay the same
  317. for rgs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rgs
  318. % modify target and beamlets
  319. targetImg4=targetImg3;
  320. % beamlets stay the same
  321. %% make new target and beamlets
  322. ROI_idx=[];
  323. ROI_idx=find(targetImg4>0);
  324. target = optGoal{goal_i}.D_final(idxValid);
  325. beamlets_pruned = beamlets(ROI_idx, :);
  326. % save to optGoal output
  327. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.ROI_idx = ROI_idx;
  328. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned = beamlets_pruned;
  329. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target = target;
  330. end
  331. end
  332. end
  333. end
  334. end
  335. %% ------ supp: RO case SSS ------
  336. function [targetImg3 ia]=get_RO_sss(targetImg2, sss_scene_shift);
  337. % translate the target image
  338. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  339. % now we need to figure out if any target voxels fell out during the
  340. % shift
  341. imgValid = imtranslate(targetImg3,-sss_scene_shift);
  342. imgInvalid = (targetImg2-imgValid);
  343. idx_1 = find(targetImg2);
  344. idx_2 = find(imgInvalid);
  345. [idxValid,ia] = setdiff(idx_1,idx_2);
  346. [C,ia, ib] = intersect(idx_1,idxValid);
  347. end