<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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 "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>

template<typename LineType> void parametrizedline(const LineType& _line)
{
  /* this test covers the following files:
     ParametrizedLine.h
  */
  using std::abs;
  typedef typename LineType::Index Index;
  const Index dim = _line.dim();
  typedef typename LineType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar, LineType::AmbientDimAtCompileTime, 1> VectorType;
  typedef Hyperplane<Scalar,LineType::AmbientDimAtCompileTime> HyperplaneType;

  VectorType p0 = VectorType::Random(dim);
  VectorType p1 = VectorType::Random(dim);

  VectorType d0 = VectorType::Random(dim).normalized();

  LineType l0(p0, d0);

  Scalar s0 = internal::random<Scalar>();
  Scalar s1 = abs(internal::random<Scalar>());

  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0), RealScalar(1) );
  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0+s0*d0), RealScalar(1) );
  VERIFY_IS_APPROX( (l0.projection(p1)-p1).norm(), l0.distance(p1) );
  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(l0.projection(p1)), RealScalar(1) );
  VERIFY_IS_APPROX( Scalar(l0.distance((p0+s0*d0) + d0.unitOrthogonal() * s1)), s1 );

  // casting
  const int Dim = LineType::AmbientDimAtCompileTime;
  typedef typename GetDifferentType<Scalar>::type OtherScalar;
  ParametrizedLine<OtherScalar,Dim> hp1f = l0.template cast<OtherScalar>();
  VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),l0);
  ParametrizedLine<Scalar,Dim> hp1d = l0.template cast<Scalar>();
  VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),l0);

  // intersections
  VectorType p2 = VectorType::Random(dim);
  VectorType n2 = VectorType::Random(dim).normalized();
  HyperplaneType hp(p2,n2);
  Scalar t = l0.intersectionParameter(hp);
  VectorType pi = l0.pointAt(t);
  VERIFY_IS_MUCH_SMALLER_THAN(hp.signedDistance(pi), RealScalar(1));
  VERIFY_IS_MUCH_SMALLER_THAN(l0.distance(pi), RealScalar(1));
  VERIFY_IS_APPROX(l0.intersectionPoint(hp), pi);
}

template<typename Scalar> void parametrizedline_alignment()
{
  typedef ParametrizedLine<Scalar,4,AutoAlign> Line4a;
  typedef ParametrizedLine<Scalar,4,DontAlign> Line4u;

  EIGEN_ALIGN_DEFAULT Scalar array1[8];
  EIGEN_ALIGN_DEFAULT Scalar array2[8];
  EIGEN_ALIGN_DEFAULT Scalar array3[8+1];
  Scalar* array3u = array3+1;

  Line4a *p1 = ::new(reinterpret_cast<void*>(array1)) Line4a;
  Line4u *p2 = ::new(reinterpret_cast<void*>(array2)) Line4u;
  Line4u *p3 = ::new(reinterpret_cast<void*>(array3u)) Line4u;

  p1->origin().setRandom();
  p1->direction().setRandom();
  *p2 = *p1;
  *p3 = *p1;

  VERIFY_IS_APPROX(p1->origin(), p2->origin());
  VERIFY_IS_APPROX(p1->origin(), p3->origin());
  VERIFY_IS_APPROX(p1->direction(), p2->direction());
  VERIFY_IS_APPROX(p1->direction(), p3->direction());

  #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY
  if(internal::packet_traits<Scalar>::Vectorizable && internal::packet_traits<Scalar>::size<=4)
    VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Line4a));
  #endif
}

void test_geo_parametrizedline()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( parametrizedline(ParametrizedLine<float,2>()) );
    CALL_SUBTEST_2( parametrizedline(ParametrizedLine<float,3>()) );
    CALL_SUBTEST_2( parametrizedline_alignment<float>() );
    CALL_SUBTEST_3( parametrizedline(ParametrizedLine<double,4>()) );
    CALL_SUBTEST_3( parametrizedline_alignment<double>() );
    CALL_SUBTEST_4( parametrizedline(ParametrizedLine<std::complex<double>,5>()) );
  }
}
<commit_msg>Updated the geo_parametrizedline_2 test for AVX.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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 "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>

template<typename LineType> void parametrizedline(const LineType& _line)
{
  /* this test covers the following files:
     ParametrizedLine.h
  */
  using std::abs;
  typedef typename LineType::Index Index;
  const Index dim = _line.dim();
  typedef typename LineType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar, LineType::AmbientDimAtCompileTime, 1> VectorType;
  typedef Hyperplane<Scalar,LineType::AmbientDimAtCompileTime> HyperplaneType;

  VectorType p0 = VectorType::Random(dim);
  VectorType p1 = VectorType::Random(dim);

  VectorType d0 = VectorType::Random(dim).normalized();

  LineType l0(p0, d0);

  Scalar s0 = internal::random<Scalar>();
  Scalar s1 = abs(internal::random<Scalar>());

  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0), RealScalar(1) );
  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0+s0*d0), RealScalar(1) );
  VERIFY_IS_APPROX( (l0.projection(p1)-p1).norm(), l0.distance(p1) );
  VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(l0.projection(p1)), RealScalar(1) );
  VERIFY_IS_APPROX( Scalar(l0.distance((p0+s0*d0) + d0.unitOrthogonal() * s1)), s1 );

  // casting
  const int Dim = LineType::AmbientDimAtCompileTime;
  typedef typename GetDifferentType<Scalar>::type OtherScalar;
  ParametrizedLine<OtherScalar,Dim> hp1f = l0.template cast<OtherScalar>();
  VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),l0);
  ParametrizedLine<Scalar,Dim> hp1d = l0.template cast<Scalar>();
  VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),l0);

  // intersections
  VectorType p2 = VectorType::Random(dim);
  VectorType n2 = VectorType::Random(dim).normalized();
  HyperplaneType hp(p2,n2);
  Scalar t = l0.intersectionParameter(hp);
  VectorType pi = l0.pointAt(t);
  VERIFY_IS_MUCH_SMALLER_THAN(hp.signedDistance(pi), RealScalar(1));
  VERIFY_IS_MUCH_SMALLER_THAN(l0.distance(pi), RealScalar(1));
  VERIFY_IS_APPROX(l0.intersectionPoint(hp), pi);
}

template<typename Scalar> void parametrizedline_alignment()
{
  typedef ParametrizedLine<Scalar,4,AutoAlign> Line4a;
  typedef ParametrizedLine<Scalar,4,DontAlign> Line4u;

  EIGEN_ALIGN_DEFAULT Scalar array1[16];
  EIGEN_ALIGN_DEFAULT Scalar array2[16];
  EIGEN_ALIGN_DEFAULT Scalar array3[16+1];
  Scalar* array3u = array3+1;

  Line4a *p1 = ::new(reinterpret_cast<void*>(array1)) Line4a;
  Line4u *p2 = ::new(reinterpret_cast<void*>(array2)) Line4u;
  Line4u *p3 = ::new(reinterpret_cast<void*>(array3u)) Line4u;

  p1->origin().setRandom();
  p1->direction().setRandom();
  *p2 = *p1;
  *p3 = *p1;

  VERIFY_IS_APPROX(p1->origin(), p2->origin());
  VERIFY_IS_APPROX(p1->origin(), p3->origin());
  VERIFY_IS_APPROX(p1->direction(), p2->direction());
  VERIFY_IS_APPROX(p1->direction(), p3->direction());

  #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY
  if(internal::packet_traits<Scalar>::Vectorizable && internal::packet_traits<Scalar>::size<=4)
    VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Line4a));
  #endif
}

void test_geo_parametrizedline()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( parametrizedline(ParametrizedLine<float,2>()) );
    CALL_SUBTEST_2( parametrizedline(ParametrizedLine<float,3>()) );
    CALL_SUBTEST_2( parametrizedline_alignment<float>() );
    CALL_SUBTEST_3( parametrizedline(ParametrizedLine<double,4>()) );
    CALL_SUBTEST_3( parametrizedline_alignment<double>() );
    CALL_SUBTEST_4( parametrizedline(ParametrizedLine<std::complex<double>,5>()) );
  }
}
<|endoftext|>


<commit_before>#include "TableLogger.h"
#include <boost/foreach.hpp>

TableLogger::TableLogger()
  :header_space_(' ', 3)
{}

TableLogger::TableLogger(const std::vector<HeaderStyle> &header)
  :header_(header), header_space_(' ', 3)
{}

void TableLogger::LogTableHead()
{
  using std::cout;
  cout << "Sphere Ellimination Records" << "\n";
  cout << "==========================" << "\n";
  cout << "Index   Color   Time (s)   Event type" << "\n";
  cout << "-----   -----   --------   ----------" << "\n";
}

void TableLogger::LogTableRow(std::vector<std::string> data)
{
  static const unsigned int kIndexHeaderWidth = 5;

  using std::cout;
  BOOST_FOREACH(const std::string& s, data) {
    cout << center(s, kIndexHeaderWidth);
    cout << header_space_;
    cout << "\n";
  }
}

std::string TableLogger::center(const std::string &s, std::string::size_type length)
{
  if(s.length() > length)
    return s.substr(0, length);

  std::string result(length, ' ');
  int spaces = (length - s.length()) / 2;

  for(unsigned int i = 0; i < s.length(); ++i)
    result[i+spaces] = s[i];
  return result;
}
<commit_msg>Implemented LogTableHeader<commit_after>#include "TableLogger.h"
#include <boost/foreach.hpp>

TableLogger::TableLogger(
  const std::string& title, const std::vector<HeaderStyle> &header)
  :title_(title), header_(header), header_space_(3, ' ')
{}

