<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <algorithm>

#include "model_morphodita_parsito.h"
#include "utils/getpara.h"
#include "utils/parse_int.h"

namespace ufal {
namespace udpipe {

input_format* model_morphodita_parsito::new_tokenizer(const string& options) const {
  named_values::map parsed_options;
  string parse_error;
  if (!named_values::parse(options, parsed_options, parse_error))
    return nullptr;

  input_format* result = tokenizer_factory ? new tokenizer_morphodita(tokenizer_factory->new_tokenizer(), *splitter.get()) : nullptr;

  return parsed_options.count("presegmented") ? input_format::new_presegmented_tokenizer(result) : result;
}

bool model_morphodita_parsito::tag(sentence& s, const string& /*options*/, string& error) const {
  error.clear();

  if (taggers.empty()) return error.assign("No tagger defined for the UDPipe model!"), false;

  tagger_cache* c = tagger_caches.pop();
  if (!c) c = new tagger_cache();

  // Prepare input forms
  c->forms.clear();
  for (size_t i = 1; i < s.words.size(); i++)
    c->forms.emplace_back(s.words[i].form);

  // Clear first
  for (size_t i = 1; i < s.words.size(); i++) {
    s.words[i].lemma.assign("_");
    s.words[i].upostag.clear();
    s.words[i].xpostag.clear();
    s.words[i].feats.clear();
  }

  // Fill information from the tagger models
  for (auto&& tagger : taggers) {
    if (!tagger.tagger) return error.assign("No tagger defined for the UDPipe model!"), false;

    tagger.tagger->tag(c->forms, c->lemmas);

    for (size_t i = 0; i < c->lemmas.size(); i++)
      fill_word_analysis(c->lemmas[i], tagger.upostag, tagger.lemma, tagger.xpostag, tagger.feats, s.words[i+1]);
  }

  tagger_caches.push(c);
  return true;
}

bool model_morphodita_parsito::parse(sentence& s, const string& options, string& error) const {
  error.clear();

  if (!parser) return error.assign("No parser defined for the UDPipe model!"), false;

  parser_cache* c = parser_caches.pop();
  if (!c) c = new parser_cache();

  int beam_search = 5;
  if (!named_values::parse(options, c->options, error))
    return false;
  if (c->options.count("beam_search"))
    if (!parse_int(c->options["beam_search"], "beam_search", beam_search, error))
      return false;

  c->tree.clear();
  for (size_t i = 1; i < s.words.size(); i++) {
    c->tree.add_node(s.words[i].form);
    c->tree.nodes.back().lemma.assign(s.words[i].lemma);
    c->tree.nodes.back().upostag.assign(s.words[i].upostag);
    c->tree.nodes.back().xpostag.assign(s.words[i].xpostag);
    c->tree.nodes.back().feats.assign(s.words[i].feats);
    c->tree.nodes.back().deps.assign(s.words[i].deps);
    c->tree.nodes.back().misc.assign(s.words[i].misc);
  }

  parser->parse(c->tree, beam_search);
  for (size_t i = 1; i < s.words.size(); i++)
    s.set_head(i, c->tree.nodes[i].head, c->tree.nodes[i].deprel);

  parser_caches.push(c);
  return true;
}

model* model_morphodita_parsito::load(istream& is) {
  char version;
  if (!is.get(version)) return nullptr;

  unique_ptr<model_morphodita_parsito> m(new model_morphodita_parsito());
  if (!m) return nullptr;

  char tokenizer;
  if (!is.get(tokenizer)) return nullptr;
  m->tokenizer_factory.reset(tokenizer ? morphodita::tokenizer_factory::load(is) : nullptr);
  if (tokenizer && !m->tokenizer_factory) return nullptr;
  m->splitter.reset(tokenizer ? multiword_splitter::load(is) : nullptr);
  if (tokenizer && !m->splitter) return nullptr;

  m->taggers.clear();
  char taggers; if (!is.get(taggers)) return nullptr;
  for (char i = 0; i < taggers; i++) {
    char lemma; if (!is.get(lemma)) return nullptr;
    char xpostag; if (!is.get(xpostag)) return nullptr;
    char feats; if (!is.get(feats)) return nullptr;
    morphodita::tagger* tagger = morphodita::tagger::load(is);
    if (!tagger) return nullptr;
    m->taggers.emplace_back(i == 0, int(lemma), bool(xpostag), bool(feats), tagger);
  }

  char parser;
  if (!is.get(parser)) return nullptr;
  m->parser.reset(parser ? parsito::parser::load(is) : nullptr);
  if (parser && !m->parser) return nullptr;

  return m.release();
}

model_morphodita_parsito::tokenizer_morphodita::tokenizer_morphodita(morphodita::tokenizer* tokenizer, const multiword_splitter& splitter)
  : tokenizer(tokenizer), splitter(splitter) {}

bool model_morphodita_parsito::tokenizer_morphodita::read_block(istream& is, string& block) const {
  return bool(getpara(is, block));
}

void model_morphodita_parsito::tokenizer_morphodita::set_text(string_piece text, bool make_copy) {
  tokenizer->set_text(text, make_copy);
}

bool model_morphodita_parsito::tokenizer_morphodita::next_sentence(sentence& s, string& error) {
  s.clear();
  error.clear();
  if (tokenizer->next_sentence(&forms, nullptr)) {
    for (size_t i = 0; i < forms.size(); i++)
      splitter.append_token(forms[i], i+1 < forms.size() && forms[i+1].str == forms[i].str + forms[i].len ? "SpaceAfter=No" : "", s);
    return true;
  }

  return false;
}

void model_morphodita_parsito::fill_word_analysis(const morphodita::tagged_lemma& analysis, bool upostag, int lemma, bool xpostag, bool feats, word& word){
  // Lemma
  if (lemma == 1) {
    word.lemma.assign(analysis.lemma);
  } else if (lemma == 2) {
    word.lemma.assign(analysis.lemma);

    // Lemma matching ~replacement~original_form is changed to replacement.
    if (analysis.lemma[0] == '~') {
      auto end = analysis.lemma.find('~', 1);
      if (end != string::npos && analysis.lemma.compare(end + 1, string::npos, word.form) == 0)
        word.lemma.assign(analysis.lemma, 1, end - 1);
    }
  }

  if (!upostag && !xpostag && !feats) return;

  // UPOSTag
  char separator = analysis.tag[0];
  size_t start = min(size_t(1), analysis.tag.size()), end = min(analysis.tag.find(separator, 1), analysis.tag.size());
  if (upostag) word.upostag.assign(analysis.tag, start, end - start);

  if (!xpostag && !feats) return;

  // XPOSTag
  start = min(end + 1, analysis.tag.size());
  end = min(analysis.tag.find(separator, start), analysis.tag.size());
  if (xpostag) word.xpostag.assign(analysis.tag, start, end - start);

  if (!feats) return;

  // Features
  start = min(end + 1, analysis.tag.size());
  word.feats.assign(analysis.tag, start, analysis.tag.size() - start);
}

} // namespace udpipe
} // namespace ufal
<commit_msg>Add forgotten version check.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <algorithm>

#include "model_morphodita_parsito.h"
#include "utils/getpara.h"
#include "utils/parse_int.h"

namespace ufal {
namespace udpipe {

input_format* model_morphodita_parsito::new_tokenizer(const string& options) const {
  named_values::map parsed_options;
  string parse_error;
  if (!named_values::parse(options, parsed_options, parse_error))
    return nullptr;

  input_format* result = tokenizer_factory ? new tokenizer_morphodita(tokenizer_factory->new_tokenizer(), *splitter.get()) : nullptr;

  return parsed_options.count("presegmented") ? input_format::new_presegmented_tokenizer(result) : result;
}

bool model_morphodita_parsito::tag(sentence& s, const string& /*options*/, string& error) const {
  error.clear();

  if (taggers.empty()) return error.assign("No tagger defined for the UDPipe model!"), false;

  tagger_cache* c = tagger_caches.pop();
  if (!c) c = new tagger_cache();

  // Prepare input forms
  c->forms.clear();
  for (size_t i = 1; i < s.words.size(); i++)
    c->forms.emplace_back(s.words[i].form);

  // Clear first
  for (size_t i = 1; i < s.words.size(); i++) {
    s.words[i].lemma.assign("_");
    s.words[i].upostag.clear();
    s.words[i].xpostag.clear();
    s.words[i].feats.clear();
  }

  // Fill information from the tagger models
  for (auto&& tagger : taggers) {
    if (!tagger.tagger) return error.assign("No tagger defined for the UDPipe model!"), false;

    tagger.tagger->tag(c->forms, c->lemmas);

    for (size_t i = 0; i < c->lemmas.size(); i++)
      fill_word_analysis(c->lemmas[i], tagger.upostag, tagger.lemma, tagger.xpostag, tagger.feats, s.words[i+1]);
  }

  tagger_caches.push(c);
  return true;
}

bool model_morphodita_parsito::parse(sentence& s, const string& options, string& error) const {
  error.clear();

  if (!parser) return error.assign("No parser defined for the UDPipe model!"), false;

  parser_cache* c = parser_caches.pop();
  if (!c) c = new parser_cache();

  int beam_search = 5;
  if (!named_values::parse(options, c->options, error))
    return false;
  if (c->options.count("beam_search"))
    if (!parse_int(c->options["beam_search"], "beam_search", beam_search, error))
      return false;

  c->tree.clear();
  for (size_t i = 1; i < s.words.size(); i++) {
    c->tree.add_node(s.words[i].form);
    c->tree.nodes.back().lemma.assign(s.words[i].lemma);
    c->tree.nodes.back().upostag.assign(s.words[i].upostag);
    c->tree.nodes.back().xpostag.assign(s.words[i].xpostag);
    c->tree.nodes.back().feats.assign(s.words[i].feats);
    c->tree.nodes.back().deps.assign(s.words[i].deps);
    c->tree.nodes.back().misc.assign(s.words[i].misc);
  }

  parser->parse(c->tree, beam_search);
  for (size_t i = 1; i < s.words.size(); i++)
    s.set_head(i, c->tree.nodes[i].head, c->tree.nodes[i].deprel);

  parser_caches.push(c);
  return true;
}

model* model_morphodita_parsito::load(istream& is) {
  char version;
  if (!is.get(version)) return nullptr;
  if (version != 1) return nullptr;

  unique_ptr<model_morphodita_parsito> m(new model_morphodita_parsito());
  if (!m) return nullptr;

  char tokenizer;
  if (!is.get(tokenizer)) return nullptr;
  m->tokenizer_factory.reset(tokenizer ? morphodita::tokenizer_factory::load(is) : nullptr);
  if (tokenizer && !m->tokenizer_factory) return nullptr;
  m->splitter.reset(tokenizer ? multiword_splitter::load(is) : nullptr);
  if (tokenizer && !m->splitter) return nullptr;

  m->taggers.clear();
  char taggers; if (!is.get(taggers)) return nullptr;
  for (char i = 0; i < taggers; i++) {
    char lemma; if (!is.get(lemma)) return nullptr;
    char xpostag; if (!is.get(xpostag)) return nullptr;
    char feats; if (!is.get(feats)) return nullptr;
    morphodita::tagger* tagger = morphodita::tagger::load(is);
    if (!tagger) return nullptr;
    m->taggers.emplace_back(i == 0, int(lemma), bool(xpostag), bool(feats), tagger);
  }

  char parser;
  if (!is.get(parser)) return nullptr;
  m->parser.reset(parser ? parsito::parser::load(is) : nullptr);
  if (parser && !m->parser) return nullptr;

  return m.release();
}

model_morphodita_parsito::tokenizer_morphodita::tokenizer_morphodita(morphodita::tokenizer* tokenizer, const multiword_splitter& splitter)
  : tokenizer(tokenizer), splitter(splitter) {}

bool model_morphodita_parsito::tokenizer_morphodita::read_block(istream& is, string& block) const {
  return bool(getpara(is, block));
}

void model_morphodita_parsito::tokenizer_morphodita::set_text(string_piece text, bool make_copy) {
  tokenizer->set_text(text, make_copy);
}

bool model_morphodita_parsito::tokenizer_morphodita::next_sentence(sentence& s, string& error) {
  s.clear();
  error.clear();
  if (tokenizer->next_sentence(&forms, nullptr)) {
    for (size_t i = 0; i < forms.size(); i++)
      splitter.append_token(forms[i], i+1 < forms.size() && forms[i+1].str == forms[i].str + forms[i].len ? "SpaceAfter=No" : "", s);
    return true;
  }

  return false;
}

void model_morphodita_parsito::fill_word_analysis(const morphodita::tagged_lemma& analysis, bool upostag, int lemma, bool xpostag, bool feats, word& word){
  // Lemma
  if (lemma == 1) {
    word.lemma.assign(analysis.lemma);
  } else if (lemma == 2) {
    word.lemma.assign(analysis.lemma);

    // Lemma matching ~replacement~original_form is changed to replacement.
    if (analysis.lemma[0] == '~') {
      auto end = analysis.lemma.find('~', 1);
      if (end != string::npos && analysis.lemma.compare(end + 1, string::npos, word.form) == 0)
        word.lemma.assign(analysis.lemma, 1, end - 1);
    }
  }

  if (!upostag && !xpostag && !feats) return;

  // UPOSTag
  char separator = analysis.tag[0];
  size_t start = min(size_t(1), analysis.tag.size()), end = min(analysis.tag.find(separator, 1), analysis.tag.size());
  if (upostag) word.upostag.assign(analysis.tag, start, end - start);

  if (!xpostag && !feats) return;

  // XPOSTag
  start = min(end + 1, analysis.tag.size());
  end = min(analysis.tag.find(separator, start), analysis.tag.size());
  if (xpostag) word.xpostag.assign(analysis.tag, start, end - start);

  if (!feats) return;

  // Features
  start = min(end + 1, analysis.tag.size());
  word.feats.assign(analysis.tag, start, analysis.tag.size() - start);
}

} // namespace udpipe
} // namespace ufal
<|endoftext|>


