// file: $isip_ifc/class/algo/CorrelationEntropy/CorrelationEntropy.h
// version: $Id: CorrelationEntropy.h 10554 2006-04-18 21:34:16Z prasad $
//

// make sure definitions are only made once
//
#ifndef ISIP_CORRELATION_ENTROPY
#define ISIP_CORRELATION_ENTROPY

// isip include files
//
#ifndef ISIP_ALGORITHM_BASE
#include <AlgorithmBase.h>
#endif

#ifndef ISIP_CORRELATION_INTEGRAL
#include <CorrelationIntegral.h>
#endif

#ifndef ISIP_RPS
#include <Rps.h>
#endif

// CorrelationEntropy: This class estimates the second order Kolmogorov entropy
// of an attractor's trajectory. Grassberger and Procaccia related the
// second order Kolmogorov entropy with the sensitivity of the correlation
// integral of an attractor's trajectory to the embedding dimension.
// The Correlation Integral as used by this algorithm is defined as:
//
//      C(epsilon,N) =     2         sum      sum  H( epsilon - ||Xi-Xj|| )
//                      --------    i<=N-w  w<j<=N
//                    (N-w)(N-w-1)
//
// where H is the Heaviside's unit step function, and, epsilon is the radius of
// the neighborhood. Xi and Xj represent the i'th and j'th points on the
// attractor's trajectory.|| || represents any valid vector norm.
// Here, a proper choice of 'w', the Theiler's window size, ensures that
// temporally correlated points are not included in estimating the correlation
// integral. A proper choice of 'w' is obtained using the space time
// separation plots of the attractor. The value of w chosen should be
// inversely proportional to the extent of autocorrelation possessed in
// the data.
//
// Hence, the CorrelationEntropy is defined as:
//
//    K(epsilon, d) =              1         C(epsilon,d)
//                     lim        ---  log  -------------
//                 epsilon ->0    tau       C(epsilon,d+1)
//
// Where tau is the time delay for embedding.
//
// An Important point to note here is that if available, time-delay embedding
// should be the preferred Phase Space Reconstruction tool for building the RPS
// because, the CorrelationEntropy utilizes the variations in the correlation
// integral with the embedding dimension at an optimal tau-separation
// (i.e., (d-1)tau ) SVD embedding uses a time delay of one sample, and hence
// may provide misleading results for Entropy.
//
// This class will take as input a time series, a value of epsilon and a range
// of embedding dimensions. The output of the class will be a vector containing
// the correlation entropy over the specified range of embedding dimensions.
//
// Refer to :
//
// Kantz and Schreiber, "Nonlinear Time Series Analysis", Cambridge, 2004.
//
// H.S. Kim, R. Eykholt, J.D. Salas, "Nonlinear dynamics, delay times, and
// embedding Windows", Physica D Letters, Elsevier, 1998.
//
// Yves Termonia, "Kolmogorov Entropy from a Time Series", Physica Review A,
// 1983

class CorrelationEntropy : public AlgorithmBase {

  //---------------------------------------------------------------------------
  //
  // public constants
  //
  //---------------------------------------------------------------------------
public:

  // define the class name
  //
  static const String CLASS_NAME;

  // define the signal type
  //
  enum ALGORITHM { NORMAL = 0, DEF_ALGORITHM = NORMAL };

  // define the implementation choices
  //
  enum IMPLEMENTATION { CORRELATION_INTEGRAL = 0,
			DEF_IMPLEMENTATION = CORRELATION_INTEGRAL };

  // define the embedding choices
  //
  enum EMBEDDING { TIME_DELAY = 0, SVD, 
			DEF_EMBEDDING = TIME_DELAY };

  // define static NameMap objects
  //
  static const NameMap ALGO_MAP;
  static const NameMap IMPL_MAP;
  static const NameMap EMBED_MAP;
  
  //----------------------------------------
  //
  // i/o related constants
  //
  //----------------------------------------  