void TableLogger::LogTableHead()
{
  using std::cout;

  cout << title_ << "\n";

  BOOST_FOREACH(const HeaderStyle& h, header_) {
    cout << h.first << header_space_;
  }
  cout << "\n";
}

void TableLogger::LogTableRow(std::vector<std::string> data)
{
  static const unsigned int kIndexHeaderWidth = 5;

  using std::cout;
  BOOST_FOREACH(const std::string& s, data) {
    cout << center(s, 8);
    cout << header_space_;
  }
  cout << "\n";
}

std::string TableLogger::center(const std::string &s, std::string::size_type length)
{
  if(s.length() > length)
    return s.substr(0, length);

  std::string result(length, ' ');
  int spaces = (length - s.length()) / 2;

  for(unsigned int i = 0; i < s.length(); ++i)
    result[i+spaces] = s[i];
  return result;
}
<|endoftext|>


<commit_before>// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Base class for a vehicle wheel.
// A wheel subsystem does not own a body. Instead, when attached to a suspension
// subsystem, the wheel's mass properties are used to update those of the
// spindle body owned by the suspension.
// A concrete wheel subsystem can optionally carry its own visualization assets
// and/or contact geometry (which are associated with the suspension's spindle
// body).
// =============================================================================

namespace chrono {

}  // end namespace chrono
<commit_msg>Add missing comment block at top of file.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Base class for a vehicle wheel.
// A wheel subsystem does not own a body. Instead, when attached to a suspension
// subsystem, the wheel's mass properties are used to update those of the
// spindle body owned by the suspension.
// A concrete wheel subsystem can optionally carry its own visualization assets
// and/or contact geometry (which are associated with the suspension's spindle
// body).
// =============================================================================

namespace chrono {

}  // end namespace chrono
<|endoftext|>


<commit_before>#ifndef CPPUT_TESTHARNESS_HPP
#define CPPUT_TESTHARNESS_HPP

///////////////////////////////////////////////////////////////////////////////
///
/// \brief    A light-weight and easy to use unit testing framework for C++
/// \details  Header-only unit testing framework that makes unit testing easy
///           and quick to set up.
/// \version  0.2.0
/// \date     December 2011
/// \author   Tommy Back
///
///
/// Simply include this header file to get started.
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, some_descriptive_name)
/// {
///   // Arrange
///   Foo foo;
///   // Act
///   bool result = foo.isBar();
///   // Assert
///   ASSERT_TRUE(result);
/// }
/// \endcode
///
/// In case you want to keep a single file with tests that compile to an
/// executable you can also add the main function to the end of the file.
/// This is simple to do with the provided macro:
///
/// \code
/// CPPUT_TEST_MAIN;
/// \endcode
///
/// For larger test suits, it's recommended to group the tests per class
/// in separate files and let the compiler combine them into a single
/// executable which has a main.cpp file that only has the main function
/// declared.
///
/// \example
/// [Test_Foo.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, foo_bar_z)
/// {
///   ...
/// \endcode
///
/// [main.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
///
/// CPPUT_TEST_MAIN;
/// \endcode
///
///

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>
#include <ctime>

namespace cpput
{

struct Failure
{
  Failure(const std::string& filename, std::size_t line, const std::string& message)
    : filename_(filename)
    , line_(line)
    , message_(message)
  {
  }

  friend std::ostream& operator<<(std::ostream& os, const Failure& f)
  {
    os << f.filename_ << ", line " << f.line_ << ": " << f.message_;
    return os;
  }

  std::string filename_;
  std::size_t line_;
  std::string message_;
};

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

struct ResultWriter
{
  virtual ~ResultWriter() {}

  virtual void startTest(const std::string& className, const std::string& name) = 0;
  virtual void endTest(bool success) = 0;

  virtual void failure(const Failure& failure) = 0;
  virtual int getNumberOfFailures() const = 0;
};

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

class TextResultWriter : public ResultWriter
{
public:
  TextResultWriter()
    : testCount_(0)
  {
  }

  virtual ~TextResultWriter()
  {
    std::cout << "\n";
    if (failures_.empty())
    {
      std::cout << "All tests pass.\n";
      return;
    }
    // print details of all failures
    std::cout << "\n";
    for (std::size_t i=0; i<failures_.size(); ++i)
    {
      std::cout << failures_[i] << "\n";
    }
    std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n";
  }

  virtual void startTest(const std::string&, const std::string&)
  {
    testCount_++;
  }

  virtual void endTest(bool success)
  {
    if (success)
      std::cout << '.';
    else
      std::cout << 'F';
  }

  virtual void failure(const Failure& failure)
  {
    failures_.push_back(failure);
  }

  virtual int getNumberOfFailures() const { return failures_.size(); }

private:
  int                  testCount_;
  std::vector<Failure> failures_;
};

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

class XmlResultWriter : public ResultWriter
{
public:
  XmlResultWriter()
    : startTime_(0)
  {
    std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    std::cout << "<testsuite>\n";
  }

  virtual ~XmlResultWriter()
  {
    std::cout << "</testsuite>\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    startTime_ = std::clock();
    std::cout << "  <testcase classname=\""
              << className
              << "\" name=\""
              << name
              << "\" time=\"";
  }

  virtual void endTest(bool success)
  {
    if (success)
    {
      std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
      std::cout << "/>\n";
    }
    else
      std::cout << "  </testcase>\n";
  }

  virtual void failure(const Failure& failure)
  {
    std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
    std::cout << ">\n"
              << "    <failure>"
              << failure.message_
              << " in "
              << failure.filename_
              << ", line "
              << failure.line_
              << "</failure>\n";
    failureCount_++;
  }

  virtual int getNumberOfFailures() const
  {
    return failureCount_;
  }

private:
  std::clock_t startTime_;
  int          failureCount_;
};

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

struct Result
{
  Result(const std::string& testClassName,
         const std::string& testName,
         ResultWriter& out)
    : out_(out)
    , pass_(true)
  {
    out_.startTest(testClassName, testName);
  }

  ~Result()
  {
    out_.endTest(pass_);
  }

  template <typename T, typename U>
  void addFailure(const char* filename,
                  std::size_t line,
                  T expected,
                  U actual)
  {
    pass_ = false;
    std::stringstream ss;
    ss << std::setprecision(20)
       << "failed comparison, expected " << expected
       << " got " << actual << "\n";
    Failure f(filename, line, ss.str());
    out_.failure(f);
  }

  void addFailure(const char* filename,
                  std::size_t line,
                  const char* message)
  {
    pass_ = false;
    Failure f(filename, line, message);
    out_.failure(f);
  }

  ResultWriter& out_;
  bool        pass_;
};

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

class Repository;

class Case
{
  friend class Repository;

public:
  Case(const char* className, const char* name);
  virtual ~Case() {}

  void run(ResultWriter& out)
  {
    Result result(test_unit_class_name_, test_unit_name_, out);
    try
    {
      do_run(result);
    }
    catch (const std::exception& e)
    {
      result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str());
    }
    catch (...)
    {
      result.addFailure(__FILE__, __LINE__, "Unspecified exception!");
    }
  }

  Case* next() { return test_unit_next_; }

private:
  virtual void do_run(Result& testResult_) = 0;

private:
  std::string test_unit_class_name_;
  std::string test_unit_name_;
  Case*       test_unit_next_;
};

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

class Repository
{
public:
  static Repository& instance()
  {
    static Repository repo;
    return repo;
  }

  void add(Case* tc)
  {
    if (!cases_)
    {
      cases_ = tc;
      return;
    }

    // add as last
    Case* tmp = cases_;
    while (tmp->test_unit_next_)
      tmp = tmp->test_unit_next_;
    tmp->test_unit_next_ = tc;
  }

  Case* getCases() { return cases_; }

private:
  Repository() : cases_(0) {}
  Repository(const Repository& other);
  Repository& operator=(const Repository& rhs) const;

private:
  Case* cases_;
};

inline Case::Case(const char* className, const char* name)
  : test_unit_class_name_(className)
  , test_unit_name_(name)
  , test_unit_next_(0)
{
  Repository::instance().add(this);
}

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

struct Runner
{
  static int run(ResultWriter& writer)
  {
    Case* c = Repository::instance().getCases();
    while (c)
    {
      c->run(writer);
      c = c->next();
    }
    return writer.getNumberOfFailures();
  }

private:
  Runner();
  Runner(const Runner& other);
  Runner& operator=(const Runner& rhs) const;
};

} // namespace cpput

// Convenience macro to get main function.
#define CPPUT_TEST_MAIN                               \
int main(int argc, char* argv[]) {                    \
  if (argc == 2 && std::string(argv[1]) == "--xml") { \
    cpput::XmlResultWriter writer;                    \
    return ::cpput::Runner::run(writer);              \
  }                                                   \
  cpput::TextResultWriter writer;                     \
  return ::cpput::Runner::run(writer);                \
}

// ----------------------------------------------------------------------------
// Test Case Macros
// ----------------------------------------------------------------------------

/// Stand-alone test case.
///
#define TEST(group,name) \
class group##name##Test : public cpput::Case \
{ \
public: \
  group##name##Test() : cpput::Case(#group,#name) {} \
  virtual ~group##name##Test() {} \
private: \
  virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_)

/// Test case with fixture.
///
#define TEST_F(group,name) \
class group##name##FixtureTest : public group { \
public: \
    void do_run(cpput::Result& testResult_); \
}; \
class group##name##Test : public cpput::Case { \
public: \
    group##name##Test() : Case(#group,#name) {} \
    virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_) { \
  group##name##FixtureTest test; \
  test.do_run(testResult_); \
} \
inline void group##name##FixtureTest::do_run(cpput::Result& testResult_)

