<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/io/readmnist.h"

#include "elm/ts/ts.h"          ///< custom assertions

#include <boost/filesystem.hpp>

#include "elm/core/exception.h"
#include "elm/io/binary.h"      ///< determine and swap endianness

using namespace std;
namespace bfs=boost::filesystem; // use alias
using namespace elm;

class FakeMNISTLabelsWriter {

public:

    static const int NB_ITEMS = 10;

    virtual ~FakeMNISTLabelsWriter()
    {
    }

    FakeMNISTLabelsWriter(const bfs::path& p)
        : path_(p)
    {
    }

    /**
     * @brief Save fake data to file
     * magic number
     * total no. of items
     * series label values [0,10)
     */
    virtual void Save(int magic_number)
    {
        SaveHeader(magic_number);
        SaveItems();
        out_.close();
    }

    void WriteInt(int n)
    {
        if(IS_32_LITTLE_ENDIAN) { elm::SwapEndian(&n); }
        out_.write(reinterpret_cast<char*>(&n), sizeof(int32_t));
    }

protected:

    virtual void SaveHeader(int magic_number)
    {
        if(out_.is_open()) {

            out_.close();
        }
        out_.open(path_.string().c_str(), ios::out | ios::binary);
        if(!out_.is_open()) {

            stringstream s;
            s << "Faied to write test file (" << path_ << ").";
            ELM_THROW_FILEIO_ERROR(s.str());
        }

        WriteInt(magic_number);
        WriteInt(NB_ITEMS);
    }

    virtual void SaveItems()
    {
        for(int i=0; i<NB_ITEMS; i++) {

            unsigned char next_label = static_cast<unsigned char>(i%10);
            out_.write(reinterpret_cast<char*>(&next_label), sizeof(unsigned char));
        }
    }

    bfs::path path_;
    ofstream out_;
};

/**
 * @brief class for testing ReadMNISTLabels
 * Fake data is written to disk first, then removed after last test
 */
class ReadMNISTLabelsTest : public testing::Test
{
protected:
    static void SetUpTestCase()
    {
        bfs::create_directory(test_data_dir_);
        FakeMNISTLabelsWriter writer(test_data_path_);

        writer.Save(ReadMNISTLabels().MagicNumber());
    }

    static void TearDownTestCase()
    {
        if(bfs::is_directory(test_data_dir_)) {

            bfs::remove_all(test_data_dir_);
        }
    }

    static const bfs::path test_data_dir_;
    static const bfs::path test_data_path_;
};
const bfs::path ReadMNISTLabelsTest::test_data_dir_("tmp_ReadMNISTFileTest");
const bfs::path ReadMNISTLabelsTest::test_data_path_(test_data_dir_/"fake_data.tmp");

