From 8ff15ae2ce42814fae27ab5eca444457f2b336ba Mon Sep 17 00:00:00 2001
From: Cyrille Valladeau <cyrille.valladeau@c-s.fr>
Date: Thu, 15 May 2008 13:56:19 +0000
Subject: [PATCH] Markov qui compile et reussi les tests.

---
 Code/Markov/otbMRFEnergy.h                    |  56 ++--
 .../otbMRFEnergyGaussianClassification.h      | 117 ++++----
 Code/Markov/otbMRFOptimizer.h                 |  22 +-
 Code/Markov/otbMRFOptimizerICM.h              |  77 +++---
 Code/Markov/otbMRFOptimizerMetropolis.h       |  26 +-
 Code/Markov/otbMRFSampler.h                   |  19 +-
 Code/Markov/otbMRFSamplerMAP.h                | 143 +++++-----
 Code/Markov/otbMRFSamplerRandom.h             | 127 +++++----
 Code/Markov/otbMRFSamplerRandomMAP.h          | 254 +++++++++---------
 Code/Markov/otbMarkovRandomFieldFilter.h      |  35 +--
 Code/Markov/otbMarkovRandomFieldFilter.txx    |  15 +-
 .../otbMRFEnergyGaussianClassification.cxx    |  12 +-
 .../Code/Markov/otbMRFOptimizerMetropolis.cxx |   7 +-
 Testing/Code/Markov/otbMRFSamplerMAP.cxx      |  15 +-
 Testing/Code/Markov/otbMRFSamplerRandom.cxx   |  18 +-
 .../Code/Markov/otbMRFSamplerRandomMAP.cxx    |  23 +-
 .../Markov/otbMarkovRandomFieldFilter.cxx     |  46 ++--
 17 files changed, 510 insertions(+), 502 deletions(-)

diff --git a/Code/Markov/otbMRFEnergy.h b/Code/Markov/otbMRFEnergy.h
index 4fed7475e2..b0dee621df 100644
--- a/Code/Markov/otbMRFEnergy.h
+++ b/Code/Markov/otbMRFEnergy.h
@@ -49,6 +49,8 @@ class ITK_EXPORT MRFEnergy : public itk::Object
     
     typedef itk::Array< double > ParametersType;
     
+    itkNewMacro(Self);
+
     itkTypeMacro(MRFEnergy,itk::Object);
     
     
@@ -68,25 +70,14 @@ class ITK_EXPORT MRFEnergy : public itk::Object
 	    itkExceptionMacro(<<"Invalid number of parameters");
 	  }
 	m_Parameters = parameters;
-	this->Modified();
-        
-// 	bool modified = false;
-// 	for( unsigned int i=0; i<m_NumberOfParameters; i++ )
-// 	  {
-// 	    if (m_Parameters[i] != parameters[i])
-// 	      {
-//                 m_Parameters[i] = parameters[i];
-//                 modified = true;
-// 	      }
-// 	  }
-// 	if (modified)
-// 	  {
-// 	    this->Modified();
-// 	  }
-      }
-    
-    virtual double GetSingleValue(const InputImagePixelType & value1,  const LabelledImagePixelType & value2) = 0;
+	this->Modified();       
+    }
     
+    virtual double GetSingleValue(const InputImagePixelType & value1,  const LabelledImagePixelType & value2)
+      {
+	itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes.");
+      }
+        
     double GetValue(const InputImagePixelType & value1,  const LabelledImagePixelType & value2)
       {
 	return GetSingleValue(value1, value2);
@@ -137,7 +128,7 @@ class ITK_EXPORT MRFEnergy : public itk::Object
     
   protected:
     // The constructor and destructor.
-    MRFEnergy() {};
+    MRFEnergy() {m_NumberOfParameters = 1;};
     virtual ~MRFEnergy() {};
     unsigned int m_NumberOfParameters;
     ParametersType m_Parameters;
@@ -158,8 +149,9 @@ class ITK_EXPORT MRFEnergy<TInput2,TInput2> : public itk::Object
     
     typedef itk::ConstNeighborhoodIterator< LabelledImageType >  LabelledNeighborhoodIterator;
     typedef itk::Array< double >                                 ParametersType;
-    
-    
+
+    itkNewMacro(Self);
+
     itkTypeMacro(MRFEnergy,itk::Object);
     
     
@@ -183,24 +175,13 @@ class ITK_EXPORT MRFEnergy<TInput2,TInput2> : public itk::Object
 	  }
 	m_Parameters = parameters;
 	this->Modified();
-        /*
-	bool modified = false;
-	for( unsigned int i=0; i<m_NumberOfParameters; i++ )
-	  {
-	    if (m_Parameters[i] != parameters[i])
-	      {
-                m_Parameters[i] = parameters[i];
-                modified = true;
-	      }
-	  }
-	if (modified)
-	  {
-	    this->Modified();
-	  }*/
       }
     