// ----------------------------------------------------------------------------
// Assertion Macros
// ----------------------------------------------------------------------------

#define ASSERT_TRUE(expression) \
{ \
  if (expression) \
    return; \
  testResult_.addFailure(__FILE__, __LINE__, #expression); \
}

#define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression))

#define ASSERT_EQ(expected,actual) \
{ \
  if (!((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEQ(expected,actual) \
{ \
  if (((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_STREQ(expected,actual) { \
  if (!(std::string(expected) == std::string(actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEAR(expected,actual,epsilon) \
{ \
  double actualTmp = actual; \
  double expectedTmp = expected; \
  double diff = expectedTmp - actualTmp; \
  if ((diff > epsilon) || (-diff > epsilon)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \
    return; \
  } \
}

#endif // CPPUT_TESTHARNESS_HPP
<commit_msg>Replaced Runner class with non-member inline function.<commit_after>#ifndef CPPUT_TESTHARNESS_HPP
#define CPPUT_TESTHARNESS_HPP

///////////////////////////////////////////////////////////////////////////////
///
/// \brief    A light-weight and easy to use unit testing framework for C++
/// \details  Header-only unit testing framework that makes unit testing easy
///           and quick to set up.
/// \version  0.2.0
/// \date     December 2011
/// \author   Tommy Back
///
///
/// Simply include this header file to get started.
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, some_descriptive_name)
/// {
///   // Arrange
///   Foo foo;
///   // Act
///   bool result = foo.isBar();
///   // Assert
///   ASSERT_TRUE(result);
/// }
/// \endcode
///
/// In case you want to keep a single file with tests that compile to an
/// executable you can also add the main function to the end of the file.
/// This is simple to do with the provided macro:
///
/// \code
/// CPPUT_TEST_MAIN;
/// \endcode
///
/// For larger test suits, it's recommended to group the tests per class
/// in separate files and let the compiler combine them into a single
/// executable which has a main.cpp file that only has the main function
/// declared.
///
/// \example
/// [Test_Foo.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, foo_bar_z)
/// {
///   ...
/// \endcode
///
/// [main.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
///
/// CPPUT_TEST_MAIN;
/// \endcode
///
///

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>
#include <ctime>

namespace cpput
{

struct Failure
{
  Failure(const std::string& filename, std::size_t line, const std::string& message)
    : filename_(filename)
    , line_(line)
    , message_(message)
  {
  }

  friend std::ostream& operator<<(std::ostream& os, const Failure& f)
  {
    os << f.filename_ << ", line " << f.line_ << ": " << f.message_;
    return os;
  }

  std::string filename_;
  std::size_t line_;
  std::string message_;
};

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

struct ResultWriter
{
  virtual ~ResultWriter() {}

  virtual void startTest(const std::string& className, const std::string& name) = 0;
  virtual void endTest(bool success) = 0;

  virtual void failure(const Failure& failure) = 0;
  virtual int getNumberOfFailures() const = 0;
};

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

class TextResultWriter : public ResultWriter
{
public:
  TextResultWriter()
    : testCount_(0)
  {
  }

  virtual ~TextResultWriter()
  {
    std::cout << "\n";
    if (failures_.empty())
    {
      std::cout << "All tests pass.\n";
      return;
    }
    // print details of all failures
    std::cout << "\n";
    for (std::size_t i=0; i<failures_.size(); ++i)
    {
      std::cout << failures_[i] << "\n";
    }
    std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n";
  }

  virtual void startTest(const std::string&, const std::string&)
  {
    testCount_++;
  }

  virtual void endTest(bool success)
  {
    if (success)
      std::cout << '.';
    else
      std::cout << 'F';
  }

  virtual void failure(const Failure& failure)
  {
    failures_.push_back(failure);
  }

  virtual int getNumberOfFailures() const { return failures_.size(); }

private:
  int                  testCount_;
  std::vector<Failure> failures_;
};

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

class XmlResultWriter : public ResultWriter
{
public:
  XmlResultWriter()
    : startTime_(0)
  {
    std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    std::cout << "<testsuite>\n";
  }

  virtual ~XmlResultWriter()
  {
    std::cout << "</testsuite>\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    startTime_ = std::clock();
    std::cout << "  <testcase classname=\""
              << className
              << "\" name=\""
              << name
              << "\" time=\"";
  }

  virtual void endTest(bool success)
  {
    if (success)
    {
      std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
      std::cout << "/>\n";
    }
    else
      std::cout << "  </testcase>\n";
  }

  virtual void failure(const Failure& failure)
  {
    std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
    std::cout << ">\n"
              << "    <failure>"
              << failure.message_
              << " in "
              << failure.filename_
              << ", line "
              << failure.line_
              << "</failure>\n";
    failureCount_++;
  }

  virtual int getNumberOfFailures() const
  {
    return failureCount_;
  }

private:
  std::clock_t startTime_;
  int          failureCount_;
};

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

struct Result
{
  Result(const std::string& testClassName,
         const std::string& testName,
         ResultWriter& out)
    : out_(out)
    , pass_(true)
  {
    out_.startTest(testClassName, testName);
  }

  ~Result()
  {
    out_.endTest(pass_);
  }

  template <typename T, typename U>
  void addFailure(const char* filename,
                  std::size_t line,
                  T expected,
                  U actual)
  {
    pass_ = false;
    std::stringstream ss;
    ss << std::setprecision(20)
       << "failed comparison, expected " << expected
       << " got " << actual << "\n";
    Failure f(filename, line, ss.str());
    out_.failure(f);
  }

  void addFailure(const char* filename,
                  std::size_t line,
                  const char* message)
  {
    pass_ = false;
    Failure f(filename, line, message);
    out_.failure(f);
  }

  ResultWriter& out_;
  bool        pass_;
};

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

class Repository;

class Case
{
  friend class Repository;

public:
  Case(const char* className, const char* name);
  virtual ~Case() {}

  void run(ResultWriter& out)
  {
    Result result(test_unit_class_name_, test_unit_name_, out);
    try
    {
      do_run(result);
    }
    catch (const std::exception& e)
    {
      result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str());
    }
    catch (...)
    {
      result.addFailure(__FILE__, __LINE__, "Unspecified exception!");
    }
  }

  Case* next() { return test_unit_next_; }

private:
  virtual void do_run(Result& testResult_) = 0;

private:
  std::string test_unit_class_name_;
  std::string test_unit_name_;
  Case*       test_unit_next_;
};

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

class Repository
{
public:
  static Repository& instance()
  {
    static Repository repo;
    return repo;
  }

  void add(Case* tc)
  {
    if (!cases_)
    {
      cases_ = tc;
      return;
    }

    // add as last
    Case* tmp = cases_;
    while (tmp->test_unit_next_)
      tmp = tmp->test_unit_next_;
    tmp->test_unit_next_ = tc;
  }

  Case* getCases() { return cases_; }

private:
  Repository() : cases_(0) {}
  Repository(const Repository& other);
  Repository& operator=(const Repository& rhs) const;

private:
  Case* cases_;
};

inline Case::Case(const char* className, const char* name)
  : test_unit_class_name_(className)
  , test_unit_name_(name)
  , test_unit_next_(0)
{
  Repository::instance().add(this);
}

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

inline int runAllTests(ResultWriter& writer)
{
  Case* c = Repository::instance().getCases();
  while (c)
  {
    c->run(writer);
    c = c->next();
  }
  return writer.getNumberOfFailures();
}

} // namespace cpput

// Convenience macro to get main function.
#define CPPUT_TEST_MAIN                               \
int main(int argc, char* argv[]) {                    \
  if (argc == 2 && std::string(argv[1]) == "--xml") { \
    cpput::XmlResultWriter writer;                    \
    return ::cpput::runAllTests(writer);              \
  }                                                   \
  cpput::TextResultWriter writer;                     \
  return ::cpput::runAllTests(writer);                \
}

// ----------------------------------------------------------------------------
// Test Case Macros
// ----------------------------------------------------------------------------

/// Stand-alone test case.
///
#define TEST(group,name) \
class group##name##Test : public cpput::Case \
{ \
public: \
  group##name##Test() : cpput::Case(#group,#name) {} \
  virtual ~group##name##Test() {} \
private: \
  virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_)

/// Test case with fixture.
///
#define TEST_F(group,name) \
class group##name##FixtureTest : public group { \
public: \
    void do_run(cpput::Result& testResult_); \
}; \
class group##name##Test : public cpput::Case { \
public: \
    group##name##Test() : Case(#group,#name) {} \
    virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_) { \
  group##name##FixtureTest test; \
  test.do_run(testResult_); \
} \
inline void group##name##FixtureTest::do_run(cpput::Result& testResult_)

// ----------------------------------------------------------------------------
// Assertion Macros
// ----------------------------------------------------------------------------

#define ASSERT_TRUE(expression) \
{ \
  if (expression) \
    return; \
  testResult_.addFailure(__FILE__, __LINE__, #expression); \
}

#define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression))

#define ASSERT_EQ(expected,actual) \
{ \
  if (!((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEQ(expected,actual) \
{ \
  if (((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_STREQ(expected,actual) { \
  if (!(std::string(expected) == std::string(actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEAR(expected,actual,epsilon) \
{ \
  double actualTmp = actual; \
  double expectedTmp = expected; \
  double diff = expectedTmp - actualTmp; \
  if ((diff > epsilon) || (-diff > epsilon)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \
    return; \
  } \
}

#endif // CPPUT_TESTHARNESS_HPP
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH

#include <algorithm>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/common/exceptions.hh>

#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/gdt/playground/products/elliptic.hh>

#include <dune/hdd/linearelliptic/discretizations/swipdg.hh>
#include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>
#include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh>

#include "linearelliptic.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Tests {
namespace internal {

template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
class DiscretizationSWIPDG
{
  typedef typename TestCaseType::GridType GridType;
  typedef typename TestCaseType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange = TestCaseType::dimRange;
public:
  typedef Discretizations::SWIPDG
      < GridType, Stuff::Grid::ChooseLayer::level, RangeFieldType, dimRange, polOrder, space_backend, la_backend > Type;
}; // class DiscretizationSWIPDG

} // namespace internal

template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
class EocStudySWIPDG
  : public EocStudyBase< TestCaseType,
                         typename internal::DiscretizationSWIPDG< TestCaseType,
                                                                  polOrder,
                                                                  space_backend,
                                                                  la_backend >::Type >
{
  typedef EocStudyBase< TestCaseType,
                        typename internal::DiscretizationSWIPDG< TestCaseType,
                                                                 polOrder,
                                                                 space_backend,
                                                                 la_backend >::Type > BaseType;
  typedef EocStudySWIPDG< TestCaseType, polOrder, space_backend, la_backend > ThisType;

  typedef typename BaseType::DiscretizationType DiscretizationType;
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::FunctionType FunctionType;
  typedef typename BaseType::VectorType   VectorType;

public:
  EocStudySWIPDG(const TestCaseType& test_case, const std::vector< std::string > only_these_norms = {})
    : BaseType(test_case, only_these_norms)
  {}

  virtual ~EocStudySWIPDG() {}

  virtual std::string identifier() const DS_OVERRIDE DS_FINAL
  {
    return DiscretizationType::static_id() + " (polorder " + Stuff::Common::toString(polOrder) + ")";
  }

  virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "L2")
      return polOrder + 1;
    else if (type == "H1_semi")
      return polOrder;
    else if (type == "energy")
      return polOrder;
    else if (type == "eta_NC_ESV2007")
      return polOrder;
    else if (type == "eta_R_ESV2007")
      return polOrder + 1;
    else if (type == "eta_DF_ESV2007")
      return polOrder;
    else if (type == "eta_ESV2007")
      return polOrder;
    else if (type == "eff_ESV2007")
      return 0;
    else if (type == "eta_ESV2007_alt")
      return polOrder;
    else if (type == "eff_ESV2007_alt")
      return 0;
    else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... expected_rate(...)

  virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL
  {
#if HAVE_ALUGRID
    if (std::is_same< TestCaseType, TestCases::ESV2007< ALUConformGrid< 2, 2 > > >::value
        || std::is_same< TestCaseType, TestCases::ESV2007< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (polOrder == 1) {
        if (type == "L2")
          return {1.84e-02, 4.54e-03, 1.13e-03, 2.79e-04};
        else if (type == "H1_semi")
          return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
        else if (type == "energy")
          return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
        else if (type == "eta_NC_ESV2007")
          return {1.90e-1, 9.73e-2, 4.90e-2, 2.46e-2};
        else if (type == "eta_R_ESV2007")
          return {7.24e-2, 1.83e-2, 4.55e-3, 1.15e-3};
        else if (type == "eta_DF_ESV2007") {
          // these are the values reported in the ESV2007 preprint:
//          return {3.39e-1, 1.70e-1, 8.40e-2, 4.19e-2};
          // but we do not want the test to fail each time, so we expect these:
          return {3.56e-1, 1.77e-1, 8.74e-2, 4.36e-2};
        } else if (type == "eta_ESV2007")
          return {4.50e-01, 2.08e-01,  9.92e-02, 4.86e-02};
        else if (type == "eff_ESV2007") {
          // these are the values reported in the ESV2007 preprint:
//          return {1.21, 1.21, 1.21, 1.21};
          // but we do not want the test to fail each time, so we expect these:
          return {1.38, 1.29, 1.24, 1.22};
        } else if (type == "eta_ESV2007_alt")
          return {5.94e-01, 2.74e-01, 1.32e-01, 6.43e-02};
        else if (type == "eff_ESV2007_alt")
          return {1.82, 1.70, 1.64, 1.61};
        else
          DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
      } else
        DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!");
    } else if (std::is_same< TestCaseType, TestCases::OS2014< ALUConformGrid< 2, 2 > > >::value
               || std::is_same< TestCaseType, TestCases::OS2014< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (polOrder == 1) {
        if (type == "energy")
          return {4.75e-01, 2.63e-01, 1.28e-01, 5.62e-02};
        else if (type == "eta_NC")
          return {2.39e-01, 1.43e-01, 6.83e-02, 3.14e-02};
        else if (type == "eta_R")
          return {8.19e-02, 1.99e-02, 4.84e-03, 1.20e-03};
        else if (type == "eta_DF") {
          return {6.35e-01, 3.62e-01, 1.88e-01, 9.18e-02};
        } else if (type == "eta")
          return {7.51e-01, 4.06e-01, 2.01e-01, 9.80e-02};
        else
          DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
      } else
        DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!");
    } else
#endif // HAVE_ALUGRID
      DUNE_THROW(NotImplemented, "Please record the expected results for this TestCaseType/GridType combination!");
  } // ... expected_results(...)

private:
  virtual std::vector< std::string > available_norms_() const DS_OVERRIDE DS_FINAL
  {
    return {
        "L2"
      , "H1_semi"
      , "energy"
    };
  } // ... available_norms_(...)

  virtual double compute_norm_(const GridViewType& grid_view,
                               const FunctionType& function,
                               const std::string type) const DS_OVERRIDE DS_FINAL
  {
    using namespace GDT;
    typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;
    typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;
    if (type == "L2") {
      return Products::L2< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "H1_semi") {
      return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "energy") {
      const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());
      assert(!diffusion_factor.parametric());
      assert(diffusion_factor.has_affine_part());
      const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());
      assert(!diffusion_tensor.parametric());
      assert(diffusion_tensor.has_affine_part());
      Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >
          elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);
      return elliptic_product.induced_norm(function);
    } else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... compute_norm_(...)

  virtual std::vector< std::string > available_estimators_() const DS_OVERRIDE DS_FINAL
  {
    auto ret = DiscretizationType::available_estimators();
    if (std::find(ret.begin(), ret.end(), "eta_ESV2007") != ret.end())
      ret.push_back("eff_ESV2007");
    if (std::find(ret.begin(), ret.end(), "eta_ESV2007_alt") != ret.end())
      ret.push_back("eff_ESV2007_alt");
    return ret;
  }

  virtual double estimate_(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "eff_ESV2007")
      return estimate_(vector, "eta_ESV2007") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else if (type == "eff_ESV2007_alt")
      return estimate_(vector, "eta_ESV2007_alt") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else {
      assert(this->current_discretization_);
      return this->current_discretization_->estimate(vector, type);
    }
  } // ... estimate_(...)
}; // class EocStudySWIPDG

} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH
<commit_msg>[test.linearelliptic-swipdg] whitespace<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH

#include <algorithm>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/common/exceptions.hh>

#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/gdt/playground/products/elliptic.hh>

#include <dune/hdd/linearelliptic/discretizations/swipdg.hh>
#include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>
#include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh>

#include "linearelliptic.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Tests {
namespace internal {

template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
class DiscretizationSWIPDG
{
  typedef typename TestCaseType::GridType GridType;
  typedef typename TestCaseType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange = TestCaseType::dimRange;
public:
  typedef Discretizations::SWIPDG
      < GridType, Stuff::Grid::ChooseLayer::level, RangeFieldType, dimRange, polOrder, space_backend, la_backend > Type;
}; // class DiscretizationSWIPDG

} // namespace internal

template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
class EocStudySWIPDG
  : public EocStudyBase< TestCaseType,
                         typename internal::DiscretizationSWIPDG< TestCaseType,
                                                                  polOrder,
                                                                  space_backend,
                                                                  la_backend >::Type >
{
  typedef EocStudyBase< TestCaseType,
                        typename internal::DiscretizationSWIPDG< TestCaseType,
                                                                 polOrder,
                                                                 space_backend,
                                                                 la_backend >::Type > BaseType;
  typedef EocStudySWIPDG< TestCaseType, polOrder, space_backend, la_backend > ThisType;

  typedef typename BaseType::DiscretizationType DiscretizationType;
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::FunctionType FunctionType;
  typedef typename BaseType::VectorType   VectorType;

public:
  EocStudySWIPDG(const TestCaseType& test_case, const std::vector< std::string > only_these_norms = {})
    : BaseType(test_case, only_these_norms)
  {}

  virtual ~EocStudySWIPDG() {}

  virtual std::string identifier() const DS_OVERRIDE DS_FINAL
  {
    return DiscretizationType::static_id() + " (polorder " + Stuff::Common::toString(polOrder) + ")";
  }

  virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "L2")
      return polOrder + 1;
    else if (type == "H1_semi")
      return polOrder;
    else if (type == "energy")
      return polOrder;
    else if (type == "eta_NC_ESV2007")
      return polOrder;
    else if (type == "eta_R_ESV2007")
      return polOrder + 1;
    else if (type == "eta_DF_ESV2007")
      return polOrder;
    else if (type == "eta_ESV2007")
      return polOrder;
    else if (type == "eff_ESV2007")
      return 0;
    else if (type == "eta_ESV2007_alt")
      return polOrder;
    else if (type == "eff_ESV2007_alt")
      return 0;
    else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... expected_rate(...)

  virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL
  {
#if HAVE_ALUGRID
    if (std::is_same< TestCaseType, TestCases::ESV2007< ALUConformGrid< 2, 2 > > >::value
        || std::is_same< TestCaseType, TestCases::ESV2007< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (polOrder == 1) {
        if (type == "L2")
          return {1.84e-02, 4.54e-03, 1.13e-03, 2.79e-04};
        else if (type == "H1_semi")
          return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
        else if (type == "energy")
          return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
        else if (type == "eta_NC_ESV2007")
          return {1.90e-1, 9.73e-2, 4.90e-2, 2.46e-2};
        else if (type == "eta_R_ESV2007")
          return {7.24e-2, 1.83e-2, 4.55e-3, 1.15e-3};
        else if (type == "eta_DF_ESV2007") {
          // these are the values reported in the ESV2007 preprint:
//          return {3.39e-1, 1.70e-1, 8.40e-2, 4.19e-2};
          // but we do not want the test to fail each time, so we expect these:
          return {3.56e-1, 1.77e-1, 8.74e-2, 4.36e-2};
        } else if (type == "eta_ESV2007")
          return {4.50e-01, 2.08e-01,  9.92e-02, 4.86e-02};
        else if (type == "eff_ESV2007") {
          // these are the values reported in the ESV2007 preprint:
//          return {1.21, 1.21, 1.21, 1.21};
          // but we do not want the test to fail each time, so we expect these:
          return {1.38, 1.29, 1.24, 1.22};
        } else if (type == "eta_ESV2007_alt")
          return {5.94e-01, 2.74e-01, 1.32e-01, 6.43e-02};
        else if (type == "eff_ESV2007_alt")
          return {1.82, 1.70, 1.64, 1.61};
        else
          DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
      } else
        DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!");
    } else if (std::is_same< TestCaseType, TestCases::OS2014< ALUConformGrid< 2, 2 > > >::value
               || std::is_same< TestCaseType, TestCases::OS2014< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (polOrder == 1) {
        if (type == "energy")
          return {4.75e-01, 2.63e-01, 1.28e-01, 5.62e-02};
        else if (type == "eta_NC")
          return {2.39e-01, 1.43e-01, 6.83e-02, 3.14e-02};
        else if (type == "eta_R")
          return {8.19e-02, 1.99e-02, 4.84e-03, 1.20e-03};
        else if (type == "eta_DF") {
          return {6.35e-01, 3.62e-01, 1.88e-01, 9.18e-02};
        } else if (type == "eta")
          return {7.51e-01, 4.06e-01, 2.01e-01, 9.80e-02};
        else
          DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
      } else
        DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!");
    } else
#endif // HAVE_ALUGRID
      DUNE_THROW(NotImplemented, "Please record the expected results for this TestCaseType/GridType combination!");
  } // ... expected_results(...)

private:
  virtual std::vector< std::string > available_norms_() const DS_OVERRIDE DS_FINAL
  {
    return {"L2", "H1_semi", "energy"};
  }

  virtual double compute_norm_(const GridViewType& grid_view,
                               const FunctionType& function,
                               const std::string type) const DS_OVERRIDE DS_FINAL
  {
    using namespace GDT;
    typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;
    typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;
    if (type == "L2") {
      return Products::L2< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "H1_semi") {
      return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "energy") {
      const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());
      assert(!diffusion_factor.parametric());
      assert(diffusion_factor.has_affine_part());
      const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());
      assert(!diffusion_tensor.parametric());
      assert(diffusion_tensor.has_affine_part());
      Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >
          elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);
      return elliptic_product.induced_norm(function);
    } else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... compute_norm_(...)

  virtual std::vector< std::string > available_estimators_() const DS_OVERRIDE DS_FINAL
  {
    auto ret = DiscretizationType::available_estimators();
    if (std::find(ret.begin(), ret.end(), "eta_ESV2007") != ret.end())
      ret.push_back("eff_ESV2007");
    if (std::find(ret.begin(), ret.end(), "eta_ESV2007_alt") != ret.end())
      ret.push_back("eff_ESV2007_alt");
    return ret;
  }

  virtual double estimate_(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "eff_ESV2007")
      return estimate_(vector, "eta_ESV2007") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else if (type == "eff_ESV2007_alt")
      return estimate_(vector, "eta_ESV2007_alt") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else {
      assert(this->current_discretization_);
      return this->current_discretization_->estimate(vector, type);
    }
  } // ... estimate_(...)
}; // class EocStudySWIPDG

} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH
<|endoftext|>


<commit_before>#include "extensions/openpower-pels/data_interface.hpp"
#include "extensions/openpower-pels/host_interface.hpp"

#include <fcntl.h>

#include <filesystem>
#include <sdeventplus/source/io.hpp>

#include <gmock/gmock.h>

namespace openpower
{
namespace pels
{

class MockDataInterface : public DataInterfaceBase
{
  public:
    MockDataInterface()
    {
    }
    MOCK_METHOD(std::string, getMachineTypeModel, (), (const override));
    MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override));
    MOCK_METHOD(std::string, getServerFWVersion, (), (const override));
    MOCK_METHOD(std::string, getBMCFWVersion, (), (const override));
    MOCK_METHOD(std::string, getBMCFWVersionID, (), (const override));

    void changeHostState(bool newState)
    {
        setHostState(newState);
    }

    void setHMCManaged(bool managed)
    {
        _hmcManaged = managed;
    }
};

/**
 * @brief The mock HostInterface class
 *
 * This replaces the PLDM calls with a FIFO for the asynchronous
 * responses.
 */
class MockHostInterface : public HostInterface
{
  public:
    /**
     * @brief Constructor
     *
     * @param[in] event - The sd_event object
     * @param[in] dataIface - The DataInterface class
     */
    MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) :
        HostInterface(event, dataIface)
    {
        char templ[] = "/tmp/cmdfifoXXXXXX";
        std::filesystem::path dir = mkdtemp(templ);
        _fifo = dir / "fifo";
    }

    /**
     * @brief Destructor
     */
    virtual ~MockHostInterface()
    {
        std::filesystem::remove_all(_fifo.parent_path());
    }

    MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override));

    /**
     * @brief Cancels waiting for a command response
     */
    virtual void cancelCmd() override
    {
        _inProgress = false;
        _source = nullptr;
    }

    /**
     * @brief Returns the amount of time to wait before retrying after
     *        a failed send command.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getSendRetryDelay() const override
    {
        return std::chrono::milliseconds(2);
    }

    /**
     * @brief Returns the amount of time to wait before retrying after
     *        a command receive.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getReceiveRetryDelay() const override
    {
        return std::chrono::milliseconds(2);
    }

    /**
     * @brief Returns the amount of time to wait before retrying if the
     *        host firmware's PEL storage was full and it can't store
     *        any more logs until it is freed up somehow.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getHostFullRetryDelay() const override
    {
        return std::chrono::milliseconds(20);
    }

    /**
     * @brief Returns the number of commands processed
     */
    size_t numCmdsProcessed() const
    {
        return _cmdsProcessed;
    }

    /**
     * @brief Writes the data passed in to the FIFO
     *
     * @param[in] hostResponse - use a 0 to indicate success
     *
     * @return CmdStatus - success or failure
     */
    CmdStatus send(uint8_t hostResponse)
    {
        // Create a FIFO once.
        if (!std::filesystem::exists(_fifo))
        {
            if (mkfifo(_fifo.c_str(), 0622))
            {
                ADD_FAILURE() << "Failed mkfifo " << _fifo << strerror(errno);
                exit(-1);
            }
        }

        // Open it and register the reponse callback to
        // be used on FD activity.
        int fd = open(_fifo.c_str(), O_NONBLOCK | O_RDWR);
        EXPECT_TRUE(fd >= 0) << "Unable to open FIFO";

        auto callback = [this](sdeventplus::source::IO& source, int fd,
                               uint32_t events) {
            this->receive(source, fd, events);
        };

        try
        {
            _source = std::make_unique<sdeventplus::source::IO>(
                _event, fd, EPOLLIN,
                std::bind(callback, std::placeholders::_1,
                          std::placeholders::_2, std::placeholders::_3));
        }
        catch (std::exception& e)
        {
            ADD_FAILURE() << "Event exception: " << e.what();
            close(fd);
            return CmdStatus::failure;
        }

        // Write the fake host reponse to the FIFO
        auto bytesWritten = write(fd, &hostResponse, sizeof(hostResponse));
        EXPECT_EQ(bytesWritten, sizeof(hostResponse));

        _inProgress = true;

        return CmdStatus::success;
    }

  protected:
    /**
     * @brief Reads the data written to the fifo and then calls
     *        the subscriber's callback.
     *
     * Nonzero data indicates a command failure (for testing bad path).
     *
     * @param[in] source - The event source object
     * @param[in] fd - The file descriptor used
     * @param[in] events - The event bits
     */
    void receive(sdeventplus::source::IO& source, int fd,
                 uint32_t events) override
    {
        if (!(events & EPOLLIN))
        {
            return;
        }

        _inProgress = false;

        int newFD = open(_fifo.c_str(), O_NONBLOCK | O_RDONLY);
        ASSERT_TRUE(newFD >= 0) << "Failed to open FIFO";

        // Read the host success/failure response from the FIFO.
        uint8_t data;
        auto bytesRead = read(newFD, &data, sizeof(data));
        EXPECT_EQ(bytesRead, sizeof(data));

        close(newFD);

        ResponseStatus status = ResponseStatus::success;
        if (data != 0)
        {
            status = ResponseStatus::failure;
        }

        if (_responseFunc)
        {
            (*_responseFunc)(status);
        }

        // Keep account of the number of commands responses for testing.
        _cmdsProcessed++;
    }

  private:
    /**
     * @brief The event source for the fifo
     */
    std::unique_ptr<sdeventplus::source::IO> _source;

    /**
     * @brief the path to the fifo
     */
    std::filesystem::path _fifo;

    /**
     * @brief The number of commands processed
     */
    size_t _cmdsProcessed = 0;
};

} // namespace pels
} // namespace openpower
<commit_msg>PEL:  Increase host full timeout val in test<commit_after>#include "extensions/openpower-pels/data_interface.hpp"
#include "extensions/openpower-pels/host_interface.hpp"

#include <fcntl.h>

#include <filesystem>
#include <sdeventplus/source/io.hpp>

#include <gmock/gmock.h>

namespace openpower
{
namespace pels
{

class MockDataInterface : public DataInterfaceBase
{
  public:
    MockDataInterface()
    {
    }
    MOCK_METHOD(std::string, getMachineTypeModel, (), (const override));
    MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override));
    MOCK_METHOD(std::string, getServerFWVersion, (), (const override));
    MOCK_METHOD(std::string, getBMCFWVersion, (), (const override));
    MOCK_METHOD(std::string, getBMCFWVersionID, (), (const override));

    void changeHostState(bool newState)
    {
        setHostState(newState);
    }

    void setHMCManaged(bool managed)
    {
        _hmcManaged = managed;
    }
};

/**
 * @brief The mock HostInterface class
 *
 * This replaces the PLDM calls with a FIFO for the asynchronous
 * responses.
 */
class MockHostInterface : public HostInterface
{
  public:
    /**
     * @brief Constructor
     *
     * @param[in] event - The sd_event object
     * @param[in] dataIface - The DataInterface class
     */
    MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) :
        HostInterface(event, dataIface)
    {
        char templ[] = "/tmp/cmdfifoXXXXXX";
        std::filesystem::path dir = mkdtemp(templ);
        _fifo = dir / "fifo";
    }

    /**
     * @brief Destructor
     */
    virtual ~MockHostInterface()
    {
        std::filesystem::remove_all(_fifo.parent_path());
    }

    MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override));

    /**
     * @brief Cancels waiting for a command response
     */
    virtual void cancelCmd() override
    {
        _inProgress = false;
        _source = nullptr;
    }

    /**
     * @brief Returns the amount of time to wait before retrying after
     *        a failed send command.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getSendRetryDelay() const override
    {
        return std::chrono::milliseconds(2);
    }

    /**
     * @brief Returns the amount of time to wait before retrying after
     *        a command receive.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getReceiveRetryDelay() const override
    {
        return std::chrono::milliseconds(2);
    }

    /**
     * @brief Returns the amount of time to wait before retrying if the
     *        host firmware's PEL storage was full and it can't store
     *        any more logs until it is freed up somehow.
     *
     * @return milliseconds - The amount of time to wait
     */
    virtual std::chrono::milliseconds getHostFullRetryDelay() const override
    {
        return std::chrono::milliseconds(400);
    }

    /**
     * @brief Returns the number of commands processed
     */
    size_t numCmdsProcessed() const
    {
        return _cmdsProcessed;
    }

    /**
     * @brief Writes the data passed in to the FIFO
     *
     * @param[in] hostResponse - use a 0 to indicate success
     *
     * @return CmdStatus - success or failure
     */
    CmdStatus send(uint8_t hostResponse)
    {
        // Create a FIFO once.
        if (!std::filesystem::exists(_fifo))
        {
            if (mkfifo(_fifo.c_str(), 0622))
            {
                ADD_FAILURE() << "Failed mkfifo " << _fifo << strerror(errno);
                exit(-1);
            }
        }

        // Open it and register the reponse callback to
        // be used on FD activity.
        int fd = open(_fifo.c_str(), O_NONBLOCK | O_RDWR);
        EXPECT_TRUE(fd >= 0) << "Unable to open FIFO";

        auto callback = [this](sdeventplus::source::IO& source, int fd,
                               uint32_t events) {
            this->receive(source, fd, events);
        };

        try
        {
            _source = std::make_unique<sdeventplus::source::IO>(
                _event, fd, EPOLLIN,
                std::bind(callback, std::placeholders::_1,
                          std::placeholders::_2, std::placeholders::_3));
        }
        catch (std::exception& e)
        {
            ADD_FAILURE() << "Event exception: " << e.what();
            close(fd);
            return CmdStatus::failure;
        }

        // Write the fake host reponse to the FIFO
        auto bytesWritten = write(fd, &hostResponse, sizeof(hostResponse));
        EXPECT_EQ(bytesWritten, sizeof(hostResponse));

        _inProgress = true;

        return CmdStatus::success;
    }

  protected:
    /**
     * @brief Reads the data written to the fifo and then calls
     *        the subscriber's callback.
     *
     * Nonzero data indicates a command failure (for testing bad path).
     *
     * @param[in] source - The event source object
     * @param[in] fd - The file descriptor used
     * @param[in] events - The event bits
     */
    void receive(sdeventplus::source::IO& source, int fd,
                 uint32_t events) override
    {
        if (!(events & EPOLLIN))
        {
            return;
        }

        _inProgress = false;

        int newFD = open(_fifo.c_str(), O_NONBLOCK | O_RDONLY);
        ASSERT_TRUE(newFD >= 0) << "Failed to open FIFO";

        // Read the host success/failure response from the FIFO.
        uint8_t data;
        auto bytesRead = read(newFD, &data, sizeof(data));
        EXPECT_EQ(bytesRead, sizeof(data));

        close(newFD);

        ResponseStatus status = ResponseStatus::success;
        if (data != 0)
        {
            status = ResponseStatus::failure;
        }

        if (_responseFunc)
        {
            (*_responseFunc)(status);
        }

        // Keep account of the number of commands responses for testing.
        _cmdsProcessed++;
    }

  private:
    /**
     * @brief The event source for the fifo
     */
    std::unique_ptr<sdeventplus::source::IO> _source;

    /**
     * @brief the path to the fifo
     */
    std::filesystem::path _fifo;

    /**
     * @brief The number of commands processed
     */
    size_t _cmdsProcessed = 0;
};

} // namespace pels
} // namespace openpower
<|endoftext|>


<commit_before>#include <functional>
#include <future>
#include <unordered_map>
#include "kernel.h"
#include "raster.h"
#include "itemdomain.h"
#include "thematicitem.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "classification/sampleset.h"
#include "classifier.h"
#include "rasterclassification.h"

using namespace Ilwis;
using namespace RasterOperations;

RasterClassification::RasterClassification()
{
}

RasterClassification::RasterClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool RasterClassification::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx,symTable)) != sPREPARED)
            return false;

    PixelIterator iterIn(_sampleSet.sampleRasterSet());
    iterIn.setFlow(PixelIterator::fZXY);

    PixelIterator iterOut(_outputRaster);

    _classifier->classify(iterIn, iterOut);

    return true;

}