TEST_F(ReadMNISTLabelsTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTLabels().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTLabelsTest, ReadHeader)
{
    const int N = FakeMNISTLabelsWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTLabels().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTLabelsTest, Next)
{
    ReadMNISTLabels to;
    const int N = to.ReadHeader(test_data_path_.string().c_str());

    EXPECT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            int label = static_cast<int>(to.Next().at<unsigned char>(0));
            EXPECT_EQ(label, i%N);

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTLabelsTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_labels_data_wrong_magic.tmp";
    FakeMNISTLabelsWriter writer(p);
    ReadMNISTLabels to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

class FakeMNISTImagesWriter : public FakeMNISTLabelsWriter
{

public:
    static const int NB_ITEMS = 10;
    static const int ROWS = 3;
    static const int COLS = 4;

    FakeMNISTImagesWriter(const bfs::path& p)
        : FakeMNISTLabelsWriter(p)
    {
    }

    /**
     * @brief Save fake data to file
     * magic number
     * total no. of items
     * series label values [0,10)
     */
    void SaveHeader(int magic_number)
    {
        FakeMNISTLabelsWriter::SaveHeader(magic_number);
        WriteInt(ROWS);
        WriteInt(COLS);
    }

    virtual void SaveItems()
    {
        for(int i=0; i<NB_ITEMS; i++) {

            unsigned char c = static_cast<unsigned char>(i % 255);
            cv::Mat next_img = cv::Mat(ROWS, COLS, CV_8UC1, c);
            out_.write(reinterpret_cast<char*>(next_img.data), sizeof(unsigned char)*next_img.total());
        }
    }

protected:
};

class ReadMNISTImagesTest : public ReadMNISTLabelsTest
{
protected:
    static void SetUpTestCase()
    {
        ReadMNISTLabelsTest::SetUpTestCase();

        FakeMNISTImagesWriter writer(test_data_path_);
        writer.Save(ReadMNISTImages().MagicNumber());
    }
};

TEST_F(ReadMNISTImagesTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTImages().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTest, ReadHeader)
{
    const int N = FakeMNISTImagesWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTImages().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTImagesTest, Next)
{
    ReadMNISTImages to;
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    const int ROWS = FakeMNISTImagesWriter::ROWS;
    const int COLS = FakeMNISTImagesWriter::COLS;

    EXPECT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            cv::Mat img = to.Next();
            EXPECT_MAT_DIMS_EQ(img, cv::Mat(ROWS, COLS, CV_8UC1));
            int sum = cv::sum(img)(0);
            sum /= (ROWS*COLS);
            EXPECT_EQ(sum, static_cast<unsigned char>(i%255));

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTImagesTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_images_data_wrong_magic.tmp";
    FakeMNISTImagesWriter writer(p);
    ReadMNISTImages to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

class ReadMNISTImagesTranslTest : public ReadMNISTImagesTest
{
protected:
    ReadMNISTImagesTransl to_; ///< test object
};

//class FakeMNISTImagesTranslWriter : public FakeMNISTImagesWriter
//{
//public:
//    FakeMNISTImagesTranslWriter(const bfs::path& p)
//        : FakeMNISTImagesWriter(p)
//    {
//        ;
//    }

//    virtual void SaveItems()
//    {

//    }
//};

TEST_F(ReadMNISTImagesTranslTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTImagesTransl().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTranslTest, SceneDims)
{
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(1, 0), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(0, 1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(-1, 1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(1, -1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(-1, -1), ExceptionBadDims);
    EXPECT_NO_THROW(ReadMNISTImagesTransl().SceneDims(1, 1));
}

TEST_F(ReadMNISTImagesTranslTest, ReadHeader)
{
    const int N = FakeMNISTImagesWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTImagesTransl().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTImagesTranslTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_images_data_wrong_magic.tmp";
    FakeMNISTImagesWriter writer(p);
    ReadMNISTImagesTransl to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTranslTest, EndOfFile)
{
    ReadMNISTImagesTransl to;
    to.SceneDims(20, 10);
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    ASSERT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            to.Next();
            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTImagesTranslTest, NextAndLocation)
{
    ReadMNISTImagesTransl to;
    to.SceneDims(20, 10);
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    ASSERT_GT(N, 0);
    const int ROWS = FakeMNISTImagesWriter::ROWS;
    const int COLS = FakeMNISTImagesWriter::COLS;

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            cv::Mat scene_img = to.Next();
            EXPECT_MAT_DIMS_EQ(scene_img, cv::Size2i(10, 20));

            cv::Rect2i loc = to.Location();

            EXPECT_EQ(loc.width, COLS);
            EXPECT_EQ(loc.height, ROWS);
            cv::Rect scene_window(cv::Point2i(0, 0), scene_img.size());
            EXPECT_TRUE(scene_window.contains(loc.tl())) << "TL outside scene window." ;
            EXPECT_TRUE(scene_window.contains(loc.br())) << "BR outside scene window.";

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}
<commit_msg>address low coverage lines in MNIST reader classes<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/io/readmnist.h"

#include "elm/ts/ts.h"          ///< custom assertions

#include <boost/filesystem.hpp>

#include "elm/core/exception.h"
#include "elm/io/binary.h"      ///< determine and swap endianness

using namespace std;
namespace bfs=boost::filesystem; // use alias
using namespace elm;

class FakeMNISTLabelsWriter {

public:

    static const int NB_ITEMS = 10;

    virtual ~FakeMNISTLabelsWriter()
    {
    }

    FakeMNISTLabelsWriter(const bfs::path& p)
        : path_(p)
    {
    }

    /**
     * @brief Save fake data to file
     * magic number
     * total no. of items
     * series label values [0,10)
     */
    virtual void Save(int magic_number)
    {
        SaveHeader(magic_number);
        SaveItems();
        out_.close();
    }

    void WriteInt(int n)
    {
        if(IS_32_LITTLE_ENDIAN) { elm::SwapEndian(&n); }
        out_.write(reinterpret_cast<char*>(&n), sizeof(int32_t));
    }

protected:

    virtual void SaveHeader(int magic_number)
    {
        if(out_.is_open()) {

            out_.close();
        }
        out_.open(path_.string().c_str(), ios::out | ios::binary);
        if(!out_.is_open()) {

            stringstream s;
            s << "Faied to write test file (" << path_ << ").";
            ELM_THROW_FILEIO_ERROR(s.str());
        }

        WriteInt(magic_number);
        WriteInt(NB_ITEMS);
    }

    virtual void SaveItems()
    {
        for(int i=0; i<NB_ITEMS; i++) {

            unsigned char next_label = static_cast<unsigned char>(i%10);
            out_.write(reinterpret_cast<char*>(&next_label), sizeof(unsigned char));
        }
    }

    bfs::path path_;
    ofstream out_;
};

/**
 * @brief class for testing ReadMNISTLabels
 * Fake data is written to disk first, then removed after last test
 */
class ReadMNISTLabelsTest : public testing::Test
{
protected:
    static void SetUpTestCase()
    {
        bfs::create_directory(test_data_dir_);
        FakeMNISTLabelsWriter writer(test_data_path_);

        writer.Save(ReadMNISTLabels().MagicNumber());
    }

    static void TearDownTestCase()
    {
        if(bfs::is_directory(test_data_dir_)) {

            bfs::remove_all(test_data_dir_);
        }
    }

    static const bfs::path test_data_dir_;
    static const bfs::path test_data_path_;
};
const bfs::path ReadMNISTLabelsTest::test_data_dir_("tmp_ReadMNISTFileTest");
const bfs::path ReadMNISTLabelsTest::test_data_path_(test_data_dir_/"fake_data.tmp");

TEST_F(ReadMNISTLabelsTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTLabels().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTLabelsTest, ReadHeader)
{
    const int N = FakeMNISTLabelsWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTLabels().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTLabelsTest, ReadHeader_repeated)
{
    const int N = FakeMNISTLabelsWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTLabels().ReadHeader(test_data_path_.string().c_str()));
    EXPECT_EQ(N, ReadMNISTLabels().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTLabelsTest, Next)
{
    ReadMNISTLabels to;
    const int N = to.ReadHeader(test_data_path_.string().c_str());

    EXPECT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            int label = static_cast<int>(to.Next().at<unsigned char>(0));
            EXPECT_EQ(label, i%N);

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTLabelsTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_labels_data_wrong_magic.tmp";
    FakeMNISTLabelsWriter writer(p);
    ReadMNISTLabels to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

class FakeMNISTImagesWriter : public FakeMNISTLabelsWriter
{

public:
    static const int NB_ITEMS = 10;
    static const int ROWS = 3;
    static const int COLS = 4;

    FakeMNISTImagesWriter(const bfs::path& p)
        : FakeMNISTLabelsWriter(p)
    {
    }

    /**
     * @brief Save fake data to file
     * magic number
     * total no. of items
     * series label values [0,10)
     */
    void SaveHeader(int magic_number)
    {
        FakeMNISTLabelsWriter::SaveHeader(magic_number);
        WriteInt(ROWS);
        WriteInt(COLS);
    }

    virtual void SaveItems()
    {
        for(int i=0; i<NB_ITEMS; i++) {

            unsigned char c = static_cast<unsigned char>(i % 255);
            cv::Mat next_img = cv::Mat(ROWS, COLS, CV_8UC1, c);
            out_.write(reinterpret_cast<char*>(next_img.data), sizeof(unsigned char)*next_img.total());
        }
    }

protected:
};

class ReadMNISTImagesTest : public ReadMNISTLabelsTest
{
protected:
    static void SetUpTestCase()
    {
        ReadMNISTLabelsTest::SetUpTestCase();

        FakeMNISTImagesWriter writer(test_data_path_);
        writer.Save(ReadMNISTImages().MagicNumber());
    }
};

TEST_F(ReadMNISTImagesTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTImages().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTest, ReadHeader)
{
    const int N = FakeMNISTImagesWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTImages().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTImagesTest, Next)
{
    ReadMNISTImages to;
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    const int ROWS = FakeMNISTImagesWriter::ROWS;
    const int COLS = FakeMNISTImagesWriter::COLS;

    EXPECT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            cv::Mat img = to.Next();
            EXPECT_MAT_DIMS_EQ(img, cv::Mat(ROWS, COLS, CV_8UC1));
            int sum = cv::sum(img)(0);
            sum /= (ROWS*COLS);
            EXPECT_EQ(sum, static_cast<unsigned char>(i%255));

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTImagesTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_images_data_wrong_magic.tmp";
    FakeMNISTImagesWriter writer(p);
    ReadMNISTImages to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

class ReadMNISTImagesTranslTest : public ReadMNISTImagesTest
{
protected:
    ReadMNISTImagesTransl to_; ///< test object
};

//class FakeMNISTImagesTranslWriter : public FakeMNISTImagesWriter
//{
//public:
//    FakeMNISTImagesTranslWriter(const bfs::path& p)
//        : FakeMNISTImagesWriter(p)
//    {
//        ;
//    }

//    virtual void SaveItems()
//    {

//    }
//};

TEST_F(ReadMNISTImagesTranslTest, WrongPath)
{
    EXPECT_THROW(ReadMNISTImagesTransl().ReadHeader("foo.bar"), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTranslTest, SceneDims)
{
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(1, 0), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(0, 1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(-1, 1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(1, -1), ExceptionBadDims);
    EXPECT_THROW(ReadMNISTImagesTransl().SceneDims(-1, -1), ExceptionBadDims);
    EXPECT_NO_THROW(ReadMNISTImagesTransl().SceneDims(1, 1));
}

TEST_F(ReadMNISTImagesTranslTest, ReadHeadersceneDims_too_small)
{
    ReadMNISTImagesTransl to; ///< test object

    EXPECT_NO_THROW(to.SceneDims(2, 2));
    EXPECT_THROW(to.ReadHeader(test_data_path_.string().c_str()), ExceptionBadDims);
}

TEST_F(ReadMNISTImagesTranslTest, ReadHeader)
{
    const int N = FakeMNISTImagesWriter::NB_ITEMS;
    EXPECT_EQ(N, ReadMNISTImagesTransl().ReadHeader(test_data_path_.string().c_str()));
}

TEST_F(ReadMNISTImagesTranslTest, Invalid)
{
    bfs::path p = test_data_dir_/"fake_images_data_wrong_magic.tmp";
    FakeMNISTImagesWriter writer(p);
    ReadMNISTImagesTransl to;
    writer.Save(to.MagicNumber()+5);
    EXPECT_THROW(to.ReadHeader(p.string().c_str()), ExceptionFileIOError);
}

TEST_F(ReadMNISTImagesTranslTest, EndOfFile)
{
    ReadMNISTImagesTransl to;
    to.SceneDims(20, 10);
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    ASSERT_GT(N, 0);

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            to.Next();
            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}

TEST_F(ReadMNISTImagesTranslTest, NextAndLocation)
{
    ReadMNISTImagesTransl to;
    to.SceneDims(20, 10);
    const int N = to.ReadHeader(test_data_path_.string().c_str());
    ASSERT_GT(N, 0);
    const int ROWS = FakeMNISTImagesWriter::ROWS;
    const int COLS = FakeMNISTImagesWriter::COLS;

    for(int i=0; i<N*2; i++) {

        if(i<N) {

            EXPECT_FALSE(to.IS_EOF());
            cv::Mat scene_img = to.Next();
            EXPECT_MAT_DIMS_EQ(scene_img, cv::Size2i(10, 20));

            cv::Rect2i loc = to.Location();

            EXPECT_EQ(loc.width, COLS);
            EXPECT_EQ(loc.height, ROWS);
            cv::Rect scene_window(cv::Point2i(0, 0), scene_img.size());
            EXPECT_TRUE(scene_window.contains(loc.tl())) << "TL outside scene window." ;
            EXPECT_TRUE(scene_window.contains(loc.br())) << "BR outside scene window.";

            if(i<N-1) { EXPECT_FALSE(to.IS_EOF()); }
            else { EXPECT_TRUE(to.IS_EOF()); }
        }
        else { EXPECT_TRUE(to.IS_EOF()); }
    }
}
<|endoftext|>


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

#include "modules/map/relative_map/navigation_lane.h"

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"

namespace apollo {
namespace relative_map {
namespace {

double GetDistance(const common::VehicleState& adc_state,
                   const common::PathPoint& p) {
  return std::hypot(adc_state.x() - p.x(), adc_state.y() - p.y());
}
}
using apollo::perception::PerceptionObstacles;
using apollo::common::VehicleStateProvider;

bool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {
  // udpate perception_obstacles_
  perception_obstacles_ = perception_obstacles;
  if (!perception_obstacles.has_lane_marker()) {
    AERROR << "No lane marker in perception_obstacles.";
    return false;
  }

  // update adc_state_ from VehicleStateProvider
  adc_state_ = VehicleStateProvider::instance()->vehicle_state();

  navigation_path_.Clear();
  auto* path = navigation_path_.mutable_path();
  const auto& lane_marker = perception_obstacles_.lane_marker();

  const double kQualityThreshold = 0.5;
  if (navigation_info_.navigation_path_size() > 0 &&
      std::fmax(lane_marker.left_lane_marker().quality(),
                lane_marker.right_lane_marker().quality()) <
          kQualityThreshold) {
    ConvertNavigationLineToPath();
  } else {
    ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);
  }
  return true;
}

double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,
                                               const double c2, const double c3,
                                               const double z) const {
  return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;
}

void NavigationLane::ConvertNavigationLineToPath() {
  if (navigation_info_.navigation_path_size() == 0 ||
      !navigation_info_.navigation_path(0).has_path() ||
      navigation_info_.navigation_path(0).path().path_point_size() == 0) {
    // path is empty
    return;
  }
  navigation_path_.Clear();
  auto* curr_path = navigation_path_.mutable_path();
  UpdateProjectionIndex();

  // TODO(All): support multiple navigation path
  // only support 1 navigation path
  const auto& path = navigation_info_.navigation_path(0).path();
  int curr_project_index = last_project_index_;
  for (int i = curr_project_index; i < path.path_point_size(); ++i) {
    auto* point = curr_path->add_path_point();
    point->CopyFrom(path.path_point(i));
    const double accumulated_s =
        path.path_point(i).s() - path.path_point(curr_project_index).s();
    point->set_s(accumulated_s);
  }
}

// project adc_state_ onto path
void NavigationLane::UpdateProjectionIndex() {
  // TODO(All): support multiple navigation path
  // only support 1 navigation path
  const auto& path = navigation_info_.navigation_path(0).path();
  int index = 0;
  double min_d = std::numeric_limits<double>::max();
  for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {
    const double d = GetDistance(adc_state_, path.path_point(i));
    if (d < min_d) {
      min_d = d;
      index = i;
    }
    const double kMaxDistance = 50.0;
    if (d > kMaxDistance) {
      break;
    }
  }
  last_project_index_ = index;
}

void NavigationLane::ConvertLaneMarkerToPath(
    const perception::LaneMarkers& lane_marker, common::Path* path) {
  const auto& left_lane = lane_marker.left_lane_marker();
  const auto& right_lane = lane_marker.right_lane_marker();

  const double unit_z = 1.0;
  double accumulated_s = 0.0;
  for (double z = 0;
       z <= std::fmin(left_lane.view_range(), right_lane.view_range());
       z += unit_z) {
    const double x_l = EvaluateCubicPolynomial(
        left_lane.c0_position(), left_lane.c1_heading_angle(),
        left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);
    const double x_r = EvaluateCubicPolynomial(
        right_lane.c0_position(), right_lane.c1_heading_angle(),
        right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);

    double x1 = 0.0;
    double y1 = 0.0;
    // rotate from vehicle axis to x-y axis
    common::math::RotateAxis(-adc_state_.heading(), z, (x_l + x_r) / 2.0, &x1,
                             &y1);

    // shift to get point on x-y axis
    x1 += adc_state_.x();
    y1 += adc_state_.y();

    auto* point = path->add_path_point();
    point->set_x(x1);
    point->set_y(y1);
    point->set_s(accumulated_s);
    accumulated_s += std::hypot(x1, y1);
  }
}

}  // namespace relative_map
}  // namespace apollo
<commit_msg>Update navigation_lane.cc<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/map/relative_map/navigation_lane.h"

#include <limits>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"

namespace apollo {
namespace relative_map {
namespace {

double GetDistance(const common::VehicleState& adc_state,
                   const common::PathPoint& p) {
  return std::hypot(adc_state.x() - p.x(), adc_state.y() - p.y());
}
}
using apollo::perception::PerceptionObstacles;
using apollo::common::VehicleStateProvider;

bool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {
  // udpate perception_obstacles_
  perception_obstacles_ = perception_obstacles;
  if (!perception_obstacles.has_lane_marker()) {
    AERROR << "No lane marker in perception_obstacles.";
    return false;
  }

  // update adc_state_ from VehicleStateProvider
  adc_state_ = VehicleStateProvider::instance()->vehicle_state();

  navigation_path_.Clear();
  auto* path = navigation_path_.mutable_path();
  const auto& lane_marker = perception_obstacles_.lane_marker();

  const double kQualityThreshold = 0.5;
  if (navigation_info_.navigation_path_size() > 0 &&
      std::fmax(lane_marker.left_lane_marker().quality(),
                lane_marker.right_lane_marker().quality()) <
          kQualityThreshold) {
    ConvertNavigationLineToPath();
  } else {
    ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);
  }
  return true;
}

double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,
                                               const double c2, const double c3,
                                               const double z) const {
  return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;
}

void NavigationLane::ConvertNavigationLineToPath() {
  if (navigation_info_.navigation_path_size() == 0 ||
      !navigation_info_.navigation_path(0).has_path() ||
      navigation_info_.navigation_path(0).path().path_point_size() == 0) {
    // path is empty
    return;
  }
  navigation_path_.Clear();
  auto* curr_path = navigation_path_.mutable_path();
  UpdateProjectionIndex();

  // TODO(All): support multiple navigation path
  // only support 1 navigation path
  const auto& path = navigation_info_.navigation_path(0).path();
  int curr_project_index = last_project_index_;
  for (int i = curr_project_index; i < path.path_point_size(); ++i) {
    auto* point = curr_path->add_path_point();
    point->CopyFrom(path.path_point(i));
    const double accumulated_s =
        path.path_point(i).s() - path.path_point(curr_project_index).s();
    point->set_s(accumulated_s);
  }
}

// project adc_state_ onto path
void NavigationLane::UpdateProjectionIndex() {
  // TODO(All): support multiple navigation path
  // only support 1 navigation path
  const auto& path = navigation_info_.navigation_path(0).path();
  int index = 0;
  double min_d = std::numeric_limits<double>::max();
  for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {
    const double d = GetDistance(adc_state_, path.path_point(i));
    if (d < min_d) {
      min_d = d;
      index = i;
    }
    const double kMaxDistance = 50.0;
    if (d > kMaxDistance) {
      break;
    }
  }
  last_project_index_ = index;
}

void NavigationLane::ConvertLaneMarkerToPath(
    const perception::LaneMarkers& lane_marker, common::Path* path) {
  const auto& left_lane = lane_marker.left_lane_marker();
  const auto& right_lane = lane_marker.right_lane_marker();

  const double unit_z = 1.0;
  double accumulated_s = 0.0;
  for (double z = 0;
       z <= std::fmin(left_lane.view_range(), right_lane.view_range());
       z += unit_z) {
    const double x_l = EvaluateCubicPolynomial(
        left_lane.c0_position(), left_lane.c1_heading_angle(),
        left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);
    const double x_r = EvaluateCubicPolynomial(
        right_lane.c0_position(), right_lane.c1_heading_angle(),
        right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);

    double x1 = 0.0;
    double y1 = 0.0;
    // rotate from vehicle axis to x-y axis
    common::math::RotateAxis(-adc_state_.heading(), z, (x_l + x_r) / 2.0, &x1,
                             &y1);

    // shift to get point on x-y axis
    x1 += adc_state_.x();
    y1 += adc_state_.y();

    auto* point = path->add_path_point();
    point->set_x(x1);
    point->set_y(y1);
    point->set_s(accumulated_s);
    accumulated_s += std::hypot(x1, y1);
  }
}

}  // namespace relative_map
}  // namespace apollo
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRawImageFileReader.h"
#include "mitkITKImageImport.h"

#include <itkImage.h>
#include <itkRawImageIO.h>
#include <itkImageFileReader.h>

mitk::RawImageFileReader::RawImageFileReader()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}

mitk::RawImageFileReader::~RawImageFileReader()
{
}

void mitk::RawImageFileReader::SetDimensions(unsigned int i, unsigned int dim)
{
  if ( i > 2 ) return;

  this->Modified();               // TODO: this order (first modified, then set the variable) is intended??
  m_Dimensions[i] = dim;
}

unsigned int mitk::RawImageFileReader::GetDimensions(unsigned int i) const
{
  if ( i > 2 ) return 0;

  return m_Dimensions[i];
}

bool mitk::RawImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
  // First check the extension
  if(  filename == "" )
    return false;

  // check if image is serie
  if( filePattern != "" && filePrefix != "" )
    return false;

  return true;
}

void mitk::RawImageFileReader::GenerateData()
{
  mitk::Image::Pointer output = this->GetOutput();

  if (this->GetOutput()==NULL)
  {
    std::cout << "Error" << std::endl;
  }

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "File Type not supported!" );
    return ;
  }

  if ( m_FileName == "--no-server" )
  {
    return ;
  }

  // check file dimensionality and pixel type and perform reading according to it
  if (m_Dimensionality == 2)
  {
         if (m_PixelType == SSHORT) TypedGenerateData<signed short int, 2 >();
    else if (m_PixelType == USHORT) TypedGenerateData<unsigned short int, 2 >();
    else if (m_PixelType == UINT)   TypedGenerateData<unsigned int, 2 >();
    else if (m_PixelType == SINT)   TypedGenerateData<signed int, 2 >();
    else if (m_PixelType == FLOAT)  TypedGenerateData<float, 2 >();
    else if (m_PixelType == DOUBLE) TypedGenerateData<double, 2 >();
    else
    {
      std::cout << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl;
      return;
    }
   }
  else if (m_Dimensionality==3)
  {
         if (m_PixelType == SSHORT) TypedGenerateData<signed short int, 3 >();
    else if (m_PixelType == USHORT) TypedGenerateData<unsigned short int, 3 >();
    else if (m_PixelType == UINT)   TypedGenerateData<unsigned int, 3 >();
    else if (m_PixelType == SINT)   TypedGenerateData<signed int, 3 >();
    else if (m_PixelType == FLOAT)  TypedGenerateData<float, 3 >();
    else if (m_PixelType == DOUBLE) TypedGenerateData<double, 3 >();
    else
    {
      std::cout << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl;
      return;
    }
  }
  else
  {
    std::cout << "Error while reading raw file: Dimensionality not supported" << std::endl;
    return;

  }

  std::cout << "...reading raw finished!" << std::endl;
}

