<commit_before>/*
 * File:   LogServer.cpp
 * Author: uli
 *
 * Created on 8. Mai 2013, 19:58
 */

#include "LogServer.hpp"
#include "macros.hpp"
#include "protocol.hpp"
#include "zutil.hpp"
#include <iostream>
#include <czmq.h>

/**
 * For a given log protocol header message, checks & returns if
 * the header frame contains a stop message
 */
inline static bool isStopServerMessage(zframe_t* headerFrame) {
    assert(headerFrame);
    assert(zframe_size(headerFrame) == 3);
    return ((char*)zframe_data(headerFrame))[2] == '\xFF';
}

LogServer::LogServer(void* ctxParam, LogLevel logLevel, bool autoStart, const std::string& endpointParam)
: logRequestInputSocket(zmq_socket_new_bind(ctxParam, ZMQ_PULL, endpointParam.c_str())),
logLevel(logLevel),
ctx(ctxParam),
thread(nullptr),
logger(ctx, "Log server"),
endpoint(endpointParam) {
    //Autostart if enabled
    if(autoStart) {
        startInNewThread();
    }
}

void COLD LogServer::terminate() {
    //Stop thread, if any
    if (thread) {
        //Final log message
        logger.info("Log server shutting down");
        //We need to create a temporary client socket
        void* tempSocket = zmq_socket_new_connect(ctx, ZMQ_PUSH, endpoint.c_str());
        //Send the STOP message to the worker thread
        if(zmq_send(tempSocket, "\x55\x01\xFF", 3, 0) == -1) {
            logMessageSendError("Log server thread stop message", logger);
        }
        thread->join(); //Wait until it exits
        //Cleanup
        zmq_close(tempSocket);
        delete thread;
        thread = nullptr;
    }
    /*
     * The log server is destructed in the late exit phase,
     * so we need to assume the context will be destroyed before
     * the logger in the current LogServer instance
     * has a chance to destroy its socket.
     * Therefore we terminate it manually to be sure.
     */
    logger.terminate();
}

LogServer::~LogServer() {
    terminate();
    //Cleanup the log sinks
    for (LogSink* sink : logSinks) {
        delete sink;
    }
}

static COLD void handleLogServerZMQError() {
    fprintf(stderr, "\x1B[31;1m[Error] Error while receiving log message in log server: %s \x1B[0;30m\n", zmq_strerror(errno));
    fflush(stderr);
}

void HOT LogServer::start() {
    //Create a socket to receive log requests
    while (true) {
        zmq_msg_t frame;
        zmq_msg_init(&frame);
        zmsg_t* msg = zmsg_recv(logRequestInputSocket);
        if (unlikely(!msg)) {
            //Interrupted (e.g. by SIGINT), but loggers might still want to log something
            // so we won't exit yet.
            if(yak_interrupted) {
                //Context was terminated (ctrl+c or other signal source), exit gracefully
                break;
            } else {
                handleLogServerZMQError
                continue;
            }
        }
        size_t msgSize = zmsg_size(msg);
        if (unlikely(msgSize != 1 && msgSize != 5)) {
            logger.warn("Received log message of illegal size: " + std::to_string(msgSize));
            zmsg_destroy(&msg);
            continue;
        }
        zframe_t* headerFrame = zmsg_first(msg);
        //Check the magic byte & protocol version in the header frame,
        // log a warning if an illegal message has been received
        byte* headerData = zframe_data(headerFrame);
        if (unlikely(headerData[0] != '\x55')) {
            logger.warn("Received log message with illegal magic byte: " + std::to_string((uint8_t) headerData[0]));
            zmsg_destroy(&msg);
            continue;
        }
        if (unlikely(headerData[1] != '\x01')) {
            logger.warn("Received log message with illegal protocol version: " + std::to_string((uint8_t) headerData[1]));
            zmsg_destroy(&msg);
            continue;
        }
        //Check if we received a stop message
        if (unlikely(isStopServerMessage(headerFrame))) {
            //Log a message that the server is exiting, to all sinks
            //We can't use the logger here because the log message
            //won't be received any more
            if (logLevel >= LogLevel::Info) {
                //Log that we're stopping
                log( "Log server", LogLevel::Info, "Log server stopping");
            }
            //Cleanup
            zmsg_destroy(&msg);
            break;
        }
        //Parse the log information from the frames
        LogLevel logLevel = extractBinary<LogLevel>(zmsg_next(msg));
        uint64_t timestamp = extractBinary<uint64_t>(zmsg_next(msg));
        std::string senderName = frameToString(zmsg_next(msg));
        std::string logMessage = frameToString(zmsg_next(msg));
        //Pass the log message to the log sinks
        for (LogSink* sink : logSinks) {
            sink->log(logLevel, timestamp, senderName, logMessage);
        }
        //Cleanup
        zmsg_destroy(&msg);
    }
    //Cleanup
    zmq_close(logRequestInputSocket);
}

void LogServer::log(const std::string& loggerName, LogLevel msgLogLevel, const std::string& message) {
    if(msgLogLevel >= logLevel) {
        uint64_t timestamp = zclock_time();
        for (LogSink* sink : logSinks) {
            sink->log(logLevel, timestamp, loggerName, message);
        }
    }
}

/**
 * Starts a new thread that executes the start() function
 */
void LogServer::startInNewThread() {
    this->thread = new std::thread(std::mem_fun(&LogServer::start), this);
}

void COLD LogServer::setLogLevel(LogLevel logLevel) {
    this->logLevel = logLevel;
}

LogLevel COLD LogServer::getLogLevel() {
    return logLevel;
}

void LogServer::addLogSink(LogSink* logSink) {
    logSinks.push_back(logSink);
}<commit_msg>Implement log server stream mode parser<commit_after>/*
 * File:   LogServer.cpp
 * Author: uli
 *
 * Created on 8. Mai 2013, 19:58
 */

#include "LogServer.hpp"
#include "macros.hpp"
#include "protocol.hpp"
#include "zutil.hpp"
#include <iostream>
#include <zmq.h>

/*
 * Utility macros for error handling code dedup and
 * to make the code shorter.
 * These shall only be used inside a LogServer msg loop.
 */
#define CHECK_MORE_FRAMES(msg, description)\
        if(unlikely(!zmq_msg_more(&msg))) {\
            log("Log server", LogLevel::Warn, "Only received " + std::string(description) + ", missing further frames");\
            continue;\
        }
#define CHECK_NO_MORE_FRAMES(msg, description)\
        if(unlikely(!zmq_msg_more(&msg))) {\
            log("Log server", LogLevel::Warn, "Expected no more frames after " + std::string(description) + ", but MORE flag is set");\
            continue;\
        }
#define RECEIVE_CHECK_ERROR(msg, socket, description)\
    if(unlikely(zmq_msg_recv(&msg, socket, 0) == -1)) {\
            if(yak_interrupted) {\
                break;\
            } else {\
                log("Log server", LogLevel::Warn, "Error while receiving "\
                    + std::string(description)+ ": " + std::string(zmq_strerror(errno)));\
                continue;\
            }\
    }\

/**
 * For a given log protocol header message, checks & returns if
 * the header frame contains a stop message
 */
inline static bool isStopServerMessage(zmq_msg_t* headerFrame) {
    assert(headerFrame);
    assert(zmq_msg_size(headerFrame) == 3);
    return ((char*)zmq_msg_data(headerFrame))[2] == '\xFF';
}

LogServer::LogServer(void* ctxParam, LogLevel logLevel, bool autoStart, const std::string& endpointParam)
: logRequestInputSocket(zmq_socket_new_bind(ctxParam, ZMQ_PULL, endpointParam.c_str())),
logLevel(logLevel),
ctx(ctxParam),
thread(nullptr),
logger(ctx, "Log server"),
endpoint(endpointParam) {
    //Autostart if enabled
    if(autoStart) {
        startInNewThread();
    }
}

void COLD LogServer::terminate() {
    //Stop thread, if any
    if (thread) {
        //Final log message
        logger.info("Log server shutting down");
        //We need to create a temporary client socket
        void* tempSocket = zmq_socket_new_connect(ctx, ZMQ_PUSH, endpoint.c_str());
        //Send the STOP message to the worker thread
        if(zmq_send(tempSocket, "\x55\x01\xFF", 3, 0) == -1) {
            logMessageSendError("Log server thread stop message", logger);
        }
        thread->join(); //Wait until it exits
        //Cleanup
        zmq_close(tempSocket);
        delete thread;
        thread = nullptr;
    }
    /*
     * The log server is destructed in the late exit phase,
     * so we need to assume the context will be destroyed before
     * the logger in the current LogServer instance
     * has a chance to destroy its socket.
     * Therefore we terminate it manually to be sure.
     */
    logger.terminate();
}

LogServer::~LogServer() {
    terminate();
    //Cleanup the log sinks
    for (LogSink* sink : logSinks) {
        delete sink;
    }
}

static COLD void handleLogServerZMQError() {
    fprintf(stderr, "\x1B[31;1m[Error] Error while receiving log message in log server: %s \x1B[0;30m\n", zmq_strerror(errno));
    fflush(stderr);
}

