<commit_before>/*
 * Copyright (C) 2011
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * 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 <string>
#include <utility>
#include <vector>

using std::string;
using std::pair;
using std::make_pair;
using std::vector;

#include <Kernel.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <utils.hpp>

using isa::OpenCL::Kernel;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::utils::replace;
using isa::utils::toString;
using isa::utils::toStringValue;
using isa::utils::giga;

#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP

namespace LOFAR {
namespace RTCP {

template< typename T > class BeamFormer : public Kernel< T > {
public:
	BeamFormer(string name, string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError);

	inline void setBeamsBlock(unsigned int block);
	inline void setNrThreadsPerBlock(unsigned int threads);

	inline void setNrStations(unsigned int stations);
	inline void setNrPencilBeams(unsigned int beams);
	inline void setNrChannels(unsigned int channels);
	inline void setNrSamplesPerSecond(unsigned int samples);
	inline void setAveragingFactor(float factor);
	inline void setStokesI();
	inline void setStokesIQUV();
	inline void setNoStokes();

private:
	cl::NDRange		globalSize;
	cl::NDRange		localSize;

	unsigned int		beamsBlock;
	unsigned int		nrThreadsPerBlock;

	unsigned int		nrStations;
	unsigned int		nrPencilBeams;
	unsigned int		nrChannels;
	unsigned int		nrSamplesPerSecond;
	float			averagingFactor;
	bool			stokesI;
	bool			stokesIQUV;
};

template< typename T > BeamFormer< T >::BeamFormer(string name, string dataType) : Kernel< T >(name, dataType), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), beamsBlock(0), nrThreadsPerBlock(0), nrStations(0), nrPencilBeams(0), nrChannels(0), nrSamplesPerSecond(0), averagingFactor(0), stokesI(false), stokesIQUV(false) {}

template< typename T > void BeamFormer< T >::generateCode() throw (OpenCLError) {
	// Assuming one kernel execution
	long long unsigned int ops = 0;
	long long unsigned int memOps = 0;

	if ( stokesI ) {
		ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 11);
		memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 4);
	}
	else if ( stokesIQUV ) {
		ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 24);
		memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 16);
	}
	else {
		ops = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 4);
		memOps = (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * (nrPencilBeams / beamsBlock) * nrStations * 16) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * nrStations * 8) + (static_cast< long long unsigned int >(nrChannels) * nrSamplesPerSecond * nrPencilBeams * 16);
	}
	this->arInt = ops / static_cast< double >(memOps);
	this->gflop = giga(ops);
	this->gb = giga(memOps);

	// Begin kernel's template
	if ( this->code != 0 ) {
		delete this->code;
	}
	this->code = new string();
	string *beamsBlock_s = toString< unsigned int >(beamsBlock);
	string *nrStations_s = toString< unsigned int >(nrStations);
	string *nrPencilBeams_s = toString< unsigned int >(nrPencilBeams);
	string *nrSamplesPerSecond_s = toString< unsigned int >(nrSamplesPerSecond + (nrSamplesPerSecond & 0x00000003));
	string *nrChannels_s = toString< unsigned int >(nrChannels);
	string *averagingFactor_s = toString< float >(averagingFactor);
	if ( averagingFactor_s->find('.') == string::npos ) {
		averagingFactor_s->append(".0f");
	}
	else {
		averagingFactor_s->append("f");
	}

	if ( stokesI ) {
		*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 *samples, __global " + this->dataType + " *results, __global float2 *weights) {\n";
	}
	else {
		*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 *samples, __global " + this->dataType + "4 *results, __global float2 *weights) {\n";
	}
	*(this->code) += "unsigned int channel = get_group_id(0);\n"
	"unsigned int sample = (get_group_id(1) * get_local_size(0)) + get_local_id(0);\n"
	"unsigned int item = 0;\n"
	"\n"
	+ this->dataType + "4 cSample = (" + this->dataType + "4)(0.0f);\n"
	"float2 weight = (float2)(0.0f);\n"
	"\n"
	"for ( unsigned int beam = 0; beam < " + *nrPencilBeams_s + "; beam += " + *beamsBlock_s + " ) {\n"
	"<%DEFINITIONS%>"
	"\n"
	"for ( unsigned int station = 0; station < " + *nrStations_s + "; station++ ) {\n"
	"item = (channel * " + *nrStations_s + " * " + *nrPencilBeams_s + ") + (station * " + *nrPencilBeams_s + ") + beam;\n"
	"cSample = samples[(channel * " + *nrStations_s + " * " + *nrSamplesPerSecond_s + ") + (station * " + *nrSamplesPerSecond_s + ") + sample];\n"
	"\n"
	"<%BEAMS%>"
	"}\n"
	"<%AVERAGE%>"
	"item = (channel * " + *nrSamplesPerSecond_s + ") + sample;\n"
	"<%STORE%>"
	"}\n"
	"}\n";

	string definitionsTemplate = Kernel< T >::getDataType() + "4 beam<%NUM%> = (" + Kernel< T >::getDataType() + "4)(0.0f);\n";

	string beamsTemplate = "weight = weights[item++];\n"
	"beam<%NUM%>.x += (cSample.x * weight.x) - (cSample.y * weight.y);\n"
	"beam<%NUM%>.y += (cSample.x * weight.y) + (cSample.y * weight.x);\n"
	"beam<%NUM%>.z += (cSample.z * weight.x) - (cSample.w * weight.y);\n"
	"beam<%NUM%>.w += (cSample.z * weight.y) + (cSample.w * weight.x);\n";

	string averageTemplate = "beam<%NUM%> *= " + *averagingFactor_s + ";\n";

	string storeTemplate;
	if ( stokesI ) {
		storeTemplate = "results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n";
	}
	else if ( stokesIQUV ) {
		storeTemplate = "cSample.x = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
		"cSample.y = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) - ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
		"cSample.z = 2.0f * ((beam<%NUM%>.x * beam<%NUM%>.z) + (beam<%NUM%>.y * beam<%NUM%>.w));\n"
		"cSample.w = 2.0f * ((beam<%NUM%>.y * beam<%NUM%>.z) - (beam<%NUM%>.x * beam<%NUM%>.w));\n"
		"results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = cSample;\n";
	}
	else {
		storeTemplate = "results[((beam + <%NUM%>) * " + *nrChannels_s + " * " + *nrSamplesPerSecond_s + ") + item] = beam<%NUM%>;\n";
	}

	delete beamsBlock_s;
	delete nrStations_s;
	delete nrPencilBeams_s;
	delete nrSamplesPerSecond_s;
	delete nrChannels_s;
	delete averagingFactor_s;
	// End kernel's template

	string *definitions = new string();
	string *beams = new string();
	string *averages = new string();
	string *stores = new string();
	for ( unsigned int beam = 0; beam < beamsBlock; beam++ ) {
		string *beam_s = toString< unsigned int >(beam);
		string *temp;

		temp = replace(&definitionsTemplate, "<%NUM%>", *beam_s);
		definitions->append(*temp);
		delete temp;
		temp = replace(&beamsTemplate, "<%NUM%>",*beam_s);
		beams->append(*temp);
		delete temp;
		temp = replace(&averageTemplate, "<%NUM%>", *beam_s);
		averages->append(*temp);
		delete temp;
		temp = replace(&storeTemplate, "<%NUM%>", *beam_s);
		stores->append(*temp);
		delete temp;

		delete beam_s;
	}
	this->code = replace(this->code, "<%DEFINITIONS%>", *definitions, true);
	this->code = replace(this->code, "<%BEAMS%>", *beams, true);
	this->code = replace(this->code, "<%AVERAGE%>", *averages, true);
	this->code = replace(this->code, "<%STORE%>", *stores, true);
	delete definitions;
	delete beams;
	delete averages;
	delete stores;

	globalSize = cl::NDRange(nrChannels * nrThreadsPerBlock, nrSamplesPerSecond / nrThreadsPerBlock);
	localSize = cl::NDRange(nrThreadsPerBlock, 1);

	this->compile();
}

template< typename T > void BeamFormer< T >::operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError) {

	this->setArgument(0, *(input->getDeviceData()));
	this->setArgument(1, *(output->getDeviceData()));
	this->setArgument(2, *(weights->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void BeamFormer< T >::setBeamsBlock(unsigned int block) {
	beamsBlock = block;
}

template< typename T > inline void BeamFormer< T >::setNrThreadsPerBlock(unsigned int threads) {
	nrThreadsPerBlock = threads;
}

template< typename T > inline void BeamFormer< T >::setNrStations(unsigned int stations) {
	nrStations = stations;
}

template< typename T > inline void BeamFormer< T >::setNrPencilBeams(unsigned int beams) {
	nrPencilBeams = beams;
}

template< typename T > inline void BeamFormer< T >::setNrChannels(unsigned int channels) {
	nrChannels = channels;
}

template< typename T > inline void BeamFormer< T >::setNrSamplesPerSecond(unsigned int samples) {
	nrSamplesPerSecond = samples;
}

template< typename T > inline void BeamFormer< T >::setAveragingFactor(float factor) {
	averagingFactor = factor;
}

template< typename T > inline void BeamFormer< T >::setStokesI() {
	stokesI = true;
	stokesIQUV = false;
}

template< typename T > inline void BeamFormer< T >::setStokesIQUV() {
	stokesI = false;
	stokesIQUV = true;
}

template< typename T > inline void BeamFormer< T >::setNoStokes() {
	stokesI = false;
	stokesIQUV = false;
}

} // RTCP
} // LOFAR

#endif // BEAM_FORMER_HPP

<commit_msg>After 3 years, the code needed some polishing. Now it uses the same libraries as the more recent code I wrote.<commit_after>//
// Copyright (C) 2011
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <string>
using std::string;
#include <vector>
using std::vector;

#include <Kernel.hpp>
using isa::OpenCL::Kernel;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::replace;
using isa::utils::toStringValue;
using isa::utils::giga;
#include <Observation.hpp>
using AstroData::Observation;

#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP

namespace LOFAR {
namespace RTCP {

template< typename T > class BeamFormer : public Kernel< T > {
public:
	BeamFormer(string name, string dataType);

	void generateCode() throw (OpenCLError);
	void operator()(CLData< T > * input, CLData< T > * output, CLData< float > * weights) throw (OpenCLError);

	inline void setBeamsBlock(unsigned int block);
	inline void setNrSamplesPerBlock(unsigned int threads);

	inline void setObservation(Observation< T > * obs);
	inline void setAveragingFactor(float factor);
	inline void setStokesI();
	inline void setStokesIQUV();
	inline void setNoStokes();

private:
	cl::NDRange	globalSize;
	cl::NDRange	localSize;

	unsigned int beamsBlock;
	unsigned int nrSamplesPerBlock;

	Observation< T > * observation;
	float averagingFactor;
	bool stokesI;
	bool stokesIQUV;
};

template< typename T > BeamFormer< T >::BeamFormer(string name, string dataType) : Kernel< T >(name, dataType), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), beamsBlock(0), nrSamplesPerBlock(0), observation(0), averagingFactor(0), stokesI(false), stokesIQUV(false) {}

template< typename T > void BeamFormer< T >::generateCode() throw (OpenCLError) {
	long long unsigned int ops = 0;
	long long unsigned int memOps = 0;

	if ( stokesI ) {
		ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 11);
		memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 4);
	}
	else if ( stokesIQUV ) {
		ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 24);
		memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 16);
	}
	else {
		ops = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 4);
		memOps = (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * (observation->getNrBeams() / beamsBlock) * observation->getNrStations() * 16) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * observation->getNrStations() * 8) + (static_cast< long long unsigned int >(observation->getNrChannels()) * observation->getNrSamplesPerSecond() * observation->getNrBeams() * 16);
	}
	this->arInt = ops / static_cast< double >(memOps);
	this->gflop = giga(ops);
	this->gb = giga(memOps);

	// Begin kernel's template
	if ( this->code != 0 ) {
		delete this->code;
	}
	this->code = new string();
	string beamsBlock_s = toStringValue< unsigned int >(beamsBlock);
	string nrStations_s = toStringValue< unsigned int >(observation->getNrStations());
	string nrBeams_s = toStringValue< unsigned int >(observation->getNrBeams());
	string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond());
	string nrSamplesPerPaddedSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerPaddedSecond());
	string nrChannels_s = toStringValue< unsigned int >(observation->getNrChannels());
	string averagingFactor_s = toStringValue< float >(averagingFactor);
	if ( averagingFactor_s->find('.') == string::npos ) {
		averagingFactor_s->append(".0f");
	}
	else {
		averagingFactor_s->append("f");
	}

	if ( stokesI ) {
		*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 * samples, __global " + this->dataType + " * results, __global float2 * weights) {\n";
	}
	else {
		*(this->code) += "__kernel void " + this->name + "(__global " + this->dataType + "4 * samples, __global " + this->dataType + "4 * results, __global float2 * weights) {\n";
	}
	*(this->code) += "const unsigned int sample = (get_group_id(0) * get_local_size(0)) + get_local_id(0);\n"
	"const unsigned	int channel = get_group_id(1);\n"
	"unsigned int item = 0;\n"
	"\n"
	+ this->dataType + "4 cSample = (" + this->dataType + "4)(0.0f);\n"
	"float2 weight = (float2)(0.0f);\n"
	"\n"
	"for ( unsigned int beam = 0; beam < " + nrBeams_s + "; beam += " + beamsBlock_s + " ) {\n"
	"<%DEFINITIONS%>"
	"\n"
	"for ( unsigned int station = 0; station < " + nrStations_s + "; station++ ) {\n"
	"item = (channel * " + *nrStations_s + " * " + nrBeams_s + ") + (station * " + nrBeams_s + ") + beam;\n"
	"cSample = samples[(channel * " + nrStations_s + " * " + nrSamplesPerPaddedSecond_s + ") + (station * " + nrSamplesPerPaddedSecond_s + ") + sample];\n"
	"\n"
	"<%BEAMS%>"
	"}\n"
	"<%AVERAGE%>"
	"item = (channel * " + nrSamplesPerSecond_s + ") + sample;\n"
	"<%STORE%>"
	"}\n"
	"}\n";

	string definitionsTemplate = Kernel< T >::getDataType() + "4 beam<%NUM%> = (" + Kernel< T >::getDataType() + "4)(0.0f);\n";

	string beamsTemplate = "weight = weights[item++];\n"
	"beam<%NUM%>.x += (cSample.x * weight.x) - (cSample.y * weight.y);\n"
	"beam<%NUM%>.y += (cSample.x * weight.y) + (cSample.y * weight.x);\n"
	"beam<%NUM%>.z += (cSample.z * weight.x) - (cSample.w * weight.y);\n"
	"beam<%NUM%>.w += (cSample.z * weight.y) + (cSample.w * weight.x);\n";

	string averageTemplate = "beam<%NUM%> *= " + averagingFactor_s + ";\n";

	string storeTemplate;
	if ( stokesI ) {
		storeTemplate = "results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n";
	}
	else if ( stokesIQUV ) {
		storeTemplate = "cSample.x = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) + ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
		"cSample.y = ((beam<%NUM%>.x * beam<%NUM%>.x) + (beam<%NUM%>.y * beam<%NUM%>.y)) - ((beam<%NUM%>.z * beam<%NUM%>.z) + (beam<%NUM%>.w * beam<%NUM%>.w));\n"
		"cSample.z = 2.0f * ((beam<%NUM%>.x * beam<%NUM%>.z) + (beam<%NUM%>.y * beam<%NUM%>.w));\n"
		"cSample.w = 2.0f * ((beam<%NUM%>.y * beam<%NUM%>.z) - (beam<%NUM%>.x * beam<%NUM%>.w));\n"
		"results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = cSample;\n";
	}
	else {
		storeTemplate = "results[((beam + <%NUM%>) * " + nrChannels_s + " * " + nrSamplesPerPaddedSecond_s + ") + item] = beam<%NUM%>;\n";
	}
	// End kernel's template

	string * definitions = new string();
	string * beams = new string();
	string * averages = new string();
	string * stores = new string();
	for ( unsigned int beam = 0; beam < beamsBlock; beam++ ) {
		string *beam_s = toString< unsigned int >(beam);
		string *temp;

		temp = replace(&definitionsTemplate, "<%NUM%>", *beam_s);
		definitions->append(*temp);
		delete temp;
		temp = replace(&beamsTemplate, "<%NUM%>",*beam_s);
		beams->append(*temp);
		delete temp;
		temp = replace(&averageTemplate, "<%NUM%>", *beam_s);
		averages->append(*temp);
		delete temp;
		temp = replace(&storeTemplate, "<%NUM%>", *beam_s);
		stores->append(*temp);
		delete temp;

		delete beam_s;
	}
	this->code = replace(this->code, "<%DEFINITIONS%>", *definitions, true);
	this->code = replace(this->code, "<%BEAMS%>", *beams, true);
	this->code = replace(this->code, "<%AVERAGE%>", *averages, true);
	this->code = replace(this->code, "<%STORE%>", *stores, true);
	delete definitions;
	delete beams;
	delete averages;
	delete stores;

	globalSize = cl::NDRange(observation->getNrSamplesPerPaddedSecond(), observation->getNrChannels());
	localSize = cl::NDRange(nrSamplesPerBlock, 1);

	this->compile();
}

template< typename T > void BeamFormer< T >::operator()(CLData< T > *input, CLData< T > *output, CLData< float > *weights) throw (OpenCLError) {

	this->setArgument(0, *(input->getDeviceData()));
	this->setArgument(1, *(output->getDeviceData()));
	this->setArgument(2, *(weights->getDeviceData()));

	this->run(globalSize, localSize);
}

template< typename T > inline void BeamFormer< T >::setBeamsBlock(unsigned int block) {
	beamsBlock = block;
}

template< typename T > inline void BeamFormer< T >::setNrSamplesPerBlock(unsigned int threads) {
	nrSamplesPerBlock = threads;
}

template< typename T > inline void BeamFormer< T >::setObservation(Observation< T > *obs) {
	observation = obs;
}

template< typename T > inline void BeamFormer< T >::setAveragingFactor(float factor) {
	averagingFactor = factor;
}

template< typename T > inline void BeamFormer< T >::setStokesI() {
	stokesI = true;
	stokesIQUV = false;
}

template< typename T > inline void BeamFormer< T >::setStokesIQUV() {
	stokesI = false;
	stokesIQUV = true;
}

template< typename T > inline void BeamFormer< T >::setNoStokes() {
	stokesI = false;
	stokesIQUV = false;
}

} // RTCP
} // LOFAR

#endif // BEAM_FORMER_HPP

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <typename T>
struct Node {
	Node *left;
	Node *right;
	T data;
};

template <class T>
class BinaryTree
{
private:
	Node<T>*root;
	int CountElements = 0;

public:
	BinaryTree();
	~BinaryTree();
	Node<T>* root_();
	unsigned int count() const;
	void insert_node(const T&x);
	Node<T> *find_node(const T&, Node<T>*)const;
	void deleteNode(Node<T>* temp);
	void writing(const std::string& filename)const;
	friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);

};

template <typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
Node<T>* BinaryTree<T>::root_()
{
	return root;
}

template <typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
	{
		throw "error";
	}
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
	if (!node)
		return ost;
	output(ost, node->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << node->data << std::endl;
	output(ost, node->left, level + 1);
	return ost;
}

template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
	//if (!temp.root)
		//throw "error";
	output(ost, temp.root, 0);
	return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <typename T>
struct Node {
	Node *left;
	Node *right;
	T data;
};

template <class T>
class BinaryTree
{
private:
	Node<T>*root;
	int CountElements = 0;

public:
	BinaryTree();
	~BinaryTree();
	Node<T>* root_();
	unsigned int count() const;
	void insert_node(const T&x);
	Node<T> *find_node(const T&, Node<T>*)const;
	void deleteNode(Node<T>* temp);
	void writing(const std::string& filename)const;
	friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);

};

template <typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
Node<T>* BinaryTree<T>::root_()
{
	return root;
}

template <typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
	{
		throw "error";
	}
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
	if (!node)
		return ost;
	output(ost, node->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << node->data << std::endl;
	output(ost, node->left, level + 1);
	return ost;
}

template <typename T> inline
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
	//if (!temp.root)
		//throw "error";
	output(ost, temp.root, 0);
	return ost;
}
<|endoftext|>


<commit_before>//=================================================================================================
//                    Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef CSVMANAGER_HPP
#define CSVMANAGER_HPP

namespace urt {

//=================================================================================================

// write Vector to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Vector<T>& x)
{
   std::ofstream myfile(filename);

   #ifdef USE_ARMA
   int nrows = x.n_rows;
   #elif defined(USE_BLAZE) || defined(USE_EIGEN)
   int nrows = x.size();
   #endif

   for (int i = 0; i < nrows; ++i)
      myfile << x[i] << "\n";

   myfile.close();
}

//*************************************************************************************************

// write Matrix to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Matrix<T>& x)
{
   std::ofstream myfile(filename);

   #ifdef USE_ARMA
   int nrows = x.n_rows;
   int ncols = x.n_cols;
   #elif USE_BLAZE
   int nrows = x.rows();
   int ncols = x.columns();
   #elif USE_EIGEN
   int nrows = x.rows();
   int ncols = x.cols();
   #endif

   for (int i = 0; i < nrows; ++i) {
      for (int j = 0; j < ncols; ++j) {

         myfile << x(i, j);

         if (j != ncols - 1) {
            myfile << ",";
         } else {
            myfile << "\n";
         }
      }
   }

   myfile.close();
}

//*************************************************************************************************

// read data from csv file and store them into a Vector
template <typename T>
void ReadFromCSV(const std::string& filename, Vector<T>& x)
{
   std::ifstream myfile(filename);

   if (!myfile.good())  {
      std::cerr << "\n  Error: " << filename << " cannot be found!\n\n";
      return;
   }

   std::string cell;

   int nrows = 0;

   // reading data
   while (std::getline(myfile, cell)) {
      #if defined(USE_ARMA) || defined(USE_BLAZE)
      x.resize(nrows + 1);
      #elif USE_EIGEN
      x.conservativeResize(nrows + 1, 1);
      #endif

      x[nrows] = std::stod(cell);
      ++nrows;
   }
   myfile.close();
}

//*************************************************************************************************

// read data from csv file and store them into a Matrix
template <typename T>
void ReadFromCSV(const std::string& filename, Matrix<T>& x)
{
   std::ifstream myfile(filename);

   if (!myfile.good())  {
      std::cerr << "\n  Error: " << filename << " cannot be found!\n\n";
      return;
   }

   std::string line;

   int nrows = 0;

   // reading data
   while (std::getline(myfile, line)) {

      std::stringstream lineStream(line);
      std::string cell;

      #ifdef USE_ARMA
      arma::Row<T> z;
      #elif USE_BLAZE
      blaze::DynamicVector<T,blaze::rowVector> z;
      #elif USE_EIGEN
      Vector<T> z;
      #endif

      int ncols = 0;

      while (std::getline(lineStream, cell, ',')) {
         #if defined(USE_ARMA) || defined(USE_BLAZE)
         z.resize(ncols + 1);
         #elif USE_EIGEN
         z.conservativeResize(ncols + 1, Eigen::NoChange);
         #endif
         z[ncols] = std::stod(cell);
         ++ncols;
      }
      #ifdef USE_ARMA
      x.insert_rows(nrows, z);
      #elif USE_BLAZE
      x.resize(nrows + 1, ncols);
      row(x, nrows) = z;
      #elif USE_EIGEN
      x.conservativeResize(nrows + 1, ncols);
      x.row(nrows) = z;
      #endif
      ++nrows;
   }
   myfile.close();
}

//=================================================================================================

}

#endif
<commit_msg>Update CsvManager.hpp<commit_after>//=================================================================================================
//                    Copyright (C) 2016 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef CSVMANAGER_HPP
#define CSVMANAGER_HPP

namespace urt {

//=================================================================================================

// write Vector to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Vector<T>& x)
{
   std::ofstream myfile(filename);

   #ifdef USE_ARMA
   int nrows = x.n_rows;
   #elif defined(USE_BLAZE) || defined(USE_EIGEN)
   int nrows = x.size();
   #endif

   for (int i = 0; i < nrows; ++i)
      myfile << x[i] << "\n";

   myfile.close();
}

//*************************************************************************************************

// write Matrix to csv file
template <typename T>
void WriteToCSV(const std::string& filename, const Matrix<T>& x)
{
   std::ofstream myfile(filename);

   #ifdef USE_ARMA
   int nrows = x.n_rows;
   int ncols = x.n_cols;
   #elif USE_BLAZE
   int nrows = x.rows();
   int ncols = x.columns();
   #elif USE_EIGEN
   int nrows = x.rows();
   int ncols = x.cols();
   #endif

   for (int i = 0; i < nrows; ++i) {
      for (int j = 0; j < ncols; ++j) {

         myfile << x(i, j);

         if (j != ncols - 1) {
            myfile << ",";
         } else {
            myfile << "\n";
         }
      }
   }

   myfile.close();
}

//*************************************************************************************************

// read data from csv file and store them into a Vector
template <typename T>
void ReadFromCSV(const std::string& filename, Vector<T>& x)
{
   std::ifstream myfile(filename);

   if (!myfile.good())  {
      std::cerr << "\n  Error: " << filename << " cannot be found!\n\n";
      return;
   }

   std::string line;

   int nrows = 0;

   // reading data
   while (std::getline(myfile, line)) {
      #if defined(USE_ARMA) || defined(USE_BLAZE)
      x.resize(nrows + 1);
      #elif USE_EIGEN
      x.conservativeResize(nrows + 1, 1);
      #endif

      std::stringstream lineStream(line);
      std::string cell;
      std::getline(lineStream, cell, ',');

      x[nrows] = std::stod(cell);
      ++nrows;
   }
   myfile.close();
}

//*************************************************************************************************

// read data from csv file and store them into a Matrix
template <typename T>
void ReadFromCSV(const std::string& filename, Matrix<T>& x)
{
   std::ifstream myfile(filename);

   if (!myfile.good())  {
      std::cerr << "\n  Error: " << filename << " cannot be found!\n\n";
      return;
   }

   std::string line;

   int nrows = 0;

   // reading data
   while (std::getline(myfile, line)) {

      std::stringstream lineStream(line);
      std::string cell;

      #ifdef USE_ARMA
      arma::Row<T> z;
      #elif USE_BLAZE
      blaze::DynamicVector<T,blaze::rowVector> z;
      #elif USE_EIGEN
      Vector<T> z;
      #endif

      int ncols = 0;

      while (std::getline(lineStream, cell, ',')) {
         #if defined(USE_ARMA) || defined(USE_BLAZE)
         z.resize(ncols + 1);
         #elif USE_EIGEN
         z.conservativeResize(ncols + 1, Eigen::NoChange);
         #endif
         z[ncols] = std::stod(cell);
         ++ncols;
      }
      #ifdef USE_ARMA
      x.insert_rows(nrows, z);
      #elif USE_BLAZE
      x.resize(nrows + 1, ncols);
      row(x, nrows) = z;
      #elif USE_EIGEN
      x.conservativeResize(nrows + 1, ncols);
      x.row(nrows) = z;
      #endif
      ++nrows;
   }
   myfile.close();
}

//=================================================================================================

}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#include    "../../../StroikaPreComp.h"

#include    "../../../../Foundation/Characters/Format.h"
#include    "../../../../Foundation/Execution/Sleep.h"
#include    "../../../../Foundation/Execution/Thread.h"
#include    "../../../../Foundation/IO/Network/Socket.h"
#include    "../../../../Foundation/Streams/BasicBinaryOutputStream.h"
#include    "../../../../Foundation/Streams/TextOutputStreamBinaryAdapter.h"

#include    "../Common.h"
#include    "PeriodicNotifier.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::IO;
using   namespace   Stroika::Foundation::IO::Network;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::UPnP;
using   namespace   Stroika::Frameworks::UPnP::SSDP;
using   namespace   Stroika::Frameworks::UPnP::SSDP::Server;

/*
********************************************************************************
******************************** PeriodicNotifier ******************************
********************************************************************************
*/
PeriodicNotifier::PeriodicNotifier ()
{
}