template < typename TPixel, unsigned int VImageDimensions >
void mitk::RawImageFileReader::TypedGenerateData()
{
  mitk::Image::Pointer output = this->GetOutput();

  if (this->GetOutput()==NULL)
  {
    std::cout << "Error" << std::endl;
  }

  std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "File Type not supported!" );
    return ;
  }

  if ( m_FileName == "--no-server" )
  {
    return ;
  }

  typedef itk::Image< TPixel, VImageDimensions > ImageType;
  typedef itk::ImageFileReader< ImageType > ReaderType;
  typedef itk::RawImageIO< TPixel, VImageDimensions >  IOType;

  typename ReaderType::Pointer reader = ReaderType::New();
  typename IOType::Pointer io = IOType::New();

  for (unsigned short int dim = 0; dim < VImageDimensions; ++dim)
  {
    io->SetDimensions(dim, m_Dimensions[dim] );
  }

  if (m_Endianity == LITTLE)
  {
    io->SetByteOrderToLittleEndian();
  }
  else if (m_Endianity == BIG)
  {
    io->SetByteOrderToBigEndian();
  }
  else
  {
    std::cout << "Warning: endianity not properly set. Resulting image might be incorrect" << std::cout;
  }

  reader->SetImageIO( io );
  reader->SetFileName(m_FileName.c_str());

  try
  {
    reader->Update();
  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr<<"An error occurred during the reading process: ";
    std::cout << err << std::endl;
  }

  mitk::Image::Pointer image = mitk::Image::New();
  mitk::CastToMitkImage(reader->GetOutput(), image);
  output->Initialize( image );
  output->SetVolume(  reader->GetOutput()->GetBufferPointer());
}

