/*
  File name: pac.c
  Created by: Ljubomir Buturovic
  Created: 07/29/2004
  Purpose: parametric classifiers menus (linear and quadratic).
*/

/*
  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.
*/

static char rcsid[] = "$Id: pac.c,v 1.25 2005/05/05 05:00:46 ljubomir Exp $";

#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include "pcp.h"
#include "bagging.h"
#include "pau.h"
#include "lau.h"
#include "lmat.h"
#include "parametric.h"
#include "lerr.h"

/*
  Collect input parameters from the user, call the parametric linear
  classifier function lin_learn() on TDS, save the classifier and
  display results of TDS classification.

  In case of error, return error code and, in case of file error,
  store the offending file name in 'xname'.
*/
int p_lin_learn(char **xname)
{
  int   errc;
  char  *fname;
  float **wmx;

  errc = 0;
  if (tds)
    {
      clear_screen();
      cursor_on();
      fname = input_filename(CLASSIFIER_MSG, PCP_PLC, stdout);
      if (fname)
	{
	  wmx = lin_learn(WEIGHTED_COV, tds, &errc);
	  if (wmx)
	    {
	      errc = fmx_save(wmx, tds->c, tds->d+1, fname, 0);
	      if (errc == -1)
		{
		  errc = errno;
		  *xname = strdup(fname);
		}
	      else
		{
		  /*
		    Run predict on tds, and display results.
		  */
		  errc = dataset_lin_predict(tds, wmx);
		  if (!errc)
		    {
		      predict_disp(tds, 0, PALG_PLC);
		      pwait();
		    }
		}
	    }
	  free(fname);
	}
    }
  else
    errc = PERR_UNDEFINED_TDS;
  return errc;
}

/*
  Collect input parameters from the user, call the parametric
  quadratic classifier learning function pqc_learn() on TDS, save the
  classifier and display results of TDS classification.

  In case of error, return error code and, in case of file error,
  store the offending file name in 'xname'.
*/
int p_pqc_learn(char **xname)
{
  int    errc;
  char   *fname;
  struct qmodel *qcx;

  errc = 0;
  if (tds)
    {
      clear_screen();
      cursor_on();
      fname = input_filename(CLASSIFIER_MSG, PCP_PQC, stdout);
      if (fname)
	{
	  qcx = pqc_learn(tds, &errc);
	  if (qcx)
	    {
	      errc = pqc_save(qcx, tds->d, tds->c, fname);
	      if (errc == -1)
		{
		  *xname = strdup(fname);
		  errc = errno;
		}
	      else
		{
		  /*
		    Run prediction on tds, and display results.
		  */
		  errc = dataset_pqc_predict(tds, qcx->wmx, qcx->sigma);
		  if (!errc)
		    {
		      predict_disp(tds, 0, PALG_PQC);
		      pwait();
		    }
		}
	    }
	  free(fname);
	}
    }
  else
    errc = PERR_UNDEFINED_TDS;
  return errc;
}

/*
  Classify test data set using parametric quadratic classifier stored
  in a file. The function obtains input parameters from the user,
  calls dataset_pqc_predict(), and displays classification results.
  
  In case of success, return 0. In case of failure, return error
  code. In case of file access error, return the relevant file name in
  'xname'.
*/
int p_pqc_predict(char **xname)
{
  int   i;
  int   j;
  int   errc;
  int   verbose;
  int   min_range;
  int   max_range;
  int   predicted_class;
  int   icx;
  int   nmodels;
  int   type;
  int   rows;
  int   columns;
  float *predictions;
  char  *fname;
  char  *output_fname;
  char  *tname;
  char  *name;
  float *weights;
  struct qmodel *model;
  struct qmodel **models;
  FILE  *outdev;
  FILE  *fptr;
  FILE  *output_fptr;

  clear_screen();
  outdev = stdout;
  cursor_on();
  fname = input_filename(PCP_UMSG_PAC_FNAME, PCP_PQC, outdev);
  fptr = fopen(fname, "r");
  if (fptr)
    {
      fclose(fptr);
      output_fname = strdup(PCP_RCL);
      output_fptr = fopen(output_fname, "w");
      if (output_fptr)
	{
	  models = pqc_load_models(fname, &type, &nmodels, &weights, &rows, &columns, &errc);
	  if (models)
	    {
	      /*
		Check consistency between the models and test data set.
	      */
	      if (((teds->c > 1) && (teds->c != rows)) || (teds->d+1 != columns))
		errc = LERR_INCONSISTENT_MODEL;
	      else
		{
		  predictions = calloc(teds->c, sizeof(float));
		  teds->prediction = malloc(teds->nv*sizeof(int));
		  for (i = 0; i < teds->nv; i++)
		    {
		      fvec_set(predictions, teds->c, 0.0);
		      for (j = 0; j < nmodels; j++)
			{
			  model = models[j];
			  predicted_class = pqc_predict(model, teds->c, teds->d+1, teds->x[i]);
			  predictions[predicted_class] += weights[j];
			}
		      predicted_class = fvec_argmax(predictions, teds->c);
		      teds->prediction[i] = predicted_class;
		      name = bname(teds->fnames[predicted_class]);
		      icx = dataset_class(i, teds->c, teds->nd);
		      tname = bname(teds->fnames[icx]);
		      fprintf(output_fptr, "%d\t%s\t%s\n", i+1, tname, name);
		    }
		  free(predictions);
		  free(models);
		  fclose(output_fptr);
		  min_range = 0;
		  max_range = 1;
		  verbose = input_integer(stdin, outdev, OUTPUT_MSG, PCP_QLEN, 
					  &min_range, &min_range, &max_range);
		  /*
		    Display results.
		  */
		  predict_disp(teds, verbose, PALG_PQC);
		  pwait();
		}
	    }
	  else
	    {
	      /*
		This is an interesting case: pqc_load_models() could
		not load the models, and yet there was no error (for
		example, file not found, or malloc() error)
		detected. This can happen if the file is empty, for
		example. We set LERR_INCONSISTENT_MODEL error.
	       */
	      if (!errc)
		errc = LERR_INCONSISTENT_MODEL;
	      *xname = fname;
	      fclose(output_fptr);
	      unlink(output_fname);
	    }
	}
      else
	{
	  errc = errno;
	  *xname = output_fname;
	}
    }
  else
    {
      errc = errno;
      *xname = fname;
    }
  reset_video();
  return errc;
}




syntax highlighted by Code2HTML, v. 0.9.1