<commit_before>/*! \file
 *
 */
#include "Layer.h"

#include "../../TEMLogger.h"
extern src::severity_logger< severity_level > glg;

Layer::Layer() {
  BOOST_LOG_SEV(glg, debug) << "Creating a (generic) layer object...";
  nextl= NULL;
  prevl= NULL;
  isSnow = false;
  isSoil = false;
  isRock = false;
  isMoss    = false;
  isMineral = false;
  isOrganic = false;
  isFibric = false;
  isHumic  = false;
  tkey  = I_UNKNOWN;
  indl  = MISSING_I;
  solind= MISSING_I;
  age   = 0.;
  dz    = MISSING_D;
  z     = MISSING_D;
  rho= MISSING_D;
  bulkden= MISSING_D;
  poro= MISSING_D;
  tcmin= MISSING_D;
  tcdry= MISSING_D;
  tcsolid= MISSING_D;
  tcsatfrz= MISSING_D;
  tcsatunf= MISSING_D;
  vhcsolid= MISSING_D;
  albdryvis= MISSING_D;
  albdrynir= MISSING_D;
  albsatvis= MISSING_D;
  albsatnir= MISSING_D;
  maxliq  = MISSING_D;
  maxice  = MISSING_D;
  psisat= MISSING_D;
  hksat = MISSING_D;
  bsw   = MISSING_D;
  // thermal status
  frozen    = MISSING_I;
  frozenfrac= MISSING_D;
  tem  = MISSING_D;
  tcond= MISSING_D;
  pce_t= MISSING_D;
  pce_f= MISSING_D;
  // hydrological status
  liq  = MISSING_D;
  ice  = MISSING_D;
  hcond= MISSING_D;
  // soil carbon pool
  rawc = MISSING_D;
  soma = MISSING_D;
  sompr= MISSING_D;
  somcr= MISSING_D;
  cfrac= MISSING_D;
};

Layer::~Layer() {
  BOOST_LOG_SEV(glg, debug) << "Deleting a (generic) layer object...";
};

void Layer::advanceOneDay() {
  age+=1/365.;
};

double Layer::getHeatCapacity() { // volumetric heat capacity
  double hcap = MISSING_D;

  if(isSoil) {
    if(frozen==-1) {
      hcap = getUnfVolHeatCapa();
    } else if(frozen ==1) {
      hcap = getFrzVolHeatCapa();
    } else if(frozen ==0) {
      hcap = getMixVolHeatCapa();
    }
  } else if(isSnow) {
    hcap = getFrzVolHeatCapa();
  } else if(isRock) {
    hcap = getFrzVolHeatCapa();
  }

  return hcap;
};

double Layer::getThermalConductivity() {
  double tc = MISSING_D;

  if(isSoil || isSnow) {
    if(frozen==1) {
      tc = getFrzThermCond();
    } else {
      tc = getUnfThermCond();
    }
  } else if (isRock) {
    tc = getFrzThermCond();
  }

  return tc;
};

double Layer::getVolWater() {
  double vice = getVolIce();
  double vliq = getVolLiq();
  return fmin((double)poro,(double)vice+vliq);
};

double Layer::getEffVolWater() {
  double effvol = 0.;

  if(isSoil) {
    effvol = getVolWater() - minliq/DENLIQ/dz;
  } else if (isSnow) {
    effvol = getVolWater();
  }

  if(effvol<0) {
    effvol =0.;
  }

  return effvol;
};

double Layer::getVolIce() {
  if (dz != 0) {
    double vice = ice/DENICE/dz; // FIX THIS: divide by zero error when there is no thickness!
    vice = fmin((double)vice, (double)poro);
    return vice;
  } else {
    return 0;
  }
};

double Layer::getVolLiq() {
  if (dz != 0) {
    double vliq = liq/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness!
    vliq = fmin((double)vliq,(double)poro);
    return vliq;
  } else {
    return 0;
  }

};

double Layer::getEffVolLiq() {
  if (dz != 0) {
    double evliq = (liq-minliq)/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness!
    evliq = fmin((double)evliq,(double)poro);
    return evliq;
  } else {
    return 0;
  }
};
<commit_msg>Fix issue with reported 'tcond'.<commit_after>/*! \file
 *
 */
#include "Layer.h"

#include "../../TEMLogger.h"
extern src::severity_logger< severity_level > glg;

Layer::Layer() {
  BOOST_LOG_SEV(glg, debug) << "Creating a (generic) layer object...";
  nextl= NULL;
  prevl= NULL;
  isSnow = false;
  isSoil = false;
  isRock = false;
  isMoss    = false;
  isMineral = false;
  isOrganic = false;
  isFibric = false;
  isHumic  = false;
  tkey  = I_UNKNOWN;
  indl  = MISSING_I;
  solind= MISSING_I;
  age   = 0.;
  dz    = MISSING_D;
  z     = MISSING_D;
  rho= MISSING_D;
  bulkden= MISSING_D;
  poro= MISSING_D;
  tcmin= MISSING_D;
  tcdry= MISSING_D;
  tcsolid= MISSING_D;
  tcsatfrz= MISSING_D;
  tcsatunf= MISSING_D;
  vhcsolid= MISSING_D;
  albdryvis= MISSING_D;
  albdrynir= MISSING_D;
  albsatvis= MISSING_D;
  albsatnir= MISSING_D;
  maxliq  = MISSING_D;
  maxice  = MISSING_D;
  psisat= MISSING_D;
  hksat = MISSING_D;
  bsw   = MISSING_D;
  // thermal status
  frozen    = MISSING_I;
  frozenfrac= MISSING_D;
  tem  = MISSING_D;
  tcond= MISSING_D;
  pce_t= MISSING_D;
  pce_f= MISSING_D;
  // hydrological status
  liq  = MISSING_D;
  ice  = MISSING_D;
  hcond= MISSING_D;
  // soil carbon pool
  rawc = MISSING_D;
  soma = MISSING_D;
  sompr= MISSING_D;
  somcr= MISSING_D;
  cfrac= MISSING_D;
};

Layer::~Layer() {
  BOOST_LOG_SEV(glg, debug) << "Deleting a (generic) layer object...";
};

void Layer::advanceOneDay() {
  age+=1/365.;
};

double Layer::getHeatCapacity() { // volumetric heat capacity
  double hcap = MISSING_D;

  if(isSoil) {
    if(frozen==-1) {
      hcap = getUnfVolHeatCapa();
    } else if(frozen ==1) {
      hcap = getFrzVolHeatCapa();
    } else if(frozen ==0) {
      hcap = getMixVolHeatCapa();
    }
  } else if(isSnow) {
    hcap = getFrzVolHeatCapa();
  } else if(isRock) {
    hcap = getFrzVolHeatCapa();
  }

  return hcap;
};

double Layer::getThermalConductivity() {
  double tc = MISSING_D;

  if(isSoil || isSnow) {
    if(frozen==1) {
      tc = getFrzThermCond();
    } else {
      tc = getUnfThermCond();
    }
  } else if (isRock) {
    tc = getFrzThermCond();
  }

  this->tcond = tc;
  return tc;
};

double Layer::getVolWater() {
  double vice = getVolIce();
  double vliq = getVolLiq();
  return fmin((double)poro,(double)vice+vliq);
};

double Layer::getEffVolWater() {
  double effvol = 0.;

  if(isSoil) {
    effvol = getVolWater() - minliq/DENLIQ/dz;
  } else if (isSnow) {
    effvol = getVolWater();
  }

  if(effvol<0) {
    effvol =0.;
  }

  return effvol;
};

