// file: $isip_ifc/class/algo/CorrelationIntegral/CorrelationIntegral.h
// version: $Id: CorrelationIntegral.h 10636 2007-01-26 22:18:09Z tm334 $
//

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

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

// CorrelationIntegral: This class estimates the correlation integral of
// of an attractor's trajectory. This is used in estimating the correlation
// dimension of the underlying attractor, the Kolmogorov entropy, the noise
// level in a time series etc.
// A numerical estimate of this quantity is defined by:
//                         
//      C(epsilon,N) =   2       sum   H( epsilon - ||Xi-Xj|| )
//                      ---   i<=j<= N
//                     N(N-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.
// In a modified form (Theiler), the integral is approximated as:
//
//      C(epsilon,N) =     2         sum      sum  H( epsilon - ||Xi-Xj|| )
//                      --------    i<=N-w  w<j<=N
//                    (N-w)(N-w-1)
//
// where a proper choice of 'w', the Theiler's window size, ensures that
// temporally correlated points are not included in estimating the correlation
// integral. A propoer 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.
//
// Spacing mode specifies the preferred spacing of the epsilon values, used
// for estimating Correlation Integral. For LINEAR_EPSILON_SPACING, the user
// provided minimum and maximum values of epsilon is broken into an appropriate
// number of regions, specified by epsilon resolution.
//
// For USER_SPECIFIED_EPSILON_SPACING, the user provides an actual vector of
// epsilons instead of a range of epsilons. In this mode, the user needs to set
// the vector of epsilon values.
//
// Note that this is different from the SCALING type, which specifies the scale
// (e.g., Linear, Logarithmic etc.) of correlation integral being output. 
//
// 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.