Ilwis::OperationImplementation::State RasterClassification::prepare(ExecutionContext *, const SymbolTable &sym){
    QString rasterSetName = _expression.parm(0).value();
    IRasterCoverage rcSet;
    if (!rcSet.prepare(rasterSetName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,rasterSetName,"");
        return sPREPAREFAILED;
    }

    QString domain = _expression.parm(1).value();
    IThematicDomain themes;
    if ( !themes.prepare(domain)){
        ERROR2(ERR_COULD_NOT_LOAD_2,domain,"");
        return sPREPAREFAILED;
    }

    QString trainingsRaster = _expression.parm(2).value();
    IRasterCoverage rcTraining;
    if (!rcTraining.prepare(trainingsRaster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,trainingsRaster,"");
        return sPREPAREFAILED;
    }

    _sampleSet = SampleSet(rcSet, themes, rcTraining);
    _sampleSet.prepare();

    QString outputName = _expression.parm(0,false).value();

    _outputRaster = OperationHelperRaster::initialize(_sampleSet.sampleRasterSet(),itRASTER, itCOORDSYSTEM | itGEODETICDATUM | itGEOREF);
   if ( !_outputRaster.isValid()) {
       ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
       return sPREPAREFAILED;
   }
   _outputRaster->datadef().domain(_sampleSet.thematicDomain());
   _outputRaster->size(_sampleSet.sampleRasterSet()->size().twod());
   if ( outputName!= sUNDEF)
       _outputRaster->name(outputName);

   return sPREPARED;
}

