/**
 * @file TestNegativeExponential.cpp
 * @date Aug 9, 2008
 * @author Ronald Kluth
 *
 * @brief Tests for ODEMx class NegativeExponential
 */

#include "TestRandom.h"
#include "../TestBase/TestBase.h"
#include <cmath>

/// @cond DOXYGEN_SKIP
SUITE( Random )
{
/// @endcond

	/**
	 * @struct NegativeExponentialFixture
	 * @brief Helper struct providing set-up/tear-down of NegativeExponential tests
	 *
	 * @copydetails EventFixture
	 */
	struct NegativeExponentialFixture
	{
		SuiteBase::SimulationTest sim;
		TestLogConsumer::Ptr log;
		double inverseMean;
		int cells;
		NegativeExponential negExp;
		statistics::Histogram histogram;
		data::TypeInfo type;

		NegativeExponentialFixture()
		:	sim( "NegativeExponentialTestSim" ),
			log( TestLogConsumer::create() ),
			inverseMean( 3 ),
			cells( (int)inverseMean * 10 ),
			negExp( sim, "NegativeExponentialTest", inverseMean ),
			histogram( sim, "NegativeExponentialTestHistogram", 0, 5, cells ),
			type( typeid(NegativeExponential) )
			{
				sim.addConsumer( log );
			}
	};

	/**
	 * @test odemx::NegativeExponential construction
	 *
	 * Expected function call effects:
	 * @li negative inverseMean value produces a warning and inverts it
	 * @li label is set
	 * @li dist context (simulation) is set
	 * @li inverseMean value is set
	 */
	TEST_FIXTURE( NegativeExponentialFixture, ConstructionDestruction )
	{
		data::Label l = "NegativeExponentialTestUserSimConstruction";
		{
			NegativeExponential negExp2( sim, l, -inverseMean );
			CHECK( log->getTraceRecord( "create", type ) );
			CHECK( log->getStatisticsRecord( "parameter", "seed", type ) );
			CHECK( log->getStatisticsRecord( "parameter", "inverse mean", type ) );
			CHECK( log->getWarningRecord( "NegativeExponential(): inverseMean <= 0; -inverseMean or 0.001 used", type ) );
			CHECK_EQUAL( l, negExp2.getLabel() );
			CHECK_EQUAL( inverseMean, negExp2.getInverseMean() );
		}
		CHECK( log->getTraceRecord( "destroy", type ) );
	}

	/**
	 * @test odemx::NegativeExponential::sample()
	 *
	 * Expected function call effects:
	 * @li samples are always greater or equal \c 0
	 * @li the given inverseMean value is very close to the computed one
	 * @li the given inverseMean value is very close to the variance
	 */
	TEST_FIXTURE( NegativeExponentialFixture, Sample )
	{
		negExp.sample();
		CHECK( log->getTraceRecord( "sample", type ) );
		CHECK( log->getStatisticsRecord( "count", "uses", type ) );

		for( int i = 0; i < 1000000; ++i )
		{
			double value = negExp.sample();
			CHECK( 0 <= value );
			histogram.update( value );
		}

		CHECK_CLOSE( 1 / negExp.getInverseMean(), histogram.getMean(), 0.001  );
		CHECK_CLOSE( 1 / std::pow( negExp.getInverseMean(), 2 ), std::pow( histogram.getStandardDeviation(), 2 ), 0.001  );
	}

/// @cond DOXYGEN_SKIP
}
/// @endcond
