<commit_before>/*!
 * \file hyo_utilities_tests.cpp
 * \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
 * \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
 *
 */

// STL Includes
#include <vector>
#include <string>
#include <iostream>

// External Includes
#include <gtest/gtest.h>    // Include GoogleTest and related libraries/headers

// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"

/*!
* INDEX OF VARIABLES
* P : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* mx, my, mz : x, y, and z momentum
* n : number density
*/

// =============================================================================
// Local helper functions

namespace
{
    struct TestParams
    {
        double gamma = 5./3.;
        std::vector<double> d {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<double> vx {1.0378624601e-100, 1.0829278656e2, 1.0800514112e100};
        std::vector<double> vy {1.0583469014e-100, 1.0283073464e2, 1.0725717864e100};
        std::vector<double> vz {1.0182972216e-100, 1.0417748226e2, 1.0855352639e100};
        std::vector<double> mx {0.2340416681e-100, 0.1019429453e2, 0.5062596954e100};
        std::vector<double> my {0.9924582299e-100, 0.1254780684e2, 0.5939640992e100};
        std::vector<double> mz {0.6703192739e-100, 0.5676716066e2, 0.2115881803e100};
        std::vector<double> E {20.9342082433e-90, 20.9976906577e10, 20.9487120853e300};
        std::vector<double> P {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
        std::vector<double> n {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<double> ge {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
    };
}

TEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ps {1e-20, 139983415580.5549, 1.2697896247496674e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ps = hydro_utilities::Calc_Pressure_Primitive(parameters.E.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));
    }
}

TEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ps {1e-20, 139984604373.87094, 1.3965808056866668e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.mx.at(i), parameters.my.at(i), parameters.mz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));
    }
}

TEST(tHYDROSYSTEMHydroUtilsCalcTemp, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ts = hydro_utilities::Calc_Temp(parameters.P.at(i), parameters.n.at(i));

        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));
    }
}

#ifdef DE
TEST(tHYDROSYSTEMHydroUtilsCalcTempDE, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ts = hydro_utilities::Calc_Temp_DE(parameters.d.at(i), parameters.ge.at(i), parameters.gamma.at(i), parameters.n.at(i));

        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));
    }
}
#endif // DE<commit_msg>add test for temperature utility function<commit_after>/*!
 * \file hyo_utilities_tests.cpp
 * \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
 * \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
 *
 */

// STL Includes
#include <vector>
#include <string>
#include <iostream>

// External Includes
#include <gtest/gtest.h>    // Include GoogleTest and related libraries/headers

// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"

/*!
* INDEX OF VARIABLES
* P : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* mx, my, mz : x, y, and z momentum
* n : number density
*/

// =============================================================================
// Local helper functions

namespace
{
    struct TestParams
    {
        double gamma = 5./3.;
        std::vector<double> d {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<double> vx {1.0378624601e-100, 1.0829278656e2, 1.0800514112e100};
        std::vector<double> vy {1.0583469014e-100, 1.0283073464e2, 1.0725717864e100};
        std::vector<double> vz {1.0182972216e-100, 1.0417748226e2, 1.0855352639e100};
        std::vector<double> mx {0.2340416681e-100, 0.1019429453e2, 0.5062596954e100};
        std::vector<double> my {0.9924582299e-100, 0.1254780684e2, 0.5939640992e100};
        std::vector<double> mz {0.6703192739e-100, 0.5676716066e2, 0.2115881803e100};
        std::vector<double> E {20.9342082433e-90, 20.9976906577e10, 20.9487120853e300};
        std::vector<double> P {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
        std::vector<double> n {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<double> ge {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<double> gamma {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};
        std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
    };
}

TEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ps {1e-20, 139983415580.5549, 1.2697896247496674e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ps = hydro_utilities::Calc_Pressure_Primitive(parameters.E.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));
    }
}

TEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ps {1e-20, 139984604373.87094, 1.3965808056866668e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.mx.at(i), parameters.my.at(i), parameters.mz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));
    }
}

TEST(tHYDROSYSTEMHydroUtilsCalcTemp, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ts = hydro_utilities::Calc_Temp(parameters.P.at(i), parameters.n.at(i));

        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));
    }
}

#ifdef DE
TEST(tHYDROSYSTEMHydroUtilsCalcTempDE, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_Ts = hydro_utilities::Calc_Temp_DE(parameters.d.at(i), parameters.ge.at(i), parameters.gamma.at(i), parameters.n.at(i));

        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));
    }
}
#endif // DE<|endoftext|>


<commit_before>/*
* Copyright (c) 2014, Autonomous Systems Lab
* 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 the Autonomous Systems Lab, ETH Zurich nor the
* names of its contributors 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 HOLDER 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.
*
*/

#ifndef IMUPREDICTION_HPP_
#define IMUPREDICTION_HPP_

#include "kindr/rotations/RotationEigen.hpp"
#include <Eigen/Dense>
#include "Prediction.hpp"
#include "State.hpp"
#include "FilterState.hpp"

namespace rot = kindr::rotations::eigen_impl;

namespace rovio {

using namespace LWF;

class PredictionMeas: public State<VectorElement<3>,VectorElement<3>>{
 public:
  static constexpr unsigned int _acc = 0;
  static constexpr unsigned int _gyr = _acc+1;
  PredictionMeas(){
    static_assert(_gyr+1==E_,"Error with indices");
  }
  ~PredictionMeas(){};
};

template<typename STATE>
class PredictionNoise: public State<TH_multiple_elements<VectorElement<3>,5>,
      ArrayElement<ScalarElement,STATE::nMax_>,
      ArrayElement<VectorElement<2>,STATE::nMax_>>{
 public:
  using State<TH_multiple_elements<VectorElement<3>,5>,
      ArrayElement<ScalarElement,STATE::nMax_>,
      ArrayElement<VectorElement<2>,STATE::nMax_>>::E_;
  static constexpr unsigned int _pos = 0;
  static constexpr unsigned int _vel = _pos+1;
  static constexpr unsigned int _acb = _vel+1;
  static constexpr unsigned int _gyb = _acb+1;
  static constexpr unsigned int _att = _gyb+1;
  static constexpr unsigned int _dep = _att+1;
  static constexpr unsigned int _nor = _dep+1;
  PredictionNoise(){
    static_assert(_nor+1==E_,"Error with indices");
  }
  ~PredictionNoise(){};
};

template<typename STATE>
class ImuPrediction: public Prediction<STATE,PredictionMeas,PredictionNoise<STATE>>{
 public:
  typedef Prediction<STATE,PredictionMeas,PredictionNoise<STATE>> Base;
  using Base::eval;
  using Base::prenoiP_;
  typedef typename Base::mtState mtState;
  typedef typename Base::mtMeas mtMeas;
  typedef typename Base::mtNoise mtNoise;
  typedef typename Base::mtJacInput mtJacInput;
  typedef typename Base::mtJacNoise mtJacNoise;
  typedef typename Base::mtCovMat mtCovMat;
  const Eigen::Vector3d g_;
  ImuPrediction():g_(0,0,-9.81){};
  ~ImuPrediction(){};
  mtState eval(const mtState& state, const mtMeas& meas, const mtNoise noise, double dt) const{
    mtState output;
    output.template get<mtState::_aux>().MwIMmeas_ = meas.template get<mtMeas::_gyr>();
    output.template get<mtState::_aux>().MwIMest_ = meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>();
    Eigen::Vector3d dOmega = -dt*(output.template get<mtState::_aux>().MwIMest_+noise.template get<mtNoise::_att>()/sqrt(dt));
    rot::RotationQuaternionPD dQ;
    dQ = dQ.exponentialMap(dOmega);
    output.template get<mtState::_att>() = state.template get<mtState::_att>()*dQ;
    output.template get<mtState::_pos>() = (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega))
        *state.template get<mtState::_pos>()-dt*(state.template get<mtState::_vel>()-noise.template get<mtNoise::_pos>()/sqrt(dt));
    output.template get<mtState::_vel>() = (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega))
        *state.template get<mtState::_vel>()-dt*(meas.template get<mtMeas::_acc>()-state.template get<mtState::_acb>()+state.template get<mtState::_att>().inverseRotate(g_)-noise.template get<mtNoise::_vel>()/sqrt(dt));
    output.template get<mtState::_acb>() = state.template get<mtState::_acb>()+noise.template get<mtNoise::_acb>()*sqrt(dt);
    output.template get<mtState::_gyb>() = state.template get<mtState::_gyb>()+noise.template get<mtNoise::_gyb>()*sqrt(dt);
    NormalVectorElement nIn, nOut;
    for(unsigned int i=0;i<mtState::nMax_;i++){
      nIn.n_ = state.template get<mtState::_nor>(i);
      output.template get<mtState::_dep>(i) = state.template get<mtState::_dep>(i)+dt*(nIn.get().transpose()*state.template get<mtState::_vel>()
          + noise.template get<mtNoise::_dep>(i)/sqrt(dt));
      nIn.boxPlus(Eigen::Vector2d(nIn.getM().transpose()*(state.template get<mtState::_vel>()/state.template get<mtState::_dep>(i)
          - output.template get<mtState::_aux>().MwIMest_.cross(nIn.get()))*dt+noise.template get<mtNoise::_nor>(i)/sqrt(dt)),nOut);
      output.template get<mtState::_nor>(i) = nOut.get();
    }
    output.template get<mtState::_aux>().wMeasCov_ = prenoiP_.template block<3,3>(mtNoise::template getId<mtNoise::_att>(),mtNoise::template getId<mtNoise::_att>())/dt;
    output.template get<mtState::_aux>().img_ = state.template get<mtState::_aux>().img_;
    output.fix();
    return output;
  }
  void noMeasCase(mtState& state, mtCovMat& cov, mtMeas& meas, double dt){
    meas.template get<mtMeas::_acc>() = state.template get<mtState::_gyb>();
    meas.template get<mtMeas::_gyr>() = state.template get<mtState::_acb>()-state.template get<mtState::_att>().inverseRotate(g_);
  }
  mtJacInput jacInput(const mtState& state, const mtMeas& meas, double dt) const{
    mtJacInput J;
    Eigen::Vector3d dOmega = -dt*(meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>());
    J.setIdentity(); // Handles clone and calibrations
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_pos>()) =
        (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega));
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_vel>()) =
        -dt*Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_gyb>()) =
        -dt*kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_pos>());
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_vel>()) =
        (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega));
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_acb>()) =
        dt*Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_gyb>()) =
        -dt*kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_vel>());
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_att>()) =
        dt*rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix().transpose()*kindr::linear_algebra::getSkewMatrixFromVector(g_);
    J.template block<3,3>(mtState::template getId<mtState::_acb>(),mtState::template getId<mtState::_acb>()) =
        Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_gyb>(),mtState::template getId<mtState::_gyb>()) =
        Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtState::template getId<mtState::_gyb>()) =
        dt*rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix()*Lmat(dOmega);
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtState::template getId<mtState::_att>()) =
        Eigen::Matrix3d::Identity();
    NormalVectorElement nIn, nOut;
    for(unsigned int i=0;i<mtState::nMax_;i++){
      nIn.n_ = state.template get<mtState::_nor>(i);
      J(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_dep>(i)) = 1.0;
      J.template block<1,3>(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_vel>()) =
          dt*nIn.get().transpose();
      J.template block<1,2>(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_nor>(i)) =
          dt*state.template get<mtState::_vel>().transpose()*nIn.getM();
      J.template block<2,2>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_nor>(i)) =
          Eigen::Matrix2d::Identity();
      J.template block<2,1>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_dep>(i)) =
          nIn.getM().transpose()*state.template get<mtState::_vel>()/std::pow(state.template get<mtState::_dep>(i),2)*dt;
      J.template block<2,3>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_vel>()) =
          nIn.getM().transpose()/state.template get<mtState::_dep>(i)*dt;
      J.template block<2,3>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_gyb>()) =
          nIn.getM().transpose()*kindr::linear_algebra::getSkewMatrixFromVector(nIn.get())*dt;
