<commit_before>/* Copyright 2014 Jonas Platte
 *
 * This file is part of Cyvasse Online.
 *
 * Cyvasse Online is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * Cyvasse Online 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _HEXAGONAL_BOARD_HPP_
#define _HEXAGONAL_BOARD_HPP_

#include <unordered_map>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <featherkit/rendering/renderer2d.hpp>
#include <featherkit/rendering/quad.hpp>
#include "hexagon.hpp"

template<int l>
class HexagonalBoard
{
	public:
		typedef typename cyvmath::hexagon<l> Hexagon;
		typedef typename Hexagon::Coordinate Coordinate;
		typedef typename std::unordered_map<Coordinate, fea::Quad*, std::hash<int>> tileMap;
		typedef std::vector<fea::Quad*> tileVec;

	private:
		// non-copyable
		HexagonalBoard(const HexagonalBoard&) = delete;
		const HexagonalBoard& operator= (const HexagonalBoard&) = delete;

		fea::Renderer2D& _renderer;

		glm::vec2 _size;
		glm::vec2 _position;
		glm::vec2 _tileSize;

		tileMap _tileMap;
		tileVec _tileVec;

		static int8_t getColorIndex(Coordinate c)
		{
			return (((c.x() - c.y()) % 3) + 3) % 3;
		}

	public:
		glm::vec2 getTilePosition(Coordinate c)
		{
			return {_tileSize.x * c.x() + (_tileSize.x / 2) * (c.y() - (Hexagon::edgeLength - 1)) + _position.x,
			        _size.y - (_tileSize.y * c.y() + _position.y)};
		}

		HexagonalBoard(fea::Renderer2D& renderer, glm::vec2 size, glm::vec2 offset)
			: _renderer(renderer)
			, _size(size)
		{
			// the tiles map never changes so it is set up here instead of in setup()
			fea::Color tileColors[3] = {
					{1.0f, 1.0f, 1.0f},
					{0.8f, 0.8f, 0.8f},
					{0.6f, 0.6f, 0.6f}
				};
			fea::Color tileColorsDark[3] = {
					{0.4f, 0.4f, 0.4f},
					{0.3f, 0.3f, 0.3f},
					{0.2f, 0.2f, 0.2f}
				};

			float tileWidth = _size.x / static_cast<float>(l * 2 - 1);
			_tileSize = {tileWidth, tileWidth / 3 * 2};

			_position = {
					offset.x,
					offset.y + (_size.y - ((l * 2 - 1) * _tileSize.y)) / 2
				};

			for(Coordinate c : Hexagon::getAllCoordinates())
			{
				fea::Quad* quad = new fea::Quad(_tileSize);

				quad->setPosition(getTilePosition(c));

				// may be no permanent solution
				if(c.y() >= (l - 1))
					quad->setColor(tileColorsDark[getColorIndex(c)]);
				else
					quad->setColor(tileColors[getColorIndex(c)]);

				// add the tile to the map and vector
				_tileVec.push_back(quad);
				std::pair<typename tileMap::iterator, bool> res = _tileMap.insert({c, quad});

				assert(res.second); // assert the insertion was successful
			}
		}

		~HexagonalBoard()
		{
			for(fea::Quad* it : _tileVec)
			{
				delete it;
			}
		}

		const glm::vec2& getTileSize() const
		{
			return _tileSize;
		}

		void tick()
		{
			for(const fea::Quad* it : _tileVec)
			{
				_renderer.queue(*it);
			}
		}
};

#endif // _HEXAGONAL_BOARD_HPP_
<commit_msg>Fixed vertical positioning of the board<commit_after>/* Copyright 2014 Jonas Platte
 *
 * This file is part of Cyvasse Online.
 *
 * Cyvasse Online is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * Cyvasse Online 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _HEXAGONAL_BOARD_HPP_
#define _HEXAGONAL_BOARD_HPP_

#include <unordered_map>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <featherkit/rendering/renderer2d.hpp>
#include <featherkit/rendering/quad.hpp>
#include "hexagon.hpp"

template<int l>
class HexagonalBoard
{
	public:
		typedef typename cyvmath::hexagon<l> Hexagon;
		typedef typename Hexagon::Coordinate Coordinate;
		typedef typename std::unordered_map<Coordinate, fea::Quad*, std::hash<int>> tileMap;
		typedef std::vector<fea::Quad*> tileVec;

	private:
		// non-copyable
		HexagonalBoard(const HexagonalBoard&) = delete;
		const HexagonalBoard& operator= (const HexagonalBoard&) = delete;

		fea::Renderer2D& _renderer;

		glm::vec2 _size;
		glm::vec2 _realSize;
		glm::vec2 _position;
		glm::vec2 _tileSize;

		tileMap _tileMap;
		tileVec _tileVec;

		static int8_t getColorIndex(Coordinate c)
		{
			return (((c.x() - c.y()) % 3) + 3) % 3;
		}

	public:
		glm::vec2 getTilePosition(Coordinate c)
		{
			// TODO: document
			return {_position.x + _tileSize.x * c.x() + (_tileSize.x / 2) * (c.y() - (Hexagon::edgeLength - 1)),
			        _position.y - _tileSize.y + (_realSize.y - (_tileSize.y * c.y()))};
		}

		HexagonalBoard(fea::Renderer2D& renderer, glm::vec2 size, glm::vec2 offset)
			: _renderer(renderer)
			, _size(size)
		{
			// the tiles map never changes so it is set up here instead of in setup()
			fea::Color tileColors[3] = {
					{1.0f, 1.0f, 1.0f},
					{0.8f, 0.8f, 0.8f},
					{0.6f, 0.6f, 0.6f}
				};
			fea::Color tileColorsDark[3] = {
					{0.4f, 0.4f, 0.4f},
					{0.3f, 0.3f, 0.3f},
					{0.2f, 0.2f, 0.2f}
				};

			float tileWidth = _size.x / static_cast<float>(l * 2 - 1);
			_tileSize = {tileWidth, tileWidth / 3 * 2};

			_realSize = {_size.x, (l * 2 - 1) * _tileSize.y};

			_position = {
					offset.x,
					offset.y + (_size.y - _realSize.y) / 2
				};

			for(Coordinate c : Hexagon::getAllCoordinates())
			{
				fea::Quad* quad = new fea::Quad(_tileSize);

				quad->setPosition(getTilePosition(c));

				// may be no permanent solution
				if(c.y() >= (l - 1))
					quad->setColor(tileColorsDark[getColorIndex(c)]);
				else
					quad->setColor(tileColors[getColorIndex(c)]);

				// add the tile to the map and vector
				_tileVec.push_back(quad);
				std::pair<typename tileMap::iterator, bool> res = _tileMap.insert({c, quad});

				assert(res.second); // assert the insertion was successful
			}
		}

		~HexagonalBoard()
		{
			for(fea::Quad* it : _tileVec)
			{
				delete it;
			}
		}

		const glm::vec2& getTileSize() const
		{
			return _tileSize;
		}

		void tick()
		{
			for(const fea::Quad* it : _tileVec)
			{
				_renderer.queue(*it);
			}
		}
};

#endif // _HEXAGONAL_BOARD_HPP_
<|endoftext|>


<commit_before>#include "game/state/base/base.h"
#include "framework/framework.h"
#include "game/state/base/facility.h"
#include "game/state/city/building.h"
#include "game/state/organisation.h"

#include <random>

namespace OpenApoc
{

Base::Base(GameState &state, StateRef<Building> building) : building(building)
{
	corridors = std::vector<std::vector<bool>>(SIZE, std::vector<bool>(SIZE, false));
	for (auto &rect : building->base_layout->baseCorridors)
	{
		for (int x = rect.p0.x; x < rect.p1.x; ++x)
		{
			for (int y = rect.p0.y; y < rect.p1.y; ++y)
			{
				corridors[x][y] = true;
			}
		}
	}
	StateRef<FacilityType> type = {&state, FacilityType::getPrefix() + "ACCESS_LIFT"};
	if (canBuildFacility(type, building->base_layout->baseLift, true) != BuildError::NoError)
	{
		LogError("Building %s has invalid lift location", building->name.c_str());
	}
	else
	{
		buildFacility(type, building->base_layout->baseLift, true);
	}
}

sp<Facility> Base::getFacility(Vec2<int> pos) const
{
	for (auto &facility : facilities)
	{
		if (pos.x >= facility->pos.x && pos.x < facility->pos.x + facility->type->size &&
		    pos.y >= facility->pos.y && pos.y < facility->pos.y + facility->type->size)
		{
			return facility;
		}
	}
	return nullptr;
}

void Base::startingBase(GameState &state)
{
	// Figure out positions available for placement
	std::vector<Vec2<int>> positions;
	for (int x = 0; x < SIZE; ++x)
	{
		for (int y = 0; y < SIZE; ++y)
		{
			if (corridors[x][y] && getFacility({x, y}) == nullptr)
			{
				// FIXME: Store free positions for every possible size?
				positions.push_back({x, y});
			}
		}
	}

	// Randomly fill them with facilities
	for (auto &facilityTypePair : state.initial_facilities)
	{
		auto type = facilityTypePair.first;
		auto count = facilityTypePair.second;
		StateRef<FacilityType> facility = {&state, type};
		while (count > 0)
		{
			if (positions.size() < facility->size * facility->size)
			{
				LogError("Can't place all starting facilities in building %s", building->name.c_str());
				return;
			}

			auto facilityPos = std::uniform_int_distribution<int>(0, positions.size() - 1);
			Vec2<int> random;
			BuildError error;
			do
			{
				random = positions[facilityPos(state.rng)];
				error = canBuildFacility(facility, random, true);
			} while (error != BuildError::NoError); // Try harder

			buildFacility(facility, random, true);

			// Clear used positions
			for (auto pos = positions.begin(); pos != positions.end();)
			{
				if (getFacility(*pos) != nullptr)
				{
					pos = positions.erase(pos);
				}
				else
				{
					++pos;
				}
			}

			count--;
		}
	}
}

Base::BuildError Base::canBuildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free) const
{
	if (pos.x < 0 || pos.y < 0 || pos.x + type->size > SIZE || pos.y + type->size > SIZE)
	{
		return BuildError::OutOfBounds;
	}
	for (int x = pos.x; x < pos.x + type->size; ++x)
	{
		for (int y = pos.y; y < pos.y + type->size; ++y)
		{
			if (!corridors[x][y])
			{
				return BuildError::OutOfBounds;
			}
		}
	}
	for (int x = pos.x; x < pos.x + type->size; ++x)
	{
		for (int y = pos.y; y < pos.y + type->size; ++y)
		{
			if (getFacility({x, y}) != nullptr)
			{
				return BuildError::Occupied;
			}
		}
	}
	if (!free)
	{
		if (!building)
		{
			LogError("Building disappeared");
			return BuildError::OutOfBounds;
		}
		else if (building->owner->balance - type->buildCost < 0)
		{
			return BuildError::NoMoney;
		}
	}
	return BuildError::NoError;
}

void Base::buildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free)
{
	if (canBuildFacility(type, pos, free) == BuildError::NoError)
	{
		auto facility = mksp<Facility>(type);
		facilities.push_back(facility);
		facility->pos = pos;
		if (!free)
		{
			if (!building)
			{
				LogError("Building disappeared");
			}
			else
			{
				building->owner->balance -= type->buildCost;
			}
			facility->buildTime = type->buildTime;
		}
	}
}

Base::BuildError Base::canDestroyFacility(Vec2<int> pos) const
{
	auto facility = getFacility(pos);
	if (facility == nullptr)
	{
		return BuildError::OutOfBounds;
	}
	if (facility->type->fixed)
	{
		return BuildError::Occupied;
	}
	// TODO: Check if facility is in use
	return BuildError::NoError;
}

void Base::destroyFacility(Vec2<int> pos)
{
	if (canDestroyFacility(pos) == BuildError::NoError)
	{
		auto facility = getFacility(pos);
		for (auto f = facilities.begin(); f != facilities.end(); ++f)
		{
			if (*f == facility)
			{
				facilities.erase(f);
				break;
			}
		}
	}
}

template <> sp<Base> StateObject<Base>::get(const GameState &state, const UString &id)
{
	auto it = state.player_bases.find(id);
	if (it == state.player_bases.end())
	{
		LogError("No baseas matching ID \"%s\"", id.c_str());
		return nullptr;
	}
	return it->second;
}

template <> const UString &StateObject<Base>::getPrefix()
{
	static UString prefix = "BASE_";
	return prefix;
}
template <> const UString &StateObject<Base>::getTypeName()
{
	static UString name = "Base";
	return name;
}
template <> const UString &StateObject<Base>::getId(const GameState &state, const sp<Base> ptr)
{
	static const UString emptyString = "";
	for (auto &b : state.player_bases)
	{
		if (b.second == ptr)
			return b.first;
	}
	LogError("No base matching pointer %p", ptr.get());
	return emptyString;
}
}; // namespace OpenApoc
<commit_msg>format<commit_after>#include "game/state/base/base.h"
#include "framework/framework.h"
#include "game/state/base/facility.h"
#include "game/state/city/building.h"
#include "game/state/organisation.h"

#include <random>

namespace OpenApoc
{

Base::Base(GameState &state, StateRef<Building> building) : building(building)
{
	corridors = std::vector<std::vector<bool>>(SIZE, std::vector<bool>(SIZE, false));
	for (auto &rect : building->base_layout->baseCorridors)
	{
		for (int x = rect.p0.x; x < rect.p1.x; ++x)
		{
			for (int y = rect.p0.y; y < rect.p1.y; ++y)
			{
				corridors[x][y] = true;
			}
		}
	}
	StateRef<FacilityType> type = {&state, FacilityType::getPrefix() + "ACCESS_LIFT"};
	if (canBuildFacility(type, building->base_layout->baseLift, true) != BuildError::NoError)
	{
		LogError("Building %s has invalid lift location", building->name.c_str());
	}
	else
	{
		buildFacility(type, building->base_layout->baseLift, true);
	}
}

sp<Facility> Base::getFacility(Vec2<int> pos) const
{
	for (auto &facility : facilities)
	{
		if (pos.x >= facility->pos.x && pos.x < facility->pos.x + facility->type->size &&
		    pos.y >= facility->pos.y && pos.y < facility->pos.y + facility->type->size)
		{
			return facility;
		}
	}
	return nullptr;
}

void Base::startingBase(GameState &state)
{
	// Figure out positions available for placement
	std::vector<Vec2<int>> positions;
	for (int x = 0; x < SIZE; ++x)
	{
		for (int y = 0; y < SIZE; ++y)
		{
			if (corridors[x][y] && getFacility({x, y}) == nullptr)
			{
				// FIXME: Store free positions for every possible size?
				positions.push_back({x, y});
			}
		}
	}

	// Randomly fill them with facilities
	for (auto &facilityTypePair : state.initial_facilities)
	{
		auto type = facilityTypePair.first;
		auto count = facilityTypePair.second;
		StateRef<FacilityType> facility = {&state, type};
		while (count > 0)
		{
			if (positions.size() < facility->size * facility->size)
			{
				LogError("Can't place all starting facilities in building %s",
				         building->name.c_str());
				return;
			}

			auto facilityPos = std::uniform_int_distribution<int>(0, positions.size() - 1);
			Vec2<int> random;
			BuildError error;
			do
			{
				random = positions[facilityPos(state.rng)];
				error = canBuildFacility(facility, random, true);
			} while (error != BuildError::NoError); // Try harder

			buildFacility(facility, random, true);

			// Clear used positions
			for (auto pos = positions.begin(); pos != positions.end();)
			{
				if (getFacility(*pos) != nullptr)
				{
					pos = positions.erase(pos);
				}
				else
				{
					++pos;
				}
			}

			count--;
		}
	}
}

Base::BuildError Base::canBuildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free) const
{
	if (pos.x < 0 || pos.y < 0 || pos.x + type->size > SIZE || pos.y + type->size > SIZE)
	{
		return BuildError::OutOfBounds;
	}
	for (int x = pos.x; x < pos.x + type->size; ++x)
	{
		for (int y = pos.y; y < pos.y + type->size; ++y)
		{
			if (!corridors[x][y])
			{
				return BuildError::OutOfBounds;
			}
		}
	}
	for (int x = pos.x; x < pos.x + type->size; ++x)
	{
		for (int y = pos.y; y < pos.y + type->size; ++y)
		{
			if (getFacility({x, y}) != nullptr)
			{
				return BuildError::Occupied;
			}
		}
	}
	if (!free)
	{
		if (!building)
		{
			LogError("Building disappeared");
			return BuildError::OutOfBounds;
		}
		else if (building->owner->balance - type->buildCost < 0)
		{
			return BuildError::NoMoney;
		}
	}
	return BuildError::NoError;
}

void Base::buildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free)
{
	if (canBuildFacility(type, pos, free) == BuildError::NoError)
	{
		auto facility = mksp<Facility>(type);
		facilities.push_back(facility);
		facility->pos = pos;
		if (!free)
		{
			if (!building)
			{
				LogError("Building disappeared");
			}
			else
			{
				building->owner->balance -= type->buildCost;
			}
			facility->buildTime = type->buildTime;
		}
	}
}

Base::BuildError Base::canDestroyFacility(Vec2<int> pos) const
{
	auto facility = getFacility(pos);
	if (facility == nullptr)
	{
		return BuildError::OutOfBounds;
	}
	if (facility->type->fixed)
	{
		return BuildError::Occupied;
	}
	// TODO: Check if facility is in use
	return BuildError::NoError;
}

void Base::destroyFacility(Vec2<int> pos)
{
	if (canDestroyFacility(pos) == BuildError::NoError)
	{
		auto facility = getFacility(pos);
		for (auto f = facilities.begin(); f != facilities.end(); ++f)
		{
			if (*f == facility)
			{
				facilities.erase(f);
				break;
			}
		}
	}
}

template <> sp<Base> StateObject<Base>::get(const GameState &state, const UString &id)
{
	auto it = state.player_bases.find(id);
	if (it == state.player_bases.end())
	{
		LogError("No baseas matching ID \"%s\"", id.c_str());
		return nullptr;
	}
	return it->second;
}

template <> const UString &StateObject<Base>::getPrefix()
{
	static UString prefix = "BASE_";
	return prefix;
}
template <> const UString &StateObject<Base>::getTypeName()
{
	static UString name = "Base";
	return name;
}
template <> const UString &StateObject<Base>::getId(const GameState &state, const sp<Base> ptr)
{
	static const UString emptyString = "";
	for (auto &b : state.player_bases)
	{
		if (b.second == ptr)
			return b.first;
	}
	LogError("No base matching pointer %p", ptr.get());
	return emptyString;
}
}; // namespace OpenApoc
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <utility>
#include <iostream>
#include <streambuf>
#include <tuple>

namespace NSaveLoad {

template<class T, typename E = void>
class TSerializer {
public:
    static void Save(std::ostream& out, const T& object) {
        object.Save(out);
    }
    static void Load(std::istream& in, T& object) {
        object.Load(in);
    }
};

template <class T>
static inline void Save(std::ostream& out, const T& t);

template <class T>
static inline void Load(std::istream& in, T& t);

template <class A, class B>
class TSerializer<std::pair<A, B> > {
public:
    static void Save(std::ostream& out, const std::pair<A, B>& object) {
        NSaveLoad::Save(out, object.first);
        NSaveLoad::Save(out, object.second);
    }
    static void Load(std::istream& in, std::pair<A, B>& object) {
        NSaveLoad::Load(in, object.first);
        NSaveLoad::Load(in, object.second);
    }
};

template<std::size_t> struct int_{};

template <class Tuple, size_t Pos>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<Pos>) {
    SaveTuple(out, tuple, int_<Pos-1>());
    NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}

template <class Tuple>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<1>) {
    NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}

template <class Tuple, size_t Pos>
void LoadTuple(std::istream& in, Tuple& tuple, int_<Pos>) {
    LoadTuple(in, tuple, int_<Pos-1>());
    NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}

template <class Tuple>
void LoadTuple(std::istream& in, Tuple& tuple, int_<1>) {
    NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}

template <class... Args>
class TSerializer<std::tuple<Args...>> {
public:
    static void Save(std::ostream& out, const std::tuple<Args...>& object) {
        SaveTuple(out, object, int_<sizeof...(Args)>());
    }
    static void Load(std::istream& in, std::tuple<Args...>& object) {
        LoadTuple(in, object, int_<sizeof...(Args)>());
    }
};

template<class TVec, class TObj>
class TVectorSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        unsigned short size = object.size();
        out.write((const char*)(&size), 2);
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        unsigned short size;
        in.read((char*)(&size), 2);
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            TObj obj;
            NSaveLoad::Load(in, obj);
            object.push_back(std::move(obj));
        }
    }
};

template<class TVec, class TKey, class TValue>
class TMapSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        unsigned short size = object.size();
        out.write((const char*)(&size), 2);
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        unsigned short size;
        in.read((char*)(&size), 2);
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            std::pair<TKey, TValue> obj;
            NSaveLoad::Load(in, obj);
            object.insert(std::move(obj));
        }
    }
};

template<class TVec, class TObj>
class TSetSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        unsigned short size = object.size();
        out.write((const char*)(&size), 2);
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        unsigned short size;
        in.read((char*)(&size), 2);
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            TObj obj;
            NSaveLoad::Load(in, obj);
            object.insert(std::move(obj));
        }
    }
};

template <class T> class TSerializer<std::vector<T> >: public TVectorSerializer<std::vector<T>, T > {};
template <class T> class TSerializer<std::list<T> >: public TVectorSerializer<std::list<T>, T > {};
template <> class TSerializer<std::string>: public TVectorSerializer<std::string, char> {};
template <> class TSerializer<std::wstring>: public TVectorSerializer<std::wstring, wchar_t> {};
template <class K, class V> class TSerializer<std::map<K, V> >: public TMapSerializer<std::map<K, V>, K, V > {};
template <class K, class V, class H> class TSerializer<std::unordered_map<K, V, H> >: public TMapSerializer<std::unordered_map<K, V, H>, K, V > {};
template <class T> class TSerializer<std::set<T> >: public TSetSerializer<std::set<T>, T > {};
template <class T> class TSerializer<std::unordered_set<T> >: public TSetSerializer<std::unordered_set<T>, T > {};

template <class T>
class TPodSerializer {
public:
    static inline void Save(std::ostream& out, const T& object) {
        out.write((const char*)(&object), sizeof(T));
    }
    static inline void Load(std::istream& in, T& object) {
        in.read((char*)(&object), sizeof(T));
    }
};

template<class T>
class TSerializer<T, typename std::enable_if<!std::is_class<T>::value>::type>: public TPodSerializer<T> {};

template <class T>
static inline void Save(std::ostream& out, const T& t) {
    TSerializer<T>::Save(out, t);
}

template<class T, class... Args>
static inline void Save(std::ostream& out, T first, Args... args) {
    NSaveLoad::Save(out, first);
    NSaveLoad::Save(out, args...);
}

template <class T>
static inline void Load(std::istream& in, T& t) {
    TSerializer<T>::Load(in, t);
}

template <class T, class... Args>
static inline void Load(std::istream& in, T& first, Args&... args) {
    NSaveLoad::Load(in, first);
    NSaveLoad::Load(in, args...);
}

#define SAVELOAD(...) \
    inline virtual void Save(std::ostream& out) const { \
        NSaveLoad::Save(out, __VA_ARGS__);             \
    } \
 \
    inline virtual void Load(std::istream& in) { \
        NSaveLoad::Load(in, __VA_ARGS__);             \
    }

struct membuf: std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*>(base));
        this->setg(p, p, p + size);
    }
};
struct imemstream: virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size)
        , std::istream(static_cast<std::streambuf*>(this)) {
    }
};

#define SAVELOAD_POD(TypeName) template <> class TSerializer<TypeName>: public TPodSerializer<TypeName> {};

} // NSaveLoad
<commit_msg>increased container size<commit_after>#pragma once

#include <string>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <utility>
#include <iostream>
#include <streambuf>
#include <tuple>

namespace NSaveLoad {

template<class T, typename E = void>
class TSerializer {
public:
    static void Save(std::ostream& out, const T& object) {
        object.Save(out);
    }
    static void Load(std::istream& in, T& object) {
        object.Load(in);
    }
};

template <class T>
static inline void Save(std::ostream& out, const T& t);

template <class T>
static inline void Load(std::istream& in, T& t);

template <class A, class B>
class TSerializer<std::pair<A, B> > {
public:
    static void Save(std::ostream& out, const std::pair<A, B>& object) {
        NSaveLoad::Save(out, object.first);
        NSaveLoad::Save(out, object.second);
    }
    static void Load(std::istream& in, std::pair<A, B>& object) {
        NSaveLoad::Load(in, object.first);
        NSaveLoad::Load(in, object.second);
    }
};

template<std::size_t> struct int_{};

template <class Tuple, size_t Pos>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<Pos>) {
    SaveTuple(out, tuple, int_<Pos-1>());
    NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}

template <class Tuple>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<1>) {
    NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}

template <class Tuple, size_t Pos>
void LoadTuple(std::istream& in, Tuple& tuple, int_<Pos>) {
    LoadTuple(in, tuple, int_<Pos-1>());
    NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}

template <class Tuple>
void LoadTuple(std::istream& in, Tuple& tuple, int_<1>) {
    NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}

template <class... Args>
class TSerializer<std::tuple<Args...>> {
public:
    static void Save(std::ostream& out, const std::tuple<Args...>& object) {
        SaveTuple(out, object, int_<sizeof...(Args)>());
    }
    static void Load(std::istream& in, std::tuple<Args...>& object) {
        LoadTuple(in, object, int_<sizeof...(Args)>());
    }
};

template<class TVec, class TObj>
class TVectorSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        uint32_t size = object.size();
        out.write((const char*)(&size), sizeof(size));
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        uint32_t size;
        in.read((char*)(&size), sizeof(size));
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            TObj obj;
            NSaveLoad::Load(in, obj);
            object.push_back(std::move(obj));
        }
    }
};

template<class TVec, class TKey, class TValue>
class TMapSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        uint32_t size = object.size();
        out.write((const char*)(&size), sizeof(size));
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        uint32_t size;
        in.read((char*)(&size), sizeof(size));
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            std::pair<TKey, TValue> obj;
            NSaveLoad::Load(in, obj);
            object.insert(std::move(obj));
        }
    }
};

template<class TVec, class TObj>
class TSetSerializer {
public:
    static inline void Save(std::ostream& out, const TVec& object) {
        uint32_t size = object.size();
        out.write((const char*)(&size), sizeof(size));
        for (const auto& obj: object) {
            NSaveLoad::Save(out, obj);
        }
    }

    static inline void Load(std::istream& in, TVec& object) {
        uint32_t size;
        in.read((char*)(&size), sizeof(size));
        object.clear();
        for (size_t i = 0; i < size; ++i) {
            TObj obj;
            NSaveLoad::Load(in, obj);
            object.insert(std::move(obj));
        }
    }
};

template <class T> class TSerializer<std::vector<T> >: public TVectorSerializer<std::vector<T>, T > {};
template <class T> class TSerializer<std::list<T> >: public TVectorSerializer<std::list<T>, T > {};
template <> class TSerializer<std::string>: public TVectorSerializer<std::string, char> {};
template <> class TSerializer<std::wstring>: public TVectorSerializer<std::wstring, wchar_t> {};
template <class K, class V> class TSerializer<std::map<K, V> >: public TMapSerializer<std::map<K, V>, K, V > {};
template <class K, class V, class H> class TSerializer<std::unordered_map<K, V, H> >: public TMapSerializer<std::unordered_map<K, V, H>, K, V > {};
template <class T> class TSerializer<std::set<T> >: public TSetSerializer<std::set<T>, T > {};
template <class T> class TSerializer<std::unordered_set<T> >: public TSetSerializer<std::unordered_set<T>, T > {};

template <class T>
class TPodSerializer {
public:
    static inline void Save(std::ostream& out, const T& object) {
        out.write((const char*)(&object), sizeof(T));
    }
    static inline void Load(std::istream& in, T& object) {
        in.read((char*)(&object), sizeof(T));
    }
};

template<class T>
class TSerializer<T, typename std::enable_if<!std::is_class<T>::value>::type>: public TPodSerializer<T> {};

template <class T>
static inline void Save(std::ostream& out, const T& t) {
    TSerializer<T>::Save(out, t);
}

template<class T, class... Args>
static inline void Save(std::ostream& out, T first, Args... args) {
    NSaveLoad::Save(out, first);
    NSaveLoad::Save(out, args...);
}

template <class T>
static inline void Load(std::istream& in, T& t) {
    TSerializer<T>::Load(in, t);
}

template <class T, class... Args>
static inline void Load(std::istream& in, T& first, Args&... args) {
    NSaveLoad::Load(in, first);
    NSaveLoad::Load(in, args...);
}

#define SAVELOAD(...) \
    inline virtual void Save(std::ostream& out) const { \
        NSaveLoad::Save(out, __VA_ARGS__);             \
    } \
 \
    inline virtual void Load(std::istream& in) { \
        NSaveLoad::Load(in, __VA_ARGS__);             \
    }

struct membuf: std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*>(base));
        this->setg(p, p, p + size);
    }
};
struct imemstream: virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size)
        , std::istream(static_cast<std::streambuf*>(this)) {
    }
};

#define SAVELOAD_POD(TypeName) template <> class TSerializer<TypeName>: public TPodSerializer<TypeName> {};

} // NSaveLoad
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/browser/browser_child_process_host_iterator.h"

#include "base/logging.h"
#include "content/browser/browser_child_process_host_impl.h"
#include "content/public/browser/browser_thread.h"

namespace content {

BrowserChildProcessHostIterator::BrowserChildProcessHostIterator()
    : all_(true), process_type_(PROCESS_TYPE_UNKNOWN) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
        "BrowserChildProcessHostIterator must be used on the IO thread.";
  iterator_ = BrowserChildProcessHostImpl::GetIterator()->begin();
}

BrowserChildProcessHostIterator::BrowserChildProcessHostIterator(int type)
    : all_(false), process_type_(type) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
        "BrowserChildProcessHostIterator must be used on the IO thread.";
  iterator_ = BrowserChildProcessHostImpl::GetIterator()->begin();
  if (!Done() && (*iterator_)->GetData().process_type != process_type_)
    ++(*this);
}

bool BrowserChildProcessHostIterator::operator++() {
  CHECK(!Done());
  do {
    ++iterator_;
    if (Done())
      break;

    if (!all_ && (*iterator_)->GetData().process_type != process_type_)
      continue;

    return true;
  } while (true);

  return false;
}

bool BrowserChildProcessHostIterator::Done() {
  return iterator_ == BrowserChildProcessHostImpl::GetIterator()->end();
}

const ChildProcessData& BrowserChildProcessHostIterator::GetData() {
  CHECK(!Done());
  return (*iterator_)->GetData();
}

bool BrowserChildProcessHostIterator::Send(IPC::Message* message) {
  CHECK(!Done());
  return (*iterator_)->Send(message);
}

BrowserChildProcessHostDelegate*
    BrowserChildProcessHostIterator::GetDelegate() {
  return (*iterator_)->delegate();
}

}  // namespace content
<commit_msg>Warn users against using an API when it will not behave as they expect.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/browser/browser_child_process_host_iterator.h"

#include "base/logging.h"
#include "content/browser/browser_child_process_host_impl.h"
#include "content/public/browser/browser_thread.h"

namespace content {

BrowserChildProcessHostIterator::BrowserChildProcessHostIterator()
    : all_(true), process_type_(PROCESS_TYPE_UNKNOWN) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
      "BrowserChildProcessHostIterator must be used on the IO thread.";
  iterator_ = BrowserChildProcessHostImpl::GetIterator()->begin();
}

BrowserChildProcessHostIterator::BrowserChildProcessHostIterator(int type)
    : all_(false), process_type_(type) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
      "BrowserChildProcessHostIterator must be used on the IO thread.";
  DCHECK_NE(PROCESS_TYPE_RENDERER, type) <<
      "BrowserChildProcessHostIterator doesn't work for renderer processes; "
      "try RenderProcessHost::AllHostsIterator() instead.";
  iterator_ = BrowserChildProcessHostImpl::GetIterator()->begin();
  if (!Done() && (*iterator_)->GetData().process_type != process_type_)
    ++(*this);
}

bool BrowserChildProcessHostIterator::operator++() {
  CHECK(!Done());
  do {
    ++iterator_;
    if (Done())
      break;

    if (!all_ && (*iterator_)->GetData().process_type != process_type_)
      continue;

    return true;
  } while (true);

  return false;
}

bool BrowserChildProcessHostIterator::Done() {
  return iterator_ == BrowserChildProcessHostImpl::GetIterator()->end();
}

const ChildProcessData& BrowserChildProcessHostIterator::GetData() {
  CHECK(!Done());
  return (*iterator_)->GetData();
}

bool BrowserChildProcessHostIterator::Send(IPC::Message* message) {
  CHECK(!Done());
  return (*iterator_)->Send(message);
}

BrowserChildProcessHostDelegate*
    BrowserChildProcessHostIterator::GetDelegate() {
  return (*iterator_)->delegate();
}

}  // namespace content
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "lowmemprovider.h"
#include "boolsysfspooler.h"

QHash<QString, QVariant> values;
QList<Context*> contexts;
BoolSysFsPooler *lowWatermark;
BoolSysFsPooler *highWatermark;

/* Helpers */