double Layer::getVolIce() {
  if (dz != 0) {
    double vice = ice/DENICE/dz; // FIX THIS: divide by zero error when there is no thickness!
    vice = fmin((double)vice, (double)poro);
    return vice;
  } else {
    return 0;
  }
};

double Layer::getVolLiq() {
  if (dz != 0) {
    double vliq = liq/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness!
    vliq = fmin((double)vliq,(double)poro);
    return vliq;
  } else {
    return 0;
  }

};

double Layer::getEffVolLiq() {
  if (dz != 0) {
    double evliq = (liq-minliq)/DENLIQ/dz; // FIX THIS: divide by zero error when there is no thickness!
    evliq = fmin((double)evliq,(double)poro);
    return evliq;
  } else {
    return 0;
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * 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.
 */
#pragma once
#include <fstream>
#include <graphene/chain/protocol/block.hpp>

namespace graphene { namespace chain {
   class index_entry;

   class block_database
   {
      public:
         void open( const fc::path& dbdir );
         bool is_open()const;
         void flush();
         void close();

         void store( const block_id_type& id, const signed_block& b );
         void remove( const block_id_type& id );

         bool                   contains( const block_id_type& id )const;
         block_id_type          fetch_block_id( uint32_t block_num )const;
         optional<signed_block> fetch_optional( const block_id_type& id )const;
         optional<signed_block> fetch_by_number( uint32_t block_num )const;
         optional<signed_block> last()const;
         optional<block_id_type> last_id()const;
      private:
         optional<index_entry> last_index_entry()const;
         fc::path _index_filename;
         mutable std::fstream _blocks;
         mutable std::fstream _block_num_to_pos;
   };
} }
<commit_msg>fix warning: 'index_entry' defined as a struct here but previously declared as a class<commit_after>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * 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.
 */
#pragma once
#include <fstream>
#include <graphene/chain/protocol/block.hpp>

namespace graphene { namespace chain {
   struct index_entry;

   class block_database
   {
      public:
         void open( const fc::path& dbdir );
         bool is_open()const;
         void flush();
         void close();

         void store( const block_id_type& id, const signed_block& b );
         void remove( const block_id_type& id );

         bool                   contains( const block_id_type& id )const;
         block_id_type          fetch_block_id( uint32_t block_num )const;
         optional<signed_block> fetch_optional( const block_id_type& id )const;
         optional<signed_block> fetch_by_number( uint32_t block_num )const;
         optional<signed_block> last()const;
         optional<block_id_type> last_id()const;
      private:
         optional<index_entry> last_index_entry()const;
         fc::path _index_filename;
         mutable std::fstream _blocks;
         mutable std::fstream _block_num_to_pos;
   };
} }
<|endoftext|>


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

#include "FramePointerValidator.h"

#include <capstone/capstone.h>

#include "FunctionFramePointerValidator.h"
#include "OrbitBase/Logging.h"

std::optional<std::vector<std::shared_ptr<Function>>>
FramePointerValidator::GetFpoFunctions(
    const std::vector<std::shared_ptr<Function>>& functions,
    const std::string& file_name, bool is_64_bit) {
  std::vector<std::shared_ptr<Function>> result;

  cs_mode mode = is_64_bit ? CS_MODE_64 : CS_MODE_32;
  csh handle;
  if (cs_open(CS_ARCH_X86, mode, &handle) != CS_ERR_OK) {
    ERROR("Unable to open capstone.");
    return {};
  }

  cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON);

  std::ifstream instream(file_name, std::ios::in | std::ios::binary);
  std::vector<uint8_t> binary((std::istreambuf_iterator<char>(instream)),
                              std::istreambuf_iterator<char>());

  for (const auto& function : functions) {
    uint64_t function_size = function->Size();
    if (function_size == 0) {
      continue;
    }

    FunctionFramePointerValidator validator{
        handle, binary.data() + function->Offset(), function_size};

    if (!validator.Validate()) {
      result.push_back(function);
    }
  }
  return result;
}<commit_msg>Fixed memory leak in FramePointerValidator<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "FramePointerValidator.h"

#include <capstone/capstone.h>

#include "FunctionFramePointerValidator.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/UniqueResource.h"

std::optional<std::vector<std::shared_ptr<Function>>>
FramePointerValidator::GetFpoFunctions(
    const std::vector<std::shared_ptr<Function>>& functions,
    const std::string& file_name, bool is_64_bit) {
  std::vector<std::shared_ptr<Function>> result;

  cs_mode mode = is_64_bit ? CS_MODE_64 : CS_MODE_32;
  csh temp_handle;
  if (cs_open(CS_ARCH_X86, mode, &temp_handle) != CS_ERR_OK) {
    ERROR("Unable to open capstone.");
    return {};
  }
  OrbitBase::unique_resource handle{std::move(temp_handle),
                                    [](csh handle) { cs_close(&handle); }};

  cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON);

  std::ifstream instream(file_name, std::ios::in | std::ios::binary);
  std::vector<uint8_t> binary((std::istreambuf_iterator<char>(instream)),
                              std::istreambuf_iterator<char>());

  for (const auto& function : functions) {
    uint64_t function_size = function->Size();
    if (function_size == 0) {
      continue;
    }

    FunctionFramePointerValidator validator{
        handle, binary.data() + function->Offset(), function_size};

    if (!validator.Validate()) {
      result.push_back(function);
    }
  }
  return result;
}<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP

#include <boost/utility/enable_if.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/dot_product.hpp>
#include <stan/math/prim/mat/fun/dot_self.hpp>
#include <stan/math/prim/mat/meta/length.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/meta/is_constant.hpp>
#include <stan/math/prim/scal/meta/is_vector_like.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian Process
 * Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in dot product.
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x", x[i]);
    check_finite("gp_dot_prod_cov", "x", x[i]);
  }

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + dot_self(x[i]);
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x[i], x[j]);
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]);
  return cov;
}

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian
 * Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in transpose
 *   and multiply
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  check_not_nan("gp_dot_prod_cov", "x", x);
  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + x[i] * x[i];
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + x[i] * x[j];
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1];
  return cov;
}