void HOT LogServer::start() {
    //Create a socket to receive log requests
    zmq_msg_t frame;
    zmq_msg_init(&frame);
    while (true) {
        /*
         * Receive and parse header frame
         */
        RECEIVE_CHECK_ERROR(frame, logRequestInputSocket, "header frame");
        CHECK_MORE_FRAMES(frame, "header frame");
        if(unlikely(zmq_msg_size(&frame) != 3)) {
            log("Log server",
                LogLevel::Warn,
                "Received log header frame of invalid size: expected size 3, got size "
                + std::to_string(zmq_msg_size(&frame)));
            continue;
        }
        //Check the magic byte & protocol version in the header frame,
        // log a warning if an illegal message has been received
        char* headerData = (char*) zmq_msg_data(&frame);
        if (unlikely(headerData[0] != '\x55')) {
            log("Log server",
                LogLevel::Warn,
                "Received log message header with illegal magic byte: " + std::to_string((uint8_t) headerData[0]));
            continue;
        }
        if (unlikely(headerData[1] != '\x01')) {
            log("Log server",
                LogLevel::Warn,
                "Received log message with illegal protocol version: " + std::to_string((uint8_t) headerData[1]));
            continue;
        }
        //Check if we received a stop message (same effect as SIGINT --> log server is
        if (unlikely(isStopServerMessage(&frame))) {
            log("Log server",
                LogLevel::Debug,
                "Received stop message, exiting...");
            break;
        }
        /*
         * Receive log level frame
         */
        RECEIVE_CHECK_ERROR(frame, logRequestInputSocket, "log level frame");
        CHECK_MORE_FRAMES(frame, "log level frame");
        if(unlikely(sizeof(LogLevel) != zmq_msg_size(&frame))) {
            log("Log server",
                LogLevel::Warn,
                "Received log level frame of invalid size: expected size "
                + std::to_string(sizeof(LogLevel)) + ", got size "
                + std::to_string(zmq_msg_size(&frame)));
            continue;
        }
        LogLevel logLevel = extractBinary<LogLevel>(&frame);
        /*
         * Receive timestamp frame
         */
        RECEIVE_CHECK_ERROR(frame, logRequestInputSocket, "log level frame");
        CHECK_MORE_FRAMES(frame, "log level frame");
        if(unlikely(sizeof(uint64_t) != zmq_msg_size(&frame))) {
            log("Log server",
                LogLevel::Warn,
                "Received log level message of invalid size: expected size "
                + std::to_string(sizeof(uint64_t)) + ", got size "
                + std::to_string(zmq_msg_size(&frame)));
            continue;
        }
        uint64_t timestamp = extractBinary<uint64_t>(&frame);
        /*
         * Receive sender name frame
         */
        RECEIVE_CHECK_ERROR(frame, logRequestInputSocket, "sender name frame");
        CHECK_MORE_FRAMES(frame, "sender name frame");
        std::string senderName((char*) zmq_msg_data(&frame), zmq_msg_size(&frame));
        /*
         * Receive log message frame
         */
        RECEIVE_CHECK_ERROR(frame, logRequestInputSocket, "log message frame");
        CHECK_NO_MORE_FRAMES(frame, "log message frame");
        std::string logMessage((char*) zmq_msg_data(&frame), zmq_msg_size(&frame));
        //Pass the log message to the log sinks
        for (LogSink* sink : logSinks) {
            sink->log(logLevel, timestamp, senderName, logMessage);
        }
    }
    zmq_msg_close(&frame);
    //Log that we're stopping
    log("Log server", LogLevel::Info, "Log server stopping");
    //Cleanup
    zmq_close(logRequestInputSocket);
}

void LogServer::log(const std::string& loggerName, LogLevel msgLogLevel, const std::string& message) {
    if(msgLogLevel >= logLevel) {
        uint64_t timestamp = zclock_time();
        for (LogSink* sink : logSinks) {
            sink->log(logLevel, timestamp, loggerName, message);
        }
    }
}

/**
 * Starts a new thread that executes the start() function
 */
void LogServer::startInNewThread() {
    this->thread = new std::thread(std::mem_fun(&LogServer::start), this);
}

void COLD LogServer::setLogLevel(LogLevel logLevel) {
    this->logLevel = logLevel;
}

LogLevel COLD LogServer::getLogLevel() {
    return logLevel;
}

void LogServer::addLogSink(LogSink* logSink) {
    logSinks.push_back(logSink);
}<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLinearTrend.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/HMM/GeneralHmmStateSpaceWrapper.hpp"
#include "Models/HMM/PosteriorSamplers/LiuWestParticleFilter.hpp"
#include "distributions.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class LiuWestParticleFilterTest : public ::testing::Test {
   protected:
    LiuWestParticleFilterTest() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(LiuWestParticleFilterTest, Basics) {
  }

  TEST_F(LiuWestParticleFilterTest, Filtering) {
    bool save_to_file = false;

    Vector true_state(100);
    Vector observations(true_state.size());
    std::vector<Ptr<DoubleData>> data;
    double true_sigma_obs = .5;
    double true_sigma_trend = .1;
    for (int i = 0; i < true_state.size(); ++i) {
      true_state[i] = (i == 0) ? rnorm(0, 3) : rnorm(true_state[i-1], true_sigma_trend);
      observations[i] = true_state[i] + rnorm(0, true_sigma_obs);
      data.push_back(new DoubleData(observations[i]));
    }

    NEW(StateSpaceModel, base_model)();
    EXPECT_TRUE(base_model->observation_model() != nullptr);
    EXPECT_DOUBLE_EQ(base_model->observation_model()->sigsq(), 1.0);

    NEW(LocalLevelStateModel, trend)();
    base_model->add_state(trend);
    NEW(GeneralHmmStateSpaceWrapper, model)(base_model);

    int number_of_particles = 1500;
    LiuWestParticleFilter filter(model, number_of_particles, .1);
    Matrix initial_parameters(number_of_particles, 2);
    Matrix initial_state(number_of_particles, 1);

    // The parameters of the model are
    // 1) a scalar observation variance.
    // 2) a scalar trend innovation variance.
    for (int i = 0; i < number_of_particles; ++i) {
      initial_parameters.row(i)[0] = 1.0 / rgamma(2, 1);
      initial_parameters.row(i)[1] = 1.0 / rgamma(2, .01);
      initial_state.row(i)[0] = rnorm(0, 10);
    }
    filter.set_particles(initial_state, initial_parameters);

    std::ofstream state_file;
    std::ofstream sigma_obs_file;
    std::ofstream sigma_trend_file;
    std::ofstream weight_file;
    if (save_to_file) {
      state_file.open("state.out");
      sigma_obs_file.open("sigma_obs.out");
      sigma_trend_file.open("sigma_trend.out");
      weight_file.open("weights.out");
    }

    Matrix state_draws(number_of_particles, true_state.size());
    for (int i = 0; i < data.size(); ++i) {
      filter.update(GlobalRng::rng, *data[i], i);
      Vector state_distribution = filter.state_distribution().col(0);
      state_draws.col(i) = state_distribution;
      if (save_to_file) {
        state_file << true_state[i] << " " << state_distribution << endl;
        Matrix parameter_distribution =
            filter.parameter_distribution(&GlobalRng::rng);
        sigma_obs_file << true_sigma_obs << ' '
                       << sqrt(parameter_distribution.col(0)) << endl;
        sigma_trend_file << true_sigma_trend << ' '
                         << sqrt(parameter_distribution.col(1)) << endl;
        weight_file << filter.particle_weights() << endl;
      }
    }

    if (save_to_file) {
      std::ofstream trend_file("trend.out");
      trend_file << true_state;

      std::ofstream data_file("data.out");
      data_file << observations;
    }
    Matrix parameter_distribution = filter.parameter_distribution();
    EXPECT_TRUE(CheckMcmcVector(sqrt(parameter_distribution.col(0)),
                                true_sigma_obs))
        << "Sigma obs didn't cover.";

    EXPECT_TRUE(CheckMcmcVector(sqrt(parameter_distribution.col(1)),
                                true_sigma_trend))
        << "Sigma trend didn't cover.";

    auto status = CheckMcmcMatrix(state_draws, true_state);
    EXPECT_TRUE(status.ok)
        << "State failed to cover" << endl
        << status;
  }

  /*
    PlotParameter <- function(fname, burn = 0) {
      ## An R function that can be used to plot the data written by this test.
      library(Boom)
      prm <- t(mscan(fname))
      if (burn > 0) {
        prm <- prm[, -(1:burn)]
      }
      truth <- prm[1, ]
      PlotDynamicDistribution(prm)
      lines(truth, col = "green")
    }
   */

}  // namespace
<commit_msg>Increased line width in particle filter plot.<commit_after>#include "gtest/gtest.h"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLinearTrend.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/HMM/GeneralHmmStateSpaceWrapper.hpp"
#include "Models/HMM/PosteriorSamplers/LiuWestParticleFilter.hpp"
#include "distributions.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class LiuWestParticleFilterTest : public ::testing::Test {
   protected:
    LiuWestParticleFilterTest() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(LiuWestParticleFilterTest, Basics) {
  }

  TEST_F(LiuWestParticleFilterTest, Filtering) {
    bool save_to_file = false;

    Vector true_state(100);
    Vector observations(true_state.size());
    std::vector<Ptr<DoubleData>> data;
    double true_sigma_obs = .5;
    double true_sigma_trend = .1;
    for (int i = 0; i < true_state.size(); ++i) {
      true_state[i] = (i == 0) ? rnorm(0, 3) : rnorm(true_state[i-1], true_sigma_trend);
      observations[i] = true_state[i] + rnorm(0, true_sigma_obs);
      data.push_back(new DoubleData(observations[i]));
    }

    NEW(StateSpaceModel, base_model)();
    EXPECT_TRUE(base_model->observation_model() != nullptr);
    EXPECT_DOUBLE_EQ(base_model->observation_model()->sigsq(), 1.0);

    NEW(LocalLevelStateModel, trend)();
    base_model->add_state(trend);
    NEW(GeneralHmmStateSpaceWrapper, model)(base_model);

    int number_of_particles = 1500;
    LiuWestParticleFilter filter(model, number_of_particles, .1);
    Matrix initial_parameters(number_of_particles, 2);
    Matrix initial_state(number_of_particles, 1);

    // The parameters of the model are
    // 1) a scalar observation variance.
    // 2) a scalar trend innovation variance.
    for (int i = 0; i < number_of_particles; ++i) {
      initial_parameters.row(i)[0] = 1.0 / rgamma(2, 1);
      initial_parameters.row(i)[1] = 1.0 / rgamma(2, .01);
      initial_state.row(i)[0] = rnorm(0, 10);
    }
    filter.set_particles(initial_state, initial_parameters);

    std::ofstream state_file;
    std::ofstream sigma_obs_file;
    std::ofstream sigma_trend_file;
    std::ofstream weight_file;
    if (save_to_file) {
      state_file.open("state.out");
      sigma_obs_file.open("sigma_obs.out");
      sigma_trend_file.open("sigma_trend.out");
      weight_file.open("weights.out");
    }

    Matrix state_draws(number_of_particles, true_state.size());
    for (int i = 0; i < data.size(); ++i) {
      filter.update(GlobalRng::rng, *data[i], i);
      Vector state_distribution = filter.state_distribution().col(0);
      state_draws.col(i) = state_distribution;
      if (save_to_file) {
        state_file << true_state[i] << " " << state_distribution << endl;
        Matrix parameter_distribution =
            filter.parameter_distribution(&GlobalRng::rng);
        sigma_obs_file << true_sigma_obs << ' '
                       << sqrt(parameter_distribution.col(0)) << endl;
        sigma_trend_file << true_sigma_trend << ' '
                         << sqrt(parameter_distribution.col(1)) << endl;
        weight_file << filter.particle_weights() << endl;
      }
    }

    if (save_to_file) {
      std::ofstream trend_file("trend.out");
      trend_file << true_state;

      std::ofstream data_file("data.out");
      data_file << observations;
    }
    Matrix parameter_distribution = filter.parameter_distribution();
    EXPECT_TRUE(CheckMcmcVector(sqrt(parameter_distribution.col(0)),
                                true_sigma_obs))
        << "Sigma obs didn't cover.";

    EXPECT_TRUE(CheckMcmcVector(sqrt(parameter_distribution.col(1)),
                                true_sigma_trend))
        << "Sigma trend didn't cover.";

    auto status = CheckMcmcMatrix(state_draws, true_state);
    EXPECT_TRUE(status.ok)
        << "State failed to cover" << endl
        << status;
  }

  /*
    PlotParameter <- function(fname, burn = 0) {
      ## An R function that can be used to plot the data written by this test.
      library(Boom)
      prm <- t(mscan(fname))
      if (burn > 0) {
        prm <- prm[, -(1:burn)]
      }
      truth <- prm[1, ]
      PlotDynamicDistribution(prm)
      lines(truth, col = "green", lwd = 3)
    }
   */

}  // namespace
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