<commit_msg>minor changes by Xabier Artaechevarria Artieda<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRawImageFileReader.h"
#include "mitkITKImageImport.h"

#include <itkImage.h>
#include <itkRawImageIO.h>
#include <itkImageFileReader.h>

mitk::RawImageFileReader::RawImageFileReader()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}

mitk::RawImageFileReader::~RawImageFileReader()
{
}

void mitk::RawImageFileReader::SetDimensions(unsigned int i, unsigned int dim)
{
  if ( i > 2 ) return;

  this->Modified();               // TODO: this order (first modified, then set the variable) is intended??
  m_Dimensions[i] = dim;
}

unsigned int mitk::RawImageFileReader::GetDimensions(unsigned int i) const
{
  if ( i > 2 ) return 0;

  return m_Dimensions[i];
}

bool mitk::RawImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
  // First check the extension
  if(  filename == "" )
    return false;

  // check if image is serie
  if( filePattern != "" && filePrefix != "" )
    return false;

  return true;
}

void mitk::RawImageFileReader::GenerateData()
{
  mitk::Image::Pointer output = this->GetOutput();

  if (this->GetOutput()==NULL)
  {
    std::cout << "Error" << std::endl;
  }

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "File Type not supported!" );
    return ;
  }

  if ( m_FileName == "--no-server" )
  {
    return ;
  }

  // check file dimensionality and pixel type and perform reading according to it
  if (m_Dimensionality == 2)
  {
         if (m_PixelType == SSHORT) TypedGenerateData<signed short int, 2 >();
    else if (m_PixelType == USHORT) TypedGenerateData<unsigned short int, 2 >();
    else if (m_PixelType == UINT)   TypedGenerateData<unsigned int, 2 >();
    else if (m_PixelType == SINT)   TypedGenerateData<signed int, 2 >();
    else if (m_PixelType == FLOAT)  TypedGenerateData<float, 2 >();
    else if (m_PixelType == DOUBLE) TypedGenerateData<double, 2 >();
    else
    {
      std::cout << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl;
      return;
    }
   }
  else if (m_Dimensionality==3)
  {
         if (m_PixelType == SSHORT) TypedGenerateData<signed short int, 3 >();
    else if (m_PixelType == USHORT) TypedGenerateData<unsigned short int, 3 >();
    else if (m_PixelType == UINT)   TypedGenerateData<unsigned int, 3 >();
    else if (m_PixelType == SINT)   TypedGenerateData<signed int, 3 >();
    else if (m_PixelType == FLOAT)  TypedGenerateData<float, 3 >();
    else if (m_PixelType == DOUBLE) TypedGenerateData<double, 3 >();
    else
    {
      std::cout << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl;
      return;
    }
  }
  else
  {
    std::cout << "Error while reading raw file: Dimensionality not supported" << std::endl;
    return;

  }

  std::cout << "...reading raw finished!" << std::endl;
}

template < typename TPixel, unsigned int VImageDimensions >
void mitk::RawImageFileReader::TypedGenerateData()
{
  mitk::Image::Pointer output = this->GetOutput();

  if (this->GetOutput()==NULL)
  {
    std::cout << "Error" << std::endl;
  }

  std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    itkWarningMacro( << "File Type not supported!" );
    return ;
  }

  if ( m_FileName == "--no-server" )
  {
    return ;
  }

  typedef itk::Image< TPixel, VImageDimensions > ImageType;
  typedef itk::ImageFileReader< ImageType > ReaderType;
  typedef itk::RawImageIO< TPixel, VImageDimensions >  IOType;

  typename ReaderType::Pointer reader = ReaderType::New();
  typename IOType::Pointer io = IOType::New();

  io->SetFileDimensionality(VImageDimensions);

  for (unsigned short int dim = 0; dim < VImageDimensions; ++dim)
  {
    io->SetDimensions(dim, m_Dimensions[dim] );
  }

  if (m_Endianity == LITTLE)
  {
    io->SetByteOrderToLittleEndian();
  }
  else if (m_Endianity == BIG)
  {
    io->SetByteOrderToBigEndian();
  }
  else
  {
    std::cout << "Warning: endianity not properly set. Resulting image might be incorrect" << std::cout;
  }

  reader->SetImageIO( io );
  reader->SetFileName(m_FileName.c_str());

  try
  {
    reader->Update();
  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr<<"An error occurred during the raw image reading process: ";
    std::cout << err << std::endl;
  }

  mitk::Image::Pointer image = mitk::Image::New();
  mitk::CastToMitkImage(reader->GetOutput(), image);
  output->Initialize( image );
  output->SetVolume(  reader->GetOutput()->GetBufferPointer());
}

<|endoftext|>