-    virtual double GetSingleValue(const LabelledImagePixelType & value1,  const LabelledImagePixelType & value2) = 0;
-    
+    virtual double GetSingleValue(const LabelledImagePixelType & value1,  const LabelledImagePixelType & value2)
+      {
+	itkExceptionMacro(<<"GetSingleValue() has to be declared in child classes.");
+      }
+
     double GetValue(const LabelledImagePixelType & value1,  const LabelledImagePixelType & value2)
       {
 	return GetSingleValue(value1, value2);
@@ -233,6 +214,7 @@ class ITK_EXPORT MRFEnergy<TInput2,TInput2> : public itk::Object
     // The constructor and destructor.
     MRFEnergy() 
     {
+      m_NumberOfParameters = 1;
       m_Parameters=0;
     };
     virtual ~MRFEnergy() {};
diff --git a/Code/Markov/otbMRFEnergyGaussianClassification.h b/Code/Markov/otbMRFEnergyGaussianClassification.h
index d761f8e0d1..3b8a9546a1 100644
--- a/Code/Markov/otbMRFEnergyGaussianClassification.h
+++ b/Code/Markov/otbMRFEnergyGaussianClassification.h
@@ -25,70 +25,69 @@
 
 namespace otb
 {
-  /**
-   * \class MRFEnergyGaussianClassification
-   * \brief This is the implementation of the Gaussian model for Markov classification.
-  *
-  * This is the implementation of the Gaussian Energy model for Markov classification, to be used for
-  * the fidelity term for classification. Energy is:
-  * \f[   U(x_s / y_s) = \frac{(y_s+\mu_{x_s})^2}{2\sigma^2_{x_s}}+\log{\sqrt{2\pi}\sigma_{x_s}} \f]
-  * with
-  * - \f$ x_s \f$ the label on site s
-  * - \f$ y_s \f$ the value on the reference image
-  * - \f$ \mu_{x_s} \f$ and \f$ \sigma^2_{x_s} \f$ the mean and variance of label \f$ x_s \f$
-   */
+/**
+ * \class MRFEnergyGaussianClassification
+ * \brief This is the implementation of the Gaussian model for Markov classification.
+ *
+ * This is the implementation of the Gaussian Energy model for Markov classification, to be used for
+ * the fidelity term for classification. Energy is:
+ * \f[   U(x_s / y_s) = \frac{(y_s+\mu_{x_s})^2}{2\sigma^2_{x_s}}+\log{\sqrt{2\pi}\sigma_{x_s}} \f]
+ * with
+ * - \f$ x_s \f$ the label on site s
+ * - \f$ y_s \f$ the value on the reference image
+ * - \f$ \mu_{x_s} \f$ and \f$ \sigma^2_{x_s} \f$ the mean and variance of label \f$ x_s \f$
+ */
   
-     template< class TInput1, class TInput2>    
-                class ITK_EXPORT MRFEnergyGaussianClassification:public MRFEnergy< TInput1, TInput2>
-    {
-      public:
-        typedef MRFEnergyGaussianClassification Self;
-        typedef MRFEnergy< TInput1, TInput2>  Superclass;
-        typedef itk::SmartPointer<Self>  Pointer;
-        typedef itk::SmartPointer<const Self>  ConstPointer;
+template< class TInput1, class TInput2>    
+class ITK_EXPORT MRFEnergyGaussianClassification:public MRFEnergy< TInput1, TInput2>
+  {
+  public:
+    typedef MRFEnergyGaussianClassification Self;
+    typedef MRFEnergy< TInput1, TInput2>    Superclass;
+    typedef itk::SmartPointer<Self>         Pointer;
+    typedef itk::SmartPointer<const Self>   ConstPointer;
         
-        typedef TInput1 InputImageType;
-        typedef TInput2 LabelledImageType;
-        typedef typename InputImageType::PixelType InputImagePixelType;
-        typedef typename LabelledImageType::PixelType LabelledImagePixelType;
-        
-        typedef itk::Array< double > ParametersType;
+    typedef TInput1                               InputImageType;
+    typedef TInput2                               LabelledImageType;
+    typedef typename InputImageType::PixelType    InputImagePixelType;
+    typedef typename LabelledImageType::PixelType LabelledImagePixelType;
+    typedef itk::Array < double >                 ParametersType;
+	    
+    itkNewMacro(Self);
     
-        itkNewMacro(Self);
-        
-        itkTypeMacro(MRFEnergyGaussianClassification, MRFEnergy);
-  
-        void SetNumberOfParameters(unsigned int nParameters)
-        { 
-          this->m_NumberOfParameters=nParameters;
-          this->m_Parameters.SetSize(this->m_NumberOfParameters);
-          this->Modified();
-        }
-          
-        double GetSingleValue(const InputImagePixelType & value1,  const LabelledImagePixelType & value2)   
-        {
-            if ((unsigned int)value2 >= this->GetNumberOfParameters()/2)
-            {
-              itkExceptionMacro(<<"Number of parameters does not correspond to number of classes" );
-            }
-	    double val1 = static_cast<double>(value1);
-
-            double result = M_SQUARE(val1-this->m_Parameters[2*static_cast<int>(value2)])
-                              / (2*M_SQUARE(this->m_Parameters[2*static_cast<int>(value2)+1]))
-                  + vcl_log(vcl_sqrt(2*M_PI)
-                          *this->m_Parameters[2*static_cast<int>(value2)+1]);
-
-            return static_cast<double>( result );
-        }
-     
-
+    itkTypeMacro(MRFEnergyGaussianClassification, MRFEnergy);
+    
+    void SetNumberOfParameters(unsigned int nParameters)
+      { 
+	Superclass::SetNumberOfParameters(nParameters);
+	this->m_Parameters.SetSize(nParameters);
+	this->Modified();
+      }
     
-      protected:
-      // The constructor and destructor.
-        MRFEnergyGaussianClassification() {};
-        virtual ~MRFEnergyGaussianClassification() {};
 
-    };
+    double GetSingleValue(const InputImagePixelType & value1,  const LabelledImagePixelType & value2)   
+      {
+	if ((unsigned int)value2 >= this->GetNumberOfParameters()/2)
+	  {
+              itkExceptionMacro(<<"Number of parameters does not correspond to number of classes" );
+	  }
+	double val1 = static_cast<double>(value1);
+	
+	double result = M_SQUARE(val1-this->m_Parameters[2*static_cast<int>(value2)])
+	                / (2*M_SQUARE(this->m_Parameters[2*static_cast<int>(value2)+1]))
+	                + vcl_log(vcl_sqrt(2*M_PI)*this->m_Parameters[2*static_cast<int>(value2)+1]);
+	
+	return static_cast<double>( result );
+      }
+    
+    
+    
+  protected:
+    // The constructor and destructor.
+    MRFEnergyGaussianClassification() {};
+    virtual ~MRFEnergyGaussianClassification() {};
+    
+  };
 }
 
 #endif
diff --git a/Code/Markov/otbMRFOptimizer.h b/Code/Markov/otbMRFOptimizer.h
index c95a173e1a..814042c596 100644
--- a/Code/Markov/otbMRFOptimizer.h
+++ b/Code/Markov/otbMRFOptimizer.h
@@ -50,28 +50,14 @@ class ITK_EXPORT MRFOptimizer : public itk::Object
       return this->m_Parameters;
     }
     
-    void SetParameters( const ParametersType & parameters )
+    virtual void SetParameters( const ParametersType & parameters )
     {
-      if( parameters.Size() != m_NumberOfParameters )
+      if( parameters.GetSize() != m_NumberOfParameters )
 	{	
-	  itkExceptionMacro(<<"Invalid number of parameters");
+	  itkExceptionMacro(<<"Invalid number of parameters ("<<parameters.GetSize()<<" , "<<m_NumberOfParameters<<")");
 	}
       m_Parameters = parameters;
       this->Modified();
-      
-//       bool modified = false;
-//       for( unsigned int i=0; i<m_NumberOfParameters; i++ )
-//       {
-//         if (m_Parameters[i] != parameters[i])
-//         {
-//           m_Parameters[i] = parameters[i];
-//           modified = true;
-//         }
-//       }
-//       if (modified)
-//       {
-//         this->Modified();
-//       }
     }
     
     virtual bool Compute(double deltaEnergy) = 0;
@@ -79,7 +65,7 @@ class ITK_EXPORT MRFOptimizer : public itk::Object
   protected:
     MRFOptimizer() 
     {
-      m_Parameters=0;
+      m_Parameters=1;
     }
     virtual ~MRFOptimizer() {}
     unsigned int m_NumberOfParameters;
diff --git a/Code/Markov/otbMRFOptimizerICM.h b/Code/Markov/otbMRFOptimizerICM.h
index 36120fd365..46cbd3faa0 100644
--- a/Code/Markov/otbMRFOptimizerICM.h
+++ b/Code/Markov/otbMRFOptimizerICM.h
@@ -23,47 +23,46 @@
 
 namespace otb
 {
-              /**
-   * \class MRFOptimizerICM
-   * \brief This is the optimizer class implementing the ICM algorithm 
-   *  
-   * This is one optimizer to be used in the MRF framework. This optimizer 
-   * follows the ICM algorithm to accept of reject the value proposed by the sampler
-               */
-  class ITK_EXPORT MRFOptimizerICM : 
-      public MRFOptimizer
-      {       
-        public:
-
-          typedef MRFOptimizerICM Self;
-          typedef MRFOptimizer Superclass;
-          typedef itk::SmartPointer<Self>  Pointer;
-          typedef itk::SmartPointer<const Self>  ConstPointer;
-            
-          itkNewMacro(Self);
-    
-          itkTypeMacro(MRFOptimizerICM,MRFOptimizer);
-            
-            
-          inline bool Compute(double deltaEnergy)
-          {
-            if (deltaEnergy < 0)
-            {
-              return true;
-            }
-            else
-            {
-              return false;
-            }
-          }
-            
-            
-        protected:
-          MRFOptimizerICM() {}
-          virtual ~MRFOptimizerICM() {}
+/**
+ * \class MRFOptimizerICM
+ * \brief This is the optimizer class implementing the ICM algorithm 
+ *  
+ * This is one optimizer to be used in the MRF framework. This optimizer 
+ * follows the ICM algorithm to accept of reject the value proposed by the sampler
+ */
+class ITK_EXPORT MRFOptimizerICM : public MRFOptimizer
+{       
+ public:
+  
+  typedef MRFOptimizerICM               Self;
+  typedef MRFOptimizer                  Superclass;
+  typedef itk::SmartPointer<Self>       Pointer;
+  typedef itk::SmartPointer<const Self> ConstPointer;
+  
+  itkNewMacro(Self);
+  
+  itkTypeMacro(MRFOptimizerICM,MRFOptimizer);
+  
+  
+  inline bool Compute(double deltaEnergy)
+    {
+      if (deltaEnergy < 0)
+	{
+	  return true;
+	}
+      else
+	{
+	  return false;
+	}
+    }
+  
   
-      };       
+ protected:
+  MRFOptimizerICM() {}
+  virtual ~MRFOptimizerICM() {}
   
+};       
+ 
 }
 
 #endif