/**
 * Returns a dot product covariance matrix of differing
 * x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of elements
 * @tparam T_x2 type of second std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1,
                const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);
    check_finite("gp_dot_prod_cov", "x1", x1[i]);
  }
  for (size_t i = 0; i < x2_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);
    check_finite("gp_dot_prod_cov", "x2", x2[i]);
  }
  Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]);
    }
  }
  return cov;
}

/**
 * Returns a dot product covariance matrix of
 * differing x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of double
 * @tparam T_x2 type of second std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma is the constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2,
                const T_sigma &sigma) {
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  check_not_nan("gp_dot_prod_cov", "x1", x1);
  check_finite("gp_dot_prod_cov", "x1", x1);
  check_not_nan("gp_dot_prod_cov", "x2", x2);
  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + x1[i] * x2[j];
    }
  }
  return cov;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP

#include <boost/utility/enable_if.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/dot_product.hpp>
#include <stan/math/prim/mat/fun/dot_self.hpp>
#include <stan/math/prim/mat/meta/length.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/meta/is_constant.hpp>
#include <stan/math/prim/scal/meta/is_vector_like.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian Process
 * Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in dot product.
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x", x[i]);
    check_finite("gp_dot_prod_cov", "x", x[i]);
  }

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + dot_self(x[i]);
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x[i], x[j]);
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]);
  return cov;
}

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian
 * Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in transpose
 *   and multiply
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
Eigen::Matrix<typename return_type<T_x, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  check_not_nan("gp_dot_prod_cov", "x", x);
  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + x[i] * x[i];
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + x[i] * x[j];
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1];
  return cov;
}

/**
 * Returns a dot product covariance matrix of differing
 * x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of elements
 * @tparam T_x2 type of second std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1,
                const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);
    check_finite("gp_dot_prod_cov", "x1", x1[i]);
  }
  for (size_t i = 0; i < x2_size; ++i) {
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);
    check_finite("gp_dot_prod_cov", "x2", x2[i]);
  }
  Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]);
    }
  }
  return cov;
}

/**
 * Returns a dot product covariance matrix of
 * differing x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of double
 * @tparam T_x2 type of second std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma is the constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
Eigen::Matrix<typename return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
              Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2,
                const T_sigma &sigma) {
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  check_not_nan("gp_dot_prod_cov", "x1", x1);
  check_finite("gp_dot_prod_cov", "x1", x1);
  check_not_nan("gp_dot_prod_cov", "x2", x2);
  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + x1[i] * x2[j];
    }
  }
  return cov;
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>void runGlauberMCpPb(Int_t option=0,Int_t N=250000)
{
  //load libraries
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libTree");
  gSystem->Load("libPWGGlauber");

  //set the random seed from current time
  TTimeStamp time;
  Int_t seed = time.GetSec();
  gRandom->SetSeed(seed);

  Int_t nevents = N; // number of events to simulate
  // supported systems are e.g. "p", "d", "Si", "Au", "Pb", "U"
  Option_t *sysA="p";
  Option_t *sysB="Pb";
  Double_t signn=70; // inelastic nucleon nucleon cross section
  //const char *fname="GlauberMC_PbPb_ntuple.root"; // name output file

  // run the code to produce an ntuple:
  //  AliGlauberMC::runAndSaveNucleons(10000,"Pb","Pb",72);
  Double_t mind=0.4;
  //  AliGlauberMC::RunAndSaveNtuple(nevents,sysA,sysB,signn,mind);
  Double_t r=6.62;
  Double_t a=0.546;
  const char *fname="glau_ppb_ntuple.root";

  AliGlauberMC mcg(sysA,sysB,signn);
  mcg.SetMinDistance(mind);
  mcg.Setr(r);
  mcg.Seta(a);
  if (option==1)
    mcg.SetDoFluc(0.55,78.5,0.82,kTRUE);
  else if (option==2)
    mcg.SetDoFluc(1.01,72.5,0.74,kTRUE);
  mcg.SetDoPartProduction(kFALSE);

  //////////////////
  mcg.SetdNdEtaType(AliGlauberMC::kNBDSV);
  mcg.GetdNdEtaParam()[0] = 2.49;    //npp
  mcg.GetdNdEtaParam()[1] = 1.7;  //ratioSgm2Mu
  mcg.GetdNdEtaParam()[2] = 0.13; //xhard
  //////////////////

  mcg.Run(nevents);

  TNtuple  *nt = mcg.GetNtuple();
  TFile out(fname,"recreate",fname,9);
  if(nt) nt->Write();
  printf("total cross section with a nucleon-nucleon cross section %.4f is %.4f\n\n",signn,mcg.GetTotXSect());
  out.Close();
}
<commit_msg>added qparts<commit_after>void runGlauberMCpPb(Int_t option=0,Int_t N=250000,Bool_t qparts=kFALSE)
{
  //load libraries
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libTree");
  gSystem->Load("libPWGGlauber");

  //set the random seed from current time
  TTimeStamp time;
  Int_t seed = time.GetSec();
  gRandom->SetSeed(seed);

  Int_t nevents = N; // number of events to simulate
  // supported systems are e.g. "p", "d", "Si", "Au", "Pb", "U"
  Option_t *sysA="p";
  Option_t *sysB="Pb";
  Double_t signn=70; // inelastic nucleon nucleon cross section
  Double_t mind=0.4;
  const char *fname="glau_ppb_ntuple.root";

  if (qparts) {
    signn/=9;
    mind=0;
  }

  AliGlauberMC mcg(sysA,sysB,signn);
  mcg.SetMinDistance(mind);
  if (qparts) {
    AliGlauberNucleus &na = mcg.GetNucA();
    na.SetN(3*na.GetN());
    AliGlauberNucleus &nb = mcg.GetNucB();
    nb.SetN(3*nb.GetN());
  }
  if (option==1)
    mcg.SetDoFluc(0.55,78.5,0.82,kTRUE);
  else if (option==2)
    mcg.SetDoFluc(1.01,72.5,0.74,kTRUE);
  mcg.SetDoPartProduction(kFALSE);

  //////////////////
  mcg.SetdNdEtaType(AliGlauberMC::kNBDSV);
  mcg.GetdNdEtaParam()[0] = 2.49;    //npp
  mcg.GetdNdEtaParam()[1] = 1.7;  //ratioSgm2Mu
  mcg.GetdNdEtaParam()[2] = 0.13; //xhard
  //////////////////

  mcg.Run(nevents);

  TNtuple  *nt = mcg.GetNtuple();
  TFile out(fname,"recreate",fname,9);
  if(nt) nt->Write();
  printf("total cross section with a nucleon-nucleon cross section %.4f is %.4f\n\n",signn,mcg.GetTotXSect());
  out.Close();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Eddic Tests
#include <boost/test/unit_test.hpp>

void assertCompiles(const std::string& file){
    eddic::parseOptions(0, {});

    eddic::Compiler compiler;

    int code = compiler.compileOnly(file);

    BOOST_CHECK_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output){
    assertCompiles("test/cases/" + file);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_CASE( samples_arrays ){
    assertCompiles("samples/arrays.eddi");
}

BOOST_AUTO_TEST_CASE( samples_asm ){
    assertCompiles("samples/asm.eddi");
}

BOOST_AUTO_TEST_CASE( samples_assembly ){
    assertCompiles("samples/assembly.eddi");
}

BOOST_AUTO_TEST_CASE( samples_const ){
    assertCompiles("samples/const.eddi");
}

BOOST_AUTO_TEST_CASE( samples_concat ){
    assertCompiles("samples/concat.eddi");
}

BOOST_AUTO_TEST_CASE( samples_functions ){
    assertCompiles("samples/functions.eddi");
}

BOOST_AUTO_TEST_CASE( samples_includes ){
    assertCompiles("samples/includes.eddi");
}

BOOST_AUTO_TEST_CASE( samples_optimize ){
    assertCompiles("samples/optimize.eddi");
}

BOOST_AUTO_TEST_CASE( samples_problem ){
    assertCompiles("samples/problem.eddi");
}

/* Specific tests */