<commit_before>/* Copyright (C) 2014 INRA
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <efyj/model.hpp>
#include <efyj/solver-basic.hpp>
#include <efyj/solver-hash.hpp>
#include <efyj/solver-bigmem.hpp>
#include <efyj/solver-gmp.hpp>

#include <sstream>
#include <cstdlib>

#if defined(__unix__)
#include <unistd.h>
#elif defined(__WIN32__)
#include <io.h>
#include <stdio.h>
#endif

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

TEST_CASE("test empty object equality", "[model]")
{
    efyj::Model x1;
    efyj::Model x2;

    REQUIRE(x1 == x2);
}

TEST_CASE("test empty object read/write", "[model]")
{
    efyj::Model x1, x2;

    {
        std::string result;
        {
            std::ostringstream os;
            os << x1;
            result = os.str();
        }

        {
            std::istringstream is(result);
            is >> x2;
        }
    }

    bool is_equal = x1 == x2;
    REQUIRE(is_equal == true);
}

#if defined EXAMPLES_DIR && defined __unix__
#include <unistd.h>

TEST_CASE("test classic Model file", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    std::vector <std::string> filepaths = { "Car.dxi", "Employ.dxi",
        "Enterprise.dxi", "IPSIM_PV_simulation1-1.dxi", "Nursery.dxi",
        "Shuttle.dxi"};

    for (const auto& filepath : filepaths) {
        std::ifstream is(filepath);
        REQUIRE(is.is_open());

        efyj::Model dex;
        REQUIRE_NOTHROW(is >> dex);
    }
}

TEST_CASE("test car.dxi load/save/load via sstream", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model car;
    std::stringstream ss;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);
        REQUIRE_NOTHROW(ss << car);
    }

    efyj::Model car2;
    REQUIRE_NOTHROW(ss >> car2);

    REQUIRE(car == car2);
}

#if (GCC_VERSION >= 40900) or (defined __clang__)
std::ofstream make_temporary(std::string& name, bool remove = true)
{
    static const char *names[] = { "TMPDIR", "TMP", "TEMP" };
    static const int names_size = sizeof(names) / sizeof(names[0]);
    std::string filename;

    // TODO replace X with random bits
    // transform_if(...);

    for (int i = 0; i != names_size and filename.empty(); ++i)
        if (::getenv(names[i]))
            filename = ::getenv(names[i]);

    if (filename.empty())
        filename = "/tmp";

    filename += "/" + name;
    name = filename;
    std::ofstream os(filename);
    if (os && remove) {
#if defined(__unix__)
        ::unlink(filename.c_str());
#elif defined(__WIN32__)
        ::_unlink(filename.c_str());
#endif
    }

    return std::move(os);
}

TEST_CASE("test car.dxi load/save/load via file", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model car;
    std::string outputfile("CarXXXXXXXX.dxi");

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);

        std::ofstream os(make_temporary(outputfile, false));
        REQUIRE(os.is_open());
        REQUIRE_NOTHROW(os << car);
    }

    efyj::Model car2;

    {
        std::ifstream is(outputfile);
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car2);
    }

    REQUIRE(car == car2);
}
#endif

TEST_CASE("test Car.dxi", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model car;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);
    }

    REQUIRE(car.attributes.size() == 10u);
    REQUIRE(car.child);
    REQUIRE(car.child->name == "CAR");
    REQUIRE(car.child->children.size() == 2u);
    REQUIRE(car.child->children[0]->name == "PRICE");
    REQUIRE(car.child->children[0]->children.size() == 2u);
    REQUIRE(car.child->children[0]->children[0]->name == "BUY.PRICE");
    REQUIRE(car.child->children[0]->children[0]->children.empty() == true);
    REQUIRE(car.child->children[0]->children[1]->name == "MAINT.PRICE");
    REQUIRE(car.child->children[0]->children[1]->children.empty() == true);
    REQUIRE(car.child->children[1]->name == "TECH.CHAR.");
    REQUIRE(car.child->children[1]->children.size() == 2u);
    REQUIRE(car.child->children[1]->children[0]->name == "COMFORT");
    REQUIRE(car.child->children[1]->children[0]->children.size() == 3u);
    REQUIRE(car.child->children[1]->children[0]->children[0]->name == "#PERS");
    REQUIRE(car.child->children[1]->children[0]->children[0]->children.empty() == true);
    REQUIRE(car.child->children[1]->children[0]->children[1]->name == "#DOORS");
    REQUIRE(car.child->children[1]->children[0]->children[1]->children.empty() == true);
    REQUIRE(car.child->children[1]->children[0]->children[2]->name == "LUGGAGE");
    REQUIRE(car.child->children[1]->children[0]->children[2]->children.empty() == true);
    REQUIRE(car.child->children[1]->children[1]->name == "SAFETY");
    REQUIRE(car.child->children[1]->children[1]->children.empty() == true);
}

TEST_CASE("test multiple Car.Model", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model src, dst;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> src);
    }

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> dst);
    }

    REQUIRE(src == dst);

    efyj::Model dst2;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> dst2);
    }

    REQUIRE(dst2 == dst);
    REQUIRE(dst2.child);
    dst2.child->name = "change";

    REQUIRE(dst2 != dst);
}

TEST_CASE("test solver Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);
}

TEST_CASE("test basic solver for Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);

    efyj::Vector opt_v3(6); opt_v3 << 1, 2, 2, 2, 2, 2;
    efyj::Vector opt_v2(6); opt_v2 << 1, 1, 2, 2, 2, 1;

    {
        efyj::solver_basic s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }

    {
        efyj::solver_hash s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }

    {
        efyj::solver_bigmem s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }

    {
        efyj::solver_bigmem s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }
}

TEST_CASE("test basic solver for Enterprise", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Enterprise.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    efyj::Vector opt_v(12); opt_v << 2, 0, 0, 0, 2, 0, 0, 0, 1, 1, 1, 1;

    efyj::solver_basic si(model);
    REQUIRE(si.solve(opt_v) == 1);

    efyj::solver_bigmem sb(model);
    REQUIRE(sb.solve(opt_v) == 1);

    efyj::solver_hash sh(model);
    REQUIRE(sh.solve(opt_v) == 1);
}

TEST_CASE("test basic solver for IPSIM_PV_simulation1-1", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("IPSIM_PV_simulation1-1.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    efyj::Vector opt_v(14); opt_v << 2, 0, 0, 1, 0, 1, 1, 0, 0, 0, 2, 0, 0, 1;

    efyj::solver_basic si(model);
    REQUIRE(si.solve(opt_v) == 6);

    efyj::solver_bigmem sb(model);
    REQUIRE(sb.solve(opt_v) == 6);

    efyj::solver_hash sh(model);
    REQUIRE(sh.solve(opt_v) == 6);
}

TEST_CASE("test multiple solver for Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);

//     const std::string opt_s3 = "1*2222";
//     const std::string opt_s2 = "122**1";

//     {
//         efyj::solver_basic s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }

//     {
//         efyj::solver_hash s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }

//     {
//         efyj::solver_bigmem s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }
}

#endif
<commit_msg>test: mpz_class can not be use into REQUIRE catch's macro<commit_after>/* Copyright (C) 2014 INRA
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <efyj/model.hpp>
#include <efyj/solver-basic.hpp>
#include <efyj/solver-hash.hpp>
#include <efyj/solver-bigmem.hpp>
#include <efyj/solver-gmp.hpp>

#include <sstream>
#include <cstdlib>

#if defined(__unix__)
    #include <unistd.h>
#elif defined(__WIN32__)
    #include <io.h>
    #include <stdio.h>
#endif

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

TEST_CASE("test empty object equality", "[model]")
{
    efyj::Model x1;
    efyj::Model x2;
    REQUIRE(x1 == x2);
}

TEST_CASE("test empty object read/write", "[model]")
{
    efyj::Model x1, x2;
    {
        std::string result;
        {
            std::ostringstream os;
            os << x1;
            result = os.str();
        }
        {
            std::istringstream is(result);
            is >> x2;
        }
    }
    bool is_equal = x1 == x2;
    REQUIRE(is_equal == true);
}

#if defined EXAMPLES_DIR && defined __unix__
#include <unistd.h>

TEST_CASE("test classic Model file", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    std::vector <std::string> filepaths = { "Car.dxi", "Employ.dxi",
                                            "Enterprise.dxi", "IPSIM_PV_simulation1-1.dxi", "Nursery.dxi",
                                            "Shuttle.dxi"
                                          };

    for (const auto &filepath : filepaths) {
        std::ifstream is(filepath);
        REQUIRE(is.is_open());
        efyj::Model dex;
        REQUIRE_NOTHROW(is >> dex);
    }
}

TEST_CASE("test car.dxi load/save/load via sstream", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model car;
    std::stringstream ss;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);
        REQUIRE_NOTHROW(ss << car);
    }
    efyj::Model car2;
    REQUIRE_NOTHROW(ss >> car2);
    REQUIRE(car == car2);
}

#if (GCC_VERSION >= 40900) or (defined __clang__)
std::ofstream make_temporary(std::string &name, bool remove = true)
{
    static const char *names[] = { "TMPDIR", "TMP", "TEMP" };
    static const int names_size = sizeof(names) / sizeof(names[0]);
    std::string filename;

    // TODO replace X with random bits
    // transform_if(...);

    for (int i = 0; i != names_size and filename.empty(); ++i)
        if (::getenv(names[i]))
            filename = ::getenv(names[i]);

    if (filename.empty())
        filename = "/tmp";

    filename += "/" + name;
    name = filename;
    std::ofstream os(filename);

    if (os && remove) {
#if defined(__unix__)
        ::unlink(filename.c_str());
#elif defined(__WIN32__)
        ::_unlink(filename.c_str());
#endif
    }

    return std::move(os);
}

TEST_CASE("test car.dxi load/save/load via file", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model car;
    std::string outputfile("CarXXXXXXXX.dxi");
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);
        std::ofstream os(make_temporary(outputfile, false));
        REQUIRE(os.is_open());
        REQUIRE_NOTHROW(os << car);
    }
    efyj::Model car2;
    {
        std::ifstream is(outputfile);
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car2);
    }
    REQUIRE(car == car2);
}
#endif

TEST_CASE("test Car.dxi", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model car;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> car);
    }
    REQUIRE(car.attributes.size() == 10u);
    REQUIRE(car.child);
    REQUIRE(car.child->name == "CAR");
    REQUIRE(car.child->children.size() == 2u);
    REQUIRE(car.child->children[0]->name == "PRICE");
    REQUIRE(car.child->children[0]->children.size() == 2u);
    REQUIRE(car.child->children[0]->children[0]->name == "BUY.PRICE");
    REQUIRE(car.child->children[0]->children[0]->children.empty() == true);
    REQUIRE(car.child->children[0]->children[1]->name == "MAINT.PRICE");
    REQUIRE(car.child->children[0]->children[1]->children.empty() == true);
    REQUIRE(car.child->children[1]->name == "TECH.CHAR.");
    REQUIRE(car.child->children[1]->children.size() == 2u);
    REQUIRE(car.child->children[1]->children[0]->name == "COMFORT");
    REQUIRE(car.child->children[1]->children[0]->children.size() == 3u);
    REQUIRE(car.child->children[1]->children[0]->children[0]->name == "#PERS");
    REQUIRE(car.child->children[1]->children[0]->children[0]->children.empty() ==
            true);
    REQUIRE(car.child->children[1]->children[0]->children[1]->name == "#DOORS");
    REQUIRE(car.child->children[1]->children[0]->children[1]->children.empty() ==
            true);
    REQUIRE(car.child->children[1]->children[0]->children[2]->name == "LUGGAGE");
    REQUIRE(car.child->children[1]->children[0]->children[2]->children.empty() ==
            true);
    REQUIRE(car.child->children[1]->children[1]->name == "SAFETY");
    REQUIRE(car.child->children[1]->children[1]->children.empty() == true);
}

TEST_CASE("test multiple Car.Model", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model src, dst;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> src);
    }
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> dst);
    }
    REQUIRE(src == dst);
    efyj::Model dst2;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> dst2);
    }
    REQUIRE(dst2 == dst);
    REQUIRE(dst2.child);
    dst2.child->name = "change";
    REQUIRE(dst2 != dst);
}

TEST_CASE("test solver Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model model;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }
    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);
}

TEST_CASE("test basic solver for Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);
    efyj::Model model;
    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }
    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);
    efyj::Vector opt_v3(6); opt_v3 << 1, 2, 2, 2, 2, 2;
    efyj::Vector opt_v2(6); opt_v2 << 1, 1, 2, 2, 2, 1;
    {
        efyj::solver_basic s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }
    {
        efyj::solver_hash s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }
    {
        efyj::solver_bigmem s(model);
        REQUIRE(s.solve(opt_v3) == 3);
        REQUIRE(s.solve(opt_v2) == 2);
    }
    {
        efyj::solver_gmp s(model);

        bool equal;

        equal = (s.solve(opt_v3) == 3);
        REQUIRE(equal);

        equal = (s.solve(opt_v2) == 2);
        REQUIRE(equal);
    }
}

TEST_CASE("test basic solver for Enterprise", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Enterprise.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    efyj::Vector opt_v(12); opt_v << 2, 0, 0, 0, 2, 0, 0, 0, 1, 1, 1, 1;

    efyj::solver_basic si(model);
    REQUIRE(si.solve(opt_v) == 1);

    efyj::solver_bigmem sb(model);
    REQUIRE(sb.solve(opt_v) == 1);

    efyj::solver_hash sh(model);
    REQUIRE(sh.solve(opt_v) == 1);
}

TEST_CASE("test basic solver for IPSIM_PV_simulation1-1", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("IPSIM_PV_simulation1-1.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    efyj::Vector opt_v(14); opt_v << 2, 0, 0, 1, 0, 1, 1, 0, 0, 0, 2, 0, 0, 1;

    efyj::solver_basic si(model);
    REQUIRE(si.solve(opt_v) == 6);

    efyj::solver_bigmem sb(model);
    REQUIRE(sb.solve(opt_v) == 6);

    efyj::solver_hash sh(model);
    REQUIRE(sh.solve(opt_v) == 6);
}

TEST_CASE("test multiple solver for Car", "[model]")
{
    int ret = ::chdir(EXAMPLES_DIR);
    REQUIRE(ret == 0);

    efyj::Model model;

    {
        std::ifstream is("Car.dxi");
        REQUIRE(is.is_open());
        REQUIRE_NOTHROW(is >> model);
    }

    REQUIRE(model.problem_size == 972u);
    REQUIRE(model.basic_scale_number == 6u);
    REQUIRE(model.scale_number == 10u);
    REQUIRE(model.scalevalue_number == 19u);

//     const std::string opt_s3 = "1*2222";
//     const std::string opt_s2 = "122**1";

//     {
//         efyj::solver_basic s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }

//     {
//         efyj::solver_hash s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }

//     {
//         efyj::solver_bigmem s(model);
//         REQUIRE(s.solve(opt_s3) == efyj::result_type({0, 3}));
//         REQUIRE(s.solve(opt_s2) == efyj::result_type({0, 2, 3}));
//     }
}

#endif
<|endoftext|>


<commit_before>#ifndef EMULATOR_PLATFORM_SETUP_H
#define EMULATOR_PLATFORM_SETUP_H

#ifndef _CRT_SECURE_NO_WARNINGS
    #define _CRT_SECURE_NO_WARNINGS
#endif

/*
 * Platform specific emulator setup
 */
