NLP_beamlet_optimizer.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. % colorwash(Geometry.data, D_full, [500, 1500], [0,70])
  2. % orthoslice(D_full, [0,70])
  3. function [D_full, w_fin, Geometry, optGoal] = NLP_beamlet_optimizer
  4. % This function performs the beamlet optimization
  5. % Inputs: none. Still needs to find "Geometry" and "beamlets" from Wiscplan
  6. % Outputs: full dose image dose: D_full, optimal beamlet weights: w_fin
  7. %
  8. % [D_full, w_fin, Geometry, optGoal] = NLP_beamlet_optimizer;
  9. %
  10. % Made by Peter Ferjancic 1. May 2018
  11. % Last updated: 14. August 2018
  12. % Inspired by Ana Barrigan's REGGUI optimization procedures
  13. N_fcallback1 = 5000;
  14. N_fcallback2 = 200000;
  15. patient = 'gbm_005';
  16. switch patient
  17. case 'patient'
  18. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PatientData';
  19. case 'tomoPhantom'
  20. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PatientData';
  21. case 'phantom_HD'
  22. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom';
  23. case 'doggo'
  24. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PatientData_dog5_3';
  25. case 'gbm_005'
  26. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PatientData_ozzy1';
  27. otherwise
  28. error('invalid case')
  29. end
  30. merge_beamlets(4, patient_dir);
  31. %% PROGRAM STARTS HERE
  32. % - no tocar lo que hay debajo -
  33. fprintf('starting NLP optimization process... ')
  34. % -- LOAD GEOMETRY AND BEAMLETS --
  35. load([patient_dir '\matlab_files\Geometry.mat'])
  36. % beamlet_batch_filename = [patient_dir '\beamlet_batch_files\' 'beamletbatch0.bin'];
  37. beamlet_batch_filename = [patient_dir '\' 'batch_dose.bin'];
  38. beamlet_cell_array = read_ryan_beamlets(beamlet_batch_filename, 'ryan');
  39. fprintf('\n loaded beamlets...')
  40. % -- SET INITIAL PARAMETERS --
  41. numVox = numel(Geometry.data);
  42. numBeamlet = size(beamlet_cell_array,2);
  43. %% -- BEAMLET DOSE DELIVERY --
  44. beamlets = get_beamlets(beamlet_cell_array, numVox);
  45. % show_joint_beamlets(beamlets, size(Geometry.data), 7:9)
  46. fprintf('\n beamlet array constructed...')
  47. % - merge beamlets into beams -
  48. load([patient_dir '\all_beams.mat'])
  49. beamletOrigin=[0 0 0];
  50. beam_i=0;
  51. beam_i_list=[];
  52. for beamlet_i = 1:numel(all_beams)
  53. newBeamletOrigin = all_beams{beamlet_i}.ip;
  54. if any(newBeamletOrigin ~= beamletOrigin)
  55. beam_i = beam_i+1;
  56. beamletOrigin = newBeamletOrigin;
  57. end
  58. beam_i_list=[beam_i_list, beam_i];
  59. end
  60. beamlets_joined=[];
  61. target_joined=[];
  62. wbar2 = waitbar(0, 'merging beamlets into beams');
  63. numBeam=numel(unique(beam_i_list));
  64. for beam_i = unique(beam_i_list)
  65. beam_full = sum(beamlets(:,beam_i_list == beam_i), 2);
  66. beamlets_joined(:,end+1) = beam_full;
  67. waitbar(beam_i/numBeam, wbar2)
  68. end
  69. close(wbar2)
  70. %% -- OPTIMIZATION TARGETS --
  71. make_ROI_goals(Geometry, beamlets, beamlets_joined, patient);
  72. [optGoal, optGoal_beam, optGoal_idx, targetMinMax_idx] = get_ROI_goals(patient);
  73. % -- make them robust --
  74. RO_params=0;
  75. optGoal_beam = make_robust_optGoal(optGoal_beam, RO_params, beamlets_joined);
  76. optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  77. %% -- INITIALIZE BEAMLET WEIGHTS --
  78. w0_beams = ones(numBeam,1);
  79. w0_beams = mean(optGoal_beam{1}.target ./ (optGoal_beam{1}.beamlets_pruned*w0_beams+0.1)) * w0_beams;
  80. w0_beams = w0_beams + (2*rand(size(w0_beams))-1) *0.1 .*w0_beams; % random perturbation
  81. % -- CALLBACK OPTIMIZATION FUNCTION --
  82. fun1 = @(x) get_penalty(x, optGoal_beam);
  83. fun2 = @(x) get_penalty(x, optGoal);
  84. % -- OPTIMIZATION PARAMETERS --
  85. % define optimization parameters
  86. A = [];
  87. b = [];
  88. Aeq = [];
  89. beq = [];
  90. lb = zeros(1, numBeamlet);
  91. lb_beam = zeros(1, numBeamlet);
  92. ub = [];
  93. nonlcon = [];
  94. % define opt limits, and make it fmincon progress
  95. options = optimoptions('fmincon');
  96. options.MaxFunctionEvaluations = N_fcallback1;
  97. options.Display = 'iter';
  98. options.PlotFcn = 'optimplotfval';
  99. % options.UseParallel = true;
  100. fprintf('\n running initial optimizer:')
  101. %% Run the optimization
  102. % -- GET FULL BEAM WEIGHTS --
  103. tic
  104. w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb_beam,ub,nonlcon,options);
  105. fprintf(' done!:')
  106. % t=toc;
  107. % disp(['Optimization time for beams = ',num2str(t)]);
  108. w_beamlets = ones(numBeamlet,1);
  109. numBeam=numel(unique(beam_i_list));
  110. for beam_i = 1:numBeam % assign weights to beamlets
  111. % beamlets from same beam get same initial weights
  112. w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  113. end
  114. w_beamlets = w_beamlets + (2*rand(size(w_beamlets))-1) *0.1 .*w_beamlets; % small random perturbation
  115. % -- GET FULL BEAMLET WEIGHTS --
  116. options.MaxFunctionEvaluations = N_fcallback2;
  117. % tic
  118. fprintf('\n running full optimizer:')
  119. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  120. fprintf(' done!:')
  121. t=toc;
  122. disp(['Optimization time for beamlets = ',num2str(t)]);
  123. %% evaluate the results
  124. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  125. %% save outputs
  126. NLP_result.dose = D_full;
  127. NLP_result.weights = w_fin;
  128. save([patient_dir '\matlab_files\NLP_result.mat'], 'NLP_result');
  129. plot_DVH(D_full, optGoal, optGoal_idx, targetMinMax_idx)
  130. colorwash(Geometry.data, D_full);
  131. % plot_DVH_robust(D_full, optGoal, optGoal_idx)
  132. end
  133. %% support functions
  134. % ---- PENALTY FUNCTION ----
  135. function penalty = get_penalty(x, optGoal)
  136. % this function gets called by the optimizer. It checks the penalty for
  137. % all the robust implementation and returns the worst result.
  138. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  139. fobj = zeros(NumScenarios,1);
  140. sc_i = 1;
  141. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  142. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  143. for rrs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  144. fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rrs_i);
  145. sc_i = sc_i + 1;
  146. end
  147. end
  148. end
  149. % take the worst case penalty of evaluated scenarios
  150. penalty=max(fobj);
  151. end
  152. % ------ supp: penalty for single scenario ------
  153. function penalty = eval_f(x, optGoal, nrs_i, sss_i, rrs_i)
  154. penalty = 0;
  155. % for each condition
  156. for goal_i = 1:numel(optGoal)
  157. switch optGoal{goal_i}.function
  158. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  159. case 'min'
  160. % penalize if achieved dose is lower than target dose
  161. d_penalty = 1.0e0 * sum(max(0, ...
  162. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  163. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)));
  164. case 'max'
  165. % penalize if achieved dose is higher than target dose
  166. d_penalty = 1.0e0 * sum(max(0, ...
  167. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  168. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target)));
  169. case 'min_sq'
  170. % penalize if achieved dose is higher than target dose
  171. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  172. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target));
  173. d_penalty = 1.0e0 * sum(temp1.^2);
  174. case 'max_sq'
  175. % penalize if achieved dose is higher than target dose
  176. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  177. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target));
  178. d_penalty = 1.0e0 * sum(temp1.^2);
  179. case 'LeastSquare'
  180. % penalize with sum of squares any deviation from target
  181. % dose
  182. d_penalty = 1.0e-1* sum(((...
  183. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) - ...
  184. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target).^2);
  185. case 'min_perc_Volume'
  186. % penalize by amount of volume under threshold
  187. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  188. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) > 0)) ...
  189. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target);
  190. d_penalty = 3.0e5 * min(perc_vox-0.05, 0)
  191. case 'max_perc_Volume'
  192. % penalize by amount of volume under threshold
  193. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  194. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) < 0)) ...
  195. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target);
  196. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  197. end
  198. penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  199. end
  200. end
  201. % ---- GET BEAMLETS ----
  202. function beamlets = get_beamlets(beamlet_cell_array, numVox);
  203. wbar1 = waitbar(0, 'Creating beamlet array');
  204. numBeam = size(beamlet_cell_array,2);
  205. batchSize=100;
  206. beamlets = sparse(0, 0);
  207. for beam_i=1:numBeam
  208. % for each beam define how much dose it delivers on each voxel
  209. idx=beamlet_cell_array{1, beam_i}.non_zero_indices;
  210. % break the beamlets into multiple batches
  211. if rem(beam_i, batchSize)==1;
  212. beamlet_batch = sparse(numVox, batchSize);
  213. beam_i_temp=1;
  214. end
  215. beamlet_batch(idx, beam_i_temp) = 1000*beamlet_cell_array{1, beam_i}.non_zero_values;
  216. waitbar(beam_i/numBeam, wbar1, ['Adding beamlet array: #', num2str(beam_i)])
  217. % add the batch to full set when filled
  218. if rem(beam_i, batchSize)==0;
  219. beamlets =[beamlets, beamlet_batch];
  220. end
  221. % crop and add the batch to full set when completed
  222. if beam_i==numBeam;
  223. beamlet_batch=beamlet_batch(:, 1:beam_i_temp);
  224. beamlets =[beamlets, beamlet_batch];
  225. end
  226. beam_i_temp=beam_i_temp+1;
  227. end
  228. close(wbar1)
  229. end
  230. function show_joint_beamlets(beamlets, IMGsize, Beam_list)
  231. % this function overlays and plots multiple beamlets. The goal is to
  232. % check whether some beamlets are part of the same beam manually.
  233. beam=sum(beamlets(:, Beam_list), 2);
  234. beamImg=reshape(full(beam), IMGsize);
  235. orthoslice(beamImg)
  236. end
  237. % ---- MAKE ROI ROBUST ----
  238. function optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  239. % take regular optimal goal and translate it into several robust cases
  240. % RO_params - should have the information below
  241. % nrs - random scenarios
  242. % sss - system setup scenarios
  243. % rrs - random range scenarios
  244. % X - X>0 moves image right
  245. % Y - Y>0 moves image down
  246. % Z - in/out.
  247. shift_mag = 1; % vox of shift
  248. nrs_scene_list={[0,0,0]};
  249. % sss_scene_list={[0,0,0]};
  250. sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0]};
  251. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0],...
  252. % [-shift_mag*2,0,0], [shift_mag*2,0,0], [0,-shift_mag*2,0], [0,shift_mag*2,0]};
  253. rrs_scene_list={[0,0,0]};
  254. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\CDP_data\CDP5_DP_target.nrrd');
  255. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom\Tomo_DP_target.nrrd');
  256. for i = 1:numel(optGoal)
  257. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  258. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  259. optGoal{i}.NbrRangeScenarios =numel(rrs_scene_list);
  260. end
  261. for goal_i = 1:numel(optGoal)
  262. % get target
  263. idx=optGoal{goal_i}.ROI_idx;
  264. targetImg1=zeros(optGoal{goal_i}.imgDim);
  265. targetImg1(idx)=1;
  266. % get beamlets
  267. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  268. % modify target and beamlets
  269. targetImg2=targetImg1;
  270. % beamlets stay the same
  271. for sss_i = 1 :optGoal{goal_i}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  272. % modify target and beamlets
  273. targetImg3=get_RO_sss(targetImg2, sss_scene_list{sss_i});
  274. % beamlets stay the same
  275. for rrs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rrs
  276. % modify target and beamlets
  277. targetImg4=targetImg3;
  278. % beamlets stay the same
  279. %% make new target and beamlets
  280. ROI_idx=[];
  281. ROI_idx=find(targetImg4>0);
  282. if isfield(optGoal{goal_i}, 'target_alpha')
  283. target = double(optGoal{goal_i}.target_alpha * targetIn(ROI_idx));
  284. % disp('exists')
  285. else
  286. target = ones(numel(ROI_idx), 1) * optGoal{goal_i}.D_final;
  287. % disp('not exists')
  288. end
  289. beamlets_pruned = beamlets(ROI_idx, :);
  290. % save to optGoal output
  291. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.ROI_idx = ROI_idx;
  292. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned = beamlets_pruned;
  293. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target = target;
  294. end
  295. end
  296. end
  297. end
  298. end
  299. % ------ supp: RO case SSS ------
  300. function targetImg3=get_RO_sss(targetImg2, sss_scene_shift);
  301. % translate the target image
  302. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  303. end