<commit_before>#include "dominantColors.hpp"
#include <iomanip>
#include <sstream>

namespace cloudcv
{

    template<int N>
    inline int quantize(int val)
    {
        val = val >> N;
        val = val << N;
        return val;
    }

    static inline int SQR(int val)
    {
        return val * val;
    }

    int Color::distanceTo(const cv::Vec3b& other) const
    {
        int r = hash & 0xFF;
        int g = (hash >> 8) & 0xFF;
        int b = (hash >> 16) & 0xFF;

        int other_r = other.val[2];
        int other_g = other.val[1];
        int other_b = other.val[0];

        return SQR(r - other_r) + SQR(g - other_g) + SQR(b - other_b);
    }

    int Color::distanceTo(const Color& other) const
    {
        int r = hash & 0xFF;
        int g = (hash >> 8) & 0xFF;
        int b = (hash >> 16) & 0xFF;

        int other_r = other.hash & 0xFF;
        int other_g = (other.hash >> 8) & 0xFF;
        int other_b = (other.hash >> 16) & 0xFF;

        return SQR(r - other_r) + SQR(g - other_g) + SQR(b - other_b);
    }

    std::string DominantColor::html() const
    {
        std::ostringstream sStream;
        sStream << "#" << std::hex << std::setw(2) << color[0]
                       << std::hex << std::setw(2) << color[1]
                       << std::hex << std::setw(2) << color[2];
        return sStream.str();
    }

    void DominantColorsExtractor::process(const cv::Mat_<cv::Vec3b>& bgrImage)
    {
        rVec.clear();
        gVec.clear();
        bVec.clear();

        fullColorsTable.clear();
        quantizedColorsTable.clear();

        for (int row = 0; row < bgrImage.rows; row++)
        {
            for (int col = 0; col < bgrImage.cols; col++)
            {
                cv::Vec3b clr = bgrImage(row, col);

                int b = clr[0];
                int g = clr[1];
                int r = clr[2];

                int hash1 = r + (b << 8) + (g << 16);
                int hash2 = quantize<2>(r) +(quantize<2>(g) << 8) + (quantize<2>(b) << 16);

                fullColorsTable[hash1]++;
                quantizedColorsTable[hash2]++;

                rVec.push_back(r);
                gVec.push_back(g);
                bVec.push_back(b);
            }
        }

        std::set<Color> colors;

        for (std::map<int, int>::const_iterator it = quantizedColorsTable.begin(); it != quantizedColorsTable.end(); ++it)
        {
            colors.insert(Color(it->first, it->second));
        }

        mainColors.clear();

        std::set<Color> mfc;
        std::set<Color> colorsSet = colors;

        int minPixelsInSet = static_cast<int>(bgrImage.rows * bgrImage.cols * 0.02); // Minimum amount for dominant color is 5% of the area of the image

        while (findLargestColorSet(3000, minPixelsInSet, colorsSet, mfc))
        {
            std::set<Color> restColors;
            std::set_difference(colorsSet.begin(), colorsSet.end(), mfc.begin(), mfc.end(), std::inserter(restColors, restColors.end()));
            colorsSet = restColors;

            DominantColor c = computeFinalColor(mfc);
            mainColors.push_back(c);

        }
    }

    DominantColor DominantColorsExtractor::computeFinalColor(const std::set<Color>& colorsSet) const
    {
        float final_r = 0, final_g = 0, final_b = 0;

        int totalPixels = 0;

        typedef std::set<Color>::const_iterator It;

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            totalPixels += it->count;
        }

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            Color c = *it;

            int r = c.hash & 0xFF;
            int g = (c.hash >> 8) & 0xFF;
            int b = (c.hash >> 16) & 0xFF;

            float weight = (float)c.count / (float)totalPixels;

            final_r += weight * r;
            final_g += weight * g;
            final_b += weight * b;
        }

        DominantColor dc;

        dc.color = cv::Vec3b
            (
            cv::saturate_cast<uint8_t>(final_b),
            cv::saturate_cast<uint8_t>(final_g),
            cv::saturate_cast<uint8_t>(final_r)
            );

        dc.totalPixels = totalPixels;
        dc.error = 0;

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            float weight = (float)it->count / (float)totalPixels;
            dc.error += weight * it->distanceTo(dc.color);
        }

        return dc;
    }

    bool DominantColorsExtractor::findLargestColorSet(int similarityTolerance, int minPixelsInSet, const std::set<Color>& input, std::set<Color>& colorsSet) const
    {
        colorsSet.clear();

        if (input.empty())
            return false;

        typedef std::set<Color>::const_iterator It;

        It largestColorIt = input.begin();
        int largestCount = largestColorIt->count;

        for (It it = input.begin(); it != input.end(); it++)
        {
            if (it->count > largestCount)
            {
                largestCount = it->count;
                largestColorIt = it;
            }
        }

        Color mfc = *largestColorIt;
        int totalPixelsInSet = 0;

        for (It it = input.begin(); it != input.end(); it++)
        {
            Color other = *it;
            int distance = mfc.distanceTo(other);

            if (distance < similarityTolerance)
            {
                totalPixelsInSet += other.count;
                colorsSet.insert(other);
            }
        }

        return !colorsSet.empty() && totalPixelsInSet > minPixelsInSet;
    }

    RGBDistribution DominantColorsExtractor::getColorDeviation() const
    {
        RGBDistribution cd;

        cd.r = distribution(rVec);
        cd.g = distribution(gVec);
        cd.b = distribution(bVec);

        return cd;
    }

    int DominantColorsExtractor::getUniqueColors() const
    {
        return fullColorsTable.size();
    }

    int DominantColorsExtractor::getRedicedColors() const
    {
        return quantizedColorsTable.size();
    }

    std::ostream& operator<<(std::ostream& out, const Color& res)
    {
        return out << "{ hash:" << res.hash << ", count: " << res.count << "}";
    }

    std::ostream& operator<<(std::ostream& out, const DominantColor& res)
    {
        return out << "{ color:" << res.color << ", totalPixels: " << res.totalPixels << "}";
    }

}
<commit_msg>Fix bug in html code generation<commit_after>#include "dominantColors.hpp"
#include <iomanip>
#include <sstream>

namespace cloudcv
{

    template<int N>
    inline int quantize(int val)
    {
        val = val >> N;
        val = val << N;
        return val;
    }

    static inline int SQR(int val)
    {
        return val * val;
    }

    int Color::distanceTo(const cv::Vec3b& other) const
    {
        int r = hash & 0xFF;
        int g = (hash >> 8) & 0xFF;
        int b = (hash >> 16) & 0xFF;

        int other_r = other.val[2];
        int other_g = other.val[1];
        int other_b = other.val[0];

        return SQR(r - other_r) + SQR(g - other_g) + SQR(b - other_b);
    }

    int Color::distanceTo(const Color& other) const
    {
        int r = hash & 0xFF;
        int g = (hash >> 8) & 0xFF;
        int b = (hash >> 16) & 0xFF;

        int other_r = other.hash & 0xFF;
        int other_g = (other.hash >> 8) & 0xFF;
        int other_b = (other.hash >> 16) & 0xFF;

        return SQR(r - other_r) + SQR(g - other_g) + SQR(b - other_b);
    }

    std::string DominantColor::html() const
    {
        std::ostringstream sStream;
        sStream << "#" << std::hex << std::setw(2) << (int)color[0]
                       << std::hex << std::setw(2) << (int)color[1]
                       << std::hex << std::setw(2) << (int)color[2];
        return sStream.str();
    }