#if (defined(_WINDOWS) || defined(__APPLE__) || defined(__linux__) || defined(__MINGW32__)) && !defined(__ANDROID__)
//Open Graphics Library (Embedded Systems)
//#define OGLES
//#define OGLES_VERSION 2

//Open Graphics Library
#define OGL

//Direct3D9
//#define D3D9

#if defined(D3D9)
#define SDL2
#endif

#if defined(OGL)
#define SDL2
#define GLEW
#endif

#elif defined(__EMSCRIPTEN__)
#define OGLES
#define OGLES_VERSION (2)
#elif defined(__ANDROID__)
#define OGLES
#define OGLES_VERSION (3)
#if OGLES_VERSION == 2
#define ES2_SHADERS
#elif OGLES_VERSION == 3
#define ES3_SHADERS
#endif
#define SDL2
#elif defined(_XBOX)
#define XED3D
#endif

#if defined(GLEW)
#define GL_GLEXT_PROTOTYPES 1
#include <GL/glew.h>
#endif

/*
 * Emulator render options.
 */
#define RO_DOUBLE_BUFFERED

#if defined(__APPLE__) || defined(__EMSCRIPTEN__)
//#include <stddef.h>
#endif

/*
 * SDL.H inclusion.
 */

#if defined(__APPLE__)
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#elif defined(__EMSCRIPTEN__)
#include <SDL2/SDL.h>
#elif (defined(_WINDOWS) || defined(__MINGW32__) || defined(__linux__)) && !defined(__ANDROID__)
#include <SDL.h>
#elif defined (__ANDROID__)
#include <SDL.h>
#endif

#if defined (OGL)
#include <SDL_opengl.h>///@FIXME see mac!
#elif defined (OGLES)
#include <SDL_syswm.h>
#if OGLES_VERSION == 2
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#elif OGLES_VERSION == 3
#include <GLES3/gl3.h>
#endif
#include <EGL/egl.h>
#elif defined(D3D9)
#include <Windows.h>
#include <d3d9.h>
#elif defined(XED3D)
#include <xtl.h>
#if _XDK_VER != 21256
#error "Invalid XDK version"
#endif
#endif

#if !defined (__EMSCRIPTEN__)
//#include <SDL_gamecontroller.h>
#endif

#if defined(OGL)
#define TEXTURE_FORMAT GL_UNSIGNED_SHORT_1_5_5_5_REV
#elif defined(OGLES)
#define TEXTURE_FORMAT GL_UNSIGNED_SHORT_5_5_5_1
#endif

#endif<commit_msg>[Emu]: Fix PLATFORM_SETUP.H<commit_after>#ifndef EMULATOR_PLATFORM_SETUP_H
#define EMULATOR_PLATFORM_SETUP_H

#ifndef _CRT_SECURE_NO_WARNINGS
    #define _CRT_SECURE_NO_WARNINGS
#endif

/*
 * Platform specific emulator setup
 */
#if (defined(_WINDOWS) || defined(__APPLE__) || defined(__linux__) || defined(__MINGW32__)) && !defined(__ANDROID__)
//Open Graphics Library (Embedded Systems)
#define OGLES
#define OGLES_VERSION 3

//Open Graphics Library
//#define OGL

//Direct3D9
//#define D3D9

#if defined(D3D9)
#define SDL2
#endif

#if defined(OGL)
#define SDL2
#define GLEW
#endif

#elif defined(__EMSCRIPTEN__)
#define OGLES
#define OGLES_VERSION (2)
#elif defined(__ANDROID__)
#define OGLES
#define OGLES_VERSION (3)
#define SDL2
#elif defined(_XBOX)
#define XED3D
#endif
#if defined(OGLES)
#if OGLES_VERSION == 2
#define ES2_SHADERS
#elif OGLES_VERSION == 3
#define ES3_SHADERS
#endif
#endif

#if defined(GLEW)
#define GL_GLEXT_PROTOTYPES 1
#include <GL/glew.h>
#endif

/*
 * Emulator render options.
 */
#define RO_DOUBLE_BUFFERED

#if defined(__APPLE__) || defined(__EMSCRIPTEN__)
//#include <stddef.h>
#endif

/*
 * SDL.H inclusion.
 */

#if defined(__APPLE__)
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#elif defined(__EMSCRIPTEN__)
#include <SDL2/SDL.h>
#elif (defined(_WINDOWS) || defined(__MINGW32__) || defined(__linux__)) && !defined(__ANDROID__)
#include <SDL.h>
#elif defined (__ANDROID__)
#include <SDL.h>
#if (OGLES_VERSION == 3)
#include <GLES3/gl3.h>
#endif
#endif