diff --git a/Code/Markov/otbMRFOptimizerMetropolis.h b/Code/Markov/otbMRFOptimizerMetropolis.h
index 622ffa72a4..bc782b8cc6 100644
--- a/Code/Markov/otbMRFOptimizerMetropolis.h
+++ b/Code/Markov/otbMRFOptimizerMetropolis.h
@@ -21,6 +21,7 @@
 #include "otbMRFOptimizer.h"
 #include "otbMath.h"
 #include "itkNumericTraits.h"
+#include "itkMersenneTwisterRandomVariateGenerator.h"
 
 namespace otb
 {
@@ -46,11 +47,23 @@ class ITK_EXPORT MRFOptimizerMetropolis : public MRFOptimizer
     typedef MRFOptimizer Superclass;
     typedef itk::SmartPointer<Self>  Pointer;
     typedef itk::SmartPointer<const Self>  ConstPointer;
+    typedef Superclass::ParametersType ParametersType;
+      
+    typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
     
     itkNewMacro(Self);
     
     itkTypeMacro(MRFOptimizerMetropolis,MRFOptimizer);
     
+    /** Set parameter to a one array filled with paramVal.*/
+    void SetSingleParameter( double parameterVal )
+      {
+	this->m_Parameters.SetSize(1);
+	this->m_Parameters.Fill(parameterVal);
+	this->Modified();
+    }
+    
+
     inline bool Compute(double deltaEnergy)
       {
 	if (deltaEnergy < 0)
@@ -64,24 +77,29 @@ class ITK_EXPORT MRFOptimizerMetropolis : public MRFOptimizer
 	else
               {
                 double proba = vcl_exp(-(deltaEnergy)/this->m_Parameters[0]);
-                if ( (rand() % 10000) < proba*10000)
+                if ( (m_Generator->GetIntegerVariate() % 10000) < proba*10000)
 		  {
-                    std::cerr << "Opti true " << std::endl;
 		    return true;
 		  }
               }
 	return false;
       }
     
-    
+    /** Methods to cancel random effects.*/
+    void InitializeSeed(int seed){ m_Generator->SetSeed(seed); }
+    void InitializeSeed(){ m_Generator->SetSeed(); }
+
   protected:
     MRFOptimizerMetropolis() {
       this->m_NumberOfParameters = 1;
-      this->m_Parameters.SetSize(this->m_NumberOfParameters);
+      this->m_Parameters.SetSize(1);
       this->m_Parameters[0]=1.0;
+      m_Generator = RandomGeneratorType::New();
+      m_Generator->SetSeed();
     }
     virtual ~MRFOptimizerMetropolis() {}
     double m_Temperature;
+    RandomGeneratorType::Pointer m_Generator;
   };       
  
 }
diff --git a/Code/Markov/otbMRFSampler.h b/Code/Markov/otbMRFSampler.h
index b38c1c40a5..491ced2b8e 100644
--- a/Code/Markov/otbMRFSampler.h
+++ b/Code/Markov/otbMRFSampler.h
@@ -32,7 +32,7 @@ namespace otb
  */
     
 template< class TInput1, class TInput2>    
-class ITK_EXPORT MRFSampler:public itk::Object
+class ITK_EXPORT MRFSampler : public itk::Object
   {
   public:
     
@@ -68,12 +68,9 @@ class ITK_EXPORT MRFSampler:public itk::Object
     itkGetConstMacro(EnergyBefore, double);
     itkGetConstMacro(EnergyAfter, double);
     
-    
     itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType);
     itkSetObjectMacro( EnergyFidelity, EnergyFidelityType);
     
-    
-    
     virtual int Compute( const InputImageNeighborhoodIterator & itData, 
 			 const LabelledImageNeighborhoodIterator & itRegul) = 0;
     
@@ -93,8 +90,18 @@ class ITK_EXPORT MRFSampler:public itk::Object
     
   protected:
     // The constructor and destructor.
-    MRFSampler() {}
-    virtual ~MRFSampler() {}
+    MRFSampler() 
+      {   
+	m_EnergyRegularization = EnergyRegularizationType::New();
+	m_EnergyFidelity =  EnergyFidelityType::New(),
+	m_NumberOfClasses =1;
+	m_EnergyBefore = 1.;
+	m_EnergyAfter = 1.;
+	m_DeltaEnergy = 1.;
+	m_EnergyCurrent = 1.;
+	m_Lambda = 1.;
+      };
+    virtual ~MRFSampler() {};
     
   };
   
diff --git a/Code/Markov/otbMRFSamplerMAP.h b/Code/Markov/otbMRFSamplerMAP.h
index 7f8685a4a4..a91ff014b7 100644
--- a/Code/Markov/otbMRFSamplerMAP.h
+++ b/Code/Markov/otbMRFSamplerMAP.h
@@ -23,93 +23,82 @@
 
 namespace otb
 {
-  /**
-   * \class MRFSamplerMAP
-   * \brief This is the base class for sampler methods used in the MRF framework.
-   * 
-   * This is one sampler to be used int he MRF framework. This sampler select the 
-   * value which maximizes the apriori probability (minimum energy).
-   *
-   */
+/**
+ * \class MRFSamplerMAP
+ * \brief This is the base class for sampler methods used in the MRF framework.
+ * 
+ * This is one sampler to be used int he MRF framework. This sampler select the 
+ * value which maximizes the apriori probability (minimum energy).
+ *
+ */
 
-  template< class TInput1, class TInput2>    
-      class ITK_EXPORT MRFSamplerMAP : public MRFSampler< TInput1, TInput2>
-      {
-        public:
-            
-          typedef MRFSamplerMAP Self;
-          typedef MRFSampler< TInput1, TInput2> Superclass;
-          typedef itk::SmartPointer<Self>  Pointer;
-          typedef itk::SmartPointer<const Self>  ConstPointer;
-            
-//           typedef itk::ConstNeighborhoodIterator< TInput1 >  InputImageNeighborhoodIterator;
-//           typedef itk::NeighborhoodIterator< TInput2 >  LabelledImageNeighborhoodIterator;
-//           typedef typename TInput2::PixelType LabelledImagePixelType;
-//             
-//           typedef MRFEnergy<TInput1, TInput2>  EnergyFidelityType;
-//           typedef MRFEnergy<TInput2, TInput2>  EnergyRegularizationType;
-//             
-//           typedef typename EnergyFidelityType::Pointer EnergyFidelityPointer;
-//           typedef typename EnergyRegularizationType::Pointer EnergyRegularizationPointer;
-          
-          typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
-          typedef typename Superclass::InputImagePixelType               InputImagePixelType;
-          typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
-          typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
-          typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
-          typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
-           
-          itkNewMacro(Self);
+template< class TInput1, class TInput2>    
+class ITK_EXPORT MRFSamplerMAP : public MRFSampler< TInput1, TInput2>
+  {
+  public:
     
-          itkTypeMacro(MRFSamplerMAP,MRFSampler);
-            
+    typedef MRFSamplerMAP Self;
+    typedef MRFSampler< TInput1, TInput2> Superclass;
+    typedef itk::SmartPointer<Self>  Pointer;
+    typedef itk::SmartPointer<const Self>  ConstPointer;
             
-          inline int Compute( const InputImageNeighborhoodIterator & itData, 
-                              const LabelledImageNeighborhoodIterator & itRegul)             
-          {
-          if (this->m_NumberOfClasses == 0)
-            {
+    typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
+    typedef typename Superclass::InputImagePixelType               InputImagePixelType;
+    typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
+    typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
+    typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
+    typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
+    
+    itkNewMacro(Self);
+    
+    itkTypeMacro(MRFSamplerMAP,MRFSampler);
+    
+    inline int Compute( const InputImageNeighborhoodIterator & itData, 
+			const LabelledImageNeighborhoodIterator & itRegul)             
+      {
+	if (this->m_NumberOfClasses == 0)
+	  {
             itkExceptionMacro(<<"NumberOfClasse has to be greater than 0.");
-            }
-            
-            this->m_EnergyBefore=this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
-            this->m_EnergyBefore  +=  this->m_Lambda 
-                * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
-              
-              //Try all possible value (how to be generic ?)
-            this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one
-            this->m_Value = itRegul.GetCenterPixel();
-
-            LabelledImagePixelType valueCurrent = 0;
-            while( valueCurrent<static_cast<LabelledImagePixelType>(this->GetNumberOfClasses()) && valueCurrent != itk::NumericTraits<LabelledImagePixelType>::max() )
-            {
-              this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, valueCurrent);
-              this->m_EnergyCurrent += this->m_Lambda 
-                  * this->m_EnergyRegularization->GetValue(itRegul, valueCurrent);  
-              if (this->m_EnergyCurrent < this->m_EnergyAfter)
+	  }
+	
+	this->m_EnergyBefore=this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
+	this->m_EnergyBefore += this->m_Lambda 
+	                        * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
+	
+	//Try all possible value (how to be generic ?)
+	this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one
+	this->m_Value = itRegul.GetCenterPixel();
+	
+	LabelledImagePixelType valueCurrent = 0;
+	while( valueCurrent<static_cast<LabelledImagePixelType>(this->GetNumberOfClasses()) && valueCurrent != itk::NumericTraits<LabelledImagePixelType>::max() )
+	  {
+	    this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, valueCurrent);
+	    this->m_EnergyCurrent += this->m_Lambda 
+	      * this->m_EnergyRegularization->GetValue(itRegul, valueCurrent);  
+	    if (this->m_EnergyCurrent < this->m_EnergyAfter)
               {
                 this->m_EnergyAfter = this->m_EnergyCurrent;
                 this->m_Value = valueCurrent;
               }
-              valueCurrent++;
-            }
-              
-                         
-            this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
-               
-            return 0;
-          }
-            
-            
+	    valueCurrent++;
+	  }
+	
+	
+	this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
+	
+	return 0;
+      }
+    
+    
         protected:
-            // The constructor and destructor.
-          MRFSamplerMAP() {}
-          virtual ~MRFSamplerMAP() {}
+    // The constructor and destructor.
+    MRFSamplerMAP() {}
+    virtual ~MRFSamplerMAP() {}
     
-      };
-  
+  };
+ 
   
 }
 
