/*
    Copyright (C) 2012 Bartosz Broda, Jacek Bochenek, Łukasz Biłeńkij, 
    Damian Jaworski, Wojciech Mazur, Dominik Piasecki, Maciej Piasecki, 
    Radosław Ramocki
    
    This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your option)
any later version.

    This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. 

    See the LICENSE and COPYING files for more details.
*/

#include "../comparator_stdheaders.h"
#include "Bhattacharyya.h"

namespace smartcomparator
{
	namespace simfunctions
	{
		Bhattacharyya::Bhattacharyya(Matrices::SuperMatrixPtr pMatrix, bool pMatrixNormalized)
		:
			SimilarityFunction(pMatrix),
			mMatrixNormalized(pMatrixNormalized)
		{

		}

		Bhattacharyya::~Bhattacharyya(void)
		{

		}


		double Bhattacharyya::CountSimilarity(
			Matrices::CompressedVector& v1,
			Matrices::CompressedVector& v2,
			size_t 						v1ind,
			size_t 						v2ind,
			const std::set<size_t>&		v1Ind,
			const std::set<size_t>&		v2Ind)
		{
			std::set<size_t> intersec;
			std::set_intersection(
				v1Ind.begin(),
				v1Ind.end(),
				v2Ind.begin(),
				v2Ind.end(),
				std::insert_iterator< std::set<size_t> >(intersec, intersec.begin()));

			double dot = 0.0;
			for(std::set<size_t>::const_iterator iter = intersec.begin(); iter != intersec.end();iter++)
			{
				double v1Val = (v1)[(*iter)];
				double v2Val = (v2)[(*iter)];
				dot += sqrt(abs(v1Val) * abs(v2Val));
			}


			if(mMatrixNormalized)
				return dot;

			double v1len = 0;
			for(std::set<size_t>::const_iterator iter = v1Ind.begin(); iter != v1Ind.end(); ++iter)
			{
				double v1Val = (v1)[(*iter)];
				v1len += abs(v1Val);
			}

			double v2len = 0;
			for(std::set<size_t>::const_iterator iter = v2Ind.begin(); iter != v2Ind.end(); ++iter)
			{
				double v2Val = (v2)[(*iter)];
				v2len += abs(v2Val);
			}

			double d = sqrt(v1len * v2len);

			if(d == 0.0)
				return MinValue();

			return dot / d;
		}


		double Bhattacharyya::MinValue() const
		{
			return 0.0;
		}

	}
}