  static const String DEF_PARAM;
  static const String PARAM_ALGORITHM;
  static const String PARAM_IMPLEMENTATION;
  static const String PARAM_EMBEDDING;
  static const String PARAM_CMODE;
  static const String PARAM_EPSILON;
  static const String PARAM_EMBED_DIM_MIN;
  static const String PARAM_EMBED_DIM_MAX;
  static const String PARAM_THEILER_CORRECTION;
  static const String PARAM_DELAY;
  static const String PARAM_SVD_WINDOW_SIZE;
  
  //----------------------------------------
  //
  // default values and arguments
  //
  //----------------------------------------  

  // define the default value(s) of the class data
  //
  static const float DEF_EPSILON = 1 ;
  static const long DEF_EMBED_DIM_MIN = 3; 
  static const long DEF_EMBED_DIM_MAX = 5;
  static const long DEF_THEILER_CORRECTION = 5;
  static const float DEF_DELAY = -1.0;
  static const long DEF_SVD_WINDOW_SIZE = -1;  

  // define default argument(s)
  //
  static const AlgorithmData::COEF_TYPE DEF_COEF_TYPE = AlgorithmData::SIGNAL; 
  
  //----------------------------------------
  //
  // error codes 
  //
  //----------------------------------------  

  static const long ERR = 73800;
  static const long ERR_UNKALG = 73801;
  static const long ERR_UNCTYP = 73802;
  static const long ERR_EPS = 73803;
  static const long ERR_DIM = 73804;

  //---------------------------------------------------------------------------
  //
  // protected data
  //
  //---------------------------------------------------------------------------
protected:

  // algorithm name
  //
  ALGORITHM algorithm_d;
  
  // implementation type
  //
  IMPLEMENTATION implementation_d;

  // Embedding type
  EMBEDDING embedding_d;

  // parameters related to the algorithm specification
  //
  Float epsilon_d;           // Radius of the neighborhood for correlation sum
  Long embed_dim_min_d;      // Minimum Embedding Dimension
  Long embed_dim_max_d;      // Maximum Embedding Dimension
  Long theiler_correction_d; // Theiler's correction for correlation sum
  Long svd_window_size_d;    // SVD window size
  Float delay_d;             // delay (tau) for embedding in sec
    
  // a static memory manager
  //
  static MemoryManager mgr_d;
  
  //---------------------------------------------------------------------------
  //
  // required public methods
  //
  //---------------------------------------------------------------------------
public:
    
  // method: name
  //
  static const String& name() {
    return CLASS_NAME;
  }

  // other static methods
  //
  static boolean diagnose(Integral::DEBUG debug_level);
  
  // debug methods:
  //  setDebug is inherited from the AlgorithmBase class
  //
  boolean debug(const unichar* msg) const;
  
  // method: destructor
  //
  ~CorrelationEntropy() {}

  // method: default constructor
  //
  CorrelationEntropy(ALGORITHM algorithm = DEF_ALGORITHM,
		     IMPLEMENTATION implementation = DEF_IMPLEMENTATION,
		     EMBEDDING embedding = DEF_EMBEDDING,
		     float epsilon = DEF_EPSILON,
		     long embed_dim_min = DEF_EMBED_DIM_MIN,
		     long embed_dim_max = DEF_EMBED_DIM_MAX,
		     long theiler_correction = DEF_THEILER_CORRECTION,
		     long svd_window_size = DEF_SVD_WINDOW_SIZE,
		     float delay = DEF_DELAY) {
    
    // initialize protected data
    //
    algorithm_d = algorithm;
    implementation_d = implementation;
    embedding_d = embedding;
    epsilon_d = epsilon;
    embed_dim_min_d = embed_dim_min;
    embed_dim_max_d = embed_dim_max;
    theiler_correction_d = theiler_correction;
    svd_window_size_d = svd_window_size;
    delay_d = delay;
    is_valid_d = false;
  }

  // assign methods:
  //
   boolean assign(const CorrelationEntropy& arg) {
    algorithm_d = arg.algorithm_d;
    implementation_d = arg.implementation_d;
    embedding_d = arg.embedding_d;
    epsilon_d = arg.epsilon_d;
    embed_dim_min_d = arg.embed_dim_min_d;
    embed_dim_max_d = arg.embed_dim_max_d;
    theiler_correction_d = arg.theiler_correction_d;
    svd_window_size_d = arg.svd_window_size_d;
    delay_d = arg.delay_d;
    return AlgorithmBase::assign(arg);
  }

