Debian Codegraph @

src/thirdparty/VLFeat/mathop.c

raw
1 /** @file mathop.c
2 ** @brief Math operations - Definition
3 ** @author Andrea Vedaldi, David Novotny
4 **/
5
6 /*
7 Copyright (C) 2014 Andrea Vedaldi.
8 Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
9 All rights reserved.
10
11 This file is part of the VLFeat library and is made available under
12 the terms of the BSD license (see the COPYING file).
13 */
14
15 /**
16 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
17 @page mathop Mathematical operations
18 @author Andrea Vedaldi
19 @author Brian Fulkerson
20 @tableofcontents
21 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
22
23 VLFeat include several low-level routines to speedup common
24 mathematical operations used throughout the library. Most are
25 collected in the @ref mathop.h module.
26
27 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
28 @section mathop-usage-vector-comparison Comparing vectors
29 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
30
31 @ref mathop.h includes a number of functions to quickly compute
32 distances or similarity of pairs of vector. Applications include
33 clustering and evaluation of SVM-like classifiers.
34
35 Use ::vl_get_vector_comparison_function_f or
36 ::vl_get_vector_comparison_function_d obtain an approprite function
37 to comprare vectors of floats or doubles, respectively. Such
38 functions are usually optimized (for instance, on X86 platforms they
39 use the SSE vector extension) and are several times faster than a
40 naive implementation. ::vl_eval_vector_comparison_on_all_pairs_f and
41 ::vl_eval_vector_comparison_on_all_pairs_d can be used to evaluate
42 the comparison function on all pairs of one or two sequences of
43 vectors.
44
45 Let @f$ \mathbf{x} = (x_1,\dots,x_d) @f$ and @f$ \mathbf{y} =
46 (y_1,\dots,y_d) @f$ be two vectors. The following comparison
47 functions are supported:
48
49 <table>
50 <tr>
51 <td>@f$ l^1 @f$</td>
52 <td>::VlDistanceL1</td>
53 <td>@f$ \sum_{i=1}^d |x_i - y_i| @f$</td>
54 <td>l1 distance (squared intersection metric)</td>
55 </tr>
56 <tr>
57 <td>@f$ l^2 @f$</td>
58 <td>::VlDistanceL2</td>
59 <td>@f$\sum_{i=1}^d (x_i - y_i)^2@f$</td>
60 <td>Squared Euclidean disance</td>
61 </tr>
62 <tr>
63 <td>@f$ \chi^2 @f$</td>
64 <td>::VlDistanceChi2</td>
65 <td>@f$\sum_{i=1}^d \frac{(x_i - y_i)^2}{x_i + y_i}@f$</td>
66 <td>Squared chi-square distance</td>
67 </tr>
68 <tr>
69 <td>-</td>
70 <td>::VlDistanceHellinger</td>
71 <td>@f$\sum_{i=1}^d (\sqrt{x_i} - \sqrt{y_i})^2@f$</td>
72 <td>Squared Hellinger's distance</td>
73 </tr>
74 <tr>
75 <td>-</td>
76 <td>::VlDistanceJS</td>
77 <td>@f$
78 \sum_{i=1}^d
79 \left(
80 x_i \log\frac{2x_i}{x_i+y_i}
81 + y_i \log\frac{2y_i}{x_i+y_i}
82 \right)
83 @f$
84 </td>
85 <td>Squared Jensen-Shannon distance</td>
86 </tr>
87 <tr>
88 <td>@f$ l^1 @f$</td>
89 <td>::VlKernelL1</td>
90 <td>@f$ \sum_{i=1}^d \min\{ x_i, y_i \} @f$</td>
91 <td>intersection kernel</td>
92 </tr>
93 <tr>
94 <td>@f$ l^2 @f$</td>
95 <td>::VlKernelL2</td>
96 <td>@f$\sum_{i=1}^d x_iy_i @f$</td>
97 <td>linear kernel</td>
98 </tr>
99 <tr>
100 <td>@f$ \chi^2 @f$</td>
101 <td>::VlKernelChi2</td>
102 <td>@f$\sum_{i=1}^d 2 \frac{x_iy_i}{x_i + y_i}@f$</td>
103 <td>chi-square kernel</td>
104 </tr>
105 <tr>
106 <td>-</td>
107 <td>::VlKernelHellinger</td>
108 <td>@f$\sum_{i=1}^d 2 \sqrt{x_i y_i}@f$</td>
109 <td>Hellinger's kernel (Bhattacharya coefficient)</td>
110 </tr>
111 <tr>
112 <td>-</td>
113 <td>::VlKernelJS</td>
114 <td>@f$
115 \sum_{i=1}^d
116 \left(
117 \frac{x_i}{2} \log_2\frac{x_i+y_i}{x_i}
118 + \frac{y_i}{2} \log_2\frac{x_i+y_i}{y_i}
119 \right)
120 @f$
121 </td>
122 <td>Jensen-Shannon kernel</td>
123 </tr>
124 </table>
125
126 @remark The definitions have been choosen so that corresponding kernels and
127 distances are related by the equation:
128 @f[
129 d^2(\mathbf{x},\mathbf{y})
130 =
131 k(\mathbf{x},\mathbf{x})
132 +k(\mathbf{y},\mathbf{y})
133 -k(\mathbf{x},\mathbf{y})
134 -k(\mathbf{y},\mathbf{x})
135 @f]
136 This means that each of these distances can be interpreted as a
137 squared distance or metric in the corresponding reproducing kernel
138 Hilbert space. Notice in particular that the @f$ l^1 @f$ or Manhattan
139 distance is also a <em>squared</em> distance in this sense.
140
141 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
142 @section mathop-integer-ops Fast basic functions operations
143 <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
144
145 In certain algorithm it is useful to quickly compute integer
146 approximation of certain mathematical operations. Presently, VLFeat
147 includes and implementations of:
148
149 - Fast single precision atan2: ::vl_fast_sqrt_f.
150 - Fast inverse square root: ::vl_fast_resqrt_f, ::vl_fast_resqrt_d.
151 - Fast square root: ::vl_fast_sqrt_f, ::vl_fast_sqrt_d.
152 - Fast integer square root: ::vl_fast_sqrt_ui16, ::vl_fast_sqrt_ui32,
153 ::vl_fast_sqrt_ui64 (see also @subpage mathop-sqrti).
154 **/
155
156 /** @fn vl_get_vector_comparison_function_f(VlVectorComparisonType)
157 **
158 ** @brief Get vector comparison function from comparison type
159 ** @param type vector comparison type.
160 ** @return comparison function.
161 **/
162
163 /** @fn vl_get_vector_comparison_function_d(VlVectorComparisonType)
164 ** @brief Get vector comparison function from comparison type
165 ** @sa vl_get_vector_comparison_function_f
166 **/
167
168 /** @fn vl_eval_vector_comparison_on_all_pairs_f(float*,vl_size,
169 ** float const*,vl_size,float const*,vl_size,VlFloatVectorComparisonFunction)
170 **
171 ** @brief Evaluate vector comparison function on all vector pairs
172 ** @param result comparison matrix (output).
173 ** @param dimension number of vector components (rows of @a X and @a Y).
174 ** @param X data matrix X.
175 ** @param Y data matrix Y.
176 ** @param numDataX number of vectors in @a X (columns of @a X)
177 ** @param numDataY number of vectros in @a Y (columns of @a Y)
178 ** @param function vector comparison function.
179 **
180 ** The function evaluates @a function on all pairs of columns
181 ** from matrices @a X and @a Y, filling a @a numDataX by @a numDataY
182 ** matrix.
183 **
184 ** If @a Y is a null pointer the function compares all columns from
185 ** @a X with themselves.
186 **/
187
188 /** @fn vl_eval_vector_comparison_on_all_pairs_d(double*,vl_size,
189 ** double const*,vl_size,double const*,vl_size,VlDoubleVectorComparisonFunction)
190 ** @brief Evaluate vector comparison function on all vector pairs
191 ** @sa vl_eval_vector_comparison_on_all_pairs_f
192 **/
193
194 /**
195 @page mathop-sqrti Fast integer square root algorithm
196 @tableofcontents
197
198 This section describes the fast integer square root algorithm used by
199 vl_fast_sqrt_ui8, ::vl_fast_sqrt_ui16, ::vl_fast_sqrt_ui32,
200 ::vl_fast_sqrt_ui64.
201
202 Given a non-negative integer $x \in \mathbb{Z}_+$, the goal of this
203 algorithm is to quickly compute the integer approximation of the
204 square root of an integer number:
205
206 \[
207 y = \max_{\bar y\in\mathbb{Z}} \bar y, \qquad \text{such that}\ \bar y^2 \leq x.
208 \]
209
210 Consider determining the k-th bit of $y$. To this end, decompose $y$
211 in three parts:
212
213 \[
214 y = y_{k+1} + q 2^k + r,
215 \qquad \text{where}\ y_{k+1} \geq 2^{k+1}, r < 2^k,
216 \]
217
218 and $q\in\{0,1\}$ is the bit to be determined. Here $y_{k+1}$ is a part
219 of the result $y$ that has already been determined, while the bit $q$
220 and the remainder $r$ are still unknown. Recall that the goal is to
221 find the largest $y^2$ such that $y^2 \leq x$. Expanding $y^2$ this
222 condition becomes
223
224 \[
225 q (2^{2k} + 2 y_{k+1} 2^k) + r(r + 2q 2^k + 2 y_{k+1}) \leq x - y_{k+1}^2.
226 \]
227
228 We can now determine if $q=1$ or $q=0$ based on the value of the
229 residual $x - y_{k+1}^2$. Specifically, $q=1$ requires that:
230
231 \[
232 \boxed{
233 2^{2k} + 2a2^k \leq x - y_{k+1}^2.
234 }
235 \]
236
237 On the other hand, if this equation is satisfied, then setting $r=0$
238 shows that there exists at least one $y$ such that $q=1$ and $y^2 \leq
239 x$. In particular, greedily choosing $q=1$ in $x=y_{k+1} + 2^k q + r$ is
240 optimal because $2^k > r$. This yields the algorithm:
241
242 1. Note that if $x$ is stored in $n$ bits and $n$ is even, then the
243 integer square root $y$ does not require more than $m = n / 2$ bit
244 to be stored. Thus the first bit to be determined is $k \leftarrow
245 m - 1 = n/2 - 1$ and $y_{n/2}=0$.
246 2. The algorithm stores and updates $y_k/2^{k}$ and $x - y_{k}^2$ for
247 convenience.
248 3. During iteration $k$, $y_k$ is determined. On entering the
249 iteration, the first step is to compute $y_{k+1}/2^k = 2
250 y_{k+1}/2^{k+1}$.
251 4. Then the bound $t = (2^{2k} + 2 y_{k+1})2^k = 2^{2k}(1 + 2
252 y_{k+1}/2^k)$.
253 5. If $t \geq x - y_{k+1}$, the $k$-th bit of $y_k$ is set to
254 one. This means applying the update $\hat y_{k}/2^k \leftarrow
255 y_{k+1}/2^k + 1$. This also requires computing $x - y_{k}^2
256 \leftarrow x - y_{k+1}^2 - t$.
257 6. Decrement $k \leftarrow k -1$ and, if $k\geq 0$, continue from 3.
258
259 **/
260
261 /* ---------------------------------------------------------------- */
262 #ifndef VL_MATHOP_INSTANTIATING
263
264 #include "mathop.h"
265 #include "mathop_sse2.h"
266 #include "mathop_avx.h"
267 #include <math.h>
268
269 #undef FLT
270 #define FLT VL_TYPE_FLOAT
271 #define VL_MATHOP_INSTANTIATING
272 #include "mathop.c"
273
274 #undef FLT
275 #define FLT VL_TYPE_DOUBLE
276 #define VL_MATHOP_INSTANTIATING
277 #include "mathop.c"
278 #endif
279
280 /* ---------------------------------------------------------------- */
281 #ifdef VL_MATHOP_INSTANTIATING
282 #include "float.h"
283
284 #undef COMPARISONFUNCTION_TYPE
285 #undef COMPARISONFUNCTION3_TYPE
286 #if (FLT == VL_TYPE_FLOAT)
287 # define COMPARISONFUNCTION_TYPE VlFloatVectorComparisonFunction
288 # define COMPARISONFUNCTION3_TYPE VlFloatVector3ComparisonFunction
289 #else
290 # define COMPARISONFUNCTION_TYPE VlDoubleVectorComparisonFunction
291 # define COMPARISONFUNCTION3_TYPE VlDoubleVector3ComparisonFunction
292 #endif
293
294 /* ---------------------------------------------------------------- */
295
296 VL_EXPORT T
297 VL_XCAT(_vl_distance_l2_, SFX)
298 (vl_size dimension, T const * X, T const * Y)
299 {
300 T const * X_end = X + dimension ;
301 T acc = 0.0 ;
302 while (X < X_end) {
303 T d = *X++ - *Y++ ;
304 acc += d * d ;
305 }
306 return acc ;
307 }
308
309 VL_EXPORT T
310 VL_XCAT(_vl_distance_l1_, SFX)
311 (vl_size dimension, T const * X, T const * Y)
312 {
313 T const * X_end = X + dimension ;
314 T acc = 0.0 ;
315 while (X < X_end) {
316 T d = *X++ - *Y++ ;
317 acc += VL_MAX(d, -d) ;
318 }
319 return acc ;
320 }
321
322 VL_EXPORT T
323 VL_XCAT(_vl_distance_chi2_, SFX)
324 (vl_size dimension, T const * X, T const * Y)
325 {
326 T const * X_end = X + dimension ;
327 T acc = 0.0 ;
328 while (X < X_end) {
329 T a = *X++ ;
330 T b = *Y++ ;
331 T delta = a - b ;
332 T denom = (a + b) ;
333 T numer = delta * delta ;
334 if (denom) {
335 T ratio = numer / denom ;
336 acc += ratio ;
337 }
338 }
339 return acc ;
340 }
341
342 VL_EXPORT T
343 VL_XCAT(_vl_distance_hellinger_, SFX)
344 (vl_size dimension, T const * X, T const * Y)
345 {
346 T const * X_end = X + dimension ;
347 T acc = 0.0 ;
348 while (X < X_end) {
349 T a = *X++ ;
350 T b = *Y++ ;
351 #if (FLT == VL_TYPE_FLOAT)
352 acc += a + b - 2.0 * sqrtf (a*b) ;
353 #else
354 acc += a + b - 2.0 * sqrt (a*b) ;
355 #endif
356 }
357 return acc ;
358 }
359
360 VL_EXPORT T
361 VL_XCAT(_vl_distance_js_, SFX)
362 (vl_size dimension, T const * X, T const * Y)
363 {
364 T const * X_end = X + dimension ;
365 T acc = 0.0 ;
366 while (X < X_end) {
367 T x = *X++ ;
368 T y = *Y++ ;
369 if (x) acc += x - x * VL_XCAT(vl_log2_,SFX)(1 + y/x) ;
370 if (y) acc += y - y * VL_XCAT(vl_log2_,SFX)(1 + x/y) ;
371 }
372 return acc ;
373 }
374
375 VL_EXPORT T
376 VL_XCAT(_vl_kernel_l2_, SFX)
377 (vl_size dimension, T const * X, T const * Y)
378 {
379 T const * X_end = X + dimension ;
380 T acc = 0.0 ;
381 while (X < X_end) {
382 T a = *X++ ;
383 T b = *Y++ ;
384 acc += a * b ;
385 }
386 return acc ;
387 }
388
389 VL_EXPORT T
390 VL_XCAT(_vl_kernel_l1_, SFX)
391 (vl_size dimension, T const * X, T const * Y)
392 {
393 T const * X_end = X + dimension ;
394 T acc = 0.0 ;
395 while (X < X_end) {
396 T a = *X++ ;
397 T b = *Y++ ;
398 T a_ = VL_XCAT(vl_abs_, SFX) (a) ;
399 T b_ = VL_XCAT(vl_abs_, SFX) (b) ;
400 acc += a_ + b_ - VL_XCAT(vl_abs_, SFX) (a - b) ;
401 }
402 return acc / ((T)2) ;
403 }
404
405 VL_EXPORT T
406 VL_XCAT(_vl_kernel_chi2_, SFX)
407 (vl_size dimension, T const * X, T const * Y)
408 {
409 T const * X_end = X + dimension ;
410 T acc = 0.0 ;
411 while (X < X_end) {
412 T a = *X++ ;
413 T b = *Y++ ;
414 T denom = (a + b) ;
415 if (denom) {
416 T numer = 2 * a * b ;
417 T ratio = numer / denom ;
418 acc += ratio ;
419 }
420 }
421 return acc ;
422 }
423
424 VL_EXPORT T
425 VL_XCAT(_vl_kernel_hellinger_, SFX)
426 (vl_size dimension, T const * X, T const * Y)
427 {
428 T const * X_end = X + dimension ;
429 T acc = 0.0 ;
430 while (X < X_end) {
431 T a = *X++ ;
432 T b = *Y++ ;
433 #if (FLT == VL_TYPE_FLOAT)
434 acc += sqrtf (a*b) ;
435 #else
436 acc += sqrt (a*b) ;
437 #endif
438 }
439 return acc ;
440 }
441
442 VL_EXPORT T
443 VL_XCAT(_vl_kernel_js_, SFX)
444 (vl_size dimension, T const * X, T const * Y)
445 {
446 T const * X_end = X + dimension ;
447 T acc = 0.0 ;
448 while (X < X_end) {
449 T x = *X++ ;
450 T y = *Y++ ;
451 if (x) acc += x * VL_XCAT(vl_log2_,SFX)(1 + y/x) ;
452 if (y) acc += y * VL_XCAT(vl_log2_,SFX)(1 + x/y) ;
453 }
454 return (T)0.5 * acc ;
455 }
456
457 VL_EXPORT T
458 VL_XCAT(_vl_distance_mahalanobis_sq_, SFX)
459 (vl_size dimension, T const * X, T const * MU, T const * S)
460 {
461 T const * X_end = X + dimension ;
462 T acc = 0.0 ;
463 while (X < X_end) {
464 T d = *X++ - *MU++ ;
465 acc += d * d * (*S++) ;
466 }
467 return acc ;
468 }
469
470 /* ---------------------------------------------------------------- */
471
472 VL_EXPORT COMPARISONFUNCTION_TYPE
473 VL_XCAT(vl_get_vector_comparison_function_, SFX)(VlVectorComparisonType type)
474 {
475 COMPARISONFUNCTION_TYPE function = 0 ;
476 switch (type) {
477 case VlDistanceL2 : function = VL_XCAT(_vl_distance_l2_, SFX) ; break ;
478 case VlDistanceL1 : function = VL_XCAT(_vl_distance_l1_, SFX) ; break ;
479 case VlDistanceChi2 : function = VL_XCAT(_vl_distance_chi2_, SFX) ; break ;
480 case VlDistanceHellinger : function = VL_XCAT(_vl_distance_hellinger_, SFX) ; break ;
481 case VlDistanceJS : function = VL_XCAT(_vl_distance_js_, SFX) ; break ;
482 case VlKernelL2 : function = VL_XCAT(_vl_kernel_l2_, SFX) ; break ;
483 case VlKernelL1 : function = VL_XCAT(_vl_kernel_l1_, SFX) ; break ;
484 case VlKernelChi2 : function = VL_XCAT(_vl_kernel_chi2_, SFX) ; break ;
485 case VlKernelHellinger : function = VL_XCAT(_vl_kernel_hellinger_, SFX) ; break ;
486 case VlKernelJS : function = VL_XCAT(_vl_kernel_js_, SFX) ; break ;
487 default: abort() ;
488 }
489
490 #ifndef VL_DISABLE_SSE2
491 /* if a SSE2 implementation is available, use it */
492 if (vl_cpu_has_sse2() && vl_get_simd_enabled()) {
493 switch (type) {
494 case VlDistanceL2 : function = VL_XCAT(_vl_distance_l2_sse2_, SFX) ; break ;
495 case VlDistanceL1 : function = VL_XCAT(_vl_distance_l1_sse2_, SFX) ; break ;
496 case VlDistanceChi2 : function = VL_XCAT(_vl_distance_chi2_sse2_, SFX) ; break ;
497 case VlKernelL2 : function = VL_XCAT(_vl_kernel_l2_sse2_, SFX) ; break ;
498 case VlKernelL1 : function = VL_XCAT(_vl_kernel_l1_sse2_, SFX) ; break ;
499 case VlKernelChi2 : function = VL_XCAT(_vl_kernel_chi2_sse2_, SFX) ; break ;
500 default: break ;
501 }
502 }
503 #endif
504
505 #ifndef VL_DISABLE_AVX
506 /* if an AVX implementation is available, use it */
507 if (vl_cpu_has_avx() && vl_get_simd_enabled()) {
508 switch (type) {
509 case VlDistanceL2 : function = VL_XCAT(_vl_distance_l2_avx_, SFX) ; break ;
510 default: break ;
511 }
512 }
513 #endif
514
515 return function ;
516 }
517
518 /* ---------------------------------------------------------------- */
519
520 VL_EXPORT COMPARISONFUNCTION3_TYPE
521 VL_XCAT(vl_get_vector_3_comparison_function_, SFX)(VlVectorComparisonType type)
522 {
523 COMPARISONFUNCTION3_TYPE function = 0 ;
524 switch (type) {
525 case VlDistanceMahalanobis : function = VL_XCAT(_vl_distance_mahalanobis_sq_, SFX) ; break ;
526 default: abort() ;
527 }
528
529 #ifndef VL_DISABLE_SSE2
530 /* if a SSE2 implementation is available, use it */
531 if (vl_cpu_has_sse2() && vl_get_simd_enabled()) {
532 switch (type) {
533 case VlDistanceMahalanobis : function = VL_XCAT(_vl_distance_mahalanobis_sq_sse2_, SFX) ; break ;
534 default: break ;
535 }
536 }
537 #endif
538
539 #ifndef VL_DISABLE_AVX
540 /* if an AVX implementation is available, use it */
541 if (vl_cpu_has_avx() && vl_get_simd_enabled()) {
542 switch (type) {
543 case VlDistanceMahalanobis : function = VL_XCAT(_vl_distance_mahalanobis_sq_avx_, SFX) ; break ;
544 default: break ;
545 }
546 }
547 #endif
548
549 return function ;
550 }
551
552 /* ---------------------------------------------------------------- */
553
554 VL_EXPORT void
555 VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)
556 (T * result, vl_size dimension,
557 T const * X, vl_size numDataX,
558 T const * Y, vl_size numDataY,
559 COMPARISONFUNCTION_TYPE function)
560 {
561 vl_uindex xi ;
562 vl_uindex yi ;
563
564 if (dimension == 0) return ;
565 if (numDataX == 0) return ;
566 assert (X) ;
567
568 if (Y) {
569 if (numDataY == 0) return ;
570 for (yi = 0 ; yi < numDataY ; ++ yi) {
571 for (xi = 0 ; xi < numDataX ; ++ xi) {
572 *result++ = (*function)(dimension, X, Y) ;
573 X += dimension ;
574 }
575 X -= dimension * numDataX ;
576 Y += dimension ;
577 }
578 } else {
579 T * resultTransp = result ;
580 Y = X ;
581 for (yi = 0 ; yi < numDataX ; ++ yi) {
582 for (xi = 0 ; xi <= yi ; ++ xi) {
583 T z = (*function)(dimension, X, Y) ;
584 X += dimension ;
585 *result = z ;
586 *resultTransp = z ;
587 result += 1 ;
588 resultTransp += numDataX ;
589 }
590 X -= dimension * (yi + 1) ;
591 Y += dimension ;
592 result += numDataX - (yi + 1) ;
593 resultTransp += 1 - (yi + 1) * numDataX ;
594 }
595 }
596 }
597
598 /* VL_MATHOP_INSTANTIATING */
599 #endif
600
601
602 /* ---------------------------------------------------------------- */
603 /* Numerical analysis */
604 /* ---------------------------------------------------------------- */
605
606 #ifndef VL_MATHOP_INSTANTIATING
607
608 /** @brief SVD of a 2x2 real matrix
609 ** @param S 2x2 real diagonal matrix of the singular values (out).
610 ** @param U first 2x2 real orthonormal matrix (out).
611 ** @param V second 2x2 real orthonormal matrix (out).
612 ** @param M 2x2 matrix.
613 **
614 ** The function comptues the SVD decomposition of the 2x2
615 ** real matrix @f$ M @f$:
616 ** @f[
617 ** M = U \operatorname S V^\top
618 ** @f]
619 ** where @f$ U @f$ and @f$ V @f$ are real orthonormal matrices
620 ** and @f$ S @f$ is the diagonal matrix of the singular values
621 ** in decreasing order.
622 **
623 ** @par Algorithm
624 **
625 ** The fist step is to find rotation matrices @f$ U_1 @f$ and
626 ** @f$ V_1 @f$ such taht
627 ** @f[
628 ** M = U_1 R V_1^\top, \quad
629 ** U_1 = \begin{barray} c_{u1} & - s_{u1} \\ s_{u1} & c_{u1} \end{barray}, \quad
630 ** V_1 = \begin{barray} c_{v1} & - s_{v1} \\ s_{v1} & c_{v1} \end{barray}, \quad
631 ** R = \begin{barray} f & g \\ 0 & h \end{barray}.
632 ** @f]
633 ** Gives a 2x2 triangular matrix. The second step is to call
634 ** ::vl_lapack_dlasv2 on the matrix @f$ R @f$ obtaining
635 ** @f[
636 ** M = U_1 (U_2 S V_2^\top) V_2.
637 ** @f]
638 **/
639
640 void
641 vl_svd2 (double* S, double *U, double *V, double const *M)
642 {
643 double m11 = M[0] ;
644 double m21 = M[1] ;
645 double m12 = M[2] ;
646 double m22 = M[3] ;
647 double cu1 = m11 ;
648 double su1 = m21 ;
649 double norm = sqrt(cu1*cu1 + su1*su1) ;
650 double cu2, su2, cv2, sv2 ;
651 double f, g, h ;
652 double smin, smax ;
653 cu1 /= norm ;
654 su1 /= norm ;
655
656 f = cu1 * m11 + su1 * m21 ;
657 g = cu1 * m12 + su1 * m22 ;
658 h = - su1 * m12 + cu1 * m22 ;
659
660 vl_lapack_dlasv2 (&smin, &smax,
661 &sv2, &cv2,
662 &su2, &cu2,
663 f, g, h) ;
664
665 assert(S) ;
666 S[0] = smax ;
667 S[1] = 0 ;
668 S[2] = 0 ;
669 S[3] = smin ;
670
671 if (U) {
672 U[0] = cu2*cu1 - su2*su1 ;
673 U[1] = su2*cu1 + cu2*su1 ;
674 U[2] = - cu2*su1 - su2*cu1 ;
675 U[3] = - su2*su1 + cu2*cu1 ;
676 }
677 if (V) {
678 V[0] = cv2 ;
679 V[1] = sv2 ;
680 V[2] = - sv2 ;
681 V[3] = cv2 ;
682 }
683 }
684
685 /** @brief SVD of a 2x2 upper triangular matrix (LAPACK @c dlasv2 equivalent)
686 ** @param smin smallest (in modulus) singular value (out).
687 ** @param smax largest (in modulus) singuarl value (out).
688 ** @param sv second component of the right singular vector of @c smax (out).
689 ** @param cv first component of the right singular vector of @c smax (out).
690 ** @param su second component of the left singular vector of @c smax (out).
691 ** @param cu first component of the left singular vector of @c smax (out).
692 ** @param f first entry of the upper triangular matrix.
693 ** @param g second entry of the upper triangular matrix.
694 ** @param h third entry of the upper triangular matrix.
695 **
696 ** @f[
697 ** \begin{bmatrix} f & g \\ 0 & h \end{bmatrix}
698 ** =
699 ** \begin{bmatrix} cv & - sv \\ sv & cv \end{bmatrix}
700 ** \begon{bmatrix} smax & 0 \\ 0 & smin \end{bmatrix}
701 ** \begin{bmatrix} cv & - sv \\ sv & cv \end{bmatrix}
702 ** @f]
703 **
704 ** Z.Bai and J.Demmel,
705 ** "Computing the Generalized Singular Value Decomposition",
706 ** SIAM J. Sci. Comput., Vol. 14, No. 6, pp. 1464-1486, November 1993
707 **/
708
709 #define isign(i) ((i)<0 ? (-1) : (+1)) /* integer sign function */
710 #define sign(x) ((x)<0.0 ? (-1) : (+1)) /* double sign function */
711
712 void
713 vl_lapack_dlasv2 (double *smin,
714 double *smax,
715 double *sv,
716 double *cv,
717 double *su,
718 double *cu,
719 double f,
720 double g,
721 double h)
722 {
723 double svt, cvt, sut, cut; /* temporary sv, cv, su, and cu */
724 double ft = f, gt = g, ht = h; /* temporary f, g, h */
725 double fa = fabs(f), ga = fabs(g), ha = fabs(h); /* |f|, |g|, and |h| */
726 int pmax = 1 ; /* pointer to max abs entry */
727 int swap = 0 ; /* is swapped */
728 int glarge = 0 ; /* is g very large */
729 int tsign ; /* tmp sign */
730 double fmh ; /* |f| -|h| */
731 double d ; /* (|f| -|h|)/|f| */
732 double dd ; /* d*d */
733 double q ; /* g/f */
734 double qq ; /* q*q */
735 double s ; /* (|f| + |h|)/|f| */
736 double ss ; /* s*s */
737 double spq ; /* sqrt(ss + qq) */
738 double dpq ; /* sqrt(dd + qq) */
739 double a ; /* (spq + dpq)/2 */
740 double tmp ; /* temporaries */
741 double tt;
742
743 /* make fa >= ha */
744 if (fa < ha) {
745 pmax = 3 ;
746 tmp =ft ; ft = ht ; ht = tmp ; /* swap ft and ht */
747 tmp =fa ; fa = ha ; ha = tmp ; /* swap fa and ha */
748 swap = 1 ;
749 }
750
751 if (ga == 0.0) { /* diagonal */
752 *smin = ha ;
753 *smax = fa ;
754 /* identity matrix */
755 cut = 1.0 ; sut = 0.0 ;
756 cvt = 1.0 ; svt = 0.0 ;
757 }
758 else { /* not diagonal */
759 if (ga > fa) { /* g is the largest entry */
760 pmax = 2 ;
761 if ((fa / ga) < VL_EPSILON_D) { /* g is very large */
762 glarge = 1 ;
763 *smax = ga ; /* 1 ulp */
764 if (ha > 1.0) {
765 *smin = fa / (ga / ha) ; /* 2 ulps */
766 } else {
767 *smin = (fa / ga) * ha ; /* 2 ulps */
768 }
769 cut = 1.0 ; sut = ht / gt ;
770 cvt = 1.0 ; svt = ft / gt ;
771 }
772 }
773
774 if (glarge == 0) { /* normal case */
775 fmh = fa - ha ; /* 1ulp */
776 if (fmh == fa) { /* cope with infinite f or h */
777 d = 1.0 ;
778 } else {
779 d = fmh / fa ; /* note 0<=d<=1.0, 2 ulps */
780 }
781 q = gt / ft ; /* note |q|<1/EPS, 1 ulp */
782 s = 2.0 - d ; /* note s>=1.0, 3 ulps */
783 dd = d*d ;
784 qq = q*q ;
785 ss = s*s ;
786 spq = sqrt(ss + qq) ; /* note 1<=spq<=1+1/EPS, 5 ulps */
787 if (d == 0.0) {
788 dpq = fabs(q) ; /* 0 ulp */
789 } else {
790 dpq = sqrt(dd + qq) ; /* note 0<=dpq<=1+1/EPS, 3.5 ulps */
791 }
792 a = 0.5 * (spq + dpq) ; /* note 1<=a<=1 + |q|, 6 ulps */
793 *smin = ha / a; /* 7 ulps */
794 *smax = fa * a; /* 7 ulps */
795 if (qq==0.0) { /* qq underflow */
796 if (d==0.0) {
797 tmp = sign(ft)*2*sign(gt); /* 0ulp */
798 }
799 else {
800 tmp = gt/(sign(ft)*fmh) + q/s; /* 6 ulps */
801 }
802 } else {
803 tmp = (q/(spq + s) + q/(dpq + d))*(1.0 + a); /* 17 ulps */
804 }
805 /* if qq */
806 tt = sqrt(tmp*tmp + 4.0) ; /* 18.5 ulps */
807 cvt = 2.0 / tt ; /* 19.5 ulps */
808 svt = tmp / tt ; /* 36.5 ulps */
809 cut = (cvt + svt*q) / a ; /* 46.5 ulps */
810 sut = (ht / ft) * svt / a ; /* 45.5 ulps */
811 } /* if g not large */
812 } /* if ga */
813 if (swap == 1) {
814 *cu = svt ; *su = cvt ;
815 *cv = sut ; *sv = cut ;
816 } else {
817 *cu = cut ; *su = sut ;
818 *cv = cvt ; *sv = svt ;
819 }
820 /* correct the signs of smax and smin */
821 if (pmax==1) { tsign = sign(*cv) * sign(*cu) * sign(f) ; }
822 if (pmax==2) { tsign = sign(*sv) * sign(*cu) * sign(g) ; }
823 if (pmax==3) { tsign = sign(*sv) * sign(*su) * sign(h) ; }
824 *smax = isign(tsign) * (*smax);
825 *smin = isign(tsign * sign(f) * sign(h)) * (*smin) ;
826 }
827
828
829 /** @brief Solve a 3x3 linear system
830 ** @param x result.
831 ** @param A system matrix.
832 ** @param b coefficients.
833 **
834 ** The function computes a solution to @f$ Ax =b @f$ for a 3x3
835 ** matrix.
836 **/
837
838 VL_EXPORT int
839 vl_solve_linear_system_3 (double * x, double const * A, double const *b)
840 {
841 int err ;
842 double M[3*4] ;
843 M[0] = A[0] ;
844 M[1] = A[1] ;
845 M[2] = A[2] ;
846 M[3] = A[3] ;
847 M[4] = A[4] ;
848 M[5] = A[5] ;
849 M[6] = A[6] ;
850 M[7] = A[7] ;
851 M[8] = A[8] ;
852 M[9] = b[0] ;
853 M[10] = b[1] ;
854 M[11] = b[2] ;
855 err = vl_gaussian_elimination(M,3,4) ;
856 x[0] = M[9] ;
857 x[1] = M[10] ;
858 x[2] = M[11] ;
859 return err ;
860 }
861
862 /** @brief Solve a 2x2 linear system
863 ** @param x result.
864 ** @param A system matrix.
865 ** @param b coefficients.
866 **
867 ** The function computes a solution to @f$ Ax =b @f$ for a 2x2
868 ** matrix.
869 **/
870
871 VL_EXPORT int
872 vl_solve_linear_system_2 (double * x, double const * A, double const *b)
873 {
874 int err ;
875 double M[2*3] ;
876 M[0] = A[0] ;
877 M[1] = A[1] ;
878 M[2] = A[2] ;
879 M[3] = A[3] ;
880 M[4] = b[0];
881 M[5] = b[1] ;
882 err = vl_gaussian_elimination(M,2,3) ;
883 x[0] = M[4] ;
884 x[1] = M[5] ;
885 return err ;
886 }
887
888 /** @brief Gaussian elimination
889 ** @param M matrix.
890 ** @param numRows number of rows of @c M.
891 ** @param numColumns number of columns of @c M.
892 **
893 ** The function runs Gaussian elimination with pivoting
894 ** on the matrix @a M in place.
895 ** @c numRows must be not larger than @c numColumns.
896 **
897 ** Let @f$ M = [A, b] @f$ to obtain the solution to the linear
898 ** system @f$ Ax=b @f$ (as the last column of @c M after
899 ** elimination).
900 **
901 ** Let @f$ M = [A, I] @f$ to compute the inverse of @c A in
902 ** a similar manner.
903 **/
904
905 VL_EXPORT vl_bool
906 vl_gaussian_elimination (double * A, vl_size numRows, vl_size numColumns)
907 {
908 vl_index i, j, ii, jj ;
909 assert(A) ;
910 assert(numRows <= numColumns) ;
911
912 #define Aat(i,j) A[(i) + (j)*numRows]
913
914 /* Gauss elimination */
915 for(j = 0 ; j < (signed)numRows ; ++j) {
916 double maxa = 0 ;
917 double maxabsa = 0 ;
918 vl_index maxi = -1 ;
919 double tmp ;
920
921 #if 0
922 {
923 vl_index iii, jjj ;
924 for (iii = 0 ; iii < 2 ; ++iii) {
925 for (jjj = 0 ; jjj < 3 ; ++jjj) {
926 VL_PRINTF("%5.2g ", Aat(iii,jjj)) ;
927
928 }
929 VL_PRINTF("\n") ;
930 }
931 VL_PRINTF("\n") ;
932 }
933 #endif
934
935 /* look for the maximally stable pivot */
936 for (i = j ; i < (signed)numRows ; ++i) {
937 double a = Aat(i,j) ;
938 double absa = vl_abs_d (a) ;
939 if (absa > maxabsa) {
940 maxa = a ;
941 maxabsa = absa ;
942 maxi = i ;
943 }
944 }
945 i = maxi ;
946
947 /* if singular give up */
948 if (maxabsa < 1e-10) return VL_ERR_OVERFLOW ;
949
950 /* swap j-th row with i-th row and normalize j-th row */
951 for(jj = j ; jj < (signed)numColumns ; ++jj) {
952 tmp = Aat(i,jj) ; Aat(i,jj) = Aat(j,jj) ; Aat(j,jj) = tmp ;
953 Aat(j,jj) /= maxa ;
954 }
955
956 #if 0
957 {
958 vl_index iii, jjj ;
959 VL_PRINTF("after swap %d %d\n", j, i);
960 for (iii = 0 ; iii < 2 ; ++iii) {
961 for (jjj = 0 ; jjj < 3 ; ++jjj) {
962 VL_PRINTF("%5.2g ", Aat(iii,jjj)) ;
963
964 }
965 VL_PRINTF("\n") ;
966 }
967 VL_PRINTF("\n") ;
968 }
969 #endif
970
971 /* elimination */
972 for (ii = j+1 ; ii < (signed)numRows ; ++ii) {
973 double x = Aat(ii,j) ;
974 for (jj = j ; jj < (signed)numColumns ; ++jj) {
975 Aat(ii,jj) -= x * Aat(j,jj) ;
976 }
977 }
978
979 #if 0
980 {
981 VL_PRINTF("after elimination\n");
982
983 vl_index iii, jjj ;
984 for (iii = 0 ; iii < 2 ; ++iii) {
985 for (jjj = 0 ; jjj < 3 ; ++jjj) {
986 VL_PRINTF("%5.2g ", Aat(iii,jjj)) ;
987
988 }
989 VL_PRINTF("\n") ;
990 }
991 VL_PRINTF("\n") ;
992 }
993 #endif
994
995 }
996
997 /* backward substitution */
998 for (i = numRows - 1 ; i > 0 ; --i) {
999 /* substitute in all rows above */
1000 for (ii = i - 1 ; ii >= 0 ; --ii) {
1001 double x = Aat(ii,i) ;
1002 /* j = numRows */
1003 for (j = numRows ; j < (signed)numColumns ; ++j) {
1004 Aat(ii,j) -= x * Aat(i,j) ;
1005 }
1006 }
1007 }
1008
1009 #if 0
1010 {
1011 VL_PRINTF("after substitution\n");
1012
1013 vl_index iii, jjj ;
1014 for (iii = 0 ; iii < 2 ; ++iii) {
1015 for (jjj = 0 ; jjj < 3 ; ++jjj) {
1016 VL_PRINTF("%5.2g ", Aat(iii,jjj)) ;
1017
1018 }
1019 VL_PRINTF("\n") ;
1020 }
1021 VL_PRINTF("\n") ;
1022 }
1023 #endif
1024
1025
1026 return VL_ERR_OK ;
1027 }
1028
1029 /* VL_MATHOP_INSTANTIATING */
1030 #endif
1031
1032 #undef VL_MATHOP_INSTANTIATING