namespace {
    void    DoSend_ (DeviceAnnouncement deviceAnnouncement, Socket s)
    {
        Memory::BLOB    data;
        {
            Streams::BasicBinaryOutputStream    out;
            Streams::TextOutputStreamBinaryAdapter  textOut (out);
            //// SUPER ROUGH FIRST DRAFT
            textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
            textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
            textOut.Write (Format (L"NT: %s\r\n", deviceAnnouncement.fST.c_str ()));
            textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
            textOut.Write (Format (L"USN: %s\r\n", deviceAnnouncement.fUSN.c_str ()));
            if (not deviceAnnouncement.fLocation.empty ()) {
                textOut.Write (Format (L"Location: %s\r\n", deviceAnnouncement.fLocation.c_str ()));
            }
            textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
            if (not deviceAnnouncement.fServer.empty ()) {
                textOut.Write (Format (L"Server: %s\r\n", deviceAnnouncement.fServer.c_str ()));
            }
            ///need fluush API on  OUTSTREAM
            data = out.As<Memory::BLOB> ();
        }
        s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
    };
}

void    PeriodicNotifier::Run (const Device& d, const FrequencyInfo& fi)
{
    Execution::Thread t ([d, fi]() {
        Socket s (Socket::SocketKind::DGRAM);
        while (true) {
            DeviceAnnouncement  dan;
#if 1
            dan.fLocation = d.fLocation;
            dan.fServer = d.fServer;
            {
                dan.fST = L"upnp:rootdevice";
                dan.fUSN = Format (L"uuid:device-%s::upnp:rootdevice", d.fDeviceID.c_str ());
                DoSend_ (dan, s);
            }
            {
                dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
                dan.fST = dan.fUSN;
                DoSend_ (dan, s);
            }
#else
            Memory::BLOB    data;
            {
                Streams::BasicBinaryOutputStream    out;
                Streams::TextOutputStreamBinaryAdapter  textOut (out);
                //// SUPER ROUGH FIRST DRAFT
                textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
                textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
                if (not d.fST.empty ()) {
                    textOut.Write (Format (L"NT: %s\r\n", d.fST.c_str ()));
                }
                textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
                // I THINK I NEED TO SNED THIS AND uuid:device-UUID (SEP MESSAGES)
                textOut.Write (Format (L"USN: uuid:%s::upnp:rootdevice\r\n", d.fDeviceID.c_str ()));
                if (not d.fLocation.empty ()) {
                    textOut.Write (Format (L"Location: %s\r\n", d.fLocation.c_str ()));
                }
                textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
                if (not d.fServer.empty ()) {
                    textOut.Write (Format (L"Server: %s\r\n", d.fServer.c_str ()));
                }
                ///need fluush API on  OUTSTREAM
                data = out.As<Memory::BLOB> ();
            }
            s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
#endif
            Execution::Sleep (30.0);
        }
    });
    t.Start ();
    t.WaitForDone ();
}
<commit_msg>progress on SSDP broadcast stuff but still not showing up in windows<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#include    "../../../StroikaPreComp.h"