class CorrelationIntegral : 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 type (this is a dummy implementation)
  //
  enum IMPLEMENTATION { REGULAR = 0, DEF_IMPLEMENTATION = REGULAR };

  // define the input spacing choices 
  //
  enum SPACING_MODE { LINEAR_EPSILON_SPACING = 0,
		      USER_SPECIFIED_EPSILON_SPACING, 
		      DEF_SPACING_MODE = LINEAR_EPSILON_SPACING };
  
  // define scaling choices for output:
  //
  enum SCALING { LOGSCALE = 0, LINSCALE, LOG2SCALE, LOG10SCALE,
		      DEF_SCALING = LOGSCALE }; 
   
  // define static NameMap objects
  //
  static const NameMap ALGO_MAP;
  static const NameMap IMPL_MAP;
  static const NameMap SPAC_MAP;
  static const NameMap SCAL_MAP;
  
  //----------------------------------------
  //
  // i/o related constants
  //
  //----------------------------------------  

  static const String DEF_PARAM;
  static const String PARAM_ALGORITHM;
  static const String PARAM_IMPLEMENTATION;
  static const String PARAM_SPACING_MODE;
  static const String PARAM_SCALING;
  static const String PARAM_EPSILON_MIN;
  static const String PARAM_EPSILON_MAX;
  static const String PARAM_EPSILON_RES;
  static const String PARAM_EPSILON;
  static const String PARAM_THEILER_CORRECTION;

  //----------------------------------------
  //
  // default values and arguments
  //
  //----------------------------------------  

  // define the default value(s) of the class data
  //
  static const float DEF_EPSILON_MIN = 1 ;
  static const float DEF_EPSILON_MAX = 10; 
  static const long DEF_EPSILON_RES = 10;
  static const long DEF_THEILER_CORRECTION = 5;

  // define the default value for negative infinity
  // as resulting from log(zero)
  //
  static const float DEF_NEG_INF = (-105.00);
  
  

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

  static const long ERR = 73600;
  static const long ERR_UNKALG = 73601;
  static const long ERR_UNCTYP = 73602;
  static const long ERR_EPSMIN = 73603;
  static const long ERR_EPSMAX = 73604;
  static const long ERR_EPSRES = 73605;
  static const long ERR_EPS = 73606;
  static const long ERR_SETEPS = 73607;

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

  // algorithm name
  //
  ALGORITHM algorithm_d;

  // dummy implementation name
  // there is no implementation methods in the CorrelationIntegral class,
  // this dummy name is provided to maintain the consistency
  // across all the algorithm classes
  //
  IMPLEMENTATION implementation_d;

  // Spacing type
  SPACING_MODE spacing_mode_d;

  // Scaling type
  SCALING scaling_d;

  // parameters related to the algorithm specification
  //
  Float epsilon_min_d;        // Radius of the neighborhood for correlation sum
  Float epsilon_max_d;        // Radius of the neighborhood for correlation sum
  Long epsilon_res_d;        // Resolution for the region min-to-max
  Long theiler_correction_d; // Theiler's correction for correlation sum
  VectorFloat epsilon_d;     // An entire range of epsilons
  
  // 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
  //
  ~CorrelationIntegral() {}

  // method: default constructor
  //
  CorrelationIntegral(ALGORITHM algorithm = DEF_ALGORITHM,
		      IMPLEMENTATION implementation = DEF_IMPLEMENTATION,
		      SCALING scaling = DEF_SCALING,
		      SPACING_MODE spacing_mode = DEF_SPACING_MODE,
		      float epsilon_min = DEF_EPSILON_MIN,
		      float epsilon_max = DEF_EPSILON_MAX,
		      long epsilon_res = DEF_EPSILON_RES,
		      long theiler_correction = DEF_THEILER_CORRECTION) {		     
    // initialize protected data
    //
    algorithm_d = algorithm;
    implementation_d = implementation;    
    scaling_d = scaling;
    spacing_mode_d = spacing_mode;
    epsilon_min_d = epsilon_min;
    epsilon_max_d = epsilon_max;
    epsilon_res_d = epsilon_res;
    theiler_correction_d = theiler_correction;
    is_valid_d = false;
  }

  // assign methods:
  //
   boolean assign(const CorrelationIntegral& arg) {
    algorithm_d = arg.algorithm_d;
    implementation_d = arg.implementation_d;
    scaling_d = arg.scaling_d;
    spacing_mode_d = arg.spacing_mode_d;	
    epsilon_min_d = arg.epsilon_min_d;
    epsilon_max_d = arg.epsilon_max_d;
    epsilon_res_d = arg.epsilon_res_d;
    epsilon_d = arg.epsilon_d;
    theiler_correction_d = arg.theiler_correction_d;
    return AlgorithmBase::assign(arg);
  }

  // method: copy constructor
  //
  CorrelationIntegral(const CorrelationIntegral& arg) {
    assign(arg);
  }
  
  // method: operator=
  //
  CorrelationIntegral& operator= (const CorrelationIntegral& 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 CorrelationIntegral& arg) const {
    return ((algorithm_d == arg.algorithm_d) &&
	    (implementation_d == arg.implementation_d) &&
	    (scaling_d == arg.scaling_d) &&
	    (spacing_mode_d == arg.spacing_mode_d) &&	    
	    (epsilon_min_d == arg.epsilon_min_d) &&
	    (epsilon_max_d == arg.epsilon_max_d) &&
	    (epsilon_res_d == arg.epsilon_res_d) &&
	    (epsilon_d.almostEqual(arg.epsilon_d)) &&
	    (theiler_correction_d == arg.theiler_correction_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: SetScaling
  //
  boolean setScaling(SCALING scaling) {
    scaling_d = scaling;
    is_valid_d = false;
    return true;  
  }

  // method: SetSpacingMode
  //
  boolean setSpacingMode(SPACING_MODE spacing_mode) {
    spacing_mode_d = spacing_mode;
    is_valid_d = false;
    return true;  
  }
  
  // method: set
  //
  boolean set(ALGORITHM algorithm = DEF_ALGORITHM,
	      IMPLEMENTATION implementation = DEF_IMPLEMENTATION,
	      SCALING scaling = DEF_SCALING,
	      SPACING_MODE spacing_mode = DEF_SPACING_MODE) {
    
    algorithm_d = algorithm;
    implementation_d = implementation;
    scaling_d = scaling;
    spacing_mode_d = spacing_mode;
    is_valid_d = false;
    return true;
  }

  // method: setEpsilon
  //
  boolean setEpsilon(float epsilon_min, float epsilon_max,
		     long epsilon_res);

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

  // method: setEpsilonMin
  //
  boolean setEpsilonMin(float epsilon_min) {
    epsilon_min_d = epsilon_min;
    is_valid_d = false;
    return true;
  }

  // method: setEpsilonMax
  //
  boolean setEpsilonMax(float epsilon_max) {
    epsilon_max_d = epsilon_max;
    is_valid_d = false;
    return true;
  }

  // method: setEpsilonRes
  //
  boolean setEpsilonRes(long epsilon_res) {
    epsilon_res_d = epsilon_res;
    is_valid_d = false;
    return true;
  }
  		     
  // method: setTheilerCorrection
  //
  boolean setTheilerCorrection(long theiler_correction) {
    theiler_correction_d =  theiler_correction;
    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: getScaling
  //
  SCALING getScaling() const {
    return scaling_d;
  }

  // method: getSpacingMode
  //
  SPACING_MODE getSpacingMode() const {
    return spacing_mode_d;
  }
  
  // method: get
  //
  boolean get(ALGORITHM& algorithm,
	      IMPLEMENTATION& implementation) {
    algorithm = algorithm_d;
    implementation = implementation_d;
    return true;
  }

  // method: getEpsilonMin
  //
  float getEpsilonMin() const {
    return epsilon_min_d;
  }

  // method: getEpsilonMax
  //
  float getEpsilonMax() const {
    return epsilon_max_d;
  }

  // method: getEpsilonRes
  //
  long getEpsilonRes() const {
    return epsilon_res_d;
  }

  // method: getEpsilon
  //
  boolean getEpsilon(VectorFloat& epsilon) const {
    epsilon = epsilon_d;
    return true;
  }

  // method: getTheilerCorrection
  //
  long getTheilerCorrection() const {
    return theiler_correction_d;
  }
  
  //---------------------------------------------------------------------------
  //
  // class-specific public methods:
  //  computational methods
  //
  //---------------------------------------------------------------------------

  // compute method when input is given as a matrix
  //
  boolean compute(VectorFloat& output, const MatrixFloat& 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
  //
  //---------------------------------------------------------------------------

  // 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;

  //---------------------------------------------------------------------------
  //
  // protected methods
  //
  //---------------------------------------------------------------------------
protected:
  // algorithm-specific computation methods: Corrint
  //
  boolean computeCorrelationIntegral(VectorFloat& correlationintegral,
				     const MatrixFloat& input);

};

// end of include file
//
#endif
