浏览代码

Merge branch 'master' of /home/dbv/git/nice/vislearning

Conflicts:
	baselib/ProgressBarQt.cpp
	baselib/ProgressBarQt.h
Erik Rodner 13 年之前
父节点
当前提交
f4f4c3423f
共有 82 个文件被更改,包括 6476 次插入6323 次删除
  1. 202 174
      baselib/ICETools.cpp
  2. 75 75
      baselib/ICETools.h
  3. 9 10
      baselib/ProgressBar.cpp
  4. 7 7
      baselib/ProgressBar.h
  5. 52 52
      baselib/ProgressBarQt.cpp
  6. 40 40
      baselib/ProgressBarQt.h
  7. 26 26
      baselib/RunningStat.h
  8. 29 34
      cbaselib/BoundingBox.h
  9. 225 225
      cbaselib/CachedExample.cpp
  10. 274 249
      cbaselib/CachedExample.h
  11. 24 24
      cbaselib/ClassificationResult.cpp
  12. 60 63
      cbaselib/ClassificationResult.h
  13. 107 107
      cbaselib/Example.h
  14. 73 62
      cbaselib/ImageInfo.h
  15. 317 317
      cbaselib/LabeledSet.cpp
  16. 107 95
      cbaselib/LabeledSet.h
  17. 175 166
      cbaselib/LabeledSetSelection.h
  18. 20 20
      cbaselib/Polygon.h
  19. 28 27
      cbaselib/progs/statisticsLabeledSetVector.cpp
  20. 58 52
      classifier/classifierbase/KernelClassifier.h
  21. 31 24
      classifier/classifierbase/VecClassifier.h
  22. 94 91
      classifier/fpclassifier/boosting/FPCBoosting.h
  23. 127 127
      classifier/fpclassifier/logisticregression/FPCSMLR.cpp
  24. 68 67
      classifier/fpclassifier/logisticregression/FPCSMLR.h
  25. 431 431
      classifier/fpclassifier/logisticregression/SLR.cpp
  26. 93 93
      classifier/fpclassifier/logisticregression/SLR.h
  27. 42 26
      classifier/fpclassifier/randomforest/FPCDecisionTree.h
  28. 118 108
      classifier/fpclassifier/randomforest/FPCRandomForests.h
  29. 10 10
      classifier/genericClassifierSelection.h
  30. 71 67
      classifier/kernelclassifier/GPLaplaceOptimizationProblem.h
  31. 57 46
      classifier/kernelclassifier/KCGPLaplace.h
  32. 43 33
      classifier/kernelclassifier/KCGPLaplaceOneVsAll.h
  33. 47 37
      classifier/kernelclassifier/KCGPOneClass.h
  34. 66 65
      classifier/kernelclassifier/KCGPRegOneVsAll.h
  35. 44 34
      classifier/kernelclassifier/KCGPRegression.h
  36. 46 36
      classifier/kernelclassifier/KCMinimumEnclosingBall.h
  37. 39 29
      classifier/kernelclassifier/KCOneVsAll.h
  38. 27 26
      classifier/kernelclassifier/LHCumulativeGauss.h
  39. 66 47
      classifier/kernelclassifier/LaplaceApproximation.h
  40. 39 44
      classifier/vclassifier/VCAmitSVM.h
  41. 28 27
      classifier/vclassifier/VCCrossGeneralization.h
  42. 1 1
      classifier/vclassifier/VCDTSVM.cpp
  43. 35 31
      classifier/vclassifier/VCOneVsOne.h
  44. 1 1
      features/fpfeatures/SparseVectorFeature.h
  45. 1 1
      features/localfeatures/GenericLFSelection.h
  46. 35 35
      features/localfeatures/GenericLocalFeatureSelection.h
  47. 163 163
      features/localfeatures/LFColorWeijer.h
  48. 40 40
      features/localfeatures/LFReadCache.cpp
  49. 80 70
      features/localfeatures/LFReadCache.tcc
  50. 2 1
      features/localfeatures/LFSiftPP.h
  51. 73 73
      features/localfeatures/LFWriteCache.cpp
  52. 78 85
      features/localfeatures/LFonHSG.cpp
  53. 49 47
      features/localfeatures/LFonHSG.h
  54. 25 25
      features/localfeatures/LocalFeatureOpponnentSift.cpp
  55. 23 23
      features/localfeatures/LocalFeatureOpponnentSift.h
  56. 62 66
      features/localfeatures/LocalFeatureRGBSift.cpp
  57. 37 36
      features/localfeatures/LocalFeatureRGBSift.h
  58. 2 1
      features/localfeatures/LocalFeatureRepresentation.h
  59. 260 181
      features/localfeatures/LocalFeatureSift.cpp
  60. 103 59
      features/localfeatures/LocalFeatureSift.h
  61. 6 3
      features/localfeatures/libdepend.inc
  62. 55 39
      features/simplefeatures/Codebook.h
  63. 669 669
      math/cluster/GMM.cpp
  64. 210 206
      math/cluster/GMM.h
  65. 32 33
      math/cluster/KMeansOnline.h
  66. 48 48
      math/distances/genericDistance.h
  67. 140 129
      math/ftransform/PCA.cpp
  68. 56 58
      math/ftransform/PCA.h
  69. 0 88
      math/ftransform/progs/Makefile.inc
  70. 59 75
      math/ftransform/tests/TestFTransform.cpp
  71. 15 14
      math/ftransform/tests/TestFTransform.h
  72. 30 0
      math/ftransform/tests/pca.data
  73. 26 21
      math/kernels/genericKernel.h
  74. 53 53
      math/mathbase/Featuretype.cpp
  75. 73 73
      math/mathbase/Featuretype.h
  76. 257 257
      math/mathbase/FullVector.cpp
  77. 47 43
      math/mathbase/FullVector.h
  78. 0 88
      math/mathbase/progs/Makefile.inc
  79. 0 88
      math/mathbase/progs/testSparseVector.cpp
  80. 44 28
      regression/gpregression/modelselcrit/genericGPModelSelection.h
  81. 42 31
      regression/regressionbase/RegressionAlgorithm.h
  82. 49 47
      regression/regressionbase/RegressionAlgorithmKernel.h

+ 202 - 174
baselib/ICETools.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ICETools.cpp
 * @brief simple ICE GUI tools
 * @author Erik Rodner
@@ -35,24 +35,24 @@ ICETools::~ICETools()
 
 void ICETools::selectRectangles ( const NICE::Image & panel, NICE::Image & overlay, vector<Vector> & x, int color )
 {
-	fthrow(Exception, "ICETools::selectRectangles -- not yet implemented due to old ICE version.");
+  fthrow ( Exception, "ICETools::selectRectangles -- not yet implemented due to old ICE version." );
 // #ifndef NOVISUAL
 //     // new NICE code
 //     vector<RectT<double> > rectangles;
-// 	 //TODO check this!
+//   //TODO check this!
 // //     NICE::selectRectangles ( panel, rectangles, "select rectangles" );
-// // 	 selectRectangles ( panel, rectangles, "select rectangles" );
-// 
+// //   selectRectangles ( panel, rectangles, "select rectangles" );
+//
 //     for ( vector<RectT<double> >::const_iterator i = rectangles.begin();
-// 	i != rectangles.end(); i++ )
+//  i != rectangles.end(); i++ )
 //     {
-// 	Vector vec (4);
-// 	vec[0] = i->left;
-// 	vec[1] = i->top;
-// 	vec[2] = i->right();
-// 	vec[3] = i->bottom();
-// 
-// 	x.push_back ( vec ); 
+//  Vector vec (4);
+//  vec[0] = i->left;
+//  vec[1] = i->top;
+//  vec[2] = i->right();
+//  vec[3] = i->bottom();
+//
+//  x.push_back ( vec );
 //     }
 // #else
 //     fprintf (stderr, "ICETools::selectRectangles: visualization disabled !\n");
@@ -61,27 +61,27 @@ void ICETools::selectRectangles ( const NICE::Image & panel, NICE::Image & overl
 
 void ICETools::selectPoints ( const NICE::Image & panel, NICE::Image & overlay, vector<Vector> & x, int color )
 {
-	fthrow(Exception, "ICETools::selectPoints -- not yet implemented due to old ICE version.");
+  fthrow ( Exception, "ICETools::selectPoints -- not yet implemented due to old ICE version." );
 // #ifndef NOVISUAL
 //     vector<CoordT<double> > points;
-// 	 //TODO check this!
+//   //TODO check this!
 // //     NICE::selectPoints ( panel, points, "select points" );
-// // 	selectPoints ( panel, points, "select points" );
-// 
+// //  selectPoints ( panel, points, "select points" );
+//
 //     for ( vector<CoordT<double> >::const_iterator i = points.begin();
-// 	i != points.end(); i++ )
+//  i != points.end(); i++ )
 //     {
-// 	Vector vec (2);
-// 	vec[0] = i->x;
-// 	vec[1] = i->y;
-// 
-// 	x.push_back ( vec ); 
+//  Vector vec (2);
+//  vec[0] = i->x;
+//  vec[1] = i->y;
+//
+//  x.push_back ( vec );
 //     }
-//    
+//
 //     /** OLD ICE Code
 //     int p[2];
 //     int rc = -1;
-// 
+//
 //     while ( (rc = SelPoint ( DEFAULT, panel, p )) != -1 )
 //     {
 //         int x1, y1;
@@ -102,144 +102,172 @@ void ICETools::selectPoints ( const NICE::Image & panel, NICE::Image & overlay,
 
 void ICETools::toColor ( double x, double & r, double & g, double & b )
 {
-    size_t seg = (size_t)(x * 6.0);
-    double y   = ( 6*x - seg );
-
-    switch ( seg ) {
-	case 0: r=0.0; g=0.0; b=y;   break; 
-	case 1: r=0.0; g=  y; b=1.0; break; 
-	case 2: r=0.0; g=1.0; b=1.0-y; break; 
-	case 3: r=  y; g=1.0; b=0.0;   break; 
-	case 4: r=1.0; g=1.0-y; b=0.0;   break; 
-	case 5: r=1.0; g=y; b=y;   break; 
-	default: r=1.0; g=1.0; b=1.0; break;
-    }
+  size_t seg = ( size_t ) ( x * 6.0 );
+  double y   = ( 6 * x - seg );
+
+  switch ( seg ) {
+    case 0:
+      r = 0.0;
+      g = 0.0;
+      b = y;
+      break;
+    case 1:
+      r = 0.0;
+      g =  y;
+      b = 1.0;
+      break;
+    case 2:
+      r = 0.0;
+      g = 1.0;
+      b = 1.0 - y;
+      break;
+    case 3:
+      r =  y;
+      g = 1.0;
+      b = 0.0;
+      break;
+    case 4:
+      r = 1.0;
+      g = 1.0 - y;
+      b = 0.0;
+      break;
+    case 5:
+      r = 1.0;
+      g = y;
+      b = y;
+      break;
+    default:
+      r = 1.0;
+      g = 1.0;
+      b = 1.0;
+      break;
+  }
 }
 
 void ICETools::convertToRGB ( const NICE::Matrix & m, NICE::ColorImage & img )
 {
-	img.resize ( m.cols(), m.rows() );
-    double max = - numeric_limits<double>::max();
-    double min = numeric_limits<double>::max();
-    for ( size_t x = 0 ; x < (size_t)m.cols(); x++ )
-	for ( size_t y = 0 ; y < (size_t)m.rows() ; y++ )
-	{
-	    if (m(y, x) > max ) max =m(y, x);
-	    if (m(y, x) < min ) min =m(y, x);
-	}
-    
-    for ( size_t y = 0 ; y < (size_t)m.rows() ; y++ )
-	for ( size_t x = 0 ; x < (size_t)m.cols(); x++ )
-	{
-	    double val =(m(y, x) - min) / (max-min);
-	    double r,g,b;
-	    toColor(val, r, g, b);
-	    img.setPixel(x,y,0,(int)(r*255));
-	    img.setPixel(x,y,1,(int)(g*255));
-	    img.setPixel(x,y,2,(int)(b*255));
-	}
+  img.resize ( m.cols(), m.rows() );
+  double max = - numeric_limits<double>::max();
+  double min = numeric_limits<double>::max();
+  for ( size_t x = 0 ; x < ( size_t ) m.cols(); x++ )
+    for ( size_t y = 0 ; y < ( size_t ) m.rows() ; y++ )
+    {
+      if ( m ( y, x ) > max ) max = m ( y, x );
+      if ( m ( y, x ) < min ) min = m ( y, x );
+    }
+cout << "max: " << max << " min: " << min << endl;
+  for ( size_t y = 0 ; y < ( size_t ) m.rows() ; y++ )
+    for ( size_t x = 0 ; x < ( size_t ) m.cols(); x++ )
+    {
+      double val = ( m ( y, x ) - min ) / ( max - min );
+      double r, g, b;
+      toColor ( val, r, g, b );
+      img.setPixel ( x, y, 0, ( int ) ( r*255 ) );
+      img.setPixel ( x, y, 1, ( int ) ( g*255 ) );
+      img.setPixel ( x, y, 2, ( int ) ( b*255 ) );
+    }
 }
 
 void ICETools::convertToRGB ( const NICE::FloatImage & m, NICE::ColorImage & img )
 {
-	img.resize ( m.width(), m.height() );
-    double max = - numeric_limits<double>::max();
-    double min = numeric_limits<double>::max();
-    for ( size_t x = 0 ; x < (size_t)m.width(); x++ )
-	for ( size_t y = 0 ; y < (size_t)m.height() ; y++ )
-	{
-	    double v = m.getPixel(x,y);
-	    if ( v > max ) max = v;
-	    if ( v < min ) min = v;
-	}
-    
-    for ( size_t y = 0 ; y < (size_t)m.height() ; y++ )
-	for ( size_t x = 0 ; x < (size_t)m.width(); x++ )
-	{
-	    double val = (m.getPixel(x,y) - min) / (max-min);
-	    double r,g,b;
-	    toColor(val, r, g, b);
-	    img.setPixel(x,y,0,(int)(r*255));
-	    img.setPixel(x,y,1,(int)(g*255));
-	    img.setPixel(x,y,2,(int)(b*255));
-	}
+  img.resize ( m.width(), m.height() );
+  double max = - numeric_limits<double>::max();
+  double min = numeric_limits<double>::max();
+  for ( size_t x = 0 ; x < ( size_t ) m.width(); x++ )
+    for ( size_t y = 0 ; y < ( size_t ) m.height() ; y++ )
+    {
+      double v = m.getPixel ( x, y );
+      if ( v > max ) max = v;
+      if ( v < min ) min = v;
+    }
+
+  for ( size_t y = 0 ; y < ( size_t ) m.height() ; y++ )
+    for ( size_t x = 0 ; x < ( size_t ) m.width(); x++ )
+    {
+      double val = ( m.getPixel ( x, y ) - min ) / ( max - min );
+      double r, g, b;
+      toColor ( val, r, g, b );
+      img.setPixel ( x, y, 0, ( int ) ( r*255 ) );
+      img.setPixel ( x, y, 1, ( int ) ( g*255 ) );
+      img.setPixel ( x, y, 2, ( int ) ( b*255 ) );
+    }
 }
 
 void ICETools::calcGrayImage ( const NICE::ColorImage & img, NICE::Image & imgg )
 {
-    imgg.resize(img.width(), img.height());
-    for ( int y = 0 ; y < img.height(); y++ )
-      for ( int x = 0 ; x < img.width() ; x++ )
-      {
-        unsigned char g = (unsigned char)(0.299*img.getPixel(x,y,0) + 
-          0.587*img.getPixel(x,y,1) + 0.114*img.getPixel(x,y,2));
-        imgg.setPixel(x,y,g);
-      }
+  imgg.resize ( img.width(), img.height() );
+  for ( int y = 0 ; y < img.height(); y++ )
+    for ( int x = 0 ; x < img.width() ; x++ )
+    {
+      unsigned char g = ( unsigned char ) ( 0.299 * img.getPixel ( x, y, 0 ) +
+                                            0.587 * img.getPixel ( x, y, 1 ) + 0.114 * img.getPixel ( x, y, 2 ) );
+      imgg.setPixel ( x, y, g );
+    }
 }
 
 double *ICETools::convertICE2M ( const NICE::Matrix & M )
 {
-    double *raw = new double [ M.rows() * M.cols() ];
-    long index = 0;
-    for ( uint i = 0 ; i < M.rows() ; i++ )
-      for ( uint j = 0 ; j < M.cols() ; j++, index++ )
-        raw[index] = M(i, j);
+  double *raw = new double [ M.rows() * M.cols() ];
+  long index = 0;
+  for ( uint i = 0 ; i < M.rows() ; i++ )
+    for ( uint j = 0 ; j < M.cols() ; j++, index++ )
+      raw[index] = M ( i, j );
 
-    return raw;
+  return raw;
 }
 
 void ICETools::convertM2ICE ( NICE::Matrix & M, double *raw )
 {
-    long index = 0;
-    for ( int i = 0 ; i < (int)M.rows() ; i++ )
-		for ( int j = 0 ; j < (int)M.cols() ; j++, index++ )
-	    	M(i, j) = raw[index];
+  long index = 0;
+  for ( int i = 0 ; i < ( int ) M.rows() ; i++ )
+    for ( int j = 0 ; j < ( int ) M.cols() ; j++, index++ )
+      M ( i, j ) = raw[index];
 }
 
 #ifndef NOVISUAL
-int ICETools::markImage (const NICE::Image & img, NICE::Image & mark, int marksize, int color)
+int ICETools::markImage ( const NICE::Image & img, NICE::Image & mark, int marksize, int color )
 {
-    fprintf (stderr, "ICETools::markImage: reimplement this function for NICE\n");
-    exit(-1);
-
-/*
-    int flags;
-    int p[2];
-    int xo = -1;
-    int yo = -1;
-    
-    while(1) {
-	// refactor-nice.pl: check this substitution
-	// old: flags = Mouse(img,p[0],p[1]);
-	// REFACTOR-FIXME Unable to map this statement
-	if ( (flags & M_LEFT_DOWN) > 0 ) {
-	    if ( (p[0] != xo) || (p[1] != yo) ) {
-		if ( marksize == 1 ) {
-		    // refactor-nice.pl: check this substitution
-		    // old: PutVal( mark, p[0], p[1], color );
-		    mark.setPixel(p[0],p[1],color);
-		} else {
-		    // refactor-nice.pl: check this substitution
-		    // old: Marker(3, p[0], p[1], color, marksize, mark);
-		    // REFACTOR-FIXME Unable to map this statement
-		}
-       
-		xo = p[0];
-		yo = p[1];
-	    }
-	}
-	if ( (flags & M_RIGHT_DOWN) > 0 ) {
-	    while ( (flags & M_RIGHT_DOWN) > 0 ) {
-		// refactor-nice.pl: check this substitution
-		// old: flags = Mouse(img,p[0],p[1]);
-		// REFACTOR-FIXME Unable to map this statement
-	    };
-	    return -1;
-	}
+  fprintf ( stderr, "ICETools::markImage: reimplement this function for NICE\n" );
+  exit ( -1 );
+
+  /*
+      int flags;
+      int p[2];
+      int xo = -1;
+      int yo = -1;
+
+      while(1) {
+   // refactor-nice.pl: check this substitution
+   // old: flags = Mouse(img,p[0],p[1]);
+   // REFACTOR-FIXME Unable to map this statement
+   if ( (flags & M_LEFT_DOWN) > 0 ) {
+       if ( (p[0] != xo) || (p[1] != yo) ) {
+    if ( marksize == 1 ) {
+        // refactor-nice.pl: check this substitution
+        // old: PutVal( mark, p[0], p[1], color );
+        mark.setPixel(p[0],p[1],color);
+    } else {
+        // refactor-nice.pl: check this substitution
+        // old: Marker(3, p[0], p[1], color, marksize, mark);
+        // REFACTOR-FIXME Unable to map this statement
     }
-*/
 
-    return 0;
+    xo = p[0];
+    yo = p[1];
+       }
+   }
+   if ( (flags & M_RIGHT_DOWN) > 0 ) {
+       while ( (flags & M_RIGHT_DOWN) > 0 ) {
+    // refactor-nice.pl: check this substitution
+    // old: flags = Mouse(img,p[0],p[1]);
+    // REFACTOR-FIXME Unable to map this statement
+       };
+       return -1;
+   }
+      }
+  */
+
+  return 0;
 }
 
 // refactor-nice.pl: check this substitution
@@ -247,46 +275,46 @@ int ICETools::markImage (const NICE::Image & img, NICE::Image & mark, int marksi
 int ICETools::showImages ( vector<NICE::Image> & imagelist )
 {
 #ifndef NOVISUAL
-    for ( size_t j = 0 ; j < imagelist.size() ; j++ )
-    {
-	// refactor-nice.pl: check this substitution
-	// old: Show(ON, imagelist[j]);
-	showImage(imagelist[j]);
-    }
+  for ( size_t j = 0 ; j < imagelist.size() ; j++ )
+  {
+    // refactor-nice.pl: check this substitution
+    // old: Show(ON, imagelist[j]);
+    showImage ( imagelist[j] );
+  }
 #endif
 
-    // assumption: same size
-    // refactor-nice.pl: check this substitution
-    // old: int xsize = imagelist[0]->xsize;
-    int xsize = imagelist[0].width();
-    // refactor-nice.pl: check this substitution
-    // old: int ysize = imagelist[0]->ysize;
-    int ysize = imagelist[0].height();
-
-    int n = imagelist.size();
-    int n1 = (int)sqrt(n);
-    int n2 = n/n1 + 1;
-
-    NICE::Image img (n1*xsize, n2*ysize);
-    img.set(0);
-    int k = 0;
-    for ( int j = 0 ; j < n2 ; j++ )
-	for ( int i = 0 ; i < n1 ; i++,k++ )
-	    if ( k >= n ) break;
-	    else {
-		for ( int y = 0 ; y < imagelist[k].height(); y++ )
-		    for ( int x = 0 ; x < imagelist[k].width(); x++ )
-		    {
-          img.setPixel( i*xsize + x, j*ysize + y,
-              imagelist[k].getPixel(x,y) );
-		    }
-	    }
-
-    img.write ("display.bmp");
-
-    getchar();
-
-    return 0;
+  // assumption: same size
+  // refactor-nice.pl: check this substitution
+  // old: int xsize = imagelist[0]->xsize;
+  int xsize = imagelist[0].width();
+  // refactor-nice.pl: check this substitution
+  // old: int ysize = imagelist[0]->ysize;
+  int ysize = imagelist[0].height();
+
+  int n = imagelist.size();
+  int n1 = ( int ) sqrt ( n );
+  int n2 = n / n1 + 1;
+
+  NICE::Image img ( n1*xsize, n2*ysize );
+  img.set ( 0 );
+  int k = 0;
+  for ( int j = 0 ; j < n2 ; j++ )
+    for ( int i = 0 ; i < n1 ; i++, k++ )
+      if ( k >= n ) break;
+      else {
+        for ( int y = 0 ; y < imagelist[k].height(); y++ )
+          for ( int x = 0 ; x < imagelist[k].width(); x++ )
+          {
+            img.setPixel ( i*xsize + x, j*ysize + y,
+                           imagelist[k].getPixel ( x, y ) );
+          }
+      }
+
+  img.write ( "display.bmp" );
+
+  getchar();
+
+  return 0;
 }
 
 #endif

+ 75 - 75
baselib/ICETools.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ICETools.h
 * @brief simple ICE GUI tools
 * @author Erik Rodner
@@ -13,7 +13,7 @@
 #include "core/vector/MatrixT.h"
 
 #include <vector>
- 
+
 
 namespace OBJREC {
 
@@ -21,82 +21,82 @@ namespace OBJREC {
 class ICETools
 {
 
-    protected:
-
-    public:
-  
-	/** simple constructor */
-	ICETools();
-      
-	/** simple destructor */
-	virtual ~ICETools();
-
-	/** select a set of rectangles (selection of top-left and bottom-right
-	    @param panel image which is displayed
-	    @param overlay overlay image which will be used to mark points
-	    @param x returned list of rectangles (top-left-x,top-left-y,width,height)
-	    @param color color which is used to mark points
-	*/
-	static void selectRectangles ( const NICE::Image & panel, NICE::Image & overlay, 
-	    std::vector<NICE::Vector> & x, int color );
-
-	/** select a set of points 
-	    @param panel image which is displayed
-	    @param overlay overlay image which will be used to mark points
-	    @param x returned list of image points
-	    @param color color which is used to mark points
-	*/
-	static void selectPoints ( const NICE::Image & panel, NICE::Image & overlay, 
-	    std::vector<NICE::Vector> & x, int color );
-
-	/** convert a double image to a pseudocolor rgb image
-	    @param m input double image
-	    @param img resulting pseudocolor rgb image
-	*/
-	static void convertToRGB ( const NICE::FloatImage & m, NICE::ColorImage & img );
-
-	/** convert a matrix to a pseudocolor rgb image
-	    @param m input double image
-	    @param img resulting pseudocolor rgb image
-	*/
-	static void convertToRGB ( const NICE::Matrix & m, NICE::ColorImage & img );
-
-	/** convert a single double value to a pseudocolor
-	    @param x input double value
-	    @param r resulting red value
-	    @param g resulting green value
-	    @param b resulting blue value
-	*/
-	static void toColor ( double x, double & r, double & g, double & b );
-
-	/** calc grayscale image from a rgb image
-	    @param img color image
-	    @param imgg resulting grayscale image
-	*/
-	static void calcGrayImage ( const NICE::ColorImage & img, NICE::Image & imgg );
-
-	/** convert a c buffer to a matrix
-	    @param M resulting matrix
-	    @param raw input c buffer
-	*/
-	static void convertM2ICE ( NICE::Matrix & M, double *raw );
-
-	/** convert a matrix to a c buffer
-	    @param M input matrix
-	    @return resulting c buffer
-	*/
-	static double *convertICE2M ( const NICE::Matrix & M );
-
-	/** show a collection of images 
-	    @param imagelist collection of images
-	    @return ...
-	*/
-	static int showImages ( std::vector<NICE::Image> & imagelist );
+  protected:
+
+  public:
+
+    /** simple constructor */
+    ICETools();
+
+    /** simple destructor */
+    virtual ~ICETools();
+
+    /** select a set of rectangles (selection of top-left and bottom-right
+        @param panel image which is displayed
+        @param overlay overlay image which will be used to mark points
+        @param x returned list of rectangles (top-left-x,top-left-y,width,height)
+        @param color color which is used to mark points
+    */
+    static void selectRectangles ( const NICE::Image & panel, NICE::Image & overlay,
+                                   std::vector<NICE::Vector> & x, int color );
+
+    /** select a set of points
+        @param panel image which is displayed
+        @param overlay overlay image which will be used to mark points
+        @param x returned list of image points
+        @param color color which is used to mark points
+    */
+    static void selectPoints ( const NICE::Image & panel, NICE::Image & overlay,
+                               std::vector<NICE::Vector> & x, int color );
+
+    /** convert a double image to a pseudocolor rgb image
+        @param m input double image
+        @param img resulting pseudocolor rgb image
+    */
+    static void convertToRGB ( const NICE::FloatImage & m, NICE::ColorImage & img );
+
+    /** convert a matrix to a pseudocolor rgb image
+        @param m input double image
+        @param img resulting pseudocolor rgb image
+    */
+    static void convertToRGB ( const NICE::Matrix & m, NICE::ColorImage & img );
+
+    /** convert a single double value to a pseudocolor
+        @param x input double value
+        @param r resulting red value
+        @param g resulting green value
+        @param b resulting blue value
+    */
+    static void toColor ( double x, double & r, double & g, double & b );
+
+    /** calc grayscale image from a rgb image
+        @param img color image
+        @param imgg resulting grayscale image
+    */
+    static void calcGrayImage ( const NICE::ColorImage & img, NICE::Image & imgg );
+
+    /** convert a c buffer to a matrix
+        @param M resulting matrix
+        @param raw input c buffer
+    */
+    static void convertM2ICE ( NICE::Matrix & M, double *raw );
+
+    /** convert a matrix to a c buffer
+        @param M input matrix
+        @return resulting c buffer
+    */
+    static double *convertICE2M ( const NICE::Matrix & M );
+
+    /** show a collection of images
+        @param imagelist collection of images
+        @return ...
+    */
+    static int showImages ( std::vector<NICE::Image> & imagelist );
 
 #ifndef NOVISUAL
-	static int markImage (const NICE::Image & img, NICE::Image & mark, int marksize, int maxColor);
+    static int markImage ( const NICE::Image & img, NICE::Image & mark, int marksize, int maxColor );
 #endif
-     
+
 };
 
 

+ 9 - 10
baselib/ProgressBar.cpp

@@ -1,9 +1,8 @@
-/** 
+/**
  * @file ProgressBar.cpp
  * @brief Show a Progress-Bar with time estimation - threaded
  * @author Michael Koch
  * @date 25/03/2010
-
  */
 #include "core/image/ImageT.h"
 #include "core/vector/VectorT.h"
@@ -22,20 +21,20 @@ using namespace std;
 
 using namespace NICE;
 
-ProgressBar::ProgressBar( std::string a ) : ProgressBarQt(a, true)
+ProgressBar::ProgressBar ( std::string a ) : ProgressBarQt ( a, true )
 {
-    start();
+  start();
 }
 ProgressBar::~ProgressBar()
 {
-	terminate();
-	wait();
+  terminate();
+  wait();
 }
 void ProgressBar::run()
 {
- if(working)
- {
-	 sleep(1);
- }
+  if ( working )
+  {
+    sleep ( 1 );
+  }
 }
 

+ 7 - 7
baselib/ProgressBar.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBar.h
  * @brief Show a Progress-Bar with time estimation - threaded
  * @author Michael Koch
@@ -19,12 +19,12 @@ namespace OBJREC
 /** @brief show a Progress-Bar with time estimation */
 class ProgressBar: public QThread, public ProgressBarQt
 {
-public:
-	ProgressBar(std::string a = "ProgressBar");
-	/** simple destructor */
-	virtual ~ProgressBar();
-	virtual void run();
-private:
+  public:
+    ProgressBar ( std::string a = "ProgressBar" );
+    /** simple destructor */
+    virtual ~ProgressBar();
+    virtual void run();
+  private:
 
 };
 

+ 52 - 52
baselib/ProgressBarQt.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBarQt.cpp
  * @brief Show a Progress-Bar with time estimation
  * @author Michael Koch
@@ -24,30 +24,30 @@ using namespace std;
 
 using namespace NICE;
 
-ProgressBarQt::ProgressBarQt(const std::string & _name, bool _useGraphics)
-	: useGraphics (_useGraphics)
+ProgressBarQt::ProgressBarQt ( const std::string & _name, bool _useGraphics )
+    : useGraphics ( _useGraphics )
 {
-	name = _name;
-	step = 0;
-
-	display_on = false;
-	working = true;
-	if (graphicIsAvailable())
-	{
-		if (qApp == NULL)
-		{
-			QtFramework::instance();
-		}
-
-		dialogwindow = new QWidget;
-
-		progressdialog = new QProgressDialog("Process at work ...", "Cancel",
-				0, 100);
-		layout = new QGridLayout(dialogwindow, 1, 1);
-		layout->addWidget(progressdialog, 0, 0);
-		dialogwindow->setLayout(layout);
-	}
-	reset(_name);
+  name = _name;
+  step = 0;
+
+  display_on = false;
+  working = true;
+  if ( graphicIsAvailable() )
+  {
+    if ( qApp == NULL )
+    {
+      QtFramework::instance();
+    }
+
+    dialogwindow = new QWidget;
+
+    progressdialog = new QProgressDialog ( "Process at work ...", "Cancel",
+                                           0, 100 );
+    layout = new QGridLayout ( dialogwindow, 1, 1 );
+    layout->addWidget ( progressdialog, 0, 0 );
+    dialogwindow->setLayout ( layout );
+  }
+  reset ( _name );
 }
 
 ProgressBarQt::~ProgressBarQt()
@@ -81,20 +81,20 @@ void ProgressBarQt::timediff2str(char *text, double dtime)
 
 void ProgressBarQt::displayTimeStat(int posy, char *text, double time)
 {
-	// Text (char *str,int x0,int y0,int val,int exp,Image img);
-	char disptext[200];
-	char timetext[200];
+  // Text (char *str,int x0,int y0,int val,int exp,Image img);
+  char disptext[200];
+  char timetext[200];
 
-	timediff2str(timetext, time);
-	sprintf(disptext, "%s %s", text, timetext);
+  timediff2str ( timetext, time );
+  sprintf ( disptext, "%s %s", text, timetext );
 
 }
 
 double ProgressBarQt::getCurrentTime()
 {
-	struct timeval curtime;
+  struct timeval curtime;
 
-	gettimeofday(&curtime, NULL);
+  gettimeofday ( &curtime, NULL );
 
 	//return curtime.tv_sec * 100.0 + curtime.tv_usec / 10000.0;
 	return curtime.tv_sec + curtime.tv_usec * 1e-6;
@@ -102,18 +102,18 @@ double ProgressBarQt::getCurrentTime()
 
 void ProgressBarQt::show()
 {
-	if (!display_on)
-	{
-		display_on = true;
-	}
-	if (graphicIsAvailable())
-	{
-		if (qApp == NULL)
-		{
-			QtFramework::instance();
-		}
-		dialogwindow->show();
-	}
+  if ( !display_on )
+  {
+    display_on = true;
+  }
+  if ( graphicIsAvailable() )
+  {
+    if ( qApp == NULL )
+    {
+      QtFramework::instance();
+    }
+    dialogwindow->show();
+  }
 }
 
 void ProgressBarQt::hide()
@@ -132,19 +132,19 @@ void ProgressBarQt::hide()
 void ProgressBarQt::stop()
 {
 
-	working = false;
+  working = false;
 }
 
-void ProgressBarQt::reset(const std::string & _name)
+void ProgressBarQt::reset ( const std::string & _name )
 {
-	name = _name;
-	step = 0;
-	elapsed_time = 0;
-	avg_time_step = 0;
-	start_time = getCurrentTime();
+  name = _name;
+  step = 0;
+  elapsed_time = 0;
+  avg_time_step = 0;
+  start_time = getCurrentTime();
 }
 
-void ProgressBarQt::update(int count)
+void ProgressBarQt::update ( int count )
 {
 	step++;
 
@@ -189,5 +189,5 @@ void ProgressBarQt::update(int count)
 
 bool ProgressBarQt::graphicIsAvailable()
 {
-	return (useGraphics && (getenv("DISPLAY") != NULL));
+  return ( useGraphics && ( getenv ( "DISPLAY" ) != NULL ) );
 }

+ 40 - 40
baselib/ProgressBarQt.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file ProgressBarQt.h
  * @brief Show a Progress-Bar with time estimation
  * @author Michael Koch
@@ -20,66 +20,66 @@ namespace OBJREC {
 class ProgressBarQt
 {
 
-protected:
+  protected:
 
-	QGridLayout* layout;
-	QWidget* dialogwindow;
-	QProgressDialog* progressdialog;
+    QGridLayout* layout;
+    QWidget* dialogwindow;
+    QProgressDialog* progressdialog;
 
 
-	NICE::Image display;
-	bool display_on;
-	bool working;
-	double start_time;
-	double avg_time_step;
-	double elapsed_time;
-	double estimated_time;
+    NICE::Image display;
+    bool display_on;
+    bool working;
+    double start_time;
+    double avg_time_step;
+    double elapsed_time;
+    double estimated_time;
 
-	int step;
+    int step;
 
-	int bar_width;
-	int bar_height;
-	int bar_top;
-	int bar_borderx;
+    int bar_width;
+    int bar_height;
+    int bar_top;
+    int bar_borderx;
 
-	int text_top;
-	int text_height;
+    int text_top;
+    int text_height;
 
-	std::string name;
+    std::string name;
 
-	bool useGraphics;
+    bool useGraphics;
 
 	void timediff2str(char *text, double time);
 	void displayTimeStat(int posy, char *text, double time);
 	double getCurrentTime();
 	bool graphicIsAvailable();
 
-public:
+  public:
 
-	/** constructor 
-	 @param name name of the operation
-	 */
-	ProgressBarQt(const std::string & name, bool useGraphics = true);
+    /** constructor
+     @param name name of the operation
+     */
+    ProgressBarQt ( const std::string & name, bool useGraphics = true );
 
-	/** simple destructor */
-	virtual ~ProgressBarQt();
+    /** simple destructor */
+    virtual ~ProgressBarQt();
 
-	/** reset the progress bar and the corresponding
-	 name of the operation */
+    /** reset the progress bar and the corresponding
+     name of the operation */
 
-	void reset(const std::string & name);
+    void reset ( const std::string & name );
 
-	/** show the progress bar */
-	void show();
-	/** hide the progress bar */
-	void hide();
+    /** show the progress bar */
+    void show();
+    /** hide the progress bar */
+    void hide();
 
-	void stop();
+    void stop();
 
-	/** update the progress bar
-	 @param count number of total steps of this operation
-	 */
-	void update(int count);
+    /** update the progress bar
+     @param count number of total steps of this operation
+     */
+    void update ( int count );
 
 };
 } // namespace

+ 26 - 26
baselib/RunningStat.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file RunningStat.h
  * @brief B. P. Welford Computation of Mean and Variance download at: http://www.johndcook.com/standard_deviation.html
  * @author Michael Koch
@@ -12,31 +12,31 @@ namespace OBJREC {
 /** @brief online statistics */
 class RunningStat
 {
-     public:
-          RunningStat() : m_n(0) {}
-
-	  /** clear the current statistics */
-          void Clear();
-          
-	  /** add a new data element */
-          void Push(double x);
-          
-	  /** get number of data elements */
-          size_t NumDataValues() const;
-
-	  /** get mean value */
-          double Mean() const;
-          
-	  /** get variance */
-	  double Variance() const;
-          
-	  /** get standard deviation */
-          double StandardDeviation() const;
-         
-
-     private:
-          size_t m_n;
-          double m_oldM, m_newM, m_oldS, m_newS;
+  public:
+    RunningStat() : m_n ( 0 ) {}
+
+    /** clear the current statistics */
+    void Clear();
+
+    /** add a new data element */
+    void Push ( double x );
+
+    /** get number of data elements */
+    size_t NumDataValues() const;
+
+    /** get mean value */
+    double Mean() const;
+
+    /** get variance */
+    double Variance() const;
+
+    /** get standard deviation */
+    double StandardDeviation() const;
+
+
+  private:
+    size_t m_n;
+    double m_oldM, m_newM, m_oldS, m_newS;
 };
 
 }

+ 29 - 34
cbaselib/BoundingBox.h

@@ -10,46 +10,41 @@
 
 #include "core/image/CoordT.h"
 
-using namespace NICE;
-
-namespace OBJREC {
+namespace OBJREC
+{
 
 //! \brief Contains category ID, top left and bottom right points of the bounding
-//!  box rectangle. 
+//!  box rectangle.
 class BoundingBox
 {
-public:
-	BoundingBox();
-	BoundingBox(const BoundingBox &copy);
-	~BoundingBox();
-	
-	void setTopLeft(const CoordT< int > &aTopLeft);
-	void setTopLeft(const int &x, const int &y);
-	void setBottomRight(const CoordT< int > &aBottomRight);
-	void setBottomRight(const int &x, const int &y);
-	void setWidth(const int &aWidth);
-	void setHeight(const int &aHeight);
-	void setID(const int &anID);
-	
-	CoordT< int > topLeft() const;
-	CoordT< int > bottomRight() const;
-	int width();
-	int height();
-	int id() const;
-	
-	bool isValid() const;
-	void validate();
-	
-private:
-	CoordT< int > top_left_;
-	CoordT< int > bottom_right_;
-	int id_;
+  public:
+    BoundingBox();
+    BoundingBox ( const BoundingBox &copy );
+    ~BoundingBox();
+
+    void setTopLeft ( const NICE::CoordT< int > &aTopLeft );
+    void setTopLeft ( const int &x, const int &y );
+    void setBottomRight ( const NICE::CoordT< int > &aBottomRight );
+    void setBottomRight ( const int &x, const int &y );
+    void setWidth ( const int &aWidth );
+    void setHeight ( const int &aHeight );
+    void setID ( const int &anID );
+
+    NICE::CoordT< int > topLeft() const;
+    NICE::CoordT< int > bottomRight() const;
+    int width();
+    int height();
+    int id() const;
+
+    bool isValid() const;
+    void validate();
+
+  private:
+    NICE::CoordT< int > top_left_;
+    NICE::CoordT< int > bottom_right_;
+    int id_;
 };
 
 } //namespace
 
 #endif /* __BOUNDINGBOX_H__ */
-
-/*
- * 
- */

+ 225 - 225
cbaselib/CachedExample.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file CachedExample.cpp
 * @brief data caching
 * @author Erik Rodner
@@ -23,292 +23,292 @@ using namespace NICE;
 
 void CachedExample::init ()
 {
-    dchannels = new MultiChannelImageT<double> [D_NUMCHANNELS];
-    ichannels = new MultiChannelImageT<int> [I_NUMCHANNELS];
-    lchannels = new MultiChannelImageT<long> [L_NUMCHANNELS];
-
-    svmap = new SparseVector *[SVNUMCHANNELS];
-    svmap_xsize = new int [SVNUMCHANNELS];
-    svmap_ysize = new int [SVNUMCHANNELS];
-    for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
-    {
-	svmap[k] = NULL;
-	svmap_xsize[k] = 0;
-	svmap_ysize[k] = 0;
-    }
+  dchannels = new MultiChannelImageT<double> [D_NUMCHANNELS];
+  ichannels = new MultiChannelImageT<int> [I_NUMCHANNELS];
+  lchannels = new MultiChannelImageT<long> [L_NUMCHANNELS];
+
+  svmap = new SparseVector *[SVNUMCHANNELS];
+  svmap_xsize = new int [SVNUMCHANNELS];
+  svmap_ysize = new int [SVNUMCHANNELS];
+  for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
+  {
+    svmap[k] = NULL;
+    svmap_xsize[k] = 0;
+    svmap_ysize[k] = 0;
+  }
+}
+
+CachedExample::CachedExample ( const std::string & _imgfn,
+                               int _newWidth,
+                               int _newHeight )
+{
+  imgfn = _imgfn;
+  newWidth = _newWidth;
+  newHeight = _newHeight;
+  Preprocess::getImageSize ( _imgfn, oxsize, oysize );
+  init();
+  hasColorInformation = true;
 }
 
-CachedExample::CachedExample( const std::string & _imgfn,
-			      int _newWidth,
-			      int _newHeight )
+CachedExample::CachedExample ( const NICE::Image & _img )
 {
-    imgfn = _imgfn;
-    newWidth = _newWidth;
-    newHeight = _newHeight;
-    Preprocess::getImageSize ( _imgfn, oxsize, oysize );
-    init();
-    hasColorInformation = true;
+  imgfn = "";
+  newWidth = -1;
+  newHeight = -1;
+  init();
+
+  oxsize = _img.width();
+  oysize = _img.height();
+  int *gray = new int [ oxsize*oysize ];
+  int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+      gray[k] = _img.getPixel ( x, y );
+
+  ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, false );
+  ichannels[I_GRAYVALUES].setImage ( gray, oxsize, oysize, 0 );
+
+  hasColorInformation = false;
 }
 
-CachedExample::CachedExample( const NICE::Image & _img )
+CachedExample::CachedExample ( const NICE::ColorImage & img, bool disableGrayConversion )
 {
-    imgfn = "";
-    newWidth = -1;
-    newHeight = -1;
-    init();
-
-    oxsize = _img.width();
-    oysize = _img.height();
-    int *gray = new int [ oxsize*oysize ];
+  imgfn = "";
+  oxsize = img.width();
+  oysize = img.height();
+  newWidth = -1;
+  newHeight = -1;
+  init();
+
+  if ( ! disableGrayConversion )
+  {
+    // refactor-nice.pl: check this substitution
+    // old: Image imggray;
+    NICE::Image imggray;
+    ICETools::calcGrayImage ( img, imggray );
+
+    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
+    int *gray = ichannels[I_GRAYVALUES].data[0];
     int k = 0;
     for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	    gray[k] = _img.getPixel(x,y);
+      for ( int x = 0 ; x < oxsize ; x++, k++ )
+        // refactor-nice.pl: check this substitution
+        // old: gray[k] = GetVal(imggray,x,y);
+        gray[k] = imggray.getPixel ( x, y );
+  }
 
-    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, false );
-    ichannels[I_GRAYVALUES].setImage ( gray, oxsize, oysize, 0 );
+  ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
 
-    hasColorInformation = false;
-}
-
-CachedExample::CachedExample( const NICE::ColorImage & img, bool disableGrayConversion )
-{
-    imgfn = "";
-    oxsize = img.width();
-    oysize = img.height();
-    newWidth = -1;
-    newHeight = -1;
-    init();
-
-    if ( ! disableGrayConversion )
+  long int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
     {
-	// refactor-nice.pl: check this substitution
-	// old: Image imggray;
-	NICE::Image imggray;
-	ICETools::calcGrayImage ( img, imggray );
-
-	ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
-	int *gray = ichannels[I_GRAYVALUES].data[0];
-	int k = 0;
-	for ( int y = 0 ; y < oysize ; y++ )
-	    for ( int x = 0 ; x < oxsize ; x++,k++ )
-		// refactor-nice.pl: check this substitution
-		// old: gray[k] = GetVal(imggray,x,y);
-		gray[k] = imggray.getPixel(x,y);
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[0][k] = GetVal(img.RedImage(), x, y);
+      ichannels[I_COLOR].data[0][k] = img.getPixel ( x, y, 0 );
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[1][k] = GetVal(img.GreenImage(), x, y);
+      ichannels[I_COLOR].data[1][k] = img.getPixel ( x, y, 1 );
+      // refactor-nice.pl: check this substitution
+      // old: ichannels[I_COLOR].data[2][k] = GetVal(img.BlueImage(), x, y);
+      ichannels[I_COLOR].data[2][k] = img.getPixel ( x, y, 2 );
     }
 
-    ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
-
-    long int k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	{
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[0][k] = GetVal(img.RedImage(), x, y);
-	    ichannels[I_COLOR].data[0][k] = img.getPixel(x,y,0);
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[1][k] = GetVal(img.GreenImage(), x, y);
-	    ichannels[I_COLOR].data[1][k] = img.getPixel(x,y,1);
-	    // refactor-nice.pl: check this substitution
-	    // old: ichannels[I_COLOR].data[2][k] = GetVal(img.BlueImage(), x, y);
-	    ichannels[I_COLOR].data[2][k] = img.getPixel(x,y,2);
-	}
-
-    hasColorInformation = true;
+  hasColorInformation = true;
 }
-	
+
 CachedExample::~CachedExample()
 {
-    delete [] dchannels;
-    delete [] ichannels;
-    delete [] lchannels;
-
-    for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
-	if ( svmap[k] != NULL )
-	    delete [] (svmap[k]);
-
-    delete [] svmap;
-    delete [] svmap_xsize;
-    delete [] svmap_ysize;
-
-    // remove all temporary files
-    for ( map<int, string>::const_iterator j = dtemps.begin();
-					   j != dtemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
-    
-    for ( map<int, string>::const_iterator j = itemps.begin();
-					   j != itemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
-
-    for ( map<int, string>::const_iterator j = ltemps.begin();
-					   j != ltemps.end();
-					   j++ )
-    {
-	//fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
-	FileMgt::deleteTempFile ( j->second );
-    }
+  delete [] dchannels;
+  delete [] ichannels;
+  delete [] lchannels;
+
+  for ( uint k = 0 ; k < SVNUMCHANNELS ; k++ )
+    if ( svmap[k] != NULL )
+      delete [] ( svmap[k] );
+
+  delete [] svmap;
+  delete [] svmap_xsize;
+  delete [] svmap_ysize;
+
+  // remove all temporary files
+  for ( map<int, string>::const_iterator j = dtemps.begin();
+        j != dtemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
+
+  for ( map<int, string>::const_iterator j = itemps.begin();
+        j != itemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
+
+  for ( map<int, string>::const_iterator j = ltemps.begin();
+        j != ltemps.end();
+        j++ )
+  {
+    //fprintf (stderr, "CachedExample: removing temp file %s\n", j->second.c_str() );
+    FileMgt::deleteTempFile ( j->second );
+  }
 
 }
 
 void CachedExample::readImageData ()
 {
-    if ( imgfn == "" ) return;
+  if ( imgfn == "" ) return;
 
-    NICE::Image orig = Preprocess::ReadImgAdv(imgfn);
-    NICE::Image imggray;
+  NICE::Image orig = Preprocess::ReadImgAdv ( imgfn );
+  NICE::Image imggray;
 
-    if ( newWidth > 0 )
-	Conversions::resizeImage ( orig, imggray, newWidth, newHeight );
-    else
-	imggray = orig;
+  if ( newWidth > 0 )
+    Conversions::resizeImage ( orig, imggray, newWidth, newHeight );
+  else
+    imggray = orig;
 
-    oxsize = imggray.width();
-    oysize = imggray.height();
+  oxsize = imggray.width();
+  oysize = imggray.height();
 
-    ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
-    int *gray = ichannels[I_GRAYVALUES].data[0];
-    int k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	    gray[k] = imggray.getPixel(x,y);
+  ichannels[I_GRAYVALUES].reInit ( oxsize, oysize, 1, true );
+  int *gray = ichannels[I_GRAYVALUES].data[0];
+  int k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+      gray[k] = imggray.getPixel ( x, y );
 }
 
 void CachedExample::readImageDataRGB ()
 {
-    if ( imgfn == "" ) return;
-
-    NICE::ColorImage img;
-    try {
-	img = Preprocess::ReadImgAdvRGB(imgfn);
-    } catch ( NICE::ImageException & ) {
-	fprintf (stderr, "error reading rgb image %s\n", imgfn.c_str());
-	hasColorInformation = false;
-	return;
-    }
+  if ( imgfn == "" ) return;
 
-    oxsize = img.width();
-    oysize = img.height();
+  NICE::ColorImage img;
+  try {
+    img = Preprocess::ReadImgAdvRGB ( imgfn );
+  } catch ( NICE::ImageException & ) {
+    fprintf ( stderr, "error reading rgb image %s\n", imgfn.c_str() );
+    hasColorInformation = false;
+    return;
+  }
 
-    hasColorInformation = true;
-    
-    ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
+  oxsize = img.width();
+  oysize = img.height();
 
-    long k = 0;
-    for ( int y = 0 ; y < oysize ; y++ )
-	for ( int x = 0 ; x < oxsize ; x++,k++ )
-	{
-	    ichannels[I_COLOR].data[0][k] = img.getPixel(x,y,0);
-	    ichannels[I_COLOR].data[1][k] = img.getPixel(x,y,1);
-	    ichannels[I_COLOR].data[2][k] = img.getPixel(x,y,2);
-	}
+  hasColorInformation = true;
+
+  ichannels[I_COLOR].reInit ( oxsize, oysize, 3, true );
+
+  long k = 0;
+  for ( int y = 0 ; y < oysize ; y++ )
+    for ( int x = 0 ; x < oxsize ; x++, k++ )
+    {
+      ichannels[I_COLOR].data[0][k] = img.getPixel ( x, y, 0 );
+      ichannels[I_COLOR].data[1][k] = img.getPixel ( x, y, 1 );
+      ichannels[I_COLOR].data[2][k] = img.getPixel ( x, y, 2 );
+    }
 }
 
 void CachedExample::calcIntegralImage ()
 {
-    if (ichannels[I_GRAYVALUES].xsize == 0)
+  if ( ichannels[I_GRAYVALUES].xsize == 0 )
+  {
+    readImageData ();
+    if ( ichannels[I_GRAYVALUES].xsize == 0 )
     {
-	readImageData ();
-	if ( ichannels[I_GRAYVALUES].xsize == 0 )
-	{
-	    fprintf (stderr, "CachedExample::getChannel: unable to recover data channel\n");
-	    exit(-1);
-	}
+      fprintf ( stderr, "CachedExample::getChannel: unable to recover data channel\n" );
+      exit ( -1 );
     }
+  }
 
-    lchannels[L_INTEGRALIMAGE].reInit ( ichannels[I_GRAYVALUES].xsize,
-					ichannels[I_GRAYVALUES].ysize,
-					1, true );
-    
-		GenericImageTools::calcIntegralImage ( 
-		lchannels[L_INTEGRALIMAGE].data[0], 
-		ichannels[I_GRAYVALUES].data[0], 
-		ichannels[I_GRAYVALUES].xsize, 
-		ichannels[I_GRAYVALUES].ysize );
+  lchannels[L_INTEGRALIMAGE].reInit ( ichannels[I_GRAYVALUES].xsize,
+                                      ichannels[I_GRAYVALUES].ysize,
+                                      1, true );
+
+  GenericImageTools::calcIntegralImage (
+    lchannels[L_INTEGRALIMAGE].data[0],
+    ichannels[I_GRAYVALUES].data[0],
+    ichannels[I_GRAYVALUES].xsize,
+    ichannels[I_GRAYVALUES].ysize );
 
 }
 
-void CachedExample::buildIntegralSV ( int svchannel, 
-				      SparseVector *_map, 
-				      int xsize_s, int ysize_s )
+void CachedExample::buildIntegralSV ( int svchannel,
+                                      SparseVector *_map,
+                                      int xsize_s, int ysize_s )
 {
-    SparseVector *map = _map;
-    svmap[svchannel] = _map;
-    svmap_xsize[svchannel] = xsize_s;
-    svmap_ysize[svchannel] = ysize_s;
+  SparseVector *map = _map;
+  svmap[svchannel] = _map;
+  svmap_xsize[svchannel] = xsize_s;
+  svmap_ysize[svchannel] = ysize_s;
 
-    int k = xsize_s;
-    for ( int y = 1 ; y < ysize_s; y++, k+=xsize_s )
-	map[k].add ( (map[k-xsize_s]) );
+  int k = xsize_s;
+  for ( int y = 1 ; y < ysize_s; y++, k += xsize_s )
+    map[k].add ( ( map[k-xsize_s] ) );
 
-    k = 1;
-    for ( int x = 1 ; x < xsize_s; x++, k++ )
-	map[k].add ( (map[k-1]) );
+  k = 1;
+  for ( int x = 1 ; x < xsize_s; x++, k++ )
+    map[k].add ( ( map[k-1] ) );
 
-    k = xsize_s + 1;
+  k = xsize_s + 1;
 
-    for ( int y = 1 ; y < ysize_s ; y++,k++ )
+  for ( int y = 1 ; y < ysize_s ; y++, k++ )
+  {
+    for ( int x = 1 ; x < xsize_s ; x++, k++ )
     {
-	for ( int x = 1 ; x < xsize_s ; x++,k++ )
-	{
-	    map[k].add ( (map[k-1]) );
-	    map[k].add ( (map[k-xsize_s]) );
-	    map[k].add ( (map[k-xsize_s-1]), -1.0 );
-	}
+      map[k].add ( ( map[k-1] ) );
+      map[k].add ( ( map[k-xsize_s] ) );
+      map[k].add ( ( map[k-xsize_s-1] ), -1.0 );
     }
+  }
 }
 
-void CachedExample::setSVMap ( int svchannel, 
-			      SparseVector *_map, 
-			      int xsize_s, int ysize_s )
+void CachedExample::setSVMap ( int svchannel,
+                               SparseVector *_map,
+                               int xsize_s, int ysize_s )
 {
-    svmap[svchannel] = _map;
-    svmap_xsize[svchannel] = xsize_s;
-    svmap_ysize[svchannel] = ysize_s;
+  svmap[svchannel] = _map;
+  svmap_xsize[svchannel] = xsize_s;
+  svmap_ysize[svchannel] = ysize_s;
 }
 
 SparseVector *CachedExample::getSVMap ( int svchannel,
-				        int & _xsize, int & _ysize,
-				        int & _tm_xsize, int & _tm_ysize ) const
+                                        int & _xsize, int & _ysize,
+                                        int & _tm_xsize, int & _tm_ysize ) const
 {
-    _xsize = oxsize;
-    _ysize = oysize;
-    _tm_xsize = svmap_xsize[svchannel];
-    _tm_ysize = svmap_ysize[svchannel];
-    assert ( svmap[svchannel] != NULL );
-    return svmap[svchannel];
+  _xsize = oxsize;
+  _ysize = oysize;
+  _tm_xsize = svmap_xsize[svchannel];
+  _tm_ysize = svmap_ysize[svchannel];
+  assert ( svmap[svchannel] != NULL );
+  return svmap[svchannel];
 }
 
 bool CachedExample::colorInformationAvailable() const
 {
-    if ( hasColorInformation ) return true;
-    else {
-	if ( imgfn.size() == 0 ) return false;
-
-	int tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr;
-	// refactor: InfImgFile ( imgfn, tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr );
-	ImageFile imgf ( imgfn );
-	const ImageFile::Header & imgfheader = imgf.getHeader();
-	tmp_xsize = imgfheader.width;
-	tmp_ysize = imgfheader.height;
-	tmp_maxval = 255;
-	tmp_nr = imgfheader.channel;
-
-	if ( tmp_nr > 1 ) return true;
-	else return false;
-    }
+  if ( hasColorInformation ) return true;
+  else {
+    if ( imgfn.size() == 0 ) return false;
+
+    int tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr;
+    // refactor: InfImgFile ( imgfn, tmp_xsize, tmp_ysize, tmp_maxval, tmp_nr );
+    ImageFile imgf ( imgfn );
+    const ImageFile::Header & imgfheader = imgf.getHeader();
+    tmp_xsize = imgfheader.width;
+    tmp_ysize = imgfheader.height;
+    tmp_maxval = 255;
+    tmp_nr = imgfheader.channel;
+
+    if ( tmp_nr > 1 ) return true;
+    else return false;
+  }
 }
 
 void CachedExample::dropPreCached()
 {
-    dropImages<double> ( dchannels, dtemps, D_NUMCHANNELS );
-    dropImages<int> ( ichannels, itemps, I_NUMCHANNELS );
-    dropImages<long> ( lchannels, ltemps, L_NUMCHANNELS );
+  dropImages<double> ( dchannels, dtemps, D_NUMCHANNELS );
+  dropImages<int> ( ichannels, itemps, I_NUMCHANNELS );
+  dropImages<long> ( lchannels, ltemps, L_NUMCHANNELS );
 }

+ 274 - 249
cbaselib/CachedExample.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file CachedExample.h
 * @brief data caching of several feature images and many more
 * @author Erik Rodner
@@ -11,294 +11,319 @@
 #include <assert.h>
 #include <map>
 
-#include "core/vector/SparseVector.h"
+#include "core/vector/SparseVectorT.h"
 #include "core/image/MultiChannelImageT.h"
 #include "core/basics/FileMgt.h"
 
-using namespace NICE;
-
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** data caching of several feature images and many more,
-    can be used in conjunction with Example 
+    can be used in conjunction with Example
     to share image data between different sliding windows within
     an image
     @see Example */
 class CachedExample
 {
 
-    protected:
-	/** resize image to this fixed width */
-	int newWidth;
-	/** resize image to this fixed height */
-	int newHeight;
-
-	/** original image width */
-	int oxsize;
-	/** original image height */
-	int oysize;
-
-	/** filename of image */
-	std::string imgfn;
-
-	/** array of double images */
-	MultiChannelImageT<double> *dchannels;
-
-	/** array of integer images */
-	MultiChannelImageT<int> *ichannels;
-
-	/** array of histogram images */
-	MultiChannelImageT<long> *lchannels;
-
-	/** maps for temporary files */
-	std::map<int, std::string> dtemps;
-	std::map<int, std::string> itemps;
-	std::map<int, std::string> ltemps;
-
-	/** read standard image data from file */
-	void readImageData ();
-	
-	/** read rgb image data from file */
-	void readImageDataRGB ();
-
-	/** calc grayvalue integral image */
-	void calcIntegralImage ();
-
-	/** array of histogram images */
-	SparseVector **svmap;
-	
-	/** sizes of histogram images */
-	int *svmap_xsize;
-	int *svmap_ysize;
-
-	bool hasColorInformation;
-
-    public:
-
-	/** whether one can obtain color information */
-	bool colorInformationAvailable() const;
-
-  	enum {
-	    L_INTEGRALIMAGE = 0,
-	    L_NUMCHANNELS
-	};
-
-	/** integer channel types */
-	enum {
-	    I_GRAYVALUES = 0,
-	    I_COLOR,
-	    I_EDGES,
-	    I_NUMCHANNELS
-	};
-
-	/** double value channels */
-	enum {
-	    D_EOH = 0,
-	    D_INTEGRALPRIOR,
-	    D_INTEGRALEOH,
-	    D_INTEGRALCOLOR,
-	    D_NUMCHANNELS
-	};
-
-	
-	/** sparse histogram channel types */
-	enum {
-	    SVTEXTON = 0,
-	    SVNUMCHANNELS
-	};
-
-	/** default init method */
-	void init ();
-
-	/** simple constructor 
-	    @param imgfn image filename
-	    @param newWidth resize raw image to this width
-	    @param newHeight resize raw image to this height
-	*/
-	CachedExample( const std::string & imgfn, int newWidth = -1, 
-					     int newHeight = -1 );
-	
-	/** constructor (disabled buffering)
-	    @param img gray-value image
-	*/
-	CachedExample( const NICE::Image & img );
-      
-	/** constructor (disabled buffering)
-	    @param img rgb image
-	    @param disableGrayConversion whether to provide gray values or not
-	*/
-	CachedExample( const NICE::ColorImage & img, bool disableGrayConversion = false );
-
-	/** simple destructor */
-	virtual ~CachedExample();
-
-	/**
-	 * get the NICE::Image Filename
-	 * @return NICE::Image Filename
-	 */
-	inline std::string getFilename();
-	
-	
-	/** get double image channel 
-	    @param channel channel type (choose from enum type)
-	    @param[out] xsize width of image
-	    @param[out] ysize height of image
-	    @return buffer to image data
-	*/
-	inline MultiChannelImageT<double> & getDChannel ( int channel ); 
-
-	/** get integer image channel 
-	    @param channel channel type (choose from enum type)
-	    @param[out] xsize width of image
-	    @param[out] ysize height of image
-	    @return buffer to image data
-	*/
-	inline MultiChannelImageT<int> & getIChannel ( int channel ); 
-
-	/** get long image channel 
-	    @param channel channel type (choose from enum type)
-	    @param[out] xsize width of image
-	    @param[out] ysize height of image
-	    @return buffer to image data
-	*/
-	inline MultiChannelImageT<long> & getLChannel ( int channel ); 
-
-	/** get histogram image
-	    @param svchannel channel type (choose from histogram channel enum)
-	    @param[out] xsize width of raw image
-	    @param[out] ysize height of raw image
-	    @param[out] tm_xsize width of histogram channel buffer
-	    @param[out] tm_ysize height of histogram channel buffer
-	    @remark buffer will be not copied !!
-	    @return pointer to histogram channel buffer
-	*/
-	SparseVector *getSVMap ( int svchannel, int & xsize, int & ysize, int & tm_xsize, int & tm_ysize ) const;
-
-	/** assign histogram channel buffer and compute integral image
-	    @param svchannel 
-	    @param _map pointer to histogram channel buffer
-	    @param xsize_s width of histogram channel buffer
-	    @param ysize_s height of histogram channel buffer
-	    @remark buffer will be not copied !!
-	*/
-	void buildIntegralSV ( int svchannel, SparseVector *_map, int xsize_s, int ysize_s );
-	
-    	/** assign histogram channel buffer
-	    @param svchannel 
-	    @param _map pointer to histogram channel buffer
-	    @param xsize_s width of histogram channel buffer
-	    @param ysize_s height of histogram channel buffer
-	    @remark buffer will be not copied !!
-	*/
-	void setSVMap ( int svchannel, SparseVector *_map, int xsize_s, int ysize_s );
-
-	/** get image sizes */
-	void getImageSize ( int & xsize, int & ysize ) const { xsize = oxsize; ysize = oysize; };
-
-	/** drop precached data: 
-		(1) this is only possible if an image filename is given 
-		(2) only data channels are deleted that can be reproduced by CachedExample itself
-	*/
-	void dropPreCached();
-
-	template<class ImgPixelValue>
-	void dropImages ( MultiChannelImageT<ImgPixelValue> *images, 
-			  std::map<int, std::string> & temps, 
-			  int numImages ); 
+  protected:
+    /** resize image to this fixed width */
+    int newWidth;
+    /** resize image to this fixed height */
+    int newHeight;
+
+    /** original image width */
+    int oxsize;
+    /** original image height */
+    int oysize;
+
+    /** filename of image */
+    std::string imgfn;
+
+    /** array of double images */
+    NICE::MultiChannelImageT<double> *dchannels;
+
+    /** array of integer images */
+    NICE::MultiChannelImageT<int> *ichannels;
+
+    /** array of histogram images */
+    NICE::MultiChannelImageT<long> *lchannels;
+
+    /** maps for temporary files */
+    std::map<int, std::string> dtemps;
+    std::map<int, std::string> itemps;
+    std::map<int, std::string> ltemps;
+
+    /** read standard image data from file */
+    void readImageData ();
+
+    /** read rgb image data from file */
+    void readImageDataRGB ();
+
+    /** calc grayvalue integral image */
+    void calcIntegralImage ();
+
+    /** array of histogram images */
+    NICE::SparseVector **svmap;
+
+    /** sizes of histogram images */
+    int *svmap_xsize;
+    int *svmap_ysize;
+
+    bool hasColorInformation;
+
+  public:
+
+    /** whether one can obtain color information */
+    bool colorInformationAvailable() const;
+
+    enum
+    {
+      L_INTEGRALIMAGE = 0,
+      L_NUMCHANNELS
+    };
+
+    /** integer channel types */
+    enum
+    {
+      I_GRAYVALUES = 0,
+      I_COLOR,
+      I_EDGES,
+      I_NUMCHANNELS
+    };
+
+    /** double value channels */
+    enum
+    {
+      D_EOH = 0,
+      D_INTEGRALPRIOR,
+      D_INTEGRALEOH,
+      D_INTEGRALCOLOR,
+      D_NUMCHANNELS
+    };
+
+
+    /** sparse histogram channel types */
+    enum
+    {
+      SVTEXTON = 0,
+      SVNUMCHANNELS
+    };
+
+    /** default init method */
+    void init ();
+
+    /** simple constructor
+        @param imgfn image filename
+        @param newWidth resize raw image to this width
+        @param newHeight resize raw image to this height
+    */
+    CachedExample ( const std::string & imgfn, int newWidth = -1,
+                    int newHeight = -1 );
+
+    /** constructor (disabled buffering)
+        @param img gray-value image
+    */
+    CachedExample ( const NICE::Image & img );
+
+    /** constructor (disabled buffering)
+        @param img rgb image
+        @param disableGrayConversion whether to provide gray values or not
+    */
+    CachedExample ( const NICE::ColorImage & img, bool disableGrayConversion = false );
+
+    /** simple destructor */
+    virtual ~CachedExample();
+
+    /**
+     * get the NICE::Image Filename
+     * @return NICE::Image Filename
+     */
+    inline std::string getFilename();
+
+
+    /** get double image channel
+        @param channel channel type (choose from enum type)
+        @param[out] xsize width of image
+        @param[out] ysize height of image
+        @return buffer to image data
+    */
+    inline NICE::MultiChannelImageT<double> & getDChannel ( int channel );
+
+    /** get integer image channel
+        @param channel channel type (choose from enum type)
+        @param[out] xsize width of image
+        @param[out] ysize height of image
+        @return buffer to image data
+    */
+    inline NICE::MultiChannelImageT<int> & getIChannel ( int channel );
+
+    /** get long image channel
+        @param channel channel type (choose from enum type)
+        @param[out] xsize width of image
+        @param[out] ysize height of image
+        @return buffer to image data
+    */
+    inline NICE::MultiChannelImageT<long> & getLChannel ( int channel );
+
+    /** get histogram image
+        @param svchannel channel type (choose from histogram channel enum)
+        @param[out] xsize width of raw image
+        @param[out] ysize height of raw image
+        @param[out] tm_xsize width of histogram channel buffer
+        @param[out] tm_ysize height of histogram channel buffer
+        @remark buffer will be not copied !!
+        @return pointer to histogram channel buffer
+    */
+    NICE::SparseVector *getSVMap ( int svchannel, int & xsize, int & ysize, int & tm_xsize, int & tm_ysize ) const;
+
+    /** assign histogram channel buffer and compute integral image
+        @param svchannel
+        @param _map pointer to histogram channel buffer
+        @param xsize_s width of histogram channel buffer
+        @param ysize_s height of histogram channel buffer
+        @remark buffer will be not copied !!
+    */
+    void buildIntegralSV ( int svchannel, NICE::SparseVector *_map, int xsize_s, int ysize_s );
+
+    /** assign histogram channel buffer
+    @param svchannel
+    @param _map pointer to histogram channel buffer
+    @param xsize_s width of histogram channel buffer
+    @param ysize_s height of histogram channel buffer
+    @remark buffer will be not copied !!
+    */
+    void setSVMap ( int svchannel, NICE::SparseVector *_map, int xsize_s, int ysize_s );
+
+    /** get image sizes */
+    void getImageSize ( int & xsize, int & ysize ) const
+    {
+      xsize = oxsize;
+      ysize = oysize;
+    };
+
+    /** drop precached data:
+     (1) this is only possible if an image filename is given
+     (2) only data channels are deleted that can be reproduced by CachedExample itself
+    */
+    void dropPreCached();
+
+    template<class ImgPixelValue>
+    void dropImages ( NICE::MultiChannelImageT<ImgPixelValue> *images,
+                      std::map<int, std::string> & temps,
+                      int numImages );
 };
 
 
 /********************** INLINE FUNCTIONS *****************************/
-inline MultiChannelImageT<double> & CachedExample::getDChannel ( int channel )
+inline NICE::MultiChannelImageT<double> & CachedExample::getDChannel ( int channel )
 {
-    assert ( (channel >= 0) && (channel < D_NUMCHANNELS) ); 
-
-    if ( dchannels[channel].data == NULL ) {
-	std::map<int, std::string>::const_iterator j = dtemps.find(channel);
-	if ( j == dtemps.end() ) {
-	    //fprintf (stderr, "MultiChannelImageT: unable to recover data channel %s (double %d)!\n", 
-	    //	imgfn.c_str(), channel);
-	} else {
-	    //fprintf (stderr, "MultiChannelImageT: restoring data from %s ", j->second.c_str() );
-	    dchannels[channel].restore ( j->second );
-	    //fprintf (stderr, "(%d x %d)\n", dchannels[channel].xsize, dchannels[channel].ysize );
-	}
+  assert ( ( channel >= 0 ) && ( channel < D_NUMCHANNELS ) );
+
+  if ( dchannels[channel].data == NULL )
+  {
+    std::map<int, std::string>::const_iterator j = dtemps.find ( channel );
+    if ( j == dtemps.end() )
+    {
+      //fprintf (stderr, "NICE::MultiChannelImageT: unable to recover data channel %s (double %d)!\n",
+      // imgfn.c_str(), channel);
+    }
+    else
+    {
+      //fprintf (stderr, "NICE::MultiChannelImageT: restoring data from %s ", j->second.c_str() );
+      dchannels[channel].restore ( j->second );
+      //fprintf (stderr, "(%d x %d)\n", dchannels[channel].xsize, dchannels[channel].ysize );
     }
+  }
 
-    return dchannels[channel];
+  return dchannels[channel];
 }
 
 inline std::string CachedExample::getFilename()
 {
-	return imgfn;
+  return imgfn;
 }
 
-inline MultiChannelImageT<int> & CachedExample::getIChannel ( int channel )
+inline NICE::MultiChannelImageT<int> & CachedExample::getIChannel ( int channel )
 {
-    assert ( (channel >= 0) && (channel < I_NUMCHANNELS) ); 
+  assert ( ( channel >= 0 ) && ( channel < I_NUMCHANNELS ) );
 
-    if ( (ichannels[channel].data == NULL) )
+  if ( ( ichannels[channel].data == NULL ) )
+  {
+    if ( ( imgfn != "" ) && ( channel == I_GRAYVALUES ) )
     {
-	if ( (imgfn != "") && (channel == I_GRAYVALUES) ) 
-	{
-	    readImageData();
-	} else if ( (imgfn != "") && (channel == I_COLOR) ) {
-	    readImageDataRGB();
-	    assert ( hasColorInformation );
-	} else {
-	    std::map<int, std::string>::const_iterator j = itemps.find(channel);
-	    if ( j == itemps.end() ) {
-		//fprintf (stderr, "MultiChannelImageT: unable to recover data channel (int %d)!\n", channel);
-		//exit(-1);
-	    } else {
-		//fprintf (stderr, "MultiChannelImageT: restoring data from %s\n", j->second.c_str() );
-		ichannels[channel].restore ( j->second );
-	    }
-	}
+      readImageData();
     }
+    else if ( ( imgfn != "" ) && ( channel == I_COLOR ) )
+    {
+      readImageDataRGB();
+      assert ( hasColorInformation );
+    }
+    else
+    {
+      std::map<int, std::string>::const_iterator j = itemps.find ( channel );
+      if ( j == itemps.end() )
+      {
+        //fprintf (stderr, "NICE::MultiChannelImageT: unable to recover data channel (int %d)!\n", channel);
+        //exit(-1);
+      }
+      else
+      {
+        //fprintf (stderr, "NICE::MultiChannelImageT: restoring data from %s\n", j->second.c_str() );
+        ichannels[channel].restore ( j->second );
+      }
+    }
+  }
 
-    return ichannels[channel];
+  return ichannels[channel];
 }
 
-inline MultiChannelImageT<long> & CachedExample::getLChannel ( int channel )
+inline NICE::MultiChannelImageT<long> & CachedExample::getLChannel ( int channel )
 {
-    assert ( (channel >= 0) && (channel < L_NUMCHANNELS) ); 
-
-    if ( lchannels[channel].data == NULL ) {
-	std::map<int, std::string>::const_iterator j = ltemps.find(channel);
-	if ( j == ltemps.end() ) {
-
-	    if ( channel == L_INTEGRALIMAGE ) {
-		calcIntegralImage();
-	    } else {
-		//fprintf (stderr, "MultiChannelImageT: unable to recover data channel (long %d)!\n", channel);
-		//exit(-1);
-	    }
-	} else {
-	    //fprintf (stderr, "MultiChannelImageT: restoring data from %s\n", j->second.c_str() );
-	    lchannels[channel].restore ( j->second );
-	}
+  assert ( ( channel >= 0 ) && ( channel < L_NUMCHANNELS ) );
+
+  if ( lchannels[channel].data == NULL )
+  {
+    std::map<int, std::string>::const_iterator j = ltemps.find ( channel );
+    if ( j == ltemps.end() )
+    {
+
+      if ( channel == L_INTEGRALIMAGE )
+      {
+        calcIntegralImage();
+      }
+      else
+      {
+        //fprintf (stderr, "NICE::MultiChannelImageT: unable to recover data channel (long %d)!\n", channel);
+        //exit(-1);
+      }
+    }
+    else
+    {
+      //fprintf (stderr, "NICE::MultiChannelImageT: restoring data from %s\n", j->second.c_str() );
+      lchannels[channel].restore ( j->second );
     }
+  }
 
-    return lchannels[channel];
+  return lchannels[channel];
 }
 
 template<class ImgPixelValue>
-void CachedExample::dropImages ( MultiChannelImageT<ImgPixelValue> *images, std::map<int, std::string> & temps, int numImages )
+void CachedExample::dropImages ( NICE::MultiChannelImageT<ImgPixelValue> *images, std::map<int, std::string> & temps, int numImages )
 {
-    for ( int i = 0 ; i < numImages; i++ )
+  for ( int i = 0 ; i < numImages; i++ )
+  {
+    std::map<int, std::string>::iterator j = temps.find ( i );
+    if ( j == temps.end() )
     {
-	std::map<int, std::string>::iterator j = temps.find(i);
-	if ( j == temps.end() )
-	{
-	    std::string tempfilename = FileMgt::createTempFile("tmp/cachedexample_%s");
-	    //fprintf (stderr, "CachedExample: dumping channel %d/%d to %s (%d x %d)\n", i, numImages, tempfilename.c_str(),
-	    //	images[i].xsize, images[i].ysize );
-	    images[i].store ( tempfilename );
-	    temps[i] = tempfilename;
-	}
-	images[i].freeData();
+      std::string tempfilename = NICE::FileMgt::createTempFile ( "tmp/cachedexample_%s" );
+      //fprintf (stderr, "CachedExample: dumping channel %d/%d to %s (%d x %d)\n", i, numImages, tempfilename.c_str(),
+      // images[i].xsize, images[i].ysize );
+      images[i].store ( tempfilename );
+      temps[i] = tempfilename;
     }
+    images[i].freeData();
+  }
 
 }
 

+ 24 - 24
cbaselib/ClassificationResult.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ClassificationResult.cpp
 * @brief classification result, what else?
 * @author Erik Rodner
@@ -20,33 +20,33 @@ using namespace NICE;
 
 
 
-ClassificationResult::ClassificationResult( int _rejection_status, int maxClassNo ) : scores(maxClassNo+1)
+ClassificationResult::ClassificationResult ( int _rejection_status, int maxClassNo ) : scores ( maxClassNo + 1 )
 {
-    rejection_status = _rejection_status;
-    classno = -1;
-    classno_groundtruth = -1;
-    classname = "rejected";
-	uncertainty = 0.0;
+  rejection_status = _rejection_status;
+  classno = -1;
+  classno_groundtruth = -1;
+  classname = "rejected";
+  uncertainty = 0.0;
 }
 
-ClassificationResult::ClassificationResult( int _classno, double _score, int maxClassNo ) : scores(maxClassNo+1)
+ClassificationResult::ClassificationResult ( int _classno, double _score, int maxClassNo ) : scores ( maxClassNo + 1 )
 {
-    rejection_status = REJECTION_NONE;
-    classno = _classno;
-    scores[classno] = _score;
-    classname = "unknown";
-    classno_groundtruth = -1;
-	uncertainty = 0.0;
+  rejection_status = REJECTION_NONE;
+  classno = _classno;
+  scores[classno] = _score;
+  classname = "unknown";
+  classno_groundtruth = -1;
+  uncertainty = 0.0;
 }
 
-ClassificationResult::ClassificationResult( int _classno, const FullVector & _scores )
+ClassificationResult::ClassificationResult ( int _classno, const FullVector & _scores )
 {
-    rejection_status = REJECTION_NONE;
-    classno = _classno;
-    scores = _scores;
-    classname = "unknown";
-    classno_groundtruth = -1;
-	uncertainty = 0.0;
+  rejection_status = REJECTION_NONE;
+  classno = _classno;
+  scores = _scores;
+  classname = "unknown";
+  classno_groundtruth = -1;
+  uncertainty = 0.0;
 }
 
 ClassificationResult::~ClassificationResult()
@@ -55,10 +55,10 @@ ClassificationResult::~ClassificationResult()
 
 double ClassificationResult::confidence () const
 {
-    return scores.get(classno);
+  return scores.get ( classno );
 }
-	
+
 bool ClassificationResult::ok () const
 {
-    return ( rejection_status == REJECTION_NONE );
+  return ( rejection_status == REJECTION_NONE );
 }

+ 60 - 63
cbaselib/ClassificationResult.h

@@ -1,6 +1,6 @@
-/** 
+/**
 * @file ClassificationResult.h
-* @brief classification result data (probabilities, most probable class, rejection status, ...) 
+* @brief classification result data (probabilities, most probable class, rejection status, ...)
 * @author Erik Rodner
 * @date 02/13/2008
 
@@ -14,9 +14,9 @@
 
 #include <string>
 #include <map>
-#include "core/vector/SparseVector.h"
+#include "core/vector/SparseVectorT.h"
 #include "vislearning/math/mathbase/FullVector.h"
-  
+
 
 namespace OBJREC {
 
@@ -24,66 +24,63 @@ namespace OBJREC {
 class ClassificationResult
 {
 
-    public:
-
-	/** rejection types */
-	enum {
-	    REJECTION_FEATURE = 0,
-	    REJECTION_CLASSIFIER,
-	    REJECTION_MISC,
-	    REJECTION_NONE,
-	    REJECTION_UNINTIALIZED
-	};
-
-	/** rejection status (selected from enum) */
-	int rejection_status;
-
-	/** std::vector consisting of scores for each class 
-	    @remark no guaranteed probabilities
-	    low scores means low probability for this class
-	*/
-	FullVector scores;
-
-	/** most important part: class number of classification result,
-	    most probable class */
-	int classno;
-
-	/** evil workaround: ground truth class number (useful within ClassificationResults)
-	    @see testClassification.cpp
-	    @see ClassificationResults
-	*/
-	int classno_groundtruth;
-
-	/** text representation of the most probable class 
-	    @remark has to be set manually !! */
-	std::string classname;
- 
- 	/** uncertainty of the estimate, only available for GP classifiers */
-	double uncertainty;
- 
-	/** simple constructor, create rejected result */
-	ClassificationResult( int rejection_status = REJECTION_UNINTIALIZED, int maxClassNo = 0 );
-      
-	/** result of classification only consists of the most probable
-	    class @p classno and a score of this assigment */
-	ClassificationResult( int classno, double score, int maxClassNo );
-	
-	/** result of classification consists of most probable class @p classno
-	    and a score for each of the other classes */
-	ClassificationResult( int classno, const FullVector & scores );
-
-	/** simple destructor */
-	virtual ~ClassificationResult();
-
-	/** was it rejected ? */
-	bool ok () const;
-
-	/** probability of predicted class */
-	double confidence () const;
-
-     
-};
+  public:
+
+    /** rejection types */
+    enum {
+      REJECTION_FEATURE = 0,
+      REJECTION_CLASSIFIER,
+      REJECTION_MISC,
+      REJECTION_NONE,
+      REJECTION_UNINTIALIZED
+    };
+
+    /** rejection status (selected from enum) */
+    int rejection_status;
+
+    /** std::vector consisting of scores for each class
+        @remark no guaranteed probabilities
+        low scores means low probability for this class
+    */
+    FullVector scores;
+
+    /** most important part: class number of classification result,
+        most probable class */
+    int classno;
+
+    /** evil workaround: ground truth class number (useful within ClassificationResults)
+        @see testClassification.cpp
+        @see ClassificationResults
+    */
+    int classno_groundtruth;
+
+    /** text representation of the most probable class
+        @remark has to be set manually !! */
+    std::string classname;
 
+    /** uncertainty of the estimate, only available for GP classifiers */
+    double uncertainty;
+
+    /** simple constructor, create rejected result */
+    ClassificationResult ( int rejection_status = REJECTION_UNINTIALIZED, int maxClassNo = 0 );
+
+    /** result of classification only consists of the most probable
+        class @p classno and a score of this assigment */
+    ClassificationResult ( int classno, double score, int maxClassNo );
+
+    /** result of classification consists of most probable class @p classno
+        and a score for each of the other classes */
+    ClassificationResult ( int classno, const FullVector & scores );
+
+    /** simple destructor */
+    virtual ~ClassificationResult();
+
+    /** was it rejected ? */
+    bool ok () const;
+
+    /** probability of predicted class */
+    double confidence () const;
+};
 
 } // namespace
 

+ 107 - 107
cbaselib/Example.h

@@ -1,7 +1,7 @@
 #ifndef EXAMPLEINCLUDE
 #define EXAMPLEINCLUDE
 
-/** 
+/**
 * @file Example.h
 * @brief data caching of several feature images and many more
 * @author Erik Rodner
@@ -15,121 +15,121 @@ namespace OBJREC {
 /** Cached example with window information */
 class Example
 {
-    public:
-	/** weight of example */
-	double weight;
-
-	/** complete image example */
-	CachedExample *ce;
-
-	/** x position of window */
-	long long int x;
-	/** y position of window */
-	long long int y;
-
-	/** width of window */
-	int width;
-	/** height of window */
-	int height;
-	
-	//! if some examples are related, they have the same position
-	int position;
-	
-	//! scale of the feature
-	double scale;
-	
-	/** evil workaround: store simple vector example */
-	NICE::Vector *vec;
-	
-	/** evil workaround: store sparse vector example */
-	NICE::SparseVector *svec;
-
-	/** simple constructor, initialize everything with 0
-	 */
-	Example();
-
-	/** constructor using a window covering the whole image
-	    @param ce associated image data
-	*/
-	Example ( CachedExample *_ce );
-
-	/** constructor 
-	    @param ce associated image data
-	    @param x x position of window
-	    @param y y position of window
-	    @param weight weight of example
-	*/
-	Example ( CachedExample *ce, int x, int y, double weight = 1.0 );
-	
-	/** constructor 
-	    @param ce associated image data
-	    @param x x position of window
-	    @param y y position of window
-	    @param weight weight of example
-	*/
-	Example ( CachedExample *ce, int x, int y, int width, int height, double weight = 1.0 );
-
-	/** evil workaround: simple constructors for std::vector examples 
-	    @param vec simple feature vector
-	    @param weight optional weight
-	*/
-	Example ( NICE::Vector *vec, double weight = 1.0 );
-
-	/**
-	 * copy constructor
-	 * @param ex input Example
-	 */
-	Example ( const Example &ex);
-	
-	/**
-	 * copies the values of ex in this example
-	 * @param ex input Example
-	 */
-	void copy ( const Example &ex);
-	
-	/** destructor */
-	~Example ();
-
-	/** delete all data associated with this example
-	    (sparse vector, vector, cached example, etc.) */
-	void clean ();
-	
-	/**
-	 * load from file (warning: no cachedexamples supported yet
-	 * @param is file
-	 * @param format 
-	 */
-	void restore (std::istream & is, int format = 0);
-	
-	
-	/**
-	 * write to file (warning: no cachedexamples supported yet
-	 * @param is file
-	 * @param format 
-	 */
-	void store (std::ostream & os, int format = 0) const;
+  public:
+    /** weight of example */
+    double weight;
+
+    /** complete image example */
+    CachedExample *ce;
+
+    /** x position of window */
+    long long int x;
+    /** y position of window */
+    long long int y;
+
+    /** width of window */
+    int width;
+    /** height of window */
+    int height;
+
+    //! if some examples are related, they have the same position
+    int position;
+
+    //! scale of the feature
+    double scale;
+
+    /** evil workaround: store simple vector example */
+    NICE::Vector *vec;
+
+    /** evil workaround: store sparse vector example */
+    NICE::SparseVector *svec;
+
+    /** simple constructor, initialize everything with 0
+     */
+    Example();
+
+    /** constructor using a window covering the whole image
+        @param ce associated image data
+    */
+    Example ( CachedExample *_ce );
+
+    /** constructor
+        @param ce associated image data
+        @param x x position of window
+        @param y y position of window
+        @param weight weight of example
+    */
+    Example ( CachedExample *ce, int x, int y, double weight = 1.0 );
+
+    /** constructor
+        @param ce associated image data
+        @param x x position of window
+        @param y y position of window
+        @param weight weight of example
+    */
+    Example ( CachedExample *ce, int x, int y, int width, int height, double weight = 1.0 );
+
+    /** evil workaround: simple constructors for std::vector examples
+        @param vec simple feature vector
+        @param weight optional weight
+    */
+    Example ( NICE::Vector *vec, double weight = 1.0 );
+
+    /**
+     * copy constructor
+     * @param ex input Example
+     */
+    Example ( const Example &ex );
+
+    /**
+     * copies the values of ex in this example
+     * @param ex input Example
+     */
+    void copy ( const Example &ex );
+
+    /** destructor */
+    ~Example ();
+
+    /** delete all data associated with this example
+        (sparse vector, vector, cached example, etc.) */
+    void clean ();
+
+    /**
+     * load from file (warning: no cachedexamples supported yet
+     * @param is file
+     * @param format
+     */
+    void restore ( std::istream & is, int format = 0 );
+
+
+    /**
+     * write to file (warning: no cachedexamples supported yet
+     * @param is file
+     * @param format
+     */
+    void store ( std::ostream & os, int format = 0 ) const;
 };
 
-/** labeled pair of Example 
+/** labeled pair of Example
     @see Example */
 class Examples : public std::vector< std::pair<int, Example> >
 {
-    public:
-		std::string filename;
+  public:
+    std::string filename;
 
-    inline int getMaxClassNo () const 
+    inline int getMaxClassNo () const
     {
-		int maxClassno = -1;
-		for ( const_iterator i = begin(); i != end(); i++ )
-			if ( i->first > maxClassno )
-			maxClassno = i->first;
-		
-		return maxClassno;
+      int maxClassno = -1;
+      for ( const_iterator i = begin(); i != end(); i++ )
+        if ( i->first > maxClassno )
+          maxClassno = i->first;
+
+      return maxClassno;
     }
 
-	/** delete all data associated with all examples
-	    (sparse vector, vector, cached example, etc.) */
-	void clean ();
+    /** delete all data associated with all examples
+        (sparse vector, vector, cached example, etc.) */
+    void clean ();
 };
 
 

+ 73 - 62
cbaselib/ImageInfo.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file ImageInfo.h
 * @brief localization info + image filename + ?
 * @author Erik Rodner
@@ -10,7 +10,7 @@
 #include "core/image/ImageT.h"
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
- 
+
 #include "vislearning/cbaselib/Polygon.h"
 #include "vislearning/cbaselib/BoundingBox.h"
 #include "vislearning/cbaselib/CategoryInfo.h"
@@ -25,71 +25,82 @@ class QDomElement;
 
 #endif //NICE_USELIB_QT4_XML
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** localization info + image filename + ? */
 class ImageInfo
 {
 
-    protected:
-	std::string imagefn;
-	LocalizationResult *lr;
-	bool localization_info;
-
-	#ifdef NICE_USELIB_QT4_XML
-	
-	Polygon	polyFromData(QString *aPolyData);
-	BoundingBox BBoxFromData(QString *aBBoxData);
-	void loadLegendFromElement(QDomElement *anElement);
-	bool loadCategoryInfo(QDomElement *anElement);
-	ImageT< unsigned int >	imageTFromData(
-		const int &aWidth,
-		const int &aHeight,
-		QString *aPureData
-	);
-
-	#endif //NICE_USELIB_QT4_XML
-
-    public:
-  
-	/** simple constructor */
-	ImageInfo( const std::string & _imagefn, LocalizationResult *_lr ) : 
-	    imagefn(_imagefn), lr(_lr), localization_info(true) {};
-	
-	ImageInfo() {};
-      
-	ImageInfo( const std::string & _imagefn ) : 
-	    imagefn(_imagefn), lr(NULL), localization_info(false) {};
-
-	/** simple destructor */
-	virtual ~ImageInfo();
-
-	const std::string & img () const { return imagefn; };
-	const LocalizationResult *localization () const { assert(localization_info); return lr; };
-	bool hasLocalizationInfo () const { return localization_info; };
-	
-	bool loadImageInfo(const std::string &aFilename);
-	
-	const std::list< CategoryInfo > * labels() const;
-	const std::list< BoundingBox > * bboxes() const;
-	const std::list< Polygon > * polys() const;
-	ImageT< unsigned int > labeledImage() const;
-	std::string tags() const;
-	std::string imagePath() const;
-	std::string imageDescription() const;
-	std::string segmentedImagePath() const;
-
-    private:
-	std::list< CategoryInfo > labels_;
-	std::list< BoundingBox > bboxes_;
-	std::list< Polygon > polys_;
-	ImageT< unsigned int > labeled_image_;
-	//std::list< std::string > tags_;
-	std::string tags_;
-	std::string image_path_;
-	std::string image_description_;
-	std::string segmented_image_path_;
-	
+  protected:
+    std::string imagefn;
+    LocalizationResult *lr;
+    bool localization_info;
+
+#ifdef NICE_USELIB_QT4_XML
+
+    Polygon polyFromData ( QString *aPolyData );
+    BoundingBox BBoxFromData ( QString *aBBoxData );
+    void loadLegendFromElement ( QDomElement *anElement );
+    bool loadCategoryInfo ( QDomElement *anElement );
+    NICE::ImageT< unsigned int > imageTFromData (
+      const int &aWidth,
+      const int &aHeight,
+      QString *aPureData
+    );
+
+#endif //NICE_USELIB_QT4_XML
+
+  public:
+
+    /** simple constructor */
+    ImageInfo ( const std::string & _imagefn, LocalizationResult *_lr ) :
+        imagefn ( _imagefn ), lr ( _lr ), localization_info ( true ) {};
+
+    ImageInfo() {};
+
+    ImageInfo ( const std::string & _imagefn ) :
+        imagefn ( _imagefn ), lr ( NULL ), localization_info ( false ) {};
+
+    /** simple destructor */
+    virtual ~ImageInfo();
+
+    const std::string & img () const
+    {
+      return imagefn;
+    };
+    const LocalizationResult *localization () const
+    {
+      assert ( localization_info );
+      return lr;
+    };
+    bool hasLocalizationInfo () const
+    {
+      return localization_info;
+    };
+
+    bool loadImageInfo ( const std::string &aFilename );
+
+    const std::list< CategoryInfo > * labels() const;
+    const std::list< BoundingBox > * bboxes() const;
+    const std::list< Polygon > * polys() const;
+    NICE::ImageT< unsigned int > labeledImage() const;
+    std::string tags() const;
+    std::string imagePath() const;
+    std::string imageDescription() const;
+    std::string segmentedImagePath() const;
+
+  private:
+    std::list< CategoryInfo > labels_;
+    std::list< BoundingBox > bboxes_;
+    std::list< Polygon > polys_;
+    NICE::ImageT< unsigned int > labeled_image_;
+    //std::list< std::string > tags_;
+    std::string tags_;
+    std::string image_path_;
+    std::string image_description_;
+    std::string segmented_image_path_;
+
 };
 
 

+ 317 - 317
cbaselib/LabeledSet.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LabeledSet.cpp
 * @brief Labeled set of vectors
 * @author Erik Rodner
@@ -23,93 +23,93 @@ using namespace std;
 using namespace NICE;
 
 
-LabeledSet::LabeledSet ( bool _selection ) : selection(_selection)
+LabeledSet::LabeledSet ( bool _selection ) : selection ( _selection )
 {
 }
-	
+
 LabeledSet::~LabeledSet ()
 {
-    //This is a big problem when using selections
-    //clear();
-    //fprintf (stderr, "LabeledSet: destructor (FIXME: memory leak)\n");
+  //This is a big problem when using selections
+  //clear();
+  //fprintf (stderr, "LabeledSet: destructor (FIXME: memory leak)\n");
 }
 
 int LabeledSet::count ( int classno ) const
 {
-    const_iterator i = find(classno);
-    return ( i == end() ) ? 0 : i->second.size();
+  const_iterator i = find ( classno );
+  return ( i == end() ) ? 0 : i->second.size();
 }
 
 int LabeledSet::count () const
 {
-    int mycount = 0;
-    for ( const_iterator i = begin() ; i != end() ; i++ )
-    {
-		mycount += i->second.size();
-    }
-    return mycount;
+  int mycount = 0;
+  for ( const_iterator i = begin() ; i != end() ; i++ )
+  {
+    mycount += i->second.size();
+  }
+  return mycount;
 }
 
 void LabeledSet::clear ()
 {
-    if ( !selection ) 
+  if ( !selection )
+  {
+    for ( Permutation::const_iterator i  = insertOrder.begin();
+          i != insertOrder.end();
+          i++ )
     {
-		for ( Permutation::const_iterator i  = insertOrder.begin(); 
-						  i != insertOrder.end();
-						  i++ )
-		{
-			const ImageInfo *s = i->second;
-			delete s;
-		}
+      const ImageInfo *s = i->second;
+      delete s;
     }
-    
-    std::map< int, vector<ImageInfo *> >::clear();
+  }
+
+  std::map< int, vector<ImageInfo *> >::clear();
 }
 
 void LabeledSet::add ( int classno, ImageInfo *x )
 {
-    if ( selection ) {
-		fprintf (stderr, "Operation not available for selections !\n");
-		exit(-1);
-    }
-
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<ImageInfo *>();
-		i = find(classno);
-    }
-    i->second.push_back ( x ); 
-    insertOrder.push_back ( ElementPointer ( classno, x ) );
+  if ( selection ) {
+    fprintf ( stderr, "Operation not available for selections !\n" );
+    exit ( -1 );
+  }
+
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<ImageInfo *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( x );
+  insertOrder.push_back ( ElementPointer ( classno, x ) );
 }
-	
+
 void LabeledSet::getPermutation ( Permutation & permutation ) const
 {
-    permutation = Permutation ( insertOrder );
+  permutation = Permutation ( insertOrder );
 }
 
 void LabeledSet::add_reference ( int classno, ImageInfo *pointer )
 {
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<ImageInfo *>();
-		i = find(classno);
-    }
-    i->second.push_back ( pointer ); 
-    insertOrder.push_back ( ElementPointer ( classno, pointer ) );
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<ImageInfo *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( pointer );
+  insertOrder.push_back ( ElementPointer ( classno, pointer ) );
 }
 
 void LabeledSet::getClasses ( std::vector<int> & classes ) const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-		classes.push_back ( i->first );
+  for ( const_iterator i = begin(); i != end(); i++ )
+    classes.push_back ( i->first );
 }
 
 void LabeledSet::printInformation () const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-    {
-	cerr << "class " << i->first << ": " << i->second.size() << endl;
-    }
+  for ( const_iterator i = begin(); i != end(); i++ )
+  {
+    cerr << "class " << i->first << ": " << i->second.size() << endl;
+  }
 }
 
 
@@ -118,353 +118,353 @@ void LabeledSet::printInformation () const
 *************************************/
 
 
-LabeledSetVector::LabeledSetVector (bool _selection) : selection(_selection)
+LabeledSetVector::LabeledSetVector ( bool _selection ) : selection ( _selection )
 {}
-	
+
 LabeledSetVector::~LabeledSetVector ()
 {
-    // FIXME: THIS is a big problem with selections !!!
-    //clear();
+  // FIXME: THIS is a big problem with selections !!!
+  //clear();
 }
 
 int LabeledSetVector::dimension () const
 {
-    if ( insertOrder.size() <= 0 ) return -1;
-    return (*(begin()->second.begin()))->size();
-    //insertOrder[0].second->size();
+  if ( insertOrder.size() <= 0 ) return -1;
+  return ( * ( begin()->second.begin() ) )->size();
+  //insertOrder[0].second->size();
 }
 
-void LabeledSetVector::restore (istream & is, int format)
+void LabeledSetVector::restore ( istream & is, int format )
 {
-    if ( format == FILEFORMAT_RAW )
-		restoreRAW ( is );
-    else
-		restoreASCII ( is, format );
+  if ( format == FILEFORMAT_RAW )
+    restoreRAW ( is );
+  else
+    restoreASCII ( is, format );
 }
 
-void LabeledSetVector::restoreASCII (istream & is, int format)
+void LabeledSetVector::restoreASCII ( istream & is, int format )
 {
-    const int bufsize = 1024*1024;
-    char *buf = new char[bufsize];
-    std::string buf_s;
+  const int bufsize = 1024 * 1024;
+  char *buf = new char[bufsize];
+  std::string buf_s;
+
+  vector<string> elements;
+  vector<string> pair;
 
-    vector<string> elements;
-    vector<string> pair;
+  // maximal dimension of all feature vectors;
+  int dataset_dimension = -numeric_limits<int>::max();
 
-	// maximal dimension of all feature vectors;
-	int dataset_dimension = -numeric_limits<int>::max();
+  while ( ! is.eof() )
+  {
+    elements.clear();
+    int classno;
 
-    while (! is.eof())
+    if ( ! ( is >> classno ) ) {
+      break;
+    }
+
+    is.get ( buf, bufsize );
+    buf_s = buf;
+
+    if ( buf_s.size() <= 0 )
+      break;
+
+    StringTools::split ( buf_s, ' ', elements );
+
+    if ( elements.size() <= 1 )
+      break;
+
+    int dimension = - numeric_limits<int>::max();
+    if ( format == FILEFORMAT_INDEX_SPARSE_ONE )
     {
-		elements.clear();
-		int classno;
-		
-		if ( ! (is >> classno) ) {
-			break;
-		}
-
-		is.get ( buf, bufsize );
-		buf_s = buf;
-
-		if ( buf_s.size() <= 0 ) 
-			break;
-
-		StringTools::split ( buf_s, ' ', elements );
-
-		if ( elements.size() <= 1 )
-			break;
-		
-		int dimension = - numeric_limits<int>::max();
-		if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) 
-		{
-			// in this format we have to determine the maximum index
-			for ( vector<string>::const_iterator i  = elements.begin()+1; 
-							 i != elements.end();
-							 i++ ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() != 2 ) continue;
-
-				int index = atoi(pair[0].c_str());
-				
-				if ( index > dimension )
-					dimension = index;
-			}
-
-			if ( dimension > dataset_dimension )
-				dataset_dimension = dimension;
-
-			
-		} else {
-			// skip first element because of white space
-			dimension = elements.size()-1;
-		}
-
-
-		NICE::Vector vec ( dimension, 0.0 );
-		size_t l = 0;
-
-		// skip first element because of white space
-		for ( vector<string>::const_iterator i  = elements.begin()+1; 
-							 i != elements.end();
-							 i++, l++ )
-		{
-			if ( format == FILEFORMAT_INDEX ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() == 2 ) {
-					double val = atof ( pair[1].c_str() );
-					vec[l] = val;
-				}
-			} else if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) 
-			{
-				pair.clear();
-				StringTools::split ( *i, ':', pair );
-				if ( pair.size() == 2 ) {
-					double val = atof ( pair[1].c_str() );
-					int index = atoi ( pair[0].c_str() ) - 1;
-					vec[index] = val;
-				}
-			} else {
-				vec[l] = atof( i->c_str() );
-			}
-		}
-		add( classno, vec );
+      // in this format we have to determine the maximum index
+      for ( vector<string>::const_iterator i  = elements.begin() + 1;
+            i != elements.end();
+            i++ )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() != 2 ) continue;
+
+        int index = atoi ( pair[0].c_str() );
+
+        if ( index > dimension )
+          dimension = index;
+      }
+
+      if ( dimension > dataset_dimension )
+        dataset_dimension = dimension;
+
+
+    } else {
+      // skip first element because of white space
+      dimension = elements.size() - 1;
     }
-    delete [] buf;
-
-	if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) {
-		// we have to resize all feature vectors of the dataset to dataset_dimension
-		for ( LabeledSetVector::iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++)
-			for ( vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); 
-									 jLOOP_ALL != iLOOP_ALL->second.end(); 
-									 jLOOP_ALL++ )
-			{
-				NICE::Vector *x = (*jLOOP_ALL);
-
-				uint old_dimension = x->size();
-
-				// resize the vector to the dataset dimension
-				x->resize(dataset_dimension);
-				
-				// set all elements to zero, which are new after the resize operation
-				for ( uint k = old_dimension; k < x->size(); k++ )
-					(*x)[k] = 0.0;
-			}
-	}
-}
 
-void LabeledSetVector::store (ostream & os, int format) const
-{
-    for ( Permutation::const_iterator i  = insertOrder.begin();
-				      i != insertOrder.end();
-				      i++ )
+
+    NICE::Vector vec ( dimension, 0.0 );
+    size_t l = 0;
+
+    // skip first element because of white space
+    for ( vector<string>::const_iterator i  = elements.begin() + 1;
+          i != elements.end();
+          i++, l++ )
     {
-		int classno = i->first;
-		const NICE::Vector & x = *(i->second);
-		
-		storeElement ( os, classno, x, format );
+      if ( format == FILEFORMAT_INDEX )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() == 2 ) {
+          double val = atof ( pair[1].c_str() );
+          vec[l] = val;
+        }
+      } else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )
+      {
+        pair.clear();
+        StringTools::split ( *i, ':', pair );
+        if ( pair.size() == 2 ) {
+          double val = atof ( pair[1].c_str() );
+          int index = atoi ( pair[0].c_str() ) - 1;
+          vec[index] = val;
+        }
+      } else {
+        vec[l] = atof ( i->c_str() );
+      }
     }
+    add ( classno, vec );
+  }
+  delete [] buf;
+
+  if ( format == FILEFORMAT_INDEX_SPARSE_ONE ) {
+    // we have to resize all feature vectors of the dataset to dataset_dimension
+    for ( LabeledSetVector::iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++ )
+      for ( vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin();
+            jLOOP_ALL != iLOOP_ALL->second.end();
+            jLOOP_ALL++ )
+      {
+        NICE::Vector *x = ( *jLOOP_ALL );
+
+        uint old_dimension = x->size();
+
+        // resize the vector to the dataset dimension
+        x->resize ( dataset_dimension );
+
+        // set all elements to zero, which are new after the resize operation
+        for ( uint k = old_dimension; k < x->size(); k++ )
+          ( *x ) [k] = 0.0;
+      }
+  }
+}
+
+void LabeledSetVector::store ( ostream & os, int format ) const
+{
+  for ( Permutation::const_iterator i  = insertOrder.begin();
+        i != insertOrder.end();
+        i++ )
+  {
+    int classno = i->first;
+    const NICE::Vector & x = * ( i->second );
+
+    storeElement ( os, classno, x, format );
+  }
 }
 
 void LabeledSetVector::storeElement ( ostream & os, int classno, const NICE::Vector & x, int format )
 {
-    if ( format != FILEFORMAT_RAW ) {
-		os << classno << " ";
-		for ( size_t k = 0 ; k < x.size() ; k++ )
-		{
-			if ( format == FILEFORMAT_INDEX )
-				os << k+1 << ":" << x[k];
-			else if ( format == FILEFORMAT_NOINDEX )  
-				os << x[k];
-			else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )  {
-				if ( x[k] != 0.0 ) 
-					os << k+1 << ":" << x[k];
-			}
-
-			if ( k != x.size() )
-				os << " ";
-		}
-		os << endl;
-	} else {
-		const double *data = x.getDataPointer();
-		int dimension = x.size();
-
-		os.write ( (char *)&classno, sizeof(int) );
-		os.write ( (char *)&dimension, sizeof(int) );
-		os.write ( (char *)data, sizeof(double)*dimension );
+  if ( format != FILEFORMAT_RAW ) {
+    os << classno << " ";
+    for ( size_t k = 0 ; k < x.size() ; k++ )
+    {
+      if ( format == FILEFORMAT_INDEX )
+        os << k + 1 << ":" << x[k];
+      else if ( format == FILEFORMAT_NOINDEX )
+        os << x[k];
+      else if ( format == FILEFORMAT_INDEX_SPARSE_ONE )  {
+        if ( x[k] != 0.0 )
+          os << k + 1 << ":" << x[k];
+      }
+
+      if ( k != x.size() )
+        os << " ";
     }
+    os << endl;
+  } else {
+    const double *data = x.getDataPointer();
+    int dimension = x.size();
+
+    os.write ( ( char * ) &classno, sizeof ( int ) );
+    os.write ( ( char * ) &dimension, sizeof ( int ) );
+    os.write ( ( char * ) data, sizeof ( double ) *dimension );
+  }
 }
 
-void LabeledSetVector::restoreRAW (istream & is)
+void LabeledSetVector::restoreRAW ( istream & is )
 {
-    while (! is.eof())
-    {
-		int classno;
-		int dimension;
-
-		is.read ( (char *)&classno, sizeof(int) );
-		if ( is.gcount() != sizeof(int) )
-			return;
-
-		is.read ( (char *)&dimension, sizeof(int) );
-		if ( is.gcount() != sizeof(int) )
-			return;
-
-		NICE::Vector vec;
-
-		try {
-			vec.resize(dimension);
-		} catch ( std::bad_alloc ) {
-			fthrow(IOException, "Unable to allocate a vector with size " << dimension << "." << endl 
-					<< "(debug: class " << classno << " ; " << "sizeof(int) = " << 8*sizeof(int) << " Bit ; " << endl
-					<< "elements read = " << count() << " )" << endl );
-		}
-		double *data = vec.getDataPointer();
-
-		is.read ( (char *)data, sizeof(double)*dimension );
-		if ( (int)is.gcount() != (int)sizeof(double)*dimension )
-			return;
-
-		for ( int k = 0 ; k < dimension ; k++ )
-			if ( isnan(data[k]) ) {
-				cerr << "WARNING: nan's found !!" << endl;
-				data[k] = 0.0;
-			}
-		
-		add( classno, vec );
+  while ( ! is.eof() )
+  {
+    int classno;
+    int dimension;
+
+    is.read ( ( char * ) &classno, sizeof ( int ) );
+    if ( is.gcount() != sizeof ( int ) )
+      return;
+
+    is.read ( ( char * ) &dimension, sizeof ( int ) );
+    if ( is.gcount() != sizeof ( int ) )
+      return;
+
+    NICE::Vector vec;
+
+    try {
+      vec.resize ( dimension );
+    } catch ( std::bad_alloc ) {
+      fthrow ( IOException, "Unable to allocate a vector with size " << dimension << "." << endl
+               << "(debug: class " << classno << " ; " << "sizeof(int) = " << 8*sizeof ( int ) << " Bit ; " << endl
+               << "elements read = " << count() << " )" << endl );
     }
+    double *data = vec.getDataPointer();
+
+    is.read ( ( char * ) data, sizeof ( double ) *dimension );
+    if ( ( int ) is.gcount() != ( int ) sizeof ( double ) *dimension )
+      return;
+
+    for ( int k = 0 ; k < dimension ; k++ )
+      if ( isnan ( data[k] ) ) {
+        cerr << "WARNING: nan's found !!" << endl;
+        data[k] = 0.0;
+      }
+
+    add ( classno, vec );
+  }
 }
 
 LabeledSetVector::ElementPointer LabeledSetVector::pickRandomSample () const
 {
-    if ( insertOrder.size() <= 0 ) {
-		fprintf (stderr, "LabeledSet::pickRandomSample: failure !\n");
-		exit(-1);
-    }
-    
-    int selection = rand() % insertOrder.size();
-    return insertOrder[selection];
+  if ( insertOrder.size() <= 0 ) {
+    fprintf ( stderr, "LabeledSet::pickRandomSample: failure !\n" );
+    exit ( -1 );
+  }
+
+  int selection = rand() % insertOrder.size();
+  return insertOrder[selection];
 }
 
 int LabeledSetVector::count ( int classno ) const
 {
-    const_iterator i = find(classno);
-    return ( i == end() ) ? 0 : i->second.size();
+  const_iterator i = find ( classno );
+  return ( i == end() ) ? 0 : i->second.size();
 }
 
 int LabeledSetVector::count () const
 {
-    int mycount = 0;
-    for ( const_iterator i = begin() ; i != end() ; i++ )
-		mycount += i->second.size();
-    return mycount;
+  int mycount = 0;
+  for ( const_iterator i = begin() ; i != end() ; i++ )
+    mycount += i->second.size();
+  return mycount;
 }
 
 int LabeledSetVector::pickRandomSample ( int classno, ElementPointer & i ) const
 {
-    const_iterator j = find(classno);
-    if ( j == end() ) return -1;
+  const_iterator j = find ( classno );
+  if ( j == end() ) return -1;
 
-    const vector<Vector *> & l = j->second;
-    int num = rand() % l.size();
+  const vector<Vector *> & l = j->second;
+  int num = rand() % l.size();
 
-    i.first = classno;
-    i.second = l[num];
+  i.first = classno;
+  i.second = l[num];
 
-    return classno;
+  return classno;
 }
 
 void LabeledSetVector::clear ()
 {
-    if ( ! selection ) {
-		for ( Permutation::const_iterator i  = insertOrder.begin(); 
-						  i != insertOrder.end();
-						  i++ )
-		{
-			const NICE::Vector *s = i->second;
-			delete s;
-		}
-		insertOrder.clear();
+  if ( ! selection ) {
+    for ( Permutation::const_iterator i  = insertOrder.begin();
+          i != insertOrder.end();
+          i++ )
+    {
+      const NICE::Vector *s = i->second;
+      delete s;
     }
+    insertOrder.clear();
+  }
 
-    std::map< int, vector<Vector *> >::clear();
+  std::map< int, vector<Vector *> >::clear();
 }
 
 void LabeledSetVector::add ( int classno, const NICE::Vector & x )
 {
-    if ( selection ) {
-		fprintf (stderr, "Add operation not available for selections !\n");
-		exit(-1);
-    }
-
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<Vector *>();
-		i = find(classno);
-    }
-    NICE::Vector *xp = new Vector(x);
-
-    i->second.push_back ( xp ); 
-    insertOrder.push_back ( ElementPointer ( classno, xp ) );
+  if ( selection ) {
+    fprintf ( stderr, "Add operation not available for selections !\n" );
+    exit ( -1 );
+  }
+
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<Vector *>();
+    i = find ( classno );
+  }
+  NICE::Vector *xp = new Vector ( x );
+
+  i->second.push_back ( xp );
+  insertOrder.push_back ( ElementPointer ( classno, xp ) );
 }
-    
+
 void LabeledSetVector::getPermutation ( Permutation & permutation ) const
 {
-    permutation = Permutation ( insertOrder );
+  permutation = Permutation ( insertOrder );
 }
 
 void LabeledSetVector::add_reference ( int classno, NICE::Vector *pointer )
 {
-    iterator i = find(classno);
-    if ( i == end() ) {
-		operator[](classno) = vector<Vector *>();
-		i = find(classno);
-    }
-    i->second.push_back ( pointer ); 
-    insertOrder.push_back ( ElementPointer ( classno, pointer ) );
+  iterator i = find ( classno );
+  if ( i == end() ) {
+    operator[] ( classno ) = vector<Vector *>();
+    i = find ( classno );
+  }
+  i->second.push_back ( pointer );
+  insertOrder.push_back ( ElementPointer ( classno, pointer ) );
 }
-	
+
 void LabeledSetVector::getClasses ( std::vector<int> & classes ) const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-	classes.push_back ( i->first );
+  for ( const_iterator i = begin(); i != end(); i++ )
+    classes.push_back ( i->first );
 }
-	
+
 void LabeledSetVector::printInformation () const
 {
-    for ( const_iterator i = begin(); i != end(); i++ )
-    {
-		cerr << "class " << i->first << ": " << i->second.size() << endl;
-    }
+  for ( const_iterator i = begin(); i != end(); i++ )
+  {
+    cerr << "class " << i->first << ": " << i->second.size() << endl;
+  }
 }
-	
+
 int LabeledSetVector::getMaxClassno() const
 {
-    int maxclassno = 0;
+  int maxclassno = 0;
 
-    for ( const_iterator i = begin(); i != end(); i++ )
-		if ( i->first > maxclassno ) 
-			maxclassno = i->first;
+  for ( const_iterator i = begin(); i != end(); i++ )
+    if ( i->first > maxclassno )
+      maxclassno = i->first;
 
-    return maxclassno;
+  return maxclassno;
 }
 
 void LabeledSetVector::getFlatRepresentation ( VVector & vecSet, NICE::Vector & vecSetLabels ) const
 {
-	int k = 0;
-	vecSetLabels.resize(count());
-	for ( LabeledSetVector::const_iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++)
-		for ( vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); 
-								 jLOOP_ALL != iLOOP_ALL->second.end(); 
-								 jLOOP_ALL++,k++ )
-		{
-			const NICE::Vector & (x) = *(*jLOOP_ALL);
-			vecSet.push_back ( x );
-			vecSetLabels[k] = iLOOP_ALL->first;
-		}
+  int k = 0;
+  vecSetLabels.resize ( count() );
+  for ( LabeledSetVector::const_iterator iLOOP_ALL = begin() ; iLOOP_ALL != end() ; iLOOP_ALL++ )
+    for ( vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin();
+          jLOOP_ALL != iLOOP_ALL->second.end();
+          jLOOP_ALL++, k++ )
+    {
+      const NICE::Vector & ( x ) = * ( *jLOOP_ALL );
+      vecSet.push_back ( x );
+      vecSetLabels[k] = iLOOP_ALL->first;
+    }
 
 }
 

+ 107 - 95
cbaselib/LabeledSet.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LabeledSet.h
 * @brief Labeled set of vectors
 * @author Erik Rodner
@@ -18,143 +18,155 @@
 #include "ImageInfo.h"
 
 #define LOOP_ALL(ls) for(LabeledSetVector::const_iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<NICE::Vector *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH(classno,x) int (classno) = iLOOP_ALL->first; \
-			const NICE::Vector & (x) = *(*jLOOP_ALL);
-	
+  const NICE::Vector & (x) = *(*jLOOP_ALL);
+
 #define LOOP_ALL_NONCONST(ls) for(LabeledSetVector::iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<NICE::Vector *>::iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH_NONCONST(classno,x) int (classno) = iLOOP_ALL->first; \
-			NICE::Vector & (x) = *(*jLOOP_ALL);
-				
+  NICE::Vector & (x) = *(*jLOOP_ALL);
+
 #define LOOP_ALL_S(ls) for(LabeledSet::const_iterator iLOOP_ALL = (ls).begin() ; iLOOP_ALL != (ls).end() ; iLOOP_ALL++) \
-				    for ( std::vector<ImageInfo *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
-									 jLOOP_ALL != iLOOP_ALL->second.end(); \
-									 jLOOP_ALL++ )
+    for ( std::vector<ImageInfo *>::const_iterator jLOOP_ALL = iLOOP_ALL->second.begin(); \
+          jLOOP_ALL != iLOOP_ALL->second.end(); \
+          jLOOP_ALL++ )
 #define EACH_S(classno,x) int (classno) = iLOOP_ALL->first; \
-			const std::string & (x) = (*jLOOP_ALL)->img();
+  const std::string & (x) = (*jLOOP_ALL)->img();
 
 #define EACH_INFO(classno,x) int (classno) = iLOOP_ALL->first; \
-			const ImageInfo & (x) = *(*jLOOP_ALL);
+  const ImageInfo & (x) = *(*jLOOP_ALL);
 
 
 namespace OBJREC {
 
-class LabeledSet : 
-	public std::map< int, std::vector<ImageInfo *> >
+class LabeledSet :
+      public std::map< int, std::vector<ImageInfo *> >
 {
-    public:
-	typedef std::vector<std::string *> ElementIterator;
-	typedef std::pair<size_t, const ImageInfo *> ElementPointer;
-	typedef std::vector< ElementPointer > Permutation;
+  public:
+    typedef std::vector<std::string *> ElementIterator;
+    typedef std::pair<size_t, const ImageInfo *> ElementPointer;
+    typedef std::vector< ElementPointer > Permutation;
+
+  private:
+    bool selection;
 
-    private:
-	bool selection;
+    Permutation insertOrder;
 
-	Permutation insertOrder;
+  public:
 
-    public:
+    void add_reference ( int classno, ImageInfo *pointer );
 
-	void add_reference ( int classno, ImageInfo *pointer );
+    LabeledSet ( bool selection = false );
+    ~LabeledSet ();
 
-	LabeledSet ( bool selection = false );
-	~LabeledSet ();
+    int numClasses () const
+    {
+      return size();
+    }
 
-	int numClasses () const
-	{   return size();   }
+    int count ( int classno ) const;
+    int count () const;
 
-	int count ( int classno ) const;
-	int count () const;
-	
-	void clear ();
+    void clear ();
 
-	void add ( int classno, ImageInfo *x );
+    void add ( int classno, ImageInfo *x );
 
-	void getPermutation ( Permutation & permutation ) const; 
-	void getClasses ( std::vector<int> & classes ) const; 
+    void getPermutation ( Permutation & permutation ) const;
+    void getClasses ( std::vector<int> & classes ) const;
 
-	void printInformation () const;
+    void printInformation () const;
 
-	friend class LabeledSetSelection<LabeledSet>;
+    friend class LabeledSetSelection<LabeledSet>;
 };
 
 
 /** simple labeled set of vectors as a specialization of std::map<> */
-class LabeledSetVector : 
-	public std::map< int, std::vector<NICE::Vector *> >, 
-	public NICE::Persistent
+class LabeledSetVector :
+      public std::map< int, std::vector<NICE::Vector *> >,
+      public NICE::Persistent
 {
-    public:
-	typedef std::vector<NICE::Vector *> ElementIterator;
-	typedef std::pair<int, const NICE::Vector *> ElementPointer;
-	typedef std::vector< ElementPointer > Permutation;	
-
-	enum {
-	    FILEFORMAT_INDEX = 0,
-	    FILEFORMAT_NOINDEX = 1,
-	    FILEFORMAT_RAW = 2,
-	    FILEFORMAT_INDEX_SPARSE_ONE = 3
-	};
-    
-    private:
-	bool selection;
+  public:
+    typedef std::vector<NICE::Vector *> ElementIterator;
+    typedef std::pair<int, const NICE::Vector *> ElementPointer;
+    typedef std::vector< ElementPointer > Permutation;
+
+    enum {
+      FILEFORMAT_INDEX = 0,
+      FILEFORMAT_NOINDEX = 1,
+      FILEFORMAT_RAW = 2,
+      FILEFORMAT_INDEX_SPARSE_ONE = 3
+    };
 
-	Permutation insertOrder;
+  private:
+    bool selection;
 
-    public:
+    Permutation insertOrder;
 
-	LabeledSetVector ( bool selection = false );
-	~LabeledSetVector ();
+  public:
 
-	void add_reference ( int classno, NICE::Vector *pointer );
+    LabeledSetVector ( bool selection = false );
+    ~LabeledSetVector ();
 
-	int dimension () const;
+    void add_reference ( int classno, NICE::Vector *pointer );
 
-	int numClasses () const
-	{   return size();   }
+    int dimension () const;
+
+    int numClasses () const
+    {
+      return size();
+    }
+
+    void restore ( std::istream & is, int format = FILEFORMAT_INDEX );
+    void restoreRAW ( std::istream & is );
+    void restoreASCII ( std::istream & is, int format = FILEFORMAT_INDEX );
+    void store ( std::ostream & os, int format = FILEFORMAT_INDEX ) const;
+    static void storeElement ( std::ostream & os, int classno, const NICE::Vector & x, int format = FILEFORMAT_INDEX );
+
+    ElementPointer pickRandomSample () const;
+
+    int count ( int classno ) const;
+    
+    /**
+     * @brief count all features
+     *
+     * @return int number of features
+     **/
+    int count () const;
 
-	void restore (std::istream & is, int format = FILEFORMAT_INDEX);
-	void restoreRAW ( std::istream & is );
-	void restoreASCII (std::istream & is, int format = FILEFORMAT_INDEX);
-	void store (std::ostream & os, int format = FILEFORMAT_INDEX) const;
-	static void storeElement ( std::ostream & os, int classno, const NICE::Vector & x, int format = FILEFORMAT_INDEX );
+    int pickRandomSample ( int classno, ElementPointer & i ) const;
 
-	ElementPointer pickRandomSample () const;
+    void clear ();
 
-	int count ( int classno ) const;
-	int count () const;
-	
-	int pickRandomSample ( int classno, ElementPointer & i ) const;
+    /** most important function: add a labeled vector */
+    void add ( int classno, const NICE::Vector & x );
 
-	void clear ();
+    void getPermutation ( Permutation & permutation ) const;
+    void getClasses ( std::vector<int> & classes ) const;
 
-	/** most important function: add a labeled vector */
-	void add ( int classno, const NICE::Vector & x );
+    void printInformation () const;
 
-	void getPermutation ( Permutation & permutation ) const; 
-	void getClasses ( std::vector<int> & classes ) const; 
-	
-	void printInformation () const;
+    void setSelection ( bool _selection = true ) {
+      selection = _selection;
+    };
 
-	void setSelection ( bool _selection = true ) { selection = _selection; };
+    /**
+     * returns the highest class number (not the number of classes!)
+     */
+    int getMaxClassno() const;
 
-	/**
-	 * returns the highest class number (not the number of classes!)
-	 */
-	int getMaxClassno() const;
+    /**
+     * converts LabeledSetVector to a NICE::VVector Set (containing data) and a Labelvector (containing labels for each Data)
+     * @param vecSet dataset (output)
+     * @param vecSetLabels labels (output)
+     */
+    void getFlatRepresentation ( NICE::VVector & vecSet, NICE::Vector & vecSetLabels ) const;
 
-	/**
-	 * converts LabeledSetVector to a NICE::VVector Set (containing data) and a Labelvector (containing labels for each Data)
-	 * @param vecSet dataset (output)
-	 * @param vecSetLabels labels (output)
-	 */
-	void getFlatRepresentation ( NICE::VVector & vecSet, NICE::Vector & vecSetLabels ) const;
-	
-	friend class LabeledSetSelection<LabeledSetVector>;
+    friend class LabeledSetSelection<LabeledSetVector>;
 };
 
 

+ 175 - 166
cbaselib/LabeledSetSelection.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LabeledSetSelection.h
 * @brief Select a subset of a LabeledSet
 * @author Erik Rodner
@@ -14,177 +14,186 @@
 
 #include <set>
 #include <map>
-  
-namespace OBJREC {
+
+namespace OBJREC
+{
 
 /** Select a subset of a LabeledSet */
 template <class F>
 class LabeledSetSelection
 {
 
-    protected:
-
-    public:
-  
-	static void selectRandom ( const std::map<int,int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
-	{
-	    F & base_nonconst = const_cast< F & >(base);
-	    //srand(time(NULL));
-
-	    for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin(); 
-				    i != fixedPositiveExamples.end() ; 
-				    i++ )
-	    {
-			int classno = i->first;
-			int fixedPositiveExamples = i->second;
-
-			std::set<int> memory;
-
-			int count = base_nonconst[classno].size();
-			if ( (count < fixedPositiveExamples) ) {
-				fthrow ( Exception, "LabeledSetSelection::selectRandom: unable to select " << fixedPositiveExamples 
-					<< " of " << count << " examples" );
-			}
-
-			for ( int j = 0 ; j < fixedPositiveExamples ; j++ )
-			{
-				int k;
-				do {
-				k = rand() % count;
-				} while ( memory.find(k) != memory.end() );
-
-				memory.insert(k);
-				positive.add_reference ( classno, base_nonconst[classno][k]);
-			}
-
-			for ( int k = 0 ; k < count ; k++ )
-				if ( memory.find(k) == memory.end() )
-				negative.add_reference ( classno, base_nonconst[classno][k]);
-	    }
-	}
-
-	static void selectRandomMax ( const std::map<int,int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
-	{
-	    F & base_nonconst = const_cast< F & >(base);
-	    //srand(time(NULL));
-
-	    for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin(); 
-				    i != fixedPositiveExamples.end() ; 
-				    i++ )
-	    {
-			int classno = i->first;
-			int fixedPositiveExamples = i->second;
-
-			std::set<int> memory;
-
-			int count = base_nonconst[classno].size();
-
-			int m = fixedPositiveExamples < count ? fixedPositiveExamples : count;
-			for ( int j = 0 ; j < m ; j++ )
-			{
-				int k;
-				do {
-					k = rand() % count;
-				} while ( memory.find(k) != memory.end() );
-
-				memory.insert(k);
-				positive.add_reference ( classno, base_nonconst[classno][k]);
-			}
-
-			for ( int k = 0 ; k < count ; k++ )
-				if ( memory.find(k) == memory.end() )
-					negative.add_reference ( classno, base_nonconst[classno][k]);
-	    }
-	}
-
-	static void selectSequentialStep ( const std::map<int, int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
-	{
-	    F & base_nonconst = const_cast< F & >(base);
-
-	    for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin(); 
-				    i != fixedPositiveExamples.end() ; 
-				    i++ )
-	    {
-			int classno = i->first;
-			int fixedPositiveExamples = i->second;
-			int count = base_nonconst[classno].size();
-			int step = fixedPositiveExamples ? (count / fixedPositiveExamples) : 0;
-
-			if ( count < fixedPositiveExamples ) {
-				fthrow ( Exception, "LabeledSetSelection::selectSequentialStep: unable to select " << fixedPositiveExamples 
-						<< " of " << count << " examples (classno " << classno << ")" );
-		}
-
-
-		int k = 0;
-		for ( int j = 0 ; j < count ; j++ )
-		{
-		    if ( (step == 0) || (k >= fixedPositiveExamples) || (j % step != 0) ) 
-				negative.add_reference ( classno, base_nonconst[classno][j] );
-		    else {
-				k++;
-				positive.add_reference ( classno, base_nonconst[classno][j] );
-		    }
-		}
-	    }
-	};
-
-
-	static void selectSequential ( const std::map<int, int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
-	{
-	    F & base_nonconst = const_cast< F & >(base);
-
-	    for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin(); 
-				    i != fixedPositiveExamples.end() ; 
-				    i++ )
-	    {
-			int classno = i->first;
-			int fixedPositiveExamples = i->second;
-			int count = base_nonconst[classno].size();
-
-			if ( count < fixedPositiveExamples ) {
-				fthrow ( Exception, "LabeledSetSelection::selectSequential: unable to select " << fixedPositiveExamples 
-					<< " of " << count << " examples" );
-			}
-
-			for ( int j = 0 ; j < fixedPositiveExamples ; j++ )
-				positive.add_reference ( classno, base_nonconst[classno][j] );
-			
-			for ( int j = fixedPositiveExamples ; j < count ; j++ )
-				negative.add_reference ( classno, base_nonconst[classno][j] );
-	    }
-
-	};
-
-	static void selectClasses ( const std::set<int> & classnos, const F & base, F & positive, F & negative )
-	{
-	    F & base_nonconst = const_cast< F & >(base);
-
-	    std::vector<int> classes;
-	    base.getClasses(classes);
-
-	    for ( std::set<int>::const_iterator i = classnos.begin(); 
-				    i != classnos.end() ; 
-				    i++ )
-	    {
-			int classno = *i;
-			int count = base_nonconst[classno].size();
-			for ( int j = 0 ; j < count ; j++ )
-				positive.add_reference ( classno, base_nonconst[classno][j]);
-	    }
-
-	    for ( std::vector<int>::const_iterator i = classes.begin(); 
-				    i != classes.end() ; 
-				    i++ )
-	    {
-			int classno = *i;
-			if ( classnos.find(classno) != classnos.end() ) continue;
-			int count = base_nonconst[classno].size();
-			for ( int j = 0 ; j < count ; j++ )
-				negative.add_reference ( classno, base_nonconst[classno][j]);
-	    }
-
-	};
+  protected:
+
+  public:
+
+    static void selectRandom ( const std::map<int,int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
+    {
+      F & base_nonconst = const_cast< F & > ( base );
+      //srand(time(NULL));
+
+      for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin();
+            i != fixedPositiveExamples.end() ;
+            i++ )
+      {
+        int classno = i->first;
+        int fixedPositiveExamples = i->second;
+
+        std::set<int> memory;
+
+        int count = base_nonconst[classno].size();
+        if ( ( count < fixedPositiveExamples ) )
+        {
+          fthrow ( NICE::Exception, "LabeledSetSelection::selectRandom: unable to select " << fixedPositiveExamples
+                   << " of " << count << " examples" );
+        }
+
+        for ( int j = 0 ; j < fixedPositiveExamples ; j++ )
+        {
+          int k;
+          do
+          {
+            k = rand() % count;
+          }
+          while ( memory.find ( k ) != memory.end() );
+
+          memory.insert ( k );
+          positive.add_reference ( classno, base_nonconst[classno][k] );
+        }
+
+        for ( int k = 0 ; k < count ; k++ )
+          if ( memory.find ( k ) == memory.end() )
+            negative.add_reference ( classno, base_nonconst[classno][k] );
+      }
+    }
+
+    static void selectRandomMax ( const std::map<int,int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
+    {
+      F & base_nonconst = const_cast< F & > ( base );
+      //srand(time(NULL));
+
+      for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin();
+            i != fixedPositiveExamples.end() ;
+            i++ )
+      {
+        int classno = i->first;
+        int fixedPositiveExamples = i->second;
+
+        std::set<int> memory;
+
+        int count = base_nonconst[classno].size();
+
+        int m = fixedPositiveExamples < count ? fixedPositiveExamples : count;
+        for ( int j = 0 ; j < m ; j++ )
+        {
+          int k;
+          do
+          {
+            k = rand() % count;
+          }
+          while ( memory.find ( k ) != memory.end() );
+
+          memory.insert ( k );
+          positive.add_reference ( classno, base_nonconst[classno][k] );
+        }
+
+        for ( int k = 0 ; k < count ; k++ )
+          if ( memory.find ( k ) == memory.end() )
+            negative.add_reference ( classno, base_nonconst[classno][k] );
+      }
+    }
+
+    static void selectSequentialStep ( const std::map<int, int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
+    {
+      F & base_nonconst = const_cast< F & > ( base );
+
+      for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin();
+            i != fixedPositiveExamples.end() ;
+            i++ )
+      {
+        int classno = i->first;
+        int fixedPositiveExamples = i->second;
+        int count = base_nonconst[classno].size();
+        int step = fixedPositiveExamples ? ( count / fixedPositiveExamples ) : 0;
+
+        if ( count < fixedPositiveExamples )
+        {
+          fthrow ( NICE::Exception, "LabeledSetSelection::selectSequentialStep: unable to select " << fixedPositiveExamples
+                   << " of " << count << " examples (classno " << classno << ")" );
+        }
+
+
+        int k = 0;
+        for ( int j = 0 ; j < count ; j++ )
+        {
+          if ( ( step == 0 ) || ( k >= fixedPositiveExamples ) || ( j % step != 0 ) )
+            negative.add_reference ( classno, base_nonconst[classno][j] );
+          else
+          {
+            k++;
+            positive.add_reference ( classno, base_nonconst[classno][j] );
+          }
+        }
+      }
+    };
+
+
+    static void selectSequential ( const std::map<int, int> & fixedPositiveExamples, const F & base, F & positive, F & negative )
+    {
+      F & base_nonconst = const_cast< F & > ( base );
+
+      for ( std::map<int,int>::const_iterator i = fixedPositiveExamples.begin();
+            i != fixedPositiveExamples.end() ;
+            i++ )
+      {
+        int classno = i->first;
+        int fixedPositiveExamples = i->second;
+        int count = base_nonconst[classno].size();
+
+        if ( count < fixedPositiveExamples )
+        {
+          fthrow ( NICE::Exception, "LabeledSetSelection::selectSequential: unable to select " << fixedPositiveExamples
+                   << " of " << count << " examples" );
+        }
+
+        for ( int j = 0 ; j < fixedPositiveExamples ; j++ )
+          positive.add_reference ( classno, base_nonconst[classno][j] );
+
+        for ( int j = fixedPositiveExamples ; j < count ; j++ )
+          negative.add_reference ( classno, base_nonconst[classno][j] );
+      }
+
+    };
+
+    static void selectClasses ( const std::set<int> & classnos, const F & base, F & positive, F & negative )
+    {
+      F & base_nonconst = const_cast< F & > ( base );
+
+      std::vector<int> classes;
+      base.getClasses ( classes );
+
+      for ( std::set<int>::const_iterator i = classnos.begin();
+            i != classnos.end() ;
+            i++ )
+      {
+        int classno = *i;
+        int count = base_nonconst[classno].size();
+        for ( int j = 0 ; j < count ; j++ )
+          positive.add_reference ( classno, base_nonconst[classno][j] );
+      }
+
+      for ( std::vector<int>::const_iterator i = classes.begin();
+            i != classes.end() ;
+            i++ )
+      {
+        int classno = *i;
+        if ( classnos.find ( classno ) != classnos.end() ) continue;
+        int count = base_nonconst[classno].size();
+        for ( int j = 0 ; j < count ; j++ )
+          negative.add_reference ( classno, base_nonconst[classno][j] );
+      }
+
+    };
 
 };
 

+ 20 - 20
cbaselib/Polygon.h

@@ -11,31 +11,31 @@
 #include "core/image/CoordT.h"
 #include <list>
 
-using namespace NICE;
 
-typedef std::list< CoordT< int > > PointsList;
+typedef std::list< NICE::CoordT< int > > PointsList;
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 //! \brief Contains category ID and point list of the polygon
 class Polygon
 {
-public:
-	Polygon();
-	Polygon(const Polygon &copy);
-	~Polygon();
-	
-	void push(const CoordT< int > &aPoint);
-	void push(const int &x, const int &y);
-	void setID(const int &anID);
-	
-	const PointsList * points() const;
-	CoordT< int > pop();
-	int id() const;
-	
-private:
-	PointsList points_;
-	int id_;
+  public:
+    Polygon();
+    Polygon ( const Polygon &copy );
+    ~Polygon();
+
+    void push ( const NICE::CoordT< int > &aPoint );
+    void push ( const int &x, const int &y );
+    void setID ( const int &anID );
+
+    const PointsList * points() const;
+    NICE::CoordT< int > pop();
+    int id() const;
+
+  private:
+    PointsList points_;
+    int id_;
 };
 
 } //namespace
@@ -43,5 +43,5 @@ private:
 #endif /* __POLYGON_H__ */
 
 /*
- * 
+ *
  */

+ 28 - 27
cbaselib/progs/statisticsLabeledSetVector.cpp

@@ -6,47 +6,48 @@
 
 using namespace std;
 using namespace OBJREC;
+using namespace NICE;
 
 int main ( int argc, char **argv )
 {
 
-    Config conf ( argc, argv );
+  Config conf ( argc, argv );
 
-    string setfn = conf.gS("main", "set", "train.vec" );
-    int format = conf.gI("main", "format", 2 );
+  string setfn = conf.gS ( "main", "set", "train.vec" );
+  int format = conf.gI ( "main", "format", 2 );
 
-    LabeledSetVector set;
+  LabeledSetVector set;
 
-    set.read ( setfn, format );
+  set.read ( setfn, format );
 
-    set.printInformation();
+  set.printInformation();
 
-    double maximum_value = - numeric_limits<double>::max();
-    double minimum_value = numeric_limits<double>::max();
-    double maximum_norm = 0;
-    double minimum_norm = numeric_limits<double>::max();
+  double maximum_value = - numeric_limits<double>::max();
+  double minimum_value = numeric_limits<double>::max();
+  double maximum_norm = 0;
+  double minimum_norm = numeric_limits<double>::max();
 
-    LOOP_ALL(set)
-    {
-	EACH(classno, x);
+  LOOP_ALL ( set )
+  {
+    EACH ( classno, x );
 
-	if ( x.Max() > maximum_value ) 
-	    maximum_value = x.Max();
+    if ( x.Max() > maximum_value )
+      maximum_value = x.Max();
 
-	if ( x.Min() < minimum_value ) 
-	    minimum_value = x.Min();
+    if ( x.Min() < minimum_value )
+      minimum_value = x.Min();
 
-	if ( x.normL2() > maximum_norm )
-	    maximum_norm = x.normL2();
+    if ( x.normL2() > maximum_norm )
+      maximum_norm = x.normL2();
 
-	if ( x.normL2() < minimum_norm )
-	    minimum_norm = x.normL2();
+    if ( x.normL2() < minimum_norm )
+      minimum_norm = x.normL2();
 
-    }
+  }
 
-    fprintf (stderr, "min value: %f\n", minimum_value );
-    fprintf (stderr, "max value: %f\n", maximum_value );
-    fprintf (stderr, "min L2-norm: %f\n", minimum_norm );
-    fprintf (stderr, "max L2-norm: %f\n", maximum_norm );
-    fprintf (stderr, "dimension: %d\n", set.dimension() );
+  fprintf ( stderr, "min value: %f\n", minimum_value );
+  fprintf ( stderr, "max value: %f\n", maximum_value );
+  fprintf ( stderr, "min L2-norm: %f\n", minimum_norm );
+  fprintf ( stderr, "max L2-norm: %f\n", maximum_norm );
+  fprintf ( stderr, "dimension: %d\n", set.dimension() );
 }

+ 58 - 52
classifier/classifierbase/KernelClassifier.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KernelClassifier.h
 * @brief classifier interface for kernel based methods
 * @author Erik Rodner
@@ -16,78 +16,84 @@
 #include "vislearning/cbaselib/LabeledSet.h"
 #include "vislearning/classifier/classifierbase/VecClassifier.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 /** classifier interface for kernel based methods */
 class KernelClassifier : public VecClassifier
 {
-	public:
-		enum {
-			KERNELCLASSIFIER_NORMALIZATION_EUCLIDEAN = 0,
-			KERNELCLASSIFIER_NORMALIZATION_NONE
-		};
+  public:
+    enum
+    {
+      KERNELCLASSIFIER_NORMALIZATION_EUCLIDEAN = 0,
+      KERNELCLASSIFIER_NORMALIZATION_NONE
+    };
+
+  protected:
+
+    /** This variable might be NULL, if you do not specify a kernel function */
+    Kernel *kernelFunction;
+
+    /** This is the training set, if you specify a kernel function */
+    NICE::VVector vecSet;
+
+    /** These are the labels of the training set, if you specify a kernel function */
+    NICE::Vector vecSetLabels;
 
-    protected:
+    /** Maybe you want to normalize feature vectors before training */
+    int normalizationType;
 
-		/** This variable might be NULL, if you do not specify a kernel function */
-		Kernel *kernelFunction;
-		
-		/** This is the training set, if you specify a kernel function */
-		NICE::VVector vecSet;
+    /** stored config to initialize KernelData with noiseSigma, cholesky method etc. */
+    NICE::Config conf;
 
-		/** These are the labels of the training set, if you specify a kernel function */
-		NICE::Vector vecSetLabels;
+  public:
+    /** simple constructor */
+    KernelClassifier() {};
 
-		/** Maybe you want to normalize feature vectors before training */
-		int normalizationType;
+    /** specify a kernel function which works on vectors and a normalization method ( use the enum defined in KernelClassifier ) */
+    KernelClassifier ( const NICE::Config *conf, Kernel *kernelFunction = NULL, int normalizationType = KERNELCLASSIFIER_NORMALIZATION_EUCLIDEAN );
 
-		/** stored config to initialize KernelData with noiseSigma, cholesky method etc. */
-		NICE::Config conf;
+    /** copy constructor which you should also call in subclasses */
+    KernelClassifier ( const KernelClassifier & src );
 
-    public:
-  		/** simple constructor */
-		KernelClassifier(){};
-	    
-		/** specify a kernel function which works on vectors and a normalization method ( use the enum defined in KernelClassifier ) */
-		KernelClassifier( const NICE::Config *conf, Kernel *kernelFunction = NULL, int normalizationType = KERNELCLASSIFIER_NORMALIZATION_EUCLIDEAN );
+    /** simple destructor */
+    virtual ~KernelClassifier();
 
-		/** copy constructor which you should also call in subclasses */
-		KernelClassifier ( const KernelClassifier & src );
 
-		/** simple destructor */
-		virtual ~KernelClassifier();
+    // interface function
 
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    virtual void teach ( KernelData *kernelData, const NICE::Vector & y ) = 0;
 
-		// interface function
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const = 0;
 
-		/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-		virtual void teach ( KernelData *kernelData, const NICE::Vector & y ) = 0;
 
-		/** classify an example by using its kernel values with the training set,
-			be careful with the order in @param kernelVector */
-		virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const = 0;
+    // functions to build an interface to VecClassifier
 
+    /** classify using simple vector, this works only if you specify a kernel function */
+    ClassificationResult classify ( const NICE::Vector & x ) const;
 
-		// functions to build an interface to VecClassifier
+    /** teach classifier with a labeled set of feature vectors, this works only if you specify a kernel function */
+    virtual void teach ( const LabeledSetVector & teachSet );
 
-		/** classify using simple vector, this works only if you specify a kernel function */
-		ClassificationResult classify ( const NICE::Vector & x ) const;
+    /** calculate classifier stuff as the last training step, pretty useless, deprecated */
+    void finishTeaching() {};
 
-		/** teach classifier with a labeled set of feature vectors, this works only if you specify a kernel function */
-		virtual void teach ( const LabeledSetVector & teachSet );
-		
-		/** calculate classifier stuff as the last training step, pretty useless, deprecated */
-		void finishTeaching() {};
+    /** clone this object */
+    KernelClassifier *clone ( void ) const
+    {
+      fthrow ( NICE::Exception, "clone() not yet implemented." );
+    }
 
-		/** clone this object */
-		KernelClassifier *clone(void) const {
-			fthrow(Exception, "clone() not yet implemented.");
-		}
+    Kernel *getKernelFunction () const
+    {
+      return kernelFunction;
+    };
 
-		Kernel *getKernelFunction () const { return kernelFunction; }; 
-		
-		virtual void restore(std::istream&, int);
-		virtual void store(std::ostream&, int) const;
+    virtual void restore ( std::istream&, int );
+    virtual void store ( std::ostream&, int ) const;
 };
 
 }

+ 31 - 24
classifier/classifierbase/VecClassifier.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file VecClassifier.h
 * @brief Simple classification interface
 * @author Erik Rodner
@@ -14,41 +14,48 @@
 #include "vislearning/cbaselib/LabeledSet.h"
 #include "vislearning/cbaselib/ClassificationResult.h"
 
-#define ROADWORKS fthrow(Exception, "clone(): not yet implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "clone(): not yet implemented!");
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** Simple classification interface */
 class VecClassifier : public NICE::Persistent
 {
-    protected:
-		int maxClassNo;
+  protected:
+    int maxClassNo;
+
+  public:
+
+    VecClassifier()
+    {
+      maxClassNo = 0;
+    };
+
+    /** simple constructor */
+    VecClassifier ( const NICE::Config *conf );
 
-    public:
- 
-		VecClassifier() { maxClassNo = 0; };
+    /** simple destructor */
+    virtual ~VecClassifier();
 
-		/** simple constructor */
-		VecClassifier( const NICE::Config *conf );
+    virtual void setMaxClassNo ( int maxClassNo );
 
-		/** simple destructor */
-		virtual ~VecClassifier();
+    virtual int getMaxClassNo () const;
 
-		virtual void setMaxClassNo ( int maxClassNo );
-		
-		virtual int getMaxClassNo () const;
+    /** classify using simple vector */
+    virtual ClassificationResult classify ( const NICE::Vector & x ) const = 0;
 
-		/** classify using simple vector */
-		virtual ClassificationResult classify ( const NICE::Vector & x ) const = 0;
+    /** teach classifier with a labeled set of feature vectors */
+    virtual void teach ( const LabeledSetVector & teachSet ) = 0;
 
-		/** teach classifier with a labeled set of feature vectors */
-		virtual void teach ( const LabeledSetVector & teachSet ) = 0;
-		
-		/** calculate classifier stuff as the last training step */
-		virtual void finishTeaching() = 0;
+    /** calculate classifier stuff as the last training step */
+    virtual void finishTeaching() = 0;
 
-		/** clone this object */
-		virtual VecClassifier *clone(void) const { ROADWORKS; };
+    /** clone this object */
+    virtual VecClassifier *clone ( void ) const
+    {
+      ROADWORKS;
+    };
 };
 
 #undef ROADWORKS

+ 94 - 91
classifier/fpclassifier/boosting/FPCBoosting.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FPCBoosting.h
 * @brief implementation of boosting algorithms
 * @author Erik Rodner
@@ -16,102 +16,105 @@
 #include "vislearning/cbaselib/FeaturePool.h"
 #include "core/basics/triplet.h"
 
-
-
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** @brief a strong classifier is a collection of weighted classifiers: \f$a \cdot h_t(\mathbf{x}) + b\f$ */
-class StrongClassifier : public std::vector< triplet<double, double, FeaturePoolClassifier *> >
-{};
+class StrongClassifier : public std::vector< NICE::triplet<double, double, FeaturePoolClassifier *> >
+  {};
 
 /** @brief implementation of boosting algorithms */
 class FPCBoosting : public FeaturePoolClassifier
 {
-    protected:
-	const NICE::Config *conf;
-
-	/** @brief normalize weights for each class independently */
-	bool classwise_normalization;
-
-	/** @brief boosting method ( select one value from the enum-type ) */
-	int boosting_method;
-
-	/** @brief class no corresponding to the positive class */
-	int positive_class;
-
-	/** @brief maximum number of rounds */
-	int maxRounds;
-
-	/** @brief memory efficiency by caching and storing of features on the hard disc */
-	bool memory_efficient;
-
-	/** @brief prototype of a weak classifier
-	    
-	    The generation of a new weak classifier is done by the clone method
-	    of this object.
-	*/
-	FeaturePoolClassifier *weakClassifier;
-
-	/** @brief final strong classifier */
-	StrongClassifier strongClassifier;
-
-	/** @brief perform boosting and build strongClassifier 
-	    @param featureStorage pre calculated features
-	    @param fp pool of features
-	    @param examples training examples */
-	void boosting ( const FeatureStorage & featureStorage,
-			FeaturePool & fp,
-			Examples & examples );
-
-	/** @brief normalize weights of examples
-	    @param examples training examples
-	*/
-	void normalizeWeights ( Examples & examples ) const;
-
-    public:
-	
-	enum {
-		BOOSTINGMETHOD_ADABOOST = 0,
-		BOOSTINGMETHOD_REAL_ADABOOST,
-		BOOSTINGMETHOD_GENTLEBOOST
-	};
-
-	/** @brief for cloning only */
-	FPCBoosting() {};
-
-	/** @brief constructor for training */
-	FPCBoosting( const NICE::Config *conf, 
-		  // refactor-nice.pl: check this substitution
-		  // old: string section = "Boost" );
-		  std::string section = "Boost" );
-    
-	/** @brief simple destructor */
-	virtual ~FPCBoosting();
-
-	/** @brief classify an unseen example */
-	ClassificationResult classify ( Example & pce );
-	
-	/** @brief train this classifier 
-	    @param fp pool of features
-	    @param examples training examples
-	*/
-	virtual void train ( FeaturePool & fp,
-		     Examples & examples );
-
-	/** @{ methods for persistency */
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
-	/** @} */
-
-	/** @brief creates a copy of this object */
-	FeaturePoolClassifier *clone () const;
-
-	/** @brief direct access to the classifier parameters */
-	StrongClassifier & getStrongClassifier () { return strongClassifier; };
-
-	/** @brief sets the maximum number of rounds */
-	void setComplexity ( int size );
+  protected:
+    const NICE::Config *conf;
+
+    /** @brief normalize weights for each class independently */
+    bool classwise_normalization;
+
+    /** @brief boosting method ( select one value from the enum-type ) */
+    int boosting_method;
+
+    /** @brief class no corresponding to the positive class */
+    int positive_class;
+
+    /** @brief maximum number of rounds */
+    int maxRounds;
+
+    /** @brief memory efficiency by caching and storing of features on the hard disc */
+    bool memory_efficient;
+
+    /** @brief prototype of a weak classifier
+
+        The generation of a new weak classifier is done by the clone method
+        of this object.
+    */
+    FeaturePoolClassifier *weakClassifier;
+
+    /** @brief final strong classifier */
+    StrongClassifier strongClassifier;
+
+    /** @brief perform boosting and build strongClassifier
+        @param featureStorage pre calculated features
+        @param fp pool of features
+        @param examples training examples */
+    void boosting ( const FeatureStorage & featureStorage,
+                    FeaturePool & fp,
+                    Examples & examples );
+
+    /** @brief normalize weights of examples
+        @param examples training examples
+    */
+    void normalizeWeights ( Examples & examples ) const;
+
+  public:
+
+    enum
+    {
+      BOOSTINGMETHOD_ADABOOST = 0,
+      BOOSTINGMETHOD_REAL_ADABOOST,
+      BOOSTINGMETHOD_GENTLEBOOST
+    };
+
+    /** @brief for cloning only */
+    FPCBoosting() {};
+
+    /** @brief constructor for training */
+    FPCBoosting ( const NICE::Config *conf,
+                  // refactor-nice.pl: check this substitution
+                  // old: string section = "Boost" );
+                  std::string section = "Boost" );
+
+    /** @brief simple destructor */
+    virtual ~FPCBoosting();
+
+    /** @brief classify an unseen example */
+    ClassificationResult classify ( Example & pce );
+
+    /** @brief train this classifier
+        @param fp pool of features
+        @param examples training examples
+    */
+    virtual void train ( FeaturePool & fp,
+                         Examples & examples );
+
+    /** @{ methods for persistency */
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
+    /** @} */
+
+    /** @brief creates a copy of this object */
+    FeaturePoolClassifier *clone () const;
+
+    /** @brief direct access to the classifier parameters */
+    StrongClassifier & getStrongClassifier ()
+    {
+      return strongClassifier;
+    };
+
+    /** @brief sets the maximum number of rounds */
+    void setComplexity ( int size );
 };
 
 

+ 127 - 127
classifier/fpclassifier/logisticregression/FPCSMLR.cpp

@@ -9,153 +9,153 @@ using namespace NICE;
 
 FPCSMLR::FPCSMLR ()
 {
-	inpic = false;
+  inpic = false;
 }
 
-FPCSMLR::FPCSMLR( const Config *_conf, string section ) : conf(_conf)
+FPCSMLR::FPCSMLR ( const Config *_conf, string section ) : conf ( _conf )
 {
-	confsection = section;
-	inpic = conf->gB(section, "inpic", false );
+  confsection = section;
+  inpic = conf->gB ( section, "inpic", false );
 }
 
 FPCSMLR::~FPCSMLR()
 {
-	//clean up
+  //clean up
 }
 
 ClassificationResult FPCSMLR::classify ( Example & pce )
 {
-	FullVector overall_distribution(maxClassNo+1);
-	overall_distribution[maxClassNo] = 0.0;
-
-	double maxp = -numeric_limits<double>::max();
-	int classno = 0;
-	
-	double sum  = 0.0;
-		
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		overall_distribution[i] = classifiers[i].classify(pce);
-		
-		sum += overall_distribution[i];
-		
-		if(maxp < overall_distribution[i])
-		{
-			classno = i;
-			maxp = overall_distribution[i];
-		}
-	}
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		overall_distribution[i] /= sum;
-	}
-
-	return ClassificationResult ( classno, overall_distribution );
+  FullVector overall_distribution ( maxClassNo + 1 );
+  overall_distribution[maxClassNo] = 0.0;
+
+  double maxp = -numeric_limits<double>::max();
+  int classno = 0;
+
+  double sum  = 0.0;
+
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    overall_distribution[i] = classifiers[i].classify ( pce );
+
+    sum += overall_distribution[i];
+
+    if ( maxp < overall_distribution[i] )
+    {
+      classno = i;
+      maxp = overall_distribution[i];
+    }
+  }
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    overall_distribution[i] /= sum;
+  }
+
+  return ClassificationResult ( classno, overall_distribution );
 }
 
 void FPCSMLR::train ( FeaturePool & _fp, Examples & examples )
 {
 
-	cout << "start train" << endl;
-	fp = FeaturePool(_fp);
-    
-	// Anzahl von Merkmalen
-	int fanz = examples.size();
-
-	maxClassNo = -1;
-	for(int i = 0; i < fanz; i++)
-	{
-		maxClassNo = std::max(maxClassNo, examples[i].first);
-	}
-	maxClassNo++;
-	
-	assert(fanz >= maxClassNo);
-	
-	classifiers.resize(maxClassNo);
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		cout << "classifier no " << i << " training starts" << endl;
-		classifiers[i] = SLR(conf, confsection);
-
-		if(inpic)
-		{
-	
-			vector<bool> classinpic;
-			
-			for(int j = 0; j < (int)examples.size(); j++)
-			{
-				if(examples[j].first == i)
-				{
-					if(examples[j].second.position < (int)classinpic.size())
-						classinpic[examples[j].second.position] = true;
-					else if(examples[j].second.position == (int)classinpic.size())
-						classinpic.push_back(true);
-					else
-					{
-						while(examples[j].second.position > (int)classinpic.size())
-						{
-							classinpic.push_back(false);
-						}
-						classinpic.push_back(true);
-					}
-				}
-			}
-			
-			Examples ex2;
-
-			for(int j = 0; j < (int)examples.size(); j++)
-			{
-				if(examples[j].second.position >= (int)classinpic.size())
-						continue;
-				if(classinpic[examples[j].second.position])
-				{
-					Example e;
-					e.svec = examples[j].second.svec;
-					e.vec = examples[j].second.vec;
-					ex2.push_back ( pair<int, Example> ( examples[j].first, e ) );
-				}
-			}
-			cout << "examples for class " << i << ": " << ex2.size() << endl;
-			
-			if(ex2.size() <= 2)
-				continue;
-			
-			classifiers[i].train(_fp, ex2, i);
-			
-			for(int j = 0; j < (int)ex2.size(); j++)
-			{
-				ex2[j].second.svec = NULL;
-			}
-		}
-		else
-		{
-			classifiers[i].train(_fp, examples, i);
-		}
-	}
-
-	cout << "end train" << endl;
+  cout << "start train" << endl;
+  fp = FeaturePool ( _fp );
+
+  // Anzahl von Merkmalen
+  int fanz = examples.size();
+
+  maxClassNo = -1;
+  for ( int i = 0; i < fanz; i++ )
+  {
+    maxClassNo = std::max ( maxClassNo, examples[i].first );
+  }
+  maxClassNo++;
+
+  assert ( fanz >= maxClassNo );
+
+  classifiers.resize ( maxClassNo );
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    cout << "classifier no " << i << " training starts" << endl;
+    classifiers[i] = SLR ( conf, confsection );
+
+    if ( inpic )
+    {
+
+      vector<bool> classinpic;
+
+      for ( int j = 0; j < ( int ) examples.size(); j++ )
+      {
+        if ( examples[j].first == i )
+        {
+          if ( examples[j].second.position < ( int ) classinpic.size() )
+            classinpic[examples[j].second.position] = true;
+          else if ( examples[j].second.position == ( int ) classinpic.size() )
+            classinpic.push_back ( true );
+          else
+          {
+            while ( examples[j].second.position > ( int ) classinpic.size() )
+            {
+              classinpic.push_back ( false );
+            }
+            classinpic.push_back ( true );
+          }
+        }
+      }
+
+      Examples ex2;
+
+      for ( int j = 0; j < ( int ) examples.size(); j++ )
+      {
+        if ( examples[j].second.position >= ( int ) classinpic.size() )
+          continue;
+        if ( classinpic[examples[j].second.position] )
+        {
+          Example e;
+          e.svec = examples[j].second.svec;
+          e.vec = examples[j].second.vec;
+          ex2.push_back ( pair<int, Example> ( examples[j].first, e ) );
+        }
+      }
+      cout << "examples for class " << i << ": " << ex2.size() << endl;
+
+      if ( ex2.size() <= 2 )
+        continue;
+
+      classifiers[i].train ( _fp, ex2, i );
+
+      for ( int j = 0; j < ( int ) ex2.size(); j++ )
+      {
+        ex2[j].second.svec = NULL;
+      }
+    }
+    else
+    {
+      classifiers[i].train ( _fp, examples, i );
+    }
+  }
+
+  cout << "end train" << endl;
 }
 
 
-void FPCSMLR::restore (istream & is, int format)
+void FPCSMLR::restore ( istream & is, int format )
 {
-	is >> maxClassNo;
-	classifiers.resize(maxClassNo);
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		classifiers[i].restore(is, format);
-	}
+  is >> maxClassNo;
+  classifiers.resize ( maxClassNo );
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    classifiers[i].restore ( is, format );
+  }
 }
 
-void FPCSMLR::store (ostream & os, int format) const
+void FPCSMLR::store ( ostream & os, int format ) const
 {
 
-	if(format!=-9999) os << maxClassNo;
+  if ( format != -9999 ) os << maxClassNo;
 
-	for(int i = 0; i < maxClassNo; i++)
-	{
-		classifiers[i].store(os, format);
-	}
+  for ( int i = 0; i < maxClassNo; i++ )
+  {
+    classifiers[i].store ( os, format );
+  }
 }
 
 void FPCSMLR::clear ()
@@ -165,15 +165,15 @@ void FPCSMLR::clear ()
 
 FeaturePoolClassifier *FPCSMLR::clone () const
 {
-	//TODO: wenn alle Variablen der Klasse bekannt sind, dann übergebe diese mit
-	FPCSMLR *o = new FPCSMLR ( conf, confsection );
+  //TODO: wenn alle Variablen der Klasse bekannt sind, dann übergebe diese mit
+  FPCSMLR *o = new FPCSMLR ( conf, confsection );
 
-	o->maxClassNo = maxClassNo;
+  o->maxClassNo = maxClassNo;
 
-	return o;
+  return o;
 }
 
 void FPCSMLR::setComplexity ( int size )
 {
-	cerr << "FPCSMLR: no complexity to set" << endl;
+  cerr << "FPCSMLR: no complexity to set" << endl;
 }

+ 68 - 67
classifier/fpclassifier/logisticregression/FPCSMLR.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file FPCSMLR.h
  * @brief implementation of Sparse Multinomial Logistic Regression (SMLR) Classififier, it uses a SLR for each class and combines the results
  * @author Björn Fröhlich
@@ -18,75 +18,76 @@
 #include "vislearning/cbaselib/FeaturePool.h"
 #include "core/algebra/GMSparseVectorMatrix.h"
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 class FPCSMLR : public FeaturePoolClassifier
 {
-    protected:
-	//! the configuration file
-	const NICE::Config *conf;
-
-	//! section in the configfile
-	std::string confsection;
-	
-	//! the featurepool
-	FeaturePool fp;
-	
-	//! the one vs all sparse logistic classifiers
-	std::vector<SLR> classifiers;
-	
-	//! just use the features from pictures, which the class contains
-	bool inpic;
-		
-    public:
-	/**
-	 * standard constructor
-	 * @param conf configfile
-	 * @param section section name in configfile for classifier
-	 */
-	FPCSMLR( const NICE::Config *conf, std::string section="SMLR");
-      
-	
-	/**
-	 * simple constructor -> does nothing
-	 */
-	FPCSMLR ();
-
-	/**
-	 * simple destructor
-	 */
-	~FPCSMLR();
-
-	/**
-	 * main classification function
-	 * @param pce input feature
-	 * @return a classification result
-	 */
-	ClassificationResult classify ( Example & pce );
-
-	/**
-	 * start training
-	 * @param fp a featurepool (how to handle which features...)
-	 * @param examples input features
-	 */
-	void train ( FeaturePool & _fp, Examples & examples );
-
-	/**
-	 * clone this object
-	 * @return a copy of this object
-	 */
-	FeaturePoolClassifier *clone () const;
-
-	/**
-	 * set complexity for the next training process e.g. number of weak classifiers
-	 * @param size new complexity
-	 */
-	void setComplexity ( int size );
-
-	/** IO functions */
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
+  protected:
+    //! the configuration file
+    const NICE::Config *conf;
+
+    //! section in the configfile
+    std::string confsection;
+
+    //! the featurepool
+    FeaturePool fp;
+
+    //! the one vs all sparse logistic classifiers
+    std::vector<SLR> classifiers;
+
+    //! just use the features from pictures, which the class contains
+    bool inpic;
+
+  public:
+    /**
+     * standard constructor
+     * @param conf configfile
+     * @param section section name in configfile for classifier
+     */
+    FPCSMLR ( const NICE::Config *conf, std::string section="SMLR" );
+
+
+    /**
+     * simple constructor -> does nothing
+     */
+    FPCSMLR ();
+
+    /**
+     * simple destructor
+     */
+    ~FPCSMLR();
+
+    /**
+     * main classification function
+     * @param pce input feature
+     * @return a classification result
+     */
+    ClassificationResult classify ( Example & pce );
+
+    /**
+     * start training
+     * @param fp a featurepool (how to handle which features...)
+     * @param examples input features
+     */
+    void train ( FeaturePool & _fp, Examples & examples );
+
+    /**
+     * clone this object
+     * @return a copy of this object
+     */
+    FeaturePoolClassifier *clone () const;
+
+    /**
+     * set complexity for the next training process e.g. number of weak classifiers
+     * @param size new complexity
+     */
+    void setComplexity ( int size );
+
+    /** IO functions */
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
 };
 
 } // namespace

+ 431 - 431
classifier/fpclassifier/logisticregression/SLR.cpp

@@ -18,115 +18,115 @@ SLR::SLR ()
 {
 }
 
-SLR::SLR( const Config *_conf, string section ) : conf(_conf)
+SLR::SLR ( const Config *_conf, string section ) : conf ( _conf )
 {
-	maxiter = conf->gI(section, "maxiter", 20000 );
-	resamp_decay = conf->gD(section, "resamp_decay", 0.5 );
-	convergence_tol = conf->gD(section, "convergence_tol", 1e-7 );
-	min_resamp =  conf->gD(section, "min_resamp", 0.001 );
-	lambda = conf->gD(section, "lambda", 0.1 );
-	samplesperclass = conf->gD(section, "samplesperclass", 200.0);
-	weight.setDim(0);
-	fdim = 0;
+  maxiter = conf->gI ( section, "maxiter", 20000 );
+  resamp_decay = conf->gD ( section, "resamp_decay", 0.5 );
+  convergence_tol = conf->gD ( section, "convergence_tol", 1e-7 );
+  min_resamp =  conf->gD ( section, "min_resamp", 0.001 );
+  lambda = conf->gD ( section, "lambda", 0.1 );
+  samplesperclass = conf->gD ( section, "samplesperclass", 200.0 );
+  weight.setDim ( 0 );
+  fdim = 0;
 }
 
 SLR::~SLR()
 {
-	//clean up
+  //clean up
 }
 
 double SLR::classify ( Example & pce )
 {
-	double result;
-	SparseVector *svec;
+  double result;
+  SparseVector *svec;
 
-	if(weight.getDim() == 0)
-		return 0.0;
+  if ( weight.getDim() == 0 )
+    return 0.0;
 
-	bool newvec = false;
-	
-	if(pce.svec != NULL)
-	{
-		svec = pce.svec;
-	}
-	else
-	{
-		Vector x;
+  bool newvec = false;
 
-		x = *(pce.vec);
+  if ( pce.svec != NULL )
+  {
+    svec = pce.svec;
+  }
+  else
+  {
+    Vector x;
+
+    x = * ( pce.vec );
 
 #ifdef featnorm
-		for(int m = 0; m < (int)x.size(); m++)
-		{
-			x[m] = (x[m]-minval[m]) /(maxval[m] - minval[m]);
-		}
+    for ( int m = 0; m < ( int ) x.size(); m++ )
+    {
+      x[m] = ( x[m] - minval[m] ) / ( maxval[m] - minval[m] );
+    }
 #endif
-		svec = new SparseVector(x);
+    svec = new SparseVector ( x );
+
+    svec->setDim ( x.size() );
 
-		svec->setDim(x.size());
+    newvec = true;
 
-		newvec = true;
+  }
 
-	}
-		
-	if(weight.size() == 0)
-		result = 0.0;
-	else
-	{
-		result = 1.0/(1.0+exp(-svec->innerProduct(weight)));
-	}
+  if ( weight.size() == 0 )
+    result = 0.0;
+  else
+  {
+    result = 1.0 / ( 1.0 + exp ( -svec->innerProduct ( weight ) ) );
+  }
 
-	if(newvec)
-		delete svec;
+  if ( newvec )
+    delete svec;
 
-	return result;
+  return result;
 }
 
 void SLR::train ( FeaturePool & _fp, Examples & examples, int classno )
 {
 
-	cout << "start train" << endl;
-	fp = FeaturePool(_fp);
-    
-	// Anzahl von Merkmalen
-	int fanz = examples.size();
-	assert(fanz >= 2);
-
-	// Merkmalsdimension bestimmen
-	Vector x;
-	fp.calcFeatureVector(examples[0].second, x);
-	fdim = x.size();
-	assert(fdim > 0);
-
-	stepwise_regression(examples, classno);	
-	cout << "end train" << endl;
+  cout << "start train" << endl;
+  fp = FeaturePool ( _fp );
+
+  // Anzahl von Merkmalen
+  int fanz = examples.size();
+  assert ( fanz >= 2 );
+
+  // Merkmalsdimension bestimmen
+  Vector x;
+  fp.calcFeatureVector ( examples[0].second, x );
+  fdim = x.size();
+  assert ( fdim > 0 );
+
+  stepwise_regression ( examples, classno );
+  cout << "end train" << endl;
 }
 
-void SLR::restore (istream & is, int format)
+void SLR::restore ( istream & is, int format )
 {
-	weight.restore(is, format);
-	fdim = (int) weight.getDim();
-	maxval.resize(fdim);
-	minval.resize(fdim);
-	for(int i = 0; i < fdim; i++)
-	{
-		is >> maxval[i];
-		is >> minval[i];
-	}
+  weight.restore ( is, format );
+  fdim = ( int ) weight.getDim();
+  maxval.resize ( fdim );
+  minval.resize ( fdim );
+  for ( int i = 0; i < fdim; i++ )
+  {
+    is >> maxval[i];
+    is >> minval[i];
+  }
 }
 
-void SLR::store (ostream & os, int format) const
+void SLR::store ( ostream & os, int format ) const
 
 {
-	if(format!=-9999){
-		weight.store(os, format);
-		for(int i = 0; i < fdim; i++)
-		{
-			os << maxval[i] << " " << minval[i] << endl;
-		}
-	}else{
-		weight.store(os, format);
-	}
+  if ( format != -9999 ) {
+    weight.store ( os, format );
+    for ( int i = 0; i < fdim; i++ )
+    {
+      os << maxval[i] << " " << minval[i] << endl;
+    }
+  } else {
+    weight.store ( os, format );
+  }
 }
 
 void SLR::clear ()
@@ -134,385 +134,385 @@ void SLR::clear ()
 //TODO: einbauen
 }
 
-int SLR::stepwise_regression(Examples &x, int classno)
+int SLR::stepwise_regression ( Examples &x, int classno )
 {
-	// initialize randomization
-	srand (time(NULL));
-	//srand (1);
-	
-	cout << "start regression" << endl;
-	
-	// get the number of features
-	int fnum = x.size();
-	
-	// create Datamatrix
-	GMSparseVectorMatrix X;
-	
-	GMSparseVectorMatrix Y;
-	
-	vector<int> count(2, 0);
-
-	maxval.resize(fdim);
-	minval.resize(fdim);
-
-	if(x[0].second.svec == NULL) //input normal vectors
-	{
-		Vector feat;
-
-		for(int i = 0; i < fdim; i++)
-		{
-			maxval[i] = numeric_limits<double>::min();
-			minval[i] = numeric_limits<double>::max();
-		}
-		
-		for(int i = 0; i < fnum; i++)
-		{
-			int pos = 0;
-			if(x[i].first != classno)
-				pos = 1;
-			
-			++count[pos];
-
-			fp.calcFeatureVector(x[i].second, feat);
+  // initialize randomization
+  srand ( time ( NULL ) );
+  //srand (1);
+
+  cout << "start regression" << endl;
+
+  // get the number of features
+  int fnum = x.size();
+
+  // create Datamatrix
+  GMSparseVectorMatrix X;
+
+  GMSparseVectorMatrix Y;
+
+  vector<int> count ( 2, 0 );
+
+  maxval.resize ( fdim );
+  minval.resize ( fdim );
+
+  if ( x[0].second.svec == NULL ) //input normal vectors
+  {
+    Vector feat;
+
+    for ( int i = 0; i < fdim; i++ )
+    {
+      maxval[i] = numeric_limits<double>::min();
+      minval[i] = numeric_limits<double>::max();
+    }
+
+    for ( int i = 0; i < fnum; i++ )
+    {
+      int pos = 0;
+      if ( x[i].first != classno )
+        pos = 1;
+
+      ++count[pos];
+
+      fp.calcFeatureVector ( x[i].second, feat );
 #ifdef featnorm
-			for(int m = 0; m < (int)feat.size(); m++)
-			{
-				minval[m] = std::min(minval[m], feat[m]);
-				maxval[m] = std::max(maxval[m], feat[m]);
-			}
+      for ( int m = 0; m < ( int ) feat.size(); m++ )
+      {
+        minval[m] = std::min ( minval[m], feat[m] );
+        maxval[m] = std::max ( maxval[m], feat[m] );
+      }
 #endif
-			fdim = feat.size();
-		}
-	}
-	else //input Sparse Vectors
-	{
-		for(int i = 0; i < fnum; i++)
-		{
-			int pos = 0;
-			if(x[i].first != classno)
-				pos = 1;
-			
-			++count[pos];
-		}
-		fdim = x[0].second.svec->getDim();
-	}
-	
-	if(count[0] == 0 || count[1] == 0)
-	{
-		cerr << "not enought samples " << count[0] << " : " << count[1] << endl;
-		weight.setDim(0);
-		return -1;
-	}
-
-	double samples = std::min(count[0], count[1]);
-	samples = std::min(samples, samplesperclass);
-	//samples = std::max(samples, 200);
-	//samples = samplesperclass;
-	
-	vector<double> rands(2,0.0);
-	vector<double> allsizes(2,0.0);
-	for(int i = 0; i < 2; i++)
-	{
-		rands[i] = 1.0;								//use all samples (default if samples>count[i])
-		if(samples>0 && samples<1) rands[i] = samples;				//use relative number of samples wrt. class size
-		if(samples>1 && samples<=count[i]) rands[i] = samples/(double)count[i]; //use (approximately) fixed absolute number of samples for each class
-		allsizes[i]=count[i];
-		count[i] = 0;
-	}
-
-	for(int i = 0; i < fnum; i++)
-	{
-		int pos = 0;
-		if(x[i].first != classno)
-			pos = 1;
-			
-			
-		double r = (double)rand()/(double)RAND_MAX;	
-			
-		if( r > rands[pos])
-			continue;
-		++count[pos];
-
-		if(x[0].second.svec == NULL) 
-		{
-			Vector feat;
-			fp.calcFeatureVector(x[i].second, feat);
+      fdim = feat.size();
+    }
+  }
+  else //input Sparse Vectors
+  {
+    for ( int i = 0; i < fnum; i++ )
+    {
+      int pos = 0;
+      if ( x[i].first != classno )
+        pos = 1;
+
+      ++count[pos];
+    }
+    fdim = x[0].second.svec->getDim();
+  }
+
+  if ( count[0] == 0 || count[1] == 0 )
+  {
+    cerr << "not enought samples " << count[0] << " : " << count[1] << endl;
+    weight.setDim ( 0 );
+    return -1;
+  }
+
+  double samples = std::min ( count[0], count[1] );
+  samples = std::min ( samples, samplesperclass );
+  //samples = std::max(samples, 200);
+  //samples = samplesperclass;
+
+  vector<double> rands ( 2, 0.0 );
+  vector<double> allsizes ( 2, 0.0 );
+  for ( int i = 0; i < 2; i++ )
+  {
+    rands[i] = 1.0;        //use all samples (default if samples>count[i])
+    if ( samples > 0 && samples < 1 ) rands[i] = samples;    //use relative number of samples wrt. class size
+    if ( samples > 1 && samples <= count[i] ) rands[i] = samples / ( double ) count[i]; //use (approximately) fixed absolute number of samples for each class
+    allsizes[i] = count[i];
+    count[i] = 0;
+  }
+
+  for ( int i = 0; i < fnum; i++ )
+  {
+    int pos = 0;
+    if ( x[i].first != classno )
+      pos = 1;
+
+
+    double r = ( double ) rand() / ( double ) RAND_MAX;
+
+    if ( r > rands[pos] )
+      continue;
+    ++count[pos];
+
+    if ( x[0].second.svec == NULL )
+    {
+      Vector feat;
+      fp.calcFeatureVector ( x[i].second, feat );
 #ifdef featnorm
-			for(int m = 0; m < (int)feat.size(); m++)
-			{
-				feat[m] = (feat[m]-minval[m]) /(maxval[m] - minval[m]);
-			}
+      for ( int m = 0; m < ( int ) feat.size(); m++ )
+      {
+        feat[m] = ( feat[m] - minval[m] ) / ( maxval[m] - minval[m] );
+      }
 #endif
 
-			X.addRow(feat);
-		}
-		else
-		{
-			X.addRow(x[i].second.svec);
-		}
-		SparseVector *v = new SparseVector(2);
-		(*v)[pos] = 1.0;
-		Y.addRow(v);
-	}
-	Y.setDel();
-
-	if(x[0].second.svec == NULL)
-		X.setDel();
-		
-	for(int i = 0; i < 2; i++)
-	{
-		cerr << "Examples for class " << i << ": " << count[i] << " out of " << allsizes[i] << " with p = " << rands[i] << endl;
-	}	
-	
+      X.addRow ( feat );
+    }
+    else
+    {
+      X.addRow ( x[i].second.svec );
+    }
+    SparseVector *v = new SparseVector ( 2 );
+    ( *v ) [pos] = 1.0;
+    Y.addRow ( v );
+  }
+  Y.setDel();
+
+  if ( x[0].second.svec == NULL )
+    X.setDel();
+
+  for ( int i = 0; i < 2; i++ )
+  {
+    cerr << "Examples for class " << i << ": " << count[i] << " out of " << allsizes[i] << " with p = " << rands[i] << endl;
+  }
+
 #undef NORMALIZATION
 #ifdef NORMALIZATION
-	GMSparseVectorMatrix Xred;
-	Xred.resize(X.rows(), X.cols());
-
-	for(int r = 0; r < (int)Xred.rows(); r++)
-	{
-		for(int c = 0; c < (int)Xred.cols(); c++)
-		{
-			double tmp = X[r].get(c);
-			
-			if(Y[r].get(0) == 1)
-				tmp *= count[0]/fnum;
-			else
-				tmp *= count[1]/fnum;
-			
-			if(fabs(tmp) > 10e-7)
-				Xred[r][c] = tmp;
-		}
-	}
+  GMSparseVectorMatrix Xred;
+  Xred.resize ( X.rows(), X.cols() );
+
+  for ( int r = 0; r < ( int ) Xred.rows(); r++ )
+  {
+    for ( int c = 0; c < ( int ) Xred.cols(); c++ )
+    {
+      double tmp = X[r].get ( c );
+
+      if ( Y[r].get ( 0 ) == 1 )
+        tmp *= count[0] / fnum;
+      else
+        tmp *= count[1] / fnum;
+
+      if ( fabs ( tmp ) > 10e-7 )
+        Xred[r][c] = tmp;
+    }
+  }
 #endif
 
-	fnum = X.rows();
-	
-	GMSparseVectorMatrix xY;
+  fnum = X.rows();
+
+  GMSparseVectorMatrix xY;
 #ifdef NORMALIZATION
-	Xred.mult(Y, xY, true);
+  Xred.mult ( Y, xY, true );
 #else
-	X.mult(Y, xY, true);
+  X.mult ( Y, xY, true );
 #endif
 
-	weight.setDim(fdim);
-
-	// for faster Computing Xw = X*w	
-	GMSparseVectorMatrix Xw;
-	X.mult(weight, Xw, false, true);
-	SparseVector S(fnum);
-
-	for(int r = 0; r < fnum; r++)
-	{
-		S[r] = 0.0;
-		for(int c = 0; c < 2; c++)
-		{
-			S[r] += exp(Xw[r].get(c));
-		}
-	}
-
-	// for faster computing ac[i] = (maxClassNo-1)/(2*maxClassNo) * Sum_j (x_i (j))^2
-	
-	Vector ac(fdim);
-	Vector lm_2_ac(fdim);
-	
-	for(int f = 0; f < fdim; f++)
-	{
-		ac[f] = 0.0;
-		for(int a = 0; a < fnum; a++)
-		{
-			ac[f] += X[a].get(f)*X[a].get(f);
-		}
-		ac[f] *= 0.25;
-		lm_2_ac[f] = (lambda/2.0)/ac[f];
-	}
-	
-	// initialize the iterative optimization
-	double incr = numeric_limits<double>::max();
-	long non_zero = 0;
-	long wasted_basis = 0;
-	long needed_basis = 0;
-	
-	// prob of resample each weight
-	vector<double> p_resamp;
-	p_resamp.resize(fdim);
-
-	// loop over cycles
-	long cycle = 0;
-	
-	for (cycle = 0; cycle < maxiter; cycle++)
-	{
+  weight.setDim ( fdim );
+
+  // for faster Computing Xw = X*w
+  GMSparseVectorMatrix Xw;
+  X.mult ( weight, Xw, false, true );
+  SparseVector S ( fnum );
+
+  for ( int r = 0; r < fnum; r++ )
+  {
+    S[r] = 0.0;
+    for ( int c = 0; c < 2; c++ )
+    {
+      S[r] += exp ( Xw[r].get ( c ) );
+    }
+  }
+
+  // for faster computing ac[i] = (maxClassNo-1)/(2*maxClassNo) * Sum_j (x_i (j))^2
+
+  Vector ac ( fdim );
+  Vector lm_2_ac ( fdim );
+
+  for ( int f = 0; f < fdim; f++ )
+  {
+    ac[f] = 0.0;
+    for ( int a = 0; a < fnum; a++ )
+    {
+      ac[f] += X[a].get ( f ) * X[a].get ( f );
+    }
+    ac[f] *= 0.25;
+    lm_2_ac[f] = ( lambda / 2.0 ) / ac[f];
+  }
+
+  // initialize the iterative optimization
+  double incr = numeric_limits<double>::max();
+  long non_zero = 0;
+  long wasted_basis = 0;
+  long needed_basis = 0;
+
+  // prob of resample each weight
+  vector<double> p_resamp;
+  p_resamp.resize ( fdim );
+
+  // loop over cycles
+  long cycle = 0;
+
+  for ( cycle = 0; cycle < maxiter; cycle++ )
+  {
 #ifdef SLRDEBUG
-		cerr << "iteration: " << cycle << " of " << maxiter << endl;
+    cerr << "iteration: " << cycle << " of " << maxiter << endl;
 #endif
-    	// zero out the diffs for assessing change
-		double sum2_w_diff = 0.0;
-		double sum2_w_old = 0.0;
-		wasted_basis = 0;
-		if (cycle==1)
-			needed_basis = 0;		
-		
-    	// update each weight
+    // zero out the diffs for assessing change
+    double sum2_w_diff = 0.0;
+    double sum2_w_old = 0.0;
+    wasted_basis = 0;
+    if ( cycle == 1 )
+      needed_basis = 0;
+
+    // update each weight
 //#pragma omp parallel for
-		for (int basis = 0; basis < fdim; basis++) // über alle Dimensionen
-		{
-			int changed = 0;
-			// get the starting weight
-			double w_old = weight.get(basis);
-
-			// set the p_resamp if it's the first cycle
-			if (cycle == 0)
-			{
-				p_resamp[basis] = 1.0;
-			}
-
-			// see if we're gonna update
-			double rval = (double)rand()/(double)RAND_MAX;			
-			
-			if ((w_old != 0) || (rval < p_resamp[basis]))
-			{
-	  			// calc the probability
-				double XdotP = 0.0;
-				for (int i = 0; i < fnum; i++)
-				{
+    for ( int basis = 0; basis < fdim; basis++ ) // über alle Dimensionen
+    {
+      int changed = 0;
+      // get the starting weight
+      double w_old = weight.get ( basis );
+
+      // set the p_resamp if it's the first cycle
+      if ( cycle == 0 )
+      {
+        p_resamp[basis] = 1.0;
+      }
+
+      // see if we're gonna update
+      double rval = ( double ) rand() / ( double ) RAND_MAX;
+
+      if ( ( w_old != 0 ) || ( rval < p_resamp[basis] ) )
+      {
+        // calc the probability
+        double XdotP = 0.0;
+        for ( int i = 0; i < fnum; i++ )
+        {
 #ifdef NORMALIZATION
-					double e = Xred[i].get(basis) * exp(Xw[i].get(0))/S[i];
+          double e = Xred[i].get ( basis ) * exp ( Xw[i].get ( 0 ) ) / S[i];
 #else
-					double e = X[i].get(basis) * exp(Xw[i].get(0))/S[i];
+          double e = X[i].get ( basis ) * exp ( Xw[i].get ( 0 ) ) / S[i];
 #endif
-					if(finite(e))
-						XdotP += e;
+          if ( finite ( e ) )
+            XdotP += e;
 #ifdef SLRDEBUG
-					else
-						throw "numerical problems";
+          else
+            throw "numerical problems";
 #endif
-				}
-					
-				// get the gradient
-				double grad = xY[basis].get(0) - XdotP;
-	  			// set the new weight
-				double w_new = w_old + grad/ac[basis];
-
-				// test that we're within bounds
-				if (w_new > lm_2_ac[basis])
-				{
-	    			// more towards bounds, but keep it
-					w_new -= lm_2_ac[basis];
-					changed = 1;
-
-	    			// umark from being zero if necessary
-					if (w_old == 0.0)
-					{
-						non_zero += 1;
-
-	      				// reset the p_resample
-						p_resamp[basis] = 1.0;
-
-	      				// we needed the basis
-						needed_basis += 1;
-					}
-				}
-				else if (w_new < -lm_2_ac[basis])
-				{
-	    			// more towards bounds, but keep it
-					w_new += lm_2_ac[basis];
-					changed = 1;
-
-	    			// umark from being zero if necessary
-					if (w_old == 0.0)
-					{
-						non_zero += 1;
-
-	      				// reset the p_resample
-						p_resamp[basis] = 1.0;
-
-	      				// we needed the basis
-						needed_basis += 1;
-					}
-				}
-				else
-				{
-	    			// gonna zero it out
-					w_new = 0.0;
-
-	    			// decrease the p_resamp
-					p_resamp[basis] -= (p_resamp[basis] - min_resamp) * resamp_decay;
-
-	    			// set the number of non-zero
-					if (w_old == 0.0)
-					{
-	     				// we didn't change
-						changed = 0;
-
-	      				// and wasted a basis
-						wasted_basis += 1;
-					}
-					else
-					{
-	      				// we changed
-						changed = 1;
-
-	      				// must update num non_zero
-						non_zero -= 1;
-					}
-				}
-	  			// process changes if necessary
-				if (changed == 1)
-				{
-	   				// update the expected values
-					double w_diff = w_new - w_old;
-					for (int i = 0; i < fnum; i++)
-					{
-						double E_old = exp(Xw[i].get(0));
-						double val = X[i].get(basis)*w_diff;
-						if(Xw[i].get(0) == 0.0)
-						{
-							if(fabs(val) > 10e-7)
-								Xw[i][0] = val;
-						}
-						else
-							Xw[i][0] += X[i].get(basis)*w_diff;
-						double E_new_m = exp(Xw[i].get(0));			
-						
-						S[i] += E_new_m - E_old;
-					}
-
-	    			// update the weight
-					if( w_new == 0.0)
-					{
-						if(weight.get(basis) != 0.0)
-						{
-							weight.erase(basis);
-						}
-					}
-					else
-						weight[basis] = w_new;
-	    			// keep track of the sqrt sum squared diffs
+        }
+
+        // get the gradient
+        double grad = xY[basis].get ( 0 ) - XdotP;
+        // set the new weight
+        double w_new = w_old + grad / ac[basis];
+
+        // test that we're within bounds
+        if ( w_new > lm_2_ac[basis] )
+        {
+          // more towards bounds, but keep it
+          w_new -= lm_2_ac[basis];
+          changed = 1;
+
+          // umark from being zero if necessary
+          if ( w_old == 0.0 )
+          {
+            non_zero += 1;
+
+            // reset the p_resample
+            p_resamp[basis] = 1.0;
+
+            // we needed the basis
+            needed_basis += 1;
+          }
+        }
+        else if ( w_new < -lm_2_ac[basis] )
+        {
+          // more towards bounds, but keep it
+          w_new += lm_2_ac[basis];
+          changed = 1;
+
+          // umark from being zero if necessary
+          if ( w_old == 0.0 )
+          {
+            non_zero += 1;
+
+            // reset the p_resample
+            p_resamp[basis] = 1.0;
+
+            // we needed the basis
+            needed_basis += 1;
+          }
+        }
+        else
+        {
+          // gonna zero it out
+          w_new = 0.0;
+
+          // decrease the p_resamp
+          p_resamp[basis] -= ( p_resamp[basis] - min_resamp ) * resamp_decay;
+
+          // set the number of non-zero
+          if ( w_old == 0.0 )
+          {
+            // we didn't change
+            changed = 0;
+
+            // and wasted a basis
+            wasted_basis += 1;
+          }
+          else
+          {
+            // we changed
+            changed = 1;
+
+            // must update num non_zero
+            non_zero -= 1;
+          }
+        }
+        // process changes if necessary
+        if ( changed == 1 )
+        {
+          // update the expected values
+          double w_diff = w_new - w_old;
+          for ( int i = 0; i < fnum; i++ )
+          {
+            double E_old = exp ( Xw[i].get ( 0 ) );
+            double val = X[i].get ( basis ) * w_diff;
+            if ( Xw[i].get ( 0 ) == 0.0 )
+            {
+              if ( fabs ( val ) > 10e-7 )
+                Xw[i][0] = val;
+            }
+            else
+              Xw[i][0] += X[i].get ( basis ) * w_diff;
+            double E_new_m = exp ( Xw[i].get ( 0 ) );
+
+            S[i] += E_new_m - E_old;
+          }
+
+          // update the weight
+          if ( w_new == 0.0 )
+          {
+            if ( weight.get ( basis ) != 0.0 )
+            {
+              weight.erase ( basis );
+            }
+          }
+          else
+            weight[basis] = w_new;
+          // keep track of the sqrt sum squared diffs
 //#pragma omp critical
-					sum2_w_diff += w_diff*w_diff;
-				}
-	  			// no matter what we keep track of the old
+          sum2_w_diff += w_diff * w_diff;
+        }
+        // no matter what we keep track of the old
 //#pragma omp critical
-				sum2_w_old += w_old*w_old;
-			}
-		}
+        sum2_w_old += w_old * w_old;
+      }
+    }
 
-    	// finished a cycle, assess convergence
-		incr = sqrt(sum2_w_diff) / (sqrt(sum2_w_old)+numeric_limits<double>::epsilon());
+    // finished a cycle, assess convergence
+    incr = sqrt ( sum2_w_diff ) / ( sqrt ( sum2_w_old ) + numeric_limits<double>::epsilon() );
 #ifdef SLRDEBUG
-		cout << "sum2_w_diff: " << sum2_w_diff << " sum2_w_old " << sum2_w_old << endl;
-		cout << "convcrit: " << incr << " tol: " << convergence_tol << endl;
-		//cout << "sum2_w_wold = " << sum2_w_old << " sum2_w_diff = " << sum2_w_diff << endl;
+    cout << "sum2_w_diff: " << sum2_w_diff << " sum2_w_old " << sum2_w_old << endl;
+    cout << "convcrit: " << incr << " tol: " << convergence_tol << endl;
+    //cout << "sum2_w_wold = " << sum2_w_old << " sum2_w_diff = " << sum2_w_diff << endl;
 #endif
-		if (incr < convergence_tol)
-		{
-      		// we converged!!!
-			break;
-		}
-	}
-
-  	// finished updating weights
-  	// assess convergence
-	cerr << "end regression after " << cycle << " steps"  << endl;
-	return cycle;
+    if ( incr < convergence_tol )
+    {
+      // we converged!!!
+      break;
+    }
+  }
+
+  // finished updating weights
+  // assess convergence
+  cerr << "end regression after " << cycle << " steps"  << endl;
+  return cycle;
 }

+ 93 - 93
classifier/fpclassifier/logisticregression/SLR.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file SLR.h
  * @brief implementation of Sparse Logistic Regression (SMLR) Classififier (one vs. all)
  * @author Björn Fröhlich
@@ -20,98 +20,98 @@ namespace OBJREC {
 
 class SLR : public NICE::Persistent
 {
-  //protected:
-	public:
-	//! the configuration file
-	const NICE::Config *conf;
-
-	//! section in the configfile
-	std::string confsection;
-	
-	//! weight vectors
-	SparseVector weight;
-	
-	//! the featurepool
-	FeaturePool fp;
-	
-	//! maximum number of iterations
-	int maxiter;
-	
-	//! Decay rate in the probability of resampling a zero weight.1.0 will immediately decrease to the min_resamp from 1.0, 0.0 will never decrease from 1.0.
-	double resamp_decay;
-	
-	//! convergence criterium for stepwise regression
-	double convergence_tol;
-	
-	//! Minimum resampling probability for zeroed weights"
-	double min_resamp;
-	
-	//! Feature Dimension
-	int fdim;
-	
-	//! The penalty term lambda. Larger values will give rise to	more sparsification
-	double lambda;
-	
-	//! how many samples per class should be used
-	double samplesperclass;
-	
-	//! for normalization
-	std::vector<double> minval, maxval;
-	
-    public:
-  
-	
-	/**
-	 * standard constructor
-	 * @param conf configfile
-	 * @param section section name in configfile for classifier
-	 */
-	SLR( const NICE::Config *conf, std::string section="SMLR");
-      
-	
-	/**
-	 * simple constructor -> does nothing
-	 */
-	SLR ();
-
-	/**
-	 * simple destructor
-	 */
-	~SLR();
-
-	/**
-	 * main classification function
-	 * @param pce input feature
-	 * @return a classification result
-	 */
-	double classify ( Example & pce );
-
-	/**
-	 * start training
-	 * @param fp a featurepool (how to handle which features...)
-	 * @param classno which class should be learned
-	 * @param examples input features
-	 */
-	void train ( FeaturePool & _fp, Examples & examples, int classno = 1 );
-
-	/**
-	 * clone this object
-	 * @return a copy of this object
-	 */
-	FeaturePoolClassifier *clone () const;
-
-	/**
-	 * perform the stepwise regression
-	 * @param x input features
-	 * @param classno which class should be learned
-	 * @return number of iterations
-	 */
-	int stepwise_regression(Examples &x, int classno = 1);
-	
-	/** IO functions */
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
+    //protected:
+  public:
+    //! the configuration file
+    const NICE::Config *conf;
+
+    //! section in the configfile
+    std::string confsection;
+
+    //! weight vectors
+    NICE::SparseVector weight;
+
+    //! the featurepool
+    FeaturePool fp;
+
+    //! maximum number of iterations
+    int maxiter;
+
+    //! Decay rate in the probability of resampling a zero weight.1.0 will immediately decrease to the min_resamp from 1.0, 0.0 will never decrease from 1.0.
+    double resamp_decay;
+
+    //! convergence criterium for stepwise regression
+    double convergence_tol;
+
+    //! Minimum resampling probability for zeroed weights"
+    double min_resamp;
+
+    //! Feature Dimension
+    int fdim;
+
+    //! The penalty term lambda. Larger values will give rise to more sparsification
+    double lambda;
+
+    //! how many samples per class should be used
+    double samplesperclass;
+
+    //! for normalization
+    std::vector<double> minval, maxval;
+
+  public:
+
+
+    /**
+     * standard constructor
+     * @param conf configfile
+     * @param section section name in configfile for classifier
+     */
+    SLR ( const NICE::Config *conf, std::string section = "SMLR" );
+
+
+    /**
+     * simple constructor -> does nothing
+     */
+    SLR ();
+
+    /**
+     * simple destructor
+     */
+    ~SLR();
+
+    /**
+     * main classification function
+     * @param pce input feature
+     * @return a classification result
+     */
+    double classify ( Example & pce );
+
+    /**
+     * start training
+     * @param fp a featurepool (how to handle which features...)
+     * @param classno which class should be learned
+     * @param examples input features
+     */
+    void train ( FeaturePool & _fp, Examples & examples, int classno = 1 );
+
+    /**
+     * clone this object
+     * @return a copy of this object
+     */
+    FeaturePoolClassifier *clone () const;
+
+    /**
+     * perform the stepwise regression
+     * @param x input features
+     * @param classno which class should be learned
+     * @return number of iterations
+     */
+    int stepwise_regression ( Examples &x, int classno = 1 );
+
+    /** IO functions */
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
 };
 
 } // namespace

+ 42 - 26
classifier/fpclassifier/randomforest/FPCDecisionTree.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FPCDecisionTree.h
 * @brief simple decision tree classifier
 * @author Erik Rodner
@@ -20,38 +20,54 @@
 #include "DecisionTree.h"
 
 #undef ROADWORKS
-#define ROADWORKS fthrow( Exception, "Persistent interface not yet implemented.");
+#define ROADWORKS fthrow( NICE::Exception, "Persistent interface not yet implemented.");
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** simple decision tree classifier */
 class FPCDecisionTree : public FeaturePoolClassifier
 {
 
-    protected:
-		const NICE::Config *conf;
-		DecisionTree *dt;
-		DecisionTreeBuilder *builder;
-
-    public:
-  
-		/** simple constructor */
-		FPCDecisionTree( const NICE::Config *conf, std::string section );
-		  
-		/** simple destructor */
-		virtual ~FPCDecisionTree();
-		 
-		virtual ClassificationResult classify ( Example & pce );
-
-		virtual void train ( FeaturePool & fp, Examples & examples );
-
-		DecisionTree & getTree () { return *dt; };
-
-		void restore (std::istream & is, int format = 0) { ROADWORKS };
-		void store (std::ostream & os, int format = 0) const { ROADWORKS };
-		void clear () { ROADWORKS };
-		FeaturePoolClassifier *clone () const { ROADWORKS };
+  protected:
+    const NICE::Config *conf;
+    DecisionTree *dt;
+    DecisionTreeBuilder *builder;
+
+  public:
+
+    /** simple constructor */
+    FPCDecisionTree ( const NICE::Config *conf, std::string section );
+
+    /** simple destructor */
+    virtual ~FPCDecisionTree();
+
+    virtual ClassificationResult classify ( Example & pce );
+
+    virtual void train ( FeaturePool & fp, Examples & examples );
+
+    DecisionTree & getTree ()
+    {
+      return *dt;
+    };
+
+    void restore ( std::istream & is, int format = 0 )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream & os, int format = 0 ) const
+    {
+      ROADWORKS
+    };
+    void clear ()
+    {
+      ROADWORKS
+    };
+    FeaturePoolClassifier *clone () const
+    {
+      ROADWORKS
+    };
 
 
 

+ 118 - 108
classifier/fpclassifier/randomforest/FPCRandomForests.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FPCRandomForests.h
 * @brief implementation of random set forests
 * @author Erik Rodner
@@ -22,117 +22,127 @@
 #include "DecisionTreeBuilder.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** implementation of random set forests */
 class FPCRandomForests : public FeaturePoolClassifier
 {
-    protected:
-		/** vector containing all decision trees */
-		std::vector<DecisionTree *> forest;	
-		
-		/** number of trees which will be generated in the
-		    during training */
-		int number_of_trees;
-
-		/** fraction of features used for each tree */
-		double features_per_tree;
-
-		/** fraction of training examples used for each tree */
-		double samples_per_tree;
-
-		/** use an equal number of training examples of each class
-		    to build a single tree */
-		bool use_simple_balancing;
-
-		/** weight examples according to a priori class probabilities
-		    as estimated using the distribution contained in the training data */
-		bool weight_examples;
-
-		/** if >0 then prune the trees using pruneTreeEntropy */
-		double minimum_entropy;
-
-		/** clear all examples after building a tree, this deletes
-		    all cached images contained in CachedExample etc. */
-		bool memory_efficient;
-
-		/** stored config to initialize a tree */
-		const NICE::Config *conf;
-
-		/** config section containing important config values */
-		std::string confsection;
-
-		/** pointer to the tree builder method */
-		DecisionTreeBuilder *builder;
-
-		/** out-of-bag statistics */
-		bool enableOutOfBagEstimates;
-		std::vector<std::pair<double, int> > oobResults;
-
-		/** classify using only a subset of all trees */
-		ClassificationResult classify ( Example & pce,
-							const std::vector<int> & outofbagtrees );
-
-		/** calculate out-of-bag statistics */
-		void calcOutOfBagEstimates ( std::vector< std::vector<int> > & outofbagtrees, 
-						 Examples & examples );
-		
-		/** save example selection per tree */
-		std::vector<std::vector<int> > exselection;
-
-    public:
-  
-		/** initialize the classifier */
-		FPCRandomForests( const NICE::Config *conf, 
-				  std::string section );
-		  
-		/** do nothing */
-		FPCRandomForests ();
-
-		/** simple destructor */
-		virtual ~FPCRandomForests();
-
-		/** main classification function */
-		ClassificationResult classify ( Example & pce );
-		int classify_optimize ( Example & pce );
-
-		/** get all leaf nodes for an given example (or inner nodes if depth is set to the level) */
-		void getLeafNodes ( Example & pce,
-					std::vector<DecisionNode *> & leafNodes,
-					int depth = 100000 );
-		/** get all leaf nodes (or inner nodes if depth is set to the level) */
-		void getAllLeafNodes ( std::vector<DecisionNode *> & leafNodes);
-		
-		/** perform training using a given feature pool and some training data */
-		virtual void train ( FeaturePool & fp,
-				 Examples & examples );
-
-		/** enumerate all nodes within the trees */
-		void indexDescendants ( std::map<DecisionNode *, std::pair<long, int> > & index ) const;
-
-		/** reset all counters in all nodes contained in the forest */
-		void resetCounters ();
-
-		/** direct access to all trees */
-		const std::vector<DecisionTree *> & getForest () const { return forest; };
-
-		/** direct write access to all trees */
-		std::vector<DecisionTree *> & getForestNonConst () { return forest; };
-
-		/** clone this object */
-		FeaturePoolClassifier *clone () const;
-		
-		/** get out of bag estimates */
-		std::vector<std::pair<double, int> > & getOutOfBagResults () { return oobResults; };
-
-		/** set the number of trees */
-		void setComplexity ( int size );
-
-		/** IO functions */
-		void restore (std::istream & is, int format = 0);
-		void store (std::ostream & os, int format = 0) const;
-		void clear ();
-	
+  protected:
+    /** vector containing all decision trees */
+    std::vector<DecisionTree *> forest;
+
+    /** number of trees which will be generated in the
+        during training */
+    int number_of_trees;
+
+    /** fraction of features used for each tree */
+    double features_per_tree;
+
+    /** fraction of training examples used for each tree */
+    double samples_per_tree;
+
+    /** use an equal number of training examples of each class
+        to build a single tree */
+    bool use_simple_balancing;
+
+    /** weight examples according to a priori class probabilities
+        as estimated using the distribution contained in the training data */
+    bool weight_examples;
+
+    /** if >0 then prune the trees using pruneTreeEntropy */
+    double minimum_entropy;
+
+    /** clear all examples after building a tree, this deletes
+        all cached images contained in CachedExample etc. */
+    bool memory_efficient;
+
+    /** stored config to initialize a tree */
+    const NICE::Config *conf;
+
+    /** config section containing important config values */
+    std::string confsection;
+
+    /** pointer to the tree builder method */
+    DecisionTreeBuilder *builder;
+
+    /** out-of-bag statistics */
+    bool enableOutOfBagEstimates;
+    std::vector<std::pair<double, int> > oobResults;
+
+    /** classify using only a subset of all trees */
+    ClassificationResult classify ( Example & pce,
+                                    const std::vector<int> & outofbagtrees );
+
+    /** calculate out-of-bag statistics */
+    void calcOutOfBagEstimates ( std::vector< std::vector<int> > & outofbagtrees,
+                                 Examples & examples );
+
+    /** save example selection per tree */
+    std::vector<std::vector<int> > exselection;
+
+  public:
+
+    /** initialize the classifier */
+    FPCRandomForests ( const NICE::Config *conf,
+                       std::string section );
+
+    /** do nothing */
+    FPCRandomForests ();
+
+    /** simple destructor */
+    virtual ~FPCRandomForests();
+
+    /** main classification function */
+    ClassificationResult classify ( Example & pce );
+    int classify_optimize ( Example & pce );
+
+    /** get all leaf nodes for an given example (or inner nodes if depth is set to the level) */
+    void getLeafNodes ( Example & pce,
+                        std::vector<DecisionNode *> & leafNodes,
+                        int depth = 100000 );
+    /** get all leaf nodes (or inner nodes if depth is set to the level) */
+    void getAllLeafNodes ( std::vector<DecisionNode *> & leafNodes );
+
+    /** perform training using a given feature pool and some training data */
+    virtual void train ( FeaturePool & fp,
+                         Examples & examples );
+
+    /** enumerate all nodes within the trees */
+    void indexDescendants ( std::map<DecisionNode *, std::pair<long, int> > & index ) const;
+
+    /** reset all counters in all nodes contained in the forest */
+    void resetCounters ();
+
+    /** direct access to all trees */
+    const std::vector<DecisionTree *> & getForest () const
+    {
+      return forest;
+    };
+
+    /** direct write access to all trees */
+    std::vector<DecisionTree *> & getForestNonConst ()
+    {
+      return forest;
+    };
+
+    /** clone this object */
+    FeaturePoolClassifier *clone () const;
+
+    /** get out of bag estimates */
+    std::vector<std::pair<double, int> > & getOutOfBagResults ()
+    {
+      return oobResults;
+    };
+
+    /** set the number of trees */
+    void setComplexity ( int size );
+
+    /** IO functions */
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
+
 
 };
 

+ 10 - 10
classifier/genericClassifierSelection.h

@@ -107,31 +107,31 @@ class GenericClassifierSelection
       } else if ( ( classifier_type == "dtgp" ) ) {
         classifier = new VCDTSVM ( conf );
       } else if ( ( classifier_type == "minimum_enclosing_ball" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCMinimumEnclosingBall ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
       } else if ( ( classifier_type == "gp_one_class" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCGPOneClass ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
       } else if ( ( classifier_type == "gp_regression_rbf" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCGPRegression ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
       } else if ( ( classifier_type == "gp_laplace_rbf" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCGPLaplace ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
       } else if ( ( classifier_type == "gp_regression_rbf_onevsall" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCGPRegOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
       } else if ( ( classifier_type == "gp_laplace_rbf_onevsall" ) ) {
-        string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
+        std::string kernel_type = conf->gS ( "Kernel", "kernel_function", "rbf" );
         classifier = new KCGPLaplaceOneVsAll ( conf, GenericKernelSelection::selectKernel ( conf, kernel_type ) );
-      } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_one\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+      } else if ( NICE::StringTools::regexMatch ( classifier_type, "^one_vs_one\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
         classifier = new VCOneVsOne ( conf, selectVecClassifier ( conf, submatches[1] ) );
-      } else if ( StringTools::regexMatch ( classifier_type, "^one_vs_all\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+      } else if ( NICE::StringTools::regexMatch ( classifier_type, "^one_vs_all\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
         classifier = new VCOneVsAll ( conf, selectVecClassifier ( conf, submatches[1] ) );
-      } else if ( StringTools::regexMatch ( classifier_type, "^random_forest\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
+      } else if ( NICE::StringTools::regexMatch ( classifier_type, "^random_forest\\(([^\\)]+)\\)$", submatches ) && ( submatches.size() == 2 ) ) {
         classifier = new VCPreRandomForest ( conf, "VCPreRandomForest", selectVecClassifier ( conf, submatches[1] ) );
       } else {
-        fthrow ( Exception, "Classifier type " << classifier_type << " not (yet) supported." << endl <<
+        fthrow ( NICE::Exception, "Classifier type " << classifier_type << " not (yet) supported." << std::endl <<
                  "(genericClassifierSelection.h contains a list of classifiers to choose from)" );
       }
 

+ 71 - 67
classifier/kernelclassifier/GPLaplaceOptimizationProblem.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file GPLaplaceOptimizationProblem.h
 * @author Erik Rodner
 * @date 12/09/2009
@@ -16,8 +16,9 @@
 #include "LaplaceApproximation.h"
 #include "LikelihoodFunction.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 /** @class GPLaplaceOptimizationProblem
  * Hyperparameter Optimization Problem for GP with Laplace Approximation
  *
@@ -26,70 +27,73 @@ namespace OBJREC {
 class GPLaplaceOptimizationProblem : public NICE::OptimizationProblemFirst
 {
 
-    protected:
-		KernelData *kernelData;
-		
-		NICE::VVector y;
-
-		double bestAvgLooError;
-		NICE::Vector bestLooParameters;
-		
-		ParameterizedKernel *kernel;
-
-		bool verbose;
-
-		const LikelihoodFunction *likelihoodFunction;
-		
-		std::vector<LaplaceApproximation *> laplaceApproximation;
-
-    public:
-  
-  
-  		/** initialize the optimization problem of laplace approximation integrated in
-		 *  GP
-		 *  @param kernelData object containing kernel matrix and other stuff
-		 *  @param y labels which have to -1 or 1
-		 *  @param kernel a parameterized kernel which provides derivations
-		 *  @param likelihoodFunction the type of the likelihood p(y_i|f_i), e.g. cumulative gaussian
-		 *  @param laplaceApproximation object containing cached matrices of the laplaceApproximation
-		 *  @param verbose print some status messages for debugging and boring work days
-		 **/
-     	GPLaplaceOptimizationProblem ( KernelData *kernelData, const NICE::Vector & y, 
-			ParameterizedKernel *kernel, const LikelihoodFunction *likelihoodFunction,
-			LaplaceApproximation *laplaceApproximation,
-			bool verbose );
-
-		/** initialize the multi-task optimization problem of laplace approximation 
-		 * integrated in GP
-		 *  @param kernelData object containing kernel matrix and other stuff
-		 *  @param y vector of labels which have to -1 or 1
-		 *  @param kernel a parameterized kernel which provides derivations
-		 *  @param likelihoodFunction the type of the likelihood p(y_i|f_i), e.g. cumulative gaussian
-		 *  @param laplaceApproximation object containing cached matrices of the laplaceApproximation
-		 *  @param verbose print some status messages for debugging and boring work days
-		 **/
-     	GPLaplaceOptimizationProblem ( KernelData *kernelData, const NICE::VVector & y, 
-			ParameterizedKernel *kernel, const LikelihoodFunction *likelihoodFunction,
-			const std::vector<LaplaceApproximation *> & laplaceApproximation,
-			bool verbose );
-
-		/** R.I.P. */
-		~GPLaplaceOptimizationProblem();
-
-		/** compute the negative log likelihood of the laplace approximation integrated GP */
-		double computeObjective();
-
-		/** compute the gradient of the negative log likelihood of the laplace approximation */
-		void computeGradient( NICE::Vector& newGradient );
-
-		/** set hyperparameters of the current kernel */
-		void setParameters ( const NICE::Vector & newParameters ) { parameters() = newParameters; };
-
-		/** use loo parameters */
-		void useLooParameters ();
-		
-		/** update cached stuff like cholesky factorization (KernelData.h) */
-		void update();
+  protected:
+    KernelData *kernelData;
+
+    NICE::VVector y;
+
+    double bestAvgLooError;
+    NICE::Vector bestLooParameters;
+
+    ParameterizedKernel *kernel;
+
+    bool verbose;
+
+    const LikelihoodFunction *likelihoodFunction;
+
+    std::vector<LaplaceApproximation *> laplaceApproximation;
+
+  public:
+
+
+    /** initialize the optimization problem of laplace approximation integrated in
+    *  GP
+    *  @param kernelData object containing kernel matrix and other stuff
+    *  @param y labels which have to -1 or 1
+    *  @param kernel a parameterized kernel which provides derivations
+    *  @param likelihoodFunction the type of the likelihood p(y_i|f_i), e.g. cumulative gaussian
+    *  @param laplaceApproximation object containing cached matrices of the laplaceApproximation
+    *  @param verbose print some status messages for debugging and boring work days
+    **/
+    GPLaplaceOptimizationProblem ( KernelData *kernelData, const NICE::Vector & y,
+                                   ParameterizedKernel *kernel, const LikelihoodFunction *likelihoodFunction,
+                                   LaplaceApproximation *laplaceApproximation,
+                                   bool verbose );
+
+    /** initialize the multi-task optimization problem of laplace approximation
+     * integrated in GP
+     *  @param kernelData object containing kernel matrix and other stuff
+     *  @param y vector of labels which have to -1 or 1
+     *  @param kernel a parameterized kernel which provides derivations
+     *  @param likelihoodFunction the type of the likelihood p(y_i|f_i), e.g. cumulative gaussian
+     *  @param laplaceApproximation object containing cached matrices of the laplaceApproximation
+     *  @param verbose print some status messages for debugging and boring work days
+     **/
+    GPLaplaceOptimizationProblem ( KernelData *kernelData, const NICE::VVector & y,
+                                   ParameterizedKernel *kernel, const LikelihoodFunction *likelihoodFunction,
+                                   const std::vector<LaplaceApproximation *> & laplaceApproximation,
+                                   bool verbose );
+
+    /** R.I.P. */
+    ~GPLaplaceOptimizationProblem();
+
+    /** compute the negative log likelihood of the laplace approximation integrated GP */
+    double computeObjective();
+
+    /** compute the gradient of the negative log likelihood of the laplace approximation */
+    void computeGradient ( NICE::Vector& newGradient );
+
+    /** set hyperparameters of the current kernel */
+    void setParameters ( const NICE::Vector & newParameters )
+    {
+      parameters() = newParameters;
+    };
+
+    /** use loo parameters */
+    void useLooParameters ();
+
+    /** update cached stuff like cholesky factorization (KernelData.h) */
+    void update();
 };
 
 }

+ 57 - 46
classifier/kernelclassifier/KCGPLaplace.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPLaplace.h
 * @brief Gaussian Process Regression for Classification
 * @author Erik Rodner
@@ -14,55 +14,66 @@
 #include "vislearning/classifier/kernelclassifier/LikelihoodFunction.h"
 
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
+
+namespace OBJREC
+{
 
-namespace OBJREC {
- 
 /** Gaussian Process Regression for Classification */
 class KCGPLaplace : public KernelClassifier
 {
-	protected:
-	
-		enum {
-			OPTIMIZATION_METHOD_RASMUSSEN = 0,
-			OPTIMIZATION_METHOD_TRUSTREGION
-		};
-
-
-		int optimizationMethod;
-
-		bool verbose;
-		bool optimizeParameters;
-
-		NICE::Vector y;
-
-		LaplaceApproximation laplaceApproximation;
-		LikelihoodFunction *likelihoodFunction;
-
-    public:
-  
-	/** simple constructor */
-	KCGPLaplace( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGPLaplace" );
-
-	/** copy constructor */
-	KCGPLaplace( const KCGPLaplace & src );
-      
-	/** simple destructor */
-	virtual ~KCGPLaplace();
-  	
-	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-	void teach ( KernelData *kernelData, const NICE::Vector & y );
-  	
-	/** classify an example by using its kernel values with the training set,
-		be careful with the order in @param kernelVector */
-	virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
-  
-  	/** clone this object */
-	KCGPLaplace *clone() const;
-
-	void restore(std::istream&, int) { ROADWORKS };
-	void store(std::ostream&, int) const { ROADWORKS };
-	void clear() { ROADWORKS };
+  protected:
+
+    enum
+    {
+      OPTIMIZATION_METHOD_RASMUSSEN = 0,
+      OPTIMIZATION_METHOD_TRUSTREGION
+    };
+
+
+    int optimizationMethod;
+
+    bool verbose;
+    bool optimizeParameters;
+
+    NICE::Vector y;
+
+    LaplaceApproximation laplaceApproximation;
+    LikelihoodFunction *likelihoodFunction;
+
+  public:
+
+    /** simple constructor */
+    KCGPLaplace ( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGPLaplace" );
+
+    /** copy constructor */
+    KCGPLaplace ( const KCGPLaplace & src );
+
+    /** simple destructor */
+    virtual ~KCGPLaplace();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    /** clone this object */
+    KCGPLaplace *clone() const;
+
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
 };
 
 

+ 43 - 33
classifier/kernelclassifier/KCGPLaplaceOneVsAll.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPLaplaceOneVsAll.h
 * @author Erik Rodner
 * @date 12/10/2009
@@ -15,10 +15,11 @@
 #include "vislearning/regression/gpregression/modelselcrit/genericGPModelSelection.h"
 #include "vislearning/classifier/kernelclassifier/LikelihoodFunction.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
 
 /** @class KCGPLaplaceOneVsAll
  * One vs. All GP Laplace classifier with joint optimization
@@ -29,44 +30,53 @@ namespace OBJREC {
 class KCGPLaplaceOneVsAll : public KernelClassifier
 {
 
-    protected:
-		NICE::Config confCopy;
-		std::string confSection;
+  protected:
+    NICE::Config confCopy;
+    std::string confSection;
+
+    bool optimizeParameters;
+
+    bool verbose;
+
+    int maxIterations;
+
+    std::vector<LaplaceApproximation *> laplaceApproximations;
+    LikelihoodFunction *likelihoodFunction;
 
-		bool optimizeParameters;
+    NICE::VVector ySetZeroMean;
+    NICE::VectorT<int> classnos;
 
-		bool verbose;
+    //GPMSCLooLikelihoodRegression *modelselcrit;
 
-		int maxIterations;
-	
-		std::vector<LaplaceApproximation *> laplaceApproximations;
-		LikelihoodFunction *likelihoodFunction;
+    bool useLooParameters;
 
-		NICE::VVector ySetZeroMean;
-		NICE::VectorT<int> classnos;
+  public:
 
-		//GPMSCLooLikelihoodRegression *modelselcrit;
+    /** simple constructor */
+    KCGPLaplaceOneVsAll ( const NICE::Config *conf, Kernel *kernelFunction = NULL, const std::string & section = "KCGPLaplaceOneVsAll" );
 
-		bool useLooParameters;
+    /** simple destructor */
+    virtual ~KCGPLaplaceOneVsAll();
 
-    public:
-		
-		/** simple constructor */
-		KCGPLaplaceOneVsAll( const NICE::Config *conf, Kernel *kernelFunction = NULL, const std::string & section = "KCGPLaplaceOneVsAll" );
-		  
-		/** simple destructor */
-		virtual ~KCGPLaplaceOneVsAll();
-     
-	 	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-		void teach ( KernelData *kernelData, const NICE::Vector & y );
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
 
-		/** classify an example by using its kernel values with the training set,
-			be careful with the order in @param kernelVector */
-		ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
 
-		void restore(std::istream&, int) { ROADWORKS };
-		void store(std::ostream&, int) const { ROADWORKS };
-		void clear() { ROADWORKS };
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
 
 };
 

+ 47 - 37
classifier/kernelclassifier/KCGPOneClass.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPOneClass.h
 * @brief One-Class Gaussian Process Regression for Classification
 * @author Erik Rodner + Mi.Ke.
@@ -14,50 +14,60 @@
 #include "vislearning/regression/regressionbase/RegressionAlgorithmKernel.h"
 
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
 
 #define VARIANCE_DETECTION_MODE 1
 #define MEAN_DETECTION_MODE 2
 
-namespace OBJREC {
- 
+namespace OBJREC
+{
+
 /** Gaussian Process Regression for One-Class Classification  (actually same as binary, don't use parameter optimization!!!)*/
 class KCGPOneClass : public KernelClassifier
 {
 
-    protected:
-		RegressionAlgorithmKernel *regressionAlgorithm;
-		NICE::Matrix InverseKernelMatrix; //only used when 'variance mode' is used and computeInverse=true
-		KernelData *kernelData; ////only used when 'variance mode' is used and computeInverse=false
-		NICE::Vector y;
-		int mode;
-		bool computeInverse;
-		double staticNoise;
-
-    public:
-  
-	/** simple constructor */
-	KCGPOneClass( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "OneClassGP" );
-
-	/** copy constructor */
-	KCGPOneClass( const KCGPOneClass & src );
-      
-	/** simple destructor */
-	virtual ~KCGPOneClass();
-  	
-	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-	void teach ( KernelData *kernelData, const NICE::Vector & y );
-  	
-	/** classify an example by using its kernel values with the training set,
-		be careful with the order in @param kernelVector */
-	virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
-  
-  	/** clone this object */
-	KCGPOneClass *clone() const;
-
-	void restore(std::istream&, int) { ROADWORKS };
-	void store(std::ostream&, int) const { ROADWORKS };
-	void clear() { ROADWORKS };
+  protected:
+    RegressionAlgorithmKernel *regressionAlgorithm;
+    NICE::Matrix InverseKernelMatrix; //only used when 'variance mode' is used and computeInverse=true
+    KernelData *kernelData; ////only used when 'variance mode' is used and computeInverse=false
+    NICE::Vector y;
+    int mode;
+    bool computeInverse;
+    double staticNoise;
+
+  public:
+
+    /** simple constructor */
+    KCGPOneClass ( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "OneClassGP" );
+
+    /** copy constructor */
+    KCGPOneClass ( const KCGPOneClass & src );
+
+    /** simple destructor */
+    virtual ~KCGPOneClass();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    /** clone this object */
+    KCGPOneClass *clone() const;
+
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
 };
 
 

+ 66 - 65
classifier/kernelclassifier/KCGPRegOneVsAll.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPRegOneVsAll.h
 * @author Erik Rodner
 * @date 12/10/2009
@@ -14,10 +14,11 @@
 
 #include <vector>
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
 
 /** @class KCGPRegOneVsAll
  * One vs. All GP regression classifier with joint optimization
@@ -28,67 +29,67 @@ namespace OBJREC {
 class KCGPRegOneVsAll : public KernelClassifier
 {
 
-    protected:
-		/** set of classifiers with the corresponding class */
-		std::vector< std::pair<int, RegGaussianProcess *> > classifiers;
-	
-		/** clone from prototype to generate new classifiers */
-		const RegGaussianProcess *prototype;
-
-		/** whether to optimize hyper-parameters */
-		bool optimizeParameters;
-
-		/** tell us something about what you are doing */
-		bool verbose;
-
-		/** maximum number of iterations of the hyper-parameter estimation */
-		int maxIterations;
-
-		TraceApproximation *traceApproximation;
-		GPMSCLooLikelihoodRegression *modelselcrit;
-
-		/** use the hyperparameters which lead to the best leave-one-out criterion */
-		bool useLooParameters;
-
-		/** whether to invest some computation time to estimate the uncertainty of the prediction */
-		bool computeUncertainty;
-
-		/** for computing uncertainties we need the cholesky decomposition of the kernel matrix */
-		NICE::Matrix choleskyMatrix;
-
-		/** whether to calibrate the probabilities using uncertainty estimates */
-		bool calibrateProbabilities;
-
-		/** how many samples should we draw to estimate the probabilities */
-		uint numSamplesCalibration;
-
-    public:
-  		/** simplest constructor */
-		KCGPRegOneVsAll(){};
-	    	
-		/** simple constructor */
-		KCGPRegOneVsAll( const NICE::Config *conf, Kernel *kernelFunction = NULL, const std::string & section = "KCGPRegOneVsAll" );
-		  
-		/** copy constructor */
-		KCGPRegOneVsAll( const KCGPRegOneVsAll &vcova );
-		
-		/** simple destructor */
-		virtual ~KCGPRegOneVsAll();
-     
-	 	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-		void teach ( KernelData *kernelData, const NICE::Vector & y );
-		void teach ( KernelData *kernelData, const std::vector<double> & y );
-
-		/** classify an example by using its kernel values with the training set,
-			be careful with the order in @param kernelVector */
-		ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
-
-		void restore(std::istream&, int);
-		void store(std::ostream&, int) const;
-		void clear();
-		
-		/** clone this object */
-		virtual KCGPRegOneVsAll *clone(void) const;
+  protected:
+    /** set of classifiers with the corresponding class */
+    std::vector< std::pair<int, RegGaussianProcess *> > classifiers;
+
+    /** clone from prototype to generate new classifiers */
+    const RegGaussianProcess *prototype;
+
+    /** whether to optimize hyper-parameters */
+    bool optimizeParameters;
+
+    /** tell us something about what you are doing */
+    bool verbose;
+
+    /** maximum number of iterations of the hyper-parameter estimation */
+    int maxIterations;
+
+    TraceApproximation *traceApproximation;
+    GPMSCLooLikelihoodRegression *modelselcrit;
+
+    /** use the hyperparameters which lead to the best leave-one-out criterion */
+    bool useLooParameters;
+
+    /** whether to invest some computation time to estimate the uncertainty of the prediction */
+    bool computeUncertainty;
+
+    /** for computing uncertainties we need the cholesky decomposition of the kernel matrix */
+    NICE::Matrix choleskyMatrix;
+
+    /** whether to calibrate the probabilities using uncertainty estimates */
+    bool calibrateProbabilities;
+
+    /** how many samples should we draw to estimate the probabilities */
+    uint numSamplesCalibration;
+
+  public:
+    /** simplest constructor */
+    KCGPRegOneVsAll() {};
+
+    /** simple constructor */
+    KCGPRegOneVsAll ( const NICE::Config *conf, Kernel *kernelFunction = NULL, const std::string & section = "KCGPRegOneVsAll" );
+
+    /** copy constructor */
+    KCGPRegOneVsAll ( const KCGPRegOneVsAll &vcova );
+
+    /** simple destructor */
+    virtual ~KCGPRegOneVsAll();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+    void teach ( KernelData *kernelData, const std::vector<double> & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    void restore ( std::istream&, int );
+    void store ( std::ostream&, int ) const;
+    void clear();
+
+    /** clone this object */
+    virtual KCGPRegOneVsAll *clone ( void ) const;
 
 };
 

+ 44 - 34
classifier/kernelclassifier/KCGPRegression.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPRegression.h
 * @brief Gaussian Process Regression for Classification
 * @author Erik Rodner
@@ -15,44 +15,54 @@
 #include "vislearning/regression/regressionbase/TeachWithInverseKernelMatrix.h"
 
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
+
+namespace OBJREC
+{
 
-namespace OBJREC {
- 
 /** Gaussian Process Regression for Classification */
 class KCGPRegression : public KernelClassifier
 {
 
-    protected:
-		RegressionAlgorithmKernel *regressionAlgorithm;
-		NICE::Vector y;
-
-    public:
-  
-	/** simple constructor */
-	KCGPRegression( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGPRegression" );
-
-	/** copy constructor */
-	KCGPRegression( const KCGPRegression & src );
-      
-	/** simple destructor */
-	virtual ~KCGPRegression();
-  	
-	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-	void teach ( KernelData *kernelData, const NICE::Vector & y );
-  	
-	/** classify an example by using its kernel values with the training set,
-		be careful with the order in @param kernelVector */
-	virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
-  
-  	/** clone this object */
-	KCGPRegression *clone() const;
-
-	void restore(std::istream&, int) { ROADWORKS };
-	void store(std::ostream&, int) const { ROADWORKS };
-	void clear() { ROADWORKS };
-
-	bool getOptimizeKernelParameters () const;
+  protected:
+    RegressionAlgorithmKernel *regressionAlgorithm;
+    NICE::Vector y;
+
+  public:
+
+    /** simple constructor */
+    KCGPRegression ( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGPRegression" );
+
+    /** copy constructor */
+    KCGPRegression ( const KCGPRegression & src );
+
+    /** simple destructor */
+    virtual ~KCGPRegression();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    /** clone this object */
+    KCGPRegression *clone() const;
+
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
+
+    bool getOptimizeKernelParameters () const;
 };
 
 

+ 46 - 36
classifier/kernelclassifier/KCMinimumEnclosingBall.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCGPOneClass.h
 * @brief One-Class Gaussian Process Regression for Classification
 * @author Erik Rodner + Mi.Ke.
@@ -12,7 +12,7 @@
 #include "vislearning/math/kernels/ParameterizedKernel.h"
 
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
 
 #define VARIANCE_DETECTION_MODE 1
 #define MEAN_DETECTION_MODE 2
@@ -21,44 +21,54 @@
 #include "vislearning/optimization/quadprog/Array.h"
 
 
-namespace OBJREC {
- 
+namespace OBJREC
+{
+
 /** Minimum Enclosing Ball Algorithm (For stationary kernels equal to 1-SVM)*/
 class KCMinimumEnclosingBall : public KernelClassifier
 {
 
-    protected:
-		int trainingSize;
-		double radius;
-		double aKa;
-		double nu;
-		QuadProgPP::Matrix<double> TwoK,Eye,Ones,ones;
-		QuadProgPP::Vector<double> alpha,b,minusDiagK,minusOne,zeros;
-
-    public:
-  
-	/** simple constructor */
-	KCMinimumEnclosingBall( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGMinimumEnclosingBall" );
-
-	/** copy constructor */
-	KCMinimumEnclosingBall( const KCMinimumEnclosingBall & src );
-      
-	/** simple destructor */
-	virtual ~KCMinimumEnclosingBall();
-  	
-	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-	void teach ( KernelData *kernelData, const NICE::Vector & y );
-  	
-	/** classify an example by using its kernel values with the training set,
-		be careful with the order in @param kernelVector */
-	virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf  ) const;
-  
-  	/** clone this object */
-	KCMinimumEnclosingBall *clone() const;
-
-	void restore(std::istream&, int) { ROADWORKS };
-	void store(std::ostream&, int) const { ROADWORKS };
-	void clear() { ROADWORKS };
+  protected:
+    int trainingSize;
+    double radius;
+    double aKa;
+    double nu;
+    QuadProgPP::Matrix<double> TwoK,Eye,Ones,ones;
+    QuadProgPP::Vector<double> alpha,b,minusDiagK,minusOne,zeros;
+
+  public:
+
+    /** simple constructor */
+    KCMinimumEnclosingBall ( const NICE::Config *conf, Kernel *kernel = NULL, const std::string & section = "KCGMinimumEnclosingBall" );
+
+    /** copy constructor */
+    KCMinimumEnclosingBall ( const KCMinimumEnclosingBall & src );
+
+    /** simple destructor */
+    virtual ~KCMinimumEnclosingBall();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    virtual ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    /** clone this object */
+    KCMinimumEnclosingBall *clone() const;
+
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
 
 };
 

+ 39 - 29
classifier/kernelclassifier/KCOneVsAll.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KCOneVsAll.h
 * @author Erik Rodner
 * @date 12/10/2009
@@ -9,43 +9,53 @@
 
 #include "vislearning/classifier/classifierbase/KernelClassifier.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 #undef ROADWORKS
-#define ROADWORKS fthrow(Exception, "Persistent interface not implemented!");
+#define ROADWORKS fthrow(NICE::Exception, "Persistent interface not implemented!");
 
 /** @class KCOneVsAll
- * One vs. All interface for kernel classifiers 
+ * One vs. All interface for kernel classifiers
  *
  * @author Erik Rodner
  */
 class KCOneVsAll : public KernelClassifier
 {
 
-    protected:
-		std::vector< std::pair<int, KernelClassifier *> > classifiers;
-		const KernelClassifier *prototype;
-		double noiseSigma;
-		bool verbose;
-
-    public:
-  
-		/** simple constructor */
-		KCOneVsAll( const NICE::Config *conf, const KernelClassifier *prototype, const std::string & section = "KCOneVsAll" );
-		  
-		/** simple destructor */
-		virtual ~KCOneVsAll();
-     
-	 	/** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
-		void teach ( KernelData *kernelData, const NICE::Vector & y );
-
-		/** classify an example by using its kernel values with the training set,
-			be careful with the order in @param kernelVector */
-		ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
-
-		void restore(std::istream&, int) { ROADWORKS };
-		void store(std::ostream&, int) const { ROADWORKS };
-		void clear() { ROADWORKS };
+  protected:
+    std::vector< std::pair<int, KernelClassifier *> > classifiers;
+    const KernelClassifier *prototype;
+    double noiseSigma;
+    bool verbose;
+
+  public:
+
+    /** simple constructor */
+    KCOneVsAll ( const NICE::Config *conf, const KernelClassifier *prototype, const std::string & section = "KCOneVsAll" );
+
+    /** simple destructor */
+    virtual ~KCOneVsAll();
+
+    /** teach the classifier with a kernel matrix and the corresponding class labels @param y ! */
+    void teach ( KernelData *kernelData, const NICE::Vector & y );
+
+    /** classify an example by using its kernel values with the training set,
+     be careful with the order in @param kernelVector */
+    ClassificationResult classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const;
+
+    void restore ( std::istream&, int )
+    {
+      ROADWORKS
+    };
+    void store ( std::ostream&, int ) const
+    {
+      ROADWORKS
+    };
+    void clear()
+    {
+      ROADWORKS
+    };
 
 };
 

+ 27 - 26
classifier/kernelclassifier/LHCumulativeGauss.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LHCumulativeGauss.h
 * @author Erik Rodner
 * @date 02/17/2010
@@ -9,38 +9,39 @@
 
 #include "LikelihoodFunction.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 /** @class LHCumulativeGauss
- * cumulative gauss function 
+ * cumulative gauss function
  *
  * @author Erik Rodner
  */
 class LHCumulativeGauss : public LikelihoodFunction
 {
 
-    protected:
-		double lengthScale;
-		double bias;
-
-    public:
-
-		/** a length scale of the likelihood function correspondes
-		 * to a an inverse scaling of the gp prior, thus you
-		 * could optimize this parameter by optimizing a hyperparameter
-		 * of the kernel function */
-		LHCumulativeGauss( double lengthScale = 1.0, double bias = 0.0 );
- 
- 		/** needed for hyperparameter estimation */
-		double thirdgrad ( double y, double f ) const;
-		double hessian ( double y, double f ) const;
-		double gradient ( double y, double f ) const;
-		double logLike ( double y, double f ) const;
-		double likelihood ( double y, double f ) const;
-
-		double predictAnalytically ( double fmean, double fvariance ) const;
-		
-		static double stdNormPDF (double x);
+  protected:
+    double lengthScale;
+    double bias;
+
+  public:
+
+    /** a length scale of the likelihood function correspondes
+     * to a an inverse scaling of the gp prior, thus you
+     * could optimize this parameter by optimizing a hyperparameter
+     * of the kernel function */
+    LHCumulativeGauss ( double lengthScale = 1.0, double bias = 0.0 );
+
+    /** needed for hyperparameter estimation */
+    double thirdgrad ( double y, double f ) const;
+    double hessian ( double y, double f ) const;
+    double gradient ( double y, double f ) const;
+    double logLike ( double y, double f ) const;
+    double likelihood ( double y, double f ) const;
+
+    double predictAnalytically ( double fmean, double fvariance ) const;
+
+    static double stdNormPDF ( double x );
 };
 
 }

+ 66 - 47
classifier/kernelclassifier/LaplaceApproximation.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LaplaceApproximation.h
 * @author Erik Rodner
 * @date 02/17/2010
@@ -11,59 +11,78 @@
 #include "vislearning/classifier/kernelclassifier/LikelihoodFunction.h"
 #include "vislearning/math/kernels/KernelData.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 /** @class LaplaceApproximation
- * some utility functions for laplace approximation 
+ * some utility functions for laplace approximation
  *
  * @author Erik Rodner
  */
 class LaplaceApproximation
 {
 
-    protected:
-		/** optimization settings */
-		uint maxiterations;
-		double minimumDelta;
-		bool verbose;
-
-		/** useful variables */
-		NICE::Vector mode;
-		NICE::Vector hessianW;
-		NICE::Vector gradientL;
-		NICE::Matrix cholB;
-
-		NICE::Vector a;
-
-		double objective;
-		double noiseTerm;
-
-		void updateCache ( const NICE::Matrix & kernelMatrix, const NICE::Vector & y, const LikelihoodFunction *likelihoodFunction );
-
-    public:
-  
-  		/** use standard settings */
-		LaplaceApproximation();
-
-		/** simple constructor using config values for numerical details */
-		LaplaceApproximation( const NICE::Config *conf, const std::string & section = "LaplaceApproximation" );
-		  
-		/** simple destructor */
-		virtual ~LaplaceApproximation();
-  
-  		void approximate ( KernelData *kernelData, const NICE::Vector & y,
-					   const LikelihoodFunction *likelihoodFunction );
-
-		double predict ( const NICE::Vector & kernelVector, double kernelSelf, const NICE::Vector & y, 
-				const LikelihoodFunction *likelihoodFunction ) const;
-
-		const NICE::Vector & getMode () const { return mode; };
-		const NICE::Vector & getHessian () const { return hessianW; };
-		const NICE::Vector & getGradient () const { return gradientL; };
-		const NICE::Vector & getAVector () const { return a; };
-		const NICE::Matrix & getCholeskyB () const { return cholB; };
-
-		double getObjective () const { return objective; };
+  protected:
+    /** optimization settings */
+    uint maxiterations;
+    double minimumDelta;
+    bool verbose;
+
+    /** useful variables */
+    NICE::Vector mode;
+    NICE::Vector hessianW;
+    NICE::Vector gradientL;
+    NICE::Matrix cholB;
+
+    NICE::Vector a;
+
+    double objective;
+    double noiseTerm;
+
+    void updateCache ( const NICE::Matrix & kernelMatrix, const NICE::Vector & y, const LikelihoodFunction *likelihoodFunction );
+
+  public:
+
+    /** use standard settings */
+    LaplaceApproximation();
+
+    /** simple constructor using config values for numerical details */
+    LaplaceApproximation ( const NICE::Config *conf, const std::string & section = "LaplaceApproximation" );
+
+    /** simple destructor */
+    virtual ~LaplaceApproximation();
+
+    void approximate ( KernelData *kernelData, const NICE::Vector & y,
+                       const LikelihoodFunction *likelihoodFunction );
+
+    double predict ( const NICE::Vector & kernelVector, double kernelSelf, const NICE::Vector & y,
+                     const LikelihoodFunction *likelihoodFunction ) const;
+
+    const NICE::Vector & getMode () const
+    {
+      return mode;
+    };
+    const NICE::Vector & getHessian () const
+    {
+      return hessianW;
+    };
+    const NICE::Vector & getGradient () const
+    {
+      return gradientL;
+    };
+    const NICE::Vector & getAVector () const
+    {
+      return a;
+    };
+    const NICE::Matrix & getCholeskyB () const
+    {
+      return cholB;
+    };
+
+    double getObjective () const
+    {
+      return objective;
+    };
 };
 
 }

+ 39 - 44
classifier/vclassifier/VCAmitSVM.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file VCAmitSVM.h
 * @brief interface to the svm generalization of Amit et al. 2007
 * @author Erik Rodner
@@ -10,57 +10,52 @@
 
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
- 
+
 #include "VCLearnFromSC.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** interface to the svm generalization of Amit et al. 2007 */
 class VCAmitSVM : public VCLearnFromSC
 {
 
-    protected:
-	double C;
-	double gamma;
-
-	// refactor-nice.pl: check this substitution
-	// old: string amitDir;
-	std::string amitDir;
-	// refactor-nice.pl: check this substitution
-	// old: string matlabExec;
-	std::string matlabExec;
-	// refactor-nice.pl: check this substitution
-	// old: string matlabArgs;
-	std::string matlabArgs;
-	
-    public:
-	// refactor-nice.pl: check this substitution
-	// old: Matrix W;
-	NICE::Matrix W;
-  
-	/** simple constructor */
-	VCAmitSVM( const NICE::Config *conf );
-      
-	/** simple destructor */
-	virtual ~VCAmitSVM();
-     
-	/** classify using simple vector */
-	// refactor-nice.pl: check this substitution
-	// old: virtual ClassificationResult classify ( const ice::Vector & x ) const;
-	virtual ClassificationResult classify ( const NICE::Vector & x ) const;
-
-	virtual void preTeach ( const LabeledSetVector & teachSet );
-
-	virtual void teach ( const LabeledSetVector & teachSet );
-
-	virtual void finishTeaching() {};
-
-	void restore ( std::istream & is, int format = 0 );
-
-	void store ( std::ostream & is, int format = 0 ) const;
-
-	void clear ();
+  protected:
+    double C;
+    double gamma;
+
+    std::string amitDir;
+
+    std::string matlabExec;
+
+    std::string matlabArgs;
+
+  public:
+
+    NICE::Matrix W;
+
+    /** simple constructor */
+    VCAmitSVM ( const NICE::Config *conf );
+
+    /** simple destructor */
+    virtual ~VCAmitSVM();
+
+    /** classify using simple vector */
+
+    virtual ClassificationResult classify ( const NICE::Vector & x ) const;
+
+    virtual void preTeach ( const LabeledSetVector & teachSet );
+
+    virtual void teach ( const LabeledSetVector & teachSet );
+
+    virtual void finishTeaching() {};
+
+    void restore ( std::istream & is, int format = 0 );
+
+    void store ( std::ostream & is, int format = 0 ) const;
+
+    void clear ();
 
 };
 

+ 28 - 27
classifier/vclassifier/VCCrossGeneralization.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file VCCrossGeneralization.h
 * @brief Combination of Classifiers
 * @author Erik Rodner
@@ -9,7 +9,7 @@
 #define VCCrossGeneralizationINCLUDE
 
 #ifdef NICE_USELIB_ICE
- 
+
 #include "VCLearnFromSC.h"
 
 #ifdef NICE_USELIB_ICE
@@ -19,47 +19,48 @@
 #include "core/basics/Config.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** Combination of Classifiers */
 class VCCrossGeneralization : public VCLearnFromSC
 {
 
-    protected:
-	bool useVotingNormalization;
+  protected:
+    bool useVotingNormalization;
+
+    VCSimpleGaussian gauss;
+
+    VCNearestNeighbour nnclassifier;
+
+    bool simpleGaussianFinished;
+
+    void normalizeVotings ( NICE::Vector & v ) const;
+
+  public:
 
-	VCSimpleGaussian gauss;
+    /** simple constructor */
+    VCCrossGeneralization ( const NICE::Config *conf );
 
-	VCNearestNeighbour nnclassifier;
+    /** simple destructor */
+    virtual ~VCCrossGeneralization();
 
-	bool simpleGaussianFinished;
-	
-	void normalizeVotings ( NICE::Vector & v ) const;
+    /** classify using simple vector */
 
-    public:
-  
-	/** simple constructor */
-	VCCrossGeneralization (const NICE::Config *conf);
-      
-	/** simple destructor */
-	virtual ~VCCrossGeneralization();
- 
-	/** classify using simple vector */
+    virtual ClassificationResult classify ( const NICE::Vector & x ) const;
 
-	virtual ClassificationResult classify ( const NICE::Vector & x ) const;
+    virtual void preTeach ( const LabeledSetVector & teachSet );
 
-	virtual void preTeach ( const LabeledSetVector & teachSet );
+    virtual void teach ( const LabeledSetVector & teachSet );
 
-	virtual void teach ( const LabeledSetVector & teachSet );
+    virtual void finishTeaching();
 
-	virtual void finishTeaching();
+    void restore ( std::istream & is, int format = 0 );
 
-	void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & is, int format = 0 ) const;
 
-	void store ( std::ostream & is, int format = 0 ) const;
+    void clear ();
 
-	void clear ();
-    
 };
 
 

+ 1 - 1
classifier/vclassifier/VCDTSVM.cpp

@@ -4,7 +4,7 @@
 
 #include "core/basics/StringTools.h"
 
-#define WRITE
+#undef WRITE
 
 using namespace OBJREC;
 

+ 35 - 31
classifier/vclassifier/VCOneVsOne.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file VCOneVsOne.h
 * @brief one-vs.-one svm voting
 * @author Erik Rodner
@@ -15,40 +15,44 @@
 #include "core/basics/triplet.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** one-vs.-one svm voting */
 class VCOneVsOne : public VecClassifier
 {
-    protected:
-	
-	VecClassifier *prototype;
-	std::vector< triplet<int, int, VecClassifier *> > classifiers;
-	bool use_weighted_voting;
-
-    public:
-  
-	/** simple constructor */
-	VCOneVsOne( const NICE::Config *conf, VecClassifier *prototype );
-      
-	/** simple destructor */
-	virtual ~VCOneVsOne();
-     
-	/** classify using simple vector */
-	ClassificationResult classify ( const NICE::Vector & x ) const;
-
-	/** classify using a simple vector */
-	void teach ( const LabeledSetVector & teachSet );
-	
-	void finishTeaching();
-
-
-	void read (const std::string& s, int format = 0);
-	void save (const std::string& s, int format = 0) const;
-
-	void clear () { classifiers.clear(); };
-	void store ( std::ostream & os, int format = 0 ) const;
-	void restore ( std::istream & is, int format = 0 );
+  protected:
+
+    VecClassifier *prototype;
+    std::vector< NICE::triplet<int, int, VecClassifier *> > classifiers;
+    bool use_weighted_voting;
+
+  public:
+
+    /** simple constructor */
+    VCOneVsOne ( const NICE::Config *conf, VecClassifier *prototype );
+
+    /** simple destructor */
+    virtual ~VCOneVsOne();
+
+    /** classify using simple vector */
+    ClassificationResult classify ( const NICE::Vector & x ) const;
+
+    /** classify using a simple vector */
+    void teach ( const LabeledSetVector & teachSet );
+
+    void finishTeaching();
+
+
+    void read ( const std::string& s, int format = 0 );
+    void save ( const std::string& s, int format = 0 ) const;
+
+    void clear ()
+    {
+      classifiers.clear();
+    };
+    void store ( std::ostream & os, int format = 0 ) const;
+    void restore ( std::istream & is, int format = 0 );
 };
 
 

+ 1 - 1
features/fpfeatures/SparseVectorFeature.h

@@ -15,7 +15,7 @@
  
 #include "core/basics/Config.h"
 #include "vislearning/cbaselib/Feature.h"
-#include "core/vector/SparseVector.h"
+#include "core/vector/SparseVectorT.h"
 
 
 namespace OBJREC {

+ 1 - 1
features/localfeatures/GenericLFSelection.h

@@ -83,7 +83,7 @@ class GenericLFSelection
 
 	  // no correct localfeature_type was given
 	  if ( lfrep == NULL )
-		  fthrow(Exception, "Local feature type not found: " << localfeature_type );
+		  fthrow(NICE::Exception, "Local feature type not found: " << localfeature_type );
 
 	  if ( conf->gB(section, "localfeature_cache_save", false) )
 	  {

+ 35 - 35
features/localfeatures/GenericLocalFeatureSelection.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file GenericLocalFeatureSelection.h
 * @brief This class provides a generic chooser function for different descriptors, which are derived from LocalFeature.
 * @author Eric Bach
@@ -23,42 +23,42 @@ namespace OBJREC {
 
 class GenericLocalFeatureSelection
 {
-    public:
-      /** LocalFeature Selector
-      * @brief This methode switches between the different LocalFeature-Types. One has to set the "localfeature_type" on a valid value and the methode returns a LocalFeatureRepresentation derived Object.
-      * @param[in] Config* - A pointer to the given configfile, which must contain "section" - "localfeature_type"
-      * @param[in] string  - This string defines the value for "section" in the configfile.
-      * @return LocalFeatureRepresentation* - The LocalFeatureRepresentation which contains the selected LocalFeature-Type.
-      */
-      static LocalFeature *selectLocalFeature ( const NICE::Config *conf, std::string section = "Features" )
+  public:
+    /** LocalFeature Selector
+    * @brief This methode switches between the different LocalFeature-Types. One has to set the "localfeature_type" on a valid value and the methode returns a LocalFeatureRepresentation derived Object.
+    * @param[in] Config* - A pointer to the given configfile, which must contain "section" - "localfeature_type"
+    * @param[in] string  - This string defines the value for "section" in the configfile.
+    * @return LocalFeatureRepresentation* - The LocalFeatureRepresentation which contains the selected LocalFeature-Type.
+    */
+    static LocalFeature *selectLocalFeature ( const NICE::Config *conf, std::string section = "Features" )
+    {
+      // return Value
+      LocalFeature *lf = NULL;
+
+      // string which defines the localfeature_type (for Ex. RGB, OppSift, Sift...)
+      std::string localfeature_type = conf->gS ( section, "localfeature_type", "not defined" );
+
+      // The prefix NICE_* indicates that this implementation comes from a NICE-Developer.
+      // Extern implementations can be added without NICE_* in this selection-class.
+      if ( localfeature_type == "NICE_SIFT" )
+      {
+        lf = new LocalFeatureSift ( conf );
+      }
+      else if ( localfeature_type == "NICE_RGBSIFT" )
       {
-	// return Value
-	LocalFeature *lf = NULL;
-      
-	// string which defines the localfeature_type (for Ex. RGB, OppSift, Sift...)
-	std::string localfeature_type = conf->gS(section, "localfeature_type", "not defined");
-	    
-	// The prefix NICE_* indicates that this implementation comes from a NICE-Developer.
-	// Extern implementations can be added without NICE_* in this selection-class.
-	if( localfeature_type == "NICE_SIFT" )
-	{
-	  lf = new LocalFeatureSift( conf );
-	}
-	else if( localfeature_type == "NICE_RGBSIFT" )
-	{
-	  lf = new LocalFeatureRGBSift( conf );
-	}
-	else if( localfeature_type == "NICE_OPPSIFT" )
-	{
-	  lf = new LocalFeatureOpponnentSift( conf );
-	}
-	
-	// no correct localfeature_type was given
-	if ( lf == NULL )
-	  fthrow(Exception, "Local feature type not found: " << localfeature_type );
-	
-	return lf;
+        lf = new LocalFeatureRGBSift ( conf );
       }
+      else if ( localfeature_type == "NICE_OPPSIFT" )
+      {
+        lf = new LocalFeatureOpponnentSift ( conf );
+      }
+
+      // no correct localfeature_type was given
+      if ( lf == NULL )
+        fthrow ( NICE::Exception, "Local feature type not found: " << localfeature_type );
+
+      return lf;
+    }
 };
 }
 

+ 163 - 163
features/localfeatures/LFColorWeijer.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file LFColorWeijer.cpp
  * @brief implementation of the color features mentioned in van de Weijer, J. & Schmid, C. Applying Color Names to Image Description (2007)
  * @author Björn Fröhlich
@@ -23,168 +23,168 @@ namespace OBJREC {
 class LFColorWeijer : public LocalFeature
 {
 
-    protected:
-		//! enum for 11 main colors
-		enum 
-		{
-			BLACK = 0,
-			BLUE,
-			BROWN,
-			GREY,
-			GREEN,
-			ORANGE,
-			PINK,
-			PURPLE,
-			RED,
-			WHITE,
-			YELLOW,
-			LASTCOLOR
-		};
-		
-		//! bins for L*, a* and b* chanel of L*a*b*
-		int bin[3];
-
-		//! upper limits for L*, a* and b* chanel of L*a*b*
-		double maxv[3];
-		
-		//! lower limits for L*, a* and b* chanel of L*a*b*
-		double minv[3];
-		
-		//! quantization interval for L*, a* and b* chanel of L*a*b* depending on bin, maxv and minv
-		double interval[3];
-		
-		//! destination of the computed lookuptable
-		std::string tfile;
-		
-		//! lookuptable for the probabilities (4d: colors, L-channel, a-channel, b-channel)
-		std::vector<std::vector<std::vector<std::vector<double> > > > hist;
-		
-		//! configuration file
-		const NICE::Config *conf;
-		
-    public:
-  
-		/** simple constructor */
-		LFColorWeijer( const NICE::Config *c);
-		  
-		/** simple destructor */
-		virtual ~LFColorWeijer();
-		
-		/**
-		 * get the size of the descriptor
-		 * @return size of descriptor
-		 */
-		int getDescSize () const;
-		
-		/**
-		 * get the colorWeijer features
-		 * @param img grayvalue input image
-		 * @param features features (output)
-		 * @param positions position of the features
-		 * @return 
-		 */
-		int getDescriptors ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & features ) const;
-		
-		/**
-		 * get the colorWeijer features
-		 * @param img color input image
-		 * @param features features (output)
-		 * @param positions given positions of the features
-		 * @return 
-		 */
-		int getDescriptors ( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & features ) const;
-		
-		/**
-		 * visualize the features
-		 * @param mark 
-		 * @param positions 
-		 * @param color 
-		 */
-		void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions,	size_t color ) const;
-		
-		/**
-		 * visualize the features
-		 * @param mark 
-		 * @param positions 
-		 * @param color 
-		 */
-		void visualizeFeatures ( NICE::ColorImage & mark, const NICE::VVector & features, const NICE::VVector & position ) const;
-		
-		/**
-		 * visualize the features
-		 * @param cimg 
-		 */
-		void visualizeFeatures ( const NICE::ColorImage & cimg) const;
-		
-		/**
-		 * visualize the features
-		 * @param cimg 
-		 * @param out
-		 */
-		void visualizeFeatures ( const NICE::ColorImage & cimg, NICE::ColorImage & out) const;
-		
-		/**
-		 * save parameters
-		 */
-		void store();
-		
-		
-		/**
-		 * load parameters
-		 */
-		void restore();
-		
-		/**
-		 * smooths the look up table
-		 */
-		void smooth();
-		
-		/**
-		 * normalizes the sum of a 3d histogram to 1
-		 * @param tab 3d histogram
-		 */
-		void normalize(std::vector<std::vector<std::vector<double> > > &tab);
-		
-		/**
-		 * creates a new and empty table
-		 * @return table of the size bin[0]xbin[1]xbin[2]
-		 */
-		std::vector<std::vector<std::vector<double > > > createTable();
-		
-		/**
-		 * finds a colorname in a given string
-		 * @param fn input string
-		 * @return number of the color
-		 */
-		int findColor(std::string &fn);
-		
-		/**
-		 * creates a new Histogram for input image depending on the image mask
-		 * @param cimg input image
-		 * @param hist histogram
-		 * @param mask which pixel should be consider
-		 */
-		void createHist(const NICE::ColorImage &cimg, std::vector<std::vector<std::vector<double> > > &hist, NICE::Image &mask);
-		
-		/**
-		 * train the lookuptable
-		 */
-		void train();
-		
-		
-		/**
-		 * add a 3d table to a 3d table elementwise
-		 * @param dest destination table
-		 * @param src source table
-		 */
-		void add(std::vector<std::vector<std::vector<double> > > &dest, std::vector<std::vector<std::vector<double> > > &src);
-		
-		/**
-		 * transform each pixel of an image
-		 * @param img input image
-		 * @param feats feature vector for each pixel
-		 */
-		void getFeats(const NICE::ColorImage &img, NICE::MultiChannelImageT<double> &feats);
+  protected:
+    //! enum for 11 main colors
+    enum
+    {
+      BLACK = 0,
+      BLUE,
+      BROWN,
+      GREY,
+      GREEN,
+      ORANGE,
+      PINK,
+      PURPLE,
+      RED,
+      WHITE,
+      YELLOW,
+      LASTCOLOR
+    };
+
+    //! bins for L*, a* and b* chanel of L*a*b*
+    int bin[3];
+
+    //! upper limits for L*, a* and b* chanel of L*a*b*
+    double maxv[3];
+
+    //! lower limits for L*, a* and b* chanel of L*a*b*
+    double minv[3];
+
+    //! quantization interval for L*, a* and b* chanel of L*a*b* depending on bin, maxv and minv
+    double interval[3];
+
+    //! destination of the computed lookuptable
+    std::string tfile;
+
+    //! lookuptable for the probabilities (4d: colors, L-channel, a-channel, b-channel)
+    std::vector<std::vector<std::vector<std::vector<double> > > > hist;
+
+    //! configuration file
+    const NICE::Config *conf;
+
+  public:
+
+    /** simple constructor */
+    LFColorWeijer ( const NICE::Config *c );
+
+    /** simple destructor */
+    virtual ~LFColorWeijer();
+
+    /**
+     * get the size of the descriptor
+     * @return size of descriptor
+     */
+    int getDescSize () const;
+
+    /**
+     * get the colorWeijer features
+     * @param img grayvalue input image
+     * @param features features (output)
+     * @param positions position of the features
+     * @return
+     */
+    int getDescriptors ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & features ) const;
+
+    /**
+     * get the colorWeijer features
+     * @param img color input image
+     * @param features features (output)
+     * @param positions given positions of the features
+     * @return
+     */
+    int getDescriptors ( const NICE::ColorImage & img, NICE::VVector & positions, NICE::VVector & features ) const;
+
+    /**
+     * visualize the features
+     * @param mark
+     * @param positions
+     * @param color
+     */
+    void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;
+
+    /**
+     * visualize the features
+     * @param mark
+     * @param positions
+     * @param color
+     */
+    void visualizeFeatures ( NICE::ColorImage & mark, const NICE::VVector & features, const NICE::VVector & position ) const;
+
+    /**
+     * visualize the features
+     * @param cimg
+     */
+    void visualizeFeatures ( const NICE::ColorImage & cimg ) const;
+
+    /**
+     * visualize the features
+     * @param cimg
+     * @param out
+     */
+    void visualizeFeatures ( const NICE::ColorImage & cimg, NICE::ColorImage & out ) const;
+
+    /**
+     * save parameters
+     */
+    void store();
+
+
+    /**
+     * load parameters
+     */
+    void restore();
+
+    /**
+     * smooths the look up table
+     */
+    void smooth();
+
+    /**
+     * normalizes the sum of a 3d histogram to 1
+     * @param tab 3d histogram
+     */
+    void normalize ( std::vector<std::vector<std::vector<double> > > &tab );
+
+    /**
+     * creates a new and empty table
+     * @return table of the size bin[0]xbin[1]xbin[2]
+     */
+    std::vector<std::vector<std::vector<double > > > createTable();
+
+    /**
+     * finds a colorname in a given string
+     * @param fn input string
+     * @return number of the color
+     */
+    int findColor ( std::string &fn );
+
+    /**
+     * creates a new Histogram for input image depending on the image mask
+     * @param cimg input image
+     * @param hist histogram
+     * @param mask which pixel should be consider
+     */
+    void createHist ( const NICE::ColorImage &cimg, std::vector<std::vector<std::vector<double> > > &hist, NICE::Image &mask );
+
+    /**
+     * train the lookuptable
+     */
+    void train();
+
+
+    /**
+     * add a 3d table to a 3d table elementwise
+     * @param dest destination table
+     * @param src source table
+     */
+    void add ( std::vector<std::vector<std::vector<double> > > &dest, std::vector<std::vector<std::vector<double> > > &src );
+
+    /**
+     * transform each pixel of an image
+     * @param img input image
+     * @param feats feature vector for each pixel
+     */
+    void getFeats ( const NICE::ColorImage &img, NICE::MultiChannelImageT<double> &feats );
 };
 
 

+ 40 - 40
features/localfeatures/LFReadCache.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LFReadCache.cpp
 * @brief read local features from file
 * @author Erik Rodner
@@ -18,26 +18,26 @@ using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
-LFReadCache::LFReadCache( const Config *conf,
-			  const LocalFeatureRepresentation *_lfrep,
-			  int _numFeatures ) : lfrep(_lfrep)
+LFReadCache::LFReadCache ( const Config *conf,
+                           const LocalFeatureRepresentation *_lfrep,
+                           int _numFeatures ) : lfrep ( _lfrep )
 {
-    //srand(time(NULL));
-    numFeatures = _numFeatures;
-    cachedir = conf->gS("cache", "root");
-    cachemode = Globals::getCacheMode ( conf->gS("cache", "mode", "cat") );
-    
-    std::string descFormat_s = conf->gS("cache", "descriptor_format", "binary_double");
-    if ( descFormat_s == "binary_double" )
-		descFormat = VVector::FILEFORMAT_BINARY_DOUBLE;
-    else if ( descFormat_s == "binary_uchar" )
-		descFormat = VVector::FILEFORMAT_BINARY_CHAR;
-    else if ( descFormat_s == "text_line" )
-		descFormat = VVector::FILEFORMAT_LINE;
-    else if ( (descFormat_s == "text_nice") || (descFormat_s == "text_ice"))
-		descFormat = VVector::FILEFORMAT_NICE;
-	else
-		fthrow(Exception, "Format " << descFormat_s << " is unknown.");
+  //srand(time(NULL));
+  numFeatures = _numFeatures;
+  cachedir = conf->gS ( "cache", "root" );
+  cachemode = Globals::getCacheMode ( conf->gS ( "cache", "mode", "cat" ) );
+
+  std::string descFormat_s = conf->gS ( "cache", "descriptor_format", "binary_double" );
+  if ( descFormat_s == "binary_double" )
+    descFormat = VVector::FILEFORMAT_BINARY_DOUBLE;
+  else if ( descFormat_s == "binary_uchar" )
+    descFormat = VVector::FILEFORMAT_BINARY_CHAR;
+  else if ( descFormat_s == "text_line" )
+    descFormat = VVector::FILEFORMAT_LINE;
+  else if ( ( descFormat_s == "text_nice" ) || ( descFormat_s == "text_ice" ) )
+    descFormat = VVector::FILEFORMAT_NICE;
+  else
+    fthrow ( Exception, "Format " << descFormat_s << " is unknown." );
 }
 
 LFReadCache::~LFReadCache()
@@ -46,39 +46,39 @@ LFReadCache::~LFReadCache()
 
 int LFReadCache::getDescSize () const
 {
-	if ( lfrep == NULL ) {
-		fthrow(Exception, "Unable to get descriptor size! (cache mode)");
-		return -1;
-	} else {
-    	return lfrep->getDescSize();
-	}
+  if ( lfrep == NULL ) {
+    fthrow ( Exception, "Unable to get descriptor size! (cache mode)" );
+    return -1;
+  } else {
+    return lfrep->getDescSize();
+  }
 }
 
 
-int LFReadCache::extractFeatures ( const NICE::ColorImage & img, 
-				   VVector & features, 
-				   VVector & positions) const
+int LFReadCache::extractFeatures ( const NICE::ColorImage & img,
+                                   VVector & features,
+                                   VVector & positions ) const
 {
-	return extractFeaturesTemplate<NICE::ColorImage> ( img, features, positions );
+  return extractFeaturesTemplate<NICE::ColorImage> ( img, features, positions );
 }
 
-int LFReadCache::extractFeatures ( const NICE::Image & img, 
-				   VVector & features, 
-				   VVector & positions) const
+int LFReadCache::extractFeatures ( const NICE::Image & img,
+                                   VVector & features,
+                                   VVector & positions ) const
 {
-	return extractFeaturesTemplate<NICE::Image> ( img, features, positions );
+  return extractFeaturesTemplate<NICE::Image> ( img, features, positions );
 }
 
-void LFReadCache::visualize ( NICE::Image & img, 
-		 const NICE::Vector & feature ) const
+void LFReadCache::visualize ( NICE::Image & img,
+                              const NICE::Vector & feature ) const
 {
-    lfrep->visualize ( img, feature );
+  lfrep->visualize ( img, feature );
 }
 
 void LFReadCache::visualizeFeatures ( NICE::Image & mark,
-				 const VVector & positions,
-				 size_t color ) const
+                                      const VVector & positions,
+                                      size_t color ) const
 {
-    lfrep->visualizeFeatures ( mark, positions, color );
+  lfrep->visualizeFeatures ( mark, positions, color );
 }
 

+ 80 - 70
features/localfeatures/LFReadCache.tcc

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LFReadCache.tcc
 * @author Erik Rodner
 * @date 02/14/2008
@@ -18,84 +18,94 @@
 #include "core/basics/FileMgt.h"
 #include "core/vector/VVector.h"
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 template <class ImageClass>
-int LFReadCache::extractFeaturesTemplate ( const ImageClass & img, 
-		  NICE::VVector & features, 
-		  NICE::VVector & positions) const
+int LFReadCache::extractFeaturesTemplate ( const ImageClass & img,
+    NICE::VVector & features,
+    NICE::VVector & positions ) const
 {
-    std::string filename = Globals::getCacheFilename ( cachedir, cachemode );
-    std::string filename_desc = filename + ".desc";
-    std::string filename_pos = filename + ".key";
+  std::string filename = Globals::getCacheFilename ( cachedir, cachemode );
+  std::string filename_desc = filename + ".desc";
+  std::string filename_pos = filename + ".key";
+
+  int ret = 0;
+
+  if ( ! NICE::FileMgt::fileExists ( filename_desc ) ||
+       ! NICE::FileMgt::fileExists ( filename_pos ) )
+  {
+    fprintf ( stderr, "LFReadCache::extractFeatures: recovering data (%s,%s not found)\n", filename_desc.c_str(),
+              filename_pos.c_str() );
+    if ( lfrep == NULL )
+      fthrow ( NICE::Exception, "LocalFeatureRepresentation not available, recovering is impossible!" );
+
+    lfrep->extractFeatures ( img, features, positions );
+
+    features.save ( filename_desc, descFormat );
+    positions.save ( filename_pos, NICE::VVector::FILEFORMAT_LINE );
+  }
+  else
+  {
+    if ( ( descFormat == NICE::VVector::FILEFORMAT_BINARY_DOUBLE ) || ( descFormat == NICE::VVector::FILEFORMAT_BINARY_CHAR ) )
+    {
+      if ( lfrep == NULL )
+      {
+        fthrow ( NICE::Exception, "Raw binary format needs a LocalFeatureRepresentation as prototype" );
+      }
+      else
+      {
+        features.setBufSize ( lfrep->getDescSize() );
+      }
+    }
 
-    int ret = 0;
+    features.read ( filename_desc, descFormat );
+    positions.read ( filename_pos, NICE::VVector::FILEFORMAT_LINE );
+
+    if ( positions.size() != features.size() )
+    {
+      std::cerr << "LFReadCache::extractFeatures: format error ! positions.size=" << positions.size() <<
+                " features.size()=" << features.size() << std::endl;
+      std::cerr << "features: " << filename_desc << std::endl;
+      std::cerr << "positions: " << filename_pos << std::endl;
+      exit ( -1 );
+    }
 
-    if ( ! NICE::FileMgt::fileExists ( filename_desc ) ||
-	 ! NICE::FileMgt::fileExists ( filename_pos ) )
+    if ( ( numFeatures >= 0 ) && ( features.size() > ( size_t ) numFeatures ) )
     {
-		fprintf (stderr, "LFReadCache::extractFeatures: recovering data (%s,%s not found)\n", filename_desc.c_str(),
-			filename_pos.c_str());
-		if ( lfrep == NULL )
-			fthrow(Exception, "LocalFeatureRepresentation not available, recovering is impossible!");
-
-		lfrep->extractFeatures ( img, features, positions );
-
-		features.save ( filename_desc, descFormat );
-		positions.save ( filename_pos, NICE::VVector::FILEFORMAT_LINE );
-    } else {
-		if ( (descFormat == NICE::VVector::FILEFORMAT_BINARY_DOUBLE) || (descFormat == NICE::VVector::FILEFORMAT_BINARY_CHAR) )
-		{
-			if ( lfrep == NULL ) {
-				fthrow(Exception, "Raw binary format needs a LocalFeatureRepresentation as prototype");
-			} else {
-				features.setBufSize(lfrep->getDescSize());
-			}
-		}
-
-		features.read( filename_desc, descFormat );
-		positions.read ( filename_pos, NICE::VVector::FILEFORMAT_LINE );
-
-		if ( positions.size() != features.size() )
-		{
-			std::cerr << "LFReadCache::extractFeatures: format error ! positions.size=" << positions.size() <<
-			" features.size()=" << features.size() << std::endl;
-			std::cerr << "features: " << filename_desc << std::endl;
-			std::cerr << "positions: " << filename_pos << std::endl;
-			exit(-1);
-		}
-
-		if ( (numFeatures >= 0) && (features.size() > (size_t)numFeatures) ) {
-			size_t n = features.size() - numFeatures; // >= 1
-			fprintf (stderr, "LFReadCache: number of local features is restricted: localfeature_count %d, real %d\n",
-			numFeatures, (int)features.size() );
-
-			if ( n > (size_t)numFeatures ) {
-				NICE::VVector nf;
-				NICE::VVector np;
-				for ( size_t l = 0 ; l < (size_t)numFeatures ; l++ )
-				{
-					size_t i = rand() % features.size();
-					nf.push_back ( features[i] );
-					np.push_back ( positions[i] );
-					features.erase ( features.begin() + i );
-					positions.erase ( positions.begin() + i );
-				}
-				positions = np;
-				features = nf;
-			} else {
-				for ( size_t l = 0 ; l < n ; l++ )
-				{
-					size_t i = rand() % features.size();
-					features.erase ( features.begin() + i );
-					positions.erase ( positions.begin() + i );
-				}
-			}
-		}
+      size_t n = features.size() - numFeatures; // >= 1
+      fprintf ( stderr, "LFReadCache: number of local features is restricted: localfeature_count %d, real %d\n",
+                numFeatures, ( int ) features.size() );
+
+      if ( n > ( size_t ) numFeatures )
+      {
+        NICE::VVector nf;
+        NICE::VVector np;
+        for ( size_t l = 0 ; l < ( size_t ) numFeatures ; l++ )
+        {
+          size_t i = rand() % features.size();
+          nf.push_back ( features[i] );
+          np.push_back ( positions[i] );
+          features.erase ( features.begin() + i );
+          positions.erase ( positions.begin() + i );
+        }
+        positions = np;
+        features = nf;
+      }
+      else
+      {
+        for ( size_t l = 0 ; l < n ; l++ )
+        {
+          size_t i = rand() % features.size();
+          features.erase ( features.begin() + i );
+          positions.erase ( positions.begin() + i );
+        }
+      }
     }
+  }
 
 
-    return ret;
+  return ret;
 }
 
 }

+ 2 - 1
features/localfeatures/LFSiftPP.h

@@ -8,10 +8,11 @@
 #ifndef LFSIFTPPINCLUDE
 #define LFSIFTPPINCLUDE
 
+#include "core/imagedisplay/ImageDisplay.h"
+
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
 #include "core/image/ImageT.h"
-#include "core/imagedisplay/ImageDisplay.h"
 
 #include "core/basics/Config.h"
 #include "LocalFeatureRepresentation.h"

+ 73 - 73
features/localfeatures/LFWriteCache.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LFWriteCache.cpp
 * @brief read local features from file
 * @author Erik Rodner
@@ -28,21 +28,21 @@ using namespace NICE;
 
 
 
-LFWriteCache::LFWriteCache( const Config *conf,
-			    const LocalFeatureRepresentation *_lfrep) : lfrep(_lfrep)
+LFWriteCache::LFWriteCache ( const Config *conf,
+                             const LocalFeatureRepresentation *_lfrep ) : lfrep ( _lfrep )
 {
-    cachedir = conf->gS("cache", "root");
-    cachemode = Globals::getCacheMode ( conf->gS("cache", "mode", "cat") );
-    
-    std::string descFormat_s = conf->gS("cache", "descriptor_format", "binary_double");
-    if ( descFormat_s == "binary_double" )
-		descFormat = VVector::FILEFORMAT_BINARY_DOUBLE;
-    else if ( descFormat_s == "binary_uchar" )
-		descFormat = VVector::FILEFORMAT_BINARY_CHAR;
-    else if ( descFormat_s == "text_line" )
-		descFormat = VVector::FILEFORMAT_LINE;
-    else if ( descFormat_s == "text_ice" )
-		descFormat = VVector::FILEFORMAT_NICE;
+  cachedir = conf->gS ( "cache", "root" );
+  cachemode = Globals::getCacheMode ( conf->gS ( "cache", "mode", "cat" ) );
+
+  std::string descFormat_s = conf->gS ( "cache", "descriptor_format", "binary_double" );
+  if ( descFormat_s == "binary_double" )
+    descFormat = VVector::FILEFORMAT_BINARY_DOUBLE;
+  else if ( descFormat_s == "binary_uchar" )
+    descFormat = VVector::FILEFORMAT_BINARY_CHAR;
+  else if ( descFormat_s == "text_line" )
+    descFormat = VVector::FILEFORMAT_LINE;
+  else if ( descFormat_s == "text_ice" )
+    descFormat = VVector::FILEFORMAT_NICE;
 
 }
 
@@ -52,76 +52,76 @@ LFWriteCache::~LFWriteCache()
 
 int LFWriteCache::getDescSize () const
 {
-    return lfrep->getDescSize();
+  return lfrep->getDescSize();
 }
 
-int LFWriteCache::extractFeatures ( const NICE::Image & img, 
-		  VVector & features, 
-		  VVector & positions) const
+int LFWriteCache::extractFeatures ( const NICE::Image & img,
+                                    VVector & features,
+                                    VVector & positions ) const
 {
-    std::string filename = Globals::getCacheFilename( cachedir, cachemode );
-
-    int ret = lfrep->extractFeatures ( img, features, positions );
-    std::string filename_desc = filename + ".desc";
-    std::string filename_pos = filename + ".key";
-
-    struct stat dummy;
-    if ( stat ( filename_desc.c_str(), &dummy ) < 0 )
-    {
-		fprintf (stderr, "features: %d, positions: %d\n", (int)features.size(),
-			(int)positions.size() );
-		if ( features.size() > 0 )
-			fprintf (stderr, "feature dimension: %d %d\n", features[0].size(), lfrep->getDescSize() );
-		features.save ( filename_desc, descFormat );
-		positions.save ( filename_pos, VVector::FILEFORMAT_LINE );
-    } else {
-		fprintf (stderr, "description file %s exists !\n", filename_desc.c_str());
-    }
-
-
-    return ret;
+  std::string filename = Globals::getCacheFilename ( cachedir, cachemode );
+
+  int ret = lfrep->extractFeatures ( img, features, positions );
+  std::string filename_desc = filename + ".desc";
+  std::string filename_pos = filename + ".key";
+
+  struct stat dummy;
+  if ( stat ( filename_desc.c_str(), &dummy ) < 0 )
+  {
+    fprintf ( stderr, "features: %d, positions: %d\n", ( int ) features.size(),
+              ( int ) positions.size() );
+    if ( features.size() > 0 )
+      fprintf ( stderr, "feature dimension: %d %d\n", features[0].size(), lfrep->getDescSize() );
+    features.save ( filename_desc, descFormat );
+    positions.save ( filename_pos, VVector::FILEFORMAT_LINE );
+  } else {
+    fprintf ( stderr, "description file %s exists !\n", filename_desc.c_str() );
+  }
+
+
+  return ret;
 }
 
-int LFWriteCache::extractFeatures ( const NICE::ColorImage & img, 
-				    VVector & features, 
-				    VVector & positions) const
+int LFWriteCache::extractFeatures ( const NICE::ColorImage & img,
+                                    VVector & features,
+                                    VVector & positions ) const
 {
-	std::string filename = Globals::getCacheFilename( cachedir, cachemode );
-
-	int ret = lfrep->extractFeatures ( img, features, positions );
-	std::string filename_desc = filename + ".desc";
-	std::string filename_pos = filename + ".key";
-	
-	struct stat dummy;
-	
-	if ( stat ( filename_desc.c_str(), &dummy ) < 0 )
-	{
-		fprintf (stderr, "features: %d, positions: %d\n", (int)features.size(),
-			 (int)positions.size() );
-		if ( features.size() > 0 )
-			fprintf (stderr, "feature dimension: %d %d\n", features[0].size(), lfrep->getDescSize() );
-		features.save ( filename_desc, descFormat );
-		positions.save ( filename_pos, VVector::FILEFORMAT_LINE );
-	} 
-	else 
-	{
-		fprintf (stderr, "description file %s exists !\n", filename_desc.c_str());
-	}
-
-
-	return ret;
+  std::string filename = Globals::getCacheFilename ( cachedir, cachemode );
+
+  int ret = lfrep->extractFeatures ( img, features, positions );
+  std::string filename_desc = filename + ".desc";
+  std::string filename_pos = filename + ".key";
+
+  struct stat dummy;
+
+  if ( stat ( filename_desc.c_str(), &dummy ) < 0 )
+  {
+    fprintf ( stderr, "features: %d, positions: %d\n", ( int ) features.size(),
+              ( int ) positions.size() );
+    if ( features.size() > 0 )
+      fprintf ( stderr, "feature dimension: %d %d\n", features[0].size(), lfrep->getDescSize() );
+    features.save ( filename_desc, descFormat );
+    positions.save ( filename_pos, VVector::FILEFORMAT_LINE );
+  }
+  else
+  {
+    fprintf ( stderr, "description file %s exists !\n", filename_desc.c_str() );
+  }
+
+
+  return ret;
 }
 
-void LFWriteCache::visualize ( NICE::Image & img, 
-		 const NICE::Vector & feature ) const
+void LFWriteCache::visualize ( NICE::Image & img,
+                               const NICE::Vector & feature ) const
 {
-    lfrep->visualize ( img, feature );
+  lfrep->visualize ( img, feature );
 }
 
 void LFWriteCache::visualizeFeatures ( NICE::Image & mark,
-				 const VVector & positions,
-				 size_t color ) const
+                                       const VVector & positions,
+                                       size_t color ) const
 {
-    lfrep->visualizeFeatures ( mark, positions, color );
+  lfrep->visualizeFeatures ( mark, positions, color );
 }
 

+ 78 - 85
features/localfeatures/LFonHSG.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LFonHSG.cpp
 * @brief Implementation of the LocalFeatureHSG.h. See description there.
 * @author Eric Bach
@@ -6,122 +6,115 @@
 */
 
 /* LocalFeatureHSG Include */
-
 #include "vislearning/features/localfeatures/LFonHSG.h"
 
-using namespace OBJREC;
-using namespace NICE;
 using namespace std;
+using namespace NICE;
+using namespace OBJREC;
 
-LFonHSG::LFonHSG( const Config *conf, const string section )
-{	
-	/** initialization **/
-	this->lf = NULL;
+#ifdef NICE_USELIB_BOOST
+using namespace boost;
+#endif
+
+LFonHSG::LFonHSG (const Config *conf, const string section)
+{
+  /** initialization **/
+  this->lf = NULL;
 
-	/** get parameters for the grid **/
-	sampleScaling    = conf->gI( section, "sample_scaling", 50  );
-	scales		 = conf->gS( section, "scales"        , "1" );
-	// the scales are seperated by '+', like in the Van de Sande implementation
-	char separator = '+';
+  /** get parameters for the grid **/
+  sampleScaling    = conf->gI (section, "sample_scaling", 50);
+  scales		 = conf->gS (section, "scales"        , "1");
+  // the scales are seperated by '+', like in the Van de Sande implementation
+  char separator = '+';
 
-	/** get debuginformation **/
-	debug 		 = conf->gB( "debug", "show_log_HSG", false );
+  /** get debuginformation **/
+  debug 		 = conf->gB ("debug", "show_log_HSG", false);
 
-	/** generate the descriptor-instanz **/
-	lf = GenericLocalFeatureSelection::selectLocalFeature( conf, section );
+  /** generate the descriptor-instanz **/
+  lf = GenericLocalFeatureSelection::selectLocalFeature (conf, section);
+
+  /** parse scales string **/
+  debug && clog << "[log] LocalFeatureHSG::LocalFeatureHSG" << endl;
+  debug && clog << "[log] try to parse the 'scales-string': " << scales << " -> ";
 
-	/** parse scales string **/
-	debug && clog << "[log] LocalFeatureHSG::LocalFeatureHSG" << endl;
-	debug && clog << "[log] try to parse the 'scales-string': " << scales << " -> ";
-		
 #ifdef NICE_USELIB_BOOST
-    	typedef tokenizer<boost::char_separator<char> > tokenizer;
-    	char_separator<char> sep(separator);
-    	tokenizer tokens(scales, sep);		// parse the string into tokens
-    	for( tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter )
-	{
-	  debug && clog << *tok_iter << " ";	
-	  scalesV.push_back( strToFloat( *tok_iter ) );
-	}
+  typedef tokenizer<boost::char_separator<char> > tokenizer;
+  char_separator<char> sep (separator);
+  tokenizer tokens (scales, sep);		// parse the string into tokens
+  for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) {
+    debug && clog << *tok_iter << " ";
+    scalesV.push_back(StringTools::convert<float>(*tok_iter));
+  }
 #else // standard
-	vector<string> temp;
-	StringTools::split( scales, separator, temp );
-	for( vector<string>::const_iterator it = temp.begin(); it != temp.end(); ++it )
-	{
-	  debug && clog << *it << " ";	
-	  scalesV.push_back( strToFloat( *it ) );
-	}
+  vector<string> temp;
+  StringTools::split (scales, separator, temp);
+  for (vector<string>::const_iterator it = temp.begin(); it != temp.end(); ++it) {
+    debug && clog << *it << " ";
+    scalesV.push_back(StringTools::convert<float>(*it));
+    //scalesV.push_back (strToFloat (*it));
+  }
 #endif
-	debug && clog << endl;
+  debug && clog << endl;
 }
 
 LFonHSG::~LFonHSG()
 {
-	/** free memory of descriptors **/
+  /** free memory of descriptors **/
 }
 
-void LFonHSG::getPositionsOnHSG ( const unsigned int imageWidth, const unsigned int imageHeight, VVector& positions ) const
+void LFonHSG::getPositionsOnHSG (const unsigned int imageWidth, const unsigned int imageHeight, VVector& positions) const
 {
-	if( sampleScaling < 1 ){ cerr << "[err] sample-scaling (" << sampleScaling << ") musst be larger the 0!" << endl; return; }
-
-	debug && clog << "[log] LocalFeatureHSG::getPositionsOnHSG calculate ";
-
-	bool oddRow = true;
-	NICE::Vector pos( 4 );
-
-	/** we have to calculate the koo. for every different scale **/
-	for( vector <float>::const_iterator it = scalesV.begin(); it != scalesV.end(); ++it )
-	{
-		oddRow = true;
-
-		for( unsigned int j = sampleScaling; j <= ( imageHeight - sampleScaling ); j += sampleScaling )
-		{
-			for( unsigned int i = ( oddRow ? sampleScaling + sampleScaling / 2 : sampleScaling ); i <= ( imageWidth - sampleScaling ); i += sampleScaling )
-			{
-				pos[ 0] = i; pos[ 1] = j; pos[ 2] = *it; pos[ 3] = 0;
-				positions.push_back( pos );
-			}
-			oddRow = !oddRow;
-		}
-	}
+  if (sampleScaling < 1) {
+    cerr << "[err] sample-scaling (" << sampleScaling << ") musst be larger the 0!" << endl;
+    return;
+  }
+
+  debug && clog << "[log] LocalFeatureHSG::getPositionsOnHSG calculate ";
+
+  bool oddRow = true;
+  NICE::Vector pos (4);
+
+  /** we have to calculate the koo. for every different scale **/
+  for (vector <float>::const_iterator it = scalesV.begin(); it != scalesV.end(); ++it) {
+    oddRow = true;
+
+    for (unsigned int j = sampleScaling; j <= (imageHeight - sampleScaling); j += sampleScaling) {
+      for (unsigned int i = (oddRow ? sampleScaling + sampleScaling / 2 : sampleScaling); i <= (imageWidth - sampleScaling); i += sampleScaling) {
+        pos[ 0] = i;
+        pos[ 1] = j;
+        pos[ 2] = *it;
+        pos[ 3] = 0;
+        positions.push_back (pos);
+      }
+      oddRow = !oddRow;
+    }
+  }
 }
 
-int LFonHSG::extractFeatures ( const NICE::ColorImage & cimg, VVector & features, VVector & positions ) const
+int LFonHSG::extractFeatures (const NICE::ColorImage & cimg, VVector & features, VVector & positions) const
 {
-	/** To get the keypoint descriptor, we need the positions of the keypoints. **/
-	getPositionsOnHSG( cimg.width(), cimg.height(), positions );
+  /** To get the keypoint descriptor, we need the positions of the keypoints. **/
+  getPositionsOnHSG (cimg.width(), cimg.height(), positions);
 
-	/** calulate the descriptor-values **/
-	return lf->getDescriptors( cimg, positions, features );	
+  /** calulate the descriptor-values **/
+  return lf->getDescriptors (cimg, positions, features);
 }
 
 
-int LFonHSG::extractFeatures ( const NICE::Image & img, VVector & features, VVector & positions ) const
+int LFonHSG::extractFeatures (const NICE::Image & img, VVector & features, VVector & positions) const
 {
-	/** To get the keypoint descriptor, we need the positions of the keypoints. **/
-	getPositionsOnHSG( img.width(), img.height(), positions );
+  /** To get the keypoint descriptor, we need the positions of the keypoints. **/
+  getPositionsOnHSG (img.width(), img.height(), positions);
 
-	/** calculate the descriptor-values **/
-	return lf->getDescriptors( img, positions, features );
+  /** calculate the descriptor-values **/
+  return lf->getDescriptors (img, positions, features);
 }
 
-void LFonHSG::visualizeFeatures ( NICE::Image & mark, const VVector & positions, size_t color ) const
+void LFonHSG::visualizeFeatures (NICE::Image & mark, const VVector & positions, size_t color) const
 {
-	// TODO: Implementierung des gewaehlten Descriptortyps aufrufen.
+  // TODO: Implementierung des gewaehlten Descriptortyps aufrufen.
 }
 
-float LFonHSG::strToFloat( const string str ) const
-{
-	float temp;
- 
-	stringstream ss;
-	ss << str;
-	ss >> temp;
-
-	return temp;
-}	
-		
-	
 
 
 

+ 49 - 47
features/localfeatures/LFonHSG.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file LFonHSG.h
 * @brief This class can be used to calculate the positions of keyfeatures in a Honeyrate Structure Grid (HSG). Also the class call the normal getDescriptors methode from a given type of SIFT.
 * @author Eric Bach
@@ -29,64 +29,66 @@
 /** STRINGTOOLS **/
 /** 1) boost **/
 #ifdef NICE_USELIB_BOOST
-  #include <boost/tokenizer.hpp>
+#include <boost/tokenizer.hpp>
 /** 2) NICE (standard) **/
 #else
-  #include <core/basics/StringTools.h>
+#include <core/basics/StringTools.h>
 #endif
 
 namespace OBJREC
 {
-	class LFonHSG : public LocalFeatureRepresentation
-	{		
-		/* private member */
-		private:
-			/* parameter for the grid */
-			//! stepwidhts of the grid
-			int sampleScaling;
-			//! which scales should be used
-			std::string scales;
-			//! vector which save the different scales
-			std::vector <float> scalesV;	
+class LFonHSG : public LocalFeatureRepresentation
+{
+    /* private member */
+  private:
+    /* parameter for the grid */
+    //! stepwidhts of the grid
+    int sampleScaling;
+    //! which scales should be used
+    std::string scales;
+    //! vector which save the different scales
+    std::vector <float> scalesV;
+
+    /** Calculate the keypoint-positions by given imagesize, sample-spacing and scales.
+        @brief The methode returns the calculated positions on a honeyrate-grid. This
+        positions starts with (0;0).
+        @param[in] unsigned int imageWidth  - width (x) of the given image
+        @param[in] unsigned int imageHeight - heigth (y) of the given image
+        @param[in,out] NICE::VVector positions    - destination for the calculated positions
+    **/
+    void getPositionsOnHSG ( const unsigned int imageWidth,
+                             const unsigned int imageHeight,
+                             NICE::VVector& positions ) const;
+
+    //! simple methode to convert a string into float
+    float strToFloat ( const std::string str ) const;
 
-			/** Calculate the keypoint-positions by given imagesize, sample-spacing and scales.
-			    @brief The methode returns the calculated positions on a honeyrate-grid. This 
-				   positions starts with (0;0).
-			    @param[in] unsigned int imageWidth  - width (x) of the given image
-			    @param[in] unsigned int imageHeight - heigth (y) of the given image
-			    @param[in,out] NICE::VVector positions    - destination for the calculated positions
-			**/
-			void getPositionsOnHSG ( const unsigned int imageWidth,
-						 const unsigned int imageHeight,
-						 NICE::VVector& positions ) const;    
+    //! if true, print some log-output
+    bool debug;
 
-			//! simple methode to convert a string into float
-			float strToFloat( const std::string str ) const;
+    //! the descritor instanz
+    LocalFeature* lf;
 
-			//! if true, print some log-output
-			bool debug;
-			
-			//! the descritor instanz
-			LocalFeature* lf; 
+    /* public member */
+  public:
+    //! simple contructor
+    LFonHSG ( const NICE::Config *conf, const std::string section = "HSG" );
+    //! simple desctructor
+    ~LFonHSG();
 
-		/* public member */
-		public:
-			//! simple contructor
-			LFonHSG( const NICE::Config *conf, const std::string section = "HSG");
-			//! simple desctructor
-			~LFonHSG();
+    //! Returns the descriptorsize
+    int getDescSize() const {
+      return lf->getDescSize();
+    };
 
-			//! Returns the descriptorsize
-			int getDescSize() const { return lf->getDescSize(); };
+    //! Extract the descriptor-Values from a given grayscale-Image.
+    int extractFeatures ( const NICE::Image & img, NICE::VVector & features, NICE::VVector & positions ) const;
 
-			//! Extract the descriptor-Values from a given grayscale-Image.
-			int extractFeatures ( const NICE::Image & img, NICE::VVector & features, NICE::VVector & positions ) const;
+    //! Extract the descriptor-Values from a given color-Image.
+    int extractFeatures ( const NICE::ColorImage & cimg, NICE::VVector & features, NICE::VVector & positions ) const;
 
-			//! Extract the descriptor-Values from a given color-Image.
-      int extractFeatures ( const NICE::ColorImage & cimg, NICE::VVector & features, NICE::VVector & positions ) const;
-			
-			//! Visualisierung
-			void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;
-	};
+    //! Visualisierung
+    void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;
+};
 }
 #endif

+ 25 - 25
features/localfeatures/LocalFeatureOpponnentSift.cpp

@@ -7,7 +7,7 @@ using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
-LocalFeatureOpponnentSift::LocalFeatureOpponnentSift( const Config *conf ):LocalFeatureRGBSift(conf)
+LocalFeatureOpponnentSift::LocalFeatureOpponnentSift ( const Config *conf ) : LocalFeatureRGBSift ( conf )
 {
 }
 
@@ -15,29 +15,29 @@ LocalFeatureOpponnentSift::~LocalFeatureOpponnentSift()
 {
 }
 
-int LocalFeatureOpponnentSift::getDescriptors ( const NICE::ColorImage & cimg, 
-		VVector & positions,
-  VVector & descriptors ) const
+int LocalFeatureOpponnentSift::getDescriptors ( const NICE::ColorImage & cimg,
+    VVector & positions,
+    VVector & descriptors ) const
 {
-	NICE::ColorImage opimg(cimg.width(), cimg.height());
-	
-	for(int y = 0; y < (int)cimg.height(); y++)
-	{
-		for(int x = 0; x < (int)cimg.width(); x++)
-		{
-			// Farbkanaele auslesen
-			int r = cimg.getPixel(x,y,0);
-			int g = cimg.getPixel(x,y,1);
-			int b = cimg.getPixel(x,y,2);
-			
-			// Transformation in den Opponent Farbraum nach Van de Sande
-			int o1 = (int)(((double)(r-g)+255.0)/2.0);
-			int o2 = (int)(((double)(r+g-b)+510.0)/4.0);
-			int o3 = (int)((double)(r+g+b)/3.0);
-
-			opimg.setPixel(x,y,o1,o2,o3);
-		}
-	}
-	
-	return LocalFeatureRGBSift::getDescriptors(opimg, positions, descriptors);
+  NICE::ColorImage opimg ( cimg.width(), cimg.height() );
+
+  for ( int y = 0; y < ( int ) cimg.height(); y++ )
+  {
+    for ( int x = 0; x < ( int ) cimg.width(); x++ )
+    {
+      // Farbkanaele auslesen
+      int r = cimg.getPixel ( x, y, 0 );
+      int g = cimg.getPixel ( x, y, 1 );
+      int b = cimg.getPixel ( x, y, 2 );
+
+      // Transformation in den Opponent Farbraum nach Van de Sande
+      int o1 = ( int ) ( ( ( double ) ( r - g ) + 255.0 ) / 2.0 );
+      int o2 = ( int ) ( ( ( double ) ( r + g - b ) + 510.0 ) / 4.0 );
+      int o3 = ( int ) ( ( double ) ( r + g + b ) / 3.0 );
+
+      opimg.setPixel ( x, y, o1, o2, o3 );
+    }
+  }
+
+  return LocalFeatureRGBSift::getDescriptors ( opimg, positions, descriptors );
 }

+ 23 - 23
features/localfeatures/LocalFeatureOpponnentSift.h

@@ -19,36 +19,36 @@
 
 namespace OBJREC
 {
-	/** local feature with sift */
+/** local feature with sift */
 
-	class LocalFeatureOpponnentSift : public LocalFeatureRGBSift
-	{
+class LocalFeatureOpponnentSift : public LocalFeatureRGBSift
+{
 
-		protected:
-			int octaves;
-			int levels;
-			bool normalizeFeature;
-			int first_octave;
-			double magnif;
+  protected:
+    int octaves;
+    int levels;
+    bool normalizeFeature;
+    int first_octave;
+    double magnif;
 
-		public:
+  public:
 
-			/** simple constructor */
-			LocalFeatureOpponnentSift(const NICE::Config *conf);
+    /** simple constructor */
+    LocalFeatureOpponnentSift ( const NICE::Config *conf );
 
-			/** simple destructor */
+    /** simple destructor */
 
-			virtual ~LocalFeatureOpponnentSift();
+    virtual ~LocalFeatureOpponnentSift();
 
-			/**
-			 * get the descriptor
-			 * @param img input image
-			 * @param positions positions for the SIFT features
-			 * @param descriptors output
-			 * @return 0
-			 */
-			int getDescriptors(const NICE::ColorImage & cimg, NICE::VVector & positions, NICE::VVector & descriptors) const;
-	};
+    /**
+     * get the descriptor
+     * @param img input image
+     * @param positions positions for the SIFT features
+     * @param descriptors output
+     * @return 0
+     */
+    int getDescriptors ( const NICE::ColorImage & cimg, NICE::VVector & positions, NICE::VVector & descriptors ) const;
+};
 
 
 } // namespace

+ 62 - 66
features/localfeatures/LocalFeatureRGBSift.cpp

@@ -11,81 +11,77 @@ using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
-#undef DEBUG_show_one_picture_per_channel
 
-LocalFeatureRGBSift::LocalFeatureRGBSift( const Config *conf ):LocalFeatureSift(conf)
+LocalFeatureRGBSift::LocalFeatureRGBSift ( const Config *conf ) : LocalFeatureSift ( conf )
 {
-    deletemode = false;
+  deletemode = false;
 }
 
 LocalFeatureRGBSift::~LocalFeatureRGBSift()
 {
-	
+
 }
 
-int LocalFeatureRGBSift::getDescriptors ( const NICE::ColorImage & img, 
-				     VVector & positions,
-				     VVector & descriptors ) const
+int
+LocalFeatureRGBSift::getDescriptors ( const NICE::ColorImage & img, VVector & positions, VVector & descriptors ) const
 {
-	sortPositions(positions);
-	descriptors.clear();
-	// Fuer jede Position wird ein leerer NICE::Vector in descriptors eingefuegt
-	for(int i = 0; i < (int) positions.size(); i++)
-	{
-		NICE::Vector v;
-		descriptors.push_back(v);
-	}
-	
-	vector<VVector> desc( 3 );
-#ifndef DEBUG_show_one_picture_per_channel
-#pragma omp parallel for
-#endif
-	// Descriptor fuer jeden der 3 Kanaele berechnen
-	for(int i = 0; i < 3; i++)
-	{
-		NICE::Image tmp(img.width(), img.height());
+  sortPositions ( positions );
+  descriptors.clear();
+  for ( int i = 0; i < ( int ) positions.size(); i++ )
+  {
+    NICE::Vector v;
+    descriptors.push_back ( v );
+  }
 
-		for(int y = 0; y < img.height(); y++)
-		{
-			for(int x = 0; x < img.width(); x++)
-			{
-				tmp.setPixel(x,y,img.getPixel(x,y,i));
-			}
-		}
-#ifdef DEBUG_show_one_picture_per_channel
-		showImage( tmp );
-#endif
-		VVector pos = positions;
-		computeDesc(tmp, pos, desc[i]);
-	}
-	// ?
-	//desc[0] = desc[2];
-	for(int i = 0; i < 3; i++)
-	{
-		assert(desc[i].size() == descriptors.size());
-		
-		if(i == 0)
-		{
-#ifndef DEBUG_show_one_picture_per_channel
-#pragma omp parallel for
-#endif
-			for(int j = 0; j < (int)desc[i].size(); j++)
-			{
-				// kopiere den roten (1.)-Kanal in den Descriptorsvektor
-				descriptors[j] = desc[i][j];
-			}
-		}
-		else
-		{
-#ifndef DEBUG_show_one_picture_per_channel
-#pragma omp parallel for
+  vector<VVector> desc ( 3 );
+
+#ifdef NICE_USELIB_OPENMP
+  // check whether siftGPU should be used
+  int numberOfCPU = omp_get_num_procs();
+  int numberOfThreads = 0;
+  if ( isGpuUsed() )
+  {
+    // in case of siftGPU it is possible to use one device
+    numberOfThreads = 1;
+    clog << "[log] LocalFeatureRGBSift: no multithreading" << endl;
+  }
+  else
+  {
+    // in case of siftpp it is possible to use all given cores
+    numberOfThreads = numberOfCPU;
+    clog << "[log] LocalFeatureRGBSift: multithreading with (max) " << numberOfCPU << " threads" << endl;
+  }
 #endif
-			for(int j = 0; j < (int)desc[i].size(); j++)
-			{
-				descriptors[j].append(desc[i][j]);
-			}
-		}
-	}
-	
-	return positions.size();
+
+#pragma omp parallel for num_threads(numberOfThreads)
+  for ( int i = 0; i < 3; i++ ) {
+    NICE::Image tmp ( img.width(), img.height() );
+
+    for ( int y = 0; y < img.height(); y++ ) {
+      for ( int x = 0; x < img.width(); x++ ) {
+        tmp.setPixel ( x, y, img.getPixel ( x, y, i ) );
+      }
+    }
+    VVector pos = positions;
+    computeDesc ( tmp, pos, desc[i] );
+  }
+
+  for ( int i = 0; i < 3; i++ ) {
+    assert ( desc[i].size() == descriptors.size() );
+
+    if ( i == 0 ) {
+#pragma omp parallel for num_threads( numberOfCPU )
+      for ( int j = 0; j < ( int ) desc[i].size(); j++ ) {
+        descriptors[j] = desc[i][j];
+      }
+    }
+    else {
+#pragma omp parallel for num_threads( numberOfCPU )
+      for ( int j = 0; j < ( int ) desc[i].size(); j++ ) {
+        descriptors[j].append ( desc[i][j] );
+      }
+    }
+  }
+
+  return positions.size();
 }

+ 37 - 36
features/localfeatures/LocalFeatureRGBSift.h

@@ -1,8 +1,8 @@
-/** 
+/**
 * @file LocalFeatureRGBSift.h
 * @brief local feature with color sift
-* @author Björn Fröhlich
-* @date 03/08/2010
+* @author Björn Fröhlich
+* @date 03/10/2012 (Eric Bach)
 */
 
 #ifndef LocalFeatureRGBSiftINCLUDE
@@ -15,45 +15,46 @@
 #include "core/basics/Config.h"
 #include "vislearning/features/localfeatures/LocalFeatureSift.h"
 
-
 namespace OBJREC {
 
 /** local feature with sift */
 class LocalFeatureRGBSift : public LocalFeatureSift
 {
 
-    protected:
-	int octaves;
-	int levels;
-	bool normalizeFeature;
-	int first_octave;
-	double magnif;
-
-    public:
-  
-	/** simple constructor */
-	LocalFeatureRGBSift ( const NICE::Config *conf );
-      
-	/** simple destructor */
-
-	virtual ~LocalFeatureRGBSift();
-	
-	/**
-	 * returns the size of each the SIFT-Feature
-	 * @return 128
-	 */
-	int getDescSize() const { return 384; };
-	
-	/** 
-	 * get the descriptor
-	 * @param img input color image
-	 * @param positions positions for the SIFT features
-	 * @param descriptors output
-	 * @return 0
-	 */
-	virtual int getDescriptors ( const NICE::ColorImage & cimg, 
-			     NICE::VVector & positions,
-			     NICE::VVector & descriptors ) const;     
+  protected:
+    int octaves;
+    int levels;
+    bool normalizeFeature;
+    int first_octave;
+    double magnif;
+
+  public:
+
+    /** simple constructor */
+    LocalFeatureRGBSift ( const NICE::Config *conf );
+
+    /** simple destructor */
+
+    virtual ~LocalFeatureRGBSift();
+
+    /**
+     * returns the size of each the SIFT-Feature
+     * @return 128
+     */
+    int getDescSize() const {
+      return 384;
+    };
+
+    /**
+     * get the descriptor
+     * @param img input color image
+     * @param positions positions for the SIFT features
+     * @param descriptors output
+     * @return 0
+     */
+    virtual int getDescriptors ( const NICE::ColorImage & cimg,
+                                 NICE::VVector & positions,
+                                 NICE::VVector & descriptors ) const;
 };
 
 

+ 2 - 1
features/localfeatures/LocalFeatureRepresentation.h

@@ -8,10 +8,11 @@
 #ifndef LOCALFEATUREREPRESENTATIONINCLUDE
 #define LOCALFEATUREREPRESENTATIONINCLUDE
 
+#include "core/imagedisplay/ImageDisplay.h"
+
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
 #include "core/image/ImageT.h"
-#include "core/imagedisplay/ImageDisplay.h"
  
 #include <vector>
 #include "core/vector/VVector.h"

+ 260 - 181
features/localfeatures/LocalFeatureSift.cpp

@@ -1,32 +1,36 @@
-/** 
+/**
 * @file LocalFeatureSift.cpp
 * @brief local feature with sift
 * @author Erik Rodner
-* @date 02/05/2008
+* @date 03/10/2012
 */
-// #ifdef NICE_USELIB_ICE
-//   #include <image_nonvis.h>
-// #endif
 #include <iostream>
 
-#include "core/basics/Exception.h"
-
 #include "vislearning/features/localfeatures/sift.h"
 #include "vislearning/features/localfeatures/LocalFeatureSift.h"
 
+
 using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
 LocalFeatureSift::LocalFeatureSift( const Config *conf )
 {
+    this->conf = conf;
+
     octaves          = conf->gI("LFSiftPP", "octaves", 			6);
     levels           = conf->gI("LFSiftPP", "levels", 			3);
-    first_octave     = conf->gI("LFSiftPP", "first_octave", 		-1);
-    normalizeFeature = conf->gB("LFSiftPP", "normalize_feature", 	true );
-    magnif 	     = conf->gD("LFSiftPP", "magnif", 			3 );
-    deletemode       = conf->gB("LFSiftPP", "deletemode", 		true );	
-    integerValues    = conf->gB("LFSiftPP", "integer_values", 		true );
+    first_octave     = conf->gI("LFSiftPP", "first_octave", 	-1);
+    normalizeFeature = conf->gB("LFSiftPP", "normalize_feature", true );
+    magnif 	         = conf->gD("LFSiftPP", "magnif", 			3 );
+    deletemode       = conf->gB("LFSiftPP", "deletemode", 		true );
+    integerValues    = conf->gB("LFSiftPP", "integer_values", 	true );
+
+#ifdef NICE_USELIB_CUDASIFT
+    usegpu 	     	 = conf->gB("LFSiftPP", "use_siftgpu",		false );
+#else
+	usegpu = false;
+#endif
 }
 
 LocalFeatureSift::~LocalFeatureSift()
@@ -35,186 +39,261 @@ LocalFeatureSift::~LocalFeatureSift()
 
 void LocalFeatureSift::sortPositions(VVector & positions) const
 {
-	// < Key  , Val >
-	map<double, bool> scales;
-
-	// in der Map entpsrechende Skalewerte auf true setzten, jeder Skalewert ist dabei einzigartig
-	for( vector< NICE::Vector >::iterator i  = positions.begin(); 
-			i != positions.end();i++)
-	{
-		const NICE::Vector & pos = *i;
-		scales[pos[2]] = true;
-	}
-	
-	VVector newpositions;
-	
-	map<double,bool>::iterator iter;
-	// Map durchlaufen
-	for( iter = scales.begin(); iter != scales.end(); ++iter ) 
-	{
-		// alle Positionen durchlaufen
-		for( vector< NICE::Vector >::iterator i  = positions.begin(); 
-				   i != positions.end();i++)
-		{
-			
-			const NICE::Vector & pos = *i;
-			if(pos[2] == iter->first)
-			{
-				newpositions.push_back(pos);
-			}
-		}
-	}
-	positions = newpositions;
+    // < Key  , Val >
+    map<double, bool> scales;
+
+    for ( vector< NICE::Vector >::iterator i  = positions.begin();
+            i != positions.end();i++)
+    {
+        const NICE::Vector & pos = *i;
+        scales[pos[2]] = true;
+    }
+
+    VVector newpositions;
+
+    map<double,bool>::iterator iter;
+    for ( iter = scales.begin(); iter != scales.end(); ++iter )
+    {
+        for ( vector< NICE::Vector >::iterator i  = positions.begin();
+                i != positions.end();i++)
+        {
+
+            const NICE::Vector & pos = *i;
+            if (pos[2] == iter->first)
+            {
+                newpositions.push_back(pos);
+            }
+        }
+    }
+    positions = newpositions;
 }
 
 void LocalFeatureSift::computeDesc( const NICE::Image & img, VVector & positions, VVector & descriptors ) const
 {
-	
-	int         O      = octaves ;
-	int const   S      = levels ;
-	int const   omin   = first_octave;
-	float const sigman = .5 ; //.5
-	float const sigma0 = 1.6 * powf(2.0f, 1.0f / S) ;
-
-	if (O < 1) 
-	{
-		O = std::max(int(std::floor(log2
-				(std::min(img.width(),img.height()))) - omin - 3), 1) ;
-	}
-	
-	const unsigned char *blockimg = (unsigned char*) img.getPixelPointer();
-	float *blockimgfl = new float[img.width() * img.height()];
-	for ( int k = 0 ; k < img.width() * img.height() ; k++ )
-		blockimgfl[k] = blockimg[k];
-
-	VL::Sift sift( blockimgfl, img.width(), img.height(),
-				   sigman, sigma0, O, S, omin, -1, S+1) ;
-
-	sift.process ( blockimgfl, img.width(), img.height() );
-
-	sift.setMagnification ( magnif );
-	sift.setNormalizeDescriptor ( normalizeFeature );
-
-	const int descr_size = 128;
-	VL::float_t *descr_pt = new VL::float_t [descr_size];
-	VL::float_t angles[4] ;
-
-	NICE::Vector feature (descr_size);
-	NICE::Vector pos     ( 4 );
-
-
-	for( vector< NICE::Vector >::iterator i  = positions.begin(); 
-			i != positions.end();)
-	{
-		const NICE::Vector & pos = *i;
-		double x = pos[0];
-		double y = pos[1];
-		assert(pos[0] < img.width());
-		assert(pos[1] < img.height());
-		double s = pos[2];
-		bool deleteFeature = false;
-		VL::Sift::Keypoint kp = sift.getKeypoint (x,y,s);
-
-		double angle = 0.0;
-
-		if ( pos.size() < 4 ) 
-		{
-			int nangles = sift.computeKeypointOrientations(angles, kp);
-
-			if ( nangles > 0 )
-			{
-				angle = angles[0]; 
-			} 
-			else 
-			{
-				if(deletemode)
-					deleteFeature = true;
-				else
-					angle = 0;
-			}
-		} 
-		else 
-		{
-			angle = pos[3];
-		}
-
-		if ( ! deleteFeature ) 
-		{
-			sift.computeKeypointDescriptor ( descr_pt, kp, angle ); 		
-			for ( int j = 0 ; j < descr_size ; j++ )
-				// Umwandlung in Integer moegl.
-				feature[j] = (integerValues ? (int)(512*descr_pt[j]) : descr_pt[j]);
-
-			descriptors.push_back ( feature );
-
-			i++;
-		} 
-		else 
-		{
-			i = positions.erase(i);
-		}
-	}
-
-	delete [] blockimgfl;
-	delete [] descr_pt;
- 
+    if ( usegpu ) {
+        try {
+#ifdef NICE_USELIB_CUDASIFT
+            withGPU( img, positions, descriptors );
+#endif
+        }
+        catch ( runtime_error& rte ) {
+            cerr << "[err] LocalFeatureSift: " << rte.what() << endl;
+            clog << "[log] use SIFTPP implementation:" << endl;
+            withPP( img, positions, descriptors );
+        }
+    }
+    else {
+        withPP( img, positions, descriptors );
+    }
 }
 
 int LocalFeatureSift::getDescriptors ( const NICE::Image & img, VVector & positions, VVector & descriptors ) const
 {
-	sortPositions(positions);
-	
-	computeDesc(img, positions, descriptors);
-	
+    sortPositions(positions);
+
+    computeDesc(img, positions, descriptors);
+
     return 0;
 }
 
-void LocalFeatureSift::visualizeFeatures ( NICE::Image & mark,
-				 const VVector & positions,
-				 size_t color ) const
+void LocalFeatureSift::visualizeFeatures ( NICE::Image & mark, const VVector & positions, size_t color ) const
 {
-	fthrow(Exception, "LocalFeatureSift::visualizeFeatures -- not yet implemented due to old ICE version.");
-//TODO check this!
-// #ifdef NICE_USELIB_ICE
-//     ice::Image mark_ice = ice::NewImg ( mark.width(), 
-// 	mark.height(), 255 );
-//     for ( size_t k = 0 ; k < positions.size() ; k++ )
-//     {
-// 		const NICE::Vector & pos = positions[k];
-// 		ice::Matrix points ( 0, 2 );
-// 		const int size = 6;
-// 		points.Append ( ice::Vector(-size, -size) );
-// 		points.Append ( ice::Vector(-size, size) );
-// 		points.Append ( ice::Vector(size, size) );
-// 		points.Append ( ice::Vector(size, -size) );
-// 
-// 		ice::Trafo tr;
-// 
-// 		tr.Scale ( 0, 0, pos[2] );
-// 		tr.Rotate ( 0, 0, pos[3] );
-// 		tr.Shift ( pos[0], pos[1] );
-// 
-// 		ice::TransformList(tr, points);
-// 
-// 		for ( int j = 0 ; j < points.rows(); j++ )
-// 		{
-// 			if (points[j][0] < 0 ) 
-// 			points[j][0] = 0;
-// 			if (points[j][0] >= mark_ice->xsize) 
-// 			points[j][0] = mark_ice->xsize - 1;
-// 			if (points[j][1] < 0 ) 
-// 			points[j][1] = 0;
-// 			if (points[j][1] >= mark_ice->ysize) 
-// 			points[j][1] = mark_ice->ysize - 1;
-// 		}
-// 		ice::DrawPolygon ( points, color, mark_ice );
-//     }
-// 
-//     for ( unsigned int y = 0 ; y < mark.height(); y++ )
-// 		for ( unsigned int x = 0 ; x < mark.width(); x++ )
-// 			mark.setPixel(x,y, GetVal(mark_ice,x,y));
-// #else
-// 	cerr << "uses ice visualization, please install ice or change to NICE visualization" << endl;
-// #endif
+	/* TODO: switch to NICE instead of ICE
+    ice::Image mark_ice = ice::NewImg ( mark.width(),
+                                        mark.height(), 255 );
+    for ( size_t k = 0 ; k < positions.size() ; k++ )
+    {
+        const NICE::Vector & pos = positions[k];
+        ice::Matrix points ( 0, 2 );
+        const int size = 6;
+        points.Append ( ice::Vector(-size, -size) );
+        points.Append ( ice::Vector(-size, size) );
+        points.Append ( ice::Vector(size, size) );
+        points.Append ( ice::Vector(size, -size) );
+
+        ice::Trafo tr;
+
+        tr.Scale ( 0, 0, pos[2] );
+        tr.Rotate ( 0, 0, pos[3] );
+        tr.Shift ( pos[0], pos[1] );
+
+        ice::TransformList(tr, points);
+
+        for ( int j = 0 ; j < points.rows(); j++ )
+        {
+            if (points[j][0] < 0 )
+                points[j][0] = 0;
+            if (points[j][0] >= mark_ice->xsize)
+                points[j][0] = mark_ice->xsize - 1;
+            if (points[j][1] < 0 )
+                points[j][1] = 0;
+            if (points[j][1] >= mark_ice->ysize)
+                points[j][1] = mark_ice->ysize - 1;
+        }
+        ice::DrawPolygon ( points, color, mark_ice );
+    }
+
+    for ( unsigned int y = 0 ; y < mark.height(); y++ )
+        for ( unsigned int x = 0 ; x < mark.width(); x++ )
+            mark.setPixel(x,y, GetVal(mark_ice,x,y));*/
+}
+
+void LocalFeatureSift::withPP( const NICE::Image & img, VVector & positions, VVector & descriptors ) const
+{
+    int         O      = octaves ;
+    int const   S      = levels ;
+    int const   omin   = first_octave;
+    float const sigman = .5 ; //.5
+    float const sigma0 = 1.6 * powf(2.0f, 1.0f / S) ;
+
+    if (O < 1)
+    {
+        O = std::max(int(std::floor(log2
+                                    (std::min(img.width(),img.height()))) - omin - 3), 1) ;
+    }
+
+    const unsigned char *blockimg = (unsigned char*) img.getPixelPointer();
+    float *blockimgfl = new float[img.width() * img.height()];
+    for ( int k = 0 ; k < img.width() * img.height() ; k++ )
+        blockimgfl[k] = blockimg[k];
+
+    VL::Sift sift( blockimgfl, img.width(), img.height(),
+                   sigman, sigma0, O, S, omin, -1, S+1) ;
+
+    sift.process ( blockimgfl, img.width(), img.height() );
+
+    sift.setMagnification ( magnif );
+    sift.setNormalizeDescriptor ( normalizeFeature );
+
+    const int descr_size = 128;
+    VL::float_t *descr_pt = new VL::float_t [descr_size];
+    VL::float_t angles[4] ;
+
+    NICE::Vector feature (descr_size);
+    NICE::Vector pos     ( 4 );
+
+
+    for ( vector< NICE::Vector >::iterator i  = positions.begin();
+            i != positions.end();)
+    {
+        const NICE::Vector & pos = *i;
+        double x = pos[0];
+        double y = pos[1];
+        assert(pos[0] < img.width());
+        assert(pos[1] < img.height());
+        double s = pos[2];
+        bool deleteFeature = false;
+        VL::Sift::Keypoint kp = sift.getKeypoint (x,y,s);
+
+        double angle = 0.0;
+
+        if ( pos.size() < 4 )
+        {
+            int nangles = sift.computeKeypointOrientations(angles, kp);
+
+            if ( nangles > 0 )
+            {
+                angle = angles[0];
+            }
+            else
+            {
+                if (deletemode)
+                    deleteFeature = true;
+                else
+                    angle = 0;
+            }
+        }
+        else
+        {
+            angle = pos[3];
+        }
+
+        if ( ! deleteFeature )
+        {
+            sift.computeKeypointDescriptor ( descr_pt, kp, angle );
+            for ( int j = 0 ; j < descr_size ; j++ )
+                // Umwandlung in Integer moegl.
+                feature[j] = (integerValues ? (int)(512*descr_pt[j]) : descr_pt[j]);
+
+            descriptors.push_back ( feature );
+
+            i++;
+        }
+        else
+        {
+            i = positions.erase(i);
+        }
+    }
+
+    delete [] blockimgfl;
+    delete [] descr_pt;
 }
 
+#ifdef NICE_USELIB_CUDASIFT
+void LocalFeatureSift::withGPU(const NICE::Image& img, VVector& positions, VVector& descriptors) const
+{
+    // fill the parameter for
+    char* argv[] = {
+        // First octave to detect DOG keypoints
+        "-fo" , const_cast<char*> (StringTools::convertToString<int> (first_octave).c_str()),
+        // Maximum number of Octaves
+        "-no" , const_cast<char*> (StringTools::convertToString<int> (octaves).c_str()),
+        // Number of DOG levels in an octave.
+        "-d"  , const_cast<char*> (StringTools::convertToString<int> (levels).c_str()),
+        // Write unnormalized descriptor if specified.
+        const_cast<char*> (normalizeFeature ? "" : "-unn"),
+        // Descriptor grid size factor (magnif ??)
+        "-dw" , const_cast<char*> (StringTools::convertToString<float> (magnif).c_str()),
+        // verbose levels
+        "-v", "0"
+    };
+    int argc = sizeof (argv) / sizeof (char*);
+
+    // sift Instanz
+    SiftGPU sift;
+
+    // give parameter to sift
+    sift.ParseParam (argc, argv);
+
+    // check, whether siftgpu is full supported
+    int support = sift.CreateContextGL();
+    if( support != SiftGPU::SIFTGPU_FULL_SUPPORTED )
+      throw runtime_error( "SiftGPU-support is not given by your device.");
+
+    // set keypoints
+    const int numberOfKeypoints = positions.size();
+    SiftGPU::SiftKeypoint keys[numberOfKeypoints];
+
+    // copy the NICEKeypoints into SiftKeypoints
+    for (int i = 0; i < numberOfKeypoints; i++) {
+        keys[i].x = positions[i][0];
+        keys[i].y = positions[i][1];
+        keys[i].s = positions[i][2];
+        keys[i].o = positions[i][3];
+    }
+    sift.SetKeypointList (numberOfKeypoints, keys);
+
+    // run SIFT
+    const int imageWidth  = img.width();
+    const int imageHeight = img.height();
+    const unsigned char* rawImageData = img.getPixelPointer();
+
+    sift.RunSIFT (imageWidth, imageHeight, rawImageData, GL_LUMINANCE, GL_UNSIGNED_BYTE);
+
+    // get descriptors
+    const int descr_size = 128;
+    const int numberOfDescriptors = sift.GetFeatureNum();
+    float desc[descr_size * numberOfDescriptors];
+
+    sift.GetFeatureVector (NULL, desc);
+
+    Vector localDesc (descr_size);
+    // copy the SiftDescriptors into NICEDescriptors
+    for (int i = 0; i < numberOfDescriptors; i++) {
+        for (int j = 0; j < descr_size; j++) {
+            localDesc[j] = (integerValues ? (int) (512 * desc[i*descr_size+j]) : desc[i*descr_size+j]);
+        }
+        descriptors.push_back (localDesc);
+    }
+}
+#endif

+ 103 - 59
features/localfeatures/LocalFeatureSift.h

@@ -1,83 +1,127 @@
-/** 
+/**
 * @file LocalFeatureSift.h
-* @brief local feature with sift (without detector)
+* @brief local feature with sift
 * @author Erik Rodner
-* @date 02/05/2008
-
+* @date 03/10/2012 (Eric Bach)
+* @note some notes to the use of siftGPU (added by Eric Bach)
+*  - install cudaSift & siftGPU (see Makefile.config)
+*  - add to libdepend.inc: $(call PKG_DEPEND_EXT, CUDASIFT) to specify: -DNICE_USELIB_CUDASIFT as compilerflag
+*  - add to section [LFSiftPP] use_siftgpu=true (or 'false' to disable the gpu-support)
+*
+*  If you use the gpu-support just one device is supported until now.
+*  If your device do not support the siftGPU completly the class switch to "normal" sift.
+*  It is possible to compile this class without siftGPU, but then you must not specify the flag: -DNICE_USELIB_CUDASIFT.
 */
 #ifndef LOCALFEATURESIFTINCLUDE
 #define LOCALFEATURESIFTINCLUDE
 
+// NICE includes
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
 #include "core/image/ImageT.h"
 #include "core/imagedisplay/ImageDisplay.h"
 
 #include "core/basics/Config.h"
+#include "core/basics/StringTools.h"
 #include "LocalFeature.h"
 
+// std includes
+#include <iostream>
+#include <string>
+#include <stdexcept>
+
+// SiftGPU & GL
+#ifdef NICE_USELIB_CUDASIFT
+#include <src/SiftGPU.h>
+#include <GL/gl.h>
+#endif
+
 
 namespace OBJREC {
 
 /** local feature with sift */
 class LocalFeatureSift : public LocalFeature
 {
+  private:
+    const NICE::Config* conf;
+
+  protected:
+    int octaves;
+    int levels;
+    bool normalizeFeature;
+    int first_octave;
+    double magnif;
+    bool deletemode;
+    bool integerValues;
+
+    // for SiftGPU
+    bool usegpu;
+
+    float threshold;
+    float edgeThreshold;
+
+    void withPP ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors ) const;
+#ifdef NICE_USELIB_CUDASIFT
+    void withGPU ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors ) const;
+#endif
+
+  public:
+
+    /** simple constructor */
+    LocalFeatureSift ( const NICE::Config *conf );
+
+    /** simple destructor */
+
+    virtual ~LocalFeatureSift();
+
+    /**
+     * returns the size of each the SIFT-Feature
+     * @return 128
+     */
+    int getDescSize() const {
+      return 128;
+    };
+
+
+    //! returns true if gpu is used
+    bool isGpuUsed() const {
+#ifdef NICE_USELIB_CUDASIFT
+      return usegpu;
+#else
+      return false;
+#endif
+    };
+
+    /**
+     * get the descriptor
+     * @param img input image
+     * @param positions positions for the SIFT features
+     * @param descriptors output
+     * @return 0
+     */
+    virtual int getDescriptors ( const NICE::Image & img,
+                                 NICE::VVector & positions,
+                                 NICE::VVector & descriptors ) const;
+
+    /**
+     * computes the descriptor for a single image
+     * @param img
+     * @param positions
+     * @param descriptors
+     */
+    void computeDesc ( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors ) const;
+
+    /**
+     * sort positions by scales for faster computing of the Keypoint orientation
+     * @param positions
+     */
+    void sortPositions ( NICE::VVector & positions ) const;
+
+    void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;
+
+
+
 
-    protected:
-	int octaves;
-	int levels;
-	bool normalizeFeature;
-	int first_octave;
-	double magnif;
-	bool deletemode;
-	bool integerValues;
-
-	float threshold;
-	float edgeThreshold;
-
-    public:
-  
-	/** simple constructor */
-	LocalFeatureSift ( const NICE::Config *conf );
-      
-	/** simple destructor */
-
-	virtual ~LocalFeatureSift();
-	
-	/**
-	 * returns the size of each the SIFT-Feature
-	 * @return 128
-	 */
-	int getDescSize() const { return 128; };
-	
-	/** 
-	 * get the descriptor
-	 * @param img input image
-	 * @param positions positions for the SIFT features
-	 * @param descriptors output
-	 * @return 0
-	 */
-	virtual int getDescriptors ( const NICE::Image & img, 
-			     NICE::VVector & positions,
-			     NICE::VVector & descriptors ) const;
-				     
-	/**
-	 * computes the descriptor for a single image
-	 * @param img 
-	 * @param positions 
-	 * @param descriptors 
-	 */
-	void computeDesc( const NICE::Image & img, NICE::VVector & positions, NICE::VVector & descriptors ) const;
-	
-	/**
-	 * sort positions by scales for faster computing of the Keypoint orientation
-	 * @param positions 
-	 */
-	void sortPositions(NICE::VVector & positions) const;
-	
-	void visualizeFeatures ( NICE::Image & mark, const NICE::VVector & positions, size_t color ) const;
-
-     
 };
 
 

+ 6 - 3
features/localfeatures/libdepend.inc

@@ -1,3 +1,6 @@
-$(call PKG_DEPEND_EXT,ICE)
-$(call PKG_DEPEND_INT,vislearning/segmentation)
-$(call PKG_DEPEND_INT,vislearning/features/fbase)
+$(call PKG_DEPEND_EXT,CUDASIFT)
+$(call PKG_DEPEND_EXT,OPENMP)
+$(call PKG_DEPEND_INT,core)
+$(call PKG_DEPEND_INT,vislearning/baselib)
+$(call PKG_DEPEND_INT,vislearning/image)
+$(call PKG_DEPEND_INT,vislearning/features/fbase)

+ 55 - 39
features/simplefeatures/Codebook.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file Codebook.h
 * @brief feature codebook
 * @author Erik Rodner
@@ -16,7 +16,7 @@
 #include <string>
 
 #include "core/basics/Persistent.h"
-#include "core/vector/SparseVector.h"
+#include "core/vector/SparseVectorT.h"
 
 
 namespace OBJREC {
@@ -24,43 +24,59 @@ namespace OBJREC {
 /** feature codebook */
 class Codebook : public NICE::Persistent
 {
-    protected:
-	NICE::Vector thresholds;
-	NICE::Vector informativeMeasure;
-	NICE::VectorT<int> classnos;
-
-    public:
-	
-	/** simple destructor */
-	virtual ~Codebook() {};
-    
-	virtual void vote ( const NICE::Vector & feature, int & codebookEntry, 
-			      double & weight, double & distance ) const = 0;
-
-	virtual void vote ( const NICE::Vector & feature, NICE::Vector & histogram, int & codebookEntry, 
-			      double & weight, double & distance ) const;
-
-	virtual void vote ( const NICE::Vector & feature, NICE::SparseVector & votes ) const;
-    	
-	virtual bool allowsMultipleVoting () { return false; };	
-	virtual void add ( const Codebook *codebook ) = 0;
-	virtual void copy ( const Codebook *codebook );
-	virtual Codebook *clone () const = 0;
-
-	size_t getCodebookSize() const { return informativeMeasure.size(); };
-	void reinit ( int numCodebookEntries );
-
-	const NICE::Vector & getThresholds () const { return thresholds; };
-	const NICE::Vector & getInformativeMeasure () const { return informativeMeasure; };
-	const NICE::VectorT<int> & getClassNos () const { return classnos; };
-	
-	void setThresholds ( const NICE::Vector & _thresholds ) { thresholds = _thresholds; };
-	void setInformativeMeasure ( const NICE::Vector & _informativeMeasure ) { informativeMeasure = _informativeMeasure; };
-	void setClassNos ( const NICE::VectorT<int> & _classnos ) { classnos = _classnos; };
-
-	virtual void clear ();
-	virtual void restore ( std::istream & is, int format );
-	virtual void store ( std::ostream & os, int format ) const;
+protected:
+    NICE::Vector thresholds;
+    NICE::Vector informativeMeasure;
+    NICE::VectorT<int> classnos;
+
+public:
+
+    /** simple destructor */
+    virtual ~Codebook() {};
+
+    virtual void vote ( const NICE::Vector & feature, int & codebookEntry,
+                        double & weight, double & distance ) const = 0;
+
+    virtual void vote ( const NICE::Vector & feature, NICE::Vector & histogram, int & codebookEntry,
+                        double & weight, double & distance ) const;
+
+    virtual void vote ( const NICE::Vector & feature, NICE::SparseVector & votes ) const;
+
+    virtual bool allowsMultipleVoting () {
+        return false;
+    };
+    virtual void add ( const Codebook *codebook ) = 0;
+    virtual void copy ( const Codebook *codebook );
+    virtual Codebook *clone () const = 0;
+
+    size_t getCodebookSize() const {
+        return informativeMeasure.size();
+    };
+    void reinit ( int numCodebookEntries );
+
+    const NICE::Vector & getThresholds () const {
+        return thresholds;
+    };
+    const NICE::Vector & getInformativeMeasure () const {
+        return informativeMeasure;
+    };
+    const NICE::VectorT<int> & getClassNos () const {
+        return classnos;
+    };
+
+    void setThresholds ( const NICE::Vector & _thresholds ) {
+        thresholds = _thresholds;
+    };
+    void setInformativeMeasure ( const NICE::Vector & _informativeMeasure ) {
+        informativeMeasure = _informativeMeasure;
+    };
+    void setClassNos ( const NICE::VectorT<int> & _classnos ) {
+        classnos = _classnos;
+    };
+
+    virtual void clear ();
+    virtual void restore ( std::istream & is, int format );
+    virtual void store ( std::ostream & os, int format ) const;
 };
 
 

+ 669 - 669
math/cluster/GMM.cpp

@@ -17,760 +17,760 @@ using namespace std;
 
 GMM::GMM()
 {
-	gaussians = 3;
-	maxiter = 200;
-	featsperclass = 0;
-	tau = 10.0;
-	srand ( time (NULL) );
-	comp = false;
+  gaussians = 3;
+  maxiter = 200;
+  featsperclass = 0;
+  tau = 10.0;
+  srand ( time ( NULL ) );
+  comp = false;
 }
 
-GMM::GMM(int _gaussians):gaussians(_gaussians)
+GMM::GMM ( int _gaussians ) : gaussians ( _gaussians )
 {
-	maxiter = 200;
-	featsperclass = 0;
-	tau = 0.0;
-	srand ( time (NULL) );
-	pyramid = false;
-	comp = false;
+  maxiter = 200;
+  featsperclass = 0;
+  tau = 0.0;
+  srand ( time ( NULL ) );
+  pyramid = false;
+  comp = false;
 }
 
-GMM::GMM(const Config *conf, int _gaussians):gaussians(_gaussians)
+GMM::GMM ( const Config *conf, int _gaussians ) : gaussians ( _gaussians )
 {
-	this->conf = conf;
-	
-	if(gaussians < 2)
-		gaussians = conf->gI("GMM", "gaussians", 2 );
-		
-	maxiter = conf->gI("GMM", "maxiter", 200 );
-		
-	featsperclass = conf->gI("GMM", "featsperclass", 0 );
-	
-	tau = conf->gD("GMM", "tau", 100.0);
-	
-	pyramid = conf->gB("GMM", "pyramid", false);
-	
-	comp = false;
-	
-	srand ( time (NULL) );
+  this->conf = conf;
+
+  if ( gaussians < 2 )
+    gaussians = conf->gI ( "GMM", "gaussians", 2 );
+
+  maxiter = conf->gI ( "GMM", "maxiter", 200 );
+
+  featsperclass = conf->gI ( "GMM", "featsperclass", 0 );
+
+  tau = conf->gD ( "GMM", "tau", 100.0 );
+
+  pyramid = conf->gB ( "GMM", "pyramid", false );
+
+  comp = false;
+
+  srand ( time ( NULL ) );
 }
 
-void GMM::computeMixture(Examples examples)
+void GMM::computeMixture ( Examples examples )
 {
-	int fsize = (int)examples.size();
-	assert(fsize >= gaussians);
-	
-	dim = examples[0].second.vec->size();
-	
-	int samples = fsize;
-	if(featsperclass > 0)
-	{
-		samples = featsperclass*gaussians;
-		samples = std::min(samples, fsize);
-	}
-		
-	// Copy data in Matrix
-	VVector dataset;
-
-	cout << "reduced training data for GMM from " << fsize << " features to " << samples << " features.";
-	for(int i = 0; i < samples; i++)
-	{
-		int k = rand() % fsize;
-		NICE::Vector *vec = examples[k].second.vec;
-		dataset.push_back(*vec);
-	}
-	
-	computeMixture(dataset);
+  int fsize = ( int ) examples.size();
+  assert ( fsize >= gaussians );
+
+  dim = examples[0].second.vec->size();
+
+  int samples = fsize;
+  if ( featsperclass > 0 )
+  {
+    samples = featsperclass * gaussians;
+    samples = std::min ( samples, fsize );
+  }
+
+  // Copy data in Matrix
+  VVector dataset;
+
+  cout << "reduced training data for GMM from " << fsize << " features to " << samples << " features.";
+  for ( int i = 0; i < samples; i++ )
+  {
+    int k = rand() % fsize;
+    NICE::Vector *vec = examples[k].second.vec;
+    dataset.push_back ( *vec );
+  }
+
+  computeMixture ( dataset );
 }
 
-void GMM::computeMixture(const VVector &DataSet)
+void GMM::computeMixture ( const VVector &DataSet )
 {
-	// Learn the GMM model
-	assert(DataSet.size() >= (uint)gaussians);
-	//initEMkMeans(DataSet); // initialize the model
-	srand ( time (NULL) );
-	
-	bool poweroftwo = false;
-	int power = 1;
-	while(power <= gaussians)
-	{
-		if(gaussians == power)
-			poweroftwo = true;
-		power *= 2;
-	}
-	
-	if(poweroftwo && pyramid)
-	{
-		initEM(DataSet); // initialize the model
-		int g = 1;
-		
-		while(g <= gaussians)
-		{
-			cout << "g = " << g << endl;
-			doEM(DataSet, g);
-			
-			if(2*g <= gaussians)
-			{
-				for(int i = g; i < g*2; i++)
-				{
-					mu[i] = mu[i-g];
-					sparse_sigma[i] = sparse_sigma[i-g];
-					sparse_inv_sigma[i] = sparse_inv_sigma[i-g];
-					log_det_sigma[i] = log_det_sigma[i-g];
-					priors[i] = priors[i-g];
-					
-					double interval = 1.0;
-					for(int k = 0; k < (int)mu[i].size(); k++)
-					{
-						interval = mu[i][k];
-						interval = std::max(interval, 0.1);
-						double r = (interval*((double)rand()/(double)RAND_MAX))-interval/2.0;
-						mu[i][k] += r;
-					}
-				}
-			}
-			g *= 2;
-		}
-	}
-	else
-	{
-		initEMkMeans(DataSet); // initialize the model
-		doEM(DataSet, gaussians);
-	}
-	// performs EM
+  // Learn the GMM model
+  assert ( DataSet.size() >= ( uint ) gaussians );
+  //initEMkMeans(DataSet); // initialize the model
+  srand ( time ( NULL ) );
+
+  bool poweroftwo = false;
+  int power = 1;
+  while ( power <= gaussians )
+  {
+    if ( gaussians == power )
+      poweroftwo = true;
+    power *= 2;
+  }
+
+  if ( poweroftwo && pyramid )
+  {
+    initEM ( DataSet ); // initialize the model
+    int g = 1;
+
+    while ( g <= gaussians )
+    {
+      cout << "g = " << g << endl;
+      doEM ( DataSet, g );
+
+      if ( 2*g <= gaussians )
+      {
+        for ( int i = g; i < g*2; i++ )
+        {
+          mu[i] = mu[i-g];
+          sparse_sigma[i] = sparse_sigma[i-g];
+          sparse_inv_sigma[i] = sparse_inv_sigma[i-g];
+          log_det_sigma[i] = log_det_sigma[i-g];
+          priors[i] = priors[i-g];
+
+          double interval = 1.0;
+          for ( int k = 0; k < ( int ) mu[i].size(); k++ )
+          {
+            interval = mu[i][k];
+            interval = std::max ( interval, 0.1 );
+            double r = ( interval * ( ( double ) rand() / ( double ) RAND_MAX ) ) - interval / 2.0;
+            mu[i][k] += r;
+          }
+        }
+      }
+      g *= 2;
+    }
+  }
+  else
+  {
+    initEMkMeans ( DataSet ); // initialize the model
+    doEM ( DataSet, gaussians );
+  }
+  // performs EM
 }
 
-inline double diagDeterminant(const NICE::Vector &sparse_mat)
+inline double diagDeterminant ( const NICE::Vector &sparse_mat )
 {
-	double det = 1.0;
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		det *= sparse_mat[i];
-	}
-	
-	return det;
+  double det = 1.0;
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    det *= sparse_mat[i];
+  }
+
+  return det;
 }
 
-inline double logdiagDeterminant(const NICE::Vector &sparse_mat)
+inline double logdiagDeterminant ( const NICE::Vector &sparse_mat )
 {
-	double det = 0.0;
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		det += log(sparse_mat[i]);
-	}
+  double det = 0.0;
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    det += log ( sparse_mat[i] );
+  }
 
-	return det;
+  return det;
 }
 
-inline NICE::Vector diagInverse(const NICE::Vector &sparse_mat)
+inline NICE::Vector diagInverse ( const NICE::Vector &sparse_mat )
 {
-	NICE::Vector inv(sparse_mat.size());
-	for(int i = 0; i < (int)sparse_mat.size(); i++)
-	{
-		inv[i] = 1.0/sparse_mat[i];
-	}
-	return inv;
+  NICE::Vector inv ( sparse_mat.size() );
+  for ( int i = 0; i < ( int ) sparse_mat.size(); i++ )
+  {
+    inv[i] = 1.0 / sparse_mat[i];
+  }
+  return inv;
 }
 
-void GMM::initEMkMeans(const VVector &DataSet)
+void GMM::initEMkMeans ( const VVector &DataSet )
 {
-	/*init GMM with k-Means*/
-	KMeans k( gaussians );
-	VVector means;
-	vector<double> weights;
-	vector<int> assignment;
-	k.cluster ( DataSet, means, weights, assignment );
-	
-	int nData = DataSet.size();
-	this->dim = DataSet[0].size();
-	cdimval = dim*log(2*3.14159);
-	vector<int> pop(gaussians, 0);
-	priors.resize(gaussians);
-	mu = VVector(gaussians, dim);
-	log_det_sigma.clear();
-	vector<int> allk;
-	
-	NICE::Vector globmean(dim);
-	globmean.set(0.0);
-	
-	for(int n = 0; n < (int)DataSet.size(); n++) /* getting the max value for time */
-	{
-		globmean = globmean + DataSet[n];
-	}
-
-	globmean *= (1.0/nData);
-	
-	NICE::Vector sparse_globsigma;
-
-	sparse_globsigma.resize(dim);
-	sparse_globsigma.set(0.0);
-	
-	for(int i = 0; i < (int)DataSet.size(); i++) // Covariances updates
-	{
-		// nur diagonal Elemente berechnen
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = (DataSet[i][d] - globmean[d]);
-			sparse_globsigma[d] += diff*diff;
-		}
-	}
-	
-	sparse_globsigma *= (1.0/DataSet.size());
-	
-	for(int i = 0; i < gaussians; i++)
-	{
-		NICE::Vector _inv_sigma = diagInverse(sparse_globsigma);
-
-		sparse_sigma.push_back(sparse_globsigma);
-		sparse_inv_sigma.push_back(_inv_sigma);
-		log_det_sigma.push_back(logdiagDeterminant(sparse_globsigma));
-		mu[i] = means[i];
-		//priors[i]=1.0/(double)gaussians; // set equi-probables states 
-		priors[i]=weights[i]; // set kMeans weights 
-	}
+  /*init GMM with k-Means*/
+  KMeans k ( gaussians );
+  VVector means;
+  vector<double> weights;
+  vector<int> assignment;
+  k.cluster ( DataSet, means, weights, assignment );
+
+  int nData = DataSet.size();
+  this->dim = DataSet[0].size();
+  cdimval = dim * log ( 2 * 3.14159 );
+  vector<int> pop ( gaussians, 0 );
+  priors.resize ( gaussians );
+  mu = VVector ( gaussians, dim );
+  log_det_sigma.clear();
+  vector<int> allk;
+
+  NICE::Vector globmean ( dim );
+  globmean.set ( 0.0 );
+
+  for ( int n = 0; n < ( int ) DataSet.size(); n++ ) /* getting the max value for time */
+  {
+    globmean = globmean + DataSet[n];
+  }
+
+  globmean *= ( 1.0 / nData );
+
+  NICE::Vector sparse_globsigma;
+
+  sparse_globsigma.resize ( dim );
+  sparse_globsigma.set ( 0.0 );
+
+  for ( int i = 0; i < ( int ) DataSet.size(); i++ ) // Covariances updates
+  {
+    // nur diagonal Elemente berechnen
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = ( DataSet[i][d] - globmean[d] );
+      sparse_globsigma[d] += diff * diff;
+    }
+  }
+
+  sparse_globsigma *= ( 1.0 / DataSet.size() );
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    NICE::Vector _inv_sigma = diagInverse ( sparse_globsigma );
+
+    sparse_sigma.push_back ( sparse_globsigma );
+    sparse_inv_sigma.push_back ( _inv_sigma );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_globsigma ) );
+    mu[i] = means[i];
+    //priors[i]=1.0/(double)gaussians; // set equi-probables states
+    priors[i] = weights[i]; // set kMeans weights
+  }
 }
 
-void GMM::initEM(const VVector &DataSet)
+void GMM::initEM ( const VVector &DataSet )
 {
 
-	/* init the GaussianMixture by using randomized meanvectors */
-	int nData = DataSet.size();
-	this->dim = DataSet[0].size();
-	cdimval = dim*log(2*3.14159);
-	vector<int> pop(gaussians, 0);
-	priors.resize(gaussians);
-	mu = VVector(gaussians, dim);
-	log_det_sigma.clear();
-	vector<int> allk;
-	
-	NICE::Vector globmean(dim);
-	globmean.set(0.0);
-	
-	for(int n = 0; n < (int)DataSet.size(); n++) /* getting the max value for time */
-	{
-		globmean = globmean + DataSet[n];
-	}
-
-	globmean *= (1.0/nData);
-	
-	NICE::Vector sparse_globsigma;
-
-	sparse_globsigma.resize(dim);
-	sparse_globsigma.set(0.0);
-	
-	for(int i = 0; i < (int)DataSet.size(); i++) // Covariances updates
-	{
-		// nur diagonal Elemente berechnen
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = (DataSet[i][d] - globmean[d]);
-			sparse_globsigma[d] += diff*diff;
-		}
-	}
-	
-	sparse_globsigma *= (1.0/DataSet.size());
-	
-	for(int i = 0; i < gaussians; i++)
-	{
-		priors[i]=1.0/(double)gaussians; // set equi-probables states 
-		NICE::Vector _inv_sigma = diagInverse(sparse_globsigma);
-
-		sparse_sigma.push_back(sparse_globsigma);
-		sparse_inv_sigma.push_back(_inv_sigma);
-		log_det_sigma.push_back(logdiagDeterminant(sparse_globsigma));
-		bool newv = false;
-		int k;
-		while(!newv)
-		{
-			newv = true;
-			k = rand() % nData;
-		
-			for(int nk = 0; nk < (int)allk.size(); nk++)
-				if(allk[nk] == k)
-				{
-					newv = false;
-				}
-			if(newv)
-				allk.push_back(k);
-		}
-		mu[i] = DataSet[k];
-	}
+  /* init the GaussianMixture by using randomized meanvectors */
+  int nData = DataSet.size();
+  this->dim = DataSet[0].size();
+  cdimval = dim * log ( 2 * 3.14159 );
+  vector<int> pop ( gaussians, 0 );
+  priors.resize ( gaussians );
+  mu = VVector ( gaussians, dim );
+  log_det_sigma.clear();
+  vector<int> allk;
+
+  NICE::Vector globmean ( dim );
+  globmean.set ( 0.0 );
+
+  for ( int n = 0; n < ( int ) DataSet.size(); n++ ) /* getting the max value for time */
+  {
+    globmean = globmean + DataSet[n];
+  }
+
+  globmean *= ( 1.0 / nData );
+
+  NICE::Vector sparse_globsigma;
+
+  sparse_globsigma.resize ( dim );
+  sparse_globsigma.set ( 0.0 );
+
+  for ( int i = 0; i < ( int ) DataSet.size(); i++ ) // Covariances updates
+  {
+    // nur diagonal Elemente berechnen
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = ( DataSet[i][d] - globmean[d] );
+      sparse_globsigma[d] += diff * diff;
+    }
+  }
+
+  sparse_globsigma *= ( 1.0 / DataSet.size() );
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    priors[i] = 1.0 / ( double ) gaussians; // set equi-probables states
+    NICE::Vector _inv_sigma = diagInverse ( sparse_globsigma );
+
+    sparse_sigma.push_back ( sparse_globsigma );
+    sparse_inv_sigma.push_back ( _inv_sigma );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_globsigma ) );
+    bool newv = false;
+    int k;
+    while ( !newv )
+    {
+      newv = true;
+      k = rand() % nData;
+
+      for ( int nk = 0; nk < ( int ) allk.size(); nk++ )
+        if ( allk[nk] == k )
+        {
+          newv = false;
+        }
+      if ( newv )
+        allk.push_back ( k );
+    }
+    mu[i] = DataSet[k];
+  }
 }
 
-inline void sumRow(NICE::Matrix mat, NICE::Vector &res)
+inline void sumRow ( NICE::Matrix mat, NICE::Vector &res )
 {
-	int row = mat.rows();
-	int column = mat.cols();
-	res =NICE::Vector(column);
-	res.set(1e-5f);
+  int row = mat.rows();
+  int column = mat.cols();
+  res = NICE::Vector ( column );
+  res.set ( 1e-5f );
 //#pragma omp parallel for
-	for(int i = 0; i < column; i++){
-		for(int j = 0; j < row; j++){
-			res[i] += mat(j, i);
-		}
-	}
+  for ( int i = 0; i < column; i++ ) {
+    for ( int j = 0; j < row; j++ ) {
+      res[i] += mat ( j, i );
+    }
+  }
 }
 
-double GMM::logpdfState(const NICE::Vector &Vin,int state)
+double GMM::logpdfState ( const NICE::Vector &Vin, int state )
 {
-	/* get the probability density for a given state and a given vector */
-	double p;
-	NICE::Vector dif;
-		
-	dif = Vin;
-	dif -= mu[state];
-		
-	p = 0.0;
-	for(int i = 0; i < (int)dif.size(); i++)
-	{
-		p += dif[i] * dif[i] * sparse_inv_sigma[state][i];
-	}
-	
-	p = -0.5*(p + cdimval + log_det_sigma[state]);
-	return p;
+  /* get the probability density for a given state and a given vector */
+  double p;
+  NICE::Vector dif;
+
+  dif = Vin;
+  dif -= mu[state];
+
+  p = 0.0;
+  for ( int i = 0; i < ( int ) dif.size(); i++ )
+  {
+    p += dif[i] * dif[i] * sparse_inv_sigma[state][i];
+  }
+
+  p = -0.5 * ( p + cdimval + log_det_sigma[state] );
+  return p;
 }
 
-int GMM::doEM(const VVector &DataSet, int nbgaussians)
+int GMM::doEM ( const VVector &DataSet, int nbgaussians )
 {
   /* perform Expectation/Maximization on the given Dataset :
-	Matrix DataSet(nSamples,Dimensions).
-	The GaussianMixture Object must be initialised before 
-	(see initEM or initEMkMeans methods ) */
-	
+  Matrix DataSet(nSamples,Dimensions).
+  The GaussianMixture Object must be initialised before
+  (see initEM or initEMkMeans methods ) */
+
 #ifdef DEBUG
-	cerr << "GMM::start EM" << endl;
-#endif	
-	
-	int nData = DataSet.size();
-	int iter = 0;
-	double log_lik;
-	double log_lik_threshold = 1e-6f;
-	double log_lik_old = -1e10f;
-
-	NICE::Matrix unity(dim,dim,0.0);
-	for(int k = 0; k < dim; k++) 
-		unity(k, k)=1.0;
-	
-	//EM loop
-	while(true)
-	{
+  cerr << "GMM::start EM" << endl;
+#endif
+
+  int nData = DataSet.size();
+  int iter = 0;
+  double log_lik;
+  double log_lik_threshold = 1e-6f;
+  double log_lik_old = -1e10f;
+
+  NICE::Matrix unity ( dim, dim, 0.0 );
+  for ( int k = 0; k < dim; k++ )
+    unity ( k, k ) = 1.0;
+
+  //EM loop
+  while ( true )
+  {
 #ifdef DEBUGGMM
-		cerr << "GMM::EM: iteration: " << iter << endl;
+    cerr << "GMM::EM: iteration: " << iter << endl;
 #endif
-		
-		vector<double> sum_p;
-		sum_p.resize(nData);
-
-		for(int i = 0; i < nData; i++)
-		{
-			sum_p[i] = 0.0;
-		}
-	
-		NICE::Matrix pxi(nData,gaussians);
-		pxi.set(0.0);
-		NICE::Matrix pix(nData,gaussians);
-		pix.set(0.0);
-		NICE::Vector E;
-		
-		iter++;
-		if (iter>maxiter){
-			cerr << "EM stops here. Max number of iterations (" << maxiter << ") has been reached." << endl;
-			return iter;
-		}
-
-		double sum_log = 0.0; 
-		
-    	// computing expectation
-		double maxp = -numeric_limits<double>::max();
-		vector<double> maxptmp(nData,-numeric_limits<double>::max());
+
+    vector<double> sum_p;
+    sum_p.resize ( nData );
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_p[i] = 0.0;
+    }
+
+    NICE::Matrix pxi ( nData, gaussians );
+    pxi.set ( 0.0 );
+    NICE::Matrix pix ( nData, gaussians );
+    pix.set ( 0.0 );
+    NICE::Vector E;
+
+    iter++;
+    if ( iter > maxiter ) {
+      cerr << "EM stops here. Max number of iterations (" << maxiter << ") has been reached." << endl;
+      return iter;
+    }
+
+    double sum_log = 0.0;
+
+    // computing expectation
+    double maxp = -numeric_limits<double>::max();
+    vector<double> maxptmp ( nData, -numeric_limits<double>::max() );
 #pragma omp parallel for
-		for(int i = 0; i < nData; i++)
-		{
-			for(int j = 0; j < nbgaussians; j++)
-			{
-				double p = logpdfState(DataSet[i],j); // log(P(x|i))
-				maxptmp[i] = std::max(maxptmp[i], p);
-				pxi(i, j) = p;
-			}
-		}
-		
-		for(int i = 0; i < nData; i++)
-		{
-			maxp = std::max(maxp, maxptmp[i]);
-		}
+    for ( int i = 0; i < nData; i++ )
+    {
+      for ( int j = 0; j < nbgaussians; j++ )
+      {
+        double p = logpdfState ( DataSet[i], j ); // log(P(x|i))
+        maxptmp[i] = std::max ( maxptmp[i], p );
+        pxi ( i, j ) = p;
+      }
+    }
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      maxp = std::max ( maxp, maxptmp[i] );
+    }
 
 #pragma omp parallel for
-		for(int i = 0; i < nData; i++)
-		{
-			sum_p[i] = 0.0;
-			for(int j = 0; j < nbgaussians; j++)
-			{
-				double p = pxi(i, j) - maxp; // log(P(x|i))
-				p = exp(p); // P(x|i)
-				
-				if(p < 1e-40)
-					p = 1e-40;
-
-				pxi(i, j) = p;
-				sum_p[i] += p*priors[j];
-			} 
-		}
-			
-		for(int i = 0; i < nData; i++)
-		{
-			sum_log += log(sum_p[i]);
-		}
-		
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_p[i] = 0.0;
+      for ( int j = 0; j < nbgaussians; j++ )
+      {
+        double p = pxi ( i, j ) - maxp; // log(P(x|i))
+        p = exp ( p ); // P(x|i)
+
+        if ( p < 1e-40 )
+          p = 1e-40;
+
+        pxi ( i, j ) = p;
+        sum_p[i] += p * priors[j];
+      }
+    }
+
+    for ( int i = 0; i < nData; i++ )
+    {
+      sum_log += log ( sum_p[i] );
+    }
+
 #pragma omp parallel for
-		for(int j = 0; j < nbgaussians; j++)
-		{
-			for(int i = 0; i < nData; i++)
-			{
-				pix(i, j) = (pxi(i, j)*priors[j])/sum_p[i]; // then P(i|x)			
-			}   
-		}
-
-		// here we compute the log likehood 
-		log_lik = sum_log/nData; 
-#ifdef DEBUGGMM	
-		cout << "diff: " << fabs((log_lik/log_lik_old)-1) << " thresh: " << log_lik_threshold << " sum: " << sum_log <<  endl;
-		//cout << "logold: " << log_lik_old << " lognew: " << log_lik << endl;
+    for ( int j = 0; j < nbgaussians; j++ )
+    {
+      for ( int i = 0; i < nData; i++ )
+      {
+        pix ( i, j ) = ( pxi ( i, j ) * priors[j] ) / sum_p[i]; // then P(i|x)
+      }
+    }
+
+    // here we compute the log likehood
+    log_lik = sum_log / nData;
+#ifdef DEBUGGMM
+    cout << "diff: " << fabs ( ( log_lik / log_lik_old ) - 1 ) << " thresh: " << log_lik_threshold << " sum: " << sum_log <<  endl;
+    //cout << "logold: " << log_lik_old << " lognew: " << log_lik << endl;
 #endif
-		
-		if(fabs((log_lik/log_lik_old)-1) < log_lik_threshold )
-		{
-			//if log likehood hasn't move enough, the algorithm has converged, exiting the loop 
-			return iter;
-		}
-
-		log_lik_old = log_lik;
-
-		// Update Step
-		sumRow(pix,E);
-		
+
+    if ( fabs ( ( log_lik / log_lik_old ) - 1 ) < log_lik_threshold )
+    {
+      //if log likehood hasn't move enough, the algorithm has converged, exiting the loop
+      return iter;
+    }
+
+    log_lik_old = log_lik;
+
+    // Update Step
+    sumRow ( pix, E );
+
 #pragma omp parallel for
-		for(int j = 0; j < nbgaussians; j++) 
-		{
-			priors[j] = (E[j]+tau)/(nData+tau*nbgaussians); // new priors 
-
-			NICE::Vector tmu(dim);
-			tmu.set(0.0);
-
-			NICE::Vector sparse_tmsigma(dim);
-			sparse_tmsigma.set(0.0);
-
-			for(int i = 0; i < nData; i++) // Means update loop
-			{
-				tmu = tmu + (DataSet[i]*pix(i,j));
-			}
-									
-			NICE::Vector tmu2 = mu[j];
-			mu[j] = tmu + tau*tmu2;
-			mu[j] = mu[j]*(1.0/(E[j]+tau));
-			
-			for(int i = 0; i < nData; i++) // Covariances updates
-			{	
-				// nur diagonal Elemente berechnen
-				for(int d = 0; d < dim; d++)
-				{
-					sparse_tmsigma[d] += DataSet[i][d]*DataSet[i][d]*pix(i, j);
-				}
-			}
-			
-			NICE::Vector sparse_tmsigma2(dim);
-			for(int d = 0; d < dim; d++)
-			{
-				sparse_tmsigma[d] += 1e-5f;
-				sparse_tmsigma2[d] = sparse_sigma[j][d]+tmu2[d]*tmu2[d];
-				sparse_sigma[j][d] = (sparse_tmsigma[d]+tau*sparse_tmsigma2[d])/(E[j]+tau)-(mu[j][d]*mu[j][d]);
-			}				
-			sparse_inv_sigma[j] = diagInverse(sparse_sigma[j]);
-				
-			log_det_sigma[j] = logdiagDeterminant(sparse_sigma[j]);
-		}
-		if(comp)
-		{
-			double dist = compare();
-			cout << "dist for iteration " << iter << endl;
-			cout << "d: " << dist << endl;
-		}	
-	}
+    for ( int j = 0; j < nbgaussians; j++ )
+    {
+      priors[j] = ( E[j] + tau ) / ( nData + tau * nbgaussians ); // new priors
+
+      NICE::Vector tmu ( dim );
+      tmu.set ( 0.0 );
+
+      NICE::Vector sparse_tmsigma ( dim );
+      sparse_tmsigma.set ( 0.0 );
+
+      for ( int i = 0; i < nData; i++ ) // Means update loop
+      {
+        tmu = tmu + ( DataSet[i] * pix ( i, j ) );
+      }
+
+      NICE::Vector tmu2 = mu[j];
+      mu[j] = tmu + tau * tmu2;
+      mu[j] = mu[j] * ( 1.0 / ( E[j] + tau ) );
+
+      for ( int i = 0; i < nData; i++ ) // Covariances updates
+      {
+        // nur diagonal Elemente berechnen
+        for ( int d = 0; d < dim; d++ )
+        {
+          sparse_tmsigma[d] += DataSet[i][d] * DataSet[i][d] * pix ( i, j );
+        }
+      }
+
+      NICE::Vector sparse_tmsigma2 ( dim );
+      for ( int d = 0; d < dim; d++ )
+      {
+        sparse_tmsigma[d] += 1e-5f;
+        sparse_tmsigma2[d] = sparse_sigma[j][d] + tmu2[d] * tmu2[d];
+        sparse_sigma[j][d] = ( sparse_tmsigma[d] + tau * sparse_tmsigma2[d] ) / ( E[j] + tau ) - ( mu[j][d] * mu[j][d] );
+      }
+      sparse_inv_sigma[j] = diagInverse ( sparse_sigma[j] );
+
+      log_det_sigma[j] = logdiagDeterminant ( sparse_sigma[j] );
+    }
+    if ( comp )
+    {
+      double dist = compare();
+      cout << "dist for iteration " << iter << endl;
+      cout << "d: " << dist << endl;
+    }
+  }
 #ifdef DEBUG
-	cerr << "GMM::finished EM after " << iter << " iterations" << endl;
+  cerr << "GMM::finished EM after " << iter << " iterations" << endl;
 #endif
-	return iter;
+  return iter;
 }
 
-int GMM::getBestClass(const NICE::Vector &v, double *bprob)
+int GMM::getBestClass ( const NICE::Vector &v, double *bprob )
 {
-	int bestclass = 0;
-	double maxprob = logpdfState(v,0)+log(priors[0]);  // log(P(x|i))
-	
-	for(int i = 1; i < gaussians; i++)
-	{
-		double prob = logpdfState(v,i)+log(priors[i]);  // log(P(x|i))
-		
-		if(prob > maxprob)
-		{
-			maxprob = prob;
-			bestclass = i;
-		}
-	}
-	
-	if(bprob != NULL)
-		*bprob = maxprob;
-	
-	return bestclass;
+  int bestclass = 0;
+  double maxprob = logpdfState ( v, 0 ) + log ( priors[0] );  // log(P(x|i))
+
+  for ( int i = 1; i < gaussians; i++ )
+  {
+    double prob = logpdfState ( v, i ) + log ( priors[i] );  // log(P(x|i))
+
+    if ( prob > maxprob )
+    {
+      maxprob = prob;
+      bestclass = i;
+    }
+  }
+
+  if ( bprob != NULL )
+    *bprob = maxprob;
+
+  return bestclass;
 }
-		
-void GMM::getProbs(const NICE::Vector &vin, SparseVector &outprobs)
+
+void GMM::getProbs ( const NICE::Vector &vin, SparseVector &outprobs )
 {
-	outprobs.clear();
-	outprobs.setDim(gaussians);
-	Vector probs;
-	getProbs(vin, probs);
-	for(int i = 0; i < gaussians; i++)
-	{
-		if(probs[i] > 1e-7f )
-			outprobs[i] = probs[i];
-	}
+  outprobs.clear();
+  outprobs.setDim ( gaussians );
+  Vector probs;
+  getProbs ( vin, probs );
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    if ( probs[i] > 1e-7f )
+      outprobs[i] = probs[i];
+  }
 }
-		
-void GMM::getProbs(const NICE::Vector &vin, Vector &outprobs)
+
+void GMM::getProbs ( const NICE::Vector &vin, Vector &outprobs )
 {
-	Vector probs;
-	probs.resize(gaussians);
-	probs.set(0.0);
-		
-	double probsum = 0.0;
-	double maxp = -numeric_limits<double>::max();
-	for(int i = 0; i < gaussians; i++)
-	{	
-		probs[i] = logpdfState(vin, i) + log(priors[i]);  // log(P(x|i))
-		maxp = std::max(maxp, probs[i]);		
-	}
-		
-	for(int i = 0; i < gaussians; i++)
-	{
-		probs[i] -= maxp;
-		probs[i] = exp(probs[i]);
-		probsum += probs[i];
-	}
-
-	// normalize probs
+  Vector probs;
+  probs.resize ( gaussians );
+  probs.set ( 0.0 );
+
+  double probsum = 0.0;
+  double maxp = -numeric_limits<double>::max();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] = logpdfState ( vin, i ) + log ( priors[i] );  // log(P(x|i))
+    maxp = std::max ( maxp, probs[i] );
+  }
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] -= maxp;
+    probs[i] = exp ( probs[i] );
+    probsum += probs[i];
+  }
+
+  // normalize probs
 #pragma omp parallel for
-	for(int i = 0; i < gaussians; i++)
-	{
-		probs[i] /= probsum;
-	}
-	outprobs = probs;
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    probs[i] /= probsum;
+  }
+  outprobs = probs;
 }
 
-void GMM::getFisher(const NICE::Vector &vin, SparseVector &outprobs)
+void GMM::getFisher ( const NICE::Vector &vin, SparseVector &outprobs )
 {
-	int size = gaussians*2*dim;
-	outprobs.clear();
-	outprobs.setDim(size);
-	
-	int counter = 0;
-	
-	NICE::Vector classprobs;
-	classprobs.resize(gaussians);
-	classprobs.set(0.0);
-
-	double maxp = -numeric_limits<double>::max();
-	for(int i = 0; i < gaussians; i++)
-	{
-		classprobs[i] = logpdfState(vin, i) + log(priors[i]);  // log(P(x|i))
-
-		maxp = std::max(maxp, classprobs[i]);
-	}
-
-	for(int i = 0; i < gaussians; i++)
-	{
-		double p = classprobs[i] - maxp;
-		
-		p = exp(p);
-		
-		for(int d = 0; d < dim; d++)
-		{
-			double diff = vin[d]-mu[i][d];
-			
-			double sigma2 = sparse_sigma[i][d]*sparse_sigma[i][d];
-			double sigma3 = sigma2*sparse_sigma[i][d];
-			double normmu = sqrt(priors[i]/sigma2);
-			double normsig = sqrt((2.0*priors[i])/sigma2);
-			
-			double gradmu = (p * (diff/sigma2))/normmu;
-			double gradsig = (p * ((diff*diff)/sigma3 - 1.0/sparse_sigma[i][d])) /normsig;
-			if(fabs(gradmu) > 1e-7f)
-				outprobs[counter] = gradmu;
-			counter++;
-			
-			if(fabs(gradsig) > 1e-7f)
-				outprobs[counter] = gradsig;
-			counter++;
-		}
-	}
+  int size = gaussians * 2 * dim;
+  outprobs.clear();
+  outprobs.setDim ( size );
+
+  int counter = 0;
+
+  NICE::Vector classprobs;
+  classprobs.resize ( gaussians );
+  classprobs.set ( 0.0 );
+
+  double maxp = -numeric_limits<double>::max();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    classprobs[i] = logpdfState ( vin, i ) + log ( priors[i] );  // log(P(x|i))
+
+    maxp = std::max ( maxp, classprobs[i] );
+  }
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    double p = classprobs[i] - maxp;
+
+    p = exp ( p );
+
+    for ( int d = 0; d < dim; d++ )
+    {
+      double diff = vin[d] - mu[i][d];
+
+      double sigma2 = sparse_sigma[i][d] * sparse_sigma[i][d];
+      double sigma3 = sigma2 * sparse_sigma[i][d];
+      double normmu = sqrt ( priors[i] / sigma2 );
+      double normsig = sqrt ( ( 2.0 * priors[i] ) / sigma2 );
+
+      double gradmu = ( p * ( diff / sigma2 ) ) / normmu;
+      double gradsig = ( p * ( ( diff * diff ) / sigma3 - 1.0 / sparse_sigma[i][d] ) ) / normsig;
+      if ( fabs ( gradmu ) > 1e-7f )
+        outprobs[counter] = gradmu;
+      counter++;
+
+      if ( fabs ( gradsig ) > 1e-7f )
+        outprobs[counter] = gradsig;
+      counter++;
+    }
+  }
 }
 
 void GMM::cluster ( const VVector & features, VVector & prototypes, vector<double> & weights, vector<int> & assignment )
 {
-	computeMixture(features);
-
-	prototypes.clear();
-	weights.clear();
-	assignment.clear();
-
-	for(int i = 0; i < (int)features.size(); i++)
-	{
-		int c = getBestClass(features[i]);
-		assignment.push_back(c);
-		
-		weights.push_back(priors[c]);
-	}
-	for(int c = 0; c < gaussians; c++)
-		prototypes.push_back(mu[c]);
-	
-	cout << "tau: " << tau << endl;
+  computeMixture ( features );
+
+  prototypes.clear();
+  weights.clear();
+  assignment.clear();
+
+  for ( int i = 0; i < ( int ) features.size(); i++ )
+  {
+    int c = getBestClass ( features[i] );
+    assignment.push_back ( c );
+
+    weights.push_back ( priors[c] );
+  }
+  for ( int c = 0; c < gaussians; c++ )
+    prototypes.push_back ( mu[c] );
+
+  cout << "tau: " << tau << endl;
 }
 
-void GMM::saveData(const std::string filename)
+void GMM::saveData ( const std::string filename )
 {
-	ofstream fout( filename.c_str() );
-
-	fout << gaussians << " " << dim << endl;
-	
-	mu >> fout;
-	fout << endl;
-			
-	for(int n = 0; n < gaussians; n++)
-	{
-		fout << sparse_sigma[n] << endl;
-	}
-	
-	for(int n = 0; n < gaussians; n++)
-	{
-		fout << priors[n] << " ";
-	}
-
-	fout.close();
+  ofstream fout ( filename.c_str() );
+
+  fout << gaussians << " " << dim << endl;
+
+  mu >> fout;
+  fout << endl;
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    fout << sparse_sigma[n] << endl;
+  }
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    fout << priors[n] << " ";
+  }
+
+  fout.close();
 }
 
-bool GMM::loadData(const std::string filename)
+bool GMM::loadData ( const std::string filename )
 {
-	cerr << "read GMM Data" << endl;
-	ifstream fin( filename.c_str() );
-
-	if(fin.fail())
-	{
-		cerr << "GMM: Datei " << filename << " nicht gefunden!" << endl;
-		return false;
-	}
-
-	fin >> gaussians;
-	fin >> dim;
-	cdimval = log(pow(2*3.14159,dim));
-	mu.clear();
-
-	for(int i = 0; i < gaussians; i++)
-	{
-		NICE::Vector tmp;
-		fin >> tmp;
-		mu.push_back(tmp);
-	}
-	
-	log_det_sigma.clear();
-
-	for(int n = 0; n < gaussians; n++)
-	{
-		NICE::Matrix _sigma;
-		NICE::Vector _sparse_sigma;
-		
-		_sparse_sigma =NICE::Vector(dim);
-		fin >> _sparse_sigma;
-		sparse_sigma.push_back(_sparse_sigma);
-				
-		sparse_inv_sigma.push_back(diagInverse(sparse_sigma[n]));
-		log_det_sigma.push_back(logdiagDeterminant(sparse_sigma[n]));
-	}
-
-	for(int n = 0; n < gaussians; n++)
-	{
-		double tmpd;
-		fin >> tmpd;
-		priors.push_back(tmpd);
-	}
-	fin.close();
-
-	cerr << "reading GMM Data finished" << endl;
-	return true;
+  cerr << "read GMM Data" << endl;
+  ifstream fin ( filename.c_str() );
+
+  if ( fin.fail() )
+  {
+    cerr << "GMM: Datei " << filename << " nicht gefunden!" << endl;
+    return false;
+  }
+
+  fin >> gaussians;
+  fin >> dim;
+  cdimval = log ( pow ( 2 * 3.14159, dim ) );
+  mu.clear();
+
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    NICE::Vector tmp;
+    fin >> tmp;
+    mu.push_back ( tmp );
+  }
+
+  log_det_sigma.clear();
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    NICE::Matrix _sigma;
+    NICE::Vector _sparse_sigma;
+
+    _sparse_sigma = NICE::Vector ( dim );
+    fin >> _sparse_sigma;
+    sparse_sigma.push_back ( _sparse_sigma );
+
+    sparse_inv_sigma.push_back ( diagInverse ( sparse_sigma[n] ) );
+    log_det_sigma.push_back ( logdiagDeterminant ( sparse_sigma[n] ) );
+  }
+
+  for ( int n = 0; n < gaussians; n++ )
+  {
+    double tmpd;
+    fin >> tmpd;
+    priors.push_back ( tmpd );
+  }
+  fin.close();
+
+  cerr << "reading GMM Data finished" << endl;
+  return true;
 }
 
-void GMM::getParams(VVector &mean, VVector &sSigma, vector<double> &p)
+void GMM::getParams ( VVector &mean, VVector &sSigma, vector<double> &p )
 {
-	mean = mu;
-	sSigma.resize(gaussians);
-	p.clear();
-	for(int i = 0; i < gaussians; i++)
-	{
-		sSigma[i] = sparse_sigma[i];
-		p.push_back(priors[i]);
-	}
+  mean = mu;
+  sSigma.resize ( gaussians );
+  p.clear();
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    sSigma[i] = sparse_sigma[i];
+    p.push_back ( priors[i] );
+  }
 }
 
-void GMM::setCompareGM(VVector mean, VVector sSigma, vector<double> p)
+void GMM::setCompareGM ( VVector mean, VVector sSigma, vector<double> p )
 {
-	mu2 = mean;
-	sparse_sigma2 = sSigma;
-	priors2 = vector<double>(p);
+  mu2 = mean;
+  sparse_sigma2 = sSigma;
+  priors2 = vector<double> ( p );
 }
-		
-double GMM::kPPK(NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p)
+
+double GMM::kPPK ( NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p )
 {
-	double d = mu1.size();
-	
-	double det1 = 1.0;
-	double det2 = 1.0;
-	double det3 = 1.0;
-	double eval = 0.0;
-	for(int i = 0; i < d; i++)
-	{
-		det1 *= sigma1[i];
-		det2 *= sigma2[i];
-		double sigma = 1.0/((1.0/sigma1[i]+1.0/sigma2[i])*p);
-		det3 *= sigma;
-		double mu = p*(mu1[i]*sigma1[i]+mu2[i]*sigma2[i]);
-		eval += 0.5*mu*sigma*mu - (p*mu1[i]*mu1[i])/(2.0*sigma1[i]) - (p*mu2[i]*mu2[i]) / (2.0*sigma2[i]);
-	}
-	
-	return (pow(2.0*M_PI, ((1.0-2.0*p)*d)/2.0) * pow(det1, -p/2.0) * pow(det2, -p/2.0) * pow(det3, 0.5) * exp(eval));
+  double d = mu1.size();
+
+  double det1 = 1.0;
+  double det2 = 1.0;
+  double det3 = 1.0;
+  double eval = 0.0;
+  for ( int i = 0; i < d; i++ )
+  {
+    det1 *= sigma1[i];
+    det2 *= sigma2[i];
+    double sigma = 1.0 / ( ( 1.0 / sigma1[i] + 1.0 / sigma2[i] ) * p );
+    det3 *= sigma;
+    double mu = p * ( mu1[i] * sigma1[i] + mu2[i] * sigma2[i] );
+    eval += 0.5 * mu * sigma * mu - ( p * mu1[i] * mu1[i] ) / ( 2.0 * sigma1[i] ) - ( p * mu2[i] * mu2[i] ) / ( 2.0 * sigma2[i] );
+  }
+
+  return ( pow ( 2.0*M_PI, ( ( 1.0 - 2.0*p ) *d ) / 2.0 ) * pow ( det1, -p / 2.0 ) * pow ( det2, -p / 2.0 ) * pow ( det3, 0.5 ) * exp ( eval ) );
 }
 
 double GMM::compare()
 {
-	double distkij = 0.0;
-	double distkjj = 0.0;
-	double distkii = 0.0;
-	for(int i = 0; i < gaussians; i++)
-	{
-		for(int j = 0; j < gaussians; j++)
-		{
-			double kij = kPPK(sparse_sigma[i],sparse_sigma2[j], mu[i], mu2[j], 0.5);
-			double kii = kPPK(sparse_sigma[i],sparse_sigma[j], mu[i], mu[j], 0.5);
-			double kjj = kPPK(sparse_sigma2[i],sparse_sigma2[j], mu2[i], mu2[j], 0.5);
-			kij = priors[i]*priors2[j]*kij;
-			kii = priors[i]*priors[j]*kii;
-			kjj = priors2[i]*priors2[j]*kjj;
-			distkij += kij;
-			distkii += kii;
-			distkjj += kjj;
-		}
-	}
-	return (distkij / (sqrt(distkii)*sqrt(distkjj)));
+  double distkij = 0.0;
+  double distkjj = 0.0;
+  double distkii = 0.0;
+  for ( int i = 0; i < gaussians; i++ )
+  {
+    for ( int j = 0; j < gaussians; j++ )
+    {
+      double kij = kPPK ( sparse_sigma[i], sparse_sigma2[j], mu[i], mu2[j], 0.5 );
+      double kii = kPPK ( sparse_sigma[i], sparse_sigma[j], mu[i], mu[j], 0.5 );
+      double kjj = kPPK ( sparse_sigma2[i], sparse_sigma2[j], mu2[i], mu2[j], 0.5 );
+      kij = priors[i] * priors2[j] * kij;
+      kii = priors[i] * priors[j] * kii;
+      kjj = priors2[i] * priors2[j] * kjj;
+      distkij += kij;
+      distkii += kii;
+      distkjj += kjj;
+    }
+  }
+  return ( distkij / ( sqrt ( distkii ) *sqrt ( distkjj ) ) );
 }
 
-void GMM::comparing(bool c)
+void GMM::comparing ( bool c )
 {
-	comp = c;
+  comp = c;
 }

+ 210 - 206
math/cluster/GMM.h

@@ -1,12 +1,12 @@
-/** 
+/**
  * @file GMM.h
- * @brief Gaussian Mixture Model based on   
+ * @brief Gaussian Mixture Model based on
   article{Calinon07SMC,
-  title="On Learning, Representing and Generalizing a Task in a Humanoid 
+  title="On Learning, Representing and Generalizing a Task in a Humanoid
   Robot",
   author="S. Calinon and F. Guenter and A. Billard",
-  journal="IEEE Transactions on Systems, Man and Cybernetics, Part B. 
-  Special issue on robot learning by observation, demonstration and 
+  journal="IEEE Transactions on Systems, Man and Cybernetics, Part B.
+  Special issue on robot learning by observation, demonstration and
   imitation",
   year="2007",
   volume="37",
@@ -22,7 +22,7 @@
 
 #include "core/vector/VectorT.h"
 #include "core/vector/MatrixT.h"
- 
+
 #include "vislearning/cbaselib/MultiDataset.h"
 #include "vislearning/cbaselib/LocalizationResult.h"
 #include "vislearning/cbaselib/CachedExample.h"
@@ -35,206 +35,210 @@ namespace OBJREC {
 
 class GMM : public ClusterAlgorithm
 {
-	protected:
-		
-		//! number of gaussians
-		int gaussians;
-		
-		//! dimension of each feature
-		int dim;
-
-		//! mean vectors
-		NICE::VVector mu;
-	
-		//! sparse sigma vectors
-		NICE::VVector sparse_sigma;
-			
-		//! sparse inverse sigma vectors (if usediag)
-		NICE::VVector sparse_inv_sigma;
-		
-		//! save det_sigma for fast computing
-		std::vector<double> log_det_sigma;
-				
-		//! the configfile
-		const NICE::Config *conf;
-		
-		//! the weight for each gaussian
-		std::vector<double> priors;
-		
-		//! parameters for other GM to compare
-		NICE::VVector mu2;
-		NICE::VVector sparse_sigma2;
-		std::vector<double> priors2;
-		bool comp;
-		
-		//! maximum number of iterations for EM
-		int maxiter;
-		
-		//! how many features to use, use 0 for alle input features
-		int featsperclass;
-				
-		//! for faster computing cdimval = dim*2*PI
-		double cdimval;
-		
-		//! parameter for the map estimation
-		double tau;
-		
-		//! whether to use pyramid initialisation or not
-		bool pyramid;
-	public:
-		/**
-	 	 * simplest constructor
-		 */
-		GMM();
-		
-		/**
-		 * simple constructor
-		 * @param _no_classes 
-		 */
-		GMM(int _no_classes);
-		
-		/**
-		 * standard constructor
-		 * @param conf a Configfile
-		 * @param _no_classes number of gaussian
-		 */
-		GMM(const NICE::Config *conf, int _no_classes = -1);
-		
-		/**
-		 * standard destructor
-		 */
-		~GMM(){std::cerr << "dadada" << std::endl;};
-		
-		/**
-		 * computes the mixture
-		 * @param examples the input features
-		 */
-		void computeMixture(Examples examples);
-		
-		/**
-		 * computes the mixture
-		 * @param DataSet the input features
-		 */
-		void computeMixture(const NICE::VVector &DataSet);
-		
-		/**
-		 * returns the probabilities for each gaussian in a sparse vector
-		 * @param vin input vector
-		 * @param probs BoV output vector
-		 */
-		void getProbs(const NICE::Vector &vin, SparseVector &probs);
-		
-		/**
-		 * returns the probabilities for each gaussian
-		 * @param vin input vector
-		 * @param probs BoV output vector
-		 */
-		void getProbs(const NICE::Vector &vin, NICE::Vector &probs);
-		
-		/**
-		 * returns the fisher score for the gmm
-		 * @param vin input vector
-		 * @param probs Fisher score output vector
-		 */
-		void getFisher(const NICE::Vector &vin, SparseVector &probs);
-		
-		/**
-		 *   init the GaussianMixture by selecting randomized mean vectors and using the coovariance of all features
-		 * @param DataSet input Matrix
-		 */
-		void initEM(const NICE::VVector &DataSet);
-				
-		/**
-		 *   alternative for initEM: init the GaussianMixture with a K-Means clustering
-		 * @param DataSet input Matrix
-		 */
-		void initEMkMeans(const NICE::VVector &DataSet);
-		
-		/**
-		 * performs Expectation Maximization on the Dataset, 	in order to obtain a nState GMM Dataset is a Matrix(no_classes,nDimensions)
-		 * @param DataSet input Matrix
-		 * @param gaussians number gaussians to use
-		 * @return number of iterations
-		 */
-		int doEM(const NICE::VVector &DataSet, int nbgaussians);
-			
-		/**
-		 * Compute log probabilty of vector v for the given state. *
-		 * @param Vin 
-		 * @param state 
-		 * @return 
-				 */
-		double logpdfState(const NICE::Vector &Vin,int state);
-		
-		/**
-		 * determine the best mixture for the input feature
-		 * @param v input feature
-		 * @param bprob probability of the best mixture
-		 * @return numer of the best mixture
-		 */
-		int getBestClass(const NICE::Vector &v, double *bprob = NULL);
-		
-		/**
-		 * Cluster a given Set of features and return the labels for each feature
-		 * @param features input features
-		 * @param prototypes mean of the best gaussian
-		 * @param weights weight of the best gaussian
-		 * @param assignment number of the best gaussian
-		 */
-		void cluster ( const NICE::VVector & features, NICE::VVector & prototypes, std::vector<double> & weights, std::vector<int> & assignment );
-		
-		/**
-		 * save GMM data
-		 * @param filename filename
-		 */
-		void saveData(const std::string filename);
-		
-        /**
-		 * load GMM data
-		 * @param filename filename
-		 * @return true if everything works fine
-	 	 */
-		bool loadData(const std::string filename);
-		
-		/**
-		 * return the parameter of the mixture
-		 * @param mu 
-		 * @param sSigma 
-		 * @param p 
-		 */
-		void getParams(NICE::VVector &mean, NICE::VVector &sSigma, std::vector<double> &p);
-		
-		/**
-		 * Set the parameters of an other mixture for comparing with this one
-		 * @param mean mean vectors
-		 * @param sSigma diagonal covariance Matrixs
-		 * @param p weights
-		 */
-		void setCompareGM(NICE::VVector mean, NICE::VVector sSigma, std::vector<double> p);
-		
-		/**
-		 * probability product kernel
-		 * @param sigma1 
-		 * @param sigma2 
-		 * @param mu1 
-		 * @param mu2 
-		 * @param p 
-		 * @return 
-		 */
-		double kPPK(NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p);
-		
-		/**
-		 * starts a comparison between this Mixture and a other one seted bei "setComparGM"
-		 */
-		double compare();
-		
-		/**
-		 * whether to compare or not
-		 * @param c 
-		 */
-		void comparing(bool c = true);
-		
-		int getSize(){return gaussians;}
+  protected:
+
+    //! number of gaussians
+    int gaussians;
+
+    //! dimension of each feature
+    int dim;
+
+    //! mean vectors
+    NICE::VVector mu;
+
+    //! sparse sigma vectors
+    NICE::VVector sparse_sigma;
+
+    //! sparse inverse sigma vectors (if usediag)
+    NICE::VVector sparse_inv_sigma;
+
+    //! save det_sigma for fast computing
+    std::vector<double> log_det_sigma;
+
+    //! the configfile
+    const NICE::Config *conf;
+
+    //! the weight for each gaussian
+    std::vector<double> priors;
+
+    //! parameters for other GM to compare
+    NICE::VVector mu2;
+    NICE::VVector sparse_sigma2;
+    std::vector<double> priors2;
+    bool comp;
+
+    //! maximum number of iterations for EM
+    int maxiter;
+
+    //! how many features to use, use 0 for alle input features
+    int featsperclass;
+
+    //! for faster computing cdimval = dim*2*PI
+    double cdimval;
+
+    //! parameter for the map estimation
+    double tau;
+
+    //! whether to use pyramid initialisation or not
+    bool pyramid;
+  public:
+    /**
+      * simplest constructor
+     */
+    GMM();
+
+    /**
+     * simple constructor
+     * @param _no_classes
+     */
+    GMM ( int _no_classes );
+
+    /**
+     * standard constructor
+     * @param conf a Configfile
+     * @param _no_classes number of gaussian
+     */
+    GMM ( const NICE::Config *conf, int _no_classes = -1 );
+
+    /**
+     * standard destructor
+     */
+    ~GMM() {
+      std::cerr << "dadada" << std::endl;
+    };
+
+    /**
+     * computes the mixture
+     * @param examples the input features
+     */
+    void computeMixture ( Examples examples );
+
+    /**
+     * computes the mixture
+     * @param DataSet the input features
+     */
+    void computeMixture ( const NICE::VVector &DataSet );
+
+    /**
+     * returns the probabilities for each gaussian in a sparse vector
+     * @param vin input vector
+     * @param probs BoV output vector
+     */
+    void getProbs ( const NICE::Vector &vin, NICE::SparseVector &probs );
+
+    /**
+     * returns the probabilities for each gaussian
+     * @param vin input vector
+     * @param probs BoV output vector
+     */
+    void getProbs ( const NICE::Vector &vin, NICE::Vector &probs );
+
+    /**
+     * returns the fisher score for the gmm
+     * @param vin input vector
+     * @param probs Fisher score output vector
+     */
+    void getFisher ( const NICE::Vector &vin, NICE::SparseVector &probs );
+
+    /**
+     *   init the GaussianMixture by selecting randomized mean vectors and using the coovariance of all features
+     * @param DataSet input Matrix
+     */
+    void initEM ( const NICE::VVector &DataSet );
+
+    /**
+     *   alternative for initEM: init the GaussianMixture with a K-Means clustering
+     * @param DataSet input Matrix
+     */
+    void initEMkMeans ( const NICE::VVector &DataSet );
+
+    /**
+     * performs Expectation Maximization on the Dataset,  in order to obtain a nState GMM Dataset is a Matrix(no_classes,nDimensions)
+     * @param DataSet input Matrix
+     * @param gaussians number gaussians to use
+     * @return number of iterations
+     */
+    int doEM ( const NICE::VVector &DataSet, int nbgaussians );
+
+    /**
+     * Compute log probabilty of vector v for the given state. *
+     * @param Vin
+     * @param state
+     * @return
+       */
+    double logpdfState ( const NICE::Vector &Vin, int state );
+
+    /**
+     * determine the best mixture for the input feature
+     * @param v input feature
+     * @param bprob probability of the best mixture
+     * @return numer of the best mixture
+     */
+    int getBestClass ( const NICE::Vector &v, double *bprob = NULL );
+
+    /**
+     * Cluster a given Set of features and return the labels for each feature
+     * @param features input features
+     * @param prototypes mean of the best gaussian
+     * @param weights weight of the best gaussian
+     * @param assignment number of the best gaussian
+     */
+    void cluster ( const NICE::VVector & features, NICE::VVector & prototypes, std::vector<double> & weights, std::vector<int> & assignment );
+
+    /**
+     * save GMM data
+     * @param filename filename
+     */
+    void saveData ( const std::string filename );
+
+    /**
+    * load GMM data
+    * @param filename filename
+    * @return true if everything works fine
+    */
+    bool loadData ( const std::string filename );
+
+    /**
+     * return the parameter of the mixture
+     * @param mu
+     * @param sSigma
+     * @param p
+     */
+    void getParams ( NICE::VVector &mean, NICE::VVector &sSigma, std::vector<double> &p );
+
+    /**
+     * Set the parameters of an other mixture for comparing with this one
+     * @param mean mean vectors
+     * @param sSigma diagonal covariance Matrixs
+     * @param p weights
+     */
+    void setCompareGM ( NICE::VVector mean, NICE::VVector sSigma, std::vector<double> p );
+
+    /**
+     * probability product kernel
+     * @param sigma1
+     * @param sigma2
+     * @param mu1
+     * @param mu2
+     * @param p
+     * @return
+     */
+    double kPPK ( NICE::Vector sigma1, NICE::Vector sigma2, NICE::Vector mu1, NICE::Vector mu2, double p );
+
+    /**
+     * starts a comparison between this Mixture and a other one seted bei "setComparGM"
+     */
+    double compare();
+
+    /**
+     * whether to compare or not
+     * @param c
+     */
+    void comparing ( bool c = true );
+
+    int getSize() {
+      return gaussians;
+    }
 };
 
 

+ 32 - 33
math/cluster/KMeansOnline.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file KMeansOnline.h
 * @brief online kmeans clustering
 * @author Erik Rodner
@@ -16,43 +16,42 @@
 #include "vislearning/cbaselib/Example.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 /** online kmeans clustering */
 class KMeansOnline : public ClusterOnline
 {
 
-    protected:
-	size_t numClusters;
-	double gamma;
-
-    public:
-  
-	/** simple constructor */
-	KMeansOnline( size_t numClusters, double gamma = 1.0 );
-      
-	/** simple destructor */
-	virtual ~KMeansOnline();
-
-	// refactor-nice.pl: check this substitution
-	// old: int updateClusters ( const Vector & x );
-	int updateClusters ( const NICE::Vector & x );
-	void init ();
-     
-	/**
-	 * Cluster algorithm using examples
-	 * @param ex input examples
-	 */
-	void cluster( const Examples &ex);
-	
-	/**
-	 * returns the distance to the centre of each cluster
-	 * @param vin input vector
-	 * @param dist distance
-	 * @param size how much centres should considered
-	 * @param hard use a hard assignment (all values = 1 or 0) or not
-		 */
-	void getDist(const NICE::Vector &vin, SparseVector &dist, int size = 1, bool hard = false);
+  protected:
+    size_t numClusters;
+    double gamma;
+
+  public:
+
+    /** simple constructor */
+    KMeansOnline ( size_t numClusters, double gamma = 1.0 );
+
+    /** simple destructor */
+    virtual ~KMeansOnline();
+
+    int updateClusters ( const NICE::Vector & x );
+    void init ();
+
+    /**
+     * Cluster algorithm using examples
+     * @param ex input examples
+     */
+    void cluster ( const Examples &ex );
+
+    /**
+     * returns the distance to the centre of each cluster
+     * @param vin input vector
+     * @param dist distance
+     * @param size how much centres should considered
+     * @param hard use a hard assignment (all values = 1 or 0) or not
+      */
+    void getDist ( const NICE::Vector &vin, NICE::SparseVector &dist, int size = 1, bool hard = false );
 };
 
 

+ 48 - 48
math/distances/genericDistance.h

@@ -8,54 +8,54 @@ namespace OBJREC
 
 class GenericDistanceSelection
 {
-public:
-
-	static NICE::VectorDistance<double> *selectDistance(
-			std::string distance_type)
-	{
-		NICE::VectorDistance<double> *distance = NULL;
-
-		if (distance_type == "euclidean")
-		{
-			distance = new NICE::EuclidianDistance<double>();
-		}
-		else if (distance_type == "manhattan" || distance_type == "cityblock")
-		{
-			distance = new NICE::ManhattanDistance<double>();
-		}
-		else if (distance_type == "median")
-		{
-			distance = new NICE::MedianDistance<double>();
-		}
-		else if (distance_type == "cosinus")
-		{
-			distance = new NICE::CosDistance<double>();
-		}
-		else if (distance_type == "spherical")
-		{
-			distance = new NICE::SphericalDistance<double>();
-		}
-		else if (distance_type == "chisquare" || distance_type == "chi2")
-		{
-			distance = new NICE::Chi2Distance<double>();
-
-		}
-		else if (distance_type == "kl" || distance_type == "kullbackleibler")
-		{
-			distance = new NICE::KLDistance<double>();
-		}
-		else if (distance_type == "bhattacharyya")
-		{
-			distance = new NICE::BhattacharyyaDistance<double>();
-		}
-		else
-		{
-			fthrow(Exception, "Distance type " << distance_type << " is unknown - euclidean distance used" );
-			distance = new NICE::EuclidianDistance<double>();
-		}
-
-		return distance;
-	}
+  public:
+
+    static NICE::VectorDistance<double> *selectDistance (
+      std::string distance_type )
+    {
+      NICE::VectorDistance<double> *distance = NULL;
+
+      if ( distance_type == "euclidean" )
+      {
+        distance = new NICE::EuclidianDistance<double>();
+      }
+      else if ( distance_type == "manhattan" || distance_type == "cityblock" )
+      {
+        distance = new NICE::ManhattanDistance<double>();
+      }
+      else if ( distance_type == "median" )
+      {
+        distance = new NICE::MedianDistance<double>();
+      }
+      else if ( distance_type == "cosinus" )
+      {
+        distance = new NICE::CosDistance<double>();
+      }
+      else if ( distance_type == "spherical" )
+      {
+        distance = new NICE::SphericalDistance<double>();
+      }
+      else if ( distance_type == "chisquare" || distance_type == "chi2" )
+      {
+        distance = new NICE::Chi2Distance<double>();
+
+      }
+      else if ( distance_type == "kl" || distance_type == "kullbackleibler" )
+      {
+        distance = new NICE::KLDistance<double>();
+      }
+      else if ( distance_type == "bhattacharyya" )
+      {
+        distance = new NICE::BhattacharyyaDistance<double>();
+      }
+      else
+      {
+        fthrow ( NICE::Exception, "Distance type " << distance_type << " is unknown - euclidean distance used" );
+        distance = new NICE::EuclidianDistance<double>();
+      }
+
+      return distance;
+    }
 
 };
 } //namespace

+ 140 - 129
math/ftransform/PCA.cpp

@@ -9,7 +9,7 @@
  * This is an example of how to use the Principal Component Analysis (PCA) class.
  */
 
-// #define DEBUG
+//#define DEBUG
 #undef DEBUG
 
 #include <iostream>
@@ -30,39 +30,39 @@ using namespace OBJREC;
 using namespace std;
 using namespace NICE;
 
-PCA::PCA(uint dim, uint maxiteration, double mindelta)
+PCA::PCA ( uint dim, uint maxiteration, double mindelta )
 {
-	init(dim, maxiteration, mindelta);
+  init ( dim, maxiteration, mindelta );
 }
 
-PCA::PCA(void)
+PCA::PCA ( void )
 {
-	init();
+  init();
 }
 
 PCA::~PCA()
 {
 }
 
-void PCA::init(uint dim, uint maxiteration, double mindelta)
+void PCA::init ( uint dim, uint maxiteration, double mindelta )
 {
-	this->targetDimension = dim;
-	this->maxiteration = maxiteration;
-	this->mindelta = mindelta;
+  this->targetDimension = dim;
+  this->maxiteration = maxiteration;
+  this->mindelta = mindelta;
 }
 
-void PCA::restore(istream & is, int format)
+void PCA::restore ( istream & is, int format )
 {
 
-	is >> basis;
-	is >> normalization;
-	is >> mean;
-	is >> targetDimension;
+  is >> basis;
+  is >> normalization;
+  is >> mean;
+  is >> targetDimension;
 }
 
-void PCA::store(ostream & os, int format) const
+void PCA::store ( ostream & os, int format ) const
 {
-	os << basis << normalization << mean << targetDimension;
+  os << basis << normalization << mean << targetDimension;
 }
 
 void PCA::clear()
@@ -70,165 +70,176 @@ void PCA::clear()
 
 }
 
-void PCA::calculateBasis(const NICE::Matrix &features,
-		const uint targetDimension, const uint mode)
+void PCA::calculateBasis ( const NICE::Matrix &features,
+                           const uint targetDimension, const uint mode )
 {
-	calculateBasis(features, targetDimension, false);
+  calculateBasis ( features, targetDimension, false );
 }
 
 void PCA::calculateMean ( const NICE::Matrix &features, NICE::Vector & mean )
 {
   // data vectors are put row-wise in the matrix
-  mean.resize(features.cols());
+  mean.resize ( features.cols() );
+  mean.set(0);
   for ( uint i = 0 ; i < features.rows(); i++ )
-    mean = mean + features.getRow(i);
+    mean = mean + features.getRow ( i );
+  mean /= features.rows();
 }
 
-void PCA::calculateBasis(const NICE::Matrix &features,
-		const uint targetDimension, const bool adaptive,
-		const double targetRatio)
+void PCA::calculateBasis ( const NICE::Matrix &features,
+                           const uint targetDimension, const bool adaptive,
+                           const double targetRatio )
 {
-	this->targetDimension = targetDimension;
+  this->targetDimension = targetDimension;
   // dimension of the feature vectors
-	uint srcFeatureSize = features.cols();
-	uint mindimension = std::min(this->targetDimension, srcFeatureSize);
+  uint srcFeatureSize = features.cols();
+  uint mindimension = std::min ( this->targetDimension, srcFeatureSize );
 
-	NICE::Matrix eigenvectors;
+  NICE::Matrix eigenvectors;
 
-	NICE::Vector eigenvalue;
+  NICE::Vector eigenvalue;
+
+  calculateMean ( features, mean );
   
-  calculateMean(features, mean);
 #ifdef NICE_USELIB_TRLAN
-  EigValues *eig = new EigValuesTRLAN();//fast lanczos TRLAN
+  EigValues *eig;
+  if(mindimension < 12)
+    eig = new EVArnoldi();//Arnoldi for (srcFeatureSize<n)
+  else
+    eig = new EigValuesTRLAN();//fast lanczos TRLAN
 #else
   EigValues *eig = new EVArnoldi();//Arnoldi for (srcFeatureSize<n)
 #endif
+
   NICE::Matrix features_transpose = features.transpose();
-  GMCovariance C(&features_transpose);
-  if (adaptive)
+
+  GMCovariance C ( &features_transpose );
+  
+  if ( adaptive )
   {
-    eig->getEigenvalues(C, eigenvalue, eigenvectors, srcFeatureSize);
+    eig->getEigenvalues ( C, eigenvalue, eigenvectors, srcFeatureSize );
   }
   else
   {
-    eig->getEigenvalues(C, eigenvalue, eigenvectors, mindimension);
+    eig->getEigenvalues ( C, eigenvalue, eigenvectors, mindimension );
   }
 
 #ifdef DEBUG
-	fprintf(stderr, "Eigenvalue Decomposition ready \n");
-	cerr << eigenvectors << endl;
-	cerr << eigenvalue << endl;
+  fprintf ( stderr, "Eigenvalue Decomposition ready \n" );
+  cerr << eigenvectors << endl;
+  cerr << eigenvalue << endl;
 
-	//sort values
-	fprintf(stderr, "Eigenvector-Rows:%i Eigenvector-Cols:%i\n", (int)eigenvectors.rows(), (int)eigenvectors.cols());
+  //sort values
+  fprintf ( stderr, "Eigenvector-Rows:%i Eigenvector-Cols:%i\n", ( int ) eigenvectors.rows(), ( int ) eigenvectors.cols() );
 #endif
 
-	multimap<double, NICE::Vector> map;
-	double sumeigen = 0.0;
-
-	NICE::Vector ratio(eigenvectors.cols());
-	for (uint i = 0; i < eigenvectors.cols(); i++)//every eigenvector
-	{
-		NICE::Vector eigenvector(srcFeatureSize);
-		for (uint k = 0; k < srcFeatureSize; k++)
-		{
-			eigenvector[k] = eigenvectors(k, i);
-		}
-		map.insert(pair<double, NICE::Vector> (eigenvalue[i], eigenvector));
-		sumeigen += eigenvalue[i];
-	}
-
-	//compute basis size
-
-
-	if (adaptive)
-	{ //compute target dimension
-		uint dimensioncount = 0;
-		double addedratio = 0.0;
-		multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
-		while (addedratio <= targetRatio && it != map.rend())
-		{
-			//calc ratio
-			ratio[dimensioncount] = (*it).first / sumeigen;
-			addedratio += ratio[dimensioncount];
-			dimensioncount++;
-			it++;
-		}
-		this->targetDimension = dimensioncount;
-	}
-
-	mindimension = std::min(this->targetDimension, srcFeatureSize);
-	this->targetDimension = mindimension;
-	basis = NICE::Matrix(srcFeatureSize, mindimension);
-	//get sorted values
-	uint count = 0;
-	multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
-	while (count < this->targetDimension && it != map.rend())
-	{
-		NICE::Vector eigenvector = (*it).second;
-		//put eigenvector into column
-		for (uint k = 0; k < srcFeatureSize; k++)
-		{
-			basis(k, count) = eigenvector[k];
-		}
-		//calc ratio
-		ratio[count] = (*it).first / sumeigen;
-
-		count++;
-		it++;
-	}
-	//normalization matrix / modify variance to 1 for all eigenvectors
-	normalization = NICE::Matrix(mindimension, mindimension, 0);
-	for (uint k = 0; k < mindimension; k++)
-	{
-		normalization(k, k) = 1.0 / sqrt(eigenvalue[k]);
-	}
+  multimap<double, NICE::Vector> map;
+  double sumeigen = 0.0;
+
+  NICE::Vector ratio ( eigenvectors.cols() );
+  for ( uint i = 0; i < eigenvectors.cols(); i++ ) //every eigenvector
+  {
+    NICE::Vector eigenvector ( srcFeatureSize );
+    for ( uint k = 0; k < srcFeatureSize; k++ )
+    {
+      eigenvector[k] = eigenvectors ( k, i );
+    }
+    map.insert ( pair<double, NICE::Vector> ( eigenvalue[i], eigenvector ) );
+    sumeigen += eigenvalue[i];
+  }
+
+  //compute basis size
+
+  if ( adaptive )
+  { //compute target dimension
+    uint dimensioncount = 0;
+    double addedratio = 0.0;
+    multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
+    while ( addedratio <= targetRatio && it != map.rend() )
+    {
+      //calc ratio
+      ratio[dimensioncount] = ( *it ).first / sumeigen;
+      addedratio += ratio[dimensioncount];
+      dimensioncount++;
+      it++;
+    }
+    this->targetDimension = dimensioncount;
+  }
+
+  mindimension = std::min ( this->targetDimension, srcFeatureSize );
+  this->targetDimension = mindimension;
+  basis = NICE::Matrix ( srcFeatureSize, mindimension );
+  //get sorted values
+  uint count = 0;
+  multimap<double, NICE::Vector>::reverse_iterator it = map.rbegin();
+  while ( count < this->targetDimension && it != map.rend() )
+  {
+    NICE::Vector eigenvector = ( *it ).second;
+    //put eigenvector into column
+    for ( uint k = 0; k < srcFeatureSize; k++ )
+    {
+      basis ( k, count ) = eigenvector[k];
+    }
+    //calc ratio
+    ratio[count] = ( *it ).first / sumeigen;
+
+    count++;
+    it++;
+  }
+  
+  //normalization matrix / modify variance to 1 for all eigenvectors
+  normalization = NICE::Matrix ( mindimension, mindimension, 0 );
+  for ( uint k = 0; k < mindimension; k++ )
+  {
+    normalization ( k, k ) = 1.0 / sqrt ( eigenvalue[k] );
+  }
 
 #ifdef DEBUG
-	cout << "Eigenvalue-absolute:" << eigenvalue << endl;
-	cout << "Eigenvalue-ratio:" << ratio << endl;
+  cout << "Eigenvalue-absolute:" << eigenvalue << endl;
+  cout << "Eigenvalue-ratio:" << ratio << endl;
 #endif
 
 }
 
-NICE::Vector PCA::getFeatureVector(const NICE::Vector &data,
-		const bool normalize)
+NICE::Vector PCA::getFeatureVector ( const NICE::Vector &data,
+                                     const bool normalize )
 {
-	//free data of mean
-	if (normalize)
-	{
-
-		NICE::Vector meanfree(data);
-		meanfree -= mean;
-		//Y=W^t * B^T
-		if(normbasis.rows() == 0)
-			normbasis.multiply(normalization, basis, false, true);
-		NICE::Vector tmp;
-		tmp.multiply(normbasis, meanfree);
-		return tmp;
-	}
-	else
-	{
-		NICE::Vector meanfree(data);
-		meanfree -= mean;
-		//Y=W^t * B^T
-		NICE::Vector tmp;
-		tmp.multiply(basis, meanfree, true);
-		return tmp;
-	}
+  //free data of mean
+  if ( normalize )
+  {
+    NICE::Vector meanfree ( data );
+    meanfree -= mean;
+    //Y=W^t * B^T
+    
+    if ( normbasis.rows() == 0 )
+      normbasis.multiply ( normalization, basis, false, true );
+    
+    NICE::Vector tmp;
+    tmp.multiply ( normbasis, meanfree );
+    return tmp;
+  }
+  else
+  {
+    NICE::Vector meanfree ( data );
+    meanfree -= mean;
+    //Y=W^t * B^T
+    NICE::Vector tmp;
+    tmp.multiply ( basis, meanfree, true );
+    return tmp;
+  }
 }
 
 NICE::Vector PCA::getMean()
 {
-	return mean;
+  return mean;
 }
 
 NICE::Matrix PCA::getBasis()
 {
-	return basis;
+  return basis;
 }
 
 int PCA::getTargetDim()
 {
-	return targetDimension;
+  return targetDimension;
 }

+ 56 - 58
math/ftransform/PCA.h

@@ -1,4 +1,4 @@
-/** 
+/**
  * @file PCA.h
  * @brief extract fourier domain value
  * @author Michael Koch
@@ -21,63 +21,61 @@ namespace OBJREC {
 class PCA: public FTransform
 {
 
-     protected:
-          NICE::Vector mean;
-
-          NICE::Matrix basis;
-		      NICE::Matrix normbasis;
-		  
-          NICE::Matrix normalization;
-          uint targetDimension; 
-          uint maxiteration;
-          double mindelta; 
-
-          void calculateMean ( const NICE::Matrix &features, NICE::Vector & mean );
- 
-     public:
-       
-          PCA (uint dim,uint maxiteration=100,double mindelta=1e-4);
-          PCA (void);
-
-          NICE::Matrix getBasis();
-     
-          NICE::Vector getMean();       
-          void restore (std::istream & is, int format = 0);
-          void store (std::ostream & os, int format = 0) const;
-          void clear ();
-          
-          /**
-           * get Basis Vectors of PCA
-           * @param features Input Features
-           * @param dimension Dimension size / number of principal components 
-          * @return Basis Vectors 
-          */
-          void calculateBasis(const NICE::Matrix &features,const uint targetDimension,const uint mode=0);
-          void calculateBasis(const NICE::Matrix &features,const uint targetDimension,const bool adaptive,const double targetRatio=1.0);
-		  
-		  /**
-		   * returns the dimension of the transformed features
-		   * @return feature dim
-		   */
-		  int getTargetDim();
-          
-          /**
-           * get Features in PCA Space
-           * @param data input data
-           * @param normalize normalisation switch
-           * @return Features as Vector
-           */
-
-          NICE::Vector getFeatureVector(const NICE::Vector &data,const bool normalize=true);
-          
-       
-          
-          ~PCA();
-
-   private:
- 
-          void init (uint dim=10,uint maxiteration=100,double mindelta=1e-4);
-        
+  protected:
+    NICE::Vector mean;
+
+    NICE::Matrix basis;
+    NICE::Matrix normbasis;
+
+    NICE::Matrix normalization;
+    uint targetDimension;
+    uint maxiteration;
+    double mindelta;
+
+    void calculateMean ( const NICE::Matrix &features, NICE::Vector & mean );
+
+  public:
+
+    PCA ( uint dim, uint maxiteration = 100, double mindelta = 1e-4 );
+    PCA ( void );
+
+    NICE::Matrix getBasis();
+
+    NICE::Vector getMean();
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
+
+    /**
+     * get Basis Vectors of PCA
+     * @param features Input Features
+     * @param dimension Dimension size / number of principal components
+    * @return Basis Vectors
+    */
+    void calculateBasis ( const NICE::Matrix &features, const uint targetDimension, const uint mode = 0 );
+    void calculateBasis ( const NICE::Matrix &features, const uint targetDimension, const bool adaptive, const double targetRatio = 1.0 );
+
+    /**
+     * returns the dimension of the transformed features
+     * @return feature dim
+     */
+    int getTargetDim();
+
+    /**
+     * get Features in PCA Space
+     * @param data input data
+     * @param normalize normalisation switch
+     * @return Features as Vector
+     */
+
+    NICE::Vector getFeatureVector ( const NICE::Vector &data, const bool normalize = true );
+
+    ~PCA();
+
+  private:
+
+    void init ( uint dim = 10, uint maxiteration = 100, double mindelta = 1e-4 );
+
 };
 
 

+ 0 - 88
math/ftransform/progs/Makefile.inc

@@ -1,88 +0,0 @@
-# BINARY-DIRECTORY-MAKEFILE
-# conventions:
-# - there are no subdirectories, they are ignored!
-# - all ".C", ".cpp" and ".c" files in the current directory are considered
-#   independent binaries, and linked as such.
-# - the binaries depend on the library of the parent directory
-# - the binary names are created with $(BINNAME), i.e. it will be more or less
-#   the name of the .o file
-# - all binaries will be added to the default build list ALL_BINARIES
-
-# --------------------------------
-# - remember the last subdirectory
-#
-# set the variable $(SUBDIR) correctly to the current subdirectory. this
-# variable can be used throughout the current makefile.inc. The many 
-# SUBDIR_before, _add, and everything are only required so that we can recover
-# the previous content of SUBDIR before exitting the makefile.inc
-
-SUBDIR_add:=$(dir $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)))
-SUBDIR_before:=$(SUBDIR)
-SUBDIR:=$(strip $(SUBDIR_add))
-SUBDIR_before_$(SUBDIR):=$(SUBDIR_before)
-
-# ------------------------
-# - include subdirectories
-#
-# note the variables $(SUBDIRS_OF_$(SUBDIR)) are required later on to recover
-# the dependencies automatically. if you handle dependencies on your own, you
-# can also dump the $(SUBDIRS_OF_$(SUBDIR)) variable, and include the
-# makefile.inc of the subdirectories on your own...
-
-#SUBDIRS_OF_$(SUBDIR):=$(patsubst %/Makefile.inc,%,$(wildcard $(SUBDIR)*/Makefile.inc))
-#include $(SUBDIRS_OF_$(SUBDIR):%=%/Makefile.inc)
-
-# ----------------------------
-# - include local dependencies
-#
-# include the libdepend.inc file, which gives additional dependencies for the
-# libraries and binaries. additionally, an automatic dependency from the library
-# of the parent directory is added (commented out in the code below).
-
--include $(SUBDIR)libdepend.inc
-
-PARENTDIR:=$(patsubst %/,%,$(dir $(patsubst %/,%,$(SUBDIR))))
-$(eval $(call PKG_DEPEND_INT,$(PARENTDIR)))
-
-# ---------------------------
-# - objects in this directory
-#
-# the use of the variable $(OBJS) is not mandatory. it is mandatory however
-# to update $(ALL_OBJS) in a way that it contains the path and name of
-# all objects. otherwise we can not include the appropriate .d files.
-
-OBJS:=$(patsubst %.cpp,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.cpp))) \
-      $(patsubst %.C,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.C))) \
-      $(shell grep -ls Q_OBJECT $(SUBDIR)*.h | sed -e's@^@/@;s@.*/@$(OBJDIR)moc_@;s@\.h$$@.o@') \
-      $(patsubst %.c,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.c)))
-ALL_OBJS += $(OBJS)
-
-# ----------------------------
-# - binaries in this directory
-#
-# output of binaries in this directory. none of the variables has to be used.
-# but everything you add to $(ALL_LIBRARIES) and $(ALL_BINARIES) will be
-# compiled with `make all`. be sure again to add the files with full path.
-
-BINARIES:=$(patsubst %.o,$(BINDIR)%,$(filter-out moc_%,$(notdir $(OBJS))))
-ALL_BINARIES+=$(BINARIES)
-
-# ---------------------
-# - binary dependencies
-#
-# there is no way of determining the binary dependencies automatically, so we
-# follow conventions. each binary depends on the corresponding .o file and
-# on the libraries specified by the INTLIBS/EXTLIBS. these dependencies can be
-# specified manually or they are automatically stored in a .bd file.
-
-$(foreach head,$(wildcard $(SUBDIR)*.h),$(eval $(shell grep -q Q_OBJECT $(head) && echo $(head) | sed -e's@^@/@;s@.*/\(.*\)\.h$$@$(BINDIR)\1:$(OBJDIR)moc_\1.o@')))
--include $(OBJS:%.o=%.bd)
-
-# -------------------
-# - subdir management
-#
-# as the last step, always add this line to correctly recover the subdirectory
-# of the makefile including this one!
-
-SUBDIR:=$(SUBDIR_before_$(SUBDIR))
-

+ 59 - 75
math/ftransform/tests/TestFTransform.cpp

@@ -29,7 +29,7 @@ using namespace std;
 using namespace NICE;
 using namespace OBJREC;
 
-CPPUNIT_TEST_SUITE_REGISTRATION(TestFTransform);
+CPPUNIT_TEST_SUITE_REGISTRATION ( TestFTransform );
 
 void TestFTransform::setUp()
 {
@@ -41,81 +41,65 @@ void TestFTransform::tearDown()
 
 void TestFTransform::TestFTransformComputation()
 {
-    uint samplecount = 16; //samples
-    uint sampledimension = 8; //sample dimension
-    bool init_random = true;
-
-    NICE::Matrix T(samplecount, sampledimension);
-
-    //trivial test
-    CPPUNIT_ASSERT_EQUAL(samplecount, (uint)T.rows());
-    CPPUNIT_ASSERT_EQUAL(sampledimension, (uint)T.cols());
-
-
-    T.set(0.0);
-    if (init_random)
-        srand48(time(NULL));
-
-    // generate random matrix
-    for (uint i = 0 ; i < T.rows() ; i++)
-        for (uint j = 0 ; j < T.cols() ; j++)
-        {
-            T(i, j) = drand48();
-        }
-//cout<<T<<endl;
-    PCA *ftransform = new PCA(sampledimension);
-#ifdef NICE_USELIB_ICE
-#ifdef NICE_USELIB_TRLAN
-	for (int mode = 0;mode <= 1;mode++)
+  uint samplecount = 13; //samples
+  uint sampledimension = 4; //sample dimension
+
+  NICE::Matrix T ( samplecount, sampledimension );
+  NICE::Matrix goalBasis ( sampledimension, sampledimension );
+  NICE::Matrix goalFeats ( samplecount, sampledimension );
+
+  //trivial test
+  CPPUNIT_ASSERT_EQUAL ( samplecount, ( uint ) T.rows() );
+  CPPUNIT_ASSERT_EQUAL ( sampledimension, ( uint ) T.cols() );
+
+  ifstream is ( "./pca.data" );
+  for ( uint i = 0 ; i < T.rows() ; i++ )
+    for ( uint j = 0 ; j < T.cols() ; j++ )
+      is >> T ( i, j );
+
+  for ( uint i = 0 ; i < goalBasis.rows() ; i++ )
+    for ( uint j = 0 ; j < goalBasis.cols() ; j++ )
+      is >> goalBasis ( i, j );
+
+  for ( uint i = 0 ; i < goalFeats.rows() ; i++ )
+    for ( uint j = 0 ; j < goalFeats.cols() ; j++ )
+      is >> goalFeats ( i, j );
+  is.close();
+
+
+  PCA *ftransform = new PCA ( sampledimension );
+
+  bool mode = false;
+  ftransform->calculateBasis ( T, sampledimension, mode ); //fastes available method
+  NICE::Matrix basis, featurematrix;
+  featurematrix = T;
+  //cout << featurematrix << endl;
+  basis = ftransform->getBasis();
+  //cout<<basis<<endl;
+  //orthogonality test
+
+  for ( uint i = 0 ; i < goalBasis.rows() ; i++ )
+    for ( uint j = 0 ; j < goalBasis.cols() ; j++ )
+    {
+      CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN ( abs ( goalBasis ( i, j ) ), abs ( basis ( i, j ) ), 1e-4 );
+    }
+  //transform features and test
+
+  for ( uint k = 0;k < T.rows();k++ )
+  {
+    NICE::Vector feature, feature_transformed;
+    feature = T.getRow ( k );
+    feature_transformed = ftransform-> getFeatureVector ( feature, false );
+    for ( uint d = 0;d < feature_transformed.size();d++ )
     {
-        ftransform->calculateBasis(T, sampledimension, mode); //fastes available method
-        NICE::Matrix basis, featurematrix;
-        featurematrix = T;
-        basis = ftransform->getBasis();
-        //cout<<basis<<endl;
-        //orthogonality test
-        for (int k = 0;k < basis.rows() - 1;k++)
-        {
-            NICE::Vector b1, b2;
-            b1 = basis.getRow(k);
-            b2 = basis.getRow(k + 1);
-            double sp = b1.scalarProduct(b2);
-            CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN(0.0, sp, 1e-4);
-        }
-        //transform features and test
-
-        for (int k = 0;k < T.rows();k++)
-        {
-            NICE::Vector feature, feature_transformed;
-            feature = T.getRow(k);
-            feature_transformed = ftransform-> getFeatureVector(feature, true);
-            for (uint d = 0;d < feature_transformed.size();d++)
-            {
-                featurematrix(k, d) = feature_transformed[d];
-            }
-        }
-
-        //cout<<featurematrix<<endl;
-        //Covariance Test
-        NICE::Matrix covariance;
-        covariance = featurematrix.transpose() * featurematrix;
-        ////cout<<covariance<<endl;
-        for (uint i = 0;i < covariance.rows();i++)
-        {
-            for (uint j = 0;j < covariance.cols();j++)
-            {
-                if (i == j)
-                {
-                    CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN((double)samplecount, covariance(i, j), 1e-4);
-                }
-                else
-                {
-                    CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN(0.0, covariance(i, j), 1e-4);
-                }
-            }
-        }
+      featurematrix ( k, d ) = feature_transformed[d];
     }
-#endif
-#endif
+  }
 
+  for ( uint i = 0 ; i < goalFeats.rows() ; i++ )
+    for ( uint j = 0 ; j < goalFeats.cols() ; j++ )
+    {
+      CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN ( abs ( goalFeats ( i, j ) ), abs ( featurematrix ( i, j ) ), 1e-2 );
+    }
 }
+

+ 15 - 14
math/ftransform/tests/TestFTransform.h

@@ -1,20 +1,20 @@
 //
 // C++ Interface: TestFTransform
 //
-// Description: 
+// Description:
 //
 //
 // Author: Michael Koch <Koch.Michael@uni-jena.de>, (C) 2009
 //
 // Copyright: See COPYING file that comes with this distribution
 //
-/** 
+/**
  * @file TestFTransform.h
  * @brief TestFTransform
  * @author Michael Koch
  * @date Di Aug 4 2009
  */
- 
+
 
 #ifndef OBJREC_TestFTransform_H
 #define OBJREC_TestFTransform_H
@@ -23,26 +23,27 @@
 #include <cppunit/extensions/HelperMacros.h>
 
 /**
- * CppUnit-Testcase. 
+ * CppUnit-Testcase.
  * Tests for EigenValue Operations
  */
 class TestFTransform : public CppUnit::TestFixture
 {
-     CPPUNIT_TEST_SUITE( TestFTransform );
+    CPPUNIT_TEST_SUITE ( TestFTransform );
+
 
-    
-     CPPUNIT_TEST( TestFTransformComputation );
+    CPPUNIT_TEST ( TestFTransformComputation );
 
-     CPPUNIT_TEST_SUITE_END();
+    CPPUNIT_TEST_SUITE_END();
 
-     private:
+  private:
+
+  public:
+    void setUp();
+    void tearDown();
+    void TestFTransformComputation();
 
-     public:
-          void setUp();
-          void tearDown();
-          void TestFTransformComputation();
-       
 };
 
 #endif // _TestFTransform_H_
 
+

+ 30 - 0
math/ftransform/tests/pca.data

@@ -0,0 +1,30 @@
+7	26	6	60
+1	29	15	52
+11	56	8	20
+11	31	8	47
+7	52	6	33
+11	55	9	22
+3	71	17	6
+1	31	22	44
+2	54	18	22
+21	47	4	26
+1	40	23	34
+11	66	9	12
+10	68	8	12
+-0.067799985695474	-0.646018286568727	0.567314540990512	0.506179559977705
+-0.678516235418647	-0.019993340484099	-0.543969276583817	0.493268092159297
+0.029020832106229	0.755309622491132	0.403553469172668	0.515567418476836
+0.730873909451461	-0.108480477171676	-0.468397518388289	0.484416225289198
+36.821825999449722	-6.870878154227368	-4.590944457629744	0.396652582713913
+29.607273420710978	4.610881963526304	-2.247578163663947	-0.395843536696488
+-12.981775719737621	-4.204913183175940	0.902243082694698	-1.126100587210614
+23.714725720918029	-6.634052554708719	1.854742000806314	-0.378564808384691
+-0.553191676624596	-4.461732123178687	-6.087412652325180	0.142384896047281
+-10.812490833309822	-3.646571174544059	0.912970791674604	-0.134968810314679
+-32.588166608817936	8.979846284936064	-1.606265913996589	0.081763927599949
+22.606395499005593	10.725906457369447	3.236537714483417	0.324334774646368
+-9.262587237675843	8.985373347478786	-0.016909578102172	-0.543746175981799
+-3.283969329640674	-14.157277337500913	7.046512994833764	0.340509860960608
+9.220031117829379	12.386080787220450	3.428342878284625	0.435152769664895
+-25.584908517429557	-2.781693148152387	-0.386716066864491	0.446817950545607
+-26.903161834677618	-2.930971165042989	-2.445522630195304	0.411607156409659

+ 26 - 21
math/kernels/genericKernel.h

@@ -1,34 +1,39 @@
 #ifndef _NICE_OBJREC_GENERICKERNELSELECTION_INCLUDE
 #define _NICE_OBJREC_GENERICKERNELSELECTION_INCLUDE
 
-
 #include <vector>
 #include "KernelRBF.h"
 #include "KernelExp.h"
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 class GenericKernelSelection
 {
-    public:
-
-		static Kernel *selectKernel ( const NICE::Config *conf, std::string kernel_type )
-		{
-			Kernel *kernel = NULL;
-
-			if ( kernel_type == "rbf" ) {
-				double log_rbf_gamma = conf->gD("Kernel","log_rbf_gamma",-2.5);
-				kernel = new KernelRBF (log_rbf_gamma);
-			} else if ( kernel_type == "exp" ) {
-				double log_rbf_gamma = conf->gD("Kernel","log_rbf_gamma",-2.5);
-				double log_rbf_sv = conf->gD("Kernel","log_rbf_sv",0.0);
-				kernel = new KernelExp (log_rbf_gamma, log_rbf_sv);
-			} else {
-				fthrow(Exception, "Kernel type " << kernel_type << " is unknown" );
-			}
-
-			return kernel;
-		}
+  public:
+
+    static Kernel *selectKernel ( const NICE::Config *conf, std::string kernel_type )
+    {
+      Kernel *kernel = NULL;
+
+      if ( kernel_type == "rbf" )
+      {
+        double log_rbf_gamma = conf->gD ( "Kernel","log_rbf_gamma",-2.5 );
+        kernel = new KernelRBF ( log_rbf_gamma );
+      }
+      else if ( kernel_type == "exp" )
+      {
+        double log_rbf_gamma = conf->gD ( "Kernel","log_rbf_gamma",-2.5 );
+        double log_rbf_sv = conf->gD ( "Kernel","log_rbf_sv",0.0 );
+        kernel = new KernelExp ( log_rbf_gamma, log_rbf_sv );
+      }
+      else
+      {
+        fthrow ( NICE::Exception, "Kernel type " << kernel_type << " is unknown" );
+      }
+
+      return kernel;
+    }
 
 };
 

+ 53 - 53
math/mathbase/Featuretype.cpp

@@ -6,85 +6,85 @@ using namespace OBJREC;
 using namespace NICE;
 using namespace std;
 
-FeatureType::FeatureType(const FeatureType &_ft)
+FeatureType::FeatureType ( const FeatureType &_ft )
 {
-	sv = _ft.sv;
-	v = _ft.v;
-	ft = _ft.ft;
+  sv = _ft.sv;
+  v = _ft.v;
+  ft = _ft.ft;
 }
 
-FeatureType::FeatureType(int f, int dim)
+FeatureType::FeatureType ( int f, int dim )
 {
-	ft = f;
-	setDim(dim);
+  ft = f;
+  setDim ( dim );
 }
 
-FeatureType::FeatureType(SparseVector &tsv) : sv(tsv)
+FeatureType::FeatureType ( SparseVector &tsv ) : sv ( tsv )
 {
-	sv = tsv;
-	ft = SPARSEVECTORFEATURE;
-	v.clear();
+  sv = tsv;
+  ft = SPARSEVECTORFEATURE;
+  v.clear();
 }
 
-FeatureType::FeatureType(Vector &tv) //: v(tv)
+FeatureType::FeatureType ( Vector &tv ) //: v(tv)
 {
-	v.resize(tv.size());
-	for(int i = 0; i < v.size(); i++)
-	{
-		v[i] = tv[i];
-	}
-	ft = VECTORFEATURE;
-	sv.clear();
+  v.resize ( tv.size() );
+  for ( int i = 0; i < v.size(); i++ )
+  {
+    v[i] = tv[i];
+  }
+  ft = VECTORFEATURE;
+  sv.clear();
 }
-					
-void FeatureType::setDim(int dim)
+
+void FeatureType::setDim ( int dim )
 {
-	if(ft == SPARSEVECTORFEATURE)
-	{
-		sv.setDim(dim);
-	}
-	else
-	{
-		v.resize(dim);
-	}
+  if ( ft == SPARSEVECTORFEATURE )
+  {
+    sv.setDim ( dim );
+  }
+  else
+  {
+    v.resize ( dim );
+  }
 }
-					
-double FeatureType::get(int pos) const
+
+double FeatureType::get ( int pos ) const
 {
-	assert(pos < getDim());
-	if(ft == SPARSEVECTORFEATURE)
-	{
-		return sv.get(pos);
-	}
-	else
-	{
-		return v[pos];
-	}
+  assert ( pos < getDim() );
+  if ( ft == SPARSEVECTORFEATURE )
+  {
+    return sv.get ( pos );
+  }
+  else
+  {
+    return v[pos];
+  }
 }
-					
+
 int FeatureType::getType()
 {
-	return ft;
+  return ft;
 }
 
 int FeatureType::getDim() const
 {
-	if(ft == SPARSEVECTORFEATURE)
-	{
-		return sv.getDim();
-	}
-	else
-	{
-		return (int)v.size();
-	}
+  if ( ft == SPARSEVECTORFEATURE )
+  {
+    return sv.getDim();
+  }
+  else
+  {
+    return ( int ) v.size();
+  }
 }
-		
+
 const NICE::Vector& FeatureType::getVec() const
 {
-	return v;
+  return v;
 }
 
 const SparseVector& FeatureType::getSVec() const
 {
-	return sv;
+  return sv;
 }

+ 73 - 73
math/mathbase/Featuretype.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FeatureType.h
 * @brief dynamic selection between SparseVector and Vector
 * @author Björn Fröhlich
@@ -8,84 +8,84 @@
 #ifndef FeatureTypeINCLUDE
 #define FeatureTypeINCLUDE
 
- 
-#include "core/vector/SparseVector.h"
+
+#include "core/vector/SparseVectorT.h"
 
 #include "core/basics/Persistent.h"
 
 
 namespace OBJREC {
 
-	//! enumeration for feature types
-	enum Featuretype
-	{
-		VECTORFEATURE,
-		SPARSEVECTORFEATURE
-	};
-
-	//! a class to differ between Vector und Sparsevector features
-	class FeatureType
-	{
-		protected:
-			//! Sparse or Vectorfeature?
-			int ft;
-			
-			//! save to sv if Sparsefeatures
-			NICE::SparseVector sv;
-			
-			//! save to v if vectorfeature
-			NICE::Vector v;
-		public:
-			
-			/**
-			 * constructor
-			 * @param f type of the faeture
-			 * @param dim dimension of the new feature
-			 */
-			FeatureType(int f, int dim);
-			
-			/**
-			 * constructor setting SparseFeature
-			 * @param tsv input SparseFeature
-			 */
-			FeatureType(NICE::SparseVector &tsv);
-			
-			/**
-			 * constructor setting VectorFeature
-			 * @param tv input VectorFeature
-			 */
-			FeatureType(NICE::Vector &tv);
-			
-			/**
-			 * copy constructor
-			 * @param _ft 
-			 */
-			FeatureType(const FeatureType &_ft);
-					
-			void setDim(int dim);
-			
-			/**
-			 * get the dimension of feature
-			 * @return dimension of feature
-			 */
-			int getDim() const;
-					
-			/**
-			 * returns adress of Vector
-			 * @return 
-			 */
-			const NICE::Vector& getVec() const;
-			
-			/**
-			 * returns adress of SparseVector
-			 * @return 
-			 */
-			const NICE::SparseVector& getSVec() const;
-			
-			double get(int pos) const;
-					
-			int getType();
-	};	
+//! enumeration for feature types
+enum Featuretype
+{
+    VECTORFEATURE,
+    SPARSEVECTORFEATURE
+};
+
+//! a class to differ between Vector und Sparsevector features
+class FeatureType
+{
+protected:
+    //! Sparse or Vectorfeature?
+    int ft;
+
+    //! save to sv if Sparsefeatures
+    NICE::SparseVector sv;
+
+    //! save to v if vectorfeature
+    NICE::Vector v;
+public:
+
+    /**
+     * constructor
+     * @param f type of the faeture
+     * @param dim dimension of the new feature
+     */
+    FeatureType(int f, int dim);
+
+    /**
+     * constructor setting SparseFeature
+     * @param tsv input SparseFeature
+     */
+    FeatureType(NICE::SparseVector &tsv);
+
+    /**
+     * constructor setting VectorFeature
+     * @param tv input VectorFeature
+     */
+    FeatureType(NICE::Vector &tv);
+
+    /**
+     * copy constructor
+     * @param _ft
+     */
+    FeatureType(const FeatureType &_ft);
+
+    void setDim(int dim);
+
+    /**
+     * get the dimension of feature
+     * @return dimension of feature
+     */
+    int getDim() const;
+
+    /**
+     * returns adress of Vector
+     * @return
+     */
+    const NICE::Vector& getVec() const;
+
+    /**
+     * returns adress of SparseVector
+     * @return
+     */
+    const NICE::SparseVector& getSVec() const;
+
+    double get(int pos) const;
+
+    int getType();
+};
 
 } // namespace
 

+ 257 - 257
math/mathbase/FullVector.cpp

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FullVector.cpp
 * @brief non sparse vector
 * @author Erik Rodner
@@ -30,389 +30,389 @@ using namespace std;
 
 FullVector::FullVector ( const map<int, double> & mymap )
 {
-    length = 0;
-    for ( map<int, double>::const_iterator i = mymap.begin();
-		i != mymap.end(); i++ )
-    {
-	int k = i->first;
-	if ( k+1 > length )
-	    length = k+1;
-    }
+  length = 0;
+  for ( map<int, double>::const_iterator i = mymap.begin();
+        i != mymap.end(); i++ )
+  {
+    int k = i->first;
+    if ( k + 1 > length )
+      length = k + 1;
+  }
+
+  data = new double[length];
+  memset ( ( void * ) data, 0, sizeof ( double ) *length );
+
+  for ( map<int, double>::const_iterator i = mymap.begin();
+        i != mymap.end(); i++ )
+  {
+    int k = i->first;
+    double v = i->second;
+    data[k] = v;
+  }
 
-    data = new double[length];
-    memset ( (void *)data, 0, sizeof(double)*length );
-  
-    for ( map<int, double>::const_iterator i = mymap.begin();
-		i != mymap.end(); i++ )
-    {
-	int k = i->first;
-	double v = i->second;
-	data[k] = v;
-    }
- 
 }
 
 FullVector::FullVector ( const map<short, double> & mymap )
 {
-	length = 0;
-	for ( map<short, double>::const_iterator i = mymap.begin();
-		     i != mymap.end(); i++ )
-	{
-		int k = (int)i->first;
-		if ( k+1 > length )
-			length = k+1;
-	}
-
-	data = new double[length];
-	memset ( (void *)data, 0, sizeof(double)*length );
-  
-	for ( map<short, double>::const_iterator i = mymap.begin();
-		     i != mymap.end(); i++ )
-	{
-		int k = i->first;
-		double v = i->second;
-		data[k] = v;
-	}
- 
+  length = 0;
+  for ( map<short, double>::const_iterator i = mymap.begin();
+        i != mymap.end(); i++ )
+  {
+    int k = ( int ) i->first;
+    if ( k + 1 > length )
+      length = k + 1;
+  }
+
+  data = new double[length];
+  memset ( ( void * ) data, 0, sizeof ( double ) *length );
+
+  for ( map<short, double>::const_iterator i = mymap.begin();
+        i != mymap.end(); i++ )
+  {
+    int k = i->first;
+    double v = i->second;
+    data[k] = v;
+  }
+
 }
 
 FullVector::FullVector ( const FullVector & v )
 {
-    length = v.length;
+  length = v.length;
 
-	if ( length == 0 )
-		data = NULL;
-	else {
-		data = new double[length];
-		memset ( (void *)data, 0, sizeof(double)*length );
+  if ( length == 0 )
+    data = NULL;
+  else {
+    data = new double[length];
+    memset ( ( void * ) data, 0, sizeof ( double ) *length );
 
-		for ( int i = 0 ; i < length ; i++ )
-			data[i] = v.data[i];
-	}
+    for ( int i = 0 ; i < length ; i++ )
+      data[i] = v.data[i];
+  }
 }
 
 FullVector::FullVector ()
 {
-    length = 0;
-    data = NULL;
+  length = 0;
+  data = NULL;
 }
 
-FullVector::FullVector (int _length) 
+FullVector::FullVector ( int _length )
 {
-    length = _length;
-    if ( length > 0 )
-    {
-		data = new double[length];
-		memset ( (void *)data, 0, sizeof(double)*length );
-    } else {
-		data = NULL;
-    }
+  length = _length;
+  if ( length > 0 )
+  {
+    data = new double[length];
+    memset ( ( void * ) data, 0, sizeof ( double ) *length );
+  } else {
+    data = NULL;
+  }
 }
 
 FullVector::~FullVector ()
 {
-    if ( data != NULL )
-		delete [] data;
+  if ( data != NULL )
+    delete [] data;
 }
 
-void FullVector::set ( double val ) 
+void FullVector::set ( double val )
 {
-    for ( int i = 0 ; i < length ; i++  )
-		data[i] = val;
+  for ( int i = 0 ; i < length ; i++ )
+    data[i] = val;
 }
 
 void FullVector::reinit ( int _length )
 {
-    if ( data != NULL ) {
-		delete [] data;
-    }
-    length = _length;
-    data = new double [ length ];
-    memset ( (void *)data, 0, sizeof(double)*length );
+  if ( data != NULL ) {
+    delete [] data;
+  }
+  length = _length;
+  data = new double [ length ];
+  memset ( ( void * ) data, 0, sizeof ( double ) *length );
 }
 
 void FullVector::add ( const FullVector & v )
 {
-    add ( v, 1.0 );
+  add ( v, 1.0 );
 }
 
-double & FullVector::operator[] (int i)
+double & FullVector::operator[] ( int i )
 {
-	assert ( i < length );
-    	return data[i];
+  assert ( i < length );
+  return data[i];
 }
 
-const double & FullVector::operator[] (int i) const
+const double & FullVector::operator[] ( int i ) const
 {
-    assert ( i < length );
-    return data[i];
+  assert ( i < length );
+  return data[i];
 }
 
 void FullVector::add ( const FullVector & v, double lambda )
 {
-    assert ( v.length >= length );
-    for ( int i = 0 ; i < v.length ; i++  )
-	data[i] += v.data[i] * lambda;
+  assert ( v.length >= length );
+  for ( int i = 0 ; i < v.length ; i++ )
+    data[i] += v.data[i] * lambda;
 }
 
 void FullVector::add ( double beta )
 {
-    for ( int i = 0 ; i < length; i++ )
-		data[i] += beta;
+  for ( int i = 0 ; i < length; i++ )
+    data[i] += beta;
 }
 
 void FullVector::divide ( const FullVector & v )
 {
-    assert ( v.length >= length );
-    for ( int i = 0 ; i < length ; i++ )
-    {
-		if ( fabs(data[i]) < 10e-11 ) continue;
-
-		double value = v.data[i];
-		if ( fabs(value) < 10e-11 ) {
-			fprintf (stderr, "FullVector::divide: Division by Zero !\n");
-			exit(-1);
-		} else {
-			data[i] /= value;
-		}
+  assert ( v.length >= length );
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    if ( fabs ( data[i] ) < 10e-11 ) continue;
+
+    double value = v.data[i];
+    if ( fabs ( value ) < 10e-11 ) {
+      fprintf ( stderr, "FullVector::divide: Division by Zero !\n" );
+      exit ( -1 );
+    } else {
+      data[i] /= value;
     }
+  }
 }
 
 void FullVector::multiply ( const FullVector & v )
 {
-    assert ( v.length >= length );
-    for ( int i = 0 ; i < length ; i++ )
-    {
-		data[i] *= v.data[i];
-    }
+  assert ( v.length >= length );
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    data[i] *= v.data[i];
+  }
 }
 
 void FullVector::multiply ( double val )
 {
-    for ( int i = 0 ; i < length ; i++ )
-		data[i] *= val;
+  for ( int i = 0 ; i < length ; i++ )
+    data[i] *= val;
 }
 
-void FullVector::restore (istream & is, int format)
+void FullVector::restore ( istream & is, int format )
 {
-	std::string tag;
-	is >> tag;
-	if ( tag != "SVECTOR" ) {
-		fprintf (stderr, "FullVector: format error !\n");
-	}
-    
-	const int bufsize = 1024*1024;
-	char *buf = new char[bufsize];
-	std::string buf_s;
-
-	vector<string> elements;
-	vector<string> pair;
-	
-	elements.clear();
-	
-	is.get ( buf, bufsize );
-	buf_s = buf;
-
-	if ( buf_s.size() <= 0 ) 
-		return;
-
-	StringTools::split ( buf_s, ' ', elements );
-
-	if ( elements.size() <= 1 )
-		return;
-
-	reinit(elements.size()-1);
-
-	size_t l = 0;
-	// skip first element because of white space
-	for ( vector<string>::const_iterator i  = elements.begin()+1; 
-						 i != elements.end();
-						 i++, l++ )
-	{
-		pair.clear();
-		StringTools::split ( *i, ':', pair );
-		if ( pair.size() == 2 ) 
-		{
-			double val = atof ( pair[1].c_str() );
-			(*this)[l] = val;
-		}
-	}
-
-    delete [] buf;
-}
+  std::string tag;
+  is >> tag;
+  if ( tag != "SVECTOR" ) {
+    fprintf ( stderr, "FullVector: format error !\n" );
+  }
 
-void FullVector::store (ostream & os, int format) const
-{
-    os << "SVECTOR ";
-    for ( int i = 0 ; i < length ; i++ )
+  const int bufsize = 1024 * 1024;
+  char *buf = new char[bufsize];
+  std::string buf_s;
+
+  vector<string> elements;
+  vector<string> pair;
+
+  elements.clear();
+
+  is.get ( buf, bufsize );
+  buf_s = buf;
+
+  if ( buf_s.size() <= 0 )
+    return;
+
+  StringTools::split ( buf_s, ' ', elements );
+
+  if ( elements.size() <= 1 )
+    return;
+
+  reinit ( elements.size() - 1 );
+
+  size_t l = 0;
+  // skip first element because of white space
+  for ( vector<string>::const_iterator i  = elements.begin() + 1;
+        i != elements.end();
+        i++, l++ )
+  {
+    pair.clear();
+    StringTools::split ( *i, ':', pair );
+    if ( pair.size() == 2 )
     {
-		os << i << ":" << data[i] << " ";
+      double val = atof ( pair[1].c_str() );
+      ( *this ) [l] = val;
     }
-    os << "END" << endl;
+  }
+
+  delete [] buf;
+}
+
+void FullVector::store ( ostream & os, int format ) const
+{
+  os << "SVECTOR ";
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    os << i << ":" << data[i] << " ";
+  }
+  os << "END" << endl;
 }
 
 void FullVector::clear ()
 {
-    if ( length != 0 ) 
-		memset ( data, 0x0, sizeof(double)*length );
+  if ( length != 0 )
+    memset ( data, 0x0, sizeof ( double ) *length );
 }
 
 double FullVector::sum () const
 {
-    double sumv = 0.0;
-    for ( int i = 0 ; i < length ; i++ )
-		sumv += data[i];
+  double sumv = 0.0;
+  for ( int i = 0 ; i < length ; i++ )
+    sumv += data[i];
 
-    return sumv;
+  return sumv;
 }
 
 void FullVector::normalize ()
 {
-    double sum = 0;
-    for ( int i = 0 ; i < length ; i++ )
-		sum += data[i];
+  double sum = 0;
+  for ( int i = 0 ; i < length ; i++ )
+    sum += data[i];
 
 #ifdef FULLVECTOR_THROW_NORMALIZATION_EXCEPTION
-    assert ( fabs(sum) > 1e-10 );
+  assert ( fabs ( sum ) > 1e-10 );
 #endif
-    if ( fabs(sum) < 1e-10 ) {
-		//fprintf (stderr, "WARNING: normalization failed !\n");
-		for ( int i = 0 ; i < length ; i++ )
-			data[i] = 0.0;
+  if ( fabs ( sum ) < 1e-10 ) {
+    //fprintf (stderr, "WARNING: normalization failed !\n");
+    for ( int i = 0 ; i < length ; i++ )
+      data[i] = 0.0;
 
-    } else {
-		for ( int i = 0 ; i < length ; i++ )
-			data[i] /= sum;
-    }
+  } else {
+    for ( int i = 0 ; i < length ; i++ )
+      data[i] /= sum;
+  }
 }
 
 void FullVector::addMap ( const map<int, int> & v, double lambda )
 {
-    for ( map<int, int>::const_iterator v_it = v.begin();
-				       v_it != v.end();
-				       v_it++ )
-    {
-		int i = v_it->first;
-		assert ( i < length );
-		data[i] += v_it->second * lambda;
-    }
+  for ( map<int, int>::const_iterator v_it = v.begin();
+        v_it != v.end();
+        v_it++ )
+  {
+    int i = v_it->first;
+    assert ( i < length );
+    data[i] += v_it->second * lambda;
+  }
 }
 
 void FullVector::addMap ( const map<int, double> & v, double lambda )
 {
-    for ( map<int, double>::const_iterator v_it = v.begin();
-				       v_it != v.end();
-				       v_it++ )
-    {
-		int i = v_it->first;
-		assert ( i < length );
-		data[i] += v_it->second * lambda;
-    }
+  for ( map<int, double>::const_iterator v_it = v.begin();
+        v_it != v.end();
+        v_it++ )
+  {
+    int i = v_it->first;
+    assert ( i < length );
+    data[i] += v_it->second * lambda;
+  }
 }
 
 int FullVector::maxElement () const
 {
-    int maxindex = 0;
-    double max = - numeric_limits<double>::max();
-    for ( int i = 0 ; i < length ; i++ )
+  int maxindex = 0;
+  double max = - numeric_limits<double>::max();
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    if ( data[i] > max )
     {
-		if ( data[i] > max )
-		{
-			maxindex = i;
-			max = data[i];
-		}
+      maxindex = i;
+      max = data[i];
     }
-    return maxindex;
+  }
+  return maxindex;
 }
 
 int FullVector::maxElementExclusive ( int key ) const
 {
-    int maxindex = (key == 0) ? 1 : 0;
-    double max = - numeric_limits<double>::max();
-    for ( int i = 0 ; i < length ; i++ )
+  int maxindex = ( key == 0 ) ? 1 : 0;
+  double max = - numeric_limits<double>::max();
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    double val = data[i];
+    if ( ( i != key ) && ( val > max ) )
     {
-		double val = data[i];
-		if ( (i != key) && (val > max) )
-		{
-			maxindex = i;
-			max = val;
-		}
+      maxindex = i;
+      max = val;
     }
-    return maxindex;
+  }
+  return maxindex;
 }
 
 double FullVector::entropy () const
 {
-    double entropy = 0.0;
-    double sum = 0.0;
-    for ( int i = 0 ; i < length ; i++ )
-    {
-		double val = data[i];
-		if ( val <= 0.0 ) continue;
-			entropy -= val*log(val);
-		sum += val;
-    }
-    entropy /= sum;
-    entropy += log(sum);
-    return entropy;
+  double entropy = 0.0;
+  double sum = 0.0;
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    double val = data[i];
+    if ( val <= 0.0 ) continue;
+    entropy -= val * log ( val );
+    sum += val;
+  }
+  entropy /= sum;
+  entropy += log ( sum );
+  return entropy;
 }
-	
+
 void FullVector::getSortedIndices ( vector<int> & indizes ) const
 {
-    vector< pair<double, int> > tmp;
-    for ( int i = 0 ; i < length ; i++ )
-	if ( fabs(data[i]) > 10e-11 )
-	    tmp.push_back ( pair<double, int> (  data[i], i  ) );
+  vector< pair<double, int> > tmp;
+  for ( int i = 0 ; i < length ; i++ )
+    if ( fabs ( data[i] ) > 10e-11 )
+      tmp.push_back ( pair<double, int> ( data[i], i ) );
 
-    sort ( tmp.begin(), tmp.end() );
+  sort ( tmp.begin(), tmp.end() );
 
-    for ( vector<pair<double,int> >::const_iterator j = tmp.begin();
-		j != tmp.end(); j++ )
-	indizes.push_back ( j->second );
+  for ( vector<pair<double, int> >::const_iterator j = tmp.begin();
+        j != tmp.end(); j++ )
+    indizes.push_back ( j->second );
 }
-	
+
 double FullVector::max () const
 {
-    double max = - numeric_limits<double>::max();
-    for ( int i = 0 ; i < length ; i++ )
-    {
-		if ( data[i] > max )
-			max = data[i];
-    }
-    return max;
+  double max = - numeric_limits<double>::max();
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    if ( data[i] > max )
+      max = data[i];
+  }
+  return max;
 }
 
 double FullVector::min () const
 {
-    double min = numeric_limits<double>::max();
-    for ( int i = 0 ; i < length ; i++ )
-    {
-		if ( data[i] < min )
-			min = data[i];
-    }
-    return min;
+  double min = numeric_limits<double>::max();
+  for ( int i = 0 ; i < length ; i++ )
+  {
+    if ( data[i] < min )
+      min = data[i];
+  }
+  return min;
 }
 
 double FullVector::get ( size_t i ) const
 {
-    assert ( (int)i < length );
-    return data[i];
+  assert ( ( int ) i < length );
+  return data[i];
 }
-	
+
 void FullVector::operator= ( const FullVector & v )
 {
-    if ( data != NULL )
-		delete [] data;
+  if ( data != NULL )
+    delete [] data;
 
-    length = v.length;
+  length = v.length;
 
-	if ( length == 0 )
-		data = NULL;
-	else {
-		data = new double[length];
-		memset ( (void *)data, 0, sizeof(double)*length );
+  if ( length == 0 )
+    data = NULL;
+  else {
+    data = new double[length];
+    memset ( ( void * ) data, 0, sizeof ( double ) *length );
 
-		for ( int i = 0 ; i < length ; i++ )
-			data[i] = v.data[i];
-	}
+    for ( int i = 0 ; i < length ; i++ )
+      data[i] = v.data[i];
+  }
 }

+ 47 - 43
math/mathbase/FullVector.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file FullVector.h
 * @brief non sparse vector
 * @author Erik Rodner
@@ -8,7 +8,7 @@
 #ifndef FullVectorINCLUDE
 #define FullVectorINCLUDE
 
- 
+
 #include <vector>
 #include <map>
 #include <iostream>
@@ -22,62 +22,66 @@ namespace OBJREC {
 class FullVector : public NICE::Persistent
 {
 
-    protected:
+  protected:
 
-    public:
+  public:
 
-	double *data;
-	int length;
+    double *data;
+    int length;
 
-	FullVector ( const std::map<int, double> & mymap );
-	FullVector ( const std::map<short, double> & mymap );
-	/**
-	 * Creates a vector with specified size (values will be randomized initialized)
-	 * @param length 
-	 */
-	FullVector (int length);
-	FullVector ();
-	FullVector ( const FullVector & v );
-	~FullVector ();
+    FullVector ( const std::map<int, double> & mymap );
+    FullVector ( const std::map<short, double> & mymap );
+    /**
+     * Creates a vector with specified size (values will be randomized initialized)
+     * @param length
+     */
+    FullVector ( int length );
+    FullVector ();
+    FullVector ( const FullVector & v );
+    ~FullVector ();
 
-	void set ( double val ); 
+    void set ( double val );
 
-	void add ( const FullVector & v );
-	void add ( const FullVector & v, double lambda );
-	void add ( double beta );
+    void add ( const FullVector & v );
+    void add ( const FullVector & v, double lambda );
+    void add ( double beta );
 
-	void addMap ( const std::map<int, int> & v, double lambda = 1.0 );
-	void addMap ( const std::map<int, double> & v, double lambda = 1.0 );
+    void addMap ( const std::map<int, int> & v, double lambda = 1.0 );
+    void addMap ( const std::map<int, double> & v, double lambda = 1.0 );
 
-	void normalize ();
+    void normalize ();
 
-	void reinit ( int length );
+    void reinit ( int length );
 
-	void restore (std::istream & is, int format = 0);
-	void store (std::ostream & os, int format = 0) const;
-	void clear ();
+    void restore ( std::istream & is, int format = 0 );
+    void store ( std::ostream & os, int format = 0 ) const;
+    void clear ();
 
-	double entropy () const;
+    double entropy () const;
 
-	void multiply ( const FullVector & v );
-	void multiply ( double val );
-	void divide ( const FullVector & v );
-	double sum () const;
+    void multiply ( const FullVector & v );
+    void multiply ( double val );
+    void divide ( const FullVector & v );
+    double sum () const;
 
-	double max () const;
-	double min () const;
-	int maxElement () const;
-	int maxElementExclusive ( int key ) const;
-	void getSortedIndices ( std::vector<int> & indizes ) const;
+    double max () const;
+    double min () const;
+    int maxElement () const;
+    int maxElementExclusive ( int key ) const;
+    void getSortedIndices ( std::vector<int> & indizes ) const;
 
-	double get( size_t i ) const;
+    double get ( size_t i ) const;
 
-	inline int size() const { return length; };
-	inline bool empty() { return length == 0; };
+    inline int size() const {
+      return length;
+    };
+    inline bool empty() {
+      return length == 0;
+    };
 
-	double & operator[] (int i);
-	void operator= ( const FullVector & v );
-	const double & operator[] (int i) const;
+    double & operator[] ( int i );
+    void operator= ( const FullVector & v );
+    const double & operator[] ( int i ) const;
 
 };
 

+ 0 - 88
math/mathbase/progs/Makefile.inc

@@ -1,88 +0,0 @@
-# BINARY-DIRECTORY-MAKEFILE
-# conventions:
-# - there are no subdirectories, they are ignored!
-# - all ".C", ".cpp" and ".c" files in the current directory are considered
-#   independent binaries, and linked as such.
-# - the binaries depend on the library of the parent directory
-# - the binary names are created with $(BINNAME), i.e. it will be more or less
-#   the name of the .o file
-# - all binaries will be added to the default build list ALL_BINARIES
-
-# --------------------------------
-# - remember the last subdirectory
-#
-# set the variable $(SUBDIR) correctly to the current subdirectory. this
-# variable can be used throughout the current makefile.inc. The many 
-# SUBDIR_before, _add, and everything are only required so that we can recover
-# the previous content of SUBDIR before exitting the makefile.inc
-
-SUBDIR_add:=$(dir $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)))
-SUBDIR_before:=$(SUBDIR)
-SUBDIR:=$(strip $(SUBDIR_add))
-SUBDIR_before_$(SUBDIR):=$(SUBDIR_before)
-
-# ------------------------
-# - include subdirectories
-#
-# note the variables $(SUBDIRS_OF_$(SUBDIR)) are required later on to recover
-# the dependencies automatically. if you handle dependencies on your own, you
-# can also dump the $(SUBDIRS_OF_$(SUBDIR)) variable, and include the
-# makefile.inc of the subdirectories on your own...
-
-#SUBDIRS_OF_$(SUBDIR):=$(patsubst %/Makefile.inc,%,$(wildcard $(SUBDIR)*/Makefile.inc))
-#include $(SUBDIRS_OF_$(SUBDIR):%=%/Makefile.inc)
-
-# ----------------------------
-# - include local dependencies
-#
-# include the libdepend.inc file, which gives additional dependencies for the
-# libraries and binaries. additionally, an automatic dependency from the library
-# of the parent directory is added (commented out in the code below).
-
--include $(SUBDIR)libdepend.inc
-
-PARENTDIR:=$(patsubst %/,%,$(dir $(patsubst %/,%,$(SUBDIR))))
-$(eval $(call PKG_DEPEND_INT,$(PARENTDIR)))
-
-# ---------------------------
-# - objects in this directory
-#
-# the use of the variable $(OBJS) is not mandatory. it is mandatory however
-# to update $(ALL_OBJS) in a way that it contains the path and name of
-# all objects. otherwise we can not include the appropriate .d files.
-
-OBJS:=$(patsubst %.cpp,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.cpp))) \
-      $(patsubst %.C,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.C))) \
-      $(shell grep -ls Q_OBJECT $(SUBDIR)*.h | sed -e's@^@/@;s@.*/@$(OBJDIR)moc_@;s@\.h$$@.o@') \
-      $(patsubst %.c,$(OBJDIR)%.o,$(notdir $(wildcard $(SUBDIR)*.c)))
-ALL_OBJS += $(OBJS)
-
-# ----------------------------
-# - binaries in this directory
-#
-# output of binaries in this directory. none of the variables has to be used.
-# but everything you add to $(ALL_LIBRARIES) and $(ALL_BINARIES) will be
-# compiled with `make all`. be sure again to add the files with full path.
-
-BINARIES:=$(patsubst %.o,$(BINDIR)%,$(filter-out moc_%,$(notdir $(OBJS))))
-ALL_BINARIES+=$(BINARIES)
-
-# ---------------------
-# - binary dependencies
-#
-# there is no way of determining the binary dependencies automatically, so we
-# follow conventions. each binary depends on the corresponding .o file and
-# on the libraries specified by the INTLIBS/EXTLIBS. these dependencies can be
-# specified manually or they are automatically stored in a .bd file.
-
-$(foreach head,$(wildcard $(SUBDIR)*.h),$(eval $(shell grep -q Q_OBJECT $(head) && echo $(head) | sed -e's@^@/@;s@.*/\(.*\)\.h$$@$(BINDIR)\1:$(OBJDIR)moc_\1.o@')))
--include $(OBJS:%.o=%.bd)
-
-# -------------------
-# - subdir management
-#
-# as the last step, always add this line to correctly recover the subdirectory
-# of the makefile including this one!
-
-SUBDIR:=$(SUBDIR_before_$(SUBDIR))
-

+ 0 - 88
math/mathbase/progs/testSparseVector.cpp

@@ -1,88 +0,0 @@
-/** 
-* @file testSparseVector.cpp
-// refactor-nice.pl: check this substitution
-// old: * @brief test sparse vector implementation
-* @brief test sparse std::vector implementation
-* @author Erik Rodner
-* @date 05/07/2008
-
-*/
-#include "core/vector/SparseVector.h"
-
-#include <iostream>
-
-using namespace NICE;
-
-
-using namespace std;
-
-void rndSparseVector ( SparseVector & v, int numIndex = 1000 )
-{
-    for ( uint k = 0 ; k < (uint)numIndex ; k++ )
-    {
-	if ( drand48() < 0.5 )
-	    v.insert ( pair<int, double> ( k, drand48() ) );
-    }
-}
-
-void calcIntegralSparseMap ( SparseVector *map, int xsize, int ysize )
-{
-    int k = xsize;
-    for ( int y = 1 ; y < ysize; y++, k+=xsize )
-    {
-        fprintf (stderr, "x %d y %d s %d\n", 0, y, (int)map[k].size() );
-	map[k].add ( (map[k-xsize]) );
-    }
-
-    k = 1;
-    for ( int x = 1 ; x < xsize; x++, k++ )
-	map[k].add ( (map[k-1]) );
-
-    k = xsize + 1;
-    for ( int y = 1 ; y < ysize ; y++,k++ )
-	for ( int x = 1 ; x < xsize ; x++,k++ )
-	{
-	    fprintf (stderr, "x %d y %d s %d\n", x, y, (int)map[k].size() );
-	    map[k].add ( (map[k-1]) );
-	    map[k].add ( (map[k-xsize]) );
-	    map[k].add ( (map[k-xsize-1]), -1.0 );
-	}
-
-
-}
-
-int main (int argc, char **argv)
-{   
-    std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
-    
-    SparseVector v;
-    SparseVector w;
-    
-    srand48(time(NULL));
-    srand(time(NULL));
-    
-    rndSparseVector ( v, 10 );
-    rndSparseVector ( w, 10 );
-
-    v.store ( cerr );
-    w.store ( cerr );
-
-    v.add(w);
-
-    v.store ( cerr );
-   
-    const int xsize = 100;
-    const int ysize = 100;
-    SparseVector *map = new SparseVector[xsize*ysize];
-
-    for ( int k = 0 ; k < xsize*ysize ; k++ )
-	rndSparseVector( map[k] );
-
-    map[xsize*ysize-1].store ( cerr );
-
-    calcIntegralSparseMap ( map, xsize, ysize );
-
-    map[xsize*ysize-1].store ( cerr );
-    
-    return 0;
-}

+ 44 - 28
regression/gpregression/modelselcrit/genericGPModelSelection.h

@@ -7,37 +7,53 @@
 #include "GPMSCLooEstimates.h"
 
 
-namespace OBJREC {
+namespace OBJREC
+{
 
 class GenericGPModelSelection
 {
-    public:
-
-		static GPMSCLooLikelihoodRegression *selectModelSel ( const NICE::Config *conf, std::string modelselcrit_s )
-		{
-			 GPMSCLooLikelihoodRegression *modelselcrit = NULL;
-
-			 if ( modelselcrit_s == "loo_pred_prob_weighted" ) {
-				 modelselcrit = new GPMSCLooLikelihoodRegression ( true );
-			 } else if ( modelselcrit_s == "loo_pred_prob" ) {
-				 modelselcrit = new GPMSCLooLikelihoodRegression ( false );
-			 } else if ( modelselcrit_s == "loo_pred_squash_opt" ) {
-				 modelselcrit = new GPMSCLooLikelihoodClassification ( );
-			 } else if ( modelselcrit_s == "loo_pred_squash" ) {
-				 modelselcrit = new GPMSCLooLikelihoodClassificationFixed ( );
-			 } else if ( modelselcrit_s == "loo_recognition_rate" ) {
-				 modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_RECOGNITIONRATE );
-			 } else if ( modelselcrit_s == "loo_auc" ) {
-				 modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_AUC );
-			 } else if ( modelselcrit_s == "loo_avgprec" ) {
-				 modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_AVGPREC );
-			 } else {
-				  fthrow ( Exception, "Model selection criterion unknown " << modelselcrit_s << " not (yet) supported." << std::endl <<
-				  			"(genericGPModelSelection.h contains a list of classifiers to choose from)");
-			 }
-
-			 return modelselcrit;
-		}
+  public:
+
+    static GPMSCLooLikelihoodRegression *selectModelSel ( const NICE::Config *conf, std::string modelselcrit_s )
+    {
+      GPMSCLooLikelihoodRegression *modelselcrit = NULL;
+
+      if ( modelselcrit_s == "loo_pred_prob_weighted" )
+      {
+        modelselcrit = new GPMSCLooLikelihoodRegression ( true );
+      }
+      else if ( modelselcrit_s == "loo_pred_prob" )
+      {
+        modelselcrit = new GPMSCLooLikelihoodRegression ( false );
+      }
+      else if ( modelselcrit_s == "loo_pred_squash_opt" )
+      {
+        modelselcrit = new GPMSCLooLikelihoodClassification ( );
+      }
+      else if ( modelselcrit_s == "loo_pred_squash" )
+      {
+        modelselcrit = new GPMSCLooLikelihoodClassificationFixed ( );
+      }
+      else if ( modelselcrit_s == "loo_recognition_rate" )
+      {
+        modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_RECOGNITIONRATE );
+      }
+      else if ( modelselcrit_s == "loo_auc" )
+      {
+        modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_AUC );
+      }
+      else if ( modelselcrit_s == "loo_avgprec" )
+      {
+        modelselcrit = new GPMSCLooVarious ( GPMSCLooVarious::P_AVGPREC );
+      }
+      else
+      {
+        fthrow ( NICE::Exception, "Model selection criterion unknown " << modelselcrit_s << " not (yet) supported." << std::endl <<
+                 "(genericGPModelSelection.h contains a list of classifiers to choose from)" );
+      }
+
+      return modelselcrit;
+    }
 
 };
 

+ 42 - 31
regression/regressionbase/RegressionAlgorithm.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file RegressionAlgorithm.h
 * @brief interface for a regression algorithm
 * @author Erik Rodner
@@ -10,41 +10,52 @@
 
 #include "core/vector/VVector.h"
 
-namespace OBJREC {
-  
-#define ROADWORKS fthrow(Exception, "Persistent Interface: not yet implemented.");
+namespace OBJREC
+{
+
+#define ROADWORKS fthrow(NICE::Exception, "Persistent Interface: not yet implemented.");
 
 /** interface for a regression algorithm */
 class RegressionAlgorithm : public NICE::Persistent
 {
 
-    protected:
-
-    public:
-  
-	/** simple constructor */
-	RegressionAlgorithm();
-      
-	/** simple destructor */
-	virtual ~RegressionAlgorithm();
-
-	/** learn parameters/models/whatever using a set of vectors and
-	 *  their corresponding function values
-	 */
-	virtual void teach ( const NICE::VVector & x, const NICE::Vector & y ) = 0; 
-
-	/** predict the function value for \c x */
-	virtual double predict ( const NICE::Vector & x ) = 0;
-    
-	/** persistent interface */
-	virtual void restore (std::istream & is, int format = 0) { ROADWORKS };
-	virtual void store (std::ostream & os, int format = 0) const { ROADWORKS };
-	virtual void clear () { ROADWORKS };
-
-	/** clone function */
-	virtual RegressionAlgorithm *clone(void) const {
-		fthrow(Exception, "clone() not yet implemented!\n");
-	}
+  protected:
+
+  public:
+
+    /** simple constructor */
+    RegressionAlgorithm();
+
+    /** simple destructor */
+    virtual ~RegressionAlgorithm();
+
+    /** learn parameters/models/whatever using a set of vectors and
+     *  their corresponding function values
+     */
+    virtual void teach ( const NICE::VVector & x, const NICE::Vector & y ) = 0;
+
+    /** predict the function value for \c x */
+    virtual double predict ( const NICE::Vector & x ) = 0;
+
+    /** persistent interface */
+    virtual void restore ( std::istream & is, int format = 0 )
+    {
+      ROADWORKS
+    };
+    virtual void store ( std::ostream & os, int format = 0 ) const
+    {
+      ROADWORKS
+    };
+    virtual void clear ()
+    {
+      ROADWORKS
+    };
+
+    /** clone function */
+    virtual RegressionAlgorithm *clone ( void ) const
+    {
+      fthrow ( NICE::Exception, "clone() not yet implemented!\n" );
+    }
 
 };
 

+ 49 - 47
regression/regressionbase/RegressionAlgorithmKernel.h

@@ -1,4 +1,4 @@
-/** 
+/**
 * @file RegressionAlgorithmKernel.h
 * @brief interface for a regression algorithm which is based on kernels
 * @author Erik Rodner
@@ -12,55 +12,57 @@
 #include "vislearning/math/kernels/KernelData.h"
 #include "RegressionAlgorithm.h"
 
-namespace OBJREC {
-  
+namespace OBJREC
+{
+
 /** interface for a regression algorithm which is based on kernels */
 class RegressionAlgorithmKernel : public RegressionAlgorithm
 {
-    protected:
-		NICE::VVector X;
-		NICE::Vector y;
-
-		NICE::Config conf;
-
-		Kernel *kernelFunction;
-
-    public:
-  
-		/** simple constructor */
-		RegressionAlgorithmKernel( const NICE::Config *conf, Kernel *kernelFunction = NULL );
-
-		/** copy constructor */
-		RegressionAlgorithmKernel( const RegressionAlgorithmKernel & src );
-		  
-		/** simple destructor */
-		virtual ~RegressionAlgorithmKernel();
-		 
-		/** learn parameters/models/whatever with a kernel matrix (contained in a general structure kernel data)
-		 *  of a set
-		 *  of vectors and the corresponding function values \c y 
-		 */
-		virtual void teach ( KernelData *kernelData, const NICE::Vector & y ) = 0;
-
-		/** predict the function value for a vector by using its kernel values with
-		 * the used training set, be careful with the order in \c kernelVector
-		 */
-		virtual double predictKernel ( const NICE::Vector & kernelVector, double kernelSelf ) = 0;
-		
-		// functions to build an interface to RegressionAlgorithm
-		
-		/** learn parameters/models/whatever using a set of vectors and
-		 *  their corresponding function values
-		 */
-		void teach ( const NICE::VVector & X, const NICE::Vector & y ); 
-
-		/** predict the function value for \c x */
-		double predict ( const NICE::Vector & x );
-
-		/** clone function */
-		virtual RegressionAlgorithmKernel *clone(void) const {
-			fthrow(Exception, "clone() not yet implemented!\n");
-		}
+  protected:
+    NICE::VVector X;
+    NICE::Vector y;
+
+    NICE::Config conf;
+
+    Kernel *kernelFunction;
+
+  public:
+
+    /** simple constructor */
+    RegressionAlgorithmKernel ( const NICE::Config *conf, Kernel *kernelFunction = NULL );
+
+    /** copy constructor */
+    RegressionAlgorithmKernel ( const RegressionAlgorithmKernel & src );
+
+    /** simple destructor */
+    virtual ~RegressionAlgorithmKernel();
+
+    /** learn parameters/models/whatever with a kernel matrix (contained in a general structure kernel data)
+     *  of a set
+     *  of vectors and the corresponding function values \c y
+     */
+    virtual void teach ( KernelData *kernelData, const NICE::Vector & y ) = 0;
+
+    /** predict the function value for a vector by using its kernel values with
+     * the used training set, be careful with the order in \c kernelVector
+     */
+    virtual double predictKernel ( const NICE::Vector & kernelVector, double kernelSelf ) = 0;
+
+    // functions to build an interface to RegressionAlgorithm
+
+    /** learn parameters/models/whatever using a set of vectors and
+     *  their corresponding function values
+     */
+    void teach ( const NICE::VVector & X, const NICE::Vector & y );
+
+    /** predict the function value for \c x */
+    double predict ( const NICE::Vector & x );
+
+    /** clone function */
+    virtual RegressionAlgorithmKernel *clone ( void ) const
+    {
+      fthrow ( NICE::Exception, "clone() not yet implemented!\n" );
+    }
 
 };