<commit_before>#include <shogun/lib/io.h>
#include <shogun/lib/Mathematics.h>
#include <shogun/base/Parameter.h>
#include <shogun/kernel/DistantSegmentsKernel.h>
#include <shogun/kernel/GaussianKernel.h>

using namespace shogun;

int32_t max=3;
const float64_t initial_value=1;
const float64_t another_value=2;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

bool test_float_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t original_parameter=initial_value;
	original_parameter_list->add(&original_parameter, "param", "");

	float64_t new_parameter=another_value;
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==another_value;

	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max];
	CMath::fill_vector(original_parameter, max, initial_value);

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	float64_t* new_parameter=new float64_t[max];
	CMath::fill_vector(new_parameter, max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
		result&=original_parameter[i]==another_value;

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max*max];
	CMath::fill_vector(original_parameter, max*max, initial_value);

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	float64_t* new_parameter=new float64_t[max*max];
	CMath::fill_vector(new_parameter, max*max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max*max; ++i)
		result&=original_parameter[i]==another_value;

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject* original_parameter=new CGaussianKernel(10, 10);
	SG_REF(original_parameter);
	original_parameter_list->add(&original_parameter, "kernel", "");

	CSGObject* new_parameter=new CDistantSegmentsKernel(10, 10, 10);
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "kernel", "");

	/* note: old_parameter is SG_UNREF'ed, new one SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==new_parameter;

	/* old original kernel was deleted by shogun's SG_UNREF */
	SG_UNREF(new_parameter);
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
	{
		original_parameter[i]=new CDistantSegmentsKernel(1, 1, 1);
		SG_REF(original_parameter[i]);
	}

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
		new_parameter[i]=new CDistantSegmentsKernel(2, 2, 2);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
		result&=original_parameter[i]==new_parameter[i];

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max; ++i)
		SG_UNREF(new_parameter[i]);

	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
		{
			original_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
			SG_REF(original_parameter[j*max+i]);
		}
	}

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
			new_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
	}

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
			result&=original_parameter[j*max+i]==new_parameter[j*max+i];
	}

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max*max; ++i)
		SG_UNREF(new_parameter[i]);

	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	bool result=true;

	/* test wheater set_from_parameters works for these types */
	result&=test_float_scalar();
	result&=test_sgobject_scalar();
	result&=test_sgobject_vector();
	result&=test_sgobject_matrix();
	result&=test_float_matrix();
	result&=test_float_vector();

	if (result)
		SG_SPRINT("SUCCESS!\n");
	else
		SG_SPRINT("FAILURE!\n");

	exit_shogun();

	return 0;
}
<commit_msg>added copyright<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Heiko Strathmann
 * DS-Kernel implementation Written (W) 2008 Sébastien Boisvert under GPLv3
 * Copyright (C) 1999-2011 Fraunhofer Institute FIRST and Max-Planck-Society
 */

#include <shogun/lib/io.h>
#include <shogun/lib/Mathematics.h>
#include <shogun/base/Parameter.h>
#include <shogun/kernel/DistantSegmentsKernel.h>
#include <shogun/kernel/GaussianKernel.h>

using namespace shogun;

int32_t max=3;
const float64_t initial_value=1;
const float64_t another_value=2;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

bool test_float_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t original_parameter=initial_value;
	original_parameter_list->add(&original_parameter, "param", "");

	float64_t new_parameter=another_value;
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==another_value;

	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max];
	CMath::fill_vector(original_parameter, max, initial_value);

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	float64_t* new_parameter=new float64_t[max];
	CMath::fill_vector(new_parameter, max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
		result&=original_parameter[i]==another_value;

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_float_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	float64_t* original_parameter=new float64_t[max*max];
	CMath::fill_vector(original_parameter, max*max, initial_value);

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	float64_t* new_parameter=new float64_t[max*max];
	CMath::fill_vector(new_parameter, max*max, another_value);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max*max; ++i)
		result&=original_parameter[i]==another_value;

	delete original_parameter;
	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_scalar()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject* original_parameter=new CGaussianKernel(10, 10);
	SG_REF(original_parameter);
	original_parameter_list->add(&original_parameter, "kernel", "");

	CSGObject* new_parameter=new CDistantSegmentsKernel(10, 10, 10);
	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add(&new_parameter, "kernel", "");

	/* note: old_parameter is SG_UNREF'ed, new one SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	result&=original_parameter==new_parameter;

	/* old original kernel was deleted by shogun's SG_UNREF */
	SG_UNREF(new_parameter);
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_vector()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
	{
		original_parameter[i]=new CDistantSegmentsKernel(1, 1, 1);
		SG_REF(original_parameter[i]);
	}

	original_parameter_list->add_vector(&original_parameter, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max];
	for (int32_t i=0; i<max; ++i)
		new_parameter[i]=new CDistantSegmentsKernel(2, 2, 2);

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_vector(&new_parameter, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
		result&=original_parameter[i]==new_parameter[i];

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max; ++i)
		SG_UNREF(new_parameter[i]);

	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

bool test_sgobject_matrix()
{
	bool result=true;

	Parameter* original_parameter_list=new Parameter();
	CSGObject** original_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
		{
			original_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
			SG_REF(original_parameter[j*max+i]);
		}
	}

	original_parameter_list->add_matrix(&original_parameter, &max, &max, "param", "");

	CSGObject** new_parameter=new CSGObject*[max*max];
	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
			new_parameter[j*max+i]=new CDistantSegmentsKernel(1, 1, 1);
	}

	Parameter* new_parameter_list=new Parameter();
	new_parameter_list->add_matrix(&new_parameter, &max, &max, "param", "");

	/* note: old_parameters are SG_UNREF'ed, new ones SG_REF'ed */
	original_parameter_list->set_from_parameters(new_parameter_list);

	for (int32_t i=0; i<max; ++i)
	{
		for (int32_t j=0; j<max; ++j)
			result&=original_parameter[j*max+i]==new_parameter[j*max+i];
	}

	/* old original kernels were deleted by shogun's SG_UNREF */
	delete original_parameter;

	for (int32_t i=0; i<max*max; ++i)
		SG_UNREF(new_parameter[i]);

	delete new_parameter;
	delete original_parameter_list;
	delete new_parameter_list;

	return result;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	bool result=true;

	/* test wheater set_from_parameters works for these types */
	result&=test_float_scalar();
	result&=test_sgobject_scalar();
	result&=test_sgobject_vector();
	result&=test_sgobject_matrix();
	result&=test_float_matrix();
	result&=test_float_vector();

	if (result)
		SG_SPRINT("SUCCESS!\n");
	else
		SG_SPRINT("FAILURE!\n");

	exit_shogun();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/statistics/QuadraticTimeMMD.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/features/DataGenerator.h>

using namespace shogun;

/** tests the quadratic mmd statistic for a single data case and ensures
 * equality with matlab implementation */
void test_quadratic_mmd_fixed()
{
	index_t n=2;
	index_t d=3;
	float64_t sigma=2;
	float64_t sq_sigma_twice=sigma*sigma*2;
	SGMatrix<float64_t> data(d,2*n);
	for (index_t i=0; i<2*d*n; ++i)
		data.matrix[i]=i;

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
	CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice);
	kernel->init(features, features);

	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, n);

	/* unbiased statistic */
	mmd->set_statistic_type(UNBIASED);
	float64_t difference=CMath::abs(mmd->compute_statistic()-0.051325806508381);
	ASSERT(difference<=10E-16);

	/* biased statistic */
	mmd->set_statistic_type(BIASED);
	difference=CMath::abs(mmd->compute_statistic()-1.017107688196714);
	ASSERT(difference<=10E-16);

	SG_UNREF(mmd);
}

/** tests the quadratic mmd statistic bootstrapping for a random data case and
 * ensures equality with matlab implementation (unbiased statistic) */
void test_quadratic_mmd_bootstrap()
{
	index_t dimension=3;
	index_t m=100;
	float64_t difference=0.5;
	float64_t sigma=2;
	index_t num_iterations=1000;
	num_iterations=10; //speed up

	SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension,
			difference);
	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);
	mmd->set_statistic_type(UNBIASED);
	mmd->set_bootstrap_iterations(num_iterations);
	SGVector<float64_t> null_samples=mmd->bootstrap_null();

	float64_t mean=CStatistics::mean(null_samples);
	float64_t var=CStatistics::variance(null_samples);

	/* MATLAB mean 2-sigma confidence interval for 1000 repretitions is
	 * [-3.169406734013459e-04, 3.296399498466372e-04] */
	SG_SPRINT("mean %f\n", mean);
//	ASSERT(mean>-3.169406734013459e-04);
//	ASSERT(mean<3.296399498466372e-04);

	/* MATLAB variance 2-sigma confidence interval for 1000 repretitions is
	 * [2.194192869469228e-05,2.936672859339959e-05] */
	SG_SPRINT("var %f\n", var);
//	ASSERT(var>2.194192869469228e-05);
//	ASSERT(var<2.936672859339959e-05);

	SG_UNREF(mmd);
}

#ifdef HAVE_LAPACK
/** tests the quadratic mmd statistic threshold method spectrum for radnom data
 * case and ensures equality with matlab implementation */
void test_quadratic_mmd_spectrum()
{
	index_t dimension=3;
	index_t m=100;
	float64_t difference=0.5;
	float64_t sigma=2;

	SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension,
			difference);

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);

	mmd->set_num_samples_sepctrum(1000);
	mmd->set_num_samples_sepctrum(10); //speed up
	mmd->set_num_eigenvalues_spectrum(m);
	mmd->set_null_approximation_method(MMD2_SPECTRUM);
	mmd->set_statistic_type(BIASED);

	/* compute p-value for a fixed statistic value */
	float64_t p=mmd->compute_p_value(2);

	/* MATLAB 1000 iterations 3 sigma confidence interval is
	 * [0.021240218376709, 0.060875781623291] */
	SG_SPRINT("p %f\n", p);
//	ASSERT(p>0.021240218376709);
//	ASSERT(p<0.060875781623291);

	SG_UNREF(mmd);
}
#endif // HAVE_LAPACK

/** tests the quadratic mmd statistic threshold method gamma for fixed data
 * case and ensures equality with matlab implementation */
void test_quadratic_mmd_gamma()
{
	index_t dimension=3;
	index_t m=100;
	float64_t sigma=4;

	/* note: fixed data this time */
	SGMatrix<float64_t> data(dimension, 2*m);
	for (index_t i=0; i<2*dimension*m; ++i)
		data.matrix[i]=i;

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);

	mmd->set_null_approximation_method(MMD2_GAMMA);
	mmd->set_statistic_type(BIASED);

	/* compute p-value for a fixed statistic value */
	float64_t p=mmd->compute_p_value(2);
	SG_SPRINT("p: %f\n", p);

	/* MATLAB 1000 iterations mean: 0.511547577996229 with variance 10E-15,
	 * asserting with only 10-12 to avoid problems. Shold never fail.
	 */
	ASSERT(CMath::abs(p-0.511547577996229)<10E-12);

	SG_UNREF(mmd);
}

