<commit_before>// Copyright 2012 Cloudera Inc.
//
// 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.

#include "runtime/timestamp-value.h"

#include "common/names.h"

using boost::date_time::not_a_date_time;
using boost::posix_time::nanoseconds;
using boost::posix_time::ptime;
using boost::posix_time::ptime_from_tm;
using boost::posix_time::to_tm;

DEFINE_bool(use_local_tz_for_unix_timestamp_conversions, false,
    "When true, TIMESTAMPs are interpreted in the local time zone when converting to "
    "and from Unix times. When false, TIMESTAMPs are interpreted in the UTC time zone. "
    "Set to true for Hive compatibility.");

namespace impala {

const char* TimestampValue::LLVM_CLASS_NAME = "class.impala::TimestampValue";
const double TimestampValue::ONE_BILLIONTH = 0.000000001;

TimestampValue::TimestampValue(const char* str, int len) {
  TimestampParser::Parse(str, len, &date_, &time_);
}

TimestampValue::TimestampValue(const char* str, int len,
    const DateTimeFormatContext& dt_ctx) {
  TimestampParser::Parse(str, len, dt_ctx, &date_, &time_);
}

int TimestampValue::Format(const DateTimeFormatContext& dt_ctx, int len, char* buff) {
  return TimestampParser::Format(dt_ctx, date_, time_, len, buff);
}

void TimestampValue::UtcToLocal() {
  DCHECK(HasDateAndTime());
  try {
    tm temp_tm = to_tm(ptime(date_, time_));  // will throw if date/time is invalid
    time_t utc = timegm(&temp_tm);
    if (UNLIKELY(NULL == localtime_r(&utc, &temp_tm))) {
      *this = ptime(not_a_date_time);
      return;
    }
    // Unlikely but a time zone conversion may push the value over the min/max
    // boundary resulting in an exception.
    ptime local = ptime_from_tm(temp_tm);
    // Neither time_t nor struct tm allow fractional seconds so they have to be handled
    // separately.
    local += nanoseconds(time_.fractional_seconds());
    *this = local;
  } catch (std::exception& from_boost) {
    *this = ptime(not_a_date_time);
  }
}

ostream& operator<<(ostream& os, const TimestampValue& timestamp_value) {
  return os << timestamp_value.DebugString();
}

}
<commit_msg>Make UTC to local TimestampValue conversion faster<commit_after>// Copyright 2012 Cloudera Inc.
//
// 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.

#include "runtime/timestamp-value.h"

#include "common/names.h"

using boost::date_time::not_a_date_time;
using boost::gregorian::date;
using boost::gregorian::date_duration;
using boost::posix_time::nanoseconds;
using boost::posix_time::ptime;
using boost::posix_time::ptime_from_tm;
using boost::posix_time::time_duration;
using boost::posix_time::to_tm;

DEFINE_bool(use_local_tz_for_unix_timestamp_conversions, false,
    "When true, TIMESTAMPs are interpreted in the local time zone when converting to "
    "and from Unix times. When false, TIMESTAMPs are interpreted in the UTC time zone. "
    "Set to true for Hive compatibility.");

// Constants for use with Unix times. Leap-seconds do not apply.
const int32_t SECONDS_IN_MINUTE = 60;
const int32_t SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
const int32_t SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;

// struct tm stores month/year data as an offset
const unsigned short TM_YEAR_OFFSET = 1900;
const unsigned short TM_MONTH_OFFSET = 1;

// Boost stores dates as an uint32_t. Since subtraction is needed, convert to signed.
const int64_t EPOCH_DAY_NUMBER =
    static_cast<int64_t>(date(1970, boost::gregorian::Jan, 1).day_number());

namespace impala {

const char* TimestampValue::LLVM_CLASS_NAME = "class.impala::TimestampValue";
const double TimestampValue::ONE_BILLIONTH = 0.000000001;

TimestampValue::TimestampValue(const char* str, int len) {
  TimestampParser::Parse(str, len, &date_, &time_);
}

TimestampValue::TimestampValue(const char* str, int len,
    const DateTimeFormatContext& dt_ctx) {
  TimestampParser::Parse(str, len, dt_ctx, &date_, &time_);
}

int TimestampValue::Format(const DateTimeFormatContext& dt_ctx, int len, char* buff) {
  return TimestampParser::Format(dt_ctx, date_, time_, len, buff);
}

void TimestampValue::UtcToLocal() {
  DCHECK(HasDateAndTime());
  // Previously, conversion was done using boost functions but it was found to be
  // too slow. Doing the conversion without function calls (which also avoids some
  // unnecessary validations) the conversion only take half as long. Original:
  // http://www.boost.org/doc/libs/1_55_0/boost/date_time/c_local_time_adjustor.hpp
  try {
    time_t utc =
        (static_cast<int64_t>(date_.day_number()) - EPOCH_DAY_NUMBER) * SECONDS_IN_DAY +
        time_.hours() * SECONDS_IN_HOUR +
        time_.minutes() * SECONDS_IN_MINUTE +
        time_.seconds();
    tm temp;
    if (UNLIKELY(NULL == localtime_r(&utc, &temp))) {
      *this = ptime(not_a_date_time);
      return;
    }
    // Unlikely but a time zone conversion may push the value over the min/max
    // boundary resulting in an exception.
    date_ = boost::gregorian::date(
        static_cast<unsigned short>(temp.tm_year + TM_YEAR_OFFSET),
        static_cast<unsigned short>(temp.tm_mon + TM_MONTH_OFFSET),
        static_cast<unsigned short>(temp.tm_mday));
    time_ = time_duration(temp.tm_hour, temp.tm_min, temp.tm_sec,
        time().fractional_seconds());
  } catch (std::exception& from_boost) {
    *this = ptime(not_a_date_time);
  }
}

ostream& operator<<(ostream& os, const TimestampValue& timestamp_value) {
  return os << timestamp_value.DebugString();
}

}
<|endoftext|>


<commit_before>/**
 * @file
 */
#include "bi/io/cpp/CppPackageGenerator.hpp"

#include "bi/io/cpp/CppRawGenerator.hpp"
#include "bi/io/cpp/CppClassGenerator.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/poset.hpp"
#include "bi/primitive/definitely.hpp"
#include "bi/build/misc.hpp"

bi::CppPackageGenerator::CppPackageGenerator(std::ostream& base,
    const int level, const bool header) :
    CppBaseGenerator(base, level, header) {
  //
}