    void DominantColorsExtractor::process(const cv::Mat_<cv::Vec3b>& bgrImage)
    {
        rVec.clear();
        gVec.clear();
        bVec.clear();

        fullColorsTable.clear();
        quantizedColorsTable.clear();

        for (int row = 0; row < bgrImage.rows; row++)
        {
            for (int col = 0; col < bgrImage.cols; col++)
            {
                cv::Vec3b clr = bgrImage(row, col);

                int b = clr[0];
                int g = clr[1];
                int r = clr[2];

                int hash1 = r + (b << 8) + (g << 16);
                int hash2 = quantize<2>(r) +(quantize<2>(g) << 8) + (quantize<2>(b) << 16);

                fullColorsTable[hash1]++;
                quantizedColorsTable[hash2]++;

                rVec.push_back(r);
                gVec.push_back(g);
                bVec.push_back(b);
            }
        }

        std::set<Color> colors;

        for (std::map<int, int>::const_iterator it = quantizedColorsTable.begin(); it != quantizedColorsTable.end(); ++it)
        {
            colors.insert(Color(it->first, it->second));
        }

        mainColors.clear();

        std::set<Color> mfc;
        std::set<Color> colorsSet = colors;

        int minPixelsInSet = static_cast<int>(bgrImage.rows * bgrImage.cols * 0.02); // Minimum amount for dominant color is 5% of the area of the image

        while (findLargestColorSet(3000, minPixelsInSet, colorsSet, mfc))
        {
            std::set<Color> restColors;
            std::set_difference(colorsSet.begin(), colorsSet.end(), mfc.begin(), mfc.end(), std::inserter(restColors, restColors.end()));
            colorsSet = restColors;

            DominantColor c = computeFinalColor(mfc);
            mainColors.push_back(c);

        }
    }

    DominantColor DominantColorsExtractor::computeFinalColor(const std::set<Color>& colorsSet) const
    {
        float final_r = 0, final_g = 0, final_b = 0;

        int totalPixels = 0;

        typedef std::set<Color>::const_iterator It;

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            totalPixels += it->count;
        }

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            Color c = *it;

            int r = c.hash & 0xFF;
            int g = (c.hash >> 8) & 0xFF;
            int b = (c.hash >> 16) & 0xFF;

            float weight = (float)c.count / (float)totalPixels;

            final_r += weight * r;
            final_g += weight * g;
            final_b += weight * b;
        }

        DominantColor dc;

        dc.color = cv::Vec3b
            (
            cv::saturate_cast<uint8_t>(final_b),
            cv::saturate_cast<uint8_t>(final_g),
            cv::saturate_cast<uint8_t>(final_r)
            );

        dc.totalPixels = totalPixels;
        dc.error = 0;

        for (It it = colorsSet.begin(); it != colorsSet.end(); it++)
        {
            float weight = (float)it->count / (float)totalPixels;
            dc.error += weight * it->distanceTo(dc.color);
        }

        return dc;
    }

    bool DominantColorsExtractor::findLargestColorSet(int similarityTolerance, int minPixelsInSet, const std::set<Color>& input, std::set<Color>& colorsSet) const
    {
        colorsSet.clear();

        if (input.empty())
            return false;

        typedef std::set<Color>::const_iterator It;

        It largestColorIt = input.begin();
        int largestCount = largestColorIt->count;

        for (It it = input.begin(); it != input.end(); it++)
        {
            if (it->count > largestCount)
            {
                largestCount = it->count;
                largestColorIt = it;
            }
        }

        Color mfc = *largestColorIt;
        int totalPixelsInSet = 0;

        for (It it = input.begin(); it != input.end(); it++)
        {
            Color other = *it;
            int distance = mfc.distanceTo(other);

            if (distance < similarityTolerance)
            {
                totalPixelsInSet += other.count;
                colorsSet.insert(other);
            }
        }

        return !colorsSet.empty() && totalPixelsInSet > minPixelsInSet;
    }

    RGBDistribution DominantColorsExtractor::getColorDeviation() const
    {
        RGBDistribution cd;

        cd.r = distribution(rVec);
        cd.g = distribution(gVec);
        cd.b = distribution(bVec);

        return cd;
    }

    int DominantColorsExtractor::getUniqueColors() const
    {
        return fullColorsTable.size();
    }

    int DominantColorsExtractor::getRedicedColors() const
    {
        return quantizedColorsTable.size();
    }

    std::ostream& operator<<(std::ostream& out, const Color& res)
    {
        return out << "{ hash:" << res.hash << ", count: " << res.count << "}";
    }

    std::ostream& operator<<(std::ostream& out, const DominantColor& res)
    {
        return out << "{ color:" << res.color << ", totalPixels: " << res.totalPixels << "}";
    }

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>

namespace mss
{

namespace workarounds
{

namespace wr_vref
{

///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[in] i_cal_steps_enabled - cal steps to exectue, used to see if WR VREF needs to be exectued
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                           const uint64_t i_rp,
                           const fapi2::buffer<uint16_t>& i_cal_steps_enabled,
                           uint8_t& o_vrefdq_train_range,
                           uint8_t& o_vrefdq_train_value )
{
    // Skip running WR VREF workarounds if:
    // 1) the chip does not need to have the workaround run
    // 2) WR VREF has not been requested in the calibration steps
    if ((! mss::chip_ec_feature_mss_wr_vref(i_target)) || (!i_cal_steps_enabled.getBit<WRITE_CTR_2D_VREF>()))
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
    FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));

fapi_try_exit:
    return fapi2::current_err;
}

} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<commit_msg>Remove ZQCAL redundant CCS inst, move to draminit_training<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>

namespace mss
{

namespace workarounds
{

namespace wr_vref
{

///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[in] i_cal_steps_enabled - cal steps to exectue, used to see if WR VREF needs to be exectued
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                           const uint64_t i_rp,
                           const fapi2::buffer<uint32_t>& i_cal_steps_enabled,
                           uint8_t& o_vrefdq_train_range,
                           uint8_t& o_vrefdq_train_value )
{
    // Skip running WR VREF workarounds if:
    // 1) the chip does not need to have the workaround run
    // 2) WR VREF has not been requested in the calibration steps
    if ((! mss::chip_ec_feature_mss_wr_vref(i_target)) || (!i_cal_steps_enabled.getBit<WRITE_CTR_2D_VREF>()))
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
    FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));

fapi_try_exit:
    return fapi2::current_err;
}

} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: invmerge.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:45:09 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <vcl/window.hxx>
#include <tools/debug.hxx>

#include "invmerge.hxx"

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

ScInvertMerger::ScInvertMerger( Window* pWindow ) :
    pWin( pWindow )
{
    //  both rectangles empty
}

ScInvertMerger::~ScInvertMerger()
{
    Flush();
}

void ScInvertMerger::Flush()
{
    FlushLine();
    FlushTotal();

    DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}

void ScInvertMerger::FlushTotal()
{
    if( aTotalRect.IsEmpty() )
        return;                         // nothing to do

    pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
    aTotalRect.SetEmpty();
}

void ScInvertMerger::FlushLine()
{
    if( aLineRect.IsEmpty() )
        return;                         // nothing to do

    if ( aTotalRect.IsEmpty() )
    {
        aTotalRect = aLineRect;         // start new total rect
    }
    else
    {
        if ( aLineRect.Left()  == aTotalRect.Left()  &&
             aLineRect.Right() == aTotalRect.Right() &&
             aLineRect.Top()   == aTotalRect.Bottom() + 1 )
        {
            // extend total rect
            aTotalRect.Bottom() = aLineRect.Bottom();
        }
        else
        {
            FlushTotal();                   // draw old total rect
            aTotalRect = aLineRect;         // and start new one
        }
    }

    aLineRect.SetEmpty();
}

void ScInvertMerger::AddRect( const Rectangle& rRect )
{
    if ( aLineRect.IsEmpty() )
    {
        aLineRect = rRect;          // start new line rect
    }
    else
    {
        if ( rRect.Top()    == aLineRect.Top()    &&
             rRect.Bottom() == aLineRect.Bottom() &&
             rRect.Left()   == aLineRect.Right() + 1 )
        {
            // extend line rect
            aLineRect.Right() = rRect.Right();
        }
        else
        {
            FlushLine();            // use old line rect for total rect
            aLineRect = rRect;      // and start new one
        }
    }
}

<commit_msg>INTEGRATION: CWS calcrtl (1.1.1.1.126); FILE MERGED 2003/06/30 17:21:41 nn 1.1.1.1.126.2: #106948# RTL layout, continued implementation 2003/03/14 19:38:12 nn 1.1.1.1.126.1: #106948# handle RTL layout<commit_after>/*************************************************************************
 *
 *  $RCSfile: invmerge.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 12:55:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <vcl/window.hxx>
#include <tools/debug.hxx>

#include "invmerge.hxx"

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

ScInvertMerger::ScInvertMerger( Window* pWindow ) :
    pWin( pWindow )
{
    //  both rectangles empty
}

ScInvertMerger::~ScInvertMerger()
{
    Flush();
}

void ScInvertMerger::Flush()
{
    FlushLine();
    FlushTotal();

    DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}

void ScInvertMerger::FlushTotal()
{
    if( aTotalRect.IsEmpty() )
        return;                         // nothing to do

    pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
    aTotalRect.SetEmpty();
}

void ScInvertMerger::FlushLine()
{
    if( aLineRect.IsEmpty() )
        return;                         // nothing to do

    if ( aTotalRect.IsEmpty() )
    {
        aTotalRect = aLineRect;         // start new total rect
    }
    else
    {
        if ( aLineRect.Left()  == aTotalRect.Left()  &&
             aLineRect.Right() == aTotalRect.Right() &&
             aLineRect.Top()   == aTotalRect.Bottom() + 1 )
        {
            // extend total rect
            aTotalRect.Bottom() = aLineRect.Bottom();
        }
        else
        {
            FlushTotal();                   // draw old total rect
            aTotalRect = aLineRect;         // and start new one
        }
    }

    aLineRect.SetEmpty();
}

void ScInvertMerger::AddRect( const Rectangle& rRect )
{
    if ( aLineRect.IsEmpty() )
    {
        aLineRect = rRect;          // start new line rect
    }
    else
    {
        Rectangle aJustified = rRect;
        if ( rRect.Left() > rRect.Right() )     // switch for RTL layout
        {
            aJustified.Left() = rRect.Right();
            aJustified.Right() = rRect.Left();
        }

        BOOL bDone = FALSE;
        if ( aJustified.Top()    == aLineRect.Top()    &&
             aJustified.Bottom() == aLineRect.Bottom() )
        {
            // try to extend line rect
            if ( aJustified.Left() == aLineRect.Right() + 1 )
            {
                aLineRect.Right() = aJustified.Right();
                bDone = TRUE;
            }
            else if ( aJustified.Right() + 1 == aLineRect.Left() )  // for RTL layout
            {
                aLineRect.Left() = aJustified.Left();
                bDone = TRUE;
            }
        }
        if (!bDone)
        {
            FlushLine();                // use old line rect for total rect
            aLineRect = aJustified;     // and start new one
        }
    }
}

