/*
    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 "SimCRM.h"

namespace smartcomparator
{
	namespace simfunctions
	{

		SimCRM::SimCRM(Matrices::SuperMatrixPtr m, double gamma, double beta) 
			: SimilarityFunction(m),
			m_dGamma(gamma),
			m_dBeta(beta)

		{
		}

		SimCRM::~SimCRM(void)
		{
		}

		double SimCRM::CountSimilarity(Matrices::CompressedVector& v1, Matrices::CompressedVector& v2,
			size_t v1_index, size_t v2_index, const std::set<size_t> &v1Ind, const std::set<size_t> &v2Ind)
		{
			//double dist = 0;

			if(v1Ind.size() == 0 || v2Ind.size() == 0 
				|| v1.GetValues()->size() == 0 || v2.GetValues()->size() == 0)
				return 0;

			double prec =0,  rec = 0, mh = 0, ma = 0;

			std::set<size_t> itersec;

			std::insert_iterator< std::set<size_t> > inserter( itersec, itersec.begin() );

			std::set_intersection(v1Ind.begin(), v1Ind.end(), v2Ind.begin(), v2Ind.end(), inserter);

			if( itersec.size() < 2 )
				return 0;

			double prec_numerator = 0, prec_denominator = 0;
			double rec_numerator = 0, rec_denominator= 0;

			for(std::set<size_t>::const_iterator i = itersec.begin(); i != itersec.end(); i++)
				prec_numerator += v1[*i];

			for(std::set<size_t>::const_iterator i = v1Ind.begin(); i != v1Ind.end(); i++)
				prec_denominator += v1[*i];

			for(std::set<size_t>::const_iterator i = itersec.begin(); i != itersec.end(); i++)
				rec_numerator += v2[*i];

			for(std::set<size_t>::const_iterator i = v2Ind.begin(); i != v2Ind.end(); i++)
				rec_denominator += v2[*i];

			if(rec_denominator)
				rec = rec_numerator / rec_denominator;

			if(prec_denominator)
				prec = prec_numerator / prec_denominator;


			if(prec || rec)		
				mh = (2. * prec * rec) / (prec+rec);

			ma = m_dBeta*prec + (1-m_dBeta)*rec;

			return m_dGamma * mh + (1-m_dGamma)*ma;
		}

		double SimCRM::MinValue() const 
		{
			return -1;
		}
	}
}