/** tests the quadratic mmd statistic for a random data case (fixed distribution
 * and ensures equality with matlab implementation (unbiased case) */
void test_quadratic_mmd_random()
{
	index_t dimension=3;
	index_t m=300;
	float64_t difference=0.5;
	float64_t sigma=2;

	index_t num_runs=100;
	num_runs=10; //speed up
	SGVector<float64_t> mmds(num_runs);

	/* pre-allocate data matrix and features, just change elements later */
	SGMatrix<float64_t> data(dimension, 2*m);
	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);
	mmd->set_statistic_type(UNBIASED);
	for (index_t i=0; i<num_runs; ++i)
	{
		/* use pre-allocated space for data generation */
		CDataGenerator::generate_mean_data(m, dimension, difference, data);
		kernel->init(features, features);
		mmds[i]=mmd->compute_statistic();
	}

	/* MATLAB 95% mean confidence interval 0.007495841715582 0.037960088792417 */
	float64_t mean=CStatistics::mean(mmds);
	SG_SPRINT("mean %f\n", mean);
//	ASSERT((mean>0.007495841715582) && (mean<0.037960088792417));

	/* MATLAB variance is 5.800439687240292e-05 quite stable */
	float64_t variance=CStatistics::variance(mmds);
	SG_SPRINT("variance: %f\n", variance);
//	ASSERT(CMath::abs(variance-5.800439687240292e-05)<10E-5);
	SG_UNREF(mmd);
}

int main(int argc, char** argv)
{
	init_shogun_with_defaults();

	/* all tests have been "speed up" by reducing the number of runs/samples.
	 * If you have any doubts in the results, set all num_runs to original
	 * numbers and activate asserts. If they fail, something is wrong. */

	test_quadratic_mmd_fixed();
	test_quadratic_mmd_random();
	test_quadratic_mmd_bootstrap();
#ifdef HAVE_LAPACK
	test_quadratic_mmd_spectrum();
#endif
	test_quadratic_mmd_gamma();

	exit_shogun();
	return 0;
}

<commit_msg>added a test for the bootstrapping with custom kernels<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/statistics/QuadraticTimeMMD.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/features/DataGenerator.h>

using namespace shogun;

/** tests the quadratic mmd statistic for a single data case and ensures
 * equality with matlab implementation */
void test_quadratic_mmd_fixed()
{
	index_t n=2;
	index_t d=3;
	float64_t sigma=2;
	float64_t sq_sigma_twice=sigma*sigma*2;
	SGMatrix<float64_t> data(d,2*n);
	for (index_t i=0; i<2*d*n; ++i)
		data.matrix[i]=i;

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
	CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice);
	kernel->init(features, features);

	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, n);

	/* unbiased statistic */
	mmd->set_statistic_type(UNBIASED);
	float64_t difference=CMath::abs(mmd->compute_statistic()-0.051325806508381);
	ASSERT(difference<=10E-16);

	/* biased statistic */
	mmd->set_statistic_type(BIASED);
	difference=CMath::abs(mmd->compute_statistic()-1.017107688196714);
	ASSERT(difference<=10E-16);

	SG_UNREF(mmd);
}

/** tests the quadratic mmd statistic bootstrapping for a random data case and
 * ensures equality with matlab implementation (unbiased statistic) */
void test_quadratic_mmd_bootstrap()
{
	index_t dimension=3;
	index_t m=100;
	float64_t difference=0.5;
	float64_t sigma=2;
	index_t num_iterations=1000;
	num_iterations=10; //speed up

	SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension,
			difference);
	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);
	mmd->set_statistic_type(UNBIASED);
	mmd->set_bootstrap_iterations(num_iterations);

	/* use fixed seed */
	CMath::init_random(1);
	SGVector<float64_t> null_samples=mmd->bootstrap_null();

	float64_t mean=CStatistics::mean(null_samples);
	float64_t var=CStatistics::variance(null_samples);

	/* MATLAB mean 2-sigma confidence interval for 1000 repretitions is
	 * [-3.169406734013459e-04, 3.296399498466372e-04] */
	SG_SPRINT("mean %f\n", mean);
//	ASSERT(mean>-3.169406734013459e-04);
//	ASSERT(mean<3.296399498466372e-04);

	/* MATLAB variance 2-sigma confidence interval for 1000 repretitions is
	 * [2.194192869469228e-05,2.936672859339959e-05] */
	SG_SPRINT("var %f\n", var);
//	ASSERT(var>2.194192869469228e-05);
//	ASSERT(var<2.936672859339959e-05);

	/* now again but with a precomputed kernel, same features.
	 * This avoids re-computing the kernel matrix in every bootstrapping
	 * iteration and should be num_iterations times faster */
	SG_REF(features);
	CCustomKernel* precomputed_kernel=new CCustomKernel(kernel);
	SG_UNREF(mmd);
	mmd=new CQuadraticTimeMMD(precomputed_kernel, features, m);
	mmd->set_statistic_type(UNBIASED);
	mmd->set_bootstrap_iterations(num_iterations);
	CMath::init_random(1);
	null_samples=mmd->bootstrap_null();

	/* assert that results do not change */
	SG_SPRINT("mean %f, var %f\n", CStatistics::mean(null_samples),
			CStatistics::variance(null_samples));
	ASSERT(CMath::abs(mean-CStatistics::mean(null_samples))<10E-5);
	ASSERT(CMath::abs(var-CStatistics::variance(null_samples))<10E-5);

	SG_UNREF(mmd);
	SG_UNREF(features);
}

#ifdef HAVE_LAPACK
/** tests the quadratic mmd statistic threshold method spectrum for radnom data
 * case and ensures equality with matlab implementation */
void test_quadratic_mmd_spectrum()
{
	index_t dimension=3;
	index_t m=100;
	float64_t difference=0.5;
	float64_t sigma=2;

	SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension,
			difference);

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);

	mmd->set_num_samples_sepctrum(1000);
	mmd->set_num_samples_sepctrum(10); //speed up
	mmd->set_num_eigenvalues_spectrum(m);
	mmd->set_null_approximation_method(MMD2_SPECTRUM);
	mmd->set_statistic_type(BIASED);

	/* compute p-value for a fixed statistic value */
	float64_t p=mmd->compute_p_value(2);

	/* MATLAB 1000 iterations 3 sigma confidence interval is
	 * [0.021240218376709, 0.060875781623291] */
	SG_SPRINT("p %f\n", p);
//	ASSERT(p>0.021240218376709);
//	ASSERT(p<0.060875781623291);

	SG_UNREF(mmd);
}
#endif // HAVE_LAPACK

/** tests the quadratic mmd statistic threshold method gamma for fixed data
 * case and ensures equality with matlab implementation */
void test_quadratic_mmd_gamma()
{
	index_t dimension=3;
	index_t m=100;
	float64_t sigma=4;

	/* note: fixed data this time */
	SGMatrix<float64_t> data(dimension, 2*m);
	for (index_t i=0; i<2*dimension*m; ++i)
		data.matrix[i]=i;

	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);

	mmd->set_null_approximation_method(MMD2_GAMMA);
	mmd->set_statistic_type(BIASED);

	/* compute p-value for a fixed statistic value */
	float64_t p=mmd->compute_p_value(2);
	SG_SPRINT("p: %f\n", p);

	/* MATLAB 1000 iterations mean: 0.511547577996229 with variance 10E-15,
	 * asserting with only 10-12 to avoid problems. Shold never fail.
	 */
	ASSERT(CMath::abs(p-0.511547577996229)<10E-12);

	SG_UNREF(mmd);
}

/** tests the quadratic mmd statistic for a random data case (fixed distribution
 * and ensures equality with matlab implementation (unbiased case) */
void test_quadratic_mmd_random()
{
	index_t dimension=3;
	index_t m=300;
	float64_t difference=0.5;
	float64_t sigma=2;

	index_t num_runs=100;
	num_runs=10; //speed up
	SGVector<float64_t> mmds(num_runs);

	/* pre-allocate data matrix and features, just change elements later */
	SGMatrix<float64_t> data(dimension, 2*m);
	CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);

	/* shoguns kernel width is different */
	CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2);
	CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m);
	mmd->set_statistic_type(UNBIASED);
	for (index_t i=0; i<num_runs; ++i)
	{
		/* use pre-allocated space for data generation */
		CDataGenerator::generate_mean_data(m, dimension, difference, data);
		kernel->init(features, features);
		mmds[i]=mmd->compute_statistic();
	}

	/* MATLAB 95% mean confidence interval 0.007495841715582 0.037960088792417 */
	float64_t mean=CStatistics::mean(mmds);
	SG_SPRINT("mean %f\n", mean);
//	ASSERT((mean>0.007495841715582) && (mean<0.037960088792417));

	/* MATLAB variance is 5.800439687240292e-05 quite stable */
	float64_t variance=CStatistics::variance(mmds);
	SG_SPRINT("variance: %f\n", variance);
//	ASSERT(CMath::abs(variance-5.800439687240292e-05)<10E-5);
	SG_UNREF(mmd);
}

int main(int argc, char** argv)
{
	init_shogun_with_defaults();

//	sg_io->set_loglevel(MSG_DEBUG);

	/* all tests have been "speed up" by reducing the number of runs/samples.
	 * If you have any doubts in the results, set all num_runs to original
	 * numbers and activate asserts. If they fail, something is wrong. */

	test_quadratic_mmd_fixed();
	test_quadratic_mmd_random();
	test_quadratic_mmd_bootstrap();
#ifdef HAVE_LAPACK
	test_quadratic_mmd_spectrum();
#endif
	test_quadratic_mmd_gamma();

	exit_shogun();
	return 0;
}

<|endoftext|>


<commit_before>/**
 * @file
 */
#pragma once

#ifdef HAVE_OMP_H
#include <omp.h>
#endif

namespace bi {
/**
 * Lockable object.
 *
 * @ingroup libbirch
 */
class Lockable {
public:
  /**
   * Constructor.
   */
  Lockable() {
    #ifdef HAVE_OMP_H
    omp_init_lock(&mutex);
    #endif
  }

  /**
   * Destructor.
   */
  ~Lockable() {
    #ifdef HAVE_OMP_H
    omp_destroy_lock(&mutex);
    #endif
  }

  /**
   * Set the lock.
   */
  void set() {
    #ifdef HAVE_OMP_H
    omp_set_lock(&mutex);
    #endif
  }

  /**
   * Unset the lock.
   */
  void unset() {
    #ifdef HAVE_OMP_H
    omp_unset_lock(&mutex);
    #endif
  }

private:
  #ifdef HAVE_OMP_H
  /**
   * Lock.
   */
  omp_lock_t mutex;
  #endif
};
}
<commit_msg>Replace use of HAVE_OMP_H define with _OPENMP define.<commit_after>/**
 * @file
 */
#pragma once

#ifdef _OPENMP
#include <omp.h>
#endif