void bi::CppPackageGenerator::visit(const Package* o) {
  /* gather important objects */
  Gatherer<Basic> basics;
  Gatherer<Class> classes, headerClasses;
  Gatherer<GlobalVariable> globals;
  Gatherer<Function> functions, headerFunctions;
  Gatherer<Fiber> fibers, headerFibers;
  Gatherer<Program> programs;
  Gatherer<BinaryOperator> binaries;
  Gatherer<UnaryOperator> unaries;
  for (auto file : o->sources) {
    file->accept(&basics);
    file->accept(&classes);
    file->accept(&globals);
    file->accept(&functions);
    file->accept(&fibers);
    file->accept(&programs);
    file->accept(&binaries);
    file->accept(&unaries);
  }
  for (auto file : o->headers) {
    file->accept(&headerClasses);
    file->accept(&headerFunctions);
    file->accept(&headerFibers);
  }

  /* base classes must be defined before their derived classes, so these are
   * gathered and sorted first */
  allowConversions = false;  // sort by inheritance, forget conversions
  poset<Type*,definitely> sorted;
  for (auto o : classes) {
    if (!o->isAlias()) {
      sorted.insert(new ClassType(o));
    }
    for (auto instantiation : o->instantiations) {
      sorted.insert(new ClassType(instantiation));
    }
  }
  for (auto o : headerClasses) {
    for (auto instantiation : o->instantiations) {
      sorted.insert(new ClassType(instantiation));
    }
  }
  allowConversions = true;
  std::list<Class*> sortedClasses;
  for (auto iter = sorted.rbegin(); iter != sorted.rend(); ++iter) {
    if (!(*iter)->getClass()->has(PRIOR_INSTANTIATION)) {
      sortedClasses.push_back((*iter)->getClass());
    }
  }

  if (header) {
    /* a `#define` include guard is preferred to `#pragma once`; the header of
     * each package is included in sources with the `-include` compile option
     * rather than `#include` preprocessor directive, including (for
     * convenience/laziness) when precompiling the header itself; this seems
     * to cause a double inclusion with `#pragma once` but not with a `#define`
     * include guard */
    line("#ifndef BI_" << tarname(o->name) << "_HPP_");
    line("#define BI_" << tarname(o->name) << "_HPP_");
    line("");

    for (auto header : o->headers) {
      fs::path include = header->path;
      include.replace_extension(".hpp");
      line("#include \"" << include.string() << "\"");
    }

    /* raw C++ code for headers */
    CppRawGenerator auxRaw(base, level, header);
    auxRaw << o;

    line("");
    line("namespace bi {");
    line("namespace type {");

    /* forward class declarations */
    for (auto o : classes) {
      if (!o->braces->isEmpty()) {
        genTemplateParams(o);
        line("class " << o->name << ';');
      }
    }
    line("");

    /* basic type aliases */
    for (auto o : basics) {
      if (o->isAlias()) {
        line("using " << o->name << " = " << o->base << ';');
      }
    }
    line("");

    /* class type aliases */
    for (auto o : classes) {
      if (o->isAlias()) {
        genTemplateParams(o);
        ++inPointer;
        line("using " << o->name << " = " << o->base << ';');
      }
    }

    line("}\n");
    line("}\n");
    line("");

    line("");
    line("namespace libbirch {");

    /* forward super type declarations */
    for (auto o : sortedClasses) {
      if (!o->base->isEmpty() && o->isBound()) {
        start("template<> ");
        middle("struct super_type<bi::type::" << o->name);
        genTemplateArgs(o);
        finish("> {");
        in();
        ++inPointer;
        line("using type = " << o->base << ';');
        out();
        line("};");
      }
    }

    /* forward assignment operator declarations */
    for (auto o : sortedClasses) {
      if (o->isBound()) {
        for (auto o1 : o->assignments) {
          start("template<> ");
          middle("struct has_assignment<bi::type::" << o->name);
          genTemplateArgs(o);
          finish("," << o1 << "> {");
          in();
          line("static const bool value = true;");
          out();
          line("};");
        }
      }
    }

    /* forward conversion operator declarations */
    for (auto o : sortedClasses) {
      if (o->isBound()) {
        for (auto o1 : o->conversions) {
          start("template<> ");
          middle("struct has_conversion<bi::type::" << o->name);
          genTemplateArgs(o);
          finish("," << o1 << "> {");
          in();
          line("static const bool value = true;");
          out();
          line("};");
        }
      }
    }
    line("");
    line("}\n");

    line("");
    line("namespace bi {");
    line("namespace type {");

    /* class definitions */
    for (auto o : sortedClasses) {
      *this << o;
    }
    for (auto o : classes) {
      if (o->isAlias()) {
        *this << o;
      }
    }
    line("");
    line("}\n");

    /* global variables */
    for (auto o : globals) {
      *this << o;
    }

    /* functions and fibers */
    for (auto o : functions) {
      *this << o;
    }
    for (auto o : fibers) {
      *this << o;
    }
    for (auto o : headerFunctions) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
    for (auto o : headerFibers) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }

    /* programs */
    for (auto o : programs) {
      *this << o;
    }

    /* operators */
    for (auto o : binaries) {
      *this << o;
    }
    for (auto o : unaries) {
      *this << o;
    }

    line("}\n");
    line("");
    line("#endif");
  } else {
    /* instantiations of generics from dependencies */
    for (auto o : sortedClasses) {
      if (o->isGeneric() && o->isBound()) {
        *this << o;
      }
    }
    for (auto o : headerFunctions) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
    for (auto o : headerFibers) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
  }
}
<commit_msg>Fixed C++ code generation for forward declaration of classes that are implemented in C++.<commit_after>/**
 * @file
 */
#include "bi/io/cpp/CppPackageGenerator.hpp"

#include "bi/io/cpp/CppRawGenerator.hpp"
#include "bi/io/cpp/CppClassGenerator.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/poset.hpp"
#include "bi/primitive/definitely.hpp"
#include "bi/build/misc.hpp"

bi::CppPackageGenerator::CppPackageGenerator(std::ostream& base,
    const int level, const bool header) :
    CppBaseGenerator(base, level, header) {
  //
}