<|endoftext|>


<commit_before>// Copyright 2013 Sean McKenna
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)

// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"

// namespace
using namespace scene;

// Sphere definition
class Sphere: public Object{
  public:

    // constructor
    Sphere(){
      center.Set(0, 0, 0);
      radius = 1.0;
    }

    // intsersect a ray against the unit sphere
    // ray must be transformed into model space, first
    bool intersectRay(Cone &r, HitInfo &h, int face=HIT_FRONT){

      // pre-compute values for quadratic solution
      Point pos = r.pos - center;
      float A = r.dir % r.dir;
      float B = 2.0 * pos % r.dir;
      float C = pos % pos - radius * radius;
      float det = (B * B) - (4 * A * C);

      // if the ray intersects, compute the z-buffer value
      if(det >= 0){
        float z1 = (-B - sqrt(det)) / (2.0 * A);
        float z2 = (-B + sqrt(det)) / (2.0 * A);

        // determine if we have a back hit
        if(z1 * z2 < 0.0)
          h.front = false;

        // if hit is too close, assume it is a back-face hit
        else if(z1 <= getBias())
          h.front = false;

        // check closest z-buffer value, if positive (ahead of our ray)
        if(z1 > getBias()){
          h.z = z1;

          // compute surface intersection, normal, and texture coordinates
          h.p = r.pos + z1 * r.dir;
          h.n = h.p.GetNormalized();
          h.uvw = getTexCoord(h.p);

          // calculate texture coordinate derivatives (approximate)
          Point minor;
          Point major;
          r.ellipseAt(h.z, h.n, major, minor);
          h.duvw[0] = minor;
          h.duvw[1] = major;

          // return true, ray is hit
          return true;

        // check the next ray, if necessary
        }else if(z2 > getBias()){
          h.z = z2;

          // compute surface intersection, normal, and texture coordinates
          h.p = r.pos + z2 * r.dir;
          h.n = h.p.GetNormalized();
          h.uvw = getTexCoord(h.p);

          // calculate texture coordinate derivatives (approximate)
          Point minor;
          Point major;
          r.ellipseAt(h.z, h.n, major, minor);
          h.duvw[0] = minor;
          h.duvw[1] = major;

          // return true, ray is hit
          return true;

        // otherwise, all z-buffer values are negative, return false
        }else
          return false;
      }

      // otherwise, return false (no ray hit)
      else
        return false;
    }

    // get sphere bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
    }

  private:

    // sphere center and its radius
    Point center;
    float radius;

    // get texture coordinates (spherical coordinates)
    Point getTexCoord(Point p){
      return Point(atan(p.x / p.y) / (2.0 * M_PI), acos(p.z / radius) / M_PI, 0.0);
    }
};

// Plane definition (a "unit" plane)
class Plane: public Object{
  public:

    // intersect a ray against the "unit" plane
    bool intersectRay(Cone &r, HitInfo &h, int face = HIT_FRONT){

      // only compute for rays not parallel to the unit plane
      if(r.dir.z > getBias() || r.dir.z < getBias()){

        // compute distance along ray direction to plane
        float t = -r.pos.z / r.dir.z;

        // only accept hits in front of ray (with some bias)
        if(t > getBias()){

          // compute the hit point
          Point hit = r.pos + t * r.dir;

          // only allow a hit to occur if on the "unit" plane
          if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){

            // detect back face hits
            if(r.pos.z < 0.0)
              h.front = false;

            // distance to hit
            h.z = t;

            // set hit point, normal, texture coordinate
            h.p = hit;
            h.n = Point(0.0, 0.0, 1.0);
            h.uvw = getTexCoord(hit);

            // calculate texture coordinate derivatives (approximate)
            Point minor;
            Point major;
            r.ellipseAt(h.z, h.n, major, minor);
            h.duvw[0] = minor * 2.0;
            h.duvw[1] = major * 2.0;

            // return hit
            return true;
          }
        }
      }

      // when no ray hits the "unit" plane
      return false;
    }

    // get plane bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
    }

  // get the texture coordinate on the unit plane
  private:
    Point getTexCoord(Point p){
      return (p + 1.0) / 2.0;
    }
};

// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
  public:

    // intersect a ray against the triangular mesh
    bool intersectRay(Cone &r, HitInfo &h, int face = HIT_FRONT){

      // check our BVH for triangular faces, update hit info
      bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());

      // return hit info from intersecting rays in the BVH faces
      return triang;
    }

    // get triangular mesh bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(GetBoundMin(), GetBoundMax());
    }

    // when loading a triangular mesh, get its bounding box
    bool load(string file){
      bvh.Clear();
      if(!LoadFromFileObj(file.c_str()))
        return false;
      if(!HasNormals())
        ComputeNormals();
      ComputeBoundingBox();
      bvh.SetMesh(this,4);
      return true;
    }

  private:

    // add BVH for each triangular mesh
    cyBVHTriMesh bvh;

    // intersect a ray with a single triangle (Moller-Trumbore algorithm)
    bool intersectTriangle(Cone &r, HitInfo &h, int face, int faceID){

      // grab vertex points
      Point a = V(F(faceID).v[0]);
      Point b = V(F(faceID).v[1]);
      Point c = V(F(faceID).v[2]);

      // compute edge vectors
      Point e1 = b - a;
      Point e2 = c - a;

      // calculate first vector, P
      Point P = r.dir ^ e2;

      // calculate the determinant of the matrix equation
      float determ = e1 % P;

      // only continue for valid determinant ranges
      if(abs(determ) > getBias()){

        // calculate second vector, T
        Point T = r.pos - a;

        // calculate a barycentric component (u)
        float u = T % P;

        // only allow valid barycentric values
        if(u > -getBias() && u < determ * (1.0 + getBias())){

          // calculate a normal of the ray with an edge vector
          Point Q = T ^ e1;

          // calculate a barycentric component (v)
          float v = r.dir % Q;

          // only allow valid barycentric values
          if(v > -getBias() && v + u < determ * (1.0 + getBias())){

            // update barycentric coordinates
            v /= determ;
            u /= determ;

            // compute the barycentric coordinates for interpolating values
            Point bc = Point(1.0 - u - v, u, v);

            // calculate the distance to hit the triangle
            float t = (e2 % Q) / determ;

            // only allow valid distances to hit
            if(t > getBias() && t < h.z){

              // distance to hit
              h.z = t;

              // set hit point, normal, texture coordinate
              h.p = GetPoint(faceID, bc);
              h.n = GetNormal(faceID, bc);
              h.uvw = GetTexCoord(faceID, bc);

              // calculate texture coordinate derivatives (approximate)
              Point minor;
              Point major;
              r.ellipseAt(h.z, h.n, major, minor);
              h.duvw[0] = minor;
              h.duvw[1] = minor;

              // detect back face hits
              if(determ < 0.0)
                h.front = false;

              // return hit info
              return true;
            }
          }
        }
      }

      // when no ray hits the triangular face
      return false;
    }

    // cast a ray into a BVH node, seeing which triangular faces may get hit
    bool traceBVHNode(Cone &r, HitInfo &h, int face, int nodeID){

      // grab node's bounding box
      BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));

      // does ray hit the node bounding box?
      bool hit = b.intersectRay(r, h.z);

      // recurse through child nodes if we hit node
      if(hit){

        // only recursively call function if not at a leaf node
        if(!bvh.IsLeafNode(nodeID)){

          // keep traversing the BVH hierarchy for hits
          int c1 = bvh.GetFirstChildNode(nodeID);
          int c2 = bvh.GetSecondChildNode(nodeID);
          bool hit1 = traceBVHNode(r, h, face, c1);
          bool hit2 = traceBVHNode(r, h, face, c2);

          // if we get no hit
          if(!hit1 && !hit2)
            hit = false;

        // for leaf nodes, trace ray into each triangular face
        }else{

          // get triangular faces of the hit BVH node
          const unsigned int* faces = bvh.GetNodeElements(nodeID);
          int size = bvh.GetNodeElementCount(nodeID);

          // trace the ray into each triangular face, tracking hits
          hit = false;
          for(int i = 0; i < size; i++){
            bool hit1 = intersectTriangle(r, h, face, faces[i]);
            if(!hit && hit1)
              hit = true;
          }
        }
      }

      // return if we hit a face within this node
      return hit;
    }
};
<commit_msg>add hack to get the texture working well enough on triangular mesh objects, need to get feedback or sleep before more<commit_after>// Copyright 2013 Sean McKenna
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)

// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"

// namespace
using namespace scene;

// Sphere definition
class Sphere: public Object{
  public:

    // constructor
    Sphere(){
      center.Set(0, 0, 0);
      radius = 1.0;
    }

    // intsersect a ray against the unit sphere
    // ray must be transformed into model space, first
    bool intersectRay(Cone &r, HitInfo &h, int face=HIT_FRONT){

      // pre-compute values for quadratic solution
      Point pos = r.pos - center;
      float A = r.dir % r.dir;
      float B = 2.0 * pos % r.dir;
      float C = pos % pos - radius * radius;
      float det = (B * B) - (4 * A * C);

      // if the ray intersects, compute the z-buffer value
      if(det >= 0){
        float z1 = (-B - sqrt(det)) / (2.0 * A);
        float z2 = (-B + sqrt(det)) / (2.0 * A);

        // determine if we have a back hit
        if(z1 * z2 < 0.0)
          h.front = false;

        // if hit is too close, assume it is a back-face hit
        else if(z1 <= getBias())
          h.front = false;

        // check closest z-buffer value, if positive (ahead of our ray)
        if(z1 > getBias()){
          h.z = z1;

          // compute surface intersection, normal, and texture coordinates
          h.p = r.pos + z1 * r.dir;
          h.n = h.p.GetNormalized();
          h.uvw = getTexCoord(h.p);

          // calculate texture coordinate derivatives (approximate)
          Point minor;
          Point major;
          r.ellipseAt(h.z, h.n, major, minor);
          h.duvw[0] = minor;
          h.duvw[1] = major;

          // return true, ray is hit
          return true;

        // check the next ray, if necessary
        }else if(z2 > getBias()){
          h.z = z2;

          // compute surface intersection, normal, and texture coordinates
          h.p = r.pos + z2 * r.dir;
          h.n = h.p.GetNormalized();
          h.uvw = getTexCoord(h.p);

          // calculate texture coordinate derivatives (approximate)
          Point minor;
          Point major;
          r.ellipseAt(h.z, h.n, major, minor);
          h.duvw[0] = minor;
          h.duvw[1] = major;

          // return true, ray is hit
          return true;

        // otherwise, all z-buffer values are negative, return false
        }else
          return false;
      }

      // otherwise, return false (no ray hit)
      else
        return false;
    }

