<commit_before>#include <cppurses/terminal/terminal.hpp>

#include <clocale>
#include <csignal>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>

#include <ncurses.h>
#include <signal.h>
#include <string.h>

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/color_definition.hpp>
#include <cppurses/painter/palette.hpp>
#include <cppurses/painter/rgb.hpp>
#include <cppurses/system/system.hpp>
#include <cppurses/terminal/input.hpp>

extern "C" void handle_sigint(int /* sig*/) {
    cppurses::System::terminal.uninitialize();
#if !defined __APPLE__
    std::quick_exit(0);
#else
    std::exit(0);
#endif
}

namespace {
using namespace cppurses;

Underlying_color_t scale(Underlying_color_t value) {
    const auto value_max = 255;
    const auto ncurses_max = 1000;
    return static_cast<Underlying_color_t>(
        (static_cast<double>(value) / value_max) * ncurses_max);
}
}  // namespace

namespace cppurses {

void Terminal::initialize() {
    if (is_initialized_) {
        return;
    }
    std::signal(SIGINT, &handle_sigint);
    this->setup_resize_signal_handler();
    std::setlocale(LC_ALL, "en_US.UTF-8");

    if (::newterm(std::getenv("TERM"), stdout, stdin) == nullptr) {
        if (::newterm("xterm-256color", stdout, stdin) == nullptr) {
            throw std::runtime_error{"Unable to initialize screen."};
        }
    }

    is_initialized_ = true;
    ::noecho();
    ::keypad(::stdscr, true);
    ::ESCDELAY = 1;
    ::mousemask(ALL_MOUSE_EVENTS, nullptr);
    ::mouseinterval(0);
    if (this->has_color()) {
        ::start_color();
        this->initialize_color_pairs();
        this->ncurses_set_palette(palette_);
    }
    this->ncurses_set_raw_mode();
    this->ncurses_set_cursor();
}

void Terminal::uninitialize() {
    if (!is_initialized_) {
        return;
    }
    ::wrefresh(::stdscr);
    is_initialized_ = false;
    ::endwin();
}

// getmaxx/getmaxy are non-standard.
std::size_t Terminal::width() const {
    int y{0};
    int x{0};
    if (is_initialized_) {
        getmaxyx(::stdscr, y, x);
    }
    return x;
}

std::size_t Terminal::height() const {
    int y{0};
    int x{0};
    if (is_initialized_) {
        getmaxyx(::stdscr, y, x);
    }
    return y;
}

void Terminal::resize(std::size_t width, std::size_t height) {
    if (is_initialized_) {
        ::resizeterm(height, width);  // glitch here w/multi-thread?
    }
}

void Terminal::set_background(const Glyph& tile) {
    background_ = tile;
    if (is_initialized_) {
        // TODO Notify Screen::flush() to repaint everything.
    }
}

void Terminal::set_color_palette(const Palette& colors) {
    palette_ = colors;
    if (is_initialized_ && this->has_color()) {
        this->ncurses_set_palette(palette_);
    }
}

void Terminal::show_cursor(bool show) {
    show_cursor_ = show;
    if (is_initialized_) {
        this->ncurses_set_cursor();
    }
}

void Terminal::raw_mode(bool enable) {
    raw_mode_ = enable;
    if (is_initialized_) {
        this->ncurses_set_raw_mode();
    }
}

bool Terminal::has_color() const {
    if (is_initialized_) {
        return ::has_colors() == TRUE;
    }
    return false;
}

bool Terminal::has_extended_colors() const {
    if (is_initialized_) {
        return COLORS >= 16;
    }
    return false;
}

short Terminal::color_count() const {
    if (is_initialized_) {
        return COLORS;
    }
    return 0;
}

bool Terminal::can_change_colors() const {
    if (is_initialized_) {
        return ::can_change_color() == TRUE;
    }
    return false;
}

short Terminal::color_pair_count() const {
    if (is_initialized_) {
        return COLOR_PAIRS;
    }
    return 0;
}

short Terminal::color_index(short fg, short bg) const {
    if (fg == 7 && bg == 0) {
        return 0;
    }
    if (fg == 15 && bg == 0) {
        return 128;
    }
    const short max_color = this->has_extended_colors() ? 16 : 8;
    return ((max_color - 1) - fg) * max_color + bg;
}

void Terminal::use_default_colors(bool use) {
    if (!is_initialized_) {
        return;
    }
    if (use) {
        ::assume_default_colors(-1, -1);
        init_default_pairs();
    } else {
        ::assume_default_colors(7, 0);
        uninit_default_pairs();
    }
}

void Terminal::setup_resize_signal_handler() const {
    struct sigaction sa;
    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_handler = input::indicate_resize;
    sigaction(SIGWINCH, &sa, NULL);
}

void Terminal::ncurses_set_palette(const Palette& colors) {
    if (this->can_change_colors()) {
        for (const Color_definition& def : colors) {
            const auto max_color = this->has_extended_colors() ? 16 : 8;
            const auto ncurses_color_number =
                static_cast<Underlying_color_t>(def.color);
            if (ncurses_color_number < max_color) {
                ::init_color(ncurses_color_number, scale(def.values.red),
                             scale(def.values.green), scale(def.values.blue));
            }
        }
    }
}

void Terminal::ncurses_set_raw_mode() const {
    if (raw_mode_) {
        ::nocbreak();
        ::raw();
    } else {
        ::noraw();
        ::cbreak();
    }
}

void Terminal::ncurses_set_cursor() const {
    show_cursor_ ? ::curs_set(1) : ::curs_set(0);
}

void Terminal::initialize_color_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (short fg = 0; fg < max_color; ++fg) {
        for (short bg = 0; bg < max_color; ++bg) {
            const auto index = color_index(fg, bg);
            if (index == 0) {
                continue;
            }
            ::init_pair(index, fg, bg);
        }
    }
}

void Terminal::init_default_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (Underlying_color_t bg = 1; bg < max_color; ++bg) {
        ::init_pair(color_index(7, bg), -1, bg);
    }
    for (Underlying_color_t fg = 0; fg < max_color; ++fg) {
        if (fg != 7) {
            ::init_pair(color_index(fg, 0), fg, -1);
        }
    }
}

void Terminal::uninit_default_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (Underlying_color_t bg = 0; bg < max_color; ++bg) {
        ::init_pair(color_index(7, bg), 7, bg);
    }
    for (Underlying_color_t fg = 0; fg < max_color; ++fg) {
        if (fg != 7) {
            ::init_pair(color_index(fg, 0), fg, 0);
        }
    }
}

}  // namespace cppurses
<commit_msg>Rearrange signal handling code in terminal.cpp to come after ::initscr<commit_after>#include <cppurses/terminal/terminal.hpp>

#include <clocale>
#include <csignal>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>

#include <ncurses.h>
#include <signal.h>
#include <string.h>

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/color_definition.hpp>
#include <cppurses/painter/palette.hpp>
#include <cppurses/painter/rgb.hpp>
#include <cppurses/system/system.hpp>
#include <cppurses/terminal/input.hpp>

extern "C" void handle_sigint(int /* sig*/) {
    cppurses::System::terminal.uninitialize();
#if !defined __APPLE__
    std::quick_exit(0);
#else
    std::exit(0);
#endif
}

namespace {
using namespace cppurses;

Underlying_color_t scale(Underlying_color_t value) {
    const auto value_max = 255;
    const auto ncurses_max = 1000;
    return static_cast<Underlying_color_t>(
        (static_cast<double>(value) / value_max) * ncurses_max);
}
}  // namespace

namespace cppurses {

void Terminal::initialize() {
    if (is_initialized_) {
        return;
    }
    std::setlocale(LC_ALL, "en_US.UTF-8");

    if (::newterm(std::getenv("TERM"), stdout, stdin) == nullptr) {
        if (::newterm("xterm-256color", stdout, stdin) == nullptr) {
            throw std::runtime_error{"Unable to initialize screen."};
        }
    }
    std::signal(SIGINT, &handle_sigint);
    this->setup_resize_signal_handler();

    is_initialized_ = true;
    ::noecho();
    ::keypad(::stdscr, true);
    ::ESCDELAY = 1;
    ::mousemask(ALL_MOUSE_EVENTS, nullptr);
    ::mouseinterval(0);
    if (this->has_color()) {
        ::start_color();
        this->initialize_color_pairs();
        this->ncurses_set_palette(palette_);
    }
    this->ncurses_set_raw_mode();
    this->ncurses_set_cursor();
}

void Terminal::uninitialize() {
    if (!is_initialized_) {
        return;
    }
    ::wrefresh(::stdscr);
    is_initialized_ = false;
    ::endwin();
}

// getmaxx/getmaxy are non-standard.
std::size_t Terminal::width() const {
    int y{0};
    int x{0};
    if (is_initialized_) {
        getmaxyx(::stdscr, y, x);
    }
    return x;
}

std::size_t Terminal::height() const {
    int y{0};
    int x{0};
    if (is_initialized_) {
        getmaxyx(::stdscr, y, x);
    }
    return y;
}

void Terminal::resize(std::size_t width, std::size_t height) {
    if (is_initialized_) {
        ::resizeterm(height, width);  // glitch here w/multi-thread?
    }
}

void Terminal::set_background(const Glyph& tile) {
    background_ = tile;
    if (is_initialized_) {
        // TODO Notify Screen::flush() to repaint everything.
    }
}

void Terminal::set_color_palette(const Palette& colors) {
    palette_ = colors;
    if (is_initialized_ && this->has_color()) {
        this->ncurses_set_palette(palette_);
    }
}

void Terminal::show_cursor(bool show) {
    show_cursor_ = show;
    if (is_initialized_) {
        this->ncurses_set_cursor();
    }
}

void Terminal::raw_mode(bool enable) {
    raw_mode_ = enable;
    if (is_initialized_) {
        this->ncurses_set_raw_mode();
    }
}

bool Terminal::has_color() const {
    if (is_initialized_) {
        return ::has_colors() == TRUE;
    }
    return false;
}

bool Terminal::has_extended_colors() const {
    if (is_initialized_) {
        return COLORS >= 16;
    }
    return false;
}

short Terminal::color_count() const {
    if (is_initialized_) {
        return COLORS;
    }
    return 0;
}

bool Terminal::can_change_colors() const {
    if (is_initialized_) {
        return ::can_change_color() == TRUE;
    }
    return false;
}

short Terminal::color_pair_count() const {
    if (is_initialized_) {
        return COLOR_PAIRS;
    }
    return 0;
}

short Terminal::color_index(short fg, short bg) const {
    if (fg == 7 && bg == 0) {
        return 0;
    }
    if (fg == 15 && bg == 0) {
        return 128;
    }
    const short max_color = this->has_extended_colors() ? 16 : 8;
    return ((max_color - 1) - fg) * max_color + bg;
}

void Terminal::use_default_colors(bool use) {
    if (!is_initialized_) {
        return;
    }
    if (use) {
        ::assume_default_colors(-1, -1);
        init_default_pairs();
    } else {
        ::assume_default_colors(7, 0);
        uninit_default_pairs();
    }
}

void Terminal::setup_resize_signal_handler() const {
    struct sigaction sa;
    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_handler = input::indicate_resize;
    sigaction(SIGWINCH, &sa, NULL);
}

void Terminal::ncurses_set_palette(const Palette& colors) {
    if (this->can_change_colors()) {
        for (const Color_definition& def : colors) {
            const auto max_color = this->has_extended_colors() ? 16 : 8;
            const auto ncurses_color_number =
                static_cast<Underlying_color_t>(def.color);
            if (ncurses_color_number < max_color) {
                ::init_color(ncurses_color_number, scale(def.values.red),
                             scale(def.values.green), scale(def.values.blue));
            }
        }
    }
}

void Terminal::ncurses_set_raw_mode() const {
    if (raw_mode_) {
        ::nocbreak();
        ::raw();
    } else {
        ::noraw();
        ::cbreak();
    }
}

void Terminal::ncurses_set_cursor() const {
    show_cursor_ ? ::curs_set(1) : ::curs_set(0);
}

void Terminal::initialize_color_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (short fg = 0; fg < max_color; ++fg) {
        for (short bg = 0; bg < max_color; ++bg) {
            const auto index = color_index(fg, bg);
            if (index == 0) {
                continue;
            }
            ::init_pair(index, fg, bg);
        }
    }
}

