forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vtkMath.cxx
3327 lines (2910 loc) · 84.9 KB
/
vtkMath.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMath.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================
Copyright 2011 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
license for use of this work by or on behalf of the
U.S. Government. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that this Notice and any
statement of authorship are reproduced on all copies.
Contact: pppebay@sandia.gov,dcthomp@sandia.gov,
=========================================================================*/
#include "vtkMath.h"
#include "vtkBoxMuellerRandomSequence.h"
#include "vtkDataArray.h"
#include "vtkDebugLeaks.h"
#include "vtkMinimalStandardRandomSequence.h"
#include "vtkObjectFactory.h"
#include "vtkTypeTraits.h"
#include <cassert>
#include <cmath>
#include <limits>
#include <vector>
vtkStandardNewMacro(vtkMath);
class vtkMathInternal : public vtkObjectBase
{
public:
vtkBaseTypeMacro(vtkMathInternal, vtkObjectBase);
static vtkMathInternal* New()
{
// Can't use object factory macros, since they cast to vtkObject*.
vtkMathInternal *ret = new vtkMathInternal;
ret->InitializeObjectBase();
return ret;
}
vtkMinimalStandardRandomSequence *Uniform;
vtkBoxMuellerRandomSequence *Gaussian;
std::vector<vtkTypeInt64> MemoizeFactorial;
private:
vtkMathInternal();
~vtkMathInternal() VTK_OVERRIDE;
};
vtkMathInternal::vtkMathInternal()
{
this->Gaussian=vtkBoxMuellerRandomSequence::New();
// This line assumes the current vtkBoxMuellerRandomSequence behavior:
// an initial vtkMinimalStandardRandomSequence is created.
this->Uniform=static_cast<vtkMinimalStandardRandomSequence *>(
this->Gaussian->GetUniformSequence());
this->Uniform->SetSeedOnly(1177); // One authors home address
this->MemoizeFactorial.resize(21, 0);
}
vtkMathInternal::~vtkMathInternal()
{
this->Gaussian->Delete();
}
vtkSmartPointer<vtkMathInternal> vtkMath::Internal = vtkSmartPointer<vtkMathInternal>::New();
#ifdef VTK_HAS_STD_NUMERIC_LIMITS
#include <limits>
#else // VTK_HAS_STD_NUMERIC_LIMITS
// Avoid aliasing optimization problems by using a union:
union vtkIEEE754Bits {
vtkTypeUInt64 i64v;
double d;
};
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x660)
// Borland C++ union initializers are broken.
// Use an otherwise-discouraged aliasing trick:
static vtkTypeUInt64 vtkMathNanBits = 0x7FF8000000000000i64;
static vtkTypeUInt64 vtkMathInfBits = 0x7FF0000000000000i64;
static vtkTypeUInt64 vtkMathNegInfBits = 0xFFF0000000000000i64;
#else
static union vtkIEEE754Bits vtkMathNanBits = { 0x7FF8000000000000LL };
static union vtkIEEE754Bits vtkMathInfBits = { 0x7FF0000000000000LL };
static union vtkIEEE754Bits vtkMathNegInfBits = { 0xFFF0000000000000LL };
#endif
#endif //VTK_HAS_STD_NUMERIC_LIMITS
#if defined(VTK_NON_FINITE_CAUSES_EXCEPTIONS)
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x660)
const vtkTypeInt64 vtkMathDoubleExponent = 0x7FF0000000000000i64;
const vtkTypeInt64 vtkMathDoubleMantissa = 0x000FFFFFFFFFFFFFi64;
#else
const vtkTypeInt64 vtkMathDoubleExponent = 0x7FF0000000000000LL;
const vtkTypeInt64 vtkMathDoubleMantissa = 0x000FFFFFFFFFFFFFLL;
#endif
#endif
//
// Some useful macros and functions
//
//----------------------------------------------------------------------------
// Return the lowest value "i" for which 2^i >= x
int vtkMath::CeilLog2(vtkTypeUInt64 x)
{
static const vtkTypeUInt64 t[6] = {
0xffffffff00000000ull,
0x00000000ffff0000ull,
0x000000000000ff00ull,
0x00000000000000f0ull,
0x000000000000000cull,
0x0000000000000002ull
};
int j = 32;
// if x is not a power of two, add 1 to final answer
// (this is the "ceil" part of the computation)
int y = (((x & (x - 1)) == 0) ? 0 : 1);
// loop through the table (this unrolls nicely)
for (int i = 0; i < 6; i++)
{
int k = (((x & t[i]) == 0) ? 0 : j);
y += k;
x >>= k;
j >>= 1;
}
return y;
}
//----------------------------------------------------------------------------
// Generate pseudo-random numbers distributed according to the uniform
// distribution between 0.0 and 1.0.
// This is used to provide portability across different systems.
double vtkMath::Random()
{
vtkMath::Internal->Uniform->Next();
return vtkMath::Internal->Uniform->GetValue();
}
//----------------------------------------------------------------------------
// Initialize seed value. NOTE: Random() has the bad property that
// the first random number returned after RandomSeed() is called
// is proportional to the seed value! To help solve this, call
// RandomSeed() a few times inside seed. This doesn't ruin the
// repeatability of Random().
//
void vtkMath::RandomSeed(int s)
{
vtkMath::Internal->Uniform->SetSeed(s);
}
//----------------------------------------------------------------------------
// Description:
// Return the current seed used by the random number generator.
int vtkMath::GetSeed()
{
return vtkMath::Internal->Uniform->GetSeed();
}
//----------------------------------------------------------------------------
double vtkMath::Random( double min, double max )
{
vtkMath::Internal->Uniform->Next();
return vtkMath::Internal->Uniform->GetRangeValue(min,max);
}
//----------------------------------------------------------------------------
double vtkMath::Gaussian()
{
vtkMath::Internal->Gaussian->Next();
return vtkMath::Internal->Gaussian->GetValue();
}
//----------------------------------------------------------------------------
double vtkMath::Gaussian( double mean, double std )
{
vtkMath::Internal->Gaussian->Next();
return vtkMath::Internal->Gaussian->GetScaledValue(mean,std);
}
//----------------------------------------------------------------------------
vtkTypeInt64 vtkMath::Factorial( int N )
{
if (N > 20)
{
vtkGenericWarningMacro("Factorial(" << N << ") would overflow.");
return vtkTypeTraits<vtkTypeInt64>::Max();
}
if (N == 0)
{
return 1;
}
if (vtkMath::Internal->MemoizeFactorial[N] != 0)
{
return vtkMath::Internal->MemoizeFactorial[N];
}
vtkTypeInt64 r = vtkMath::Factorial(N - 1) * N;
vtkMath::Internal->MemoizeFactorial[N] = r;
return r;
}
//----------------------------------------------------------------------------
// The number of combinations of n objects from a pool of m objects (m>n).
//
vtkTypeInt64 vtkMath::Binomial( int m, int n )
{
double r = 1;
for (int i = 1; i <= n; ++i)
{
r *= static_cast<double>(m - i + 1) / i;
}
return static_cast<vtkTypeInt64>(r);
}
//----------------------------------------------------------------------------
// Start iterating over "m choose n" objects.
// This function returns an array of n integers, each from 0 to m-1.
// These integers represent the n items chosen from the set [0,m[.
//
int* vtkMath::BeginCombination( int m, int n )
{
if ( m < n )
{
return 0;
}
int* r = new int[ n ];
for ( int i=0; i<n; ++i )
{
r[i] = i;
}
return r;
}
//----------------------------------------------------------------------------
// Given \a m, \a n, and a valid \a combination of \a n integers in
// the range [0,m[, this function alters the integers into the next
// combination in a sequence of all combinations of \a n items from
// a pool of \a m.
// If the \a combination is the last item in the sequence on input,
// then \a combination is unaltered and 0 is returned.
// Otherwise, 1 is returned and \a combination is updated.
//
int vtkMath::NextCombination( int m, int n, int* r )
{
int status = 0;
for (int i = n - 1; i >= 0; --i)
{
if (r[i] < m - n + i)
{
int j = r[i] + 1;
while (i < n)
{
r[i++] = j++;
}
status = 1;
break;
}
}
return status;
}
//----------------------------------------------------------------------------
// Free the "iterator" array created by vtkMath::BeginCombination.
//
void vtkMath::FreeCombination( int* r )
{
delete [] r;
}
//----------------------------------------------------------------------------
// Given a unit vector v1, find two other unit vectors v2 and v3 which
// which form an orthonormal set.
template<class T1, class T2, class T3>
inline void vtkMathPerpendiculars(const T1 v1[3], T2 v2[3], T3 v3[3],
double theta)
{
int dv1,dv2,dv3;
double v1sq = v1[0]*v1[0];
double v2sq = v1[1]*v1[1];
double v3sq = v1[2]*v1[2];
double r = sqrt(v1sq + v2sq + v3sq);
// transpose the vector to avoid divide-by-zero error
if (v1sq > v2sq && v1sq > v3sq)
{
dv1 = 0; dv2 = 1; dv3 = 2;
}
else if (v2sq > v3sq)
{
dv1 = 1; dv2 = 2; dv3 = 0;
}
else
{
dv1 = 2; dv2 = 0; dv3 = 1;
}
double a = v1[dv1]/r;
double b = v1[dv2]/r;
double c = v1[dv3]/r;
double tmp = sqrt(a*a+c*c);
if (theta != 0)
{
double sintheta = sin(theta);
double costheta = cos(theta);
if (v2)
{
v2[dv1] = (c*costheta - a*b*sintheta)/tmp;
v2[dv2] = sintheta*tmp;
v2[dv3] = (-a*costheta - b*c*sintheta)/tmp;
}
if (v3)
{
v3[dv1] = (-c*sintheta - a*b*costheta)/tmp;
v3[dv2] = costheta*tmp;
v3[dv3] = (a*sintheta - b*c*costheta)/tmp;
}
}
else
{
if (v2)
{
v2[dv1] = c/tmp;
v2[dv2] = 0;
v2[dv3] = -a/tmp;
}
if (v3)
{
v3[dv1] = -a*b/tmp;
v3[dv2] = tmp;
v3[dv3] = -b*c/tmp;
}
}
}
void vtkMath::Perpendiculars(const double v1[3], double v2[3], double v3[3],
double theta)
{
vtkMathPerpendiculars(v1, v2, v3, theta);
}
void vtkMath::Perpendiculars(const float v1[3], float v2[3], float v3[3],
double theta)
{
vtkMathPerpendiculars(v1, v2, v3, theta);
}
#define VTK_SMALL_NUMBER 1.0e-12
//----------------------------------------------------------------------------
// Solve linear equations Ax = b using Crout's method. Input is square matrix A
// and load vector x. Solution x is written over load vector. The dimension of
// the matrix is specified in size. If error is found, method returns a 0.
int vtkMath::SolveLinearSystem(double **A, double *x, int size)
{
// if we solving something simple, just solve it
//
if (size == 2)
{
double det, y[2];
det = vtkMath::Determinant2x2(A[0][0], A[0][1], A[1][0], A[1][1]);
static const double eps = 256*std::numeric_limits<double>::epsilon();
if (std::fabs(det) < eps)
{
// Unable to solve linear system
return 0;
}
y[0] = (A[1][1]*x[0] - A[0][1]*x[1]) / det;
y[1] = (-A[1][0]*x[0] + A[0][0]*x[1]) / det;
x[0] = y[0];
x[1] = y[1];
return 1;
}
else if (size == 1)
{
if (A[0][0] == 0.0)
{
// Unable to solve linear system
return 0;
}
x[0] /= A[0][0];
return 1;
}
//
// System of equations is not trivial, use Crout's method
//
// Check on allocation of working vectors
//
int *index, scratch[10];
index = ( size < 10 ? scratch : new int[size] );
//
// Factor and solve matrix
//
if ( vtkMath::LUFactorLinearSystem(A, index, size) == 0 )
{
return 0;
}
vtkMath::LUSolveLinearSystem(A,index,x,size);
if (size >= 10 ) delete [] index;
return 1;
}
//----------------------------------------------------------------------------
// Invert input square matrix A into matrix AI. Note that A is modified during
// the inversion. The size variable is the dimension of the matrix. Returns 0
// if inverse not computed.
int vtkMath::InvertMatrix(double **A, double **AI, int size)
{
int *index, iScratch[10];
double *column, dScratch[10];
// Check on allocation of working vectors
//
if ( size <= 10 )
{
index = iScratch;
column = dScratch;
}
else
{
index = new int[size];
column = new double[size];
}
int retVal = vtkMath::InvertMatrix(A, AI, size, index, column);
if ( size > 10 )
{
delete [] index;
delete [] column;
}
return retVal;
}
//----------------------------------------------------------------------------
// Factor linear equations Ax = b using LU decompostion A = LU where L is
// lower triangular matrix and U is upper triangular matrix. Input is
// square matrix A, integer array of pivot indices index[0->n-1], and size
// of square matrix n. Output factorization LU is in matrix A. If error is
// found, method returns 0.
int vtkMath::LUFactorLinearSystem(double **A, int *index, int size)
{
double scratch[10];
double *scale = (size<10 ? scratch : new double[size]);
int i, j, k;
int maxI = 0;
double largest, temp1, temp2, sum;
//
// Loop over rows to get implicit scaling information
//
for ( i = 0; i < size; i++ )
{
for ( largest = 0.0, j = 0; j < size; j++ )
{
if ( (temp2 = fabs(A[i][j])) > largest )
{
largest = temp2;
}
}
if ( largest == 0.0 )
{
vtkGenericWarningMacro(<<"Unable to factor linear system");
return 0;
}
scale[i] = 1.0 / largest;
}
//
// Loop over all columns using Crout's method
//
for ( j = 0; j < size; j++ )
{
for (i = 0; i < j; i++)
{
sum = A[i][j];
for ( k = 0; k < i; k++ )
{
sum -= A[i][k] * A[k][j];
}
A[i][j] = sum;
}
//
// Begin search for largest pivot element
//
for ( largest = 0.0, i = j; i < size; i++ )
{
sum = A[i][j];
for ( k = 0; k < j; k++ )
{
sum -= A[i][k] * A[k][j];
}
A[i][j] = sum;
if ( (temp1 = scale[i]*fabs(sum)) >= largest )
{
largest = temp1;
maxI = i;
}
}
//
// Check for row interchange
//
if ( j != maxI )
{
for ( k = 0; k < size; k++ )
{
temp1 = A[maxI][k];
A[maxI][k] = A[j][k];
A[j][k] = temp1;
}
scale[maxI] = scale[j];
}
//
// Divide by pivot element and perform elimination
//
index[j] = maxI;
if ( fabs(A[j][j]) <= VTK_SMALL_NUMBER )
{
vtkGenericWarningMacro(<<"Unable to factor linear system");
return 0;
}
if ( j != (size-1) )
{
temp1 = 1.0 / A[j][j];
for ( i = j + 1; i < size; i++ )
{
A[i][j] *= temp1;
}
}
}
if (size >= 10 ) delete [] scale;
return 1;
}
//----------------------------------------------------------------------------
// Solve linear equations Ax = b using LU decompostion A = LU where L is
// lower triangular matrix and U is upper triangular matrix. Input is
// factored matrix A=LU, integer array of pivot indices index[0->n-1],
// load vector x[0->n-1], and size of square matrix n. Note that A=LU and
// index[] are generated from method LUFactorLinearSystem). Also, solution
// vector is written directly over input load vector.
void vtkMath::LUSolveLinearSystem(double **A, int *index,
double *x, int size)
{
int i, j, ii, idx;
double sum;
//
// Proceed with forward and backsubstitution for L and U
// matrices. First, forward substitution.
//
for ( ii = -1, i = 0; i < size; i++ )
{
idx = index[i];
sum = x[idx];
x[idx] = x[i];
if ( ii >= 0 )
{
for ( j = ii; j <= (i-1); j++ )
{
sum -= A[i][j]*x[j];
}
}
else if (sum != 0.0)
{
ii = i;
}
x[i] = sum;
}
//
// Now, back substitution
//
for ( i = size-1; i >= 0; i-- )
{
sum = x[i];
for ( j = i + 1; j < size; j++ )
{
sum -= A[i][j]*x[j];
}
x[i] = sum / A[i][i];
}
}
#undef VTK_SMALL_NUMBER
#define VTK_ROTATE(a,i,j,k,l) g=a[i][j];h=a[k][l];a[i][j]=g-s*(h+g*tau);\
a[k][l]=h+s*(g-h*tau)
#define VTK_MAX_ROTATIONS 20
//#undef VTK_MAX_ROTATIONS
//#define VTK_MAX_ROTATIONS 50
// Jacobi iteration for the solution of eigenvectors/eigenvalues of a nxn
// real symmetric matrix. Square nxn matrix a; size of matrix in n;
// output eigenvalues in w; and output eigenvectors in v. Resulting
// eigenvalues/vectors are sorted in decreasing order; eigenvectors are
// normalized.
template<class T>
int vtkJacobiN(T **a, int n, T *w, T **v)
{
int i, j, k, iq, ip, numPos;
T tresh, theta, tau, t, sm, s, h, g, c, tmp;
T bspace[4], zspace[4];
T *b = bspace;
T *z = zspace;
// only allocate memory if the matrix is large
if (n > 4)
{
b = new T[n];
z = new T[n];
}
// initialize
for (ip=0; ip<n; ip++)
{
for (iq=0; iq<n; iq++)
{
v[ip][iq] = 0.0;
}
v[ip][ip] = 1.0;
}
for (ip=0; ip<n; ip++)
{
b[ip] = w[ip] = a[ip][ip];
z[ip] = 0.0;
}
// begin rotation sequence
for (i=0; i<VTK_MAX_ROTATIONS; i++)
{
sm = 0.0;
for (ip=0; ip<n-1; ip++)
{
for (iq=ip+1; iq<n; iq++)
{
sm += fabs(a[ip][iq]);
}
}
if (sm == 0.0)
{
break;
}
if (i < 3) // first 3 sweeps
{
tresh = 0.2*sm/(n*n);
}
else
{
tresh = 0.0;
}
for (ip=0; ip<n-1; ip++)
{
for (iq=ip+1; iq<n; iq++)
{
g = 100.0*fabs(a[ip][iq]);
// after 4 sweeps
if (i > 3 && (fabs(w[ip])+g) == fabs(w[ip])
&& (fabs(w[iq])+g) == fabs(w[iq]))
{
a[ip][iq] = 0.0;
}
else if (fabs(a[ip][iq]) > tresh)
{
h = w[iq] - w[ip];
if ( (fabs(h)+g) == fabs(h))
{
t = (a[ip][iq]) / h;
}
else
{
theta = 0.5*h / (a[ip][iq]);
t = 1.0 / (fabs(theta)+sqrt(1.0+theta*theta));
if (theta < 0.0)
{
t = -t;
}
}
c = 1.0 / sqrt(1+t*t);
s = t*c;
tau = s/(1.0+c);
h = t*a[ip][iq];
z[ip] -= h;
z[iq] += h;
w[ip] -= h;
w[iq] += h;
a[ip][iq]=0.0;
// ip already shifted left by 1 unit
for (j = 0;j <= ip-1;j++)
{
VTK_ROTATE(a,j,ip,j,iq);
}
// ip and iq already shifted left by 1 unit
for (j = ip+1;j <= iq-1;j++)
{
VTK_ROTATE(a,ip,j,j,iq);
}
// iq already shifted left by 1 unit
for (j=iq+1; j<n; j++)
{
VTK_ROTATE(a,ip,j,iq,j);
}
for (j=0; j<n; j++)
{
VTK_ROTATE(v,j,ip,j,iq);
}
}
}
}
for (ip=0; ip<n; ip++)
{
b[ip] += z[ip];
w[ip] = b[ip];
z[ip] = 0.0;
}
}
//// this is NEVER called
if ( i >= VTK_MAX_ROTATIONS )
{
vtkGenericWarningMacro(
"vtkMath::Jacobi: Error extracting eigenfunctions");
return 0;
}
// sort eigenfunctions these changes do not affect accuracy
for (j=0; j<n-1; j++) // boundary incorrect
{
k = j;
tmp = w[k];
for (i=j+1; i<n; i++) // boundary incorrect, shifted already
{
if (w[i] >= tmp) // why exchange if same?
{
k = i;
tmp = w[k];
}
}
if (k != j)
{
w[k] = w[j];
w[j] = tmp;
for (i=0; i<n; i++)
{
tmp = v[i][j];
v[i][j] = v[i][k];
v[i][k] = tmp;
}
}
}
// insure eigenvector consistency (i.e., Jacobi can compute vectors that
// are negative of one another (.707,.707,0) and (-.707,-.707,0). This can
// reek havoc in hyperstreamline/other stuff. We will select the most
// positive eigenvector.
int ceil_half_n = (n >> 1) + (n & 1);
for (j=0; j<n; j++)
{
for (numPos=0, i=0; i<n; i++)
{
if ( v[i][j] >= 0.0 )
{
numPos++;
}
}
// if ( numPos < ceil(double(n)/double(2.0)) )
if ( numPos < ceil_half_n)
{
for(i=0; i<n; i++)
{
v[i][j] *= -1.0;
}
}
}
if (n > 4)
{
delete [] b;
delete [] z;
}
return 1;
}
#undef VTK_ROTATE
#undef VTK_MAX_ROTATIONS
//----------------------------------------------------------------------------
int vtkMath::JacobiN(float **a, int n, float *w, float **v)
{
return vtkJacobiN(a,n,w,v);
}
//----------------------------------------------------------------------------
int vtkMath::JacobiN(double **a, int n, double *w, double **v)
{
return vtkJacobiN(a,n,w,v);
}
//----------------------------------------------------------------------------
// Jacobi iteration for the solution of eigenvectors/eigenvalues of a 3x3
// real symmetric matrix. Square 3x3 matrix a; output eigenvalues in w;
// and output eigenvectors in v. Resulting eigenvalues/vectors are sorted
// in decreasing order; eigenvectors are normalized.
int vtkMath::Jacobi(float **a, float *w, float **v)
{
return vtkMath::JacobiN(a, 3, w, v);
}
//----------------------------------------------------------------------------
int vtkMath::Jacobi(double **a, double *w, double **v)
{
return vtkMath::JacobiN(a, 3, w, v);
}
//----------------------------------------------------------------------------
// Estimate the condition number of a LU factored matrix. Used to judge the
// accuracy of the solution. The matrix A must have been previously factored
// using the method LUFactorLinearSystem. The condition number is the ratio
// of the infinity matrix norm (i.e., maximum value of matrix component)
// divided by the minimum diagonal value. (This works for triangular matrices
// only: see Conte and de Boor, Elementary Numerical Analysis.)
double vtkMath::EstimateMatrixCondition(double **A, int size)
{
int i;
int j;
double min=VTK_FLOAT_MAX, max=(-VTK_FLOAT_MAX);
// find the maximum value
for (i=0; i < size; i++)
{
for (j=i; j < size; j++)
{
if ( fabs(A[i][j]) > max )
{
max = fabs(A[i][j]);
}
}
}
// find the minimum diagonal value
for (i=0; i < size; i++)
{
if ( fabs(A[i][i]) < min )
{
min = fabs(A[i][i]);
}
}
if ( min == 0.0 )
{
return VTK_FLOAT_MAX;
}
else
{
return (max/min);
}
}
//----------------------------------------------------------------------------
// Solves for the least squares best fit matrix for the homogeneous equation X'M' = 0'.
// Uses the method described on pages 40-41 of Computer Vision by
// Forsyth and Ponce, which is that the solution is the eigenvector
// associated with the minimum eigenvalue of T(X)X, where T(X) is the
// transpose of X.
// The inputs and output are transposed matrices.
// Dimensions: X' is numberOfSamples by xOrder,
// M' dimension is xOrder by 1.
// M' should be pre-allocated. All matrices are row major. The resultant
// matrix M' should be pre-multiplied to X' to get 0', or transposed and
// then post multiplied to X to get 0
int vtkMath::SolveHomogeneousLeastSquares(int numberOfSamples, double **xt, int xOrder,
double **mt)
{
// check dimensional consistency
if (numberOfSamples < xOrder)
{
vtkGenericWarningMacro("Insufficient number of samples. Underdetermined.");
return 0;
}
int i, j, k;
// set up intermediate variables
// Allocate matrix to hold X times transpose of X
double **XXt = new double *[xOrder]; // size x by x
// Allocate the array of eigenvalues and eigenvectors
double *eigenvals = new double [xOrder];
double **eigenvecs = new double *[xOrder];
// Clear the upper triangular region (and btw, allocate the eigenvecs as well)
for (i = 0; i < xOrder; i++)
{
eigenvecs[i] = new double[xOrder];
XXt[i] = new double[xOrder];
for (j = 0; j < xOrder; j++)
{
XXt[i][j] = 0.0;
}
}
// Calculate XXt upper half only, due to symmetry
for (k = 0; k < numberOfSamples; k++)
{
for (i = 0; i < xOrder; i++)
{
for (j = i; j < xOrder; j++)
{
XXt[i][j] += xt[k][i] * xt[k][j];
}
}
}
// now fill in the lower half of the XXt matrix
for (i = 0; i < xOrder; i++)
{
for (j = 0; j < i; j++)
{
XXt[i][j] = XXt[j][i];
}
}
// Compute the eigenvectors and eigenvalues
vtkMath::JacobiN(XXt, xOrder, eigenvals, eigenvecs);
// Smallest eigenval is at the end of the list (xOrder-1), and solution is
// corresponding eigenvec.
for (i=0; i<xOrder; i++)
{
mt[i][0] = eigenvecs[i][xOrder-1];
}
// Clean up:
for (i=0; i<xOrder; i++)
{
delete [] XXt[i];
delete [] eigenvecs[i];
}
delete [] XXt;
delete [] eigenvecs;
delete [] eigenvals;
return 1;
}