int RasterClassification::fillOperationMetadata(OperationResource &operation)
{
    operation.addInParameter(0,itRASTER , TR("Multiband raster"),TR("Multi band raster to be classified"));
    operation.addInParameter(1,itITEMDOMAIN , TR("Thematic domain"),TR("Domain of the classified map"));
    operation.addInParameter(2,itRASTER , TR("Training set"),TR("Raster containing trainingset(s) of pixels"));

    return 3;
}
//-------------------------------------------------------

REGISTER_OPERATION(BoxClassification)

BoxClassification::BoxClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : RasterClassification(metaid, expr)
{

}

Ilwis::OperationImplementation *BoxClassification::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new BoxClassification(metaid, expr);
}

Ilwis::OperationImplementation::State BoxClassification::prepare(ExecutionContext *ctx, const SymbolTable &sym)
{
    OperationImplementation::State prepareState = sNOTPREPARED;

    if ( (prepareState = RasterClassification::prepare(ctx,sym)) != sPREPARED){
        return prepareState;
    }

    bool ok;
    _widenFactor = _expression.parm(3).value().toDouble(&ok);
    if (!ok || _widenFactor <= 0){
        ERROR2(ERR_ILLEGAL_VALUE_2, "widen factor", _expression.parm(1).value());
    }

    _classifier.reset( new BoxClassifier(_widenFactor,_sampleSet));

    return sPREPARED;
}