#include    "../../../../Foundation/Characters/Format.h"
#include    "../../../../Foundation/Execution/Sleep.h"
#include    "../../../../Foundation/Execution/Thread.h"
#include    "../../../../Foundation/IO/Network/Socket.h"
#include    "../../../../Foundation/Streams/BasicBinaryOutputStream.h"
#include    "../../../../Foundation/Streams/TextOutputStreamBinaryAdapter.h"

#include    "../Common.h"
#include    "PeriodicNotifier.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::IO;
using   namespace   Stroika::Foundation::IO::Network;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::UPnP;
using   namespace   Stroika::Frameworks::UPnP::SSDP;
using   namespace   Stroika::Frameworks::UPnP::SSDP::Server;

/*
********************************************************************************
******************************** PeriodicNotifier ******************************
********************************************************************************
*/
PeriodicNotifier::PeriodicNotifier ()
{
}

namespace {
    void    DoSend_ (DeviceAnnouncement deviceAnnouncement, Socket s)
    {
        Memory::BLOB    data;
        {
            Streams::BasicBinaryOutputStream    out;
            Streams::TextOutputStreamBinaryAdapter  textOut (out);
            //// SUPER ROUGH FIRST DRAFT
            textOut.Write (Format (L"NOTIFY * HTTP/1.1\r\n"));
            textOut.Write (Format (L"Host: %s:%d\r\n", SSDP::V4::kSocketAddress.GetInternetAddress ().As<String> ().AsUTF8 ().c_str (), SSDP::V4::kSocketAddress.GetPort ()));
            textOut.Write (Format (L"NT: %s\r\n", deviceAnnouncement.fST.c_str ()));
            textOut.Write (Format (L"NTS: ssdp:alive\r\n"));
            textOut.Write (Format (L"USN: %s\r\n", deviceAnnouncement.fUSN.c_str ()));
            if (not deviceAnnouncement.fLocation.empty ()) {
                textOut.Write (Format (L"Location: %s\r\n", deviceAnnouncement.fLocation.c_str ()));
            }
            textOut.Write (Format (L"Cache-Control: max-age = 7393\r\n"));
            if (not deviceAnnouncement.fServer.empty ()) {
                textOut.Write (Format (L"Server: %s\r\n", deviceAnnouncement.fServer.c_str ()));
            }
            ///need fluush API on  OUTSTREAM
            data = out.As<Memory::BLOB> ();
        }
        s.SendTo (data.begin (), data.end (), UPnP::SSDP::V4::kSocketAddress);
    };
}