/***************************************************************************
OgreExternalTextureSourceManager.cpp  -
	Implementation of the manager class

-------------------
date                 : Jan 1 2004
email                : pjcast@yahoo.com
***************************************************************************/

#include "OgreStableHeaders.h"
#include "OgreExternalTextureSourceManager.h"
#include "OgreLogManager.h"

namespace Ogre
{
	//****************************************************************************************
    template<> ExternalTextureSourceManager* Singleton<ExternalTextureSourceManager>::msSingleton = 0;
    ExternalTextureSourceManager* ExternalTextureSourceManager::getSingletonPtr(void)
    {
        return msSingleton;
    }
    ExternalTextureSourceManager& ExternalTextureSourceManager::getSingleton(void)
    {
        assert( msSingleton );  return ( *msSingleton );
    }
	//****************************************************************************************

	//****************************************************************************************
	ExternalTextureSourceManager::ExternalTextureSourceManager()
	{
		mCurrExternalTextureSource = 0;
	}

	//****************************************************************************************
	ExternalTextureSourceManager::~ExternalTextureSourceManager()
	{
		mTextureSystems.clear();
	}

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

	void ExternalTextureSourceManager::setCurrentPlugIn( const String& sTexturePlugInType )
	{
		TextureSystemList::iterator i;

		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
			{
				mCurrExternalTextureSource = i->second;
				mCurrExternalTextureSource->initialise();	//Now call overridden Init function
				return;
			}
		}
		mCurrExternalTextureSource = 0;
		LogManager::getSingleton().logMessage( "ExternalTextureSourceManager::SetCurrentPlugIn(ENUM) failed setting texture plugin ");
	}

	//****************************************************************************************
	void ExternalTextureSourceManager::destroyAdvancedTexture( const String& sTextureName,
		const String& groupName )
	{
		TextureSystemList::iterator i;
		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			//Broadcast to every registered System... Only the true one will destroy texture
			i->second->destroyAdvancedTexture( sTextureName, groupName );
		}
	}

	//****************************************************************************************
	void ExternalTextureSourceManager::setExternalTextureSource( const String& sTexturePlugInType, ExternalTextureSource* pTextureSystem )
	{
		LogManager::getSingleton().logMessage( "Registering Texture Controller: Type = "
						+ sTexturePlugInType + " Name = " + pTextureSystem->getPlugInStringName());

		TextureSystemList::iterator i;

		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
			{
				LogManager::getSingleton().logMessage( "Shutting Down Texture Controller: "
						+ i->second->getPlugInStringName()
						+ " To be replaced by: "
						+ pTextureSystem->getPlugInStringName());

				i->second->shutDown();				//Only one plugIn of Sent Type can be registered at a time
													//so shut down old plugin before starting new plugin
				i->second = pTextureSystem;
				// **Moved this line b/c Rendersystem needs to be selected before things
				// such as framelistners can be added
				// pTextureSystem->Initialise();
				return;
			}
		}
		mTextureSystems[sTexturePlugInType] = pTextureSystem;	//If we got here then add it to map
	}

	//****************************************************************************************
	ExternalTextureSource* ExternalTextureSourceManager::getExternalTextureSource( const String& sTexturePlugInType )
	{
		TextureSystemList::iterator i;
		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
				return i->second;
		}
		return 0;
	}

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

}  //End Ogre Namespace

<commit_msg>Compile fix<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

/***************************************************************************
OgreExternalTextureSourceManager.cpp  -
	Implementation of the manager class

-------------------
date                 : Jan 1 2004
email                : pjcast@yahoo.com
***************************************************************************/

#include "OgreStableHeaders.h"
#include "OgreExternalTextureSourceManager.h"
#include "OgreLogManager.h"

namespace Ogre
{
	//****************************************************************************************
    template<> ExternalTextureSourceManager* Singleton<ExternalTextureSourceManager>::msSingleton = 0;
    ExternalTextureSourceManager* ExternalTextureSourceManager::getSingletonPtr(void)
    {
        return msSingleton;
    }
    ExternalTextureSourceManager& ExternalTextureSourceManager::getSingleton(void)
    {
        assert( msSingleton );  return ( *msSingleton );
    }
	//****************************************************************************************

	//****************************************************************************************
	ExternalTextureSourceManager::ExternalTextureSourceManager()
	{
		mCurrExternalTextureSource = 0;
	}

	//****************************************************************************************
	ExternalTextureSourceManager::~ExternalTextureSourceManager()
	{
		mTextureSystems.clear();
	}

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

	void ExternalTextureSourceManager::setCurrentPlugIn( const String& sTexturePlugInType )
	{
		TextureSystemList::iterator i;

		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
			{
				mCurrExternalTextureSource = i->second;
				mCurrExternalTextureSource->initialise();	//Now call overridden Init function
				return;
			}
		}
		mCurrExternalTextureSource = 0;
		LogManager::getSingleton().logMessage( "ExternalTextureSourceManager::SetCurrentPlugIn(ENUM) failed setting texture plugin ");
	}

	//****************************************************************************************
	void ExternalTextureSourceManager::destroyAdvancedTexture( const String& sTextureName,
		const String& groupName )
	{
		TextureSystemList::iterator i;
		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			//Broadcast to every registered System... Only the true one will destroy texture
			i->second->destroyAdvancedTexture( sTextureName, groupName );
		}
	}

	//****************************************************************************************
	void ExternalTextureSourceManager::setExternalTextureSource( const String& sTexturePlugInType, ExternalTextureSource* pTextureSystem )
	{
		LogManager::getSingleton().logMessage( "Registering Texture Controller: Type = "
						+ sTexturePlugInType + " Name = " + pTextureSystem->getPluginStringName());

		TextureSystemList::iterator i;

		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
			{
				LogManager::getSingleton().logMessage( "Shutting Down Texture Controller: "
						+ i->second->getPluginStringName()
						+ " To be replaced by: "
						+ pTextureSystem->getPluginStringName());

				i->second->shutDown();				//Only one plugIn of Sent Type can be registered at a time
													//so shut down old plugin before starting new plugin
				i->second = pTextureSystem;
				// **Moved this line b/c Rendersystem needs to be selected before things
				// such as framelistners can be added
				// pTextureSystem->Initialise();
				return;
			}
		}
		mTextureSystems[sTexturePlugInType] = pTextureSystem;	//If we got here then add it to map
	}

	//****************************************************************************************
	ExternalTextureSource* ExternalTextureSourceManager::getExternalTextureSource( const String& sTexturePlugInType )
	{
		TextureSystemList::iterator i;
		for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i )
		{
			if( i->first == sTexturePlugInType )
				return i->second;
		}
		return 0;
	}

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

}  //End Ogre Namespace

