1
0

FullRO_NLP_optimizer_v3.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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] = FullRO_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. [path2scBeams] = uigetdir([WiscPlan_preferences.patientDataPath ], 'Select folder with scenario beamlets');
  30. else
  31. Pat_path = varargin{1};
  32. path2geometry = [Pat_path, '\matlab_files\Geometry.mat'];
  33. path2goal = varargin{2};
  34. [Goal_path,Goal_file,ext] = fileparts(path2goal);
  35. path2scBeams = varargin{3};
  36. end
  37. dialogue_box = 'no'
  38. switch dialogue_box
  39. case 'yes'
  40. str = inputdlg({'N of iterations for initial calc', 'N of iterations for full calc', ...
  41. 'Use pre-existing NLP_result to initiate? (y/n)'}, 'input', [1,35], {'100000', '500000', 'n'});
  42. N_fcallback1 = str2double(str{1}); % 100000 is a good guesstimate
  43. N_fcallback2 = str2double(str{2}); % 500000 is a good guesstimate
  44. pre_beamWeights = str{3};
  45. case 'no'
  46. disp('dialogue box skipped')
  47. N_fcallback1 = 1e5;
  48. N_fcallback2 = 2e6; % 500000;
  49. pre_beamWeights = 'n';
  50. end
  51. switch pre_beamWeights
  52. case 'y'
  53. [NLP_file,NLP_path,indx] = uigetfile([Pat_path '\matlab_files\*.mat'], 'Select NLP_result file');
  54. load([NLP_path, NLP_file])
  55. w_beamlets = NLP_result.weights;
  56. load([path2scBeams '\scenario1\all_beams.mat'])
  57. if numel(all_beams) ~= numel(w_beamlets)
  58. error('Provided weight number does not match beamlet number!')
  59. end
  60. case 'n'
  61. disp('Initial beam weights will be calculated.')
  62. end
  63. %% PROGRAM STARTS HERE
  64. % - no tocar lo que hay debajo -
  65. fprintf('starting NLP optimization process... \n')
  66. % % -- LOAD GEOMETRY, GOALS, BEAMLETS --
  67. load(path2geometry)
  68. load(path2goal)
  69. %%%% FIGURE out this part for the full RO appraoch.
  70. % [beamlets, numBeamlet] = get_beamlets(Geometry, Pat_path, OptGoals);
  71. % [beamlets, beamlets_joined, numBeamlet, numBeam, beam_i_list] = get_beam_lets(Geometry, Pat_path);
  72. %% -- OPTIMIZATION TARGETS --
  73. % -- make the optimization optGoal structure --
  74. for i_goal = 1:size(OptGoals.goals,1)
  75. if isfield(OptGoals.data{i_goal}, 'SupVox_num')
  76. SupVox_num = OptGoals.data{i_goal}.SupVox_num;
  77. else
  78. answer = inputdlg(['# of supervoxels for "' OptGoals.data{i_goal}.name '" with ' num2str(numel(OptGoals.data{i_goal}.ROI_idx)) ' vox: ("0" to skip)'])
  79. SupVox_num = str2double(answer{1})
  80. end
  81. optGoal{i_goal} = OptGoals.data{i_goal};
  82. optGoal{i_goal}.sss_scene_list = OptGoals.sss_scene_list;
  83. optGoal{i_goal}.maxModulation = OptGoals.maxModulation;
  84. optGoal{i_goal}.BeamSmoothMax = OptGoals.BeamSmoothMax;
  85. optGoal{i_goal}.optFuncNum = OptGoals.optFuncNum;
  86. % modulation
  87. if strcmp( '-||-' , optGoal{i_goal}.ROI_name)
  88. % optGoal{i_goal}.ROI_idx_old = optGoal{i_goal-1}.ROI_idx_old; % copy old index data
  89. % optGoal{i_goal}.opt_weight = optGoal{i_goal}.opt_weight * numel(optGoal{i_goal}.ROI_idx_old)/numel(optGoal{i_goal}.ROI_idx);
  90. optGoal{i_goal}.ROI_idx = optGoal{i_goal-1}.ROI_idx
  91. if isfield(OptGoals.data{i_goal}, 'wgt_map')
  92. optGoal{i_goal}.vox_wgt = optGoal{i_goal-1}.vox_wgt;
  93. end
  94. optGoal{i_goal}.beamlets_pruned = optGoal{i_goal-1}.beamlets_pruned;
  95. else
  96. switch SupVox_num
  97. case 0
  98. error('You should always specify supervoxels now')
  99. % if not supervoxel, just select provided ROI_idx
  100. % optGoal{i_goal}.beamlets_pruned = sparse(beamlets(optGoal{i_goal}.ROI_idx, :));
  101. otherwise
  102. % -- if supervoxel, merge given columns
  103. % - make supervoxel map
  104. switch OptGoals.goals{i_goal, 3}
  105. case 'Fixed dose'
  106. mask = zeros(OptGoals.data{i_goal}.imgDim);
  107. mask(OptGoals.data{i_goal}.ROI_idx) = 1;
  108. case 'Dose map'
  109. mask = zeros(OptGoals.data{i_goal}.imgDim);
  110. mask(OptGoals.data{i_goal}.ROI_idx) = OptGoals.data{i_goal}.D_final;
  111. mask2 = round(mask/3)*3;
  112. end
  113. % group superpixels
  114. superMask = superpix_group(mask, SupVox_num, 'no');
  115. optGoal{i_goal}.superMask = superMask;
  116. % orthoslice(superMask)
  117. end
  118. end
  119. end
  120. % -- make them robust --
  121. RO_params=0;
  122. [optGoal, numBeamlet] = make_fullRO_optGoal(optGoal, RO_params, path2scBeams);
  123. % save([Goal_path, Goal_file '_robust.mat'], 'optGoal')
  124. % -- get beamlet indeces --
  125. load([path2scBeams '\scenario1\all_beams.mat'])
  126. Nbeamlets = all_beams{1}.Mxp; % number of beamlets in a beam - usually 64 or 32
  127. weightTable = zeros(3,Nbeamlets);
  128. for ind_bmlt = 1:numel(all_beams)
  129. bLet_idx.y(ind_bmlt) = floor(all_beams{1, ind_bmlt}.num/Nbeamlets)+1;
  130. bLet_idx.x(ind_bmlt) = rem(all_beams{1, ind_bmlt}.num, Nbeamlets)+1;
  131. weightTable(bLet_idx.y(ind_bmlt),bLet_idx.x(ind_bmlt)) = 1;
  132. end
  133. bLet_idx.idx = find(weightTable>0);
  134. bLet_idx.Nbeamlets = Nbeamlets;
  135. disp('.')
  136. % -- CALLBACK OPTIMIZATION FUNCTION --
  137. fun1 = @(x) get_penalty(x, optGoal_beam, bLet_idx);
  138. fun2 = @(x) get_penalty(x, optGoal, bLet_idx);
  139. % -- OPTIMIZATION PARAMETERS --
  140. % define optimization parameters
  141. A = [];
  142. b = [];
  143. Aeq = [];
  144. beq = [];
  145. lb = zeros(1, numBeamlet);
  146. % lb_beam = zeros(1, numBeam);
  147. ub = [];
  148. nonlcon = [];
  149. % define opt limits, and make it fmincon progress
  150. options = optimoptions('fmincon');
  151. options.MaxFunctionEvaluations = N_fcallback1;
  152. options.Display = 'iter';
  153. options.PlotFcn = 'optimplotfval';
  154. % options.UseParallel = true;
  155. options.UseParallel = false;
  156. % options.OptimalityTolerance = 1e-9;
  157. %% -- INITIALIZE BEAMLET WEIGHTS --
  158. switch pre_beamWeights
  159. case 'y'
  160. % should have been assigned previously.
  161. disp('Provided beamlet weights used for initial comparison')
  162. case 'n'
  163. % if initial beamlet weights are not provided, get quick estimate
  164. % fprintf('\n running initial optimizer:')
  165. % initialize beamlet weights, OR
  166. w0 = ones(numBeamlet,1);
  167. % w0 = mean(optGoal{1}.D_final(optGoal{1}.ROI_idx) ./ (optGoal{1}.beamlets_pruned*w0+0.1)) * w0; % old
  168. w0 = mean(optGoal{1}.D_final(:)) ./ mean(optGoal{1}.nrs{1}.sss{1}.rgs{1}.beamlets_pruned*w0+0.05) * w0;
  169. w_beamlets = double(w0);
  170. % -- GET BEAM WEIGHTS --
  171. % tic
  172. % w_beam = fmincon(fun1,w0_beams,A,b,Aeq,beq,lb,ub,nonlcon,options);
  173. % fprintf(' done!:')
  174. % t=toc;
  175. % disp(['Optimization time for beams = ',num2str(t)]);
  176. %
  177. % w_beamlets = ones(numBeamlet,1);
  178. % numBeam=numel(unique(beam_i_list));
  179. % for beam_i = 1:numBeam % assign weights to beamlets
  180. % % beamlets from same beam get same initial weights
  181. % w_beamlets(beam_i_list == beam_i) = w_beam(beam_i);
  182. % end
  183. end
  184. %% FULL OPTIMIZATION
  185. % -- GET FULL BEAMLET WEIGHTS --
  186. options.MaxFunctionEvaluations = N_fcallback2;
  187. tic
  188. fprintf('\n running full optimizer:')
  189. w_fin = fmincon(fun2,w_beamlets,A,b,Aeq,beq,lb,ub,nonlcon,options);
  190. fprintf(' done!:')
  191. t=toc;
  192. disp(['Optimization time for beamlets = ',num2str(t)]);
  193. %% evaluate the results
  194. [beamlets, numBeamlet] = get_beamlets_fullRO(optGoal{1}.imgDim, [path2scBeams '\scenario1'], optGoal);
  195. D_full = reshape(beamlets * w_fin, size(Geometry.data));
  196. %% save outputs
  197. NLP_result.dose = D_full;
  198. NLP_result.weights = w_fin;
  199. NLP_result.sss_scene_list = optGoal{1}.sss_scene_list;
  200. NLP_result.maxModulation = OptGoals.maxModulation;
  201. NLP_result.BeamSmoothMax = OptGoals.BeamSmoothMax;
  202. save([path2scBeams, '\FRO_result_' Goal_file '.mat'], 'NLP_result');
  203. % plot_DVH(Geometry, D_full)
  204. DQM_DVH(Geometry, D_full)
  205. colorwash(Geometry.data, D_full, [500, 1500], [0, 90]);
  206. end
  207. %% support functions
  208. % ---- PENALTY FUNCTION ----
  209. function penalty = get_penalty(x, optGoal, bLet_idx)
  210. % this function gets called by the optimizer. It checks the penalty for
  211. % all the robust implementation and returns the worst result.
  212. NumScenarios = optGoal{1}.NbrRandScenarios * optGoal{1}.NbrSystSetUpScenarios * optGoal{1}.NbrRangeScenarios;
  213. fobj = zeros(NumScenarios,numel(optGoal)+2);
  214. sc_i = 1;
  215. for nrs_i = 1:optGoal{1}.NbrRandScenarios
  216. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  217. for rgs_i = 1:optGoal{1}.NbrRangeScenarios % range scenario = rs
  218. % fobj(sc_i)=eval_f(x, optGoal, nrs_i, sss_i, rgs_i, bLet_idx);
  219. fobj(sc_i,:) = eval_f(x, optGoal, nrs_i, sss_i, rgs_i, bLet_idx);
  220. sc_i = sc_i + 1;
  221. end
  222. end
  223. end
  224. switch optGoal{1}.optFuncNum
  225. case 1 % "RO max"
  226. penalty=max(sum(fobj,2));
  227. case 2 % "RO mean"
  228. penalty=mean(sum(fobj,2));
  229. case 3 % "RO objective-based"
  230. penalty=sum(max(fobj,[],1));
  231. case 4 % "Classical"
  232. penalty=sum(fobj(1,:));
  233. end
  234. % take the worst case penalty of evaluated scenarios
  235. % penalty=max(fobj);
  236. % take the median worst case (stochastic robust)
  237. % penalty=median(fobj);
  238. end
  239. % ------ supp: penalty for single scenario ------
  240. function penArray = eval_f(x, optGoal, nrs_i, sss_i, rgs_i, bLet_idx)
  241. % penalty = 0;
  242. penArray = zeros(1,numel(optGoal)+2); % all the optGoals, plus modulation plus smoothing
  243. % for each condition
  244. for goal_i = 1:numel(optGoal)
  245. switch optGoal{goal_i}.function
  246. % min, max, min_sq, max_sq, LeastSquare, min_perc_Volume, max_perc_Volume
  247. case 'min'
  248. % penalize if achieved dose is lower than target dose
  249. d_penalty = 1.0e0 * sum(max(0, ...
  250. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  251. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)));
  252. case 'max'
  253. % penalize if achieved dose is higher than target dose
  254. d_penalty = 1.0e0 * sum(max(0, ...
  255. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  256. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target)));
  257. case 'min_sq'
  258. % penalize if achieved dose is lower than target dose
  259. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  260. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  261. d_penalty = 1.0e0 * sum(temp1.*temp1);
  262. case 'max_sq'
  263. % penalize if achieved dose is higher than target dose
  264. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  265. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  266. d_penalty = 1.0e0 * sum(temp1.*temp1);
  267. case 'min_step'
  268. % penalize if achieved dose is lower than target dose
  269. temp1=-min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  270. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  271. d_penalty = 1.0e1 * (sum(temp1.*temp1) + 1.0e3* sum(temp1>0)/numel(temp1));
  272. case 'max_step'
  273. % penalize if achieved dose is higher than target dose
  274. temp1=max(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  275. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  276. d_penalty = 1.0e1 * (sum(temp1.*temp1) + 1.0e3* sum(temp1>0)/numel(temp1));
  277. case 'LeastSquare'
  278. % penalize with sum of squares any deviation from target
  279. % dose
  280. temp1 = (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) - ...
  281. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target;
  282. d_penalty = 1.0e0* sum(temp1.^2);
  283. case 'min_perc_Volume'
  284. % penalize by amount of volume under threshold
  285. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  286. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) > 0)) ...
  287. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  288. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  289. case 'max_perc_Volume'
  290. % penalize by amount of volume under threshold
  291. perc_vox = numel(find((optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target) -...
  292. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x) < 0)) ...
  293. / numel(optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target);
  294. d_penalty = 3.0e4 * min(perc_vox-0.05, 0)
  295. case 'min_sq_voxwgt'
  296. % penalize if achieved dose is lower than target dose
  297. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  298. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  299. d_penalty = 1.0e0 * sum(temp1.*temp1.* optGoal{goal_i}.vox_wgt');
  300. case 'max_sq_voxwgt'
  301. % penalize if achieved dose is lower than target dose
  302. temp1=min(0, (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned * x)-...
  303. (optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target));
  304. d_penalty = 1.0e0 * sum(temp1.*temp1.* optGoal{goal_i}.vox_wgt');
  305. end
  306. % penalty = penalty + d_penalty * optGoal{goal_i}.opt_weight;
  307. penArray(goal_i) = d_penalty * optGoal{goal_i}.opt_weight;
  308. end
  309. %% add modulation penalty
  310. if true
  311. if isfield(optGoal{goal_i}, 'maxModulation')
  312. max_modulation = optGoal{goal_i}.maxModulation;
  313. else
  314. error('no Max modulation parameter enterd!')
  315. max_modulation = 5;
  316. end
  317. mod_pen_weight = 1.0e10;
  318. % calc the penalty
  319. mod_excess = max(0, x-max_modulation*mean(x));
  320. % mod_excess = max(0, x-max_modulation*mean(x(x>1)));
  321. mod_pen1 = mod_pen_weight*(sum(mod_excess) + numel(mod_excess)* any(mod_excess));
  322. % penalty = penalty + mod_pen1;
  323. penArray(end-1) = mod_pen1;
  324. end
  325. %% add penlty for single off beamlets - version 2
  326. if false
  327. if isfield(optGoal{goal_i}, 'BeamSmoothMax')
  328. BeamSmoothMax = optGoal{goal_i}.BeamSmoothMax;
  329. else
  330. error('no Max beam smooth parameter enterd!')
  331. BeamSmoothMax = 1e6;
  332. end
  333. mod_pen_weight = BeamSmoothMax; %1.0e6
  334. x_down = zeros(size(x));
  335. x_down(2:end) = x(1:end-1);
  336. x_down2 = zeros(size(x));
  337. x_down2(3:end) = x(1:end-2);
  338. x_up = zeros(size(x));
  339. x_up(1:end-1) = x(2:end);
  340. x_up2 = zeros(size(x));
  341. x_up2(1:end-2) = x(3:end);
  342. mod_pen2 = mod_pen_weight*sum((x_down+x_up-2*x).^2 + 0.5*(x_down2+x_up2-2*x).^2)/(mean(x)^(2)*numel(x));
  343. % penalty = penalty + mod_pen2;
  344. penArray(end) = mod_pen2;
  345. end
  346. %% add penlty for single off beamlets - version 3
  347. if true
  348. if isfield(optGoal{goal_i}, 'BeamSmoothMax')
  349. BeamSmoothMax = optGoal{goal_i}.BeamSmoothMax;
  350. else
  351. error('no Max beam smooth parameter enterd!')
  352. BeamSmoothMax = 1e6;
  353. end
  354. mod_pen_weight = BeamSmoothMax; %1.0e6
  355. % make 2D beamletWeight map
  356. maxY = max(bLet_idx.y);
  357. tabula = zeros(maxY, bLet_idx.Nbeamlets);
  358. tabula(bLet_idx.idx) = x;
  359. % for each index calculate laplace
  360. myWeights = 1/12*[1,3,1; 1,-12,1; 1,3,1];
  361. i=2:maxY-1;
  362. j=2:bLet_idx.Nbeamlets-1;
  363. tabula2(i,j) = ...
  364. myWeights(1)*tabula(i-1,j-1) + myWeights(4)*tabula(i-1,j) + myWeights(7)*tabula(i-1,j+1)...
  365. +myWeights(2)*tabula(i,j-1) + myWeights(8)*tabula(i,j+1) ...
  366. +myWeights(3)*tabula(i+1,j-1) + myWeights(6)*tabula(i+1,j) + myWeights(9)*tabula(i+1,j+1)...
  367. +myWeights(5)*tabula(i,j);
  368. tabula2(1,j) = ...
  369. myWeights(2)*tabula(1,j-1) + myWeights(8)*tabula(1,j+1)...
  370. +myWeights(3)*tabula(2,j-1) + myWeights(6)*tabula(2,j) + myWeights(9)*tabula(2,j+1)...
  371. +myWeights(5)*tabula(1,j);
  372. tabula2(maxY,j) =...
  373. myWeights(1)*tabula(maxY-1,j-1) + myWeights(4)*tabula(maxY-1,j) + myWeights(7)*tabula(maxY-1,j+1)...
  374. +myWeights(2)*tabula(maxY,j-1) + myWeights(8)*tabula(maxY,j+1) ...
  375. +myWeights(5)*tabula(maxY,j);
  376. % make sum of squares
  377. mod_pen2 = mod_pen_weight*sum((tabula2(:)).^2)/(mean(x.^2)*numel(x));
  378. % penalty = penalty + mod_pen2;
  379. penArray(end) = mod_pen2;
  380. end
  381. end
  382. % ---- MAKE ROI ROBUST ----
  383. function [optGoal, numBeamlet] = make_fullRO_optGoal(optGoal, RO_params, path2scBeams);
  384. % take regular optimal goal and translate it into several robust cases
  385. % RO_params - should have the information below
  386. % nrs - random scenarios
  387. % sss - system setup scenarios
  388. % rgs - random range scenarios
  389. % X - X>0 moves image right
  390. % Y - Y>0 moves image down
  391. % Z - in/out.
  392. shift_X = 2; % vox of shift
  393. shift_Y = 2; % vox of shift
  394. shift_Z = 1; % vox of shift
  395. nrs_scene_list={[0,0,0]};
  396. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  397. if isfield(optGoal{1}, 'sss_scene_list')
  398. sss_scene_list = optGoal{1}.sss_scene_list;
  399. else
  400. error('New OptGoals should no longer reach this code!')
  401. % 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]};
  402. % optGoal{1}.sss_scene_list = sss_scene_list;
  403. end
  404. % sss_scene_list={[0,0,0]};
  405. % ----====#### CHANGE ROBUSTNESS HERE ####====----
  406. rgs_scene_list={[0,0,0]};
  407. for i = 1:numel(optGoal)
  408. optGoal{i}.NbrRandScenarios =numel(nrs_scene_list);
  409. optGoal{i}.NbrSystSetUpScenarios=numel(sss_scene_list);
  410. optGoal{i}.NbrRangeScenarios =numel(rgs_scene_list);
  411. end
  412. % for each scenario
  413. for sss_i = 1 :optGoal{1}.NbrSystSetUpScenarios % syst. setup scenarios = sss
  414. % load new beamlets
  415. patient_dir = [path2scBeams '\scenario' num2str(sss_i)];
  416. [beamlets, numBeamlet] = get_beamlets_fullRO(optGoal{1}.imgDim, patient_dir, optGoal);
  417. disp(['- scenario ' num2str(sss_i) ' beamlets loaded.'])
  418. for goal_i = 1:numel(optGoal)
  419. % get target
  420. idx=optGoal{goal_i}.ROI_idx;
  421. targetImg1=zeros(optGoal{goal_i}.imgDim);
  422. targetImg1(idx)=1;
  423. % get beamlets
  424. for nrs_i = 1:optGoal{goal_i}.NbrRandScenarios % num. of random scenarios
  425. % modify target and beamlets
  426. % targetImg3=targetImg1;
  427. % beamlets stay the same
  428. for rgs_i = 1:optGoal{goal_i}.NbrRangeScenarios % range scenario = rgs
  429. % modify target and beamlets
  430. targetImg4=targetImg1;
  431. % beamlets stay the same
  432. % function to put in superMask and get out updated optGoal
  433. [beamlets_pruned, targetD] = superVoxMerge(optGoal{goal_i}, beamlets);
  434. % needs to return "beamlets_pruned" and "target" arrays
  435. % save to optGoal output
  436. % optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.ROI_idx = ROI_idx; % some old code, not used?
  437. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.beamlets_pruned = beamlets_pruned; % beamlets, only within target and supervoxeled
  438. optGoal{goal_i}.nrs{nrs_i}.sss{sss_i}.rgs{rgs_i}.target = targetD'; % target does that we try to achieve
  439. end
  440. end
  441. end
  442. end
  443. end
  444. %% ---- Supervoxel merge optGoals ----
  445. function [beamlets_pruned, targetD] = superVoxMerge(optGoal, beamlets)
  446. superMask = optGoal.superMask;
  447. superVoxList = unique(superMask);
  448. superVoxList = superVoxList(superVoxList>0);
  449. optGoal.ROI_idx_full = optGoal.ROI_idx; % copy old index data
  450. % optGoal.ROI_idx = zeros(numel(superVoxList), 1);
  451. optGoal.opt_weight = optGoal.opt_weight * numel(optGoal.ROI_idx_full)/numel(optGoal.ROI_idx);
  452. if isfield(optGoal, 'wgt_map')
  453. tabula_wgtmap = zeros(size(superMask));
  454. tabula_wgtmap(optGoal.optGoal.ROI_idx_full) = optGoal.wgt_map;
  455. end
  456. h_w1 = waitbar(0, 'merging superboxels');
  457. dose_tabula = zeros(optGoal.imgDim);
  458. dose_tabula(optGoal.ROI_idx_full) = optGoal.D_final;
  459. for i_supVox = 1:numel(superVoxList)
  460. waitbar(i_supVox/numel(superVoxList), h_w1)
  461. supVox_idx = superVoxList(i_supVox);
  462. idxList = find(superMask == supVox_idx);
  463. % merge beamlet doses
  464. beamlets_pruned(i_supVox,:) = sparse(mean(beamlets(idxList, :),1));
  465. targetD(i_supVox) = mean(dose_tabula(idxList),1);
  466. if isfield(optGoal, 'vox_wgt')
  467. optGoal.vox_wgt(i_supVox) = sum(tabula_wgtmap(idxList));
  468. end
  469. % -- make new indeces
  470. % optGoal.ROI_idx(i_supVox) = idxList(1);
  471. end
  472. close(h_w1)
  473. end
  474. %% ------ supp: RO case SSS ------
  475. function [targetImg3 ia]=get_RO_sss(targetImg2, sss_scene_shift);
  476. % translate the target image
  477. targetImg3 = imtranslate(targetImg2,sss_scene_shift);
  478. % now we need to figure out if any target voxels fell out during the
  479. % shift
  480. imgValid = imtranslate(targetImg3,-sss_scene_shift);
  481. imgInvalid = (targetImg2-imgValid);
  482. idx_1 = find(targetImg2);
  483. idx_2 = find(imgInvalid);
  484. [idxValid,ia] = setdiff(idx_1,idx_2);
  485. [C,ia, ib] = intersect(idx_1,idxValid);
  486. end