namespace bi {
/**
 * Lockable object.
 *
 * @ingroup libbirch
 */
class Lockable {
public:
  /**
   * Constructor.
   */
  Lockable() {
    #ifdef _OPENMP
    omp_init_lock(&mutex);
    #endif
  }

  /**
   * Destructor.
   */
  ~Lockable() {
    #ifdef _OPENMP
    omp_destroy_lock(&mutex);
    #endif
  }

  /**
   * Set the lock.
   */
  void set() {
    #ifdef _OPENMP
    omp_set_lock(&mutex);
    #endif
  }

  /**
   * Unset the lock.
   */
  void unset() {
    #ifdef _OPENMP
    omp_unset_lock(&mutex);
    #endif
  }

private:
  #ifdef _OPENMP
  /**
   * Lock.
   */
  omp_lock_t mutex;
  #endif
};
}
<|endoftext|>


<commit_before>// This file is part of Fuxedo
// Copyright (C) 2017 Aivars Kalvans <aivars.kalvans@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <xatmi.h>
#include <algorithm>
#include <cstddef>
#include <cstring>

#include <vector>
#include "misc.h"

#include <iostream>

struct tptype {
  char type[8];
  char subtype[16];
  int default_size;
  void (*init)(void *mem, size_t size);
  void (*reinit)(void *mem, size_t size);
  void (*finit)(void *mem);
  size_t (*used)(void *mem);
};

size_t strused(void *ptr) { return strlen(reinterpret_cast<char *>(ptr)) + 1; }

void fml32init(void *, size_t);
void fml32reinit(void *, size_t);
void fml32finit(void *);
size_t fml32used(void *);

std::vector<tptype> _tptypes = {
    tptype{"CARRAY", "*", 0, nullptr, nullptr, nullptr, nullptr},
    tptype{"STRING", "*", 512, nullptr, nullptr, nullptr, strused},
    tptype{"FML32", "*", 512, fml32init, fml32reinit, fml32finit, fml32used}};

struct tpmem {
  long size;
  char **owner;
  char type[8];
  char subtype[16];
  char data[];
};

static tpmem *memptr(char *ptr) {
  return (tpmem *)(ptr - offsetof(struct tpmem, data));
}

static tptype *typeptr(const char *type, const char *subtype) {
  const auto &tptype =
      std::find_if(_tptypes.begin(), _tptypes.end(), [&](const auto &t) {
        return (strncmp(t.type, type, sizeof(t.type)) == 0 &&
                (subtype == nullptr || subtype[0] == '\0' ||
                 strncmp(t.subtype, subtype, sizeof(t.subtype)) == 0));
      });
  if (tptype == _tptypes.end()) {
    TPERROR(TPENOENT, "unknown type [%s] and subtype[%s]", type,
            subtype == nullptr ? "" : subtype);
    return nullptr;
  }
  return &(*tptype);
}

char *tpalloc(const char *type, const char *subtype, long size) try {
  if (type == nullptr) {
    TPERROR(TPEINVAL, "type is nullptr");
    return nullptr;
  }

  const auto tptype = typeptr(type, subtype);
  if (tptype == nullptr) {
    return nullptr;
  }

  size = size >= tptype->default_size ? size : tptype->default_size;
  auto mem = (tpmem *)malloc(sizeof(tpmem) + size);
  strncpy(mem->type, type, sizeof(mem->type));
  if (subtype != nullptr) {
    strncpy(mem->subtype, subtype, sizeof(mem->subtype));
  } else {
    mem->subtype[0] = '\0';
  }
  mem->size = size;
  mem->owner = nullptr;
  if (tptype->init != nullptr) {
    tptype->init(mem->data, size);
  }

  return mem->data;
} catch (...) {
  return nullptr;
}

char *tprealloc(char *ptr, long size) try {
  if (ptr == nullptr) {
    TPERROR(TPEINVAL, "ptr is nullptr");
    return nullptr;
  }

  auto mem = memptr(ptr);
  const auto tptype = typeptr(mem->type, mem->subtype);
  if (tptype == nullptr) {
    return nullptr;
  }

  size = size >= tptype->default_size ? size : tptype->default_size;
  mem = (tpmem *)realloc(mem, sizeof(tpmem) + size);
  if (tptype->reinit != nullptr) {
    tptype->reinit(ptr, size);
  }

  if (mem->owner != nullptr && *(mem->owner) == ptr) {
    *(mem->owner) = mem->data;
  }
  return mem->data;
} catch (...) {
  return nullptr;
}

void tpfree(char *ptr) try {
  if (ptr != nullptr) {
    // Inside service routines do not free buffer past into a service routine
    auto mem = memptr(ptr);
    const auto tptype = typeptr(mem->type, mem->subtype);
    if (tptype == nullptr) {
      return;
    }
    if (tptype->finit != nullptr) {
      tptype->finit(ptr);
    }
    if (mem->owner != nullptr && *(mem->owner) == ptr) {
      *(mem->owner) = nullptr;
    }
    free(mem);
  }
} catch (...) {
}

long tptypes(char *ptr, char *type, char *subtype) try {
  if (ptr == nullptr) {
    TPERROR(TPEINVAL, "ptr is nullptr");
    return -1;
  }

  auto mem = memptr(ptr);
  if (type != nullptr) {
    std::copy_n(mem->type, sizeof(mem->type), type);
  }
  if (subtype != nullptr) {
    std::copy_n(mem->subtype, sizeof(mem->subtype), subtype);
  }

  return 0;
} catch (...) {
  return -1;
}

int tpimport(char *istr, long ilen, char **obuf, long *olen, long flags) try {
  if (istr == nullptr) {
    TPERROR(TPEINVAL, "istr is NULL");
    return -1;
  }
  if (obuf == nullptr || *obuf == nullptr) {
    TPERROR(TPEINVAL, "obuf is NULL");
    return -1;
  }

  if (ilen == 0) {
    flags |= TPEX_STRING;
  }

  long needed = sizeof(tpmem);
  if (flags & TPEX_STRING) {
    ilen = strlen(istr);
    if (ilen % 4) {
      TPERROR(TPEINVAL, "Invalid base64 string");
      return -1;
    }
    needed += ilen / 4 * 3;
  } else {
    needed += ilen;
  }

  auto omem = memptr(*obuf);
  if (needed > omem->size) {
    *obuf = tprealloc(*obuf, needed);
    omem = memptr(*obuf);
  }

  if (flags & TPEX_STRING) {
    auto n = base64decode(
        istr, ilen, reinterpret_cast<char *>(omem) + offsetof(tpmem, type),
        ilen);
  } else {
    std::copy_n(istr, ilen,
                reinterpret_cast<char *>(omem) + offsetof(tpmem, type));
  }

  const auto tptype = typeptr(omem->type, omem->subtype);
  if (tptype == nullptr) {
    return -1;
  }
  if (tptype->reinit != nullptr) {
    tptype->reinit(omem->data, omem->size);
  }

  if (olen != nullptr) {
    *olen = ilen;
  }
  return 0;
} catch (...) {
  return -1;
}

int tpexport(char *ibuf, long ilen, char *ostr, long *olen, long flags) try {
  if (ibuf == nullptr || ostr == nullptr || olen == nullptr) {
    TPERROR(TPEINVAL, "Invalid arguments");
    return -1;
  }

  auto mem = memptr(ibuf);
  long used = fux::mem::bufsize(ibuf, ilen);
  if (used == -1) {
    return -1;
  }

  long needed;
  if (flags & TPEX_STRING) {
    needed = base64chars(used) + 1;
  } else {
    needed = used;
  }

  if (*olen < needed) {
    TPERROR(TPELIMIT, "Output buffer too small");
    *olen = needed;
    return -1;
  }

  if (flags & TPEX_STRING) {
    auto n = base64encode(reinterpret_cast<char *>(mem) + offsetof(tpmem, type),
                          used, ostr, *olen);
    ostr[n] = '\0';
  } else {
    std::copy_n(reinterpret_cast<char *>(mem) + offsetof(tpmem, type), used,
                ostr);
  }

  *olen = needed;
  return 0;
} catch (...) {
  return -1;
}

namespace fux {
namespace mem {
void setowner(char *ptr, char **owner) { memptr(ptr)->owner = owner; }

long bufsize(char *ptr, long used) {
  auto mem = memptr(ptr);
  const auto tptype = typeptr(mem->type, mem->subtype);
  if (tptype == nullptr) {
    return -1;
  }
  if (tptype->used != nullptr) {
    return tptype->used(mem->data) + sizeof(*mem) - offsetof(tpmem, type);
  } else if (used != -1) {
    return used + sizeof(*mem) - offsetof(tpmem, type);
  } else {
    return mem->size - offsetof(tpmem, type);
  }
}
}
}
<commit_msg>:shirt: Fix unused variable warning<commit_after>// This file is part of Fuxedo
// Copyright (C) 2017 Aivars Kalvans <aivars.kalvans@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <xatmi.h>
#include <algorithm>
#include <cstddef>
#include <cstring>

#include <vector>
#include "misc.h"

#include <iostream>

struct tptype {
  char type[8];
  char subtype[16];
  int default_size;
  void (*init)(void *mem, size_t size);
  void (*reinit)(void *mem, size_t size);
  void (*finit)(void *mem);
  size_t (*used)(void *mem);
};

size_t strused(void *ptr) { return strlen(reinterpret_cast<char *>(ptr)) + 1; }

void fml32init(void *, size_t);
void fml32reinit(void *, size_t);
void fml32finit(void *);
size_t fml32used(void *);

std::vector<tptype> _tptypes = {
    tptype{"CARRAY", "*", 0, nullptr, nullptr, nullptr, nullptr},
    tptype{"STRING", "*", 512, nullptr, nullptr, nullptr, strused},
    tptype{"FML32", "*", 512, fml32init, fml32reinit, fml32finit, fml32used}};

struct tpmem {
  long size;
  char **owner;
  char type[8];
  char subtype[16];
  char data[];
};

static tpmem *memptr(char *ptr) {
  return (tpmem *)(ptr - offsetof(struct tpmem, data));
}

static tptype *typeptr(const char *type, const char *subtype) {
  const auto &tptype =
      std::find_if(_tptypes.begin(), _tptypes.end(), [&](const auto &t) {
        return (strncmp(t.type, type, sizeof(t.type)) == 0 &&
                (subtype == nullptr || subtype[0] == '\0' ||
                 strncmp(t.subtype, subtype, sizeof(t.subtype)) == 0));
      });
  if (tptype == _tptypes.end()) {
    TPERROR(TPENOENT, "unknown type [%s] and subtype[%s]", type,
            subtype == nullptr ? "" : subtype);
    return nullptr;
  }
  return &(*tptype);
}