  // method: copy constructor
  //
  CorrelationEntropy(const CorrelationEntropy& arg) {
    assign(arg);
  }
  
  // method: operator=
  //
  CorrelationEntropy& operator= (const CorrelationEntropy& arg) {
    assign(arg);
    return *this;
  }
  
  // i/o methods:
  //
  long sofSize() const;
  
  boolean read(Sof& sof, long tag, const String& name = CLASS_NAME);

  boolean write(Sof& sof, long tag, const String& name = CLASS_NAME) const;
  
  boolean readData(Sof& sof, const String& pname = DEF_PARAM,
                   long size = SofParser::FULL_OBJECT,
                   boolean param = true,
                   boolean nested = false);
  
  boolean writeData(Sof& sof, const String& pname = DEF_PARAM) const;

  // method: eq
  //
  boolean eq(const CorrelationEntropy& arg) const {
    return ((algorithm_d == arg.algorithm_d) &&
	    (implementation_d == arg.implementation_d) &&
	    (embedding_d == arg.embedding_d) &&
	    (epsilon_d == arg.epsilon_d) &&
	    (embed_dim_min_d == arg.embed_dim_min_d) &&
	    (embed_dim_max_d == arg.embed_dim_max_d) &&
	    (theiler_correction_d == arg.theiler_correction_d) &&
	    (svd_window_size_d == arg.svd_window_size_d) &&
	    (delay_d == arg.delay_d));    
  }
  
  // method: new
  //
  static void* operator new(size_t size) {
    return mgr_d.get();
  }

  // method: new[]
  //
  static void* operator new[](size_t size) {
    return mgr_d.getBlock(size);
  }

  // method: delete
  //
  static void operator delete(void* ptr) {
    mgr_d.release(ptr);
  }

  // method: delete[]
  //
  static void operator delete[](void* ptr) {
    mgr_d.releaseBlock(ptr);
  }

  // method: setGrowSize
  //
  static boolean setGrowSize(long grow_size) {
    return mgr_d.setGrow(grow_size);
  }

  // other memory management methods
  //
  boolean clear(Integral::CMODE ctype = Integral::DEF_CMODE);
 
  //---------------------------------------------------------------------------
  //
  // class-specific public methods:
  //  set methods
  //
  //---------------------------------------------------------------------------
public:

  // method: setAlgorithm
  //
  boolean setAlgorithm(ALGORITHM algorithm) {
    algorithm_d = algorithm;
    is_valid_d = false;
    return true;
  }
  
  // method: setImplementation
  //
  boolean setImplementation(IMPLEMENTATION implementation) {
    implementation_d = implementation;
    is_valid_d = false;
    return true;  
  }

  // method: setEmbedding
  //
  boolean setEmbedding(EMBEDDING embedding) {
    embedding_d = embedding;
    is_valid_d = false;
    return true;  
  }

  // method: set
  //
  boolean set(ALGORITHM algorithm = DEF_ALGORITHM,
	      IMPLEMENTATION implementation = DEF_IMPLEMENTATION,
	      EMBEDDING embedding = DEF_EMBEDDING,
	      float epsilon = DEF_EPSILON,
	      long embed_dim_min = DEF_EMBED_DIM_MIN,
	      long embed_dim_max = DEF_EMBED_DIM_MAX,
	      long theiler_correction = DEF_THEILER_CORRECTION,
	      long svd_window_size = DEF_SVD_WINDOW_SIZE,
	      float delay = DEF_DELAY) {
    
    algorithm_d = algorithm;
    implementation_d = implementation;
    embedding_d = embedding;
    epsilon_d = epsilon; 
    embed_dim_min_d = embed_dim_min; 
    embed_dim_max_d = embed_dim_max; 
    theiler_correction_d =  theiler_correction;
    svd_window_size_d = svd_window_size;
    delay_d = delay;
    is_valid_d = false;
    return true;
  }

  // method: setEpsilon
  //
  boolean setEpsilon(float epsilon) {
    epsilon_d = epsilon;      
    is_valid_d = false;
    return true;
  }