void Terminal::init_default_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (Underlying_color_t bg = 1; bg < max_color; ++bg) {
        ::init_pair(color_index(7, bg), -1, bg);
    }
    for (Underlying_color_t fg = 0; fg < max_color; ++fg) {
        if (fg != 7) {
            ::init_pair(color_index(fg, 0), fg, -1);
        }
    }
}

void Terminal::uninit_default_pairs() const {
    Underlying_color_t max_color = this->has_extended_colors() ? 16 : 8;
    for (Underlying_color_t bg = 0; bg < max_color; ++bg) {
        ::init_pair(color_index(7, bg), 7, bg);
    }
    for (Underlying_color_t fg = 0; fg < max_color; ++fg) {
        if (fg != 7) {
            ::init_pair(color_index(fg, 0), fg, 0);
        }
    }
}
}  // namespace cppurses
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of [LCIOWriter] module
 * @copyright MIT License
 */

#include "LCIOWriterModule.hpp"

#include <string>
#include <utility>
#include <vector>

#include "core/messenger/Messenger.hpp"

#include "core/utils/log.h"

#include <IMPL/LCCollectionVec.h>
#include <IMPL/LCEventImpl.h>
#include <IMPL/LCRunHeaderImpl.h>
#include <IMPL/TrackerDataImpl.h>
#include <IO/LCWriter.h>
#include <IOIMPL/LCFactory.h>
#include <UTIL/CellIDEncoder.h>
#include <lcio.h>

using namespace allpix;
using namespace lcio;

LCIOWriterModule::LCIOWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo)
    : Module(config), config_(std::move(config)) {
    // ... Implement ... (Typically bounds the required messages and optionally sets configuration defaults)
    LOG(TRACE) << "Initializing module " << getUniqueName();
    // Bind pixel hits message
    messenger->bindMulti(this, &LCIOWriterModule::pixel_messages_, MsgFlags::REQUIRED);

    // get all detector names and assign id.
    std::vector<std::shared_ptr<Detector>> detectors = geo->getDetectors();
    unsigned int i = 0;
    for(const auto& det : detectors) {
        detectorIDs[det->getName()] = i;
        LOG(DEBUG) << det->getName() << " has ID " << detectorIDs[det->getName()];
        i++;
    }

    _pixelType = config_.get<int>("pixelType", 2),

    // Open LCIO file and write run header
        lcWriter = LCFactory::getInstance()->createLCWriter();
    lcWriter->open(config_.get<std::string>("file_name", "output.slcio"), LCIO::WRITE_NEW);
    LCRunHeaderImpl* run = new LCRunHeaderImpl();
    run->setRunNumber(1);
    run->setDetectorName("telescope");
    lcWriter->writeRunHeader(run);
    delete run;
    LOG(DEBUG) << "LCIO run header written";
}

void LCIOWriterModule::run(unsigned int eventNb) {

    // ... Implement ... (Typically uses the configuration to execute function and outputs an message)
    LOG(TRACE) << "Running module " << getUniqueName();
    // LOG(DEBUG) << "Adding hits in " << pixels_message_->getData().size() << " pixels";

    LCEventImpl* evt = new LCEventImpl(); // create the event
    evt->setRunNumber(1);
    evt->setEventNumber(static_cast<int>(eventNb)); // set the event attributes

    // Prepare charge vectors
    std::vector<std::vector<float>> charges;
    for(unsigned int i = 0; i < detectorIDs.size(); i++) {
        std::vector<float> charge;
        charges.push_back(charge);
    }

    // Receive all pixel messages, fill charge vectors
    for(const auto& hit_msg : pixel_messages_) {
        LOG(DEBUG) << hit_msg->getDetector()->getName();
        for(const auto& hitdata : hit_msg->getData()) {
            LOG(DEBUG) << "X: " << hitdata.getPixel().getIndex().x() << ", Y:" << hitdata.getPixel().getIndex().y()
                       << ", Signal: " << hitdata.getSignal();

            unsigned int detectorID = detectorIDs[hit_msg->getDetector()->getName()];

            charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x
            charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y
            charges[detectorID].push_back(static_cast<float>(hitdata.getSignal()));               // signal
            charges[detectorID].push_back(static_cast<float>(0));                                 // time
        }
    }

    // Prepare hitvector
    LCCollectionVec* hitVec = new LCCollectionVec(LCIO::TRACKERDATA);

    // Fill hitvector with event data
    for(unsigned int detectorID = 0; detectorID < detectorIDs.size(); detectorID++) {
        TrackerDataImpl* hit = new TrackerDataImpl();
        CellIDEncoder<TrackerDataImpl> sparseDataEncoder("sensorID:7,sparsePixelType:5", hitVec);
        sparseDataEncoder["sensorID"] = detectorID;
        sparseDataEncoder["sparsePixelType"] = _pixelType;
        sparseDataEncoder.setCellID(hit);
        hit->setChargeValues(charges[detectorID]);
        hitVec->push_back(hit);
    }

    // Add collection to event and write event to LCIO file
    evt->addCollection(hitVec, "original_zsdata"); // add the collection with a name
    lcWriter->writeEvent(evt);                     // write the event to the file
    delete evt;
}

void LCIOWriterModule::finalize() {
    LOG(TRACE) << "Finalizing module " << getUniqueName();
    lcWriter->close();
    delete lcWriter;
}
<commit_msg>Remove debug comments<commit_after>/**
 * @file
 * @brief Implementation of [LCIOWriter] module
 * @copyright MIT License
 */

#include "LCIOWriterModule.hpp"

#include <string>
#include <utility>
#include <vector>

#include "core/messenger/Messenger.hpp"

#include "core/utils/log.h"

#include <IMPL/LCCollectionVec.h>
#include <IMPL/LCEventImpl.h>
#include <IMPL/LCRunHeaderImpl.h>
#include <IMPL/TrackerDataImpl.h>
#include <IO/LCWriter.h>
#include <IOIMPL/LCFactory.h>
#include <UTIL/CellIDEncoder.h>
#include <lcio.h>

using namespace allpix;
using namespace lcio;

LCIOWriterModule::LCIOWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo)
    : Module(config), config_(std::move(config)) {

    // Bind pixel hits message
    messenger->bindMulti(this, &LCIOWriterModule::pixel_messages_, MsgFlags::REQUIRED);

    // get all detector names and assign id.
    std::vector<std::shared_ptr<Detector>> detectors = geo->getDetectors();
    unsigned int i = 0;
    for(const auto& det : detectors) {
        detectorIDs[det->getName()] = i;
        LOG(DEBUG) << det->getName() << " has ID " << detectorIDs[det->getName()];
        i++;
    }

    _pixelType = config_.get<int>("pixelType", 2),

    // Open LCIO file and write run header
        lcWriter = LCFactory::getInstance()->createLCWriter();
    lcWriter->open(config_.get<std::string>("file_name", "output.slcio"), LCIO::WRITE_NEW);
    LCRunHeaderImpl* run = new LCRunHeaderImpl();
    run->setRunNumber(1);
    run->setDetectorName("telescope");
    lcWriter->writeRunHeader(run);
    delete run;
}

void LCIOWriterModule::run(unsigned int eventNb) {

    LCEventImpl* evt = new LCEventImpl(); // create the event
    evt->setRunNumber(1);
    evt->setEventNumber(static_cast<int>(eventNb)); // set the event attributes

    // Prepare charge vectors
    std::vector<std::vector<float>> charges;
    for(unsigned int i = 0; i < detectorIDs.size(); i++) {
        std::vector<float> charge;
        charges.push_back(charge);
    }

    // Receive all pixel messages, fill charge vectors
    for(const auto& hit_msg : pixel_messages_) {
        LOG(DEBUG) << hit_msg->getDetector()->getName();
        for(const auto& hitdata : hit_msg->getData()) {
            LOG(DEBUG) << "X: " << hitdata.getPixel().getIndex().x() << ", Y:" << hitdata.getPixel().getIndex().y()
                       << ", Signal: " << hitdata.getSignal();

            unsigned int detectorID = detectorIDs[hit_msg->getDetector()->getName()];

            charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x
            charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y
            charges[detectorID].push_back(static_cast<float>(hitdata.getSignal()));               // signal
            charges[detectorID].push_back(static_cast<float>(0));                                 // time
        }
    }

    // Prepare hitvector
    LCCollectionVec* hitVec = new LCCollectionVec(LCIO::TRACKERDATA);

    // Fill hitvector with event data
    for(unsigned int detectorID = 0; detectorID < detectorIDs.size(); detectorID++) {
        TrackerDataImpl* hit = new TrackerDataImpl();
        CellIDEncoder<TrackerDataImpl> sparseDataEncoder("sensorID:7,sparsePixelType:5", hitVec);
        sparseDataEncoder["sensorID"] = detectorID;
        sparseDataEncoder["sparsePixelType"] = _pixelType;
        sparseDataEncoder.setCellID(hit);
        hit->setChargeValues(charges[detectorID]);
        hitVec->push_back(hit);
    }

    // Add collection to event and write event to LCIO file
    evt->addCollection(hitVec, "original_zsdata"); // add the collection with a name
    lcWriter->writeEvent(evt);                     // write the event to the file
    delete evt;
}

void LCIOWriterModule::finalize() {
    lcWriter->close();
    delete lcWriter;
}
<|endoftext|>


<commit_before>#include "FileReader.hpp"
#include "FrameReader.hpp"

#include <QtNetwork>

FileReader::FileReader(const QString& file_) : file(file_) {
}

void FileReader::process() {
  timer.start();
  // TODO: Support reading files from the API
  startRequest(QUrl("http://data.comma.life/"+file));
}

void FileReader::startRequest(const QUrl &url) {
  qnam = new QNetworkAccessManager;
  reply = qnam->get(QNetworkRequest(url));
  connect(reply, &QNetworkReply::finished, this, &FileReader::httpFinished);
  connect(reply, &QIODevice::readyRead, this, &FileReader::readyRead);
  qDebug() << "requesting" << url;
}

void FileReader::httpFinished() {
  if (reply->error()) {
    qWarning() << reply->errorString();
  }

  const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
  if (!redirectionTarget.isNull()) {
    const QUrl redirectedUrl = redirectionTarget.toUrl();
    //qDebug() << "redirected to" << redirectedUrl;
    startRequest(redirectedUrl);
  } else {
    qDebug() << "done in" << timer.elapsed() << "ms";
    done();
  }
}

void FileReader::readyRead() {
  QByteArray dat = reply->readAll();
  printf("got http ready read: %d\n", dat.size());
}

FileReader::~FileReader() {

}

LogReader::LogReader(const QString& file, Events *events_, QReadWriteLock* events_lock_, QMap<int, QPair<int, int> > *eidx_) :
    FileReader(file), events(events_), events_lock(events_lock_), eidx(eidx_) {
  bStream.next_in = NULL;
  bStream.avail_in = 0;
  bStream.bzalloc = NULL;
  bStream.bzfree = NULL;
  bStream.opaque = NULL;

  int ret = BZ2_bzDecompressInit(&bStream, 0, 0);
  if (ret != BZ_OK) qWarning() << "bz2 init failed";

  // start with 64MB buffer
  raw.resize(1024*1024*64);

  // auto increment?
  bStream.next_out = raw.data();
  bStream.avail_out = raw.size();

  // parsed no events yet
  event_offset = 0;

  parser = new std::thread([&]() {
    while (1) {
      mergeEvents(cdled.get());
    }
  });
}