char *tpalloc(const char *type, const char *subtype, long size) try {
  if (type == nullptr) {
    TPERROR(TPEINVAL, "type is nullptr");
    return nullptr;
  }

  const auto tptype = typeptr(type, subtype);
  if (tptype == nullptr) {
    return nullptr;
  }

  size = size >= tptype->default_size ? size : tptype->default_size;
  auto mem = (tpmem *)malloc(sizeof(tpmem) + size);
  strncpy(mem->type, type, sizeof(mem->type));
  if (subtype != nullptr) {
    strncpy(mem->subtype, subtype, sizeof(mem->subtype));
  } else {
    mem->subtype[0] = '\0';
  }
  mem->size = size;
  mem->owner = nullptr;
  if (tptype->init != nullptr) {
    tptype->init(mem->data, size);
  }

  return mem->data;
} catch (...) {
  return nullptr;
}

char *tprealloc(char *ptr, long size) try {
  if (ptr == nullptr) {
    TPERROR(TPEINVAL, "ptr is nullptr");
    return nullptr;
  }

  auto mem = memptr(ptr);
  const auto tptype = typeptr(mem->type, mem->subtype);
  if (tptype == nullptr) {
    return nullptr;
  }

  size = size >= tptype->default_size ? size : tptype->default_size;
  mem = (tpmem *)realloc(mem, sizeof(tpmem) + size);
  if (tptype->reinit != nullptr) {
    tptype->reinit(ptr, size);
  }

  if (mem->owner != nullptr && *(mem->owner) == ptr) {
    *(mem->owner) = mem->data;
  }
  return mem->data;
} catch (...) {
  return nullptr;
}

void tpfree(char *ptr) try {
  if (ptr != nullptr) {
    // Inside service routines do not free buffer past into a service routine
    auto mem = memptr(ptr);
    const auto tptype = typeptr(mem->type, mem->subtype);
    if (tptype == nullptr) {
      return;
    }
    if (tptype->finit != nullptr) {
      tptype->finit(ptr);
    }
    if (mem->owner != nullptr && *(mem->owner) == ptr) {
      *(mem->owner) = nullptr;
    }
    free(mem);
  }
} catch (...) {
}

long tptypes(char *ptr, char *type, char *subtype) try {
  if (ptr == nullptr) {
    TPERROR(TPEINVAL, "ptr is nullptr");
    return -1;
  }

  auto mem = memptr(ptr);
  if (type != nullptr) {
    std::copy_n(mem->type, sizeof(mem->type), type);
  }
  if (subtype != nullptr) {
    std::copy_n(mem->subtype, sizeof(mem->subtype), subtype);
  }

  return 0;
} catch (...) {
  return -1;
}

int tpimport(char *istr, long ilen, char **obuf, long *olen, long flags) try {
  if (istr == nullptr) {
    TPERROR(TPEINVAL, "istr is NULL");
    return -1;
  }
  if (obuf == nullptr || *obuf == nullptr) {
    TPERROR(TPEINVAL, "obuf is NULL");
    return -1;
  }

  if (ilen == 0) {
    flags |= TPEX_STRING;
  }

  long needed = sizeof(tpmem);
  if (flags & TPEX_STRING) {
    ilen = strlen(istr);
    if (ilen % 4) {
      TPERROR(TPEPROTO, "Invalid base64 string");
      return -1;
    }
    needed += ilen / 4 * 3;
  } else {
    needed += ilen;
  }

  auto omem = memptr(*obuf);
  if (needed > omem->size) {
    *obuf = tprealloc(*obuf, needed);
    omem = memptr(*obuf);
  }

  if (flags & TPEX_STRING) {
    (void)base64decode(istr, ilen,
                       reinterpret_cast<char *>(omem) + offsetof(tpmem, type),
                       ilen);
  } else {
    std::copy_n(istr, ilen,
                reinterpret_cast<char *>(omem) + offsetof(tpmem, type));
  }

  const auto tptype = typeptr(omem->type, omem->subtype);
  if (tptype == nullptr) {
    return -1;
  }
  if (tptype->reinit != nullptr) {
    tptype->reinit(omem->data, omem->size);
  }

  if (olen != nullptr) {
    *olen = ilen;
  }
  return 0;
} catch (...) {
  TPERROR(TPEPROTO, "Invalid base64 string");
  return -1;
}

int tpexport(char *ibuf, long ilen, char *ostr, long *olen, long flags) try {
  if (ibuf == nullptr || ostr == nullptr || olen == nullptr) {
    TPERROR(TPEINVAL, "Invalid arguments");
    return -1;
  }

  auto mem = memptr(ibuf);
  long used = fux::mem::bufsize(ibuf, ilen);
  if (used == -1) {
    return -1;
  }

  long needed;
  if (flags & TPEX_STRING) {
    needed = base64chars(used) + 1;
  } else {
    needed = used;
  }

  if (*olen < needed) {
    TPERROR(TPELIMIT, "Output buffer too small");
    *olen = needed;
    return -1;
  }

  if (flags & TPEX_STRING) {
    auto n = base64encode(reinterpret_cast<char *>(mem) + offsetof(tpmem, type),
                          used, ostr, *olen);
    ostr[n] = '\0';
  } else {
    std::copy_n(reinterpret_cast<char *>(mem) + offsetof(tpmem, type), used,
                ostr);
  }

  *olen = needed;
  return 0;
} catch (...) {
  return -1;
}

namespace fux {
namespace mem {
void setowner(char *ptr, char **owner) { memptr(ptr)->owner = owner; }

long bufsize(char *ptr, long used) {
  auto mem = memptr(ptr);
  const auto tptype = typeptr(mem->type, mem->subtype);
  if (tptype == nullptr) {
    return -1;
  }
  if (tptype->used != nullptr) {
    return tptype->used(mem->data) + sizeof(*mem) - offsetof(tpmem, type);
  } else if (used != -1) {
    return used + sizeof(*mem) - offsetof(tpmem, type);
  } else {
    return mem->size - offsetof(tpmem, type);
  }
}
}
}
<|endoftext|>


<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-

 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <fnmatch.h>
#include "dnf-reldep.h"
#include "dnf-sack-private.hpp"
#include "hy-subject.h"
#include "hy-iutil-private.hpp"
#include "nevra.hpp"
#include "nsvcap.hpp"
#include "hy-types.h"
#include "hy-query-private.hpp"
#include "hy-selector.h"
#include "hy-util-private.hpp"
#include "sack/query.hpp"
#include "sack/packageset.hpp"

// most specific to least
const HyForm HY_FORMS_MOST_SPEC[] = {
    HY_FORM_NEVRA, HY_FORM_NA, HY_FORM_NAME, HY_FORM_NEVR, HY_FORM_NEV, _HY_FORM_STOP_ };

const HyModuleForm HY_MODULE_FORMS_MOST_SPEC[] = {
        HY_MODULE_FORM_NSVCAP,
        HY_MODULE_FORM_NSVCA,
        HY_MODULE_FORM_NSVAP,
        HY_MODULE_FORM_NSVA,
        HY_MODULE_FORM_NSAP,
        HY_MODULE_FORM_NSA,
        HY_MODULE_FORM_NSVCP,
        HY_MODULE_FORM_NSVP,
        HY_MODULE_FORM_NSVC,
        HY_MODULE_FORM_NSV,
        HY_MODULE_FORM_NSP,
        HY_MODULE_FORM_NS,
        HY_MODULE_FORM_NAP,
        HY_MODULE_FORM_NA,
        HY_MODULE_FORM_NP,
        HY_MODULE_FORM_N,
        _HY_MODULE_FORM_STOP_};

HySubject
hy_subject_create(const char * pattern)
{
    return g_strdup(pattern);
}

void
hy_subject_free(HySubject subject)
{
    g_free(subject);
}

/* Given a subject, attempt to create a query choose the first one, and update
 * the query to try to match it.
 *
 * Since then, it was amended to add a `with_src` flag to avoid finding source packages
 * from provides.
 */
HyQuery
hy_subject_get_best_solution(HySubject subject, DnfSack *sack, HyForm *forms, HyNevra *out_nevra,
                             gboolean icase, gboolean with_nevra, gboolean with_provides,
                             gboolean with_filenames, gboolean with_src)
{
    std::unique_ptr<libdnf::Query> query(new libdnf::Query(sack, libdnf::Query::ExcludeFlags::APPLY_EXCLUDES));
    auto ret = query->filterSubject(subject, forms, icase, with_nevra, with_provides, with_filenames);
    *out_nevra = ret.second.release();
    return query.release();
}

HySelector
hy_subject_get_best_selector(HySubject subject, DnfSack *sack, HyForm *forms, bool obsoletes,
    const char *reponame)
{
    HyNevra nevra{nullptr};
    HyQuery query = hy_subject_get_best_solution(subject, sack, forms, &nevra, FALSE, TRUE, TRUE,
                                                 TRUE, false);
    if (!hy_query_is_empty(query)) {
        if (obsoletes && nevra && nevra->hasJustName()) {
            DnfPackageSet *pset;
            pset = hy_query_run_set(query);
            HyQuery query_obsoletes = hy_query_clone(query);
            hy_query_filter_package_in(query_obsoletes, HY_PKG_OBSOLETES, HY_EQ, pset);
            delete pset;
            hy_query_union(query, query_obsoletes);
            hy_query_free(query_obsoletes);
        }
        if (reponame != NULL) {
            HyQuery installed_query = hy_query_clone(query);
            hy_query_filter(installed_query, HY_PKG_REPONAME, HY_EQ, HY_SYSTEM_REPO_NAME);
            hy_query_filter(query, HY_PKG_REPONAME, HY_EQ, reponame);
            hy_query_union(query, installed_query);
            hy_query_free(installed_query);
        }
    }
    delete nevra;
    HySelector selector = hy_query_to_selector(query);
    hy_query_free(query);
    return selector;
}
<commit_msg>Fix: use with_src in hy_subject_get_best_solution()<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-

 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <fnmatch.h>
#include "dnf-reldep.h"
#include "dnf-sack-private.hpp"
#include "hy-subject.h"
#include "hy-iutil-private.hpp"
#include "nevra.hpp"
#include "nsvcap.hpp"
#include "hy-types.h"
#include "hy-query-private.hpp"
#include "hy-selector.h"
#include "hy-util-private.hpp"
#include "sack/query.hpp"
#include "sack/packageset.hpp"

// most specific to least
const HyForm HY_FORMS_MOST_SPEC[] = {
    HY_FORM_NEVRA, HY_FORM_NA, HY_FORM_NAME, HY_FORM_NEVR, HY_FORM_NEV, _HY_FORM_STOP_ };

const HyModuleForm HY_MODULE_FORMS_MOST_SPEC[] = {
        HY_MODULE_FORM_NSVCAP,
        HY_MODULE_FORM_NSVCA,
        HY_MODULE_FORM_NSVAP,
        HY_MODULE_FORM_NSVA,
        HY_MODULE_FORM_NSAP,
        HY_MODULE_FORM_NSA,
        HY_MODULE_FORM_NSVCP,
        HY_MODULE_FORM_NSVP,
        HY_MODULE_FORM_NSVC,
        HY_MODULE_FORM_NSV,
        HY_MODULE_FORM_NSP,
        HY_MODULE_FORM_NS,
        HY_MODULE_FORM_NAP,
        HY_MODULE_FORM_NA,
        HY_MODULE_FORM_NP,
        HY_MODULE_FORM_N,
        _HY_MODULE_FORM_STOP_};