diff --git a/Code/Markov/otbMRFSamplerRandom.h b/Code/Markov/otbMRFSamplerRandom.h
index 3ec6871812..6482093d94 100644
--- a/Code/Markov/otbMRFSamplerRandom.h
+++ b/Code/Markov/otbMRFSamplerRandom.h
@@ -24,77 +24,70 @@
 
 namespace otb
 {
-  /**
-   * \class MRFSamplerRandom
-   * \brief This is the base class for sampler methods used in the MRF framework.
-   * 
-   * This is one sampler to be used int he MRF framework. This sampler select the 
-   * value randomly according to a uniform probability.
-   * 
-   */
-
-  template< class TInput1, class TInput2>    
-      class ITK_EXPORT MRFSamplerRandom: public MRFSampler< TInput1, TInput2>
-      {
-        public: 
-          typedef MRFSamplerRandom Self;
-          typedef otb::MRFSampler< TInput1, TInput2> Superclass;
-          typedef itk::SmartPointer<Self>  Pointer;
-          typedef itk::SmartPointer<const Self>  ConstPointer;
- 
-          typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
-          typedef typename Superclass::InputImagePixelType               InputImagePixelType;
-          typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
-          typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
-          typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
-          typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
-          
-          typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
-
-          itkNewMacro(Self);
-
-          itkTypeMacro(MRFSamplerRandom,MRFSampler);
-
-          inline int Compute( const InputImageNeighborhoodIterator & itData, 
-                              const LabelledImageNeighborhoodIterator & itRegul)   
-          {
-            this->m_EnergyBefore = 
-                this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
-            this->m_EnergyBefore +=  this->m_Lambda 
-                * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
+/**
+ * \class MRFSamplerRandom
+ * \brief This is the base class for sampler methods used in the MRF framework.
+ * 
+ * This is one sampler to be used int he MRF framework. This sampler select the 
+ * value randomly according to a uniform probability.
+ * 
+ */
   
-            
-            this->m_Value = 
-                static_cast<LabelledImagePixelType> 
-                (m_Generator->GetIntegerVariate() % this->m_NumberOfClasses);
-  
-            this->m_EnergyAfter = 
-                this->m_EnergyFidelity->GetValue(itData, this->m_Value);
-            this->m_EnergyAfter +=  this->m_Lambda 
-                * this->m_EnergyRegularization->GetValue(itRegul, this->m_Value);
+template< class TInput1, class TInput2>    
+class ITK_EXPORT MRFSamplerRandom: public MRFSampler< TInput1, TInput2>
+  {
+  public: 
+    typedef MRFSamplerRandom                  Self;
+    typedef otb::MRFSampler<TInput1, TInput2> Superclass;
+    typedef itk::SmartPointer<Self>           Pointer;
+    typedef itk::SmartPointer<const Self>     ConstPointer;
+    
+    typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
+    typedef typename Superclass::InputImagePixelType               InputImagePixelType;
+    typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
+    typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
+    typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
+    typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
+    
+    typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
+
+    itkNewMacro(Self);
     
-            this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
+    itkTypeMacro(MRFSamplerRandom,MRFSampler);
+
+    inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul)   
+      {
+	this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
+	this->m_EnergyBefore += this->m_Lambda 
+	                              * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
+	
+	this->m_Value = static_cast<LabelledImagePixelType>(m_Generator->GetIntegerVariate() % this->m_NumberOfClasses);
+	this->m_EnergyAfter = this->m_EnergyFidelity->GetValue(itData, this->m_Value);
+	this->m_EnergyAfter +=  this->m_Lambda * this->m_EnergyRegularization->GetValue(itRegul, this->m_Value);
+	this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
      
-            return 0;
-          }
-  
-  
-        protected:
-// The constructor and destructor.
-          MRFSamplerRandom() {
-            m_Generator =
-                RandomGeneratorType::New();
-            m_Generator->SetSeed();
-          }
-          virtual ~MRFSamplerRandom() {}
+	return 0;
+      }
     
-        private:
-          RandomGeneratorType::Pointer m_Generator;
-      };
-  
-  
+    /** Methods to cancel random effects.*/
+    void InitializeSeed(int seed){ m_Generator->SetSeed(seed); }
+    void InitializeSeed(){ m_Generator->SetSeed(); }
+    
+  protected:
+    // The constructor and destructor.
+    MRFSamplerRandom() 
+      {
+	m_Generator = RandomGeneratorType::New();
+	m_Generator->SetSeed();
+      }
+    virtual ~MRFSamplerRandom() {}
+	  
+    
+  private:
+    RandomGeneratorType::Pointer m_Generator;
+  };  
 }
 
 #endif
diff --git a/Code/Markov/otbMRFSamplerRandomMAP.h b/Code/Markov/otbMRFSamplerRandomMAP.h
index cd25ec9443..3700c43c43 100644
--- a/Code/Markov/otbMRFSamplerRandomMAP.h
+++ b/Code/Markov/otbMRFSamplerRandomMAP.h
@@ -19,141 +19,149 @@
 #ifndef _MRFSamplerRandomMAP_h
 #define _MRFSamplerRandomMAP_h
 