void LogReader::mergeEvents(int dled) {
  auto amsg = kj::arrayPtr((const capnp::word*)(raw.data() + event_offset), (dled-event_offset)/sizeof(capnp::word));
  Events events_local;
  QMap<int, QPair<int, int> > eidx_local;

  while (amsg.size() > 0) {
    try {
      capnp::FlatArrayMessageReader cmsg = capnp::FlatArrayMessageReader(amsg);

      // this needed? it is
      capnp::FlatArrayMessageReader *tmsg =
        new capnp::FlatArrayMessageReader(kj::arrayPtr(amsg.begin(), cmsg.getEnd()));

      amsg = kj::arrayPtr(cmsg.getEnd(), amsg.end());

      cereal::Event::Reader event = tmsg->getRoot<cereal::Event>();
      events_local.insert(event.getLogMonoTime(), event);

      // hack
      // TODO: rewrite with callback
      if (event.which() == cereal::Event::ENCODE_IDX) {
        auto ee = event.getEncodeIdx();
        eidx_local.insert(ee.getFrameId(), qMakePair(ee.getSegmentNum(), ee.getSegmentId()));
      }

      // increment
      event_offset = (char*)cmsg.getEnd() - raw.data();
    } catch (const kj::Exception& e) {
      // partial messages trigger this
      //qDebug() << e.getDescription().cStr();
      break;
    }
  }

  // merge in events
  // TODO: add lock
  events_lock->lockForWrite();
  *events += events_local;
  eidx->unite(eidx_local);
  events_lock->unlock();

  printf("parsed %d into %d events with offset %d\n", dled, events->size(), event_offset);
}

void LogReader::readyRead() {
  QByteArray dat = reply->readAll();

  bStream.next_in = dat.data();
  bStream.avail_in = dat.size();

  while (bStream.avail_in > 0) {
    int ret = BZ2_bzDecompress(&bStream);
    if (ret != BZ_OK && ret != BZ_STREAM_END) {
      qWarning() << "bz2 decompress failed";
      break;
    }
    qDebug() << "got" << dat.size() << "with" << bStream.avail_out << "size" << raw.size();
  }

  int dled = raw.size() - bStream.avail_out;
  cdled.put(dled);
}

<commit_msg>[Memory leak]uniq_ptr for tmsg (#985)<commit_after>#include "FileReader.hpp"
#include "FrameReader.hpp"
#include <memory>

#include <QtNetwork>

FileReader::FileReader(const QString& file_) : file(file_) {
}

void FileReader::process() {
  timer.start();
  // TODO: Support reading files from the API
  startRequest(QUrl("http://data.comma.life/"+file));
}

void FileReader::startRequest(const QUrl &url) {
  qnam = new QNetworkAccessManager;
  reply = qnam->get(QNetworkRequest(url));
  connect(reply, &QNetworkReply::finished, this, &FileReader::httpFinished);
  connect(reply, &QIODevice::readyRead, this, &FileReader::readyRead);
  qDebug() << "requesting" << url;
}

void FileReader::httpFinished() {
  if (reply->error()) {
    qWarning() << reply->errorString();
  }

  const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
  if (!redirectionTarget.isNull()) {
    const QUrl redirectedUrl = redirectionTarget.toUrl();
    //qDebug() << "redirected to" << redirectedUrl;
    startRequest(redirectedUrl);
  } else {
    qDebug() << "done in" << timer.elapsed() << "ms";
    done();
  }
}

void FileReader::readyRead() {
  QByteArray dat = reply->readAll();
  printf("got http ready read: %d\n", dat.size());
}

FileReader::~FileReader() {

}

LogReader::LogReader(const QString& file, Events *events_, QReadWriteLock* events_lock_, QMap<int, QPair<int, int> > *eidx_) :
    FileReader(file), events(events_), events_lock(events_lock_), eidx(eidx_) {
  bStream.next_in = NULL;
  bStream.avail_in = 0;
  bStream.bzalloc = NULL;
  bStream.bzfree = NULL;
  bStream.opaque = NULL;

  int ret = BZ2_bzDecompressInit(&bStream, 0, 0);
  if (ret != BZ_OK) qWarning() << "bz2 init failed";

  // start with 64MB buffer
  raw.resize(1024*1024*64);

  // auto increment?
  bStream.next_out = raw.data();
  bStream.avail_out = raw.size();

  // parsed no events yet
  event_offset = 0;

  parser = new std::thread([&]() {
    while (1) {
      mergeEvents(cdled.get());
    }
  });
}

void LogReader::mergeEvents(int dled) {
  auto amsg = kj::arrayPtr((const capnp::word*)(raw.data() + event_offset), (dled-event_offset)/sizeof(capnp::word));
  Events events_local;
  QMap<int, QPair<int, int> > eidx_local;

  while (amsg.size() > 0) {
    try {
      capnp::FlatArrayMessageReader cmsg = capnp::FlatArrayMessageReader(amsg);

      // this needed? it is
      std::unique_ptr<capnp::FlatArrayMessageReader> tmsg(new capnp::FlatArrayMessageReader(kj::arrayPtr(amsg.begin(), cmsg.getEnd()));

      amsg = kj::arrayPtr(cmsg.getEnd(), amsg.end());

      cereal::Event::Reader event = tmsg->getRoot<cereal::Event>();
      events_local.insert(event.getLogMonoTime(), event);

      // hack
      // TODO: rewrite with callback
      if (event.which() == cereal::Event::ENCODE_IDX) {
        auto ee = event.getEncodeIdx();
        eidx_local.insert(ee.getFrameId(), qMakePair(ee.getSegmentNum(), ee.getSegmentId()));
      }

      // increment
      event_offset = (char*)cmsg.getEnd() - raw.data();
    } catch (const kj::Exception& e) {
      // partial messages trigger this
      //qDebug() << e.getDescription().cStr();
      break;
    }
  }

  // merge in events
  // TODO: add lock
  events_lock->lockForWrite();
  *events += events_local;
  eidx->unite(eidx_local);
  events_lock->unlock();

  printf("parsed %d into %d events with offset %d\n", dled, events->size(), event_offset);
}

void LogReader::readyRead() {
  QByteArray dat = reply->readAll();

  bStream.next_in = dat.data();
  bStream.avail_in = dat.size();

  while (bStream.avail_in > 0) {
    int ret = BZ2_bzDecompress(&bStream);
    if (ret != BZ_OK && ret != BZ_STREAM_END) {
      qWarning() << "bz2 decompress failed";
      break;
    }
    qDebug() << "got" << dat.size() << "with" << bStream.avail_out << "size" << raw.size();
  }

  int dled = raw.size() - bStream.avail_out;
  cdled.put(dled);
}

<|endoftext|>


<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <amount.h>
#include <arith_uint256.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <core_io.h>
#include <crypto/common.h>
#include <crypto/siphash.h>
#include <key_io.h>
#include <memusage.h>
#include <netbase.h>
#include <policy/settings.h>
#include <pow.h>
#include <pubkey.h>
#include <rpc/util.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <serialize.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <uint256.h>
#include <util/moneystr.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/time.h>
#include <version.h>

#include <cassert>
#include <limits>
#include <vector>

void initialize()
{
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    if (buffer.size() < sizeof(uint256) + sizeof(uint160)) {
        return;
    }
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256)));
    const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160)));
    const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
    const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
    const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
    const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>();
    const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>();
    const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>();
    const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>();
    const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>();
    // We cannot assume a specific value of std::is_signed<char>::value:
    // ConsumeIntegral<char>() instead of casting from {u,}int8_t.
    const char ch = fuzzed_data_provider.ConsumeIntegral<char>();
    const bool b = fuzzed_data_provider.ConsumeBool();

    const Consensus::Params& consensus_params = Params().GetConsensus();
    (void)CheckProofOfWork(u256, u32, consensus_params);
    if (u64 <= MAX_MONEY) {
        const uint64_t compressed_money_amount = CompressAmount(u64);
        assert(u64 == DecompressAmount(compressed_money_amount));
        static const uint64_t compressed_money_amount_max = CompressAmount(MAX_MONEY - 1);
        assert(compressed_money_amount <= compressed_money_amount_max);
    } else {
        (void)CompressAmount(u64);
    }
    static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000"));
    static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
    const std::vector<uint256> v256{u256, u256_min, u256_max};
    (void)ComputeMerkleRoot(v256);
    (void)CountBits(u64);
    (void)DecompressAmount(u64);
    (void)FormatISO8601Date(i64);
    (void)FormatISO8601DateTime(i64);
    // FormatMoney(i) not defined when i == std::numeric_limits<int64_t>::min()
    if (i64 != std::numeric_limits<int64_t>::min()) {
        int64_t parsed_money;
        if (ParseMoney(FormatMoney(i64), parsed_money)) {
            assert(parsed_money == i64);
        }
    }
    (void)GetSizeOfCompactSize(u64);
    (void)GetSpecialScriptSize(u32);
    // (void)GetVirtualTransactionSize(i64, i64); // function defined only for a subset of int64_t inputs
    // (void)GetVirtualTransactionSize(i64, i64, u32); // function defined only for a subset of int64_t/uint32_t inputs
    (void)HexDigit(ch);
    (void)MoneyRange(i64);
    (void)i64tostr(i64);
    (void)IsDigit(ch);
    (void)IsSpace(ch);
    (void)IsSwitchChar(ch);
    (void)itostr(i32);
    (void)memusage::DynamicUsage(ch);
    (void)memusage::DynamicUsage(i16);
    (void)memusage::DynamicUsage(i32);
    (void)memusage::DynamicUsage(i64);
    (void)memusage::DynamicUsage(i8);
    (void)memusage::DynamicUsage(u16);
    (void)memusage::DynamicUsage(u32);
    (void)memusage::DynamicUsage(u64);
    (void)memusage::DynamicUsage(u8);
    const unsigned char uch = static_cast<unsigned char>(u8);
    (void)memusage::DynamicUsage(uch);
    (void)MillisToTimeval(i64);
    const double d = ser_uint64_to_double(u64);
    assert(ser_double_to_uint64(d) == u64);
    const float f = ser_uint32_to_float(u32);
    assert(ser_float_to_uint32(f) == u32);
    (void)SighashToStr(uch);
    (void)SipHashUint256(u64, u64, u256);
    (void)SipHashUint256Extra(u64, u64, u256, u32);
    (void)ToLower(ch);
    (void)ToUpper(ch);
    // ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min()
    if (i64 != std::numeric_limits<int64_t>::min()) {
        int64_t parsed_money;
        if (ParseMoney(ValueFromAmount(i64).getValStr(), parsed_money)) {
            assert(parsed_money == i64);
        }
    }

    const arith_uint256 au256 = UintToArith256(u256);
    assert(ArithToUint256(au256) == u256);
    assert(uint256S(au256.GetHex()) == u256);
    (void)au256.bits();
    (void)au256.GetCompact(/* fNegative= */ false);
    (void)au256.GetCompact(/* fNegative= */ true);
    (void)au256.getdouble();
    (void)au256.GetHex();
    (void)au256.GetLow64();
    (void)au256.size();
    (void)au256.ToString();

    const CKeyID key_id{u160};
    const CScriptID script_id{u160};
    // CTxDestination = CNoDestination ∪ PKHash ∪ ScriptHash ∪ WitnessV0ScriptHash ∪ WitnessV0KeyHash ∪ WitnessUnknown
    const PKHash pk_hash{u160};
    const ScriptHash script_hash{u160};
    const WitnessV0KeyHash witness_v0_key_hash{u160};
    const WitnessV0ScriptHash witness_v0_script_hash{u256};
    const std::vector<CTxDestination> destinations{pk_hash, script_hash, witness_v0_key_hash, witness_v0_script_hash};
    const SigningProvider store;
    for (const CTxDestination& destination : destinations) {
        (void)DescribeAddress(destination);
        (void)EncodeDestination(destination);
        (void)GetKeyForDestination(store, destination);
        (void)GetScriptForDestination(destination);
        (void)IsValidDestination(destination);
    }

    {
        CDataStream stream(SER_NETWORK, INIT_PROTO_VERSION);

        uint256 deserialized_u256;
        stream << u256;
        stream >> deserialized_u256;
        assert(u256 == deserialized_u256 && stream.empty());

        uint160 deserialized_u160;
        stream << u160;
        stream >> deserialized_u160;
        assert(u160 == deserialized_u160 && stream.empty());

        uint64_t deserialized_u64;
        stream << u64;
        stream >> deserialized_u64;
        assert(u64 == deserialized_u64 && stream.empty());

        int64_t deserialized_i64;
        stream << i64;
        stream >> deserialized_i64;
        assert(i64 == deserialized_i64 && stream.empty());

        uint32_t deserialized_u32;
        stream << u32;
        stream >> deserialized_u32;
        assert(u32 == deserialized_u32 && stream.empty());

        int32_t deserialized_i32;
        stream << i32;
        stream >> deserialized_i32;
        assert(i32 == deserialized_i32 && stream.empty());

        uint16_t deserialized_u16;
        stream << u16;
        stream >> deserialized_u16;
        assert(u16 == deserialized_u16 && stream.empty());

        int16_t deserialized_i16;
        stream << i16;
        stream >> deserialized_i16;
        assert(i16 == deserialized_i16 && stream.empty());

        uint8_t deserialized_u8;
        stream << u8;
        stream >> deserialized_u8;
        assert(u8 == deserialized_u8 && stream.empty());

        int8_t deserialized_i8;
        stream << i8;
        stream >> deserialized_i8;
        assert(i8 == deserialized_i8 && stream.empty());

        char deserialized_ch;
        stream << ch;
        stream >> deserialized_ch;
        assert(ch == deserialized_ch && stream.empty());

        bool deserialized_b;
        stream << b;
        stream >> deserialized_b;
        assert(b == deserialized_b && stream.empty());
    }
}
<commit_msg>tests: Fuzz HasAllDesirableServiceFlags(...) and MayHaveUsefulAddressDB(...)<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <amount.h>
#include <arith_uint256.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <core_io.h>
#include <crypto/common.h>
#include <crypto/siphash.h>
#include <key_io.h>
#include <memusage.h>
#include <netbase.h>
#include <policy/settings.h>
#include <pow.h>
#include <protocol.h>
#include <pubkey.h>
#include <rpc/util.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <serialize.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <uint256.h>
#include <util/moneystr.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/time.h>
#include <version.h>