    // get sphere bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
    }

  private:

    // sphere center and its radius
    Point center;
    float radius;

    // get texture coordinates (spherical coordinates)
    Point getTexCoord(Point p){
      return Point(atan(p.x / p.y) / (2.0 * M_PI), acos(p.z / radius) / M_PI, 0.0);
    }
};

// Plane definition (a "unit" plane)
class Plane: public Object{
  public:

    // intersect a ray against the "unit" plane
    bool intersectRay(Cone &r, HitInfo &h, int face = HIT_FRONT){

      // only compute for rays not parallel to the unit plane
      if(r.dir.z > getBias() || r.dir.z < getBias()){

        // compute distance along ray direction to plane
        float t = -r.pos.z / r.dir.z;

        // only accept hits in front of ray (with some bias)
        if(t > getBias()){

          // compute the hit point
          Point hit = r.pos + t * r.dir;

          // only allow a hit to occur if on the "unit" plane
          if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){

            // detect back face hits
            if(r.pos.z < 0.0)
              h.front = false;

            // distance to hit
            h.z = t;

            // set hit point, normal, texture coordinate
            h.p = hit;
            h.n = Point(0.0, 0.0, 1.0);
            h.uvw = getTexCoord(hit);

            // calculate texture coordinate derivatives (approximate)
            Point minor;
            Point major;
            r.ellipseAt(h.z, h.n, major, minor);
            h.duvw[0] = minor * 2.0;
            h.duvw[1] = major * 2.0;

            // return hit
            return true;
          }
        }
      }

      // when no ray hits the "unit" plane
      return false;
    }

    // get plane bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
    }

  // get the texture coordinate on the unit plane
  private:
    Point getTexCoord(Point p){
      return (p + 1.0) / 2.0;
    }
};

// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
  public:

    // intersect a ray against the triangular mesh
    bool intersectRay(Cone &r, HitInfo &h, int face = HIT_FRONT){

      // check our BVH for triangular faces, update hit info
      bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());

      // return hit info from intersecting rays in the BVH faces
      return triang;
    }

    // get triangular mesh bounding box
    BoundingBox getBoundBox(){
      return BoundingBox(GetBoundMin(), GetBoundMax());
    }

    // when loading a triangular mesh, get its bounding box
    bool load(string file){
      bvh.Clear();
      if(!LoadFromFileObj(file.c_str()))
        return false;
      if(!HasNormals())
        ComputeNormals();
      ComputeBoundingBox();
      bvh.SetMesh(this,4);
      return true;
    }

  private:

    // add BVH for each triangular mesh
    cyBVHTriMesh bvh;

    // intersect a ray with a single triangle (Moller-Trumbore algorithm)
    bool intersectTriangle(Cone &r, HitInfo &h, int face, int faceID){

      // grab vertex points
      Point a = V(F(faceID).v[0]);
      Point b = V(F(faceID).v[1]);
      Point c = V(F(faceID).v[2]);

      // compute edge vectors
      Point e1 = b - a;
      Point e2 = c - a;

      // calculate first vector, P
      Point P = r.dir ^ e2;

      // calculate the determinant of the matrix equation
      float determ = e1 % P;

      // only continue for valid determinant ranges
      if(abs(determ) > getBias()){

        // calculate second vector, T
        Point T = r.pos - a;

        // calculate a barycentric component (u)
        float u = T % P;

        // only allow valid barycentric values
        if(u > -getBias() && u < determ * (1.0 + getBias())){

          // calculate a normal of the ray with an edge vector
          Point Q = T ^ e1;

          // calculate a barycentric component (v)
          float v = r.dir % Q;

          // only allow valid barycentric values
          if(v > -getBias() && v + u < determ * (1.0 + getBias())){

            // update barycentric coordinates
            v /= determ;
            u /= determ;

            // compute the barycentric coordinates for interpolating values
            Point bc = Point(1.0 - u - v, u, v);

            // calculate the distance to hit the triangle
            float t = (e2 % Q) / determ;

            // only allow valid distances to hit
            if(t > getBias() && t < h.z){

              // distance to hit
              h.z = t;

              // set hit point, normal, texture coordinate
              h.p = GetPoint(faceID, bc);
              h.n = GetNormal(faceID, bc);
              h.uvw = GetTexCoord(faceID, bc);

              // calculate texture coordinate derivatives (approximate)
              Point minor;
              Point major;
              r.ellipseAt(h.z, h.n, major, minor);
              h.duvw[0] = minor / 2.0;
              h.duvw[1] = minor / 2.0;

              // detect back face hits
              if(determ < 0.0)
                h.front = false;

              // return hit info
              return true;
            }
          }
        }
      }

      // when no ray hits the triangular face
      return false;
    }

    // cast a ray into a BVH node, seeing which triangular faces may get hit
    bool traceBVHNode(Cone &r, HitInfo &h, int face, int nodeID){

      // grab node's bounding box
      BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));

      // does ray hit the node bounding box?
      bool hit = b.intersectRay(r, h.z);

      // recurse through child nodes if we hit node
      if(hit){

        // only recursively call function if not at a leaf node
        if(!bvh.IsLeafNode(nodeID)){

          // keep traversing the BVH hierarchy for hits
          int c1 = bvh.GetFirstChildNode(nodeID);
          int c2 = bvh.GetSecondChildNode(nodeID);
          bool hit1 = traceBVHNode(r, h, face, c1);
          bool hit2 = traceBVHNode(r, h, face, c2);

          // if we get no hit
          if(!hit1 && !hit2)
            hit = false;

        // for leaf nodes, trace ray into each triangular face
        }else{

          // get triangular faces of the hit BVH node
          const unsigned int* faces = bvh.GetNodeElements(nodeID);
          int size = bvh.GetNodeElementCount(nodeID);

          // trace the ray into each triangular face, tracking hits
          hit = false;
          for(int i = 0; i < size; i++){
            bool hit1 = intersectTriangle(r, h, face, faces[i]);
            if(!hit && hit1)
              hit = true;
          }
        }
      }

      // return if we hit a face within this node
      return hit;
    }
};
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <iostream>
#include "itkWarpImageFilter.h"
#include "itkStreamingImageFilter.h"

#include "itkPipelineMonitorImageFilter.h"
#include "itkMath.h"

using ImageType = itk::Image<float,3>;
using DisplacementFieldType = itk::Image<itk::Vector<double,3> , 3 >;
using WarpFilterType = itk::WarpImageFilter<ImageType,
                             ImageType,
                             DisplacementFieldType>;

using MonitorFilter = itk::PipelineMonitorImageFilter<ImageType>;
#define AllocateImageFromRegionAndSpacing(ImageType,rval,region,spacing) \
{ \
  rval = ImageType::New(); \
  rval->SetSpacing(spacing); \
  rval->SetRegions(region); \
  rval->Allocate(); \
}

namespace {

ImageType::Pointer
MakeCheckerboard()
{
  using IteratorType = itk::ImageRegionIterator<ImageType>;
  ImageType::SizeType size = {{16,16,16}};
  ImageType::SpacingType spacing;
  spacing[0] = spacing[1] = spacing[2] = 1.0;
  ImageType::IndexType index = {{0,0,0}};
  ImageType::RegionType region;
  region.SetSize(size);
  region.SetIndex(index);
  ImageType::Pointer image;
  AllocateImageFromRegionAndSpacing(ImageType,image,region,spacing);
  image->FillBuffer(0.0);
  for( IteratorType it(image,image->GetLargestPossibleRegion()); !it.IsAtEnd(); ++it)
    {
    ImageType::IndexType ind(it.GetIndex());
    // initially checkboard 4 pixels wide
    int x = ind[0] / 4;
    int y = ind[1] / 4;
    int z = ind[2] / 4;
    bool black(((x&1) + (y&1)) & 1);
    if(z & 1)
      {
      black = !black;
      }
    it.Set(black ? 255.0 : 0.0);
    }
  return image;
}

template <long unsigned int TImageIndexSpaceSize>
typename DisplacementFieldType::Pointer MakeDisplacementField()
{
  using IteratorType = itk::ImageRegionIterator<DisplacementFieldType>;
  const DisplacementFieldType::SizeType size = {{TImageIndexSpaceSize,TImageIndexSpaceSize,TImageIndexSpaceSize}};
  DisplacementFieldType::SpacingType spacing;
  spacing[0] = spacing[1] = spacing[2] = 16.0/(double)TImageIndexSpaceSize;
  DisplacementFieldType::IndexType index = {{0,0,0}};
  DisplacementFieldType::RegionType region;
  region.SetSize(size);
  region.SetIndex(index);
  DisplacementFieldType::Pointer image;
  AllocateImageFromRegionAndSpacing(DisplacementFieldType,image,region,spacing);
  for( IteratorType it(image,image->GetLargestPossibleRegion()); ! it.IsAtEnd(); ++it)
    {
    DisplacementFieldType::PixelType pix;
    for(unsigned i = 0; i < 3; i++)
      {
      pix[i] = 1.0;
      }
    it.Set(pix);
    }
  return image;
}

}