<|endoftext|>


<commit_before>#include <TChain.h>
#include <TParticle.h>

#include "AliAnalysisCODEXtask.h"
#include "AliAnalysisCODEX.h"

#include "AliAnalysisManager.h"
#include "AliCentrality.h"
#include "AliMultSelection.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliESDTOFCluster.h"
#include "AliInputEventHandler.h"
#include "AliPIDResponse.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliTOFPIDResponse.h"
#include "TH2I.h"

#include <climits>

ClassImp(AliAnalysisCODEXtask);

using namespace AliAnalysisCODEX;

AliAnalysisCODEXtask::AliAnalysisCODEXtask(const char* name)
  :AliAnalysisTaskSE(name)
  ,mMCtrue(false)
  ,mCentralityMode(0)
  ,Cuts()
  ,mOutput(0x0)
  ,mTree(0x0)
  ,mPIDresponse(0x0)
  ,mHeader()
  ,mTracks()
  ,mTimeChan(0x0)
  ,mEventCuts(false)
{
  Cuts.SetMinNClustersTPC(60);
  Cuts.SetMaxChi2PerClusterTPC(6);
  Cuts.SetAcceptKinkDaughters(false);
  Cuts.SetRequireTPCRefit(true);
  Cuts.SetRequireITSRefit(false);
  Cuts.SetMaxDCAToVertexZ(3);
  Cuts.SetMaxDCAToVertexXY(3);
  Cuts.SetMaxChi2PerClusterITS(100000000.);
  Cuts.SetMaxChi2TPCConstrainedGlobal(100000000.);
  Cuts.SetEtaRange(-0.8,0.8);
  DefineInput(0, TChain::Class());
  DefineOutput(1, TTree::Class());
  DefineOutput(2, TList::Class());
}

AliAnalysisCODEXtask::~AliAnalysisCODEXtask() {
  if (mPIDresponse) {
    delete mPIDresponse;
    mPIDresponse = 0x0;
  }

  if (mTree) {
    delete mTree;
    mTree = 0x0;
  }

  if (mOutput){
    delete mOutput;
    mOutput = 0x0;
  }

}

void AliAnalysisCODEXtask::UserCreateOutputObjects() {
  // Creation of the histograms, this is called once
  //
  OpenFile(1);
  mTree = new TTree("AliCODEX","Alice COmpressed Dataset for EXotica");
  mTree->Branch("Header",&mHeader);
  mTree->Branch("Tracks",&mTracks);
  //
  mTree->SetAutoSave(100000000);
  PostData(1,mTree);

  OpenFile(2);
  if (!mOutput) mOutput = new TList();
  mOutput->SetOwner();

  //
  // Get PID response object
  AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager();
  if(!man)
    AliFatal("Could not find manager");
  AliInputEventHandler* handler = dynamic_cast<AliInputEventHandler*> (man->GetInputEventHandler());
  if(!handler)
    AliFatal("No input event handler");
  mPIDresponse = dynamic_cast<AliPIDResponse*>(handler->GetPIDResponse());
  if (!mPIDresponse)
    AliFatal("PIDResponse object was not created"); // Escalated to fatal. Task is unusable without PID response.

  //
  //Define output histograms
  //
  mTimeChan = new TH2I("mTimeChan", "Histogram with Channel/Time correlation;Channel;TOF (ps)", 3276, 0. -.5, 157248. -.5, 5000, 10000, 80000);
  mOutput->AddLast(mTimeChan);

  mEventCuts.AddQAplotsToList(mOutput);
  PostData(2,mOutput);

}

void AliAnalysisCODEXtask::UserExec(Option_t *){
  mHeader.mEventMask = 0;

  AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!event) return;
  if (!mEventCuts.AcceptEvent(event)) {
    PostData(2, mOutput);
    return;
  }

  AliTOFPIDResponse& tofPID = mPIDresponse->GetTOFResponse();
  for (int iB = 0; iB < 10; ++iB) {
    mHeader.mT0event[iB] = tofPID.GetT0bin(iB);
    mHeader.mT0resolution[iB] = tofPID.GetT0binRes(iB);
    mHeader.mT0mask[iB] = tofPID.GetT0binMask(iB);
  }

  const AliESDVertex *vertex = static_cast<const AliESDVertex*>(mEventCuts.GetPrimaryVertex());
  mHeader.SetVertexZposition(vertex->GetZ());

  const unsigned short standard_mask = (Cuts.GetRequireTPCRefit()) ? kTPCrefit : 0;

  float cent = mEventCuts.GetCentrality(0);
  mHeader.SetCentrality(cent);

  if (event->GetMagneticField() < 0) mHeader.mEventMask |= kNegativeB;

  /// Check Monte Carlo information and other access first:
  AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  if (!eventHandler) {
    if (mMCtrue)
      AliFatal("You asked for MC analysis, but I don't find any MCEventHandler... did you forget to add it to your analysis manager?");
  }
  //
  AliMCEvent* mcEvent = 0x0;
  AliStack* stack = 0x0;
  if (eventHandler) mcEvent = eventHandler->MCEvent();
  if (!mcEvent && mMCtrue)
    AliFatal("Missing MC event");
  if (mMCtrue) {
    stack = mcEvent->Stack();
    if (!stack)
      AliFatal("Missing MC stack");
    mHeader.mEventMask |= kMCevent;
  }

  bool first = true;
  mTracks.clear();
  Track t;
  for (int iEv = 0;iEv < event->GetNumberOfTracks(); ++iEv) {
    AliESDtrack *track = event->GetTrack(iEv);

    /// Tracking quality cuts
    if (!track->GetInnerParam()) continue;
    if (!Cuts.AcceptTrack(track)) continue;

    /// PID cuts
    float sigEl = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kElectron);
    float sigPi = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kPion);
    float sigKa = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kKaon);
    float sigPr = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kProton);
    float sigDe = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kDeuteron);
    float sigH3  = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kTriton);
    float sigHe3 = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kHe3);
    float sigHe4 = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kAlpha);

    /// Cut tracks without TOF matching at moderate high pT
    float time = 0.;
    int   channel = -1;
    if (!(track->GetStatus() & AliESDtrack::kTOFout) || !(track->GetStatus() & AliESDtrack::kTIME)) {
      time = -1.f;
    } else {
      float len = track->GetIntegratedLength();
      if (len < 350.f) {
        time = -1.f;
      } else {
        float time0 = mPIDresponse->GetTOFResponse().GetStartTime(track->P());
        time = track->GetTOFsignal() - time0;

        // TOF number of clusters
        t.SetTOFNcls(track->GetNTOFclusters());

        // Momentum at the TOF
        const double t_d = tofPID.GetExpectedSignal(track, AliPID::kDeuteron);
        const double beta_d = len / (t_d * kCtof);
        t.SetTOFmomentum((fabs(beta_d - 1.f) < 1.e-24) ? track->GetTPCmomentum() : kDeuteronMass * beta_d / sqrt(1. - (beta_d * beta_d)));

        channel = track->GetTOFCalChannel();
        // Get mismatch signal
        if (t.GetTOFNcls() > 1) {
          int idx = track->GetTOFclusterArray()[t.TOFnClusters - 1];
          AliESDTOFCluster* clust = (AliESDTOFCluster *)event->GetESDTOFClusters()->At(idx);
          int clsindex = -1;
          for(Int_t iMTr = 0; iMTr < clust->GetNMatchableTracks(); iMTr++){
            if(clust->GetTrackIndex(iMTr) == track->GetID()){
              clsindex = iMTr;
              break;
            }
          }
          if (clsindex > -1) {
            float TOFmismatch = clust->GetTime(clsindex) * clust->GetLength(clsindex) / len;
            mTimeChan->Fill(channel, TOFmismatch);
          }
        }
      }
    }
    t.SetTOFchannel(channel);
    t.SetTOFsignal(time);
    t.SetIntegratedLength(track->GetIntegratedLength());

    if (track->GetNumberOfTRDClusters() > 0)
      t.mask |= AliAnalysisCODEX::kTRDout;

    /// Put the right information in the right place
    t.eta = track->Eta();
    t.phi = track->Phi();
    t.pTPC = track->GetInnerParam()->GetP();
    t.pT = track->Pt();
    if (track->Charge() < 0) t.pT = -t.pT;

    /// PID information
    //for (int i = 0; i < 8; ++i) t.TPCsigmas[i] = SCHAR_MAX;
    t.SetTPCsigma(kEl,sigEl);
    t.SetTPCsigma(kPi,sigPi);
    t.SetTPCsigma(kKa,sigKa);
    t.SetTPCsigma(kPr,sigPr);
    t.SetTPCsigma(kDe,sigDe);
    t.SetTPCsigma(kH3,sigH3);
    t.SetTPCsigma(kHe3,sigHe3);
    t.SetTPCsigma(kHe4,sigHe4);
    t.TPCsignal = track->GetTPCsignal();

    /// Number of clusters
    t.TPCnClusters = track->GetTPCNcls();
    /// Number of findable clusters
    t.TPCnClustersF = track->GetTPCNclsF();
    /// Number of crossed rows
    t.TPCnXedRows = track->GetTPCCrossedRows();
    t.TPCnSignal = track->GetTPCsignalN();
    t.ITSmap = track->GetITSClusterMap();
    if ((track->GetStatus() & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) t.ITSmap |= AliAnalysisCODEX::kITSrefit;
    /// Track length in active region
    t.ActiveLength = track->GetLengthInActiveZone(0, 3, 220., event->GetMagneticField());

    /// Mask
    t.mask = standard_mask | kIsReconstructed;

    /// Binned information
    float cov[3],dca[2];
    track->GetImpactParameters(dca,cov);
    t.SetDCAxy(dca[0]);
    t.SetDCAz(dca[1]);
    t.SetTPCChi2NDF(track->GetTPCchi2() / track->GetTPCNcls());
    t.SetITSChi2NDF((track->GetITSNcls()) ? track->GetITSchi2() / track->GetITSNcls() : 1.e9);
    t.SetGoldenChi2NDF(track->GetChi2TPCConstrainedVsGlobal(vertex));

    if (mMCtrue) {
      int label = track->GetLabel();
      TParticle* part = stack->Particle(abs(label));
      if (!part) continue;
      int particle_mask = GetParticleMask(part);
      if (!particle_mask) continue;
      t.mask |= particle_mask;

      if (label < 0) t.mask |= kIsFake;

      if (time > 0) {
        int TOFlabel[3];
        track->GetTOFLabel(TOFlabel);
        bool TOFmismatch = true;
        for (int i = 0; i < 3; ++i)
          if (TOFlabel[i] > 0 && TOFlabel[i] == abs(label))
            TOFmismatch = false;
        if (TOFmismatch) t.mask |= kTOFmismatch;
      }

      if (stack->IsPhysicalPrimary(abs(label))) t.mask |= kIsPrimary;
      else if (stack->IsSecondaryFromMaterial(abs(label))) t.mask |= kIsSecondaryFromMaterial;
    }

    /// If everything went OK pushing the track
    mTracks.push_back(t);
  }

  if (mMCtrue) {
    t.TPCnClusters = 0;
    t.TPCnSignal = 0;
    for (int i = 0; i < 8; ++i) t.TPCsigmas[i] = SCHAR_MAX;
    t.TOFsignal = -1;
    t.ITSmap = 0;
    t.DCAxy = 0;
    t.DCAz = 0;
    t.TPCchi2NDF = 0;
    t.ITSchi2NDF = 0;
    for (int iP = 0; iP < stack->GetNtrack(); ++iP) {
      TParticle* particle = stack->Particle(iP);
      if (!particle)
        continue;

      if (particle->Energy() <= fabs(particle->Pz())) continue; // fix improper TParticle->Y() behaviour
      if (fabs(particle->Y()) > 1.)
        continue;

      int particle_mask = GetParticleMask(particle);
      if (!particle_mask)
        continue;
      t.mask = particle_mask;
      if (stack->IsPhysicalPrimary(iP)) t.mask |= kIsPrimary;
      else if (stack->IsSecondaryFromMaterial(iP)) t.mask |= kIsSecondaryFromMaterial;

      t.eta = particle->Eta();
      t.phi = particle->Phi();
      t.pT = (particle->GetPdgCode() > 0) ? particle->Pt() : -particle->Pt();
      t.pTPC = particle->P();

      /// Pushing the MC particle
      mTracks.push_back(t);
    }
  }
  mTree->Fill();
  PostData(1,mTree);

  PostData(2,mOutput);
}