HySubject
hy_subject_create(const char * pattern)
{
    return g_strdup(pattern);
}

void
hy_subject_free(HySubject subject)
{
    g_free(subject);
}

/* Given a subject, attempt to create a query choose the first one, and update
 * the query to try to match it.
 *
 * Since then, it was amended to add a `with_src` flag to avoid finding source packages
 * from provides.
 */
HyQuery
hy_subject_get_best_solution(HySubject subject, DnfSack *sack, HyForm *forms, HyNevra *out_nevra,
                             gboolean icase, gboolean with_nevra, gboolean with_provides,
                             gboolean with_filenames, gboolean with_src)
{
    std::unique_ptr<libdnf::Query> query(new libdnf::Query(sack, libdnf::Query::ExcludeFlags::APPLY_EXCLUDES));
    if (!with_src)
        query->addFilter(HY_PKG_ARCH, HY_NEQ, "src");
    auto ret = query->filterSubject(subject, forms, icase, with_nevra, with_provides, with_filenames);
    *out_nevra = ret.second.release();
    return query.release();
}

HySelector
hy_subject_get_best_selector(HySubject subject, DnfSack *sack, HyForm *forms, bool obsoletes,
    const char *reponame)
{
    HyNevra nevra{nullptr};
    HyQuery query = hy_subject_get_best_solution(subject, sack, forms, &nevra, FALSE, TRUE, TRUE,
                                                 TRUE, false);
    if (!hy_query_is_empty(query)) {
        if (obsoletes && nevra && nevra->hasJustName()) {
            DnfPackageSet *pset;
            pset = hy_query_run_set(query);
            HyQuery query_obsoletes = hy_query_clone(query);
            hy_query_filter_package_in(query_obsoletes, HY_PKG_OBSOLETES, HY_EQ, pset);
            delete pset;
            hy_query_union(query, query_obsoletes);
            hy_query_free(query_obsoletes);
        }
        if (reponame != NULL) {
            HyQuery installed_query = hy_query_clone(query);
            hy_query_filter(installed_query, HY_PKG_REPONAME, HY_EQ, HY_SYSTEM_REPO_NAME);
            hy_query_filter(query, HY_PKG_REPONAME, HY_EQ, reponame);
            hy_query_union(query, installed_query);
            hy_query_free(installed_query);
        }
    }
    delete nevra;
    HySelector selector = hy_query_to_selector(query);
    hy_query_free(query);
    return selector;
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Common.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Common.h"
#include <random>
#include <boost/algorithm/string/case_conv.hpp>
#include <libdevcore/Base64.h>
#include <libdevcore/Terminal.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libdevcore/SHA3.h>
#include "Exceptions.h"
#include "Params.h"
#include "BlockInfo.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace eth
{

const unsigned c_protocolVersion = 61;
#if ETH_FATDB
const unsigned c_minorProtocolVersion = 3;
const unsigned c_databaseBaseVersion = 9;
const unsigned c_databaseVersionModifier = 1;
#else
const unsigned c_minorProtocolVersion = 2;
const unsigned c_databaseBaseVersion = 9;
const unsigned c_databaseVersionModifier = 0;
#endif

#if ETH_FRONTIER
Network c_network = resetNetwork(Network::Frontier);
#else
Network c_network = resetNetwork(Network::Olympic);
#endif

Network resetNetwork(Network _n)
{
	c_network = _n;
	c_maximumExtraDataSize = c_network == Network::Olympic ? 1024 : 32;
	c_minGasLimit = c_network == Network::Turbo ? 100000000 : 125000;
	c_gasLimitBoundDivisor = 1024;
	c_minimumDifficulty = 131072;
	c_difficultyBoundDivisor = 2048;
	c_durationLimit = c_network == Network::Turbo ? 2 : c_network == Network::Olympic ? 8 : 12;
	c_blockReward = c_network == Network::Olympic ? (1500 * finney) : (5 * ether);
	return _n;
}

const unsigned c_databaseVersion = c_databaseBaseVersion + (c_databaseVersionModifier << 8) + (23 << 9);

vector<pair<u256, string>> const& units()
{
	static const vector<pair<u256, string>> s_units =
	{
		{exp10<54>(), "Uether"},
		{exp10<51>(), "Vether"},
		{exp10<48>(), "Dether"},
		{exp10<45>(), "Nether"},
		{exp10<42>(), "Yether"},
		{exp10<39>(), "Zether"},
		{exp10<36>(), "Eether"},
		{exp10<33>(), "Pether"},
		{exp10<30>(), "Tether"},
		{exp10<27>(), "Gether"},
		{exp10<24>(), "Mether"},
		{exp10<21>(), "grand"},
		{exp10<18>(), "ether"},
		{exp10<15>(), "finney"},
		{exp10<12>(), "szabo"},
		{exp10<9>(), "Gwei"},
		{exp10<6>(), "Mwei"},
		{exp10<3>(), "Kwei"},
		{exp10<0>(), "wei"}
	};

	return s_units;
}

std::string formatBalance(bigint const& _b)
{
	ostringstream ret;
	u256 b;
	if (_b < 0)
	{
		ret << "-";
		b = (u256)-_b;
	}
	else
		b = (u256)_b;

	if (b > units()[0].first * 10000)
	{
		ret << (b / units()[0].first) << " " << units()[0].second;
		return ret.str();
	}
	ret << setprecision(5);
	for (auto const& i: units())
		if (i.first != 1 && b >= i.first * 100)
		{
			ret << (double(b / (i.first / 1000)) / 1000.0) << " " << i.second;
			return ret.str();
		}
	ret << b << " wei";
	return ret.str();
}

static void badBlockInfo(BlockInfo const& _bi, string const& _err)
{
	string const c_line = EthReset EthOnMaroon + string(80, ' ') + EthReset;
	string const c_border = EthReset EthOnMaroon + string(2, ' ') + EthReset EthMaroonBold;
	string const c_space = c_border + string(76, ' ') + c_border + EthReset;
	stringstream ss;
	ss << c_line << endl;
	ss << c_space << endl;
	ss << c_border + "  Import Failure     " + _err + string(max<int>(0, 53 - _err.size()), ' ') + "  " + c_border << endl;
	ss << c_space << endl;
	string bin = toString(_bi.number());
	ss << c_border + ("                     Guru Meditation #" + string(max<int>(0, 8 - bin.size()), '0') + bin + "." + _bi.hash().abridged() + "                    ") + c_border << endl;
	ss << c_space << endl;
	ss << c_line;
	cwarn << "\n" + ss.str();
}

void badBlock(bytesConstRef _block, string const& _err)
{
	BlockInfo bi;
	DEV_IGNORE_EXCEPTIONS(bi = BlockInfo(_block, CheckNothing));
	badBlockInfo(bi, _err);
}

}
}
<commit_msg>decrase minblockGasLimit to 5000 for frontier<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Common.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Common.h"
#include <random>
#include <boost/algorithm/string/case_conv.hpp>
#include <libdevcore/Base64.h>
#include <libdevcore/Terminal.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libdevcore/SHA3.h>
#include "Exceptions.h"
#include "Params.h"
#include "BlockInfo.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace eth
{

const unsigned c_protocolVersion = 61;
#if ETH_FATDB
const unsigned c_minorProtocolVersion = 3;
const unsigned c_databaseBaseVersion = 9;
const unsigned c_databaseVersionModifier = 1;
#else
const unsigned c_minorProtocolVersion = 2;
const unsigned c_databaseBaseVersion = 9;
const unsigned c_databaseVersionModifier = 0;
#endif

#if ETH_FRONTIER
Network c_network = resetNetwork(Network::Frontier);
#else
Network c_network = resetNetwork(Network::Olympic);
#endif

Network resetNetwork(Network _n)
{
	c_network = _n;
	c_maximumExtraDataSize = c_network == Network::Olympic ? 1024 : 32;
	c_minGasLimit = c_network == Network::Turbo ? 100000000 : 5000;
	c_gasLimitBoundDivisor = 1024;
	c_minimumDifficulty = 131072;
	c_difficultyBoundDivisor = 2048;
	c_durationLimit = c_network == Network::Turbo ? 2 : c_network == Network::Olympic ? 8 : 12;
	c_blockReward = c_network == Network::Olympic ? (1500 * finney) : (5 * ether);
	return _n;
}

const unsigned c_databaseVersion = c_databaseBaseVersion + (c_databaseVersionModifier << 8) + (23 << 9);

vector<pair<u256, string>> const& units()
{
	static const vector<pair<u256, string>> s_units =
	{
		{exp10<54>(), "Uether"},
		{exp10<51>(), "Vether"},
		{exp10<48>(), "Dether"},
		{exp10<45>(), "Nether"},
		{exp10<42>(), "Yether"},
		{exp10<39>(), "Zether"},
		{exp10<36>(), "Eether"},
		{exp10<33>(), "Pether"},
		{exp10<30>(), "Tether"},
		{exp10<27>(), "Gether"},
		{exp10<24>(), "Mether"},
		{exp10<21>(), "grand"},
		{exp10<18>(), "ether"},
		{exp10<15>(), "finney"},
		{exp10<12>(), "szabo"},
		{exp10<9>(), "Gwei"},
		{exp10<6>(), "Mwei"},
		{exp10<3>(), "Kwei"},
		{exp10<0>(), "wei"}
	};

	return s_units;
}

std::string formatBalance(bigint const& _b)
{
	ostringstream ret;
	u256 b;
	if (_b < 0)
	{
		ret << "-";
		b = (u256)-_b;
	}
	else
		b = (u256)_b;

	if (b > units()[0].first * 10000)
	{
		ret << (b / units()[0].first) << " " << units()[0].second;
		return ret.str();
	}
	ret << setprecision(5);
	for (auto const& i: units())
		if (i.first != 1 && b >= i.first * 100)
		{
			ret << (double(b / (i.first / 1000)) / 1000.0) << " " << i.second;
			return ret.str();
		}
	ret << b << " wei";
	return ret.str();
}

static void badBlockInfo(BlockInfo const& _bi, string const& _err)
{
	string const c_line = EthReset EthOnMaroon + string(80, ' ') + EthReset;
	string const c_border = EthReset EthOnMaroon + string(2, ' ') + EthReset EthMaroonBold;
	string const c_space = c_border + string(76, ' ') + c_border + EthReset;
	stringstream ss;
	ss << c_line << endl;
	ss << c_space << endl;
	ss << c_border + "  Import Failure     " + _err + string(max<int>(0, 53 - _err.size()), ' ') + "  " + c_border << endl;
	ss << c_space << endl;
	string bin = toString(_bi.number());
	ss << c_border + ("                     Guru Meditation #" + string(max<int>(0, 8 - bin.size()), '0') + bin + "." + _bi.hash().abridged() + "                    ") + c_border << endl;
	ss << c_space << endl;
	ss << c_line;
	cwarn << "\n" + ss.str();
}

void badBlock(bytesConstRef _block, string const& _err)
{
	BlockInfo bi;
	DEV_IGNORE_EXCEPTIONS(bi = BlockInfo(_block, CheckNothing));
	badBlockInfo(bi, _err);
}

}
}
<|endoftext|>