int
itkWarpImageFilterTest2(int, char * [])
{
  //  itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(1);
  // make test image
  ImageType::Pointer image = MakeCheckerboard();
  // make full-res displacement field
  DisplacementFieldType::Pointer defField1 = MakeDisplacementField<16u>();
  // make half-res displacement field
  DisplacementFieldType::Pointer defField2 = MakeDisplacementField<8u>();

  WarpFilterType::Pointer filter = WarpFilterType::New();
  // test with full res
  filter->SetDisplacementField(defField1);
  filter->SetInput(image);
  filter->SetOutputParametersFromImage(image);
  filter->Update();
  ImageType::Pointer result1 = filter->GetOutput();
  // test with half res
  filter->SetDisplacementField(defField2);
  filter->SetInput(image);
  filter->SetOutputParametersFromImage(image);
  filter->Update();
  ImageType::Pointer result2 = filter->GetOutput();
  itk::ImageRegionIterator<ImageType>
    it1(result1,result1->GetLargestPossibleRegion()),
    it2(result2,result1->GetLargestPossibleRegion());
  for(it1.GoToBegin(),it2.GoToBegin();
      !it1.IsAtEnd() && !it2.IsAtEnd();
      ++it1, ++it2)
    {
    if(itk::Math::NotAlmostEquals( it1.Value(), it2.Value() ))
      {
      std::cout << "Pixels differ " << it1.Value() << " "
                << it2.Value()
                << std::endl;
      return EXIT_FAILURE;
      }
    }
  if(it1.IsAtEnd() != it2.IsAtEnd())
    {
    std::cout << "Iterators don't agree on end of image" << std::endl;
    return EXIT_FAILURE;
    }
  //
  // try streaming
  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( image );

  WarpFilterType::Pointer filter2 = WarpFilterType::New();
  filter2->SetDisplacementField(defField2);
  filter2->SetInput( monitor1->GetOutput() );
  filter2->SetOutputParametersFromImage(image);

  MonitorFilter::Pointer monitor2 = MonitorFilter::New();
  monitor2->SetInput(filter2->GetOutput());

  using StreamerType = itk::StreamingImageFilter<ImageType,ImageType>;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput(monitor2->GetOutput());
  streamer->SetNumberOfStreamDivisions(4);
  streamer->Update();
  itk::ImageRegionIterator<ImageType> streamIt(streamer->GetOutput(),
                                               streamer->GetOutput()->GetBufferedRegion());
  for(streamIt.GoToBegin(),it2.GoToBegin();
      !streamIt.IsAtEnd() && !it2.IsAtEnd();
      ++streamIt, ++it2)
    {
    if(itk::Math::NotAlmostEquals( streamIt.Value(), it2.Value() ))
      {
      std::cout << "Pixels differ " << streamIt.Value() << " "
                << it2.Value()
                << std::endl;
      return EXIT_FAILURE;
      }

    }
  if(streamIt.IsAtEnd() != it2.IsAtEnd())
    {
    std::cout << "Iterators don't agree on end of image" << std::endl;
    return EXIT_FAILURE;
    }

  // this verifies that the pipeline was executed as expected along
  // with correct region propagation and output information
  if (!monitor2->VerifyAllInputCanStream(4))
    {
    std::cout << "Filter failed to execute as expected!" << std::endl;
    std::cout << monitor2;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>BUG: avoid overwriting output in 2nd run used for comparison in test:<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include <iostream>
#include "itkWarpImageFilter.h"
#include "itkStreamingImageFilter.h"

#include "itkPipelineMonitorImageFilter.h"
#include "itkMath.h"

using ImageType = itk::Image<float,3>;
using DisplacementFieldType = itk::Image<itk::Vector<double,3> , 3 >;
using WarpFilterType = itk::WarpImageFilter<ImageType,
                             ImageType,
                             DisplacementFieldType>;

using MonitorFilter = itk::PipelineMonitorImageFilter<ImageType>;
#define AllocateImageFromRegionAndSpacing(ImageType,rval,region,spacing) \
{ \
  rval = ImageType::New(); \
  rval->SetSpacing(spacing); \
  rval->SetRegions(region); \
  rval->Allocate(); \
}

namespace {

ImageType::Pointer
MakeCheckerboard()
{
  using IteratorType = itk::ImageRegionIterator<ImageType>;
  ImageType::SizeType size = {{16,16,16}};
  ImageType::SpacingType spacing;
  spacing[0] = spacing[1] = spacing[2] = 1.0;
  ImageType::IndexType index = {{0,0,0}};
  ImageType::RegionType region;
  region.SetSize(size);
  region.SetIndex(index);
  ImageType::Pointer image;
  AllocateImageFromRegionAndSpacing(ImageType,image,region,spacing);
  image->FillBuffer(0.0);
  for( IteratorType it(image,image->GetLargestPossibleRegion()); !it.IsAtEnd(); ++it)
    {
    ImageType::IndexType ind(it.GetIndex());
    // initially checkboard 4 pixels wide
    int x = ind[0] / 4;
    int y = ind[1] / 4;
    int z = ind[2] / 4;
    bool black(((x&1) + (y&1)) & 1);
    if(z & 1)
      {
      black = !black;
      }
    it.Set(black ? 255.0 : 0.0);
    }
  return image;
}

template <long unsigned int TImageIndexSpaceSize>
typename DisplacementFieldType::Pointer MakeDisplacementField()
{
  using IteratorType = itk::ImageRegionIterator<DisplacementFieldType>;
  const DisplacementFieldType::SizeType size = {{TImageIndexSpaceSize,TImageIndexSpaceSize,TImageIndexSpaceSize}};
  DisplacementFieldType::SpacingType spacing;
  spacing[0] = spacing[1] = spacing[2] = 16.0/(double)TImageIndexSpaceSize;
  DisplacementFieldType::IndexType index = {{0,0,0}};
  DisplacementFieldType::RegionType region;
  region.SetSize(size);
  region.SetIndex(index);
  DisplacementFieldType::Pointer image;
  AllocateImageFromRegionAndSpacing(DisplacementFieldType,image,region,spacing);
  for( IteratorType it(image,image->GetLargestPossibleRegion()); ! it.IsAtEnd(); ++it)
    {
    DisplacementFieldType::PixelType pix;
    for(unsigned i = 0; i < 3; i++)
      {
      pix[i] = 1.0;
      }
    it.Set(pix);
    }
  return image;
}

}

int
itkWarpImageFilterTest2(int, char * [])
{
  //  itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(1);
  // make test image
  ImageType::Pointer image = MakeCheckerboard();
  // make full-res displacement field
  DisplacementFieldType::Pointer defField1 = MakeDisplacementField<16u>();
  // make half-res displacement field
  DisplacementFieldType::Pointer defField2 = MakeDisplacementField<8u>();

  WarpFilterType::Pointer filter = WarpFilterType::New();
  // test with full res
  filter->SetDisplacementField(defField1);
  filter->SetInput(image);
  filter->SetOutputParametersFromImage(image);
  filter->Update();
  ImageType::Pointer result1 = filter->GetOutput(); // save output for later comparison
  result1->DisconnectPipeline(); // disconnect to create new output
  // test with half res
  filter->SetDisplacementField(defField2);
  filter->SetInput(image);
  filter->SetOutputParametersFromImage(image);
  filter->Modified(); // enforce re-execution just to be sure
  filter->Update();
  ImageType::Pointer result2 = filter->GetOutput();
  itk::ImageRegionIterator<ImageType>
    it1(result1,result1->GetLargestPossibleRegion()),
    it2(result2,result1->GetLargestPossibleRegion());
  for(it1.GoToBegin(),it2.GoToBegin();
      !it1.IsAtEnd() && !it2.IsAtEnd();
      ++it1, ++it2)
    {
    if(itk::Math::NotAlmostEquals( it1.Value(), it2.Value() ))
      {
      std::cout << "Pixels differ " << it1.Value() << " "
                << it2.Value()
                << std::endl;
      return EXIT_FAILURE;
      }
    }
  if(it1.IsAtEnd() != it2.IsAtEnd())
    {
    std::cout << "Iterators don't agree on end of image" << std::endl;
    return EXIT_FAILURE;
    }
  //
  // try streaming
  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( image );

  WarpFilterType::Pointer filter2 = WarpFilterType::New();
  filter2->SetDisplacementField(defField2);
  filter2->SetInput( monitor1->GetOutput() );
  filter2->SetOutputParametersFromImage(image);

  MonitorFilter::Pointer monitor2 = MonitorFilter::New();
  monitor2->SetInput(filter2->GetOutput());

  using StreamerType = itk::StreamingImageFilter<ImageType,ImageType>;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput(monitor2->GetOutput());
  streamer->SetNumberOfStreamDivisions(4);
  streamer->Update();
  itk::ImageRegionIterator<ImageType> streamIt(streamer->GetOutput(),
                                               streamer->GetOutput()->GetBufferedRegion());
  for(streamIt.GoToBegin(),it2.GoToBegin();
      !streamIt.IsAtEnd() && !it2.IsAtEnd();
      ++streamIt, ++it2)
    {
    if(itk::Math::NotAlmostEquals( streamIt.Value(), it2.Value() ))
      {
      std::cout << "Pixels differ " << streamIt.Value() << " "
                << it2.Value()
                << std::endl;
      return EXIT_FAILURE;
      }

    }
  if(streamIt.IsAtEnd() != it2.IsAtEnd())
    {
    std::cout << "Iterators don't agree on end of image" << std::endl;
    return EXIT_FAILURE;
    }

  // this verifies that the pipeline was executed as expected along
  // with correct region propagation and output information
  if (!monitor2->VerifyAllInputCanStream(4))
    {
    std::cout << "Filter failed to execute as expected!" << std::endl;
    std::cout << monitor2;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "Input_Parser.hxx"

#include <boost/filesystem.hpp>

namespace
{
  void start_element_callback(void *user_data, const xmlChar *name,
                              const xmlChar **)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_start_element(reinterpret_cast<const char *>(name));
  }

  void end_element_callback(void *user_data, const xmlChar *name)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_end_element(reinterpret_cast<const char *>(name));
  }

  void
  characters_callback(void *user_data, const xmlChar *characters, int length)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_characters(characters, length);
  }

  void warning_callback(void *, const char *msg, ...)
  {
    va_list args;
    va_start(args, msg);
    vprintf(msg, args);
    va_end(args);
  }

  void error_callback(void *, const char *msg, ...)
  {
    va_list args;
    va_start(args, msg);
    vprintf(msg, args);
    va_end(args);
    throw std::runtime_error("Invalid Input file");
  }
}

void read_input(const boost::filesystem::path &input_file,
                std::vector<El::BigFloat> &objectives,
                std::vector<El::BigFloat> &normalization,
                std::vector<Positive_Matrix_With_Prefactor> &matrices)
{
  LIBXML_TEST_VERSION;

  Input_Parser input_parser;

  xmlSAXHandler xml_handlers;
  // This feels unclean.
  memset(&xml_handlers, 0, sizeof(xml_handlers));
  xml_handlers.startElement = start_element_callback;
  xml_handlers.endElement = end_element_callback;
  xml_handlers.characters = characters_callback;
  xml_handlers.warning = warning_callback;
  xml_handlers.error = error_callback;

  if(xmlSAXUserParseFile(&xml_handlers, &input_parser, input_file.c_str()) < 0)
    {
      throw std::runtime_error("Unable to parse input file: "
                               + input_file.string());
    }

  std::swap(objectives, input_parser.objective_state.value);
  std::swap(normalization, input_parser.normalization_state.value);
  std::swap(matrices,
            input_parser.positive_matrices_with_prefactor_state.value);

  // for(auto &o : objectives)
  //   std::cout << "Objective: " << o << "\n";
  // for(auto &o : normalization)
  //   std::cout << "Normalization: " << o << "\n";
  // for(auto &o : matrices)
  //   {
  //     std::cout << "Damped: " << o.damped_rational.constant << " "
  //               << o.damped_rational.base << "\n";
  //     // for(auto &pole: o.damped_rational.poles)
  //     //   std::cout << "\t" << pole << "\n";
  //     // for(auto &polynomial: o.polynomials)
  //     //   std::cout << polynomial << "\n";
  //   }
}
<commit_msg>Remove commented out debug code<commit_after>#include "Input_Parser.hxx"

#include <boost/filesystem.hpp>

namespace
{
  void start_element_callback(void *user_data, const xmlChar *name,
                              const xmlChar **)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_start_element(reinterpret_cast<const char *>(name));
  }

  void end_element_callback(void *user_data, const xmlChar *name)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_end_element(reinterpret_cast<const char *>(name));
  }

  void
  characters_callback(void *user_data, const xmlChar *characters, int length)
  {
    Input_Parser *input_parser = static_cast<Input_Parser *>(user_data);
    input_parser->on_characters(characters, length);
  }

  void warning_callback(void *, const char *msg, ...)
  {
    va_list args;
    va_start(args, msg);
    vprintf(msg, args);
    va_end(args);
  }

  void error_callback(void *, const char *msg, ...)
  {
    va_list args;
    va_start(args, msg);
    vprintf(msg, args);
    va_end(args);
    throw std::runtime_error("Invalid Input file");
  }
}