//      nIn.boxPlus(Eigen::Vector2d(nIn.getM().transpose()*(state.template get<mtState::_vel>()/state.template get<mtState::_dep>(i)
//          - output.template get<mtState::_aux>().MwIMest_.cross(nIn.get()))+noise.template get<mtNoise::_nor>(i)/sqrt(dt)),nOut);
//      output.template get<mtState::_nor>(i) = nOut.get();
    }
    return J;
  }
  mtJacNoise jacNoise(const mtState& state, const mtMeas& meas, double dt) const{
    mtJacNoise J;
    Eigen::Vector3d dOmega = -dt*(meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>());
    J.setZero();
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtNoise::template getId<mtNoise::_pos>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtNoise::template getId<mtNoise::_att>()) =
        kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_pos>())*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtNoise::template getId<mtNoise::_vel>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtNoise::template getId<mtNoise::_att>()) =
        kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_vel>())*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_acb>(),mtNoise::template getId<mtNoise::_acb>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_gyb>(),mtNoise::template getId<mtNoise::_gyb>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtNoise::template getId<mtNoise::_att>()) =
        -rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix()*Lmat(dOmega)*sqrt(dt);
    for(unsigned int i=0;i<mtState::nMax_;i++){
      J(mtState::template getId<mtState::_dep>(i),mtNoise::template getId<mtNoise::_dep>(i)) = sqrt(dt);
      J.template block<2,2>(mtState::template getId<mtState::_nor>(i),mtNoise::template getId<mtNoise::_nor>(i)) =
          Eigen::Matrix2d::Identity()*sqrt(dt);
    }
    return J;
  }
};

}

#endif /* IMUPREDICTION_HPP_ */
<commit_msg>worked on prediction<commit_after>/*
* Copyright (c) 2014, Autonomous Systems Lab
* 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 the Autonomous Systems Lab, ETH Zurich nor the
* names of its contributors 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 HOLDER 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.
*
*/

#ifndef IMUPREDICTION_HPP_
#define IMUPREDICTION_HPP_

#include "kindr/rotations/RotationEigen.hpp"
#include <Eigen/Dense>
#include "Prediction.hpp"
#include "State.hpp"
#include "FilterState.hpp"

namespace rot = kindr::rotations::eigen_impl;

