Changeset 477 for library/tests
- Timestamp:
- 08/05/09 14:40:03 (16 years ago)
- Location:
- library/tests
- Files:
-
- 89 modified
Legend:
- Unmodified
- Added
- Removed
-
TabularUnified library/tests/additive_generator.cpp ¶
r467 r477 5 5 using bdm::UI; 6 6 7 void additive_generator::from_setting (const Setting &set) {8 9 UI::get(sz, set, "size");7 void additive_generator::from_setting ( const Setting &set ) { 8 int sz; 9 UI::get ( sz, set, "size" ); 10 10 11 mat a0 = randu(sz, sz);12 13 vec v = randu(sz);14 v2 = outer_product(v, v);11 mat a0 = randu ( sz, sz ); 12 a = a0 * a0.T(); 13 vec v = randu ( sz ); 14 v2 = outer_product ( v, v ); 15 15 16 if (set.exists("lambda")) {17 UI::get(lambda, set, "lambda");18 16 if ( set.exists ( "lambda" ) ) { 17 UI::get ( lambda, set, "lambda" ); 18 } 19 19 } 20 20 21 21 mat additive_generator::next() { 22 23 a = (1 - lambda) * a + lambda * v2;24 22 mat b = a; 23 a = ( 1 - lambda ) * a + lambda * v2; 24 return b; 25 25 } -
TabularUnified library/tests/additive_generator.h ¶
r467 r477 19 19 /*! Iteratively adds squared random vector to a random matrix. 20 20 */ 21 class additive_generator : public generator 22 { 21 class additive_generator : public generator { 23 22 private: 24 25 26 23 itpp::mat a; 24 itpp::mat v2; 25 double lambda; 27 26 28 27 public: 29 additive_generator():lambda(0.5) { }28 additive_generator() : lambda ( 0.5 ) { } 30 29 31 30 itpp::mat next(); 32 31 33 34 35 36 37 38 39 40 void from_setting(const Setting &set);32 //! Load from structure with elements: 33 //! \code 34 //! { size = 7; // size (rows == cols) of the generated matrix 35 //! lambda = 0.5; // weight of the added vector 36 //! } 37 //! \endcode 38 //! size is mandatory, lambda optional (with default as shown). 39 void from_setting ( const Setting &set ); 41 40 }; 42 41 -
TabularUnified library/tests/arx_elem_test.cpp ¶
r386 r477 3 3 4 4 int main() { 5 // Setup model : ARX for 1D Gaussian 5 // Setup model : ARX for 1D Gaussian 6 6 //Test constructor 7 mat V0 = 0.00001*eye(2); V0(0,0)= 0.1; // 8 ARX Ar; Ar.set_statistics(1, V0, -1.0); 9 10 mat mu(1,1); 11 mat R(1,1); 12 Ar._e()->mean_mat(mu,R); 13 cout << "Prior moments: mu="<< mu << ", R=" << R <<endl; 14 7 mat V0 = 0.00001 * eye ( 2 ); 8 V0 ( 0, 0 ) = 0.1; // 9 ARX Ar; 10 Ar.set_statistics ( 1, V0, -1.0 ); 11 12 mat mu ( 1, 1 ); 13 mat R ( 1, 1 ); 14 Ar._e()->mean_mat ( mu, R ); 15 cout << "Prior moments: mu=" << mu << ", R=" << R << endl; 16 15 17 int ndat = 200; 16 vec smp =randn(ndat);18 vec smp = randn ( ndat ); 17 19 // 18 mat Smp =ones(2,ndat);19 Smp.set_row (0,smp);20 mat Smp = ones ( 2, ndat ); 21 Smp.set_row ( 0, smp ); 20 22 // 21 Ar.bayesB (Smp);23 Ar.bayesB ( Smp ); 22 24 // Ar is now filled with estimates of N(0,1); 23 cout << "Empirical moments: mu=" << sum (smp)/ndat << ", R=" << sum_sqr(smp)/ndat - pow(sum(smp)/ndat,2) << endl;24 Ar._e()->mean_mat (mu,R);25 cout << "Posterior moments: mu=" << mu << ", R=" << R <<endl;26 25 cout << "Empirical moments: mu=" << sum ( smp ) / ndat << ", R=" << sum_sqr ( smp ) / ndat - pow ( sum ( smp ) / ndat, 2 ) << endl; 26 Ar._e()->mean_mat ( mu, R ); 27 cout << "Posterior moments: mu=" << mu << ", R=" << R << endl; 28 27 29 //////// TEST prediction 28 vec x =linspace(-3.0,3.0,100);29 double xstep = 6.0 /100.0;30 mat X (1,100);31 mat X2 (2,100);32 X.set_row (0,x);33 X2.set_row (0,x);34 30 vec x = linspace ( -3.0, 3.0, 100 ); 31 double xstep = 6.0 / 100.0; 32 mat X ( 1, 100 ); 33 mat X2 ( 2, 100 ); 34 X.set_row ( 0, x ); 35 X2.set_row ( 0, x ); 36 35 37 mlstudent* Ap = Ar.predictor_student(); 36 vec Ap_x =Ap->evallogcond_m(X,vec_1(1.0));37 vec ll_x = Ar.logpred_m (X2);38 39 cout << "normalize : " << xstep*sum (exp(Ap_x)) << endl;40 cout << "normalize : " << xstep*sum (exp(ll_x)) << endl;41 42 it_file it ("arx_elem_test.it");43 it << Name ("Ap_x") << Ap_x;44 it << Name ("ll_x") << ll_x;38 vec Ap_x = Ap->evallogcond_m ( X, vec_1 ( 1.0 ) ); 39 vec ll_x = Ar.logpred_m ( X2 ); 40 41 cout << "normalize : " << xstep*sum ( exp ( Ap_x ) ) << endl; 42 cout << "normalize : " << xstep*sum ( exp ( ll_x ) ) << endl; 43 44 it_file it ( "arx_elem_test.it" ); 45 it << Name ( "Ap_x" ) << Ap_x; 46 it << Name ( "ll_x" ) << ll_x; 45 47 } -
TabularUnified library/tests/arx_test.cpp ¶
r386 r477 1 1 /*! 2 \file 2 \file 3 3 \brief Test of basic elements of the ARX class 4 4 … … 17 17 // Setup model 18 18 vec th ( "0.8 -0.3 0.4 0.01" ); 19 int ord =th.length(); //auxiliary variable20 double sqr =0.1;19 int ord = th.length(); //auxiliary variable 20 double sqr = 0.1; 21 21 22 22 //Test constructor 23 mat V0 = 0.00001*eye ( ord+1 ); V0 ( 0.0 ) = 1; // 24 double nu0 = ord+5.0; 23 mat V0 = 0.00001 * eye ( ord + 1 ); 24 V0 ( 0.0 ) = 1; // 25 double nu0 = ord + 5.0; 25 26 26 27 ARX Ar; 27 Ar.set_statistics (1, V0, nu0 );// Estimator28 Ar.set_statistics ( 1, V0, nu0 ); // Estimator 28 29 const epdf& f_thr = Ar.posterior(); // refrence to posterior of the estimator 29 30 … … 31 32 int ndat = 100; // number of data records 32 33 vec Yt ( ndat ); // Store generated data 33 Yt.set_subvector ( 0, randn ( ord ) ); //initial values34 Yt.set_subvector ( 0, randn ( ord ) ); //initial values 34 35 vec rgr ( ord ); // regressor 35 vec Psi ( ord +1 );// extended regressor36 vec Psi ( ord + 1 ); // extended regressor 36 37 37 38 //print moments of the prior distribution 38 cout << "prior mean: " << f_thr.mean() << endl;39 cout << "prior variance: " << f_thr.variance() << endl;39 cout << "prior mean: " << f_thr.mean() << endl; 40 cout << "prior variance: " << f_thr.variance() << endl; 40 41 41 42 // cycle over time: 42 for ( int t =ord; t<ndat; t++ ) {43 for ( int t = ord; t < ndat; t++ ) { 43 44 //Generate regressor 44 for ( int j=0;j< ( ord );j++ ) {rgr ( j ) =Yt ( t-j-1 );} 45 for ( int j = 0; j < ( ord ); j++ ) { 46 rgr ( j ) = Yt ( t - j - 1 ); 47 } 45 48 //model 46 Yt ( t ) = th *rgr + sqr * NorRNG();49 Yt ( t ) = th * rgr + sqr * NorRNG(); 47 50 48 51 Psi = concat ( Yt ( t ), rgr ); // Inefficient! Used for compatibility with Matlab! … … 53 56 // Test similarity of likelihoods from the Bayes rule and the predictor 54 57 cout << "BR log-lik: " << Ar._ll(); 55 cout << " , predictor ll: " << Pr->evallogcond ( vec_1 ( Yt ( t ) ),rgr ) <<endl;58 cout << " , predictor ll: " << Pr->evallogcond ( vec_1 ( Yt ( t ) ), rgr ) << endl; 56 59 delete Pr; 57 60 } 58 61 //print posterior moments 59 cout << "posterior mean: " << f_thr.mean() << endl;60 cout << "posterior variance: " << f_thr.variance() << endl;62 cout << "posterior mean: " << f_thr.mean() << endl; 63 cout << "posterior variance: " << f_thr.variance() << endl; 61 64 62 65 // Test brute-froce structure estimation 63 64 cout << "Structure estimation: " << endl;65 cout << Ar.structure_est ( egiw ( 1,V0,nu0 ) ) <<endl;66 67 cout << "Structure estimation: " << endl; 68 cout << Ar.structure_est ( egiw ( 1, V0, nu0 ) ) << endl; 66 69 } -
TabularUnified library/tests/blas_test.cpp ¶
r262 r477 10 10 11 11 mat matmul ( mat &A, mat &B ) { 12 mat C ( A.rows(), B.cols() );13 int i, j,k;12 mat C ( A.rows(), B.cols() ); 13 int i, j, k; 14 14 double sum; 15 15 16 for ( i =0;i<A.rows();i++ ) {17 for ( j =0;j<A.cols();j++ ) {16 for ( i = 0; i < A.rows(); i++ ) { 17 for ( j = 0; j < A.cols(); j++ ) { 18 18 sum = 0.0; 19 for ( k =0;k<A.cols();k++ ) {20 sum +=A._elem ( i,k ) *B._elem ( k,j );19 for ( k = 0; k < A.cols(); k++ ) { 20 sum += A._elem ( i, k ) * B._elem ( k, j ); 21 21 } 22 C ( i, j ) = sum;22 C ( i, j ) = sum; 23 23 } 24 24 } … … 27 27 28 28 void matmul2 ( int n, double *A, double *B, double *C ) { 29 int i, j,k;29 int i, j, k; 30 30 double sum; 31 31 32 for ( i =0;i<n;i++ ) {33 for ( j =0;j<n;j++ ) {32 for ( i = 0; i < n; i++ ) { 33 for ( j = 0; j < n; j++ ) { 34 34 sum = 0.0; 35 for ( k =0;k<n;k++ ) {36 sum +=A [ i*n+k ] * B [ k*n+j ];35 for ( k = 0; k < n; k++ ) { 36 sum += A [ i*n+k ] * B [ k*n+j ]; 37 37 } 38 38 C[ i*n+j] = sum; … … 52 52 mat C; 53 53 54 vec vn ="5 50 200 500";54 vec vn = "5 50 200 500"; 55 55 int n; 56 56 57 for ( int i =0;i<vn.length();i++ ) {57 for ( int i = 0; i < vn.length(); i++ ) { 58 58 n = vn ( i ); 59 A = randu ( n, n );60 B = randu ( n, n );59 A = randu ( n, n ); 60 B = randu ( n, n ); 61 61 62 62 tt.tic(); 63 for ( int ii=0;ii<10;ii++ ) {C = matmul ( A,B );} 64 exec_times ( i ) =tt.toc(); 63 for ( int ii = 0; ii < 10; ii++ ) { 64 C = matmul ( A, B ); 65 } 66 exec_times ( i ) = tt.toc(); 65 67 66 68 tt.tic(); 67 for ( int ii=0;ii<10;ii++ ) {C = A*B;} 68 exec_times_b ( i ) =tt.toc(); 69 for ( int ii = 0; ii < 10; ii++ ) { 70 C = A * B; 71 } 72 exec_times_b ( i ) = tt.toc(); 69 73 70 C = zeros (n,n);74 C = zeros ( n, n ); 71 75 tt.tic(); 72 for ( int ii=0;ii<10;ii++ ) { matmul2(n,A._data(),B._data(),C._data());} 73 exec_times_c ( i ) =tt.toc(); 76 for ( int ii = 0; ii < 10; ii++ ) { 77 matmul2 ( n, A._data(), B._data(), C._data() ); 78 } 79 exec_times_c ( i ) = tt.toc(); 74 80 } 75 cout << exec_times << endl;76 cout << exec_times_b << endl;77 cout << exec_times_c << endl;81 cout << exec_times << endl; 82 cout << exec_times_b << endl; 83 cout << exec_times_c << endl; 78 84 79 85 it_file itf ( "blas_test.it" ); 80 itf << Name ( "exec_times" ) << exec_times;81 itf << Name ( "exec_times_b" ) << exec_times_b;82 itf << Name ( "exec_times_c" ) << exec_times_c;86 itf << Name ( "exec_times" ) << exec_times; 87 itf << Name ( "exec_times_b" ) << exec_times_b; 88 itf << Name ( "exec_times_c" ) << exec_times_c; 83 89 84 90 return 0; -
TabularUnified library/tests/datalink_test.cpp ¶
r424 r477 5 5 using namespace bdm; 6 6 7 TEST (test_datalink) {8 9 10 RV a = RV("{dla }", "2");11 RV b = RV("{dlb }");12 RV c = RV("{dlc }");7 TEST ( test_datalink ) { 8 // RV names are global, and a, b and c are already taken by a 9 // different test... 10 RV a = RV ( "{dla }", "2" ); 11 RV b = RV ( "{dlb }" ); 12 RV c = RV ( "{dlc }" ); 13 13 14 15 ab.add(b);14 RV ab = a; 15 ab.add ( b ); 16 16 17 18 abc.add(c);17 RV abc = ab; 18 abc.add ( c ); 19 19 20 datalink dl(ab, abc);21 vec total("0 37 42 66");22 vec filtered = dl.pushdown(total);23 24 int exp_sz = sizeof(exp_f) / sizeof(exp_f[0]);25 CHECK_EQUAL(exp_sz, filtered.size());26 for (int i = 0; i < exp_sz; ++i) {27 CHECK_EQUAL(exp_f[i], filtered(i));28 20 datalink dl ( ab, abc ); 21 vec total ( "0 37 42 66" ); 22 vec filtered = dl.pushdown ( total ); 23 int exp_f[] = { 0, 37, 42 }; 24 int exp_sz = sizeof ( exp_f ) / sizeof ( exp_f[0] ); 25 CHECK_EQUAL ( exp_sz, filtered.size() ); 26 for ( int i = 0; i < exp_sz; ++i ) { 27 CHECK_EQUAL ( exp_f[i], filtered ( i ) ); 28 } 29 29 } 30 30 31 TEST (test_datalink_m2e) {32 RV a = RV("{dla }", "2");33 RV b = RV("{dlb }");34 RV c = RV("{dlc }");31 TEST ( test_datalink_m2e ) { 32 RV a = RV ( "{dla }", "2" ); 33 RV b = RV ( "{dlb }" ); 34 RV c = RV ( "{dlc }" ); 35 35 36 37 ab.add(b);36 RV ab = a; 37 ab.add ( b ); 38 38 39 40 ba.add(b);39 RV ba = a; 40 ba.add ( b ); 41 41 42 43 abc.add(c);42 RV abc = ab; 43 abc.add ( c ); 44 44 45 46 dl.set_connection(ba, c, abc);47 vec total("0 37 42 66");48 vec cond = dl.get_cond(total);49 CHECK_EQUAL(1, cond.size());50 CHECK_EQUAL(66, cond(0));45 datalink_m2e dl; 46 dl.set_connection ( ba, c, abc ); 47 vec total ( "0 37 42 66" ); 48 vec cond = dl.get_cond ( total ); 49 CHECK_EQUAL ( 1, cond.size() ); 50 CHECK_EQUAL ( 66, cond ( 0 ) ); 51 51 } 52 52 53 TEST (test_datalink_m2m) {54 RV a = RV("{dla }", "2");55 RV b = RV("{dlb }");56 RV c = RV("{dlc }");53 TEST ( test_datalink_m2m ) { 54 RV a = RV ( "{dla }", "2" ); 55 RV b = RV ( "{dlb }" ); 56 RV c = RV ( "{dlc }" ); 57 57 58 59 dl.set_connection(a, concat(b, c), concat(a, b), c);58 datalink_m2m dl; 59 dl.set_connection ( a, concat ( b, c ), concat ( a, b ), c ); 60 60 61 vec val("1 1.5 2");62 vec cond("3");61 vec val ( "1 1.5 2" ); 62 vec cond ( "3" ); 63 63 64 vec p = dl.pushdown(val);65 66 int exp_sz = sizeof(exp_p) / sizeof(exp_p[0]);67 CHECK_EQUAL(exp_sz, p.size());68 for (int i = 0; i < exp_sz; ++i) {69 CHECK_EQUAL(exp_p[i], p(i));70 64 vec p = dl.pushdown ( val ); 65 double exp_p[] = { 1.0, 1.5 }; 66 int exp_sz = sizeof ( exp_p ) / sizeof ( exp_p[0] ); 67 CHECK_EQUAL ( exp_sz, p.size() ); 68 for ( int i = 0; i < exp_sz; ++i ) { 69 CHECK_EQUAL ( exp_p[i], p ( i ) ); 70 } 71 71 72 vec dlcond = dl.get_cond(val, cond);73 74 exp_sz = sizeof(exp_c) / sizeof(exp_c[0]);75 CHECK_EQUAL(exp_sz, dlcond.size());76 for (int i = 0; i < exp_sz; ++i) {77 CHECK_EQUAL(exp_c[i], dlcond(i));78 72 vec dlcond = dl.get_cond ( val, cond ); 73 int exp_c[] = { 2, 3 }; 74 exp_sz = sizeof ( exp_c ) / sizeof ( exp_c[0] ); 75 CHECK_EQUAL ( exp_sz, dlcond.size() ); 76 for ( int i = 0; i < exp_sz; ++i ) { 77 CHECK_EQUAL ( exp_c[i], dlcond ( i ) ); 78 } 79 79 } -
TabularUnified library/tests/dirent.h ¶
r469 r477 9 9 History: Created March 1997. Updated June 2003. 10 10 Rights: See end of file. 11 11 12 12 */ 13 13 14 14 #ifdef __cplusplus 15 extern "C" 16 { 15 extern "C" { 17 16 #endif 18 17 19 typedef struct DIR DIR;18 typedef struct DIR DIR; 20 19 21 struct dirent 22 { 23 char *d_name; 24 }; 20 struct dirent { 21 char *d_name; 22 }; 25 23 26 DIR *opendir(const char *);27 int closedir(DIR *);28 struct dirent *readdir(DIR *);29 void rewinddir(DIR *);24 DIR *opendir ( const char * ); 25 int closedir ( DIR * ); 26 struct dirent *readdir ( DIR * ); 27 void rewinddir ( DIR * ); 30 28 31 /*29 /* 32 30 33 Copyright Kevlin Henney, 1997, 2003. All rights reserved.31 Copyright Kevlin Henney, 1997, 2003. All rights reserved. 34 32 35 Permission to use, copy, modify, and distribute this software and its 36 documentation for any purpose is hereby granted without fee, provided 37 that this copyright and permissions notice appear in all copies and 38 derivatives. 39 40 This software is supplied "as is" without express or implied warranty. 33 Permission to use, copy, modify, and distribute this software and its 34 documentation for any purpose is hereby granted without fee, provided 35 that this copyright and permissions notice appear in all copies and 36 derivatives. 41 37 42 But that said, if there are any problems please get in touch.38 This software is supplied "as is" without express or implied warranty. 43 39 44 */ 40 But that said, if there are any problems please get in touch. 41 42 */ 45 43 46 44 #ifdef __cplusplus -
TabularUnified library/tests/egiw_harness.cpp ¶
r475 r477 7 7 namespace bdm { 8 8 9 void egiw_harness::from_setting (const Setting &set) {10 epdf_harness::from_setting(set); 11 UI::get(lognc, set, "lognc", UI::compulsory);9 void egiw_harness::from_setting ( const Setting &set ) { 10 epdf_harness::from_setting ( set ); 11 UI::get ( lognc, set, "lognc", UI::compulsory ); 12 12 } 13 13 14 void egiw_harness::test(const char *config_name, int idx) 15 { 16 epdf_harness::test(config_name, idx); 14 void egiw_harness::test ( const char *config_name, int idx ) { 15 epdf_harness::test ( config_name, idx ); 17 16 18 CurrentContext cc(config_name, idx);17 CurrentContext cc ( config_name, idx ); 19 18 20 egiw *wide = dynamic_cast<egiw *>(get_epdf());21 CHECK(wide);19 egiw *wide = dynamic_cast<egiw *> ( get_epdf() ); 20 CHECK ( wide ); 22 21 23 if (wide) {24 CHECK_CLOSE_EX(lognc, wide->lognc(), get_tolerance());25 22 if ( wide ) { 23 CHECK_CLOSE_EX ( lognc, wide->lognc(), get_tolerance() ); 24 } 26 25 } 27 26 -
TabularUnified library/tests/egiw_harness.h ¶
r456 r477 16 16 #include "epdf_harness.h" 17 17 18 namespace bdm 19 { 18 namespace bdm { 20 19 21 class egiw_harness : public epdf_harness 22 { 20 class egiw_harness : public epdf_harness { 23 21 private: 24 22 double lognc; 25 23 26 24 public: 27 egiw_harness():lognc(0) { }25 egiw_harness() : lognc ( 0 ) { } 28 26 29 void test(const char *config_name, int idx);27 void test ( const char *config_name, int idx ); 30 28 31 void from_setting(const Setting &set);29 void from_setting ( const Setting &set ); 32 30 }; 33 31 -
TabularUnified library/tests/egiw_test.cpp ¶
r456 r477 14 14 15 15 template<> 16 const ParticularUI<egiw> &ParticularUI<egiw>::factory (17 ParticularUI<egiw> ("egiw"));16 const ParticularUI<egiw> &ParticularUI<egiw>::factory ( 17 ParticularUI<egiw> ( "egiw" ) ); 18 18 19 19 template<> 20 const ParticularUI<egiw_harness> &ParticularUI<egiw_harness>::factory (21 ParticularUI<egiw_harness> ("egiw_harness"));20 const ParticularUI<egiw_harness> &ParticularUI<egiw_harness>::factory ( 21 ParticularUI<egiw_harness> ( "egiw_harness" ) ); 22 22 23 TEST (test_egiw) {24 epdf_harness::test_config("egiw.cfg");23 TEST ( test_egiw ) { 24 epdf_harness::test_config ( "egiw.cfg" ); 25 25 } 26 26 27 TEST (test_egiw_1_2) {28 29 30 31 27 TEST ( test_egiw_1_2 ) { 28 // Setup model 29 double mu = 1.1; //unit step parametr 30 double b = 3.0; // sequence of <1 -1 1 -1...> 31 double s = 0.1; 32 32 33 33 34 35 mat V(3, 3);36 V(0, 0) = pow(mu, 2) + pow(b, 2) + s;37 V(1, 0) = mu;38 V(2, 0) = b;34 // TEST 1x1 EGIW 35 mat V ( 3, 3 ); 36 V ( 0, 0 ) = pow ( mu, 2 ) + pow ( b, 2 ) + s; 37 V ( 1, 0 ) = mu; 38 V ( 2, 0 ) = b; 39 39 40 V(0, 1) = V(1, 0);41 V(1, 1) = 1.0;42 V(2, 1) = 0.0;40 V ( 0, 1 ) = V ( 1, 0 ); 41 V ( 1, 1 ) = 1.0; 42 V ( 2, 1 ) = 0.0; 43 43 44 V(0, 2) = V(2, 0);45 V(1, 2) = V(2, 1);46 V(2, 2) = 1.0;44 V ( 0, 2 ) = V ( 2, 0 ); 45 V ( 1, 2 ) = V ( 2, 1 ); 46 V ( 2, 2 ) = 1.0; 47 47 48 48 double nu = 20; 49 49 50 egiw E(1, nu * V, nu); 51 CHECK_CLOSE(vec("1.1 3.0 0.142857"), E.mean(), epsilon);52 CHECK_CLOSE(7.36731, E.lognc(), epsilon);50 egiw E ( 1, nu * V, nu ); 51 CHECK_CLOSE ( vec ( "1.1 3.0 0.142857" ), E.mean(), epsilon ); 52 CHECK_CLOSE ( 7.36731, E.lognc(), epsilon ); 53 53 54 55 vec rgr(3);54 int n = 100; 55 vec rgr ( 3 ); 56 56 57 mat Tmp(2 * n, n);57 mat Tmp ( 2 * n, n ); 58 58 59 60 for (int k = 0; k < n; k++) { // ALL b61 rgr(1) = 1 + k * (1.0 / n) * 4.0;62 for (int i = 0; i < 2*n; i++) { //ALL mu63 rgr(0) = -2 + i * (1.0 / n) * 3.0;64 for (int j = 0; j < n; j++) { // All sigma65 rgr(2) = (j + 1) * (1.0 / n) * 2.0;59 double summ = 0.0; 60 for ( int k = 0; k < n; k++ ) { // ALL b 61 rgr ( 1 ) = 1 + k * ( 1.0 / n ) * 4.0; 62 for ( int i = 0; i < 2*n; i++ ) { //ALL mu 63 rgr ( 0 ) = -2 + i * ( 1.0 / n ) * 3.0; 64 for ( int j = 0; j < n; j++ ) { // All sigma 65 rgr ( 2 ) = ( j + 1 ) * ( 1.0 / n ) * 2.0; 66 66 67 Tmp(i, j) = E.evallog(rgr); 68 } 67 Tmp ( i, j ) = E.evallog ( rgr ); 68 } 69 } 70 summ += sumsum ( exp ( Tmp ) ) / n / n / n * 3.0 * 2.0 * 4.0; 69 71 } 70 summ += sumsum(exp(Tmp)) / n / n / n * 3.0 * 2.0 * 4.0;71 }72 72 73 CHECK_CLOSE(1.0, summ, 0.1);73 CHECK_CLOSE ( 1.0, summ, 0.1 ); 74 74 } 75 75 -
TabularUnified library/tests/emix_test.cpp ¶
r461 r477 9 9 using std::endl; 10 10 11 double normcoef ( const epdf* ep, const vec &xb, const vec &yb, int Ngr=100 ) {12 mat PPdf ( Ngr +1,Ngr+1 );11 double normcoef ( const epdf* ep, const vec &xb, const vec &yb, int Ngr = 100 ) { 12 mat PPdf ( Ngr + 1, Ngr + 1 ); 13 13 vec rgr ( 2 ); 14 14 15 int i =0,j=0;16 double xstep = ( xb ( 1 )-xb ( 0 ) ) /Ngr;17 double ystep = ( yb ( 1 )-yb ( 0 ) ) /Ngr;15 int i = 0, j = 0; 16 double xstep = ( xb ( 1 ) - xb ( 0 ) ) / Ngr; 17 double ystep = ( yb ( 1 ) - yb ( 0 ) ) / Ngr; 18 18 19 for ( double x=xb ( 0 );x<=xb ( 1 );x+= xstep,i++ ) { 20 rgr ( 0 ) =x;j=0; 21 for ( double y=yb ( 0 );y<=yb ( 1 );y+=ystep,j++ ) { 22 rgr ( 1 ) =y; 23 PPdf ( i,j ) =exp ( ep->evallog ( rgr ) ); 19 for ( double x = xb ( 0 ); x <= xb ( 1 ); x += xstep, i++ ) { 20 rgr ( 0 ) = x; 21 j = 0; 22 for ( double y = yb ( 0 ); y <= yb ( 1 ); y += ystep, j++ ) { 23 rgr ( 1 ) = y; 24 PPdf ( i, j ) = exp ( ep->evallog ( rgr ) ); 24 25 } 25 26 } … … 32 33 RV x ( "{x }" ); 33 34 RV y ( "{y }" ); 34 RV xy=concat(x,y); 35 36 enorm<ldmat> E1; E1.set_rv ( xy ); 37 38 E1.set_parameters( "1.00054 1.0455" , mat ( "0.740142 -0.259015; -0.259015 1.0302" )); 39 enorm<ldmat> E2;E2.set_rv ( xy ); 40 E2.set_parameters( "-1.2 -0.1" , mat ( "1 0.4; 0.4 0.5" )); 35 RV xy = concat ( x, y ); 41 36 42 Array<epdf*> A1(1); 43 A1(0) = &E1; 44 45 emix M1; M1.set_rv(xy); 46 M1.set_parameters(vec("1"), A1, false); 47 cout << "======== test if ARX and emix with one ARX are the same ==="<<endl; 48 49 epdf* Mm = M1.marginal(y); 50 epdf* Am = E1.marginal(y); 51 mpdf* Mc = M1.condition(y); 52 mpdf* Ac = E1.condition(y); 53 54 cout << *((mlnorm<ldmat>*)Ac) <<endl; 55 56 cout << "Mix marg at 0: " << Mm->evallog(vec_1(0.0)) <<endl; 57 cout << "ARX marg at 0: " << Am->evallog(vec_1(0.0)) <<endl; 58 cout << "Mix cond at 0,0: " << Mc->evallogcond(vec_1(0.0),vec_1(0.0)) <<endl; 59 cout << "ARX cond at 0,0: " << Ac->evallogcond(vec_1(0.0),vec_1(0.0)) <<endl; 60 61 cout << "======== Mixture with two components ==="<<endl; 62 Array<epdf*> A2(2); 63 A2(0) = &E1; 64 A2(1) = &E2; 65 66 emix M2; M2.set_rv(xy); 67 M2.set_parameters(vec("1"), A2, false); 68 69 70 cout << "Mixture normalization: " << normcoef(&M2, vec("-3 3 "), vec("-3 3 ")) <<endl; 71 72 int N=3; 37 enorm<ldmat> E1; 38 E1.set_rv ( xy ); 39 40 E1.set_parameters ( "1.00054 1.0455" , mat ( "0.740142 -0.259015; -0.259015 1.0302" ) ); 41 enorm<ldmat> E2; 42 E2.set_rv ( xy ); 43 E2.set_parameters ( "-1.2 -0.1" , mat ( "1 0.4; 0.4 0.5" ) ); 44 45 Array<epdf*> A1 ( 1 ); 46 A1 ( 0 ) = &E1; 47 48 emix M1; 49 M1.set_rv ( xy ); 50 M1.set_parameters ( vec ( "1" ), A1, false ); 51 cout << "======== test if ARX and emix with one ARX are the same ===" << endl; 52 53 epdf* Mm = M1.marginal ( y ); 54 epdf* Am = E1.marginal ( y ); 55 mpdf* Mc = M1.condition ( y ); 56 mpdf* Ac = E1.condition ( y ); 57 58 cout << * ( ( mlnorm<ldmat>* ) Ac ) << endl; 59 60 cout << "Mix marg at 0: " << Mm->evallog ( vec_1 ( 0.0 ) ) << endl; 61 cout << "ARX marg at 0: " << Am->evallog ( vec_1 ( 0.0 ) ) << endl; 62 cout << "Mix cond at 0,0: " << Mc->evallogcond ( vec_1 ( 0.0 ), vec_1 ( 0.0 ) ) << endl; 63 cout << "ARX cond at 0,0: " << Ac->evallogcond ( vec_1 ( 0.0 ), vec_1 ( 0.0 ) ) << endl; 64 65 cout << "======== Mixture with two components ===" << endl; 66 Array<epdf*> A2 ( 2 ); 67 A2 ( 0 ) = &E1; 68 A2 ( 1 ) = &E2; 69 70 emix M2; 71 M2.set_rv ( xy ); 72 M2.set_parameters ( vec ( "1" ), A2, false ); 73 74 75 cout << "Mixture normalization: " << normcoef ( &M2, vec ( "-3 3 " ), vec ( "-3 3 " ) ) << endl; 76 77 int N = 3; 73 78 vec ll ( N ); 74 79 vec ll2 ( N ); 75 mat Smp=M2.sample_m ( N ); 76 ll = M2.evallog_m(Smp); 77 78 vec Emu = sum ( Smp,2 ) /N; 79 mat Er = ( Smp*Smp.transpose() ) /N - outer_product ( Emu,Emu ); 80 mat Smp = M2.sample_m ( N ); 81 ll = M2.evallog_m ( Smp ); 80 82 81 cout << "original empirical mean: " <<Emu <<endl;82 cout << "original empirical variance: " <<Er <<endl;83 vec Emu = sum ( Smp, 2 ) / N; 84 mat Er = ( Smp * Smp.transpose() ) / N - outer_product ( Emu, Emu ); 83 85 84 shared_ptr<epdf> Mg(dynamic_cast<epdf *>(M2.marginal(y)));85 mpdf* Cn = (mpdf*)M2.condition ( x );86 cout << "original empirical mean: " << Emu << endl; 87 cout << "original empirical variance: " << Er << endl; 86 88 87 it_file it("emix_test.it");88 it << Name("Smp") << Smp;89 shared_ptr<epdf> Mg ( dynamic_cast<epdf *> ( M2.marginal ( y ) ) ); 90 mpdf* Cn = ( mpdf* ) M2.condition ( x ); 89 91 90 cout<< "marginal mean: " << Mg->mean() <<endl; 92 it_file it ( "emix_test.it" ); 93 it << Name ( "Smp" ) << Smp; 91 94 92 cout << "========== putting them back together ======= "<<endl; 95 cout << "marginal mean: " << Mg->mean() << endl; 96 97 cout << "========== putting them back together ======= " << endl; 93 98 mepdf mMg ( Mg ); 94 99 Array<mpdf*> AA ( 2 ); … … 97 102 mprod mEp ( AA ); 98 103 99 for ( int j=0; j<N; j++){100 ll2 (j)=mEp.evallogcond (Smp.get_col(j), vec ( 0 ));104 for ( int j = 0; j < N; j++ ) { 105 ll2 ( j ) = mEp.evallogcond ( Smp.get_col ( j ), vec ( 0 ) ); 101 106 } 102 it << Name ("ll") << ll;103 it << Name ("ll2") << ll2;104 105 107 it << Name ( "ll" ) << ll; 108 it << Name ( "ll2" ) << ll2; 109 110 106 111 } -
TabularUnified library/tests/epdf_harness.cpp ¶
r471 r477 12 12 13 13 template<> 14 const ParticularUI<epdf_harness> &ParticularUI<epdf_harness>::factory (15 ParticularUI<epdf_harness> ("epdf_harness"));14 const ParticularUI<epdf_harness> &ParticularUI<epdf_harness>::factory ( 15 ParticularUI<epdf_harness> ( "epdf_harness" ) ); 16 16 17 void epdf_harness::test_config (const char *config_file_name) {18 17 void epdf_harness::test_config ( const char *config_file_name ) { 18 RV::clear_all(); 19 19 20 UIFile in(config_file_name);21 22 UI::get(input, in, "data");23 24 CHECK(sz > 0);25 for (int i = 0; i < sz; ++i) {26 input(i)->test(config_file_name, i);27 20 UIFile in ( config_file_name ); 21 Array<epdf_harness *> input; 22 UI::get ( input, in, "data" ); 23 int sz = input.size(); 24 CHECK ( sz > 0 ); 25 for ( int i = 0; i < sz; ++i ) { 26 input ( i )->test ( config_file_name, i ); 27 } 28 28 } 29 29 30 void epdf_harness::from_setting (const Setting &set) {31 hepdf = UI::build<epdf>(set, "epdf", UI::compulsory);32 UI::get(mean, set, "mean", UI::compulsory);33 UI::get(variance, set, "variance", UI::compulsory);30 void epdf_harness::from_setting ( const Setting &set ) { 31 hepdf = UI::build<epdf> ( set, "epdf", UI::compulsory ); 32 UI::get ( mean, set, "mean", UI::compulsory ); 33 UI::get ( variance, set, "variance", UI::compulsory ); 34 34 35 35 36 UI::get (support, set, "support");37 UI::get (nbins, set, "nbins");38 UI::get(nsamples, set, "nsamples");39 UI::get(R, set, "R");36 UI::get ( support, set, "support" ); 37 UI::get ( nbins, set, "nbins" ); 38 UI::get ( nsamples, set, "nsamples" ); 39 UI::get ( R, set, "R" ); 40 40 41 RV* rv = UI::build<RV> (set, "marginal_rv");42 if (rv) 43 mrv = shared_ptr<RV>(rv); 41 RV* rv = UI::build<RV> ( set, "marginal_rv" ); 42 if ( rv ) 43 mrv = shared_ptr<RV> ( rv ); 44 44 45 UI::get (tolerance, set, "tolerance");45 UI::get ( tolerance, set, "tolerance" ); 46 46 } 47 47 48 void epdf_harness::test(const char *config_name, int idx) 49 { 50 CurrentContext cc(config_name, idx); 48 void epdf_harness::test ( const char *config_name, int idx ) { 49 CurrentContext cc ( config_name, idx ); 51 50 52 CHECK_CLOSE_EX(mean, hepdf->mean(), tolerance);53 CHECK_CLOSE_EX(variance, hepdf->variance(), tolerance);51 CHECK_CLOSE_EX ( mean, hepdf->mean(), tolerance ); 52 CHECK_CLOSE_EX ( variance, hepdf->variance(), tolerance ); 54 53 55 if (support.rows() == 2) {56 vec xb = support.get_row(0);57 vec yb = support.get_row(1);54 if ( support.rows() == 2 ) { 55 vec xb = support.get_row ( 0 ); 56 vec yb = support.get_row ( 1 ); 58 57 59 int old_size = nbins.size();60 if (old_size < 2) {61 vec new_nbins("100 100");62 for (int i = 0; i < old_size; ++i) {63 new_nbins(i) = nbins(i);64 58 int old_size = nbins.size(); 59 if ( old_size < 2 ) { 60 vec new_nbins ( "100 100" ); 61 for ( int i = 0; i < old_size; ++i ) { 62 new_nbins ( i ) = nbins ( i ); 63 } 65 64 66 nbins = new_nbins; 65 nbins = new_nbins; 66 } 67 68 CHECK_CLOSE_EX ( mean, num_mean2 ( hepdf.get(), xb, yb, nbins ( 0 ), nbins ( 1 ) ), tolerance ); 69 CHECK_CLOSE_EX ( 1.0, normcoef ( hepdf.get(), xb, yb, nbins ( 0 ), nbins ( 1 ) ), tolerance ); 67 70 } 68 71 69 CHECK_CLOSE_EX(mean, num_mean2(hepdf.get(), xb, yb, nbins(0), nbins(1)), tolerance); 70 CHECK_CLOSE_EX(1.0, normcoef(hepdf.get(), xb, yb, nbins(0), nbins(1)), tolerance); 71 } 72 if ( R.rows() > 0 ) { 73 mat smp = hepdf->sample_m ( nsamples ); 74 vec emu = smp * ones ( nsamples ) / nsamples; 75 mat er = ( smp * smp.T() ) / nsamples - outer_product ( emu, emu ); 72 76 73 if (R.rows() > 0) { 74 mat smp = hepdf->sample_m(nsamples); 75 vec emu = smp * ones(nsamples) / nsamples; 76 mat er = (smp * smp.T()) / nsamples - outer_product(emu, emu); 77 // simplify overloading for Visual Studio 78 vec delta = sqrt ( variance ) / sqrt ( static_cast<double> ( nsamples ) ); 79 CHECK_CLOSE_EX ( mean, emu, delta ); 77 80 78 // simplify overloading for Visual Studio 79 vec delta = sqrt(variance) / sqrt(static_cast<double>(nsamples)); 80 CHECK_CLOSE_EX(mean, emu, delta); 81 82 CHECK_CLOSE_EX(R, er, tolerance); 83 } 84 85 if (mrv.get()) { 86 RV crv = hepdf->_rv().subt(*mrv); 87 shared_ptr<epdf> m = hepdf->marginal(*mrv); 88 shared_ptr<mpdf> c = hepdf->condition(crv); 89 mepdf mm(m); 90 91 Array<mpdf *> aa(2); 92 aa(0) = c.get(); 93 aa(1) = &mm; 94 mprod mEp(aa); 95 96 mat smp = mEp.samplecond(vec(0), nsamples); 97 vec emu = sum(smp, 2) / nsamples; 98 99 // simplify overloading for Visual Studio 100 vec delta = sqrt(variance) / sqrt(static_cast<double>(nsamples)); 101 CHECK_CLOSE_EX(mean, emu, delta); 102 103 if (R.rows() > 0) { 104 mat er = (smp * smp.T()) / nsamples - outer_product(emu, emu); 105 CHECK_CLOSE_EX(R, er, tolerance); 81 CHECK_CLOSE_EX ( R, er, tolerance ); 106 82 } 107 83 108 // test of pdflog at zero 109 vec zero(0); 110 vec zeron(hepdf->dimension()); 111 for (int i = 0; i < zeron.size(); ++i) { 112 zeron(i) = 0; 84 if ( mrv.get() ) { 85 RV crv = hepdf->_rv().subt ( *mrv ); 86 shared_ptr<epdf> m = hepdf->marginal ( *mrv ); 87 shared_ptr<mpdf> c = hepdf->condition ( crv ); 88 mepdf mm ( m ); 89 90 Array<mpdf *> aa ( 2 ); 91 aa ( 0 ) = c.get(); 92 aa ( 1 ) = &mm; 93 mprod mEp ( aa ); 94 95 mat smp = mEp.samplecond ( vec ( 0 ), nsamples ); 96 vec emu = sum ( smp, 2 ) / nsamples; 97 98 // simplify overloading for Visual Studio 99 vec delta = sqrt ( variance ) / sqrt ( static_cast<double> ( nsamples ) ); 100 CHECK_CLOSE_EX ( mean, emu, delta ); 101 102 if ( R.rows() > 0 ) { 103 mat er = ( smp * smp.T() ) / nsamples - outer_product ( emu, emu ); 104 CHECK_CLOSE_EX ( R, er, tolerance ); 105 } 106 107 // test of pdflog at zero 108 vec zero ( 0 ); 109 vec zeron ( hepdf->dimension() ); 110 for ( int i = 0; i < zeron.size(); ++i ) { 111 zeron ( i ) = 0; 112 } 113 114 CHECK_CLOSE_EX ( hepdf->evallog ( zeron ), mEp.evallogcond ( zeron, zero ), tolerance ); 113 115 } 114 115 CHECK_CLOSE_EX(hepdf->evallog(zeron), mEp.evallogcond(zeron, zero), tolerance);116 }117 116 } 118 117 -
TabularUnified library/tests/epdf_harness.h ¶
r462 r477 22 22 #include "base/user_info.h" 23 23 24 namespace bdm 25 { 24 namespace bdm { 26 25 27 class epdf_harness : public root 28 { 26 class epdf_harness : public root { 29 27 private: 30 31 32 33 34 35 36 37 38 28 shared_ptr<epdf> hepdf; 29 vec mean; 30 vec variance; 31 mat support; 32 vec nbins; 33 int nsamples; 34 mat R; 35 shared_ptr<RV> mrv; 36 double tolerance; 39 37 40 38 public: 41 static void test_config(const char *config_file_name);39 static void test_config ( const char *config_file_name ); 42 40 43 epdf_harness():nsamples(1000), tolerance(0.1) { }41 epdf_harness() : nsamples ( 1000 ), tolerance ( 0.1 ) { } 44 42 45 virtual void test(const char *config_name, int idx);43 virtual void test ( const char *config_name, int idx ); 46 44 47 void from_setting(const Setting &set);45 void from_setting ( const Setting &set ); 48 46 49 47 protected: 50 epdf *get_epdf() { return hepdf.get(); } 48 epdf *get_epdf() { 49 return hepdf.get(); 50 } 51 51 52 double get_tolerance() const { return tolerance; } 52 double get_tolerance() const { 53 return tolerance; 54 } 53 55 }; 54 56 -
TabularUnified library/tests/epdf_test.cpp ¶
r457 r477 8 8 9 9 template<> 10 const ParticularUI<egamma> &ParticularUI<egamma>::factory (11 ParticularUI<egamma> ("egamma"));10 const ParticularUI<egamma> &ParticularUI<egamma>::factory ( 11 ParticularUI<egamma> ( "egamma" ) ); 12 12 13 13 template<> 14 const ParticularUI<enorm<ldmat> > &ParticularUI<enorm<ldmat> >::factory (15 ParticularUI<enorm<ldmat> > ("enorm<ldmat>"));14 const ParticularUI<enorm<ldmat> > &ParticularUI<enorm<ldmat> >::factory ( 15 ParticularUI<enorm<ldmat> > ( "enorm<ldmat>" ) ); 16 16 17 17 template<> 18 const ParticularUI<enorm<fsqmat> > &ParticularUI<enorm<fsqmat> >::factory (19 ParticularUI<enorm<fsqmat> > ("enorm<fsqmat>"));18 const ParticularUI<enorm<fsqmat> > &ParticularUI<enorm<fsqmat> >::factory ( 19 ParticularUI<enorm<fsqmat> > ( "enorm<fsqmat>" ) ); 20 20 21 22 const ParticularUI<enorm<chmat> > &ParticularUI<enorm<chmat> >::factory (23 ParticularUI<enorm<chmat> > ("enorm<chmat>"));21 template<> 22 const ParticularUI<enorm<chmat> > &ParticularUI<enorm<chmat> >::factory ( 23 ParticularUI<enorm<chmat> > ( "enorm<chmat>" ) ); 24 24 25 TEST (test_egamma) {26 epdf_harness::test_config("egamma.cfg");25 TEST ( test_egamma ) { 26 epdf_harness::test_config ( "egamma.cfg" ); 27 27 } 28 28 29 TEST (test_enorm) {30 epdf_harness::test_config("enorm.cfg");29 TEST ( test_enorm ) { 30 epdf_harness::test_config ( "enorm.cfg" ); 31 31 } -
TabularUnified library/tests/generator.h ¶
r467 r477 19 19 /*! An input iterator over IT++ matrices. 20 20 */ 21 class generator : public bdm::root 22 { 21 class generator : public bdm::root { 23 22 public: 24 23 generator(); 25 24 26 27 28 25 //! Generates a matrix. Returned matrices should become 26 //! progressively more complicated. 27 virtual itpp::mat next() = 0; 29 28 }; 30 29 -
TabularUnified library/tests/loggers_test.cpp ¶
r470 r477 10 10 using namespace bdm; 11 11 12 TEST(test_dirfilelog) 13 { 14 RV th = RV("{alog blog }"); 15 RV r = RV("{r }", "2"); 12 TEST ( test_dirfilelog ) { 13 RV th = RV ( "{alog blog }" ); 14 RV r = RV ( "{r }", "2" ); 16 15 17 string ls("exp");18 remove_all(ls.c_str());19 makedir(ls, false);20 remove_all("exp/dirfile");16 string ls ( "exp" ); 17 remove_all ( ls.c_str() ); 18 makedir ( ls, false ); 19 remove_all ( "exp/dirfile" ); 21 20 22 dirfilelog L("exp/dirfile", 10);21 dirfilelog L ( "exp/dirfile", 10 ); 23 22 24 25 23 int rid; 24 int thid; 26 25 27 rid = L.add(r, "");28 thid = L.add(th, "th");26 rid = L.add ( r, "" ); 27 thid = L.add ( th, "th" ); 29 28 30 29 L.init(); 31 30 32 for (int i = 0; i < 150; i++) {33 L.logit(rid, vec_2((double)i, (double)(i + 1)));34 L.logit(thid, vec_2((double)(100 - i), (double)(i - 50)));35 36 31 for ( int i = 0; i < 150; i++ ) { 32 L.logit ( rid, vec_2 ( ( double ) i, ( double ) ( i + 1 ) ) ); 33 L.logit ( thid, vec_2 ( ( double ) ( 100 - i ), ( double ) ( i - 50 ) ) ); 34 L.step(); 35 } 37 36 38 37 L.finalize(); 39 38 40 std::string expected(load_test_file("dirfile-format.matrix"));41 std::string actual(load_test_file("exp/dirfile/format"));42 CHECK_EQUAL(expected, actual);39 std::string expected ( load_test_file ( "dirfile-format.matrix" ) ); 40 std::string actual ( load_test_file ( "exp/dirfile/format" ) ); 41 CHECK_EQUAL ( expected, actual ); 43 42 } -
TabularUnified library/tests/mat_checks.cpp ¶
r465 r477 1 1 #include "mat_checks.h" 2 2 3 namespace UnitTest 4 { 3 namespace UnitTest { 5 4 6 bool AreClose (const itpp::vec &expected, const itpp::vec &actual,7 double tolerance) {8 if (expected.length() != actual.length()) {9 10 5 bool AreClose ( const itpp::vec &expected, const itpp::vec &actual, 6 double tolerance ) { 7 if ( expected.length() != actual.length() ) { 8 return false; 9 } 11 10 12 for (int i = 0; i < expected.length(); ++i) { 13 if (!AreClose(expected(i), actual(i), tolerance)) { 14 return false; 11 for ( int i = 0; i < expected.length(); ++i ) { 12 if ( !AreClose ( expected ( i ), actual ( i ), tolerance ) ) { 13 return false; 14 } 15 15 } 16 }17 16 18 17 return true; 19 18 } 20 19 21 bool AreClose (const itpp::vec &expected, const itpp::vec &actual,22 const itpp::vec &tolerance) {23 if ((expected.length() != actual.length()) ||24 (actual.length() != tolerance.length())) {25 26 20 bool AreClose ( const itpp::vec &expected, const itpp::vec &actual, 21 const itpp::vec &tolerance ) { 22 if ( ( expected.length() != actual.length() ) || 23 ( actual.length() != tolerance.length() ) ) { 24 return false; 25 } 27 26 28 for (int i = 0; i < expected.length(); ++i) { 29 if (!AreClose(expected(i), actual(i), tolerance(i))) { 30 return false; 27 for ( int i = 0; i < expected.length(); ++i ) { 28 if ( !AreClose ( expected ( i ), actual ( i ), tolerance ( i ) ) ) { 29 return false; 30 } 31 31 } 32 }33 32 34 33 return true; 35 34 } 36 35 37 bool AreClose (const itpp::mat &expected, const itpp::mat &actual, double tolerance) {38 if ((expected.rows() != actual.rows()) ||39 (expected.cols() != actual.cols())) {40 41 36 bool AreClose ( const itpp::mat &expected, const itpp::mat &actual, double tolerance ) { 37 if ( ( expected.rows() != actual.rows() ) || 38 ( expected.cols() != actual.cols() ) ) { 39 return false; 40 } 42 41 43 for (int i = 0; i < expected.rows(); ++i) { 44 for (int j = 0; j < expected.cols(); ++j) { 45 if (!AreClose(expected(i, j), actual(i, j), tolerance)) { 46 return false; 47 } 42 for ( int i = 0; i < expected.rows(); ++i ) { 43 for ( int j = 0; j < expected.cols(); ++j ) { 44 if ( !AreClose ( expected ( i, j ), actual ( i, j ), tolerance ) ) { 45 return false; 46 } 47 } 48 48 } 49 }50 49 51 50 return true; 52 51 } 53 52 … … 58 57 int CurrentContext::index = -1; 59 58 60 CurrentContext::CurrentContext(const char *name, int idx) 61 { 62 config_name = name; 63 index = idx; 59 CurrentContext::CurrentContext ( const char *name, int idx ) { 60 config_name = name; 61 index = idx; 64 62 } 65 63 66 CurrentContext::~CurrentContext() 67 { 68 config_name = "???"; 69 index = -1; 64 CurrentContext::~CurrentContext() { 65 config_name = "???"; 66 index = -1; 70 67 } -
TabularUnified library/tests/mat_checks.h ¶
r465 r477 17 17 #include "UnitTest++.h" 18 18 19 namespace UnitTest 20 { 19 namespace UnitTest { 21 20 22 bool AreClose (const itpp::vec &expected, const itpp::vec &actual,23 double tolerance);21 bool AreClose ( const itpp::vec &expected, const itpp::vec &actual, 22 double tolerance ); 24 23 25 bool AreClose (const itpp::vec &expected, const itpp::vec &actual,26 const itpp::vec &tolerance);24 bool AreClose ( const itpp::vec &expected, const itpp::vec &actual, 25 const itpp::vec &tolerance ); 27 26 28 bool AreClose (const itpp::mat &expected, const itpp::mat &actual,29 double tolerance);27 bool AreClose ( const itpp::mat &expected, const itpp::mat &actual, 28 double tolerance ); 30 29 31 inline void CheckClose (TestResults &results, const itpp::vec &expected,32 33 TestDetails const &details) {34 if (!AreClose(expected, actual, tolerance)) { 35 MemoryOutStream stream;36 stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual;30 inline void CheckClose ( TestResults &results, const itpp::vec &expected, 31 const itpp::vec &actual, double tolerance, 32 TestDetails const &details ) { 33 if ( !AreClose ( expected, actual, tolerance ) ) { 34 MemoryOutStream stream; 35 stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual; 37 36 38 results.OnTestFailure(details, stream.GetText());39 37 results.OnTestFailure ( details, stream.GetText() ); 38 } 40 39 } 41 40 42 inline void CheckClose (TestResults &results, const itpp::mat &expected,43 44 TestDetails const &details) {45 if (!AreClose(expected, actual, tolerance)) { 46 47 41 inline void CheckClose ( TestResults &results, const itpp::mat &expected, 42 const itpp::mat &actual, double tolerance, 43 TestDetails const &details ) { 44 if ( !AreClose ( expected, actual, tolerance ) ) { 45 MemoryOutStream stream; 46 stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual; 48 47 49 results.OnTestFailure(details, stream.GetText());50 48 results.OnTestFailure ( details, stream.GetText() ); 49 } 51 50 } 52 51 … … 56 55 blocks having an instance of this class (which sets the globals for 57 56 error reporting). */ 58 class CurrentContext 59 { 57 class CurrentContext { 60 58 private: 61 62 59 static const char *config_name; 60 static int index; 63 61 64 62 public: 65 66 CurrentContext(const char *name, int idx);67 63 // the pointer must stay valid for the lifetime of the object 64 CurrentContext ( const char *name, int idx ); 65 ~CurrentContext(); 68 66 69 70 static void CheckEqualEx(UnitTest::TestResults& results,71 72 73 UnitTest::TestDetails const& details) {74 if (!(expected == actual)) {75 76 67 template<typename Expected, typename Actual> 68 static void CheckEqualEx ( UnitTest::TestResults& results, 69 Expected const& expected, 70 Actual const& actual, 71 UnitTest::TestDetails const& details ) { 72 if ( ! ( expected == actual ) ) { 73 UnitTest::MemoryOutStream stream; 74 stream << "error at " << config_name << '[' << index << "]: expected " << expected << " but was " << actual; 77 75 78 results.OnTestFailure(details, stream.GetText()); 76 results.OnTestFailure ( details, stream.GetText() ); 77 } 79 78 } 80 }81 79 82 83 static void CheckCloseEx(UnitTest::TestResults& results,84 85 86 87 UnitTest::TestDetails const& details) {88 if (!UnitTest::AreClose(expected, actual, tolerance)) { 89 90 80 template<typename Expected, typename Actual, typename Tolerance> 81 static void CheckCloseEx ( UnitTest::TestResults& results, 82 Expected const& expected, 83 Actual const& actual, 84 Tolerance const& tolerance, 85 UnitTest::TestDetails const& details ) { 86 if ( !UnitTest::AreClose ( expected, actual, tolerance ) ) { 87 UnitTest::MemoryOutStream stream; 88 stream << "error at " << config_name << '[' << index << "]: expected " << expected << " +/- " << tolerance << " but was " << actual; 91 89 92 results.OnTestFailure(details, stream.GetText()); 90 results.OnTestFailure ( details, stream.GetText() ); 91 } 93 92 } 94 }95 93 }; 96 94 -
TabularUnified library/tests/merger_2d_test.cpp ¶
r386 r477 14 14 15 15 RNG_randomize(); 16 17 RV x ( "{x }","1" );18 RV y ( "{y }","1" );19 16 20 RV xy=x; xy.add(y); 21 22 enorm<fsqmat> f1; f1.set_rv ( xy ); 23 enorm<fsqmat> f2; f1.set_rv ( xy ); 24 17 RV x ( "{x }", "1" ); 18 RV y ( "{y }", "1" ); 19 20 RV xy = x; 21 xy.add ( y ); 22 23 enorm<fsqmat> f1; 24 f1.set_rv ( xy ); 25 enorm<fsqmat> f2; 26 f1.set_rv ( xy ); 27 25 28 mat R1 ( "0.5 0.48; 0.48 0.5" ); 26 29 mat R2 ( "0.5 0; 0 0.1" ); 27 f1.set_parameters ( "1 1", R1 );28 f2.set_parameters ( "1 1", mat ( "0.5 0; 0 0.1" ) );29 30 f1.set_parameters ( "1 1", R1 ); 31 f2.set_parameters ( "1 1", mat ( "0.5 0; 0 0.1" ) ); 32 30 33 Array<mpdf* > A ( 2 ); 31 mepdf A1 (&f1);32 mepdf A2 (&f2);33 A ( 0 ) = &A1;34 A ( 1 ) = &A2;35 36 int Npoints =100;37 mat x_grid (1,Npoints);38 x_grid.set_row (0,linspace ( -2.0, 4.0, Npoints ));39 mat y_grid (1,Npoints);40 y_grid.set_row (0,linspace ( -2.0, 4.0, Npoints ));41 42 mat Grid ( 2,Npoints*Npoints);43 Grid.set_submatrix ( 0, 0, kron(x_grid,ones(1,Npoints)) );44 Grid.set_submatrix ( 1, 0, kron(ones(1,Npoints), y_grid) );45 34 mepdf A1 ( &f1 ); 35 mepdf A2 ( &f2 ); 36 A ( 0 ) = &A1; 37 A ( 1 ) = &A2; 38 39 int Npoints = 100; 40 mat x_grid ( 1, Npoints ); 41 x_grid.set_row ( 0, linspace ( -2.0, 4.0, Npoints ) ); 42 mat y_grid ( 1, Npoints ); 43 y_grid.set_row ( 0, linspace ( -2.0, 4.0, Npoints ) ); 44 45 mat Grid ( 2, Npoints*Npoints ); 46 Grid.set_submatrix ( 0, 0, kron ( x_grid, ones ( 1, Npoints ) ) ); 47 Grid.set_submatrix ( 1, 0, kron ( ones ( 1, Npoints ), y_grid ) ); 48 46 49 merger_mix M ( A ); 47 enorm<fsqmat> g0; g0.set_rv(xy); 48 g0.set_parameters(vec("1 1"),mat("10 0; 0 10")); 49 50 M.set_parameters(1); 51 M.set_method(LOGNORMAL,1e8); 52 M.set_support(g0,400); 50 enorm<fsqmat> g0; 51 g0.set_rv ( xy ); 52 g0.set_parameters ( vec ( "1 1" ), mat ( "10 0; 0 10" ) ); 53 54 M.set_parameters ( 1 ); 55 M.set_method ( LOGNORMAL, 1e8 ); 56 M.set_support ( g0, 400 ); 53 57 M.merge(); 54 58 55 59 MixEF &MM = M._Mix(); 56 60 emix* MP = MM.epredictor(); //xy 57 58 vec Res1 = M.evallog_m (Grid);59 mat Res2 = ( MP)->evallog_M(Grid);60 61 it_file it ("merger_2d_test.it");62 it << Name ("Npoints") << Npoints;63 it << Name ("Grid") << Grid;64 it << Name ("Res1") << Res1;65 it << Name ("Res2") << Res2;66 it << Name ("S1") << f1.evallog_m(Grid);67 it << Name ("S2") << f2.evallog_m(Grid);68 cout << ( (enorm<ldmat>*)(MP->_Coms(0)))->_R().to_mat() << endl;61 62 vec Res1 = M.evallog_m ( Grid ); 63 mat Res2 = ( MP )->evallog_M ( Grid ); 64 65 it_file it ( "merger_2d_test.it" ); 66 it << Name ( "Npoints" ) << Npoints; 67 it << Name ( "Grid" ) << Grid; 68 it << Name ( "Res1" ) << Res1; 69 it << Name ( "Res2" ) << Res2; 70 it << Name ( "S1" ) << f1.evallog_m ( Grid ); 71 it << Name ( "S2" ) << f2.evallog_m ( Grid ); 72 cout << ( ( enorm<ldmat>* ) ( MP->_Coms ( 0 ) ) )->_R().to_mat() << endl; 69 73 } -
TabularUnified library/tests/merger_iter_test.cpp ¶
r386 r477 14 14 15 15 RNG_randomize(); 16 17 RV x ( "{x }","1" );18 RV y ( "{y }","1" );19 16 20 RV xy=x; xy.add(y); 21 22 enorm<fsqmat> f1;f1.set_rv ( xy ); 23 enorm<fsqmat> f2;f2.set_rv ( xy ); 24 enorm<fsqmat> f3;f3.set_rv(y); 25 26 f1.set_parameters ( "4 3",mat ( "0.4 0.3; 0.3 0.4" ) ); 27 f2.set_parameters ( "1 3",mat ( "0.3 -0.2; -0.2 0.3" ) ); 28 f3.set_parameters ( "2",mat("0.4") ); 29 17 RV x ( "{x }", "1" ); 18 RV y ( "{y }", "1" ); 19 20 RV xy = x; 21 xy.add ( y ); 22 23 enorm<fsqmat> f1; 24 f1.set_rv ( xy ); 25 enorm<fsqmat> f2; 26 f2.set_rv ( xy ); 27 enorm<fsqmat> f3; 28 f3.set_rv ( y ); 29 30 f1.set_parameters ( "4 3", mat ( "0.4 0.3; 0.3 0.4" ) ); 31 f2.set_parameters ( "1 3", mat ( "0.3 -0.2; -0.2 0.3" ) ); 32 f3.set_parameters ( "2", mat ( "0.4" ) ); 33 30 34 Array<mpdf* > A ( 3 ); 31 mepdf A1 (&f1);32 mepdf A2 (&f2);33 mepdf A3 (&f3);34 A ( 0 ) = &A1;35 A ( 1 ) = &A2;36 A ( 2 ) = &A3;37 38 int Npoints =100;39 mat x_grid (1,Npoints);40 x_grid.set_row (0,linspace ( -2.0, 4.0, Npoints ));41 mat y_grid (1,Npoints);42 y_grid.set_row (0,linspace ( -2.0, 4.0, Npoints ));43 44 mat Grid ( 2,Npoints*Npoints);45 Grid.set_submatrix ( 0, 0, kron(x_grid,ones(1,Npoints)) );46 Grid.set_submatrix ( 1, 0, kron(ones(1,Npoints), y_grid) );47 35 mepdf A1 ( &f1 ); 36 mepdf A2 ( &f2 ); 37 mepdf A3 ( &f3 ); 38 A ( 0 ) = &A1; 39 A ( 1 ) = &A2; 40 A ( 2 ) = &A3; 41 42 int Npoints = 100; 43 mat x_grid ( 1, Npoints ); 44 x_grid.set_row ( 0, linspace ( -2.0, 4.0, Npoints ) ); 45 mat y_grid ( 1, Npoints ); 46 y_grid.set_row ( 0, linspace ( -2.0, 4.0, Npoints ) ); 47 48 mat Grid ( 2, Npoints*Npoints ); 49 Grid.set_submatrix ( 0, 0, kron ( x_grid, ones ( 1, Npoints ) ) ); 50 Grid.set_submatrix ( 1, 0, kron ( ones ( 1, Npoints ), y_grid ) ); 51 48 52 merger_mix M ( A ); 49 enorm<fsqmat> g0; g0.set_rv(xy); 50 g0.set_parameters(vec("4 4"),mat("1 0; 0 1")); 51 52 M.set_parameters(5); 53 M.set_method(LOGNORMAL,1.2); 54 M.set_support(g0,400); 53 enorm<fsqmat> g0; 54 g0.set_rv ( xy ); 55 g0.set_parameters ( vec ( "4 4" ), mat ( "1 0; 0 1" ) ); 56 57 M.set_parameters ( 5 ); 58 M.set_method ( LOGNORMAL, 1.2 ); 59 M.set_support ( g0, 400 ); 55 60 M.merge(); 56 61 57 62 MixEF &MM = M._Mix(); 58 63 epdf* MP = MM.epredictor();//xy 59 60 vec Res1 = M.evallog_m (Grid);61 mat Res2 = ( (emix*)MP)->evallog_M(Grid);62 63 it_file it ("merger_iter_test.it");64 it << Name ("Npoints") << Npoints;65 it << Name ("Grid") << Grid;66 it << Name ("Res1") << Res1;67 it << Name ("Res2") << Res2;64 65 vec Res1 = M.evallog_m ( Grid ); 66 mat Res2 = ( ( emix* ) MP )->evallog_M ( Grid ); 67 68 it_file it ( "merger_iter_test.it" ); 69 it << Name ( "Npoints" ) << Npoints; 70 it << Name ( "Grid" ) << Grid; 71 it << Name ( "Res1" ) << Res1; 72 it << Name ( "Res2" ) << Res2; 68 73 } -
TabularUnified library/tests/merger_test.cpp ¶
r386 r477 13 13 RNG_randomize(); 14 14 15 RV x ( "{x }", "1" );15 RV x ( "{x }", "1" ); 16 16 17 17 RV z ( x ); 18 18 19 enorm<fsqmat> f1; f1.set_rv ( x ); 20 enorm<fsqmat> f2; f2.set_rv ( x ); 19 enorm<fsqmat> f1; 20 f1.set_rv ( x ); 21 enorm<fsqmat> f2; 22 f2.set_rv ( x ); 21 23 22 f1.set_parameters ( "-5", mat ( "2" ) );23 f2.set_parameters ( "5", mat ( "10" ) );24 f1.set_parameters ( "-5", mat ( "2" ) ); 25 f2.set_parameters ( "5", mat ( "10" ) ); 24 26 25 27 Array<mpdf* > A ( 2 ); 26 28 mepdf A1 ( &f1 ); 27 29 mepdf A2 ( &f2 ); 28 A ( 0 ) = &A1;29 A ( 1 ) = &A2;30 A ( 0 ) = &A1; 31 A ( 1 ) = &A2; 30 32 31 int Npoints =100;32 mat x_grid ( 1, Npoints );33 x_grid.set_row ( 0, linspace ( -10.0, 10.0 ) );33 int Npoints = 100; 34 mat x_grid ( 1, Npoints ); 35 x_grid.set_row ( 0, linspace ( -10.0, 10.0 ) ); 34 36 35 vec l_f1 =f1.evallog_m ( x_grid );36 vec l_f2 =f2.evallog_m ( x_grid );37 mat lW ( 2, Npoints );37 vec l_f1 = f1.evallog_m ( x_grid ); 38 vec l_f2 = f2.evallog_m ( x_grid ); 39 mat lW ( 2, Npoints ); 38 40 lW.set_row ( 0, l_f1 ); 39 41 lW.set_row ( 1, l_f2 ); 40 42 41 43 merger_base M ( A ); 42 enorm<fsqmat> g0; g0.set_rv ( x ); 43 g0.set_parameters ( vec ( "0.0" ),mat ( "100.0" ) ); 44 enorm<fsqmat> g0; 45 g0.set_rv ( x ); 46 g0.set_parameters ( vec ( "0.0" ), mat ( "100.0" ) ); 44 47 45 M.set_method ( 46 M.set_support (g0,200);48 M.set_method ( LOGNORMAL, 1.2 ); 49 M.set_support ( g0, 200 ); 47 50 M.merge (); 48 51 -
TabularUnified library/tests/mixtures_test.cpp ¶
r394 r477 9 9 10 10 void disp_mix2D ( const MixEF &Mi ) { 11 const eprod &ep =((const eprod&)(Mi.posterior()));11 const eprod &ep = ( ( const eprod& ) ( Mi.posterior() ) ); 12 12 int i; 13 mat Var ( 2, 2 ),M ( 1,2 );14 for ( i =0; i<ep._rv().length() - 1; i++ ) { // -1 => last one is the weight15 ( ( egiw* ) ep ( i ) )->mean_mat ( M, Var );16 cout << "Mean: " << M <<endl << "Variance: "<<endl <<Var<<endl;13 mat Var ( 2, 2 ), M ( 1, 2 ); 14 for ( i = 0; i < ep._rv().length() - 1; i++ ) { // -1 => last one is the weight 15 ( ( egiw* ) ep ( i ) )->mean_mat ( M, Var ); 16 cout << "Mean: " << M << endl << "Variance: " << endl << Var << endl; 17 17 } 18 cout << "Weights: "<< ep ( i )->mean() <<endl;18 cout << "Weights: " << ep ( i )->mean() << endl; 19 19 } 20 20 21 mat grid2D ( const MixEF &M, const vec &xb, const vec &yb, int Ngr=100 ) {22 mat PPdf ( Ngr +1,Ngr+1 );21 mat grid2D ( const MixEF &M, const vec &xb, const vec &yb, int Ngr = 100 ) { 22 mat PPdf ( Ngr + 1, Ngr + 1 ); 23 23 vec rgr ( 3 ); 24 24 25 rgr ( 2 ) =1; 26 int i=0,j=0; 27 double xstep=( xb ( 1 )-xb ( 0 ) ) /Ngr; 28 double ystep=( yb ( 1 )-yb ( 0 ) ) /Ngr; 29 30 for ( double x=xb ( 0 );x<=xb ( 1 );x+= xstep,i++ ) { 31 rgr ( 0 ) =x;j=0; 32 for ( double y=yb(0);y<=yb(1);y+=ystep,j++ ) { 33 rgr ( 1 ) =y; 34 PPdf ( i,j ) =exp ( M.logpred ( rgr ) ); 25 rgr ( 2 ) = 1; 26 int i = 0, j = 0; 27 double xstep = ( xb ( 1 ) - xb ( 0 ) ) / Ngr; 28 double ystep = ( yb ( 1 ) - yb ( 0 ) ) / Ngr; 29 30 for ( double x = xb ( 0 ); x <= xb ( 1 ); x += xstep, i++ ) { 31 rgr ( 0 ) = x; 32 j = 0; 33 for ( double y = yb ( 0 ); y <= yb ( 1 ); y += ystep, j++ ) { 34 rgr ( 1 ) = y; 35 PPdf ( i, j ) = exp ( M.logpred ( rgr ) ); 35 36 } 36 37 } … … 39 40 40 41 int main() { 41 RV x ( "{x }", "2" );42 RV x ( "{x }", "2" ); 42 43 43 44 44 45 cout << "Test for estimation of a 2D Gaussian mixture" << endl; 45 46 /////////////////////////////////// … … 52 53 fsqmat V2 ( mat ( "2 -0.1; -0.1 2" ) ); 53 54 54 enorm<fsqmat> C1; C1.set_rv ( x ); 55 C1.set_parameters ( m1,V1 ); 56 enorm<fsqmat> C2; C2.set_rv ( x ); 57 C2.set_parameters ( m2,V2 ); 55 enorm<fsqmat> C1; 56 C1.set_rv ( x ); 57 C1.set_parameters ( m1, V1 ); 58 enorm<fsqmat> C2; 59 C2.set_rv ( x ); 60 C2.set_parameters ( m2, V2 ); 58 61 59 Array<epdf*> Sim ( 2 ); Sim ( 0 ) =&C1;Sim ( 1 ) =&C2; 60 emix Simul;Simul.set_rv ( x ); 62 Array<epdf*> Sim ( 2 ); 63 Sim ( 0 ) = &C1; 64 Sim ( 1 ) = &C2; 65 emix Simul; 66 Simul.set_rv ( x ); 61 67 Simul.set_parameters ( "0.5 0.6", Sim, false ); 62 68 63 69 // Sample parameters 64 70 int ndat = 100; 65 mat Smp = Simul.sample_m ( ndat );71 mat Smp = Simul.sample_m ( ndat ); 66 72 67 cout << "Simulated means: " << m1 << " and " << m2 <<endl;68 cout << "Simulated covariances: " << endl <<V1 <<" and " <<endl<< V2 <<endl;73 cout << "Simulated means: " << m1 << " and " << m2 << endl; 74 cout << "Simulated covariances: " << endl << V1 << " and " << endl << V2 << endl; 69 75 70 76 ////////////////////////////// … … 72 78 73 79 // Initial values of components 74 mat V0=1e-4*eye ( 3 ); V0 ( 0,0 ) *=100;V0 ( 1,1 ) *=100; 75 mat Vp="0 0 1; 0 0 1; 1 1 0"; 76 Vp*=5*1e-5; 80 mat V0 = 1e-4 * eye ( 3 ); 81 V0 ( 0, 0 ) *= 100; 82 V0 ( 1, 1 ) *= 100; 83 mat Vp = "0 0 1; 0 0 1; 1 1 0"; 84 Vp *= 5 * 1e-5; 77 85 78 ARX M1;M1.set_statistics(2,V0 - Vp,8 ); 79 ARX M2;M2.set_statistics (2, V0 + Vp,8 ); 80 86 ARX M1; 87 M1.set_statistics ( 2, V0 - Vp, 8 ); 88 ARX M2; 89 M2.set_statistics ( 2, V0 + Vp, 8 ); 90 81 91 // Build mixture model 82 Array<BMEF*> A ( 2 ); A ( 0 ) =&M1; A ( 1 ) =&M2; 83 MixEF Post ( A,"0.5 0.5" ); 84 cout << "Initial mixture:"<<endl; 85 disp_mix2D(Post); 86 92 Array<BMEF*> A ( 2 ); 93 A ( 0 ) = &M1; 94 A ( 1 ) = &M2; 95 MixEF Post ( A, "0.5 0.5" ); 96 cout << "Initial mixture:" << endl; 97 disp_mix2D ( Post ); 98 87 99 // Add ones for constant coefficients 88 mat Data = concat_vertical ( Smp, ones ( 1, Smp.cols() ) );100 mat Data = concat_vertical ( Smp, ones ( 1, Smp.cols() ) ); 89 101 Post.bayes ( Data ); 90 102 91 cout << "Posterior mixture:" << endl;92 disp_mix2D (Post);103 cout << "Posterior mixture:" << endl; 104 disp_mix2D ( Post ); 93 105 94 106 //TEST random initialization 95 107 RNG_randomize(); 96 108 ARX Aflat; 97 Aflat.set_statistics (2,V0,7);109 Aflat.set_statistics ( 2, V0, 7 ); 98 110 MixEF RND; 99 RND.init(&Aflat,Data,10); // already initialized! 100 cout << endl<< "== Randomly initialized mixture ==" <<endl; 101 cout << endl<< "== INIT ==" <<endl; 102 disp_mix2D(RND); 103 mat PPdf_I=grid2D(RND, vec_2(-5.0,5.0), vec_2(-5.0,5.0));; 104 105 RND.bayes(Data); 106 cout << endl<< "== BAYES ==" <<endl; 107 disp_mix2D(RND); 111 RND.init ( &Aflat, Data, 10 ); // already initialized! 112 cout << endl << "== Randomly initialized mixture ==" << endl; 113 cout << endl << "== INIT ==" << endl; 114 disp_mix2D ( RND ); 115 mat PPdf_I = grid2D ( RND, vec_2 ( -5.0, 5.0 ), vec_2 ( -5.0, 5.0 ) );; 108 116 109 110 it_file of ( "mixef_test.it",true ); 111 of<< Name ( "Smp" ) <<Smp; 112 of<<Name ( "PPdf" ) <<grid2D(Post, vec_2(-5.0,5.0), vec_2(-5.0,5.0)); 113 of<<Name ( "PPdf_I" ) <<PPdf_I; 114 of<<Name ( "PPdf_RND" ) <<grid2D(RND, vec_2(-5.0,5.0), vec_2(-5.0,5.0)); 117 RND.bayes ( Data ); 118 cout << endl << "== BAYES ==" << endl; 119 disp_mix2D ( RND ); 115 120 116 cout << endl <<"Variables written to file mixef_test.it:"<<endl; 117 cout << "Smp : data sampled from the simulator " <<endl; 118 cout << "PPdf : posterior density on a grid <-5,5><-5,5>"<<endl; 119 cout << "PPdf_RND : posterior density of randomly initilaized mixture on a grid <-5,5><-5,5>"<<endl; 121 122 it_file of ( "mixef_test.it", true ); 123 of << Name ( "Smp" ) << Smp; 124 of << Name ( "PPdf" ) << grid2D ( Post, vec_2 ( -5.0, 5.0 ), vec_2 ( -5.0, 5.0 ) ); 125 of << Name ( "PPdf_I" ) << PPdf_I; 126 of << Name ( "PPdf_RND" ) << grid2D ( RND, vec_2 ( -5.0, 5.0 ), vec_2 ( -5.0, 5.0 ) ); 127 128 cout << endl << "Variables written to file mixef_test.it:" << endl; 129 cout << "Smp : data sampled from the simulator " << endl; 130 cout << "PPdf : posterior density on a grid <-5,5><-5,5>" << endl; 131 cout << "PPdf_RND : posterior density of randomly initilaized mixture on a grid <-5,5><-5,5>" << endl; 120 132 } -
TabularUnified library/tests/mpdf_harness.cpp ¶
r471 r477 10 10 11 11 template<> 12 const ParticularUI<mpdf_harness> &ParticularUI<mpdf_harness>::factory (13 ParticularUI<mpdf_harness> ("mpdf_harness"));12 const ParticularUI<mpdf_harness> &ParticularUI<mpdf_harness>::factory ( 13 ParticularUI<mpdf_harness> ( "mpdf_harness" ) ); 14 14 15 void mpdf_harness::test_config (const char *config_file_name) {16 15 void mpdf_harness::test_config ( const char *config_file_name ) { 16 RV::clear_all(); 17 17 18 UIFile in(config_file_name);19 20 UI::get (input, in, "data");21 22 CHECK(sz > 0);23 for (int i = 0; i < sz; ++i) {24 input(i)->test(config_file_name, i);25 18 UIFile in ( config_file_name ); 19 Array<mpdf_harness *> input; 20 UI::get ( input, in, "data" ); 21 int sz = input.size(); 22 CHECK ( sz > 0 ); 23 for ( int i = 0; i < sz; ++i ) { 24 input ( i )->test ( config_file_name, i ); 25 } 26 26 } 27 27 28 void mpdf_harness::from_setting (const Setting &set) {29 hmpdf = UI::build<mpdf> (set, "mpdf", UI::compulsory);30 UI::get(cond, set, "cond", UI::compulsory);31 UI::get(mean, set, "mean", UI::compulsory);28 void mpdf_harness::from_setting ( const Setting &set ) { 29 hmpdf = UI::build<mpdf> ( set, "mpdf", UI::compulsory ); 30 UI::get ( cond, set, "cond", UI::compulsory ); 31 UI::get ( mean, set, "mean", UI::compulsory ); 32 32 33 33 34 UI::get (nsamples, set, "nsamples");35 UI::get(R, set, "R");36 UI::get (tolerance, set, "tolerance");34 UI::get ( nsamples, set, "nsamples" ); 35 UI::get ( R, set, "R" ); 36 UI::get ( tolerance, set, "tolerance" ); 37 37 } 38 38 39 void mpdf_harness::test(const char *config_name, int idx) 40 { 41 CurrentContext cc(config_name, idx); 39 void mpdf_harness::test ( const char *config_name, int idx ) { 40 CurrentContext cc ( config_name, idx ); 42 41 43 mat smp = hmpdf->samplecond_m(cond, nsamples);44 45 vec emu = smp * ones(n) / n;46 mat er = (smp * smp.T()) / n - outer_product(emu, emu);47 CHECK_CLOSE_EX(mean, emu, tolerance);48 CHECK_CLOSE_EX(R, er, tolerance);42 mat smp = hmpdf->samplecond_m ( cond, nsamples ); 43 int n = smp.cols(); 44 vec emu = smp * ones ( n ) / n; 45 mat er = ( smp * smp.T() ) / n - outer_product ( emu, emu ); 46 CHECK_CLOSE_EX ( mean, emu, tolerance ); 47 CHECK_CLOSE_EX ( R, er, tolerance ); 49 48 } 50 49 -
TabularUnified library/tests/mpdf_harness.h ¶
r456 r477 22 22 #include "base/user_info.h" 23 23 24 namespace bdm 25 { 24 namespace bdm { 26 25 27 class mpdf_harness : public root 28 { 26 class mpdf_harness : public root { 29 27 private: 30 31 32 33 34 35 28 shared_ptr<mpdf> hmpdf; 29 vec cond; 30 vec mean; 31 int nsamples; 32 mat R; 33 double tolerance; 36 34 37 public: 38 static void test_config(const char *config_file_name);35 public: 36 static void test_config ( const char *config_file_name ); 39 37 40 mpdf_harness():nsamples(1000), tolerance(0.1) { }38 mpdf_harness() : nsamples ( 1000 ), tolerance ( 0.1 ) { } 41 39 42 virtual void test(const char *config_name, int idx);40 virtual void test ( const char *config_name, int idx ); 43 41 44 void from_setting(const Setting &set);42 void from_setting ( const Setting &set ); 45 43 46 44 protected: 47 mpdf *get_mpdf() { return hmpdf.get(); } 45 mpdf *get_mpdf() { 46 return hmpdf.get(); 47 } 48 48 }; 49 49 -
TabularUnified library/tests/mpdf_test.cpp ¶
r462 r477 11 11 12 12 template<> 13 const ParticularUI<mgamma> &ParticularUI<mgamma>::factory (14 ParticularUI<mgamma> ("mgamma"));13 const ParticularUI<mgamma> &ParticularUI<mgamma>::factory ( 14 ParticularUI<mgamma> ( "mgamma" ) ); 15 15 16 16 template<> 17 const ParticularUI<mlnorm<ldmat> > &ParticularUI<mlnorm<ldmat> >::factory (18 ParticularUI<mlnorm<ldmat> > ("mlnorm<ldmat>"));17 const ParticularUI<mlnorm<ldmat> > &ParticularUI<mlnorm<ldmat> >::factory ( 18 ParticularUI<mlnorm<ldmat> > ( "mlnorm<ldmat>" ) ); 19 19 20 TEST (test_mepdf) {21 mpdf_harness::test_config("mepdf.cfg");20 TEST ( test_mepdf ) { 21 mpdf_harness::test_config ( "mepdf.cfg" ); 22 22 } 23 23 24 TEST (test_mgamma) {25 mpdf_harness::test_config("mgamma.cfg");24 TEST ( test_mgamma ) { 25 mpdf_harness::test_config ( "mgamma.cfg" ); 26 26 } 27 27 28 TEST (test_mlnorm) {29 mpdf_harness::test_config("mlnorm.cfg");28 TEST ( test_mlnorm ) { 29 mpdf_harness::test_config ( "mlnorm.cfg" ); 30 30 } -
TabularUnified library/tests/rv_test.cpp ¶
r431 r477 6 6 using namespace bdm; 7 7 8 TEST(test_rv) 9 { 10 RV a = RV("{a }", "3"); 11 CHECK_EQUAL(1, a.length()); 12 CHECK_EQUAL(3, a.size(0)); 13 CHECK_EQUAL(std::string("a"), a.name(0)); 8 TEST ( test_rv ) { 9 RV a = RV ( "{a }", "3" ); 10 CHECK_EQUAL ( 1, a.length() ); 11 CHECK_EQUAL ( 3, a.size ( 0 ) ); 12 CHECK_EQUAL ( std::string ( "a" ), a.name ( 0 ) ); 14 13 15 RV b = RV("{b }", "2");16 CHECK_EQUAL(0, b.mint());14 RV b = RV ( "{b }", "2" ); 15 CHECK_EQUAL ( 0, b.mint() ); 17 16 18 RV c = RV("{c }");19 CHECK_EQUAL(1, c.length());20 CHECK_EQUAL(1, c.size(0));17 RV c = RV ( "{c }" ); 18 CHECK_EQUAL ( 1, c.length() ); 19 CHECK_EQUAL ( 1, c.size ( 0 ) ); 21 20 22 RV trv = RV("{e f }", "1 2", "3 4");23 CHECK_EQUAL(2, trv.length());24 CHECK_EQUAL(3, trv.mint());21 RV trv = RV ( "{e f }", "1 2", "3 4" ); 22 CHECK_EQUAL ( 2, trv.length() ); 23 CHECK_EQUAL ( 3, trv.mint() ); 25 24 26 27 28 bool added = ab.add(b);29 CHECK(added);30 CHECK_EQUAL(2, ab.length());31 CHECK_EQUAL(3, ab.size(0));32 CHECK_EQUAL(std::string("a"), ab.name(0));33 CHECK_EQUAL(2, ab.size(1));34 CHECK_EQUAL(std::string("b"), ab.name(1));25 // add a and b 26 RV ab = a; 27 bool added = ab.add ( b ); 28 CHECK ( added ); 29 CHECK_EQUAL ( 2, ab.length() ); 30 CHECK_EQUAL ( 3, ab.size ( 0 ) ); 31 CHECK_EQUAL ( std::string ( "a" ), ab.name ( 0 ) ); 32 CHECK_EQUAL ( 2, ab.size ( 1 ) ); 33 CHECK_EQUAL ( std::string ( "b" ), ab.name ( 1 ) ); 35 34 36 37 38 CHECK_EQUAL(std::string("1(3)=a_{0}; 2(2)=b_{0}; "), abss.str());35 std::stringstream abss; 36 abss << ab; 37 CHECK_EQUAL ( std::string ( "1(3)=a_{0}; 2(2)=b_{0}; " ), abss.str() ); 39 38 40 41 RV abc = concat(ab, c);42 CHECK_EQUAL(3, abc.length());43 44 45 CHECK_EQUAL(std::string("1(3)=a_{0}; 2(2)=b_{0}; 3(1)=c_{0}; "), abcss.str());39 // concat a, b and c 40 RV abc = concat ( ab, c ); 41 CHECK_EQUAL ( 3, abc.length() ); 42 std::stringstream abcss; 43 abcss << abc; 44 CHECK_EQUAL ( std::string ( "1(3)=a_{0}; 2(2)=b_{0}; 3(1)=c_{0}; " ), abcss.str() ); 46 45 47 48 49 50 int exp_sz = sizeof(exp_ids) / sizeof(exp_ids[0]);51 CHECK_EQUAL(exp_sz, s.ids.size());52 CHECK_EQUAL(exp_sz, s.times.size());53 for (int i = 0; i < exp_sz; ++i) {54 CHECK_EQUAL(exp_ids[i], s.ids(i));55 CHECK_EQUAL(0, s.times(i));56 46 // structure of a, b, c 47 str s = abc.tostr(); 48 int exp_ids[] = { 1, 1, 1, 2, 2, 3 }; 49 int exp_sz = sizeof ( exp_ids ) / sizeof ( exp_ids[0] ); 50 CHECK_EQUAL ( exp_sz, s.ids.size() ); 51 CHECK_EQUAL ( exp_sz, s.times.size() ); 52 for ( int i = 0; i < exp_sz; ++i ) { 53 CHECK_EQUAL ( exp_ids[i], s.ids ( i ) ); 54 CHECK_EQUAL ( 0, s.times ( i ) ); 55 } 57 56 58 RV slice = abc(1, 2);59 CHECK_EQUAL(1, slice.length());60 CHECK_EQUAL(3, slice.size(0));61 CHECK_EQUAL(std::string("a"), slice.name(0));57 RV slice = abc ( 1, 2 ); 58 CHECK_EQUAL ( 1, slice.length() ); 59 CHECK_EQUAL ( 3, slice.size ( 0 ) ); 60 CHECK_EQUAL ( std::string ( "a" ), slice.name ( 0 ) ); 62 61 63 64 ivec f = a.findself(abc);65 CHECK_EQUAL(1, f.length());66 CHECK_EQUAL(0, f(0));62 // find a in abc 63 ivec f = a.findself ( abc ); 64 CHECK_EQUAL ( 1, f.length() ); 65 CHECK_EQUAL ( 0, f ( 0 ) ); 67 66 68 69 f = abc.findself(a);70 71 CHECK_EQUAL(3, f.length());72 for (unsigned i = 0;73 i < sizeof(exp_indices) / sizeof(exp_indices[0]);74 ++i) {75 CHECK_EQUAL(exp_indices[i], f(i));76 67 // find abc in a 68 f = abc.findself ( a ); 69 int exp_indices[] = { 0, -1, -1 }; 70 CHECK_EQUAL ( 3, f.length() ); 71 for ( unsigned i = 0; 72 i < sizeof ( exp_indices ) / sizeof ( exp_indices[0] ); 73 ++i ) { 74 CHECK_EQUAL ( exp_indices[i], f ( i ) ); 75 } 77 76 78 79 RV ac = abc.subt(b);80 81 82 CHECK_EQUAL(std::string("1(3)=a_{0}; 3(1)=c_{0}; "), acss.str());77 // subtract b from abc 78 RV ac = abc.subt ( b ); 79 std::stringstream acss; 80 acss << ac; 81 CHECK_EQUAL ( std::string ( "1(3)=a_{0}; 3(1)=c_{0}; " ), acss.str() ); 83 82 84 85 ivec di = ac.dataind(abc);86 87 exp_sz = sizeof(exp_di) / sizeof(exp_di[0]);88 CHECK_EQUAL(exp_sz, di.size());89 for (int i = 0; i < exp_sz; ++i) {90 CHECK_EQUAL(exp_di[i], di(i));91 83 // data index of ac in abc 84 ivec di = ac.dataind ( abc ); 85 int exp_di[] = { 0, 1, 2, 5 }; 86 exp_sz = sizeof ( exp_di ) / sizeof ( exp_di[0] ); 87 CHECK_EQUAL ( exp_sz, di.size() ); 88 for ( int i = 0; i < exp_sz; ++i ) { 89 CHECK_EQUAL ( exp_di[i], di ( i ) ); 90 } 92 91 93 // Copy indices between ba and ab 94 RV ba = b; 95 ba.add(a); 96 97 ivec ai; 98 ivec bi; 99 ba.dataind(ac, ai, bi); 92 // Copy indices between ba and ab 93 RV ba = b; 94 ba.add ( a ); 100 95 101 int exp_ai[] = { 2, 3, 4 }; 102 exp_sz = sizeof(exp_ai) / sizeof(exp_ai[0]); 103 CHECK_EQUAL(exp_sz, ai.size()); 104 for (unsigned i = 0; 105 i < sizeof(exp_ai) / sizeof(exp_ai[0]); 106 ++i) { 107 CHECK_EQUAL(exp_ai[i], ai(i)); 108 } 96 ivec ai; 97 ivec bi; 98 ba.dataind ( ac, ai, bi ); 109 99 110 int exp_bi[] = { 0, 1, 2 }; 111 exp_sz = sizeof(exp_bi) / sizeof(exp_bi[0]); 112 CHECK_EQUAL(exp_sz, bi.size()); 113 for (unsigned i = 0; 114 i < sizeof(exp_bi) / sizeof(exp_bi[0]); 115 ++i) { 116 CHECK_EQUAL(exp_bi[i], bi(i)); 117 } 100 int exp_ai[] = { 2, 3, 4 }; 101 exp_sz = sizeof ( exp_ai ) / sizeof ( exp_ai[0] ); 102 CHECK_EQUAL ( exp_sz, ai.size() ); 103 for ( unsigned i = 0; 104 i < sizeof ( exp_ai ) / sizeof ( exp_ai[0] ); 105 ++i ) { 106 CHECK_EQUAL ( exp_ai[i], ai ( i ) ); 107 } 108 109 int exp_bi[] = { 0, 1, 2 }; 110 exp_sz = sizeof ( exp_bi ) / sizeof ( exp_bi[0] ); 111 CHECK_EQUAL ( exp_sz, bi.size() ); 112 for ( unsigned i = 0; 113 i < sizeof ( exp_bi ) / sizeof ( exp_bi[0] ); 114 ++i ) { 115 CHECK_EQUAL ( exp_bi[i], bi ( i ) ); 116 } 118 117 } -
TabularUnified library/tests/size_generator.cpp ¶
r467 r477 5 5 using bdm::UI; 6 6 7 void size_generator::from_setting (const Setting &set) {8 if (set.exists("size")) {9 UI::get(sz, set, "size");10 7 void size_generator::from_setting ( const Setting &set ) { 8 if ( set.exists ( "size" ) ) { 9 UI::get ( sz, set, "size" ); 10 } 11 11 12 if (set.exists("step")) {13 UI::get(step, set, "step");14 12 if ( set.exists ( "step" ) ) { 13 UI::get ( step, set, "step" ); 14 } 15 15 } 16 16 17 17 mat size_generator::next() { 18 mat A0 = randu(sz, sz);19 20 21 18 mat A0 = randu ( sz, sz ); 19 mat A = A0 * A0.T(); 20 sz *= step; 21 return A; 22 22 } -
TabularUnified library/tests/size_generator.h ¶
r467 r477 19 19 /*! Generates progressively larger random matrices. 20 20 */ 21 class size_generator : public generator 22 { 21 class size_generator : public generator { 23 22 private: 24 25 23 int step; 24 int sz; 26 25 27 26 public: 28 size_generator():step(7), sz(step) { }27 size_generator() : step ( 7 ), sz ( step ) { } 29 28 30 29 itpp::mat next(); 31 30 32 33 34 35 36 37 38 39 void from_setting(const Setting &set);31 //! Load from structure with elements: 32 //! \code 33 //! { size = 7; // size (rows == cols) of the first generated matrix 34 //! step = 7; // how many times to increase the generated matrix in every iteration 35 //! } 36 //! \endcode 37 //! Both elements are optional, with defaults as shown. 38 void from_setting ( const Setting &set ); 40 39 }; 41 40 -
TabularUnified library/tests/square_mat_point.cpp ¶
r468 r477 4 4 using bdm::UI; 5 5 6 void square_mat_point::from_setting (const Setting &set) {7 UI::get(matrix, set, "matrix");8 UI::get(vector, set, "vector");9 UI::get(scalar, set, "scalar");6 void square_mat_point::from_setting ( const Setting &set ) { 7 UI::get ( matrix, set, "matrix" ); 8 UI::get ( vector, set, "vector" ); 9 UI::get ( scalar, set, "scalar" ); 10 10 } 11 11 12 void square_mat_point::to_setting (Setting &set) const {13 Setting &number_setting = set.add("scalar", Setting::TypeFloat);14 12 void square_mat_point::to_setting ( Setting &set ) const { 13 Setting &number_setting = set.add ( "scalar", Setting::TypeFloat ); 14 number_setting = scalar; 15 15 16 UI::save(vector, set, "vector");17 UI::save(matrix, set, "matrix");16 UI::save ( vector, set, "vector" ); 17 UI::save ( matrix, set, "matrix" ); 18 18 } 19 19 -
TabularUnified library/tests/square_mat_point.h ¶
r468 r477 20 20 random vector and one random scalar. 21 21 */ 22 class square_mat_point : public bdm::root 23 { 22 class square_mat_point : public bdm::root { 24 23 private: 25 26 27 24 itpp::mat matrix; 25 itpp::vec vector; 26 double scalar; 28 27 29 28 public: 30 square_mat_point():scalar(0) { }29 square_mat_point() : scalar ( 0 ) { } 31 30 32 33 return matrix;34 31 itpp::mat get_matrix() const { 32 return matrix; 33 } 35 34 36 37 return vector;38 35 itpp::vec get_vector() const { 36 return vector; 37 } 39 38 40 41 42 39 double get_scalar() const { 40 return scalar; 41 } 43 42 44 void set_parameters(const itpp::mat &m, const itpp::vec &v, double s) {45 46 vector = v;47 scalar = s;48 43 void set_parameters ( const itpp::mat &m, const itpp::vec &v, double s ) { 44 matrix = m; 45 vector = v; 46 scalar = s; 47 } 49 48 50 51 52 53 54 55 56 57 58 void from_setting(const Setting &set);59 60 void to_setting(Setting &set) const;49 //! Load from structure with elements: 50 //! \code 51 //! { matrix = ( "matrix", ... 52 //! vector = [ ... 53 //! scalar = ... 54 //! } 55 //! \endcode 56 //! All elements are mandatory. 57 void from_setting ( const Setting &set ); 58 59 void to_setting ( Setting &set ) const; 61 60 }; 62 61 -
TabularUnified library/tests/square_mat_prep.cpp ¶
r468 r477 14 14 using namespace itpp; 15 15 16 UIREGISTER (size_generator);17 UIREGISTER (additive_generator);18 UIREGISTER (square_mat_point);16 UIREGISTER ( size_generator ); 17 UIREGISTER ( additive_generator ); 18 UIREGISTER ( square_mat_point ); 19 19 20 20 const char *generator_file_name = "generator.cfg"; … … 22 22 int agenda_length = 10; 23 23 24 int main (int argc, char const *argv[]) {25 24 int main ( int argc, char const *argv[] ) { 25 RNG_randomize(); 26 26 27 bool unknown = false; 28 int update_next = 0; // 1 generator file, 2 agenda file, 3 agenda length 29 const char **param = argv + 1; 30 while (*param && !unknown) { 31 if (update_next) { 32 if (update_next == 1) { 33 generator_file_name = *param; 34 } else if (update_next == 2) { 35 agenda_file_name = *param; 36 } else { 37 int length = atoi(*param); 38 if (length > 0) { 39 agenda_length = length; 27 bool unknown = false; 28 int update_next = 0; // 1 generator file, 2 agenda file, 3 agenda length 29 const char **param = argv + 1; 30 while ( *param && !unknown ) { 31 if ( update_next ) { 32 if ( update_next == 1 ) { 33 generator_file_name = *param; 34 } else if ( update_next == 2 ) { 35 agenda_file_name = *param; 36 } else { 37 int length = atoi ( *param ); 38 if ( length > 0 ) { 39 agenda_length = length; 40 } else { 41 cerr << "invalid agenda length value ignored" << endl; 42 } 43 } 44 45 update_next = 0; 40 46 } else { 41 cerr << "invalid agenda length value ignored" << endl; 47 if ( !strcmp ( *param, "-a" ) ) { 48 update_next = 2; 49 } else if ( !strcmp ( *param, "-g" ) ) { 50 update_next = 1; 51 } else if ( !strcmp ( *param, "-l" ) ) { 52 update_next = 3; 53 } else { 54 unknown = true; 55 } 42 56 } 43 }44 57 45 update_next = 0; 46 } else { 47 if (!strcmp(*param, "-a")) { 48 update_next = 2; 49 } else if (!strcmp(*param, "-g")) { 50 update_next = 1; 51 } else if (!strcmp(*param, "-l")) { 52 update_next = 3; 53 } else { 54 unknown = true; 55 } 58 ++param; 56 59 } 57 60 58 ++param; 59 } 61 if ( unknown || update_next ) { 62 cerr << "usage: " << argv[0] << " [ -g generator.cfg ] [ -a agenda_output.cfg ] [ -l agenda_length ]" << endl; 63 } else { 64 Array<square_mat_point *> mag ( agenda_length ); 60 65 61 if (unknown || update_next) { 62 cerr << "usage: " << argv[0] << " [ -g generator.cfg ] [ -a agenda_output.cfg ] [ -l agenda_length ]" << endl; 63 } else { 64 Array<square_mat_point *> mag(agenda_length); 66 UIFile gspec ( generator_file_name ); 67 auto_ptr<generator> gen ( UI::build<generator> ( gspec, "generator" ) ); 68 for ( int i = 0; i < agenda_length; ++i ) { 69 mat m = gen->next(); 70 square_mat_point *p = new square_mat_point(); 71 p->set_parameters ( m, randu ( m.rows() ), randu() ); 72 mag ( i ) = p; 73 } 65 74 66 UIFile gspec(generator_file_name); 67 auto_ptr<generator> gen(UI::build<generator>(gspec, "generator")); 68 for (int i = 0; i < agenda_length; ++i) { 69 mat m = gen->next(); 70 square_mat_point *p = new square_mat_point(); 71 p->set_parameters(m, randu(m.rows()), randu()); 72 mag(i) = p; 75 UIFile fag; 76 UI::save ( mag, fag, "agenda" ); 77 fag.save ( agenda_file_name ); 78 79 for ( int i = 0; i < agenda_length; ++i ) { 80 square_mat_point *p = mag ( i ); 81 mag ( i ) = 0; 82 delete p; 83 } 73 84 } 74 75 UIFile fag;76 UI::save(mag, fag, "agenda");77 fag.save(agenda_file_name);78 79 for (int i = 0; i < agenda_length; ++i) {80 square_mat_point *p = mag(i);81 mag(i) = 0;82 delete p;83 }84 }85 85 } -
TabularUnified library/tests/square_mat_stress.cpp ¶
r468 r477 22 22 23 23 namespace bdm { 24 UIREGISTER(square_mat_point); 25 } 26 27 namespace UnitTest 28 { 24 UIREGISTER ( square_mat_point ); 25 } 26 27 namespace UnitTest { 29 28 30 29 // can't include mat_checks.h because CheckClose is different in this file 31 extern bool AreClose (const itpp::vec &expected, const itpp::vec &actual,32 double tolerance);33 34 extern bool AreClose (const itpp::mat &expected, const itpp::mat &actual,35 double tolerance);36 37 void CheckClose (TestResults &results, const itpp::mat &expected,38 39 TestDetails const& details) {40 if (!AreClose(expected, actual, tolerance)) { 41 42 43 44 45 results.OnTestFailure(details, stream.GetText());46 47 } 48 49 } 50 51 typedef void ( *FTestMatrix)(int, square_mat_point *);30 extern bool AreClose ( const itpp::vec &expected, const itpp::vec &actual, 31 double tolerance ); 32 33 extern bool AreClose ( const itpp::mat &expected, const itpp::mat &actual, 34 double tolerance ); 35 36 void CheckClose ( TestResults &results, const itpp::mat &expected, 37 const itpp::mat &actual, double tolerance, 38 TestDetails const& details ) { 39 if ( !AreClose ( expected, actual, tolerance ) ) { 40 MemoryOutStream stream; 41 stream << "failed at " << expected.rows() 42 << " x " << expected.cols(); 43 44 results.OnTestFailure ( details, stream.GetText() ); 45 } 46 } 47 48 } 49 50 typedef void ( *FTestMatrix ) ( int, square_mat_point * ); 52 51 53 52 template<typename TMatrix> 54 void test_matrix(int index, square_mat_point *point) { 55 Real_Timer tt; 56 57 cout << "agenda[" << index << "]:" << endl; 58 mat A = point->get_matrix(); 59 int sz = A.rows(); 60 CHECK_EQUAL(A.cols(), sz); 61 62 tt.tic(); 63 TMatrix sqmat(A); 64 double elapsed = tt.toc(); 65 cout << "ctor(" << sz << " x " << sz << "): " << elapsed << " s" << endl; 66 67 tt.tic(); 68 mat res = sqmat.to_mat(); 69 elapsed = tt.toc(); 70 71 if (!fast) { 72 CHECK_CLOSE(A, res, epsilon); 73 } 74 75 cout << "to_mat: " << elapsed << " s" << endl; 76 77 vec v = point->get_vector(); 78 double w = point->get_scalar(); 79 TMatrix sqmat2 = sqmat; 80 81 tt.tic(); 82 sqmat2.opupdt(v, w); 83 elapsed = tt.toc(); 84 85 if (!fast) { 86 mat expA = A + w * outer_product(v, v); 87 CHECK_CLOSE(expA, sqmat2.to_mat(), epsilon); 88 } 89 90 cout << "opupdt: " << elapsed << " s" << endl; 91 92 TMatrix invmat(sz); 93 94 tt.tic(); 95 sqmat.inv(invmat); 96 elapsed = tt.toc(); 97 98 mat invA; 99 if (!fast) { 100 invA = inv(A); 101 CHECK_CLOSE(invA, invmat.to_mat(), epsilon); 102 } 103 104 cout << "inv: " << elapsed << " s" << endl; 105 106 tt.tic(); 107 double ld = sqmat.logdet(); 108 elapsed = tt.toc(); 109 110 if (!fast) { 111 double d = det(A); 112 CHECK_CLOSE(log(d), ld, epsilon); 113 } 114 115 cout << "logdet: " << elapsed << " s" << endl; 116 117 tt.tic(); 118 double q = sqmat.qform(ones(sz)); 119 elapsed = tt.toc(); 120 121 if (!fast) { 122 CHECK_CLOSE(sumsum(A), q, epsilon); 123 } 124 125 cout << "qform(1): " << elapsed << " s" << endl; 126 127 tt.tic(); 128 q = sqmat.qform(v); 129 elapsed = tt.toc(); 130 131 if (!fast) { 132 double r = (A * v) * v; 133 CHECK_CLOSE(r, q, epsilon); 134 } 135 136 cout << "qform(v): " << elapsed << " s" << endl; 137 138 tt.tic(); 139 q = sqmat.invqform(v); 140 elapsed = tt.toc(); 141 142 if (!fast) { 143 double r = (invA * v) * v; 144 CHECK_CLOSE(r, q, epsilon); 145 } 146 147 cout << "invqform: " << elapsed << " s" << endl; 148 149 TMatrix twice = sqmat; 150 151 tt.tic(); 152 twice += sqmat; 153 elapsed = tt.toc(); 154 155 if (!fast) { 156 res = 2 * A; 157 CHECK_CLOSE(res, twice.to_mat(), epsilon); 158 } 159 160 cout << "+=: " << elapsed << " s" << endl; 161 162 sqmat2 = sqmat; 163 164 tt.tic(); 165 sqmat2.mult_sym(A); 166 elapsed = tt.toc(); 167 168 if (!fast) { 169 res = (A * A) * A.T(); 170 CHECK_CLOSE(res, sqmat2.to_mat(), epsilon); 171 } 172 173 cout << "^2: " << elapsed << " s" << endl; 174 } 175 176 void test_agenda(FTestMatrix test) { 177 UIFile fag(agenda_file_name); 178 Array<square_mat_point *> mag; 179 UI::get(mag, fag, "agenda"); 180 int sz = mag.size(); 181 CHECK(sz > 0); 182 for (int i = 0; i < sz; ++i) { 183 test(i, mag(i)); 184 } 185 186 for (int i = 0; i < sz; ++i) { 187 square_mat_point *p = mag(i); 188 mag(i) = 0; 189 delete p; 190 } 191 } 192 193 SUITE(ldmat) { 194 TEST(agenda) { 195 test_agenda(test_matrix<ldmat>); 196 } 197 } 198 199 SUITE(fsqmat) { 200 TEST(agenda) { 201 test_agenda(test_matrix<fsqmat>); 202 } 203 } 204 205 SUITE(chmat) { 206 TEST(agenda) { 207 test_agenda(test_matrix<chmat>); 208 } 209 } 210 211 int main(int argc, char const *argv[]) { 212 bool unknown = false; 213 int update_next = 0; // 1 suite, 2 epsilon, 3 agenda file 214 const char *suite = "ldmat"; 215 const char **param = argv + 1; 216 while (*param && !unknown) { 217 if (update_next) { 218 if (update_next == 1) { 219 suite = *param; 220 } else if (update_next == 2) { 221 double eps = atof(*param); 222 if (eps > 0) { 223 epsilon = eps; 53 void test_matrix ( int index, square_mat_point *point ) { 54 Real_Timer tt; 55 56 cout << "agenda[" << index << "]:" << endl; 57 mat A = point->get_matrix(); 58 int sz = A.rows(); 59 CHECK_EQUAL ( A.cols(), sz ); 60 61 tt.tic(); 62 TMatrix sqmat ( A ); 63 double elapsed = tt.toc(); 64 cout << "ctor(" << sz << " x " << sz << "): " << elapsed << " s" << endl; 65 66 tt.tic(); 67 mat res = sqmat.to_mat(); 68 elapsed = tt.toc(); 69 70 if ( !fast ) { 71 CHECK_CLOSE ( A, res, epsilon ); 72 } 73 74 cout << "to_mat: " << elapsed << " s" << endl; 75 76 vec v = point->get_vector(); 77 double w = point->get_scalar(); 78 TMatrix sqmat2 = sqmat; 79 80 tt.tic(); 81 sqmat2.opupdt ( v, w ); 82 elapsed = tt.toc(); 83 84 if ( !fast ) { 85 mat expA = A + w * outer_product ( v, v ); 86 CHECK_CLOSE ( expA, sqmat2.to_mat(), epsilon ); 87 } 88 89 cout << "opupdt: " << elapsed << " s" << endl; 90 91 TMatrix invmat ( sz ); 92 93 tt.tic(); 94 sqmat.inv ( invmat ); 95 elapsed = tt.toc(); 96 97 mat invA; 98 if ( !fast ) { 99 invA = inv ( A ); 100 CHECK_CLOSE ( invA, invmat.to_mat(), epsilon ); 101 } 102 103 cout << "inv: " << elapsed << " s" << endl; 104 105 tt.tic(); 106 double ld = sqmat.logdet(); 107 elapsed = tt.toc(); 108 109 if ( !fast ) { 110 double d = det ( A ); 111 CHECK_CLOSE ( log ( d ), ld, epsilon ); 112 } 113 114 cout << "logdet: " << elapsed << " s" << endl; 115 116 tt.tic(); 117 double q = sqmat.qform ( ones ( sz ) ); 118 elapsed = tt.toc(); 119 120 if ( !fast ) { 121 CHECK_CLOSE ( sumsum ( A ), q, epsilon ); 122 } 123 124 cout << "qform(1): " << elapsed << " s" << endl; 125 126 tt.tic(); 127 q = sqmat.qform ( v ); 128 elapsed = tt.toc(); 129 130 if ( !fast ) { 131 double r = ( A * v ) * v; 132 CHECK_CLOSE ( r, q, epsilon ); 133 } 134 135 cout << "qform(v): " << elapsed << " s" << endl; 136 137 tt.tic(); 138 q = sqmat.invqform ( v ); 139 elapsed = tt.toc(); 140 141 if ( !fast ) { 142 double r = ( invA * v ) * v; 143 CHECK_CLOSE ( r, q, epsilon ); 144 } 145 146 cout << "invqform: " << elapsed << " s" << endl; 147 148 TMatrix twice = sqmat; 149 150 tt.tic(); 151 twice += sqmat; 152 elapsed = tt.toc(); 153 154 if ( !fast ) { 155 res = 2 * A; 156 CHECK_CLOSE ( res, twice.to_mat(), epsilon ); 157 } 158 159 cout << "+=: " << elapsed << " s" << endl; 160 161 sqmat2 = sqmat; 162 163 tt.tic(); 164 sqmat2.mult_sym ( A ); 165 elapsed = tt.toc(); 166 167 if ( !fast ) { 168 res = ( A * A ) * A.T(); 169 CHECK_CLOSE ( res, sqmat2.to_mat(), epsilon ); 170 } 171 172 cout << "^2: " << elapsed << " s" << endl; 173 } 174 175 void test_agenda ( FTestMatrix test ) { 176 UIFile fag ( agenda_file_name ); 177 Array<square_mat_point *> mag; 178 UI::get ( mag, fag, "agenda" ); 179 int sz = mag.size(); 180 CHECK ( sz > 0 ); 181 for ( int i = 0; i < sz; ++i ) { 182 test ( i, mag ( i ) ); 183 } 184 185 for ( int i = 0; i < sz; ++i ) { 186 square_mat_point *p = mag ( i ); 187 mag ( i ) = 0; 188 delete p; 189 } 190 } 191 192 SUITE ( ldmat ) { 193 TEST ( agenda ) { 194 test_agenda ( test_matrix<ldmat> ); 195 } 196 } 197 198 SUITE ( fsqmat ) { 199 TEST ( agenda ) { 200 test_agenda ( test_matrix<fsqmat> ); 201 } 202 } 203 204 SUITE ( chmat ) { 205 TEST ( agenda ) { 206 test_agenda ( test_matrix<chmat> ); 207 } 208 } 209 210 int main ( int argc, char const *argv[] ) { 211 bool unknown = false; 212 int update_next = 0; // 1 suite, 2 epsilon, 3 agenda file 213 const char *suite = "ldmat"; 214 const char **param = argv + 1; 215 while ( *param && !unknown ) { 216 if ( update_next ) { 217 if ( update_next == 1 ) { 218 suite = *param; 219 } else if ( update_next == 2 ) { 220 double eps = atof ( *param ); 221 if ( eps > 0 ) { 222 epsilon = eps; 223 } else { 224 cerr << "invalid epsilon value ignored" << endl; 225 } 226 } else { 227 agenda_file_name = *param; 228 } 229 230 update_next = 0; 224 231 } else { 225 cerr << "invalid epsilon value ignored" << endl; 232 if ( !strcmp ( *param, "-a" ) ) { 233 update_next = 3; 234 } else if ( !strcmp ( *param, "-c" ) ) { 235 update_next = 1; 236 } else if ( !strcmp ( *param, "-e" ) ) { 237 update_next = 2; 238 } else if ( !strcmp ( *param, "-f" ) ) { 239 fast = true; 240 } else { 241 unknown = true; 242 } 226 243 } 227 } else { 228 agenda_file_name = *param; 229 } 230 231 update_next = 0; 244 245 ++param; 246 } 247 248 if ( unknown || update_next ) { 249 cerr << "usage: " << argv[0] << " [ -f ] [ -e epsilon ] [ -a agenda_input.cfg ] [ -c class ]" << endl; 232 250 } else { 233 if (!strcmp(*param, "-a")) { 234 update_next = 3; 235 } else if (!strcmp(*param, "-c")) { 236 update_next = 1; 237 } else if (!strcmp(*param, "-e")) { 238 update_next = 2; 239 } else if (!strcmp(*param, "-f")) { 240 fast = true; 241 } else { 242 unknown = true; 243 } 244 } 245 246 ++param; 247 } 248 249 if (unknown || update_next) { 250 cerr << "usage: " << argv[0] << " [ -f ] [ -e epsilon ] [ -a agenda_input.cfg ] [ -c class ]" << endl; 251 } else { 252 UnitTest::TestReporterStdout reporter; 253 UnitTest::TestRunner runner(reporter); 254 return runner.RunTestsIf(UnitTest::Test::GetTestList(), 255 suite, 256 UnitTest::True(), 257 0); 258 } 259 } 251 UnitTest::TestReporterStdout reporter; 252 UnitTest::TestRunner runner ( reporter ); 253 return runner.RunTestsIf ( UnitTest::Test::GetTestList(), 254 suite, 255 UnitTest::True(), 256 0 ); 257 } 258 } -
TabularUnified library/tests/square_mat_test.cpp ¶
r456 r477 8 8 9 9 template<typename TMatrix> 10 void test_square_matrix(double epsilon) { 11 int sz = 3; 12 mat A0 = randu(sz, sz); 13 mat A = A0 * A0.T(); 14 15 TMatrix sqmat(A); 16 CHECK_EQUAL(sz, sqmat.rows()); 17 CHECK_EQUAL(sz, sqmat.cols()); 10 void test_square_matrix ( double epsilon ) { 11 int sz = 3; 12 mat A0 = randu ( sz, sz ); 13 mat A = A0 * A0.T(); 18 14 19 mat res = sqmat.to_mat(); 20 CHECK_CLOSE(A, res, epsilon); 15 TMatrix sqmat ( A ); 16 CHECK_EQUAL ( sz, sqmat.rows() ); 17 CHECK_EQUAL ( sz, sqmat.cols() ); 21 18 22 vec v = randu(sz); 23 double w = randu(); 24 TMatrix sqmat2 = sqmat; 25 sqmat2.opupdt(v, w); 19 mat res = sqmat.to_mat(); 20 CHECK_CLOSE ( A, res, epsilon ); 26 21 27 res = A + w * outer_product(v, v); 28 CHECK_CLOSE(res, sqmat2.to_mat(), epsilon); 22 vec v = randu ( sz ); 23 double w = randu(); 24 TMatrix sqmat2 = sqmat; 25 sqmat2.opupdt ( v, w ); 29 26 30 TMatrix invmat(sz); 31 sqmat.inv(invmat); 32 mat invA = inv(A); 33 CHECK_CLOSE(invA, invmat.to_mat(), epsilon); 27 res = A + w * outer_product ( v, v ); 28 CHECK_CLOSE ( res, sqmat2.to_mat(), epsilon ); 34 29 35 double d = det(A); 36 CHECK_CLOSE(log(d), sqmat.logdet(), epsilon); 30 TMatrix invmat ( sz ); 31 sqmat.inv ( invmat ); 32 mat invA = inv ( A ); 33 CHECK_CLOSE ( invA, invmat.to_mat(), epsilon ); 37 34 38 double q = sqmat.qform(ones(sz));39 CHECK_CLOSE(sumsum(A), q, epsilon);35 double d = det ( A ); 36 CHECK_CLOSE ( log ( d ), sqmat.logdet(), epsilon ); 40 37 41 q = sqmat.qform(v); 42 double r = (A * v) * v; 43 CHECK_CLOSE(r, q, epsilon); 38 double q = sqmat.qform ( ones ( sz ) ); 39 CHECK_CLOSE ( sumsum ( A ), q, epsilon ); 44 40 45 q = sqmat.invqform(v);46 r = (invA * v) * v;47 CHECK_CLOSE(r, q, epsilon);41 q = sqmat.qform ( v ); 42 double r = ( A * v ) * v; 43 CHECK_CLOSE ( r, q, epsilon ); 48 44 49 sqmat2 = sqmat;50 sqmat2.clear();51 CHECK_EQUAL(0, sqmat2.qform(ones(sz)));45 q = sqmat.invqform ( v ); 46 r = ( invA * v ) * v; 47 CHECK_CLOSE ( r, q, epsilon ); 52 48 53 TMatrix twice = sqmat; 54 twice += sqmat; 55 res = 2 * A; 56 CHECK_CLOSE(res, twice.to_mat(), epsilon); 49 sqmat2 = sqmat; 50 sqmat2.clear(); 51 CHECK_EQUAL ( 0, sqmat2.qform ( ones ( sz ) ) ); 57 52 58 twice = sqmat; 59 twice *= 2; 60 CHECK_CLOSE(res, twice.to_mat(), epsilon); 53 TMatrix twice = sqmat; 54 twice += sqmat; 55 res = 2 * A; 56 CHECK_CLOSE ( res, twice.to_mat(), epsilon ); 61 57 62 sqmat2 = sqmat; 63 mat B = randu(sz, sz); 64 sqmat2.mult_sym(B); 65 res = (B * A) * B.T(); 66 CHECK_CLOSE(res, sqmat2.to_mat(), epsilon); 58 twice = sqmat; 59 twice *= 2; 60 CHECK_CLOSE ( res, twice.to_mat(), epsilon ); 67 61 68 mat C = randu(sz, sz-1);69 TMatrix CAC(sz-1);70 sqmat.mult_sym_t(C,CAC);71 res = (C.T() * A) * C;72 CHECK_CLOSE(res, CAC.to_mat(), epsilon);62 sqmat2 = sqmat; 63 mat B = randu ( sz, sz ); 64 sqmat2.mult_sym ( B ); 65 res = ( B * A ) * B.T(); 66 CHECK_CLOSE ( res, sqmat2.to_mat(), epsilon ); 73 67 74 sqmat2 = sqmat; 75 sqmat2.mult_sym_t(B); 76 res = (B.T() * A) * B; 77 CHECK_CLOSE(res, sqmat2.to_mat(), epsilon); 68 mat C = randu ( sz, sz - 1 ); 69 TMatrix CAC ( sz - 1 ); 70 sqmat.mult_sym_t ( C, CAC ); 71 res = ( C.T() * A ) * C; 72 CHECK_CLOSE ( res, CAC.to_mat(), epsilon ); 73 74 sqmat2 = sqmat; 75 sqmat2.mult_sym_t ( B ); 76 res = ( B.T() * A ) * B; 77 CHECK_CLOSE ( res, sqmat2.to_mat(), epsilon ); 78 78 } 79 79 80 TEST (test_ldmat) {81 test_square_matrix<ldmat>(epsilon);80 TEST ( test_ldmat ) { 81 test_square_matrix<ldmat> ( epsilon ); 82 82 } 83 83 84 TEST (test_fsqmat) {85 test_square_matrix<fsqmat>(epsilon);84 TEST ( test_fsqmat ) { 85 test_square_matrix<fsqmat> ( epsilon ); 86 86 } 87 87 88 TEST (test_chmat) {89 test_square_matrix<chmat>(epsilon);88 TEST ( test_chmat ) { 89 test_square_matrix<chmat> ( epsilon ); 90 90 } -
TabularUnified library/tests/testResample.cpp ¶
r386 r477 12 12 int main() { 13 13 14 RV x("1"); 15 RV xm=x; xm.t(-1);const 16 RV y("2"); 17 14 RV x ( "1" ); 15 RV xm = x; 16 xm.t ( -1 ); 17 const 18 RV y ( "2" ); 19 18 20 mat A = "1"; 19 21 vec vR = "1"; 20 ldmat R (vR);21 22 ldmat R ( vR ); 23 22 24 eEmp emp; 23 25 euni eun; 24 eun.set_parameters("0","1"); 25 emp.set_statistics(ones(10),&eun); 26 vec &v=emp._w(); 27 Array<vec> &S=emp._samples(); 28 29 for (int i=0;i<10;i++){ v(i) = exp(-0.5*sum(pow(S(i)-1,2.0))*10);} 30 v/=sum(v); 31 26 eun.set_parameters ( "0", "1" ); 27 emp.set_statistics ( ones ( 10 ), &eun ); 28 vec &v = emp._w(); 29 Array<vec> &S = emp._samples(); 30 31 for ( int i = 0; i < 10; i++ ) { 32 v ( i ) = exp ( -0.5 * sum ( pow ( S ( i ) - 1, 2.0 ) ) * 10 ); 33 } 34 v /= sum ( v ); 35 32 36 cout << "p:" << S << endl; 33 37 cout << "w:" << v << endl; 34 38 35 39 ivec ind = emp.resample(); 36 40 37 41 cout << ind << endl; 38 42 39 43 //Exit program: 40 44 return 0; -
TabularUnified library/tests/testSmp.cpp ¶
r461 r477 9 9 using std::endl; 10 10 11 void disp (const vec &tmu, const mat &tR,const mat &Smp){11 void disp ( const vec &tmu, const mat &tR, const mat &Smp ) { 12 12 int N = Smp.cols(); 13 vec Emu = Smp *ones(N) /N ;14 mat Er = ( Smp*Smp.transpose())/N - outer_product(Emu,Emu);15 cout << "True mu:" << tmu << endl;16 cout << "Emp mu:" << Emu << endl;17 18 cout << "True R:" << tR << endl;19 cout << "Emp R:" << Er << endl;13 vec Emu = Smp * ones ( N ) / N ; 14 mat Er = ( Smp * Smp.transpose() ) / N - outer_product ( Emu, Emu ); 15 cout << "True mu:" << tmu << endl; 16 cout << "Emp mu:" << Emu << endl; 17 18 cout << "True R:" << tR << endl; 19 cout << "Emp R:" << Er << endl; 20 20 } 21 21 … … 24 24 RNG_randomize(); 25 25 26 RV x ("{x }","2");27 RV y ("{y }","2");26 RV x ( "{x }", "2" ); 27 RV y ( "{y }", "2" ); 28 28 int N = 10000; //number of samples 29 29 vec mu0 = "1.5 1.7"; 30 mat V0 ("1.2 0.3; 0.3 5");31 ldmat R = ldmat (V0);32 33 cout << "====== ENorm ====== " << endl;30 mat V0 ( "1.2 0.3; 0.3 5" ); 31 ldmat R = ldmat ( V0 ); 32 33 cout << "====== ENorm ====== " << endl; 34 34 enorm<ldmat> eN; 35 eN.set_parameters (mu0,R);36 mat Smp = eN.sample_m (N);35 eN.set_parameters ( mu0, R ); 36 mat Smp = eN.sample_m ( N ); 37 37 38 disp (mu0,R.to_mat(),Smp);38 disp ( mu0, R.to_mat(), Smp ); 39 39 40 cout << "====== MlNorm ====== " << endl;41 mat I = eye (2);40 cout << "====== MlNorm ====== " << endl; 41 mat I = eye ( 2 ); 42 42 mlnorm<ldmat> ML; 43 ML.set_parameters(I,zeros(2),R); 44 Smp = ML.samplecond_m(mu0,N); 45 46 disp(mu0,R.to_mat(),Smp); 43 ML.set_parameters ( I, zeros ( 2 ), R ); 44 Smp = ML.samplecond_m ( mu0, N ); 47 45 48 cout << "====== EGamma ====== " <<endl; 46 disp ( mu0, R.to_mat(), Smp ); 47 48 cout << "====== EGamma ====== " << endl; 49 49 vec a = "100000,10000"; 50 vec b = a /10.0;50 vec b = a / 10.0; 51 51 egamma eG; 52 eG.set_parameters(a,b); 53 54 cout << eG.evallog(a)<<endl; 55 Smp = eG.sample_m(N); 52 eG.set_parameters ( a, b ); 56 53 57 vec g_mu = elem_div(a,b); 58 vec g_var = elem_div(a,pow(b,2.0)); 59 disp(g_mu,diag(g_var),Smp); 54 cout << eG.evallog ( a ) << endl; 55 Smp = eG.sample_m ( N ); 60 56 61 cout << "====== MGamma ====== " <<endl; 57 vec g_mu = elem_div ( a, b ); 58 vec g_var = elem_div ( a, pow ( b, 2.0 ) ); 59 disp ( g_mu, diag ( g_var ), Smp ); 60 61 cout << "====== MGamma ====== " << endl; 62 62 mgamma mG; 63 63 double k = 10.0; 64 mG.set_parameters (k,mu0);64 mG.set_parameters ( k, mu0 ); 65 65 66 Smp =mG.samplecond_m(mu0,N);67 disp (mu0,pow(mu0,2.0)/k,Smp);68 66 Smp = mG.samplecond_m ( mu0, N ); 67 disp ( mu0, pow ( mu0, 2.0 ) / k, Smp ); 68 69 69 cout << "======= EMix ======== " << endl; 70 70 emix eMix; 71 Array<epdf*> Coms (2);72 Coms (0) = &eG;73 Coms (1) = &eN;74 75 eMix.set_parameters (vec_2(0.5,0.5), Coms);71 Array<epdf*> Coms ( 2 ); 72 Coms ( 0 ) = &eG; 73 Coms ( 1 ) = &eN; 74 75 eMix.set_parameters ( vec_2 ( 0.5, 0.5 ), Coms ); 76 76 vec smp = eMix.sample(); 77 Smp = eMix.sample_m (N);78 disp (eMix.mean(),zeros(2),Smp);77 Smp = eMix.sample_m ( N ); 78 disp ( eMix.mean(), zeros ( 2 ), Smp ); 79 79 80 80 cout << "======= MEpdf ======== " << endl; 81 mepdf meMix (&eMix);82 83 Smp = meMix.samplecond_m (mu0,N);84 disp (eMix.mean(),zeros(2),Smp);81 mepdf meMix ( &eMix ); 82 83 Smp = meMix.samplecond_m ( mu0, N ); 84 disp ( eMix.mean(), zeros ( 2 ), Smp ); 85 85 86 86 cout << "======= MMix ======== " << endl; 87 87 mmix mMix; 88 Array<mpdf*> mComs (2);89 mComs (0) = &mG;90 eN.set_mu (vec_2(0.0,0.0));91 mepdf mEnorm (&eN);92 mComs (1) = &mEnorm;93 mMix.set_parameters (vec_2(0.5,0.5),mComs);94 95 Smp = mMix.samplecond_m (mu0,N);96 disp (mMix.e()->mean(), zeros(2), Smp);88 Array<mpdf*> mComs ( 2 ); 89 mComs ( 0 ) = &mG; 90 eN.set_mu ( vec_2 ( 0.0, 0.0 ) ); 91 mepdf mEnorm ( &eN ); 92 mComs ( 1 ) = &mEnorm; 93 mMix.set_parameters ( vec_2 ( 0.5, 0.5 ), mComs ); 94 95 Smp = mMix.samplecond_m ( mu0, N ); 96 disp ( mMix.e()->mean(), zeros ( 2 ), Smp ); 97 97 98 98 cout << "======= EProd ======== " << endl; 99 99 // we have to change eG.rv to y 100 eN.set_rv (x);101 eG.set_rv (y);102 //create array 103 Array<mpdf*> A (2);104 mepdf meN (&eN);105 mepdf meG (&eG);106 A (0) = &meN;107 A (1) = &meG;108 109 mprod eP (A);110 mat epV =zeros(4,4);111 epV.set_submatrix (0,0,V0);112 epV.set_submatrix (2,2,diag(g_var));113 114 vec v0 =vec(0);115 Smp = eP.samplecond (v0,N);116 disp (concat(eN.mean(),eG.mean()), epV,Smp);117 100 eN.set_rv ( x ); 101 eG.set_rv ( y ); 102 //create array 103 Array<mpdf*> A ( 2 ); 104 mepdf meN ( &eN ); 105 mepdf meG ( &eG ); 106 A ( 0 ) = &meN; 107 A ( 1 ) = &meG; 108 109 mprod eP ( A ); 110 mat epV = zeros ( 4, 4 ); 111 epV.set_submatrix ( 0, 0, V0 ); 112 epV.set_submatrix ( 2, 2, diag ( g_var ) ); 113 114 vec v0 = vec ( 0 ); 115 Smp = eP.samplecond ( v0, N ); 116 disp ( concat ( eN.mean(), eG.mean() ), epV, Smp ); 117 118 118 cout << "======= eWishart ======== " << endl; 119 mat wM="1.0 0.9; 0.9 1.0"; 120 eWishartCh eW; eW.set_parameters(wM/100,100); 121 mat mea=zeros(2,2); 122 mat Ch(2,2); 123 for (int i=0;i<100;i++){Ch=eW.sample_mat(); mea+=Ch.T()*Ch;} 124 cout << mea /100 <<endl; 125 119 mat wM = "1.0 0.9; 0.9 1.0"; 120 eWishartCh eW; 121 eW.set_parameters ( wM / 100, 100 ); 122 mat mea = zeros ( 2, 2 ); 123 mat Ch ( 2, 2 ); 124 for ( int i = 0; i < 100; i++ ) { 125 Ch = eW.sample_mat(); 126 mea += Ch.T() * Ch; 127 } 128 cout << mea / 100 << endl; 129 126 130 cout << "======= rwiWishart ======== " << endl; 127 rwiWishartCh rwW; rwW.set_parameters(2,0.1,"1 1",0.9); 128 mea=zeros(2,2); 129 mat wMch=chol(wM); 130 for (int i=0;i<100;i++){ 131 vec tmp=rwW.samplecond(vec(wMch._data(),4)); 132 copy_vector(4,tmp._data(), Ch._data()); 133 mea+=Ch.T()*Ch; 131 rwiWishartCh rwW; 132 rwW.set_parameters ( 2, 0.1, "1 1", 0.9 ); 133 mea = zeros ( 2, 2 ); 134 mat wMch = chol ( wM ); 135 for ( int i = 0; i < 100; i++ ) { 136 vec tmp = rwW.samplecond ( vec ( wMch._data(), 4 ) ); 137 copy_vector ( 4, tmp._data(), Ch._data() ); 138 mea += Ch.T() * Ch; 134 139 } 135 cout << mea / 100 <<endl;140 cout << mea / 100 << endl; 136 141 //Exit program: 137 142 return 0; -
TabularUnified library/tests/test_kalman.cpp ¶
r386 r477 10 10 int main() { 11 11 // Kalman filter 12 mat A, B, C,D,R,Q,P0;12 mat A, B, C, D, R, Q, P0; 13 13 vec mu0; 14 14 mat Mu0;; 15 15 // input from Matlab 16 it_file fin ( "testKF.it" );16 it_file fin ( "testKF.it" ); 17 17 18 18 mat Dt; 19 19 int Ndat; 20 20 21 bool xxx= fin.seek( "d" ); 22 if (!xxx){ it_error("testKF.it not found");} 23 fin >>Dt; 24 fin.seek( "A" ); 21 bool xxx = fin.seek ( "d" ); 22 if ( !xxx ) { 23 it_error ( "testKF.it not found" ); 24 } 25 fin >> Dt; 26 fin.seek ( "A" ); 25 27 fin >> A; 26 fin.seek ( "B" );28 fin.seek ( "B" ); 27 29 fin >> B; 28 fin.seek ( "C" );30 fin.seek ( "C" ); 29 31 fin >> C; 30 fin.seek ( "D" );32 fin.seek ( "D" ); 31 33 fin >> D; 32 fin.seek ( "R" );34 fin.seek ( "R" ); 33 35 fin >> R; 34 fin.seek( "Q" ); fin >> Q; 35 fin.seek( "P0" ); fin >> P0; 36 fin.seek( "mu0" ); fin >> Mu0; 37 mu0=Mu0.get_col(0); 38 36 fin.seek ( "Q" ); 37 fin >> Q; 38 fin.seek ( "P0" ); 39 fin >> P0; 40 fin.seek ( "mu0" ); 41 fin >> Mu0; 42 mu0 = Mu0.get_col ( 0 ); 43 39 44 Ndat = 10;//Dt.cols(); 40 45 int dimx = A.rows(); 41 46 42 47 // Prepare for Kalman filters in BDM: 43 RV rx ("{x }",vec_1(A.cols()));44 RV ru ("{u }",vec_1(B.cols()));45 RV ry ("{y }",vec_1(C.rows()));46 48 RV rx ( "{x }", vec_1 ( A.cols() ) ); 49 RV ru ( "{u }", vec_1 ( B.cols() ) ); 50 RV ry ( "{y }", vec_1 ( C.rows() ) ); 51 47 52 // // LDMAT 48 53 // Kalman<ldmat> KF(rx,ry,ru); … … 50 55 // KF.set_est(mu0,ldmat(P0) ); 51 56 // epdf& KFep = KF.posterior(); 52 // mat Xt(2,Ndat); 57 // mat Xt(2,Ndat); 53 58 // Xt.set_col( 0,KFep.mean() ); 54 59 55 60 //Chol 56 61 KalmanCh KF; 57 KF.set_parameters (A,B,C,D,chmat(R),chmat(Q));58 KF.set_est (mu0,chmat(P0) ); //prediction!62 KF.set_parameters ( A, B, C, D, chmat ( R ), chmat ( Q ) ); 63 KF.set_est ( mu0, chmat ( P0 ) ); //prediction! 59 64 const epdf& KFep = KF.posterior(); 60 mat Xt(dimx,Ndat); 61 Xt.set_col( 0,KFep.mean() );62 63 // 65 mat Xt ( dimx, Ndat ); 66 Xt.set_col ( 0, KFep.mean() ); 67 68 // 64 69 // FSQMAT 65 70 Kalman<ldmat> KFf; 66 KFf.set_parameters (A,B,C,D,ldmat(R),ldmat(Q));67 KFf.set_est (mu0,ldmat(P0) );71 KFf.set_parameters ( A, B, C, D, ldmat ( R ), ldmat ( Q ) ); 72 KFf.set_est ( mu0, ldmat ( P0 ) ); 68 73 const epdf& KFfep = KFf.posterior(); 69 mat Xtf (dimx,Ndat);70 Xtf.set_col ( 0,KFfep.mean() );71 74 mat Xtf ( dimx, Ndat ); 75 Xtf.set_col ( 0, KFfep.mean() ); 76 72 77 // FULL 73 KalmanFull KF2 ( A,B,C,D,R,Q,P0,mu0 );74 mat Xt2 (dimx,Ndat);75 Xt2.set_col ( 0,mu0);78 KalmanFull KF2 ( A, B, C, D, R, Q, P0, mu0 ); 79 mat Xt2 ( dimx, Ndat ); 80 Xt2.set_col ( 0, mu0 ); 76 81 77 82 78 83 // EKF 79 bilinfn fxu (A,B);80 bilinfn hxu (C,D);84 bilinfn fxu ( A, B ); 85 bilinfn hxu ( C, D ); 81 86 EKFCh KFE; 82 KFE.set_parameters (&fxu,&hxu,Q,R);83 KFE.set_est (mu0,chmat(P0));87 KFE.set_parameters ( &fxu, &hxu, Q, R ); 88 KFE.set_est ( mu0, chmat ( P0 ) ); 84 89 const epdf& KFEep = KFE.posterior(); 85 mat XtE (dimx,Ndat);86 XtE.set_col ( 0,KFEep.mean() );90 mat XtE ( dimx, Ndat ); 91 XtE.set_col ( 0, KFEep.mean() ); 87 92 88 93 //test performance of each filter 89 94 Real_Timer tt; 90 vec exec_times(4); // KF, KFf KF2, KFE 91 92 tt.tic(); 93 for ( int t=1;t<Ndat;t++ ) { 94 KF.bayes( Dt.get_col( t )); 95 Xt.set_col( t,KFep.mean() ); 96 } 97 exec_times(0) = tt.toc(); 98 99 tt.tic(); 100 for ( int t=1;t<Ndat;t++ ) { 101 KFf.bayes( Dt.get_col( t )); 102 Xtf.set_col( t,KFfep.mean() ); 103 } 104 exec_times(1) = tt.toc(); 95 vec exec_times ( 4 ); // KF, KFf KF2, KFE 105 96 106 97 tt.tic(); 107 for ( int t =1;t<Ndat;t++ ) {108 KF 2.bayes( Dt.get_col( t ));109 Xt 2.set_col( t,KF2.mu);98 for ( int t = 1; t < Ndat; t++ ) { 99 KF.bayes ( Dt.get_col ( t ) ); 100 Xt.set_col ( t, KFep.mean() ); 110 101 } 111 exec_times (2) = tt.toc();102 exec_times ( 0 ) = tt.toc(); 112 103 113 104 tt.tic(); 114 for ( int t =1;t<Ndat;t++ ) {115 KF E.bayes( Dt.get_col( t ));116 Xt E.set_col( t,KFEep.mean() );105 for ( int t = 1; t < Ndat; t++ ) { 106 KFf.bayes ( Dt.get_col ( t ) ); 107 Xtf.set_col ( t, KFfep.mean() ); 117 108 } 118 exec_times(3) = tt.toc(); 109 exec_times ( 1 ) = tt.toc(); 110 111 tt.tic(); 112 for ( int t = 1; t < Ndat; t++ ) { 113 KF2.bayes ( Dt.get_col ( t ) ); 114 Xt2.set_col ( t, KF2.mu ); 115 } 116 exec_times ( 2 ) = tt.toc(); 117 118 tt.tic(); 119 for ( int t = 1; t < Ndat; t++ ) { 120 KFE.bayes ( Dt.get_col ( t ) ); 121 XtE.set_col ( t, KFEep.mean() ); 122 } 123 exec_times ( 3 ) = tt.toc(); 119 124 120 125 121 it_file fou ( "testKF_res.it" );122 fou << Name ("xth") << Xt;123 fou << Name ("xthf") << Xtf;124 fou << Name ("xth2") << Xt2;125 fou << Name ("xthE") << XtE;126 fou << Name ("exec_times") << exec_times;126 it_file fou ( "testKF_res.it" ); 127 fou << Name ( "xth" ) << Xt; 128 fou << Name ( "xthf" ) << Xtf; 129 fou << Name ( "xth2" ) << Xt2; 130 fou << Name ( "xthE" ) << XtE; 131 fou << Name ( "exec_times" ) << exec_times; 127 132 //Exit program: 128 133 return 0; -
TabularUnified library/tests/test_kalman_QR.cpp ¶
r461 r477 11 11 int main() { 12 12 // Klaman filter 13 mat A, B, C,D,R,Q,P0;13 mat A, B, C, D, R, Q, P0; 14 14 vec mu0; 15 15 mat Mu0;// read from matlab 16 16 // input from Matlab 17 it_file fin ( "testKF.it" );17 it_file fin ( "testKF.it" ); 18 18 19 mat Dt, XQRt, eR,eQ;19 mat Dt, XQRt, eR, eQ; 20 20 int Ndat; 21 21 22 bool xxx= fin.seek( "d" ); 23 if (!xxx){ it_error("testKF.it not found");} 24 fin >>Dt; 25 fin.seek( "A" ); 22 bool xxx = fin.seek ( "d" ); 23 if ( !xxx ) { 24 it_error ( "testKF.it not found" ); 25 } 26 fin >> Dt; 27 fin.seek ( "A" ); 26 28 fin >> A; 27 fin.seek ( "B" );29 fin.seek ( "B" ); 28 30 fin >> B; 29 fin.seek ( "C" );31 fin.seek ( "C" ); 30 32 fin >> C; 31 fin.seek ( "D" );33 fin.seek ( "D" ); 32 34 fin >> D; 33 fin.seek ( "R" );35 fin.seek ( "R" ); 34 36 fin >> R; 35 fin.seek( "Q" ); fin >> Q; 36 fin.seek( "P0" ); fin >> P0; 37 fin.seek( "mu0" ); fin >> Mu0; 38 mu0=Mu0.get_col(0); 39 37 fin.seek ( "Q" ); 38 fin >> Q; 39 fin.seek ( "P0" ); 40 fin >> P0; 41 fin.seek ( "mu0" ); 42 fin >> Mu0; 43 mu0 = Mu0.get_col ( 0 ); 44 40 45 Ndat = Dt.cols(); 41 XQRt =zeros( 5,Ndat );42 mat Xt =zeros( 2,Ndat );46 XQRt = zeros ( 5, Ndat ); 47 mat Xt = zeros ( 2, Ndat ); 43 48 44 49 // cout << KF; 45 RV rx ("{x }","2");46 RV ru ("{u }","1");47 RV ry ("{y }","1");48 RV rQR ("{Q,R }","3");50 RV rx ( "{x }", "2" ); 51 RV ru ( "{u }", "1" ); 52 RV ry ( "{y }", "1" ); 53 RV rQR ( "{Q,R }", "3" ); 49 54 // 50 55 KFcondQR KF; 51 56 // KF with R unknown 52 KF.set_parameters (A,B,C,D,ldmat(R),ldmat(Q));53 KF.set_est (mu0,ldmat(P0) );57 KF.set_parameters ( A, B, C, D, ldmat ( R ), ldmat ( Q ) ); 58 KF.set_est ( mu0, ldmat ( P0 ) ); 54 59 // 55 60 Kalman<ldmat> KFtr; 56 61 // KF with R unknown 57 KFtr.set_parameters (A,B,C,D,ldmat(R),ldmat(Q));58 KFtr.set_est (mu0,ldmat(P0) );59 62 KFtr.set_parameters ( A, B, C, D, ldmat ( R ), ldmat ( Q ) ); 63 KFtr.set_est ( mu0, ldmat ( P0 ) ); 64 60 65 mgamma evolQR; 61 evolQR.set_parameters (10.0,"1 1 1"); //sigma = 1/10 mu62 66 evolQR.set_parameters ( 10.0, "1 1 1" ); //sigma = 1/10 mu 67 63 68 MPF<KFcondQR> KF_QR; 64 KF_QR.set_parameters (&evolQR,&evolQR,100);65 evolQR.condition ("1 1 1");66 KF_QR.set_statistics (evolQR.e(), &KF);67 const epdf& mpost =KF_QR.posterior();68 const epdf& mposttr =KFtr.posterior();69 KF_QR.set_parameters ( &evolQR, &evolQR, 100 ); 70 evolQR.condition ( "1 1 1" ); 71 KF_QR.set_statistics ( evolQR.e(), &KF ); 72 const epdf& mpost = KF_QR.posterior(); 73 const epdf& mposttr = KFtr.posterior(); 69 74 70 XQRt.set_col ( 0,mpost.mean());71 Xt.set_col ( 0,mposttr.mean());72 for ( int t =1;t<Ndat;t++ ) {73 KF_QR.bayes ( Dt.get_col( t ));74 KFtr.bayes ( Dt.get_col( t ));75 76 XQRt.set_col (t,mpost.mean());77 Xt.set_col (t,mposttr.mean());75 XQRt.set_col ( 0, mpost.mean() ); 76 Xt.set_col ( 0, mposttr.mean() ); 77 for ( int t = 1; t < Ndat; t++ ) { 78 KF_QR.bayes ( Dt.get_col ( t ) ); 79 KFtr.bayes ( Dt.get_col ( t ) ); 80 81 XQRt.set_col ( t, mpost.mean() ); 82 Xt.set_col ( t, mposttr.mean() ); 78 83 } 79 80 it_file fou ( "testKF_QR_res.it" );81 fou << Name ("xqrth") << XQRt;82 fou << Name ("xth") << Xt;84 85 it_file fou ( "testKF_QR_res.it" ); 86 fou << Name ( "xqrth" ) << XQRt; 87 fou << Name ( "xth" ) << Xt; 83 88 //Exit program: 84 89 return 0; -
TabularUnified library/tests/test_kalman_QRexh.cpp ¶
r386 r477 11 11 int main() { 12 12 // Klaman filter 13 mat A, B, C,D,R,Q,P0;13 mat A, B, C, D, R, Q, P0; 14 14 vec mu0; 15 15 mat Mu0;// read from matlab … … 17 17 it_file fin ( "testKF.it" ); 18 18 19 mat Dt, XQRt, eR,eQ;19 mat Dt, XQRt, eR, eQ; 20 20 int Ndat; 21 21 22 bool xxx = fin.seek ( "d" );22 bool xxx = fin.seek ( "d" ); 23 23 24 if ( !xxx ) { it_error ( "testKF.it not found" );} 24 if ( !xxx ) { 25 it_error ( "testKF.it not found" ); 26 } 25 27 26 fin >> Dt;28 fin >> Dt; 27 29 28 30 fin.seek ( "A" ); … … 36 38 fin.seek ( "R" ); 37 39 fin >> R; 38 fin.seek ( "Q" ); fin >> Q; 39 fin.seek ( "P0" ); fin >> P0; 40 fin.seek ( "mu0" ); fin >> Mu0; 41 mu0=Mu0.get_col ( 0 ); 40 fin.seek ( "Q" ); 41 fin >> Q; 42 fin.seek ( "P0" ); 43 fin >> P0; 44 fin.seek ( "mu0" ); 45 fin >> Mu0; 46 mu0 = Mu0.get_col ( 0 ); 42 47 43 48 vec vQ1 = "0.01:0.04:1"; … … 48 53 Ndat = Dt.cols(); 49 54 50 RV rx ( "{x}", "2" );51 RV ru ( "{u}", "1" );52 RV ry ( "{y}", "2" );55 RV rx ( "{x}", "2" ); 56 RV ru ( "{u}", "1" ); 57 RV ry ( "{y}", "2" ); 53 58 // 54 59 // 55 60 Kalman<ldmat> KFtr; 56 61 57 for ( int i = 0; i<vQ1.length();i++ ) {62 for ( int i = 0; i < vQ1.length(); i++ ) { 58 63 59 for ( int j = 0; j <vQ2.length();j++ ) {64 for ( int j = 0; j < vQ2.length(); j++ ) { 60 65 // KF with R unknown 61 66 mat Qj = Q; 62 Qj ( 0, 0 ) = vQ1 ( i );63 Qj ( 1, 1 ) = vQ2 ( j );64 KFtr.set_parameters ( A, B,C,D,ldmat ( R ),ldmat ( Qj ) );65 KFtr.set_est ( mu0, ldmat ( P0 ) );67 Qj ( 0, 0 ) = vQ1 ( i ); 68 Qj ( 1, 1 ) = vQ2 ( j ); 69 KFtr.set_parameters ( A, B, C, D, ldmat ( R ), ldmat ( Qj ) ); 70 KFtr.set_est ( mu0, ldmat ( P0 ) ); 66 71 67 for ( int t =1;t<Ndat;t++ ) {72 for ( int t = 1; t < Ndat; t++ ) { 68 73 KFtr.bayes ( Dt.get_col ( t ) ); 69 LL ( i, j ) += KFtr._ll();74 LL ( i, j ) += KFtr._ll(); 70 75 } 71 76 } -
TabularUnified library/tests/test_particle.cpp ¶
r386 r477 12 12 int main() { 13 13 14 RV x("1"); 15 RV xm=x; xm.t(-1);const 16 RV y("2"); 17 14 RV x ( "1" ); 15 RV xm = x; 16 xm.t ( -1 ); 17 const 18 RV y ( "2" ); 19 18 20 mat A = "1"; 19 21 vec vR = "1"; 20 ldmat R (vR);21 22 ldmat R ( vR ); 23 22 24 eEmp emp; 23 25 euni eun; 24 eun.set_parameters("0","1"); 25 emp.set_statistics(ones(10),&eun); 26 vec &v=emp._w(); 27 Array<vec> &S=emp._samples(); 28 29 for (int i=0;i<10;i++){ v(i) = exp(-0.5*sum(pow(S(i)-1,2.0))*10);} 30 v/=sum(v); 31 26 eun.set_parameters ( "0", "1" ); 27 emp.set_statistics ( ones ( 10 ), &eun ); 28 vec &v = emp._w(); 29 Array<vec> &S = emp._samples(); 30 31 for ( int i = 0; i < 10; i++ ) { 32 v ( i ) = exp ( -0.5 * sum ( pow ( S ( i ) - 1, 2.0 ) ) * 10 ); 33 } 34 v /= sum ( v ); 35 32 36 cout << "p:" << S << endl; 33 37 cout << "w:" << v << endl; 34 38 35 39 ivec ind = emp.resample(); 36 40 37 41 cout << ind << endl; 38 42 39 43 //Exit program: 40 44 return 0; -
TabularUnified library/tests/test_shared_ptr.cpp ¶
r421 r477 3 3 #include <vector> 4 4 5 class Foo 6 { 5 class Foo { 7 6 private: 8 7 int x; 9 8 10 9 public: 11 Foo(int x):x(x) { }10 Foo ( int x ) : x ( x ) { } 12 11 13 int get_x() const { return x; } 12 int get_x() const { 13 return x; 14 } 14 15 15 void set_x(int nx) { x = nx; } 16 void set_x ( int nx ) { 17 x = nx; 18 } 16 19 }; 17 20 18 21 typedef std::vector<bdm::shared_ptr<Foo> > TFooVector; 19 22 20 TEST(test_shared_ptr) 21 { 22 TFooVector v; 23 TEST ( test_shared_ptr ) { 24 TFooVector v; 23 25 24 25 CHECK_EQUAL(0l, zero.use_count());26 bdm::shared_ptr<Foo> z2(zero);27 CHECK_EQUAL(0l, z2.use_count());26 bdm::shared_ptr<Foo> zero; 27 CHECK_EQUAL ( 0l, zero.use_count() ); 28 bdm::shared_ptr<Foo> z2 ( zero ); 29 CHECK_EQUAL ( 0l, z2.use_count() ); 28 30 29 bdm::shared_ptr<Foo> one(new Foo(1));30 v.push_back(one);31 CHECK(!one.unique());31 bdm::shared_ptr<Foo> one ( new Foo ( 1 ) ); 32 v.push_back ( one ); 33 CHECK ( !one.unique() ); 32 34 33 v.push_back(one);34 v.push_back(bdm::shared_ptr<Foo>(new Foo(2)));35 CHECK_EQUAL(static_cast<TFooVector::size_type>(3), v.size());35 v.push_back ( one ); 36 v.push_back ( bdm::shared_ptr<Foo> ( new Foo ( 2 ) ) ); 37 CHECK_EQUAL ( static_cast<TFooVector::size_type> ( 3 ), v.size() ); 36 38 37 CHECK(v[0] == v[1]);38 CHECK(v[1] != v[2]);39 CHECK ( v[0] == v[1] ); 40 CHECK ( v[1] != v[2] ); 39 41 40 Foo c(*(v[0])); 41 CHECK_EQUAL(1, c.get_x()); 42 43 Foo *p = v[1].get(); 44 CHECK_EQUAL(1, p->get_x()); 45 p->set_x(12); 46 CHECK_EQUAL(12, one->get_x()); 42 Foo c ( * ( v[0] ) ); 43 CHECK_EQUAL ( 1, c.get_x() ); 47 44 48 CHECK(v[2].unique()); 49 CHECK_EQUAL(2, v[2]->get_x()); 45 Foo *p = v[1].get(); 46 CHECK_EQUAL ( 1, p->get_x() ); 47 p->set_x ( 12 ); 48 CHECK_EQUAL ( 12, one->get_x() ); 49 50 CHECK ( v[2].unique() ); 51 CHECK_EQUAL ( 2, v[2]->get_x() ); 50 52 } -
TabularUnified library/tests/test_util.cpp ¶
r469 r477 27 27 using itpp::mat; 28 28 29 std::string load_test_file(const char *fname) 30 { 31 char buffer[8192]; 32 memset(buffer, 0, sizeof(buffer)); 33 std::ifstream src(fname, std::ios_base::binary); 34 src.read(buffer, sizeof(buffer) - 1); 35 return std::string(buffer); 29 std::string load_test_file ( const char *fname ) { 30 char buffer[8192]; 31 memset ( buffer, 0, sizeof ( buffer ) ); 32 std::ifstream src ( fname, std::ios_base::binary ); 33 src.read ( buffer, sizeof ( buffer ) - 1 ); 34 return std::string ( buffer ); 36 35 } 37 36 38 bool remove_all (const char *path) {39 40 37 bool remove_all ( const char *path ) { 38 DIR *dir; 39 dirent *de; 41 40 42 43 if ((dir = opendir(path)) != 0) {44 45 std::string top(path);46 41 bool rv = true; 42 if ( ( dir = opendir ( path ) ) != 0 ) { 43 try { 44 std::string top ( path ); 45 top += "/"; 47 46 48 while ((de = readdir(dir)) != 0) { 49 if (strcmp(de->d_name, ".") && strcmp(de->d_name, "..")) { 50 std::string subpath(top); 51 subpath += de->d_name; 52 remove_all(subpath.c_str()); 47 while ( ( de = readdir ( dir ) ) != 0 ) { 48 if ( strcmp ( de->d_name, "." ) && strcmp ( de->d_name, ".." ) ) { 49 std::string subpath ( top ); 50 subpath += de->d_name; 51 remove_all ( subpath.c_str() ); 52 } 53 } 54 } catch ( ... ) { 55 closedir ( dir ); 56 throw; 53 57 } 54 } 55 } catch (...) { 56 closedir(dir); 57 throw; 58 59 closedir ( dir ); 60 61 if ( rmdir ( path ) ) { 62 std::string msg = "can't remove dir "; 63 msg += path; 64 throw std::runtime_error ( msg ); 65 } 66 } else { 67 if ( errno == ENOTDIR ) { 68 if ( unlink ( path ) ) { 69 std::string msg = "can't remove file "; 70 msg += path; 71 throw std::runtime_error ( msg ); 72 } 73 } else { 74 if ( errno != ENOENT ) { 75 std::string msg = "can't remove "; 76 msg += path; 77 throw std::runtime_error ( msg ); 78 } else { 79 // it wasn't there in the first place 80 rv = false; 81 } 82 } 58 83 } 59 84 60 closedir(dir); 61 62 if (rmdir(path)) { 63 std::string msg = "can't remove dir "; 64 msg += path; 65 throw std::runtime_error(msg); 66 } 67 } else { 68 if (errno == ENOTDIR) { 69 if (unlink(path)) { 70 std::string msg = "can't remove file "; 71 msg += path; 72 throw std::runtime_error(msg); 73 } 74 } else { 75 if (errno != ENOENT) { 76 std::string msg = "can't remove "; 77 msg += path; 78 throw std::runtime_error(msg); 79 } else { 80 // it wasn't there in the first place 81 rv = false; 82 } 83 } 84 } 85 86 return rv; 85 return rv; 87 86 } 88 87 89 double normcoef (const epdf *ep, const vec &xb, const vec &yb,90 int xn, int yn) {91 mat Pdf(xn + 1, yn + 1);92 vec rgr(2);88 double normcoef ( const epdf *ep, const vec &xb, const vec &yb, 89 int xn, int yn ) { 90 mat Pdf ( xn + 1, yn + 1 ); 91 vec rgr ( 2 ); 93 92 94 double xstep = (xb(1) - xb(0)) / xn;95 double ystep = (yb(1) - yb(0)) / yn;93 double xstep = ( xb ( 1 ) - xb ( 0 ) ) / xn; 94 double ystep = ( yb ( 1 ) - yb ( 0 ) ) / yn; 96 95 97 double x = xb(0); 98 for (int i = 0; i <= xn; x += xstep, i++) { 99 rgr(0) = x; 100 double y = yb(0); 101 for (int j = 0; j <= yn; y += ystep, j++) { 102 rgr(1) = y; 103 Pdf(i, j) = exp(ep->evallog(rgr)); 96 double x = xb ( 0 ); 97 for ( int i = 0; i <= xn; x += xstep, i++ ) { 98 rgr ( 0 ) = x; 99 double y = yb ( 0 ); 100 for ( int j = 0; j <= yn; y += ystep, j++ ) { 101 rgr ( 1 ) = y; 102 Pdf ( i, j ) = exp ( ep->evallog ( rgr ) ); 103 } 104 104 } 105 }106 105 107 return sumsum(Pdf) * xstep * ystep;106 return sumsum ( Pdf ) * xstep * ystep; 108 107 } 109 108 110 vec num_mean2 (const epdf *ep, const vec &xb, const vec &yb,111 int xn, int yn) {112 mat Pdf(xn + 1, yn + 1);113 vec rgr(2);109 vec num_mean2 ( const epdf *ep, const vec &xb, const vec &yb, 110 int xn, int yn ) { 111 mat Pdf ( xn + 1, yn + 1 ); 112 vec rgr ( 2 ); 114 113 115 double xstep = (xb(1) - xb(0)) / xn;116 double ystep = (yb(1) - yb(0)) / yn;114 double xstep = ( xb ( 1 ) - xb ( 0 ) ) / xn; 115 double ystep = ( yb ( 1 ) - yb ( 0 ) ) / yn; 117 116 118 vec Mu(xn + 1);119 vec Si(yn + 1);117 vec Mu ( xn + 1 ); 118 vec Si ( yn + 1 ); 120 119 121 double x = xb(0); 122 for (int i = 0; i <= xn; x += xstep, i++) { 123 Mu(i) = x; 124 rgr(0) = x; 125 double y = yb(0); 126 for (int j = 0; j <= yn; y += ystep, j++) { 127 Si(j) = y; 128 rgr(1) = y; 129 Pdf(i, j) = exp(ep->evallog(rgr)); 120 double x = xb ( 0 ); 121 for ( int i = 0; i <= xn; x += xstep, i++ ) { 122 Mu ( i ) = x; 123 rgr ( 0 ) = x; 124 double y = yb ( 0 ); 125 for ( int j = 0; j <= yn; y += ystep, j++ ) { 126 Si ( j ) = y; 127 rgr ( 1 ) = y; 128 Pdf ( i, j ) = exp ( ep->evallog ( rgr ) ); 129 } 130 130 } 131 }132 131 133 vec fm = sum(Pdf, 2);134 double sfm = sum(fm);135 vec fs = sum(Pdf, 1);136 double sfs = sum(fs);137 138 139 return vec_2(vi0, vi1);132 vec fm = sum ( Pdf, 2 ); 133 double sfm = sum ( fm ); 134 vec fs = sum ( Pdf, 1 ); 135 double sfs = sum ( fs ); 136 double vi0 = Mu * fm / sfm; 137 double vi1 = Si * fs / sfs; 138 return vec_2 ( vi0, vi1 ); 140 139 } 141 140 -
TabularUnified library/tests/test_util.h ¶
r436 r477 26 26 characters, but for testing that should be enough. 27 27 */ 28 std::string load_test_file (const char *fname);28 std::string load_test_file ( const char *fname ); 29 29 30 30 /*! \brief Recursively removes directories and files. … … 35 35 exception otherwise. 36 36 */ 37 bool remove_all (const char *path);37 bool remove_all ( const char *path ); 38 38 39 double normcoef (const epdf *ep, const itpp::vec &xb, const itpp::vec &yb,40 int xn = 100, int yn = 100);39 double normcoef ( const epdf *ep, const itpp::vec &xb, const itpp::vec &yb, 40 int xn = 100, int yn = 100 ); 41 41 42 itpp::vec num_mean2 (const epdf *ep, const itpp::vec &xb, const itpp::vec &yb,43 int xn = 100, int yn = 100);42 itpp::vec num_mean2 ( const epdf *ep, const itpp::vec &xb, const itpp::vec &yb, 43 int xn = 100, int yn = 100 ); 44 44 45 45 } -
TabularUnified library/tests/testsuite.cpp ¶
r452 r477 2 2 #include "itpp_ext.h" 3 3 4 int main(int, char const *[]) 5 { 6 itpp::RNG_randomize(); 7 return UnitTest::RunAllTests(); 4 int main ( int, char const *[] ) { 5 itpp::RNG_randomize(); 6 return UnitTest::RunAllTests(); 8 7 } -
TabularUnified library/tests/tutorial/arx_simple.cpp ¶
r386 r477 1 1 #include "estim/arx.h" 2 2 using namespace bdm; 3 3 4 4 // estimation of AR(0) model 5 5 int main() { 6 //prior 7 mat V0 = 0.00001*eye(2); V0(0,0)= 0.1; // 8 ARX Ar; 9 Ar.set_statistics(1, V0); //nu is default (set to have finite moments) 10 // forgetting is default: 1.0 11 mat Data = concat_vertical( randn(1,100), ones(1,100) ); 12 Ar.bayesB( Data); 13 14 cout << "Expected value of Theta is: " << Ar.posterior().mean() <<endl; 6 //prior 7 mat V0 = 0.00001 * eye ( 2 ); 8 V0 ( 0, 0 ) = 0.1; // 9 ARX Ar; 10 Ar.set_statistics ( 1, V0 ); //nu is default (set to have finite moments) 11 // forgetting is default: 1.0 12 mat Data = concat_vertical ( randn ( 1, 100 ), ones ( 1, 100 ) ); 13 Ar.bayesB ( Data ); 14 15 cout << "Expected value of Theta is: " << Ar.posterior().mean() << endl; 15 16 } -
TabularUnified library/tests/tutorial/kalman_simple.cpp ¶
r386 r477 1 1 #include "estim/kalman.h" 2 2 using namespace bdm; 3 3 4 4 // estimation of AR(0) model 5 5 int main() { 6 6 //dimensions 7 int dx =3, dy=3, du=1;7 int dx = 3, dy = 3, du = 1; 8 8 // matrices 9 mat A = eye (dx);10 mat B = zeros (dx,du);11 mat C = eye (dx);12 mat D = zeros (dy,du);13 mat Q = eye (dx);14 mat R = 0.1 *eye(dy);9 mat A = eye ( dx ); 10 mat B = zeros ( dx, du ); 11 mat C = eye ( dx ); 12 mat D = zeros ( dy, du ); 13 mat Q = eye ( dx ); 14 mat R = 0.1 * eye ( dy ); 15 15 //prior 16 mat P0 = 100 *eye(dx);17 vec mu0 = zeros (dx);16 mat P0 = 100 * eye ( dx ); 17 vec mu0 = zeros ( dx ); 18 18 // Estimator 19 19 KalmanCh KF; 20 KF.set_parameters (A,B,C,D,/*covariances*/ Q,R);21 KF.set_statistics (mu0,P0);20 KF.set_parameters ( A, B, C, D,/*covariances*/ Q, R ); 21 KF.set_statistics ( mu0, P0 ); 22 22 // Estimation loop 23 for ( int i=0;i<100;i++){24 KF.bayes (randn(dx+du));23 for ( int i = 0; i < 100; i++ ) { 24 KF.bayes ( randn ( dx + du ) ); 25 25 } 26 26 //print results 27 27 cout << "Posterior estimate of x is: " << endl; 28 cout << "mean: " << KF.posterior().mean()<< endl;29 cout << "variance: " << KF.posterior().variance()<< endl;28 cout << "mean: " << KF.posterior().mean() << endl; 29 cout << "variance: " << KF.posterior().variance() << endl; 30 30 } -
TabularUnified library/tests/unittest-cpp/AssertException.cpp ¶
r418 r477 4 4 namespace UnitTest { 5 5 6 AssertException::AssertException(char const* description, char const* filename, int lineNumber) 7 : m_lineNumber(lineNumber) 8 { 6 AssertException::AssertException ( char const* description, char const* filename, int lineNumber ) 7 : m_lineNumber ( lineNumber ) { 9 8 using namespace std; 10 9 11 strcpy(m_description, description);12 strcpy(m_filename, filename);10 strcpy ( m_description, description ); 11 strcpy ( m_filename, filename ); 13 12 } 14 13 15 AssertException::~AssertException() throw() 16 { 14 AssertException::~AssertException() throw() { 17 15 } 18 16 19 char const* AssertException::what() const throw() 20 { 21 return m_description; 17 char const* AssertException::what() const throw() { 18 return m_description; 22 19 } 23 20 24 char const* AssertException::Filename() const 25 { 26 return m_filename; 21 char const* AssertException::Filename() const { 22 return m_filename; 27 23 } 28 24 29 int AssertException::LineNumber() const 30 { 31 return m_lineNumber; 25 int AssertException::LineNumber() const { 26 return m_lineNumber; 32 27 } 33 28 -
TabularUnified library/tests/unittest-cpp/AssertException.h ¶
r418 r477 7 7 namespace UnitTest { 8 8 9 class AssertException : public std::exception 10 { 9 class AssertException : public std::exception { 11 10 public: 12 AssertException(char const* description, char const* filename, int lineNumber);13 11 AssertException ( char const* description, char const* filename, int lineNumber ); 12 virtual ~AssertException() throw(); 14 13 15 14 virtual char const* what() const throw(); 16 15 17 18 16 char const* Filename() const; 17 int LineNumber() const; 19 18 20 19 private: 21 22 23 20 char m_description[512]; 21 char m_filename[256]; 22 int m_lineNumber; 24 23 }; 25 24 -
TabularUnified library/tests/unittest-cpp/CheckMacros.h ¶
r418 r477 1 #ifndef UNITTEST_CHECKMACROS_H 1 #ifndef UNITTEST_CHECKMACROS_H 2 2 #define UNITTEST_CHECKMACROS_H 3 3 … … 9 9 10 10 #ifdef CHECK 11 11 #error UnitTest++ redefines CHECK 12 12 #endif 13 13 14 14 #ifdef CHECK_EQUAL 15 15 #error UnitTest++ redefines CHECK_EQUAL 16 16 #endif 17 17 18 18 #ifdef CHECK_CLOSE 19 19 #error UnitTest++ redefines CHECK_CLOSE 20 20 #endif 21 21 22 22 #ifdef CHECK_ARRAY_EQUAL 23 23 #error UnitTest++ redefines CHECK_ARRAY_EQUAL 24 24 #endif 25 25 26 26 #ifdef CHECK_ARRAY_CLOSE 27 27 #error UnitTest++ redefines CHECK_ARRAY_CLOSE 28 28 #endif 29 29 30 30 #ifdef CHECK_ARRAY2D_CLOSE 31 31 #error UnitTest++ redefines CHECK_ARRAY2D_CLOSE 32 32 #endif 33 33 -
TabularUnified library/tests/unittest-cpp/Checks.cpp ¶
r418 r477 6 6 namespace { 7 7 8 void CheckStringsEqual(TestResults& results, char const* expected, char const* actual, 9 TestDetails const& details) 10 { 8 void CheckStringsEqual ( TestResults& results, char const* expected, char const* actual, 9 TestDetails const& details ) { 11 10 using namespace std; 12 11 13 if (strcmp(expected, actual)) 14 { 15 UnitTest::MemoryOutStream stream; 16 stream << "Expected " << expected << " but was " << actual; 12 if ( strcmp ( expected, actual ) ) { 13 UnitTest::MemoryOutStream stream; 14 stream << "Expected " << expected << " but was " << actual; 17 15 18 results.OnTestFailure(details, stream.GetText());19 16 results.OnTestFailure ( details, stream.GetText() ); 17 } 20 18 } 21 19 … … 23 21 24 22 25 void CheckEqual(TestResults& results, char const* expected, char const* actual, 26 TestDetails const& details) 27 { 28 CheckStringsEqual(results, expected, actual, details); 23 void CheckEqual ( TestResults& results, char const* expected, char const* actual, 24 TestDetails const& details ) { 25 CheckStringsEqual ( results, expected, actual, details ); 29 26 } 30 27 31 void CheckEqual(TestResults& results, char* expected, char* actual, 32 TestDetails const& details) 33 { 34 CheckStringsEqual(results, expected, actual, details); 28 void CheckEqual ( TestResults& results, char* expected, char* actual, 29 TestDetails const& details ) { 30 CheckStringsEqual ( results, expected, actual, details ); 35 31 } 36 32 37 void CheckEqual(TestResults& results, char* expected, char const* actual, 38 TestDetails const& details) 39 { 40 CheckStringsEqual(results, expected, actual, details); 33 void CheckEqual ( TestResults& results, char* expected, char const* actual, 34 TestDetails const& details ) { 35 CheckStringsEqual ( results, expected, actual, details ); 41 36 } 42 37 43 void CheckEqual(TestResults& results, char const* expected, char* actual, 44 TestDetails const& details) 45 { 46 CheckStringsEqual(results, expected, actual, details); 38 void CheckEqual ( TestResults& results, char const* expected, char* actual, 39 TestDetails const& details ) { 40 CheckStringsEqual ( results, expected, actual, details ); 47 41 } 48 42 -
TabularUnified library/tests/unittest-cpp/Checks.h ¶
r418 r477 10 10 11 11 template< typename Value > 12 bool Check(Value const value) 13 { 14 return !!value; // doing double negative to avoid silly VS warnings 12 bool Check ( Value const value ) { 13 return !!value; // doing double negative to avoid silly VS warnings 15 14 } 16 15 17 16 18 17 template< typename Expected, typename Actual > 19 void CheckEqual(TestResults& results, Expected const& expected, Actual const& actual, TestDetails const& details) 20 { 21 if (!(expected == actual)) 22 { 23 UnitTest::MemoryOutStream stream; 24 stream << "Expected " << expected << " but was " << actual; 18 void CheckEqual ( TestResults& results, Expected const& expected, Actual const& actual, TestDetails const& details ) { 19 if ( ! ( expected == actual ) ) { 20 UnitTest::MemoryOutStream stream; 21 stream << "Expected " << expected << " but was " << actual; 25 22 26 results.OnTestFailure(details, stream.GetText());27 23 results.OnTestFailure ( details, stream.GetText() ); 24 } 28 25 } 29 26 30 void CheckEqual (TestResults& results, char const* expected, char const* actual, TestDetails const& details);27 void CheckEqual ( TestResults& results, char const* expected, char const* actual, TestDetails const& details ); 31 28 32 void CheckEqual (TestResults& results, char* expected, char* actual, TestDetails const& details);29 void CheckEqual ( TestResults& results, char* expected, char* actual, TestDetails const& details ); 33 30 34 void CheckEqual (TestResults& results, char* expected, char const* actual, TestDetails const& details);31 void CheckEqual ( TestResults& results, char* expected, char const* actual, TestDetails const& details ); 35 32 36 void CheckEqual (TestResults& results, char const* expected, char* actual, TestDetails const& details);33 void CheckEqual ( TestResults& results, char const* expected, char* actual, TestDetails const& details ); 37 34 38 35 template< typename Expected, typename Actual, typename Tolerance > 39 bool AreClose(Expected const& expected, Actual const& actual, Tolerance const& tolerance) 40 { 41 return (actual >= (expected - tolerance)) && (actual <= (expected + tolerance)); 36 bool AreClose ( Expected const& expected, Actual const& actual, Tolerance const& tolerance ) { 37 return ( actual >= ( expected - tolerance ) ) && ( actual <= ( expected + tolerance ) ); 42 38 } 43 39 44 40 template< typename Expected, typename Actual, typename Tolerance > 45 void CheckClose(TestResults& results, Expected const& expected, Actual const& actual, Tolerance const& tolerance, 46 TestDetails const& details) 47 { 48 if (!AreClose(expected, actual, tolerance)) 49 { 50 UnitTest::MemoryOutStream stream; 51 stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual; 41 void CheckClose ( TestResults& results, Expected const& expected, Actual const& actual, Tolerance const& tolerance, 42 TestDetails const& details ) { 43 if ( !AreClose ( expected, actual, tolerance ) ) { 44 UnitTest::MemoryOutStream stream; 45 stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual; 52 46 53 results.OnTestFailure(details, stream.GetText());54 47 results.OnTestFailure ( details, stream.GetText() ); 48 } 55 49 } 56 50 57 51 58 52 template< typename Expected, typename Actual > 59 void CheckArrayEqual(TestResults& results, Expected const& expected, Actual const& actual, 60 int const count, TestDetails const& details) 61 { 62 bool equal = true; 63 for (int i = 0; i < count; ++i) 64 equal &= (expected[i] == actual[i]); 53 void CheckArrayEqual ( TestResults& results, Expected const& expected, Actual const& actual, 54 int const count, TestDetails const& details ) { 55 bool equal = true; 56 for ( int i = 0; i < count; ++i ) 57 equal &= ( expected[i] == actual[i] ); 65 58 66 if (!equal) 67 { 68 UnitTest::MemoryOutStream stream; 59 if ( !equal ) { 60 UnitTest::MemoryOutStream stream; 69 61 70 62 stream << "Expected [ "; 71 63 72 for ( int expectedIndex = 0; expectedIndex < count; ++expectedIndex)73 64 for ( int expectedIndex = 0; expectedIndex < count; ++expectedIndex ) 65 stream << expected[expectedIndex] << " "; 74 66 75 67 stream << "] but was [ "; 76 68 77 for ( int actualIndex = 0; actualIndex < count; ++actualIndex)78 69 for ( int actualIndex = 0; actualIndex < count; ++actualIndex ) 70 stream << actual[actualIndex] << " "; 79 71 80 72 stream << "]"; 81 73 82 results.OnTestFailure(details, stream.GetText());83 74 results.OnTestFailure ( details, stream.GetText() ); 75 } 84 76 } 85 77 86 78 template< typename Expected, typename Actual, typename Tolerance > 87 bool ArrayAreClose(Expected const& expected, Actual const& actual, int const count, Tolerance const& tolerance) 88 { 89 bool equal = true; 90 for (int i = 0; i < count; ++i) 91 equal &= AreClose(expected[i], actual[i], tolerance); 92 return equal; 79 bool ArrayAreClose ( Expected const& expected, Actual const& actual, int const count, Tolerance const& tolerance ) { 80 bool equal = true; 81 for ( int i = 0; i < count; ++i ) 82 equal &= AreClose ( expected[i], actual[i], tolerance ); 83 return equal; 93 84 } 94 85 95 86 template< typename Expected, typename Actual, typename Tolerance > 96 void CheckArrayClose(TestResults& results, Expected const& expected, Actual const& actual, 97 int const count, Tolerance const& tolerance, TestDetails const& details) 98 { 99 bool equal = ArrayAreClose(expected, actual, count, tolerance); 87 void CheckArrayClose ( TestResults& results, Expected const& expected, Actual const& actual, 88 int const count, Tolerance const& tolerance, TestDetails const& details ) { 89 bool equal = ArrayAreClose ( expected, actual, count, tolerance ); 100 90 101 if (!equal) 102 { 103 UnitTest::MemoryOutStream stream; 91 if ( !equal ) { 92 UnitTest::MemoryOutStream stream; 104 93 105 106 for (int expectedIndex = 0; expectedIndex < count; ++expectedIndex)107 108 94 stream << "Expected [ "; 95 for ( int expectedIndex = 0; expectedIndex < count; ++expectedIndex ) 96 stream << expected[expectedIndex] << " "; 97 stream << "] +/- " << tolerance << " but was [ "; 109 98 110 for ( int actualIndex = 0; actualIndex < count; ++actualIndex)111 112 99 for ( int actualIndex = 0; actualIndex < count; ++actualIndex ) 100 stream << actual[actualIndex] << " "; 101 stream << "]"; 113 102 114 results.OnTestFailure(details, stream.GetText());115 103 results.OnTestFailure ( details, stream.GetText() ); 104 } 116 105 } 117 106 118 107 template< typename Expected, typename Actual, typename Tolerance > 119 void CheckArray2DClose(TestResults& results, Expected const& expected, Actual const& actual, 120 int const rows, int const columns, Tolerance const& tolerance, TestDetails const& details) 121 { 122 bool equal = true; 123 for (int i = 0; i < rows; ++i) 124 equal &= ArrayAreClose(expected[i], actual[i], columns, tolerance); 108 void CheckArray2DClose ( TestResults& results, Expected const& expected, Actual const& actual, 109 int const rows, int const columns, Tolerance const& tolerance, TestDetails const& details ) { 110 bool equal = true; 111 for ( int i = 0; i < rows; ++i ) 112 equal &= ArrayAreClose ( expected[i], actual[i], columns, tolerance ); 125 113 126 if (!equal) 127 { 128 UnitTest::MemoryOutStream stream; 114 if ( !equal ) { 115 UnitTest::MemoryOutStream stream; 129 116 130 stream << "Expected [ "; 117 stream << "Expected [ "; 131 118 132 for (int expectedRow = 0; expectedRow < rows; ++expectedRow) 133 { 134 stream << "[ "; 135 for (int expectedColumn = 0; expectedColumn < columns; ++expectedColumn) 136 stream << expected[expectedRow][expectedColumn] << " "; 137 stream << "] "; 138 } 119 for ( int expectedRow = 0; expectedRow < rows; ++expectedRow ) { 120 stream << "[ "; 121 for ( int expectedColumn = 0; expectedColumn < columns; ++expectedColumn ) 122 stream << expected[expectedRow][expectedColumn] << " "; 123 stream << "] "; 124 } 139 125 140 126 stream << "] +/- " << tolerance << " but was [ "; 141 127 142 for (int actualRow = 0; actualRow < rows; ++actualRow) 143 { 144 stream << "[ "; 145 for (int actualColumn = 0; actualColumn < columns; ++actualColumn) 146 stream << actual[actualRow][actualColumn] << " "; 147 stream << "] "; 148 } 128 for ( int actualRow = 0; actualRow < rows; ++actualRow ) { 129 stream << "[ "; 130 for ( int actualColumn = 0; actualColumn < columns; ++actualColumn ) 131 stream << actual[actualRow][actualColumn] << " "; 132 stream << "] "; 133 } 149 134 150 135 stream << "]"; 151 136 152 results.OnTestFailure(details, stream.GetText());153 137 results.OnTestFailure ( details, stream.GetText() ); 138 } 154 139 } 155 140 -
TabularUnified library/tests/unittest-cpp/Config.h ¶
r418 r477 5 5 6 6 #if defined(_MSC_VER) 7 8 9 7 #pragma warning(disable:4127) // conditional expression is constant 8 #pragma warning(disable:4702) // unreachable code 9 #pragma warning(disable:4722) // destructor never returns, potential memory leak 10 10 11 12 13 14 11 #if (_MSC_VER == 1200) // VC6 12 #pragma warning(disable:4786) 13 #pragma warning(disable:4290) 14 #endif 15 15 #endif 16 16 17 17 #if defined(unix) || defined(__unix__) || defined(__unix) || defined(linux) || \ 18 defined(__APPLE__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) 19 18 defined(__APPLE__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) 19 #define UNITTEST_POSIX 20 20 #endif 21 21 22 22 #if defined(__MINGW32__) 23 23 #define UNITTEST_MINGW 24 24 #endif 25 25 -
TabularUnified library/tests/unittest-cpp/CurrentTest.cpp ¶
r418 r477 4 4 namespace UnitTest { 5 5 6 TestResults*& CurrentTest::Results() 7 { 6 TestResults*& CurrentTest::Results() { 8 7 static TestResults* testResults = NULL; 9 8 return testResults; 10 9 } 11 10 12 const TestDetails*& CurrentTest::Details() 13 { 11 const TestDetails*& CurrentTest::Details() { 14 12 static const TestDetails* testDetails = NULL; 15 13 return testDetails; -
TabularUnified library/tests/unittest-cpp/CurrentTest.h ¶
r418 r477 7 7 class TestDetails; 8 8 9 namespace CurrentTest 10 { 11 TestResults*& Results(); 12 const TestDetails*& Details(); 9 namespace CurrentTest { 10 TestResults*& Results(); 11 const TestDetails*& Details(); 13 12 } 14 13 -
TabularUnified library/tests/unittest-cpp/DeferredTestReporter.cpp ¶
r418 r477 4 4 using namespace UnitTest; 5 5 6 void DeferredTestReporter::ReportTestStart(TestDetails const& details) 7 { 8 m_results.push_back(DeferredTestResult(details.suiteName, details.testName)); 6 void DeferredTestReporter::ReportTestStart ( TestDetails const& details ) { 7 m_results.push_back ( DeferredTestResult ( details.suiteName, details.testName ) ); 9 8 } 10 9 11 void DeferredTestReporter::ReportFailure(TestDetails const& details, char const* failure) 12 { 13 DeferredTestResult& r = m_results.back(); 14 r.failed = true; 15 r.failures.push_back(DeferredTestResult::Failure(details.lineNumber, failure)); 16 r.failureFile = details.filename; 10 void DeferredTestReporter::ReportFailure ( TestDetails const& details, char const* failure ) { 11 DeferredTestResult& r = m_results.back(); 12 r.failed = true; 13 r.failures.push_back ( DeferredTestResult::Failure ( details.lineNumber, failure ) ); 14 r.failureFile = details.filename; 17 15 } 18 16 19 void DeferredTestReporter::ReportTestFinish(TestDetails const&, float secondsElapsed) 20 { 21 DeferredTestResult& r = m_results.back(); 22 r.timeElapsed = secondsElapsed; 17 void DeferredTestReporter::ReportTestFinish ( TestDetails const&, float secondsElapsed ) { 18 DeferredTestResult& r = m_results.back(); 19 r.timeElapsed = secondsElapsed; 23 20 } 24 21 25 DeferredTestReporter::DeferredTestResultList& DeferredTestReporter::GetResults() 26 { 27 return m_results; 22 DeferredTestReporter::DeferredTestResultList& DeferredTestReporter::GetResults() { 23 return m_results; 28 24 } -
TabularUnified library/tests/unittest-cpp/DeferredTestReporter.h ¶
r418 r477 8 8 #include <vector> 9 9 10 namespace UnitTest 11 { 10 namespace UnitTest { 12 11 13 class DeferredTestReporter : public TestReporter 14 { 12 class DeferredTestReporter : public TestReporter { 15 13 public: 16 virtual void ReportTestStart(TestDetails const& details);17 virtual void ReportFailure(TestDetails const& details, char const* failure);18 virtual void ReportTestFinish(TestDetails const& details, float secondsElapsed);14 virtual void ReportTestStart ( TestDetails const& details ); 15 virtual void ReportFailure ( TestDetails const& details, char const* failure ); 16 virtual void ReportTestFinish ( TestDetails const& details, float secondsElapsed ); 19 17 20 21 18 typedef std::vector< DeferredTestResult > DeferredTestResultList; 19 DeferredTestResultList& GetResults(); 22 20 23 21 private: 24 22 DeferredTestResultList m_results; 25 23 }; 26 24 -
TabularUnified library/tests/unittest-cpp/DeferredTestResult.cpp ¶
r418 r477 2 2 #include "Config.h" 3 3 4 namespace UnitTest 5 { 4 namespace UnitTest { 6 5 7 6 DeferredTestResult::DeferredTestResult() 8 : suiteName("") 9 , testName("") 10 , failureFile("") 11 , timeElapsed(0.0f) 12 , failed(false) 13 { 7 : suiteName ( "" ) 8 , testName ( "" ) 9 , failureFile ( "" ) 10 , timeElapsed ( 0.0f ) 11 , failed ( false ) { 14 12 } 15 13 16 DeferredTestResult::DeferredTestResult(char const* suite, char const* test) 17 : suiteName(suite) 18 , testName(test) 19 , failureFile("") 20 , timeElapsed(0.0f) 21 , failed(false) 22 { 14 DeferredTestResult::DeferredTestResult ( char const* suite, char const* test ) 15 : suiteName ( suite ) 16 , testName ( test ) 17 , failureFile ( "" ) 18 , timeElapsed ( 0.0f ) 19 , failed ( false ) { 23 20 } 24 21 25 DeferredTestResult::~DeferredTestResult() 26 { 22 DeferredTestResult::~DeferredTestResult() { 27 23 } 28 24 -
TabularUnified library/tests/unittest-cpp/DeferredTestResult.h ¶
r418 r477 7 7 #include <vector> 8 8 9 namespace UnitTest 10 { 9 namespace UnitTest { 11 10 12 struct DeferredTestResult 13 { 11 struct DeferredTestResult { 14 12 DeferredTestResult(); 15 DeferredTestResult(char const* suite, char const* test);16 17 18 19 20 21 22 23 24 25 26 13 DeferredTestResult ( char const* suite, char const* test ); 14 ~DeferredTestResult(); 15 16 std::string suiteName; 17 std::string testName; 18 std::string failureFile; 19 20 typedef std::pair< int, std::string > Failure; 21 typedef std::vector< Failure > FailureVec; 22 FailureVec failures; 23 24 float timeElapsed; 27 25 bool failed; 28 26 }; -
TabularUnified library/tests/unittest-cpp/ExecuteTest.h ¶
r418 r477 8 8 9 9 #ifdef UNITTEST_POSIX 10 10 #include "Posix/SignalTranslator.h" 11 11 #endif 12 12 … … 14 14 15 15 template< typename T > 16 void ExecuteTest(T& testObject, TestDetails const& details) 17 { 16 void ExecuteTest ( T& testObject, TestDetails const& details ) { 18 17 CurrentTest::Details() = &details; 19 18 20 try 21 { 19 try { 22 20 #ifdef UNITTEST_POSIX 23 21 UNITTEST_THROW_SIGNALS 24 22 #endif 25 23 testObject.RunImpl(); 26 } 27 catch (AssertException const& e) 28 { 29 CurrentTest::Results()->OnTestFailure( 30 TestDetails(details.testName, details.suiteName, e.Filename(), e.LineNumber()), e.what()); 31 } 32 catch (std::exception const& e) 33 { 24 } catch ( AssertException const& e ) { 25 CurrentTest::Results()->OnTestFailure ( 26 TestDetails ( details.testName, details.suiteName, e.Filename(), e.LineNumber() ), e.what() ); 27 } catch ( std::exception const& e ) { 34 28 MemoryOutStream stream; 35 29 stream << "Unhandled exception: " << e.what(); 36 CurrentTest::Results()->OnTestFailure(details, stream.GetText()); 37 } 38 catch (...) 39 { 40 CurrentTest::Results()->OnTestFailure(details, "Unhandled exception: Crash!"); 30 CurrentTest::Results()->OnTestFailure ( details, stream.GetText() ); 31 } catch ( ... ) { 32 CurrentTest::Results()->OnTestFailure ( details, "Unhandled exception: Crash!" ); 41 33 } 42 34 } -
TabularUnified library/tests/unittest-cpp/MemoryOutStream.cpp ¶
r418 r477 6 6 namespace UnitTest { 7 7 8 char const* MemoryOutStream::GetText() const 9 { 10 m_text = this->str(); 11 return m_text.c_str(); 8 char const* MemoryOutStream::GetText() const { 9 m_text = this->str(); 10 return m_text.c_str(); 12 11 } 13 12 … … 27 26 28 27 template<typename ValueType> 29 void FormatToStream(MemoryOutStream& stream, char const* format, ValueType const& value) 30 { 28 void FormatToStream ( MemoryOutStream& stream, char const* format, ValueType const& value ) { 31 29 using namespace std; 32 30 33 34 sprintf(txt, format, value);35 31 char txt[32]; 32 sprintf ( txt, format, value ); 33 stream << txt; 36 34 } 37 35 38 int RoundUpToMultipleOfPow2Number (int n, int pow2Number) 39 { 40 return (n + (pow2Number - 1)) & ~(pow2Number - 1); 36 int RoundUpToMultipleOfPow2Number ( int n, int pow2Number ) { 37 return ( n + ( pow2Number - 1 ) ) & ~ ( pow2Number - 1 ); 41 38 } 42 39 … … 44 41 45 42 46 MemoryOutStream::MemoryOutStream (int const size)47 : m_capacity (0)48 , m_buffer (0)43 MemoryOutStream::MemoryOutStream ( int const size ) 44 : m_capacity ( 0 ) 45 , m_buffer ( 0 ) 49 46 50 47 { 51 GrowBuffer(size);48 GrowBuffer ( size ); 52 49 } 53 50 54 MemoryOutStream::~MemoryOutStream() 55 { 56 delete [] m_buffer; 51 MemoryOutStream::~MemoryOutStream() { 52 delete [] m_buffer; 57 53 } 58 54 59 char const* MemoryOutStream::GetText() const 60 { 61 return m_buffer; 55 char const* MemoryOutStream::GetText() const { 56 return m_buffer; 62 57 } 63 58 64 MemoryOutStream& MemoryOutStream::operator << (char const* txt) 65 { 59 MemoryOutStream& MemoryOutStream::operator << ( char const* txt ) { 66 60 using namespace std; 67 61 68 int const bytesLeft = m_capacity - (int)strlen(m_buffer);69 int const bytesRequired = (int)strlen(txt) + 1;62 int const bytesLeft = m_capacity - ( int ) strlen ( m_buffer ); 63 int const bytesRequired = ( int ) strlen ( txt ) + 1; 70 64 71 if (bytesRequired > bytesLeft) 72 { 73 int const requiredCapacity = bytesRequired + m_capacity - bytesLeft; 74 GrowBuffer(requiredCapacity); 75 } 65 if ( bytesRequired > bytesLeft ) { 66 int const requiredCapacity = bytesRequired + m_capacity - bytesLeft; 67 GrowBuffer ( requiredCapacity ); 68 } 76 69 77 strcat(m_buffer, txt); 78 return *this; 79 } 80 81 MemoryOutStream& MemoryOutStream::operator << (int const n) 82 { 83 FormatToStream(*this, "%i", n); 84 return *this; 85 } 86 87 MemoryOutStream& MemoryOutStream::operator << (long const n) 88 { 89 FormatToStream(*this, "%li", n); 90 return *this; 91 } 92 93 MemoryOutStream& MemoryOutStream::operator << (unsigned long const n) 94 { 95 FormatToStream(*this, "%lu", n); 96 return *this; 97 } 98 99 MemoryOutStream& MemoryOutStream::operator << (float const f) 100 { 101 FormatToStream(*this, "%ff", f); 102 return *this; 103 } 104 105 MemoryOutStream& MemoryOutStream::operator << (void const* p) 106 { 107 FormatToStream(*this, "%p", p); 108 return *this; 109 } 110 111 MemoryOutStream& MemoryOutStream::operator << (unsigned int const s) 112 { 113 FormatToStream(*this, "%u", s); 114 return *this; 115 } 116 117 MemoryOutStream& MemoryOutStream::operator <<(double const d) 118 { 119 FormatToStream(*this, "%f", d); 70 strcat ( m_buffer, txt ); 120 71 return *this; 121 72 } 122 73 123 int MemoryOutStream::GetCapacity() const 124 { 125 return m_capacity; 74 MemoryOutStream& MemoryOutStream::operator << ( int const n ) { 75 FormatToStream ( *this, "%i", n ); 76 return *this; 77 } 78 79 MemoryOutStream& MemoryOutStream::operator << ( long const n ) { 80 FormatToStream ( *this, "%li", n ); 81 return *this; 82 } 83 84 MemoryOutStream& MemoryOutStream::operator << ( unsigned long const n ) { 85 FormatToStream ( *this, "%lu", n ); 86 return *this; 87 } 88 89 MemoryOutStream& MemoryOutStream::operator << ( float const f ) { 90 FormatToStream ( *this, "%ff", f ); 91 return *this; 92 } 93 94 MemoryOutStream& MemoryOutStream::operator << ( void const* p ) { 95 FormatToStream ( *this, "%p", p ); 96 return *this; 97 } 98 99 MemoryOutStream& MemoryOutStream::operator << ( unsigned int const s ) { 100 FormatToStream ( *this, "%u", s ); 101 return *this; 102 } 103 104 MemoryOutStream& MemoryOutStream::operator << ( double const d ) { 105 FormatToStream ( *this, "%f", d ); 106 return *this; 107 } 108 109 int MemoryOutStream::GetCapacity() const { 110 return m_capacity; 126 111 } 127 112 128 113 129 void MemoryOutStream::GrowBuffer(int const desiredCapacity) 130 { 131 int const newCapacity = RoundUpToMultipleOfPow2Number(desiredCapacity, GROW_CHUNK_SIZE); 114 void MemoryOutStream::GrowBuffer ( int const desiredCapacity ) { 115 int const newCapacity = RoundUpToMultipleOfPow2Number ( desiredCapacity, GROW_CHUNK_SIZE ); 132 116 133 117 using namespace std; 134 118 135 136 if (m_buffer)137 strcpy(buffer, m_buffer);138 139 strcpy(buffer, "");119 char* buffer = new char[newCapacity]; 120 if ( m_buffer ) 121 strcpy ( buffer, m_buffer ); 122 else 123 strcpy ( buffer, "" ); 140 124 141 142 143 125 delete [] m_buffer; 126 m_buffer = buffer; 127 m_capacity = newCapacity; 144 128 } 145 129 -
TabularUnified library/tests/unittest-cpp/MemoryOutStream.h ¶
r418 r477 8 8 #include <sstream> 9 9 10 namespace UnitTest 11 { 10 namespace UnitTest { 12 11 13 class MemoryOutStream : public std::ostringstream 14 { 12 class MemoryOutStream : public std::ostringstream { 15 13 public: 16 17 18 14 MemoryOutStream() {} 15 ~MemoryOutStream() {} 16 char const* GetText() const; 19 17 20 18 private: 21 MemoryOutStream(MemoryOutStream const&);22 void operator =(MemoryOutStream const&);19 MemoryOutStream ( MemoryOutStream const& ); 20 void operator = ( MemoryOutStream const& ); 23 21 24 22 mutable std::string m_text; 25 23 }; 26 24 … … 31 29 #include <cstddef> 32 30 33 namespace UnitTest 34 { 31 namespace UnitTest { 35 32 36 class MemoryOutStream 37 { 33 class MemoryOutStream { 38 34 public: 39 explicit MemoryOutStream(int const size = 256);40 35 explicit MemoryOutStream ( int const size = 256 ); 36 ~MemoryOutStream(); 41 37 42 38 char const* GetText() const; 43 39 44 MemoryOutStream& operator << (char const* txt);45 MemoryOutStream& operator << (int n);46 MemoryOutStream& operator << (long n);47 MemoryOutStream& operator << (unsigned long n);48 MemoryOutStream& operator << (float f);49 MemoryOutStream& operator << (double d);50 MemoryOutStream& operator << (void const* p);51 MemoryOutStream& operator << (unsigned int s);40 MemoryOutStream& operator << ( char const* txt ); 41 MemoryOutStream& operator << ( int n ); 42 MemoryOutStream& operator << ( long n ); 43 MemoryOutStream& operator << ( unsigned long n ); 44 MemoryOutStream& operator << ( float f ); 45 MemoryOutStream& operator << ( double d ); 46 MemoryOutStream& operator << ( void const* p ); 47 MemoryOutStream& operator << ( unsigned int s ); 52 48 53 54 49 enum { GROW_CHUNK_SIZE = 32 }; 50 int GetCapacity() const; 55 51 56 52 private: 57 void operator= (MemoryOutStream const&);58 void GrowBuffer(int capacity);53 void operator= ( MemoryOutStream const& ); 54 void GrowBuffer ( int capacity ); 59 55 60 61 56 int m_capacity; 57 char* m_buffer; 62 58 }; 63 59 -
TabularUnified library/tests/unittest-cpp/Posix/SignalTranslator.cpp ¶
r418 r477 7 7 namespace { 8 8 9 void SignalHandler(int sig) 10 { 11 siglongjmp(*SignalTranslator::s_jumpTarget, sig ); 9 void SignalHandler ( int sig ) { 10 siglongjmp ( *SignalTranslator::s_jumpTarget, sig ); 12 11 } 13 12 … … 15 14 16 15 17 SignalTranslator::SignalTranslator() 18 { 19 m_oldJumpTarget = s_jumpTarget; 20 s_jumpTarget = &m_currentJumpTarget; 16 SignalTranslator::SignalTranslator() { 17 m_oldJumpTarget = s_jumpTarget; 18 s_jumpTarget = &m_currentJumpTarget; 21 19 22 23 24 25 sigemptyset( &action.sa_mask );20 struct sigaction action; 21 action.sa_flags = 0; 22 action.sa_handler = SignalHandler; 23 sigemptyset ( &action.sa_mask ); 26 24 27 sigaction( SIGSEGV, &action, &m_old_SIGSEGV_action );28 sigaction( SIGFPE , &action, &m_old_SIGFPE_action);29 sigaction( SIGTRAP, &action, &m_old_SIGTRAP_action );30 sigaction( SIGBUS , &action, &m_old_SIGBUS_action);31 sigaction( SIGILL , &action, &m_old_SIGBUS_action);25 sigaction ( SIGSEGV, &action, &m_old_SIGSEGV_action ); 26 sigaction ( SIGFPE , &action, &m_old_SIGFPE_action ); 27 sigaction ( SIGTRAP, &action, &m_old_SIGTRAP_action ); 28 sigaction ( SIGBUS , &action, &m_old_SIGBUS_action ); 29 sigaction ( SIGILL , &action, &m_old_SIGBUS_action ); 32 30 } 33 31 34 SignalTranslator::~SignalTranslator() 35 { 36 sigaction( SIGILL , &m_old_SIGBUS_action , 0 ); 37 sigaction( SIGBUS , &m_old_SIGBUS_action , 0 ); 38 sigaction( SIGTRAP, &m_old_SIGTRAP_action, 0 ); 39 sigaction( SIGFPE , &m_old_SIGFPE_action , 0 ); 40 sigaction( SIGSEGV, &m_old_SIGSEGV_action, 0 ); 32 SignalTranslator::~SignalTranslator() { 33 sigaction ( SIGILL , &m_old_SIGBUS_action , 0 ); 34 sigaction ( SIGBUS , &m_old_SIGBUS_action , 0 ); 35 sigaction ( SIGTRAP, &m_old_SIGTRAP_action, 0 ); 36 sigaction ( SIGFPE , &m_old_SIGFPE_action , 0 ); 37 sigaction ( SIGSEGV, &m_old_SIGSEGV_action, 0 ); 41 38 42 39 s_jumpTarget = m_oldJumpTarget; 43 40 } 44 41 -
TabularUnified library/tests/unittest-cpp/Posix/SignalTranslator.h ¶
r418 r477 7 7 namespace UnitTest { 8 8 9 class SignalTranslator 10 { 9 class SignalTranslator { 11 10 public: 12 13 11 SignalTranslator(); 12 ~SignalTranslator(); 14 13 15 14 static sigjmp_buf* s_jumpTarget; 16 15 17 16 private: 18 19 17 sigjmp_buf m_currentJumpTarget; 18 sigjmp_buf* m_oldJumpTarget; 20 19 21 22 23 24 25 26 20 struct sigaction m_old_SIGFPE_action; 21 struct sigaction m_old_SIGTRAP_action; 22 struct sigaction m_old_SIGSEGV_action; 23 struct sigaction m_old_SIGBUS_action; 24 struct sigaction m_old_SIGABRT_action; 25 struct sigaction m_old_SIGALRM_action; 27 26 }; 28 27 29 28 #if !defined (__GNUC__) 30 29 #define UNITTEST_EXTENSION 31 30 #else 32 31 #define UNITTEST_EXTENSION __extension__ 33 32 #endif 34 33 … … 36 35 UnitTest::SignalTranslator sig; \ 37 36 if (UNITTEST_EXTENSION sigsetjmp(*UnitTest::SignalTranslator::s_jumpTarget, 1) != 0) \ 38 throw ("Unhandled system exception"); 37 throw ("Unhandled system exception"); 39 38 40 39 } -
TabularUnified library/tests/unittest-cpp/Posix/TimeHelpers.cpp ¶
r418 r477 4 4 namespace UnitTest { 5 5 6 Timer::Timer() 7 { 8 m_startTime.tv_sec = 0; 9 m_startTime.tv_usec = 0; 6 Timer::Timer() { 7 m_startTime.tv_sec = 0; 8 m_startTime.tv_usec = 0; 10 9 } 11 10 12 void Timer::Start() 13 { 14 gettimeofday(&m_startTime, 0); 11 void Timer::Start() { 12 gettimeofday ( &m_startTime, 0 ); 15 13 } 16 14 17 double Timer::GetTimeInMs() const 18 { 19 struct timeval currentTime; 20 gettimeofday(¤tTime, 0); 15 double Timer::GetTimeInMs() const { 16 struct timeval currentTime; 17 gettimeofday ( ¤tTime, 0 ); 21 18 22 19 double const dsecs = currentTime.tv_sec - m_startTime.tv_sec; 23 20 double const dus = currentTime.tv_usec - m_startTime.tv_usec; 24 21 25 return ( dsecs * 1000.0) + (dus / 1000.0);22 return ( dsecs * 1000.0 ) + ( dus / 1000.0 ); 26 23 } 27 24 28 void TimeHelpers::SleepMs(int ms) 29 { 30 usleep(ms * 1000); 25 void TimeHelpers::SleepMs ( int ms ) { 26 usleep ( ms * 1000 ); 31 27 } 32 28 -
TabularUnified library/tests/unittest-cpp/Posix/TimeHelpers.h ¶
r418 r477 6 6 namespace UnitTest { 7 7 8 class Timer 9 { 8 class Timer { 10 9 public: 11 12 13 double GetTimeInMs() const; 10 Timer(); 11 void Start(); 12 double GetTimeInMs() const; 14 13 15 14 private: 16 struct timeval m_startTime; 15 struct timeval m_startTime; 17 16 }; 18 17 19 18 20 namespace TimeHelpers 21 { 22 void SleepMs (int ms); 19 namespace TimeHelpers { 20 void SleepMs ( int ms ); 23 21 } 24 22 -
TabularUnified library/tests/unittest-cpp/ReportAssert.cpp ¶
r418 r477 4 4 namespace UnitTest { 5 5 6 void ReportAssert(char const* description, char const* filename, int lineNumber) 7 { 8 throw AssertException(description, filename, lineNumber); 6 void ReportAssert ( char const* description, char const* filename, int lineNumber ) { 7 throw AssertException ( description, filename, lineNumber ); 9 8 } 10 9 -
TabularUnified library/tests/unittest-cpp/ReportAssert.h ¶
r418 r477 4 4 namespace UnitTest { 5 5 6 void ReportAssert (char const* description, char const* filename, int lineNumber);7 6 void ReportAssert ( char const* description, char const* filename, int lineNumber ); 7 8 8 } 9 9 -
TabularUnified library/tests/unittest-cpp/Test.cpp ¶
r435 r477 9 9 10 10 #ifdef UNITTEST_POSIX 11 11 #include "Posix/SignalTranslator.h" 12 12 #endif 13 13 14 14 namespace UnitTest { 15 15 16 TestList& Test::GetTestList() 17 { 18 static TestList s_list; 19 return s_list; 16 TestList& Test::GetTestList() { 17 static TestList s_list; 18 return s_list; 20 19 } 21 20 22 Test::Test(char const* testName, char const* suiteName, char const* filename, int lineNumber) 23 : m_details(testName, suiteName, filename, lineNumber) 24 , next(0) 25 , m_timeConstraintExempt(false) 26 { 21 Test::Test ( char const* testName, char const* suiteName, char const* filename, int lineNumber ) 22 : m_details ( testName, suiteName, filename, lineNumber ) 23 , next ( 0 ) 24 , m_timeConstraintExempt ( false ) { 27 25 } 28 26 29 Test::~Test() 30 { 27 Test::~Test() { 31 28 } 32 29 33 void Test::Run() 34 { 30 void Test::Run() { 35 31 // made more chatty; presumes the only used test reporter is 36 32 // TestReporterStdout 37 std::printf ("running %s...\n", m_details.testName);33 std::printf ( "running %s...\n", m_details.testName ); 38 34 39 ExecuteTest (*this, m_details);35 ExecuteTest ( *this, m_details ); 40 36 } 41 37 42 void Test::RunImpl() const 43 { 38 void Test::RunImpl() const { 44 39 } 45 40 -
TabularUnified library/tests/unittest-cpp/Test.h ¶
r418 r477 9 9 class TestList; 10 10 11 class Test 12 { 11 class Test { 13 12 public: 14 explicit Test(char const* testName, char const* suiteName = "DefaultSuite", char const* filename = "", int lineNumber = 0);15 16 13 explicit Test ( char const* testName, char const* suiteName = "DefaultSuite", char const* filename = "", int lineNumber = 0 ); 14 virtual ~Test(); 15 void Run(); 17 16 18 19 20 17 TestDetails const m_details; 18 Test* next; 19 mutable bool m_timeConstraintExempt; 21 20 22 21 static TestList& GetTestList(); 23 22 24 23 virtual void RunImpl() const; 25 24 26 25 private: 27 Test (Test const&);28 Test& operator =(Test const&);26 Test ( Test const& ); 27 Test& operator = ( Test const& ); 29 28 }; 30 29 -
TabularUnified library/tests/unittest-cpp/TestDetails.cpp ¶
r456 r477 3 3 namespace UnitTest { 4 4 5 TestDetails::TestDetails(char const* testName_, char const* suiteName_, char const* filename_, int lineNumber_, bool useFilename_) 6 : suiteName(suiteName_) 7 , testName(testName_) 8 , filename(filename_) 9 , lineNumber(lineNumber_) 10 , useFilename(useFilename_) 11 { 5 TestDetails::TestDetails ( char const* testName_, char const* suiteName_, char const* filename_, int lineNumber_, bool useFilename_ ) 6 : suiteName ( suiteName_ ) 7 , testName ( testName_ ) 8 , filename ( filename_ ) 9 , lineNumber ( lineNumber_ ) 10 , useFilename ( useFilename_ ) { 12 11 } 13 12 14 TestDetails::TestDetails(const TestDetails& details, int lineNumber_, bool useFilename_) 15 : suiteName(details.suiteName) 16 , testName(details.testName) 17 , filename(details.filename) 18 , lineNumber(lineNumber_) 19 , useFilename(useFilename_) 20 { 13 TestDetails::TestDetails ( const TestDetails& details, int lineNumber_, bool useFilename_ ) 14 : suiteName ( details.suiteName ) 15 , testName ( details.testName ) 16 , filename ( details.filename ) 17 , lineNumber ( lineNumber_ ) 18 , useFilename ( useFilename_ ) { 21 19 } 22 20 -
TabularUnified library/tests/unittest-cpp/TestDetails.h ¶
r456 r477 4 4 namespace UnitTest { 5 5 6 class TestDetails 7 { 6 class TestDetails { 8 7 public: 9 TestDetails(char const* testName, char const* suiteName, char const* filename, int lineNumber, bool useFilename = true);10 TestDetails(const TestDetails& details, int lineNumber, bool useFilename = true);8 TestDetails ( char const* testName, char const* suiteName, char const* filename, int lineNumber, bool useFilename = true ); 9 TestDetails ( const TestDetails& details, int lineNumber, bool useFilename = true ); 11 10 12 13 14 15 16 11 char const* const suiteName; 12 char const* const testName; 13 char const* const filename; 14 int const lineNumber; 15 bool const useFilename; 17 16 18 TestDetails(TestDetails const&); // Why is it public? --> http://gcc.gnu.org/bugs.html#cxx_rvalbind17 TestDetails ( TestDetails const& ); // Why is it public? --> http://gcc.gnu.org/bugs.html#cxx_rvalbind 19 18 private: 20 TestDetails& operator=(TestDetails const&);19 TestDetails& operator= ( TestDetails const& ); 21 20 }; 22 21 -
TabularUnified library/tests/unittest-cpp/TestList.cpp ¶
r418 r477 6 6 namespace UnitTest { 7 7 8 TestList::TestList() 9 : m_head(0) 10 , m_tail(0) 11 { 8 TestList::TestList() 9 : m_head ( 0 ) 10 , m_tail ( 0 ) { 12 11 } 13 12 14 void TestList::Add(Test* test) 15 { 16 if (m_tail == 0) 17 { 18 assert(m_head == 0); 19 m_head = test; 20 m_tail = test; 21 } 22 else 23 { 24 m_tail->next = test; 25 m_tail = test; 26 } 13 void TestList::Add ( Test* test ) { 14 if ( m_tail == 0 ) { 15 assert ( m_head == 0 ); 16 m_head = test; 17 m_tail = test; 18 } else { 19 m_tail->next = test; 20 m_tail = test; 21 } 27 22 } 28 23 29 Test* TestList::GetHead() const 30 { 31 return m_head; 24 Test* TestList::GetHead() const { 25 return m_head; 32 26 } 33 27 34 ListAdder::ListAdder(TestList& list, Test* test) 35 { 36 list.Add(test); 28 ListAdder::ListAdder ( TestList& list, Test* test ) { 29 list.Add ( test ); 37 30 } 38 31 -
TabularUnified library/tests/unittest-cpp/TestList.h ¶
r418 r477 7 7 class Test; 8 8 9 class TestList 10 { 9 class TestList { 11 10 public: 12 13 void Add (Test* test);11 TestList(); 12 void Add ( Test* test ); 14 13 15 14 Test* GetHead() const; 16 15 17 16 private: 18 19 17 Test* m_head; 18 Test* m_tail; 20 19 }; 21 20 22 21 23 class ListAdder 24 { 22 class ListAdder { 25 23 public: 26 ListAdder(TestList& list, Test* test);24 ListAdder ( TestList& list, Test* test ); 27 25 }; 28 26 -
TabularUnified library/tests/unittest-cpp/TestMacros.h ¶
r418 r477 9 9 10 10 #ifndef UNITTEST_POSIX 11 11 #define UNITTEST_THROW_SIGNALS 12 12 #else 13 13 #include "Posix/SignalTranslator.h" 14 14 #endif 15 15 16 16 #ifdef TEST 17 17 #error UnitTest++ redefines TEST 18 18 #endif 19 19 20 20 #ifdef TEST_EX 21 21 #error UnitTest++ redefines TEST_EX 22 22 #endif 23 23 24 24 #ifdef TEST_FIXTURE_EX 25 25 #error UnitTest++ redefines TEST_FIXTURE_EX 26 26 #endif 27 27 -
TabularUnified library/tests/unittest-cpp/TestReporter.cpp ¶
r418 r477 4 4 5 5 6 TestReporter::~TestReporter() 7 { 6 TestReporter::~TestReporter() { 8 7 } 9 8 -
TabularUnified library/tests/unittest-cpp/TestReporter.h ¶
r418 r477 6 6 class TestDetails; 7 7 8 class TestReporter 9 { 8 class TestReporter { 10 9 public: 11 10 virtual ~TestReporter(); 12 11 13 virtual void ReportTestStart(TestDetails const& test) = 0;14 virtual void ReportFailure(TestDetails const& test, char const* failure) = 0;15 virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed) = 0;16 virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed) = 0;12 virtual void ReportTestStart ( TestDetails const& test ) = 0; 13 virtual void ReportFailure ( TestDetails const& test, char const* failure ) = 0; 14 virtual void ReportTestFinish ( TestDetails const& test, float secondsElapsed ) = 0; 15 virtual void ReportSummary ( int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed ) = 0; 17 16 }; 18 17 -
TabularUnified library/tests/unittest-cpp/TestReporterStdout.cpp ¶
r456 r477 6 6 // cstdio doesn't pull in namespace std on VC6, so we do it here. 7 7 #if defined(_MSC_VER) && (_MSC_VER == 1200) 8 8 namespace std {} 9 9 #endif 10 10 11 11 namespace UnitTest { 12 12 13 void TestReporterStdout::ReportFailure(TestDetails const& details, char const* failure) 14 { 13 void TestReporterStdout::ReportFailure ( TestDetails const& details, char const* failure ) { 15 14 #if defined(__APPLE__) || defined(__GNUG__) 16 15 char const* const errorFormat = "%s:%d: error: Failure in %s: %s\n"; 17 16 #else 18 17 char const* const errorFormat = "%s(%d): error: Failure in %s: %s\n"; 19 18 #endif 20 19 21 20 using namespace std; 22 21 23 if (details.useFilename) {24 25 printf(errorFormat, details.filename, details.lineNumber, details.testName, failure);26 } else { 27 28 // (custom) test location info29 printf("%s\n", failure);30 22 if ( details.useFilename ) { 23 // standard way 24 printf ( errorFormat, details.filename, details.lineNumber, details.testName, failure ); 25 } else { 26 // extended for BDM - the failure string already includes 27 // (custom) test location info 28 printf ( "%s\n", failure ); 29 } 31 30 } 32 31 33 void TestReporterStdout::ReportTestStart(TestDetails const& /*test*/) 34 { 32 void TestReporterStdout::ReportTestStart ( TestDetails const& /*test*/ ) { 35 33 } 36 34 37 void TestReporterStdout::ReportTestFinish(TestDetails const& /*test*/, float) 38 { 35 void TestReporterStdout::ReportTestFinish ( TestDetails const& /*test*/, float ) { 39 36 } 40 37 41 void TestReporterStdout::ReportSummary(int const totalTestCount, int const failedTestCount, 42 int const failureCount, float secondsElapsed) 43 { 38 void TestReporterStdout::ReportSummary ( int const totalTestCount, int const failedTestCount, 39 int const failureCount, float secondsElapsed ) { 44 40 using namespace std; 45 41 46 if (failureCount > 0)47 printf("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);48 49 printf("Success: %d tests passed.\n", totalTestCount);42 if ( failureCount > 0 ) 43 printf ( "FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount ); 44 else 45 printf ( "Success: %d tests passed.\n", totalTestCount ); 50 46 51 printf("Test time: %.2f seconds.\n", secondsElapsed);47 printf ( "Test time: %.2f seconds.\n", secondsElapsed ); 52 48 } 53 49 -
TabularUnified library/tests/unittest-cpp/TestReporterStdout.h ¶
r418 r477 6 6 namespace UnitTest { 7 7 8 class TestReporterStdout : public TestReporter 9 { 8 class TestReporterStdout : public TestReporter { 10 9 private: 11 virtual void ReportTestStart(TestDetails const& test);12 virtual void ReportFailure(TestDetails const& test, char const* failure);13 virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed);14 virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);10 virtual void ReportTestStart ( TestDetails const& test ); 11 virtual void ReportFailure ( TestDetails const& test, char const* failure ); 12 virtual void ReportTestFinish ( TestDetails const& test, float secondsElapsed ); 13 virtual void ReportSummary ( int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed ); 15 14 }; 16 15 17 16 } 18 17 19 #endif 18 #endif -
TabularUnified library/tests/unittest-cpp/TestResults.cpp ¶
r418 r477 6 6 namespace UnitTest { 7 7 8 TestResults::TestResults(TestReporter* testReporter) 9 : m_testReporter(testReporter) 10 , m_totalTestCount(0) 11 , m_failedTestCount(0) 12 , m_failureCount(0) 13 , m_currentTestFailed(false) 14 { 8 TestResults::TestResults ( TestReporter* testReporter ) 9 : m_testReporter ( testReporter ) 10 , m_totalTestCount ( 0 ) 11 , m_failedTestCount ( 0 ) 12 , m_failureCount ( 0 ) 13 , m_currentTestFailed ( false ) { 15 14 } 16 15 17 void TestResults::OnTestStart(TestDetails const& test) 18 { 19 ++m_totalTestCount; 20 m_currentTestFailed = false; 21 if (m_testReporter) 22 m_testReporter->ReportTestStart(test); 16 void TestResults::OnTestStart ( TestDetails const& test ) { 17 ++m_totalTestCount; 18 m_currentTestFailed = false; 19 if ( m_testReporter ) 20 m_testReporter->ReportTestStart ( test ); 23 21 } 24 22 25 void TestResults::OnTestFailure(TestDetails const& test, char const* failure) 26 { 27 ++m_failureCount; 28 if (!m_currentTestFailed) 29 { 30 ++m_failedTestCount; 31 m_currentTestFailed = true; 32 } 23 void TestResults::OnTestFailure ( TestDetails const& test, char const* failure ) { 24 ++m_failureCount; 25 if ( !m_currentTestFailed ) { 26 ++m_failedTestCount; 27 m_currentTestFailed = true; 28 } 33 29 34 if (m_testReporter)35 m_testReporter->ReportFailure(test, failure);30 if ( m_testReporter ) 31 m_testReporter->ReportFailure ( test, failure ); 36 32 } 37 33 38 void TestResults::OnTestFinish(TestDetails const& test, float secondsElapsed) 39 { 40 if (m_testReporter) 41 m_testReporter->ReportTestFinish(test, secondsElapsed); 34 void TestResults::OnTestFinish ( TestDetails const& test, float secondsElapsed ) { 35 if ( m_testReporter ) 36 m_testReporter->ReportTestFinish ( test, secondsElapsed ); 42 37 } 43 38 44 int TestResults::GetTotalTestCount() const 45 { 46 return m_totalTestCount; 39 int TestResults::GetTotalTestCount() const { 40 return m_totalTestCount; 47 41 } 48 42 49 int TestResults::GetFailedTestCount() const 50 { 51 return m_failedTestCount; 43 int TestResults::GetFailedTestCount() const { 44 return m_failedTestCount; 52 45 } 53 46 54 int TestResults::GetFailureCount() const 55 { 56 return m_failureCount; 47 int TestResults::GetFailureCount() const { 48 return m_failureCount; 57 49 } 58 50 -
TabularUnified library/tests/unittest-cpp/TestResults.h ¶
r418 r477 7 7 class TestDetails; 8 8 9 class TestResults 10 { 9 class TestResults { 11 10 public: 12 explicit TestResults(TestReporter* reporter = 0);11 explicit TestResults ( TestReporter* reporter = 0 ); 13 12 14 void OnTestStart(TestDetails const& test);15 void OnTestFailure(TestDetails const& test, char const* failure);16 void OnTestFinish(TestDetails const& test, float secondsElapsed);13 void OnTestStart ( TestDetails const& test ); 14 void OnTestFailure ( TestDetails const& test, char const* failure ); 15 void OnTestFinish ( TestDetails const& test, float secondsElapsed ); 17 16 18 19 20 17 int GetTotalTestCount() const; 18 int GetFailedTestCount() const; 19 int GetFailureCount() const; 21 20 22 21 private: 23 24 25 26 22 TestReporter* m_testReporter; 23 int m_totalTestCount; 24 int m_failedTestCount; 25 int m_failureCount; 27 26 28 27 bool m_currentTestFailed; 29 28 30 TestResults(TestResults const&);31 TestResults& operator =(TestResults const&);29 TestResults ( TestResults const& ); 30 TestResults& operator = ( TestResults const& ); 32 31 }; 33 32 -
TabularUnified library/tests/unittest-cpp/TestRunner.cpp ¶
r418 r477 11 11 namespace UnitTest { 12 12 13 int RunAllTests() 14 { 13 int RunAllTests() { 15 14 TestReporterStdout reporter; 16 TestRunner runner (reporter);17 return runner.RunTestsIf (Test::GetTestList(), NULL, True(), 0);15 TestRunner runner ( reporter ); 16 return runner.RunTestsIf ( Test::GetTestList(), NULL, True(), 0 ); 18 17 } 19 18 20 19 21 TestRunner::TestRunner(TestReporter& reporter) 22 : m_reporter(&reporter) 23 , m_result(new TestResults(&reporter)) 24 , m_timer(new Timer) 25 { 20 TestRunner::TestRunner ( TestReporter& reporter ) 21 : m_reporter ( &reporter ) 22 , m_result ( new TestResults ( &reporter ) ) 23 , m_timer ( new Timer ) { 26 24 m_timer->Start(); 27 25 } 28 26 29 TestRunner::~TestRunner() 30 { 27 TestRunner::~TestRunner() { 31 28 delete m_result; 32 29 delete m_timer; 33 30 } 34 31 35 int TestRunner::Finish() const 36 { 37 float const secondsElapsed = static_cast<float>(m_timer->GetTimeInMs() / 1000.0); 38 m_reporter->ReportSummary(m_result->GetTotalTestCount(), 39 m_result->GetFailedTestCount(), 40 m_result->GetFailureCount(), 41 secondsElapsed); 42 32 int TestRunner::Finish() const { 33 float const secondsElapsed = static_cast<float> ( m_timer->GetTimeInMs() / 1000.0 ); 34 m_reporter->ReportSummary ( m_result->GetTotalTestCount(), 35 m_result->GetFailedTestCount(), 36 m_result->GetFailureCount(), 37 secondsElapsed ); 38 43 39 return m_result->GetFailureCount(); 44 40 } 45 41 46 bool TestRunner::IsTestInSuite(const Test* const curTest, char const* suiteName) const 47 { 42 bool TestRunner::IsTestInSuite ( const Test* const curTest, char const* suiteName ) const { 48 43 using namespace std; 49 return ( suiteName == NULL) || !strcmp(curTest->m_details.suiteName, suiteName);44 return ( suiteName == NULL ) || !strcmp ( curTest->m_details.suiteName, suiteName ); 50 45 } 51 46 52 void TestRunner::RunTest(TestResults* const result, Test* const curTest, int const maxTestTimeInMs) const 53 { 47 void TestRunner::RunTest ( TestResults* const result, Test* const curTest, int const maxTestTimeInMs ) const { 54 48 CurrentTest::Results() = result; 55 49 … … 57 51 testTimer.Start(); 58 52 59 result->OnTestStart (curTest->m_details);53 result->OnTestStart ( curTest->m_details ); 60 54 61 55 curTest->Run(); 62 56 63 57 double const testTimeInMs = testTimer.GetTimeInMs(); 64 if (maxTestTimeInMs > 0 && testTimeInMs > maxTestTimeInMs && !curTest->m_timeConstraintExempt) 65 { 66 MemoryOutStream stream; 67 stream << "Global time constraint failed. Expected under " << maxTestTimeInMs << 68 "ms but took " << testTimeInMs << "ms."; 58 if ( maxTestTimeInMs > 0 && testTimeInMs > maxTestTimeInMs && !curTest->m_timeConstraintExempt ) { 59 MemoryOutStream stream; 60 stream << "Global time constraint failed. Expected under " << maxTestTimeInMs << 61 "ms but took " << testTimeInMs << "ms."; 69 62 70 result->OnTestFailure(curTest->m_details, stream.GetText());63 result->OnTestFailure ( curTest->m_details, stream.GetText() ); 71 64 } 72 65 73 result->OnTestFinish (curTest->m_details, static_cast<float>(testTimeInMs/1000.0));66 result->OnTestFinish ( curTest->m_details, static_cast<float> ( testTimeInMs / 1000.0 ) ); 74 67 } 75 68 -
TabularUnified library/tests/unittest-cpp/TestRunner.h ¶
r418 r477 14 14 int RunAllTests(); 15 15 16 struct True 17 { 18 bool operator()(const Test* const) const 19 { 20 return true; 16 struct True { 17 bool operator() ( const Test* const ) const { 18 return true; 21 19 } 22 20 }; 23 21 24 class TestRunner 25 { 22 class TestRunner { 26 23 public: 27 explicit TestRunner (TestReporter& reporter);24 explicit TestRunner ( TestReporter& reporter ); 28 25 ~TestRunner(); 29 26 30 27 template <class Predicate> 31 int RunTestsIf(TestList const& list, char const* suiteName, 32 const Predicate& predicate, int maxTestTimeInMs) const 33 { 34 Test* curTest = list.GetHead(); 28 int RunTestsIf ( TestList const& list, char const* suiteName, 29 const Predicate& predicate, int maxTestTimeInMs ) const { 30 Test* curTest = list.GetHead(); 35 31 36 while (curTest != 0) 37 { 38 if (IsTestInSuite(curTest, suiteName) && predicate(curTest)) 39 RunTest(m_result, curTest, maxTestTimeInMs); 32 while ( curTest != 0 ) { 33 if ( IsTestInSuite ( curTest, suiteName ) && predicate ( curTest ) ) 34 RunTest ( m_result, curTest, maxTestTimeInMs ); 40 35 41 36 curTest = curTest->next; 42 37 } 43 38 44 45 } 39 return Finish(); 40 } 46 41 47 42 private: … … 51 46 52 47 int Finish() const; 53 bool IsTestInSuite (const Test* const curTest, char const* suiteName) const;54 void RunTest (TestResults* const result, Test* const curTest, int const maxTestTimeInMs) const;48 bool IsTestInSuite ( const Test* const curTest, char const* suiteName ) const; 49 void RunTest ( TestResults* const result, Test* const curTest, int const maxTestTimeInMs ) const; 55 50 }; 56 51 -
TabularUnified library/tests/unittest-cpp/TestSuite.h ¶
r418 r477 2 2 #define UNITTEST_TESTSUITE_H 3 3 4 namespace UnitTestSuite 5 { 6 inline char const* GetSuiteName () 7 { 8 return "DefaultSuite"; 9 } 4 namespace UnitTestSuite { 5 inline char const* GetSuiteName () { 6 return "DefaultSuite"; 7 } 10 8 } 11 9 -
TabularUnified library/tests/unittest-cpp/TimeConstraint.cpp ¶
r418 r477 7 7 8 8 9 TimeConstraint::TimeConstraint(int ms, TestDetails const& details) 10 : m_details(details) 11 , m_maxMs(ms) 12 { 13 m_timer.Start(); 9 TimeConstraint::TimeConstraint ( int ms, TestDetails const& details ) 10 : m_details ( details ) 11 , m_maxMs ( ms ) { 12 m_timer.Start(); 14 13 } 15 14 16 TimeConstraint::~TimeConstraint() 17 { 18 double const totalTimeInMs = m_timer.GetTimeInMs(); 19 if (totalTimeInMs > m_maxMs) 20 { 21 MemoryOutStream stream; 22 stream << "Time constraint failed. Expected to run test under " << m_maxMs << 23 "ms but took " << totalTimeInMs << "ms."; 15 TimeConstraint::~TimeConstraint() { 16 double const totalTimeInMs = m_timer.GetTimeInMs(); 17 if ( totalTimeInMs > m_maxMs ) { 18 MemoryOutStream stream; 19 stream << "Time constraint failed. Expected to run test under " << m_maxMs << 20 "ms but took " << totalTimeInMs << "ms."; 24 21 25 UnitTest::CurrentTest::Results()->OnTestFailure (m_details, stream.GetText());26 22 UnitTest::CurrentTest::Results()->OnTestFailure ( m_details, stream.GetText() ); 23 } 27 24 } 28 25 -
TabularUnified library/tests/unittest-cpp/TimeConstraint.h ¶
r418 r477 9 9 class TestDetails; 10 10 11 class TimeConstraint 12 { 11 class TimeConstraint { 13 12 public: 14 TimeConstraint(int ms, TestDetails const& details);15 13 TimeConstraint ( int ms, TestDetails const& details ); 14 ~TimeConstraint(); 16 15 17 16 private: 18 void operator=(TimeConstraint const&); 19 TimeConstraint (TimeConstraint const&);17 void operator= ( TimeConstraint const& ); 18 TimeConstraint ( TimeConstraint const& ); 20 19 21 20 Timer m_timer; 22 21 TestDetails const& m_details; 23 22 int const m_maxMs; 24 23 }; -
TabularUnified library/tests/unittest-cpp/TimeHelpers.h ¶
r418 r477 2 2 3 3 #if defined UNITTEST_POSIX 4 4 #include "Posix/TimeHelpers.h" 5 5 #else 6 6 #include "Win32/TimeHelpers.h" 7 7 #endif -
TabularUnified library/tests/unittest-cpp/Win32/TimeHelpers.cpp ¶
r418 r477 5 5 6 6 Timer::Timer() 7 : m_threadHandle(::GetCurrentThread()) 8 , m_startTime(0) 9 { 7 : m_threadHandle ( ::GetCurrentThread() ) 8 , m_startTime ( 0 ) { 10 9 #if defined(_MSC_VER) && (_MSC_VER == 1200) // VC6 doesn't have DWORD_PTR? 11 10 typedef unsigned long DWORD_PTR; … … 13 12 14 13 DWORD_PTR systemMask; 15 ::GetProcessAffinityMask (GetCurrentProcess(), &m_processAffinityMask, &systemMask);16 ::SetThreadAffinityMask (m_threadHandle, 1);17 ::QueryPerformanceFrequency (reinterpret_cast< LARGE_INTEGER* >(&m_frequency));18 ::SetThreadAffinityMask (m_threadHandle, m_processAffinityMask);14 ::GetProcessAffinityMask ( GetCurrentProcess(), &m_processAffinityMask, &systemMask ); 15 ::SetThreadAffinityMask ( m_threadHandle, 1 ); 16 ::QueryPerformanceFrequency ( reinterpret_cast< LARGE_INTEGER* > ( &m_frequency ) ); 17 ::SetThreadAffinityMask ( m_threadHandle, m_processAffinityMask ); 19 18 } 20 19 21 void Timer::Start() 22 { 20 void Timer::Start() { 23 21 m_startTime = GetTime(); 24 22 } 25 23 26 double Timer::GetTimeInMs() const 27 { 24 double Timer::GetTimeInMs() const { 28 25 __int64 const elapsedTime = GetTime() - m_startTime; 29 double const seconds = double (elapsedTime) / double(m_frequency);26 double const seconds = double ( elapsedTime ) / double ( m_frequency ); 30 27 return seconds * 1000.0; 31 28 } 32 29 33 __int64 Timer::GetTime() const 34 { 30 __int64 Timer::GetTime() const { 35 31 LARGE_INTEGER curTime; 36 ::SetThreadAffinityMask (m_threadHandle, 1);37 ::QueryPerformanceCounter (&curTime);38 ::SetThreadAffinityMask (m_threadHandle, m_processAffinityMask);32 ::SetThreadAffinityMask ( m_threadHandle, 1 ); 33 ::QueryPerformanceCounter ( &curTime ); 34 ::SetThreadAffinityMask ( m_threadHandle, m_processAffinityMask ); 39 35 return curTime.QuadPart; 40 36 } 41 37 42 void TimeHelpers::SleepMs(int const ms) 43 { 44 ::Sleep(ms); 38 void TimeHelpers::SleepMs ( int const ms ) { 39 ::Sleep ( ms ); 45 40 } 46 41 -
TabularUnified library/tests/unittest-cpp/Win32/TimeHelpers.h ¶
r418 r477 6 6 7 7 #ifdef UNITTEST_MINGW 8 9 10 8 #ifndef __int64 9 #define __int64 long long 10 #endif 11 11 #endif 12 12 13 13 namespace UnitTest { 14 14 15 class Timer 16 { 15 class Timer { 17 16 public: 18 17 Timer(); 19 18 void Start(); 20 double GetTimeInMs() const; 19 double GetTimeInMs() const; 21 20 22 21 private: 23 22 __int64 GetTime() const; 24 23 25 24 void* m_threadHandle; 26 25 27 26 #if defined(_WIN64) 28 27 unsigned __int64 m_processAffinityMask; 29 28 #else 30 29 unsigned long m_processAffinityMask; 31 30 #endif 32 31 … … 36 35 37 36 38 namespace TimeHelpers 39 { 40 void SleepMs (int ms); 37 namespace TimeHelpers { 38 void SleepMs ( int ms ); 41 39 } 42 40 -
TabularUnified library/tests/unittest-cpp/XmlTestReporter.cpp ¶
r418 r477 12 12 namespace { 13 13 14 void ReplaceChar(string& str, char c, string const& replacement) 15 { 16 for (size_t pos = str.find(c); pos != string::npos; pos = str.find(c, pos + 1)) 17 str.replace(pos, 1, replacement); 14 void ReplaceChar ( string& str, char c, string const& replacement ) { 15 for ( size_t pos = str.find ( c ); pos != string::npos; pos = str.find ( c, pos + 1 ) ) 16 str.replace ( pos, 1, replacement ); 18 17 } 19 18 20 string XmlEscape(string const& value) 21 { 22 string escaped = value; 19 string XmlEscape ( string const& value ) { 20 string escaped = value; 23 21 24 ReplaceChar(escaped, '&', "&");25 ReplaceChar(escaped, '<', "<");26 ReplaceChar(escaped, '>', ">");27 ReplaceChar(escaped, '\'', "'");28 ReplaceChar(escaped, '\"', """);29 30 22 ReplaceChar ( escaped, '&', "&" ); 23 ReplaceChar ( escaped, '<', "<" ); 24 ReplaceChar ( escaped, '>', ">" ); 25 ReplaceChar ( escaped, '\'', "'" ); 26 ReplaceChar ( escaped, '\"', """ ); 27 28 return escaped; 31 29 } 32 30 33 string BuildFailureMessage(string const& file, int line, string const& message) 34 { 35 ostringstream failureMessage; 36 failureMessage << file << "(" << line << ") : " << message; 37 return failureMessage.str(); 31 string BuildFailureMessage ( string const& file, int line, string const& message ) { 32 ostringstream failureMessage; 33 failureMessage << file << "(" << line << ") : " << message; 34 return failureMessage.str(); 38 35 } 39 36 … … 42 39 namespace UnitTest { 43 40 44 XmlTestReporter::XmlTestReporter(ostream& ostream) 45 : m_ostream(ostream) 46 { 41 XmlTestReporter::XmlTestReporter ( ostream& ostream ) 42 : m_ostream ( ostream ) { 47 43 } 48 44 49 void XmlTestReporter::ReportSummary(int totalTestCount, int failedTestCount, 50 int failureCount, float secondsElapsed) 51 { 52 AddXmlElement(m_ostream, NULL); 45 void XmlTestReporter::ReportSummary ( int totalTestCount, int failedTestCount, 46 int failureCount, float secondsElapsed ) { 47 AddXmlElement ( m_ostream, NULL ); 53 48 54 BeginResults(m_ostream, totalTestCount, failedTestCount, failureCount, secondsElapsed);49 BeginResults ( m_ostream, totalTestCount, failedTestCount, failureCount, secondsElapsed ); 55 50 56 DeferredTestResultList const& results = GetResults(); 57 for (DeferredTestResultList::const_iterator i = results.begin(); i != results.end(); ++i) 58 { 59 BeginTest(m_ostream, *i); 51 DeferredTestResultList const& results = GetResults(); 52 for ( DeferredTestResultList::const_iterator i = results.begin(); i != results.end(); ++i ) { 53 BeginTest ( m_ostream, *i ); 60 54 61 if (i->failed)62 AddFailure(m_ostream, *i);55 if ( i->failed ) 56 AddFailure ( m_ostream, *i ); 63 57 64 EndTest(m_ostream, *i);65 58 EndTest ( m_ostream, *i ); 59 } 66 60 67 EndResults(m_ostream);61 EndResults ( m_ostream ); 68 62 } 69 63 70 void XmlTestReporter::AddXmlElement(ostream& os, char const* encoding) 71 { 72 os << "<?xml version=\"1.0\""; 64 void XmlTestReporter::AddXmlElement ( ostream& os, char const* encoding ) { 65 os << "<?xml version=\"1.0\""; 73 66 74 if (encoding != NULL)75 67 if ( encoding != NULL ) 68 os << " encoding=\"" << encoding << "\""; 76 69 77 70 os << "?>"; 78 71 } 79 72 80 void XmlTestReporter::BeginResults(std::ostream& os, int totalTestCount, int failedTestCount, 81 int failureCount, float secondsElapsed) 82 { 83 os << "<unittest-results" 84 << " tests=\"" << totalTestCount << "\"" 85 << " failedtests=\"" << failedTestCount << "\"" 86 << " failures=\"" << failureCount << "\"" 87 << " time=\"" << secondsElapsed << "\"" 88 << ">"; 73 void XmlTestReporter::BeginResults ( std::ostream& os, int totalTestCount, int failedTestCount, 74 int failureCount, float secondsElapsed ) { 75 os << "<unittest-results" 76 << " tests=\"" << totalTestCount << "\"" 77 << " failedtests=\"" << failedTestCount << "\"" 78 << " failures=\"" << failureCount << "\"" 79 << " time=\"" << secondsElapsed << "\"" 80 << ">"; 89 81 } 90 82 91 void XmlTestReporter::EndResults(std::ostream& os) 92 { 93 os << "</unittest-results>"; 83 void XmlTestReporter::EndResults ( std::ostream& os ) { 84 os << "</unittest-results>"; 94 85 } 95 86 96 void XmlTestReporter::BeginTest(std::ostream& os, DeferredTestResult const& result) 97 { 98 os << "<test" 99 << " suite=\"" << result.suiteName << "\"" 100 << " name=\"" << result.testName << "\"" 101 << " time=\"" << result.timeElapsed << "\""; 87 void XmlTestReporter::BeginTest ( std::ostream& os, DeferredTestResult const& result ) { 88 os << "<test" 89 << " suite=\"" << result.suiteName << "\"" 90 << " name=\"" << result.testName << "\"" 91 << " time=\"" << result.timeElapsed << "\""; 102 92 } 103 93 104 void XmlTestReporter::EndTest(std::ostream& os, DeferredTestResult const& result) 105 { 106 if (result.failed) 107 os << "</test>"; 108 else 109 os << "/>"; 94 void XmlTestReporter::EndTest ( std::ostream& os, DeferredTestResult const& result ) { 95 if ( result.failed ) 96 os << "</test>"; 97 else 98 os << "/>"; 110 99 } 111 100 112 void XmlTestReporter::AddFailure(std::ostream& os, DeferredTestResult const& result) 113 { 114 os << ">"; // close <test> element 101 void XmlTestReporter::AddFailure ( std::ostream& os, DeferredTestResult const& result ) { 102 os << ">"; // close <test> element 115 103 116 for (DeferredTestResult::FailureVec::const_iterator it = result.failures.begin(); 117 it != result.failures.end(); 118 ++it) 119 { 120 string const escapedMessage = XmlEscape(it->second); 121 string const message = BuildFailureMessage(result.failureFile, it->first, escapedMessage); 104 for ( DeferredTestResult::FailureVec::const_iterator it = result.failures.begin(); 105 it != result.failures.end(); 106 ++it ) { 107 string const escapedMessage = XmlEscape ( it->second ); 108 string const message = BuildFailureMessage ( result.failureFile, it->first, escapedMessage ); 122 109 123 124 110 os << "<failure" << " message=\"" << message << "\"" << "/>"; 111 } 125 112 } 126 113 -
TabularUnified library/tests/unittest-cpp/XmlTestReporter.h ¶
r418 r477 6 6 #include <iosfwd> 7 7 8 namespace UnitTest 9 { 8 namespace UnitTest { 10 9 11 class XmlTestReporter : public DeferredTestReporter 12 { 10 class XmlTestReporter : public DeferredTestReporter { 13 11 public: 14 explicit XmlTestReporter(std::ostream& ostream);12 explicit XmlTestReporter ( std::ostream& ostream ); 15 13 16 virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);14 virtual void ReportSummary ( int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed ); 17 15 18 16 private: 19 XmlTestReporter(XmlTestReporter const&);20 XmlTestReporter& operator=(XmlTestReporter const&);17 XmlTestReporter ( XmlTestReporter const& ); 18 XmlTestReporter& operator= ( XmlTestReporter const& ); 21 19 22 void AddXmlElement(std::ostream& os, char const* encoding);23 void BeginResults(std::ostream& os, int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);24 void EndResults(std::ostream& os);25 void BeginTest(std::ostream& os, DeferredTestResult const& result);26 void AddFailure(std::ostream& os, DeferredTestResult const& result);27 void EndTest(std::ostream& os, DeferredTestResult const& result);20 void AddXmlElement ( std::ostream& os, char const* encoding ); 21 void BeginResults ( std::ostream& os, int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed ); 22 void EndResults ( std::ostream& os ); 23 void BeginTest ( std::ostream& os, DeferredTestResult const& result ); 24 void AddFailure ( std::ostream& os, DeferredTestResult const& result ); 25 void EndTest ( std::ostream& os, DeferredTestResult const& result ); 28 26 29 27 std::ostream& m_ostream; 30 28 }; 31 29