void bi::CppPackageGenerator::visit(const Package* o) {
  /* gather important objects */
  Gatherer<Basic> basics;
  Gatherer<Class> classes, headerClasses;
  Gatherer<GlobalVariable> globals;
  Gatherer<Function> functions, headerFunctions;
  Gatherer<Fiber> fibers, headerFibers;
  Gatherer<Program> programs;
  Gatherer<BinaryOperator> binaries;
  Gatherer<UnaryOperator> unaries;
  for (auto file : o->sources) {
    file->accept(&basics);
    file->accept(&classes);
    file->accept(&globals);
    file->accept(&functions);
    file->accept(&fibers);
    file->accept(&programs);
    file->accept(&binaries);
    file->accept(&unaries);
  }
  for (auto file : o->headers) {
    file->accept(&headerClasses);
    file->accept(&headerFunctions);
    file->accept(&headerFibers);
  }

  /* base classes must be defined before their derived classes, so these are
   * gathered and sorted first */
  allowConversions = false;  // sort by inheritance, forget conversions
  poset<Type*,definitely> sorted;
  for (auto o : classes) {
    if (!o->isAlias()) {
      sorted.insert(new ClassType(o));
    }
    for (auto instantiation : o->instantiations) {
      sorted.insert(new ClassType(instantiation));
    }
  }
  for (auto o : headerClasses) {
    for (auto instantiation : o->instantiations) {
      sorted.insert(new ClassType(instantiation));
    }
  }
  allowConversions = true;
  std::list<Class*> sortedClasses;
  for (auto iter = sorted.rbegin(); iter != sorted.rend(); ++iter) {
    if (!(*iter)->getClass()->has(PRIOR_INSTANTIATION)) {
      sortedClasses.push_back((*iter)->getClass());
    }
  }

  if (header) {
    /* a `#define` include guard is preferred to `#pragma once`; the header of
     * each package is included in sources with the `-include` compile option
     * rather than `#include` preprocessor directive, including (for
     * convenience/laziness) when precompiling the header itself; this seems
     * to cause a double inclusion with `#pragma once` but not with a `#define`
     * include guard */
    line("#ifndef BI_" << tarname(o->name) << "_HPP_");
    line("#define BI_" << tarname(o->name) << "_HPP_");
    line("");

    for (auto header : o->headers) {
      fs::path include = header->path;
      include.replace_extension(".hpp");
      line("#include \"" << include.string() << "\"");
    }

    /* raw C++ code for headers */
    CppRawGenerator auxRaw(base, level, header);
    auxRaw << o;

    line("");
    line("namespace bi {");
    line("namespace type {");

    /* forward class declarations */
    for (auto o : classes) {
      if (!o->isAlias()) {
        genTemplateParams(o);
        line("class " << o->name << ';');
      }
    }
    line("");

    /* basic type aliases */
    for (auto o : basics) {
      if (o->isAlias()) {
        line("using " << o->name << " = " << o->base << ';');
      }
    }
    line("");

    /* class type aliases */
    for (auto o : classes) {
      if (o->isAlias()) {
        genTemplateParams(o);
        ++inPointer;
        line("using " << o->name << " = " << o->base << ';');
      }
    }

    line("}\n");
    line("}\n");
    line("");

    line("");
    line("namespace libbirch {");

    /* forward super type declarations */
    for (auto o : sortedClasses) {
      if (!o->base->isEmpty() && o->isBound()) {
        start("template<> ");
        middle("struct super_type<bi::type::" << o->name);
        genTemplateArgs(o);
        finish("> {");
        in();
        ++inPointer;
        line("using type = " << o->base << ';');
        out();
        line("};");
      }
    }

    /* forward assignment operator declarations */
    for (auto o : sortedClasses) {
      if (o->isBound()) {
        for (auto o1 : o->assignments) {
          start("template<> ");
          middle("struct has_assignment<bi::type::" << o->name);
          genTemplateArgs(o);
          finish("," << o1 << "> {");
          in();
          line("static const bool value = true;");
          out();
          line("};");
        }
      }
    }

    /* forward conversion operator declarations */
    for (auto o : sortedClasses) {
      if (o->isBound()) {
        for (auto o1 : o->conversions) {
          start("template<> ");
          middle("struct has_conversion<bi::type::" << o->name);
          genTemplateArgs(o);
          finish("," << o1 << "> {");
          in();
          line("static const bool value = true;");
          out();
          line("};");
        }
      }
    }
    line("");
    line("}\n");

    line("");
    line("namespace bi {");
    line("namespace type {");

    /* class definitions */
    for (auto o : sortedClasses) {
      *this << o;
    }
    for (auto o : classes) {
      if (o->isAlias()) {
        *this << o;
      }
    }
    line("");
    line("}\n");

    /* global variables */
    for (auto o : globals) {
      *this << o;
    }

    /* functions and fibers */
    for (auto o : functions) {
      *this << o;
    }
    for (auto o : fibers) {
      *this << o;
    }
    for (auto o : headerFunctions) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
    for (auto o : headerFibers) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }

    /* programs */
    for (auto o : programs) {
      *this << o;
    }

    /* operators */
    for (auto o : binaries) {
      *this << o;
    }
    for (auto o : unaries) {
      *this << o;
    }

    line("}\n");
    line("");
    line("#endif");
  } else {
    /* instantiations of generics from dependencies */
    for (auto o : sortedClasses) {
      if (o->isGeneric() && o->isBound()) {
        *this << o;
      }
    }
    for (auto o : headerFunctions) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
    for (auto o : headerFibers) {
      for (auto instantiation : o->instantiations) {
        if (!instantiation->has(PRIOR_INSTANTIATION)) {
          *this << instantiation;
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file standard_gaussian_mapping.hpp
 * \date May 2014
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__DISTRIBUTION__INTERFACE__STANDARD_GAUSSIAN_MAPPING_HPP
#define FL__DISTRIBUTION__INTERFACE__STANDARD_GAUSSIAN_MAPPING_HPP

#include <Eigen/Dense>

#include <type_traits>

#include <fl/util/traits.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/standard_gaussian.hpp>

namespace fl
{

/**
 * \ingroup distribution_interfaces
 *
 * \brief Represents the interface which provides a mapping
 *        from a standard normal variate onto the underlying distribution which
 *        implements this interface
 *
 * \tparam Variate              The Distribution variate type. This is the type
 *                              which is being returned by the mapping or
 *                              sampling, respectively.
 * \tparam StdVariateDimension  Dimension of the source variate type which is
 *                              the standard normal variate
 *                              \f$x_{SNV}\sim{\cal N}(0, I)\f$
 */
template <typename Variate, int StdVariateDimension>
class StandardGaussianMapping
    : public Sampling<Variate>
{
public:
    typedef Eigen::Matrix<Real, StdVariateDimension, 1> StandardVariate;

    /**
     * StandardGaussianMapping constructor. It initializes the mapper
     *
     * \param snv_dimension     Dimension of the standard normal variate
     */
    explicit StandardGaussianMapping(
            int snv_dimension = DimensionOf<StandardVariate>())
        : standard_gaussian_(snv_dimension)
    { }

    /**
     * \brief Overridable default destructor
     */
    virtual ~StandardGaussianMapping() { }

    /**
     * \brief Mapps a standard normal variate onto a sample of the underlying
     *        distribution which implements this mapper
     *
     * \param sample  SNV sample which will be mapped onto a variate sampe
     *
     * \return A variate according to the underlying distribution
     */
    virtual Variate map_standard_normal(const StandardVariate& sample) const = 0;

    /**
     * \return A variate according to the underlying distribution
     */
    virtual Variate sample() const
    {
        return map_standard_normal(standard_gaussian_.sample());
    }

    /**
     * \return Dimension of the standard normal variate used for mapping
     */
    virtual int standard_variate_dimension() const
    {
        return standard_gaussian_.dimension();
    }

    /**
     * \brief Sets the dimension of the standard normal variate
     *
     * \param snv_dimension The new dimension of the SNV
     */
    virtual void standard_variate_dimension(int snv_dimension)
    {
        standard_gaussian_.dimension(snv_dimension);
    }

protected:
    /**
     * \brief SNV generator
     */
    mutable StandardGaussian<StandardVariate> standard_gaussian_;
};

/**
 * \ingroup distribution_interfaces
 *
 * \brief Represents the interface which provides a mapping
 *        from a scalar standard normal variate onto the underlying distribution
 *        which implements this interface.
 *
 * \tparam Variate          The Distribution variate type. This is the type
 *                          which is being returned by the mapping or sampling,
 *                          respectively.
 */
template <typename Variate>
class StandardGaussianMapping<Variate, 1>
    : public Sampling<Variate>
{
public:
    typedef Real StandardVariate;

    /**
     * \brief Overridable default destructor
     */
    virtual ~StandardGaussianMapping() { }

    /**
     * \brief Mapps a one dimensional standard normal variate onto a sample of
     *        the underlying distribution which implements this mapper
     *
     * \param sample SNV sample which will be mapped onto a variate sampe
     *
     * \return A variate according to the underlying distribution
     */
    virtual Variate map_standard_normal(const Real& sample) const = 0;

    /**
     * \return A variate according to the underlying distribution
     */
    virtual Variate sample() const
    {
        return map_standard_normal(standard_gaussian_.sample());
    }

    /**
     * \return Dimension of the standard normal variate used for mapping
     */
    virtual int standard_variate_dimension() const
    {
        return 1;
    }

protected:
    /**
     * \brief One dimensional SNV generator
     */
    mutable StandardGaussian<Real> standard_gaussian_;
};

}

#endif
<commit_msg>added missing functions to standard_gaussian_map specialization for scalars<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file standard_gaussian_mapping.hpp
 * \date May 2014
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__DISTRIBUTION__INTERFACE__STANDARD_GAUSSIAN_MAPPING_HPP
#define FL__DISTRIBUTION__INTERFACE__STANDARD_GAUSSIAN_MAPPING_HPP

#include <Eigen/Dense>

#include <type_traits>

#include <fl/util/traits.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/standard_gaussian.hpp>

namespace fl
{

/**
 * \ingroup distribution_interfaces
 *
 * \brief Represents the interface which provides a mapping
 *        from a standard normal variate onto the underlying distribution which
 *        implements this interface
 *
 * \tparam Variate              The Distribution variate type. This is the type
 *                              which is being returned by the mapping or
 *                              sampling, respectively.
 * \tparam StdVariateDimension  Dimension of the source variate type which is
 *                              the standard normal variate
 *                              \f$x_{SNV}\sim{\cal N}(0, I)\f$
 */
template <typename Variate, int StdVariateDimension>
class StandardGaussianMapping
    : public Sampling<Variate>
{
public:
    typedef Eigen::Matrix<Real, StdVariateDimension, 1> StandardVariate;

    /**
     * StandardGaussianMapping constructor. It initializes the mapper
     *
     * \param snv_dimension     Dimension of the standard normal variate
     */
    explicit StandardGaussianMapping(
            int snv_dimension = DimensionOf<StandardVariate>())
        : standard_gaussian_(snv_dimension)
    { }

    /**
     * \brief Overridable default destructor
     */
    virtual ~StandardGaussianMapping() { }

    /**
     * \brief Mapps a standard normal variate onto a sample of the underlying
     *        distribution which implements this mapper
     *
     * \param sample  SNV sample which will be mapped onto a variate sampe
     *
     * \return A variate according to the underlying distribution
     */
    virtual Variate map_standard_normal(const StandardVariate& sample) const = 0;

    /**
     * \return A variate according to the underlying distribution
     */
    virtual Variate sample() const
    {
        return map_standard_normal(standard_gaussian_.sample());
    }

    /**
     * \return Dimension of the standard normal variate used for mapping
     */
    virtual int standard_variate_dimension() const
    {
        return standard_gaussian_.dimension();
    }

    /**
     * \brief Sets the dimension of the standard normal variate
     *
     * \param snv_dimension The new dimension of the SNV
     */
    virtual void standard_variate_dimension(int snv_dimension)
    {
        standard_gaussian_.dimension(snv_dimension);
    }

protected:
    /**
     * \brief SNV generator
     */
    mutable StandardGaussian<StandardVariate> standard_gaussian_;
};

/**
 * \ingroup distribution_interfaces
 *
 * \brief Represents the interface which provides a mapping
 *        from a scalar standard normal variate onto the underlying distribution
 *        which implements this interface.
 *
 * \tparam Variate          The Distribution variate type. This is the type
 *                          which is being returned by the mapping or sampling,
 *                          respectively.
 */
template <typename Variate>
class StandardGaussianMapping<Variate, 1>
    : public Sampling<Variate>
{
public:
    typedef Real StandardVariate;

    /// \todo fix this (unused argument)
    explicit StandardGaussianMapping(int snv_dimension = 1)
    { }

    /**
     * \brief Overridable default destructor
     */
    virtual ~StandardGaussianMapping() { }

    /**
     * \brief Mapps a one dimensional standard normal variate onto a sample of
     *        the underlying distribution which implements this mapper
     *
     * \param sample SNV sample which will be mapped onto a variate sampe
     *
     * \return A variate according to the underlying distribution
     */
    virtual Variate map_standard_normal(const Real& sample) const = 0;

    /**
     * \return A variate according to the underlying distribution
     */
    virtual Variate sample() const
    {
        return map_standard_normal(standard_gaussian_.sample());
    }

    /**
     * \return Dimension of the standard normal variate used for mapping
     */
    virtual int standard_variate_dimension() const
    {
        return 1;
    }

    /// \todo fix this (unused argument)
    virtual void standard_variate_dimension(int snv_dimension)
    {
    }

protected:
    /**
     * \brief One dimensional SNV generator
     */
    mutable StandardGaussian<Real> standard_gaussian_;
};

}

#endif
<|endoftext|>


<commit_before>#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>

int
main (int argc, char** argv)
{
  // Load input file into a PointCloud<T> with an appropriate type
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
  // Load bun0.pcd -- should be available with the PCL archive in test
  pcl::io::loadPCDFile ("bun0.pcd", *cloud);

  // Create a KD-Tree
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);

  // Output has the same type as the input one, it will be only smoothed
  pcl::PointCloud<pcl::PointXYZ> mls_points;

  // Init object (second point type is for the normals, even if unused)
  pcl::MovingLeastSquares<pcl::PointXYZ, pcl::Normal> mls;

  // Optionally, a pointer to a cloud can be provided, to be set by MLS
  pcl::PointCloud<pcl::Normal>::Ptr mls_normals (new pcl::PointCloud<pcl::Normal> ());
  mls.setOutputNormals (mls_normals);

  // Set parameters
  mls.setInputCloud (cloud);
  mls.setPolynomialFit (true);
  mls.setSearchMethod (tree);
  mls.setSearchRadius (0.03);

  // Reconstruct
  mls.reconstruct (mls_points);

  // Concatenate fields for saving
  pcl::PointCloud<pcl::PointNormal> mls_cloud;
  pcl::concatenateFields (mls_points, *mls_normals, mls_cloud);

  // Save output
  pcl::io::savePCDFile ("bun0-mls.pcd", mls_cloud);
}
<commit_msg>fixing tutorials for the new MLS code<commit_after>#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>

int
main (int argc, char** argv)
{
  // Load input file into a PointCloud<T> with an appropriate type
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
  // Load bun0.pcd -- should be available with the PCL archive in test
  pcl::io::loadPCDFile ("bun0.pcd", *cloud);

  // Create a KD-Tree
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);

  // Output has the PointNormal type in order to store the normals calculated by MLS
  pcl::PointCloud<pcl::PointNormal> mls_points;

  // Init object (second point type is for the normals, even if unused)
  pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;

  mls.setComputeNormals (true);

  // Set parameters
  mls.setInputCloud (cloud);
  mls.setPolynomialFit (true);
  mls.setSearchMethod (tree);
  mls.setSearchRadius (0.03);

  // Reconstruct
  mls.process (mls_points);

  // Save output
  pcl::io::savePCDFile ("bun0-mls.pcd", mls_points);
}
<|endoftext|>


<commit_before>// @(#)root/eve:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveLine.h"
#include "TEveProjectionManager.h"

//==============================================================================
//==============================================================================
// TEveLine
//==============================================================================

//______________________________________________________________________________
//
// An arbitrary polyline with fixed line and marker attributes.

ClassImp(TEveLine);

Bool_t TEveLine::fgDefaultSmooth = kFALSE;

//______________________________________________________________________________
TEveLine::TEveLine(Int_t n_points, ETreeVarType_e tv_type) :
   TEvePointSet("Line", n_points, tv_type),
   fRnrLine   (kTRUE),
   fRnrPoints (kFALSE),
   fSmooth    (fgDefaultSmooth)
{
   // Constructor.

   fMainColorPtr = &fLineColor;
   fMarkerColor  =  kGreen;
}

//______________________________________________________________________________
TEveLine::TEveLine(const char* name, Int_t n_points, ETreeVarType_e tv_type) :
   TEvePointSet(name, n_points, tv_type),
   fRnrLine   (kTRUE),
   fRnrPoints (kFALSE),
   fSmooth    (fgDefaultSmooth)
{
   // Constructor.

   fMainColorPtr = &fLineColor;
   fMarkerColor = kGreen;
}

//______________________________________________________________________________
const TGPicture* TEveLine::GetListTreeIcon(Bool_t)
{
   // Returns list-tree icon for TEveLine.

   return fgListTreeIcons[8];
}

//______________________________________________________________________________
void TEveLine::SetMarkerColor(Color_t col)
{
   // Set marker color. Propagate to projected lines.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l && fMarkerColor == l->GetMarkerColor())
      {
         l->SetMarkerColor(col);
         l->StampObjProps();
      }
      ++pi;
   }
   TAttMarker::SetMarkerColor(col);
}

//______________________________________________________________________________
void TEveLine::SetLineStyle(Style_t lstyle)
{
   // Set line-style of the line.
   // The style is propagated to projecteds.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* pt = dynamic_cast<TEveLine*>(*pi);
      if (pt)
      {
         pt->SetLineStyle(lstyle);
         pt->StampObjProps();
      }
      ++pi;
   }
   TAttLine::SetLineStyle(lstyle);
}