+#include "itkMersenneTwisterRandomVariateGenerator.h"
 #include "otbMRFSampler.h"
 
 namespace otb
 {
-        /**
-   * \class MRFSamplerRandomMAP
-   * \brief This is the base class for sampler methods used in the MRF framework.
-   * 
-   * This is one sampler to be used int he MRF framework. This sampler select the 
-   * value randomly according to the apriori probability.
-   * 
-        * The probability is defined from the energy as:
-   * 
-   *  \f[ P(X=x)= \frac{1}{Z} \exp^{-U(x)}  \f]
-   * 
-   * where \f$ Z = \sum_x \exp^{-U(x)}\f$
-   * 
-         */
-
-  template< class TInput1, class TInput2>    
-      class ITK_EXPORT MRFSamplerRandomMAP: public MRFSampler< TInput1, TInput2>
+/**
+ * \class MRFSamplerRandomMAP
+ * \brief This is the base class for sampler methods used in the MRF framework.
+ * 
+ * This is one sampler to be used int he MRF framework. This sampler select the 
+ * value randomly according to the apriori probability.
+ * 
+ * The probability is defined from the energy as:
+ * 
+ *  \f[ P(X=x)= \frac{1}{Z} \exp^{-U(x)}  \f]
+ * 
+ * where \f$ Z = \sum_x \exp^{-U(x)}\f$
+ * 
+ */
+  
+template< class TInput1, class TInput2>    
+class ITK_EXPORT MRFSamplerRandomMAP: public MRFSampler< TInput1, TInput2>
+  {
+  public:
+    
+    typedef MRFSamplerRandomMAP               Self;
+    typedef otb::MRFSampler<TInput1, TInput2> Superclass;
+    typedef itk::SmartPointer<Self>           Pointer;
+    typedef itk::SmartPointer<const Self>     ConstPointer;
+    
+    typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
+    typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
+    typedef typename Superclass::InputImagePixelType               InputImagePixelType;
+    typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
+    typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
+    typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
+    typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
+    typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
+    
+    itkNewMacro(Self);
+    
+    itkTypeMacro(MRFSamplerRandomMAP,MRFSampler);
+    
+    
+    void SetNumberOfClasses(const unsigned int nClasses)
       {
-        public:
-            
-          typedef MRFSamplerRandomMAP Self;
-          typedef otb::MRFSampler< TInput1, TInput2> Superclass;
-          typedef itk::SmartPointer<Self>  Pointer;
-          typedef itk::SmartPointer<const Self>  ConstPointer;
-            
-          typedef typename Superclass::InputImageNeighborhoodIterator    InputImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImageNeighborhoodIterator LabelledImageNeighborhoodIterator;
-          typedef typename Superclass::LabelledImagePixelType            LabelledImagePixelType;
-          typedef typename Superclass::InputImagePixelType               InputImagePixelType;
-          typedef typename Superclass::EnergyFidelityType                EnergyFidelityType;
-          typedef typename Superclass::EnergyRegularizationType          EnergyRegularizationType;
-          typedef typename Superclass::EnergyFidelityPointer             EnergyFidelityPointer;
-          typedef typename Superclass::EnergyRegularizationPointer       EnergyRegularizationPointer;     
-          
-          itkNewMacro(Self);
+	if (nClasses != this->m_NumberOfClasses || energiesInvalid == true)
+	  {
+	    this->m_NumberOfClasses = nClasses;
+	    if (energy != NULL) 
+	      free(energy);
+	    if (repartitionFunction != NULL) 
+	      free(repartitionFunction);
+	    energy = (double *) calloc(this->m_NumberOfClasses, sizeof(double));
+	    repartitionFunction = (double *) calloc(this->m_NumberOfClasses, sizeof(double));
+	    this->Modified();
+	  }
+      }
     
-          itkTypeMacro(MRFSamplerRandomMAP,MRFSampler);
-            
-            
-          void SetNumberOfClasses(const unsigned int nClasses)
-          {
-            if (nClasses != this->m_NumberOfClasses)
-            {
-              this->m_NumberOfClasses = nClasses;
-              if (energy != NULL) free(energy);
-              if (repartitionFunction != NULL) free(repartitionFunction);
-              energy = (double *) calloc(this->m_NumberOfClasses, sizeof(double));
-              repartitionFunction = (double *) calloc(this->m_NumberOfClasses, sizeof(double));
-              this->Modified();
-            }
-          }
-      
-          inline int Compute( const InputImageNeighborhoodIterator & itData, 
-                              const LabelledImageNeighborhoodIterator & itRegul)
-          {
-            if (this->m_NumberOfClasses == 0)
-            {
+    inline int Compute( const InputImageNeighborhoodIterator & itData, const LabelledImageNeighborhoodIterator & itRegul)
+      {
+	if (this->m_NumberOfClasses == 0)
+	  {
             itkExceptionMacro(<<"NumberOfClasse has to be greater than 0.");
-            }
-            
-            this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
-            this->m_EnergyBefore += this->m_Lambda 
-                 * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
-              
-              //Try all possible value (how to be generic ?)
-            this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one
-            this->m_Value = itRegul.GetCenterPixel();
-              
-            //Compute probability for each possibility
-            double totalProba=0.0;
-            for (LabelledImagePixelType valueCurrent = 0; 
-                 valueCurrent < static_cast<LabelledImagePixelType>(this->m_NumberOfClasses);
-                 ++valueCurrent)
-            {
-              this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, valueCurrent);
-              this->m_EnergyCurrent += this->m_Lambda 
-                  * this->m_EnergyRegularization->GetValue(itRegul, valueCurrent);
-
-              energy[static_cast<unsigned int>(valueCurrent)] 
-                  = this->m_EnergyCurrent;
-              repartitionFunction[static_cast<unsigned int>(valueCurrent)] 
-                  = vcl_exp(-this->m_EnergyCurrent)+totalProba;
-              totalProba 
-                  = repartitionFunction[static_cast<unsigned int>(valueCurrent)];
-
-            }
-              
-              //Pick a value according to probability
-              
-            double select = (rand()/(double(RAND_MAX)+1) * totalProba);
-             unsigned int valueCurrent = 0;
+	  }
+	
+	this->m_EnergyBefore = this->m_EnergyFidelity->GetValue(itData, itRegul.GetCenterPixel());
+	this->m_EnergyBefore += this->m_Lambda 
+	                        * this->m_EnergyRegularization->GetValue(itRegul, itRegul.GetCenterPixel());
+	
+	//Try all possible value (how to be generic ?)
+	this->m_EnergyAfter = this->m_EnergyBefore; //default values to current one
+	this->m_Value = itRegul.GetCenterPixel();
+	
+	//Compute probability for each possibility
+	double totalProba=0.0;
+	for (unsigned int  valueCurrent = 0; valueCurrent < this->m_NumberOfClasses; ++valueCurrent)
+	  {
+	    this->m_EnergyCurrent = this->m_EnergyFidelity->GetValue(itData, static_cast<LabelledImagePixelType>(valueCurrent));
+	    this->m_EnergyCurrent += this->m_Lambda 
+	                             * this->m_EnergyRegularization->GetValue(itRegul, static_cast<LabelledImagePixelType>(valueCurrent));
+	    
+	    energy[valueCurrent] = this->m_EnergyCurrent;
+	    repartitionFunction[valueCurrent] = vcl_exp(-this->m_EnergyCurrent)+totalProba;
+	    totalProba = repartitionFunction[valueCurrent];
+	    
+	  }
+	
+	//Pick a value according to probability
+	
+	double select = (m_Generator->GetIntegerVariate()/(double(RAND_MAX)+1) * totalProba);
+	unsigned int valueCurrent = 0;
         while( valueCurrent<this->GetNumberOfClasses() && repartitionFunction[valueCurrent] <= select)
-        {
+	  {
             valueCurrent++;
-        }
-   
+	  }
+	
         if ( valueCurrent==this->GetNumberOfClasses() )
-        {
+	  {
             valueCurrent = this->GetNumberOfClasses()-1;
-        }
-           
-              
-            if ( this->m_Value != static_cast<LabelledImagePixelType>(valueCurrent))
-            {
-              this->m_Value = static_cast<LabelledImagePixelType>(valueCurrent);
-              this->m_EnergyAfter = energy[static_cast<unsigned int>(valueCurrent)];
-            }
-                            
-            this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
-            
-            return 0;
-          }
-            
-        private:
-          double * repartitionFunction;
-          double * energy; 
-            
-        protected:
-          // The constructor and destructor.
-          MRFSamplerRandomMAP() {
-            energy=NULL;
-            repartitionFunction=NULL;
-          };
-          virtual ~MRFSamplerRandomMAP() {
-            if (energy != NULL) free(energy);
-            if (repartitionFunction != NULL) free(repartitionFunction);
-          };
+	  }
+	
+	
+	if ( this->m_Value != static_cast<LabelledImagePixelType>(valueCurrent))
+	  {
+	    this->m_Value = static_cast<LabelledImagePixelType>(valueCurrent);
+	    this->m_EnergyAfter = energy[static_cast<unsigned int>(valueCurrent)];
+	  }
+	
+	this->m_DeltaEnergy=  this->m_EnergyAfter - this->m_EnergyBefore;
+	
+	return 0;
+      }
     
-      };
-  
-  
+    /** Methods to cancel random effects.*/
+    void InitializeSeed(int seed){ m_Generator->SetSeed(seed); }
+    void InitializeSeed(){ m_Generator->SetSeed(); }
+    
+  private:
+    double * repartitionFunction;
+    double * energy; 
+    bool energiesInvalid;
+    RandomGeneratorType::Pointer m_Generator;
+    
+  protected:
+    // The constructor and destructor.
+    MRFSamplerRandomMAP() 
+      {
+	energy=NULL;
+	repartitionFunction=NULL;
+	energiesInvalid = true;
+	m_Generator = RandomGeneratorType::New();
+	m_Generator->SetSeed();
+      }
+    virtual ~MRFSamplerRandomMAP() 
+      {
+	if (energy != NULL) 
+	  free(energy);
+	if (repartitionFunction != NULL) 
+	  free(repartitionFunction);
+      }
+  };
 }
 
 #endif
