#include "model_tools.h"
#include <math.h>
#include <stdlib.h> // random numbers

double model_tools::CalcEfficiency(double *obs, double *sim, int size)
{
	double sum_obsminsim_2	= 0.0;
	double sum_obsminmean_2 = 0.0;
	double mean_obs			= 0.0;
	double sum_obs			= 0.0; // sum of observed discharge

	// calculate mean of observed time series
	for (int i = 0; i < size; i++)
		mean_obs += obs[i] / size;
	
	for (int i = 0; i < size; i++)
	{
		sum_obsminsim_2 += pow(obs[i] - sim[i], 2.0);
		sum_obsminmean_2 += pow(obs[i] - mean_obs, 2.0);
	}
	
	return (1 - sum_obsminsim_2 / sum_obsminmean_2);
}


//-------------------------------------------------------------------
double model_tools::Random_double(double lb, double ub)
{
	// lb = lower bound, ub = upper bound
	double random;

	random = rand()/(1.+RAND_MAX);
	random = lb + (ub - lb) * random;

	return(random);
}
//-------------------------------------------------------------------

bool model_tools::LeapYear(int year)
{
	if ( (year % 4   == 0) &&
		 (year % 100 != 0) ||
		 (year % 400 == 0) )
		 return(true);
	else 
		return(false);
}
//-------------------------------------------------------------------


//---------------------------------------------------------------------
// Find indices of lowest values
//---------------------------------------------------------------------
void model_tools::FindLowestIndices(double *array, int size, int *TopIndex, int top)
{
	double min_temp = 99999999.0;
	double x		= -99999999.0;
	int index		= 0;

	for (int k = 0; k < top; k++)
	{
		for (int j = 0; j < size; j++)
		{
			if (array[j] < min_temp && array[j] > x)
			{
				min_temp = array[j];
				index = j;
			}
		}
		TopIndex[k] = index;
		x = min_temp;
		min_temp = 99999999.0;
	}
}

//---------------------------------------------------------------------
// Find indices of highest values
//---------------------------------------------------------------------
void model_tools::FindHighestIndices(double *array, int size, int *TopIndex, int top, double min)
{
	double max_temp = -99999999.0;
	double x		= 99999999.0;
	int index		= 0;
	bool exist		= false;

	for (int k = 0; k < top; k++)
	{
		for (int j = 0; j < size; j++)
		{
			if (array[j] > max_temp && array[j] < x && array[j] > min)
			{
				max_temp = array[j];
				index = j;
				exist = true;
			}
		}
		if (exist)
		{
			TopIndex[k] = index;
		} else {
			TopIndex[k] = -1;
		}
		exist = false;
		x = max_temp;
		max_temp = -99999999.0;
	}
}
