//------------------------------------------------------------------------------
//	Copyright (C) 2009 Humboldt-Universitaet zu Berlin
//
//	This library 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 2.1 of the License, or (at your option) any later version.
//
//	This library 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 GNU
//	Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public
//	License along with this library; if not, write to the Free Software
//	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/**
 * @file Accumulate.cpp
 * @author Ronald Kluth
 * @date created at 2009/03/01
 * @brief Implementation of odemx::statistics::Accumulate
 * @sa Accumulate.h
 * @since 3.0
 */

#include <odemx/statistics/Accumulate.h>
#include <odemx/data/ReportTable.h>
#include <odemx/data/Report.h>

#include <cmath>

namespace odemx {
namespace statistics {

//------------------------------------------------------construction/destruction

Accumulate::Accumulate( base::Simulation& sim, const data::Label& label, Approx app )
:	Tab( sim, label )
,	approximation_( app )
,	startTime_( 0 )
,	lastTime_( 0 )
,	lastValue_( 0 )
,	zeros_( 0 )
,	minValue_( 0.0 )
,	maxValue_( 0.0 )
,	sum_( 0.0 )
,	sumSq_( 0.0 )
,	sumWeight_( 0.0 )
,	sumSqWeight_( 0.0 )
{
}

Accumulate::~Accumulate()
{
}

//---------------------------------------------------------------------modifiers

void Accumulate::update( base::SimTime time, double value )
{
	// set start time for later computation of time span
	if( getUpdateCount() == 0 )
	{
		startTime_ = time;
	}

	// update usage counter
	Tab::update();

	// update non-weighted sums
	sum_ += value;
	sumSq_ += std::pow( value, 2 );

	// compute time span since last update and save current time
	base::SimTime lastSpan = time - lastTime_;
	lastTime_ = time;

	// compute weighted sums according to the approximation mode
    if( getUpdateCount() > 1 )
    {
    	if( approximation_ == linear )
		{
	        double mean = ( value + lastValue_ ) / 2;
	        sumWeight_ += mean * lastSpan;
	        sumSqWeight_ += std::pow( mean, 2 ) * lastSpan;
		}
		else // approximation_ == stepwise
		{
	        sumWeight_   += lastValue_ * lastSpan;
	        sumSqWeight_ += lastValue_ * lastValue_ * lastSpan;
	    }
    }

    // remember the current update value
	lastValue_ = value;

	// update min and max values
	if( Tab::getUpdateCount() == 1 )
	{
		minValue_ = maxValue_ = value;
	}
	else if( value < minValue_ )
	{
		minValue_ = value;
	}
	else if( value > maxValue_ )
	{
		maxValue_ = value;
	}

	if( value == 0 )
	{
		++zeros_;
	}
}

void Accumulate::reset( base::SimTime time )
{
	Tab::reset( time );

	zeros_ = 0;
	minValue_ = maxValue_ =	sum_ = sumSq_ = sumWeight_ = sumSqWeight_ = lastValue_ = 0.0;

	startTime_ = lastTime_ = time;
}

//-----------------------------------------------------------------------getters

std::size_t Accumulate::getZeros() const
{
	return zeros_;
}

double Accumulate::getMin() const
{
	return minValue_;
}

double Accumulate::getMax() const
{
	return maxValue_;
}

double Accumulate::getMean() const
{
	return getUpdateCount() > 0 ? sum_ / getUpdateCount() : 0.0;
}

double Accumulate::getWeightedMean() const
{
	base::SimTime span = lastTime_ - startTime_;

	// does not consider the last time span till this call,
	// call update once more before getting the mean value ?!?
	if( span == 0 )
	{
		return 0.0;
	}

	return sumWeight_ / span;
}

double Accumulate::getStandardDeviation() const
{
	if( getUpdateCount() <= 1 )
	{
		return 0.0;
	}

	double mean = getMean();
	double variance = std::fabs( sumSq_ / getUpdateCount() - std::pow( mean, 2 ) );
	return std::sqrt( variance );
}

double Accumulate::getWeightedStandardDeviation() const
{
	if( getUpdateCount() <= 1 )
	{
		return 0.0;
	}

	base::SimTime span = lastTime_ - startTime_;

	if( span == 0 )
	{
		return 0.0;
	}

	double weightedMean = getWeightedMean();
	double variance = std::fabs( sumSqWeight_ / span - std::pow( weightedMean, 2 ) );
	return std::sqrt( variance );
}

//------------------------------------------------------------------------report

void Accumulate::report( data::Report& report )
{
	using namespace data;
	ReportTable::Definition def;
	def.addColumn( "Name", ReportTable::Column::STRING );
	def.addColumn( "Reset at", ReportTable::Column::SIMTIME );
	def.addColumn( "Uses", ReportTable::Column::INTEGER );
	def.addColumn( "Min", ReportTable::Column::REAL );
	def.addColumn( "Max", ReportTable::Column::REAL );
	def.addColumn( "Mean", ReportTable::Column::REAL );
	def.addColumn( "Weighted Mean", ReportTable::Column::REAL );
	def.addColumn( "Std Deviation", ReportTable::Column::REAL );
	def.addColumn( "Weighted StDev", ReportTable::Column::REAL );
	ReportTable& table = report.getTable( "Accumulate Statistics", def );
	table
	<< getLabel()
	<< getResetTime()
	<< getUpdateCount()
	<< getMin()
	<< getMax()
	<< getMean()
	<< getWeightedMean()
	<< getStandardDeviation()
	<< getWeightedStandardDeviation();
}

} } // namespace odemx::statistics