void emitFirstOn(const QString &name)
{
    foreach(Context* context, contexts) {
        if (context->getKey() == name)
            context->fakeFirst();
    }
}

void emitLastOn(const QString &name)
{
    foreach(Context* context, contexts) {
        if (context->getKey() == name)
            context->fakeLast();
    }
}

/* Mocked BoolSysFsPooler */

BoolSysFsPooler::BoolSysFsPooler(const QString &f)
{
    if (f == "/sys/kernel/low_watermark")
        lowWatermark = this;
    else if (f == "/sys/kernel/high_watermark")
        highWatermark = this;
}

BoolSysFsPooler::TriState BoolSysFsPooler::getState()
{
    return state;
}

void BoolSysFsPooler::setState(TriState s)
{
    state = s;
    emit stateChanged(s);
}

/* Mocked Context */

Context::Context(const QString &k, QObject *parent) : key(k)
{
    contexts.append(this);
}

Context::~Context()
{
    contexts.removeAll(this);
}

void Context::set(const QVariant &v)
{
    values.insert(key, v);
}

void Context::unset()
{
    values.insert(key, QVariant());
}

QVariant Context::get()
{
    if (values.contains(key))
        return values.value(key);
    else
        return QVariant();
}

QString Context::getKey()
{
    return key;
}