//______________________________________________________________________________
void TEveLine::SetLineWidth(Width_t lwidth)
{
   // Set line-style of the line.
   // The style is propagated to projecteds.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* pt = dynamic_cast<TEveLine*>(*pi);
      if (pt)
      {
         pt->SetLineWidth(lwidth);
         pt->StampObjProps();
      }
      ++pi;
   }
   TAttLine::SetLineWidth(lwidth);
}

//______________________________________________________________________________
void TEveLine::SetRnrLine(Bool_t r)
{
   // Set rendering of line. Propagate to projected lines.

   fRnrLine = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetRnrLine(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//______________________________________________________________________________
void TEveLine::SetRnrPoints(Bool_t r)
{
   // Set rendering of points. Propagate to projected lines.

   fRnrPoints = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetRnrPoints(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//______________________________________________________________________________
void TEveLine::SetSmooth(Bool_t r)
{
   // Set smooth rendering. Propagate to projected lines.

   fSmooth = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetSmooth(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//==============================================================================

//______________________________________________________________________________
void TEveLine::ReduceSegmentLengths(Float_t max)
{
   // Make sure that no segment is longer than max.
   // Per point references and integer ids are lost.

   const Float_t max2 = max*max;

   Float_t    *p = GetP();
   Int_t       s = Size();
   TEveVector  a, b, d;

   std::vector<TEveVector> q;

   b.Set(p);
   q.push_back(b);
   for (Int_t i = 1; i < s; ++i)
   {
      a = b; b.Set(&p[3*i]); d = b - a;
      Float_t m2 = d.Mag2();
      if (m2 > max2)
      {
         Float_t f = TMath::Sqrt(m2) / max;
         Int_t   n = TMath::FloorNint(f);
         d *= 1.0f / (n + 1);
         for (Int_t j = 0; j < n; ++j)
         {
            a += d;
            q.push_back(a);
         }
      }
      q.push_back(b);
   }

   s = q.size();
   Reset(s);
   for (std::vector<TEveVector>::iterator i = q.begin(); i != q.end(); ++i)
      SetNextPoint(i->fX, i->fY, i->fZ);
}

//______________________________________________________________________________
TEveVector TEveLine::GetLineStart() const
{
   // Return the first point of the line.
   // If there are no points (0,0,0) is returned.

   TEveVector v;
   GetPoint(0, v.fX, v.fY, v.fZ);
   return v;
}

//______________________________________________________________________________
TEveVector TEveLine::GetLineEnd() const
{
   // Return the last point of the line.
   // If there are no points (0,0,0) is returned.

   TEveVector v;
   GetPoint(fLastPoint, v.fX, v.fY, v.fZ);
   return v;
}

//==============================================================================

//______________________________________________________________________________
void TEveLine::CopyVizParams(const TEveElement* el)
{
   // Copy visualization parameters from element el.

   const TEveLine* m = dynamic_cast<const TEveLine*>(el);
   if (m)
   {
      TAttLine::operator=(*m);
      fRnrLine   = m->fRnrLine;
      fRnrPoints = m->fRnrPoints;
      fSmooth    = m->fSmooth;
   }

   TEvePointSet::CopyVizParams(el);
}

//______________________________________________________________________________
void TEveLine::WriteVizParams(ostream& out, const TString& var)
{
   // Write visualization parameters.

   TEvePointSet::WriteVizParams(out, var);

   TString t = "   " + var + "->";
   TAttLine::SaveLineAttributes(out, var);
   out << t << "SetRnrLine("   << ToString(fRnrLine)   << ");\n";
   out << t << "SetRnrPoints(" << ToString(fRnrPoints) << ");\n";
   out << t << "SetSmooth("    << ToString(fSmooth)    << ");\n";
}

//______________________________________________________________________________
TClass* TEveLine::ProjectedClass(const TEveProjection*) const
{
   // Virtual from TEveProjectable, returns TEvePointSetProjected class.

   return TEveLineProjected::Class();
}

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

//______________________________________________________________________________
Bool_t TEveLine::GetDefaultSmooth()
{
   // Get default value for smooth-line drawing flag.
   // Static function.

   return fgDefaultSmooth;
}

//______________________________________________________________________________
void TEveLine::SetDefaultSmooth(Bool_t r)
{
   // Set default value for smooth-line drawing flag (default kFALSE).
   // Static function.

   fgDefaultSmooth = r;
}

//==============================================================================
//==============================================================================
// TEveLineProjected
//==============================================================================

//______________________________________________________________________________
//
// Projected copy of a TEvePointSet.

ClassImp(TEveLineProjected);

//______________________________________________________________________________
TEveLineProjected::TEveLineProjected() :
   TEveLine      (),
   TEveProjected ()
{
   // Default constructor.
}

//______________________________________________________________________________
void TEveLineProjected::SetProjection(TEveProjectionManager* mng,
                                      TEveProjectable* model)
{
   // Set projection manager and projection model.
   // Virtual from TEveProjected.

   TEveProjected::SetProjection(mng, model);
   CopyVizParams(dynamic_cast<TEveElement*>(model));
}

//______________________________________________________________________________
void TEveLineProjected::SetDepthLocal(Float_t d)
{
   // Set depth (z-coordinate) of the projected points.

   SetDepthCommon(d, this, fBBox);

   Int_t    n = Size();
   Float_t *p = GetP() + 2;
   for (Int_t i = 0; i < n; ++i, p+=3)
      *p = fDepth;
}

//______________________________________________________________________________
void TEveLineProjected::UpdateProjection()
{
   // Re-apply the projection.
   // Virtual from TEveProjected.

   TEveProjection& proj = * fManager->GetProjection();
   TEveLine      & als  = * dynamic_cast<TEveLine*>(fProjectable);
   TEveTrans      *tr   =   als.PtrMainTrans(kFALSE);

   Int_t n = als.Size();
   Reset(n);
   fLastPoint = n - 1;
   Float_t *o = als.GetP(), *p = GetP();
   for (Int_t i = 0; i < n; ++i, o+=3, p+=3)
   {
      proj.ProjectPointfv(tr, o, p, fDepth);
   }
}
<commit_msg>Typo in comment.<commit_after>// @(#)root/eve:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveLine.h"
#include "TEveProjectionManager.h"

//==============================================================================
//==============================================================================
// TEveLine
//==============================================================================

//______________________________________________________________________________
//
// An arbitrary polyline with fixed line and marker attributes.

ClassImp(TEveLine);

Bool_t TEveLine::fgDefaultSmooth = kFALSE;

//______________________________________________________________________________
TEveLine::TEveLine(Int_t n_points, ETreeVarType_e tv_type) :
   TEvePointSet("Line", n_points, tv_type),
   fRnrLine   (kTRUE),
   fRnrPoints (kFALSE),
   fSmooth    (fgDefaultSmooth)
{
   // Constructor.

   fMainColorPtr = &fLineColor;
   fMarkerColor  =  kGreen;
}

//______________________________________________________________________________
TEveLine::TEveLine(const char* name, Int_t n_points, ETreeVarType_e tv_type) :
   TEvePointSet(name, n_points, tv_type),
   fRnrLine   (kTRUE),
   fRnrPoints (kFALSE),
   fSmooth    (fgDefaultSmooth)
{
   // Constructor.

   fMainColorPtr = &fLineColor;
   fMarkerColor = kGreen;
}

//______________________________________________________________________________
const TGPicture* TEveLine::GetListTreeIcon(Bool_t)
{
   // Returns list-tree icon for TEveLine.

   return fgListTreeIcons[8];
}

//______________________________________________________________________________
void TEveLine::SetMarkerColor(Color_t col)
{
   // Set marker color. Propagate to projected lines.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l && fMarkerColor == l->GetMarkerColor())
      {
         l->SetMarkerColor(col);
         l->StampObjProps();
      }
      ++pi;
   }
   TAttMarker::SetMarkerColor(col);
}

//______________________________________________________________________________
void TEveLine::SetLineStyle(Style_t lstyle)
{
   // Set line-style of the line.
   // The style is propagated to projecteds.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* pt = dynamic_cast<TEveLine*>(*pi);
      if (pt)
      {
         pt->SetLineStyle(lstyle);
         pt->StampObjProps();
      }
      ++pi;
   }
   TAttLine::SetLineStyle(lstyle);
}

//______________________________________________________________________________
void TEveLine::SetLineWidth(Width_t lwidth)
{
   // Set line-style of the line.
   // The style is propagated to projecteds.

   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* pt = dynamic_cast<TEveLine*>(*pi);
      if (pt)
      {
         pt->SetLineWidth(lwidth);
         pt->StampObjProps();
      }
      ++pi;
   }
   TAttLine::SetLineWidth(lwidth);
}

//______________________________________________________________________________
void TEveLine::SetRnrLine(Bool_t r)
{
   // Set rendering of line. Propagate to projected lines.

   fRnrLine = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetRnrLine(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//______________________________________________________________________________
void TEveLine::SetRnrPoints(Bool_t r)
{
   // Set rendering of points. Propagate to projected lines.

   fRnrPoints = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetRnrPoints(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//______________________________________________________________________________
void TEveLine::SetSmooth(Bool_t r)
{
   // Set smooth rendering. Propagate to projected lines.

   fSmooth = r;
   std::list<TEveProjected*>::iterator pi = fProjectedList.begin();
   while (pi != fProjectedList.end())
   {
      TEveLine* l = dynamic_cast<TEveLine*>(*pi);
      if (l)
      {
         l->SetSmooth(r);
         l->ElementChanged();
      }
      ++pi;
   }
}

//==============================================================================

//______________________________________________________________________________
void TEveLine::ReduceSegmentLengths(Float_t max)
{
   // Make sure that no segment is longer than max.
   // Per point references and integer ids are lost.

   const Float_t max2 = max*max;

   Float_t    *p = GetP();
   Int_t       s = Size();
   TEveVector  a, b, d;

   std::vector<TEveVector> q;

   b.Set(p);
   q.push_back(b);
   for (Int_t i = 1; i < s; ++i)
   {
      a = b; b.Set(&p[3*i]); d = b - a;
      Float_t m2 = d.Mag2();
      if (m2 > max2)
      {
         Float_t f = TMath::Sqrt(m2) / max;
         Int_t   n = TMath::FloorNint(f);
         d *= 1.0f / (n + 1);
         for (Int_t j = 0; j < n; ++j)
         {
            a += d;
            q.push_back(a);
         }
      }
      q.push_back(b);
   }

   s = q.size();
   Reset(s);
   for (std::vector<TEveVector>::iterator i = q.begin(); i != q.end(); ++i)
      SetNextPoint(i->fX, i->fY, i->fZ);
}

//______________________________________________________________________________
TEveVector TEveLine::GetLineStart() const
{
   // Return the first point of the line.
   // If there are no points (0,0,0) is returned.

   TEveVector v;
   GetPoint(0, v.fX, v.fY, v.fZ);
   return v;
}

//______________________________________________________________________________
TEveVector TEveLine::GetLineEnd() const
{
   // Return the last point of the line.
   // If there are no points (0,0,0) is returned.

   TEveVector v;
   GetPoint(fLastPoint, v.fX, v.fY, v.fZ);
   return v;
}

//==============================================================================

//______________________________________________________________________________
void TEveLine::CopyVizParams(const TEveElement* el)
{
   // Copy visualization parameters from element el.

   const TEveLine* m = dynamic_cast<const TEveLine*>(el);
   if (m)
   {
      TAttLine::operator=(*m);
      fRnrLine   = m->fRnrLine;
      fRnrPoints = m->fRnrPoints;
      fSmooth    = m->fSmooth;
   }

   TEvePointSet::CopyVizParams(el);
}

//______________________________________________________________________________
void TEveLine::WriteVizParams(ostream& out, const TString& var)
{
   // Write visualization parameters.

   TEvePointSet::WriteVizParams(out, var);

   TString t = "   " + var + "->";
   TAttLine::SaveLineAttributes(out, var);
   out << t << "SetRnrLine("   << ToString(fRnrLine)   << ");\n";
   out << t << "SetRnrPoints(" << ToString(fRnrPoints) << ");\n";
   out << t << "SetSmooth("    << ToString(fSmooth)    << ");\n";
}

//______________________________________________________________________________
TClass* TEveLine::ProjectedClass(const TEveProjection*) const
{
   // Virtual from TEveProjectable, returns TEvePointSetProjected class.

   return TEveLineProjected::Class();
}

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

//______________________________________________________________________________
Bool_t TEveLine::GetDefaultSmooth()
{
   // Get default value for smooth-line drawing flag.
   // Static function.

   return fgDefaultSmooth;
}

//______________________________________________________________________________
void TEveLine::SetDefaultSmooth(Bool_t r)
{
   // Set default value for smooth-line drawing flag (default kFALSE).
   // Static function.

   fgDefaultSmooth = r;
}

//==============================================================================
//==============================================================================
// TEveLineProjected
//==============================================================================

//______________________________________________________________________________
//
// Projected copy of a TEveLine.

ClassImp(TEveLineProjected);

//______________________________________________________________________________
TEveLineProjected::TEveLineProjected() :
   TEveLine      (),
   TEveProjected ()
{
   // Default constructor.
}

//______________________________________________________________________________
void TEveLineProjected::SetProjection(TEveProjectionManager* mng,
                                      TEveProjectable* model)
{
   // Set projection manager and projection model.
   // Virtual from TEveProjected.

   TEveProjected::SetProjection(mng, model);
   CopyVizParams(dynamic_cast<TEveElement*>(model));
}

//______________________________________________________________________________
void TEveLineProjected::SetDepthLocal(Float_t d)
{
   // Set depth (z-coordinate) of the projected points.

   SetDepthCommon(d, this, fBBox);

   Int_t    n = Size();
   Float_t *p = GetP() + 2;
   for (Int_t i = 0; i < n; ++i, p+=3)
      *p = fDepth;
}

//______________________________________________________________________________
void TEveLineProjected::UpdateProjection()
{
   // Re-apply the projection.
   // Virtual from TEveProjected.

   TEveProjection& proj = * fManager->GetProjection();
   TEveLine      & als  = * dynamic_cast<TEveLine*>(fProjectable);
   TEveTrans      *tr   =   als.PtrMainTrans(kFALSE);

   Int_t n = als.Size();
   Reset(n);
   fLastPoint = n - 1;
   Float_t *o = als.GetP(), *p = GetP();
   for (Int_t i = 0; i < n; ++i, o+=3, p+=3)
   {
      proj.ProjectPointfv(tr, o, p, fDepth);
   }
}
<|endoftext|>


<commit_before>
#include "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "GeneratedTypes.h"
#include "HdmiControlRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <sys/mman.h>
#include "i2chdmi.h"

HdmiControlRequestProxy *device = 0;
PortalAlloc srcAlloc;
PortalAlloc dstAlloc;
int srcFd = -1;
int dstFd = -1;
char *srcBuffer = 0;
char *dstBuffer = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s: ", prefix);
    for (int i = 0; i < 16; i++)
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
    fprintf(stderr, "\n");
}

int main(int argc, const char **argv)
{
    PortalPoller *poller = new PortalPoller();

    device = new HdmiControlRequestProxy(IfcNames_HdmiControlRequest, poller);

    int status = poller->setClockFrequency(1, 160000000, 0);
    init_i2c_hdmi();
    portalExec(0);
}
<commit_msg>updated gralloc/testhdmidisplay.cpp to start frame buffer<commit_after>
#include "DmaConfigProxy.h"
#include "DmaIndicationWrapper.h"
#include "StdDmaIndication.h"
#include "GeneratedTypes.h"
#include "HdmiControlRequestProxy.h"
#include "portal.h"
#include <stdio.h>
#include <sys/mman.h>
#include "i2chdmi.h"

HdmiControlRequestProxy *device = 0;
PortalAlloc srcAlloc;
PortalAlloc dstAlloc;
int srcFd = -1;
int dstFd = -1;
char *srcBuffer = 0;
char *dstBuffer = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s: ", prefix);
    for (int i = 0; i < 16; i++)
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
    fprintf(stderr, "\n");
}

static void *thread_routine(void *data)
{
    fprintf(stderr, "Calling portalExec\n");
    portalExec(0);
    fprintf(stderr, "portalExec returned ???\n");
    return data;
}

int main(int argc, const char **argv)
{
    PortalPoller *poller = new PortalPoller();
    PortalAlloc *portalAlloc = 0;;
    DmaConfigProxy *dma;
    DmaIndicationWrapper *dmaIndication;

    device = new HdmiControlRequestProxy(IfcNames_HdmiControlRequest, poller);
    dma = new DmaConfigProxy(IfcNames_DmaConfig);
    dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);

    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&thread, &attr, thread_routine, 0);

    int status = poller->setClockFrequency(1, 160000000, 0);
    init_i2c_hdmi();

    int fbsize = 720*480*4;
    int err = dma->alloc(fbsize, &portalAlloc);
    int fd = portalAlloc->header.fd;
    int *ptr = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    fprintf(stderr, "Filling frame buffer ptr=%p... ", ptr);
    for (int i = 0; i < fbsize/4; i++) {
      ptr[i] = 0x00FF00FF;
    }
    fprintf(stderr, "done\n");
    dma->dCacheFlushInval(portalAlloc, ptr);
    fprintf(stderr, "calling dma->reference\n");
    unsigned int ref_srcAlloc = dma->reference(portalAlloc);
    sleep(10);
    fprintf(stderr, "Starting frame buffer ref=%d...", ref_srcAlloc);
    device->startFrameBuffer0(ref_srcAlloc);
    fprintf(stderr, "done\n");
}
<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : A.cpp
 * Author  : Kazune Takahashi
 * Created : 3/2/2019, 2:05:44 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, T;

void CE()
{
  assert(false);
}

void WA()
{
  while (true)
  {
    cout << 0 << endl;
    int x;
    cin >> x;
    cout << 49 << endl;
    cin >> x;
  }
}

void AC()
{
  cout << -1 << endl;
}

int a[50];

int main()
{
  cin >> N >> T;
  fill(a, a + N, -1);
  int cnt = 0;
  int score = 0;
  for (auto i = 0; i < N; i++)
  {
    cout << i << endl;
    cin >> a[i];
    if (i >= 1 && a[i - 1] == a[i])
    {
      score += a[i];
    }
    if (score == 1)
    {
      CE();
    }
    else if (score > 1)
    {
      WA();
    }
    if (a[i] == 1)
    {
      cnt++;
    }
    if (cnt == 2)
    {
      for (auto j = 0; j < i; j++)
      {
        if (a[j] == 1)
        {
          cout << j << endl;
          int x;
          cin >> x;
          CE();
        }
      }
    }
  }
  WA();
}<commit_msg>submit A.cpp to 'A - めくってそろえる' (rco-contest-2019-final-open) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1

/**
 * File    : A.cpp
 * Author  : Kazune Takahashi
 * Created : 3/2/2019, 2:05:44 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, T;

void CE()
{
  assert(false);
}

void WA()
{
  while (true)
  {
    cout << 99 << endl;
    int x;
    cin >> x;
    cout << 0 << endl;
    cin >> x;
  }
}

void AC()
{
  cout << -1 << endl;
}

int a[50];

int main()
{
  cin >> N >> T;
  fill(a, a + N, -1);
  int cnt = 0;
  int score = 0;
  for (auto i = 0; i < N; i++)
  {
    cout << i << endl;
    cin >> a[i];
    if (i >= 1 && a[i - 1] == a[i])
    {
      score += a[i];
    }
    if (score == 1)
    {
      CE();
    }
    else if (score > 1)
    {
      WA();
    }
    if (a[i] == 1)
    {
      cnt++;
    }
    if (cnt == 2)
    {
      for (auto j = 0; j < i; j++)
      {
        if (a[j] == 1)
        {
          cout << j << endl;
          int x;
          cin >> x;
          CE();
        }
      }
    }
  }
  WA();
}<|endoftext|>


<commit_before>
/**
 * @file   soundManager.cpp
 * @brief  SE,BGMなどサウンド関係を管理します
 *
 * @author y.akira
 * @date   2017.01.15
 */

#include "precompiled.h"

//! サウンドを配列で保管
vector<shared_ptr<ofSoundPlayer>> g_sounds;

/**
 * @brief ゲームで使うサウンドを全て読み込む
 */
void LoadAllSound(const string& path) {
  ofxJSON json;
  json.open(path);

  // enumとjson内の数に相違がないか確認
  assert(json["Sounds"].size() == SOUND_NUM);

  // 配列の初期化、メモリ確保
  g_sounds.clear();
  g_sounds.resize(SOUND_NUM);

  // サウンドの名前を配列で取得
  auto names = json["Sounds"].getMemberNames();

  // jsonまでのパスの取得
  string root = json["Root"].asString();

  // サウンドの読み込み
  for (unsigned int i = 0; i < SOUND_NUM; i++) {
    g_sounds[i] = make_shared<ofSoundPlayer>();
    g_sounds[i]->load(root + names[i]);

    // 読み込めてなかった時のためヌルチェック
    if (auto& sound = g_sounds[i]) {
      auto j = json["Sounds"][names[i]];

      // パラメータの設定
      if (j.isMember("volume")) {
        sound->setVolume(j["volume"].asFloat());
      }
      if (j.isMember("speed")) {
        sound->setSpeed(j["speed"].asFloat());
      }
      if (j.isMember("loop")) {
        sound->setLoop(j["loop"].asBool());
      }
      if (j.isMember("multiplay")) {
        sound->setMultiPlay(j["multiplay"].asBool());
      }
    }
  }
}

/**
 * @brief サウンドの取得
 * @brief 細かな設定をしたい時に使用してください
 */
shared_ptr<ofSoundPlayer> FindSound(SoundTag tag) {
  return g_sounds[tag];
}

//! サウンドの再生
void PlaySound(SoundTag tag) {
  g_sounds[tag]->play();
}

//! サウンドを止める
void StopSound(SoundTag tag) {
  g_sounds[tag]->stop();
}
<commit_msg>specify static<commit_after>
/**
 * @file   soundManager.cpp
 * @brief  SE,BGMなどサウンド関係を管理します
 *
 * @author y.akira
 * @date   2017.01.15
 */

#include "precompiled.h"

//! サウンドを配列で保管
static vector<shared_ptr<ofSoundPlayer>> g_sounds;

/**
 * @brief ゲームで使うサウンドを全て読み込む
 */
void LoadAllSound(const string& path) {
  ofxJSON json;
  json.open(path);

  // enumとjson内の数に相違がないか確認
  assert(json["Sounds"].size() == SOUND_NUM);

  // 配列の初期化、メモリ確保
  g_sounds.clear();
  g_sounds.resize(SOUND_NUM);

  // サウンドの名前を配列で取得
  auto names = json["Sounds"].getMemberNames();

  // jsonまでのパスの取得
  string root = json["Root"].asString();

  // サウンドの読み込み
  for (unsigned int i = 0; i < SOUND_NUM; i++) {
    g_sounds[i] = make_shared<ofSoundPlayer>();
    g_sounds[i]->load(root + names[i]);

    // 読み込めてなかった時のためヌルチェック
    if (auto& sound = g_sounds[i]) {
      auto j = json["Sounds"][names[i]];

      // パラメータの設定
      if (j.isMember("volume")) {
        sound->setVolume(j["volume"].asFloat());
      }
      if (j.isMember("speed")) {
        sound->setSpeed(j["speed"].asFloat());
      }
      if (j.isMember("loop")) {
        sound->setLoop(j["loop"].asBool());
      }
      if (j.isMember("multiplay")) {
        sound->setMultiPlay(j["multiplay"].asBool());
      }
    }
  }
}

/**
 * @brief サウンドの取得
 * @brief 細かな設定をしたい時に使用してください
 */
shared_ptr<ofSoundPlayer> FindSound(SoundTag tag) {
  return g_sounds[tag];
}

//! サウンドの再生
void PlaySound(SoundTag tag) {
  g_sounds[tag]->play();
}

//! サウンドを止める
void StopSound(SoundTag tag) {
  g_sounds[tag]->stop();
}
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH

// we still need this for the vtk writer
#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif

#include <vector>

#include <dune/grid/io/file/vtk/vtkwriter.hh>

#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>
#include <dune/stuff/function/fixed.hh>

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

// forward of the nonparametric default
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class ModelDefault;

// forward to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class ModelInterface
{
public:
  ModelInterface() = delete;
};

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class ModelInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef ModelInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;

  typedef DomainFieldImp  DomainFieldType;
  static const int        dimDomain = domainDim;

  typedef RangeFieldImp   RangeFieldType;
  static const int        dimRange = 1;

  typedef typename Stuff::Common::Parameter::FieldType  ParamFieldType;
  static const int                                      maxParamDim = Stuff::Common::Parameter::maxDim;
  typedef typename Stuff::Common::Parameter::Type       ParamType;

  typedef Dune::Stuff::FunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType;

  static const std::string id()
  {
    return "model.linearelliptic";
  }

  /** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
  /* @{ */
  virtual bool parametric() const
  {
    if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
      return true;
    else
      return false;
  }

  virtual bool affineparametric() const
  {
    if (parametric()) {
      if (diffusion()->parametric() && !diffusion()->affineparametric())
        return false;
      if (force()->parametric() && !force()->affineparametric())
        return false;
      if (dirichlet()->parametric() && !dirichlet()->affineparametric())
        return false;
      if (neumann()->parametric() && !neumann()->affineparametric())
        return false;
      return true;
    } else
      return false;
  } // ... affineparametric()
  /* @} */

  /** \defgroup purevirtual ´´These methods have to be implemented.'' */
  /* @{ */
  virtual std::shared_ptr< const FunctionType > diffusion() const = 0;

  virtual std::shared_ptr< const FunctionType > force() const = 0;

  virtual std::shared_ptr< const FunctionType > dirichlet() const = 0;

  virtual std::shared_ptr< const FunctionType > neumann() const = 0;
  /* @} */

  /** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
  /* @{ */
  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  /**
   * \brief     Maps a global to a local parameter.
   * \param[in] ParamType _globalMu
   *            global parameter
   * \param[in] std::string _id
   *            To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
   *            force, dirichlet or neumann
   * \return    ParamType
   *            local parameter
   */
  virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
  {
    if (!parametric())
      return ParamType();
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }
  /* @} */

  virtual std::shared_ptr< const ThisType > fix(const ParamType& mu) const
  {
    if (!parametric() && mu.size() != 0)
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " do not call fix(mu) with a nonempty mu for a nonparametric model (check parametric() == true beforehand)!");
    typedef Dune::Stuff::FunctionFixed< DomainFieldType, dimDomain, RangeFieldType, dimRange > FixedFunctionType;
    typedef ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange > DefaultModelType;
    return std::make_shared< DefaultModelType >(diffusion()->parametric() ? std::make_shared< const FixedFunctionType >(diffusion(), mapParam(mu, "diffusion")) : diffusion(),
                                                force()->parametric() ? std::make_shared< const FixedFunctionType >(force(), mapParam(mu, "force")) : force(),
                                                dirichlet()->parametric() ? std::make_shared< const FixedFunctionType >(dirichlet(), mapParam(mu, "dirichlet")) : dirichlet(),
                                                neumann()->parametric() ? std::make_shared< const FixedFunctionType >(neumann(), mapParam(mu, "neumann")) : neumann());
  }

  template< class GridViewType >
  void visualize(const GridViewType& gridView, std::string filename) const
  {
    // prepare data
    Dune::VTKWriter< GridViewType > vtkWriter(gridView);
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
        = preparePlot(gridView, *(diffusion()), "diffusion");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
        = preparePlot(gridView, *(force()), "force");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
        = preparePlot(gridView, *(dirichlet()), "dirichlet");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
        = preparePlot(gridView, *(neumann()), "neumann");
    // walk the grid view
    for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
         it != gridView.template end< 0 >();
         ++it) {
      const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
      const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
      const typename FunctionType::DomainType center = entity.geometry().center();
      // do a piecewise constant projection of the data functions
      //   * diffusion
      if (diffusion()->parametric() && diffusion()->affineparametric())
        for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
          diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
      else if (!diffusion()->parametric())
        diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * force
      if (force()->parametric() && force()->affineparametric())
        for (size_t qq = 0; qq < force()->numComponents(); ++qq)
          forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
      else if (!force()->parametric())
        forcePlots[0].second->operator[](index) = force()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * dirichlet
      if (dirichlet()->parametric() && dirichlet()->affineparametric())
        for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
          dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
      else if (!dirichlet()->parametric())
        dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * neumann
      if (neumann()->parametric() && neumann()->affineparametric())
        for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
          neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
      else if (!neumann()->parametric())
        neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
    } // walk the grid view
    // write
    //   * diffusion
    for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
      vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
    //   * force
    for (size_t qq = 0; qq < forcePlots.size(); ++qq)
      vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
    //   * dirichlet
    for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
      vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
    //   * neumann
    for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
      vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
    vtkWriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const GridViewType& gridView, std::string filename) const

private:
  template< class GridViewType, class FunctionType >
  std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
                                                                                const FunctionType& function,
                                                                                const std::string name) const
  {
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
    if (function.parametric()) {
      if (function.affineparametric()) {
        const std::vector< std::string >& paramExplanations = function.paramExplanation();
        for (size_t qq = 0; qq < function.numCoefficients(); ++qq)
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
        if (function.numComponents() > function.numCoefficients())
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(function.numCoefficients()),
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
      } else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
    } else {
      ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                      name,
                      new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
    }
    return ret;
  } // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const

}; // class ModelInterface

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#include "default.hh"

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH
<commit_msg>[linearelliptic.model.interface] added possibility for matrix-valued diffusion<commit_after>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH

