├── .gitignore
├── 3rd_party
├── div_op.m
├── div_op3d.m
├── gradient_op.m
├── gradient_op3d.m
├── norm_tv.m
├── norm_tv3d.m
├── prox_tv3d_nn.m
├── prox_tv_nn.m
└── test_gamma.m
├── COPYING
├── README.md
├── data
├── attenuationDb.mat
├── data_cbct_head.mat
├── data_cbct_pelvis.mat
├── fandata.mat
├── scat_param.mat
└── scatter_est_head.mat
├── demo_polyquant_cbct.m
├── demo_polyquant_fanbeam.m
├── demo_polyquant_scatter.m
├── gpl-3.0.txt
├── polyquant.m
└── utilities
├── bit_rev.m
├── ell_centroid.m
├── mat_to_den.m
├── poly_sks.m
└── pw_knee_fit.m
/.gitignore:
--------------------------------------------------------------------------------
1 | *.mat
2 | *.m~
3 | !fandata.mat
4 | !attenuationDb.mat
5 | !scat_param.mat
6 | !data_cbct_pelvis.mat
7 | !data_cbct_head.mat
8 | !scatter_est_head.mat
9 | pathdef.m
10 |
--------------------------------------------------------------------------------
/3rd_party/div_op.m:
--------------------------------------------------------------------------------
1 | function I = div_op(dx, dy, wx, wy)
2 | %DIV_OP Divergence operator in 2 dimensions
3 | % Usage: I = div_op(dx, dy)
4 | % I = div_op(dx, dy, wx, wy)
5 | %
6 | % Input parameters:
7 | % dx : Gradient along x
8 | % dy : Gradient along y
9 | % wx : Weights along x
10 | % wy : Weights along y
11 | %
12 | % Output parameters:
13 | % I : Output divergence image
14 | %
15 | % Compute the 2-dimensional divergence of an image. If a cube is given,
16 | % it will compute the divergence of all images in the cube.
17 | %
18 | % Warning: computes the divergence operator defined as minus the adjoint
19 | % of the gradient
20 | %
21 | % .. div = - grad'
22 | %
23 | % .. math:: \text{div} = - \nabla^*
24 | %
25 | % See also: gradient_op div_op3d div_op1d laplacian_op prox_tv
26 |
27 | % Author: Nathanael Perraudin
28 | % Date: 1 February 2014
29 |
30 | if nargin > 2
31 | dx = dx .* conj(wx);
32 | dy = dy .* conj(wy);
33 | end
34 |
35 | I = [dx(1, :,:) ; ...
36 | dx(2:end-1, :,:)-dx(1:end-2, :,:) ;...
37 | -dx(end-1, :,:)];
38 | I = I + [dy(:, 1,:) ,...
39 | dy(:, 2:end-1,:)-dy(:, 1:end-2,:) ,...
40 | -dy(:, end-1,:)];
41 |
42 | end
43 |
--------------------------------------------------------------------------------
/3rd_party/div_op3d.m:
--------------------------------------------------------------------------------
1 | function I = div_op3d(dx, dy, dz, wx, wy, wz)
2 | %DIV_OP3D Divergence operator in 3 dimentions
3 | % Usage: I = div_op3d(dx, dy, dz)
4 | % I = div_op3d(dx, dy, dz, wx, wy, wz)
5 | %
6 | % Input parameters:
7 | % dx : Gradient along x
8 | % dy : Gradient along y
9 | % dz : Gradient along z
10 | % wx : Weights along x
11 | % wy : Weights along y
12 | % wz : Weights along z
13 | %
14 | % Output parameters:
15 | % I : Output image
16 | %
17 | % Compute the 3-dimentional divergence of a 3D-image. If a 4 dimentional
18 | % signal is given, it will compute the divergence of all cubes in the
19 | % 4 diementionals signal.
20 | %
21 | % Warning this function compute the divergence operator defined as minus
22 | % the adjoint of the gradient
23 | %
24 | % .. div = - grad'
25 | %
26 | % .. math:: \text{div} = - \nabla^*
27 | %
28 | % See also: gradient_op div_op div_op1d laplacian_op
29 |
30 | % Author: Nathanael Perraudin
31 | % Date: 1 February 2014
32 |
33 | if nargin > 3
34 | dx = dx .* conj(wx);
35 | dy = dy .* conj(wy);
36 | dz = dz .* conj(wz);
37 | end
38 |
39 | I = [dx(1, :, :,:) ; dx(2:end-1, :, :,:) - ...
40 | dx(1:end-2, :, :,:) ; -dx(end-1, :, :,:)];
41 | I = I + [dy(:, 1, :,:) , dy(:, 2:end-1, :,:) - ...
42 | dy(:, 1:end-2, :,:) , -dy(:, end-1, :,:)];
43 | I = I + cat(3, dz(:, :, 1,:) , dz(:, :, 2:end-1,:) - ...
44 | dz(:, :, 1:end-2,:) , -dz(:, :, end-1,:));
45 | end
46 |
--------------------------------------------------------------------------------
/3rd_party/gradient_op.m:
--------------------------------------------------------------------------------
1 | function [dx, dy] = gradient_op(I, wx, wy)
2 | %GRADIENT_OP 2 Dimensional gradient operator
3 | % Usage: [dx, dy] = gradient_op(I)
4 | % [dx, dy] = gradient_op(I, wx, wy)
5 | %
6 | % Input parameters:
7 | % I : Input data
8 | % wx : Weights along x
9 | % wy : Weights along y
10 | %
11 | % Output parameters:
12 | % dx : Gradient along x
13 | % dy : Gradient along y
14 | %
15 | % Compute the 2-dimensional gradient of I. If the input I is a cube. This
16 | % function will compute the gradient of all image and return two cubes.
17 | %
18 | % See also: gradient_op3d gradient_op1d div_op laplacian_op
19 |
20 | % Author: Nathanael Perraudin
21 | % Date: 1 February 2014
22 |
23 | dx = [I(2:end, :,:)-I(1:end-1, :,:) ; zeros(1, size(I, 2),size(I, 3))];
24 | dy = [I(:, 2:end,:)-I(:, 1:end-1,:) , zeros(size(I, 1), 1,size(I, 3))];
25 |
26 | if nargin>1
27 | dx = dx .* wx;
28 | dy = dy .* wy;
29 | end
30 |
31 | end
32 |
--------------------------------------------------------------------------------
/3rd_party/gradient_op3d.m:
--------------------------------------------------------------------------------
1 | function [dx, dy, dz] = gradient_op3d(I, wx, wy, wz)
2 | %GRADIENT_OP3D 3 Dimentional gradient operator
3 | % Usage: [dx, dy, dz] = gradient_op3d(I)
4 | % [dx, dy, dz] = gradient_op3d(I, wx, wy, wz)
5 | %
6 | % Input parameters:
7 | % I : Input data
8 | % wx : Weights along x
9 | % wy : Weights along y
10 | % wz : Weights along z
11 | %
12 | % Output parameters:
13 | % dx : Gradient along x
14 | % dy : Gradient along y
15 | % dz : Gradient along z
16 | %
17 | % Compute the 3-dimentional gradient of I. If the input I has 4
18 | % dimentions. This function will compute the gradient of all cubes and
19 | % return 3 4-dimentionals signals
20 | %
21 | % See also: gradient_op gradient_op1d div_op laplacian_op
22 |
23 | % Author: Nathanael Perraudin
24 | % Date: 1 February 2014
25 |
26 | dx = [I(2:end, :, :,:)-I(1:end-1, :, :,:) ;...
27 | zeros(1, size(I, 2), size(I, 3),size(I, 4))];
28 | dy = [I(:, 2:end, :,:)-I(:, 1:end-1, :,:) , ...
29 | zeros(size(I, 1), 1, size(I, 3),size(I, 4))];
30 | dz = cat(3, I(:, :, 2:end,:)-I(:, :, 1:end-1,:) , ...
31 | zeros(size(I, 1),size(I, 2), 1,size(I, 4)));
32 |
33 | if nargin>1
34 | dx = dx .* wx;
35 | dy = dy .* wy;
36 | dz = dz .* wz;
37 | end
38 |
39 | end
40 |
--------------------------------------------------------------------------------
/3rd_party/norm_tv.m:
--------------------------------------------------------------------------------
1 | function y = norm_tv(I,wx,wy)
2 | %NORM_TV 2 Dimentional TV norm
3 | % Usage: y = norm_tv(x);
4 | % y = norm_tv(I,wx,wy);
5 | %
6 | % Input parameters:
7 | % I : Input data
8 | % wx : Weights along x
9 | % wy : Weights along y
10 | % Output parameters:
11 | % y : Norm
12 | %
13 | % Compute the 2-dimentional TV norm of I. If the input I is a cube. This
14 | % function will compute the norm of all image and return a vector of
15 | % norms.
16 | %
17 | % See also: norm_tv3d norm_tvnd
18 |
19 | % Author: Nathanael Perraudin
20 | % Date: 1 February 2014
21 |
22 | if nargin>1
23 | [dx, dy] = gradient_op(I,wx, wy);
24 | else
25 | [dx, dy] = gradient_op(I);
26 | end
27 | temp = sqrt(abs(dx).^2 + abs(dy).^2);
28 |
29 | %y = sum(temp(:));
30 | y = reshape(sum(sum(temp,1),2),[],1);
31 |
32 | end
33 |
--------------------------------------------------------------------------------
/3rd_party/norm_tv3d.m:
--------------------------------------------------------------------------------
1 | function y = norm_tv3d(u,wx, wy, wz)
2 | %NORM_TV3D 3 Dimentional TV norm
3 | % Usage: y = norm_tv3d(x)
4 | % y = norm_tv3d(x, wx, wy, wz )
5 | %
6 | % Input parameters:
7 | % x : Input data (3 dimentional matrix)
8 | % wx : Weights along x
9 | % wy : Weights along y
10 | % wz : Weights along z
11 | %
12 | % Output parameters:
13 | % y : Norm
14 | %
15 | % Compute the 3-dimentional TV norm of x. If the input I is a 4
16 | % dimentional signal. This function will compute the norm of all cubes
17 | % and return a vector of norms.
18 | %
19 | % See also: norm_tv norm_tvnd
20 |
21 | % Author: Nathanael Perraudin
22 | % Date: 1 February 2014
23 |
24 | if nargin>1
25 | [dx, dy, dz] = gradient_op3d(u,wx, wy, wz);
26 | else
27 | [dx, dy, dz] = gradient_op3d(u);
28 | end
29 |
30 | temp = sqrt(abs(dx).^2 + abs(dy).^2 + abs(dz).^2);
31 | % y = sum(temp(:));
32 |
33 | % This allows to return a vector of norms
34 | y = reshape(sum(sum(sum(temp,1),2),3),[],1);
35 |
36 |
37 | end
38 |
--------------------------------------------------------------------------------
/3rd_party/prox_tv3d_nn.m:
--------------------------------------------------------------------------------
1 | function [sol,info] = prox_tv3d_nn(x, gamma, param)
2 | %PROX_TV3D Total variation proximal operator
3 | % Usage: sol=prox_tv3d(x, gamma)
4 | % sol=prox_tv3d(x, gamma,param)
5 | % [sol, info]=prox_tv3d(...)
6 | %
7 | % Input parameters:
8 | % x : Input signal.
9 | % gamma : Regularization parameter.
10 | % param : Structure of optional parameters.
11 | % Output parameters:
12 | % sol : Solution.
13 | % info : Structure summarizing informations at convergence
14 | %
15 | % This function compute the 3 dimentional TV proximal operator evaluated
16 | % in b. If b is 4 dimentional, this function will evaluate the TV
17 | % proximal operator on each cube. For 2 dimention TV proximal of cubes
18 | % operator the function prox_tv can be used.
19 | %
20 | % `prox_tv3d(y, gamma, param)` solves:
21 | %
22 | % .. sol = argmin_{z} 0.5*||x - z||_2^2 + gamma * ||x||_TV
23 | %
24 | % .. math:: sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \|x\|_{TV}
25 | %
26 | % param is a Matlab structure containing the following fields:
27 | %
28 | % * *param.tol* : is stop criterion for the loop. The algorithm stops if
29 | %
30 | % .. ( n(t) - n(t-1) ) / n(t) < tol,
31 | %
32 | % .. math:: \frac{ n(t) - n(t-1) }{ n(t)} < tol,
33 | %
34 | % where $n(t) = f(x)+ 0.5 \|x-z\|_2^2$ is the objective function at iteration *t*
35 | % by default, `tol=10e-4`.
36 | %
37 | % * *param.maxit* : max. nb. of iterations (default: 200).
38 | %
39 | % * *param.parrallel* : Parallelisation level. 0 means no
40 | % parallelization, 1 means all cubes (fourth dimension changing) at the
41 | % same time.
42 | %
43 | % * *param.verbose* : 0 no log, 1 a summary at convergence, 2 print main
44 | % steps (default: 1)
45 | %
46 | % * *param.useGPU* : Use GPU to compute the TV prox operator. Please prior
47 | % call init_gpu and free_gpu to launch and release the GPU library (default: 0).
48 | %
49 | % * *param.weights* : weights for each dimention (default $[1, 1, 1]$)
50 | %
51 | % * *param.up* : upper limit for box constraints (default: inf)
52 | %
53 | % infos is a Matlab structure containing the following fields:
54 | %
55 | % * *info.algo* : Algorithm used
56 | %
57 | % * *info.iter* : Number of iteration
58 | %
59 | % * *info.time* : Time of exectution of the function in sec.
60 | %
61 | % * *info.final_eval* : Final evaluation of the function
62 | %
63 | % * *info.crit* : Stopping critterion used
64 | %
65 | %
66 | % See also: prox_l1 prox_tv
67 | %
68 | % References: beck2009fastTV
69 |
70 |
71 | % Author: Nathanael Perraudin, William Guicquero
72 | % Date: October 15, 2010
73 | % Modified: Jonathan H Mason, 2017
74 | % - included non-negativity and optional box constraint
75 | %
76 |
77 | % Start the time counter
78 | t1 = tic;
79 |
80 | % for the GPU
81 |
82 | % Optional input arguments
83 | if nargin<3, param=struct; end
84 |
85 | if ~isfield(param, 'tol'), param.tol = 10e-4; end
86 | if ~isfield(param, 'verbose'), param.verbose = 0; end
87 | if ~isfield(param, 'maxit'), param.maxit = 5; end
88 | if ~isfield(param, 'up'), param.up = inf; end
89 | if ~isfield(param, 'useGPU')
90 | param.useGPU = (isa(x,'gpuArray'));
91 | end
92 | if ~isfield(param, 'weights'), param.weights = [1,1,1]; end
93 |
94 |
95 | if ~isfield(param, 'parallel')
96 | if size(x,4)==1
97 | param.parallel = 1;
98 | else
99 | param.parallel = 0;
100 | end
101 | end
102 |
103 |
104 |
105 | if param.parallel == 0
106 | % call prox 3d for each cube
107 | param.parallel = 1;
108 | sol = zeros(size(x));
109 | info.iter = 0;
110 | info.time = 0;
111 | info.algo=mfilename;
112 | info.final_eval = 0;
113 | info.crit = 'TOL_EPS'; % return this only if ALL subproblems finish with this criterion.
114 | param.verbose = param.verbose-1; % Handle verbosity
115 |
116 | for ii = 1:size(x, 4)
117 | [sol(:, :, :, ii), infos_ii] = prox_tv3d(x(:,:,:,ii), gamma, param);
118 | info.iter = info.iter + infos_ii.iter;
119 | info.time = info.time + infos_ii.time;
120 | info.final_eval = info.final_eval + infos_ii.final_eval;
121 |
122 | if strcmpi(infos_ii.crit, 'MAX_IT');
123 | info.crit = 'MAX_IT'; % if ANY subproblem reaches maximum iterations, return this as criterion!
124 | end
125 | end
126 |
127 | return
128 |
129 | end
130 |
131 | % If once parfor is working generally on MATLAB
132 | % if strcmpi(param.parallel, 'parfor')
133 | % % recall prox 3d for each cube
134 | % param.parallel = 'full';
135 | % sol = zeros(size(x));
136 | %
137 | % parfor ii = 1:size(x,4)
138 | % sol(:,:,:,ii) = prox_tv3d(x(:,:,:,ii), gamma, param);
139 | % end
140 | %
141 | % return
142 | %
143 | % end
144 |
145 |
146 | % Test of gamma
147 | if test_gamma(gamma)
148 | sol = x;
149 | info.algo=mfilename;
150 | info.iter=0;
151 | info.final_eval=0;
152 | info.crit='--';
153 | info.time=toc(t1);
154 | return;
155 | end
156 |
157 |
158 | wx = param.weights(1);
159 | wy = param.weights(2);
160 | wz = param.weights(3);
161 | mt = max(param.weights);
162 |
163 | % Initializations
164 | if param.useGPU
165 | %gpuDevice(1);
166 | gamma=gpuArray(gamma);
167 | if isa(x,'gpuArray')
168 | allGPU=1;
169 | else
170 | x=gpuArray(x);
171 | allGPU=0;
172 | end
173 | % Initializations
174 | [r, s, k] = gradient_op3d(x*0);
175 | pold = r; qold = s; kold = k;
176 | told = gpuArray(1); prev_obj = gpuArray(0);
177 | verbose=gpuArray(param.verbose);
178 | tol=gpuArray(param.tol);
179 | else
180 | [r, s, k] = gradient_op3d(x*0);
181 | pold = r; qold = s; kold = k;
182 | told = 1; prev_obj = 0;
183 | verbose=param.verbose;
184 | tol=param.tol;
185 | end
186 |
187 | % Main iterations
188 | if verbose > 1
189 | if param.useGPU
190 | fprintf(' Proximal TV operator using TV:\n');
191 | else
192 | fprintf(' Proximal TV operator:\n');
193 | end
194 | end
195 |
196 |
197 | for iter = 1:param.maxit
198 |
199 | % Current solution
200 | sol = projC(x - gamma * div_op3d(r, s, k,wx,wy,wz),param.up);
201 |
202 | % Objective function value
203 | obj = .5*norm(x(:)-sol(:), 2)^2 + gamma * sum(norm_tv3d(sol,wx,wy,wz));
204 | rel_obj = abs(obj-prev_obj)/obj;
205 | prev_obj = obj;
206 |
207 | % Stopping criterion
208 | if verbose>1
209 | fprintf(' Iter %i, obj = %e, rel_obj = %e\n', ...
210 | iter, obj, rel_obj);
211 | end
212 | if rel_obj < tol
213 | crit = 'TOL_EPS'; break;
214 | end
215 |
216 | % Udpate divergence vectors and project
217 | % TODO: read reference for good explanation... We change lemma 4.2 to
218 | % be valid for 3D denoising and we should get a bound with 12 instead
219 | % of 8.
220 | [dx, dy, dz] = gradient_op3d(sol,wx,wy,wz);
221 | r = r - 1/(12*gamma*mt^2) * dx;
222 | s = s - 1/(12*gamma*mt^2) * dy;
223 | k = k - 1/(12*gamma*mt^2) * dz;
224 | % Isotropic tv
225 | weights = max(1, sqrt(abs(r).^2+abs(s).^2+abs(k).^2));
226 | % anisotropic TV
227 | %weights = max(1, abs(r)+abs(s)+abs(k));
228 | p = r./weights;
229 | q = s./weights;
230 | o = k./weights;
231 |
232 |
233 | % FISTA update
234 | t = (1+sqrt(4*told^2))/2;
235 | r = p + (told-1)/t * (p - pold); pold = p;
236 | s = q + (told-1)/t * (q - qold); qold = q;
237 | k = o + (told-1)/t * (o - kold); kold = o;
238 | told = t;
239 |
240 | end
241 |
242 | % Log after the minimization
243 | if ~exist('crit', 'var'), crit = 'MAX_IT'; end
244 |
245 |
246 |
247 | if verbose >= 1
248 | if param.useGPU
249 | fprintf([' GPU Prox_TV 3D: obj = %e, rel_obj = %e,' ...
250 | ' %s, iter = %i\n'], obj, rel_obj, crit, iter);
251 | else
252 | fprintf([' Prox_TV 3D: obj = %e, rel_obj = %e,' ...
253 | ' %s, iter = %i\n'], obj, rel_obj, crit, iter);
254 | end
255 | end
256 |
257 |
258 |
259 | if param.useGPU
260 | if ~allGPU
261 | sol=gather(sol);
262 | end
263 | info.iter=gather(iter);
264 | info.final_eval=gather(obj);
265 | else
266 | info.iter=iter;
267 | info.final_eval=obj;
268 | end
269 |
270 | info.algo=mfilename;
271 | info.iter=iter;
272 | info.final_eval=obj;
273 | info.crit=crit;
274 | info.time=toc(t1);
275 |
276 | end
277 |
278 | function out = projC(in,up)
279 | in(in<0) = 0;
280 | in(in>up) = up;
281 | out = in;
282 | end
--------------------------------------------------------------------------------
/3rd_party/prox_tv_nn.m:
--------------------------------------------------------------------------------
1 | function [sol, info] = prox_tv_nn(b, gamma, param)
2 | %PROX_TV Total variation proximal operator
3 | % Usage: sol=prox_tv(x, gamma)
4 | % sol=prox_tv(x, gamma,param)
5 | % [sol, info]=prox_tv(...)
6 | %
7 | % Input parameters:
8 | % x : Input signal.
9 | % gamma : Regularization parameter.
10 | % param : Structure of optional parameters.
11 | % Output parameters
12 | % sol : Solution.
13 | % info : Structure summarizing informations at convergence
14 | %
15 | % This function compute the 2 dimentional TV proximal operator evaluated
16 | % in b. If b is a cube, this function will evaluate the TV proximal
17 | % operator on each image of the cube. For 3 dimention TV proximal
18 | % operator the function prox_tv3d can be used.
19 | %
20 | % `prox_tv(y, gamma, param)` solves:
21 | %
22 | % .. sol = argmin_{z} 0.5*||x - z||_2^2 + gamma * ||z||_TV
23 | %
24 | % .. math:: sol = arg\min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \|z\|_{TV}
25 | %
26 | % param is a Matlab structure containing the following fields:
27 | %
28 | % * *param.tol* : is stop criterion for the loop. The algorithm stops if
29 | %
30 | % .. ( n(t) - n(t-1) ) / n(t) < tol,
31 | %
32 | % .. math:: \frac{ n(t) - n(t-1) }{ n(t)} < tol,
33 | %
34 | % where $n(t) = f(x)+ 0.5 \|x-z\|_2^2$ is the objective function at iteration *t*
35 | % by default, `tol=10e-4`.
36 | %
37 | % * *param.maxit* : max. nb. of iterations (default: 200).
38 | %
39 | % * *param.useGPU* : Use GPU to compute the TV prox operator. Please prior
40 | % call init_gpu and free_gpu to launch and release the GPU library (default: 0).
41 | %
42 | % * *param.verbose* : 0 no log, 1 a summary at convergence, 2 print main
43 | % steps (default: 1)
44 | %
45 | % * *param.weights* : weights for each dimention (default $[1, 1]$)
46 | %
47 | % * *param.up* : upper limit for box constraints (default: inf)
48 | %
49 | % info is a Matlab structure containing the following fields:
50 | %
51 | % * *info.algo* : Algorithm used
52 | %
53 | % * *info.iter* : Number of iteration
54 | %
55 | % * *info.time* : Time of exectution of the function in sec.
56 | %
57 | % * *info.final_eval* : Final evaluation of the function
58 | %
59 | % * *info.crit* : Stopping critterion used
60 | %
61 | % See also: prox_l1 prox_tv3d prox_tv1d gradient_op div_op
62 | %
63 | %
64 | % References: beck2009fastTV
65 |
66 |
67 | % Author: Nathanael Perraudin, Gilles Puy, Eyal Hirsch
68 | % Date: Jan 2013
69 | % Modified: Jonathan H Mason, 2017
70 | % - included non-negativity and optional box constraint
71 | %
72 |
73 | % Start the time counter
74 | t1 = tic;
75 |
76 | % for the GPU
77 | global GLOBAL_useGPU;
78 |
79 | if ~size(GLOBAL_useGPU,1), GLOBAL_useGPU = 0; end
80 |
81 | % Optional input arguments
82 |
83 | if nargin<3, param=struct; end
84 |
85 | if ~isfield(param, 'tol'), param.tol = 10e-4; end
86 | if ~isfield(param, 'verbose'), param.verbose = 0; end
87 | if ~isfield(param, 'maxit'), param.maxit = 20; end
88 | if ~isfield(param, 'weights'), param.weights = [1, 1]; end
89 | if ~isfield(param, 'up'), param.up = inf; end
90 | if ~isfield(param, 'useGPU')
91 | param.useGPU = (GLOBAL_useGPU) || (isa(b,'gpuArray'));
92 | end
93 |
94 | % Test of gamma
95 | if test_gamma(gamma)
96 | sol = b;
97 | info.algo=mfilename;
98 | info.iter=0;
99 | info.final_eval=0;
100 | info.crit='--';
101 | info.time=toc(t1);
102 | return;
103 | end
104 |
105 | if param.useGPU
106 | %gpuDevice(1);
107 | gamma=gpuArray(gamma);
108 | if isa(b,'gpuArray')
109 | allGPU=1;
110 | else
111 | b=gpuArray(b);
112 | allGPU=0;
113 | end
114 | % Initializations
115 | [r, s] = gradient_op(b*0);
116 | pold = r; qold = s;
117 | told = gpuArray(1); prev_obj = gpuArray(0);
118 | verbose=gpuArray(param.verbose);
119 | tol=gpuArray(param.tol);
120 | else
121 | % Initializations
122 | [r, s] = gradient_op(b*0);
123 | pold = r; qold = s;
124 | told = 1; prev_obj = 0;
125 | verbose=param.verbose;
126 | tol=param.tol;
127 | end
128 |
129 |
130 | wx = param.weights(1);
131 | wy = param.weights(2);
132 | mt = max(param.weights);
133 |
134 | % Main iterations
135 | if verbose > 1
136 | fprintf(' Proximal TV operator:\n');
137 | end
138 |
139 |
140 |
141 |
142 | for iter = 1:param.maxit
143 |
144 | % Current solution
145 | sol = projC(b - gamma*div_op(r, s, wx, wy),param.up);
146 |
147 | % Objective function value
148 | tmp = gamma * sum(norm_tv(sol, wx, wy));
149 | obj = .5*norm(b(:)-sol(:), 2)^2 + tmp;
150 | rel_obj = abs(obj-prev_obj)/obj;
151 | prev_obj = obj;
152 |
153 | % Stopping criterion
154 | if verbose>1
155 | fprintf(' Iter %i, obj = %e, rel_obj = %e\n', ...
156 | iter, obj, rel_obj);
157 | end
158 | if rel_obj < tol
159 | crit = 'TOL_EPS'; break;
160 | end
161 |
162 | % Udpate divergence vectors and project
163 | [dx, dy] = gradient_op(sol, wx, wy);
164 |
165 | r = r - 1/(8*gamma)/mt^2 * dx;
166 | s = s - 1/(8*gamma)/mt^2 * dy;
167 |
168 | weights = max(1, sqrt(abs(r).^2+abs(s).^2));
169 |
170 | p = r./weights;
171 | q = s./weights;
172 |
173 | % FISTA update
174 | t = (1+sqrt(4*told.^2))/2;
175 | r = p + (told-1)/t * (p - pold); pold = p;
176 | s = q + (told-1)/t * (q - qold); qold = q;
177 | told = t;
178 |
179 | end
180 |
181 |
182 | % Log after the minimization
183 | if ~exist('crit', 'var'), crit = 'MAX_IT'; end
184 |
185 | if verbose >= 1
186 | if param.useGPU
187 | fprintf([' GPU Prox_TV: obj = %e, rel_obj = %e,' ...
188 | ' %s, iter = %i\n'], obj, rel_obj, crit, iter);
189 | else
190 | fprintf([' Prox_TV: obj = %e, rel_obj = %e,' ...
191 | ' %s, iter = %i\n'], obj, rel_obj, crit, iter);
192 | end
193 | end
194 |
195 |
196 |
197 | if param.useGPU
198 | if ~allGPU
199 | sol=gather(sol);
200 | end
201 | info.iter=gather(iter);
202 | info.final_eval=gather(obj);
203 | else
204 | info.iter=iter;
205 | info.final_eval=obj;
206 | end
207 |
208 | info.algo=mfilename;
209 | info.crit=crit;
210 | info.final_eval = tmp;
211 | info.time=toc(t1);
212 |
213 | end
214 |
215 | function out = projC(in,up)
216 | in(in<0) = 0;
217 | in(in>up) = up;
218 | out = in;
219 | end
220 |
--------------------------------------------------------------------------------
/3rd_party/test_gamma.m:
--------------------------------------------------------------------------------
1 | function [ stop ]=test_gamma(gamma)
2 | %TEST_GAMMA test if gamma is correct
3 | % Usage: stop = test_gamma(gamma)
4 | % test_gamma(gamma)
5 | %
6 | % Input parameters:
7 | % gamma : number
8 | % Output parameters:
9 | % stop : boolean
10 | %
11 | % This function test is gamma is stricly positive
12 | %
13 | % If gamma is negativ, this function return an error. If gamma is zero
14 | % this function, set stop to 1.
15 | %
16 | %
17 |
18 | % Author: Nathanael Perraudin
19 | % Date: February 2012
20 | %
21 |
22 |
23 | if gamma<0
24 | error('gamma can not be negativ!');
25 | % elseif (gamma==0) && warning
26 | % gamma=gamma+eps;
27 | % fprintf(' WARNING!!! gamma is 0. We add eps to gamma to keep going...\n');
28 | % else
29 | % % gamma = gamma;
30 | end
31 |
32 | if gamma==0
33 | stop = 1;
34 | else
35 | stop = 0;
36 | end
37 |
38 | end
39 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | This software is licensed under the GPL 3.0, so any copies or derivatives of this code must also be licensed under GPL.
2 |
3 | For the exact terms of the GPL, see the file glp-3.0.txt
4 |
5 | If you would like portions of this code under a different license, please contact us at j.mason@ed.ac.uk
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Polyquant CT Reconstruction Toolbox
2 | This Matlab toolbox allows direct quantitative reconstruction from polyenergetic X-ray computed tomography (CT) measurements. We hope you find it useful and welcome any feedback or questions [j.mason@ed.ac.uk].
3 |
4 | ## Features
5 | - Allows quantitative reconstruction into **electron density**, mass density, proton stopping power, quasi-monoenergetic and more.
6 | - Iterative statistical reconstruction under Poisson noise.
7 | - Metal artefact compensation and correction.
8 | - Designed for use with [Michigan Image Reconstruction Toolbox](https://web.eecs.umich.edu/~fessler/code) operators: ensure the toolbox is in your path (by running its 'setup.m') before running these demos.
9 | - Non-negative total variation (TV) reguarisation in 2D and 3D, adapted from [UNLocBoX](https://epfl-lts2.github.io/unlocbox-html/).
10 | - Integrated polyenergetic scatter estimation and mitigation.
11 | - Accelerated ordered sub-sets algorithm with bit-reversal ordering.
12 |
13 | ## Demos
14 | We have included several demos to cover some of its functionality, including:
15 | - 2D fanbeam CT reconstruction of brain, head, chest, abdomen and pelvis regions.
16 | - 2D fanbeam CT metal artefact mitigation, from double titanium hip implants.
17 | - 3D cone-beam CT reconstruction of head and pelvis regions, under 'full-fan' and 'half-fan' scans respectively.
18 | - 3D cone-beam CT reconstruction with integrated polyenergetic scatter modelling (PolySKS).
19 |
20 | ## References
21 | These methods are presented in the following publications (please cite if using):
22 | - [Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739](https://doi.org/10.1088/1361-6560/aa9162)
23 | - [Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001](https://doi.org/10.1088/1361-6560/aae794)
24 |
25 | For more details, extensions and its use in radiotherapy, you can read the thesis:
26 | [Quantitative cone-beam computed tomography reconstruction for radiotherapy planning](http://hdl.handle.net/1842/33193 )
27 |
28 | ## Acknowledgements
29 | Thanks to Mike Davies, Bill Nailon and Alessandro Perelli for their collaboration and supervision during the development of this work. Another thanks to Alessandro for kindly reviewing this code.
30 |
--------------------------------------------------------------------------------
/data/attenuationDb.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/attenuationDb.mat
--------------------------------------------------------------------------------
/data/data_cbct_head.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/data_cbct_head.mat
--------------------------------------------------------------------------------
/data/data_cbct_pelvis.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/data_cbct_pelvis.mat
--------------------------------------------------------------------------------
/data/fandata.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/fandata.mat
--------------------------------------------------------------------------------
/data/scat_param.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/scat_param.mat
--------------------------------------------------------------------------------
/data/scatter_est_head.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cimentaur/polyquant/005be2b8765999d7fb1e0d7d3280ab2b06b6d206/data/scatter_est_head.mat
--------------------------------------------------------------------------------
/demo_polyquant_cbct.m:
--------------------------------------------------------------------------------
1 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 | % Cone-beam CT Polyquant demo
3 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 | % Description
5 | % ----------
6 | % This script demonstrates polyquant reconstruction for cone-beam CT, with
7 | % high levels of scatter. The data was generated using Gate without a
8 | % collimator. Please refer to 'demo_polyquant_fanbeam.m' for a description
9 | % of the variables, which are the same in this case, only with a different
10 | % spectrum (head.specData.spectrum).
11 | % In this demo, we are given a pre-calculated estimate of the scatter
12 | % (scatEst) generated from an fASKS-like approach.
13 | %
14 | % Things to try
15 | % ------------
16 | % o Substitute the scatter estimate (mode.scatFun) for the true scatter
17 | % (head.scat), to see the ultimate scatter estimate's performance.
18 | % o Remove the 'mode.scatFun' line to see the scatter artefacts.
19 | % o Adjust regularisation and convergence parameters an compare to fanbeam.
20 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
21 | % Created: 26/04/2019
22 | % Last edit: 31/05/2019
23 | % Jonathan Hugh Mason
24 | %
25 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | % References: (please cite if making use of this code or its methods)
27 | % Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739
28 | % Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001
29 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
30 | %% Load data
31 | load data/scatter_est_head
32 | load data/data_cbct_head
33 | addpath(genpath('.'));
34 | i0 = repmat(head.i0,1,1,160);
35 |
36 | %% Setup the geometry
37 | cg = ct_geom('fan', 'ns', 256, 'nt', 128, 'na', 160, ...
38 | 'orbit_start',-90, 'orbit',-360,...
39 | 'ds', 0.1552, 'dt', 0.2328, ...
40 | 'offset_s', 0, ...
41 | 'offset_t', 0.0, ...
42 | 'dsd', 150,'dod', 50, 'dfs', inf);
43 | ig = image_geom('nx', 99, 'ny', 137, 'nz', 70, 'dx', 0.1775,'dy',0.1775,'dz',0.484);
44 | A = Gcone(cg, ig, 'type', 'sf2', 'class', 'Fatrix');
45 |
46 | %% Polyquant setup and reconstruction
47 | mode = [];
48 | mode.useConst = true;
49 | mode.verbose = 2;
50 | mode.tau = 2;
51 | mode.nSplit = 32;
52 | mode.maxIter = 300;
53 | mode.scatFun = scatEst;
54 | lambda = 2; % can be optimised for better results
55 | mode.proxFun = @(z,t) prox_tv3d_nn(z,t*lambda);
56 | mode.regFun = @(z) norm_tv3d(z);
57 | out = polyquant(mode,head.specData,head.proj,i0,A,head.eden);
58 | fprintf('Reconstructed with PSNR = %.2f dB\n',20*log10(max(head.eden(:))./out.rmse(end)));
--------------------------------------------------------------------------------
/demo_polyquant_fanbeam.m:
--------------------------------------------------------------------------------
1 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 | % Fanbeam Polyquant demo
3 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 | % Description
5 | % ----------
6 | % This script demonstrates direct quantitative reconstruction into relative
7 | % electron density from polyenergetic X-ray CT measurements. There are 6
8 | % samples, including various anatomical sites from the ICRP 110 female
9 | % computational phantom, and one ('implant') with added double titanium
10 | % hips.
11 | % The measurements were generated using Gate software and consist of:
12 | % proj -- the total measured photons after detector response function.
13 | % scat -- the photons from scatter (very small and ignored here).
14 | % i0 -- the incident source flux.
15 | % The structure in fandata.specData contains the spectral information of
16 | % the source (only a subsampling of source used in simulation):
17 | % specData.energy -- the energies (MeV) in the subsampled spectrum.
18 | % specData.spectrum -- the subsampled source spectrum.
19 | % specData.response -- the detector response function.
20 | % specData.hinge -- the location of the piecewise linear fit
21 | % transitions, for 3 linear sections.
22 | % specData.knee -- contains the equations for the piecewise linear fits
23 | % between relative electron density and each energy in
24 | % specData.energy. This was fitted against the
25 | % biological materials in the ICRP 89 and for titanium
26 | % (density = 4.506 g/cm3).
27 | % Things to try
28 | % ------------
29 | % o Test the various samples by changing 'sample' string.
30 | % o Test the influence on regularisation constant 'lambda'.
31 | % o Try removing the 'mode.proxFun' line, to give ML reconstruction.
32 | % o Adjust 'mode.maxIter', 'mode.tau' and 'mode.nSplit' to change
33 | % convergence properties.
34 | % o Set 'mode.numLinFit = 1' to see beam-hardening artefacts, which is
35 | % equivalent to a linearised model (monoenergetic).
36 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
37 | % Created: 26/04/2019
38 | % Last edit: 31/05/2019
39 | % Jonathan Hugh Mason
40 | %
41 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42 | % References: (please cite if making use of this code or its methods)
43 | % Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739
44 | % Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001
45 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
46 | %% Load data
47 | load data/attenuationDb
48 | load data/fandata
49 | addpath(genpath('.'));
50 |
51 | %% Setup the geometry
52 | ig = image_geom('nx',137,'ny',299,'dx',0.1775,'dy',0.1775);
53 | sg = sino_geom('fan','dfs',inf,'dsd',120.3,'dso',64.5,'units','cm',...
54 | 'ns',512,'ds',85/512,'strip_width','ds','na',360,'down',1);
55 | A = Gtomo2_dscmex(sg, ig);
56 |
57 | %% Polyquant setup
58 | sample = 'chest'; % 'brain', 'head', 'abdomen', 'pelvis', 'implant'
59 | mode = [];
60 | mode.useConst = true; % just to offset objective function to better range
61 | mode.contrast = [0.5,1.4]; % display contrast
62 | mode.verbose = 2; % 0 = no output; 1 = text output; 2 = text+image output
63 | mode.tau = 5; % conservative choice
64 | mode.nSplit = 24;
65 | mode.maxIter = 500; % more iterations recommended for implant
66 | lambda = 0.5; % can be optimised for better results
67 | mode.numLinFit = 2; % can be set to 2 for tissue, but use 3 for implant
68 | mode.proxFun = @(z,t) prox_tv_nn(z,t*lambda);
69 | mode.regFun = @(z) norm_tv(z);
70 | xTrue = mat_to_den(attenuationDb,single(fandata.(sample).mat));
71 |
72 | %% Perform the reconstruction
73 | out = polyquant(mode,fandata.specData,fandata.(sample).proj,fandata.i0,A,xTrue);
74 | fprintf('Reconstructed with PSNR = %.2f dB\n',20*log10(max(xTrue(:))./out.rmse(end)));
--------------------------------------------------------------------------------
/demo_polyquant_scatter.m:
--------------------------------------------------------------------------------
1 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 | % Cone-beam CT Polyquant with scatter model demo
3 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 | % Description
5 | % ----------
6 | % This script demonstrates polyquant reconstruction for cone-beam CT, with
7 | % high levels of scatter. The data was generated using Gate without a
8 | % collimator. Please refer to 'demo_polyquant_fanbeam.m' for a description
9 | % of the variables, which are the same in this case, only with a different
10 | % spectrum (pelvis.specData.spectrum).
11 | % In this demo, the scatter esimation function 'poly_sks' is called at each
12 | % iteration.
13 | % This is data is very extreme in terms of scatter and photon starvation,
14 | % so is challenging to generate accurate results.
15 | %
16 | % Things to try
17 | % ------------
18 | % o See the influence of the edge compensation factor by replacing the
19 | % '[0.3,15]' parameters with '0', which will disable it.
20 | % o Compare the estimated scatter in 'out.scat' against the true scatter
21 | % from 'pelvis.scat'.
22 | % o Substitute the scatter estimate (mode.scatFun) for the true scatter
23 | % (pelvis.scat), to see the ultimate scatter estimate's performance.
24 | % o Remove the 'mode.scatFun' line to see the scatter artefacts.
25 | % o Adjust regularisation and convergence parameters an compare to fanbeam.
26 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
27 | % Created: 26/04/2019
28 | % Last edit: 31/05/2019
29 | % Jonathan Hugh Mason
30 | %
31 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32 | % References: (please cite if making use of this code or its methods)
33 | % Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739
34 | % Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001
35 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
36 |
37 | %% Load data
38 | load data/scat_param
39 | load data/data_cbct_pelvis
40 | addpath(genpath('.'));
41 | i0 = repmat(pelvis.i0,1,1,160);
42 |
43 | %% Setup the geometry
44 | cg = ct_geom('fan', 'ns', 256, 'nt', 128, 'na', 160, ...
45 | 'orbit_start',-90, 'orbit',-360,... 201.528 ,...+1.125, ...
46 | 'ds', 0.1552, 'dt', 0.2328, ...
47 | 'offset_s', 16/0.1552, ... % quarter detector
48 | 'offset_t', 0.0, ...
49 | 'dsd', 150,'dod', 50, 'dfs', inf);
50 | ig = image_geom('nx', 299, 'ny', 137, 'nz', 60, 'dx', 0.1775,'dy',0.1775,'dz',0.484);
51 | A = Gcone(cg, ig, 'type', 'sf2', 'class', 'Fatrix');
52 | %% Polyquant setup and reconstruction
53 | mode = [];
54 | mode.useConst = true;
55 | mode.verbose = 2;
56 | mode.tau = 5; % a little more aggressive
57 | mode.offset = true;
58 | mode.cg = cg;
59 | mode.nSplit = 32;
60 | mode.maxIter = 500;
61 | mode.numLinFit = 2; % since there's no metal implants
62 | lambda = 0.1; % can be optimised for better results
63 | mode.proxFun = @(z,t) prox_tv3d_nn(z,t*lambda);
64 | mode.regFun = @(z) norm_tv3d(z);
65 | angArray = ((-90:2.25:270-2.25));
66 | %% Scatter estimation function
67 | % The factor 1.5 on the incident intensity is to compensate for the
68 | % detector not having square elements.
69 | % The edge factor 0.3 can be increased to around 0.5 for full-fan scanning.
70 | mode.scatFun = @(i0,projA,projB,projC,rho,subSet,knee) ...
71 | poly_sks(1.5*i0,projA,projB,projC,rho,angArray(subSet),...
72 | pelvis.specData,scatParam,32,cg,ig,[0.3,15]);
73 | %% Perfrm Polyquant reconstrution
74 | out = polyquant(mode,pelvis.specData,pelvis.proj,i0,A,pelvis.eden);
75 | fprintf('Reconstructed with PSNR = %.2f dB\n',20*log10(max(pelvis.eden(:))./out.rmse(end)));
--------------------------------------------------------------------------------
/gpl-3.0.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/polyquant.m:
--------------------------------------------------------------------------------
1 | function out = polyquant(mode,specData,y,I0,Af,xTrue)
2 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3 | % Performs direct quantitative reconstruction from polyergetic data.
4 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 | % Parameters
6 | % ----------
7 | % mode -- structure containing the settings and functions:
8 | % (all these settings have default values: see initialise_mode)
9 | % mode.tau -- stepsize scaling factor (< 2 is conservative).
10 | % mode.maxIter -- number of iterations.
11 | % mode.nest -- use FISTA-like Nesterov acceleration.
12 | % mode.nSplit -- number of ordered subset divisions (1 is full).
13 | % mode.verbose -- output settings: 0 = silent; 1 = text; 2 = figure.
14 | % mode.contrast -- display contrast for output live updat figure.
15 | % mode.regFun -- handle to regularisation function.
16 | % mode.proxFun -- handle to proximity operator for regularisation.
17 | % mode.scatFun -- scatter estimation function (see poly_sks.m).
18 | % mode.useConst -- offset objective function to better range.
19 | % mode.bitRev -- use subset shuffling (bit-reversal ordering).
20 | % mode.offset -- use Wang offset detector weighting for half-fan.
21 | % mode.L -- supplying Lipschitz estimate will save time.
22 | % specData -- structure containing spectral information:
23 | % specData.energy -- the energies (MeV) in the subsampled spectrum.
24 | % specData.spectrum -- the subsampled source spectrum.
25 | % specData.response -- the detector response function.
26 | % specData.hinge -- the location of the piecewise linear fit
27 | % transitions, for 3 linear sections.
28 | % specData.knee -- contains the equations for the piecewise linear
29 | % fits between relative electron density and each
30 | % energy in specData.energy. This was fitted against
31 | % the biological materials in the ICRP 89 and for
32 | % titanium (density = 4.506 g/cm3).
33 | % y -- the raw X-ray CT measurements.
34 | % I0 -- the incident flux profile.
35 | % Af -- the CT system operator generated from Fessler's toolbox.
36 | % xTrue -- ground truth image (can be 0 if unknown).
37 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
38 | % Created: 07/03/2018
39 | % Last edit: 02/06/2019
40 | % Jonathan Hugh Mason
41 | %
42 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
43 | % References: (please cite if making use of this code or its methods)
44 | % Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739
45 | % Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001
46 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47 | %% Initialisation
48 | mode = initialise_mode(mode);
49 | if ismatrix(y)
50 | x0 = ones(size(Af.arg.mask));
51 | else
52 | x0 = ones(Af.arg.ig.dim);
53 | end
54 | Ab = Gblock(Af,mode.nSplit);
55 |
56 | A = @(x,ind) Ab{ind}*x;
57 | At = @(p,ind) Ab{ind}'*p;
58 |
59 | if mode.offset
60 | w = @(z) offset_weight(z,mode.cg);
61 | else
62 | w = @(z) z;
63 | end
64 |
65 | if isfield(mode,'numLinFit')
66 | specData.hinge = [specData.hinge(1:mode.numLinFit);inf];
67 | end
68 |
69 | if isfield(specData,'response')
70 | specData.spectrum = specData.spectrum.*specData.response;
71 | end
72 |
73 |
74 | if ~isfield(mode,'L') % estimate Lipschitz if unknown
75 | mode.L = lipscitz_estimate(specData,I0,mode.scat,y,Ab*x0,Af);
76 | end
77 |
78 | alpha = mode.nSplit*mode.tau/mode.L; % the step-size
79 | if mode.useConst
80 | const = y-y.*log(y+eps);
81 | const = sum(const(:)); % a constant offset for objective function
82 | else
83 | const = 0;
84 | end
85 |
86 | x1 = x0;
87 | timeTot = tic;
88 |
89 | if mode.nest
90 | t = 1;
91 | end
92 |
93 | out.rmse(1) = rms(x1(:)-xTrue(:));
94 | if mode.verbose == 2
95 | if ndims(xTrue) == 3
96 | subplot(2,3,1),imshow(imrotate(xTrue(:,:,20),-90),mode.contrast);
97 | subplot(2,3,2),imshow(imrotate(xTrue(:,:,30),-90),mode.contrast),title('ground truth');
98 | subplot(2,3,3),imshow(imrotate(xTrue(:,:,40),-90),mode.contrast);
99 | else
100 | subplot(2,1,1),imshow(xTrue,mode.contrast),title('ground truth');
101 | subplot(2,1,2)
102 | end
103 | drawnow;
104 | end
105 | grAx = @(x1,is,ys,ind,subSet) polyquant_grad(specData,A,At,is,x1,ys,ind,mode.scatFun,subSet,w);
106 | objFac = zeros(size(y)); out.scat = zeros(size(y));
107 | %% The main iterative loop
108 | if mode.verbose > 0
109 | fprintf('Starting Polyquant reconstruction:\n');
110 | end
111 | for k = 1:mode.maxIter
112 | ind = mod(k,mode.nSplit)+1;
113 | if mode.bitRev
114 | ind = bit_rev(ind-1,mode.nSplit)+1;
115 | end
116 | subSet = ind:mode.nSplit:size(y,ndims(x0));
117 |
118 | if ndims(x0) == 3
119 | is = I0(:,:,subSet);
120 | ys = y(:,:,subSet);
121 | else
122 | is = I0(:,subSet);
123 | ys = y(:,subSet);
124 | end
125 |
126 | gradAx = grAx(x1,is,ys,ind,subSet);
127 | if ndims(x0) == 3
128 | out.scat(:,:,subSet) = gradAx.s;
129 | objFac(:,:,subSet) = gradAx.objFac;
130 | else
131 | out.scat(:,subSet) = gradAx.s;
132 | objFac(:,subSet) = gradAx.objFac;
133 | end
134 | xNew = mode.proxFun(x1-alpha*gradAx.grad,alpha);
135 |
136 | if mode.nest
137 | t1 = 0.5*(1+sqrt(1+4*t^2));
138 | x1 = xNew+(t-1)/t1*(xNew-x0);
139 | x0 = xNew;
140 | t = t1;
141 | else
142 | x1 = xNew;
143 | end
144 |
145 | out.rmse(k+1) = rms(x1(:)-xTrue(:));
146 | out.obj(k+1) = sum(double(objFac(:)+out.scat(:)-y(:).*log(objFac(:)+out.scat(:)+eps)))-const+mode.regFun(x1);
147 | if mode.verbose > 0
148 | fprintf('\rIter = %i;\t RMSE = %.4e;\t obj = %.4e;\t subset = %i ',k,out.rmse(k+1),out.obj(k+1),ind);
149 | end
150 | if mode.verbose == 2
151 | str = ['polyquant at iteration: ',num2str(k)];
152 | if ndims(x1) == 3
153 | subplot(2,3,4),imshow(imrotate(x1(:,:,20),-90),mode.contrast);
154 | subplot(2,3,5),imshow(imrotate(x1(:,:,30),-90),mode.contrast),title(str);
155 | subplot(2,3,6),imshow(imrotate(x1(:,:,40),-90),mode.contrast);
156 | else
157 | imshow(x1,mode.contrast),title(str);
158 | end
159 | drawnow;
160 | end
161 |
162 | end
163 | time = toc(timeTot);
164 | out.time = time;
165 | out.recon = xNew;
166 | if mode.verbose > 0
167 | fprintf('\n Finished in %.2e seconds\n',time);
168 | end
169 |
170 | end
171 |
172 | function strOut = polyquant_grad(specData,A,At,I0,rho,y,ind,scatFun,subSet,w)
173 | % This function calculates the gradient, objective function unless using
174 | % OS, and the scatter if calculated on the fly.
175 | projSet = cell(length(specData.hinge)-1,2);
176 | mask = cell(length(specData.hinge)-1,1);
177 | projSet{1,2} = 0;
178 | for k = 1:length(specData.hinge)-1
179 | mask{k} = double(rho > specData.hinge(k) & rho < specData.hinge(k+1));
180 | projSet{k,1} = A(mask{k}.*rho,ind);
181 | if k>1
182 | projSet{k,2} = A(mask{k},ind);
183 | end
184 | end
185 | specProb = specData.spectrum./sum(specData.spectrum(:));
186 |
187 | mainFac = zeros(size(y));
188 | hingeFac = cell(length(specData.hinge)-1);
189 | for k = 1:length(specData.hinge)-1
190 | hingeFac{k} = zeros(size(y));
191 | end
192 |
193 | if length(specData.hinge)>2 % to bodge error for one linear fit
194 | s = scatFun(I0,projSet{1,1},projSet{2,1},projSet{2,2},rho,subSet,specData.knee);
195 | else
196 | s = scatFun(I0,projSet{1,1},projSet{1,1},projSet{1,2},rho,subSet,specData.knee);
197 | end
198 | for k = 1:length(specData.spectrum)
199 | linSum = zeros(size(y));
200 | for l = 1:length(specData.hinge)-1
201 | linSum = linSum+specData.knee(1,l,k)*projSet{l,1}...
202 | +specData.knee(2,l,k)*projSet{l,2};
203 | end
204 | tmp = specProb(k).*exp(-linSum);
205 | mainFac = mainFac+tmp;
206 | for l = 1:length(specData.hinge)-1
207 | hingeFac{l} = hingeFac{l}+tmp*specData.knee(1,l,k);
208 | end
209 | end
210 | mainFac = I0.*mainFac;
211 |
212 | deriFac = w(y./(mainFac+s)-1);
213 |
214 | out = zeros(size(rho));
215 | for l = 1:length(specData.hinge)-1
216 | out = out+mask{l}.*At(I0.*hingeFac{l}.*deriFac,ind);
217 | end
218 |
219 | strOut.grad = out;
220 | strOut.objFac = mainFac;
221 | strOut.s = s;
222 | end
223 |
224 | function out = lipscitz_estimate(specData,I0,s,y,flat,At)
225 | % A crude but reasonably acceptable estimate of the Lipschitz constant
226 | specProb = specData.spectrum./sum(specData.spectrum(:));
227 | tmpA = 0;
228 | for k = 1:length(specData.spectrum)
229 | tmpA = tmpA+specProb(k)*specData.knee(1,1,k).^2;
230 | end
231 | fac = I0.*(1-y.*s./((I0+s).^2));
232 | p2A = At'*(flat.*tmpA.*fac);
233 | out = max(p2A(:));
234 | end
235 |
236 | function out = prox_nz(in,up)
237 | % Simple proximal function to enforce box constraints
238 | if nargin > 1
239 | in(in>up) = up;
240 | end
241 | in(in<0) = 0;
242 | out = in;
243 | end
244 |
245 | function mode = initialise_mode(mode)
246 | % Make sure everything is in order
247 | if ~isfield(mode,'nest'), mode.nest = true; end
248 | if ~isfield(mode,'maxIter'), mode.maxIter = 100; end
249 | if ~isfield(mode,'bitRev'), mode.bitRev = true; end
250 | if ~isfield(mode,'offset'), mode.offset = false; end
251 | if ~isfield(mode,'verbose'), mode.verbose = 1; end
252 | if ~isfield(mode,'tau'), mode.tau = 1.99; end
253 | if ~isfield(mode,'nSplit'), mode.nSplit = 1; end
254 | if ~isfield(mode,'flip'), mode.flip = false; end
255 | if ~isfield(mode,'regFun'), mode.regFun = @(z) 0; end
256 | if ~isfield(mode,'proxFun'), mode.proxFun = @(z,t) prox_nz(z); end
257 | if ~isfield(mode,'contrast'), mode.contrast = [0,2]; end
258 | if ~isfield(mode,'useConst'), mode.useConst = false; end
259 | if ~isfield(mode,'scatFun')
260 | mode.scat = 0;
261 | mode.scatFun = @(z,~,~,~,~,~,~) 0;
262 | elseif ~isa(mode.scatFun,'function_handle')
263 | mode.scat = mode.scatFun;
264 | mode.scatFun = @(z,~,~,~,~,subSet,~) mode.scat(:,:,subSet);
265 | else
266 | mode.scat = 0;
267 | end
268 | end
269 |
270 | function out = offset_weight(proj,cg)
271 | % Offset weighting for half-fan case from [G. Wang, Med Phys. 2002]
272 | out = proj;
273 | us = ((cg.ns/2-0.5):-1:(-cg.ns/2+0.5))*cg.ds - cg.offset_s*cg.ds;
274 | overlap = max(us);
275 | overLoc = sum(abs(us)<=overlap);
276 | replaceLoc = 1:overLoc;
277 | denom = 2*atan(overlap/cg.dsd);
278 | num = pi*atan(us(replaceLoc)/cg.dsd);
279 | %weightArray = 1-cos(linspace(0,pi/2,overLoc)).^2;
280 | weightArray = 1-0.5*(sin(num./denom)+1);
281 | weightMat = repmat(weightArray',1,cg.nt);
282 | replaceLoc = 1:size(weightMat,1);
283 |
284 | for k = 1:size(proj,3)
285 | out(end-replaceLoc+1,:,k) = proj(end-replaceLoc+1,:,k).*weightMat;
286 | end
287 | end
--------------------------------------------------------------------------------
/utilities/bit_rev.m:
--------------------------------------------------------------------------------
1 | function out = bit_rev(in,sz)
2 | % Bit-reversal ordering as in [G. Herman and L. Meyer, IEEE TMI 1993]
3 | facs = factor(sz);
4 | unit = zeros(size(facs));
5 | unit(1) = 1;
6 | if length(facs)>1
7 | for i = 2:length(facs)
8 | unit(i) = prod(facs(1:i-1));
9 | end
10 | end
11 | remain = in;
12 | vec = zeros(size(facs));
13 | while remain>0
14 | ind = 1;
15 | while unit(ind)*facs(ind)-1 edge attenuation scaling factor.
20 | % gamma(2) -> sets upper limit for attenuating effect.
21 | % gamma==0 -> no edge compensation.
22 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
23 | % Created: 07/03/2018
24 | % Last edit: 26/04/2019
25 | % Jonathan Hugh Mason
26 | %
27 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28 | % References: (please cite if making use of this code or its methods)
29 | % Jonathan H Mason et al 2017 Phys. Med. Biol. 62 8739
30 | % Jonathan H Mason et al 2018 Phys. Med. Biol. 63 225001
31 | %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32 | arr1 = (-(cg.ns-1)/2-nPad:(cg.ns-1)/2+nPad)*cg.ds; %
33 | if size(i0,2) == size(i0,1)
34 | arr2 = arr1;
35 | else
36 | arr2 = (-(cg.nt-1)/2-nPad:(cg.nt-1)/2+nPad)*cg.dt;
37 | end
38 | [us,vs] = ndgrid(arr1,arr2);
39 | uu = ((-(cg.ns-1)/2:(cg.ns-1)/2)+cg.offset_s)*cg.ds;
40 | eDen = projA+projB;
41 |
42 | %% Calculate the magnification factor
43 | projScat = zeros(size(i0));
44 | centPo = round(size(im)/2);
45 | RP = regionprops(double(im(:,:,centPo(3))>0.1),'Centroid','MajorAxisLength','MinorAxisLength','Orientation');
46 |
47 | tranF = (RP.Centroid-centPo([2,1]))*ig.dx;
48 | trans = [tranF,0];
49 | magFactor = zeros(size(i0,3),1);
50 | tmpFac = zeros(size(i0));
51 | for k = 1:size(i0,3)
52 | rotAng = ang(k);
53 | out = ell_centroid(rotAng,RP.MinorAxisLength*ig.dx/2,RP.MajorAxisLength*ig.dx/2,...
54 | tranF(1),tranF(2),uu,true,cg);
55 | tmpFac(:,:,k) = repmat((cg.dod-out')./cg.dod,1,size(i0,2));
56 | rotAng = ang(k);
57 | rotMat = [cosd(rotAng),-sind(rotAng),0;
58 | sind(rotAng),cosd(rotAng),0;
59 | 0,0,1];
60 | rotTrans = rotMat*trans';
61 |
62 | magFactor(k) = (cg.dod-rotTrans(1))/cg.dod;
63 | tmpFac(:,:,k) = repmat(magFactor(k),size(i0,1),size(i0,2)).^2;
64 |
65 | end
66 |
67 | %% Calculate the convolutional scatters
68 | scat1 = zeros(size(i0,1)+2*nPad,size(i0,2)+2*nPad,size(i0,3));
69 | g = scat1;
70 | broad = zeros(size(i0));
71 | specProb = specData.spectrum(:).*specData.response(:)./sum(specData.spectrum(:).*specData.response(:));
72 |
73 | for k = 1:length(specData.energy)
74 | % Estimate the attenuation from the polyquant projections
75 | atten = specData.knee(1,1,k)*projA+specData.knee(1,2,k)*projB+specData.knee(2,2,k)*projC;
76 | % Narrow scatter field calculation
77 | A = scatParam.fA1(k,1)*ones(size(i0));...
78 | C = scatParam.C1(k);
79 | for i = 1:size(i0,3)
80 | A(:,:,i) = A(:,:,i)./tmpFac(:,:,i);
81 | tmpC = magFactor(i)*C;
82 | g(:,:,i) = exp(-(us.^2+vs.^2)/(tmpC^2));
83 | end
84 |
85 | fg = fft2(g);
86 |
87 | projFor = specProb(k)*A.*i0.*exp(-atten).*(eDen);
88 | scat1 = scat1+fft2(padarray(projFor,[nPad,nPad,0])).*fg;
89 |
90 | % Broad scatter field calculation
91 | A = scatParam.fA2(k,1)*ones(size(i0)); x2 = scatParam.fA2(k,2); x3 = scatParam.fA2(k,3);
92 | for i = 1:size(i0,3)
93 | A(:,:,i) = A(:,:,i)./tmpFac(:,:,i);
94 | end
95 | broadTmp = specProb(k)*A.*i0.*exp(-atten*x2).*(eDen.^x3);
96 |
97 | broad = broad+broadTmp;
98 | end
99 |
100 | if (gamma)
101 | broad = edge_factor(scatParam.eFac.*gamma(1),eDen,broad,abs(gamma(2)),cg);
102 | end
103 |
104 | gBroad = zeros(size(scat1));
105 | for i = 1:size(i0,3)
106 | tmpC = sqrt(magFactor(i))*scatParam.C2(1);
107 | gBroad(:,:,i) = exp(-(us.^2+vs.^2)/(tmpC^2));
108 | end
109 |
110 | fg = fft2(gBroad);
111 | scat1 = scat1+fft2(padarray(broad,[nPad,nPad,0])).*fg;
112 |
113 | for j = 1:size(projA,3)
114 | projScat(:,:,j) = real(unpad(ifftshift(ifft2(scat1(:,:,j))),nPad));
115 | end
116 |
117 | projScat(projScat<0) = 0; % ensure the scatter is non-negative
118 |
119 | out = projScat;
120 | end
121 |
122 | function out = unpad(in,nPad)
123 | sz1 = size(in,1); sz2 = size(in,2);
124 | out = in(1+nPad:sz1-nPad,1+nPad:sz2-nPad,:);
125 | end
126 |
127 | function out = edge_factor(factor,eDen,broadIn,sig,cg)
128 | %% The edge compensation factor
129 | eDen = imgaussfilt(eDen,10);
130 | [gradX,gradY] = gradient_op3d(eDen);
131 |
132 | shiftFacX = eDen.*gradX.*factor./cg.ds;
133 | shiftFacY = eDen.*gradY.*factor./cg.dt;
134 | shiftFacX(abs(shiftFacX)>sig) = sig;
135 | shiftFacY(abs(shiftFacX)>sig) = sig;
136 |
137 | out = broadIn.*exp(-(shiftFacX.^2)./(35.^2)-(shiftFacY.^2)./(35.^2));
138 | end
139 |
--------------------------------------------------------------------------------
/utilities/pw_knee_fit.m:
--------------------------------------------------------------------------------
1 | function [out,fac] = pw_knee_fit(specData,attenuationDb,mden,tiMa)
2 | comp = attenuationDb.comp(2:53,:);
3 | comp = [comp,zeros(52,1)];
4 | comp = [comp;zeros(1,14)];
5 | comp(end,end) = 1;
6 | dens = attenuationDb.density(2:53);
7 | dens(end+1) = 4.506;
8 | mA = attenuationDb.massAtten(2:53,:);
9 | mA = [mA;tiMa'];
10 | Z = [1,6,7,8,11,12,15,16,17,19,20,26,53,22];
11 | A = [1.01,12.01,14.01,16.00,22.99,24.305,30.97,32.066,35.45,39.098,40.08,55.845,126.90,47.867];
12 | eDen = comp*(Z'./A');
13 | waterE = 0.1119*1/1.01+0.8881*8/16;
14 | [relDen,unIdx] = unique(dens.*eDen./waterE);
15 | dens = dens(unIdx);
16 | monoAtten = mA(unIdx,9).*dens;
17 | if mden, relDen = dens; end
18 | if mden == 2, relDen = monoAtten; end
19 | warning('off','MATLAB:rankDeficientMatrix');
20 | obj = @(z) ls_fit(specData,mA(unIdx,:),dens,relDen,z);
21 | if mden == 2
22 | fac = fminsearch(obj,[0.15;1]);
23 | [~,out] = ls_fit(specData,mA(unIdx,:),dens,relDen,fac);
24 | %fac = [0.2;1];
25 | else
26 | fac = fminsearch(obj,[1;3]);
27 | [~,out] = ls_fit(specData,mA(unIdx,:),dens,relDen,fac);
28 | end
29 | end
30 |
31 | function [out,knee] = ls_fit(specData,mA,dens,relDen,z)
32 | fac = [z;5];
33 | res = zeros(size(dens));
34 | for k = 1:length(specData.energy)
35 | fit = ls_knee(relDen,mA(:,k).*dens,fac);
36 | intPoint = interp1([0;fac],[0;fit],relDen);
37 | res = res+(mA(:,k).*dens-intPoint).^2;
38 | knee(:,k) = fac_to_knee([0;fac],[0;fit]);
39 | end
40 | res = sum(res);
41 | out = res;
42 | end
43 |
44 | function out = ls_knee(in,y,kneeArray)
45 | A = zeros(length(in),length(kneeArray)+1);
46 | yOrd = zeros(size(y));
47 | ind = [0;kneeArray];
48 | start = 1;
49 | for k = 1:length(kneeArray)
50 | inSub = in(in=ind(k));
51 | ySub = y(in=ind(k));
52 | aSub1 = (-inSub+ind(k))./(ind(k+1)-ind(k))+1;
53 | aSub2 = (inSub-ind(k))./(ind(k+1)-ind(k));
54 | A(start:(start+length(inSub)-1),[k,k+1]) = [aSub1,aSub2];
55 | yOrd(start:(start+length(inSub)-1)) = ySub;
56 | start = start+length(inSub);
57 | end
58 | A(:,1) = [];
59 | out = A\yOrd;
60 | end
61 |
62 | function out = fac_to_knee(fac,fit)
63 | knee = zeros((length(fac)-1)*2,1);
64 | for k = 1:length(fit)-1
65 | knee(2*(k-1)+1) = (fit(k+1)-fit(k))/(fac(k+1)-fac(k));
66 | if k>1
67 | knee(2*k) = fit(k)-fac(k)*(knee(2*(k-1)+1));
68 | else
69 | knee(2*k) = 0;
70 | end
71 | end
72 | knee(2) = [];
73 | out = knee;
74 | end
--------------------------------------------------------------------------------