namespace rovio {

using namespace LWF;

class PredictionMeas: public State<VectorElement<3>,VectorElement<3>>{
 public:
  static constexpr unsigned int _acc = 0;
  static constexpr unsigned int _gyr = _acc+1;
  PredictionMeas(){
    static_assert(_gyr+1==E_,"Error with indices");
  }
  ~PredictionMeas(){};
};

template<typename STATE>
class PredictionNoise: public State<TH_multiple_elements<VectorElement<3>,5>,
      ArrayElement<ScalarElement,STATE::nMax_>,
      ArrayElement<VectorElement<2>,STATE::nMax_>>{
 public:
  using State<TH_multiple_elements<VectorElement<3>,5>,
      ArrayElement<ScalarElement,STATE::nMax_>,
      ArrayElement<VectorElement<2>,STATE::nMax_>>::E_;
  static constexpr unsigned int _pos = 0;
  static constexpr unsigned int _vel = _pos+1;
  static constexpr unsigned int _acb = _vel+1;
  static constexpr unsigned int _gyb = _acb+1;
  static constexpr unsigned int _att = _gyb+1;
  static constexpr unsigned int _dep = _att+1;
  static constexpr unsigned int _nor = _dep+1;
  PredictionNoise(){
    static_assert(_nor+1==E_,"Error with indices");
  }
  ~PredictionNoise(){};
};

template<typename STATE>
class ImuPrediction: public Prediction<STATE,PredictionMeas,PredictionNoise<STATE>>{
 public:
  typedef Prediction<STATE,PredictionMeas,PredictionNoise<STATE>> Base;
  using Base::eval;
  using Base::prenoiP_;
  typedef typename Base::mtState mtState;
  typedef typename Base::mtMeas mtMeas;
  typedef typename Base::mtNoise mtNoise;
  typedef typename Base::mtJacInput mtJacInput;
  typedef typename Base::mtJacNoise mtJacNoise;
  typedef typename Base::mtCovMat mtCovMat;
  const Eigen::Vector3d g_;
  ImuPrediction():g_(0,0,-9.81){};
  ~ImuPrediction(){};
  mtState eval(const mtState& state, const mtMeas& meas, const mtNoise noise, double dt) const{
    mtState output;
    output.template get<mtState::_aux>().MwIMmeas_ = meas.template get<mtMeas::_gyr>();
    output.template get<mtState::_aux>().MwIMest_ = meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>();
    Eigen::Vector3d dOmega = -dt*(output.template get<mtState::_aux>().MwIMest_+noise.template get<mtNoise::_att>()/sqrt(dt));
    rot::RotationQuaternionPD dQ;
    dQ = dQ.exponentialMap(dOmega);
    output.template get<mtState::_att>() = state.template get<mtState::_att>()*dQ;
    output.template get<mtState::_pos>() = (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega))
        *state.template get<mtState::_pos>()-dt*(state.template get<mtState::_vel>()-noise.template get<mtNoise::_pos>()/sqrt(dt));
    output.template get<mtState::_vel>() = (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega))
        *state.template get<mtState::_vel>()-dt*(meas.template get<mtMeas::_acc>()-state.template get<mtState::_acb>()+state.template get<mtState::_att>().inverseRotate(g_)-noise.template get<mtNoise::_vel>()/sqrt(dt));
    output.template get<mtState::_acb>() = state.template get<mtState::_acb>()+noise.template get<mtNoise::_acb>()*sqrt(dt);
    output.template get<mtState::_gyb>() = state.template get<mtState::_gyb>()+noise.template get<mtNoise::_gyb>()*sqrt(dt);
    NormalVectorElement nIn, nOut;
    for(unsigned int i=0;i<mtState::nMax_;i++){
      nIn.n_ = state.template get<mtState::_nor>(i);
      output.template get<mtState::_dep>(i) = state.template get<mtState::_dep>(i)+dt*(nIn.get().transpose()*state.template get<mtState::_vel>()
          + noise.template get<mtNoise::_dep>(i)/sqrt(dt));
      nIn.boxPlus(Eigen::Vector2d(nIn.getM().transpose()*(
              dt*state.template get<mtState::_vel>()/state.template get<mtState::_dep>(i)
              + dOmega.cross(nIn.get()))
              + noise.template get<mtNoise::_nor>(i)*sqrt(dt)
          ),nOut);
      output.template get<mtState::_nor>(i) = nOut.get();
    }
    output.template get<mtState::_aux>().wMeasCov_ = prenoiP_.template block<3,3>(mtNoise::template getId<mtNoise::_att>(),mtNoise::template getId<mtNoise::_att>())/dt;
    output.template get<mtState::_aux>().img_ = state.template get<mtState::_aux>().img_;
    output.fix();
    return output;
  }
  void noMeasCase(mtState& state, mtCovMat& cov, mtMeas& meas, double dt){
    meas.template get<mtMeas::_acc>() = state.template get<mtState::_gyb>();
    meas.template get<mtMeas::_gyr>() = state.template get<mtState::_acb>()-state.template get<mtState::_att>().inverseRotate(g_);
  }
  mtJacInput jacInput(const mtState& state, const mtMeas& meas, double dt) const{
    mtJacInput J;
    Eigen::Vector3d dOmega = -dt*(meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>());
    J.setIdentity(); // Handles clone and calibrations
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_pos>()) =
        (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega));
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_vel>()) =
        -dt*Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtState::template getId<mtState::_gyb>()) =
        -dt*kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_pos>());
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_vel>()) =
        (Eigen::Matrix3d::Identity()+kindr::linear_algebra::getSkewMatrixFromVector(dOmega));
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_acb>()) =
        dt*Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_gyb>()) =
        -dt*kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_vel>());
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtState::template getId<mtState::_att>()) =
        dt*rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix().transpose()*kindr::linear_algebra::getSkewMatrixFromVector(g_);
    J.template block<3,3>(mtState::template getId<mtState::_acb>(),mtState::template getId<mtState::_acb>()) =
        Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_gyb>(),mtState::template getId<mtState::_gyb>()) =
        Eigen::Matrix3d::Identity();
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtState::template getId<mtState::_gyb>()) =
        dt*rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix()*Lmat(dOmega);
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtState::template getId<mtState::_att>()) =
        Eigen::Matrix3d::Identity();
    NormalVectorElement nIn, nOut;
    for(unsigned int i=0;i<mtState::nMax_;i++){
      nIn.n_ = state.template get<mtState::_nor>(i);
      nIn.boxPlus(Eigen::Vector2d(nIn.getM().transpose()*(
              dt*state.template get<mtState::_vel>()/state.template get<mtState::_dep>(i)
              + dOmega.cross(nIn.get())
          )),nOut);
      J(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_dep>(i)) = 1.0;
      J.template block<1,3>(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_vel>()) =
          dt*nIn.get().transpose();
      J.template block<1,2>(mtState::template getId<mtState::_dep>(i),mtState::template getId<mtState::_nor>(i)) =
          dt*state.template get<mtState::_vel>().transpose()*nIn.getM();
      J.template block<2,2>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_nor>(i)) =
          nIn.getM().transpose()*kindr::linear_algebra::getSkewMatrixFromVector(dOmega)*nIn.getM()
          + nOut.getM().transpose()*(Eigen::Matrix3d::Identity())*nIn.getM();
      J.template block<2,1>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_dep>(i)) =
          -nIn.getM().transpose()*state.template get<mtState::_vel>()/std::pow(state.template get<mtState::_dep>(i),2)*dt;
      J.template block<2,3>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_vel>()) =
          nIn.getM().transpose()*dt/state.template get<mtState::_dep>(i);
      J.template block<2,3>(mtState::template getId<mtState::_nor>(i),mtState::template getId<mtState::_gyb>()) =
          -nIn.getM().transpose()*kindr::linear_algebra::getSkewMatrixFromVector(nIn.get())*dt;
    }
    return J;
  }
  mtJacNoise jacNoise(const mtState& state, const mtMeas& meas, double dt) const{
    mtJacNoise J;
    Eigen::Vector3d dOmega = -dt*(meas.template get<mtMeas::_gyr>()-state.template get<mtState::_gyb>());
    J.setZero();
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtNoise::template getId<mtNoise::_pos>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_pos>(),mtNoise::template getId<mtNoise::_att>()) =
        kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_pos>())*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtNoise::template getId<mtNoise::_vel>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_vel>(),mtNoise::template getId<mtNoise::_att>()) =
        kindr::linear_algebra::getSkewMatrixFromVector(state.template get<mtState::_vel>())*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_acb>(),mtNoise::template getId<mtNoise::_acb>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_gyb>(),mtNoise::template getId<mtNoise::_gyb>()) = Eigen::Matrix3d::Identity()*sqrt(dt);
    J.template block<3,3>(mtState::template getId<mtState::_att>(),mtNoise::template getId<mtNoise::_att>()) =
        -rot::RotationMatrixPD(state.template get<mtState::_att>()).matrix()*Lmat(dOmega)*sqrt(dt);
    for(unsigned int i=0;i<mtState::nMax_;i++){
      J(mtState::template getId<mtState::_dep>(i),mtNoise::template getId<mtNoise::_dep>(i)) = sqrt(dt);
      J.template block<2,2>(mtState::template getId<mtState::_nor>(i),mtNoise::template getId<mtNoise::_nor>(i)) =
          Eigen::Matrix2d::Identity()*sqrt(dt);
    }
    return J;
  }
};

}

#endif /* IMUPREDICTION_HPP_ */
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstdio>

#include <string>
#include <vector>
#include <cstring>

#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>

#include "utils.hpp"  //revoke_root for the drivers
#include "config.hpp" //config for the drivers

namespace asgard {

struct driver_connector {
    //Buffer
    char write_buffer[buffer_size];
    char receive_buffer[buffer_size];

    // The socket file descriptor
    int socket_fd;

    // The socket addresses
    struct sockaddr_un client_address;
    struct sockaddr_un server_address;
};

inline bool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path) {
    // Open the socket
    driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (driver.socket_fd < 0) {
        std::cerr << "asgard:driversystem: socket() failed" << std::endl;
        return false;
    }

    // Init the client address
    memset(&driver.client_address, 0, sizeof(struct sockaddr_un));
    driver.client_address.sun_family = AF_UNIX;
    snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);

    // Unlink the client socket
    unlink(client_socket_path);

    // Bind to client socket
    if (bind(driver.socket_fd, (const struct sockaddr*)&driver.client_address, sizeof(struct sockaddr_un)) < 0) {
        std::cerr << "asgard:driver: bind() failed" << std::endl;
        return false;
    }

    // Init the server address
    memset(&driver.server_address, 0, sizeof(struct sockaddr_un));
    driver.server_address.sun_family = AF_UNIX;
    snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);

    return true;
}

inline int register_source(driver_connector& driver, const std::string& source_name) {
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the source
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received                   = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr*)&driver.server_address, &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto source_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote source: " << source_id << std::endl;

    return source_id;
}

inline int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name) {
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the sensor
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received                   = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr*)&driver.server_address, &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto sensor_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;

    return sensor_id;
}

inline int register_action(driver_connector& driver, int source_id, const std::string& type, const std::string& name) {
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the action
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_ACTION %d %s %s", source_id, type.c_str(), name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received                   = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr*)&driver.server_address, &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto action_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote action(" << name << "):" << action_id << std::endl;

    return action_id;
}

inline int register_actuator(driver_connector& driver, int source_id, const std::string& name) {
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the actuator
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received                   = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr*)&driver.server_address, &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto actuator_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote actuator(" << name << "):" << actuator_id << std::endl;

    return actuator_id;
}

inline void send_data(driver_connector& driver, int source_id, int sensor_id, double value) {
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
}

inline void send_event(driver_connector& driver, int source_id, int actuator_id, std::string value) {
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "EVENT %d %d %s", source_id, actuator_id, value.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
}

inline void unregister_sensor(driver_connector& driver, int source_id, int sensor_id) {
    // Unregister the sensor, if necessary
    if (sensor_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
    }
}

inline void unregister_action(driver_connector& driver, int source_id, int action_id) {
    // Unregister the action, if necessary
    if (action_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_ACTION %d %d", source_id, action_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
    }
}

inline void unregister_actuator(driver_connector& driver, int source_id, int actuator_id) {
    // Unregister the actuator, if necessary
    if (actuator_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, actuator_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
    }
}

inline void unregister_source(driver_connector& driver, int source_id) {
    // Unregister the source, if necessary
    if (source_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr*)&driver.server_address, sizeof(struct sockaddr_un));
    }
}

} //end of namespace asgard
<commit_msg>Handle multiple connections<commit_after>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstdio>

#include <string>
#include <vector>
#include <cstring>

#include <arpa/inet.h> //inet_addr
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>

#include "utils.hpp"  //revoke_root for the drivers
#include "config.hpp" //config for the drivers

namespace asgard {

struct driver_connector {
    //Buffer
    char write_buffer[buffer_size];
    char receive_buffer[buffer_size];

    // The socket file descriptor
    int socket_fd;
};

inline bool open_driver_connection(driver_connector& driver, const char* server_socket_addr, int server_socket_port) {
    // Open the socket
    driver.socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (driver.socket_fd < 0) {
        std::cerr << "asgard:driversystem: socket() failed" << std::endl;
        return false;
    }

    struct sockaddr_in server;

    server.sin_addr.s_addr = inet_addr(server_socket_addr);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_socket_port);