void Context::fakeFirst()
{
    emit firstSubscriberAppeared(key);
}

void Context::fakeLast()
{
    emit lastSubscriberDisappeared(key);
}

/* LowMemProviderUnitTest */

class LowMemProviderUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void init();
    void cleanup();
    void keys();
    void initialValues();
    void normalState();
    void highState();
    void criticalState();

private:
    LowMemProvider *provider;
};

// Before each test
void LowMemProviderUnitTest::init()
{
    provider = new LowMemProvider();
    provider->initialize();
}

// After each test
void LowMemProviderUnitTest::cleanup()
{
    delete provider;
}

void LowMemProviderUnitTest::keys()
{
    QStringList keys = provider->keys();
    QVERIFY(keys.contains("System.MemoryPressure"));
}

void LowMemProviderUnitTest::initialValues()
{
    QCOMPARE(Context("System.MemoryPressure").get(), QVariant());
}

void LowMemProviderUnitTest::normalState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateFalse);
    highWatermark->setState(BoolSysFsPooler::TriStateFalse);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 0);
}

void LowMemProviderUnitTest::highState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateTrue);
    highWatermark->setState(BoolSysFsPooler::TriStateFalse);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 1);
}

void LowMemProviderUnitTest::criticalState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateTrue);
    highWatermark->setState(BoolSysFsPooler::TriStateTrue);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 2);
}