#if defined (OGL)
#include <SDL_opengl.h>///@FIXME see mac!
#elif defined (OGLES)
#include <SDL_syswm.h>
#if OGLES_VERSION == 2
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#elif OGLES_VERSION == 3
#include <GLES3/gl3.h>
#endif
#include <EGL/egl.h>
#elif defined(D3D9)
#include <Windows.h>
#include <d3d9.h>
#elif defined(XED3D)
#include <xtl.h>
#if _XDK_VER != 21256
#error "Invalid XDK version"
#endif
#endif

#if !defined (__EMSCRIPTEN__)
//#include <SDL_gamecontroller.h>
#endif

#if defined(OGL)
#define TEXTURE_FORMAT GL_UNSIGNED_SHORT_1_5_5_5_REV
#elif defined(OGLES)
#define TEXTURE_FORMAT GL_UNSIGNED_SHORT_5_5_5_1
#endif

#endif<|endoftext|>


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

#define private public
#define protected public
#include "modules/perception/lib/io/file_util.h"

namespace apollo {
namespace perception {
namespace lib {

TEST(FileUtilTest, TestGetType) {
  FileType type;
  EXPECT_FALSE(FileUtil::GetType(
      "/apollo/modules/perception/testdata/lib/data/2.txt", &type));
  EXPECT_FALSE(FileUtil::GetType(
      "/apollo/modules/perception/testdata/lib/data/-/*/", &type));
  EXPECT_TRUE(FileUtil::GetType(
      "/apollo/modules/perception/testdata/lib/data", &type));
}

TEST(FileUtilTest, TestCreateDir) {
  EXPECT_TRUE(FileUtil::CreateDir(
      "/apollo/modules/perception/testdata/lib/data3/data4/data5"));
}

TEST(FileUtilTest, TestGetAbsolutPath) {
  EXPECT_EQ(FileUtil::GetAbsolutePath("", "./xx.txt"), "./xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/abc", ""), "/abc");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "xx.txt"),
            "/home/work/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work/", "xx.txt"),
            "/home/work/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "/xx.txt"), "/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "./xx.txt"),
            "/home/work/./xx.txt");
}

TEST(FileUtilTest, TestGetFileName) {
  std::string name;
  FileUtil::GetFileName("/home/work/data/1.txt", &name);
  EXPECT_EQ("1", name);
  FileUtil::GetFileName(
      "/apollo/modules/perception/testdata/lib/data/data/11.txt", &name);
  EXPECT_EQ("11", name);
  FileUtil::GetFileName("111.txt", &name);
  EXPECT_EQ("111", name);
  FileUtil::GetFileName("111", &name);
  EXPECT_EQ("111", name);
}

TEST(FileUtilTest, TestCompareFileByDigital) {
  EXPECT_TRUE(FileUtil::CompareFileByDigital(
      "/apollo/modules/perception/testdata/lib/data/1.txt",
      "/home/data/2.txt"));
  EXPECT_TRUE(FileUtil::CompareFileByDigital("1.txt", "/home/data/2.txt"));
  EXPECT_TRUE(FileUtil::CompareFileByDigital("01.txt", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("10", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("010", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("100", "001"));
}

TEST(FileUtilTest, TestCompareFileByLexicographical) {
  std::string data_folder = "/apollo/modules/perception/testdata/lib/data";
  EXPECT_TRUE(FileUtil::CompareFileByLexicographical(
      data_folder + "/QB1234_2222_3333_0001.pcd",
      data_folder + "/QB1234_2222_3333_1000.pcd"));
  EXPECT_TRUE(FileUtil::CompareFileByLexicographical(
      data_folder + "/QB1234_2222_3333_0001.pcd",
      data_folder + "/QB1234_3333_3333_1000.pcd"));
}

TEST(FileUtilTest, TestCompareFile) {
  EXPECT_TRUE(FileUtil::CompareFile("1.txt", "1.txt", FCT_UNKNOWN));
}

TEST(FileUtilTest, TestExists) {
  ASSERT_TRUE(FileUtil::CreateDir("./tmp"));
  EXPECT_TRUE(FileUtil::CreateDir(""));
  EXPECT_FALSE(FileUtil::Exists("./tmp", ".txt"));
  ASSERT_EQ(system("touch ./tmp/a.txt"), 0);
  EXPECT_TRUE(FileUtil::Exists("./tmp", ".txt"));
  EXPECT_FALSE(FileUtil::Exists("./tmp", ".bat"));
  EXPECT_TRUE(FileUtil::Exists("./tmp/a.txt"));
  EXPECT_FALSE(FileUtil::Exists("./tmp1"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmp/a.txt"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmp"));
  // ASSERT_TRUE(FileUtil::DeleteFile("./tmp1"));
  ASSERT_EQ(system(
      "chmod -R -x /apollo/modules/perception/testdata/lib/data3"), 256);
  ASSERT_FALSE(
      FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  ASSERT_EQ(system(
      "chmod -R +x /apollo/modules/perception/testdata/lib/data3"), 0);
  ASSERT_EQ(system(
      "chmod -R -r /apollo/modules/perception/testdata/lib/data3"), 256);
  ASSERT_FALSE(
      FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  ASSERT_EQ(system(
      "chmod -R +r /apollo/modules/perception/testdata/lib/data3"), 0);
  ASSERT_EQ(system(
      "chmod -R -w /apollo/modules/perception/testdata/lib/data3"), 0);
  ASSERT_FALSE(
      FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  ASSERT_EQ(system(
      "chmod -R +w /apollo/modules/perception/testdata/lib/data3"), 0);
  ASSERT_EQ(system("mkdir -p tmpa/tmpb"), 0);
  ASSERT_EQ(system("mkdir -p tmpa/tmpc"), 0);
  ASSERT_EQ(system("touch tmpa/tmpb/b.txt"), 0);
  ASSERT_EQ(system("touch tmpa/tmpb/b2.txt"), 0);
  ASSERT_EQ(system("touch tmpa/a.txt"), 0);
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa/tmpb/b.txt"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa/tmpb"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa"));
}

TEST(FileUtilTest, TestReadLines) {
  std::string path = "/apollo/modules/perception/testdata/lib/data/1.txt";
  std::vector<std::string> lines;
  EXPECT_FALSE(FileUtil::ReadLines("/not_exist_path", &lines));
  EXPECT_FALSE(FileUtil::ReadLines(
      "/apollo/modules/perception/testdata/lib/data/1.txt", nullptr));
  EXPECT_TRUE(FileUtil::ReadLines(path, &lines));
  EXPECT_EQ(lines.size(), 2u);
}

TEST(FileUtilTest, TestRemoveFileSuffix) {
  EXPECT_EQ(FileUtil::RemoveFileSuffix(
      "/apollo/modules/perception/testdata/lib/data/1.txt"), "1");
  EXPECT_EQ(FileUtil::RemoveFileSuffix("/home/111"), "111");
}

TEST(FileUtilTest, TestGetFileList) {
  std::string path = "/apollo/modules/perception/testdata/lib/data";
  std::vector<std::string> files;
  EXPECT_TRUE(FileUtil::GetFileList(path, &files));
  EXPECT_FALSE(FileUtil::GetFileList("/not_exist_path", &files));
  EXPECT_TRUE(FileUtil::GetFileList(
      "/apollo/modules/perception/testdata/lib/data", "txt", &files));
}

TEST(FileUtilTest, TestNumLines) {
  EXPECT_EQ(FileUtil::NumLines(
      "/apollo/modules/perception/testdata/lib/data/1.txt"), 3);
  EXPECT_EQ(FileUtil::NumLines(
      "/apollo/modules/perception/testdata/lib/data/11.txt"), -1);
}

TEST(FileUtilTest, TestRenameFile) {
  EXPECT_TRUE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/123.txt",
      "/apollo/modules/perception/testdata/lib/data2/321.txt"));
  EXPECT_TRUE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/321.txt",
      "/apollo/modules/perception/testdata/lib/data2/123.txt"));
  EXPECT_FALSE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/111.txt",
      "/apollo/modules/perception/testdata/lib/data2/222.txt"));
}

TEST(FileUtilTest, TestGetFileContent) {
  std::string path = "/apollo/modules/perception/testdata/lib/data/1.txt";
  std::string content;
  EXPECT_FALSE(FileUtil::GetFileContent(path, NULL));
  EXPECT_FALSE(FileUtil::GetFileContent(
      "/apollo/modules/perception/testdata/lib/data/2.txt", &content));
  EXPECT_TRUE(FileUtil::GetFileContent(path, &content));
  ASSERT_EQ(system(
      "chmod a-r /apollo/modules/perception/testdata/lib/data3/1.txt"), 0);
  ASSERT_FALSE(FileUtil::GetFileContent(
      "/apollo/modules/perception/testdata/lib/data3/1.txt", &content));
  ASSERT_EQ(system(
      "chmod a+r /apollo/modules/perception/testdata/lib/data3/1.txt"), 0);
}