long AliAnalysisCODEXtask::GetParticleMask(TParticle *part) {
  int pdg = part->GetPdgCode();
  switch (abs(pdg)) {
    case 11: return kEl;
    case 211: return kPi;
    case 321: return kKa;
    case 2212: return kPr;
    case 1000010020: return kDe;
    case 1000010030: return kH3;
    case 1000020030: return kHe3;
    case 1000020040: return kHe4;
  }
  return 0;
}
<commit_msg>Remove AliStack from CODEX creation<commit_after>#include <TChain.h>
#include <TParticle.h>

#include "AliAnalysisCODEXtask.h"
#include "AliAnalysisCODEX.h"

#include "AliAnalysisManager.h"
#include "AliCentrality.h"
#include "AliMultSelection.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliESDTOFCluster.h"
#include "AliInputEventHandler.h"
#include "AliPIDResponse.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliTOFPIDResponse.h"
#include "TH2I.h"

#include <climits>

ClassImp(AliAnalysisCODEXtask);

using namespace AliAnalysisCODEX;

AliAnalysisCODEXtask::AliAnalysisCODEXtask(const char* name)
  :AliAnalysisTaskSE(name)
  ,mMCtrue(false)
  ,mCentralityMode(0)
  ,Cuts()
  ,mOutput(0x0)
  ,mTree(0x0)
  ,mPIDresponse(0x0)
  ,mHeader()
  ,mTracks()
  ,mTimeChan(0x0)
  ,mEventCuts(false)
{
  Cuts.SetMinNClustersTPC(60);
  Cuts.SetMaxChi2PerClusterTPC(6);
  Cuts.SetAcceptKinkDaughters(false);
  Cuts.SetRequireTPCRefit(true);
  Cuts.SetRequireITSRefit(false);
  Cuts.SetMaxDCAToVertexZ(3);
  Cuts.SetMaxDCAToVertexXY(3);
  Cuts.SetMaxChi2PerClusterITS(100000000.);
  Cuts.SetMaxChi2TPCConstrainedGlobal(100000000.);
  Cuts.SetEtaRange(-0.8,0.8);
  DefineInput(0, TChain::Class());
  DefineOutput(1, TTree::Class());
  DefineOutput(2, TList::Class());
}

AliAnalysisCODEXtask::~AliAnalysisCODEXtask() {
  if (mPIDresponse) {
    delete mPIDresponse;
    mPIDresponse = 0x0;
  }

  if (mTree) {
    delete mTree;
    mTree = 0x0;
  }

  if (mOutput){
    delete mOutput;
    mOutput = 0x0;
  }

}

void AliAnalysisCODEXtask::UserCreateOutputObjects() {
  // Creation of the histograms, this is called once
  //
  OpenFile(1);
  mTree = new TTree("AliCODEX","Alice COmpressed Dataset for EXotica");
  mTree->Branch("Header",&mHeader);
  mTree->Branch("Tracks",&mTracks);
  //
  mTree->SetAutoSave(100000000);
  PostData(1,mTree);

  OpenFile(2);
  if (!mOutput) mOutput = new TList();
  mOutput->SetOwner();

  //
  // Get PID response object
  AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager();
  if(!man)
    AliFatal("Could not find manager");
  AliInputEventHandler* handler = dynamic_cast<AliInputEventHandler*> (man->GetInputEventHandler());
  if(!handler)
    AliFatal("No input event handler");
  mPIDresponse = dynamic_cast<AliPIDResponse*>(handler->GetPIDResponse());
  if (!mPIDresponse)
    AliFatal("PIDResponse object was not created"); // Escalated to fatal. Task is unusable without PID response.

  //
  //Define output histograms
  //
  mTimeChan = new TH2I("mTimeChan", "Histogram with Channel/Time correlation;Channel;TOF (ps)", 3276, 0. -.5, 157248. -.5, 5000, 10000, 80000);
  mOutput->AddLast(mTimeChan);

  mEventCuts.AddQAplotsToList(mOutput);
  PostData(2,mOutput);

}

