]> granicus.if.org Git - imagemagick/blob - MagickCore/matrix.c
(no commit message)
[imagemagick] / MagickCore / matrix.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                  M   M   AAA   TTTTT  RRRR   IIIII  X   X                   %
7 %                  MM MM  A   A    T    R   R    I     X X                    %
8 %                  M M M  AAAAA    T    RRRR     I      X                     %
9 %                  M   M  A   A    T    R R      I     X X                    %
10 %                  M   M  A   A    T    R  R   IIIII  X   X                   %
11 %                                                                             %
12 %                                                                             %
13 %                         MagickCore Matrix Methods                           %
14 %                                                                             %
15 %                            Software Design                                  %
16 %                              John Cristy                                    %
17 %                              August 2007                                    %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/matrix.h"
44 #include "MagickCore/memory_.h"
45 #include "MagickCore/utility.h"
46 \f
47 /*
48 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49 %                                                                             %
50 %                                                                             %
51 %                                                                             %
52 %   A c q u i r e M a g i c k M a t r i x                                     %
53 %                                                                             %
54 %                                                                             %
55 %                                                                             %
56 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
57 %
58 %  AcquireMagickMatrix() allocates and returns a matrix in the form of an
59 %  array of pointers to an array of doubles, with all values pre-set to zero.
60 %
61 %  This used to generate the two dimensional matrix, and vectors required
62 %  for the GaussJordanElimination() method below, solving some system of
63 %  simultanious equations.
64 %
65 %  The format of the AcquireMagickMatrix method is:
66 %
67 %      double **AcquireMagickMatrix(const size_t number_rows,
68 %        const size_t size)
69 %
70 %  A description of each parameter follows:
71 %
72 %    o number_rows: the number pointers for the array of pointers
73 %      (first dimension).
74 %
75 %    o size: the size of the array of doubles each pointer points to
76 %      (second dimension).
77 %
78 */
79 MagickExport double **AcquireMagickMatrix(const size_t number_rows,
80   const size_t size)
81 {
82   double
83     **matrix;
84
85   register ssize_t
86     i,
87     j;
88
89   matrix=(double **) AcquireQuantumMemory(number_rows,sizeof(*matrix));
90   if (matrix == (double **) NULL)
91     return((double **)NULL);
92   for (i=0; i < (ssize_t) number_rows; i++)
93   {
94     matrix[i]=(double *) AcquireQuantumMemory(size,sizeof(*matrix[i]));
95     if (matrix[i] == (double *) NULL)
96     {
97       for (j=0; j < i; j++)
98         matrix[j]=(double *) RelinquishMagickMemory(matrix[j]);
99       matrix=(double **) RelinquishMagickMemory(matrix);
100       return((double **) NULL);
101     }
102     for (j=0; j < (ssize_t) size; j++)
103       matrix[i][j]=0.0;
104   }
105   return(matrix);
106 }
107 \f
108 /*
109 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
110 %                                                                             %
111 %                                                                             %
112 %                                                                             %
113 %   G a u s s J o r d a n E l i m i n a t i o n                               %
114 %                                                                             %
115 %                                                                             %
116 %                                                                             %
117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
118 %
119 %  GaussJordanElimination() returns a matrix in reduced row echelon form,
120 %  while simultaneously reducing and thus solving the augumented results
121 %  matrix.
122 %
123 %  See also  http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
124 %
125 %  The format of the GaussJordanElimination method is:
126 %
127 %      MagickBooleanType GaussJordanElimination(double **matrix,double **vectors,
128 %        const size_t rank,const size_t number_vectors)
129 %
130 %  A description of each parameter follows:
131 %
132 %    o matrix: the matrix to be reduced, as an 'array of row pointers'.
133 %
134 %    o vectors: the additional matrix argumenting the matrix for row reduction.
135 %             Producing an 'array of column vectors'.
136 %
137 %    o rank:  The size of the matrix (both rows and columns).
138 %             Also represents the number terms that need to be solved.
139 %
140 %    o number_vectors: Number of vectors columns, argumenting the above matrix.
141 %             Usally 1, but can be more for more complex equation solving.
142 %
143 %  Note that the 'matrix' is given as a 'array of row pointers' of rank size.
144 %  That is values can be assigned as   matrix[row][column]   where 'row' is
145 %  typically the equation, and 'column' is the term of the equation.
146 %  That is the matrix is in the form of a 'row first array'.
147 %
148 %  However 'vectors' is a 'array of column pointers' which can have any number
149 %  of columns, with each column array the same 'rank' size as 'matrix'.
150 %
151 %  This allows for simpler handling of the results, especially is only one
152 %  column 'vector' is all that is required to produce the desired solution.
153 %
154 %  For example, the 'vectors' can consist of a pointer to a simple array of
155 %  doubles.  when only one set of simultanious equations is to be solved from
156 %  the given set of coefficient weighted terms.
157 %
158 %     double **matrix = AcquireMagickMatrix(8UL,8UL);
159 %     double coefficents[8];
160 %     ...
161 %     GaussJordanElimination(matrix, &coefficents, 8UL, 1UL);
162 %
163 %  However by specifing more 'columns' (as an 'array of vector columns',
164 %  you can use this function to solve a set of 'separable' equations.
165 %
166 %  For example a distortion function where    u = U(x,y)   v = V(x,y)
167 %  And the functions U() and V() have separate coefficents, but are being
168 %  generated from a common x,y->u,v  data set.
169 %
170 %  Another example is generation of a color gradient from a set of colors
171 %  at specific coordients, such as a list    x,y -> r,g,b,a
172 %  (Reference to be added - Anthony)
173 %
174 %  You can also use the 'vectors' to generate an inverse of the given 'matrix'
175 %  though as a 'column first array' rather than a 'row first array'. For
176 %  details see    http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
177 %
178 */
179 MagickExport MagickBooleanType GaussJordanElimination(double **matrix,
180   double **vectors,const size_t rank,const size_t number_vectors)
181 {
182 #define GaussJordanSwap(x,y) \
183 { \
184   if ((x) != (y)) \
185     { \
186       (x)+=(y); \
187       (y)=(x)-(y); \
188       (x)=(x)-(y); \
189     } \
190 }
191
192   double
193     max,
194     scale;
195
196   register ssize_t
197     i,
198     j,
199     k;
200
201   ssize_t
202     column,
203     *columns,
204     *pivots,
205     row,
206     *rows;
207
208   columns=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*columns));
209   rows=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*rows));
210   pivots=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*pivots));
211   if ((rows == (ssize_t *) NULL) || (columns == (ssize_t *) NULL) ||
212       (pivots == (ssize_t *) NULL))
213     {
214       if (pivots != (ssize_t *) NULL)
215         pivots=(ssize_t *) RelinquishMagickMemory(pivots);
216       if (columns != (ssize_t *) NULL)
217         columns=(ssize_t *) RelinquishMagickMemory(columns);
218       if (rows != (ssize_t *) NULL)
219         rows=(ssize_t *) RelinquishMagickMemory(rows);
220       return(MagickFalse);
221     }
222   (void) ResetMagickMemory(columns,0,rank*sizeof(*columns));
223   (void) ResetMagickMemory(rows,0,rank*sizeof(*rows));
224   (void) ResetMagickMemory(pivots,0,rank*sizeof(*pivots));
225   column=0;
226   row=0;
227   for (i=0; i < (ssize_t) rank; i++)
228   {
229     max=0.0;
230     for (j=0; j < (ssize_t) rank; j++)
231       if (pivots[j] != 1)
232         {
233           for (k=0; k < (ssize_t) rank; k++)
234             if (pivots[k] != 0)
235               {
236                 if (pivots[k] > 1)
237                   return(MagickFalse);
238               }
239             else
240               if (fabs(matrix[j][k]) >= max)
241                 {
242                   max=fabs(matrix[j][k]);
243                   row=j;
244                   column=k;
245                 }
246         }
247     pivots[column]++;
248     if (row != column)
249       {
250         for (k=0; k < (ssize_t) rank; k++)
251           GaussJordanSwap(matrix[row][k],matrix[column][k]);
252         for (k=0; k < (ssize_t) number_vectors; k++)
253           GaussJordanSwap(vectors[k][row],vectors[k][column]);
254       }
255     rows[i]=row;
256     columns[i]=column;
257     if (matrix[column][column] == 0.0)
258       return(MagickFalse);  /* sigularity */
259     scale=1.0/matrix[column][column];
260     matrix[column][column]=1.0;
261     for (j=0; j < (ssize_t) rank; j++)
262       matrix[column][j]*=scale;
263     for (j=0; j < (ssize_t) number_vectors; j++)
264       vectors[j][column]*=scale;
265     for (j=0; j < (ssize_t) rank; j++)
266       if (j != column)
267         {
268           scale=matrix[j][column];
269           matrix[j][column]=0.0;
270           for (k=0; k < (ssize_t) rank; k++)
271             matrix[j][k]-=scale*matrix[column][k];
272           for (k=0; k < (ssize_t) number_vectors; k++)
273             vectors[k][j]-=scale*vectors[k][column];
274         }
275   }
276   for (j=(ssize_t) rank-1; j >= 0; j--)
277     if (columns[j] != rows[j])
278       for (i=0; i < (ssize_t) rank; i++)
279         GaussJordanSwap(matrix[i][rows[j]],matrix[i][columns[j]]);
280   pivots=(ssize_t *) RelinquishMagickMemory(pivots);
281   rows=(ssize_t *) RelinquishMagickMemory(rows);
282   columns=(ssize_t *) RelinquishMagickMemory(columns);
283   return(MagickTrue);
284 }
285 \f
286 /*
287 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
288 %                                                                             %
289 %                                                                             %
290 %                                                                             %
291 %   L e a s t S q u a r e s A d d T e r m s                                   %
292 %                                                                             %
293 %                                                                             %
294 %                                                                             %
295 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
296 %
297 %  LeastSquaresAddTerms() adds one set of terms and associate results to the
298 %  given matrix and vectors for solving using least-squares function fitting.
299 %
300 %  The format of the AcquireMagickMatrix method is:
301 %
302 %      void LeastSquaresAddTerms(double **matrix,double **vectors,
303 %        const double *terms,const double *results,const size_t rank,
304 %        const size_t number_vectors);
305 %
306 %  A description of each parameter follows:
307 %
308 %    o matrix: the square matrix to add given terms/results to.
309 %
310 %    o vectors: the result vectors to add terms/results to.
311 %
312 %    o terms: the pre-calculated terms (without the unknown coefficent
313 %             weights) that forms the equation being added.
314 %
315 %    o results: the result(s) that should be generated from the given terms
316 %               weighted by the yet-to-be-solved coefficents.
317 %
318 %    o rank: the rank or size of the dimentions of the square matrix.
319 %            Also the length of vectors, and number of terms being added.
320 %
321 %    o number_vectors: Number of result vectors, and number or results being
322 %      added.  Also represents the number of separable systems of equations
323 %      that is being solved.
324 %
325 %  Example of use...
326 %
327 %     2 dimensional Affine Equations (which are separable)
328 %         c0*x + c2*y + c4*1 => u
329 %         c1*x + c3*y + c5*1 => v
330 %
331 %     double **matrix = AcquireMagickMatrix(3UL,3UL);
332 %     double **vectors = AcquireMagickMatrix(2UL,3UL);
333 %     double terms[3], results[2];
334 %     ...
335 %     for each given x,y -> u,v
336 %        terms[0] = x;
337 %        terms[1] = y;
338 %        terms[2] = 1;
339 %        results[0] = u;
340 %        results[1] = v;
341 %        LeastSquaresAddTerms(matrix,vectors,terms,results,3UL,2UL);
342 %     ...
343 %     if ( GaussJordanElimination(matrix,vectors,3UL,2UL) ) {
344 %       c0 = vectors[0][0];
345 %       c2 = vectors[0][1];
346 %       c4 = vectors[0][2];
347 %       c1 = vectors[1][0];
348 %       c3 = vectors[1][1];
349 %       c5 = vectors[1][2];
350 %     }
351 %     else
352 %       printf("Matrix unsolvable\n);
353 %     RelinquishMagickMatrix(matrix,3UL);
354 %     RelinquishMagickMatrix(vectors,2UL);
355 %
356 */
357 MagickExport void LeastSquaresAddTerms(double **matrix,double **vectors,
358   const double *terms,const double *results,const size_t rank,
359   const size_t number_vectors)
360 {
361   register ssize_t
362     i,
363     j;
364
365   for (j=0; j < (ssize_t) rank; j++)
366   {
367     for (i=0; i < (ssize_t) rank; i++)
368       matrix[i][j]+=terms[i]*terms[j];
369     for (i=0; i < (ssize_t) number_vectors; i++)
370       vectors[i][j]+=results[i]*terms[j];
371   }
372   return;
373 }
374 \f
375 /*
376 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
377 %                                                                             %
378 %                                                                             %
379 %                                                                             %
380 %   R e l i n q u i s h M a g i c k M a t r i x                               %
381 %                                                                             %
382 %                                                                             %
383 %                                                                             %
384 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
385 %
386 %  RelinquishMagickMatrix() frees the previously acquired matrix (array of
387 %  pointers to arrays of doubles).
388 %
389 %  The format of the RelinquishMagickMatrix method is:
390 %
391 %      double **RelinquishMagickMatrix(double **matrix,
392 %        const size_t number_rows)
393 %
394 %  A description of each parameter follows:
395 %
396 %    o matrix: the matrix to relinquish
397 %
398 %    o number_rows: the first dimension of the acquired matrix (number of
399 %      pointers)
400 %
401 */
402 MagickExport double **RelinquishMagickMatrix(double **matrix,
403   const size_t number_rows)
404 {
405   register ssize_t
406     i;
407
408   if (matrix == (double **) NULL )
409     return(matrix);
410   for (i=0; i < (ssize_t) number_rows; i++)
411      matrix[i]=(double *) RelinquishMagickMemory(matrix[i]);
412   matrix=(double **) RelinquishMagickMemory(matrix);
413   return(matrix);
414 }
415