TEST(FileUtilTest, TestFileUtil) { FileUtil file_util; }

}  // namespace lib
}  // namespace perception
}  // namespace apollo
<commit_msg>fixed broken test.<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/
#include <gtest/gtest.h>

#define private public
#define protected public
#include "modules/perception/lib/io/file_util.h"

namespace apollo {
namespace perception {
namespace lib {

TEST(FileUtilTest, TestGetType) {
  FileType type;
  EXPECT_FALSE(FileUtil::GetType(
      "/apollo/modules/perception/testdata/lib/data/2.txt", &type));
  EXPECT_FALSE(FileUtil::GetType(
      "/apollo/modules/perception/testdata/lib/data/-/*/", &type));
  EXPECT_TRUE(
      FileUtil::GetType("/apollo/modules/perception/testdata/lib/data", &type));
}

TEST(FileUtilTest, TestCreateDir) {
  EXPECT_TRUE(FileUtil::CreateDir(
      "/apollo/modules/perception/testdata/lib/data3/data4/data5"));
}

TEST(FileUtilTest, TestGetAbsolutPath) {
  EXPECT_EQ(FileUtil::GetAbsolutePath("", "./xx.txt"), "./xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/abc", ""), "/abc");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "xx.txt"),
            "/home/work/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work/", "xx.txt"),
            "/home/work/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "/xx.txt"), "/xx.txt");
  EXPECT_EQ(FileUtil::GetAbsolutePath("/home/work", "./xx.txt"),
            "/home/work/./xx.txt");
}

TEST(FileUtilTest, TestGetFileName) {
  std::string name;
  FileUtil::GetFileName("/home/work/data/1.txt", &name);
  EXPECT_EQ("1", name);
  FileUtil::GetFileName(
      "/apollo/modules/perception/testdata/lib/data/data/11.txt", &name);
  EXPECT_EQ("11", name);
  FileUtil::GetFileName("111.txt", &name);
  EXPECT_EQ("111", name);
  FileUtil::GetFileName("111", &name);
  EXPECT_EQ("111", name);
}

TEST(FileUtilTest, TestCompareFileByDigital) {
  EXPECT_TRUE(FileUtil::CompareFileByDigital(
      "/apollo/modules/perception/testdata/lib/data/1.txt",
      "/home/data/2.txt"));
  EXPECT_TRUE(FileUtil::CompareFileByDigital("1.txt", "/home/data/2.txt"));
  EXPECT_TRUE(FileUtil::CompareFileByDigital("01.txt", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("10", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("010", "/home/data/2.txt"));
  EXPECT_FALSE(FileUtil::CompareFileByDigital("100", "001"));
}

TEST(FileUtilTest, TestCompareFileByLexicographical) {
  std::string data_folder = "/apollo/modules/perception/testdata/lib/data";
  EXPECT_TRUE(FileUtil::CompareFileByLexicographical(
      data_folder + "/QB1234_2222_3333_0001.pcd",
      data_folder + "/QB1234_2222_3333_1000.pcd"));
  EXPECT_TRUE(FileUtil::CompareFileByLexicographical(
      data_folder + "/QB1234_2222_3333_0001.pcd",
      data_folder + "/QB1234_3333_3333_1000.pcd"));
}

TEST(FileUtilTest, TestCompareFile) {
  EXPECT_TRUE(FileUtil::CompareFile("1.txt", "1.txt", FCT_UNKNOWN));
}

TEST(FileUtilTest, TestExists) {
  ASSERT_TRUE(FileUtil::CreateDir("./tmp"));
  EXPECT_TRUE(FileUtil::CreateDir(""));
  EXPECT_FALSE(FileUtil::Exists("./tmp", ".txt"));
  ASSERT_EQ(system("touch ./tmp/a.txt"), 0);
  EXPECT_TRUE(FileUtil::Exists("./tmp", ".txt"));
  EXPECT_FALSE(FileUtil::Exists("./tmp", ".bat"));
  EXPECT_TRUE(FileUtil::Exists("./tmp/a.txt"));
  EXPECT_FALSE(FileUtil::Exists("./tmp1"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmp/a.txt"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmp"));
  // ASSERT_TRUE(FileUtil::DeleteFile("./tmp1"));
  // ASSERT_EQ(system("chmod -R -x
  // /apollo/modules/perception/testdata/lib/data3"),
  //           256);
  // ASSERT_FALSE(
  //     FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  // ASSERT_EQ(system("chmod -R +x
  // /apollo/modules/perception/testdata/lib/data3"),
  //           0);
  // ASSERT_EQ(system("chmod -R -r
  // /apollo/modules/perception/testdata/lib/data3"),
  //           256);
  // ASSERT_FALSE(
  //     FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  // ASSERT_EQ(system("chmod -R +r
  // /apollo/modules/perception/testdata/lib/data3"),
  //           0);
  // ASSERT_EQ(system("chmod -R -w
  // /apollo/modules/perception/testdata/lib/data3"),
  //           0);
  // ASSERT_FALSE(
  //     FileUtil::DeleteFile("/apollo/modules/perception/testdata/lib/data3"));
  // ASSERT_EQ(system("chmod -R +w
  // /apollo/modules/perception/testdata/lib/data3"),
  //           0);
  ASSERT_EQ(system("mkdir -p tmpa/tmpb"), 0);
  ASSERT_EQ(system("mkdir -p tmpa/tmpc"), 0);
  ASSERT_EQ(system("touch tmpa/tmpb/b.txt"), 0);
  ASSERT_EQ(system("touch tmpa/tmpb/b2.txt"), 0);
  ASSERT_EQ(system("touch tmpa/a.txt"), 0);
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa/tmpb/b.txt"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa/tmpb"));
  ASSERT_TRUE(FileUtil::DeleteFile("./tmpa"));
}

TEST(FileUtilTest, TestReadLines) {
  std::string path = "/apollo/modules/perception/testdata/lib/data/1.txt";
  std::vector<std::string> lines;
  EXPECT_FALSE(FileUtil::ReadLines("/not_exist_path", &lines));
  EXPECT_FALSE(FileUtil::ReadLines(
      "/apollo/modules/perception/testdata/lib/data/1.txt", nullptr));
  EXPECT_TRUE(FileUtil::ReadLines(path, &lines));
  EXPECT_EQ(lines.size(), 2u);
}

TEST(FileUtilTest, TestRemoveFileSuffix) {
  EXPECT_EQ(FileUtil::RemoveFileSuffix(
                "/apollo/modules/perception/testdata/lib/data/1.txt"),
            "1");
  EXPECT_EQ(FileUtil::RemoveFileSuffix("/home/111"), "111");
}

TEST(FileUtilTest, TestGetFileList) {
  std::string path = "/apollo/modules/perception/testdata/lib/data";
  std::vector<std::string> files;
  EXPECT_TRUE(FileUtil::GetFileList(path, &files));
  EXPECT_FALSE(FileUtil::GetFileList("/not_exist_path", &files));
  EXPECT_TRUE(FileUtil::GetFileList(
      "/apollo/modules/perception/testdata/lib/data", "txt", &files));
}

TEST(FileUtilTest, TestNumLines) {
  EXPECT_EQ(
      FileUtil::NumLines("/apollo/modules/perception/testdata/lib/data/1.txt"),
      3);
  EXPECT_EQ(
      FileUtil::NumLines("/apollo/modules/perception/testdata/lib/data/11.txt"),
      -1);
}

TEST(FileUtilTest, TestRenameFile) {
  EXPECT_TRUE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/123.txt",
      "/apollo/modules/perception/testdata/lib/data2/321.txt"));
  EXPECT_TRUE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/321.txt",
      "/apollo/modules/perception/testdata/lib/data2/123.txt"));
  EXPECT_FALSE(FileUtil::RenameFile(
      "/apollo/modules/perception/testdata/lib/data2/111.txt",
      "/apollo/modules/perception/testdata/lib/data2/222.txt"));
}

TEST(FileUtilTest, TestGetFileContent) {
  std::string path = "/apollo/modules/perception/testdata/lib/data/1.txt";
  std::string content;
  EXPECT_FALSE(FileUtil::GetFileContent(path, NULL));
  EXPECT_FALSE(FileUtil::GetFileContent(
      "/apollo/modules/perception/testdata/lib/data/2.txt", &content));
  EXPECT_TRUE(FileUtil::GetFileContent(path, &content));
  ASSERT_EQ(
      system("chmod a-r /apollo/modules/perception/testdata/lib/data3/1.txt"),
      0);
  ASSERT_FALSE(FileUtil::GetFileContent(
      "/apollo/modules/perception/testdata/lib/data3/1.txt", &content));
  ASSERT_EQ(
      system("chmod a+r /apollo/modules/perception/testdata/lib/data3/1.txt"),
      0);
}

TEST(FileUtilTest, TestFileUtil) { FileUtil file_util; }

}  // namespace lib
}  // namespace perception
}  // namespace apollo
<|endoftext|>