<commit_before>
#include <libdevcrypto/SHA3.h>
#include <libevm/FeeStructure.h>
#include <libevm/ExtVMFace.h>

#include <evmjit/libevmjit/Utils.h>

extern "C"
{
	#ifdef _MSC_VER
		#define EXPORT __declspec(dllexport)
	#else
		#define EXPORT
	#endif

	using namespace dev;
	using namespace dev::eth;
	using jit::i256;
	using jit::eth2llvm;

	EXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value)
	{
		auto index = llvm2eth(*_index);
		auto value = _env->store(index); // Interface uses native endianness
		*o_value = eth2llvm(value);
	}

	EXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value)
	{
		auto index = llvm2eth(*_index);
		auto value = llvm2eth(*_value);

		if (value == 0 && _env->store(index) != 0)	// If delete
			_env->sub.refunds += c_sstoreRefundGas;	// Increase refund counter

		_env->setStore(index, value);	// Interface uses native endianness
	}

	EXPORT void ext_balance(ExtVMFace* _env, h256* _address, i256* o_value)
	{
		auto u = _env->balance(right160(*_address));
		*o_value = eth2llvm(u);
	}

	EXPORT void ext_suicide(ExtVMFace* _env, h256 const* _address)
	{
		_env->suicide(right160(*_address));
	}

	EXPORT void env_create(ExtVMFace* _env, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address)
	{
		assert(_env->depth < 1024);	// TODO: Handle call depth

		auto endowment = llvm2eth(*_endowment);

		if (_env->balance(_env->myAddress) >= endowment)
		{
			_env->subBalance(endowment);
			u256 gas;   // TODO: Handle gas
			OnOpFunc onOp {}; // TODO: Handle that thing
			h256 address(_env->create(endowment, gas, {_initBeg, _initSize}, onOp), h256::AlignRight);
			*o_address = address;
		}
		else
			*o_address = {};
	}

	EXPORT bool env_call(ExtVMFace* _env, i256* io_gas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress)
	{
		if (_env->depth == 1024)
			jit::terminate(jit::ReturnCode::OutOfGas);

		assert(_env->depth < 1024);	// TODO: Handle call depth

		auto value = llvm2eth(*_value);
		if (_env->balance(_env->myAddress) >= value)
		{
			_env->subBalance(value);
			auto receiveAddress = right160(*_receiveAddress);
			auto inRef = bytesConstRef{_inBeg, _inSize};
			auto outRef = bytesConstRef{_outBeg, _outSize};
			OnOpFunc onOp {}; // TODO: Handle that thing
			auto codeAddress = right160(*_codeAddress);
			auto gas = llvm2eth(*io_gas);
			auto ret = _env->call(receiveAddress, value, inRef, gas, outRef, onOp, {}, codeAddress);
			*io_gas = eth2llvm(gas);
			return ret;
		}

		return false;
	}

	EXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash)
	{
		auto hash = sha3({_begin, _size});
		*o_hash = hash;
	}

	EXPORT byte const* env_getExtCode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		*o_size = code.size();
		return code.data();
	}

	EXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4)
	{
		dev::h256s topics;

		if (_topic1)
			topics.push_back(*_topic1);

		if (_topic2)
			topics.push_back(*_topic2);

		if (_topic3)
			topics.push_back(*_topic3);

		if (_topic4)
			topics.push_back(*_topic4);

		_env->log(std::move(topics), {_beg, _size});
	}
}

<commit_msg>Remove TODO comment<commit_after>
#include <libdevcrypto/SHA3.h>
#include <libevm/FeeStructure.h>
#include <libevm/ExtVMFace.h>

#include <evmjit/libevmjit/Utils.h>

extern "C"
{
	#ifdef _MSC_VER
		#define EXPORT __declspec(dllexport)
	#else
		#define EXPORT
	#endif

	using namespace dev;
	using namespace dev::eth;
	using jit::i256;
	using jit::eth2llvm;

	EXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value)
	{
		auto index = llvm2eth(*_index);
		auto value = _env->store(index); // Interface uses native endianness
		*o_value = eth2llvm(value);
	}

	EXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value)
	{
		auto index = llvm2eth(*_index);
		auto value = llvm2eth(*_value);

		if (value == 0 && _env->store(index) != 0)	// If delete
			_env->sub.refunds += c_sstoreRefundGas;	// Increase refund counter

		_env->setStore(index, value);	// Interface uses native endianness
	}

	EXPORT void ext_balance(ExtVMFace* _env, h256* _address, i256* o_value)
	{
		auto u = _env->balance(right160(*_address));
		*o_value = eth2llvm(u);
	}

	EXPORT void ext_suicide(ExtVMFace* _env, h256 const* _address)
	{
		_env->suicide(right160(*_address));
	}

	EXPORT void env_create(ExtVMFace* _env, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address)
	{
		assert(_env->depth < 1024);	// TODO: Handle call depth

		auto endowment = llvm2eth(*_endowment);

		if (_env->balance(_env->myAddress) >= endowment)
		{
			_env->subBalance(endowment);
			u256 gas;   // TODO: Handle gas
			OnOpFunc onOp {}; // TODO: Handle that thing
			h256 address(_env->create(endowment, gas, {_initBeg, _initSize}, onOp), h256::AlignRight);
			*o_address = address;
		}
		else
			*o_address = {};
	}

	EXPORT bool env_call(ExtVMFace* _env, i256* io_gas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress)
	{
		if (_env->depth == 1024)
			jit::terminate(jit::ReturnCode::OutOfGas);

		assert(_env->depth < 1024);

		auto value = llvm2eth(*_value);
		if (_env->balance(_env->myAddress) >= value)
		{
			_env->subBalance(value);
			auto receiveAddress = right160(*_receiveAddress);
			auto inRef = bytesConstRef{_inBeg, _inSize};
			auto outRef = bytesConstRef{_outBeg, _outSize};
			OnOpFunc onOp {}; // TODO: Handle that thing
			auto codeAddress = right160(*_codeAddress);
			auto gas = llvm2eth(*io_gas);
			auto ret = _env->call(receiveAddress, value, inRef, gas, outRef, onOp, {}, codeAddress);
			*io_gas = eth2llvm(gas);
			return ret;
		}

		return false;
	}

	EXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash)
	{
		auto hash = sha3({_begin, _size});
		*o_hash = hash;
	}

	EXPORT byte const* env_getExtCode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		*o_size = code.size();
		return code.data();
	}

	EXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4)
	{
		dev::h256s topics;

		if (_topic1)
			topics.push_back(*_topic1);

		if (_topic2)
			topics.push_back(*_topic2);

		if (_topic3)
			topics.push_back(*_topic3);

		if (_topic4)
			topics.push_back(*_topic4);

		_env->log(std::move(topics), {_beg, _size});
	}
}

<|endoftext|>


<commit_before>#include "template_type.hpp"

using namespace mstch;

template_type::template_type(const std::string& str) {
  tokenize(str);
  strip_whitespace();
}

void template_type::process_text(citer begin, citer end) {
  if (begin == end)
    return;
  auto start = begin;
  for (auto it = begin; it != end; ++it)
    if (*it == '\n' || it == end - 1) {
      tokens.push_back({{start, it + 1}});
      start = it + 1;
    }
}

void template_type::tokenize(const std::string& tmp) {
  std::string open{"{{"}, close{"}}"};
  citer beg = tmp.begin();
  auto npos = std::string::npos;

  for (unsigned long long cur_pos = 0; cur_pos < tmp.size();) {
    auto open_pos = tmp.find(open, cur_pos);
    auto close_pos = tmp.find(
        close, open_pos == npos ? open_pos : open_pos + 1);

    if (close_pos != npos && open_pos != npos) {
      if (*(beg + open_pos + open.size()) == '{' &&
          *(beg + close_pos + close.size()) == '}')
        ++close_pos;

      process_text(beg + cur_pos, beg + open_pos);
      cur_pos = close_pos + close.size();
      tokens.push_back({{beg + open_pos, beg + close_pos + close.size()},
          open.size(), close.size()});

      if(cur_pos == tmp.size()) {
        tokens.push_back({{""}});
        tokens.back().eol(true);
      }

      if (*(beg + open_pos + open.size()) == '=' &&
          *(beg + close_pos - 1) == '=')
      {
        auto tok_beg = beg + open_pos + open.size() + 1;
        auto tok_end = beg + close_pos - 1;
        auto front_skip = first_not_ws(tok_beg, tok_end);
        auto back_skip = first_not_ws(reverse(tok_end), reverse(tok_beg));
        open = {front_skip, beg + tmp.find(' ', front_skip - beg)};
        close = {beg + tmp.rfind(' ', back_skip - beg) + 1, back_skip + 1};
      }
    } else {
      process_text(beg + cur_pos, tmp.end());
      cur_pos = close_pos;
    }
  }
}

void template_type::strip_whitespace() {
  auto line_begin = tokens.begin();
  bool has_tag = false, non_space = false;

  for (auto it = tokens.begin(); it != tokens.end(); ++it) {
    auto type = (*it).token_type();
    if (type != token::type::text && type != token::type::variable &&
        type != token::type::unescaped_variable)
      has_tag = true;
    else if (!(*it).ws_only())
      non_space = true;

    if ((*it).eol()) {
      if (has_tag && !non_space) {
        store_prefixes(line_begin);

        auto c = line_begin;
        for (bool end = false; !end; c = (*c).ws_only() ? tokens.erase(c) : ++c)
          if ((end = (*c).eol()))
            it = c - 1;
      }

      non_space = has_tag = false;
      line_begin = it + 1;
    }
  }
}

void template_type::store_prefixes(std::vector<token>::iterator beg) {
  for (auto cur = beg; !(*cur).eol(); ++cur)
    if ((*cur).token_type() == token::type::partial &&
        cur != beg && (*(cur - 1)).ws_only())
      (*cur).partial_prefix((*(cur - 1)).raw());
}
<commit_msg>fix unnecessary assignment<commit_after>#include "template_type.hpp"

using namespace mstch;

template_type::template_type(const std::string& str) {
  tokenize(str);
  strip_whitespace();
}

void template_type::process_text(citer begin, citer end) {
  if (begin == end)
    return;
  auto start = begin;
  for (auto it = begin; it != end; ++it)
    if (*it == '\n' || it == end - 1) {
      tokens.push_back({{start, it + 1}});
      start = it + 1;
    }
}