quint64 BoxClassification::createMetadata()
{
    OperationResource operation({"ilwis://operations/boxclassification"});
    operation.setSyntax("boxclassifcation(samplesetname,widen-factor)");
    operation.setDescription(TR("performs a multi-spectral image classification according to training pixels in a sample set"));
    unsigned int n = RasterClassification::fillOperationMetadata(operation);
    operation.setInParameterCount({1 + n});
    operation.addInParameter(n,itNUMBER , TR("widen-factor"),TR("allows you to widen (factor > 1) the boxes that are 'drawn' around class means"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(1,itRASTER, TR("output rastercoverage with the domain of the sampleset"));
    operation.setKeywords("classification,raster");

    mastercatalog()->addItems({operation});
    return operation.id();
}

<commit_msg>added setting of output for classifier<commit_after>#include <functional>
#include <future>
#include <unordered_map>
#include "kernel.h"
#include "raster.h"
#include "itemdomain.h"
#include "thematicitem.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "classification/sampleset.h"
#include "classifier.h"
#include "rasterclassification.h"

using namespace Ilwis;
using namespace RasterOperations;

RasterClassification::RasterClassification()
{
}

RasterClassification::RasterClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool RasterClassification::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx,symTable)) != sPREPARED)
            return false;

    PixelIterator iterIn(_sampleSet.sampleRasterSet());
    iterIn.setFlow(PixelIterator::fZXY);

    PixelIterator iterOut(_outputRaster);

    bool res = _classifier->classify(iterIn, iterOut);

    _outputRaster->statistics()
    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IRasterCoverage>(_outputRaster);
        ctx->setOutput(symTable,value,_outputRaster->name(), itRASTER, _outputRaster->source(IlwisObject::cmEXTENDED) );
    }
    return res;
}