#include "lowmemproviderunittest.moc"
QTEST_MAIN(LowMemProviderUnitTest);
<commit_msg>100% coverage in lowmemprovider.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "lowmemprovider.h"
#include "boolsysfspooler.h"

QHash<QString, QVariant> values;
QList<Context*> contexts;
BoolSysFsPooler *lowWatermark;
BoolSysFsPooler *highWatermark;

/* Helpers */

void emitFirstOn(const QString &name)
{
    foreach(Context* context, contexts) {
        if (context->getKey() == name)
            context->fakeFirst();
    }
}

void emitLastOn(const QString &name)
{
    foreach(Context* context, contexts) {
        if (context->getKey() == name)
            context->fakeLast();
    }
}

/* Mocked BoolSysFsPooler */

BoolSysFsPooler::BoolSysFsPooler(const QString &f)
{
    if (f == "/sys/kernel/low_watermark")
        lowWatermark = this;
    else if (f == "/sys/kernel/high_watermark")
        highWatermark = this;
}

BoolSysFsPooler::TriState BoolSysFsPooler::getState()
{
    return state;
}

void BoolSysFsPooler::setState(TriState s)
{
    state = s;
    emit stateChanged(s);
}

/* Mocked Context */

Context::Context(const QString &k, QObject *parent) : key(k)
{
    contexts.append(this);
}

Context::~Context()
{
    contexts.removeAll(this);
}

void Context::set(const QVariant &v)
{
    values.insert(key, v);
}

void Context::unset()
{
    values.insert(key, QVariant());
}

QVariant Context::get()
{
    if (values.contains(key))
        return values.value(key);
    else
        return QVariant();
}

QString Context::getKey()
{
    return key;
}

void Context::fakeFirst()
{
    emit firstSubscriberAppeared(key);
}

void Context::fakeLast()
{
    emit lastSubscriberDisappeared(key);
}

/* LowMemProviderUnitTest */

class LowMemProviderUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void init();
    void cleanup();
    void keys();
    void initialValues();
    void normalState();
    void highState();
    void criticalState();
    void rogueState();

private:
    LowMemProvider *provider;
};

// Before each test
void LowMemProviderUnitTest::init()
{
    provider = new LowMemProvider();
    provider->initialize();
}

// After each test
void LowMemProviderUnitTest::cleanup()
{
    delete provider;
}

void LowMemProviderUnitTest::keys()
{
    QStringList keys = provider->keys();
    QVERIFY(keys.contains("System.MemoryPressure"));
}

void LowMemProviderUnitTest::initialValues()
{
    QCOMPARE(Context("System.MemoryPressure").get(), QVariant());
}

void LowMemProviderUnitTest::normalState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateFalse);
    highWatermark->setState(BoolSysFsPooler::TriStateFalse);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 0);

    emitLastOn("System.MemoryPressure");
}

void LowMemProviderUnitTest::highState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateTrue);
    highWatermark->setState(BoolSysFsPooler::TriStateFalse);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 1);

    emitLastOn("System.MemoryPressure");
}

void LowMemProviderUnitTest::criticalState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateTrue);
    highWatermark->setState(BoolSysFsPooler::TriStateTrue);
    QCOMPARE(Context("System.MemoryPressure").get().toInt(), 2);

    emitLastOn("System.MemoryPressure");
}

void LowMemProviderUnitTest::rogueState()
{
    emitFirstOn("System.MemoryPressure");
    QVERIFY(lowWatermark != NULL);
    QVERIFY(highWatermark != NULL);

    lowWatermark->setState(BoolSysFsPooler::TriStateFalse);
    highWatermark->setState(BoolSysFsPooler::TriStateTrue);
    QCOMPARE(Context("System.MemoryPressure").get(), QVariant(0));

    lowWatermark->setState(BoolSysFsPooler::TriStateTrue);
    highWatermark->setState(BoolSysFsPooler::TriStateTrue);
    QCOMPARE(Context("System.MemoryPressure").get(), QVariant(2));

    emitLastOn("System.MemoryPressure");
}

#include "lowmemproviderunittest.moc"
QTEST_MAIN(LowMemProviderUnitTest);
<|endoftext|>


<commit_before>
/* $Id$ */

#include "TChain.h"
#include "TTree.h"

#include "AliAnalysisTaskME.h"
#include "AliAnalysisManager.h"

#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include "AliAODVertex.h"
#include "AliMultiEventInputHandler.h"
#include "AliAODHandler.h"

#include "AliAnalysisTaskCreateMixedDimuons.h"
#include "AliEventPoolMuon.h"
#include "TDatabasePDG.h"
#include "TRandom.h"

// Example of an analysis task creating aod events filled with mixed muon pairs
//
// Authors Alessandro De Falco and Antonio Uras, INFN Cagliari
// alessandro.de.falco@ca.infn.it  antonio.uras@ca.infn.it

#define AliAnalysisTaskCreateMixedDimuons_CXX

ClassImp(AliAnalysisTaskCreateMixedDimuons)

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

AliAnalysisTaskCreateMixedDimuons::AliAnalysisTaskCreateMixedDimuons(const char *name)
: AliAnalysisTaskME(name),
  fBufferSize(0),
  fOutputUserHandler(0x0),
  fOutputUserAOD(0X0),
  fOutputUserAODTree(0X0),
  fPoolMuon(0X0),
  fDebug(0X0)
{

  // Constructor

  // Default input and output containers
  DefineInput (0, TChain::Class());

  // User-defined input and output containers
  DefineOutput(1, TTree::Class());

  // ---------------------------------------------------------------

  fDebug = kFALSE;
  fBufferSize = 0;

  RequireFreshBuffer();

  for (Int_t i=0; i<100; i++) fInputAOD[i] = 0;

  fOutputUserHandler = 0;
  fOutputUserAOD     = 0;
  fOutputUserAODTree = 0;

}

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

void AliAnalysisTaskCreateMixedDimuons::ConnectInputData(Option_t *) {

  // Connect ESD or AOD here
  // Called once

  printf("-> AliAnalysisTaskCreateMixedDimuons::ConnectInputData\n");

  TTree* tree = (TTree*) GetInputData(0);

  if (!tree) {
    Printf("ERROR: Could not read chain from input slot 0");
  }
  else {

    fInputHandler = (AliMultiEventInputHandler*) AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
    fPoolMuon     = (AliEventPoolMuon*)          AliAnalysisManager::GetAnalysisManager()->GetEventPool();
    fBufferSize = fInputHandler->GetBufferSize();
    if (fBufferSize>100) {
      printf("\n*** WARNING AliAnalysisTaskCreateMixedDimuons::ConnectInputData -> Trying to set fBufferSize>100, forcing fBufferSize=100 ***\n\n");
      fBufferSize = 100;
    }

    if (!fInputHandler) Printf("ERROR: Could not get AliMultiAODInputHandler");
    else for (Int_t i=0; i<fBufferSize; i++) fInputAOD[i] = (AliAODEvent*) fInputHandler->GetEvent(i);
  }

  printf("<- AliAnalysisTaskCreateMixedDimuons::ConnectInputData\n");

}

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

void AliAnalysisTaskCreateMixedDimuons::UserCreateOutputObjects() {

  // Here the user-defined output containers should be created!!!
  // Called once

  fOutputUserHandler = new AliAODHandler();

  fOutputUserHandler -> Init("");

  fOutputUserAOD = fOutputUserHandler -> GetAOD();

  fOutputUserAODTree = fOutputUserHandler -> GetTree();

}

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

void AliAnalysisTaskCreateMixedDimuons::UserExec(Option_t *) {

  if (!fOutputUserAOD) {
    Printf("ERROR: fOutputUserAOD not available\n");
    return;
  }

  printf("Calling USER EXEC\n\n");

  for (Int_t iEv=0; iEv<fBufferSize; iEv++) {
    if (!fInputAOD[iEv]) {
      Printf("ERROR: fInputAOD[%d] not available\n",iEv);
      continue;
    }

    for (Int_t jEv=0; jEv<iEv; jEv++) {

      if (!fInputAOD) {
    Printf("ERROR: fInputAOD not available\n");
    return;
  }

      Int_t nTracksEv[2]  = {0};
      Int_t nFWMuonsEv[2] = {0};

      nTracksEv[0] = fInputAOD[iEv]->GetNTracks();
      nTracksEv[1] = fInputAOD[jEv]->GetNTracks();

      for (Int_t i=0; i<nTracksEv[0]; i++) if(fInputAOD[iEv]->GetTrack(i)->IsMuonTrack()) nFWMuonsEv[0]++;
      for (Int_t i=0; i<nTracksEv[1]; i++) if(fInputAOD[jEv]->GetTrack(i)->IsMuonTrack()) nFWMuonsEv[1]++;

      // Muon track mixing to fill a mass spectrum

      if (nFWMuonsEv[0] && nFWMuonsEv[1]) {

	Int_t rndMuonTrack[2] = {0};
	rndMuonTrack[0] = gRandom->Integer(nFWMuonsEv[0]);
	rndMuonTrack[1] = gRandom->Integer(nFWMuonsEv[1]);

	Int_t nFWMUonsAdded = 0;
	Int_t nPosTracksAdded = 0;
	Int_t nNegTracksAdded = 0;

	AliAODVertex *vertex = new AliAODVertex();
	vertex -> SetX(0.0);
	vertex -> SetY(0.0);
	vertex -> SetZ(fPoolMuon->GetMeanPrimaryVertexZ());

	Int_t muonCounter[2] = {0};

	// adding tracks and vertex to the output event...

	for (Int_t i=0; i<nTracksEv[0]; i++) {
	  if(fInputAOD[iEv]->GetTrack(i)->IsMuonTrack()) {
	    if (fDebug) printf("fInputAOD[%d]->GetTrack(%d) = %p    pt = %f     uniqueID = %d\n",
			       iEv,i,fInputAOD[iEv]->GetTrack(i),fInputAOD[iEv]->GetTrack(i)->Pt(),
			       fInputAOD[iEv]->GetTrack(i)->GetUniqueID());
	    if (muonCounter[0]==rndMuonTrack[0]) {
	      fOutputUserAOD->AddTrack(fInputAOD[iEv]->GetTrack(i));
	      nFWMUonsAdded++;
	      if (fInputAOD[iEv]->GetTrack(i)->Charge()>0) nPosTracksAdded++;
	      else nNegTracksAdded++;
	    }
	    muonCounter[0]++;
	  }
	}

	for (Int_t i=0; i<nTracksEv[1]; i++) {
	  if(fInputAOD[jEv]->GetTrack(i)->IsMuonTrack()) {
	    if (fDebug) printf("fInputAOD[%d]->GetTrack(%d) = %p    pt = %f     uniqueID = %d\n",
			       jEv,i,fInputAOD[jEv]->GetTrack(i),fInputAOD[jEv]->GetTrack(i)->Pt(),
			       fInputAOD[jEv]->GetTrack(i)->GetUniqueID());
	    if (muonCounter[1]==rndMuonTrack[1]) {
	      fOutputUserAOD->AddTrack(fInputAOD[jEv]->GetTrack(i));
	      nFWMUonsAdded++;
	      if (fInputAOD[jEv]->GetTrack(i)->Charge()>0) nPosTracksAdded++;
	      else nNegTracksAdded++;
	    }
	    muonCounter[1]++;
	  }
	}

	fOutputUserAOD->AddVertex(vertex);

	// ... done!

	if (fDebug) {
	  for (Int_t i=0; i<nFWMUonsAdded; i++) {
	    AliAODTrack *tr = (AliAODTrack*) fOutputUserAOD->GetTrack(i);
	    printf("fOutputUserAOD->GetTrack(%d) = %p    pt = %f\n",i,tr,tr->Pt());
	  }
	}

	fOutputUserAOD->GetHeader()->SetRefMultiplicity(nFWMUonsAdded);
	fOutputUserAOD->GetHeader()->SetRefMultiplicityPos(nPosTracksAdded);
	fOutputUserAOD->GetHeader()->SetRefMultiplicityNeg(nNegTracksAdded);

	fOutputUserHandler -> FinishEvent();

      }

      PostData(1, fOutputUserAODTree);

    }

  }

}

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

