/*
  File name: cda.c
  Created by: Ljubomir Buturovic
  Created: 02/12/2003
  Purpose: principal components analysis and Fisher's linear
  discriminant.
*/

/*
  Copyright 2004 Ljubomir J. Buturovic

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "lerr.h"
#include "cda.h"
#include "pcp.h"
#include "pau.h"
#include "lau.h"
#include "lmat.h"

static char rcsid[] = "$Id: cda.c,v 1.23 2005/02/11 19:35:54 ljubomir Exp $";

/*
  Calculate principal components transformation matrix on 'dset'.
  
  Return -1 in case of error and set 'errc'. Errors are malloc()
  errors and LERR_ITMAX in eigen().
*/
float **pca(struct dataset *dset, int *errc)
{
  int   i;
  int   j;
  int   nv;
  int   status;
  float **sigma;
  float **pcamx;

  pcamx = (float **) 0;
  /*
    Calculate Sw matrix, which is the overall covariance matrix
    estimate times (nv-1).
  */
  sigma = cest(dset->x, dset->d, dset->nv, COVARIANCE_MATRIX);
  nv = dset->nv;
  for (i = 0; i < dset->d; i++)
    for (j = 0; j < dset->d; j++)
      sigma[i][j] = (nv-1)*sigma[i][j];
  /*
    Peform eigenanalysis.
  */
  status = eigsn(sigma, dset->d, (float **) 0, &pcamx, errc);
  mx_free((void **) sigma, dset->d);
  if (status == -1)
    pcamx = (float **) 0;
  return pcamx;
}

/*
  Calculate Fisher's linear discriminant (transformation matrix) on
  'dset'.
  
  Return -1 in case of error and set 'errc'. Errors are malloc()
  errors and LERR_ITMAX in eigen().
*/
float **fld(struct dataset *dset, int *errc)
{
  int   i;
  int   j;
  int   m;
  int   d;
  int   status;
  int   offset;
  int   nv;
  float dsign;
  float dexp;
  float *mean; /* data set mean */
  float *diff;
  float **xmean; /* class means */
  float **sigma;
  float **sw; /* scatter matrix */
  float **swi; /* inverse of scatter matrix */
  float **sb;  /* general between-class scatter matrix */
  float **mx;  /* inv(Sw)*Sb */
  float **tmx; /* the transformation matrix */
  
  float *evl; /* TESTING */
  /*
    Calculate Sw.
  */
  status = 0;
  tmx = (float **) 0;
  d = dset->d;
  evl = malloc(d*sizeof(float)); /* TESTING */
  mean  = mest(dset->x, d, dset->nv);
  xmean = malloc(dset->c*sizeof(float *));
  offset = 0;
  for (i = 0; i < dset->c; i++)
    {
      xmean[i] = mest(&dset->x[offset], d, dset->nd[i]);
      offset += dset->nd[i];
    }
  sw = fmx_alloc(d, d);
  if (sw)
    {
      fmx_set(sw, d, d, 0.0);
      offset = 0;
      for (m = 0; (m < dset->c) && !status; m++)
	{
	  sigma = cest(&dset->x[offset], d, dset->nd[m], COVARIANCE_MATRIX);
	  if (sigma)
	    {
	      nv = dset->nd[m]-1;
	      for (i = 0; i < d; i++)
		for (j = 0; j < d; j++)
		  sw[i][j] += nv*sigma[i][j];
	      mx_free((void **) sigma, d);
	      offset += dset->nd[m];
	    }
	  else
	    status = -1;
	}
      if (!status)
	{
	  /*
	    Invert Sw.
	  */
	  swi = fmx_inv(sw, d, &dsign, &dexp, errc);
	  mx_free((void **) sw, d);
	  if (!(*errc))
	    {
	      diff = malloc(d*sizeof(float));
	      if (diff)
		{
		  /*
		    Calculate Sb.
		  */
		  sb = fmx_alloc(d, d);
		  if (sb)
		    {
		      fmx_set(sb, d, d, 0.0);
		      for (m = 0; m < dset->c; m++)
			{
			  nv = dset->nd[m];
			  for (j = 0; j < d; j++)
			    diff[j] = xmean[m][j]-mean[j];
			  for (i = 0; i < d; i++)
			    for (j = 0; j < d; j++)
			      sb[i][j] += nv*diff[i]*diff[j];
			}
		      /*
			Multiply inv(Sw)*Sb.
		      */
		      mx = fmx_mult(swi, d, d, sb, d, 0);
		      /*
			Calculate eigenvectors of the product.
		      */
		      status = eigen(mx, d, &evl, &tmx, errc);
		      if (status == -1)
			tmx = (float **) mx_free((void **) tmx, d);
		      mx_free((void **) sb, d);
		      mx_free((void **) mx, d);
		    }
		  vx_free(diff);
		}
	    }
	  mx_free((void **) swi, d);
	}
    }
  vx_free(mean);
  mx_free((void **) xmean, dset->c);
  return tmx;
}

/*
  Collect user input and call Principal Component Analysis linear
  feature extractor pca() (type == PDR_PCA) or calculate Fisher's
  linear discriminant(s) (type == PDR_FISHER), using the training data
  set.
*/
void p_cda(int type, int *errc, char **xname)
{
  int   status;
  int   itd;
  int   max_value;
  int   default_value;
  char  *fname;
  float **tmx;

  max_value = -1;
  default_value = -1;
  tmx = (float **) 0;
  if (tds)
    {
      /*
	This transformation is only defined if dimension is less than
	the number of vectors.
      */
      if (tds->d >= tds->nv)
	{
	  status = -1;
	  *errc = PERR_INCONSISTENT_FE;
	}
      else
	{
	  clear_screen();
	  inverse_video();
	  cursor_on();
	  if (type == PDR_PCA)
	    {
	      default_value = 2;
	      max_value = tds->d;
	    }
	  else if (type == PDR_FISHER)
	    {
	      if (tds->c-1 < tds->d)
		default_value = tds->c-1;
	      else
		default_value = tds->d;
	      max_value = default_value;
	    }
	  itd = input_d(stdin, stdout, max_value, default_value);
	  fname = input_filename(PMSG_LIN_OUTPUT_FNAME, PCP_LIN, stdout);
	  cursor_off();
	  print_line(stdout, PCA_MSG, PCP_QLEN);
	  reset_video();
	  if (type == PDR_PCA)
	    tmx = pca(tds, errc);
	  else if (type == PDR_FISHER)
	    tmx = fld(tds, errc);
	  if (tmx)
	    {
	      status = fmx_save(tmx, itd, tds->d, fname, 0);
	      mx_free((void **) tmx, tds->d);
	      if (status == -1)
		{
		  *errc = errno;
		  *xname = strdup(fname);
		}
	    }
	  else
	    status = -1;
	}
    }
  else
    *errc = PERR_UNDEFINED_TDS;
}


syntax highlighted by Code2HTML, v. 0.9.1