#include <cassert>
#include <limits>
#include <vector>

void initialize()
{
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    if (buffer.size() < sizeof(uint256) + sizeof(uint160)) {
        return;
    }
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256)));
    const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160)));
    const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
    const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
    const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
    const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>();
    const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>();
    const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>();
    const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>();
    const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>();
    // We cannot assume a specific value of std::is_signed<char>::value:
    // ConsumeIntegral<char>() instead of casting from {u,}int8_t.
    const char ch = fuzzed_data_provider.ConsumeIntegral<char>();
    const bool b = fuzzed_data_provider.ConsumeBool();

    const Consensus::Params& consensus_params = Params().GetConsensus();
    (void)CheckProofOfWork(u256, u32, consensus_params);
    if (u64 <= MAX_MONEY) {
        const uint64_t compressed_money_amount = CompressAmount(u64);
        assert(u64 == DecompressAmount(compressed_money_amount));
        static const uint64_t compressed_money_amount_max = CompressAmount(MAX_MONEY - 1);
        assert(compressed_money_amount <= compressed_money_amount_max);
    } else {
        (void)CompressAmount(u64);
    }
    static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000"));
    static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
    const std::vector<uint256> v256{u256, u256_min, u256_max};
    (void)ComputeMerkleRoot(v256);
    (void)CountBits(u64);
    (void)DecompressAmount(u64);
    (void)FormatISO8601Date(i64);
    (void)FormatISO8601DateTime(i64);
    // FormatMoney(i) not defined when i == std::numeric_limits<int64_t>::min()
    if (i64 != std::numeric_limits<int64_t>::min()) {
        int64_t parsed_money;
        if (ParseMoney(FormatMoney(i64), parsed_money)) {
            assert(parsed_money == i64);
        }
    }
    (void)GetSizeOfCompactSize(u64);
    (void)GetSpecialScriptSize(u32);
    // (void)GetVirtualTransactionSize(i64, i64); // function defined only for a subset of int64_t inputs
    // (void)GetVirtualTransactionSize(i64, i64, u32); // function defined only for a subset of int64_t/uint32_t inputs
    (void)HexDigit(ch);
    (void)MoneyRange(i64);
    (void)i64tostr(i64);
    (void)IsDigit(ch);
    (void)IsSpace(ch);
    (void)IsSwitchChar(ch);
    (void)itostr(i32);
    (void)memusage::DynamicUsage(ch);
    (void)memusage::DynamicUsage(i16);
    (void)memusage::DynamicUsage(i32);
    (void)memusage::DynamicUsage(i64);
    (void)memusage::DynamicUsage(i8);
    (void)memusage::DynamicUsage(u16);
    (void)memusage::DynamicUsage(u32);
    (void)memusage::DynamicUsage(u64);
    (void)memusage::DynamicUsage(u8);
    const unsigned char uch = static_cast<unsigned char>(u8);
    (void)memusage::DynamicUsage(uch);
    (void)MillisToTimeval(i64);
    const double d = ser_uint64_to_double(u64);
    assert(ser_double_to_uint64(d) == u64);
    const float f = ser_uint32_to_float(u32);
    assert(ser_float_to_uint32(f) == u32);
    (void)SighashToStr(uch);
    (void)SipHashUint256(u64, u64, u256);
    (void)SipHashUint256Extra(u64, u64, u256, u32);
    (void)ToLower(ch);
    (void)ToUpper(ch);
    // ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min()
    if (i64 != std::numeric_limits<int64_t>::min()) {
        int64_t parsed_money;
        if (ParseMoney(ValueFromAmount(i64).getValStr(), parsed_money)) {
            assert(parsed_money == i64);
        }
    }

    const arith_uint256 au256 = UintToArith256(u256);
    assert(ArithToUint256(au256) == u256);
    assert(uint256S(au256.GetHex()) == u256);
    (void)au256.bits();
    (void)au256.GetCompact(/* fNegative= */ false);
    (void)au256.GetCompact(/* fNegative= */ true);
    (void)au256.getdouble();
    (void)au256.GetHex();
    (void)au256.GetLow64();
    (void)au256.size();
    (void)au256.ToString();

    const CKeyID key_id{u160};
    const CScriptID script_id{u160};
    // CTxDestination = CNoDestination ∪ PKHash ∪ ScriptHash ∪ WitnessV0ScriptHash ∪ WitnessV0KeyHash ∪ WitnessUnknown
    const PKHash pk_hash{u160};
    const ScriptHash script_hash{u160};
    const WitnessV0KeyHash witness_v0_key_hash{u160};
    const WitnessV0ScriptHash witness_v0_script_hash{u256};
    const std::vector<CTxDestination> destinations{pk_hash, script_hash, witness_v0_key_hash, witness_v0_script_hash};
    const SigningProvider store;
    for (const CTxDestination& destination : destinations) {
        (void)DescribeAddress(destination);
        (void)EncodeDestination(destination);
        (void)GetKeyForDestination(store, destination);
        (void)GetScriptForDestination(destination);
        (void)IsValidDestination(destination);
    }

    {
        CDataStream stream(SER_NETWORK, INIT_PROTO_VERSION);

        uint256 deserialized_u256;
        stream << u256;
        stream >> deserialized_u256;
        assert(u256 == deserialized_u256 && stream.empty());

        uint160 deserialized_u160;
        stream << u160;
        stream >> deserialized_u160;
        assert(u160 == deserialized_u160 && stream.empty());

        uint64_t deserialized_u64;
        stream << u64;
        stream >> deserialized_u64;
        assert(u64 == deserialized_u64 && stream.empty());

        int64_t deserialized_i64;
        stream << i64;
        stream >> deserialized_i64;
        assert(i64 == deserialized_i64 && stream.empty());

        uint32_t deserialized_u32;
        stream << u32;
        stream >> deserialized_u32;
        assert(u32 == deserialized_u32 && stream.empty());

        int32_t deserialized_i32;
        stream << i32;
        stream >> deserialized_i32;
        assert(i32 == deserialized_i32 && stream.empty());

        uint16_t deserialized_u16;
        stream << u16;
        stream >> deserialized_u16;
        assert(u16 == deserialized_u16 && stream.empty());

        int16_t deserialized_i16;
        stream << i16;
        stream >> deserialized_i16;
        assert(i16 == deserialized_i16 && stream.empty());

        uint8_t deserialized_u8;
        stream << u8;
        stream >> deserialized_u8;
        assert(u8 == deserialized_u8 && stream.empty());

        int8_t deserialized_i8;
        stream << i8;
        stream >> deserialized_i8;
        assert(i8 == deserialized_i8 && stream.empty());

        char deserialized_ch;
        stream << ch;
        stream >> deserialized_ch;
        assert(ch == deserialized_ch && stream.empty());

        bool deserialized_b;
        stream << b;
        stream >> deserialized_b;
        assert(b == deserialized_b && stream.empty());
    }

    {
        const ServiceFlags service_flags = (ServiceFlags)u64;
        (void)HasAllDesirableServiceFlags(service_flags);
        (void)MayHaveUsefulAddressDB(service_flags);
    }
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------------
// Class for HF corrections as a function of many variables and step
// Author : C. Zampolli, CERN
// D. Caffarri, Univ & INFN Padova caffarri@pd.infn.it
// Base class for HF Unfolding - agrelli@uu.nl
//-----------------------------------------------------------------------

#include "AliAODRecoDecayHF2Prong.h"
#include "AliAODMCParticle.h"
#include "AliAODEvent.h"
#include "TClonesArray.h"
#include "AliCFVertexingHF.h"
#include "AliESDtrack.h"
#include "TDatabasePDG.h"

#include "AliCFVertexingHF2Prong.h"
#include "AliCFContainer.h"

ClassImp(AliCFVertexingHF2Prong)

//_________________________________________
  AliCFVertexingHF2Prong::AliCFVertexingHF2Prong(TClonesArray *mcArray, UShort_t originDselection):
	  AliCFVertexingHF(mcArray, originDselection)
{
	//
	// constructor
	//

	SetNProngs(2);
}

//_____________________________________
AliCFVertexingHF2Prong& AliCFVertexingHF2Prong::operator=(const AliCFVertexingHF2Prong& c)
{
	//
	// copy constructor
	//

	if  (this != &c) {
		AliCFVertexingHF::operator=(c);
	}
	return *this;
}