void    PeriodicNotifier::Run (const Device& d, const FrequencyInfo& fi)
{
    Execution::Thread t ([d, fi]() {
        Socket s (Socket::SocketKind::DGRAM);
        while (true) {
            DeviceAnnouncement  dan;
            dan.fLocation = d.fLocation;
            dan.fServer = d.fServer;
            {
                dan.fST = L"upnp:rootdevice";
                dan.fUSN = Format (L"uuid:device-%s::upnp:rootdevice", d.fDeviceID.c_str ());
                DoSend_ (dan, s);
            }
            {
                dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
                dan.fST = dan.fUSN;
                DoSend_ (dan, s);
            }
            Execution::Sleep (30.0);
        }
    });
    t.Start ();
    t.WaitForDone ();
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>

#include <mitkGIFGreyLevelSizeZone.h>

class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );

  MITK_TEST(ImageDescription_PhantomTest_3D);
  MITK_TEST(ImageDescription_PhantomTest_2D);

  CPPUNIT_TEST_SUITE_END();

private:
  mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
  mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
  mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
  mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;

public:

  void setUp(void) override
  {
    m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
    m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
    m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
    m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
  }

  void ImageDescription_PhantomTest_3D()
  {
    mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();

    featureCalculator->SetUseBinsize(true);
    featureCalculator->SetBinsize(1.0);
    featureCalculator->SetUseMinimumIntensity(true);
    featureCalculator->SetUseMaximumIntensity(true);
    featureCalculator->SetMinimumIntensity(0.5);
    featureCalculator->SetMaximumIntensity(6.5);

    auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);

    std::map<std::string, double> results;
    for (auto valuePair : featureList)
    {
      MITK_INFO << valuePair.first << " : " << valuePair.second;
      results[valuePair.first] = valuePair.second;
    }
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 19 features.", std::size_t(19), featureList.size());

    // These values are obtained with IBSI
    // Standard accuracy is 0.01
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Small Distance Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Large Distance Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 5, results["Grey Level Size Zone::Distance Size Non-Uniformity"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0,   results["Grey Level Size Zone::Zone Distance Variance"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.92, results["Grey Level Size Zone::Zone Distance Entropy"], 0.01);
    //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);

    // These values are obtained by manually running the tool
    // Values might be wrong.
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Distance Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.92, results["Grey Level Size Zone::Grey Level Entropy"], 0.01);
  }

  void ImageDescription_PhantomTest_2D()
  {
    mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();

    featureCalculator->SetUseBinsize(true);
    featureCalculator->SetBinsize(1.0);
    featureCalculator->SetUseMinimumIntensity(true);
    featureCalculator->SetUseMaximumIntensity(true);
    featureCalculator->SetMinimumIntensity(0.5);
    featureCalculator->SetMaximumIntensity(6.5);

    auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);

    std::map<std::string, double> results;
    for (auto valuePair : featureList)
    {
      MITK_INFO << valuePair.first << " : " << valuePair.second;
      results[valuePair.first] = valuePair.second;
    }
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 114 features.", std::size_t(114), featureList.size());

    // These values are obtained with IBSI
    // Standard accuracy is 0.01
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 0.946, results["SliceWise Mean Grey Level Size Zone::Small Distance Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1.21, results["SliceWise Mean Grey Level Size Zone::Large Distance Emphasis"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.367, results["SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.2, results["SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.386, results["SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 21.3, results["SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 3.79, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.898, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0.051, results["SliceWise Mean Grey Level Size Zone::Zone Distance Variance"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.73, results["SliceWise Mean Grey Level Size Zone::Zone Distance Entropy"], 0.01);
    //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);

    // These values are obtained by manually running the tool
    // Values might be wrong.
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.526, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1.071, results["SliceWise Mean Grey Level Size Zone::Zone Distance Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.732, results["SliceWise Mean Grey Level Size Zone::Grey Level Entropy"], 0.01);
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<commit_msg>3D Test is running and ok<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include "mitkIOUtil.h"
#include <cmath>

#include <mitkGIFGreyLevelSizeZone.h>

class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );

  MITK_TEST(ImageDescription_PhantomTest_3D);
  //MITK_TEST(ImageDescription_PhantomTest_2D);

  CPPUNIT_TEST_SUITE_END();

private:
  mitk::Image::Pointer m_IBSI_Phantom_Image_Small;
  mitk::Image::Pointer m_IBSI_Phantom_Image_Large;
  mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;
  mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;

public:

  void setUp(void) override
  {
    m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd"));
    m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd"));
    m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd"));
    m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd"));
  }

  void ImageDescription_PhantomTest_3D()
  {
    mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();

    featureCalculator->SetUseBinsize(true);
    featureCalculator->SetBinsize(1.0);
    featureCalculator->SetUseMinimumIntensity(true);
    featureCalculator->SetUseMaximumIntensity(true);
    featureCalculator->SetMinimumIntensity(0.5);
    featureCalculator->SetMaximumIntensity(6.5);

    auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);

    std::map<std::string, double> results;
    for (auto valuePair : featureList)
    {
      MITK_INFO << valuePair.first << " : " << valuePair.second;
      results[valuePair.first] = valuePair.second;
    }
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 18 features.", std::size_t(18), featureList.size());

    // These values are obtained with IBSI
    // Standard accuracy is 0.01
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.255, results["Grey Level Size Zone::Small Zone Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 550, results["Grey Level Size Zone::Large Zone Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0256, results["Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 2.76, results["Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 503, results["Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 1495, results["Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.2, results["Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 331,   results["Grey Level Size Zone::Zone Size Variance"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 2.32, results["Grey Level Size Zone::Zone Size Entropy"], 0.01);
    //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);

    // These values are obtained by manually running the tool
    // Values might be wrong.
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 14.8, results["Grey Level Size Zone::Zone Size Mean"], 0.001);
  }

  void ImageDescription_PhantomTest_2D()
  {
    mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();

    featureCalculator->SetUseBinsize(true);
    featureCalculator->SetBinsize(1.0);
    featureCalculator->SetUseMinimumIntensity(true);
    featureCalculator->SetUseMaximumIntensity(true);
    featureCalculator->SetMinimumIntensity(0.5);
    featureCalculator->SetMaximumIntensity(6.5);

    auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);

    std::map<std::string, double> results;
    for (auto valuePair : featureList)
    {
      MITK_INFO << valuePair.first << " : " << valuePair.second;
      results[valuePair.first] = valuePair.second;
    }
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 114 features.", std::size_t(114), featureList.size());

    // These values are obtained with IBSI
    // Standard accuracy is 0.01
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Emphasis with Large IBSI Phantom Image", 0.946, results["SliceWise Mean Grey Level Size Zone::Small Distance Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Emphasis with Large IBSI Phantom Image", 1.21, results["SliceWise Mean Grey Level Size Zone::Large Distance Emphasis"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.367, results["SliceWise Mean Grey Level Size Zone::Small Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis with Large IBSI Phantom Image", 15.2, results["SliceWise Mean Grey Level Size Zone::Small Distance High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis with Large IBSI Phantom Image", 0.386, results["SliceWise Mean Grey Level Size Zone::Large Distance Low Grey Level Emphasis"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis with Large IBSI Phantom Image", 21.3, results["SliceWise Mean Grey Level Size Zone::Large Distance High Grey Level Emphasis"], 0.1);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity with Large IBSI Phantom Image", 3.79, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.898, results["SliceWise Mean Grey Level Size Zone::Distance Size Non-Uniformity Normalized"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Variance with Large IBSI Phantom Image", 0.051, results["SliceWise Mean Grey Level Size Zone::Zone Distance Variance"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Entropy with Large IBSI Phantom Image", 1.73, results["SliceWise Mean Grey Level Size Zone::Zone Distance Entropy"], 0.01);
    //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001);

    // These values are obtained by manually running the tool
    // Values might be wrong.
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.526, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Distance Mean with Large IBSI Phantom Image", 1.071, results["SliceWise Mean Grey Level Size Zone::Zone Distance Mean"], 0.001);
    CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Entropy with Large IBSI Phantom Image", 1.732, results["SliceWise Mean Grey Level Size Zone::Grey Level Entropy"], 0.01);
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>

#define FLATC_VERSION "1.2.0 (" __DATE__ ")"

static void Error(const std::string &err, bool usage = false,
                  bool show_exe_name = true);

// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
  bool (*generate)(const flatbuffers::Parser &parser,
                   const std::string &path,
                   const std::string &file_name);
  const char *generator_opt_short;
  const char *generator_opt_long;
  const char *lang_name;
  flatbuffers::IDLOptions::Language lang;
  const char *generator_help;

  std::string (*make_rule)(const flatbuffers::Parser &parser,
                           const std::string &path,
                           const std::string &file_name);
};

const Generator generators[] = {
  { flatbuffers::GenerateBinary,   "-b", "--binary", "binary",
    flatbuffers::IDLOptions::kMAX,
    "Generate wire format binaries for any data definitions",
    flatbuffers::BinaryMakeRule },
  { flatbuffers::GenerateTextFile, "-t", "--json", "text",
    flatbuffers::IDLOptions::kMAX,
    "Generate text output for any data definitions",
    flatbuffers::TextMakeRule },
  { flatbuffers::GenerateCPP,      "-c", "--cpp", "C++",
    flatbuffers::IDLOptions::kMAX,
    "Generate C++ headers for tables/structs",
    flatbuffers::CPPMakeRule },
  { flatbuffers::GenerateGo,       "-g", "--go", "Go",
    flatbuffers::IDLOptions::kGo,
    "Generate Go files for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GenerateGeneral,  "-j", "--java", "Java",
    flatbuffers::IDLOptions::kJava,
    "Generate Java classes for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GenerateJS,       "-s", "--js", "JavaScript",
    flatbuffers::IDLOptions::kMAX,
    "Generate JavaScript code for tables/structs",
    flatbuffers::JSMakeRule },
  { flatbuffers::GenerateGeneral,  "-n", "--csharp", "C#",
    flatbuffers::IDLOptions::kCSharp,
    "Generate C# classes for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GeneratePython,   "-p", "--python", "Python",
    flatbuffers::IDLOptions::kMAX,
    "Generate Python files for tables/structs",
    flatbuffers::GeneralMakeRule },
    { flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
    flatbuffers::IDLOptions::kMAX,
    "Generate PHP files for tables/structs",
    flatbuffers::GeneralMakeRule },
};

const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;

static void Error(const std::string &err, bool usage, bool show_exe_name) {
  if (show_exe_name) printf("%s: ", program_name);
  printf("%s\n", err.c_str());
  if (usage) {
    printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
    for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
      printf("  %-12s %s %s.\n",
             generators[i].generator_opt_long,
             generators[i].generator_opt_short
               ? generators[i].generator_opt_short
               : "  ",
             generators[i].generator_help);
    printf(
      "  -o PATH         Prefix PATH to all generated files.\n"
      "  -I PATH         Search for includes in the specified path.\n"
      "  -M              Print make rules for generated files.\n"
      "  -v, --version   Print the version number of flatc and exit.\n"
      "  --strict-json   Strict JSON: field names must be / will be quoted,\n"
      "                  no trailing commas in tables/vectors.\n"
      "  --defaults-json Output fields whose value is the default when\n"
      "                  writing JSON\n"
      "  --unknown-json  Allow fields in JSON that are not defined in the\n"
      "                  schema. These fields will be discared when generating\n"
      "                  binaries.\n"
      "  --no-prefix     Don\'t prefix enum values with the enum type in C++.\n"
      "  --scoped-enums  Use C++11 style scoped and strongly typed enums.\n"
      "                  also implies --no-prefix.\n"
      "  --gen-includes  (deprecated), this is the default behavior.\n"
      "                  If the original behavior is required (no include\n"
      "                  statements) use --no-includes.\n"
      "  --no-includes   Don\'t generate include statements for included\n"
      "                  schemas the generated file depends on (C++).\n"
      "  --gen-mutable   Generate accessors that can mutate buffers in-place.\n"
      "  --gen-onefile   Generate single output file for C#\n"
      "  --raw-binary    Allow binaries without file_indentifier to be read.\n"
      "                  This may crash flatc given a mismatched schema.\n"
      "  --proto         Input is a .proto, translate to .fbs.\n"
      "  --schema        Serialize schemas instead of JSON (use with -b)\n"
      "FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
      "FILEs after the -- must be binary flatbuffer format files.\n"
      "Output files are named using the base file name of the input,\n"
      "and written to the current directory or the path given by -o.\n"
      "example: %s -c -b schema1.fbs schema2.fbs data.json\n",
      program_name);
  }
  if (parser) delete parser;
  exit(1);
}

int main(int argc, const char *argv[]) {
  program_name = argv[0];
  flatbuffers::IDLOptions opts;
  std::string output_path;
  const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
  bool generator_enabled[num_generators] = { false };
  bool any_generator = false;
  bool print_make_rules = false;
  bool raw_binary = false;
  bool schema_binary = false;
  std::vector<std::string> filenames;
  std::vector<const char *> include_directories;
  size_t binary_files_from = std::numeric_limits<size_t>::max();
  for (int argi = 1; argi < argc; argi++) {
    std::string arg = argv[argi];
    if (arg[0] == '-') {
      if (filenames.size() && arg[1] != '-')
        Error("invalid option location: " + arg, true);
      if (arg == "-o") {
        if (++argi >= argc) Error("missing path following: " + arg, true);
        output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
      } else if(arg == "-I") {
        if (++argi >= argc) Error("missing path following" + arg, true);
        include_directories.push_back(argv[argi]);
      } else if(arg == "--strict-json") {
        opts.strict_json = true;
      } else if(arg == "--no-js-exports") {
        opts.skip_js_exports = true;
      } else if(arg == "--defaults-json") {
        opts.output_default_scalars_in_json = true;
      } else if (arg == "--unknown-json") {
        opts.skip_unexpected_fields_in_json = true;
      } else if(arg == "--no-prefix") {
        opts.prefixed_enums = false;
      } else if(arg == "--scoped-enums") {
        opts.prefixed_enums = false;
        opts.scoped_enums = true;
      } else if(arg == "--gen-mutable") {
        opts.mutable_buffer = true;
      } else if(arg == "--gen-all") {
        opts.generate_all = true;
        opts.include_dependence_headers = false;
      } else if(arg == "--gen-includes") {
        // Deprecated, remove this option some time in the future.
        printf("warning: --gen-includes is deprecated (it is now default)\n");
      } else if(arg == "--no-includes") {
        opts.include_dependence_headers = false;
      } else if (arg == "--gen-onefile") {
        opts.one_file = true;
      } else if (arg == "--raw-binary") {
        raw_binary = true;
      } else if(arg == "--") {  // Separator between text and binary inputs.
        binary_files_from = filenames.size();
      } else if(arg == "--proto") {
        opts.proto_mode = true;
      } else if(arg == "--schema") {
        schema_binary = true;
      } else if(arg == "-M") {
        print_make_rules = true;
      } else if(arg == "-v" || arg == "--version") {
        printf("flatc version %s\n", FLATC_VERSION);
        exit(0);
      } else {
        for (size_t i = 0; i < num_generators; ++i) {
          if (arg == generators[i].generator_opt_long ||
              (generators[i].generator_opt_short &&
               arg == generators[i].generator_opt_short)) {
            generator_enabled[i] = true;
            any_generator = true;
            goto found;
          }
        }
        Error("unknown commandline argument" + arg, true);
        found:;
      }
    } else {
      filenames.push_back(argv[argi]);
    }
  }

  if (!filenames.size()) Error("missing input files", false, true);

  if (opts.proto_mode) {
    if (any_generator)
      Error("cannot generate code directly from .proto files", true);
  } else if (!any_generator) {
    Error("no options: specify at least one generator.", true);
  }

  // Now process the files:
  parser = new flatbuffers::Parser(opts);
  for (auto file_it = filenames.begin();
            file_it != filenames.end();
          ++file_it) {
      std::string contents;
      if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
        Error("unable to load file: " + *file_it);

      bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
                       binary_files_from;
      if (is_binary) {
        parser->builder_.Clear();
        parser->builder_.PushFlatBuffer(
          reinterpret_cast<const uint8_t *>(contents.c_str()),
          contents.length());
        if (!raw_binary) {
          // Generally reading binaries that do not correspond to the schema
          // will crash, and sadly there's no way around that when the binary
          // does not contain a file identifier.
          // We'd expect that typically any binary used as a file would have
          // such an identifier, so by default we require them to match.
          if (!parser->file_identifier_.length()) {
            Error("current schema has no file_identifier: cannot test if \"" +
                 *file_it +
                 "\" matches the schema, use --raw-binary to read this file"
                 " anyway.");
          } else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
                                             parser->file_identifier_.c_str())) {
            Error("binary \"" +
                 *file_it +
                 "\" does not have expected file_identifier \"" +
                 parser->file_identifier_ +
                 "\", use --raw-binary to read this file anyway.");
          }
        }
      } else {
        // Check if file contains 0 bytes.
        if (contents.length() != strlen(contents.c_str())) {
          Error("input file appears to be binary: " + *file_it, true);
        }
        if (flatbuffers::GetExtension(*file_it) == "fbs") {
          // If we're processing multiple schemas, make sure to start each
          // one from scratch. If it depends on previous schemas it must do
          // so explicitly using an include.
          delete parser;
          parser = new flatbuffers::Parser(opts);
        }
        auto local_include_directory = flatbuffers::StripFileName(*file_it);
        include_directories.push_back(local_include_directory.c_str());
        include_directories.push_back(nullptr);
        if (!parser->Parse(contents.c_str(), &include_directories[0],
                          file_it->c_str()))
          Error(parser->error_, false, false);
        if (schema_binary) {
          parser->Serialize();
          parser->file_extension_ = reflection::SchemaExtension();
        }
        include_directories.pop_back();
        include_directories.pop_back();
      }

      std::string filebase = flatbuffers::StripPath(
                               flatbuffers::StripExtension(*file_it));

      for (size_t i = 0; i < num_generators; ++i) {
        parser->opts.lang = generators[i].lang;
        if (generator_enabled[i]) {
          if (!print_make_rules) {
            flatbuffers::EnsureDirExists(output_path);
            if (!generators[i].generate(*parser, output_path, filebase)) {
              Error(std::string("Unable to generate ") +
                    generators[i].lang_name +
                    " for " +
                    filebase);
            }
          } else {
            std::string make_rule = generators[i].make_rule(
                *parser, output_path, *file_it);
            if (!make_rule.empty())
              printf("%s\n", flatbuffers::WordWrap(
                  make_rule, 80, " ", " \\").c_str());
          }
        }
      }

      if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);

      // We do not want to generate code for the definitions in this file
      // in any files coming up next.
      parser->MarkGenerated();
  }

  delete parser;
  return 0;
}
<commit_msg>Remove -v as option for printing version # (based on PR feedback).<commit_after>/*
 * Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>

#define FLATC_VERSION "1.2.0 (" __DATE__ ")"

static void Error(const std::string &err, bool usage = false,
                  bool show_exe_name = true);

// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
  bool (*generate)(const flatbuffers::Parser &parser,
                   const std::string &path,
                   const std::string &file_name);
  const char *generator_opt_short;
  const char *generator_opt_long;
  const char *lang_name;
  flatbuffers::IDLOptions::Language lang;
  const char *generator_help;

  std::string (*make_rule)(const flatbuffers::Parser &parser,
                           const std::string &path,
                           const std::string &file_name);
};

