NLP_optimizer_v2.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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_v2(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], {'10000', '500000', 'n'});
  37. N_fcallback1 = str2double(str{1}); % 10000 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, beamlets_joined, numBeamlet, numBeam, beam_i_list] = get_beam_lets(Geometry, Pat_path);
  59. %% -- OPTIMIZATION TARGETS --
  60. % -- make the optimization optGoal structure --
  61. for i_goal = 1:size(OptGoals.goals,1)
  62. if isfield(OptGoals.data{i_goal}, 'SupVox_num')
  63. SupVox_num = OptGoals.data{i_goal}.SupVox_num;
  64. else
  65. answer = inputdlg(['# of supervoxels for "' OptGoals.data{i_goal}.name '" with ' num2str(numel(OptGoals.data{i_goal}.ROI_idx)) ' vox: ("0" to skip)'])
  66. SupVox_num = str2double(answer{1})
  67. end
  68. switch SupVox_num
  69. case 0
  70. % if not supervoxel, just select provided ROI_idx
  71. optGoal{i_goal} = OptGoals.data{i_goal};
  72. optGoal{i_goal}.beamlets_pruned = sparse(beamlets(optGoal{i_goal}.ROI_idx, :));
  73. optGoal_beam{i_goal} = OptGoals.data{i_goal};
  74. optGoal_beam{i_goal}.beamlets_pruned = sparse(beamlets_joined(optGoal{i_goal}.ROI_idx, :));
  75. otherwise
  76. % -- if supervoxel, merge given columns
  77. % - make supervoxel map
  78. mask = zeros(OptGoals.data{i_goal}.imgDim);
  79. mask(OptGoals.data{i_goal}.ROI_idx) = 1;
  80. superMask = superpix_group(mask, SupVox_num);
  81. superVoxList = unique(superMask);
  82. superVoxList = superVoxList(superVoxList>0);
  83. optGoal{i_goal} = OptGoals.data{i_goal};
  84. optGoal{i_goal}.ROI_idx_old = optGoal{i_goal}.ROI_idx; % copy old index data
  85. optGoal{i_goal}.ROI_idx = zeros(numel(superVoxList), 1);
  86. optGoal{i_goal}.opt_weight = optGoal{i_goal}.opt_weight * numel(optGoal{i_goal}.ROI_idx_old)/numel(optGoal{i_goal}.ROI_idx);
  87. optGoal_beam{i_goal} = OptGoals.data{i_goal};
  88. optGoal_beam{i_goal}.ROI_idx_old = optGoal_beam{i_goal}.ROI_idx;
  89. optGoal_beam{i_goal}.ROI_idx = zeros(numel(superVoxList), 1);
  90. optGoal_beam{i_goal}.opt_weight = optGoal_beam{i_goal}.opt_weight * numel(optGoal_beam{i_goal}.ROI_idx_old)/numel(optGoal_beam{i_goal}.ROI_idx);
  91. h_w1 = waitbar(0, 'merging superboxels');
  92. for i_supVox = 1:numel(superVoxList)
  93. supVox_idx = superVoxList(i_supVox);
  94. waitbar(i_supVox/numel(superVoxList), h_w1)
  95. idxList = find(superMask == supVox_idx);
  96. optGoal{i_goal}.beamlets_pruned(i_supVox,:) = sparse(mean(beamlets(idxList, :),1));
  97. optGoal_beam{i_goal}.beamlets_pruned(i_supVox,:) = sparse(mean(beamlets_joined(idxList, :),1));
  98. % -- make new indeces
  99. optGoal{i_goal}.ROI_idx(i_supVox) = idxList(1);
  100. optGoal_beam{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_beam = make_robust_optGoal(optGoal_beam, RO_params, beamlets_joined);
  108. optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  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_beams = ones(numBeam,1);
  140. w0_beams = mean(optGoal_beam{1}.D_final(optGoal{1}.ROI_idx) ./ (optGoal_beam{1}.beamlets_pruned*w0_beams+0.1)) * w0_beams;
  141. w0_beams = double(w0_beams);
  142. % -- GET BEAM WEIGHTS --
  143. tic
  144. w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb_beam,ub,nonlcon,options);
  145. fprintf(' done!:')
  146. t=toc;
  147. disp(['Optimization time for beams = ',num2str(t)]);
  148. w_beamlets = ones(numBeamlet,1);
  149. numBeam=numel(unique(beam_i_list));
  150. for beam_i = 1:numBeam % assign weights to beamlets
  151. % beamlets from same beam get same initial weights
  152. w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  153. end
  154. end
  155. %% FULL OPTIMIZATION
  156. % -- GET FULL BEAMLET WEIGHTS --
  157. options.MaxFunctionEvaluations = N_fcallback2;
  158. tic
  159. fprintf('\n running full optimizer:')
  160. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  161. fprintf(' done!:')
  162. t=toc;
  163. disp(['Optimization time for beamlets = ',num2str(t)]);
  164. %% evaluate the results
  165. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  166. %% save outputs
  167. NLP_result.dose = D_full;
  168. NLP_result.weights = w_fin;
  169. save([Pat_path, '\matlab_files\NLP_result_' Goal_file '.mat'], 'NLP_result');
  170. plot_DVH(Geometry, D_full)
  171. colorwash(Geometry.data, D_full, [500, 1500], [0, 36]);
  172. end
  173. %% support functions
  174. % ---- PENALTY FUNCTION ----
  175. function penalty = get_penalty(x, optGoal)
  176. % this function gets called by the optimizer. It checks the penalty for
  177. % all the robust implementation and returns the worst result.
  178. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  179. fobj = zeros(NumScenarios,1);
  180. sc_i = 1;
  181. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  182. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  183. for rgs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  184. fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rgs_i);
  185. sc_i = sc_i + 1;
  186. end
  187. end
  188. end
  189. % take the worst case penalty of evaluated scenarios
  190. penalty=max(fobj);
  191. end
  192. % ------ supp: penalty for single scenario ------
  193. function penalty = eval_f(x, optGoal, nrs_i, sss_i, rgs_i)
  194. penalty = 0;
  195. % for each condition
  196. for goal_i = 1:numel(optGoal)
  197. switch optGoal{goal_i}.function
  198. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  199. case 'min'
  200. % penalize if achieved dose is lower than target dose
  201. d_penalty = 1.0e0 * sum(max(0, ...
  202. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  203. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)));
  204. case 'max'
  205. % penalize if achieved dose is higher than target dose
  206. d_penalty = 1.0e0 * sum(max(0, ...
  207. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  208. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target)));
  209. case 'min_sq'
  210. % penalize if achieved dose is lower than target dose
  211. temp1=min(0, (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. d_penalty = 1.0e0 * sum(temp1.*temp1);
  214. case 'max_sq'
  215. % penalize if achieved dose is higher than target dose
  216. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  217. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  218. d_penalty = 1.0e0 * sum(temp1.*temp1);
  219. case 'min_exp'
  220. % penalize if achieved dose is lower than target dose
  221. temp1=-min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  222. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  223. d_penalty = 1.0e0 * sum(exp(temp1));
  224. case 'max_exp'
  225. % penalize if achieved dose is higher than target dose
  226. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  227. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  228. d_penalty = 1.0e0 * sum(exp(temp1));
  229. case 'LeastSquare'
  230. % penalize with sum of squares any deviation from target
  231. % dose
  232. temp1 = (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) - ...
  233. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target;
  234. d_penalty = 1.0e0* sum(temp1.^2);
  235. case 'min_perc_Volume'
  236. % penalize by amount of volume under threshold
  237. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  238. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) > 0)) ...
  239. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  240. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  241. case 'max_perc_Volume'
  242. % penalize by amount of volume under threshold
  243. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  244. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) < 0)) ...
  245. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  246. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  247. end
  248. penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  249. end
  250. end
  251. % ---- MAKE ROI ROBUST ----
  252. function optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  253. % take regular optimal goal and translate it into several robust cases
  254. % RO_params - should have the information below
  255. % nrs - random scenarios
  256. % sss - system setup scenarios
  257. % rgs - random range scenarios
  258. % X - X>0 moves image right
  259. % Y - Y>0 moves image down
  260. % Z - in/out.
  261. shift_mag = 1; % vox of shift
  262. nrs_scene_list={[0,0,0]};
  263. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  264. sss_scene_list={[0,0,0]};
  265. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0], [0,0,-1], [0,0,1]};
  266. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0],...
  267. % [-shift_mag*2,0,0], [shift_mag*2,0,0], [0,-shift_mag*2,0], [0,shift_mag*2,0]};
  268. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  269. rgs_scene_list={[0,0,0]};
  270. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  271. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom\Tomo_DP_target.nrrd');
  272. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  273. for i = 1:numel(optGoal)
  274. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  275. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  276. optGoal{i}.NbrRangeScenarios =numel(rgs_scene_list);
  277. end
  278. for goal_i = 1:numel(optGoal)
  279. % get target
  280. idx=optGoal{goal_i}.ROI_idx;
  281. targetImg1=zeros(optGoal{goal_i}.imgDim);
  282. targetImg1(idx)=1;
  283. % get beamlets
  284. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  285. % modify target and beamlets
  286. targetImg2=targetImg1;
  287. % beamlets stay the same
  288. for sss_i = 1 :optGoal{goal_i}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  289. % modify target and beamlets
  290. [targetImg3 idxValid]=get_RO_sss(targetImg2, sss_scene_list{sss_i});
  291. % beamlets stay the same
  292. for rgs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rgs
  293. % modify target and beamlets
  294. targetImg4=targetImg3;
  295. % beamlets stay the same
  296. %% make new target and beamlets
  297. ROI_idx=[];
  298. ROI_idx=find(targetImg4>0);
  299. target = optGoal{goal_i}.D_final(idxValid);
  300. beamlets_pruned = beamlets(ROI_idx, :);
  301. % save to optGoal output
  302. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.ROI_idx = ROI_idx;
  303. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned = beamlets_pruned;
  304. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target = target;
  305. end
  306. end
  307. end
  308. end
  309. end
  310. % ------ supp: RO case SSS ------
  311. function [targetImg3 ia]=get_RO_sss(targetImg2, sss_scene_shift);
  312. % translate the target image
  313. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  314. % now we need to figure out if any target voxels fell out during the
  315. % shift
  316. imgValid = imtranslate(targetImg3,-sss_scene_shift);
  317. imgInvalid = (targetImg2-imgValid);
  318. idx_1 = find(targetImg2);
  319. idx_2 = find(imgInvalid);
  320. [idxValid,ia] = setdiff(idx_1,idx_2);
  321. [C,ia, ib] = intersect(idx_1,idxValid);
  322. end