    //Connect to remote server
    if (connect(driver.socket_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
        std::perror("connect failed. Error");
        return false;
    }
    std::cout << "Connected\n" << std::endl;

    return true;
}

inline int register_source(driver_connector& driver, const std::string& source_name) {
    // Register the source
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
    send(driver.socket_fd, driver.write_buffer, nbytes, 0);

    auto bytes_received                   = recv(driver.socket_fd, driver.receive_buffer, buffer_size, 0);
    driver.receive_buffer[bytes_received] = '\0';

    auto source_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote source: " << source_id << std::endl;

    return source_id;
}

inline int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name) {
    // Register the sensor
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
    send(driver.socket_fd, driver.write_buffer, nbytes, 0);

    auto bytes_received                   = recv(driver.socket_fd, driver.receive_buffer, buffer_size, 0);
    driver.receive_buffer[bytes_received] = '\0';

    auto sensor_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;

    return sensor_id;
}

inline int register_actuator(driver_connector& driver, int source_id, const std::string& name) {

    // Register the actuator
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, name.c_str());
    send(driver.socket_fd, driver.write_buffer, nbytes, 0);

    auto bytes_received                   = recv(driver.socket_fd, driver.receive_buffer, buffer_size, 0);
    driver.receive_buffer[bytes_received] = '\0';

    auto actuator_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote actuator(" << name << "):" << actuator_id << std::endl;

    return actuator_id;
}

inline void send_data(driver_connector& driver, int source_id, int sensor_id, double value) {
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
    send(driver.socket_fd, driver.write_buffer, nbytes, 0);
}

inline void send_event(driver_connector& driver, int source_id, int actuator_id, std::string value) {
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "EVENT %d %d %s", source_id, actuator_id, value.c_str());
    send(driver.socket_fd, driver.write_buffer, nbytes, 0);
}

inline void unregister_sensor(driver_connector& driver, int source_id, int sensor_id) {
    // Unregister the sensor, if necessary
    if (sensor_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
        send(driver.socket_fd, driver.write_buffer, nbytes, 0);
    }
}

inline void unregister_actuator(driver_connector& driver, int source_id, int actuator_id) {
    // Unregister the actuator, if necessary
    if (actuator_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, actuator_id);
        send(driver.socket_fd, driver.write_buffer, nbytes, 0);
    }
}

inline void unregister_source(driver_connector& driver, int source_id) {
    // Unregister the source, if necessary
    if (source_id >= 0) {
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
        send(driver.socket_fd, driver.write_buffer, nbytes, 0);
    }
}

} //end of namespace asgard
<|endoftext|>