const Generator generators[] = {
  { flatbuffers::GenerateBinary,   "-b", "--binary", "binary",
    flatbuffers::IDLOptions::kMAX,
    "Generate wire format binaries for any data definitions",
    flatbuffers::BinaryMakeRule },
  { flatbuffers::GenerateTextFile, "-t", "--json", "text",
    flatbuffers::IDLOptions::kMAX,
    "Generate text output for any data definitions",
    flatbuffers::TextMakeRule },
  { flatbuffers::GenerateCPP,      "-c", "--cpp", "C++",
    flatbuffers::IDLOptions::kMAX,
    "Generate C++ headers for tables/structs",
    flatbuffers::CPPMakeRule },
  { flatbuffers::GenerateGo,       "-g", "--go", "Go",
    flatbuffers::IDLOptions::kGo,
    "Generate Go files for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GenerateGeneral,  "-j", "--java", "Java",
    flatbuffers::IDLOptions::kJava,
    "Generate Java classes for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GenerateJS,       "-s", "--js", "JavaScript",
    flatbuffers::IDLOptions::kMAX,
    "Generate JavaScript code for tables/structs",
    flatbuffers::JSMakeRule },
  { flatbuffers::GenerateGeneral,  "-n", "--csharp", "C#",
    flatbuffers::IDLOptions::kCSharp,
    "Generate C# classes for tables/structs",
    flatbuffers::GeneralMakeRule },
  { flatbuffers::GeneratePython,   "-p", "--python", "Python",
    flatbuffers::IDLOptions::kMAX,
    "Generate Python files for tables/structs",
    flatbuffers::GeneralMakeRule },
    { flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
    flatbuffers::IDLOptions::kMAX,
    "Generate PHP files for tables/structs",
    flatbuffers::GeneralMakeRule },
};

