pinn2matlab.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. %% pinn2matlab.m
  2. % Ryan T Flynn 23 August 2007
  3. %
  4. % Reads in raw Pinnacle data to a MATLAB data structure. The patient CT,
  5. % ROIs, and Trial files can all be read in if available and desired. The
  6. % result is a structure called 'Geometry', which contains ROIS and Trial
  7. % fields.
  8. %
  9. % The CT image and all of the ROIs are flipped onto a coordinate system in
  10. % which the position of each voxel index (i,j,k) are given by:
  11. %
  12. % x(i) = x0 + i*delx; (i=0,...,M-1)
  13. % y(j) = y0 + j*delx; (j=0,...,N-1)
  14. % z(k) = z0 + k*delx; (k=0,...,Q-1)
  15. %
  16. % As opposed to the Pinnacle coordinate system, which
  17. %
  18. % x(i) = x0 + i*delx; (i=0,...,M-1)
  19. % y(j) = y0 + (N-1-j)*dely; (j=0,...,N-1)
  20. % z(k) = z0 + k*delz; (k=0,...,Q-1)
  21. %
  22. % Stephen R Bowen April 2009
  23. %
  24. % The MATLAB structure Geometry has the following format:
  25. %
  26. % Geometry.voxel_size (dx dy dz)
  27. % .start (x y z)
  28. % .data (M x N x Q single float matrix)
  29. % .ROIS {1 x Nroi cell array} if readROIS flag on
  30. %
  31. % Within each index of the ROIS cell array, a data structure exists
  32. % containing the vector information from each Pinnacle mesh contour and indices
  33. % of the corresponding ROI mask used by WiscPlan:
  34. %
  35. % Geometry.ROIS{1}.name 'string'
  36. % .num_curves int
  37. % .curves {1 x num_curves cell array}
  38. % .ind (int32 data array)
  39. % .dim (M N Q)
  40. % .pix_dim (dx dy dz)
  41. % .start (x y z)
  42. % .start_ind 'string'
  43. %
  44. % This enables seamless translation between Pinnacle and MATLAB.
  45. %%
  46. %%%%% Start of user supplied inputs %%%%%
  47. % Read-in flags
  48. readTrial = 'no'; % either 'yes' or 'no'
  49. readROIS = 'yes'; % either 'yes' or 'no'
  50. % locations of the Pinnacle files
  51. roifile = '../plan/HN003/plan.roi';
  52. imageheaderfile = '../plan/HN003/HN003_planningCT.header';
  53. imagefile = '../plan/HN003/HN003_planningCT.img'; % CT file
  54. save_file = '../plan/HN003/HN003.mat';
  55. %%%%% End of user supplied inputs %%%%%
  56. %%
  57. start_ind = '(1,1,1)'; % this tag will be added to the ROIS so it is known where the start voxel is
  58. clear roi ROIS Trial Geometry CTimage; % start with a clean slate of structures
  59. % extract geometric information from the header file
  60. fid_imageheaderfile = fopen(imageheaderfile,'r');
  61. tline = fgets(fid_imageheaderfile);
  62. while tline ~= -1
  63. % check the line for key words
  64. if length(findstr(tline,'byte_order'))
  65. eval(tline);
  66. elseif length(findstr(tline,'x_dim')) & ~length(findstr(tline,'fname_index_start'))
  67. eval(tline); % run the line to get x_dim
  68. elseif length(findstr(tline,'y_dim'))
  69. eval(tline); % run the line to get y_dim
  70. elseif length(findstr(tline,'z_dim'))
  71. eval(tline); % run the line to get z_dim
  72. elseif length(findstr(tline,'x_pixdim'))
  73. eval(tline); % run the line to get x_pixdim
  74. elseif length(findstr(tline,'y_pixdim'))
  75. eval(tline); % run the line to get y_pixdim
  76. elseif length(findstr(tline,'z_pixdim'))
  77. eval(tline); % run the line to get z_pixdim
  78. elseif length(findstr(tline,'x_start'))
  79. eval(tline); % run the line to get x_start
  80. elseif length(findstr(tline,'y_start'))
  81. eval(tline); % run the line to get x_start
  82. elseif length(findstr(tline,'z_start'))
  83. eval(tline); % run the line to get x_start
  84. end
  85. tline = fgets(fid_imageheaderfile);
  86. end
  87. fclose(fid_imageheaderfile);
  88. % Read in the CT data
  89. fid_image = fopen(imagefile,'rb');
  90. if byte_order == 0
  91. CTimage = fread(fid_image,'short=>int16');
  92. elseif byte_order == 1
  93. CTimage = fread(fid_image,'short=>int16','ieee-be');
  94. end
  95. CTimage = reshape(CTimage,x_dim,y_dim,z_dim);
  96. fclose(fid_image);
  97. % flip the CT image onto the non-Pinnacle coordinate system
  98. CTimage = flipdim(CTimage,2);
  99. % save the results to the Geometry structure
  100. Geometry.start = single([x_start y_start z_start]);
  101. Geometry.voxel_size = single([x_pixdim y_pixdim z_pixdim]);
  102. Geometry.data = single(CTimage)/1024; % convert the CT data to density data, Pinnacle style
  103. Geometry.data(Geometry.data < 0) = 0; % truncate anything less than zero
  104. clear CTimage;
  105. if strcmp(readROIS,'yes')
  106. % read in the roi file
  107. fid_roifile = fopen(roifile,'r');
  108. roinames = {}; % start a cell array of the roi names
  109. Nroi = 0; % number of rois read in
  110. % Flags to indicate which sets of angled brackets in the roi file tline is
  111. % inside.
  112. inroi = 0;
  113. incurve = 0;
  114. inpoints = 0;
  115. roi_num = 0; % current roi number
  116. tline = fgets(fid_roifile);
  117. while tline ~= -1
  118. % check the line for key words
  119. if length(findstr(tline,'roi={'))
  120. inroi = 1; % mark that we are now currently inside of an roi
  121. roi_num = roi_num + 1;
  122. % next line contains the roi name
  123. tline = fgets(fid_roifile);
  124. % pop off first token in line, the remainder of the line is the roi name
  125. [T,R] = strtok(tline);
  126. roi.name = strtrim(R);
  127. % pop off lines until we get to the number of curves in this roi
  128. while ~length(findstr(tline,'num_curve'))
  129. tline = fgets(fid_roifile);
  130. end
  131. % pop off the num_curve string
  132. [T,R] = strtok(tline);
  133. % pop off the equals sign
  134. [T,R] = strtok(R);
  135. % pop off the number of curves in this roi
  136. T = strtok(R,';');
  137. % save the number of curves to the roi stucture
  138. eval(['roi.num_curves = ' num2str(T) ';']);
  139. roi.curves = {}; % get the curves structure started
  140. % read in the next curve structure
  141. curve_num = 0; % number of the current curve
  142. while roi.num_curves > 0 & curve_num < roi.num_curves
  143. while ~length(findstr(tline,'curve={'));
  144. tline = fgets(fid_roifile);
  145. end
  146. curve_num = curve_num + 1;
  147. incurve = 1; % inside the curve structure now
  148. % find the number of points in this structure
  149. while ~length(findstr(tline,'num_points'))
  150. tline = fgets(fid_roifile);
  151. end
  152. % pop off the num_points string
  153. [T,R] = strtok(tline);
  154. % pop off the equals sign
  155. [T,R] = strtok(R);
  156. % pop off the number of points in this curve
  157. T = strtok(R,';');
  158. eval(['num_points = ' num2str(T) ';']);
  159. % find the points identifier
  160. while ~length(findstr(tline,'points={'))
  161. tline = fgets(fid_roifile);
  162. end
  163. inpoints = 1; % inside the points structure now
  164. % read in the block of points data
  165. block = fscanf(fid_roifile,'%g',[3 num_points]);
  166. % save the block of points to the roi stucture
  167. roi.curves{curve_num} = block';
  168. % read in the right parantheses for the points and curve
  169. % structures
  170. while ~length(findstr(tline,'};'))
  171. tline = fgets(fid_roifile);
  172. end
  173. inpoints = 0; % stepped outside of the points structure
  174. while ~length(findstr(tline,'};'))
  175. tline = fgets(fid_roifile);
  176. end
  177. incurve = 0; % stepped outside of the curves structure
  178. end
  179. % read until the roi closing bracket appears
  180. while ~length(findstr(tline,'};'))
  181. tline = fgets(fid_roifile);
  182. end
  183. inroi = 0; % we are now outside of the roi
  184. fprintf('read in %s roi\n',roi.name);
  185. ROIS{roi_num} = roi;
  186. end
  187. tline = fgets(fid_roifile);
  188. end
  189. fclose(fid_roifile);
  190. % ROIS have all been read-in, now just have to convert them to mask
  191. % matrices. We'll use roipoly for this.
  192. % Recall that we must use the Pinnacle coordinate system for this to work,
  193. % that is, (x,y,z) coordinates are given by:
  194. % x(i) = x_start + i*x_pixdim, i=0..x_dim-1
  195. % y(j) = y_start + (y_dim-1)*y_pixdim - j*y_pixdim, j=0..y_dim-1
  196. % z(k) = z_start + k*z_pixdim, k=0..z_dim-1
  197. %
  198. % Not all treatment planning systems use this type of coordinate system
  199. % definition, so it is very important to get them straight.
  200. %
  201. % To get around this we will manipulate the data such that we'll have:
  202. %
  203. % x(i) = x_start + i*x_pixdim, i=0..x_dim-1
  204. % y(j) = y_start + j*y_pixdim, j=0..y_dim-1
  205. % z(k) = z_start + k*z_pixdim, k=0..z_dim-1
  206. %
  207. % This can be done by a simple fliplr operation on all of the CT slices
  208. % define the coordinate system
  209. x = x_start:x_pixdim:x_start + (x_dim-1)*x_pixdim;
  210. y = y_start:y_pixdim:y_start + (y_dim-1)*y_pixdim;
  211. z = z_start:z_pixdim:z_start + (z_dim-1)*z_pixdim;
  212. % define the locations of the corners of the pixels in each slice
  213. xCorners = [x - x_pixdim/2 x(end) + x_pixdim/2];
  214. yCorners = [y - y_pixdim/2 y(end) + y_pixdim/2];
  215. % loop through all rois
  216. for roi_num=1:length(ROIS)
  217. % set up the roi mask
  218. roimask = zeros(x_dim,y_dim,z_dim,'int8');
  219. roimaskCorners = zeros(x_dim+1,y_dim+1,z_dim,'int8');
  220. % loop through all of the curves in the roi
  221. for curve_num=1:length(ROIS{roi_num}.curves)
  222. % make a copy of the curve for easy access
  223. current_curve = ROIS{roi_num}.curves{curve_num};
  224. % find the z-index (slice number) of this curve
  225. q = round((current_curve(1,3)-z_start)/z_pixdim) + 1;
  226. % put these index vectors into roipoly
  227. if q >= 1 & q <= z_dim
  228. roisliceCorners = double(roimaskCorners(:,:,q));
  229. % find which corners are inside the contour
  230. BWcorners = roipoly(yCorners,xCorners,roisliceCorners,current_curve(:,2),current_curve(:,1));
  231. % Mark all all pixels bordering corners that are inside the
  232. % contour
  233. roi_vox = sum(BWcorners(:)); % number of voxels in this ROI
  234. % find the voxel overlap between the current roi and BW:
  235. overlap_vox = sum(sum(BWcorners.*roisliceCorners));
  236. if overlap_vox == roi_vox
  237. roisliceCorners = roisliceCorners - BWcorners;
  238. else % if there is not perfect overlap, add the rois
  239. roisliceCorners = roisliceCorners + BWcorners;
  240. end
  241. roisliceCorners(roisliceCorners > 0) = 1; % make sure all mask values are unity
  242. roimaskCorners(:,:,q) = int8(roisliceCorners); % update the overall mask
  243. end
  244. end
  245. % save time be resampling only a subregion
  246. ind = find(roimaskCorners);
  247. [I,J,K] = ind2sub([x_dim+1 y_dim+1 z_dim],ind);
  248. indx = min(I)-3:max(I)+3;
  249. indy = min(J)-3:max(J)+3;
  250. indz = min(K)-3:max(K)+3;
  251. indx = indx(indx >= 1 & indx <= x_dim);
  252. indy = indy(indy >= 1 & indy <= y_dim);
  253. indz = indz(indz >= 1 & indz <= z_dim);
  254. % convert the corners to a 3-D roi mask
  255. roimask(indx,indy,indz) = ceil(gridResample3D(xCorners,yCorners,z,roimaskCorners,x(indx),y(indy),z(indz)));
  256. % save the indices of the roi mask
  257. ROIS{roi_num}.ind = int32(find(roimask ~= 0));
  258. ROIS{roi_num}.dim = [x_dim y_dim z_dim];
  259. ROIS{roi_num}.pixdim = [x_pixdim y_pixdim z_pixdim];
  260. ROIS{roi_num}.start = [x_start y_start z_start];
  261. ROIS{roi_num}.start_ind = start_ind;
  262. fprintf('Converted %s vectors to an roi mask.\n',ROIS{roi_num}.name);
  263. end
  264. % save ROIS to the Geometry structure
  265. Geometry.ROIS = ROIS;
  266. clear ROIS;
  267. end
  268. if strcmp(readTrial,'yes')
  269. % read in the Trial information
  270. fid_trialfile = fopen(trialfile,'r');
  271. tline = fgets(fid_trialfile);
  272. structstack = {}; % stack for determining which field we're inside
  273. structind = []; % structure index values for each field
  274. lines = 1;
  275. while tline ~= -1 % read through the trial file
  276. tline = regexprep(tline,'"',''''); % replace " with '
  277. tline = regexprep(tline,'[',''); % bad characters to remove
  278. tline = regexprep(tline,']',''); % bad characters to remove
  279. tline = regexprep(tline,'#','num');
  280. tline = regexprep(tline,'\\','''');
  281. % fprintf(tline);
  282. if length(findstr(tline,'{'))
  283. % mark the structure we just entered, removing any blank space
  284. structstack{length(structstack) + 1} = regexprep(strtok(tline,'='),' ','');
  285. if length(structstack) == 1
  286. structstack{1} = 'Trial'; % make sure structure name is always the same
  287. end
  288. if strcmp(structstack{end},'Beam') % found a beam structure
  289. % find the number of existing beams at this location
  290. eval_line = ['beams = getfield(' structstack{1}];
  291. for k=2:length(structstack)
  292. eval_line = [eval_line ',''' structstack{k} ''''];
  293. end
  294. eval_line = [eval_line ');'];
  295. try
  296. eval(eval_line);
  297. num_beams = length(beams) + 1; % this is the current beam number
  298. catch % there was an error, so there are no beams yet
  299. num_beams = 1; % we're on the first beam now
  300. end
  301. end
  302. elseif length(findstr(tline,'}'))
  303. structstack(end) = []; % step outside of the current field
  304. else % the line must be a subfield assignment
  305. if strcmp(structstack{end},'Points') % this case treated specially
  306. % read-in values until the next '}' is reached
  307. lines = lines + 1;
  308. mlc_vec = ['['];
  309. while ~length(findstr(tline,'}'))
  310. % build up the vector of MLC positions
  311. mlc_vec = [mlc_vec regexprep(tline,' ','')];
  312. tline = fgets(fid_trialfile);
  313. % fprintf(tline);
  314. lines = lines + 1;
  315. end
  316. mlc_vec = [mlc_vec ']'];
  317. % evaluate the points vector
  318. eval_statement = structstack{1};
  319. for k=2:length(structstack)
  320. if strcmp(structstack{k},'Beam')
  321. % include the beam number
  322. eval_statement = [eval_statement '.' structstack{k} '(' num2str(num_beams) ')'];
  323. else % non-beam structure, so don't worry about it
  324. eval_statement = [eval_statement '.' structstack{k}];
  325. end
  326. end
  327. eval_statement = [eval_statement ' = ' mlc_vec ';'];
  328. eval(eval_statement);
  329. structstack(end) = []; % step outside of the current Points[] field
  330. else
  331. % see if there are any subfields in the expression
  332. % evaluate the statement
  333. eval_statement = structstack{1};
  334. for k=2:length(structstack)
  335. if strcmp(structstack{k},'Beam')
  336. % include the beam number
  337. eval_statement = [eval_statement '.' structstack{k} '(' num2str(num_beams) ')'];
  338. else % non-beam structure, so don't worry about it
  339. eval_statement = [eval_statement '.' structstack{k}];
  340. end
  341. end
  342. eval_statement = [eval_statement '.' tline];
  343. eval(eval_statement);
  344. end
  345. end
  346. tline = fgets(fid_trialfile);
  347. lines = lines + 1;
  348. if isempty(structstack)
  349. break; % we're done if we're no longer inside any sets of curly brackets
  350. end
  351. end
  352. fclose(fid_trialfile);
  353. % dose grid dimensions
  354. xdim = Trial.DoseGrid.Dimension.X;
  355. ydim = Trial.DoseGrid.Dimension.Y;
  356. zdim = Trial.DoseGrid.Dimension.Z;
  357. siz = [xdim ydim zdim]; % dosegrid size vector
  358. % vector describing the start location of the dose grids
  359. xstart = Trial.DoseGrid.Origin.X;
  360. ystart = Trial.DoseGrid.Origin.Y;
  361. zstart = Trial.DoseGrid.Origin.Z;
  362. start = [xstart ystart zstart]; % dosegrid start vector
  363. % vector describing the size of each voxel
  364. dx = Trial.DoseGrid.VoxelSize.X;
  365. dy = Trial.DoseGrid.VoxelSize.Y;
  366. dz = Trial.DoseGrid.VoxelSize.Z;
  367. voxel_size = [dx dy dz];
  368. % Read in the beamlet dose distributions, DRRs, and fluences and store them in
  369. % Trial.BeamList.Beam(k), where k is the beam number
  370. for k=0:num_beams-1
  371. % read-in the dose distribution
  372. num_vec = num2str(k*5+4);
  373. % ensure that num_vec has a length of 3
  374. while length(num_vec) < 3
  375. num_vec = ['0' num_vec];
  376. end
  377. dose_file = [dose_file_base_name '.' num_vec];
  378. fid = fopen(dose_file,'rb','ieee-be');
  379. if fid ~= -1
  380. dose = fread(fid,'float=>float');
  381. fclose(fid);
  382. try
  383. dose = reshape(dose,siz);
  384. % flip the dose distribution in accordance with the CT image
  385. for j=1:siz(3)
  386. dose(:,:,j) = single(fliplr(double(dose(:,:,j))));
  387. end
  388. % save the dose
  389. Trial = setfield(Trial,'BeamList','Beam',{k+1},'dose',dose);
  390. catch
  391. fprintf('Dose for beam %g did not meet specifications so it was not read-in.\n',k+1);
  392. end
  393. end
  394. % read-in the DRR
  395. % find the size of this drr
  396. drr_x = Trial.BeamList.Beam(1).FilmImageList.FilmImage.Image.Dimension.X;
  397. drr_y = Trial.BeamList.Beam(1).FilmImageList.FilmImage.Image.Dimension.Y;
  398. siz_drr = [drr_x drr_y];
  399. num_vec = num2str(k*5+3);
  400. % ensure that num_vec has a length of 3
  401. while length(num_vec) < 3
  402. num_vec = ['0' num_vec];
  403. end
  404. drr_file = [dose_file_base_name '.' num_vec];
  405. fid = fopen(drr_file,'rb','ieee-be');
  406. if fid ~= -1
  407. drr = fread(fid,'float');
  408. fclose(fid);
  409. try % proceed only if the drr was read-in properly
  410. drr = reshape(drr,siz_drr);
  411. % save the DRR
  412. Trial = setfield(Trial,'BeamList','Beam',{k+1},'FilmImageList','FilmImage','Image','drr',drr);
  413. catch
  414. fprintf('DRR for beam %g did not meet specifications so it was not read-in.\n',k+1);
  415. end
  416. end
  417. % read in the fluence map
  418. num_vec = num2str(k*5+2);
  419. fluence_siz = [101 101 3]; % all fluence must have this size otherwise and error will be thrown
  420. % ensure that num_vec has a length of 3
  421. while length(num_vec) < 3
  422. num_vec = ['0' num_vec];
  423. end
  424. fluence_file = [dose_file_base_name '.' num_vec];
  425. fid = fopen(fluence_file,'rb','ieee-be');
  426. if fid ~= -1
  427. fluence = fread(fid,'float');
  428. fclose(fid);
  429. % check to see if fluence matches dose grid size
  430. if Trial.FluenceGridMatchesDoseGrid ~= 1
  431. error('Fluence grid does not match dose grid for beam %g, don''t know what to do here.',k+1);
  432. end
  433. try % proceed only if the fluence is read-in properly
  434. fluence = reshape(fluence,fluence_siz);
  435. % save the fluence
  436. Trial = setfield(Trial,'BeamList','Beam',{k+1},'FluenceMap',fluence);
  437. catch
  438. fprintf('Fluence map for beam %g did not meet specifications so it was not read-in.\n',k+1);
  439. end
  440. end
  441. end
  442. % add up all of the doses
  443. dose_tot = zeros(siz);
  444. for k=1:num_beams
  445. if isfield(Trial.BeamList.Beam(k),'dose') & ~isempty(Trial.BeamList.Beam(k).dose)
  446. dose_tot = dose_tot + double(Trial.BeamList.Beam(k).dose);
  447. end
  448. end
  449. Geometry.Trial = Trial;
  450. clear Trial;
  451. end
  452. save(save_file,'Geometry');