void template_type::tokenize(const std::string& tmp) {
  std::string open{"{{"}, close{"}}"};
  citer beg = tmp.begin();
  auto npos = std::string::npos;

  for (unsigned long long cur_pos = 0; cur_pos < tmp.size();) {
    auto open_pos = tmp.find(open, cur_pos);
    auto close_pos = tmp.find(
        close, open_pos == npos ? open_pos : open_pos + 1);

    if (close_pos != npos && open_pos != npos) {
      if (*(beg + open_pos + open.size()) == '{' &&
          *(beg + close_pos + close.size()) == '}')
        ++close_pos;

      process_text(beg + cur_pos, beg + open_pos);
      cur_pos = close_pos + close.size();
      tokens.push_back({{beg + open_pos, beg + close_pos + close.size()},
          open.size(), close.size()});

      if(cur_pos == tmp.size()) {
        tokens.push_back({{""}});
        tokens.back().eol(true);
      }

      if (*(beg + open_pos + open.size()) == '=' &&
          *(beg + close_pos - 1) == '=')
      {
        auto tok_beg = beg + open_pos + open.size() + 1;
        auto tok_end = beg + close_pos - 1;
        auto front_skip = first_not_ws(tok_beg, tok_end);
        auto back_skip = first_not_ws(reverse(tok_end), reverse(tok_beg));
        open = {front_skip, beg + tmp.find(' ', front_skip - beg)};
        close = {beg + tmp.rfind(' ', back_skip - beg) + 1, back_skip + 1};
      }
    } else {
      process_text(beg + cur_pos, tmp.end());
      cur_pos = close_pos;
    }
  }
}

void template_type::strip_whitespace() {
  auto line_begin = tokens.begin();
  bool has_tag = false, non_space = false;

  for (auto it = tokens.begin(); it != tokens.end(); ++it) {
    auto type = (*it).token_type();
    if (type != token::type::text && type != token::type::variable &&
        type != token::type::unescaped_variable)
      has_tag = true;
    else if (!(*it).ws_only())
      non_space = true;

    if ((*it).eol()) {
      if (has_tag && !non_space) {
        store_prefixes(line_begin);

        auto c = line_begin;
        for (bool end = false; !end; (*c).ws_only() ? c = tokens.erase(c) : ++c)
          if ((end = (*c).eol()))
            it = c - 1;
      }

      non_space = has_tag = false;
      line_begin = it + 1;
    }
  }
}

void template_type::store_prefixes(std::vector<token>::iterator beg) {
  for (auto cur = beg; !(*cur).eol(); ++cur)
    if ((*cur).token_type() == token::type::partial &&
        cur != beg && (*(cur - 1)).ws_only())
      (*cur).partial_prefix((*(cur - 1)).raw());
}
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2011 New Dream Network
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "test/unit.h"
#include "common/Formatter.h"

#include <sstream>
#include <string>

using std::ostringstream;

TEST(JsonFormatter, Simple1) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.dump_int("a", 1);
  fmt.dump_int("b", 2);
  fmt.dump_int("c", 3);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "{\"a\":1,\"b\":2,\"c\":3}");
}

TEST(JsonFormatter, Simple2) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.open_object_section("bar");
  fmt.dump_int("int", 0xf00000000000ll);
  fmt.dump_unsigned("unsigned", 0x8000000000000001llu);
  fmt.dump_float("float", 1.234);
  fmt.close_section();
  fmt.dump_string("string", "str");
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "{\"bar\":{\"int\":263882790666240,\
\"unsigned\":9223372036854775809,\"float\":\"1.234000\"},\
\"string\":\"str\"}");
}

TEST(JsonFormatter, Empty) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "");
}

TEST(XmlFormatter, Simple1) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.dump_int("a", 1);
  fmt.dump_int("b", 2);
  fmt.dump_int("c", 3);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo>12<c>3</c></foo>");
}

TEST(XmlFormatter, Simple2) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.open_object_section("bar");
  fmt.dump_int("int", 0xf00000000000ll);
  fmt.dump_unsigned("unsigned", 0x8000000000000001llu);
  fmt.dump_float("float", 1.234);
  fmt.close_section();
  fmt.dump_string("string", "str");
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><bar>\
<int>263882790666240</int>\
<unsigned>9223372036854775809</unsigned>\
<float>1.234</float>\
</bar><string>str</string>\
</foo>");
}

TEST(XmlFormatter, Empty) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "");
}

TEST(XmlFormatter, DumpStream1) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.dump_stream("blah") << "hithere";
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<blah>hithere</blah>");
}

TEST(XmlFormatter, DumpStream2) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><blah>hithere</blah></foo>");
}

TEST(XmlFormatter, DumpStream3) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.dump_float("pi", 3.14);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><blah>hithere</blah><pi>3.14</pi></foo>");
}

TEST(XmlFormatter, DTD) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.write_raw_data(XMLFormatter::XML_1_DTD);
  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.dump_float("pi", 3.14);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    "<foo><blah>hithere</blah><pi>3.14</pi></foo>");
}
<commit_msg>test/formatter: test stream clearing<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2011 New Dream Network
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "test/unit.h"
#include "common/Formatter.h"

#include <sstream>
#include <string>

using std::ostringstream;

TEST(JsonFormatter, Simple1) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.dump_int("a", 1);
  fmt.dump_int("b", 2);
  fmt.dump_int("c", 3);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "{\"a\":1,\"b\":2,\"c\":3}");
}

TEST(JsonFormatter, Simple2) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.open_object_section("bar");
  fmt.dump_int("int", 0xf00000000000ll);
  fmt.dump_unsigned("unsigned", 0x8000000000000001llu);
  fmt.dump_float("float", 1.234);
  fmt.close_section();
  fmt.dump_string("string", "str");
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "{\"bar\":{\"int\":263882790666240,\
\"unsigned\":9223372036854775809,\"float\":\"1.234000\"},\
\"string\":\"str\"}");
}

TEST(JsonFormatter, Empty) {
  ostringstream oss;
  JSONFormatter fmt(false);
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "");
}

TEST(XmlFormatter, Simple1) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.dump_int("a", 1);
  fmt.dump_int("b", 2);
  fmt.dump_int("c", 3);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo>12<c>3</c></foo>");
}

TEST(XmlFormatter, Simple2) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.open_object_section("foo");
  fmt.open_object_section("bar");
  fmt.dump_int("int", 0xf00000000000ll);
  fmt.dump_unsigned("unsigned", 0x8000000000000001llu);
  fmt.dump_float("float", 1.234);
  fmt.close_section();
  fmt.dump_string("string", "str");
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><bar>\
<int>263882790666240</int>\
<unsigned>9223372036854775809</unsigned>\
<float>1.234</float>\
</bar><string>str</string>\
</foo>");
}

TEST(XmlFormatter, Empty) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "");
}

TEST(XmlFormatter, DumpStream1) {
  ostringstream oss;
  XMLFormatter fmt(false);
  fmt.dump_stream("blah") << "hithere";
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<blah>hithere</blah>");
}

TEST(XmlFormatter, DumpStream2) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><blah>hithere</blah></foo>");
}

TEST(XmlFormatter, DumpStream3) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.dump_float("pi", 3.14);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<foo><blah>hithere</blah><pi>3.14</pi></foo>");
}

TEST(XmlFormatter, DTD) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.write_raw_data(XMLFormatter::XML_1_DTD);
  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.dump_float("pi", 3.14);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    "<foo><blah>hithere</blah><pi>3.14</pi></foo>");
}

TEST(XmlFormatter, Clear) {
  ostringstream oss;
  XMLFormatter fmt(false);

  fmt.write_raw_data(XMLFormatter::XML_1_DTD);
  fmt.open_array_section("foo");
  fmt.dump_stream("blah") << "hithere";
  fmt.dump_float("pi", 3.14);
  fmt.close_section();
  fmt.flush(oss);
  ASSERT_EQ(oss.str(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    "<foo><blah>hithere</blah><pi>3.14</pi></foo>");

  ostringstream oss2;
  fmt.flush(oss2);
  ASSERT_EQ(oss2.str(), "");

  ostringstream oss3;
  fmt.reset();
  fmt.flush(oss3);
  ASSERT_EQ(oss3.str(), "");
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <test/fuzz/fuzz.h>

#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string random_hex_string(buffer.begin(), buffer.end());
    const std::vector<unsigned char> data = ParseHex(random_hex_string);
    const std::string hex_data = HexStr(data);
    if (IsHex(random_hex_string)) {
        assert(ToLower(random_hex_string) == hex_data);
    }
}
<commit_msg>tests: Fuzz additional functions in the hex fuzzing harness<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <core_io.h>
#include <primitives/block.h>
#include <rpc/util.h>
#include <test/fuzz/fuzz.h>
#include <uint256.h>
#include <univalue.h>
#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string random_hex_string(buffer.begin(), buffer.end());
    const std::vector<unsigned char> data = ParseHex(random_hex_string);
    const std::string hex_data = HexStr(data);
    if (IsHex(random_hex_string)) {
        assert(ToLower(random_hex_string) == hex_data);
    }
    (void)IsHexNumber(random_hex_string);
    uint256 result;
    (void)ParseHashStr(random_hex_string, result);
    (void)uint256S(random_hex_string);
    try {
        (void)HexToPubKey(random_hex_string);
    } catch (const UniValue&) {
    }
    CBlockHeader block_header;
    (void)DecodeHexBlockHeader(block_header, random_hex_string);
}
<|endoftext|>


<commit_before>//
// Created by Jannis Hoppe on 28.01.16.
//

#include "../utils/fft_lib.h"
#include "gtest/gtest.h"

TEST(FftLibTest,FftTest) {
    taylortrack::utils::FftLib::CArray vec(16);
    vec[0] = 1;
    vec[1] = 1;
    vec[2] = 1;
    vec[3] = 1;
    vec[4] = 0;
    vec[5] = 7;
    vec[6] = 2;
    vec[7] = 2;
    vec[8] = 2;
    vec[9] = 2;
    vec[10] = 1;
    vec[11] = 1;
    vec[12] = 1;
    vec[13] = 0;
    vec[14] = 7;
    vec[15] = 2;

    taylortrack::utils::FftLib::fft(vec);
    for (int i=0;i<16;i++){
        std::cout << vec[i]<< "\n";
    }
    // testing real parts
    ASSERT_TRUE(std::abs(vec[0].real()-15) < 0.0001);
    ASSERT_TRUE(std::abs(vec[1].real()+2.5355) < 0.0001);
    ASSERT_TRUE(std::abs(vec[2].real()+2.0000) < 0.0001);
    ASSERT_TRUE(std::abs(vec[3].real()-4.5355) < 0.0001);
    ASSERT_TRUE(std::abs(vec[4].real()+7) < 0.0001);
    ASSERT_TRUE(std::abs(vec[5].real()-4.5355) < 0.0001);
    ASSERT_TRUE(std::abs(vec[6].real()+2) < 0.0001);
    ASSERT_TRUE(std::abs(vec[7].real()+2.5355) < 0.0001);
    // testing complex parts
    ASSERT_TRUE(std::abs(vec[0].imag()) < 0.0001);
    ASSERT_TRUE(std::abs(vec[1].imag()-5.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[2].imag()+5) < 0.0001);
    ASSERT_TRUE(std::abs(vec[3].imag()-3.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[4].imag()) < 0.0001);
    ASSERT_TRUE(std::abs(vec[5].imag()+3.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[6].imag()-5) < 0.0001);
    ASSERT_TRUE(std::abs(vec[7].imag()+5.9497) < 0.0001);

};