const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;

static void Error(const std::string &err, bool usage, bool show_exe_name) {
  if (show_exe_name) printf("%s: ", program_name);
  printf("%s\n", err.c_str());
  if (usage) {
    printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
    for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
      printf("  %-12s %s %s.\n",
             generators[i].generator_opt_long,
             generators[i].generator_opt_short
               ? generators[i].generator_opt_short
               : "  ",
             generators[i].generator_help);
    printf(
      "  -o PATH         Prefix PATH to all generated files.\n"
      "  -I PATH         Search for includes in the specified path.\n"
      "  -M              Print make rules for generated files.\n"
      "  --version       Print the version number of flatc and exit.\n"
      "  --strict-json   Strict JSON: field names must be / will be quoted,\n"
      "                  no trailing commas in tables/vectors.\n"
      "  --defaults-json Output fields whose value is the default when\n"
      "                  writing JSON\n"
      "  --unknown-json  Allow fields in JSON that are not defined in the\n"
      "                  schema. These fields will be discared when generating\n"
      "                  binaries.\n"
      "  --no-prefix     Don\'t prefix enum values with the enum type in C++.\n"
      "  --scoped-enums  Use C++11 style scoped and strongly typed enums.\n"
      "                  also implies --no-prefix.\n"
      "  --gen-includes  (deprecated), this is the default behavior.\n"
      "                  If the original behavior is required (no include\n"
      "                  statements) use --no-includes.\n"
      "  --no-includes   Don\'t generate include statements for included\n"
      "                  schemas the generated file depends on (C++).\n"
      "  --gen-mutable   Generate accessors that can mutate buffers in-place.\n"
      "  --gen-onefile   Generate single output file for C#\n"
      "  --raw-binary    Allow binaries without file_indentifier to be read.\n"
      "                  This may crash flatc given a mismatched schema.\n"
      "  --proto         Input is a .proto, translate to .fbs.\n"
      "  --schema        Serialize schemas instead of JSON (use with -b)\n"
      "FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
      "FILEs after the -- must be binary flatbuffer format files.\n"
      "Output files are named using the base file name of the input,\n"
      "and written to the current directory or the path given by -o.\n"
      "example: %s -c -b schema1.fbs schema2.fbs data.json\n",
      program_name);
  }
  if (parser) delete parser;
  exit(1);
}