<commit_before>void AddTask_GammaConvCalo_pPb(  Int_t trainConfig = 1,  //change different set of cuts
                              Bool_t isMC   = kFALSE, //run MC
                              Int_t enableQAMesonTask = 0, //enable QA in AliAnalysisTaskGammaConvV1
                              Int_t enableQAPhotonTask = 0, // enable additional QA task
                              TString fileNameInputForWeighting = "MCSpectraInput.root", // path to file for weigting input
                              Int_t doWeightingPart = 0,  //enable Weighting
                              TString generatorName = "DPMJET",
                              TString cutnumberAODBranch = "8000000060084000001500000" // cutnumber for AOD branch
							) {

	// ================= Load Librariers =================================
	gSystem->Load("libCore.so");
	gSystem->Load("libTree.so");
	gSystem->Load("libGeom.so");
	gSystem->Load("libVMC.so");
	gSystem->Load("libPhysics.so");
	gSystem->Load("libMinuit");
	gSystem->Load("libSTEERBase");
	gSystem->Load("libESD");
	gSystem->Load("libAOD");
	gSystem->Load("libANALYSIS");
	gSystem->Load("libANALYSISalice");
	gSystem->Load("libPWGGAGammaConv.so");
	gSystem->Load("libCDB.so");
	gSystem->Load("libSTEER.so");
	gSystem->Load("libSTEERBase.so");
	gSystem->Load("libTENDER.so");
	gSystem->Load("libTENDERSupplies.so");

	Int_t isHeavyIon = 2;

	// ================== GetAnalysisManager ===============================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
		return ;
	}

	// ================== GetInputEventHandler =============================
	AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

	//========= Add PID Reponse to ANALYSIS manager ====
	if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
		gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
		AddTaskPIDResponse(isMC);
	}

	Printf("here \n");

	//=========  Set Cutnumber for V0Reader ================================
	TString cutnumberPhoton = "060084001001500000000";
	TString cutnumberEvent = "8000000";
	Bool_t doEtaShift = kFALSE;
	AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

	//========= Add V0 Reader to  ANALYSIS manager if not yet existent =====
	if( !(AliV0ReaderV1*)mgr->GetTask("V0ReaderV1") ){
		AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1("V0ReaderV1");

		fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
		fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
		fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);

		if (!mgr) {
			Error("AddTask_V0ReaderV1", "No analysis manager found.");
			return;
		}

		AliConvEventCuts *fEventCuts=NULL;
		if(cutnumberEvent!=""){
			fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
			fEventCuts->SetPreSelectionCutFlag(kTRUE);
			if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
				fEventCuts->DoEtaShift(doEtaShift);
				fV0ReaderV1->SetEventCuts(fEventCuts);
				fEventCuts->SetFillCutHistograms("",kTRUE);
			}
		}

		// Set AnalysisCut Number
		AliConversionPhotonCuts *fCuts=NULL;
		if(cutnumberPhoton!=""){
			fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
			fCuts->SetPreSelectionCutFlag(kTRUE);
			fCuts->SetIsHeavyIon(isHeavyIon);
			if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
				fV0ReaderV1->SetConversionCuts(fCuts);
				fCuts->SetFillCutHistograms("",kTRUE);
			}
		}
		if(inputHandler->IsA()==AliAODInputHandler::Class()){
		// AOD mode
			fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
		}
		fV0ReaderV1->Init();

		AliLog::SetGlobalLogLevel(AliLog::kFatal);

		//connect input V0Reader
		mgr->AddTask(fV0ReaderV1);
		mgr->ConnectInput(fV0ReaderV1,0,cinput);

	}

	//================================================
	//========= Add task to the ANALYSIS manager =====
	//================================================
	AliAnalysisTaskGammaConvCalo *task=NULL;
	task= new AliAnalysisTaskGammaConvCalo(Form("GammaConvCalo_%i",trainConfig));
	task->SetIsHeavyIon(isHeavyIon);
	task->SetIsMC(isMC);
	// Cut Numbers to use in Analysis
	Int_t numberOfCuts = 2;

	TString *eventCutArray = new TString[numberOfCuts];
	TString *photonCutArray = new TString[numberOfCuts];
	TString *clusterCutArray = new TString[numberOfCuts];
	TString *mesonCutArray = new TString[numberOfCuts];

	// cluster cuts
	// 0 "ClusterType",  1 "EtaMin", 2 "EtaMax", 3 "PhiMin", 4 "PhiMax", 5 "DistanceToBadChannel", 6 "Timing", 7 "TrackMatching", 8 "ExoticCell",
	// 9 "MinEnergy", 10 "MinNCells", 11 "MinM02", 12 "MaxM02", 13 "MinM20", 14 "MaxM20", 15 "MaximumDispersion", 16 "NLM"

	if (trainConfig == 1){
		eventCutArray[ 0] = "8000001"; photonCutArray[ 0] = "002092970028250400000"; clusterCutArray[0] = "10000040022030000"; mesonCutArray[0] = "01525065000000"; //standart cut, kINT7 // EMCAL clusters
		eventCutArray[ 1] = "8005201"; photonCutArray[ 1] = "002092970028250400000"; clusterCutArray[1] = "10000040022030000"; mesonCutArray[1] = "01525065000000"; //standard cut, kEMC7 // EMCAL clusters
	} else if (trainConfig == 2) {
		eventCutArray[ 0] = "8000001"; photonCutArray[ 0] = "002092970028250400000"; clusterCutArray[0] = "20000030022000000"; mesonCutArray[0] = "01525065000000"; //standart cut, kINT7 // PHOS clusters
		eventCutArray[ 1] = "8006201"; photonCutArray[ 1] = "002092970028250400000"; clusterCutArray[1] = "20000030022000000"; mesonCutArray[1] = "01525065000000"; //standard cut, kPHI7	// PHOS clusters
	} else {
		Error(Form("GammaConvCalo_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
		return;
	}

	TList *EventCutList = new TList();
	TList *ConvCutList = new TList();
	TList *ClusterCutList = new TList();
	TList *MesonCutList = new TList();

	TList *HeaderList = new TList();
	if (doWeightingPart==1) {
		TObjString *Header1 = new TObjString("pi0_1");
		HeaderList->Add(Header1);
	}
	if (doWeightingPart==2){
		TObjString *Header3 = new TObjString("eta_2");
		HeaderList->Add(Header3);
	}
	if (doWeightingPart==3) {
		TObjString *Header1 = new TObjString("pi0_1");
		HeaderList->Add(Header1);
		TObjString *Header3 = new TObjString("eta_2");
		HeaderList->Add(Header3);
	}

	EventCutList->SetOwner(kTRUE);
	AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts];
	ConvCutList->SetOwner(kTRUE);
	AliConversionPhotonCuts **analysisCuts = new AliConversionPhotonCuts*[numberOfCuts];
	ClusterCutList->SetOwner(kTRUE);
	AliCaloPhotonCuts **analysisClusterCuts = new AliCaloPhotonCuts*[numberOfCuts];
	MesonCutList->SetOwner(kTRUE);
	AliConversionMesonCuts **analysisMesonCuts = new AliConversionMesonCuts*[numberOfCuts];

	for(Int_t i = 0; i<numberOfCuts; i++){
		analysisEventCuts[i] = new AliConvEventCuts();
		analysisEventCuts[i]->InitializeCutsFromCutString(eventCutArray[i].Data());
		EventCutList->Add(analysisEventCuts[i]);
		analysisEventCuts[i]->SetFillCutHistograms("",kFALSE);

		analysisCuts[i] = new AliConversionPhotonCuts();
		analysisCuts[i]->InitializeCutsFromCutString(photonCutArray[i].Data());
		analysisCuts[i]->SetIsHeavyIon(isHeavyIon);
		ConvCutList->Add(analysisCuts[i]);
		analysisCuts[i]->SetFillCutHistograms("",kFALSE);

		analysisClusterCuts[i] = new AliCaloPhotonCuts();
		analysisClusterCuts[i]->InitializeCutsFromCutString(clusterCutArray[i].Data());
		ClusterCutList->Add(analysisClusterCuts[i]);
		analysisClusterCuts[i]->SetFillCutHistograms("");

		analysisMesonCuts[i] = new AliConversionMesonCuts();
		analysisMesonCuts[i]->InitializeCutsFromCutString(mesonCutArray[i].Data());
		MesonCutList->Add(analysisMesonCuts[i]);
		analysisMesonCuts[i]->SetFillCutHistograms("");
		analysisEventCuts[i]->SetAcceptedHeader(HeaderList);
	}

	task->SetEventCutList(numberOfCuts,EventCutList);
	task->SetConversionCutList(numberOfCuts,ConvCutList);
	task->SetCaloCutList(numberOfCuts,ClusterCutList);
	task->SetMesonCutList(numberOfCuts,MesonCutList);
	task->SetMoveParticleAccordingToVertex(kTRUE);
	task->SetDoMesonAnalysis(kTRUE);
	task->SetDoMesonQA(enableQAMesonTask); //Attention new switch for Pi0 QA
	task->SetDoPhotonQA(enableQAPhotonTask);  //Attention new switch small for Photon QA
	task->SetDoClusterQA(1);  //Attention new switch small for Cluster QA

	//connect containers
	AliAnalysisDataContainer *coutput =
		mgr->CreateContainer(Form("GammaConvCalo_%i",trainConfig), TList::Class(),
							AliAnalysisManager::kOutputContainer,Form("GammaConvCalo_%i.root",trainConfig));

	mgr->AddTask(task);
	mgr->ConnectInput(task,0,cinput);
	mgr->ConnectOutput(task,1,coutput);

	return;

}
<commit_msg>- added cuts<commit_after>void AddTask_GammaConvCalo_pPb(  Int_t trainConfig = 1,  //change different set of cuts
                              Bool_t isMC   = kFALSE, //run MC
                              Int_t enableQAMesonTask = 0, //enable QA in AliAnalysisTaskGammaConvV1
                              Int_t enableQAPhotonTask = 0, // enable additional QA task
                              TString fileNameInputForWeighting = "MCSpectraInput.root", // path to file for weigting input
                              Int_t doWeightingPart = 0,  //enable Weighting
                              TString generatorName = "DPMJET",
                              TString cutnumberAODBranch = "8000000060084000001500000" // cutnumber for AOD branch
							) {

	// ================= Load Librariers =================================
	gSystem->Load("libCore.so");
	gSystem->Load("libTree.so");
	gSystem->Load("libGeom.so");
	gSystem->Load("libVMC.so");
	gSystem->Load("libPhysics.so");
	gSystem->Load("libMinuit");
	gSystem->Load("libSTEERBase");
	gSystem->Load("libESD");
	gSystem->Load("libAOD");
	gSystem->Load("libANALYSIS");
	gSystem->Load("libANALYSISalice");
	gSystem->Load("libPWGGAGammaConv.so");
	gSystem->Load("libCDB.so");
	gSystem->Load("libSTEER.so");
	gSystem->Load("libSTEERBase.so");
	gSystem->Load("libTENDER.so");
	gSystem->Load("libTENDERSupplies.so");

	Int_t isHeavyIon = 2;

	// ================== GetAnalysisManager ===============================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
		return ;
	}

	// ================== GetInputEventHandler =============================
	AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

	//========= Add PID Reponse to ANALYSIS manager ====
	if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
		gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
		AddTaskPIDResponse(isMC);
	}

	Printf("here \n");

	//=========  Set Cutnumber for V0Reader ================================
	TString cutnumberPhoton = "060084001001500000000";
	TString cutnumberEvent = "8000000";
	Bool_t doEtaShift = kFALSE;
	AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

	//========= Add V0 Reader to  ANALYSIS manager if not yet existent =====
	if( !(AliV0ReaderV1*)mgr->GetTask("V0ReaderV1") ){
		AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1("V0ReaderV1");

		fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
		fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
		fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);

		if (!mgr) {
			Error("AddTask_V0ReaderV1", "No analysis manager found.");
			return;
		}

		AliConvEventCuts *fEventCuts=NULL;
		if(cutnumberEvent!=""){
			fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
			fEventCuts->SetPreSelectionCutFlag(kTRUE);
			if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
				fEventCuts->DoEtaShift(doEtaShift);
				fV0ReaderV1->SetEventCuts(fEventCuts);
				fEventCuts->SetFillCutHistograms("",kTRUE);
			}
		}

		// Set AnalysisCut Number
		AliConversionPhotonCuts *fCuts=NULL;
		if(cutnumberPhoton!=""){
			fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
			fCuts->SetPreSelectionCutFlag(kTRUE);
			fCuts->SetIsHeavyIon(isHeavyIon);
			if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
				fV0ReaderV1->SetConversionCuts(fCuts);
				fCuts->SetFillCutHistograms("",kTRUE);
			}
		}
		if(inputHandler->IsA()==AliAODInputHandler::Class()){
		// AOD mode
			fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
		}
		fV0ReaderV1->Init();

		AliLog::SetGlobalLogLevel(AliLog::kFatal);

		//connect input V0Reader
		mgr->AddTask(fV0ReaderV1);
		mgr->ConnectInput(fV0ReaderV1,0,cinput);

	}

	//================================================
	//========= Add task to the ANALYSIS manager =====
	//================================================
	AliAnalysisTaskGammaConvCalo *task=NULL;
	task= new AliAnalysisTaskGammaConvCalo(Form("GammaConvCalo_%i",trainConfig));
	task->SetIsHeavyIon(isHeavyIon);
	task->SetIsMC(isMC);
	// Cut Numbers to use in Analysis
	Int_t numberOfCuts = 2;
	if (trainConfig==3){ numberOfCuts =6;}

	TString *eventCutArray = new TString[numberOfCuts];
	TString *photonCutArray = new TString[numberOfCuts];
	TString *clusterCutArray = new TString[numberOfCuts];
	TString *mesonCutArray = new TString[numberOfCuts];

	// cluster cuts
	// 0 "ClusterType",  1 "EtaMin", 2 "EtaMax", 3 "PhiMin", 4 "PhiMax", 5 "DistanceToBadChannel", 6 "Timing", 7 "TrackMatching", 8 "ExoticCell",
	// 9 "MinEnergy", 10 "MinNCells", 11 "MinM02", 12 "MaxM02", 13 "MinM20", 14 "MaxM20", 15 "MaximumDispersion", 16 "NLM"

	if (trainConfig == 1){
		eventCutArray[ 0] = "8000001"; photonCutArray[ 0] = "002092970028250400000"; clusterCutArray[0] = "10000040022030000"; mesonCutArray[0] = "01525065000000"; //standart cut, kINT7 // EMCAL clusters
		eventCutArray[ 1] = "8005201"; photonCutArray[ 1] = "002092970028250400000"; clusterCutArray[1] = "10000040022030000"; mesonCutArray[1] = "01525065000000"; //standard cut, kEMC7 // EMCAL clusters
	} else if (trainConfig == 2) {
		eventCutArray[ 0] = "8000001"; photonCutArray[ 0] = "002092970028250400000"; clusterCutArray[0] = "20000030022000000"; mesonCutArray[0] = "01525065000000"; //standart cut, kINT7 // PHOS clusters
		eventCutArray[ 1] = "8006201"; photonCutArray[ 1] = "002092970028250400000"; clusterCutArray[1] = "20000030022000000"; mesonCutArray[1] = "01525065000000"; //standard cut, kPHI7	// PHOS clusters
	} else if (trainConfig == 3){
		eventCutArray[ 0] = "8008101"; photonCutArray[ 0] = "002092970028250400000"; clusterCutArray[0] = "10000040022030000"; mesonCutArray[0] = "01525065000000"; //standart cut, kEMCEGA based on INT7 // EMCAL clusters
		eventCutArray[ 1] = "8008301"; photonCutArray[ 1] = "002092970028250400000"; clusterCutArray[1] = "10000040022030000"; mesonCutArray[1] = "01525065000000"; //standard cut, kEMCEG1 based on INT7 // EMCAL clusters
		eventCutArray[ 2] = "8008501"; photonCutArray[ 2] = "002092970028250400000"; clusterCutArray[2] = "10000040022030000"; mesonCutArray[2] = "01525065000000"; //standard cut, kEMCEG2 based on INT7 // EMCAL clusters
		eventCutArray[ 3] = "8009101"; photonCutArray[ 3] = "002092970028250400000"; clusterCutArray[3] = "10000040022030000"; mesonCutArray[3] = "01525065000000"; //standard cut, kEMCEJE based on INT7 // EMCAL clusters
		eventCutArray[ 4] = "8009301"; photonCutArray[ 4] = "002092970028250400000"; clusterCutArray[4] = "10000040022030000"; mesonCutArray[4] = "01525065000000"; //standard cut, kEMCEJ1 based on INT7 // EMCAL clusters
		eventCutArray[ 5] = "8009501"; photonCutArray[ 5] = "002092970028250400000"; clusterCutArray[5] = "10000040022030000"; mesonCutArray[5] = "01525065000000"; //standard cut, kEMCEG2 based on INT7 // EMCAL clusters
	} else {
		Error(Form("GammaConvCalo_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
		return;
	}

	TList *EventCutList = new TList();
	TList *ConvCutList = new TList();
	TList *ClusterCutList = new TList();
	TList *MesonCutList = new TList();

	TList *HeaderList = new TList();
	if (doWeightingPart==1) {
		TObjString *Header1 = new TObjString("pi0_1");
		HeaderList->Add(Header1);
	}
	if (doWeightingPart==2){
		TObjString *Header3 = new TObjString("eta_2");
		HeaderList->Add(Header3);
	}
	if (doWeightingPart==3) {
		TObjString *Header1 = new TObjString("pi0_1");
		HeaderList->Add(Header1);
		TObjString *Header3 = new TObjString("eta_2");
		HeaderList->Add(Header3);
	}

	EventCutList->SetOwner(kTRUE);
	AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts];
	ConvCutList->SetOwner(kTRUE);
	AliConversionPhotonCuts **analysisCuts = new AliConversionPhotonCuts*[numberOfCuts];
	ClusterCutList->SetOwner(kTRUE);
	AliCaloPhotonCuts **analysisClusterCuts = new AliCaloPhotonCuts*[numberOfCuts];
	MesonCutList->SetOwner(kTRUE);
	AliConversionMesonCuts **analysisMesonCuts = new AliConversionMesonCuts*[numberOfCuts];

	for(Int_t i = 0; i<numberOfCuts; i++){
		analysisEventCuts[i] = new AliConvEventCuts();
		analysisEventCuts[i]->InitializeCutsFromCutString(eventCutArray[i].Data());
		EventCutList->Add(analysisEventCuts[i]);
		analysisEventCuts[i]->SetFillCutHistograms("",kFALSE);

		analysisCuts[i] = new AliConversionPhotonCuts();
		analysisCuts[i]->InitializeCutsFromCutString(photonCutArray[i].Data());
		analysisCuts[i]->SetIsHeavyIon(isHeavyIon);
		ConvCutList->Add(analysisCuts[i]);
		analysisCuts[i]->SetFillCutHistograms("",kFALSE);

		analysisClusterCuts[i] = new AliCaloPhotonCuts();
		analysisClusterCuts[i]->InitializeCutsFromCutString(clusterCutArray[i].Data());
		ClusterCutList->Add(analysisClusterCuts[i]);
		analysisClusterCuts[i]->SetFillCutHistograms("");

		analysisMesonCuts[i] = new AliConversionMesonCuts();
		analysisMesonCuts[i]->InitializeCutsFromCutString(mesonCutArray[i].Data());
		MesonCutList->Add(analysisMesonCuts[i]);
		analysisMesonCuts[i]->SetFillCutHistograms("");
		analysisEventCuts[i]->SetAcceptedHeader(HeaderList);
	}

	task->SetEventCutList(numberOfCuts,EventCutList);
	task->SetConversionCutList(numberOfCuts,ConvCutList);
	task->SetCaloCutList(numberOfCuts,ClusterCutList);
	task->SetMesonCutList(numberOfCuts,MesonCutList);
	task->SetMoveParticleAccordingToVertex(kTRUE);
	task->SetDoMesonAnalysis(kTRUE);
	task->SetDoMesonQA(enableQAMesonTask); //Attention new switch for Pi0 QA
	task->SetDoPhotonQA(enableQAPhotonTask);  //Attention new switch small for Photon QA
	task->SetDoClusterQA(1);  //Attention new switch small for Cluster QA

	//connect containers
	AliAnalysisDataContainer *coutput =
		mgr->CreateContainer(Form("GammaConvCalo_%i",trainConfig), TList::Class(),
							AliAnalysisManager::kOutputContainer,Form("GammaConvCalo_%i.root",trainConfig));

	mgr->AddTask(task);
	mgr->ConnectInput(task,0,cinput);
	mgr->ConnectOutput(task,1,coutput);

	return;

}
<|endoftext|>