Ilwis::OperationImplementation::State RasterClassification::prepare(ExecutionContext *, const SymbolTable &sym){
    QString rasterSetName = _expression.parm(0).value();
    IRasterCoverage rcSet;
    if (!rcSet.prepare(rasterSetName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,rasterSetName,"");
        return sPREPAREFAILED;
    }

    QString domain = _expression.parm(1).value();
    IThematicDomain themes;
    if ( !themes.prepare(domain)){
        ERROR2(ERR_COULD_NOT_LOAD_2,domain,"");
        return sPREPAREFAILED;
    }

    QString trainingsRaster = _expression.parm(2).value();
    IRasterCoverage rcTraining;
    if (!rcTraining.prepare(trainingsRaster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,trainingsRaster,"");
        return sPREPAREFAILED;
    }

    _sampleSet = SampleSet(rcSet, themes, rcTraining);
    _sampleSet.prepare();

    QString outputName = _expression.parm(0,false).value();

    OperationHelperRaster::initialize(_sampleSet.sampleRasterSet(), _outputRaster, itCOORDSYSTEM | itGEODETICDATUM | itGEOREF | itRASTERSIZE);
   if ( !_outputRaster.isValid()) {
       ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
       return sPREPAREFAILED;
   }
   _outputRaster->datadef().domain(_sampleSet.thematicDomain());
   _outputRaster->size(_sampleSet.sampleRasterSet()->size().twod());
   if ( outputName!= sUNDEF)
       _outputRaster->name(outputName);

   return sPREPARED;
}

int RasterClassification::fillOperationMetadata(OperationResource &operation)
{
    operation.addInParameter(0,itRASTER , TR("Multiband raster"),TR("Multi band raster to be classified"));
    operation.addInParameter(1,itITEMDOMAIN , TR("Thematic domain"),TR("Domain of the classified map"));
    operation.addInParameter(2,itRASTER , TR("Training set"),TR("Raster containing trainingset(s) of pixels"));

    return 3;
}
//-------------------------------------------------------

REGISTER_OPERATION(BoxClassification)

BoxClassification::BoxClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : RasterClassification(metaid, expr)
{

}

Ilwis::OperationImplementation *BoxClassification::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new BoxClassification(metaid, expr);
}

Ilwis::OperationImplementation::State BoxClassification::prepare(ExecutionContext *ctx, const SymbolTable &sym)
{
    OperationImplementation::State prepareState = sNOTPREPARED;

    if ( (prepareState = RasterClassification::prepare(ctx,sym)) != sPREPARED){
        return prepareState;
    }

    bool ok;
    _widenFactor = _expression.parm(3).value().toDouble(&ok);
    if (!ok || _widenFactor <= 0){
        ERROR2(ERR_ILLEGAL_VALUE_2, "widen factor", _expression.parm(1).value());
    }

    _classifier.reset( new BoxClassifier(_widenFactor,_sampleSet));
    if(!_classifier->prepare())
        return sPREPAREFAILED;

    return sPREPARED;
}

