testILSConjugateGradients.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * @file testILSConjugateGradients.cpp
  3. * @author Paul Bodesheim
  4. * @date 23/01/2012
  5. * @brief test routine for Iterative Linear Solver: Conjugate Gradients Method (CGM)
  6. */
  7. #include "core/vector/MatrixT.h"
  8. #include "core/vector/VectorT.h"
  9. #include <stdio.h>
  10. #include <ctime>
  11. #include "iostream"
  12. #include "core/basics/Exception.h"
  13. #include "core/vector/Algorithms.h"
  14. #include "core/algebra/ILSConjugateGradients.h"
  15. #include "core/algebra/GMStandard.h"
  16. using namespace std;
  17. using namespace NICE;
  18. int main(int argc, char* argv[])
  19. {
  20. int mySize = 20; // number of equations
  21. FILE * logfile;
  22. std::string logfilename;
  23. if ( argc < 2 )
  24. {
  25. std::cerr << "Warning: you have to specify a log-file with write-access. Program will be closed." << std::endl;
  26. return -1;
  27. }
  28. else
  29. {
  30. logfilename = argv[1];
  31. }
  32. logfile = fopen(logfilename.c_str(), "w");
  33. //is the given logfile writable
  34. if (logfile == NULL)
  35. {
  36. std::cerr << "Error opening file" << std::endl;
  37. return -1;
  38. }
  39. // generate matrix A
  40. Matrix A(mySize,mySize,0.0);
  41. fprintf(logfile, "A:\n");
  42. for (uint i = 0; i < A.rows(); i++)
  43. {
  44. for (uint j = 0; j < A.cols(); j++)
  45. {
  46. if ( j == i ) A(i,j) = (i+1)+(j+1);
  47. else {
  48. A(i,j) = sqrt( (double) ( (i+1)*(j+1) ) );
  49. }
  50. fprintf(logfile, "%f ",A(i,j));
  51. }
  52. fprintf(logfile, "\n");
  53. }
  54. // generate vector b (RHS of LS)
  55. Vector b(mySize,0.0);
  56. fprintf(logfile, "b:\n");
  57. for (uint i = 0; i < b.size(); i++)
  58. {
  59. b(i) = (i+1)*sqrt( (double)(i+1) );
  60. fprintf(logfile, "%f ",b(i));
  61. }
  62. fprintf(logfile, "\n");
  63. // solve Ax = b
  64. Vector x(mySize,0.0);
  65. ILSConjugateGradients cgm(true,mySize);
  66. //tic
  67. time_t start = clock();
  68. cgm.solveLin(GMStandard(A),b,x);
  69. //toc
  70. float duration = (float) (clock() - start);
  71. std::cerr << "Time for solveLin: " << duration/CLOCKS_PER_SEC << std::endl;
  72. fprintf(logfile, "x:\n");
  73. for (uint i = 0; i < x.size(); i++)
  74. {
  75. fprintf(logfile, "%f ",x(i));
  76. }
  77. fprintf(logfile, "\n");
  78. // check result
  79. Vector Ax(mySize,0.0);
  80. Ax = A*x;
  81. fprintf(logfile, "A*x:\n");
  82. for (uint i = 0; i < Ax.size(); i++)
  83. {
  84. fprintf(logfile, "%f ",Ax(i));
  85. }
  86. fprintf(logfile, "\n");
  87. fclose(logfile);
  88. return 0;
  89. }