int main(int argc, const char *argv[]) {
  program_name = argv[0];
  flatbuffers::IDLOptions opts;
  std::string output_path;
  const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
  bool generator_enabled[num_generators] = { false };
  bool any_generator = false;
  bool print_make_rules = false;
  bool raw_binary = false;
  bool schema_binary = false;
  std::vector<std::string> filenames;
  std::vector<const char *> include_directories;
  size_t binary_files_from = std::numeric_limits<size_t>::max();
  for (int argi = 1; argi < argc; argi++) {
    std::string arg = argv[argi];
    if (arg[0] == '-') {
      if (filenames.size() && arg[1] != '-')
        Error("invalid option location: " + arg, true);
      if (arg == "-o") {
        if (++argi >= argc) Error("missing path following: " + arg, true);
        output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
      } else if(arg == "-I") {
        if (++argi >= argc) Error("missing path following" + arg, true);
        include_directories.push_back(argv[argi]);
      } else if(arg == "--strict-json") {
        opts.strict_json = true;
      } else if(arg == "--no-js-exports") {
        opts.skip_js_exports = true;
      } else if(arg == "--defaults-json") {
        opts.output_default_scalars_in_json = true;
      } else if (arg == "--unknown-json") {
        opts.skip_unexpected_fields_in_json = true;
      } else if(arg == "--no-prefix") {
        opts.prefixed_enums = false;
      } else if(arg == "--scoped-enums") {
        opts.prefixed_enums = false;
        opts.scoped_enums = true;
      } else if(arg == "--gen-mutable") {
        opts.mutable_buffer = true;
      } else if(arg == "--gen-all") {
        opts.generate_all = true;
        opts.include_dependence_headers = false;
      } else if(arg == "--gen-includes") {
        // Deprecated, remove this option some time in the future.
        printf("warning: --gen-includes is deprecated (it is now default)\n");
      } else if(arg == "--no-includes") {
        opts.include_dependence_headers = false;
      } else if (arg == "--gen-onefile") {
        opts.one_file = true;
      } else if (arg == "--raw-binary") {
        raw_binary = true;
      } else if(arg == "--") {  // Separator between text and binary inputs.
        binary_files_from = filenames.size();
      } else if(arg == "--proto") {
        opts.proto_mode = true;
      } else if(arg == "--schema") {
        schema_binary = true;
      } else if(arg == "-M") {
        print_make_rules = true;
      } else if(arg == "--version") {
        printf("flatc version %s\n", FLATC_VERSION);
        exit(0);
      } else {
        for (size_t i = 0; i < num_generators; ++i) {
          if (arg == generators[i].generator_opt_long ||
              (generators[i].generator_opt_short &&
               arg == generators[i].generator_opt_short)) {
            generator_enabled[i] = true;
            any_generator = true;
            goto found;
          }
        }
        Error("unknown commandline argument" + arg, true);
        found:;
      }
    } else {
      filenames.push_back(argv[argi]);
    }
  }

  if (!filenames.size()) Error("missing input files", false, true);

  if (opts.proto_mode) {
    if (any_generator)
      Error("cannot generate code directly from .proto files", true);
  } else if (!any_generator) {
    Error("no options: specify at least one generator.", true);
  }

  // Now process the files:
  parser = new flatbuffers::Parser(opts);
  for (auto file_it = filenames.begin();
            file_it != filenames.end();
          ++file_it) {
      std::string contents;
      if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
        Error("unable to load file: " + *file_it);

      bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
                       binary_files_from;
      if (is_binary) {
        parser->builder_.Clear();
        parser->builder_.PushFlatBuffer(
          reinterpret_cast<const uint8_t *>(contents.c_str()),
          contents.length());
        if (!raw_binary) {
          // Generally reading binaries that do not correspond to the schema
          // will crash, and sadly there's no way around that when the binary
          // does not contain a file identifier.
          // We'd expect that typically any binary used as a file would have
          // such an identifier, so by default we require them to match.
          if (!parser->file_identifier_.length()) {
            Error("current schema has no file_identifier: cannot test if \"" +
                 *file_it +
                 "\" matches the schema, use --raw-binary to read this file"
                 " anyway.");
          } else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
                                             parser->file_identifier_.c_str())) {
            Error("binary \"" +
                 *file_it +
                 "\" does not have expected file_identifier \"" +
                 parser->file_identifier_ +
                 "\", use --raw-binary to read this file anyway.");
          }
        }
      } else {
        // Check if file contains 0 bytes.
        if (contents.length() != strlen(contents.c_str())) {
          Error("input file appears to be binary: " + *file_it, true);
        }
        if (flatbuffers::GetExtension(*file_it) == "fbs") {
          // If we're processing multiple schemas, make sure to start each
          // one from scratch. If it depends on previous schemas it must do
          // so explicitly using an include.
          delete parser;
          parser = new flatbuffers::Parser(opts);
        }
        auto local_include_directory = flatbuffers::StripFileName(*file_it);
        include_directories.push_back(local_include_directory.c_str());
        include_directories.push_back(nullptr);
        if (!parser->Parse(contents.c_str(), &include_directories[0],
                          file_it->c_str()))
          Error(parser->error_, false, false);
        if (schema_binary) {
          parser->Serialize();
          parser->file_extension_ = reflection::SchemaExtension();
        }
        include_directories.pop_back();
        include_directories.pop_back();
      }

      std::string filebase = flatbuffers::StripPath(
                               flatbuffers::StripExtension(*file_it));

      for (size_t i = 0; i < num_generators; ++i) {
        parser->opts.lang = generators[i].lang;
        if (generator_enabled[i]) {
          if (!print_make_rules) {
            flatbuffers::EnsureDirExists(output_path);
            if (!generators[i].generate(*parser, output_path, filebase)) {
              Error(std::string("Unable to generate ") +
                    generators[i].lang_name +
                    " for " +
                    filebase);
            }
          } else {
            std::string make_rule = generators[i].make_rule(
                *parser, output_path, *file_it);
            if (!make_rule.empty())
              printf("%s\n", flatbuffers::WordWrap(
                  make_rule, 80, " ", " \\").c_str());
          }
        }
      }

      if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);

      // We do not want to generate code for the definitions in this file
      // in any files coming up next.
      parser->MarkGenerated();
  }

  delete parser;
  return 0;
}
<|endoftext|>


