1
0

NLP_optimizer_v3.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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], {'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);
  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. h_w1 = waitbar(0, 'merging superboxels');
  87. for i_supVox = 1:numel(superVoxList)
  88. waitbar(i_supVox/numel(superVoxList), h_w1)
  89. supVox_idx = superVoxList(i_supVox);
  90. idxList = find(superMask == supVox_idx);
  91. optGoal{i_goal}.beamlets_pruned(i_supVox,:) = sparse(mean(beamlets(idxList, :),1));
  92. % -- make new indeces
  93. optGoal{i_goal}.ROI_idx(i_supVox) = idxList(1);
  94. end
  95. close(h_w1)
  96. end
  97. end
  98. % -- make them robust --
  99. RO_params=0;
  100. optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  101. % -- CALLBACK OPTIMIZATION FUNCTION --
  102. fun1 = @(x) get_penalty(x, optGoal_beam);
  103. fun2 = @(x) get_penalty(x, optGoal);
  104. % -- OPTIMIZATION PARAMETERS --
  105. % define optimization parameters
  106. A = [];
  107. b = [];
  108. Aeq = [];
  109. beq = [];
  110. lb = zeros(1, numBeamlet);
  111. % lb_beam = zeros(1, numBeam);
  112. ub = [];
  113. nonlcon = [];
  114. % define opt limits, and make it fmincon progress
  115. options = optimoptions('fmincon');
  116. options.MaxFunctionEvaluations = N_fcallback1;
  117. options.Display = 'iter';
  118. options.PlotFcn = 'optimplotfval';
  119. % options.UseParallel = true;
  120. options.UseParallel = false;
  121. % options.OptimalityTolerance = 1e-9;
  122. %% -- INITIALIZE BEAMLET WEIGHTS --
  123. switch pre_beamWeights
  124. case 'y'
  125. % should have been assigned previously.
  126. disp('Provided beamlet weights used for initial comparison')
  127. case 'n'
  128. % if initial beamlet weights are not provided, get quick estimate
  129. % fprintf('\n running initial optimizer:')
  130. % initialize beamlet weights, OR
  131. w0 = ones(numBeamlet,1);
  132. w0 = mean(optGoal{1}.D_final(optGoal{1}.ROI_idx) ./ (optGoal{1}.beamlets_pruned*w0+0.1)) * w0;
  133. w_beamlets = double(w0);
  134. % -- GET BEAM WEIGHTS --
  135. % tic
  136. % w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb,ub,nonlcon,options);
  137. % fprintf(' done!:')
  138. % t=toc;
  139. % disp(['Optimization time for beams = ',num2str(t)]);
  140. %
  141. % w_beamlets = ones(numBeamlet,1);
  142. % numBeam=numel(unique(beam_i_list));
  143. % for beam_i = 1:numBeam % assign weights to beamlets
  144. % % beamlets from same beam get same initial weights
  145. % w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  146. % end
  147. end
  148. %% FULL OPTIMIZATION
  149. % -- GET FULL BEAMLET WEIGHTS --
  150. options.MaxFunctionEvaluations = N_fcallback2;
  151. tic
  152. fprintf('\n running full optimizer:')
  153. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  154. fprintf(' done!:')
  155. t=toc;
  156. disp(['Optimization time for beamlets = ',num2str(t)]);
  157. %% evaluate the results
  158. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  159. %% save outputs
  160. NLP_result.dose = D_full;
  161. NLP_result.weights = w_fin;
  162. save([Pat_path, '\matlab_files\NLP_result_' Goal_file '.mat'], 'NLP_result');
  163. plot_DVH(Geometry, D_full)
  164. colorwash(Geometry.data, D_full, [500, 1500], [0, 36]);
  165. end
  166. %% support functions
  167. % ---- PENALTY FUNCTION ----
  168. function penalty = get_penalty(x, optGoal)
  169. % this function gets called by the optimizer. It checks the penalty for
  170. % all the robust implementation and returns the worst result.
  171. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  172. fobj = zeros(NumScenarios,1);
  173. sc_i = 1;
  174. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  175. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  176. for rgs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  177. fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rgs_i);
  178. sc_i = sc_i + 1;
  179. end
  180. end
  181. end
  182. % take the worst case penalty of evaluated scenarios
  183. penalty=max(fobj);
  184. end
  185. % ------ supp: penalty for single scenario ------
  186. function penalty = eval_f(x, optGoal, nrs_i, sss_i, rgs_i)
  187. penalty = 0;
  188. % for each condition
  189. for goal_i = 1:numel(optGoal)
  190. switch optGoal{goal_i}.function
  191. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  192. case 'min'
  193. % penalize if achieved dose is lower than target dose
  194. d_penalty = 1.0e0 * sum(max(0, ...
  195. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  196. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)));
  197. case 'max'
  198. % penalize if achieved dose is higher than target dose
  199. d_penalty = 1.0e0 * sum(max(0, ...
  200. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  201. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target)));
  202. case 'min_sq'
  203. % penalize if achieved dose is lower than target dose
  204. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  205. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  206. d_penalty = 1.0e0 * sum(temp1.*temp1);
  207. case 'max_sq'
  208. % penalize if achieved dose is higher than target dose
  209. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  210. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  211. d_penalty = 1.0e0 * sum(temp1.*temp1);
  212. case 'min_exp'
  213. % penalize if achieved dose is lower than target dose
  214. temp1=-min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  215. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  216. d_penalty = 1.0e0 * sum(exp(temp1));
  217. case 'max_exp'
  218. % penalize if achieved dose is higher than target dose
  219. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  220. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  221. d_penalty = 1.0e0 * sum(exp(temp1));
  222. case 'LeastSquare'
  223. % penalize with sum of squares any deviation from target
  224. % dose
  225. temp1 = (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(temp1.^2);
  228. case 'min_perc_Volume'
  229. % penalize by amount of volume under threshold
  230. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  231. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) > 0)) ...
  232. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  233. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  234. case 'max_perc_Volume'
  235. % penalize by amount of volume under threshold
  236. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  237. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) < 0)) ...
  238. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  239. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  240. end
  241. penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  242. end
  243. end
  244. % ---- MAKE ROI ROBUST ----
  245. function optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  246. % take regular optimal goal and translate it into several robust cases
  247. % RO_params - should have the information below
  248. % nrs - random scenarios
  249. % sss - system setup scenarios
  250. % rgs - random range scenarios
  251. % X - X>0 moves image right
  252. % Y - Y>0 moves image down
  253. % Z - in/out.
  254. shift_mag = 1; % vox of shift
  255. nrs_scene_list={[0,0,0]};
  256. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  257. % sss_scene_list={[0,0,0]};
  258. 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]};
  259. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0],...
  260. % [-shift_mag*2,0,0], [shift_mag*2,0,0], [0,-shift_mag*2,0], [0,shift_mag*2,0]};
  261. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  262. rgs_scene_list={[0,0,0]};
  263. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  264. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom\Tomo_DP_target.nrrd');
  265. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  266. for i = 1:numel(optGoal)
  267. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  268. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  269. optGoal{i}.NbrRangeScenarios =numel(rgs_scene_list);
  270. end
  271. for goal_i = 1:numel(optGoal)
  272. % get target
  273. idx=optGoal{goal_i}.ROI_idx;
  274. targetImg1=zeros(optGoal{goal_i}.imgDim);
  275. targetImg1(idx)=1;
  276. % get beamlets
  277. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  278. % modify target and beamlets
  279. targetImg2=targetImg1;
  280. % beamlets stay the same
  281. for sss_i = 1 :optGoal{goal_i}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  282. % modify target and beamlets
  283. [targetImg3 idxValid]=get_RO_sss(targetImg2, sss_scene_list{sss_i});
  284. % beamlets stay the same
  285. for rgs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rgs
  286. % modify target and beamlets
  287. targetImg4=targetImg3;
  288. % beamlets stay the same
  289. %% make new target and beamlets
  290. ROI_idx=[];
  291. ROI_idx=find(targetImg4>0);
  292. target = optGoal{goal_i}.D_final(idxValid);
  293. beamlets_pruned = beamlets(ROI_idx, :);
  294. % save to optGoal output
  295. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.ROI_idx = ROI_idx;
  296. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned = beamlets_pruned;
  297. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target = target;
  298. end
  299. end
  300. end
  301. end
  302. end
  303. % ------ supp: RO case SSS ------
  304. function [targetImg3 ia]=get_RO_sss(targetImg2, sss_scene_shift);
  305. % translate the target image
  306. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  307. % now we need to figure out if any target voxels fell out during the
  308. % shift
  309. imgValid = imtranslate(targetImg3,-sss_scene_shift);
  310. imgInvalid = (targetImg2-imgValid);
  311. idx_1 = find(targetImg2);
  312. idx_2 = find(imgInvalid);
  313. [idxValid,ia] = setdiff(idx_1,idx_2);
  314. [C,ia, ib] = intersect(idx_1,idxValid);
  315. end