void AliAnalysisTaskCreateMixedDimuons::Terminate(Option_t *) {

  // Called once at the end of the query

  printf("\n\nCalling TERMINATE \n\n\n");

  fOutputUserHandler -> Terminate();

}

//===================================================================================
<commit_msg>Covery fixes (Ivana, Antonio)<commit_after>#include "TChain.h"
#include "TTree.h"

#include "AliAnalysisTaskME.h"
#include "AliAnalysisManager.h"

#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include "AliAODVertex.h"
#include "AliMultiEventInputHandler.h"
#include "AliAODHandler.h"

#include "AliAnalysisTaskCreateMixedDimuons.h"
#include "AliEventPoolMuon.h"
#include "TDatabasePDG.h"
#include "TRandom.h"

// Example of an analysis task creating aod events filled with mixed muon pairs
//
// Authors Alessandro De Falco and Antonio Uras, INFN Cagliari
// alessandro.de.falco@ca.infn.it  antonio.uras@ca.infn.it

#define AliAnalysisTaskCreateMixedDimuons_CXX

ClassImp(AliAnalysisTaskCreateMixedDimuons)

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

AliAnalysisTaskCreateMixedDimuons::AliAnalysisTaskCreateMixedDimuons(const char *name)
: AliAnalysisTaskME(name),
  fBufferSize(0),
  fOutputUserHandler(0x0),
  fOutputUserAOD(0X0),
  fOutputUserAODTree(0X0),
  fPoolMuon(0X0),
  fDebug(0X0)
{

  // Constructor

  // Default input and output containers
  DefineInput (0, TChain::Class());

  // User-defined input and output containers
  DefineOutput(1, TTree::Class());

  // ---------------------------------------------------------------

  fDebug = kFALSE;
  fBufferSize = 0;

  RequireFreshBuffer();

  for (Int_t i=0; i<100; i++) fInputAOD[i] = 0;

  fOutputUserHandler = 0;
  fOutputUserAOD     = 0;
  fOutputUserAODTree = 0;

}

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

void AliAnalysisTaskCreateMixedDimuons::ConnectInputData(Option_t *) {

  // Connect ESD or AOD here
  // Called once

  printf("-> AliAnalysisTaskCreateMixedDimuons::ConnectInputData\n");

  TTree* tree = (TTree*) GetInputData(0);

  if (!tree) {
    Printf("ERROR: Could not read chain from input slot 0");
  }
  else {

    fInputHandler = (AliMultiEventInputHandler*) AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
    fPoolMuon     = (AliEventPoolMuon*)          AliAnalysisManager::GetAnalysisManager()->GetEventPool();

    if (!fInputHandler) {
      Printf("ERROR: Could not get AliMultiAODInputHandler");
    }
    else {
      fBufferSize = fInputHandler->GetBufferSize();
      if (fBufferSize>100) {
        printf("\n*** WARNING AliAnalysisTaskCreateMixedDimuons::ConnectInputData -> Trying to set fBufferSize>100, forcing fBufferSize=100 ***\n\n");
        fBufferSize = 100;
      }
      for (Int_t i=0; i<fBufferSize; i++) fInputAOD[i] = (AliAODEvent*) fInputHandler->GetEvent(i);
    }
  }

  printf("<- AliAnalysisTaskCreateMixedDimuons::ConnectInputData\n");

}

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

void AliAnalysisTaskCreateMixedDimuons::UserCreateOutputObjects() {

  // Here the user-defined output containers should be created!!!
  // Called once

  fOutputUserHandler = new AliAODHandler();

  fOutputUserHandler -> Init("");

  fOutputUserAOD = fOutputUserHandler -> GetAOD();

  fOutputUserAODTree = fOutputUserHandler -> GetTree();

}

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

void AliAnalysisTaskCreateMixedDimuons::UserExec(Option_t *) {

  if (!fInputAOD) {
    Printf("ERROR: fInputAOD not available\n");
    return;
  }

  if (!fOutputUserAOD) {
    Printf("ERROR: fOutputUserAOD not available\n");
    return;
  }

  printf("Calling USER EXEC\n\n");

  for (Int_t iEv=0; iEv<fBufferSize; iEv++) {
    for (Int_t jEv=0; jEv<iEv; jEv++) {

      Int_t nTracksEv[2]  = {0};
      Int_t nFWMuonsEv[2] = {0};

      nTracksEv[0] = fInputAOD[iEv]->GetNTracks();
      nTracksEv[1] = fInputAOD[jEv]->GetNTracks();

      for (Int_t i=0; i<nTracksEv[0]; i++) if(fInputAOD[iEv]->GetTrack(i)->IsMuonTrack()) nFWMuonsEv[0]++;
      for (Int_t i=0; i<nTracksEv[1]; i++) if(fInputAOD[jEv]->GetTrack(i)->IsMuonTrack()) nFWMuonsEv[1]++;

      // Muon track mixing to fill a mass spectrum

      if (nFWMuonsEv[0] && nFWMuonsEv[1]) {

	Int_t rndMuonTrack[2] = {0};
	rndMuonTrack[0] = gRandom->Integer(nFWMuonsEv[0]);
	rndMuonTrack[1] = gRandom->Integer(nFWMuonsEv[1]);

	Int_t nFWMUonsAdded = 0;
	Int_t nPosTracksAdded = 0;
	Int_t nNegTracksAdded = 0;

	AliAODVertex *vertex = new AliAODVertex();
	vertex -> SetX(0.0);
	vertex -> SetY(0.0);
	vertex -> SetZ(fPoolMuon->GetMeanPrimaryVertexZ());

	Int_t muonCounter[2] = {0};

	// adding tracks and vertex to the output event...

	for (Int_t i=0; i<nTracksEv[0]; i++) {
	  if(fInputAOD[iEv]->GetTrack(i)->IsMuonTrack()) {
	    if (fDebug) printf("fInputAOD[%d]->GetTrack(%d) = %p    pt = %f     uniqueID = %d\n",
			       iEv,i,fInputAOD[iEv]->GetTrack(i),fInputAOD[iEv]->GetTrack(i)->Pt(),
			       fInputAOD[iEv]->GetTrack(i)->GetUniqueID());
	    if (muonCounter[0]==rndMuonTrack[0]) {
	      fOutputUserAOD->AddTrack(fInputAOD[iEv]->GetTrack(i));
	      nFWMUonsAdded++;
	      if (fInputAOD[iEv]->GetTrack(i)->Charge()>0) nPosTracksAdded++;
	      else nNegTracksAdded++;
	    }
	    muonCounter[0]++;
	  }
	}

	for (Int_t i=0; i<nTracksEv[1]; i++) {
	  if(fInputAOD[jEv]->GetTrack(i)->IsMuonTrack()) {
	    if (fDebug) printf("fInputAOD[%d]->GetTrack(%d) = %p    pt = %f     uniqueID = %d\n",
			       jEv,i,fInputAOD[jEv]->GetTrack(i),fInputAOD[jEv]->GetTrack(i)->Pt(),
			       fInputAOD[jEv]->GetTrack(i)->GetUniqueID());
	    if (muonCounter[1]==rndMuonTrack[1]) {
	      fOutputUserAOD->AddTrack(fInputAOD[jEv]->GetTrack(i));
	      nFWMUonsAdded++;
	      if (fInputAOD[jEv]->GetTrack(i)->Charge()>0) nPosTracksAdded++;
	      else nNegTracksAdded++;
	    }
	    muonCounter[1]++;
	  }
	}

	fOutputUserAOD->AddVertex(vertex);

	// ... done!

	if (fDebug) {
	  for (Int_t i=0; i<nFWMUonsAdded; i++) {
	    AliAODTrack *tr = (AliAODTrack*) fOutputUserAOD->GetTrack(i);
	    printf("fOutputUserAOD->GetTrack(%d) = %p    pt = %f\n",i,tr,tr->Pt());
	  }
	}

	fOutputUserAOD->GetHeader()->SetRefMultiplicity(nFWMUonsAdded);
	fOutputUserAOD->GetHeader()->SetRefMultiplicityPos(nPosTracksAdded);
	fOutputUserAOD->GetHeader()->SetRefMultiplicityNeg(nNegTracksAdded);

	fOutputUserHandler -> FinishEvent();

      }

      PostData(1, fOutputUserAODTree);

    }

  }

}

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

void AliAnalysisTaskCreateMixedDimuons::Terminate(Option_t *) {

  // Called once at the end of the query

  printf("\n\nCalling TERMINATE \n\n\n");

  fOutputUserHandler -> Terminate();

}

//===================================================================================
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2016, Esteban Tovagliari. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreAppleseed/ParameterAlgo.h"

#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/SplineData.h"
#include "IECore/VectorTypedData.h"

#include "boost/algorithm/string.hpp"
#include "boost/lexical_cast.hpp"

#include "renderer/api/color.h"

using namespace IECore;
using namespace Imath;

using namespace boost;
using namespace std;

namespace asf = foundation;
namespace asr = renderer;

//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////

namespace
{

template<typename Spline>
void declareSplineBasisAndPositions( const InternedString &name, const Spline &spline, asr::ParamArray &params )
{
	string basisParamName = name.string() + "Basis";

	if( spline.basis == Spline::Basis::bezier() )
	{
		params.insert( basisParamName.c_str(), "string bezier" );
	}
	else if( spline.basis == Spline::Basis::bSpline() )
	{
		params.insert( basisParamName.c_str(), "string bspline" );
	}
	else if( spline.basis == Spline::Basis::linear() )
	{
		params.insert( basisParamName.c_str(), "string linear" );
	}
	else
	{
		params.insert( basisParamName.c_str(), "string catmull-rom" );
	}

	stringstream ss;
	ss << "float[] ";
	for( typename Spline::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		ss << it->first << " ";
	}

	string positionsParamName = name.string() + "Positions";
	params.insert( positionsParamName.c_str(), ss.str().c_str() );
}

void declareSpline( const InternedString &name, const Splineff &spline, asr::ParamArray &params )
{
	declareSplineBasisAndPositions( name, spline, params );

	stringstream ss;
	ss << "float[] ";
	for( Splineff::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		ss << it->second << " ";
	}

	string valuesParamName = name.string() + "Values";
	params.insert( valuesParamName.c_str(), ss.str().c_str() );
}

void declareSpline( const InternedString &name, const SplinefColor3f &spline, asr::ParamArray &params )
{
	declareSplineBasisAndPositions( name, spline, params );

	stringstream ss;
	ss << "color[] ";
	for( SplinefColor3f::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		const Color3f &c = it->second;
		ss << c.x << " " << c.y << " " << c.z << " ";
	}

	string valuesParamName = name.string() + "Values";
	params.insert( valuesParamName.c_str(), ss.str().c_str() );
}

}

//////////////////////////////////////////////////////////////////////////
// Implementation of public API.
//////////////////////////////////////////////////////////////////////////