diff --git a/Code/Markov/otbMarkovRandomFieldFilter.h b/Code/Markov/otbMarkovRandomFieldFilter.h
index cb0369c1d5..075e234d66 100644
--- a/Code/Markov/otbMarkovRandomFieldFilter.h
+++ b/Code/Markov/otbMarkovRandomFieldFilter.h
@@ -22,6 +22,7 @@
 
 #include "vnl/vnl_vector.h"
 #include "vnl/vnl_matrix.h"
+#include "itkMersenneTwisterRandomVariateGenerator.h"
 
 #include "itkImageClassifierBase.h"
 
@@ -157,7 +158,11 @@ public itk::ImageToImageFilter<TInputImage,TClassifiedImage>
     
     typedef typename LabelledImageFaceListType::iterator 
       LabelledImageFaceListIterator;
-    
+
+    /** Typedef for random values. */
+    typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
+
+
     /** Set the pointer to the classifer being used. */
     void SetClassifier( typename ClassifierType::Pointer ptrToClassifier );
     
@@ -179,19 +184,11 @@ public itk::ImageToImageFilter<TInputImage,TClassifiedImage>
    /**
    ************ ACCESSORS ************
    */
-
-//      void SetEnergyRegularization( EnergyRegularizationPointer enerReg ){ m_EnergyRegularization=enerReg; this->Modified(); };
-//   EnergyRegularizationPointer GetEnergyRegularization(){ return m_EnergyRegularization; };
-//   void SetEnergyFidelity( EnergyFidelityPointer enerFid ){ m_EnergyFidelity=enerFid; this->Modified(); };
-//   EnergyFidelityPointer GetEnergyFidelity(){ return m_EnergyFidelity; };
-  
-  itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType);
-  itkGetObjectMacro( EnergyRegularization, EnergyRegularizationType);
-  
-  itkSetObjectMacro( EnergyFidelity, EnergyFidelityType);
-  itkGetObjectMacro( EnergyFidelity, EnergyFidelityType);      
-  
-   
+    itkSetObjectMacro( EnergyRegularization, EnergyRegularizationType);
+    itkGetObjectMacro( EnergyRegularization, EnergyRegularizationType);
+    
+    itkSetObjectMacro( EnergyFidelity, EnergyFidelityType);
+    itkGetObjectMacro( EnergyFidelity, EnergyFidelityType);        
     
     itkSetObjectMacro( Sampler, SamplerType);
     itkGetObjectMacro( Sampler, SamplerType);
@@ -282,7 +279,10 @@ public itk::ImageToImageFilter<TInputImage,TClassifiedImage>
 		    (itk::Concept::SameDimension<InputImageDimension, ClassifiedImageDimension>));
     /** End concept checking */
 #endif
-    
+
+    /** Methods to cancel random effects.*/
+    void InitializeSeed(int seed){ m_Generator->SetSeed(seed); }
+    void InitializeSeed(){ m_Generator->SetSeed(); }
 
   protected:
     MarkovRandomFieldFilter();
@@ -344,7 +344,8 @@ public itk::ImageToImageFilter<TInputImage,TClassifiedImage>
     std::vector<double>       m_NeighborInfluence;
     std::vector<double>       m_DummyVector;
     
-    
+    RandomGeneratorType::Pointer m_Generator;
+
     /** Pointer to different elements */
     
     EnergyRegularizationPointer m_EnergyRegularization;
@@ -353,7 +354,7 @@ public itk::ImageToImageFilter<TInputImage,TClassifiedImage>
     SamplerPointer              m_Sampler;        
     
     virtual void MinimizeOnce();
-    
+
   private: 
     
   }; // class MarkovRandomFieldFilter
diff --git a/Code/Markov/otbMarkovRandomFieldFilter.txx b/Code/Markov/otbMarkovRandomFieldFilter.txx
index e8251e3c4c..5adf9e97e2 100644
--- a/Code/Markov/otbMarkovRandomFieldFilter.txx
+++ b/Code/Markov/otbMarkovRandomFieldFilter.txx
@@ -25,7 +25,7 @@ namespace otb
 /** ATTENTION : j'ai passe les initialisation dans le constructeur car certaines plateformes (dont NEMO) n'aiment cette maniere d'initialiser*/
 template<class TInputImage, class TClassifiedImage>
 MarkovRandomFieldFilter<TInputImage,TClassifiedImage>