//__________________________________________
Bool_t AliCFVertexingHF2Prong::SetRecoCandidateParam(AliAODRecoDecayHF *recoCand)
{
	//
	// setting the recontructed candidate
	//

	Bool_t bSignAssoc = kFALSE;
	fRecoCandidate = recoCand;
	if (!fRecoCandidate) {
		AliError("fRecoCandidate not found, problem in assignement\n");
		return bSignAssoc;
	}

	if (fRecoCandidate->GetPrimaryVtx()) AliDebug(3,"fReco Candidate has a pointer to PrimVtx\n");
	if (recoCand->GetPrimaryVtx()) AliDebug(3,"Reco Cand has a pointer to PrimVtx\n");

	Int_t pdgCand = 421;
	Int_t pdgDgD0toKpi[2]={321,211};
	Int_t nentries = fmcArray->GetEntriesFast();

	AliDebug(3,Form("nentries = %d\n", nentries));

	Int_t mcLabel = fRecoCandidate->MatchToMC(pdgCand,fmcArray,2,pdgDgD0toKpi);
	if (mcLabel == -1) return bSignAssoc;
	SetMCLabel(mcLabel);
	fmcPartCandidate = dynamic_cast<AliAODMCParticle*>(fmcArray->At(fmcLabel));
	if (!fmcPartCandidate){
		AliDebug(3,"No part candidate");
		return bSignAssoc;
	}
	bSignAssoc = kTRUE;
	return bSignAssoc;
}

//______________________________________________
Bool_t AliCFVertexingHF2Prong::GetGeneratedValuesFromMCParticle(Double_t* vectorMC)
{
	//
	// collecting all the necessary info (pt, y, cosThetaStar, ptPi, ptKa, cT) from MC particle
	//

	Bool_t bGenValues = kFALSE;
	Double_t vtx1[3] = {0,0,0};   // primary vertex
	Double_t vtx2daughter0[3] = {0,0,0};   // secondary vertex from daughter 0
	Double_t vtx2daughter1[3] = {0,0,0};   // secondary vertex from daughter 1
	fmcPartCandidate->XvYvZv(vtx1);  // cm

	Int_t daughter0 = fmcPartCandidate->GetDaughter(0);
	Int_t daughter1 = fmcPartCandidate->GetDaughter(1);
	AliAODMCParticle* mcPartDaughter0 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter0));
	AliAODMCParticle* mcPartDaughter1 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter1));

	// getting vertex from daughters
	mcPartDaughter0->XvYvZv(vtx2daughter0);  // cm
	mcPartDaughter1->XvYvZv(vtx2daughter1);  //cm
	if (vtx2daughter0[0] != vtx2daughter1[0] && vtx2daughter0[1] != vtx2daughter1[1] && vtx2daughter0[2] != vtx2daughter1[2]) {
		AliError("Daughters have different secondary vertex, skipping the track");
		return bGenValues;
	}

	Int_t nprongs = 2;
	Short_t charge = 0;
	// always instantiate the AliAODRecoDecay with the positive daughter first, the negative second
	AliAODMCParticle* positiveDaugh = mcPartDaughter0;
	AliAODMCParticle* negativeDaugh = mcPartDaughter1;
	if (mcPartDaughter0->GetPdgCode()<0 && mcPartDaughter1->GetPdgCode()>0){
		// inverting in case the positive daughter is the second one
		positiveDaugh = mcPartDaughter1;
		negativeDaugh = mcPartDaughter0;
	}
	// getting the momentum from the daughters
	Double_t px[2] = {positiveDaugh->Px(), negativeDaugh->Px()};
	Double_t py[2] = {positiveDaugh->Py(), negativeDaugh->Py()};
	Double_t pz[2] = {positiveDaugh->Pz(), negativeDaugh->Pz()};

	Double_t d0[2] = {0.,0.};

	AliAODRecoDecayHF* decay = new AliAODRecoDecayHF(vtx1,vtx2daughter0,nprongs,charge,px,py,pz,d0);

	Double_t cosThetaStar = 0.;
	Double_t cosThetaStarD0 = 0.;
	Double_t cosThetaStarD0bar = 0.;
	cosThetaStarD0 = decay->CosThetaStar(1,421,211,321);
	cosThetaStarD0bar = decay->CosThetaStar(0,421,321,211);
	if (fmcPartCandidate->GetPdgCode() == 421){  // D0
		AliDebug(3, Form("D0, with pdgprong0 = %d, pdgprong1 = %d",mcPartDaughter0->GetPdgCode(),mcPartDaughter1->GetPdgCode()));
		cosThetaStar = cosThetaStarD0;
	}
	else if (fmcPartCandidate->GetPdgCode() == -421){  // D0bar{
		AliDebug(3, Form("D0bar, with pdgprong0 = %d, pdgprong1 = %d",mcPartDaughter0->GetPdgCode(),mcPartDaughter1->GetPdgCode()));
		cosThetaStar = cosThetaStarD0bar;
	}
	else{
		AliWarning("There are problems!! particle was expected to be either a D0 or a D0bar, check...");
		return vectorMC;
	}
	if (cosThetaStar < -1 || cosThetaStar > 1) {
		AliWarning("Invalid value for cosine Theta star, returning");
		return bGenValues;
	}

	//ct
	Double_t cT = decay->Ct(421);
	// get the pT of the daughters
	Double_t pTpi = 0.;
	Double_t pTK = 0.;

	if (TMath::Abs(mcPartDaughter0->GetPdgCode()) == 211) {
		pTpi = mcPartDaughter0->Pt();
		pTK = mcPartDaughter1->Pt();
	}
	else {
		pTpi = mcPartDaughter1->Pt();
		pTK = mcPartDaughter0->Pt();
	}

	vectorMC[0] = fmcPartCandidate->Pt();
	vectorMC[1] = fmcPartCandidate->Y() ;
	vectorMC[2] = cosThetaStar ;
	vectorMC[3] = pTpi ;
	vectorMC[4] = pTK ;
	vectorMC[5] = cT*1.E4 ;  // in micron
	vectorMC[6] = 0.;   // dummy value, meaningless in MC
	vectorMC[7] = 0.;   // dummy value, meaningless in MC, in micron
	vectorMC[8] = 0.;   // dummy value, meaningless in MC, in micron
	vectorMC[9] = -100000.; // dummy value, meaningless in MC, in micron^2
	vectorMC[10] = 1.01;    // dummy value, meaningless in MC
	vectorMC[11] = fmcPartCandidate->Phi();
	vectorMC[12] = fzMCVertex;    // z of reconstructed of primary vertex
	delete decay;
	bGenValues = kTRUE;
	return bGenValues;
}
//____________________________________________
Bool_t AliCFVertexingHF2Prong::GetRecoValuesFromCandidate(Double_t *vectorReco) const
{
	//
	// Getting the reconstructed values from the candidate
	//

	Bool_t bFillRecoValues=kFALSE;

	AliAODRecoDecayHF2Prong *d0toKpi = (AliAODRecoDecayHF2Prong*)fRecoCandidate;

	if (d0toKpi->GetPrimaryVtx())AliDebug(3,"d0toKpi has primary vtx\n");
	if (fRecoCandidate->GetPrimaryVtx())AliDebug(3,"fRecoCandidate has primary vtx\n");

	Double_t pt = d0toKpi->Pt();
	Double_t rapidity = d0toKpi->YD0();
	Double_t invMass=0.;
	Double_t cosThetaStar = 9999.;
	Double_t pTpi = 0.;
	Double_t pTK = 0.;
	Double_t dca = d0toKpi->GetDCA();
	Double_t d0pi = 0.;
	Double_t d0K = 0.;
	Double_t d0xd0 = d0toKpi->Prodd0d0();
	Double_t cosPointingAngle = d0toKpi->CosPointingAngle();
	Double_t phi = d0toKpi->Phi();
	Int_t pdgCode = fmcPartCandidate->GetPdgCode();

	if (pdgCode > 0){
		cosThetaStar = d0toKpi->CosThetaStarD0();
		pTpi = d0toKpi->PtProng(0);
		pTK = d0toKpi->PtProng(1);
		d0pi = d0toKpi->Getd0Prong(0);
		d0K = d0toKpi->Getd0Prong(1);
		invMass=d0toKpi->InvMassD0();
	}
	else {
		cosThetaStar = d0toKpi->CosThetaStarD0bar();
		pTpi = d0toKpi->PtProng(1);
		pTK = d0toKpi->PtProng(0);
		d0pi = d0toKpi->Getd0Prong(1);
		d0K = d0toKpi->Getd0Prong(0);
		invMass= d0toKpi->InvMassD0bar();
	}

	Double_t cT = d0toKpi->CtD0();

	vectorReco[0] = pt;
	vectorReco[1] = rapidity;
	vectorReco[2] = cosThetaStar;
	vectorReco[3] = pTpi;
	vectorReco[4] = pTK;
	vectorReco[5] = cT*1.E4;  // in micron
	vectorReco[6] = dca*1.E4;  // in micron
	vectorReco[7] = d0pi*1.E4;  // in micron
	vectorReco[8] = d0K*1.E4;  // in micron
	vectorReco[9] = d0xd0*1.E8;  // in micron^2
	vectorReco[10] = cosPointingAngle;  // in micron
	vectorReco[11] = phi;
	vectorReco[12] = fzPrimVertex;    // z of reconstructed of primary vertex
	bFillRecoValues = kTRUE;

	return bFillRecoValues;
}

//_____________________________________________________________
Bool_t AliCFVertexingHF2Prong::CheckMCChannelDecay() const
{
	//
	// checking the MC decay channel
	//
	Bool_t checkCD = kFALSE;
	Int_t daughter0 = fmcPartCandidate->GetDaughter(0);
	Int_t daughter1 = fmcPartCandidate->GetDaughter(1);
	AliAODMCParticle* mcPartDaughter0 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter0));
	AliAODMCParticle* mcPartDaughter1 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter1));

	if (!mcPartDaughter0 || !mcPartDaughter1) {
		AliDebug (2,"Problems in the MC Daughters\n");
		return checkCD;
	}

	if (!(TMath::Abs(mcPartDaughter0->GetPdgCode())==321 &&
	      TMath::Abs(mcPartDaughter1->GetPdgCode())==211) &&
	    !(TMath::Abs(mcPartDaughter0->GetPdgCode())==211 &&
	      TMath::Abs(mcPartDaughter1->GetPdgCode())==321)) {
		AliDebug(2, "The D0 MC doesn't come from a Kpi decay, skipping!!");
		return checkCD;
	}

	checkCD = kTRUE;
	return checkCD;

}

<commit_msg>Avoid comparing floats with != (ChiaraZ)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------------
// Class for HF corrections as a function of many variables and step
// Author : C. Zampolli, CERN
// D. Caffarri, Univ & INFN Padova caffarri@pd.infn.it
// Base class for HF Unfolding - agrelli@uu.nl
//-----------------------------------------------------------------------

#include "AliAODRecoDecayHF2Prong.h"
#include "AliAODMCParticle.h"
#include "AliAODEvent.h"
#include "TClonesArray.h"
#include "AliCFVertexingHF.h"
#include "AliESDtrack.h"
#include "TDatabasePDG.h"

#include "AliCFVertexingHF2Prong.h"
#include "AliCFContainer.h"

ClassImp(AliCFVertexingHF2Prong)

//_________________________________________
  AliCFVertexingHF2Prong::AliCFVertexingHF2Prong(TClonesArray *mcArray, UShort_t originDselection):
	  AliCFVertexingHF(mcArray, originDselection)
{
	//
	// constructor
	//

	SetNProngs(2);
}

//_____________________________________
AliCFVertexingHF2Prong& AliCFVertexingHF2Prong::operator=(const AliCFVertexingHF2Prong& c)
{
	//
	// copy constructor
	//

	if  (this != &c) {
		AliCFVertexingHF::operator=(c);
	}
	return *this;
}