<commit_before>enum AlgoType {kKT, kANTIKT};
enum JetType  {kFULLJETS, kCHARGEDJETS, kNEUTRALJETS};

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char * njetsBase,
						     const char * njetsTag,
						     const Double_t R,
						     const char * nrhoBase,
						     const char * nrhoTag,
						     const char * ntracks,
						     const char * nclusters,
						     const char *type,
						     const char *CentEst,
						     Int_t       pSel,
						     TString     trigClass      = "",
						     TString     kEmcalTriggers = "");

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(TString     kTracksName         = "PicoTracks",
						     TString     kClusName           = "caloClustersCorr",
						     Double_t    R                   = 0.4,
						     Double_t    ptminTrack          = 0.15,
						     Double_t    etminClus           = 0.3,
						     Double_t    ptminTag            = 4.,
						     Int_t       rhoType             = 1,
						     const char *type                = "EMCAL",
						     const char *CentEst             = "V0M",
						     Int_t       pSel                = AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB,
						     TString     trigClass           = "",
						     TString     kEmcalTriggers      = "",
						     TString     kPeriod             = "LHC11h",
						     Int_t       recombScheme        = 0,
						     TString     tag1                = "Jet",
						     TString     tag2                = ""
						     ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskEmcalJetTagger","No analysis manager found.");
      return 0;
    }

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

  // #### Add necessary jet finder tasks
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");

  if(tag2.IsNull()) tag2=tag1;

  AliEmcalJetTask* jetFinderTaskBase = 0x0;
  if (strcmp(type,"TPC")==0)
    jetFinderTaskBase = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus,0.005,recombScheme,tag1.Data(),ptminTrack,kFALSE,kFALSE);
  else if (strcmp(type,"EMCAL")==0)
    jetFinderTaskBase = AddTaskEmcalJet(kTracksName, kClusName, kANTIKT, R, kFULLJETS, ptminTrack, etminClus,0.005,recombScheme,tag1.Data(),ptminTrack,kFALSE,kFALSE);
  jetFinderTaskBase->SelectCollisionCandidates(AliVEvent::kAny);

  AliEmcalJetTask* jetFinderTaskTag  = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kCHARGEDJETS, ptminTag, etminClus,0.005,recombScheme,tag2.Data(),ptminTag,kFALSE,kFALSE);
  jetFinderTaskTag->SelectCollisionCandidates(AliVEvent::kAny);

  if(tag1.EqualTo("JetPythia"))
    jetFinderTaskBase->SetTrackLabelRange(99999,9999999);
  //    jetFinderTaskBase->SelectConstituents(TObject::kBitMask, 0);
  if(tag2.EqualTo("JetPythia"))
    jetFinderTaskTag->SetTrackLabelRange(99999,9999999);
  //    jetFinderTaskTag->SelectConstituents(TObject::kBitMask, 0);

  TString strJetsBase = jetFinderTaskBase->GetName();
  TString strJetsTag  = jetFinderTaskTag->GetName();

  AliAnalysisTaskRhoBase *rhoTaskBase;
  AliAnalysisTaskRhoBase *rhoTaskTag;
  TString rhoNameBase = "";
  TString rhoNameTag  = "";
  if(rhoType==1) {
    rhoTaskBase = AttachRhoTaskTagger(kPeriod,kTracksName,kClusName,R,ptminTrack,etminClus,recombScheme,tag1);
    if(rhoTaskBase) {
      rhoTaskBase->SetCentralityEstimator(CentEst);
      rhoTaskBase->SelectCollisionCandidates(AliVEvent::kAny);
      if (strcmp(type,"TPC")==0)
	rhoNameBase = rhoTaskBase->GetOutRhoName();
      if (strcmp(type,"EMCAL")==0)
	rhoNameBase = rhoTaskBase->GetOutRhoScaledName();
    }
    if(rhoTaskTag) {
      rhoTaskTag = AttachRhoTaskTagger(kPeriod,kTracksName,kClusName,R,ptminTag,0.,recombScheme,tag2);
      rhoTaskTag->SetCentralityEstimator(CentEst);
      rhoTaskTag->SelectCollisionCandidates(AliVEvent::kAny);
      rhoNameTag  = rhoTaskTag->GetOutRhoName();
    }
  }

  //Configure jet tagger task
  AliAnalysisTaskEmcalJetTagger *task = AddTaskEmcalJetTagger(jetFinderTaskBase->GetName(),
							      jetFinderTaskTag->GetName(),
							      R,
							      rhoNameBase,
							      rhoNameTag,
							      kTracksName.Data(),
							      kClusName.Data(),
							      type,
							      CentEst,
							      pSel,
							      trigClass,
							      kEmcalTriggers
							      );

  return task;

}

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char * njetsBase,
						     const char * njetsTag,
						     const Double_t R,
						     const char * nrhoBase,
						     const char * nrhoTag,
						     const char * ntracks,
						     const char * nclusters,
						     const char * type,
						     const char * CentEst,
						     Int_t        pSel,
						     TString      trigClass,
						     TString      kEmcalTriggers
						     ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskEmcalJetTagger","No analysis manager found.");
      return 0;
    }

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

  TString wagonName = Form("JetTagger_%s_%s_TC%s",njetsBase,njetsTag,trigClass.Data());

  //Configure jet tagger task
  AliAnalysisTaskEmcalJetTagger *task = new AliAnalysisTaskEmcalJetTagger(wagonName.Data());

  task->SetNCentBins(4);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackCont  = task->AddParticleContainer(ntracks);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  task->SetJetContainerBase(0);
  task->SetJetContainerTag(1);

  TString strType(type);
  AliJetContainer *jetContBase = task->AddJetContainer(njetsBase,strType,R);
  if(jetContBase) {
    jetContBase->SetRhoName(nrhoBase);
    jetContBase->ConnectParticleContainer(trackCont);
    jetContBase->ConnectClusterContainer(clusterCont);
    jetContBase->SetMaxTrackPt(10000.);
  }

  AliJetContainer *jetContTag = task->AddJetContainer(njetsTag,"TPC",R);
  if(jetContTag) {
    jetContTag->SetRhoName(nrhoTag);
    jetContTag->ConnectParticleContainer(trackCont);
    jetContTag->ConnectClusterContainer(clusterCont);
    jetContTag->SetMaxTrackPt(10000.);
  }
  for(Int_t i=0; i<2; i++) {
    task->SetPercAreaCut(0.6, i); //keep?
  }
  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName(wagonName);
  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}