TEST(FftLibTest,IfftTest) {
    taylortrack::utils::FftLib::CArray vec(8);
    vec[0] = 1;
    vec[1] = 1;
    vec[2] = 1;
    vec[3] = 1;
    vec[4] = 0;
    vec[5] = 7;
    vec[6] = 2;
    vec[7] = 2;

    taylortrack::utils::FftLib::fft(vec);
    taylortrack::utils::FftLib::ifft(vec);
    ASSERT_TRUE(vec[0].real()-1 < 0.0001);
    ASSERT_TRUE(vec[1].real()-1 < 0.0001);
    ASSERT_TRUE(vec[2].real()-1 < 0.0001);
    ASSERT_TRUE(vec[3].real()-1 < 0.0001);
    ASSERT_TRUE(vec[4].real() < 0.0001);
    ASSERT_TRUE(vec[5].real()-7 < 0.0001);
    ASSERT_TRUE(vec[6].real()-2 < 0.0001);
    ASSERT_TRUE(vec[7].real()-2 < 0.0001);
    ASSERT_TRUE(std::abs(vec[0].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[1].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[2].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[3].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[4].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[5].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[6].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[7].imag()) < 0.00001);

};

TEST(FftLibTest,Circshifttest) {
    taylortrack::utils::FftLib::RArray vec(6);
    taylortrack::utils::FftLib::RArray outvec(6);
    vec[0] = 1;
    vec[1] = 2;
    vec[2] = 3;
    vec[3] = 4;
    vec[4] = 5;
    vec[5] = 6;
    outvec[0] = 1;
    outvec[1] = 2;
    outvec[2] = 3;
    outvec[3] = 4;
    outvec[4] = 5;
    outvec[5] = 6;

    taylortrack::utils::FftLib::circshift(outvec,vec,1,6,0,2);

    ASSERT_EQ(outvec[0],5);
    ASSERT_EQ(outvec[1],6);
    ASSERT_EQ(outvec[2],1);
    ASSERT_EQ(outvec[3],2);
    ASSERT_EQ(outvec[4],3);
    ASSERT_EQ(outvec[5],4);
}

TEST(FftLibTest,Fftshifttest) {
    taylortrack::utils::FftLib::RArray vec(6);
    taylortrack::utils::FftLib::RArray outvec(6);
    vec[0] = 1;
    vec[1] = 2;
    vec[2] = 3;
    vec[3] = 4;
    vec[4] = 5;
    vec[5] = 6;
    outvec[0] = 1;
    outvec[1] = 2;
    outvec[2] = 3;
    outvec[3] = 4;
    outvec[4] = 5;
    outvec[5] = 6;

    taylortrack::utils::FftLib::fftshift(outvec,vec);

    ASSERT_EQ(outvec[0],4);
    ASSERT_EQ(outvec[1],5);
    ASSERT_EQ(outvec[2],6);
    ASSERT_EQ(outvec[3],1);
    ASSERT_EQ(outvec[4],2);
    ASSERT_EQ(outvec[5],3);
}

// suspected memory errors in this test
TEST(FftLibTest,Zeropadding_Test) {
    taylortrack::utils::FftLib::CArray vec(8);
    taylortrack::utils::FftLib::CArray newvec(16);
    vec[0] = 0.1;
    vec[1] = 0.2;
    vec[2] = 0.3;
    vec[3] = 0.4;
    vec[4] = 0.5;
    vec[5] = 0.6;
    vec[6] = 0.7;
    vec[7] = 0.8;
    newvec = taylortrack::utils::FftLib::zeropadding(vec,8);
    //taylortrack::utils::FftLib::fft(newvec);
    for (int i=0;i<16;i++){
        std::cout << newvec[i]<< "\n";
    }
    ASSERT_EQ(newvec.size(),16);
    ASSERT_EQ(newvec[0].real(),0.1);
    ASSERT_EQ(newvec[1].real(),0.2);
    ASSERT_EQ(newvec[2].real(),0.3);
    ASSERT_EQ(newvec[3].real(),0.4);
    ASSERT_EQ(newvec[4].real(),0.5);
    ASSERT_EQ(newvec[5].real(),0.6);
    ASSERT_EQ(newvec[6].real(),0.7);
    ASSERT_EQ(newvec[7].real(),0.8);
    ASSERT_EQ(newvec[8].real(),0);
    ASSERT_EQ(newvec[9].real(),0);
    ASSERT_EQ(newvec[10].real(),0);
}<commit_msg>fixed fft test<commit_after>//
// Created by Jannis Hoppe on 28.01.16.
//

#include "../utils/fft_lib.h"
#include "gtest/gtest.h"

TEST(FftLibTest,FftTest) {
    taylortrack::utils::FftLib::CArray vec(8);
    vec[0] = 1;
    vec[1] = 1;
    vec[2] = 1;
    vec[3] = 1;
    vec[4] = 0;
    vec[5] = 7;
    vec[6] = 2;
    vec[7] = 2;

    taylortrack::utils::FftLib::fft(vec);
    // testing real parts
    ASSERT_TRUE(std::abs(vec[0].real()-15) < 0.0001);
    ASSERT_TRUE(std::abs(vec[1].real()+2.53553) < 0.0001);
    ASSERT_TRUE(std::abs(vec[2].real()+2) < 0.0001);
    ASSERT_TRUE(std::abs(vec[3].real()-4.53553) < 0.0001);
    ASSERT_TRUE(std::abs(vec[4].real()+7) < 0.0001);
    ASSERT_TRUE(std::abs(vec[5].real()-4.53553) < 0.0001);
    ASSERT_TRUE(std::abs(vec[6].real()+2) < 0.0001);
    ASSERT_TRUE(std::abs(vec[7].real()+2.53553) < 0.0001);
    // testing complex parts
    ASSERT_TRUE(std::abs(vec[0].imag()) < 0.0001);
    ASSERT_TRUE(std::abs(vec[1].imag()-5.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[2].imag()+5) < 0.0001);
    ASSERT_TRUE(std::abs(vec[3].imag()-3.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[4].imag()) < 0.0001);
    ASSERT_TRUE(std::abs(vec[5].imag()+3.9497) < 0.0001);
    ASSERT_TRUE(std::abs(vec[6].imag()-5) < 0.0001);
    ASSERT_TRUE(std::abs(vec[7].imag()+5.9497) < 0.0001);

};

TEST(FftLibTest,IfftTest) {
    taylortrack::utils::FftLib::CArray vec(8);
    vec[0] = 1;
    vec[1] = 1;
    vec[2] = 1;
    vec[3] = 1;
    vec[4] = 0;
    vec[5] = 7;
    vec[6] = 2;
    vec[7] = 2;

    taylortrack::utils::FftLib::fft(vec);
    taylortrack::utils::FftLib::ifft(vec);
    ASSERT_TRUE(vec[0].real()-1 < 0.0001);
    ASSERT_TRUE(vec[1].real()-1 < 0.0001);
    ASSERT_TRUE(vec[2].real()-1 < 0.0001);
    ASSERT_TRUE(vec[3].real()-1 < 0.0001);
    ASSERT_TRUE(vec[4].real() < 0.0001);
    ASSERT_TRUE(vec[5].real()-7 < 0.0001);
    ASSERT_TRUE(vec[6].real()-2 < 0.0001);
    ASSERT_TRUE(vec[7].real()-2 < 0.0001);
    ASSERT_TRUE(std::abs(vec[0].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[1].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[2].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[3].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[4].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[5].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[6].imag()) < 0.00001);
    ASSERT_TRUE(std::abs(vec[7].imag()) < 0.00001);

};

TEST(FftLibTest,Circshifttest) {
    taylortrack::utils::FftLib::RArray vec(6);
    taylortrack::utils::FftLib::RArray outvec(6);
    vec[0] = 1;
    vec[1] = 2;
    vec[2] = 3;
    vec[3] = 4;
    vec[4] = 5;
    vec[5] = 6;
    outvec[0] = 1;
    outvec[1] = 2;
    outvec[2] = 3;
    outvec[3] = 4;
    outvec[4] = 5;
    outvec[5] = 6;

    taylortrack::utils::FftLib::circshift(outvec,vec,1,6,0,2);

    ASSERT_EQ(outvec[0],5);
    ASSERT_EQ(outvec[1],6);
    ASSERT_EQ(outvec[2],1);
    ASSERT_EQ(outvec[3],2);
    ASSERT_EQ(outvec[4],3);
    ASSERT_EQ(outvec[5],4);
}

TEST(FftLibTest,Fftshifttest) {
    taylortrack::utils::FftLib::RArray vec(6);
    taylortrack::utils::FftLib::RArray outvec(6);
    vec[0] = 1;
    vec[1] = 2;
    vec[2] = 3;
    vec[3] = 4;
    vec[4] = 5;
    vec[5] = 6;
    outvec[0] = 1;
    outvec[1] = 2;
    outvec[2] = 3;
    outvec[3] = 4;
    outvec[4] = 5;
    outvec[5] = 6;

    taylortrack::utils::FftLib::fftshift(outvec,vec);

    ASSERT_EQ(outvec[0],4);
    ASSERT_EQ(outvec[1],5);
    ASSERT_EQ(outvec[2],6);
    ASSERT_EQ(outvec[3],1);
    ASSERT_EQ(outvec[4],2);
    ASSERT_EQ(outvec[5],3);
}

// suspected memory errors in this test
TEST(FftLibTest,Zeropadding_Test) {
    taylortrack::utils::FftLib::CArray vec(8);
    taylortrack::utils::FftLib::CArray newvec(16);
    vec[0] = 0.1;
    vec[1] = 0.2;
    vec[2] = 0.3;
    vec[3] = 0.4;
    vec[4] = 0.5;
    vec[5] = 0.6;
    vec[6] = 0.7;
    vec[7] = 0.8;
    newvec = taylortrack::utils::FftLib::zeropadding(vec,8);

    ASSERT_EQ(newvec.size(),16);
    ASSERT_EQ(newvec[0].real(),0.1);
    ASSERT_EQ(newvec[1].real(),0.2);
    ASSERT_EQ(newvec[2].real(),0.3);
    ASSERT_EQ(newvec[3].real(),0.4);
    ASSERT_EQ(newvec[4].real(),0.5);
    ASSERT_EQ(newvec[5].real(),0.6);
    ASSERT_EQ(newvec[6].real(),0.7);
    ASSERT_EQ(newvec[7].real(),0.8);
    ASSERT_EQ(newvec[8].real(),0);
    ASSERT_EQ(newvec[9].real(),0);
    ASSERT_EQ(newvec[10].real(),0);
}<|endoftext|>