//__________________________________________
Bool_t AliCFVertexingHF2Prong::SetRecoCandidateParam(AliAODRecoDecayHF *recoCand)
{
	//
	// setting the recontructed candidate
	//

	Bool_t bSignAssoc = kFALSE;
	fRecoCandidate = recoCand;
	if (!fRecoCandidate) {
		AliError("fRecoCandidate not found, problem in assignement\n");
		return bSignAssoc;
	}

	if (fRecoCandidate->GetPrimaryVtx()) AliDebug(3,"fReco Candidate has a pointer to PrimVtx\n");
	if (recoCand->GetPrimaryVtx()) AliDebug(3,"Reco Cand has a pointer to PrimVtx\n");

	Int_t pdgCand = 421;
	Int_t pdgDgD0toKpi[2]={321,211};
	Int_t nentries = fmcArray->GetEntriesFast();

	AliDebug(3,Form("nentries = %d\n", nentries));

	Int_t mcLabel = fRecoCandidate->MatchToMC(pdgCand,fmcArray,2,pdgDgD0toKpi);
	if (mcLabel == -1) return bSignAssoc;
	SetMCLabel(mcLabel);
	fmcPartCandidate = dynamic_cast<AliAODMCParticle*>(fmcArray->At(fmcLabel));
	if (!fmcPartCandidate){
		AliDebug(3,"No part candidate");
		return bSignAssoc;
	}
	bSignAssoc = kTRUE;
	return bSignAssoc;
}

//______________________________________________
Bool_t AliCFVertexingHF2Prong::GetGeneratedValuesFromMCParticle(Double_t* vectorMC)
{
	//
	// collecting all the necessary info (pt, y, cosThetaStar, ptPi, ptKa, cT) from MC particle
	//

	Bool_t bGenValues = kFALSE;
	Double_t vtx1[3] = {0,0,0};   // primary vertex
	Double_t vtx2daughter0[3] = {0,0,0};   // secondary vertex from daughter 0
	Double_t vtx2daughter1[3] = {0,0,0};   // secondary vertex from daughter 1
	fmcPartCandidate->XvYvZv(vtx1);  // cm

	Int_t daughter0 = fmcPartCandidate->GetDaughter(0);
	Int_t daughter1 = fmcPartCandidate->GetDaughter(1);
	AliAODMCParticle* mcPartDaughter0 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter0));
	AliAODMCParticle* mcPartDaughter1 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter1));

	// getting vertex from daughters
	mcPartDaughter0->XvYvZv(vtx2daughter0);  // cm
	mcPartDaughter1->XvYvZv(vtx2daughter1);  //cm
	if (TMath::Abs(vtx2daughter0[0] - vtx2daughter1[0]) > 1E-5 || TMath::Abs(vtx2daughter0[1] - vtx2daughter1[1]) > 1E-5 || TMath::Abs(vtx2daughter0[2] - vtx2daughter1[2])>1E-5) {
		AliError("Daughters have different secondary vertex, skipping the track");
		return bGenValues;
	}

	Int_t nprongs = 2;
	Short_t charge = 0;
	// always instantiate the AliAODRecoDecay with the positive daughter first, the negative second
	AliAODMCParticle* positiveDaugh = mcPartDaughter0;
	AliAODMCParticle* negativeDaugh = mcPartDaughter1;
	if (mcPartDaughter0->GetPdgCode()<0 && mcPartDaughter1->GetPdgCode()>0){
		// inverting in case the positive daughter is the second one
		positiveDaugh = mcPartDaughter1;
		negativeDaugh = mcPartDaughter0;
	}
	// getting the momentum from the daughters
	Double_t px[2] = {positiveDaugh->Px(), negativeDaugh->Px()};
	Double_t py[2] = {positiveDaugh->Py(), negativeDaugh->Py()};
	Double_t pz[2] = {positiveDaugh->Pz(), negativeDaugh->Pz()};

	Double_t d0[2] = {0.,0.};

	AliAODRecoDecayHF* decay = new AliAODRecoDecayHF(vtx1,vtx2daughter0,nprongs,charge,px,py,pz,d0);

	Double_t cosThetaStar = 0.;
	Double_t cosThetaStarD0 = 0.;
	Double_t cosThetaStarD0bar = 0.;
	cosThetaStarD0 = decay->CosThetaStar(1,421,211,321);
	cosThetaStarD0bar = decay->CosThetaStar(0,421,321,211);
	if (fmcPartCandidate->GetPdgCode() == 421){  // D0
		AliDebug(3, Form("D0, with pdgprong0 = %d, pdgprong1 = %d",mcPartDaughter0->GetPdgCode(),mcPartDaughter1->GetPdgCode()));
		cosThetaStar = cosThetaStarD0;
	}
	else if (fmcPartCandidate->GetPdgCode() == -421){  // D0bar{
		AliDebug(3, Form("D0bar, with pdgprong0 = %d, pdgprong1 = %d",mcPartDaughter0->GetPdgCode(),mcPartDaughter1->GetPdgCode()));
		cosThetaStar = cosThetaStarD0bar;
	}
	else{
		AliWarning("There are problems!! particle was expected to be either a D0 or a D0bar, check...");
		return vectorMC;
	}
	if (cosThetaStar < -1 || cosThetaStar > 1) {
		AliWarning("Invalid value for cosine Theta star, returning");
		return bGenValues;
	}

	//ct
	Double_t cT = decay->Ct(421);
	// get the pT of the daughters
	Double_t pTpi = 0.;
	Double_t pTK = 0.;

	if (TMath::Abs(mcPartDaughter0->GetPdgCode()) == 211) {
		pTpi = mcPartDaughter0->Pt();
		pTK = mcPartDaughter1->Pt();
	}
	else {
		pTpi = mcPartDaughter1->Pt();
		pTK = mcPartDaughter0->Pt();
	}

	vectorMC[0] = fmcPartCandidate->Pt();
	vectorMC[1] = fmcPartCandidate->Y() ;
	vectorMC[2] = cosThetaStar ;
	vectorMC[3] = pTpi ;
	vectorMC[4] = pTK ;
	vectorMC[5] = cT*1.E4 ;  // in micron
	vectorMC[6] = 0.;   // dummy value, meaningless in MC
	vectorMC[7] = 0.;   // dummy value, meaningless in MC, in micron
	vectorMC[8] = 0.;   // dummy value, meaningless in MC, in micron
	vectorMC[9] = -100000.; // dummy value, meaningless in MC, in micron^2
	vectorMC[10] = 1.01;    // dummy value, meaningless in MC
	vectorMC[11] = fmcPartCandidate->Phi();
	vectorMC[12] = fzMCVertex;    // z of reconstructed of primary vertex
	delete decay;
	bGenValues = kTRUE;
	return bGenValues;
}
//____________________________________________
Bool_t AliCFVertexingHF2Prong::GetRecoValuesFromCandidate(Double_t *vectorReco) const
{
	//
	// Getting the reconstructed values from the candidate
	//

	Bool_t bFillRecoValues=kFALSE;

	AliAODRecoDecayHF2Prong *d0toKpi = (AliAODRecoDecayHF2Prong*)fRecoCandidate;

	if (d0toKpi->GetPrimaryVtx())AliDebug(3,"d0toKpi has primary vtx\n");
	if (fRecoCandidate->GetPrimaryVtx())AliDebug(3,"fRecoCandidate has primary vtx\n");

	Double_t pt = d0toKpi->Pt();
	Double_t rapidity = d0toKpi->YD0();
	Double_t invMass=0.;
	Double_t cosThetaStar = 9999.;
	Double_t pTpi = 0.;
	Double_t pTK = 0.;
	Double_t dca = d0toKpi->GetDCA();
	Double_t d0pi = 0.;
	Double_t d0K = 0.;
	Double_t d0xd0 = d0toKpi->Prodd0d0();
	Double_t cosPointingAngle = d0toKpi->CosPointingAngle();
	Double_t phi = d0toKpi->Phi();
	Int_t pdgCode = fmcPartCandidate->GetPdgCode();

	if (pdgCode > 0){
		cosThetaStar = d0toKpi->CosThetaStarD0();
		pTpi = d0toKpi->PtProng(0);
		pTK = d0toKpi->PtProng(1);
		d0pi = d0toKpi->Getd0Prong(0);
		d0K = d0toKpi->Getd0Prong(1);
		invMass=d0toKpi->InvMassD0();
	}
	else {
		cosThetaStar = d0toKpi->CosThetaStarD0bar();
		pTpi = d0toKpi->PtProng(1);
		pTK = d0toKpi->PtProng(0);
		d0pi = d0toKpi->Getd0Prong(1);
		d0K = d0toKpi->Getd0Prong(0);
		invMass= d0toKpi->InvMassD0bar();
	}

	Double_t cT = d0toKpi->CtD0();

	vectorReco[0] = pt;
	vectorReco[1] = rapidity;
	vectorReco[2] = cosThetaStar;
	vectorReco[3] = pTpi;
	vectorReco[4] = pTK;
	vectorReco[5] = cT*1.E4;  // in micron
	vectorReco[6] = dca*1.E4;  // in micron
	vectorReco[7] = d0pi*1.E4;  // in micron
	vectorReco[8] = d0K*1.E4;  // in micron
	vectorReco[9] = d0xd0*1.E8;  // in micron^2
	vectorReco[10] = cosPointingAngle;  // in micron
	vectorReco[11] = phi;
	vectorReco[12] = fzPrimVertex;    // z of reconstructed of primary vertex
	bFillRecoValues = kTRUE;

	return bFillRecoValues;
}

//_____________________________________________________________
Bool_t AliCFVertexingHF2Prong::CheckMCChannelDecay() const
{
	//
	// checking the MC decay channel
	//
	Bool_t checkCD = kFALSE;
	Int_t daughter0 = fmcPartCandidate->GetDaughter(0);
	Int_t daughter1 = fmcPartCandidate->GetDaughter(1);
	AliAODMCParticle* mcPartDaughter0 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter0));
	AliAODMCParticle* mcPartDaughter1 = dynamic_cast<AliAODMCParticle*>(fmcArray->At(daughter1));

	if (!mcPartDaughter0 || !mcPartDaughter1) {
		AliDebug (2,"Problems in the MC Daughters\n");
		return checkCD;
	}

	if (!(TMath::Abs(mcPartDaughter0->GetPdgCode())==321 &&
	      TMath::Abs(mcPartDaughter1->GetPdgCode())==211) &&
	    !(TMath::Abs(mcPartDaughter0->GetPdgCode())==211 &&
	      TMath::Abs(mcPartDaughter1->GetPdgCode())==321)) {
		AliDebug(2, "The D0 MC doesn't come from a Kpi decay, skipping!!");
		return checkCD;
	}

	checkCD = kTRUE;
	return checkCD;

}