//this AddTask only creates the task, need to add manually all the rest (for subwagons)
AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char *wagonName){

	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr)
    {
    	Error("AddTaskEmcalJetTagger","No analysis manager found.");
    	return 0;
    }

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

    //Define jet tagger task
    AliAnalysisTaskEmcalJetTagger *task = new AliAnalysisTaskEmcalJetTagger(wagonName.Data());
    mgr->AddTask(task);
    // all the configuration is missing, do it in the wagon/subwagon
    //Connnect input
    mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

    //Connect output
    TString contName(wagonName);
    TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
    AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
    mgr->ConnectOutput(task,1,coutput1);

    return task;
}

//Attach rho task
AliAnalysisTaskRhoBase *AttachRhoTaskTagger(TString     kPeriod             = "LHC13b",
					    TString     kTracksName         = "PicoTracks",
					    TString     kClusName           = "caloClustersCorr",
					    Double_t    R                   = 0.4,
					    Double_t    ptminTrack          = 0.15,
					    Double_t    etminClus           = 0.3,
					    Int_t       recombScheme        = 0,
					    TString     tag                 = "Jet"
					    ) {

  AliAnalysisTaskRhoBase *rhoTaskBase;

  kPeriod.ToLower();

  // Add kt jet finder and rho task in case we want background subtraction
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");
  AliEmcalJetTask *jetFinderKt;
  AliEmcalJetTask *jetFinderAKt;
  jetFinderAKt  = AddTaskEmcalJet(kTracksName, "", kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus,0.005,recombScheme,tag.Data(),1.);
  jetFinderAKt->SelectCollisionCandidates(AliVEvent::kAny);
  if(kPeriod.EqualTo("lhc13b") || kPeriod.EqualTo("lhc13c") || kPeriod.EqualTo("lhc13d") || kPeriod.EqualTo("lhc13e") || kPeriod.EqualTo("lhc13f")) {
    jetFinderKt   = AddTaskEmcalJet(kTracksName, "", kKT, R, kCHARGEDJETS, ptminTrack, etminClus,0.005,recombScheme,tag.Data(),0.);

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C");
    TF1 *fScale = new TF1("fScale","1.42",0.,100.); //scale factor for pPb
    AliAnalysisTaskRhoSparse *rhoTaskSparse = AddTaskRhoSparse(
			       jetFinderKt->GetName(),
			       jetFinderAKt->GetName(),
			       kTracksName,
			       kClusName,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       R,
			       "TPC",
			       0.01,
			       0.15,
			       0,
			       fScale,
			       0,
			       kTRUE,
			       Form("RhoSparseR%03d",(int)(100*R)),
			       kTRUE
			       );
    rhoTaskSparse->SetUseAliAnaUtils(kTRUE);
    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTaskSparse;
  }
  else if(kPeriod.EqualTo("lhc10h") || kPeriod.EqualTo("lhc11h") ) {
    jetFinderKt   = AddTaskEmcalJet(kTracksName, "", kKT, R, kCHARGEDJETS, ptminTrack, etminClus,0.005,recombScheme,tag.Data(),0.1);

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/EMCALJetTasks/macros/AddTaskRho.C");
    TF1* sfunc = new TF1("sfunc","[0]*x*x+[1]*x+[2]",-1,100);
    sfunc->SetParameter(2,1.76458);
    sfunc->SetParameter(1,-0.0111656);
    sfunc->SetParameter(0,0.000107296);
    TString rhoname = Form("%sRhoR%03dptmin%3.0f%s",tag.Data(),(int)(100*R),ptminTrack*1000.0,kTracksName.Data());
    Printf("rhoname: %s",rhoname.Data());
    AliAnalysisTaskRho *rhoTask = AddTaskRho(
					     jetFinderKt->GetName(),
					     kTracksName,
					     kClusName,
					     rhoname,
					     R,
					     "TPC",
					     0.01,
					     0,
					     sfunc,
					     2,
					     kTRUE);
    rhoTask->SetHistoBins(100,0,250);

    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>rhoTask;
  }
  jetFinderKt->SelectCollisionCandidates(AliVEvent::kAny);
  if(tag.EqualTo("JetPythia")) {
    jetFinderKt->SetTrackLabelRange(99999,9999999);
    jetFinderAKt->SetTrackLabelRange(99999,9999999);
  }

  return rhoTaskBase;
}
<commit_msg>Move back to 8bedf6<commit_after>enum AlgoType {kKT, kANTIKT};
enum JetType  {kFULLJETS, kCHARGEDJETS, kNEUTRALJETS};

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char * njetsBase,
    const char * njetsTag,
    const Double_t R,
    const char * nrhoBase,
    const char * nrhoTag,
    const char * ntracks,
    const char * nclusters,
    const char *type,
    const char *CentEst,
    Int_t       pSel,
    TString     trigClass      = "",
    TString     kEmcalTriggers = "");

