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

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

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

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

		PoissonFixture()
		:	sim( "PoissonTestSim" ),
			log( TestLogConsumer::create() ),
			mean( 100 ),
			cells( (int)mean * 2 ),
			poisson( sim, "PoissonTest", mean ),
			histogram( sim, "PoissonTestHistogram", 0, mean * 2, cells ),
			type( typeid(Poisson) )
			{
				sim.addConsumer( log );
			}
	};

	/**
	 * @test odemx::Poisson construction
	 *
	 * Expected function call effects:
	 * @li negative mean value produces a warning and inverts it
	 * @li label is set
	 * @li dist context (simulation) is set
	 * @li mean value is set
	 */
	TEST_FIXTURE( PoissonFixture, ConstructionDestruction )
	{
		data::Label l = "PoissonTestUserSimConstruction";
		{
			Poisson poisson2( sim, l, -mean );
			CHECK( log->getTraceRecord( "create", type ) );
			CHECK( log->getStatisticsRecord( "parameter", "seed", type ) );
			CHECK( log->getStatisticsRecord( "parameter", "mean", type ) );
			CHECK( log->getWarningRecord( "Poisson(): mean value is <= 0.0; changed to -mean", type ) );

			CHECK_EQUAL( l, poisson2.getLabel() );
			CHECK_EQUAL( mean, poisson2.getMean() );
		}
		CHECK( log->getTraceRecord( "destroy", type ) );
	}

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

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

		CHECK_CLOSE( poisson.getMean(), histogram.getMean(), 0.01  );
		CHECK_CLOSE( poisson.getMean(), std::pow( histogram.getStandardDeviation(), 2 ), 0.1  );
	}

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