<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskHFEFlowTPCTOFEPSP(UInt_t trigger=131073,Int_t aodfilter=16,Bool_t scalarProduct=kFALSE,Bool_t cutPileup=kFALSE,Int_t tpcCls=110, Double_t tpcClsr=60, Int_t tpcClspid=80, Int_t itsCls=4, Int_t pixellayer=2, Double_t dcaxy=100,Double_t dcaz=200, Double_t tofsig=30., Double_t tpceff=50., Int_t vzero=1, Int_t debuglevel=2, Double_t etarange=80, Bool_t ptbinsmall=kFALSE, Double_t ITSclustersback=0, Double_t minTPCback=-2.0, Double_t maxTPCback=5.0){

  //
  // Define TPC cut for 2011 data
  //
  Double_t tpcdedx[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; //0-5,5-10,10-20,20-30,30-40,40-50,50-60,60-100
  // -0.2 0-5%
  // -0.15 5-10%
  // -0.1 10-20%
  // -0.0 20-30%, sigma=1.17
  // 0.156 30-40%, sigma=1.2
  // 0.19 40-50%, sigma=1.2
  // 0.2 50-60%
  // 0.2 60-80% list_t65536f16TPC110r60p80s11km0ITS4C36Pi2DCAr100z200TOF30TPCe50V1D0er8i0t-20t50
  tpcdedx[0]=-0.2;
  tpcdedx[1]=-0.15;
  tpcdedx[2]=-0.1;
  tpcdedx[3]=0.0;
  tpcdedx[4]=0.156;
  tpcdedx[5]=0.19;
  tpcdedx[6]=0.2;
  tpcdedx[7]=0.2;
  if(TMath::Abs(tpceff-55)<0.01) {
    tpcdedx[0]=-0.365;
    tpcdedx[1]=-0.314;
    tpcdedx[2]=-0.267;
    tpcdedx[3]=-0.165;
    tpcdedx[4]=-0.022;
    tpcdedx[5]= 0.01;
    tpcdedx[6]= 0.018;
    tpcdedx[7]= 0.018;
  }
  if(TMath::Abs(tpceff-45)<0.01) {
    tpcdedx[0]=-0.062;
    tpcdedx[1]=-0.015;
    tpcdedx[2]=0.035;
    tpcdedx[3]=0.131;
    tpcdedx[4]=0.278;
    tpcdedx[5]=0.32;
    tpcdedx[6]=0.32;
    tpcdedx[7]=0.32;
  }
  if(TMath::Abs(tpceff-60)<0.01) {
    tpcdedx[0]=-0.518;
    tpcdedx[1]=-0.47;
    tpcdedx[2]=-0.42;
    tpcdedx[3]=-0.315;
    tpcdedx[4]=-0.178;
    tpcdedx[5]=-0.145;
    tpcdedx[6]=-0.135;
    tpcdedx[7]=-0.135;
  }
  if(TMath::Abs(tpceff-40)<0.01) {
    tpcdedx[0]=0.09;
    tpcdedx[1]=0.14;
    tpcdedx[2]=0.188;
    tpcdedx[3]=0.28;
    tpcdedx[4]=0.43;
    tpcdedx[5]=0.462;
    tpcdedx[6]=0.473;
    tpcdedx[7]=0.473;
  }

  // Name
  TString appendixx(TString::Format("t%df%ds%dp%dTPC%dr%dp%dITS%dPi%dDCAr%dz%dTOF%dTPCe%dV%dD%der%di%dt%dt%d",(Int_t)trigger,aodfilter,(Int_t)scalarProduct,(Int_t)cutPileup,tpcCls,(Int_t)tpcClsr,tpcClspid,itsCls,(Int_t) pixellayer,(Int_t) dcaxy,(Int_t)dcaz,(Int_t) tofsig,(Int_t)tpceff,vzero,debuglevel,(Int_t)(etarange*0.1),(Int_t)ITSclustersback,(Int_t)(minTPCback*10.0),(Int_t)(maxTPCback*10.0)));
  //TString appendixx("tpctofv2");

  //set config file name
  TString configFile("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  //TString configFile("/hera/alice/bailhach/AliRootInstallations/30_09_2013/AliRoot/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  TString checkconfig="ConfigHFE_FLOW_TOFTPC";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskFlowTPCTOFEPSP *task = ConfigHFE_FLOW_TOFTPC(kFALSE,appendixx,trigger,aodfilter,scalarProduct,cutPileup,tpcCls, tpcClsr, tpcClspid, itsCls, pixellayer, dcaxy, dcaz,tofsig,&tpcdedx[0],vzero,debuglevel,etarange,kFALSE,ITSclustersback,minTPCback,maxTPCback);

  task->SetNbBinsCentralityQCumulant(4);
  //task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(1,10.0);
  task->SetBinCentralityLess(2,20.0);
  task->SetBinCentralityLess(3,40.0);
  task->SetBinCentralityLess(4,50.0);
  //task->SetBinCentralityLess(5,60.0);
  //task->SetBinCentralityLess(7,80.0);

  if(debuglevel==3) {

    //***************************************//
    //    test   Configure NPE plugin        //
    //***************************************//

    AliHFENonPhotonicElectron *backe = new AliHFENonPhotonicElectron(Form("HFEBackGroundSubtractionPID2%s",appendixx.Data()),"Background subtraction");  //appendix
    //Setting the Cuts for the Associated electron-pool
    AliHFEcuts *hfeBackgroundCuts = new AliHFEcuts(Form("HFEBackSub%s",appendixx.Data()),"Background sub Cuts");
    //hfeBackgroundCuts->SetEtaRange(assETA);
    hfeBackgroundCuts->SetEtaRange(-0.8,0.8);
    hfeBackgroundCuts->SetPtRange(0.1,1e10);
    hfeBackgroundCuts->SetMaxChi2perClusterTPC(4);
    hfeBackgroundCuts->SetMinNClustersITS(ITSclustersback);
    hfeBackgroundCuts->SetMinNClustersTPC(100);
    hfeBackgroundCuts->SetMinNClustersTPCPID(80);
    hfeBackgroundCuts->SetMaxImpactParam(1.,2.);
    hfeBackgroundCuts->SetAODFilterBit(4);
    //hfeBackgroundCuts->SetQAOn();			        // QA break

    AliHFEpid *pidbackground = backe->GetPIDBackground();
    pidbackground->AddDetector("TPC", 0);
    pidbackground->ConfigureTPCasymmetric(0.0,9999.,minTPCback,maxTPCback);
    backe->GetPIDBackgroundQAManager()->SetHighResolutionHistos();
    backe->SetHFEBackgroundCuts(hfeBackgroundCuts);

    // Selection of associated tracks for the pool
    backe->SelectCategory1Tracks(kTRUE);
    /*
      if(useCat2Tracks){
      backe->SelectCategory2Tracks(kTRUE);
      backe-> SetITSMeanShift(-0.5);
      }
    */

    // apply opening angle cut to reduce file size
    backe->SetMaxInvMass(0.3);

    task->SetHFEBackgroundSubtraction(backe);
    //AliLog::SetClassDebugLevel("AliAnalysisTaskHFEFlowTPCTOFEPSP",3);
    /////////////////////////////////////////////
    /////////////////////////////////////////////

  }

  if(ptbinsmall){

    Int_t nBinsPt = 33;
    Double_t binLimPt[34] = {0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1., 1.1, 1.2,
			     1.3, 1.4, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3.,3.25, 3.5, 3.75, 4.,4.25,4.5,4.75,5.,5.25,5.5,5.75,6.};
    task.SetPtBinning(nBinsPt+1, binLimPt);

  }

  task->SetHFEVZEROEventPlane(0x0);
  //AliLog::SetClassDebugLevel("AliAnalysisTaskHFEFlow",3);

  mgr->AddTask(task);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":";
  containerName += appendixx.Data();

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("list_%s",appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data()));
  mgr->ConnectInput(task,0, cinput );

  return NULL;

}
<commit_msg>Bug fix<commit_after>AliAnalysisTask *AddTaskHFEFlowTPCTOFEPSP(UInt_t trigger=131073,Int_t aodfilter=16,Bool_t scalarProduct=kFALSE,Bool_t cutPileup=kFALSE,Int_t tpcCls=110, Double_t tpcClsr=60, Int_t tpcClspid=80, Int_t itsCls=4, Int_t pixellayer=2, Double_t dcaxy=100,Double_t dcaz=200, Double_t tofsig=30., Double_t tpceff=50., Int_t vzero=1, Int_t debuglevel=2, Double_t etarange=80, Bool_t ptbinsmall=kFALSE, Double_t ITSclustersback=0, Double_t minTPCback=-2.0, Double_t maxTPCback=5.0){

  //
  // Define TPC cut for 2011 data
  //
  Double_t tpcdedx[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; //0-5,5-10,10-20,20-30,30-40,40-50,50-60,60-100
  // -0.2 0-5%
  // -0.15 5-10%
  // -0.1 10-20%
  // -0.0 20-30%, sigma=1.17
  // 0.156 30-40%, sigma=1.2
  // 0.19 40-50%, sigma=1.2
  // 0.2 50-60%
  // 0.2 60-80% list_t65536f16TPC110r60p80s11km0ITS4C36Pi2DCAr100z200TOF30TPCe50V1D0er8i0t-20t50
  tpcdedx[0]=-0.2;
  tpcdedx[1]=-0.15;
  tpcdedx[2]=-0.1;
  tpcdedx[3]=0.0;
  tpcdedx[4]=0.156;
  tpcdedx[5]=0.19;
  tpcdedx[6]=0.2;
  tpcdedx[7]=0.2;
  if(TMath::Abs(tpceff-55)<0.01) {
    tpcdedx[0]=-0.365;
    tpcdedx[1]=-0.314;
    tpcdedx[2]=-0.267;
    tpcdedx[3]=-0.165;
    tpcdedx[4]=-0.022;
    tpcdedx[5]= 0.01;
    tpcdedx[6]= 0.018;
    tpcdedx[7]= 0.018;
  }
  if(TMath::Abs(tpceff-45)<0.01) {
    tpcdedx[0]=-0.062;
    tpcdedx[1]=-0.015;
    tpcdedx[2]=0.035;
    tpcdedx[3]=0.131;
    tpcdedx[4]=0.278;
    tpcdedx[5]=0.32;
    tpcdedx[6]=0.32;
    tpcdedx[7]=0.32;
  }
  if(TMath::Abs(tpceff-60)<0.01) {
    tpcdedx[0]=-0.518;
    tpcdedx[1]=-0.47;
    tpcdedx[2]=-0.42;
    tpcdedx[3]=-0.315;
    tpcdedx[4]=-0.178;
    tpcdedx[5]=-0.145;
    tpcdedx[6]=-0.135;
    tpcdedx[7]=-0.135;
  }
  if(TMath::Abs(tpceff-40)<0.01) {
    tpcdedx[0]=0.09;
    tpcdedx[1]=0.14;
    tpcdedx[2]=0.188;
    tpcdedx[3]=0.28;
    tpcdedx[4]=0.43;
    tpcdedx[5]=0.462;
    tpcdedx[6]=0.473;
    tpcdedx[7]=0.473;
  }

  // Name
  TString appendixx(TString::Format("t%df%ds%dp%dTPC%dr%dp%dITS%dPi%dDCAr%dz%dTOF%dTPCe%dV%dD%der%dbin%di%dt%dt%d",(Int_t)trigger,aodfilter,(Int_t)scalarProduct,(Int_t)cutPileup,tpcCls,(Int_t)tpcClsr,tpcClspid,itsCls,(Int_t) pixellayer,(Int_t) dcaxy,(Int_t)dcaz,(Int_t) tofsig,(Int_t)tpceff,vzero,debuglevel,(Int_t)(etarange*0.1),(Int_t)ptbinsmall,(Int_t)ITSclustersback,(Int_t)(minTPCback*10.0),(Int_t)(maxTPCback*10.0)));
  //TString appendixx("tpctofv2");

  //set config file name
  TString configFile("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  //TString configFile("/hera/alice/bailhach/AliRootInstallations/30_09_2013/AliRoot/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  TString checkconfig="ConfigHFE_FLOW_TOFTPC";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskFlowTPCTOFEPSP *task = ConfigHFE_FLOW_TOFTPC(kFALSE,appendixx,trigger,aodfilter,scalarProduct,cutPileup,tpcCls, tpcClsr, tpcClspid, itsCls, pixellayer, dcaxy, dcaz,tofsig,&tpcdedx[0],vzero,debuglevel,etarange,kFALSE,ITSclustersback,minTPCback,maxTPCback);

  task->SetNbBinsCentralityQCumulant(4);
  //task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(1,10.0);
  task->SetBinCentralityLess(2,20.0);
  task->SetBinCentralityLess(3,40.0);
  task->SetBinCentralityLess(4,50.0);
  //task->SetBinCentralityLess(5,60.0);
  //task->SetBinCentralityLess(7,80.0);

  if(debuglevel==3) {

    //***************************************//
    //    test   Configure NPE plugin        //
    //***************************************//

    AliHFENonPhotonicElectron *backe = new AliHFENonPhotonicElectron(Form("HFEBackGroundSubtractionPID2%s",appendixx.Data()),"Background subtraction");  //appendix
    //Setting the Cuts for the Associated electron-pool
    AliHFEcuts *hfeBackgroundCuts = new AliHFEcuts(Form("HFEBackSub%s",appendixx.Data()),"Background sub Cuts");
    //hfeBackgroundCuts->SetEtaRange(assETA);
    hfeBackgroundCuts->SetEtaRange(-0.8,0.8);
    hfeBackgroundCuts->SetPtRange(0.1,1e10);
    hfeBackgroundCuts->SetMaxChi2perClusterTPC(4);
    hfeBackgroundCuts->SetMinNClustersITS(ITSclustersback);
    hfeBackgroundCuts->SetMinNClustersTPC(100);
    hfeBackgroundCuts->SetMinNClustersTPCPID(80);
    hfeBackgroundCuts->SetMaxImpactParam(1.,2.);
    hfeBackgroundCuts->SetAODFilterBit(4);
    //hfeBackgroundCuts->SetQAOn();			        // QA break

    AliHFEpid *pidbackground = backe->GetPIDBackground();
    pidbackground->AddDetector("TPC", 0);
    pidbackground->ConfigureTPCasymmetric(0.0,9999.,minTPCback,maxTPCback);
    backe->GetPIDBackgroundQAManager()->SetHighResolutionHistos();
    backe->SetHFEBackgroundCuts(hfeBackgroundCuts);

    // Selection of associated tracks for the pool
    backe->SelectCategory1Tracks(kTRUE);
    /*
      if(useCat2Tracks){
      backe->SelectCategory2Tracks(kTRUE);
      backe-> SetITSMeanShift(-0.5);
      }
    */

    // apply opening angle cut to reduce file size
    backe->SetMaxInvMass(0.3);

    task->SetHFEBackgroundSubtraction(backe);
    //AliLog::SetClassDebugLevel("AliAnalysisTaskHFEFlowTPCTOFEPSP",3);
    /////////////////////////////////////////////
    /////////////////////////////////////////////

  }

  if(ptbinsmall){

    Int_t nBinsPt = 33;
    Double_t binLimPt[34] = {0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1., 1.1, 1.2,
			     1.3, 1.4, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3.,3.25, 3.5, 3.75, 4.,4.25,4.5,4.75,5.,5.25,5.5,5.75,6.};
    task.SetPtBinning(nBinsPt, binLimPt);

  }

  task->SetHFEVZEROEventPlane(0x0);
  //AliLog::SetClassDebugLevel("AliAnalysisTaskHFEFlow",3);

  mgr->AddTask(task);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":";
  containerName += appendixx.Data();

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("list_%s",appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data()));
  mgr->ConnectInput(task,0, cinput );

  return NULL;

}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// Macro to setup AliPerformanceTask for
// TPC performance QA to run on PWG1 QA train.
//
// Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional)
// ESD and MC input handlers must be attached to AliAnalysisManager
// to run default configuration.
//
// By default 1 performance components are added to
// the task:
// 1. AliPerformanceTPC (TPC cluster and track and event information)
// 2. AliPerformancedEdx (TPC dEdx information)
//
// Usage on the analysis train (default configuration):
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libTPCcalib.so");
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
//
// gROOT->LoadMacro("$ALICE_ROOT/PWG1/TPC/macros/AddTaskPerformanceTPCdEdxQA.C");
// AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","triggerClass");
//
// Output:
// TPC.Performance.root file with TPC performance components is created.
//
// Each of the components contains THnSparse generic histograms which
// have to be analysed (post-analysis) by using Analyse() function.
// Each component contains such function.
//
//30.09.2010 -  J.Otwinowski@gsi.de
///////////////////////////////////////////////////////////////////////////////

//____________________________________________
AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, const char *triggerClass=0)
{
  //
  // Add AliPerformanceTask with TPC performance components
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if(!mgr) {
    Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!");
    return NULL;
  }

  TString type = mgr->GetInputEventHandler()->GetDataType();
  if (!type.Contains("ESD")) {
    Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!");
    return NULL;
  }

  AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
  if (!mcH && bUseMCInfo) {
    Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!");
    return NULL;
  }

  //
  // Create task
  //
  AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA","TPC Performance");
  if (!task) {
    Error("AddTaskPerformanceTPCdEdxQA", "TPC performance task cannot be created!");
    return NULL;
  }
  task->SetUseMCInfo(bUseMCInfo);
  task->SetUseESDfriend(bUseESDfriend);

  //
  // Add task to analysis manager
  //
  mgr->AddTask(task);

  //
  // Create TPC-ESD track reconstruction cuts
  // MB tracks
  //
  AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts();
  if(pRecInfoCutsTPC) {
    pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0);
    pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0);
    pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE);
    pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE);
    pRecInfoCutsTPC->SetAcceptKinkDaughters(kTRUE);
    pRecInfoCutsTPC->SetMinNClustersTPC(70);
    pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(1000000.);
    pRecInfoCutsTPC->SetDCAToVertex2D(kFALSE);

    pRecInfoCutsTPC->SetHistogramsOn(kFALSE);
  }
  else {
    Error("AddTaskPerformanceTPC", "AliRecInfoCutsTPC cannot be created!");
    return NULL;
  }

  //
  // Create TPC-MC track reconstruction cuts
  //
  AliMCInfoCuts  *pMCInfoCuts = new AliMCInfoCuts();
  if(pMCInfoCuts) {
    pMCInfoCuts->SetMinTrackLength(70);
  }
  else {
    Error("AddTaskPerformanceTPC", "AliMCInfoCuts cannot be created!");
    return NULL;
  }

  //
  // Create performance objects for TPC and set cuts
  //
  enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec };

  //
  // TPC performance
  //
  AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE);
  if(!pCompTPC0) {
    Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceTPC");
  }
  pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC);
  pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts);
  pCompTPC0->SetUseTrackVertex(kFALSE);
  pCompTPC0->SetUseHLT(kFALSE);
  //
  // dEdx
  //
  AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE);
  if(!pCompDEdx3) {
    Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceDEdxTPCInner");
  }
  pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC);
  pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts);
  pCompDEdx3->SetUseTrackVertex(kFALSE);

  //
  // Add components to the performance task
  //
  if(!bUseMCInfo) {
    pCompTPC0->SetTriggerClass(triggerClass);
    pCompDEdx3->SetTriggerClass(triggerClass);
  }
  task->AddPerformanceObject( pCompTPC0 );
  task->AddPerformanceObject( pCompDEdx3 );

  //
  // Create containers for input
  //
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());

  //
  // Create containers for output
  //
  AliAnalysisDataContainer *coutput_tpc = mgr->CreateContainer("TPCQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TPC_%s", mgr->GetCommonFileName(), task->GetName()));

  AliAnalysisDataContainer *coutput2_tpc = mgr->CreateContainer("TPCQASummary", TTree::Class(), AliAnalysisManager::kOutputContainer, "SummaryTPCQA.root");

  mgr->ConnectOutput(task, 1, coutput_tpc);
  mgr->ConnectOutput(task, 2, coutput2_tpc);