BOOST_AUTO_TEST_CASE( if_ ){
    assertOutputEquals("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    assertOutputEquals("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    assertOutputEquals("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    assertOutputEquals("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880");
}
<commit_msg>Add the new sample to the integration tests<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Eddic Tests
#include <boost/test/unit_test.hpp>

void assertCompiles(const std::string& file){
    eddic::parseOptions(0, {});

    eddic::Compiler compiler;

    int code = compiler.compileOnly(file);

    BOOST_CHECK_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output){
    assertCompiles("test/cases/" + file);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_CASE( samples_arrays ){
    assertCompiles("samples/arrays.eddi");
}

BOOST_AUTO_TEST_CASE( samples_asm ){
    assertCompiles("samples/asm.eddi");
}

BOOST_AUTO_TEST_CASE( samples_assembly ){
    assertCompiles("samples/assembly.eddi");
}

BOOST_AUTO_TEST_CASE( samples_const ){
    assertCompiles("samples/const.eddi");
}

BOOST_AUTO_TEST_CASE( samples_concat ){
    assertCompiles("samples/concat.eddi");
}

BOOST_AUTO_TEST_CASE( samples_functions ){
    assertCompiles("samples/functions.eddi");
}

BOOST_AUTO_TEST_CASE( samples_includes ){
    assertCompiles("samples/includes.eddi");
}

BOOST_AUTO_TEST_CASE( samples_optimize ){
    assertCompiles("samples/optimize.eddi");
}

BOOST_AUTO_TEST_CASE( samples_problem ){
    assertCompiles("samples/problem.eddi");
}

BOOST_AUTO_TEST_CASE( samples_sort ){
    assertCompiles("samples/sort.eddi");
}

/* Specific tests */

BOOST_AUTO_TEST_CASE( if_ ){
    assertOutputEquals("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    assertOutputEquals("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    assertOutputEquals("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    assertOutputEquals("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880");
}
<|endoftext|>


<commit_before>/**
 * This is the macro to include the Forward multiplicity in a train.
 *
 * @ingroup pwg2_forward_analysis_scripts
 */
AliAnalysisTask*
AddTaskFMD(Int_t nCutBins=1, Float_t correctionCut=0.1)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskFMD", "No analysis manager to connect to.");
    return NULL;
  }

  AliForwardMultiplicity* task = new AliForwardMultiplicity("FMD");
  task->GetHistCollector().SetNCutBins(nCutBins);
  task->GetHistCollector().SetCorrectionCut(correctionCut);
  task->SetLowFluxCut(1000);
  mgr->AddTask(task);

  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();
  AliMCEventHandler* mcHandler =
    dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  Info("AddTaskFMD", "MC handler %p", mcHandler);
  if(mcHandler) {
    pars->SetRealData(kFALSE);
    pars->SetProcessPrimary(kTRUE);
    pars->SetProcessHits(kFALSE);
  }
  else {
    pars->SetRealData(kTRUE);
    pars->SetProcessPrimary(kFALSE);
    pars->SetProcessHits(kFALSE);
  }
  pars->Init();

  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += Form(":%s",pars->GetDndetaAnalysisName());
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,outputfile);

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);

  return task;
}
<commit_msg>Show examples of all parameters that can be tuned  More documentation.<commit_after>/**
 * This is the macro to include the Forward multiplicity in a train.
 *
 * @ingroup pwg2_forward_analysis_scripts
 */
AliAnalysisTask*
AddTaskFMD(Int_t nCutBins=1, Float_t correctionCut=0.1)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskFMD", "No analysis manager to connect to.");
    return NULL;
  }

  // --- Make the task and add it to the manager ---------------------
  AliForwardMultiplicity* task = new AliForwardMultiplicity("FMD");
  mgr->AddTask(task);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.4);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetBinsToSubtract(4);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNLandau(5);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(1000);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(10);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(300);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set the low cut used for sharing
  task->GetSharingFilter().SetLowCut(0.3);
  // Set the number of extra bins (beyond the secondary map border)
  task->GetHistCollector().SetNCutBins(nCutBins);
  // Set the correction cut, that is, when bins in the secondary map
  // is smaller than this, they are considered empty
  task->GetHistCollector().SetCorrectionCut(correctionCut);
  // Set the overall debug level (1: some output, 3: a lot of output)
  task->SetDebug(0);
  // Set the debug level of a single algorithm
  task->GetEnergyFitter().SetDebug(3);

  // --- Set up the parameer manager ---------------------------------
  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();
  AliMCEventHandler* mcHandler =
    dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  Info("AddTaskFMD", "MC handler %p", mcHandler);
  if(mcHandler) {
    pars->SetRealData(kFALSE);
    pars->SetProcessPrimary(kTRUE);
    pars->SetProcessHits(kFALSE);
  }
  else {
    pars->SetRealData(kTRUE);
    pars->SetProcessPrimary(kFALSE);
    pars->SetProcessHits(kFALSE);
  }
  pars->Init();

  // --- Makek the output container and connect it -------------------
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += Form(":%s",pars->GetDndetaAnalysisName());
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);

  return task;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/rev/mat/fun/dot_product.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian Process
 * Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in dot product.
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x", x[i]);

  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + dot_self(x[i]);
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x[i], x[j]);
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]);
  return cov;
}

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian
 * Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in transpose
 *   and multiply
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<double> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x", x[i]);

  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + x[i] * x[i];
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + x[i] * x[j];
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1];
  return cov;
}

/**
 * Returns a dot product covariance matrix of differing
 * x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of elements
 * @tparam T_x2 type of second std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
inline typename Eigen::Matrix<
    typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
    Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);

  check_finite("gp_dot_prod_cov", "x1", x1);

  for (size_t i = 0; i < x2_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);

  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]);
    }
  }
  return cov;
}

/**
 * Returns a dot product covariance matrix of
 * differing x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of double
 * @tparam T_x2 type of second std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma is the constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<double> &x1, const std::vector<double> &x2,
                const T_sigma &sigma) {
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);

  check_finite("gp_dot_prod_cov", "x1", x1);

  for (size_t i = 0; i < x2_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);

  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + x1[i] * x2[j];
    }
  }
  return cov;
}
}  // namespace math
}  // namespace stan
#endif
<commit_msg>change rev inclue to prim include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_DOT_PROD_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/mat/fun/dot_product.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian Process
 * Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in dot product.
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_x, typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x", x[i]);

  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<T_x, T_sigma>::type, Eigen::Dynamic,
                Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + dot_self(x[i]);
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x[i], x[j]);
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + dot_self(x[x_size - 1]);
  return cov;
}

/**
 * Returns a dot product covariance matrix. A member of Stan's Gaussian
 * Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x type of std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x std::vector of elements that can be used in transpose
 *   and multiply
 *    This function assumes each element of x is the same size.
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is positive semi-definite
 * @throw std::domain_error if sigma < 0, nan, inf or
 *   x is nan or infinite
 */
template <typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<double> &x, const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x", x[i]);

  check_finite("gp_dot_prod_cov", "x", x);

  Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < (x_size - 1); ++i) {
    cov(i, i) = sigma_sq + x[i] * x[i];
    for (size_t j = i + 1; j < x_size; ++j) {
      cov(i, j) = sigma_sq + x[i] * x[j];
      cov(j, i) = cov(i, j);
    }
  }
  cov(x_size - 1, x_size - 1) = sigma_sq + x[x_size - 1] * x[x_size - 1];
  return cov;
}

/**
 * Returns a dot product covariance matrix of differing
 * x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of elements
 * @tparam T_x2 type of second std::vector of elements
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_x1, typename T_x2, typename T_sigma>
inline typename Eigen::Matrix<
    typename stan::return_type<T_x1, T_x2, T_sigma>::type, Eigen::Dynamic,
    Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2,
                const T_sigma &sigma) {
  using stan::math::dot_product;
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);

  check_finite("gp_dot_prod_cov", "x1", x1);

  for (size_t i = 0; i < x2_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);

  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + dot_product(x1[i], x2[j]);
    }
  }
  return cov;
}

/**
 * Returns a dot product covariance matrix of
 * differing x's. A member of Stan's Gaussian Process Library.
 *
 * \f$k(x,x') = \sigma^2 + x \cdot x'\f$
 *
 * A dot product covariance matrix is the same covariance matrix
 * as in bayesian regression with \f$N(0,1)\f$ priors on regression coefficients
 * and a \f$N(0,\sigma^2)\f$ prior on the constant function. See Rasmussen and
 * Williams et al 2006, Chapter 4.
 *
 * @tparam T_x1 type of first std::vector of double
 * @tparam T_x2 type of second std::vector of double
 * @tparam T_sigma type of sigma
 *
 * @param x1 std::vector of elements that can be used in dot_product
 * @param x2 std::vector of elements that can be used in dot_product
 * @param sigma is the constant function that can be used in stan::math::square
 * @return dot product covariance matrix that is not always symmetric
 * @throw std::domain_error if sigma < 0, nan or inf
 *   or if x1 or x2 are nan or inf
 */