AliAnalysisTaskRhoBase *AttachRhoTaskTagger(TString     kPeriod             = "LHC13b",
    TString     kTracksName         = "PicoTracks",
    TString     kClusName           = "caloClustersCorr",
    Double_t    R                   = 0.4,
    Double_t    ptminTrack          = 0.15,
    Double_t    etminClus           = 0.3,
    Int_t       recombScheme        = 0,
    TString     tag                 = "Jet"
);

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(TString     kTracksName         = "PicoTracks",
    TString     kClusName           = "caloClustersCorr",
    Double_t    R                   = 0.4,
    Double_t    ptminTrack          = 0.15,
    Double_t    etminClus           = 0.3,
    Double_t    ptminTag            = 4.,
    Int_t       rhoType             = 1,
    const char *type                = "EMCAL",
    const char *CentEst             = "V0M",
    Int_t       pSel                = AliVEvent::kCentral | AliVEvent::kSemiCentral | AliVEvent::kMB,
    TString     trigClass           = "",
    TString     kEmcalTriggers      = "",
    TString     kPeriod             = "LHC11h",
    Int_t       recombScheme        = 0,
    TString     tag1                = "Jet",
    TString     tag2                = ""
) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    Error("AddTaskEmcalJetTagger","No analysis manager found.");
    return 0;
  }

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

  // #### Add necessary jet finder tasks
  TMacro jetfinderadd(Form("%s/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C", gSystem->Getenv("ALICE_PHYSICS")));

  if(tag2.IsNull()) tag2=tag1;

  AliEmcalJetTask* jetFinderTaskBase = 0x0;
  if (strcmp(type,"TPC")==0)
    jetFinderTaskBase = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"\", %d, %f, %d, %f, %f, 0.005, %d, %s, %f, kFALSE, kFALSE", kTracksName.Data(), kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus,recombScheme,tag1.Data(),ptminTrack));
  else if (strcmp(type,"EMCAL")==0)
    jetFinderTaskBase = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"%s\", %d, %f, %d, %f, %f, 0.005, %d, %s, %f, kFALSE, kFALSE", kTracksName.Data(), kClusName.Data(), kANTIKT, R, kFULLJETS, ptminTrack, etminClus,recombScheme,tag1.Data(),ptminTrack));
  jetFinderTaskBase->SelectCollisionCandidates(AliVEvent::kAny);

  AliEmcalJetTask* jetFinderTaskTag  = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"\", %d, %f, %d, %f, %f, 0.005, %d, %s, %f, kFALSE, kFALSE", kTracksName.Data(), kANTIKT, R, kCHARGEDJETS, ptminTag, etminClus,recombScheme,tag2.Data(),ptminTag));
  jetFinderTaskTag->SelectCollisionCandidates(AliVEvent::kAny);

  /*
  if(tag1.EqualTo("JetPythia"))
    jetFinderTaskBase->SetTrackLabelRange(99999,9999999);
  //    jetFinderTaskBase->SelectConstituents(TObject::kBitMask, 0);
  if(tag2.EqualTo("JetPythia"))
    jetFinderTaskTag->SetTrackLabelRange(99999,9999999);
    */
  //    jetFinderTaskTag->SelectConstituents(TObject::kBitMask, 0);

  TString strJetsBase = jetFinderTaskBase->GetName();
  TString strJetsTag  = jetFinderTaskTag->GetName();

  AliAnalysisTaskRhoBase *rhoTaskBase;
  AliAnalysisTaskRhoBase *rhoTaskTag;
  TString rhoNameBase = "";
  TString rhoNameTag  = "";
  if(rhoType==1) {
    rhoTaskBase = AttachRhoTaskTagger(kPeriod,kTracksName,kClusName,R,ptminTrack,etminClus,recombScheme,tag1);
    if(rhoTaskBase) {
      rhoTaskBase->SetCentralityEstimator(CentEst);
      rhoTaskBase->SelectCollisionCandidates(AliVEvent::kAny);
      if (strcmp(type,"TPC")==0)
        rhoNameBase = rhoTaskBase->GetOutRhoName();
      if (strcmp(type,"EMCAL")==0)
        rhoNameBase = rhoTaskBase->GetOutRhoScaledName();
    }
    if(rhoTaskTag) {
      rhoTaskTag = AttachRhoTaskTagger(kPeriod,kTracksName,kClusName,R,ptminTag,0.,recombScheme,tag2);
      rhoTaskTag->SetCentralityEstimator(CentEst);
      rhoTaskTag->SelectCollisionCandidates(AliVEvent::kAny);
      rhoNameTag  = rhoTaskTag->GetOutRhoName();
    }
  }

  //Configure jet tagger task
  AliAnalysisTaskEmcalJetTagger *task = AddTaskEmcalJetTagger(jetFinderTaskBase->GetName(),
      jetFinderTaskTag->GetName(),
      R,
      rhoNameBase,
      rhoNameTag,
      kTracksName.Data(),
      kClusName.Data(),
      type,
      CentEst,
      pSel,
      trigClass,
      kEmcalTriggers
  );

  return task;

}

AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char * njetsBase,
    const char * njetsTag,
    const Double_t R,
    const char * nrhoBase,
    const char * nrhoTag,
    const char * ntracks,
    const char * nclusters,
    const char * type,
    const char * CentEst,
    Int_t        pSel,
    TString      trigClass,
    TString      kEmcalTriggers
) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    Error("AddTaskEmcalJetTagger","No analysis manager found.");
    return 0;
  }

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

  TString wagonName = Form("JetTagger_%s_%s_TC%s",njetsBase,njetsTag,trigClass.Data());

  //Configure jet tagger task
  AliAnalysisTaskEmcalJetTagger *task = new AliAnalysisTaskEmcalJetTagger(wagonName);

  task->SetNCentBins(4);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackCont  = task->AddParticleContainer(ntracks);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  task->SetJetContainerBase(0);
  task->SetJetContainerTag(1);

  TString strType(type);
  AliJetContainer *jetContBase = task->AddJetContainer(njetsBase,strType,R);
  if(jetContBase) {
    jetContBase->SetRhoName(nrhoBase);
    jetContBase->ConnectParticleContainer(trackCont);
    jetContBase->ConnectClusterContainer(clusterCont);
    jetContBase->SetMaxTrackPt(10000.);
  }

  AliJetContainer *jetContTag = task->AddJetContainer(njetsTag,"TPC",R);
  if(jetContTag) {
    jetContTag->SetRhoName(nrhoTag);
    jetContTag->ConnectParticleContainer(trackCont);
    jetContTag->ConnectClusterContainer(clusterCont);
    jetContTag->SetMaxTrackPt(10000.);
  }
  for(Int_t i=0; i<2; i++) {
    task->SetPercAreaCut(0.6, i); //keep?
  }
  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName(wagonName);
  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}

//this AddTask only creates the task, need to add manually all the rest (for subwagons)
AliAnalysisTaskEmcalJetTagger* AddTaskEmcalJetTagger(const char *wagonName){

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    Error("AddTaskEmcalJetTagger","No analysis manager found.");
    return 0;
  }

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

  //Define jet tagger task
  AliAnalysisTaskEmcalJetTagger *task = new AliAnalysisTaskEmcalJetTagger(wagonName);
  mgr->AddTask(task);
  // all the configuration is missing, do it in the wagon/subwagon
  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName(wagonName);
  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}

//Attach rho task
AliAnalysisTaskRhoBase *AttachRhoTaskTagger(TString kPeriod,
    TString     kTracksName,
    TString     kClusName,
    Double_t    R,
    Double_t    ptminTrack,
    Double_t    etminClus,
    Int_t       recombScheme,
    TString     tag
) {

  AliAnalysisTaskRhoBase *rhoTaskBase;

  kPeriod.ToLower();

  // Add kt jet finder and rho task in case we want background subtraction
  TMacro jetfinderadd(Form("%s/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C", gSystem->Getenv("ALICE_PHYSICS")));
  TMacro rhosparseadd(Form("%s/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C", gSystem->Getenv("ALICE_PHYSICS")));
  AliEmcalJetTask *jetFinderKt;
  AliEmcalJetTask *jetFinderAKt;
  jetFinderAKt  = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"\", %d, %f, %d, %f, %f, 0.005, %d, %s, %f", kTracksName.Data(), kANTIKT, R, kCHARGEDJETS, ptminTrack, etminClus,recombScheme,tag.Data(),1.));
  jetFinderAKt->SelectCollisionCandidates(AliVEvent::kAny);
  if(kPeriod.EqualTo("lhc13b") || kPeriod.EqualTo("lhc13c") || kPeriod.EqualTo("lhc13d") || kPeriod.EqualTo("lhc13e") || kPeriod.EqualTo("lhc13f")) {
    jetFinderKt   = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"\", %d, %f, %d, %f, %f, 0.005, %d, %s, %f", kTracksName.Data(), kKT, R, kCHARGEDJETS, ptminTrack, etminClus,recombScheme,tag.Data(),0.));

    TF1 *fScale = new TF1("fScale","1.42",0.,100.); //scale factor for pPb
    AliAnalysisTaskRhoSparse *rhoTaskSparse = (AliAnalysisTaskRhoSparse *)rhosparseadd.Exec(Form(
        "\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %f, \"TPC\", 0.01, 0.15, 0, (TF1 *)%p, 0, kTRUE, \"%s\", kTRUE",
        jetFinderKt->GetName(),
        jetFinderAKt->GetName(),
        kTracksName.Data(),
        kClusName.Data(),
        Form("RhoSparseR%03d",(int)(100*R)),
        R,
        fScale,
        Form("RhoSparseR%03d",(int)(100*R))
    ));
    rhoTaskSparse->SetUseAliAnaUtils(kTRUE);
    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>(rhoTaskSparse);
  }
  else if(kPeriod.EqualTo("lhc10h") || kPeriod.EqualTo("lhc11h") ) {
    jetFinderKt   = (AliEmcalJetTask *)jetfinderadd.Exec(Form("\"%s\", \"\", %d, %f, %d, %f, %f, 0.005, %d, %s, 0.1", kTracksName.Data(), kKT, R, kCHARGEDJETS, ptminTrack, etminClus,recombScheme,tag.Data()));

    TF1* sfunc = new TF1("sfunc","[0]*x*x+[1]*x+[2]",-1,100);
    sfunc->SetParameter(2,1.76458);
    sfunc->SetParameter(1,-0.0111656);
    sfunc->SetParameter(0,0.000107296);
    TString rhoname = Form("%sRhoR%03dptmin%3.0f%s",tag.Data(),(int)(100*R),ptminTrack*1000.0,kTracksName.Data());
    Printf("rhoname: %s",rhoname.Data());
    AliAnalysisTaskRho *rhoTask = (AliAnalysisTaskRho *)rhosparseadd.Exec(Form(
        "\"%s\", \"%s\", \"%s\", \"%s\", %f, \"TPC\", 0.01, 0, (TF1 *)%p, 2, kTRUE",
        jetFinderKt->GetName(),
        kTracksName.Data(),
        kClusName.Data(),
        rhoname.Data(),
        R,
        sfunc
        ));
    rhoTask->SetHistoBins(100,0,250);

    rhoTaskBase = dynamic_cast<AliAnalysisTaskRhoBase*>(rhoTask);
  }
  jetFinderKt->SelectCollisionCandidates(AliVEvent::kAny);
  /*
  if(tag.EqualTo("JetPythia")) {
    jetFinderKt->SetTrackLabelRange(99999,9999999);
    jetFinderAKt->SetTrackLabelRange(99999,9999999);
  }
  */

  return rhoTaskBase;
}
<|endoftext|>