namespace IECoreAppleseed
{

namespace ParameterAlgo
{

string dataToString( const Data *value )
{
	assert( value );

	stringstream ss;

	switch( value->typeId() )
	{
		case IntDataTypeId :
			{
				int x = static_cast<const IntData*>( value )->readable();
				ss << x;
			}
			break;

		case FloatDataTypeId :
			{
				float x = static_cast<const FloatData*>( value )->readable();
				ss << x;
			}
			break;

		case StringDataTypeId :
			{
				const string &x = static_cast<const StringData*>( value )->readable();
				ss << x;
			}
			break;

		case V2iDataTypeId :
			{
				const V2i &x = static_cast<const V2iData*>( value )->readable();
				ss << x.x << ", " << x.y;
			}
			break;

		case Color3fDataTypeId :
			{
				const Color3f &x = static_cast<const Color3fData*>( value )->readable();
				ss << x.x << ", " << x.y << ", " << x.z;
			}
			break;
		case BoolDataTypeId :
			{
				bool x = static_cast<const BoolData*>( value )->readable();
				ss << x;
			}
			break;

		default:
			msg( MessageHandler::Warning, "IECoreAppleseed::dataToString", format( "Unknown data typeid \"%s\"." ) % value->typeName() );
			break;
	}

	return ss.str();
}

string dataToString( ConstDataPtr value )
{
	return dataToString( value.get() );
}

void setParam( const string &name, const Data *value, asr::ParamArray &params )
{
	switch( value->typeId() )
	{
		case IntDataTypeId :
			{
				int x = static_cast<const IntData*>( value )->readable();
				params.insert( name, x );
			}
			break;

		case FloatDataTypeId :
			{
				float x = static_cast<const FloatData*>( value )->readable();
				params.insert( name, x );
			}
			break;

		case StringDataTypeId :
			{
				const string &x = static_cast<const StringData*>( value )->readable();
				params.insert( name, x.c_str() );
			}
			break;

		case BoolDataTypeId :
			{
				bool x = static_cast<const BoolData*>( value )->readable();
				params.insert( name, x );
			}
			break;

		default:
			msg( MessageHandler::Warning, "IECoreAppleseed::setParam", format( "Unknown data typeid \"%s\"." ) % value->typeName() );
			break;
	}
}

asr::ParamArray convertParams( const CompoundDataMap &parameters )
{
	asr::ParamArray result;

	for( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it )
		setParam( it->first.value(), it->second.get(), result );

	return result;
}

asr::ParamArray convertShaderParameters( const CompoundDataMap &parameters )
{
	asr::ParamArray params;

	for( CompoundDataMap::const_iterator it = parameters.begin(), eIt = parameters.end(); it != eIt; ++it )
	{
		std::stringstream ss;

		const Data *data = it->second.get();
		switch( data->typeId() )
		{
			case FloatDataTypeId :
			{
				const float *p = static_cast<const FloatData *>( data )->baseReadable();
				ss << "float " << *p;
			}
			break;

			case IntDataTypeId :
			{
				const int *p = static_cast<const IntData *>( data )->baseReadable();
				ss << "int " << *p;
			}
			break;

			case V3fDataTypeId :
			{
				const float *p = static_cast<const V3fData *>( data )->baseReadable();
				ss << "vector " << p[0] << " " << p[1] << " " << p[2];
			}
			break;

			case Color3fDataTypeId :
			{
				const float *p = static_cast<const Color3fData *>( data )->baseReadable();
				ss << "color " << p[0] << " " << p[1] << " " << p[2];
			}
			break;

			case StringDataTypeId :
			{
				const std::string *p = &(static_cast<const StringData *>( data )->readable() );
				ss << "string " << *p;
			}
			break;

			case M44fDataTypeId:
			{
				const float *p = static_cast<const M44fData *>( data )->baseReadable();
				ss << "matrix ";
				ss << p[ 0] << " " << p[ 1] << " " << p[ 2] << " " << p[ 3] << " ";
				ss << p[ 4] << " " << p[ 5] << " " << p[ 6] << " " << p[ 7] << " ";
				ss << p[ 8] << " " << p[ 9] << " " << p[10] << " " << p[11] << " ";
				ss << p[12] << " " << p[13] << " " << p[14] << " " << p[15];
			}
			break;

			case IntVectorDataTypeId:
			{
				const std::vector<int> &p = static_cast<const IntVectorData *>( data )->readable();
				ss << "int[] ";
				for( size_t i = 0, e = p.size(); i < e; ++i )
				{
					ss << p[i] << " ";
				}
			}
			break;

			case FloatVectorDataTypeId:
			{
				const std::vector<float> &p = static_cast<const FloatVectorData *>( data )->readable();
				ss << "float[] ";
				for( size_t i = 0, e = p.size(); i < e; ++i )
				{
					ss << p[i] << " ";
				}
			}
			break;

			case SplineffDataTypeId:
			{
				const SplineffData *splineData = static_cast<const SplineffData *>( data );
				declareSpline( it->first, splineData->readable(), params );
				continue;
			}
			break;

			case SplinefColor3fDataTypeId:
			{
				const SplinefColor3fData *splineData = static_cast<const SplinefColor3fData *>( data );
				declareSpline( it->first, splineData->readable(), params );
				continue;
			}
			break;

			default:
				msg( Msg::Warning, "AppleseedRenderer", boost::format( "Parameter \"%s\" has unsupported type \"%s\"" ) % it->first.string() % it->second->typeName() );
			break;
		}

		if( !ss.str().empty() )
		{
			params.insert( it->first.c_str(), ss.str() );
		}
	}

	return params;
}

} // namespace ParameterAlgo

} // namespace IECoreAppleseed
<commit_msg>appleseed: remove messages from ParameterAlgo.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2016, Esteban Tovagliari. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreAppleseed/ParameterAlgo.h"

#include "IECore/SimpleTypedData.h"
#include "IECore/SplineData.h"
#include "IECore/VectorTypedData.h"

#include "boost/algorithm/string.hpp"
#include "boost/lexical_cast.hpp"

#include "renderer/api/color.h"

using namespace IECore;
using namespace Imath;

using namespace boost;
using namespace std;

namespace asf = foundation;
namespace asr = renderer;

//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////