quint64 BoxClassification::createMetadata()
{
    OperationResource operation({"ilwis://operations/boxclassification"});
    operation.setSyntax("boxclassifcation(samplesetname,widen-factor)");
    operation.setDescription(TR("performs a multi-spectral image classification according to training pixels in a sample set"));
    unsigned int n = RasterClassification::fillOperationMetadata(operation);
    operation.setInParameterCount({1 + n});
    operation.addInParameter(n,itNUMBER , TR("widen-factor"),TR("allows you to widen (factor > 1) the boxes that are 'drawn' around class means"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(1,itRASTER, TR("output rastercoverage with the domain of the sampleset"));
    operation.setKeywords("classification,raster");

    mastercatalog()->addItems({operation});
    return operation.id();
}

<|endoftext|>


<commit_before>//===--- swift-serialize-diagnostics.cpp ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Convert localization YAML files to a srialized format.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/LocalizationFormat.h"
#include "swift/Basic/LLVMInitialize.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>

using namespace swift;
using namespace swift::diag;

namespace options {

static llvm::cl::OptionCategory Category("swift-serialize-diagnostics Options");

static llvm::cl::opt<std::string>
    InputFilePath("input-file-path",
                  llvm::cl::desc("Path to the YAML input file"),
                  llvm::cl::cat(Category));

static llvm::cl::opt<std::string>
    OutputDirectory("output-directory",
                    llvm::cl::desc("Directory for the output file"),
                    llvm::cl::cat(Category));

} // namespace options

int main(int argc, char *argv[]) {
  PROGRAM_START(argc, argv);
  INITIALIZE_LLVM();

  llvm::cl::HideUnrelatedOptions(options::Category);
  llvm::cl::ParseCommandLineOptions(argc, argv,
                                    "Swift Serialize Diagnostics Tool\n");

  if (!llvm::sys::fs::exists(options::InputFilePath)) {
    llvm::errs() << "YAML file not found\n";
    return 1;
  }

  YAMLLocalizationProducer yaml(options::InputFilePath);

  auto localeCode = llvm::sys::path::filename(options::InputFilePath);
  llvm::SmallString<128> SerializedFilePath(options::OutputDirectory);
  llvm::sys::path::append(SerializedFilePath, localeCode);
  llvm::sys::path::replace_extension(SerializedFilePath, ".db");

  SerializedLocalizationWriter Serializer;
  yaml.forEachAvailable(
      [&Serializer](swift::DiagID id, llvm::StringRef translation) {
        Serializer.insert(id, translation);
      });

  if (Serializer.emit(SerializedFilePath.str())) {
    llvm::errs() << "Cannot serialize diagnostic file "
                 << options::InputFilePath << '\n';
    return 1;
  }

  return 0;
}
<commit_msg>[Localization] Make return type of the serialization main cross platform<commit_after>//===--- swift-serialize-diagnostics.cpp ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Convert localization YAML files to a srialized format.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/LocalizationFormat.h"
#include "swift/Basic/LLVMInitialize.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>

using namespace swift;
using namespace swift::diag;

namespace options {

static llvm::cl::OptionCategory Category("swift-serialize-diagnostics Options");

static llvm::cl::opt<std::string>
    InputFilePath("input-file-path",
                  llvm::cl::desc("Path to the YAML input file"),
                  llvm::cl::cat(Category));

static llvm::cl::opt<std::string>
    OutputDirectory("output-directory",
                    llvm::cl::desc("Directory for the output file"),
                    llvm::cl::cat(Category));

} // namespace options

int main(int argc, char *argv[]) {
  PROGRAM_START(argc, argv);

  llvm::cl::HideUnrelatedOptions(options::Category);
  llvm::cl::ParseCommandLineOptions(argc, argv,
                                    "Swift Serialize Diagnostics Tool\n");

  if (!llvm::sys::fs::exists(options::InputFilePath)) {
    llvm::errs() << "YAML file not found\n";
    return EXIT_FAILURE;
  }

  YAMLLocalizationProducer yaml(options::InputFilePath);

  auto localeCode = llvm::sys::path::filename(options::InputFilePath);
  llvm::SmallString<128> SerializedFilePath(options::OutputDirectory);
  llvm::sys::path::append(SerializedFilePath, localeCode);
  llvm::sys::path::replace_extension(SerializedFilePath, ".db");

  SerializedLocalizationWriter Serializer;
  yaml.forEachAvailable(
      [&Serializer](swift::DiagID id, llvm::StringRef translation) {
        Serializer.insert(id, translation);
      });

  if (Serializer.emit(SerializedFilePath.str())) {
    llvm::errs() << "Cannot serialize diagnostic file "
                 << options::InputFilePath << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Use IOMessageLoop in a SyncFileSystem test<commit_after><|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dll_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,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                                                     */

// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_WORKAROUNDS_DLL_H_
#define _MSS_WORKAROUNDS_DLL_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <map>

namespace mss
{

///
/// @brief class to keep trace of DLL info for workaround
///
struct dll_map
{
    // Same values for DP16 and ADR enumerations
    // Used DP16 enumerations...just because
    static constexpr uint64_t REGS_RXDLL_DAC_COARSE = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE;
    static constexpr uint64_t REGS_RXDLL_DAC_COARSE_LEN =
        MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE_LEN;
    static constexpr uint64_t DLL_CNTL_CAL_ERROR = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR;
    static constexpr uint64_t DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR_FINE;
    static constexpr uint64_t DLL_CAL_GOOD = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_GOOD;

    // Value for UPPER and LOWER DAC are the same
    // Used LOWER DAC enumeration...just because
    static constexpr uint64_t REGS_RXDLL_VREG = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER;
    static constexpr uint64_t REGS_RXDLL_VREG_LEN = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER_LEN;

    ///
    /// @brief Checks for DLL error status
    /// @param[in] i_cntrl_reg
    /// @param[in] i_vreg_coarse_same_dll
    /// @param[in] i_vreg_coarse_neighbor_dll
    /// @param[in] i_dll_dac_upper
    /// @param[in] i_dll_dac_lower
    ///
    constexpr dll_map(const uint64_t i_cntrl_reg,
                      const uint64_t i_vreg_coarse_same_dll,
                      const uint64_t i_vreg_coarse_neighbor_dll,
                      const uint64_t i_dll_dac_lower,
                      const uint64_t i_dll_dac_upper)
        : iv_cntrl(i_cntrl_reg),
          iv_vreg_coarse_same_dll(i_vreg_coarse_same_dll),
          iv_vreg_coarse_neighbor_dll(i_vreg_coarse_neighbor_dll),
          iv_dll_dac_lower(i_dll_dac_lower),
          iv_dll_dac_upper(i_dll_dac_upper)
    {}

    const uint64_t iv_cntrl; // DP16 or ADR CNTRL register
    const uint64_t iv_vreg_coarse_same_dll; // VREG_COARSE register for same DLL as iv_cntrl_reg
    const uint64_t iv_vreg_coarse_neighbor_dll; // VREG_COARSE register for DLL neighbor for this workaround
    const uint64_t iv_dll_dac_lower; // DLL DAC Upper register
    const uint64_t iv_dll_dac_upper; // DLL DAC Lower register
};

namespace workarounds
{
namespace dll
{

///
/// @brief Clears the DLL firs
/// @param[in] i_target the MCA target
/// @return returns true unless if scom errors
///
fapi2::ReturnCode clear_dll_fir( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target  );

///
/// @brief Checks if CAL_ERROR and CAL_ERROR_FINE bits are set
/// @param[in] i_dll_cntrl_data DLL CNTRL data
/// @return bool
///
bool did_cal_fail( const fapi2::buffer<uint64_t>& i_dll_cntrl_data );

///
/// @brief Logs DLL error mappings from failed DLLs
/// @param[in] i_target the fapi2 target
/// @param[in] i_map dll map of DLLs to log errors from
/// @param[in,out] io_failed_dll_cntrl failed list of DLL CNTRL regs
/// @param[in,out] io_failed_dll_vreg_coarse map of VREG COARSE from failed DLLs
/// @param[in,out] io_failed_dll_dac map of DLL DAC from failed DLLs
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode log_fails(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                            const mss::dll_map& i_map,
                            std::vector< uint64_t >& io_failed_dll_cntrl,
                            std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_vreg_coarse,
                            std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_dac);

///
/// @brief Checks for DLL error status
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_cntrl vector of failed DLLs
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode check_status(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                               const std::vector< uint64_t >& i_failed_dll_cntrl);

///
/// @brief Change VREG_COARSE for failed DLLs
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_map failed DLL VREG COARSE map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode change_vreg_coarse(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                                     const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_map);

///
/// @brief Change DLL DAC for failled DLLs map
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_dac_map failed DLL DAC map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode change_dac(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                             const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_dac_map);

///
/// @brief DLL Workaround algorithm to fax bad voltage settings
/// @tparam T fapi2 Target Type - derived
/// @param[in] i_target the fapi2 target
/// @return FAPI2_RC_SUCCESS iff ok
///
template< fapi2::TargetType T  >
fapi2::ReturnCode fix_bad_voltage_settings(const fapi2::Target<T>& i_target);

} // close namespace dll
} // close namespace workarounds
} // close namespace mss

#endif
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dll_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,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                                                     */

// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef _MSS_WORKAROUNDS_DLL_H_
#define _MSS_WORKAROUNDS_DLL_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <map>

namespace mss
{

///
/// @brief class to keep trace of DLL info for workaround
///
struct dll_map
{
    // Same values for DP16 and ADR enumerations
    // Used DP16 enumerations...just because
    static constexpr uint64_t REGS_RXDLL_DAC_COARSE = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE;
    static constexpr uint64_t REGS_RXDLL_DAC_COARSE_LEN =
        MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE_LEN;
    static constexpr uint64_t DLL_CNTL_CAL_ERROR = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR;
    static constexpr uint64_t DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR_FINE;
    static constexpr uint64_t DLL_CAL_GOOD = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_GOOD;

    // Value for UPPER and LOWER DAC are the same
    // Used LOWER DAC enumeration...just because
    static constexpr uint64_t REGS_RXDLL_VREG = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER;
    static constexpr uint64_t REGS_RXDLL_VREG_LEN = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER_LEN;

    ///
    /// @brief Checks for DLL error status
    /// @param[in] i_cntrl_reg
    /// @param[in] i_vreg_coarse_same_dll
    /// @param[in] i_vreg_coarse_neighbor_dll
    /// @param[in] i_dll_dac_upper
    /// @param[in] i_dll_dac_lower
    ///
    constexpr dll_map(const uint64_t i_cntrl_reg,
                      const uint64_t i_vreg_coarse_same_dll,
                      const uint64_t i_vreg_coarse_neighbor_dll,
                      const uint64_t i_dll_dac_lower,
                      const uint64_t i_dll_dac_upper)
        : iv_cntrl(i_cntrl_reg),
          iv_vreg_coarse_same_dll(i_vreg_coarse_same_dll),
          iv_vreg_coarse_neighbor_dll(i_vreg_coarse_neighbor_dll),
          iv_dll_dac_lower(i_dll_dac_lower),
          iv_dll_dac_upper(i_dll_dac_upper)
    {}

    const uint64_t iv_cntrl; // DP16 or ADR CNTRL register
    const uint64_t iv_vreg_coarse_same_dll; // VREG_COARSE register for same DLL as iv_cntrl_reg
    const uint64_t iv_vreg_coarse_neighbor_dll; // VREG_COARSE register for DLL neighbor for this workaround
    const uint64_t iv_dll_dac_lower; // DLL DAC Upper register
    const uint64_t iv_dll_dac_upper; // DLL DAC Lower register
};

namespace workarounds
{
namespace dll
{

///
/// @brief Clears the DLL firs
/// @param[in] i_target the MCA target
/// @return returns true unless if scom errors
///
fapi2::ReturnCode clear_dll_fir( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target  );

///
/// @brief Checks if CAL_ERROR and CAL_ERROR_FINE bits are set
/// @param[in] i_dll_cntrl_data DLL CNTRL data
/// @return bool
///
bool did_cal_fail( const fapi2::buffer<uint64_t>& i_dll_cntrl_data );

///
/// @brief Logs DLL error mappings from failed DLLs
/// @param[in] i_target the fapi2 target
/// @param[in] i_map dll map of DLLs to log errors from
/// @param[in,out] io_failed_dll_cntrl failed list of DLL CNTRL regs
/// @param[in,out] io_failed_dll_vreg_coarse map of VREG COARSE from failed DLLs
/// @param[in,out] io_failed_dll_dac map of DLL DAC from failed DLLs
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode log_fails(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                            const mss::dll_map& i_map,
                            std::vector< uint64_t >& io_failed_dll_cntrl,
                            std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_vreg_coarse,
                            std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_dac);

///
/// @brief Checks for DLL error status
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_cntrl vector of failed DLLs
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode check_status(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                               const std::vector< uint64_t >& i_failed_dll_cntrl);

///
/// @brief Change VREG_COARSE for failed DLLs
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_map failed DLL VREG COARSE map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode change_vreg_coarse(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                                     const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_map);

///
/// @brief Change DLL DAC for failled DLLs map
/// @param[in] i_target the fapi2 target
/// @param[in] i_failed_dll_dac_map failed DLL DAC map
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode change_dac(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                             const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_dac_map);

///
/// @brief DLL Workaround algorithm to fax bad voltage settings
/// @tparam T fapi2 Target Type - derived
/// @param[in] i_target the fapi2 target
/// @return FAPI2_RC_SUCCESS iff ok
///
template< fapi2::TargetType T  >
fapi2::ReturnCode fix_bad_voltage_settings(const fapi2::Target<T>& i_target);

} // close namespace dll
} // close namespace workarounds
} // close namespace mss

#endif
<|endoftext|>