<commit_before>#ifndef     _IAGENT_HH_
# define    _IAGENT_HH_

#include <string>

#include <pcl-1.7/pcl/common/common.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <pcl-1.7/pcl/common/projection_matrix.h>

#include "event/Dispatcher.h"
#include "Capture.hh"

class       IAgent : public Utils::Dispatcher
{
public:

    //Defined in IAgent.cpp
    static const double DEGREESPERSCAN; // meter
    static const double CAMERAPROBLEM; // meter

    IAgent(double degreePerScan = DEGREESPERSCAN, double cameraProblem = CAMERAPROBLEM, std::string const &name = "Default");
    virtual ~IAgent();

    pcl::PointXYZ   const   &getPos() const;
    double          getBearing() const;
    Capture const &getCapture() const;

    void            setBearing(double bearing);
    void            setPos(pcl::PointXYZ const &pos);
    void            setPos(double x, double y, double z);

    virtual pcl::PointCloud<pcl::PointXYZ> const &takeData() = 0;
    virtual void            updateState() = 0;
    virtual void            goTowardsGoal() = 0;

    inline std::string const &name() const { return (_name); }

    double const    degreePerScan;
    double const    cameraProblem;

protected:
    double          _bearing;
    pcl::PointXYZ   _pos;
    std::string     _name;
    Capture         _capture;

public:
    //Use to align class with pointCloud
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

#endif      /* !_IAGENT_HH_ */
<commit_msg>Agent: add status to agent (in string)<commit_after>#ifndef     _IAGENT_HH_
# define    _IAGENT_HH_

#include <string>

#include <pcl-1.7/pcl/common/common.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <pcl-1.7/pcl/common/projection_matrix.h>

#include "event/Dispatcher.h"
#include "Capture.hh"

class       IAgent : public Utils::Dispatcher
{
public:

    //Defined in IAgent.cpp
    static const double DEGREESPERSCAN; // meter
    static const double CAMERAPROBLEM; // meter

    IAgent(double degreePerScan = DEGREESPERSCAN, double cameraProblem = CAMERAPROBLEM, std::string const &name = "Default");
    virtual ~IAgent();

    pcl::PointXYZ   const   &getPos() const;
    double          getBearing() const;
    Capture const &getCapture() const;

    void            setBearing(double bearing);
    void            setPos(pcl::PointXYZ const &pos);
    void            setPos(double x, double y, double z);

    virtual pcl::PointCloud<pcl::PointXYZ> const &takeData() = 0;
    virtual void            updateState() = 0;
    virtual void            goTowardsGoal() = 0;

    inline std::string const &name() const { return (_name); }
    inline std::string const &status() const {return (_status) ;}
    inline std::string const &status(std::string const &status) {_status = status; return (_status);}

    double const    degreePerScan;
    double const    cameraProblem;

protected:
    double          _bearing;
    pcl::PointXYZ   _pos;
    std::string     _name;
    std::string     _status;
    Capture         _capture;

public:
    //Use to align class with pointCloud
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

#endif      /* !_IAGENT_HH_ */
<|endoftext|>