NLP_beamlet_optimizer.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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\archive\PatientData_dog5_3';
  25. case 'gbm_005'
  26. patient_dir = 'C:\010-work\003_localGit\WiscPlan_v2\data\PatData_ausGli_005';
  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. w0_beams = double(w0_beams);
  82. % -- CALLBACK OPTIMIZATION FUNCTION --
  83. fun1 = @(x) get_penalty(x, optGoal_beam);
  84. fun2 = @(x) get_penalty(x, optGoal);
  85. % -- OPTIMIZATION PARAMETERS --
  86. % define optimization parameters
  87. A = [];
  88. b = [];
  89. Aeq = [];
  90. beq = [];
  91. lb = zeros(1, numBeamlet);
  92. lb_beam = zeros(1, numBeam);
  93. ub = [];
  94. nonlcon = [];
  95. % define opt limits, and make it fmincon progress
  96. options = optimoptions('fmincon');
  97. options.MaxFunctionEvaluations = N_fcallback1;
  98. options.Display = 'iter';
  99. options.PlotFcn = 'optimplotfval';
  100. % options.UseParallel = true;
  101. % options.OptimalityTolerance = 1e-9;
  102. fprintf('\n running initial optimizer:')
  103. %% Run the optimization
  104. % -- GET FULL BEAM WEIGHTS --
  105. tic
  106. w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb_beam,ub,nonlcon,options);
  107. fprintf(' done!:')
  108. % t=toc;
  109. % disp(['Optimization time for beams = ',num2str(t)]);
  110. w_beamlets = ones(numBeamlet,1);
  111. numBeam=numel(unique(beam_i_list));
  112. for beam_i = 1:numBeam % assign weights to beamlets
  113. % beamlets from same beam get same initial weights
  114. w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  115. end
  116. w_beamlets = w_beamlets + (2*rand(size(w_beamlets))-1) *0.1 .*w_beamlets; % small random perturbation
  117. w_beamlets = 1.1* w_beamlets; % this just kicks the beamlets up a bit to make it easier for the optimizer to start
  118. % -- GET FULL BEAMLET WEIGHTS --
  119. options.MaxFunctionEvaluations = N_fcallback2;
  120. % tic
  121. fprintf('\n running full optimizer:')
  122. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  123. fprintf(' done!:')
  124. t=toc;
  125. disp(['Optimization time for beamlets = ',num2str(t)]);
  126. %% evaluate the results
  127. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  128. %% save outputs
  129. NLP_result.dose = D_full;
  130. NLP_result.weights = w_fin;
  131. save([patient_dir '\matlab_files\NLP_result.mat'], 'NLP_result');
  132. plot_DVH(D_full, optGoal, optGoal_idx, targetMinMax_idx)
  133. colorwash(Geometry.data, D_full);
  134. % plot_DVH_robust(D_full, optGoal, optGoal_idx)
  135. end
  136. %% support functions
  137. % ---- PENALTY FUNCTION ----
  138. function penalty = get_penalty(x, optGoal)
  139. % this function gets called by the optimizer. It checks the penalty for
  140. % all the robust implementation and returns the worst result.
  141. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  142. fobj = zeros(NumScenarios,1);
  143. sc_i = 1;
  144. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  145. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  146. for rrs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  147. fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rrs_i);
  148. sc_i = sc_i + 1;
  149. end
  150. end
  151. end
  152. % take the worst case penalty of evaluated scenarios
  153. penalty=max(fobj);
  154. end
  155. % ------ supp: penalty for single scenario ------
  156. function penalty = eval_f(x, optGoal, nrs_i, sss_i, rrs_i)
  157. penalty = 0;
  158. % for each condition
  159. for goal_i = 1:numel(optGoal)
  160. switch optGoal{goal_i}.function
  161. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  162. case 'min'
  163. % penalize if achieved dose is lower than target dose
  164. d_penalty = 1.0e0 * sum(max(0, ...
  165. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  166. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)));
  167. case 'max'
  168. % penalize if achieved dose is higher than target dose
  169. d_penalty = 1.0e0 * sum(max(0, ...
  170. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  171. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target)));
  172. case 'min_sq'
  173. % penalize if achieved dose is higher than target dose
  174. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  175. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target));
  176. d_penalty = 1.0e0 * sum(temp1.^2);
  177. case 'max_sq'
  178. % penalize if achieved dose is higher than target dose
  179. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x)-...
  180. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target));
  181. d_penalty = 1.0e0 * sum(temp1.^2);
  182. case 'LeastSquare'
  183. % penalize with sum of squares any deviation from target
  184. % dose
  185. d_penalty = 1.0e-1* sum(((...
  186. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) - ...
  187. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target).^2);
  188. case 'min_perc_Volume'
  189. % penalize by amount of volume under threshold
  190. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  191. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) > 0)) ...
  192. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target);
  193. d_penalty = 3.0e5 * min(perc_vox-0.05, 0)
  194. case 'max_perc_Volume'
  195. % penalize by amount of volume under threshold
  196. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target) -...
  197. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned * x) < 0)) ...
  198. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target);
  199. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  200. end
  201. penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  202. end
  203. end
  204. % ---- GET BEAMLETS ----
  205. function beamlets = get_beamlets(beamlet_cell_array, numVox);
  206. wbar1 = waitbar(0, 'Creating beamlet array');
  207. numBeam = size(beamlet_cell_array,2);
  208. batchSize=100;
  209. beamlets = sparse(0, 0);
  210. for beam_i=1:numBeam
  211. % for each beam define how much dose it delivers on each voxel
  212. idx=beamlet_cell_array{1, beam_i}.non_zero_indices;
  213. % break the beamlets into multiple batches
  214. if rem(beam_i, batchSize)==1;
  215. beamlet_batch = sparse(numVox, batchSize);
  216. beam_i_temp=1;
  217. end
  218. beamlet_batch(idx, beam_i_temp) = 1000*beamlet_cell_array{1, beam_i}.non_zero_values;
  219. waitbar(beam_i/numBeam, wbar1, ['Adding beamlet array: #', num2str(beam_i)])
  220. % add the batch to full set when filled
  221. if rem(beam_i, batchSize)==0;
  222. beamlets =[beamlets, beamlet_batch];
  223. end
  224. % crop and add the batch to full set when completed
  225. if beam_i==numBeam;
  226. beamlet_batch=beamlet_batch(:, 1:beam_i_temp);
  227. beamlets =[beamlets, beamlet_batch];
  228. end
  229. beam_i_temp=beam_i_temp+1;
  230. end
  231. close(wbar1)
  232. end
  233. function show_joint_beamlets(beamlets, IMGsize, Beam_list)
  234. % this function overlays and plots multiple beamlets. The goal is to
  235. % check whether some beamlets are part of the same beam manually.
  236. beam=sum(beamlets(:, Beam_list), 2);
  237. beamImg=reshape(full(beam), IMGsize);
  238. orthoslice(beamImg)
  239. end
  240. % ---- MAKE ROI ROBUST ----
  241. function optGoal = make_robust_optGoal(optGoal, RO_params, beamlets);
  242. % take regular optimal goal and translate it into several robust cases
  243. % RO_params - should have the information below
  244. % nrs - random scenarios
  245. % sss - system setup scenarios
  246. % rrs - random range scenarios
  247. % X - X>0 moves image right
  248. % Y - Y>0 moves image down
  249. % Z - in/out.
  250. shift_mag = 3; % vox of shift
  251. nrs_scene_list={[0,0,0]};
  252. % sss_scene_list={[0,0,0]};
  253. sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0]};
  254. % sss_scene_list={[0,0,0], [-shift_mag,0,0], [shift_mag,0,0], [0,-shift_mag,0], [0,shift_mag,0],...
  255. % [-shift_mag*2,0,0], [shift_mag*2,0,0], [0,-shift_mag*2,0], [0,shift_mag*2,0]};
  256. rrs_scene_list={[0,0,0]};
  257. [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  258. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\PD_HD_dicomPhantom\Tomo_DP_target.nrrd');
  259. % [targetIn, meta] = nrrdread('C:\010-work\003_localGit\WiscPlan_v2\data\archive\CDP_data\CDP5_DP_target.nrrd');
  260. for i = 1:numel(optGoal)
  261. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  262. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  263. optGoal{i}.NbrRangeScenarios =numel(rrs_scene_list);
  264. end
  265. for goal_i = 1:numel(optGoal)
  266. % get target
  267. idx=optGoal{goal_i}.ROI_idx;
  268. targetImg1=zeros(optGoal{goal_i}.imgDim);
  269. targetImg1(idx)=1;
  270. % get beamlets
  271. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  272. % modify target and beamlets
  273. targetImg2=targetImg1;
  274. % beamlets stay the same
  275. for sss_i = 1 :optGoal{goal_i}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  276. % modify target and beamlets
  277. targetImg3=get_RO_sss(targetImg2, sss_scene_list{sss_i});
  278. % beamlets stay the same
  279. for rrs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rrs
  280. % modify target and beamlets
  281. targetImg4=targetImg3;
  282. % beamlets stay the same
  283. %% make new target and beamlets
  284. ROI_idx=[];
  285. ROI_idx=find(targetImg4>0);
  286. if isfield(optGoal{goal_i}, 'target_alpha')
  287. target = double(optGoal{goal_i}.target_alpha * targetIn(ROI_idx));
  288. % disp('exists')
  289. else
  290. target = ones(numel(ROI_idx), 1) .* optGoal{goal_i}.D_final;
  291. % disp('not exists')
  292. end
  293. beamlets_pruned = beamlets(ROI_idx, :);
  294. % save to optGoal output
  295. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.ROI_idx = ROI_idx;
  296. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.beamlets_pruned = beamlets_pruned;
  297. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rrs{rrs_i}.target = target;
  298. end
  299. end
  300. end
  301. end
  302. end
  303. % ------ supp: RO case SSS ------
  304. function targetImg3=get_RO_sss(targetImg2, sss_scene_shift);
  305. % translate the target image
  306. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  307. end