return task;
}
<commit_msg>Changed trending output container to kParam container so that it is handled automatically by the framework. The trending output is written to trending.root in the folder SummaryTPCQA.<commit_after>///////////////////////////////////////////////////////////////////////////////
// Macro to setup AliPerformanceTask for
// TPC performance QA to run on PWG1 QA train.
//
// Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional)
// ESD and MC input handlers must be attached to AliAnalysisManager
// to run default configuration.
//
// By default 1 performance components are added to
// the task:
// 1. AliPerformanceTPC (TPC cluster and track and event information)
// 2. AliPerformancedEdx (TPC dEdx information)
//
// Usage on the analysis train (default configuration):
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libTPCcalib.so");
// gSystem->Load("libTENDER.so");
// gSystem->Load("libPWG1.so");
//
// gROOT->LoadMacro("$ALICE_ROOT/PWG1/TPC/macros/AddTaskPerformanceTPCdEdxQA.C");
// AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","triggerClass");
//
// Output:
// TPC.Performance.root file with TPC performance components is created.
//
// Each of the components contains THnSparse generic histograms which
// have to be analysed (post-analysis) by using Analyse() function.
// Each component contains such function.
//
//30.09.2010 -  J.Otwinowski@gsi.de
///////////////////////////////////////////////////////////////////////////////

//____________________________________________
AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, const char *triggerClass=0)
{
  //
  // Add AliPerformanceTask with TPC performance components
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if(!mgr) {
    Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!");
    return NULL;
  }

  TString type = mgr->GetInputEventHandler()->GetDataType();
  if (!type.Contains("ESD")) {
    Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!");
    return NULL;
  }

  AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
  if (!mcH && bUseMCInfo) {
    Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!");
    return NULL;
  }

  //
  // Create task
  //
  AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA","TPC Performance");
  if (!task) {
    Error("AddTaskPerformanceTPCdEdxQA", "TPC performance task cannot be created!");
    return NULL;
  }
  task->SetUseMCInfo(bUseMCInfo);
  task->SetUseESDfriend(bUseESDfriend);

  //
  // Add task to analysis manager
  //
  mgr->AddTask(task);

  //
  // Create TPC-ESD track reconstruction cuts
  // MB tracks
  //
  AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts();
  if(pRecInfoCutsTPC) {
    pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0);
    pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0);
    pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE);
    pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE);
    pRecInfoCutsTPC->SetAcceptKinkDaughters(kTRUE);
    pRecInfoCutsTPC->SetMinNClustersTPC(70);
    pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(1000000.);
    pRecInfoCutsTPC->SetDCAToVertex2D(kFALSE);

    pRecInfoCutsTPC->SetHistogramsOn(kFALSE);
  }
  else {
    Error("AddTaskPerformanceTPC", "AliRecInfoCutsTPC cannot be created!");
    return NULL;
  }

  //
  // Create TPC-MC track reconstruction cuts
  //
  AliMCInfoCuts  *pMCInfoCuts = new AliMCInfoCuts();
  if(pMCInfoCuts) {
    pMCInfoCuts->SetMinTrackLength(70);
  }
  else {
    Error("AddTaskPerformanceTPC", "AliMCInfoCuts cannot be created!");
    return NULL;
  }

  //
  // Create performance objects for TPC and set cuts
  //
  enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec };

  //
  // TPC performance
  //
  AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE);
  if(!pCompTPC0) {
    Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceTPC");
  }
  pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC);
  pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts);
  pCompTPC0->SetUseTrackVertex(kFALSE);
  pCompTPC0->SetUseHLT(kFALSE);
  //
  // dEdx
  //
  AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE);
  if(!pCompDEdx3) {
    Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceDEdxTPCInner");
  }
  pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC);
  pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts);
  pCompDEdx3->SetUseTrackVertex(kFALSE);

  //
  // Add components to the performance task
  //
  if(!bUseMCInfo) {
    pCompTPC0->SetTriggerClass(triggerClass);
    pCompDEdx3->SetTriggerClass(triggerClass);
  }
  task->AddPerformanceObject( pCompTPC0 );
  task->AddPerformanceObject( pCompDEdx3 );

  //
  // Create containers for input
  //
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());

  //
  // Create containers for output
  //
  AliAnalysisDataContainer *coutput_tpc = mgr->CreateContainer("TPCQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TPC_%s", mgr->GetCommonFileName(), task->GetName()));

  AliAnalysisDataContainer *coutput2_tpc = mgr->CreateContainer("TPCQASummary", TTree::Class(), AliAnalysisManager::kParamContainer, "trending.root:SummaryTPCQA");

  mgr->ConnectOutput(task, 1, coutput_tpc);
  mgr->ConnectOutput(task, 2, coutput2_tpc);

return task;
}
<|endoftext|>