5837
|
1 ## Copyright (C) 2004 Piotr Krzyzanowski <piotr.krzyzanowski@mimuw.edu.pl> |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
5838
|
21 ## @deftypefn {Function File} {@var{x} =} pcg (@var{a}, @var{b}, @var{tol}, @var{maxit}, @var{m}, @var{x0}, @dots{}) |
5837
|
22 ## @deftypefnx {Function File} {[@var{x}, @var{flag}, @var{relres}, @var{iter}, @var{resvec}, @var{eigest}] =} pcg (@dots{}) |
|
23 ## |
5838
|
24 ## Solves the linear system of equations @code{@var{a} * @var{x} = |
5837
|
25 ## @var{b}} by means of the Preconditioned Conjugate Gradient iterative |
|
26 ## method. The input arguments are |
|
27 ## |
|
28 ## @itemize |
|
29 ## @item |
5838
|
30 ## @var{a} can be either a square (preferably sparse) matrix or a |
5837
|
31 ## function handle, inline function or string containing the name |
5838
|
32 ## of a function which computes @code{@var{a} * @var{x}}. In principle |
|
33 ## @var{a} should be symmetric and positive definite; if @code{pcg} |
|
34 ## finds @var{a} to not be positive definite, you will get a warning |
5837
|
35 ## message and the @var{flag} output parameter will be set. |
|
36 ## |
|
37 ## @item |
|
38 ## @var{b} is the right hand side vector. |
|
39 ## |
|
40 ## @item |
|
41 ## @var{tol} is the required relative tolerance for the residual error, |
5838
|
42 ## @code{@var{b} - @var{a} * @var{x}}. The iteration stops if @code{norm |
|
43 ## (@var{b} - @var{a} * @var{x}) <= @var{tol} * norm (@var{b} - @var{a} * |
5837
|
44 ## @var{x0})}. If @var{tol} is empty or is omitted, the function sets |
|
45 ## @code{@var{tol} = 1e-6} by default. |
|
46 ## |
|
47 ## @item |
|
48 ## @var{maxit} is the maximum allowable number of iterations; if |
|
49 ## @code{[]} is supplied for @code{maxit}, or @code{pcg} has less |
|
50 ## arguments, a default value equal to 20 is used. |
|
51 ## |
|
52 ## @item |
5838
|
53 ## @var{m} is the (left) preconditioning matrix, so that the iteration is |
5837
|
54 ## (theoretically) equivalent to solving by @code{pcg} @code{@var{P} * |
5838
|
55 ## @var{x} = @var{m} \ @var{b}}, with @code{@var{P} = @var{m} \ @var{a}}. |
5837
|
56 ## Note that a proper choice of the preconditioner may dramatically |
|
57 ## improve the overall performance of the method. Instead of matrix |
5838
|
58 ## @var{m}, the user may pass a function which returns the results of |
|
59 ## applying the inverse of @var{m} to a vector (usually this is the |
5837
|
60 ## preferred way of using the preconditioner). If @code{[]} is supplied |
5838
|
61 ## for @var{m}, or @var{m} is omitted, no preconditioning is applied. |
5837
|
62 ## |
|
63 ## @item |
|
64 ## @var{x0} is the initial guess. If @var{x0} is empty or omitted, the |
|
65 ## function sets @var{x0} to a zero vector by default. |
|
66 ## @end itemize |
|
67 ## |
|
68 ## The arguments which follow @var{x0} are treated as parameters, and |
5838
|
69 ## passed in a proper way to any of the functions (@var{a} or @var{m}) |
5837
|
70 ## which are passed to @code{pcg}. See the examples below for further |
|
71 ## details. The output arguments are |
|
72 ## |
|
73 ## @itemize |
|
74 ## @item |
|
75 ## @var{x} is the computed approximation to the solution of |
5838
|
76 ## @code{@var{a} * @var{x} = @var{b}}. |
5837
|
77 ## |
|
78 ## @item |
|
79 ## @var{flag} reports on the convergence. @code{@var{flag} = 0} means |
|
80 ## the solution converged and the tolerance criterion given by @var{tol} |
|
81 ## is satisfied. @code{@var{flag} = 1} means that the @var{maxit} limit |
|
82 ## for the iteration count was reached. @code{@var{flag} = 3} reports that |
|
83 ## the (preconditioned) matrix was found not positive definite. |
|
84 ## |
|
85 ## @item |
|
86 ## @var{relres} is the ratio of the final residual to its initial value, |
|
87 ## measured in the Euclidean norm. |
|
88 ## |
|
89 ## @item |
|
90 ## @var{iter} is the actual number of iterations performed. |
|
91 ## |
|
92 ## @item |
|
93 ## @var{resvec} describes the convergence history of the method. |
|
94 ## @code{@var{resvec} (i,1)} is the Euclidean norm of the residual, and |
|
95 ## @code{@var{resvec} (i,2)} is the preconditioned residual norm, |
|
96 ## after the (@var{i}-1)-th iteration, @code{@var{i} = |
6547
|
97 ## 1, 2, @dots{}, @var{iter}+1}. The preconditioned residual norm |
|
98 ## is defined as |
5838
|
99 ## @code{norm (@var{r}) ^ 2 = @var{r}' * (@var{m} \ @var{r})} where |
|
100 ## @code{@var{r} = @var{b} - @var{a} * @var{x}}, see also the |
|
101 ## description of @var{m}. If @var{eigest} is not required, only |
5837
|
102 ## @code{@var{resvec} (:,1)} is returned. |
|
103 ## |
|
104 ## @item |
|
105 ## @var{eigest} returns the estimate for the smallest @code{@var{eigest} |
|
106 ## (1)} and largest @code{@var{eigest} (2)} eigenvalues of the |
5838
|
107 ## preconditioned matrix @code{@var{P} = @var{m} \ @var{a}}. In |
5837
|
108 ## particular, if no preconditioning is used, the extimates for the |
5838
|
109 ## extreme eigenvalues of @var{a} are returned. @code{@var{eigest} (1)} |
5837
|
110 ## is an overestimate and @code{@var{eigest} (2)} is an underestimate, |
|
111 ## so that @code{@var{eigest} (2) / @var{eigest} (1)} is a lower bound |
|
112 ## for @code{cond (@var{P}, 2)}, which nevertheless in the limit should |
|
113 ## theoretically be equal to the actual value of the condition number. |
|
114 ## The method which computes @var{eigest} works only for symmetric positive |
5838
|
115 ## definite @var{a} and @var{m}, and the user is responsible for |
5837
|
116 ## verifying this assumption. |
|
117 ## @end itemize |
|
118 ## |
|
119 ## Let us consider a trivial problem with a diagonal matrix (we exploit the |
|
120 ## sparsity of A) |
|
121 ## |
|
122 ## @example |
|
123 ## @group |
|
124 ## N = 10; |
6547
|
125 ## A = spdiag ([1:N]); |
|
126 ## b = rand (N, 1); |
5837
|
127 ## @end group |
|
128 ## @end example |
|
129 ## |
|
130 ## @sc{Example 1:} Simplest use of @code{pcg} |
|
131 ## |
|
132 ## @example |
|
133 ## x = pcg(A,b) |
|
134 ## @end example |
|
135 ## |
|
136 ## @sc{Example 2:} @code{pcg} with a function which computes |
5838
|
137 ## @code{@var{a} * @var{x}} |
5837
|
138 ## |
|
139 ## @example |
|
140 ## @group |
6547
|
141 ## function y = applyA (x) |
5837
|
142 ## y = [1:N]'.*x; |
|
143 ## endfunction |
|
144 ## |
6547
|
145 ## x = pcg ("applyA", b) |
5837
|
146 ## @end group |
|
147 ## @end example |
|
148 ## |
|
149 ## @sc{Example 3:} Preconditioned iteration, with full diagnostics. The |
|
150 ## preconditioner (quite strange, because even the original matrix |
5838
|
151 ## @var{a} is trivial) is defined as a function |
5837
|
152 ## |
|
153 ## @example |
|
154 ## @group |
6547
|
155 ## function y = applyM(x) |
|
156 ## K = floor (length (x) - 2); |
|
157 ## y = x; |
|
158 ## y(1:K) = x(1:K)./[1:K]'; |
5837
|
159 ## endfunction |
|
160 ## |
6547
|
161 ## [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], [], "applyM"); |
|
162 ## semilogy (1:iter+1, resvec); |
5837
|
163 ## @end group |
|
164 ## @end example |
|
165 ## |
|
166 ## @sc{Example 4:} Finally, a preconditioner which depends on a |
|
167 ## parameter @var{k}. |
|
168 ## |
|
169 ## @example |
|
170 ## @group |
6547
|
171 ## function y = applyM (x, varargin) |
5837
|
172 ## K = varargin@{1@}; |
6547
|
173 ## y = x; |
|
174 ## y(1:K) = x(1:K)./[1:K]'; |
5837
|
175 ## endfuntion |
|
176 ## |
|
177 ## [x, flag, relres, iter, resvec, eigest] = ... |
6547
|
178 ## pcg (A, b, [], [], "applyM", [], 3) |
5837
|
179 ## @end group |
|
180 ## @end example |
|
181 ## |
|
182 ## @sc{References} |
|
183 ## |
|
184 ## [1] C.T.Kelley, 'Iterative methods for linear and nonlinear equations', |
|
185 ## SIAM, 1995 (the base PCG algorithm) |
|
186 ## |
|
187 ## [2] Y.Saad, 'Iterative methods for sparse linear systems', PWS 1996 |
|
188 ## (condition number estimate from PCG) Revised version of this book is |
|
189 ## available online at http://www-users.cs.umn.edu/~saad/books.html |
|
190 ## |
|
191 ## |
|
192 ## @seealso{sparse, pcr} |
|
193 ## @end deftypefn |
|
194 |
5838
|
195 ## Author: Piotr Krzyzanowski <piotr.krzyzanowski@mimuw.edu.pl> |
5837
|
196 |
5838
|
197 function [x, flag, relres, iter, resvec, eigest] = pcg (A, b, tol, maxit, M, x0, varargin) |
5837
|
198 |
5838
|
199 if (nargin < 6 || isempty (x0)) |
|
200 x = zeros (size (b)); |
5837
|
201 else |
|
202 x = x0; |
|
203 endif |
|
204 |
|
205 if (nargin < 5) |
|
206 M = []; |
|
207 endif |
|
208 |
5838
|
209 if (nargin < 4 || isempty (maxit)) |
|
210 maxit = min (size (b, 1), 20); |
5837
|
211 endif |
|
212 |
5838
|
213 maxit += 2; |
5837
|
214 |
5838
|
215 if (nargin < 3 || isempty (tol)) |
5837
|
216 tol = 1e-6; |
|
217 endif |
|
218 |
|
219 preconditioned_residual_out = false; |
|
220 if (nargout > 5) |
5838
|
221 T = zeros (maxit, maxit); |
5837
|
222 preconditioned_residual_out = true; |
|
223 endif |
|
224 |
|
225 matrix_positive_definite = true; # assume A is positive definite |
|
226 |
5838
|
227 p = zeros (size (b)); |
5837
|
228 oldtau = 1; |
5838
|
229 if (isnumeric (A)) # is A a matrix? |
5837
|
230 r = b - A*x; |
|
231 else # then A should be a function! |
5838
|
232 r = b - feval (A, x, varargin{:}); |
5837
|
233 endif |
|
234 |
5838
|
235 resvec(1,1) = norm (r); |
5837
|
236 alpha = 1; |
|
237 iter = 2; |
|
238 |
5838
|
239 while (resvec(iter-1,1) > tol*resvec(1,1) && iter < maxit) |
|
240 if (isnumeric (M)) # is M a matrix? |
|
241 if (isempty (M)) # if M is empty, use no precond |
5837
|
242 z = r; |
|
243 else # otherwise, apply the precond |
|
244 z = M \ r; |
|
245 endif |
|
246 else # then M should be a function! |
5838
|
247 z = feval (M, r, varargin{:}); |
5837
|
248 endif |
5838
|
249 tau = z' * r; |
|
250 resvec(iter-1,2) = sqrt (tau); |
|
251 beta = tau / oldtau; |
5837
|
252 oldtau = tau; |
|
253 p = z + beta*p; |
5838
|
254 if (isnumeric (A)) # is A a matrix? |
|
255 w = A * p; |
5837
|
256 else # then A should be a function! |
5838
|
257 w = feval (A, p, varargin{:}); |
5837
|
258 endif |
|
259 oldalpha = alpha; # needed only for eigest |
5838
|
260 alpha = tau / (p'*w); |
5837
|
261 if (alpha <= 0.0) # negative matrix? |
|
262 matrix_positive_definite = false; |
|
263 endif |
5838
|
264 x += alpha*p; |
|
265 r -= alpha*w; |
|
266 if (nargout > 5 && iter > 2) |
5837
|
267 T(iter-1:iter, iter-1:iter) = T(iter-1:iter, iter-1:iter) + ... |
|
268 [1 sqrt(beta); sqrt(beta) beta]./oldalpha; |
|
269 ## EVS = eig(T(2:iter-1,2:iter-1)); |
|
270 ## fprintf(stderr,"PCG condest: %g (iteration: %d)\n", max(EVS)/min(EVS),iter); |
|
271 endif |
5838
|
272 resvec(iter,1) = norm (r); |
|
273 iter++; |
5837
|
274 endwhile |
|
275 |
|
276 if (nargout > 5) |
5838
|
277 if (matrix_positive_definite) |
5837
|
278 if (iter > 3) |
|
279 T = T(2:iter-2,2:iter-2); |
|
280 l = eig(T); |
5838
|
281 eigest = [min(l), max(l)]; |
6498
|
282 ## fprintf (stderr, "pcg condest: %g\n", eigest(2)/eigest(1)); |
5837
|
283 else |
5838
|
284 eigest = [NaN, NaN]; |
6498
|
285 warning ("pcg: eigenvalue estimate failed: iteration converged too fast."); |
5837
|
286 endif |
|
287 else |
5838
|
288 eigest = [NaN, NaN]; |
5837
|
289 endif |
|
290 |
|
291 ## apply the preconditioner once more and finish with the precond |
|
292 ## residual |
5838
|
293 if (isnumeric (M)) # is M a matrix? |
|
294 if (isempty (M)) # if M is empty, use no precond |
5837
|
295 z = r; |
|
296 else # otherwise, apply the precond |
5838
|
297 z = M \ r; |
5837
|
298 endif |
|
299 else # then M should be a function! |
5838
|
300 z = feval (M, r, varargin{:}); |
5837
|
301 endif |
5838
|
302 resvec(iter-1,2) = sqrt (r'*z); |
5837
|
303 else |
5838
|
304 resvec = resvec(:,1); |
5837
|
305 endif |
|
306 |
|
307 flag = 0; |
|
308 relres = resvec(iter-1,1)./resvec(1,1); |
5838
|
309 iter -= 2; |
|
310 if (iter >= maxit-2) |
5837
|
311 flag = 1; |
|
312 if (nargout < 2) |
6498
|
313 warning ("pcg: maximum number of iterations (%d) reached\n", iter); |
|
314 warning ("the initial residual norm was reduced %g times.\n", 1.0/relres); |
5837
|
315 endif |
5838
|
316 elseif (nargout < 2) |
6498
|
317 fprintf (stderr, "pcg: converged in %d iterations. ", iter); |
|
318 fprintf (stderr, "the initial residual norm was reduced %g times.\n",... |
5838
|
319 1.0/relres); |
5837
|
320 endif |
|
321 |
5838
|
322 if (! matrix_positive_definite) |
5837
|
323 flag = 3; |
|
324 if (nargout < 2) |
6498
|
325 warning ("pcg: matrix not positive definite?\n"); |
5837
|
326 endif |
|
327 endif |
|
328 endfunction |
|
329 |
|
330 %!demo |
|
331 %! |
|
332 %! # Simplest usage of pcg (see also 'help pcg') |
|
333 %! |
|
334 %! N = 10; |
|
335 %! A = diag([1:N]); b = rand(N,1); y = A\b; #y is the true solution |
|
336 %! x = pcg(A,b); |
|
337 %! printf('The solution relative error is %g\n', norm(x-y)/norm(y)); |
|
338 %! |
|
339 %! # You shouldn't be afraid if pcg issues some warning messages in this |
|
340 %! # example: watch out in the second example, why it takes N iterations |
|
341 %! # of pcg to converge to (a very accurate, by the way) solution |
|
342 %!demo |
|
343 %! |
|
344 %! # Full output from pcg, except for the eigenvalue estimates |
|
345 %! # We use this output to plot the convergence history |
|
346 %! |
|
347 %! N = 10; |
|
348 %! A = diag([1:N]); b = rand(N,1); X = A\b; #X is the true solution |
|
349 %! [x, flag, relres, iter, resvec] = pcg(A,b); |
|
350 %! printf('The solution relative error is %g\n', norm(x-X)/norm(X)); |
|
351 %! title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||/||b||)'); |
|
352 %! semilogy([0:iter],resvec/resvec(1),'o-g;relative residual;'); |
|
353 %!demo |
|
354 %! |
|
355 %! # Full output from pcg, including the eigenvalue estimates |
|
356 %! # Hilbert matrix is extremely ill conditioned, so pcg WILL have problems |
|
357 %! |
|
358 %! N = 10; |
|
359 %! A = hilb(N); b = rand(N,1); X = A\b; #X is the true solution |
|
360 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,[],200); |
|
361 %! printf('The solution relative error is %g\n', norm(x-X)/norm(X)); |
|
362 %! printf('Condition number estimate is %g\n', eigest(2)/eigest(1)); |
|
363 %! printf('Actual condition number is %g\n', cond(A)); |
|
364 %! title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)'); |
|
365 %! semilogy([0:iter],resvec,['o-g;absolute residual;';'+-r;absolute preconditioned residual;']); |
|
366 %!demo |
|
367 %! |
|
368 %! # Full output from pcg, including the eigenvalue estimates |
|
369 %! # We use the 1-D Laplacian matrix for A, and cond(A) = O(N^2) |
|
370 %! # and that's the reasone we need some preconditioner; here we take |
|
371 %! # a very simple and not powerful Jacobi preconditioner, |
|
372 %! # which is the diagonal of A |
|
373 %! |
|
374 %! N = 100; |
|
375 %! A = zeros(N,N); |
|
376 %! for i=1:N-1 # form 1-D Laplacian matrix |
|
377 %! A(i:i+1,i:i+1) = [2 -1; -1 2]; |
|
378 %! endfor |
|
379 %! b = rand(N,1); X = A\b; #X is the true solution |
|
380 %! maxit = 80; |
|
381 %! printf('System condition number is %g\n',cond(A)); |
|
382 %! # No preconditioner: the convergence is very slow! |
|
383 %! |
|
384 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,[],maxit); |
|
385 %! printf('System condition number estimate is %g\n',eigest(2)/eigest(1)); |
|
386 %! title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)'); |
|
387 %! semilogy([0:iter],resvec(:,1),'o-g;NO preconditioning: absolute residual;'); |
|
388 %! |
|
389 %! pause(1); |
|
390 %! # Test Jacobi preconditioner: it will not help much!!! |
|
391 %! |
|
392 %! M = diag(diag(A)); # Jacobi preconditioner |
|
393 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,[],maxit,M); |
|
394 %! printf('JACOBI preconditioned system condition number estimate is %g\n',eigest(2)/eigest(1)); |
|
395 %! hold on; |
|
396 %! semilogy([0:iter],resvec(:,1),'o-r;JACOBI preconditioner: absolute residual;'); |
|
397 %! |
|
398 %! pause(1); |
|
399 %! # Test nonoverlapping block Jacobi preconditioner: it will help much! |
|
400 %! |
|
401 %! M = zeros(N,N);k=4 |
|
402 %! for i=1:k:N # form 1-D Laplacian matrix |
|
403 %! M(i:i+k-1,i:i+k-1) = A(i:i+k-1,i:i+k-1); |
|
404 %! endfor |
|
405 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,[],maxit,M); |
|
406 %! printf('BLOCK JACOBI preconditioned system condition number estimate is %g\n',eigest(2)/eigest(1)); |
|
407 %! semilogy([0:iter],resvec(:,1),'o-b;BLOCK JACOBI preconditioner: absolute residual;'); |
|
408 %! hold off; |
|
409 %!test |
|
410 %! |
|
411 %! #solve small diagonal system |
|
412 %! |
|
413 %! N = 10; |
|
414 %! A = diag([1:N]); b = rand(N,1); X = A\b; #X is the true solution |
|
415 %! [x, flag] = pcg(A,b,[],N+1); |
|
416 %! assert(norm(x-X)/norm(X),0,1e-10); |
|
417 %! assert(flag,0); |
|
418 %! |
|
419 %!test |
|
420 %! |
|
421 %! #solve small indefinite diagonal system |
|
422 %! #despite A is indefinite, the iteration continues and converges |
|
423 %! #indefiniteness of A is detected |
|
424 %! |
|
425 %! N = 10; |
|
426 %! A = diag([1:N].*(-ones(1,N).^2)); b = rand(N,1); X = A\b; #X is the true solution |
|
427 %! [x, flag] = pcg(A,b,[],N+1); |
|
428 %! assert(norm(x-X)/norm(X),0,1e-10); |
|
429 %! assert(flag,3); |
|
430 %! |
|
431 %!test |
|
432 %! |
|
433 %! #solve tridiagonal system, do not converge in default 20 iterations |
|
434 %! |
|
435 %! N = 100; |
|
436 %! A = zeros(N,N); |
|
437 %! for i=1:N-1 # form 1-D Laplacian matrix |
|
438 %! A(i:i+1,i:i+1) = [2 -1; -1 2]; |
|
439 %! endfor |
|
440 %! b = ones(N,1); X = A\b; #X is the true solution |
|
441 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,1e-12); |
|
442 %! assert(flag); |
|
443 %! assert(relres>1.0); |
|
444 %! assert(iter,20); #should perform max allowable default number of iterations |
|
445 %! |
|
446 %!test |
|
447 %! |
|
448 %! #solve tridiagonal system with 'prefect' preconditioner |
|
449 %! #converges in one iteration, so the eigest does not work |
|
450 %! #and issues a warning |
|
451 %! |
|
452 %! N = 100; |
|
453 %! A = zeros(N,N); |
|
454 %! for i=1:N-1 # form 1-D Laplacian matrix |
|
455 %! A(i:i+1,i:i+1) = [2 -1; -1 2]; |
|
456 %! endfor |
|
457 %! b = ones(N,1); X = A\b; #X is the true solution |
|
458 %! [x, flag, relres, iter, resvec, eigest] = pcg(A,b,[],[],A,b); |
|
459 %! assert(norm(x-X)/norm(X),0,1e-6); |
|
460 %! assert(flag,0); |
|
461 %! assert(iter,1); #should converge in one iteration |
|
462 %! assert(isnan(eigest),isnan([NaN NaN])); |
|
463 %! |