void AliAnalysisCODEXtask::UserExec(Option_t *){
  mHeader.mEventMask = 0;

  AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!event) return;
  if (!mEventCuts.AcceptEvent(event)) {
    PostData(2, mOutput);
    return;
  }

  AliTOFPIDResponse& tofPID = mPIDresponse->GetTOFResponse();
  for (int iB = 0; iB < 10; ++iB) {
    mHeader.mT0event[iB] = tofPID.GetT0bin(iB);
    mHeader.mT0resolution[iB] = tofPID.GetT0binRes(iB);
    mHeader.mT0mask[iB] = tofPID.GetT0binMask(iB);
  }

  const AliESDVertex *vertex = static_cast<const AliESDVertex*>(mEventCuts.GetPrimaryVertex());
  mHeader.SetVertexZposition(vertex->GetZ());

  const unsigned short standard_mask = (Cuts.GetRequireTPCRefit()) ? kTPCrefit : 0;

  float cent = mEventCuts.GetCentrality(0);
  mHeader.SetCentrality(cent);

  if (event->GetMagneticField() < 0) mHeader.mEventMask |= kNegativeB;

  /// Check Monte Carlo information and other access first:
  AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  if (!eventHandler) {
    if (mMCtrue)
      AliFatal("You asked for MC analysis, but I don't find any MCEventHandler... did you forget to add it to your analysis manager?");
  }
  //
  AliMCEvent* mcEvent = nullptr;
  if (eventHandler) mcEvent = eventHandler->MCEvent();
  if (!mcEvent && mMCtrue)
    AliFatal("Missing MC event");
  if (mMCtrue) {
    mHeader.mEventMask |= kMCevent;
  }

  bool first = true;
  mTracks.clear();
  Track t;
  for (int iEv = 0;iEv < event->GetNumberOfTracks(); ++iEv) {
    AliESDtrack *track = event->GetTrack(iEv);

    /// Tracking quality cuts
    if (!track->GetInnerParam()) continue;
    if (!Cuts.AcceptTrack(track)) continue;

    /// PID cuts
    float sigEl = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kElectron);
    float sigPi = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kPion);
    float sigKa = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kKaon);
    float sigPr = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kProton);
    float sigDe = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kDeuteron);
    float sigH3  = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kTriton);
    float sigHe3 = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kHe3);
    float sigHe4 = mPIDresponse->NumberOfSigmas(AliPIDResponse::kTPC,track,AliPID::kAlpha);

    /// Cut tracks without TOF matching at moderate high pT
    float time = 0.;
    int   channel = -1;
    if (!(track->GetStatus() & AliESDtrack::kTOFout) || !(track->GetStatus() & AliESDtrack::kTIME)) {
      time = -1.f;
    } else {
      float len = track->GetIntegratedLength();
      if (len < 350.f) {
        time = -1.f;
      } else {
        float time0 = mPIDresponse->GetTOFResponse().GetStartTime(track->P());
        time = track->GetTOFsignal() - time0;

        // TOF number of clusters
        t.SetTOFNcls(track->GetNTOFclusters());

        // Momentum at the TOF
        const double t_d = tofPID.GetExpectedSignal(track, AliPID::kDeuteron);
        const double beta_d = len / (t_d * kCtof);
        t.SetTOFmomentum((fabs(beta_d - 1.f) < 1.e-24) ? track->GetTPCmomentum() : kDeuteronMass * beta_d / sqrt(1. - (beta_d * beta_d)));

        channel = track->GetTOFCalChannel();
        // Get mismatch signal
        if (t.GetTOFNcls() > 1) {
          int idx = track->GetTOFclusterArray()[t.TOFnClusters - 1];
          AliESDTOFCluster* clust = (AliESDTOFCluster *)event->GetESDTOFClusters()->At(idx);
          int clsindex = -1;
          for(Int_t iMTr = 0; iMTr < clust->GetNMatchableTracks(); iMTr++){
            if(clust->GetTrackIndex(iMTr) == track->GetID()){
              clsindex = iMTr;
              break;
            }
          }
          if (clsindex > -1) {
            float TOFmismatch = clust->GetTime(clsindex) * clust->GetLength(clsindex) / len;
            mTimeChan->Fill(channel, TOFmismatch);
          }
        }
      }
    }
    t.SetTOFchannel(channel);
    t.SetTOFsignal(time);
    t.SetIntegratedLength(track->GetIntegratedLength());

    if (track->GetNumberOfTRDClusters() > 0)
      t.mask |= AliAnalysisCODEX::kTRDout;

    /// Put the right information in the right place
    t.eta = track->Eta();
    t.phi = track->Phi();
    t.pTPC = track->GetInnerParam()->GetP();
    t.pT = track->Pt();
    if (track->Charge() < 0) t.pT = -t.pT;

    /// PID information
    //for (int i = 0; i < 8; ++i) t.TPCsigmas[i] = SCHAR_MAX;
    t.SetTPCsigma(kEl,sigEl);
    t.SetTPCsigma(kPi,sigPi);
    t.SetTPCsigma(kKa,sigKa);
    t.SetTPCsigma(kPr,sigPr);
    t.SetTPCsigma(kDe,sigDe);
    t.SetTPCsigma(kH3,sigH3);
    t.SetTPCsigma(kHe3,sigHe3);
    t.SetTPCsigma(kHe4,sigHe4);
    t.TPCsignal = track->GetTPCsignal();

    /// Number of clusters
    t.TPCnClusters = track->GetTPCNcls();
    /// Number of findable clusters
    t.TPCnClustersF = track->GetTPCNclsF();
    /// Number of crossed rows
    t.TPCnXedRows = track->GetTPCCrossedRows();
    t.TPCnSignal = track->GetTPCsignalN();
    t.ITSmap = track->GetITSClusterMap();
    if ((track->GetStatus() & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) t.ITSmap |= AliAnalysisCODEX::kITSrefit;
    /// Track length in active region
    t.ActiveLength = track->GetLengthInActiveZone(0, 3, 220., event->GetMagneticField());

    /// Mask
    t.mask = standard_mask | kIsReconstructed;

    /// Binned information
    float cov[3],dca[2];
    track->GetImpactParameters(dca,cov);
    t.SetDCAxy(dca[0]);
    t.SetDCAz(dca[1]);
    t.SetTPCChi2NDF(track->GetTPCchi2() / track->GetTPCNcls());
    t.SetITSChi2NDF((track->GetITSNcls()) ? track->GetITSchi2() / track->GetITSNcls() : 1.e9);
    t.SetGoldenChi2NDF(track->GetChi2TPCConstrainedVsGlobal(vertex));

    if (mMCtrue) {
      int label = track->GetLabel();
      TParticle* part = mcEvent->Particle(abs(label));
      if (!part) continue;
      int particle_mask = GetParticleMask(part);
      if (!particle_mask) continue;
      t.mask |= particle_mask;

      if (label < 0) t.mask |= kIsFake;

      if (time > 0) {
        int TOFlabel[3];
        track->GetTOFLabel(TOFlabel);
        bool TOFmismatch = true;
        for (int i = 0; i < 3; ++i)
          if (TOFlabel[i] > 0 && TOFlabel[i] == abs(label))
            TOFmismatch = false;
        if (TOFmismatch) t.mask |= kTOFmismatch;
      }

      if (mcEvent->IsPhysicalPrimary(abs(label))) t.mask |= kIsPrimary;
      else if (mcEvent->IsSecondaryFromMaterial(abs(label))) t.mask |= kIsSecondaryFromMaterial;
    }

    /// If everything went OK pushing the track
    mTracks.push_back(t);
  }

  if (mMCtrue) {
    t.TPCnClusters = 0;
    t.TPCnSignal = 0;
    for (int i = 0; i < 8; ++i) t.TPCsigmas[i] = SCHAR_MAX;
    t.TOFsignal = -1;
    t.ITSmap = 0;
    t.DCAxy = 0;
    t.DCAz = 0;
    t.TPCchi2NDF = 0;
    t.ITSchi2NDF = 0;
    for (int iP = 0; iP < mcEvent->GetNumberOfTracks(); ++iP) {
      TParticle* particle = mcEvent->Particle(iP);
      if (!particle)
        continue;

      if (particle->Energy() <= fabs(particle->Pz())) continue; // fix improper TParticle->Y() behaviour
      if (fabs(particle->Y()) > 1.)
        continue;

      int particle_mask = GetParticleMask(particle);
      if (!particle_mask)
        continue;
      t.mask = particle_mask;
      if (mcEvent->IsPhysicalPrimary(iP)) t.mask |= kIsPrimary;
      else if (mcEvent->IsSecondaryFromMaterial(iP)) t.mask |= kIsSecondaryFromMaterial;

      t.eta = particle->Eta();
      t.phi = particle->Phi();
      t.pT = (particle->GetPdgCode() > 0) ? particle->Pt() : -particle->Pt();
      t.pTPC = particle->P();

      /// Pushing the MC particle
      mTracks.push_back(t);
    }
  }
  mTree->Fill();
  PostData(1,mTree);

  PostData(2,mOutput);
}

long AliAnalysisCODEXtask::GetParticleMask(TParticle *part) {
  int pdg = part->GetPdgCode();
  switch (abs(pdg)) {
    case 11: return kEl;
    case 211: return kPi;
    case 321: return kKa;
    case 2212: return kPr;
    case 1000010020: return kDe;
    case 1000010030: return kH3;
    case 1000020030: return kHe3;
    case 1000020040: return kHe4;
  }
  return 0;
}
<|endoftext|>