-::MarkovRandomFieldFilter(void) :
+::MarkovRandomFieldFilter(void)/* :
   m_NumberOfClasses(0),
   m_MaximumNumberOfIterations(50),
   m_ErrorCounter(0),
@@ -38,9 +38,9 @@ MarkovRandomFieldFilter<TInputImage,TClassifiedImage>
   m_NumberOfIterations(0),
   m_StopCondition(MaximumNumberOfIterations),
   m_ExternalClassificationSet(false)
-  
+			       */			
 {
-  /*m_NumberOfClasses = 0;
+  m_NumberOfClasses = 0;
   m_MaximumNumberOfIterations = 50;
   m_ErrorCounter = 0;
   m_ImageDeltaEnergy = 0.0;
@@ -51,7 +51,10 @@ MarkovRandomFieldFilter<TInputImage,TClassifiedImage>
   m_SmoothingFactor = 1;
   m_NumberOfIterations = 0;
   m_StopCondition = MaximumNumberOfIterations;
-  m_ExternalClassificationSet = false;*/
+  m_ExternalClassificationSet = false;
+  m_Generator = RandomGeneratorType::New();
+  m_Generator->SetSeed();
+
   this->SetNumberOfRequiredInputs(1);
   if( (int)InputImageDimension != (int)ClassifiedImageDimension )
     {
@@ -66,7 +69,7 @@ MarkovRandomFieldFilter<TInputImage,TClassifiedImage>
   //     this->SetMRFNeighborhoodWeight( m_DummyVector );
   //     this->SetDefaultMRFNeighborhoodWeight();
   
-  srand((unsigned)time(0));
+  //srand((unsigned)time(0));
   
 }
   
@@ -315,7 +318,7 @@ MarkovRandomFieldFilter<TInputImage, TClassifiedImage>
       while ( !outImageIt.IsAtEnd() )
 	{
 	  LabelledImagePixelType randomvalue = static_cast<LabelledImagePixelType>(
-              rand() % static_cast<int>(m_NumberOfClasses)
+              m_Generator->GetIntegerVariate() % static_cast<int>(m_NumberOfClasses)
             );
 	  outImageIt.Set( randomvalue );
 	  ++outImageIt;
diff --git a/Testing/Code/Markov/otbMRFEnergyGaussianClassification.cxx b/Testing/Code/Markov/otbMRFEnergyGaussianClassification.cxx
index 5d11fe4fdb..e0cf022094 100644
--- a/Testing/Code/Markov/otbMRFEnergyGaussianClassification.cxx
+++ b/Testing/Code/Markov/otbMRFEnergyGaussianClassification.cxx
@@ -37,13 +37,21 @@ int otbMRFEnergyGaussianClassification(int argc, char * argv[])
 
   MRFGaussianType::Pointer classif = MRFGaussianType::New();
 
- 
+  classif->SetNumberOfParameters(6);
+  MRFGaussianType::ParametersType param(6);
+  param[0] = 0;
+  param[1] = 1;
+  param[2] = 2;  
+  param[3] = 3;
+  param[4] = 4;
+  param[5] = 5;
+  classif->SetParameters(param);
   std::ofstream file;
   file.open(outputFile);
 
   file<<std::endl;
   file<<"Number of paramters: "<<classif->GetNumberOfParameters()<<std::endl;
-  file<<"GetSingleValue(10, 1): "<<classif->GetSingleValue(10, 1)<<std::endl;
+  file<<"GetSingleValue(10, 1): "<<classif->GetSingleValue(10, 2)<<std::endl;
 
   file.close();
 
diff --git a/Testing/Code/Markov/otbMRFOptimizerMetropolis.cxx b/Testing/Code/Markov/otbMRFOptimizerMetropolis.cxx
index 29046f8e39..89aa24a27c 100644
--- a/Testing/Code/Markov/otbMRFOptimizerMetropolis.cxx
+++ b/Testing/Code/Markov/otbMRFOptimizerMetropolis.cxx
@@ -33,18 +33,13 @@ int otbMRFOptimizerMetropolis(int argc, char * argv[])
   MRFOptimizerType::ParametersType param(1);
   param.Fill(10.);
   object->SetParameters(param);
-
-  // USED TO OVERPASS RANDOM CALCULATION
-  //object->SetValueInsteadRandom(1);
+  object->InitializeSeed(0);// USED TO OVERPASS RANDOM CALCULATION
 
   std::ofstream file;
   file.open(outputFile);
 
   file<<"Compute(0)                                       : "<<object->Compute(0.)<<std::endl;
   file<<"Compute(-1.)                                     : "<<object->Compute(-1.)<<std::endl;
-  file<<"Compute(1.) avec m_ValueInsteadRandom<proba*1000 : "<<object->Compute(1.)<<std::endl;
-  //object->SetValueInsteadRandom( 10000 );
-  file<<"Compute(1.) avec m_ValueInsteadRandom>=proba*1000: "<<object->Compute(1.)<<std::endl;
 
   file.close();
    
diff --git a/Testing/Code/Markov/otbMRFSamplerMAP.cxx b/Testing/Code/Markov/otbMRFSamplerMAP.cxx
index f24abf2031..30844ff091 100644
--- a/Testing/Code/Markov/otbMRFSamplerMAP.cxx
+++ b/Testing/Code/Markov/otbMRFSamplerMAP.cxx
@@ -22,6 +22,7 @@
 #include "otbMRFSamplerMAP.h"
 #include "otbImageFileReader.h"
 #include "otbImage.h"
+#include "otbMRFEnergyPotts.h"
 #include <fstream>
 
 
@@ -41,11 +42,19 @@ int otbMRFSamplerMAP(int argc, char * argv[])
   typedef MRFSamplerMAPType::LabelledImageNeighborhoodIterator LabelledNeighborhoodIterator;
   typedef MRFSamplerMAPType::InputImageNeighborhoodIterator    InputNeighborhoodIterator;
 
+  typedef otb::MRFEnergyPotts <ImageType, LabelType> EnergyFidelityType;
+  typedef otb::MRFEnergyPotts <LabelType, LabelType> EnergyRegularizationType;
 
-  MRFSamplerMAPType::Pointer object    = MRFSamplerMAPType::New();
-  ReaderInputType::Pointer   readerIn  = ReaderInputType::New();
-  ReaderLabelType::Pointer   readerLab = ReaderLabelType::New();
+
+  MRFSamplerMAPType::Pointer        object               = MRFSamplerMAPType::New();
+  EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
+  EnergyFidelityType::Pointer       energyFidelity       = EnergyFidelityType::New();
+  ReaderInputType::Pointer          readerIn             = ReaderInputType::New();
+  ReaderLabelType::Pointer          readerLab            = ReaderLabelType::New();
  
+  object->SetEnergyFidelity(energyFidelity);
+  object->SetEnergyRegularization(energyRegularization);
+
   readerIn->SetFileName( inputImage );
   readerLab->SetFileName( labelImage );
   readerIn->Update();
diff --git a/Testing/Code/Markov/otbMRFSamplerRandom.cxx b/Testing/Code/Markov/otbMRFSamplerRandom.cxx
index 25ff374eb2..46fcb51d2a 100644
--- a/Testing/Code/Markov/otbMRFSamplerRandom.cxx
+++ b/Testing/Code/Markov/otbMRFSamplerRandom.cxx
@@ -22,6 +22,7 @@
 #include "otbMRFSamplerRandom.h"
 #include "otbImageFileReader.h"
 #include "otbImage.h"
+#include "otbMRFEnergyPotts.h"
 #include <fstream>
 
 
@@ -41,19 +42,24 @@ int otbMRFSamplerRandom(int argc, char * argv[])
   typedef MRFSamplerRandomType::LabelledImageNeighborhoodIterator LabelledNeighborhoodIterator;
   typedef MRFSamplerRandomType::InputImageNeighborhoodIterator    InputNeighborhoodIterator;
 
+  typedef otb::MRFEnergyPotts <ImageType, LabelType>              EnergyFidelityType;
+  typedef otb::MRFEnergyPotts <LabelType, LabelType>              EnergyRegularizationType;
 
-  MRFSamplerRandomType::Pointer object    = MRFSamplerRandomType::New();
-  ReaderInputType::Pointer      readerIn  = ReaderInputType::New();
-  ReaderLabelType::Pointer      readerLab = ReaderLabelType::New();
+  MRFSamplerRandomType::Pointer     object               = MRFSamplerRandomType::New();
+  EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
+  EnergyFidelityType::Pointer       energyFidelity       = EnergyFidelityType::New();
+  ReaderInputType::Pointer          readerIn             = ReaderInputType::New();
+  ReaderLabelType::Pointer          readerLab            = ReaderLabelType::New();
  
+  object->SetEnergyFidelity(energyFidelity);
+  object->SetEnergyRegularization(energyRegularization);
+  object->InitializeSeed(0);// USED TO OVERPASS RANDOM CALCULATION
+
   readerIn->SetFileName( inputImage );
   readerLab->SetFileName( labelImage );
   readerIn->Update();
   readerLab->Update();
 
-  // USED TO OVERPASS RANDOM CALCULATION
-  // object->SetValueInsteadRandom(300); 
-
   ImageType::IndexType idIn;
   LabelType::IndexType idLab;
   idIn[0] = 50; 
diff --git a/Testing/Code/Markov/otbMRFSamplerRandomMAP.cxx b/Testing/Code/Markov/otbMRFSamplerRandomMAP.cxx
index f2c3cc1b5d..2eed948ceb 100644
--- a/Testing/Code/Markov/otbMRFSamplerRandomMAP.cxx
+++ b/Testing/Code/Markov/otbMRFSamplerRandomMAP.cxx
@@ -22,6 +22,8 @@
 #include "otbMRFSamplerRandomMAP.h"
 #include "otbImageFileReader.h"
 #include "otbImage.h"
+#include "otbMRFEnergyPotts.h"
+
 #include <fstream>
 
 
@@ -38,23 +40,30 @@ int otbMRFSamplerRandomMAP(int argc, char * argv[])
   typedef otb::ImageFileReader< ImageType >                          ReaderInputType;
   typedef otb::ImageFileReader< LabelType >                          ReaderLabelType;
   typedef otb::MRFSamplerRandomMAP< ImageType, LabelType>            MRFSamplerRandomMAPType;
+ 
+  typedef otb::MRFEnergyPotts <ImageType, LabelType>                 EnergyFidelityType;
+  typedef otb::MRFEnergyPotts <LabelType, LabelType>                 EnergyRegularizationType;
+
+
   typedef MRFSamplerRandomMAPType::LabelledImageNeighborhoodIterator LabelledNeighborhoodIterator;
   typedef MRFSamplerRandomMAPType::InputImageNeighborhoodIterator    InputNeighborhoodIterator;
 
+  MRFSamplerRandomMAPType::Pointer  object               = MRFSamplerRandomMAPType::New();
+  EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
+  EnergyFidelityType::Pointer       energyFidelity       = EnergyFidelityType::New();
+  ReaderInputType::Pointer          readerIn             = ReaderInputType::New();
+  ReaderLabelType::Pointer          readerLab            = ReaderLabelType::New();
+
 
-  MRFSamplerRandomMAPType::Pointer object    = MRFSamplerRandomMAPType::New();
-  ReaderInputType::Pointer         readerIn  = ReaderInputType::New();
-  ReaderLabelType::Pointer         readerLab = ReaderLabelType::New();
- 
   readerIn->SetFileName( inputImage );
   readerLab->SetFileName( labelImage );
   readerIn->Update();
   readerLab->Update();
 
   object->SetNumberOfClasses(1);
-
-  // USED TO OVERPASS RANDOM CALCULATION
-  //object->SetValueInsteadRandom(300); 
+  object->SetEnergyFidelity(energyFidelity);
+  object->SetEnergyRegularization(energyRegularization);
+  object->InitializeSeed(0);// USED TO OVERPASS RANDOM CALCULATION
 
   ImageType::IndexType idIn;
   LabelType::IndexType idLab;
diff --git a/Testing/Code/Markov/otbMarkovRandomFieldFilter.cxx b/Testing/Code/Markov/otbMarkovRandomFieldFilter.cxx
index 068311850d..fad4516431 100755
--- a/Testing/Code/Markov/otbMarkovRandomFieldFilter.cxx
+++ b/Testing/Code/Markov/otbMarkovRandomFieldFilter.cxx
@@ -40,12 +40,12 @@ int otbMarkovRandomFieldFilter(int argc, char* argv[] )
 {
   const unsigned int Dimension = 2;
   
-  typedef double InternalPixelType;
-  typedef unsigned char LabelledPixelType;
+  typedef double                                    InternalPixelType;
+  typedef unsigned char                             LabelledPixelType;
   typedef otb::Image<InternalPixelType, Dimension>  InputImageType;
-  typedef otb::Image<LabelledPixelType, Dimension>    LabelledImageType;
-  typedef otb::ImageFileReader< InputImageType >  ReaderType;
-  typedef otb::ImageFileWriter< LabelledImageType >  WriterType;
+  typedef otb::Image<LabelledPixelType, Dimension>  LabelledImageType;
+  typedef otb::ImageFileReader< InputImageType >    ReaderType;
+  typedef otb::ImageFileWriter< LabelledImageType > WriterType;
   
   ReaderType::Pointer reader = ReaderType::New();
   WriterType::Pointer writer = WriterType::New();
@@ -56,24 +56,18 @@ int otbMarkovRandomFieldFilter(int argc, char* argv[] )
   reader->SetFileName( inputFilename );
   writer->SetFileName( outputFilename );
 
-  typedef otb::MarkovRandomFieldFilter
-	  <InputImageType,LabelledImageType> MarkovRandomFieldFilterType;
-
-  typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType> SamplerType;
-
-  typedef otb::MRFOptimizerMetropolis OptimizerType;
-
-  typedef otb::MRFEnergyPotts
-		  <LabelledImageType, LabelledImageType>  EnergyRegularizationType;
-  typedef otb::MRFEnergyGaussianClassification
-		  <InputImageType, LabelledImageType>  EnergyFidelityType;
+  typedef otb::MarkovRandomFieldFilter<InputImageType,LabelledImageType>          MarkovRandomFieldFilterType;
+  typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType>               SamplerType;
+  typedef otb::MRFOptimizerMetropolis                                             OptimizerType;
+  typedef otb::MRFEnergyPotts<LabelledImageType, LabelledImageType>               EnergyRegularizationType;
+  typedef otb::MRFEnergyGaussianClassification<InputImageType, LabelledImageType> EnergyFidelityType;
 
  
-  MarkovRandomFieldFilterType::Pointer markovFilter = MarkovRandomFieldFilterType::New();
-  EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
-  EnergyFidelityType::Pointer energyFidelity = EnergyFidelityType::New();
-  OptimizerType::Pointer optimizer = OptimizerType::New();
-  SamplerType::Pointer sampler = SamplerType::New();
+  MarkovRandomFieldFilterType::Pointer markovFilter         = MarkovRandomFieldFilterType::New();
+  EnergyRegularizationType::Pointer    energyRegularization = EnergyRegularizationType::New();
+  EnergyFidelityType::Pointer          energyFidelity       = EnergyFidelityType::New();
+  OptimizerType::Pointer               optimizer            = OptimizerType::New();
+  SamplerType::Pointer                 sampler              = SamplerType::New();
 
  
   unsigned int nClass = 4;
@@ -90,16 +84,18 @@ int otbMarkovRandomFieldFilter(int argc, char* argv[] )
   parameters[7]=10.0; //Class 3 stde
   energyFidelity->SetParameters(parameters);
 
-  
-  optimizer->SetParameters(atoi(argv[5]));
+  optimizer->SetSingleParameter(atof(argv[5]));
+  markovFilter->InitializeSeed(0);
   markovFilter->SetNumberOfClasses(nClass);  
   markovFilter->SetMaximumNumberOfIterations(atoi(argv[4]));
   markovFilter->SetErrorTolerance(0.0);
   markovFilter->SetLambda(atof(argv[3]));
   markovFilter->SetNeighborhoodRadius(1);
   
-  markovFilter->SetEnergyRegularization(static_cast<MarkovRandomFieldFilterType::EnergyRegularizationPointer>(energyRegularization));
-  markovFilter->SetEnergyFidelity(static_cast<MarkovRandomFieldFilterType::EnergyFidelityPointer>(energyFidelity));
+  //markovFilter->SetEnergyRegularization(static_cast<MarkovRandomFieldFilterType::EnergyRegularizationPointer>(energyRegularization));
+  //markovFilter->SetEnergyFidelity(static_cast<MarkovRandomFieldFilterType::EnergyFidelityPointer>(energyFidelity));
+  markovFilter->SetEnergyRegularization(energyRegularization);
+  markovFilter->SetEnergyFidelity(energyFidelity);
   markovFilter->SetOptimizer(optimizer);
   markovFilter->SetSampler(sampler);
   
-- 
GitLab