template <typename T_sigma>
inline typename Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                              Eigen::Dynamic, Eigen::Dynamic>
gp_dot_prod_cov(const std::vector<double> &x1, const std::vector<double> &x2,
                const T_sigma &sigma) {
  using stan::math::square;

  check_not_nan("gp_dot_prod_cov", "sigma", sigma);
  check_nonnegative("gp_dot_prod_cov", "sigma", sigma);
  check_finite("gp_dot_prod_cov", "sigma", sigma);

  size_t x1_size = x1.size();
  size_t x2_size = x2.size();
  for (size_t i = 0; i < x1_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x1", x1[i]);

  check_finite("gp_dot_prod_cov", "x1", x1);

  for (size_t i = 0; i < x2_size; ++i)
    check_not_nan("gp_dot_prod_cov", "x2", x2[i]);

  check_finite("gp_dot_prod_cov", "x2", x2);

  Eigen::Matrix<typename stan::return_type<double, T_sigma>::type,
                Eigen::Dynamic, Eigen::Dynamic>
      cov(x1_size, x2_size);

  if (x1_size == 0 || x2_size == 0)
    return cov;

  T_sigma sigma_sq = square(sigma);

  for (size_t i = 0; i < x1_size; ++i) {
    for (size_t j = 0; j < x2_size; ++j) {
      cov(i, j) = sigma_sq + x1[i] * x2[j];
    }
  }
  return cov;
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>Bool_t   kSimulation    = kFALSE;
TString  fDataType      = "AOD";
Int_t    kYears         = 2011;
TString  kCollisions    = "PbPb";
TString  fTrigger       = "EMCGA";
Bool_t   kEventTriggerAtTaskSE = kFALSE;
Float_t  fMinCen        = -1;
Float_t  fMaxCen        = -1;
TString  fAnaMesonType  = "Pi0";
Bool_t   kAnaPhotonCorr = kTRUE;
Bool_t   kAnaMesonCorr  = kFALSE;
Bool_t   kTimeCut      = kFALSE;
Bool_t   kDistBC       = kTRUE;
Bool_t   kRecalClus    = kTRUE;
Bool_t   kRecalClusE   = kTRUE;
Bool_t   kRecalClusPos = kTRUE;
Bool_t   kRecalClusSSA = kTRUE;
Bool_t   kNonLin       = kTRUE;
Bool_t   kTM           = kFALSE;
Float_t  fDPhiCut      = 0.03;
Float_t  fDEtaCut      = 0.025;
Bool_t   kExotic       = kTRUE;
Float_t  fExoticFraction = 0.95;///for pp:0.97, for PbPb:0.95
Bool_t   kFidul          = kFALSE;
Bool_t   kReClusterier   = kFALSE;
TString  fName           = "V2";
Float_t  fMinCell        = 0.1;
Float_t  fMinSeed        = 0.3;

AliAnalysisTaskEMCALCaloTrackCorr *AddTaskEmcalCaloTrackCorr(
  const TString  data          = "AOD",
  const TString  coll          = "pp",
  const Bool_t   simulation    = kFALSE,
  const TString  trigger       = "MB",
  const Bool_t   triggerSE     = kFALSE,
  const Float_t  minCen        = -1,
  const Float_t  maxCen        = -1,
  const Bool_t   anaPhotonCorr = kTRUE,
  const Bool_t   anaMesonCorr  = kFALSE,
  const TString  anaMesonType  = "Pi0",
  const Bool_t   timecut       = kFALSE,
  const Bool_t   tm            = kFALSE,
  const Float_t  dphicut       = 0.03,
  const Float_t  detacut       = 0.025,
  const Bool_t   exotic       = kTRUE,
  const Float_t  exoticFraction = 0.95,
  const Bool_t   reClusterizer  = kFALSE,
  const TString  name          = "V2",
  const Float_t  minCell       = 0.1,
  const Float_t  minSeed       = 0.3)
{
  fDataType      = data;
  kCollisions    = coll;
  kSimulation    = simulation;
  fTrigger       = trigger;
  kEventTriggerAtTaskSE = triggerSE;
  fMinCen        = minCen;
  fMaxCen        = maxCen;
  fAnaMesonType  = anaMesonType;
  kAnaPhotonCorr = anaPhotonCorr;
  kAnaMesonCorr  = anaMesonCorr;
  kTimeCut      = timecut;
  kTM           = tm;
  fDPhiCut      = dphicut;
  fDEtaCut      = detacut;
  kExotic       = exotic;
  fExoticFraction = exoticFraction;
  kReClusterier   = reClusterizer;
  fName           = name;
  fMinCell        = minCell;
  fMinSeed        = minSeed;

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

  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskHadCorr", "This task requires an input event handler");
    return NULL;
  }

  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/macros/CreateTrackCutsPWGJE.C");
  AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10041004);
  trackCuts->SetEtaRange(-0.8,0.8);

  AliAnalysisTaskEMCALCaloTrackCorr *task = new AliAnalysisTaskEMCALCaloTrackCorr("NeutralCorr");
  task->SetMC(kSimulation);
  task->SetDataType(fDataType);
  task->SetTrackCuts(esdTrackCuts);
  task->SetTrackMatchedDPhiCut(fDPhiCut);
  task->SetTrackMatchedDEtaCut(fDEtaCut);
  task->SetLargeCorrTrigger(5, 50);

  if(kAnaPhotonCorr && !kAnaMesonCorr){
   task->SwitchOnAnaPhotonCorr();
   task->SwitchOffAnaMesonCorr();
   task->SwitchOffFillMesonAOD();
  }
  else if(!kAnaPhotonCorr && kAnaMesonCorr){
   task->SwitchOffAnaPhotonCorr();
   task->SwitchOnAnaMesonCorr();
   task->SetAnaMesonType(fAnaMesonType);
   task->SwitchOnFillMesonAOD();
  }
  else {
   task->SwitchOffAnaPhotonCorr();
   task->SwitchOffAnaMesonCorr();
  }

  task->SetCentralityClass("V0M");
  task->SetCentralityBin(fMinCen,fMaxCen);
  task->SetEventPlaneMethod("Q");
  task->SetEMCALGeometryName("EMCAL_COMPLETEV1");
  mgr->AddTask(task);

  if(kCollisions =="pp")   task->SwitchOnTrackMultBins();
  if(kCollisions =="PbPb") task->SwitchOffTrackMultBins();

  task->SetDeltaPhiCutRange(TMath::Pi()/2., 3*TMath::Pi()/2.);
  task->SetNTriggPtBins(2);
  Float_t fTriggerPtBins[3]={8,15,25};
  task->SetTriggerBins(fTriggerPtBins);
  task->SetNAssocPtBins(5);
  Float_t fAssociatedPtBins[6]={0.5, 1, 2, 4, 6, 15};
  task->SetAssociatedBins(fAssociatedPtBins);

  ConfigureTrigger(task);

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
   if(kAnaPhotonCorr && !kAnaMesonCorr) {
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusivePhotonCen%.1f_%.1f",fMinCen, fMaxCen), TList::Class(),
                            AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
   else if (!kAnaPhotonCorr && kAnaMesonCorr){
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("Inclusive%sCen%.1f_%.1f", fAnaMesonType.Data(),fMinCen, fMaxCen), TList::Class(),
                             AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
   else {
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusiveNoCorrCen%.1f_%.1f", fMinCen, fMaxCen), TList::Class(),
                             AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutputpt1);
    return task;

}

void ConfigureTrigger(AliAnalysisTaskEMCALCaloTrackCorr *task1)
{
  if(!kEventTriggerAtTaskSE){
   task1->SwitchOffEventTriggerAtSE();
   if(fTrigger=="EMC7"){
    printf("CaloTrackCorr trigger EMC7\n");
    task1->SetEventTriggerMask(AliVEvent::kEMC7);
   }
   else if (fTrigger=="INT7"){
    printf("CaloTrackCorr trigger INT7\n");
    task1->SetEventTriggerMask(AliVEvent::kINT7);
   }
   else if(fTrigger=="EMC1"){
    printf("CaloTrackCorr trigger EMC1\n");
    task1->SetEventTriggerMask(AliVEvent::kEMC1);
   }
   else if(fTrigger=="MB"){
    printf("CaloTrackCorr trigger MB\n");
    task1->SetEventTriggerMask(AliVEvent::kMB);
   }
   else if(fTrigger=="AnyINT"){
    printf("CaloTrackCorr trigger AnyINT\n");
    task1->SetEventTriggerMask(AliVEvent::kAnyINT);
   }
   else if(fTrigger=="EMCEGA"){
    printf("CaloTrackCorr trigger EMC Gamma\n");
    task1->SetEventTriggerMask(AliVEvent::kEMCEGA);
   }
   else if(fTrigger=="EMCEJE"){
    printf("CaloTrackCorr trigger EMC Jet\n");
    task1->SetEventTriggerMask(AliVEvent::kEMCEJE);
   }
   else if(fTrigger=="Central"){
    printf("CaloTrackCorr trigger Central\n");
    task1->SetEventTriggerMask(AliVEvent::kCentral);
   }
   else if(fTrigger=="SemiCentral"){
    printf("CaloTrackCorr trigger SemiCentral\n");
    task1->SetEventTriggerMask(AliVEvent::kSemiCentral);
   }
   else if(fTrigger=="SemiOrCentral"){
    printf("CaloTrackCorr trigger SemiCentral Or Central\n");
    task->SetEventTriggerMask(AliVEvent::kSemiCentral | AliVEvent::kCentral);
   }
   else{
    task1->SetEventTriggerMask(AliVEvent::kAny);
   }

  }
  else {
   task1->SwitchOnEventTriggerAtSE();
   if(fTrigger=="EMC7"){
    printf("CaloTrackCorr trigger EMC7\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMC7);
   }
   else if (fTrigger=="INT7"){
    printf("CaloTrackCorr trigger INT7\n");
    task1->SelectCollisionCandidates(AliVEvent::kINT7);
   }
   else if(fTrigger=="EMC1"){
    printf("CaloTrackCorr trigger EMC1\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMC1);
   }
   else if(fTrigger=="MB"){
    printf("CaloTrackCorr trigger MB\n");
    task1->SelectCollisionCandidates(AliVEvent::kMB);
   }
   else if(fTrigger=="AnyINT"){
    printf("CaloTrackCorr trigger AnyINT\n");
    task1->SelectCollisionCandidates(AliVEvent::kAnyINT);
   }
   else if(fTrigger=="EMCEGA"){
    printf("CaloTrackCorr trigger EMC Gamma\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMCEGA);
   }
   else if(fTrigger=="EMCEJE"){
    printf("CaloTrackCorr trigger EMC Jet\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMCEJE);
   }
   else if(fTrigger=="Central"){
    printf("CaloTrackCorr trigger Central\n");
    task1->SelectCollisionCandidates(AliVEvent::kCentral);
   }
   else if(fTrigger=="SemiCentral"){
    printf("CaloTrackCorr trigger SemiCentral\n");
    task1->SelectCollisionCandidates(AliVEvent::kSemiCentral);
   }
   else if(fTrigger=="SemiOrCentral"){
    printf("CaloTrackCorr trigger SemiCentral Or Central\n");
    task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kCentral);
   }
   else{
    task1->SelectCollisionCandidates(AliVEvent::kAny);
   }
  }

}
<commit_msg>changes from xzhu<commit_after>Bool_t   kSimulation    = kFALSE;
TString  fDataType      = "AOD";
Int_t    kYears         = 2011;
TString  kCollisions    = "PbPb";
TString  fTrigger       = "EMCGA";
Bool_t   kEventTriggerAtTaskSE = kFALSE;
Float_t  fMinCen        = -1;
Float_t  fMaxCen        = -1;
TString  fAnaMesonType  = "Pi0";
Bool_t   kAnaPhotonCorr = kTRUE;
Bool_t   kAnaMesonCorr  = kFALSE;
Bool_t   kTimeCut      = kFALSE;
Bool_t   kDistBC       = kTRUE;
Bool_t   kRecalClus    = kTRUE;
Bool_t   kRecalClusE   = kTRUE;
Bool_t   kRecalClusPos = kTRUE;
Bool_t   kRecalClusSSA = kTRUE;
Bool_t   kNonLin       = kTRUE;
Bool_t   kTM           = kFALSE;
Float_t  fDPhiCut      = 0.03;
Float_t  fDEtaCut      = 0.025;
Bool_t   kExotic       = kTRUE;
Float_t  fExoticFraction = 0.95;///for pp:0.97, for PbPb:0.95
Bool_t   kFidul          = kFALSE;
Bool_t   kReClusterier   = kFALSE;
TString  fName           = "V2";
Float_t  fMinCell        = 0.1;
Float_t  fMinSeed        = 0.3;

AliAnalysisTaskEMCALCaloTrackCorr *AddTaskEmcalCaloTrackCorr(
  const TString  data          = "AOD",
  const TString  coll          = "pp",
  const Bool_t   simulation    = kFALSE,
  const TString  trigger       = "MB",
  const Bool_t   triggerSE     = kFALSE,
  const Float_t  minCen        = -1,
  const Float_t  maxCen        = -1,
  const Bool_t   anaPhotonCorr = kTRUE,
  const Bool_t   anaMesonCorr  = kFALSE,
  const TString  anaMesonType  = "Pi0",
  const Bool_t   timecut       = kFALSE,
  const Bool_t   tm            = kFALSE,
  const Float_t  dphicut       = 0.03,
  const Float_t  detacut       = 0.025,
  const Bool_t   exotic       = kTRUE,
  const Float_t  exoticFraction = 0.95,
  const Bool_t   reClusterizer  = kFALSE,
  const TString  name          = "V2",
  const Float_t  minCell       = 0.1,
  const Float_t  minSeed       = 0.3)
{
  fDataType      = data;
  kCollisions    = coll;
  kSimulation    = simulation;
  fTrigger       = trigger;
  kEventTriggerAtTaskSE = triggerSE;
  fMinCen        = minCen;
  fMaxCen        = maxCen;
  fAnaMesonType  = anaMesonType;
  kAnaPhotonCorr = anaPhotonCorr;
  kAnaMesonCorr  = anaMesonCorr;
  kTimeCut      = timecut;
  kTM           = tm;
  fDPhiCut      = dphicut;
  fDEtaCut      = detacut;
  kExotic       = exotic;
  fExoticFraction = exoticFraction;
  kReClusterier   = reClusterizer;
  fName           = name;
  fMinCell        = minCell;
  fMinSeed        = minSeed;

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

  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskHadCorr", "This task requires an input event handler");
    return NULL;
  }

  if(fDataType == "ESD"){
   gROOT->LoadMacro("$ALICE_ROOT/PWGJE/macros/CreateTrackCutsPWGJE.C");
   AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10041004);
   esdTrackCuts->SetEtaRange(-0.8,0.8);
  }

  AliAnalysisTaskEMCALCaloTrackCorr *task = new AliAnalysisTaskEMCALCaloTrackCorr("NeutralCorr");
  task->SetMC(kSimulation);
  task->SetDataType(fDataType);
  if(fDataType == "ESD")task->SetTrackCuts(esdTrackCuts);
  if(fDataType == "AOD") task->SwitchOnAODHybridTrackSelection();
  task->SetTrackMatchedDPhiCut(fDPhiCut);
  task->SetTrackMatchedDEtaCut(fDEtaCut);
  task->SetLargeCorrTrigger(5, 50);

  if(kAnaPhotonCorr && !kAnaMesonCorr){
   task->SwitchOnAnaPhotonCorr();
   task->SwitchOffAnaMesonCorr();
   task->SwitchOffFillMesonAOD();
  }
  else if(!kAnaPhotonCorr && kAnaMesonCorr){
   task->SwitchOffAnaPhotonCorr();
   task->SwitchOnAnaMesonCorr();
   task->SetAnaMesonType(fAnaMesonType);
   task->SwitchOnFillMesonAOD();
  }
  else {
   task->SwitchOffAnaPhotonCorr();
   task->SwitchOffAnaMesonCorr();
  }

  task->SetCentralityClass("V0M");
  task->SetCentralityBin(fMinCen,fMaxCen);
  task->SetEventPlaneMethod("V0");
  task->SetEMCALGeometryName("EMCAL_COMPLETEV1");
  mgr->AddTask(task);

  if(kCollisions =="pp")   task->SwitchOnTrackMultBins();
  if(kCollisions =="PbPb") task->SwitchOffTrackMultBins();

  task->SetDeltaPhiCutRange(TMath::Pi()/2., 3*TMath::Pi()/2.);
  task->SetNTriggPtBins(2);
  Float_t fTriggerPtBins[3]={8,15,25};
  task->SetTriggerBins(fTriggerPtBins);
  task->SetNAssocPtBins(5);
  Float_t fAssociatedPtBins[6]={0.5, 1, 2, 4, 6, 15};
  task->SetAssociatedBins(fAssociatedPtBins);

  ConfigureTrigger(task);

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

 if(kAnaPhotonCorr && !kAnaMesonCorr) {
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusivePhotonCen%.1f_%.1f",fMinCen, fMaxCen), TList::Class(),
                            AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
   else if (!kAnaPhotonCorr && kAnaMesonCorr){
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("Inclusive%sCen%.1f_%.1f", fAnaMesonType.Data(),fMinCen, fMaxCen), TList::Class(),
                             AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
   else {
    AliAnalysisDataContainer *coutputpt1 = mgr->CreateContainer(Form("InclusiveNoCorrCen%.1f_%.1f", fMinCen, fMaxCen), TList::Class(),
                             AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
   }
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutputpt1);
    return task;

}

void ConfigureTrigger(AliAnalysisTaskEMCALCaloTrackCorr *task1)
{
  if(!kEventTriggerAtTaskSE){
   task1->SwitchOffEventTriggerAtSE();
   if(fTrigger=="EMC7"){
    printf("CaloTrackCorr trigger EMC7\n");
    task1->SetEventTriggerMask(AliVEvent::kEMC7);
   }
   else if (fTrigger=="INT7"){
    printf("CaloTrackCorr trigger INT7\n");
    task1->SetEventTriggerMask(AliVEvent::kINT7);
   }
   else if(fTrigger=="EMC1"){
    printf("CaloTrackCorr trigger EMC1\n");
    task1->SetEventTriggerMask(AliVEvent::kEMC1);
   }
   else if(fTrigger=="MB"){
    printf("CaloTrackCorr trigger MB\n");
    task1->SetEventTriggerMask(AliVEvent::kMB);
   }
   else if(fTrigger=="AnyINT"){
    printf("CaloTrackCorr trigger AnyINT\n");
    task1->SetEventTriggerMask(AliVEvent::kAnyINT);
   }
   else if(fTrigger=="EMCEGA"){
    printf("CaloTrackCorr trigger EMC Gamma\n");
    task1->SetEventTriggerMask(AliVEvent::kEMCEGA);
   }
   else if(fTrigger=="EMCEJE"){
    printf("CaloTrackCorr trigger EMC Jet\n");
    task1->SetEventTriggerMask(AliVEvent::kEMCEJE);
   }
   else if(fTrigger=="Central"){
    printf("CaloTrackCorr trigger Central\n");
    task1->SetEventTriggerMask(AliVEvent::kCentral);
   }
   else if(fTrigger=="SemiCentral"){
    printf("CaloTrackCorr trigger SemiCentral\n");
    task1->SetEventTriggerMask(AliVEvent::kSemiCentral);
   }
   else if(fTrigger=="SemiOrCentral"){
    printf("CaloTrackCorr trigger SemiCentral Or Central\n");
    task->SetEventTriggerMask(AliVEvent::kSemiCentral | AliVEvent::kCentral);
   }
   else{
    task1->SetEventTriggerMask(AliVEvent::kAny);
   }

  }
  else {
   task1->SwitchOnEventTriggerAtSE();
   if(fTrigger=="EMC7"){
    printf("CaloTrackCorr trigger EMC7\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMC7);
   }
   else if (fTrigger=="INT7"){
    printf("CaloTrackCorr trigger INT7\n");
    task1->SelectCollisionCandidates(AliVEvent::kINT7);
   }
   else if(fTrigger=="EMC1"){
    printf("CaloTrackCorr trigger EMC1\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMC1);
   }
   else if(fTrigger=="MB"){
    printf("CaloTrackCorr trigger MB\n");
    task1->SelectCollisionCandidates(AliVEvent::kMB);
   }
   else if(fTrigger=="AnyINT"){
    printf("CaloTrackCorr trigger AnyINT\n");
    task1->SelectCollisionCandidates(AliVEvent::kAnyINT);
   }
   else if(fTrigger=="EMCEGA"){
    printf("CaloTrackCorr trigger EMC Gamma\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMCEGA);
   }
   else if(fTrigger=="EMCEJE"){
    printf("CaloTrackCorr trigger EMC Jet\n");
    task1->SelectCollisionCandidates(AliVEvent::kEMCEJE);
   }
   else if(fTrigger=="Central"){
    printf("CaloTrackCorr trigger Central\n");
    task1->SelectCollisionCandidates(AliVEvent::kCentral);
   }
   else if(fTrigger=="SemiCentral"){
    printf("CaloTrackCorr trigger SemiCentral\n");
    task1->SelectCollisionCandidates(AliVEvent::kSemiCentral);
   }
   else if(fTrigger=="SemiOrCentral"){
    printf("CaloTrackCorr trigger SemiCentral Or Central\n");
    task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kCentral);
   }
   else{
    task1->SelectCollisionCandidates(AliVEvent::kAny);
   }
  }

}
<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2017, Balazs Racz
 * 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.
 *
 * 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.
 *
 * \file CallableFlow.hxx
 *
 * Base class for State Flows that can be called as a subflow from a state
 * flow.
 *
 * @author Balazs Racz
 * @date 4 Feb 2017
 */

#ifndef _EXECUTOR_CALLABLEFLOW_HXX_
#define _EXECUTOR_CALLABLEFLOW_HXX_

#include "executor/StateFlow.hxx"

/// All callable flow request objects have to derive from this struct.
struct CallableFlowRequestBase {
    /// Call this from all instances of reset(...).
    void reset_base() {
        resultCode = 0;
    }

    /// If high bits are zero, this is a 16-bit OpenLCB result code. Higher
    /// values are OpenMRN errors.
    int resultCode;
    /// Used internally by the invoke_subflow mechanism of StateFlow to notify
    /// the calling flow upon completion.
    BarrierNotifiable done;
};

template<class RequestType> class CallableFlow : public StateFlow<Buffer<RequestType>, QList<1> > {
public:
    /// Creates a callable flow. @param s defines the service we are operating
    /// upon.
    CallableFlow(Service* s) :  StateFlow<Buffer<RequestType>, QList<1> >(s) {}

protected:
    using Action = StateFlowBase::Action;

    /// @return the current request we are working on.
    RequestType* request() {
        return this->message()->data();
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an error code of OK (zero).
    Action return_ok()
    {
        return return_with_error(0);
    }

    /// Waits to be notified before moving onto the next state for termination.
    Action wait_and_return_ok()
    {
        return this->wait_and_call(STATE(wait_done));
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an error code of OK (zero).
    Action wait_done()
    {
        return return_ok();
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an specific error code.
    Action return_with_error(int error)
    {
        request()->resultCode = error;
        this->return_buffer();
        return this->exit();
    }
};

/** Helper function for testing flow invocations. */
template<class T, typename... Args>
BufferPtr<T> invoke_flow(FlowInterface<Buffer<T>>* flow, Args &&... args) {
    SyncNotifiable n;
    BufferPtr<T> b(flow->alloc());
    b->data()->reset(std::forward<Args>(args)...);
    b->data()->done.reset(&n);
    flow->send(b->ref());
    n.wait_for_notification();
    return b;
}

#endif // _EXECUTOR_CALLABLEFLOW_HXX_
<commit_msg>Fixes nullptr bug in CallableFlow. (#630)<commit_after>/** \copyright
 * Copyright (c) 2017, Balazs Racz
 * 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.
 *
 * 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.
 *
 * \file CallableFlow.hxx
 *
 * Base class for State Flows that can be called as a subflow from a state
 * flow.
 *
 * @author Balazs Racz
 * @date 4 Feb 2017
 */

#ifndef _EXECUTOR_CALLABLEFLOW_HXX_
#define _EXECUTOR_CALLABLEFLOW_HXX_

#include "executor/StateFlow.hxx"

/// All callable flow request objects have to derive from this struct.
struct CallableFlowRequestBase {
    /// Call this from all instances of reset(...).
    void reset_base() {
        resultCode = 0;
    }

    /// If high bits are zero, this is a 16-bit OpenLCB result code. Higher
    /// values are OpenMRN errors.
    int resultCode;
    /// Used internally by the invoke_subflow mechanism of StateFlow to notify
    /// the calling flow upon completion.
    BarrierNotifiable done;
};

template<class RequestType> class CallableFlow : public StateFlow<Buffer<RequestType>, QList<1> > {
public:
    /// Creates a callable flow. @param s defines the service we are operating
    /// upon.
    CallableFlow(Service* s) :  StateFlow<Buffer<RequestType>, QList<1> >(s) {}

protected:
    using Action = StateFlowBase::Action;

    /// @return the current request we are working on.
    RequestType* request() {
        return this->message() ? this->message()->data() : nullptr;
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an error code of OK (zero).
    Action return_ok()
    {
        return return_with_error(0);
    }

    /// Waits to be notified before moving onto the next state for termination.
    Action wait_and_return_ok()
    {
        return this->wait_and_call(STATE(wait_done));
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an error code of OK (zero).
    Action wait_done()
    {
        return return_ok();
    }

    /// Terminates the flow and returns the request buffer to the caller with
    /// an specific error code.
    Action return_with_error(int error)
    {
        request()->resultCode = error;
        this->return_buffer();
        return this->exit();
    }
};

/** Helper function for testing flow invocations. */
template<class T, typename... Args>
BufferPtr<T> invoke_flow(FlowInterface<Buffer<T>>* flow, Args &&... args) {
    SyncNotifiable n;
    BufferPtr<T> b(flow->alloc());
    b->data()->reset(std::forward<Args>(args)...);
    b->data()->done.reset(&n);
    flow->send(b->ref());
    n.wait_for_notification();
    return b;
}

#endif // _EXECUTOR_CALLABLEFLOW_HXX_
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP
#define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP

#include <stan/math/rev/core/chainablestack.hpp>

#include <tbb/task_scheduler_observer.h>

#include <mutex>
#include <unordered_map>
#include <utility>
#include <thread>
#include <tuple>

namespace stan {
namespace math {

/**
 * TBB observer object which is a callback hook called whenever the
 * TBB scheduler adds a new thread to the TBB managed threadpool. This
 * hook ensures that each worker thread has an initialized AD tape
 * ready for use.
 *
 * Refer to https://software.intel.com/en-us/node/506314 for details
 * on the observer concept.
 */
class ad_tape_observer : public tbb::task_scheduler_observer {
  using stack_ptr = std::unique_ptr<ChainableStack>;
  using ad_map = std::unordered_map<std::thread::id, stack_ptr>;

 public:
  ad_tape_observer() : tbb::task_scheduler_observer(), thread_tape_map_() {
    on_scheduler_entry(true);  // register current process
    observe(true);             // activates the observer
  }

  void on_scheduler_entry(bool worker) {
    std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
    const std::thread::id thread_id = std::this_thread::get_id();
    if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) {
      ad_map::iterator insert_elem;
      bool status = false;
      std::tie(insert_elem, status)
          = thread_tape_map_.emplace(ad_map::value_type{thread_id, nullptr});
      insert_elem->second = stack_ptr(new ChainableStack());
    }
  }

  void on_scheduler_exit(bool worker) {
    std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
    auto elem = thread_tape_map_.find(std::this_thread::get_id());
    if (elem != thread_tape_map_.end()) {
      thread_tape_map_.erase(elem);
    }
  }

 private:
  ad_map thread_tape_map_;
  std::mutex thread_tape_map_mutex_;
};

namespace {

ad_tape_observer global_observer;

}  // namespace
}  // namespace math
}  // namespace stan

#endif
<commit_msg>Fixed #1637 Merge pull request #1638 from stan-dev/bugfix/issue-1637<commit_after>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP
#define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP

#include <stan/math/rev/core/chainablestack.hpp>

#include <tbb/task_scheduler_observer.h>

#include <mutex>
#include <unordered_map>
#include <utility>
#include <thread>
#include <tuple>

namespace stan {
namespace math {

/**
 * TBB observer object which is a callback hook called whenever the
 * TBB scheduler adds a new thread to the TBB managed threadpool. This
 * hook ensures that each worker thread has an initialized AD tape
 * ready for use.
 *
 * Refer to https://software.intel.com/en-us/node/506314 for details
 * on the observer concept.
 */
class ad_tape_observer : public tbb::task_scheduler_observer {
  using stack_ptr = std::unique_ptr<ChainableStack>;
  using ad_map = std::unordered_map<std::thread::id, stack_ptr>;

 public:
  ad_tape_observer() : tbb::task_scheduler_observer(), thread_tape_map_() {
    on_scheduler_entry(true);  // register current process
    observe(true);             // activates the observer
  }

  ~ad_tape_observer() { observe(false); }

  void on_scheduler_entry(bool worker) {
    std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
    const std::thread::id thread_id = std::this_thread::get_id();
    if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) {
      ad_map::iterator insert_elem;
      bool status = false;
      std::tie(insert_elem, status)
          = thread_tape_map_.emplace(ad_map::value_type{thread_id, nullptr});
      insert_elem->second = stack_ptr(new ChainableStack());
    }
  }

  void on_scheduler_exit(bool worker) {
    std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
    auto elem = thread_tape_map_.find(std::this_thread::get_id());
    if (elem != thread_tape_map_.end()) {
      thread_tape_map_.erase(elem);
    }
  }

 private:
  ad_map thread_tape_map_;
  std::mutex thread_tape_map_mutex_;
};

namespace {

ad_tape_observer global_observer;

}  // namespace
}  // namespace math
}  // namespace stan

#endif
<|endoftext|>