// we still need this for the vtk writer
#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif

#include <vector>

#include <dune/grid/io/file/vtk/vtkwriter.hh>

#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>
#include <dune/stuff/function/fixed.hh>

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

// forward of the nonparametric default
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, bool scalarDiffusion >
class ModelDefault;

// forward to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, bool scalarDiffusion = true >
class ModelInterface
{
public:
  ModelInterface() = delete;
};

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class ModelInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, true >
{
public:
  typedef ModelInterface< DomainFieldImp, domainDim, RangeFieldImp, 1, true > ThisType;

  typedef DomainFieldImp  DomainFieldType;
  static const int        dimDomain = domainDim;

  typedef RangeFieldImp   RangeFieldType;
  static const int        dimRange = 1;

  typedef typename Stuff::Common::Parameter::FieldType  ParamFieldType;
  static const int                                      maxParamDim = Stuff::Common::Parameter::maxDim;
  typedef typename Stuff::Common::Parameter::Type       ParamType;

  typedef Dune::Stuff::GenericStationaryFunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > DiffusionType;
  typedef Dune::Stuff::GenericStationaryFunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > ForceType;
  typedef Dune::Stuff::GenericStationaryFunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > DirichletType;
  typedef Dune::Stuff::GenericStationaryFunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > NeumannType;

  static const std::string id()
  {
    return "model.linearelliptic";
  }

  /** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
  /* @{ */
  virtual bool parametric() const
  {
    if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
      return true;
    else
      return false;
  }

  virtual bool affineparametric() const
  {
    if (parametric()) {
      if (diffusion()->parametric() && !diffusion()->affineparametric())
        return false;
      if (force()->parametric() && !force()->affineparametric())
        return false;
      if (dirichlet()->parametric() && !dirichlet()->affineparametric())
        return false;
      if (neumann()->parametric() && !neumann()->affineparametric())
        return false;
      return true;
    } else
      return false;
  } // ... affineparametric()
  /* @} */

  /** \defgroup purevirtual ´´These methods have to be implemented.'' */
  /* @{ */
  virtual std::shared_ptr< const DiffusionType > diffusion() const = 0;

  virtual std::shared_ptr< const ForceType > force() const = 0;

  virtual std::shared_ptr< const DirichletType > dirichlet() const = 0;

  virtual std::shared_ptr< const NeumannType > neumann() const = 0;
  /* @} */

  /** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
  /* @{ */
  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  /**
   * \brief     Maps a global to a local parameter.
   * \param[in] ParamType _globalMu
   *            global parameter
   * \param[in] std::string _id
   *            To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
   *            force, dirichlet or neumann
   * \return    ParamType
   *            local parameter
   */
  virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
  {
    if (!parametric())
      return ParamType();
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }
  /* @} */

  virtual std::shared_ptr< const ThisType > fix(const ParamType& mu) const
  {
    if (!parametric() && mu.size() != 0)
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " do not call fix(mu) with a nonempty mu for a nonparametric model (check parametric() == true beforehand)!");
    typedef Dune::Stuff::FunctionFixed< DomainFieldType, dimDomain, RangeFieldType, dimRange > FixedFunctionType;
    typedef ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange > DefaultModelType;
    return std::make_shared< DefaultModelType >(diffusion()->parametric() ? std::make_shared< const FixedFunctionType >(diffusion(), mapParam(mu, "diffusion")) : diffusion(),
                                                force()->parametric() ? std::make_shared< const FixedFunctionType >(force(), mapParam(mu, "force")) : force(),
                                                dirichlet()->parametric() ? std::make_shared< const FixedFunctionType >(dirichlet(), mapParam(mu, "dirichlet")) : dirichlet(),
                                                neumann()->parametric() ? std::make_shared< const FixedFunctionType >(neumann(), mapParam(mu, "neumann")) : neumann());
  }

  template< class GridViewType >
  void visualize(const GridViewType& gridView, std::string filename) const
  {
    // prepare data
    Dune::VTKWriter< GridViewType > vtkWriter(gridView);
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
        = preparePlot(gridView, *(diffusion()), "diffusion");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
        = preparePlot(gridView, *(force()), "force");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
        = preparePlot(gridView, *(dirichlet()), "dirichlet");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
        = preparePlot(gridView, *(neumann()), "neumann");
    // walk the grid view
    for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
         it != gridView.template end< 0 >();
         ++it) {
      const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
      const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
      const typename FunctionType::DomainType center = entity.geometry().center();
      // do a piecewise constant projection of the data functions
      //   * diffusion
      if (diffusion()->parametric() && diffusion()->affineparametric())
        for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
          diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
      else if (!diffusion()->parametric())
        diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * force
      if (force()->parametric() && force()->affineparametric())
        for (size_t qq = 0; qq < force()->numComponents(); ++qq)
          forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
      else if (!force()->parametric())
        forcePlots[0].second->operator[](index) = force()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * dirichlet
      if (dirichlet()->parametric() && dirichlet()->affineparametric())
        for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
          dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
      else if (!dirichlet()->parametric())
        dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
      //   * neumann
      if (neumann()->parametric() && neumann()->affineparametric())
        for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
          neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
      else if (!neumann()->parametric())
        neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
    } // walk the grid view
    // write
    //   * diffusion
    for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
      vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
    //   * force
    for (size_t qq = 0; qq < forcePlots.size(); ++qq)
      vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
    //   * dirichlet
    for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
      vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
    //   * neumann
    for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
      vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
    vtkWriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const GridViewType& gridView, std::string filename) const

private:
  template< class GridViewType, class FunctionType >
  std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
                                                                                const FunctionType& function,
                                                                                const std::string name) const
  {
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
    if (function.parametric()) {
      if (function.affineparametric()) {
        const std::vector< std::string >& paramExplanations = function.paramExplanation();
        for (size_t qq = 0; qq < function.numCoefficients(); ++qq)
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
        if (function.numComponents() > function.numCoefficients())
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(function.numCoefficients()),
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
      } else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not affineparametric data functions!");
    } else {
      ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                      name,
                      new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
    }
    return ret;
  } // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const

}; // class ModelInterface

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#include "default.hh"

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_INTERFACE_HH
<|endoftext|>