  // method: setEmbedDimMin
  //
  boolean setEmbedDimMin(long embed_dim_min) {
    embed_dim_min_d = embed_dim_min;      
    is_valid_d = false;
    return true;
  }

  // method: setEmbedDimMax
  //
  boolean setEmbedDimMax(long embed_dim_max) {
    embed_dim_max_d = embed_dim_max;      
    is_valid_d = false;
    return true;
  }

  // method: setTheilerCorrection
  //
  boolean setTheilerCorrection(long theiler_correction) {
    theiler_correction_d =  theiler_correction;
    is_valid_d = false;
    return true;
  }
  
  // method: setSVDWindowSize
  //
  boolean setSVDWindowSize(long svd_window_size) {
    svd_window_size_d = svd_window_size;
    is_valid_d = false;
    return true;  
  }

  // method: setDelay
  //
  boolean setDelay(float delay ) {
    delay_d = delay;
    is_valid_d = false;
    return true;  
  }

  //---------------------------------------------------------------------------
  //
  // class-specific public methods
  //  get methods
  //
  //---------------------------------------------------------------------------

  // method: getAlgorithm
  //
  ALGORITHM getAlgorithm() const {
    return algorithm_d;
  }
  
  // method: getImplementation
  //
  IMPLEMENTATION getImplementation() const {
    return implementation_d;
  }

  // method: getEmbedding
  //
  EMBEDDING getEmbedding() const {
    return embedding_d;
  }

  // method: get
  //
  boolean get(ALGORITHM& algorithm,
	      IMPLEMENTATION& implementation,
	      EMBEDDING& embedding) {
    algorithm = algorithm_d;
    implementation = implementation_d;
    embedding = embedding_d;
    return true;
  }

  // method: getEpsilon
  //
  float getEpsilon() const {
    return epsilon_d;
  }

  // method: getEmbedDimMin
  //
  long getEmbedDimMin() const {
    return embed_dim_min_d;
  }

  // method: getEmbedDimMax
  //
  long getEmbedDimMax() const {
    return embed_dim_max_d;
  }

  // method: getTheilerCorrection
  //
  long getTheilerCorrection() const {
    return theiler_correction_d;
  }

  // method: getSVDWindowSize
  //
  long getSVDWindowSize() const {
    return svd_window_size_d;
  }

  // method: getDelay
  //
  float getDelay() const {
    return delay_d;
  }
  
  //---------------------------------------------------------------------------
  //
  // class-specific public methods:
  //  computational methods
  //
  //---------------------------------------------------------------------------

  // compute method when input is given as a matrix
  //
  boolean compute(VectorFloat& output, const VectorFloat& input,
		  AlgorithmData::COEF_TYPE coef_type = DEF_COEF_TYPE,
		  long channel_index = DEF_CHANNEL_INDEX);
 
  //---------------------------------------------------------------------------
  //
  // class-specific public methods:
  //  public methods required by the AlgorithmBase interface contract
  //
  //---------------------------------------------------------------------------

  // assign method
  //
  boolean assign(const AlgorithmBase& arg);

  // equality method
  //
  boolean eq(const AlgorithmBase& arg) const;

  // method: className
  //
  const String& className() const {
    return CLASS_NAME;
  }

  // no initialization method is needed since none of the
  // algorithms currently supported require a history

  // initialization method
  //
  //boolean init();
  
  // apply method
  //
  boolean apply(Vector<AlgorithmData>& output,
		const Vector< CircularBuffer<AlgorithmData> >& input);

  // method to get the parser
  //
  boolean setParser(SofParser* parser);

  //---------------------------------------------------------------------------
  //
  // private methods
  //
  //---------------------------------------------------------------------------
private:

  // common i/o methods
  //
  boolean readDataCommon(Sof& sof, const String& pname,
			 long size = SofParser::FULL_OBJECT,
			 boolean param = true, boolean nested = false);
  boolean writeDataCommon(Sof& sof, const String& pname) const;

  // algorithm-specific computation methods: Corrint
  //
  boolean computeCorrelationEntropy(VectorFloat& entropy,
				     const VectorFloat& input);

};

// end of include file
//
#endif