void read_input(const boost::filesystem::path &input_file,
                std::vector<El::BigFloat> &objectives,
                std::vector<El::BigFloat> &normalization,
                std::vector<Positive_Matrix_With_Prefactor> &matrices)
{
  LIBXML_TEST_VERSION;

  Input_Parser input_parser;

  xmlSAXHandler xml_handlers;
  // This feels unclean.
  memset(&xml_handlers, 0, sizeof(xml_handlers));
  xml_handlers.startElement = start_element_callback;
  xml_handlers.endElement = end_element_callback;
  xml_handlers.characters = characters_callback;
  xml_handlers.warning = warning_callback;
  xml_handlers.error = error_callback;

  if(xmlSAXUserParseFile(&xml_handlers, &input_parser, input_file.c_str()) < 0)
    {
      throw std::runtime_error("Unable to parse input file: "
                               + input_file.string());
    }

  std::swap(objectives, input_parser.objective_state.value);
  std::swap(normalization, input_parser.normalization_state.value);
  std::swap(matrices,
            input_parser.positive_matrices_with_prefactor_state.value);
}
<|endoftext|>


<commit_before><commit_msg>test: re-deflake TabletServerQuiescingITest<commit_after><|endoftext|>


<commit_before>void *AddTaskDFilterAndCorrelations(
  AliAnalysisTaskSEDmesonsFilterCJ::ECandidateType cand = AliAnalysisTaskSEDmesonsFilterCJ::kDstartoKpipi,
  TString filename = "DStartoKpipiCuts.root",
  Bool_t theMCon = kFALSE,
  Bool_t reco = kTRUE /*must be true if theMCon is false*/,
  TString suffix = "",
  TString jetArrname = "",
  TString trackArrname = "PicoTracks",
  Bool_t triggerOnLeadingJet = kFALSE,
  Int_t leadingHadType = 0 /*0 = charged, 1 = neutral, 2 = both*/,
  Float_t R = 0.4,
  Float_t jptcut = 10.,
  const char *cutType = "TPC",
  Int_t thnsparse=1, /*-1 = no thnsparse, 0 = heavy, 1 = light*/
  Double_t percjetareacut = -1.,
  AliAnalysisTaskEmcal::TriggerType trType=AliAnalysisTaskEmcal::kND,
  Int_t typeDjet=2,
  TString subwagons=""
)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskSEDmesonsFilterCJ", "No analysis manager to connect to.");
    return NULL;
  }

  Bool_t useStdC = kFALSE;
  TFile* filecuts=TFile::Open(filename);
  if(!filecuts || (filecuts && !filecuts->IsOpen())) {
    cout<<"Input file not found: use std cuts"<<endl;
    useStdC = kTRUE;
  }

  AliRDHFCuts *analysiscuts=0x0;
  switch (cand) {
  case 0 :
    if(useStdC) {
      analysiscuts = new AliRDHFCutsD0toKpi();
      analysiscuts->SetStandardCutsPP2010();
    } else
      analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get("D0toKpiCuts");
    break;
  case 1 :
    if(useStdC) {
      analysiscuts = new AliRDHFCutsDStartoKpipi();
      analysiscuts->SetStandardCutsPP2010();
    } else
      analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts");
    analysiscuts->SetName("DStartoKpipiCuts");
    break;
  }

  if (!analysiscuts) { // mm let's see if everything is ok
    AliFatal("Specific AliRDHFCuts not found");
    return;
  }

  printf("CREATE TASK\n"); //CREATE THE TASK

  TString candname="DStar";
  if(cand==0)  candname="D0";
  TString sR = Form("R%.0f",R*10);

  TString taskFiltername="DmesonsFilterCJ";
  taskFiltername+=candname;
  taskFiltername+=suffix;
  if(theMCon) taskFiltername+="MC";
  if(!reco)   taskFiltername+="gen";

  AliAnalysisTaskSEDmesonsFilterCJ* taskFilter = mgr->GetTask(taskFiltername.Data());
  Bool_t bTaskFilter=kTRUE;
  if (!taskFilter){
     bTaskFilter=kFALSE;
     taskFilter = new AliAnalysisTaskSEDmesonsFilterCJ(taskFiltername.Data(),analysiscuts,cand);
     if(!theMCon) reco=kTRUE;
     taskFilter->SetMC(theMCon); //D meson settings
     taskFilter->SetUseReco(reco);
     mgr->AddTask(taskFilter);
  } else Printf("Task %s already exist, continue",taskFiltername.Data());

  // create the task
  TString taskCorrName="TaskFlavourJetCorrelations";
  taskCorrName+=candname;
  taskCorrName+=suffix;
  if(theMCon) taskCorrName+="MC";
  if(!reco)   taskCorrName+="gen";
  taskCorrName+=cutType;
  taskCorrName+=Form("PTj%.0f",jptcut);
  taskCorrName+=sR;
  taskCorrName+=Form("Typ%d",typeDjet);

  AliAnalysisTaskFlavourJetCorrelations *taskCorr = new AliAnalysisTaskFlavourJetCorrelations(taskCorrName.Data(),
     analysiscuts, cand);

  taskCorr->SetJetArrayName(jetArrname);
  taskCorr->SetTrackArrayName(trackArrname);
  //taskCorr->SetRadius(R);
  AliParticleContainer *trackCont  = taskCorr->AddParticleContainer(trackArrname);
  trackCont->SetClassName("AliVTrack");

  AliJetContainer *jetCont = taskCorr->AddJetContainer(jetArrname,cutType,R);
  if(jetCont) {
     jetCont->ConnectParticleContainer(trackCont);
     //jetCont->SetJetAcceptanceType(cutType);
     jetCont->SetJetPtCut(jptcut);
     jetCont->SetPercAreaCut(percjetareacut);
  }
  taskCorr->SetMC(theMCon);
  taskCorr->SetUseReco(reco);
  taskCorr->SetTriggerOnLeadingJet(triggerOnLeadingJet);
  taskCorr->SetTypeDJetSelection(typeDjet);
  if(theMCon && trType!=AliAnalysisTaskEmcal::kND){
     taskCorr->SetCaloTriggerPatchInfoName("EmcalTriggers");
     taskCorr->SetTriggerTypeSel(trType);
  }
  if(thnsparse==-1)taskCorr->TurnOffTHnSparse();
  if(thnsparse==0) taskCorr->HeavyTHnSparse();
  if(thnsparse==1) taskCorr->LightTHnSparse();

  mgr->AddTask(taskCorr);

  if(theMCon) {
     suffix+="MC";
     if(reco) suffix+="rec";
  }

  // Create and connect containers for input/output
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  TString outputfileF = outputfile, outputfileC = outputfile;
  outputfileF += ":PWG3_D2H_DmesonsForJetCorrelations";
  outputfileC += ":PWG3_D2H_DEmcalJet";

  outputfileF += suffix;
  outputfileC += suffix;

  TString nameContainerF0="histograms";
  TString nameContainerF1="cuts";

  TString nameContainerC0="hCor";
  TString nameContainerC1="cutsJ";

  TString nameContainerFC2="Dcandidates";
  TString nameContainerFC3="DSBcandidates";

  nameContainerF0  += candname;
  nameContainerF1  += candname;
  nameContainerC0  += candname;
  nameContainerC1  += candname;
  nameContainerFC2 += candname;
  nameContainerFC3 += candname;

  nameContainerF0  += suffix;
  nameContainerF1  += suffix;
  nameContainerC0  += suffix;
  nameContainerC1  += suffix;
  nameContainerFC2 += suffix;
  nameContainerFC3 += suffix;

  nameContainerC0+=sR;
  nameContainerC1+=sR;
  if(typeDjet!=2) { //no particular name for default
     nameContainerC0+=Form("Typ%d",typeDjet);
     nameContainerC1+=Form("Typ%d",typeDjet);
  }
  // ------ input data ------
  AliAnalysisDataContainer *cinput0  = mgr->GetCommonInputContainer();
  cinput0->SetName(Form("in%s%s",candname.Data(),suffix.Data()));

  // ----- output data -----
  AliAnalysisDataContainer *coutputF0;
  AliAnalysisDataContainer *coutputF1;
  AliAnalysisDataContainer *coutputFC2;
  AliAnalysisDataContainer *coutputFC3;

  if(!bTaskFilter){
  coutputF0 = mgr->CreateContainer(nameContainerF0, TList::Class(),AliAnalysisManager::kOutputContainer,outputfileF.Data());

  coutputF1 = mgr->CreateContainer(nameContainerF1, AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, outputfileF.Data());

  coutputFC2 = mgr->CreateContainer(nameContainerFC2, TClonesArray::Class(),AliAnalysisManager::kExchangeContainer, outputfileF.Data()); // exchange

  coutputFC3 = mgr->CreateContainer(nameContainerFC3, TClonesArray::Class(),AliAnalysisManager::kExchangeContainer, outputfileF.Data()); // exchange

  } else {
     TObjArray * cnt = mgr->GetContainers();
     coutputF0 = (AliAnalysisDataContainer*)cnt->FindObject(nameContainerF0);
     coutputF1 = (AliAnalysisDataContainer*)cnt->FindObject(nameContainerF1);
     coutputFC2= (AliAnalysisDataContainer*)cnt->FindObject(nameContainerFC2);
     coutputFC3= (AliAnalysisDataContainer*)cnt->FindObject(nameContainerFC3);
  }

  AliAnalysisDataContainer *coutputC0 = mgr->CreateContainer(nameContainerC0, TList::Class(),AliAnalysisManager::kOutputContainer,outputfileC.Data());

  AliAnalysisDataContainer *coutputC1 = mgr->CreateContainer(nameContainerC1, AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, outputfileC.Data());

  mgr->ConnectInput(taskFilter,0,cinput0);
  mgr->ConnectInput(taskCorr,0,cinput0);

  mgr->ConnectOutput(taskFilter,1,coutputF0);
  mgr->ConnectOutput(taskFilter,2,coutputF1);
  mgr->ConnectOutput(taskFilter,3,coutputFC2);
  mgr->ConnectOutput(taskFilter,4,coutputFC3);

  mgr->ConnectInput(taskCorr,1,coutputFC2);
  mgr->ConnectInput(taskCorr,2,coutputFC3);
  mgr->ConnectOutput(taskCorr,1,coutputC0);
  mgr->ConnectOutput(taskCorr,2,coutputC1);
  //if(cand==1) mgr->ConnectOutput(task,4,coutput4);

  Printf("Input and Output connected to the manager");
  return;
}

