/** 
* @file KernelLinearCombination.cpp
* @brief Interface for the popular exponential mercer kernels
* @author Erik Rodner
* @date 10/24/2007

*/
#include <iostream>

#include <math.h>
#include "KernelLinearCombination.h"

using namespace OBJREC;

using namespace std;
using namespace NICE;



KernelLinearCombination::KernelLinearCombination( uint num, bool _exponential )
	: alpha ( num ), exponential(_exponential)
{
	for ( uint i = 0 ; i < num ; i++ )
		alpha[i] = - log((double)num);
}

KernelLinearCombination::KernelLinearCombination ( const KernelLinearCombination & src )
{
	alpha.resize ( src.alpha.size() );
	alpha = src.alpha;
	exponential = src.exponential;
}

KernelLinearCombination::~KernelLinearCombination()
{
}

KernelLinearCombination *KernelLinearCombination::clone(void) const
{
	return new KernelLinearCombination ( *this );
}

	
double KernelLinearCombination::K (const NICE::Vector & x, const NICE::Vector & y) const
{
	fthrow(Exception, "Unable to calculate kernel values directly.");
}

void KernelLinearCombination::updateKernelData ( KernelData *kernelData ) const
{
	NICE::Matrix & kernelMatrix = kernelData->getKernelMatrix();

	for ( uint k = 0 ; k < alpha.size(); k++ )
	{
		const NICE::Matrix & cachedMatrix = kernelData->getCachedMatrix ( k );
			
		if ( k == 0 ) {
			kernelMatrix.resize ( cachedMatrix.rows(), cachedMatrix.cols() );
			kernelMatrix.set(0.0);
		}
		kernelMatrix += exp(alpha[k]) * cachedMatrix;
	}

	if ( exponential ) {
		for ( uint i = 0 ; i < kernelMatrix.rows(); i++ )
			for ( uint j = 0 ; j < kernelMatrix.cols(); j++ )
				kernelMatrix(i,j) = exp(- kernelMatrix(i,j));
	}
}

void KernelLinearCombination::getKernelJacobi ( size_t parameter, const NICE::Vector & parameters, const KernelData *kernelData, NICE::Matrix & jacobiMatrix ) const
{
	const NICE::Matrix & kernelMatrix = kernelData->getKernelMatrix();

	if ( parameter >= alpha.size() )
		fthrow(Exception, "Parameter index exceeds parameter vector size" );

	jacobiMatrix.resize ( kernelMatrix.rows(), kernelMatrix.cols() );

	const Matrix & kernelMatrixParameter = kernelData->getCachedMatrix( parameter );
	if ( exponential ) {
		for ( uint i = 0 ; i < jacobiMatrix.rows(); i++ )
			for ( uint j = 0 ; j < jacobiMatrix.cols(); j++ )
				jacobiMatrix(i,j) = - kernelMatrixParameter(i,j) * exp(alpha[parameter]) * kernelMatrix(i,j);
	} else {
		jacobiMatrix = exp(alpha[parameter]) * kernelMatrixParameter;
	}
}

void KernelLinearCombination::setParameters( const NICE::Vector & newParameters ) 
{
	alpha = newParameters;
}

void KernelLinearCombination::getParameters( NICE::Vector & newParameters ) const
{
	newParameters.resize ( alpha.size() );
	newParameters = alpha;
}