namespace
{

template<typename Spline>
void declareSplineBasisAndPositions( const InternedString &name, const Spline &spline, asr::ParamArray &params )
{
	string basisParamName = name.string() + "Basis";

	if( spline.basis == Spline::Basis::bezier() )
	{
		params.insert( basisParamName.c_str(), "string bezier" );
	}
	else if( spline.basis == Spline::Basis::bSpline() )
	{
		params.insert( basisParamName.c_str(), "string bspline" );
	}
	else if( spline.basis == Spline::Basis::linear() )
	{
		params.insert( basisParamName.c_str(), "string linear" );
	}
	else
	{
		params.insert( basisParamName.c_str(), "string catmull-rom" );
	}

	stringstream ss;
	ss << "float[] ";
	for( typename Spline::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		ss << it->first << " ";
	}

	string positionsParamName = name.string() + "Positions";
	params.insert( positionsParamName.c_str(), ss.str().c_str() );
}

void declareSpline( const InternedString &name, const Splineff &spline, asr::ParamArray &params )
{
	declareSplineBasisAndPositions( name, spline, params );

	stringstream ss;
	ss << "float[] ";
	for( Splineff::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		ss << it->second << " ";
	}

	string valuesParamName = name.string() + "Values";
	params.insert( valuesParamName.c_str(), ss.str().c_str() );
}

void declareSpline( const InternedString &name, const SplinefColor3f &spline, asr::ParamArray &params )
{
	declareSplineBasisAndPositions( name, spline, params );

	stringstream ss;
	ss << "color[] ";
	for( SplinefColor3f::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
	{
		const Color3f &c = it->second;
		ss << c.x << " " << c.y << " " << c.z << " ";
	}

	string valuesParamName = name.string() + "Values";
	params.insert( valuesParamName.c_str(), ss.str().c_str() );
}

}

//////////////////////////////////////////////////////////////////////////
// Implementation of public API.
//////////////////////////////////////////////////////////////////////////

namespace IECoreAppleseed
{

namespace ParameterAlgo
{

string dataToString( const Data *value )
{
	assert( value );

	stringstream ss;

	switch( value->typeId() )
	{
		case IntDataTypeId :
		{
			int x = static_cast<const IntData*>( value )->readable();
			ss << x;
		}
		break;

		case FloatDataTypeId :
		{
			float x = static_cast<const FloatData*>( value )->readable();
			ss << x;
		}
		break;

		case StringDataTypeId :
		{
			const string &x = static_cast<const StringData*>( value )->readable();
			ss << x;
		}
		break;

		case V2iDataTypeId :
		{
			const V2i &x = static_cast<const V2iData*>( value )->readable();
			ss << x.x << ", " << x.y;
		}
		break;

		case Color3fDataTypeId :
		{
			const Color3f &x = static_cast<const Color3fData*>( value )->readable();
			ss << x.x << ", " << x.y << ", " << x.z;
		}
		break;

		case BoolDataTypeId :
		{
			bool x = static_cast<const BoolData*>( value )->readable();
			ss << x;
		}
		break;

		default:
		break;
	}

	return ss.str();
}

string dataToString( ConstDataPtr value )
{
	return dataToString( value.get() );
}

void setParam( const string &name, const Data *value, asr::ParamArray &params )
{
	switch( value->typeId() )
	{
		case IntDataTypeId :
		{
			int x = static_cast<const IntData*>( value )->readable();
			params.insert( name, x );
		}
		break;

		case FloatDataTypeId :
		{
			float x = static_cast<const FloatData*>( value )->readable();
			params.insert( name, x );
		}
		break;

		case StringDataTypeId :
		{
			const string &x = static_cast<const StringData*>( value )->readable();
			params.insert( name, x.c_str() );
		}
		break;

		case BoolDataTypeId :
		{
			bool x = static_cast<const BoolData*>( value )->readable();
			params.insert( name, x );
		}
		break;

		default:
		break;
	}
}

asr::ParamArray convertParams( const CompoundDataMap &parameters )
{
	asr::ParamArray result;

	for( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it )
		setParam( it->first.value(), it->second.get(), result );

	return result;
}

asr::ParamArray convertShaderParameters( const CompoundDataMap &parameters )
{
	asr::ParamArray params;

	for( CompoundDataMap::const_iterator it = parameters.begin(), eIt = parameters.end(); it != eIt; ++it )
	{
		std::stringstream ss;

		const Data *data = it->second.get();
		switch( data->typeId() )
		{
			case FloatDataTypeId :
			{
				const float *p = static_cast<const FloatData *>( data )->baseReadable();
				ss << "float " << *p;
			}
			break;

			case IntDataTypeId :
			{
				const int *p = static_cast<const IntData *>( data )->baseReadable();
				ss << "int " << *p;
			}
			break;

			case V3fDataTypeId :
			{
				const float *p = static_cast<const V3fData *>( data )->baseReadable();
				ss << "vector " << p[0] << " " << p[1] << " " << p[2];
			}
			break;

			case Color3fDataTypeId :
			{
				const float *p = static_cast<const Color3fData *>( data )->baseReadable();
				ss << "color " << p[0] << " " << p[1] << " " << p[2];
			}
			break;

			case StringDataTypeId :
			{
				const std::string *p = &(static_cast<const StringData *>( data )->readable() );
				ss << "string " << *p;
			}
			break;

			case M44fDataTypeId:
			{
				const float *p = static_cast<const M44fData *>( data )->baseReadable();
				ss << "matrix ";
				ss << p[ 0] << " " << p[ 1] << " " << p[ 2] << " " << p[ 3] << " ";
				ss << p[ 4] << " " << p[ 5] << " " << p[ 6] << " " << p[ 7] << " ";
				ss << p[ 8] << " " << p[ 9] << " " << p[10] << " " << p[11] << " ";
				ss << p[12] << " " << p[13] << " " << p[14] << " " << p[15];
			}
			break;

			case IntVectorDataTypeId:
			{
				const std::vector<int> &p = static_cast<const IntVectorData *>( data )->readable();
				ss << "int[] ";
				for( size_t i = 0, e = p.size(); i < e; ++i )
				{
					ss << p[i] << " ";
				}
			}
			break;

			case FloatVectorDataTypeId:
			{
				const std::vector<float> &p = static_cast<const FloatVectorData *>( data )->readable();
				ss << "float[] ";
				for( size_t i = 0, e = p.size(); i < e; ++i )
				{
					ss << p[i] << " ";
				}
			}
			break;

			case SplineffDataTypeId:
			{
				const SplineffData *splineData = static_cast<const SplineffData *>( data );
				declareSpline( it->first, splineData->readable(), params );
				continue;
			}
			break;

			case SplinefColor3fDataTypeId:
			{
				const SplinefColor3fData *splineData = static_cast<const SplinefColor3fData *>( data );
				declareSpline( it->first, splineData->readable(), params );
				continue;
			}
			break;

			default:
			break;
		}

		if( !ss.str().empty() )
		{
			params.insert( it->first.c_str(), ss.str() );
		}
	}

	return params;
}

} // namespace ParameterAlgo

} // namespace IECoreAppleseed
<|endoftext|>


<commit_before>///*******************************************************
///Config Description
//configIndex = 0 ---> Default cuts and PID
//configIndex = 1 ---> Non-HFE, Op Angle < 0.1
//configIndex = 2 --->
///*******************************************************

AliAnalysisTaskEMCalHFEpA* ConfigEMCalHFEpA(

Bool_t isMC=kFALSE,
Int_t triggerIndex=0,
Int_t configIndex=0,
Int_t centralityIndex=0,
Bool_t isAOD = kFALSE,
Bool_t isEMCal = kFALSE,
Int_t EMCalThreshould = 0 //0 == EG1, 1 == EG2
)

{
///_______________________________________________________________________________________________________________
///Track selection: Cuts used to ensure a minimum quality level of the tracks selected to perform the analysis
	AliHFEcuts *hfecuts = new AliHFEcuts("hfeCutsMinBias","HFE Cuts");
	hfecuts->CreateStandardCuts();

	//TPC Cuts
	hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
	if(configIndex==2) 	hfecuts->SetMinNClustersTPC(90);			                //Minimum number of clusters on TPC
	else if(configIndex==3) 	hfecuts->SetMinNClustersTPC(110);			        //Minimum number of clusters on TPC
	else hfecuts->SetMinNClustersTPC(100);							                //Minimum number of clusters on TPC

	if(configIndex==22) hfecuts->SetMinNClustersTPCPID(70);
	else if (configIndex==23) hfecuts->SetMinNClustersTPCPID(80);					//Minimum number of clusters for dE/dx
	else hfecuts->SetMinNClustersTPCPID(90);					    //Minimum number of clusters for dE/dx

	hfecuts->SetMinRatioTPCclusters(0.6);						                    //Number of clusters (Found/Findable)

	//ITS
	if(configIndex==25) hfecuts->SetCutITSpixel(AliHFEextraCuts::kBoth);			//Require at least one cluster on SPD
	else hfecuts->SetCutITSpixel(AliHFEextraCuts::kAny);							//Require at least one cluster on SPD
	//hfecuts->SetCutITSdrift(AliHFEextraCuts::kAny); 			                    //Require at least one cluster on SDD
	hfecuts->SetCheckITSLayerStatus(kFALSE);

	if(configIndex==4) hfecuts->SetMinNClustersITS(2);								//Minimum number of clusters on ITS
	else if(configIndex==5) hfecuts->SetMinNClustersITS(4);								//Minimum number of clusters on ITS
	else hfecuts->SetMinNClustersITS(3);								            //Minimum number of clusters on ITS

	//Additional Cuts
	hfecuts->SetPtRange(2, 1e6);								                    //Transversal momentum range in GeV/c
	//hfecuts->SetMaxImpactParam(1,2); 							                    //DCA to vertex

	//Event Selection
	hfecuts->SetVertexRange(10.);													//
	//hfecuts->SetProductionVertex(0,0.3,0,0.3);									//
///_______________________________________________________________________________________________________________
	// new cuts for event selection

	//hfecuts->SetUseCorrelationVertex();
	//hfecuts->SetSPDVtxResolutionCut();
	//hfecuts->SetpApileupCut();

///_________________________________________________________________________________________________________________________
///Task config
	AliAnalysisTaskEMCalHFEpA *task = new AliAnalysisTaskEMCalHFEpA(Form("HFECuts%d_%d_%d",triggerIndex,configIndex,centralityIndex));
	printf("task ------------------------ %p\n ", task);
	task->SetHFECuts(hfecuts);
	task->SetCorrelationAnalysis(kFALSE);
	task->SetAODanalysis(isAOD);
	task->SetEventMixing(kTRUE);

	//to separate trigger threshould
	if(EMCalThreshould==0 && triggerIndex==2) task->SetEMCalTriggerEG1();
	if(EMCalThreshould==1 && triggerIndex==2) task->SetEMCalTriggerEG2();

	if(isEMCal) task->SetUseEMCal();

	if(configIndex==26){
		task->SetUseShowerShapeCut(kTRUE);
		//task->SetM02Cut(0.0,0.3);
		task->SetM20Cut(0.0,0.3);
	}
	task->SetBackground(kTRUE);

	if(configIndex==6) task->SetNonHFEmassCut(0.05);
	else task->SetNonHFEmassCut(0.1);

	//if(isEMCal) task->SetEtaCut(-0.6,0.6);
	//else task->SetEtaCut(-0.9,0.9);

	if(configIndex==12) task->SetEtaCut(-0.6,-0.2);
	else if (configIndex==13) task->SetEtaCut(-0.5,-0.1);
	else if (configIndex==14) task->SetEtaCut(-0.4,0);
	else if (configIndex==15) task->SetEtaCut(-0.3,0.1);
	else if (configIndex==16) task->SetEtaCut(-0.2,0.2);
	else if (configIndex==17) task->SetEtaCut(-0.1,0.3);
	else if (configIndex==18) task->SetEtaCut(0,0.4);
	else task->SetEtaCut(-0.6,0.6);

	if(configIndex==19) task->SetdPhidEtaCut(0.02,0.02);
	else if (configIndex==20) task->SetdPhidEtaCut(0.03,0.03);
	else if (configIndex==21) task->SetdPhidEtaCut(0.04,0.04);
	else task->SetdPhidEtaCut(0.05,0.05);

	if (configIndex==7) task->SetEoverPCut(0.85,1.2);
	else if (configIndex==8) task->SetEoverPCut(0.75,1.25);
	else task->SetEoverPCut(0.8,1.2);

	if(configIndex==1) task->SetNonHFEangleCut(0.1);

	if(centralityIndex==0) task->SetCentrality(0,20);
	if(centralityIndex==1) task->SetCentrality(20,40);
	if(centralityIndex==2) task->SetCentrality(40,60);
	if(centralityIndex==3) task->SetCentrality(60,80);
	if(centralityIndex==4) task->SetCentrality(80,100);
	if(centralityIndex==5) task->SetCentrality(0,100);
///_______________________________________________________________________________________________________________

///_______________________________________________________________________________________________________________
///Particle identification
	AliHFEpid *pid = task->GetPID();

//______________________________________
//In the case of a simulation
	if(isMC)
	{
	  pid->SetHasMCData(kTRUE);
	  task->SetMCanalysis();
	}
//______________________________________

//______________________________________________________
//Configure PID
	//_________________________
	//TPC PID
	pid->AddDetector("TPC", 1);				//Add TPC PID

	//_________________________
	//Configure TPC cut
	//Defaul = -1 to 3 sigmas
	//Note that it is also possible to define a model instead of a constant
	//--------->For this change the "cut model"

	Double_t params[4];
	char *cutmodel;
	cutmodel = "pol0";

	if(configIndex==9) params[0] = -1.5;
	else if (configIndex==10) params[0] = -0.5;
	else if (configIndex==11) params[0] = 0;
	else params[0] = -1;

	pid->ConfigureTPCdefaultCut(cutmodel,params,3.0);
//_______________________________________________________
///_______________________________________________________________________________________________________________

	printf("*************************************\n");
	printf("Configuring standard Task:\n");
	pid->PrintStatus();
	printf("*************************************\n");

	return task;
}
<commit_msg>updated<commit_after>///*******************************************************
///Config Description

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

AliAnalysisTaskEMCalHFEpA* ConfigEMCalHFEpA(

Bool_t isMC=kFALSE,
Int_t triggerIndex=0,
Int_t configIndex=0,
Int_t centralityIndex=0,
Bool_t isAOD = kFALSE,
Bool_t isEMCal = kFALSE,
Int_t EMCalThreshould = 0 //0 == EG1, 1 == EG2
)

{
///_______________________________________________________________________________________________________________
///Track selection: Cuts used to ensure a minimum quality level of the tracks selected to perform the analysis
	AliHFEcuts *hfecuts = new AliHFEcuts("hfeCutsMinBias","HFE Cuts");
	hfecuts->CreateStandardCuts();

	//TPC Cuts
	hfecuts->SetTPCmodes(AliHFEextraCuts::kFound, AliHFEextraCuts::kFoundOverFindable);
	if(configIndex==1) 	hfecuts->SetMinNClustersTPC(90);			                //Minimum number of clusters on TPC
	else if(configIndex==2) 	hfecuts->SetMinNClustersTPC(110);
	else if(configIndex==3) 	hfecuts->SetMinNClustersTPC(80);
	else if(configIndex==4) 	hfecuts->SetMinNClustersTPC(85);
	else if(configIndex==5) 	hfecuts->SetMinNClustersTPC(115);
	else if(configIndex==6) 	hfecuts->SetMinNClustersTPC(120);					//Minimum number of clusters on TPC
	else hfecuts->SetMinNClustersTPC(100);							                //Minimum number of clusters on TPC

	if(configIndex==7) hfecuts->SetMinNClustersTPCPID(70);
	else if (configIndex==8) hfecuts->SetMinNClustersTPCPID(90);
	else if (configIndex==9) hfecuts->SetMinNClustersTPCPID(60)
	else if (configIndex==10) hfecuts->SetMinNClustersTPCPID(65);
	else if (configIndex==11) hfecuts->SetMinNClustersTPCPID(100);
	else if (configIndex==12) hfecuts->SetMinNClustersTPCPID(95);
	else hfecuts->SetMinNClustersTPCPID(80);										//Minimum number of clusters for dE/dx

	hfecuts->SetMinRatioTPCclusters(0.6);						                    //Number of clusters (Found/Findable)

	//ITS
	if(configIndex==13) hfecuts->SetCutITSpixel(AliHFEextraCuts::kBoth);				//Require at least one cluster on SPD
	else hfecuts->SetCutITSpixel(AliHFEextraCuts::kAny);							//Require at least one cluster on SPD
	//hfecuts->SetCutITSdrift(AliHFEextraCuts::kAny); 			                    //Require at least one cluster on SDD
	hfecuts->SetCheckITSLayerStatus(kFALSE);

	if(configIndex==14) hfecuts->SetMinNClustersITS(2);								//Minimum number of clusters on ITS
	else if(configIndex==15) hfecuts->SetMinNClustersITS(4);
	else if(configIndex==16) hfecuts->SetMinNClustersITS(1);
	else if(configIndex==17) hfecuts->SetMinNClustersITS(5);
	else hfecuts->SetMinNClustersITS(3);								            //Minimum number of clusters on ITS

	//Additional Cuts
	hfecuts->SetPtRange(2, 1e6);								                    //Transversal momentum range in GeV/c
	//hfecuts->SetMaxImpactParam(1,2); 							                    //DCA to vertex

	//Event Selection
	hfecuts->SetVertexRange(10.);													//
	//hfecuts->SetProductionVertex(0,0.3,0,0.3);									//
///_______________________________________________________________________________________________________________
	// new cuts for event selection

	//hfecuts->SetUseCorrelationVertex();
	//hfecuts->SetSPDVtxResolutionCut();
	//hfecuts->SetpApileupCut();

///_________________________________________________________________________________________________________________________
///Task config
	AliAnalysisTaskEMCalHFEpA *task = new AliAnalysisTaskEMCalHFEpA(Form("HFECuts%d_%d_%d",triggerIndex,configIndex,centralityIndex));
	printf("task ------------------------ %p\n ", task);
	task->SetHFECuts(hfecuts);
	task->SetCorrelationAnalysis(kFALSE);
	task->SetAODanalysis(isAOD);
	task->SetEventMixing(kTRUE);

	//to separate trigger threshould
	if(EMCalThreshould==0 && triggerIndex==2) task->SetEMCalTriggerEG1();
	if(EMCalThreshould==1 && triggerIndex==2) task->SetEMCalTriggerEG2();

	if(isEMCal) task->SetUseEMCal();

	if(configIndex==100){
		task->SetUseShowerShapeCut(kTRUE);
		//task->SetM02Cut(0.0,0.3);
		task->SetM20Cut(0.0,0.3);
	}
	task->SetBackground(kTRUE);

	//nonHFE cuts
	if(configIndex==20) task->SetNonHFEmassCut(0.05);
	else if(configIndex==21) task->SetNonHFEmassCut(0.15);
	else if(configIndex==22) task->SetNonHFEmassCut(0.03);
	else if(configIndex==23) task->SetNonHFEmassCut(0.18);
	else if(configIndex==24) task->SetNonHFEmassCut(0.01);
	else if(configIndex==25) task->SetNonHFEmassCut(0.2);
	else task->SetNonHFEmassCut(0.1);

	if(configIndex==26) task->SetNonHFEangleCut(0.1);
	if(configIndex==27) task->SetNonHFEangleCut(0.15);
	if(configIndex==28) task->SetNonHFEangleCut(0.05);

	//eta cuts
	if(configIndex==40) task->SetEtaCut(-0.6,-0.2);
	else if (configIndex==41) task->SetEtaCut(-0.5,-0.1);
	else if (configIndex==42) task->SetEtaCut(-0.4,0);
	else if (configIndex==43) task->SetEtaCut(-0.3,0.1);
	else if (configIndex==44) task->SetEtaCut(-0.2,0.2);
	else if (configIndex==45) task->SetEtaCut(-0.1,0.3);
	else if (configIndex==46) task->SetEtaCut(0,0.4);
	else if (configIndex==47) task->SetEtaCut(-0.4,0.4);
	else if (configIndex==48) task->SetEtaCut(-0.3,0.3);
	else task->SetEtaCut(-0.6,0.6);

	//track matching cuts
	if(configIndex==50) task->SetdPhidEtaCut(0.02,0.02);
	else if (configIndex==51) task->SetdPhidEtaCut(0.03,0.03);
	else if (configIndex==52) task->SetdPhidEtaCut(0.04,0.04);
	else task->SetdPhidEtaCut(0.05,0.05);

	//E/p Cuts
	if (configIndex==60) task->SetEoverPCut(0.85,1.2);
	else if (configIndex==61) task->SetEoverPCut(0.75,1.25);
	else if (configIndex==62) task->SetEoverPCut(0.70,1.2);
	else if (configIndex==63) task->SetEoverPCut(0.80,1.25);
	else if (configIndex==64) task->SetEoverPCut(0.9,1.3);
	else if (configIndex==65) task->SetEoverPCut(0.95,1.3);
	else if (configIndex==66) task->SetEoverPCut(0.75,1.2);
	else task->SetEoverPCut(0.8,1.2);

	if(centralityIndex==0) task->SetCentrality(0,20);
	if(centralityIndex==1) task->SetCentrality(20,40);
	if(centralityIndex==2) task->SetCentrality(40,60);
	if(centralityIndex==3) task->SetCentrality(60,80);
	if(centralityIndex==4) task->SetCentrality(80,100);
	if(centralityIndex==5) task->SetCentrality(0,100);
///_______________________________________________________________________________________________________________

///_______________________________________________________________________________________________________________
///Particle identification
	AliHFEpid *pid = task->GetPID();

//______________________________________
//In the case of a simulation
	if(isMC)
	{
	  pid->SetHasMCData(kTRUE);
	  task->SetMCanalysis();
	}
//______________________________________

//______________________________________________________
//Configure PID
	//_________________________
	//TPC PID
	pid->AddDetector("TPC", 1);				//Add TPC PID

	//_________________________
	//Configure TPC cut
	//Defaul = -1 to 3 sigmas
	//Note that it is also possible to define a model instead of a constant
	//--------->For this change the "cut model"

	Double_t params[4];
	char *cutmodel;
	cutmodel = "pol0";

	if(configIndex==70) params[0] = -1.5;
	else if (configIndex==71) params[0] = -0.5;
	else if (configIndex==72) params[0] = 0;
	else if (configIndex==73) params[0] = 0.25;
	else if (configIndex==74) params[0] = -1.75;
	else params[0] = -1;

	pid->ConfigureTPCdefaultCut(cutmodel,params,3.0);
//_______________________________________________________
///_______________________________________________________________________________________________________________

	printf("*************************************\n");
	printf("Configuring standard Task:\n");
	pid->PrintStatus();
	printf("*************************************\n");

	return task;
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>

#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/robot_trajectory/robot_trajectory.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <tf2_ros/transform_listener.h>

#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Transform.h>
#include <moveit_msgs/RobotTrajectory.h>

class MoveGroupInterface {
  moveit::planning_interface::MoveGroup move_group_;

  tf2_ros::Buffer buffer_;
  tf2_ros::TransformListener listener_;

  geometry_msgs::Pose tomapo_;
  std::vector<geometry_msgs::Pose> waypoints_;

  static constexpr double eef_length {0.3}; // TODO
  static constexpr double eef_step {0.10};

public:
  MoveGroupInterface(const std::string& group_name, const double& joint_tolerance)
    : move_group_ {group_name},
      buffer_ {},
      listener_ {buffer_},
      tomapo_ {},
      waypoints_ {}
  {
    move_group_.allowReplanning(true);
    move_group_.setGoalJointTolerance(joint_tolerance);
    move_group_.setPlanningTime(5.0);
  }

  bool queryTargetExistence()
  {
    try {
      geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform("rail", "tomato", ros::Time(0), ros::Duration(5.0))};
      tomapo_.position.x = transform_stamped_.transform.translation.x;
      tomapo_.position.y = transform_stamped_.transform.translation.y;
      tomapo_.position.z = transform_stamped_.transform.translation.z;
      tomapo_.orientation.w = 1.0;
      return true;
    } catch (const tf2::TransformException& ex) {
      ROS_INFO_STREAM(ex.what());
      return false;
    }
  }

  bool startSequence()
  {
    moveit_msgs::RobotTrajectory trajectory_msgs_ {getCartesianPaths()};

    robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()};
    robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_);