<commit_msg>Use the subwagon string<commit_after>void *AddTaskDFilterAndCorrelations(
  AliAnalysisTaskSEDmesonsFilterCJ::ECandidateType cand = AliAnalysisTaskSEDmesonsFilterCJ::kDstartoKpipi,
  TString filename = "DStartoKpipiCuts.root",
  Bool_t theMCon = kFALSE,
  Bool_t reco = kTRUE /*must be true if theMCon is false*/,
  TString suffix = "",
  TString jetArrname = "",
  TString trackArrname = "PicoTracks",
  Bool_t triggerOnLeadingJet = kFALSE,
  Int_t leadingHadType = 0 /*0 = charged, 1 = neutral, 2 = both*/,
  Float_t R = 0.4,
  Float_t jptcut = 10.,
  const char *cutType = "TPC",
  Int_t thnsparse=1, /*-1 = no thnsparse, 0 = heavy, 1 = light*/
  Double_t percjetareacut = -1.,
  AliAnalysisTaskEmcal::TriggerType trType=AliAnalysisTaskEmcal::kND,
  Int_t typeDjet=2,
  TString subwagons=""
)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskSEDmesonsFilterCJ", "No analysis manager to connect to.");
    return NULL;
  }

  Bool_t useStdC = kFALSE;
  TFile* filecuts=TFile::Open(filename);
  if(!filecuts || (filecuts && !filecuts->IsOpen())) {
    cout<<"Input file not found: use std cuts"<<endl;
    useStdC = kTRUE;
  }

  AliRDHFCuts *analysiscuts=0x0;
  switch (cand) {
  case 0 :
    if(useStdC) {
      analysiscuts = new AliRDHFCutsD0toKpi();
      analysiscuts->SetStandardCutsPP2010();
    } else
      analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get("D0toKpiCuts");
    break;
  case 1 :
    if(useStdC) {
      analysiscuts = new AliRDHFCutsDStartoKpipi();
      analysiscuts->SetStandardCutsPP2010();
    } else
      analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts");
    analysiscuts->SetName("DStartoKpipiCuts");
    break;
  }

  if (!analysiscuts) { // mm let's see if everything is ok
    AliFatal("Specific AliRDHFCuts not found");
    return;
  }

  printf("CREATE TASK\n"); //CREATE THE TASK

  TString candname="DStar";
  if(cand==0)  candname="D0";
  TString sR = Form("R%.0f",R*10);

  TString taskFiltername="DmesonsFilterCJ";
  taskFiltername+=candname;
  taskFiltername+=suffix;
  if(theMCon) taskFiltername+="MC";
  if(!reco)   taskFiltername+="gen";

  AliAnalysisTaskSEDmesonsFilterCJ* taskFilter = mgr->GetTask(taskFiltername.Data());
  Bool_t bTaskFilter=kTRUE;
  if (!taskFilter){
     bTaskFilter=kFALSE;
     taskFilter = new AliAnalysisTaskSEDmesonsFilterCJ(taskFiltername.Data(),analysiscuts,cand);
     if(!theMCon) reco=kTRUE;
     taskFilter->SetMC(theMCon); //D meson settings
     taskFilter->SetUseReco(reco);
     mgr->AddTask(taskFilter);
  } else Printf("Task %s already exist, continue",taskFiltername.Data());

  // create the task
  TString taskCorrName="TaskFlavourJetCorrelations";
  taskCorrName+=candname;
  taskCorrName+=suffix;
  if(theMCon) taskCorrName+="MC";
  if(!reco)   taskCorrName+="gen";
  taskCorrName+=cutType;
  taskCorrName+=Form("PTj%.0f",jptcut);
  taskCorrName+=sR;
  taskCorrName+=Form("Typ%d",typeDjet);

  AliAnalysisTaskFlavourJetCorrelations *taskCorr = new AliAnalysisTaskFlavourJetCorrelations(taskCorrName.Data(),
     analysiscuts, cand);

  taskCorr->SetJetArrayName(jetArrname);
  taskCorr->SetTrackArrayName(trackArrname);
  //taskCorr->SetRadius(R);
  AliParticleContainer *trackCont  = taskCorr->AddParticleContainer(trackArrname);
  trackCont->SetClassName("AliVTrack");

  AliJetContainer *jetCont = taskCorr->AddJetContainer(jetArrname,cutType,R);
  if(jetCont) {
     jetCont->ConnectParticleContainer(trackCont);
     //jetCont->SetJetAcceptanceType(cutType);
     jetCont->SetJetPtCut(jptcut);
     jetCont->SetPercAreaCut(percjetareacut);
  }
  taskCorr->SetMC(theMCon);
  taskCorr->SetUseReco(reco);
  taskCorr->SetTriggerOnLeadingJet(triggerOnLeadingJet);
  taskCorr->SetTypeDJetSelection(typeDjet);
  if(theMCon && trType!=AliAnalysisTaskEmcal::kND){
     taskCorr->SetCaloTriggerPatchInfoName("EmcalTriggers");
     taskCorr->SetTriggerTypeSel(trType);
  }
  if(thnsparse==-1)taskCorr->TurnOffTHnSparse();
  if(thnsparse==0) taskCorr->HeavyTHnSparse();
  if(thnsparse==1) taskCorr->LightTHnSparse();

  mgr->AddTask(taskCorr);

  if(theMCon) {
     suffix+="MC";
     if(reco) suffix+="rec";
  }

  // Create and connect containers for input/output
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  TString outputfileF = outputfile, outputfileC = outputfile;
  outputfileF += ":PWG3_D2H_DmesonsForJetCorrelations";
  outputfileC += ":PWG3_D2H_DEmcalJet";

  outputfileF += suffix;
  outputfileC += suffix;

  TString nameContainerF0="histograms";
  TString nameContainerF1="cuts";

  TString nameContainerC0="hCor";
  TString nameContainerC1="cutsJ";

  TString nameContainerFC2="Dcandidates";
  TString nameContainerFC3="DSBcandidates";

  nameContainerF0  += candname;
  nameContainerF1  += candname;
  nameContainerC0  += candname;
  nameContainerC1  += candname;
  nameContainerFC2 += candname;
  nameContainerFC3 += candname;

  nameContainerF0  += suffix;
  nameContainerF1  += suffix;
  nameContainerC0  += suffix;
  nameContainerC1  += suffix;
  nameContainerFC2 += suffix;
  nameContainerFC3 += suffix;

  nameContainerC0+=sR;
  nameContainerC1+=sR;
  if(typeDjet!=2) { //no particular name for default
     nameContainerC0+=Form("Typ%d",typeDjet);
     nameContainerC1+=Form("Typ%d",typeDjet);
  }

  nameContainerC0 += subwagons;
  nameContainerC1 += subwagons;

  // ------ input data ------
  AliAnalysisDataContainer *cinput0  = mgr->GetCommonInputContainer();
  cinput0->SetName(Form("in%s%s",candname.Data(),suffix.Data()));

  // ----- output data -----
  AliAnalysisDataContainer *coutputF0;
  AliAnalysisDataContainer *coutputF1;
  AliAnalysisDataContainer *coutputFC2;
  AliAnalysisDataContainer *coutputFC3;

  if(!bTaskFilter){
  coutputF0 = mgr->CreateContainer(nameContainerF0, TList::Class(),AliAnalysisManager::kOutputContainer,outputfileF.Data());

  coutputF1 = mgr->CreateContainer(nameContainerF1, AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, outputfileF.Data());

  coutputFC2 = mgr->CreateContainer(nameContainerFC2, TClonesArray::Class(),AliAnalysisManager::kExchangeContainer, outputfileF.Data()); // exchange

  coutputFC3 = mgr->CreateContainer(nameContainerFC3, TClonesArray::Class(),AliAnalysisManager::kExchangeContainer, outputfileF.Data()); // exchange

  } else {
     TObjArray * cnt = mgr->GetContainers();
     coutputF0 = (AliAnalysisDataContainer*)cnt->FindObject(nameContainerF0);
     coutputF1 = (AliAnalysisDataContainer*)cnt->FindObject(nameContainerF1);
     coutputFC2= (AliAnalysisDataContainer*)cnt->FindObject(nameContainerFC2);
     coutputFC3= (AliAnalysisDataContainer*)cnt->FindObject(nameContainerFC3);
  }

  AliAnalysisDataContainer *coutputC0 = mgr->CreateContainer(nameContainerC0, TList::Class(),AliAnalysisManager::kOutputContainer,outputfileC.Data());

  AliAnalysisDataContainer *coutputC1 = mgr->CreateContainer(nameContainerC1, AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, outputfileC.Data());

  mgr->ConnectInput(taskFilter,0,cinput0);
  mgr->ConnectInput(taskCorr,0,cinput0);

  mgr->ConnectOutput(taskFilter,1,coutputF0);
  mgr->ConnectOutput(taskFilter,2,coutputF1);
  mgr->ConnectOutput(taskFilter,3,coutputFC2);
  mgr->ConnectOutput(taskFilter,4,coutputFC3);

  mgr->ConnectInput(taskCorr,1,coutputFC2);
  mgr->ConnectInput(taskCorr,2,coutputFC3);
  mgr->ConnectOutput(taskCorr,1,coutputC0);
  mgr->ConnectOutput(taskCorr,2,coutputC1);
  //if(cand==1) mgr->ConnectOutput(task,4,coutput4);

  Printf("Input and Output connected to the manager");
  return;
}

<|endoftext|>


<commit_before><commit_msg>Update quantized add limits<commit_after><|endoftext|>


<commit_before><commit_msg>Add an extra sync before dropping feedview<commit_after><|endoftext|>