<commit_before>/***************************************************************************
// Chitrasen Jena (cjena@cern.ch) -last modified on 15 Oct 2016

// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) path where all configs are stored
// ---
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/

AliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeV
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kFALSE,
 Int_t       Strcut = 2015,
 Int_t       customQualityCutsID = 1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaK = 3.0,
 Bool_t      enableMonitor = kTRUE,
 Int_t       nmix = 5,
 Float_t     maxDiffVzMix = 1.0,
 Float_t     maxDiffMultMix = 5.0,
 Double_t    vtxZcut = 10.0,
 Double_t    Ylab = 0.5,
 TString     outNameSuffix = "PbPb"
 )
{
  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask=AliVEvent::kINT7;
  Bool_t      rejectPileUp=kTRUE;
  Int_t       MultBins=1;//Using AliMultSelection for centrality determination

  //-------------------------------------------
  // pair cuts
  //-------------------------------------------
  Double_t    minYlab=-Ylab;
  Double_t    maxYlab=Ylab;

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskPhiPbPb5TeV", "No analysis manager to connect to.");
      return NULL;
   }

   // create the task and configure
   TString taskName = Form("Phi%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));

   AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
   //task->SelectCollisionCandidates(triggerMask);//AOD
   task->UseESDTriggerMask(triggerMask);//ESD
   if (isPP)
     task->UseMultiplicity("QUALITY");
   else
     //task->UseCentrality("V0M");
     task->UseMultiplicity("AliMultSelection_V0M");//For Run II

   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   task->UseMC(isMC);
   ::Info("AddTaskPhiPbPb5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

   AliRsnCutPrimaryVertex* cutVertex=0;
  if(!MultBins){
    cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
    cutVertex->SetCheckZResolutionSPD();
    cutVertex->SetCheckDispersionSPD();
    cutVertex->SetCheckZDifferenceSPDTrack();
  }

  AliRsnCutEventUtils* cutEventUtils=0;
  cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
  if(!MultBins){
    cutEventUtils->SetCheckIncompleteDAQ();
    cutEventUtils->SetCheckSPDClusterVsTrackletBG();
    cutEventUtils->SetCheckInelGt0SPDtracklets();
  }else{
    cutEventUtils->SetCheckAcceptedMultSelection();
  }
  if(isPP && (!isMC) && cutVertex){
    cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
    ::Info("AddTaskPhiPbPb5TeV", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
  }

  // define and fill cut set for event cut
  AliRsnCutSet* eventCuts=0;
  if(cutEventUtils || cutVertex){
    eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);

    if(cutEventUtils && cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
    }else if(cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
    }else if(!cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
    }

   // set cuts in task
   task->SetEventCuts(eventCuts);
  }

   //
   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //
   //vertex
   Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
   AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
   outVtx->AddAxis(vtxID, 400, -20.0, 20.0);

   //multiplicity or centrality
   Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
   AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
   if (isPP)
     outMult->AddAxis(multID, 400, 0.0, 400.0);
   else
     outMult->AddAxis(multID, 100, 0.0, 100.0);

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   //

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(-0.5, 0.5);
   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   cutsPair->SetCutScheme(cutY->GetName());

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   //
   //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeV.C");
   gROOT->LoadMacro("ConfigPhiPbPb5TeV.C");
   if (!ConfigPhiPbPb5TeV(task, isMC, isPP, "", cutsPair, Strcut, customQualityCutsID, cutKaCandidate, nsigmaK, enableMonitor)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddTaskPhiPbPb5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							   TList::Class(),
							   AliAnalysisManager::kOutputContainer,
							   outputFileName);
   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}
<commit_msg>change the directory of LoadMacro for Phi analysis in PbPb @ 5TeV<commit_after>/***************************************************************************
// Chitrasen Jena (cjena@cern.ch) -last modified on 15 Oct 2016

// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) path where all configs are stored
// ---
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/

AliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeV
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kFALSE,
 Int_t       Strcut = 2015,
 Int_t       customQualityCutsID = 1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaK = 3.0,
 Bool_t      enableMonitor = kTRUE,
 Int_t       nmix = 5,
 Float_t     maxDiffVzMix = 1.0,
 Float_t     maxDiffMultMix = 5.0,
 Double_t    vtxZcut = 10.0,
 Double_t    Ylab = 0.5,
 TString     outNameSuffix = "PbPb"
 )
{
  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask=AliVEvent::kINT7;
  Bool_t      rejectPileUp=kTRUE;
  Int_t       MultBins=1;//Using AliMultSelection for centrality determination

  //-------------------------------------------
  // pair cuts
  //-------------------------------------------
  Double_t    minYlab=-Ylab;
  Double_t    maxYlab=Ylab;

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskPhiPbPb5TeV", "No analysis manager to connect to.");
      return NULL;
   }

   // create the task and configure
   TString taskName = Form("Phi%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));

   AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
   //task->SelectCollisionCandidates(triggerMask);//AOD
   task->UseESDTriggerMask(triggerMask);//ESD
   if (isPP)
     task->UseMultiplicity("QUALITY");
   else
     //task->UseCentrality("V0M");
     task->UseMultiplicity("AliMultSelection_V0M");//For Run II

   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   task->UseMC(isMC);
   ::Info("AddTaskPhiPbPb5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

   AliRsnCutPrimaryVertex* cutVertex=0;
  if(!MultBins){
    cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
    cutVertex->SetCheckZResolutionSPD();
    cutVertex->SetCheckDispersionSPD();
    cutVertex->SetCheckZDifferenceSPDTrack();
  }

  AliRsnCutEventUtils* cutEventUtils=0;
  cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
  if(!MultBins){
    cutEventUtils->SetCheckIncompleteDAQ();
    cutEventUtils->SetCheckSPDClusterVsTrackletBG();
    cutEventUtils->SetCheckInelGt0SPDtracklets();
  }else{
    cutEventUtils->SetCheckAcceptedMultSelection();
  }
  if(isPP && (!isMC) && cutVertex){
    cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
    ::Info("AddTaskPhiPbPb5TeV", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
  }

  // define and fill cut set for event cut
  AliRsnCutSet* eventCuts=0;
  if(cutEventUtils || cutVertex){
    eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);

    if(cutEventUtils && cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
    }else if(cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
    }else if(!cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
    }

   // set cuts in task
   task->SetEventCuts(eventCuts);
  }

   //
   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //
   //vertex
   Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
   AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
   outVtx->AddAxis(vtxID, 400, -20.0, 20.0);

   //multiplicity or centrality
   Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
   AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
   if (isPP)
     outMult->AddAxis(multID, 400, 0.0, 400.0);
   else
     outMult->AddAxis(multID, 100, 0.0, 100.0);

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   //

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(-0.5, 0.5);
   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   cutsPair->SetCutScheme(cutY->GetName());

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   //
   gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeV.C");
   //gROOT->LoadMacro("ConfigPhiPbPb5TeV.C");
   if (!ConfigPhiPbPb5TeV(task, isMC, isPP, "", cutsPair, Strcut, customQualityCutsID, cutKaCandidate, nsigmaK, enableMonitor)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddTaskPhiPbPb5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							   TList::Class(),
							   AliAnalysisManager::kOutputContainer,
							   outputFileName);
   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}
<|endoftext|>


<commit_before>/// \file AddTaskEMCALPi0Calibration.C
/// \ingroup EMCALPerfAddTaskMacros
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///

// Root6
#if !defined(__CINT__) || defined(__MAKECINT__)

#include <TString.h>
#include <TROOT.h>
#include <TSystem.h>

#include "AliLog.h"
#include "AliAnalysisTaskEMCALPi0CalibSelectionV2.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

R__ADD_INCLUDE_PATH($ALICE_PHYSICS)

#endif // CINT

/// Main method
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger   : TString, event that triggered must contain this string. Leave for backward compatibility with old wagons
/// \param recalE    : Bool, recalibrate EMCal energy all other settings for clusterization & EMCal calibration are handled by correction frame work and correspodning yaml file
/// \param simu      : Int, 0: data, 1: MC, 2: JJ MC
/// \param fSaveCells: Bool, save the tree output for cells
/// \param fSaveClusters : Bool, save the tree output for clusters
/// \param minClusterEnergy : Double, minimum cluster energy used for pairing (GeV)
/// \param maxClusterEnergy : Double, maximum cluster energy used for pairing (GeV)
/// \param minNCells : Int, minimum number of cells for clusters
/// \param minClusterTime : Float, minimum cluster time (ns)
/// \param maxClusterTime : Float, maximum cluster time (ns)
/// \param maxDiffTimeClusterPair : Float, maximum cluster time difference between paired clusters (ns)
/// \param bSameSM : Bool, switch on/off paring only in same SM
/// \param outputFile: TString with name of output file (AnalysisResults.root).
/// \param trigSuffix :  A string with the trigger class, abbreviated, to run multiple triggers in same train
///
AliAnalysisTaskEMCALPi0CalibSelectionV2 * AddTaskEMCALPi0CalibrationV2(
  TString calibPath              = "", // "alienpath/RecalibrationFactors.root"
  TString trigger                = "",
  Bool_t  recalE                 = kFALSE,
  Int_t  simu                    = 0,
  Bool_t  fSaveCells             = kFALSE,
  Bool_t  fSaveClusters          = kFALSE,
  Bool_t  isHeavyIon             = kFALSE,
  Double_t minClusterEnergy      = 0.7,
  Double_t maxClusterEnergy      = 10,
  Int_t minNCells                = 2,
  Float_t minClusterTime         = 300,  // 560 ns in Run1
  Float_t maxClusterTime         = 800,  // 610 ns in Run1
  Float_t maxDiffTimeClusterPair = 100,  //  20 ns in Run1
  Bool_t bSameSM                 = kTRUE,
  TString outputFile             = "", // AnalysisResults.root
  const char *trigSuffix         = ""
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
    return NULL;
  }

  TString wagon = trigSuffix;
  if ( wagon.Length() > 0 ) trigger = wagon;

  AliAnalysisTaskEMCALPi0CalibSelectionV2 * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelectionV2(Form("EMCALPi0Calibration_%s",trigger.Data()));
  pi0calib->SetClusterMinEnergy(minClusterEnergy);
  pi0calib->SetClusterMaxEnergy(maxClusterEnergy);
  pi0calib->SetClusterLambda0Cuts(0.1,0.5);

  pi0calib->SetAsymmetryCut(1.);
  pi0calib->SetClusterMinNCells(minNCells);
  pi0calib->SetNCellsGroup(0);
  if (bSameSM) pi0calib->SwitchOnSameSM();
    else pi0calib->SwitchOffSameSM();

  // Timing cuts
  pi0calib->SetPairDTimeCut(maxDiffTimeClusterPair);
  pi0calib->SetClusterMinTime(minClusterTime);
  pi0calib->SetClusterMaxTime(maxClusterTime);

  pi0calib->SetTriggerName(trigger);

  //---------------------
  // Geometry alignment
  //---------------------

  pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");
  pi0calib->SwitchOnLoadOwnGeometryMatrices();
  // pi0calib->SetOADBFilePath("/home/ewa/alice/AliPhysics/OADB/OADB/EMCAL");

  if( simu == 1 ) {
    pi0calib->SetIsMC();
  } else if (simu == 2){
    pi0calib->SetJJMC();
  }

  if( isHeavyIon ) {
    pi0calib->SetHeavyIon();
  }

  if( fSaveCells ){
    pi0calib->SetSaveCells();
  }

  if( fSaveClusters ){
    pi0calib->SetSaveClusters();
  }

  //---------------------
  // Print info
  //---------------------

  pi0calib->PrintInfo();

  mgr->AddTask(pi0calib);

  if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  AliAnalysisDataContainer *coutput1 = 0;
  AliAnalysisDataContainer *coutput2 = 0;
  if( wagon.Length()==0 ){
    coutput1 = mgr->CreateContainer(Form("Pi0Calibration_Trig%s",trigger.Data()), TList::Class(),
                                   AliAnalysisManager::kOutputContainer,outputFile.Data());
    if( fSaveCells || fSaveClusters) coutput2 = mgr->CreateContainer(Form("Pi0Calibration_Trig%s_tree",trigger.Data()), TTree::Class(),
                                   AliAnalysisManager::kOutputContainer,Form("%s_tree",outputFile.Data()));
  } else {
    TString containerName = "Pi0Calibration";
    coutput1 = mgr->CreateContainer(wagon, TList::Class(),
                                   AliAnalysisManager::kOutputContainer,Form("%s:%s",outputFile.Data(),containerName.Data()));

    if( fSaveCells || fSaveClusters ) coutput2 = mgr->CreateContainer(Form("%s_tree",trigger.Data()), TTree::Class(),
                                   AliAnalysisManager::kOutputContainer,Form("%s:%s_tree",outputFile.Data(),containerName.Data()));
  }

  mgr->AddTask(pi0calib);

  mgr->ConnectInput  (pi0calib, 0, cinput1);
  mgr->ConnectOutput (pi0calib, 1, coutput1);
  if(fSaveCells || fSaveClusters) mgr->ConnectOutput( pi0calib, 2, coutput2);

  return pi0calib;
}
<commit_msg>PWGPP/EMCAL: save tree to separate file<commit_after>/// \file AddTaskEMCALPi0Calibration.C
/// \ingroup EMCALPerfAddTaskMacros
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///

// Root6
#if !defined(__CINT__) || defined(__MAKECINT__)

#include <TString.h>
#include <TROOT.h>
#include <TSystem.h>

#include "AliLog.h"
#include "AliAnalysisTaskEMCALPi0CalibSelectionV2.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

R__ADD_INCLUDE_PATH($ALICE_PHYSICS)

#endif // CINT

/// Main method
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger   : TString, event that triggered must contain this string. Leave for backward compatibility with old wagons
/// \param recalE    : Bool, recalibrate EMCal energy all other settings for clusterization & EMCal calibration are handled by correction frame work and correspodning yaml file
/// \param simu      : Int, 0: data, 1: MC, 2: JJ MC
/// \param fSaveCells: Bool, save the tree output for cells
/// \param fSaveClusters : Bool, save the tree output for clusters
/// \param minClusterEnergy : Double, minimum cluster energy used for pairing (GeV)
/// \param maxClusterEnergy : Double, maximum cluster energy used for pairing (GeV)
/// \param minNCells : Int, minimum number of cells for clusters
/// \param minClusterTime : Float, minimum cluster time (ns)
/// \param maxClusterTime : Float, maximum cluster time (ns)
/// \param maxDiffTimeClusterPair : Float, maximum cluster time difference between paired clusters (ns)
/// \param bSameSM : Bool, switch on/off paring only in same SM
/// \param outputFile: TString with name of output file (AnalysisResults.root).
/// \param trigSuffix :  A string with the trigger class, abbreviated, to run multiple triggers in same train
///
AliAnalysisTaskEMCALPi0CalibSelectionV2 * AddTaskEMCALPi0CalibrationV2(
  TString calibPath              = "", // "alienpath/RecalibrationFactors.root"
  TString trigger                = "",
  Bool_t  recalE                 = kFALSE,
  Int_t  simu                    = 0,
  Bool_t  fSaveCells             = kFALSE,
  Bool_t  fSaveClusters          = kFALSE,
  Bool_t  isHeavyIon             = kFALSE,
  Double_t minClusterEnergy      = 0.7,
  Double_t maxClusterEnergy      = 10,
  Int_t minNCells                = 2,
  Float_t minClusterTime         = 300,  // 560 ns in Run1
  Float_t maxClusterTime         = 800,  // 610 ns in Run1
  Float_t maxDiffTimeClusterPair = 100,  //  20 ns in Run1
  Bool_t bSameSM                 = kTRUE,
  TString outputFile             = "", // AnalysisResults.root
  const char *trigSuffix         = ""
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
    return NULL;
  }

  TString wagon = trigSuffix;
  if ( wagon.Length() > 0 ) trigger = wagon;

  AliAnalysisTaskEMCALPi0CalibSelectionV2 * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelectionV2(Form("EMCALPi0Calibration_%s",trigger.Data()));
  pi0calib->SetClusterMinEnergy(minClusterEnergy);
  pi0calib->SetClusterMaxEnergy(maxClusterEnergy);
  pi0calib->SetClusterLambda0Cuts(0.1,0.5);

  pi0calib->SetAsymmetryCut(1.);
  pi0calib->SetClusterMinNCells(minNCells);
  pi0calib->SetNCellsGroup(0);
  if (bSameSM) pi0calib->SwitchOnSameSM();
    else pi0calib->SwitchOffSameSM();

  // Timing cuts
  pi0calib->SetPairDTimeCut(maxDiffTimeClusterPair);
  pi0calib->SetClusterMinTime(minClusterTime);
  pi0calib->SetClusterMaxTime(maxClusterTime);

  pi0calib->SetTriggerName(trigger);

  //---------------------
  // Geometry alignment
  //---------------------

  pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");
  pi0calib->SwitchOnLoadOwnGeometryMatrices();
  pi0calib->SetOADBFilePath("/home/ewa/alice/AliPhysics/OADB/OADB/EMCAL");

  if( simu == 1 ) {
    pi0calib->SetIsMC();
  } else if (simu == 2){
    pi0calib->SetJJMC();
  }

  if( isHeavyIon ) {
    pi0calib->SetHeavyIon();
  }

  if( fSaveCells ){
    pi0calib->SetSaveCells();
  }

  if( fSaveClusters ){
    pi0calib->SetSaveClusters();
  }

  //---------------------
  // Print info
  //---------------------

  pi0calib->PrintInfo();

  mgr->AddTask(pi0calib);

  if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  AliAnalysisDataContainer *couthistos  = 0;
  AliAnalysisDataContainer *couttree    = 0;
  if( wagon.Length()==0 ){
    couthistos  = mgr->CreateContainer( Form( "Pi0Calibration_Trig%s",trigger.Data() ),
                                        TList::Class(),
                                        AliAnalysisManager::kOutputContainer,
                                        outputFile.Data() );
    if( fSaveCells || fSaveClusters )   couttree    = mgr->CreateContainer( Form("Pi0Calibration_Trig%s",trigger.Data()),
                                                                            TTree::Class(),
                                                                            AliAnalysisManager::kOutputContainer,
                                                                            "Pi0CalibrationTree.root");
  } else {
    TString containerName = "Pi0Calibration";
    couthistos  = mgr->CreateContainer( wagon,
                                        TList::Class(),
                                        AliAnalysisManager::kOutputContainer,
                                        Form("%s:%s",outputFile.Data(),containerName.Data()) );
    if( fSaveCells || fSaveClusters )   couttree    = mgr->CreateContainer( Form("Pi0Calibration_Trig%s",trigger.Data()),
                                                                            TTree::Class(),
                                                                            AliAnalysisManager::kOutputContainer,
                                                                            "Pi0CalibrationTree.root");
  }

  mgr->AddTask(pi0calib);
  mgr->ConnectInput(pi0calib, 0, cinput1);
  mgr->ConnectOutput (pi0calib, 1, couthistos);
  if(fSaveCells || fSaveClusters) mgr->ConnectOutput( pi0calib, 2, couttree);

  return pi0calib;
}
<|endoftext|>