    trajectory_processing::IterativeParabolicTimeParameterization iptp;
    iptp.computeTimeStamps(robot_trajectory_);

    robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_);

    moveit::planning_interface::MoveGroup::Plan motion_plan_;
    motion_plan_.trajectory_ = trajectory_msgs_;

    return move_group_.execute(motion_plan_);
  }

private:
  moveit_msgs::RobotTrajectory getCartesianPaths()
  {
    waypoints_.push_back(linear(tomapo_, -eef_length));
    waypoints_.push_back(tomapo_);
    waypoints_.push_back(roll(tomapo_, 1.0));
    waypoints_.push_back(linearXX(tomapo_, -eef_length));

    moveit_msgs::RobotTrajectory robot_trajectory_;
    move_group_.computeCartesianPath(waypoints_, eef_step, 0.0, robot_trajectory_);

    return robot_trajectory_;
  }

  geometry_msgs::Pose linear(const geometry_msgs::Pose& pose, const double& distance)
  {
    geometry_msgs::Pose pose_ {pose};
    pose_.position.x += distance;
    return pose_;
  }

  geometry_msgs::Pose linearXX(const geometry_msgs::Pose& pose, const double& distance)
  {
    geometry_msgs::Pose pose_ {pose};
    pose_.position.y += distance;
    return pose_;
  }

  geometry_msgs::Pose roll(const geometry_msgs::Pose& pose, const double& radian)
  {
    geometry_msgs::Pose pose_ {pose};
    pose_.orientation = tf::createQuaternionMsgFromRollPitchYaw(radian, 0, 0);
    return pose_;
  }
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "arcsys2_move_group_interface_node");

  ros::NodeHandle node_handle {"~"};
  // ros::Rate rate {ros::Duration(10.0)};

  MoveGroupInterface interface {"arcsys2", node_handle.param("joint_tolerance", 0.1)};

  ros::AsyncSpinner spinner {1};
  spinner.start();

  while (ros::ok()) {
    if (interface.queryTargetExistence()) interface.startSequence();
    // rate.sleep();
  }

  spinner.stop();

  return 0;
}
<commit_msg>Delete function for debug<commit_after>#include <string>
#include <vector>

#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/robot_trajectory/robot_trajectory.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <tf2_ros/transform_listener.h>

#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Transform.h>
#include <moveit_msgs/RobotTrajectory.h>

class MoveGroupInterface {
  moveit::planning_interface::MoveGroup move_group_;

  tf2_ros::Buffer buffer_;
  tf2_ros::TransformListener listener_;

  geometry_msgs::Pose tomapo_;
  std::vector<geometry_msgs::Pose> waypoints_;

  static constexpr double eef_length {0.3}; // TODO
  static constexpr double eef_step {0.10};

public:
  MoveGroupInterface(const std::string& group_name, const double& joint_tolerance)
    : move_group_ {group_name},
      buffer_ {},
      listener_ {buffer_},
      tomapo_ {},
      waypoints_ {}
  {
    move_group_.allowReplanning(true);
    move_group_.setGoalJointTolerance(joint_tolerance);
    move_group_.setPlanningTime(5.0);
  }

  bool queryTargetExistence()
  {
    try {
      geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform("rail", "tomato", ros::Time(0), ros::Duration(5.0))};
      tomapo_.position.x = transform_stamped_.transform.translation.x;
      tomapo_.position.y = transform_stamped_.transform.translation.y;
      tomapo_.position.z = transform_stamped_.transform.translation.z;
      tomapo_.orientation.x = 0;
      tomapo_.orientation.y = 0;
      tomapo_.orientation.z = 0;
      tomapo_.orientation.w = 1.0;
      return true;
    } catch (const tf2::TransformException& ex) {
      ROS_INFO_STREAM(ex.what());
      return false;
    }
  }

  bool startSequence()
  {
    moveit_msgs::RobotTrajectory trajectory_msgs_ {getCartesianPaths()};

    robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()};
    robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_);

    trajectory_processing::IterativeParabolicTimeParameterization iptp;
    iptp.computeTimeStamps(robot_trajectory_);

    robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_);

    moveit::planning_interface::MoveGroup::Plan motion_plan_;
    motion_plan_.trajectory_ = trajectory_msgs_;

    return move_group_.execute(motion_plan_);
  }

private:
  moveit_msgs::RobotTrajectory getCartesianPaths()
  {
    waypoints_.push_back(linear(tomapo_, -eef_length));
    waypoints_.push_back(tomapo_);
    waypoints_.push_back(roll(tomapo_, 1.0));
    waypoints_.push_back(linear(tomapo_, -eef_length));

    moveit_msgs::RobotTrajectory robot_trajectory_;
    move_group_.computeCartesianPath(waypoints_, eef_step, 0.0, robot_trajectory_);

    return robot_trajectory_;
  }

  geometry_msgs::Pose linear(const geometry_msgs::Pose& pose, const double& distance)
  {
    geometry_msgs::Pose pose_ {pose};
    pose_.position.x += distance;
    return pose_;
  }

  geometry_msgs::Pose roll(const geometry_msgs::Pose& pose, const double& radian)
  {
    geometry_msgs::Pose pose_ {pose};
    pose_.orientation = tf::createQuaternionMsgFromRollPitchYaw(radian, 0, 0);
    return pose_;
  }
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "arcsys2_move_group_interface_node");

  ros::NodeHandle node_handle {"~"};
  // ros::Rate rate {ros::Duration(10.0)};

  MoveGroupInterface interface {"arcsys2", node_handle.param("joint_tolerance", 0.1)};

  ros::AsyncSpinner spinner {1};
  spinner.start();

  while (ros::ok()) {
    if (interface.queryTargetExistence()) interface.startSequence();
    // rate.sleep();
  }

  spinner.stop();

  return 0;
}
<|endoftext|>