<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>
#include <fstream>
#include <sstream>
#include "modules/perception/common/io/io_util.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lidar/lib/ground_detector/ground_service_detector/ground_service_detector.h"

DECLARE_string(work_root);
DECLARE_string(config_manager_path);

namespace apollo {
namespace perception {
namespace lidar {

class LidarLibGroundServiceDetectorTest : public testing::Test {
 protected:
  void SetUp() {
    char cybertron_path[] = "CYBERTRON_PATH=";
    putenv(cybertron_path);
    char module_path[] = "MODULE_PATH=";
    putenv(module_path);
    FLAGS_work_root = "/apollo/modules/perception/testdata/"
        "lidar/lib/ground_detector/ground_service_detector";
    FLAGS_config_manager_path = "./conf";
    lib::ConfigManager* config_manager =
        lib::Singleton<lib::ConfigManager>::get_instance();
    config_manager->Reset();
  }

  void TearDown() {}
};

void LoadPlanes(std::string path, GroundNode* node_ptr) {
  int index = 0;
  std::ifstream file(path.c_str(), std::ifstream::in);
  while (file.good()) {
    std::string buf;
    getline(file, buf);
    if (buf.size() == 0) {
      continue;
    }
    std::stringstream ss;
    ss << buf;
    ss >> index;
    GroundNode* node = node_ptr + index;
    ss >> node->params(0) >> node->params(1) >> node->params(2) >>
        node->params(3) >> node->confidence;
  }
}

void LoadPoints(const std::string path, std::vector<std::vector<double>>* pts,
                std::vector<float>* height_gts) {
  std::vector<double> pt;
  std::ifstream file(path.c_str(), std::ifstream::in);
  double temp;
  float height;
  while (file.good()) {
    pt.clear();
    std::string buf;
    getline(file, buf);
    if (buf.size() == 0) {
      continue;
    }
    std::stringstream ss;
    ss << buf;
    for (int i = 0; i < 3; ++i) {
      ss >> temp;
      pt.push_back(temp);
    }
    ss >> height;
    height_gts->push_back(height);
    pts->push_back(pt);
  }
}

TEST_F(LidarLibGroundServiceDetectorTest,
       lidar_lib_scene_manager_ground_service_test) {
  GroundServiceDetector ground_service_detector;
  EXPECT_EQ(ground_service_detector.Name(), "GroundServiceDetector");
  EXPECT_FALSE(ground_service_detector.Init(GroundDetectorInitOptions()));

  EXPECT_TRUE(SceneManager::Instance().Init());
  EXPECT_TRUE(ground_service_detector.Init(GroundDetectorInitOptions()));
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions(), nullptr));
  LidarFrame frame;
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));
  frame.world_cloud = base::PointDCloudPool::Instance().Get();
  frame.cloud = base::PointFCloudPool::Instance().Get();
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));

  GroundServiceContent ground_service_content;
  auto ground_service = SceneManager::Instance().Service("GroundService");
  CHECK(ground_service);
  ground_service->GetServiceContentCopy(&ground_service_content);
  ground_service->UpdateServiceContent(ground_service_content);

  GroundServicePtr ground_service_cast =
      std::dynamic_pointer_cast<GroundService>(ground_service);

  // test query
  std::vector<std::vector<double>> world_pts;
  std::vector<float> height_gts;
  float out_gt = 0.f;
  float out = 0.f;
  GroundNode* node_ptr =
      ground_service_cast->GetGroundServiceContent()->grid_.DataPtr();
  ground_service_cast->GetGroundServiceContent()->grid_center_
      << 461957.33791688998, 4404672.5859791003, 19.143968966679999;
  LoadPlanes(
      "/apollo/modules/perception/testdata/lidar/lib/ground_detector/"
      "ground_service_detector/data/resources/planes.txt",
      node_ptr);
  LoadPoints(
      "/apollo/modules/perception/testdata/lidar/lib/ground_detector/"
      "ground_service_detector/data/resources/points.txt",
      &world_pts, &height_gts);

  for (size_t i = 0; i < world_pts.size(); ++i) {
    base::PointD world_pt;
    base::PointF local_pt;
    local_pt.x = world_pt.x = world_pts[i][0];
    local_pt.y = world_pt.y = world_pts[i][1];
    local_pt.z = world_pt.z = world_pts[i][2];
    frame.world_cloud->push_back(world_pt);
    frame.cloud->push_back(local_pt);
  }
  EXPECT_TRUE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));
  for (size_t i = 0; i < frame.world_cloud->size(); ++i) {
    out_gt = height_gts[i];
    out = frame.cloud->points_height(i);
    EXPECT_NEAR(out_gt, out, 1e-6);
  }
}

}  // namespace lidar
}  // namespace perception
}  // namespace apollo
<commit_msg>fix lint<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>
#include <fstream>
#include <sstream>
#include "modules/perception/common/io/io_util.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lidar/lib/ground_detector/ground_service_detector/ground_service_detector.h"

DECLARE_string(work_root);
DECLARE_string(config_manager_path);

namespace apollo {
namespace perception {
namespace lidar {

class LidarLibGroundServiceDetectorTest : public testing::Test {
 protected:
  void SetUp() {
    char cybertron_path[] = "CYBERTRON_PATH=";
    putenv(cybertron_path);
    char module_path[] = "MODULE_PATH=";
    putenv(module_path);
    FLAGS_work_root = "/apollo/modules/perception/testdata/"
        "lidar/lib/ground_detector/ground_service_detector";
    FLAGS_config_manager_path = "./conf";
    lib::ConfigManager* config_manager =
        lib::Singleton<lib::ConfigManager>::get_instance();
    config_manager->Reset();
  }

  void TearDown() {}
};

void LoadPlanes(std::string path, GroundNode* node_ptr) {
  int index = 0;
  std::ifstream file(path.c_str(), std::ifstream::in);
  while (file.good()) {
    std::string buf;
    getline(file, buf);
    if (buf.size() == 0) {
      continue;
    }
    std::stringstream ss;
    ss << buf;
    ss >> index;
    GroundNode* node = node_ptr + index;
    ss >> node->params(0) >> node->params(1) >> node->params(2) >>
        node->params(3) >> node->confidence;
  }
}

void LoadPoints(const std::string path, std::vector<std::vector<double>>* pts,
                std::vector<float>* height_gts) {
  std::vector<double> pt;
  std::ifstream file(path.c_str(), std::ifstream::in);
  double temp;
  float height;
  while (file.good()) {
    pt.clear();
    std::string buf;
    getline(file, buf);
    if (buf.size() == 0) {
      continue;
    }
    std::stringstream ss;
    ss << buf;
    for (int i = 0; i < 3; ++i) {
      ss >> temp;
      pt.push_back(temp);
    }
    ss >> height;
    height_gts->push_back(height);
    pts->push_back(pt);
  }
}

TEST_F(LidarLibGroundServiceDetectorTest,
       lidar_lib_scene_manager_ground_service_test) {
  GroundServiceDetector ground_service_detector;
  EXPECT_EQ(ground_service_detector.Name(), "GroundServiceDetector");
  EXPECT_FALSE(ground_service_detector.Init(GroundDetectorInitOptions()));

  EXPECT_TRUE(SceneManager::Instance().Init());
  EXPECT_TRUE(ground_service_detector.Init(GroundDetectorInitOptions()));
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions()
    , nullptr));
  LidarFrame frame;
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));
  frame.world_cloud = base::PointDCloudPool::Instance().Get();
  frame.cloud = base::PointFCloudPool::Instance().Get();
  EXPECT_FALSE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));

  GroundServiceContent ground_service_content;
  auto ground_service = SceneManager::Instance().Service("GroundService");
  CHECK(ground_service);
  ground_service->GetServiceContentCopy(&ground_service_content);
  ground_service->UpdateServiceContent(ground_service_content);

  GroundServicePtr ground_service_cast =
      std::dynamic_pointer_cast<GroundService>(ground_service);

  // test query
  std::vector<std::vector<double>> world_pts;
  std::vector<float> height_gts;
  float out_gt = 0.f;
  float out = 0.f;
  GroundNode* node_ptr =
      ground_service_cast->GetGroundServiceContent()->grid_.DataPtr();
  ground_service_cast->GetGroundServiceContent()->grid_center_
      << 461957.33791688998, 4404672.5859791003, 19.143968966679999;
  LoadPlanes(
      "/apollo/modules/perception/testdata/lidar/lib/ground_detector/"
      "ground_service_detector/data/resources/planes.txt",
      node_ptr);
  LoadPoints(
      "/apollo/modules/perception/testdata/lidar/lib/ground_detector/"
      "ground_service_detector/data/resources/points.txt",
      &world_pts, &height_gts);

  for (size_t i = 0; i < world_pts.size(); ++i) {
    base::PointD world_pt;
    base::PointF local_pt;
    local_pt.x = world_pt.x = world_pts[i][0];
    local_pt.y = world_pt.y = world_pts[i][1];
    local_pt.z = world_pt.z = world_pts[i][2];
    frame.world_cloud->push_back(world_pt);
    frame.cloud->push_back(local_pt);
  }
  EXPECT_TRUE(ground_service_detector.Detect(GroundDetectorOptions(), &frame));
  for (size_t i = 0; i < frame.world_cloud->size(); ++i) {
    out_gt = height_gts[i];
    out = frame.cloud->points_height(i);
    EXPECT_NEAR(out_gt, out, 1e-6);
  }
}

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


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XFAIL: apple-darwin

// REQUIRES: locale.en_US.UTF-8
// REQUIRES: locale.fr_FR.UTF-8
// REQUIRES: locale.ru_RU.UTF-8
// REQUIRES: locale.zh_CN.UTF-8

// <locale>

// class moneypunct_byname<charT, International>

// string_type curr_symbol() const;

#include <locale>
#include <limits>
#include <cassert>

#include "test_macros.h"
#include "platform_support.h" // locale name macros

class Fnf
    : public std::moneypunct_byname<char, false>
{
public:
    explicit Fnf(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<char, false>(nm, refs) {}
};

class Fnt
    : public std::moneypunct_byname<char, true>
{
public:
    explicit Fnt(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<char, true>(nm, refs) {}
};

class Fwf
    : public std::moneypunct_byname<wchar_t, false>
{
public:
    explicit Fwf(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<wchar_t, false>(nm, refs) {}
};

class Fwt
    : public std::moneypunct_byname<wchar_t, true>
{
public:
    explicit Fwt(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<wchar_t, true>(nm, refs) {}
};

int main()
{
    {
        Fnf f("C", 1);
        assert(f.curr_symbol() == std::string());
    }
    {
        Fnt f("C", 1);
        assert(f.curr_symbol() == std::string());
    }
    {
        Fwf f("C", 1);
        assert(f.curr_symbol() == std::wstring());
    }
    {
        Fwt f("C", 1);
        assert(f.curr_symbol() == std::wstring());
    }

    {
        Fnf f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == "$");
    }
    {
        Fnt f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == "USD ");
    }
    {
        Fwf f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == L"$");
    }
    {
        Fwt f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == L"USD ");
    }

    {
        Fnf f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == " \u20ac");
    }
    {
        Fnt f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == " EUR");
    }
    {
        Fwf f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == L" \u20ac");
    }
    {
        Fwt f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == L" EUR");
    }

    {
        Fnf f(LOCALE_ru_RU_UTF_8, 1);
        // GLIBC <= 2.23 uses currency_symbol="<U0440><U0443><U0431>"
        // GLIBC >= 2.24 uses currency_symbol="<U20BD>"
        // See also: http://www.fileformat.info/info/unicode/char/20bd/index.htm
#if defined(TEST_GLIBC_PREREQ) && TEST_GLIBC_PREREQ(2, 24)
        assert(f.curr_symbol() == " \xE2\x82\xBD");
#else
        assert(f.curr_symbol() == " \xD1\x80\xD1\x83\xD0\xB1");
#endif
    }
    {
        Fnt f(LOCALE_ru_RU_UTF_8, 1);
        assert(f.curr_symbol() == " RUB");
    }
    {
        Fwf f(LOCALE_ru_RU_UTF_8, 1);
        assert(f.curr_symbol() == L" \x440\x443\x431");
    }
    {
        Fwt f(LOCALE_ru_RU_UTF_8, 1);
        assert(f.curr_symbol() == L" RUB");
    }

    {
        Fnf f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == "\xEF\xBF\xA5");
    }
    {
        Fnt f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == "CNY ");
    }
    {
        Fwf f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == L"\xFFE5");
    }
    {
        Fwt f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == L"CNY ");
    }
}
<commit_msg>Apply curr_symbol.pass.cpp test fix to missed test case<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XFAIL: apple-darwin

// REQUIRES: locale.en_US.UTF-8
// REQUIRES: locale.fr_FR.UTF-8
// REQUIRES: locale.ru_RU.UTF-8
// REQUIRES: locale.zh_CN.UTF-8

// <locale>

// class moneypunct_byname<charT, International>

// string_type curr_symbol() const;

#include <locale>
#include <limits>
#include <cassert>

#include "test_macros.h"
#include "platform_support.h" // locale name macros

class Fnf
    : public std::moneypunct_byname<char, false>
{
public:
    explicit Fnf(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<char, false>(nm, refs) {}
};

class Fnt
    : public std::moneypunct_byname<char, true>
{
public:
    explicit Fnt(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<char, true>(nm, refs) {}
};

class Fwf
    : public std::moneypunct_byname<wchar_t, false>
{
public:
    explicit Fwf(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<wchar_t, false>(nm, refs) {}
};

class Fwt
    : public std::moneypunct_byname<wchar_t, true>
{
public:
    explicit Fwt(const std::string& nm, std::size_t refs = 0)
        : std::moneypunct_byname<wchar_t, true>(nm, refs) {}
};

int main()
{
    {
        Fnf f("C", 1);
        assert(f.curr_symbol() == std::string());
    }
    {
        Fnt f("C", 1);
        assert(f.curr_symbol() == std::string());
    }
    {
        Fwf f("C", 1);
        assert(f.curr_symbol() == std::wstring());
    }
    {
        Fwt f("C", 1);
        assert(f.curr_symbol() == std::wstring());
    }

    {
        Fnf f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == "$");
    }
    {
        Fnt f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == "USD ");
    }
    {
        Fwf f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == L"$");
    }
    {
        Fwt f(LOCALE_en_US_UTF_8, 1);
        assert(f.curr_symbol() == L"USD ");
    }

    {
        Fnf f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == " \u20ac");
    }
    {
        Fnt f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == " EUR");
    }
    {
        Fwf f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == L" \u20ac");
    }
    {
        Fwt f(LOCALE_fr_FR_UTF_8, 1);
        assert(f.curr_symbol() == L" EUR");
    }

    {
        Fnf f(LOCALE_ru_RU_UTF_8, 1);
        // GLIBC <= 2.23 uses currency_symbol="<U0440><U0443><U0431>"
        // GLIBC >= 2.24 uses currency_symbol="<U20BD>"
        // See also: http://www.fileformat.info/info/unicode/char/20bd/index.htm
#if defined(TEST_GLIBC_PREREQ) && TEST_GLIBC_PREREQ(2, 24)
        assert(f.curr_symbol() == " \u20BD");
#else
        assert(f.curr_symbol() == " \xD1\x80\xD1\x83\xD0\xB1");
#endif
    }
    {
        Fnt f(LOCALE_ru_RU_UTF_8, 1);
        assert(f.curr_symbol() == " RUB");
    }
    {
        Fwf f(LOCALE_ru_RU_UTF_8, 1);
#if defined(TEST_GLIBC_PREREQ) && TEST_GLIBC_PREREQ(2, 24)
        assert(f.curr_symbol() == L" \u20BD");
#else
        assert(f.curr_symbol() == L" \x440\x443\x431");
#endif
    }

    {
        Fwt f(LOCALE_ru_RU_UTF_8, 1);
        assert(f.curr_symbol() == L" RUB");
    }

    {
        Fnf f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == "\xEF\xBF\xA5");
    }
    {
        Fnt f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == "CNY ");
    }
    {
        Fwf f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == L"\xFFE5");
    }
    {
        Fwt f(LOCALE_zh_CN_UTF_8, 1);
        assert(f.curr_symbol() == L"CNY ");
    }
}
<|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/common/log.h
#include <gtest/gtest.h>
#include <caffe/caffe.hpp>
#include <opencv2/opencv.hpp>

#include "modules/obstacle/camera/common/flags.h"
#include "modules/obstacle/camera/common/util.h"
#include "modules/obstacle/camera/detector/common/feature_extractor.h"
#include "modules/obstacle/camera/detector/yolo_camera_detector/util.h"
#include "modules/obstacle/camera/detector/yolo_camera_detector/yolo.pb.h"
#include "modules/obstacle/camera/detector/yolo_camera_detector/yolo_camera_detector.h"
#include "modules/obstacle/camera/interface/base_camera_detector.h"

namespace apollo {
namespace perception {
namespace obstacle {
/*
TEST(YoloCameraAnakinDetectorTest, yolo_camera_detector_test) {
    std::string yolo_test_config =
"./data/models/yolo_camera_detector/config_test.pt";

    std::string yolo_config = "./data/models/yolo_camera_detector/config.pt";

    adu::perception::obstacle::yolo::YoloParam yolo_param;
    adu::perception::obstacle::yolo::YoloParam origin_yolo_param;

    load_text_proto_message_file(yolo_test_config, yolo_param);
    // roipooling feature extractor
    load_text_proto_message_file(yolo_config, origin_yolo_param);
    {
        yolo_param.mutable_model_param()->set_model_type(yolo::ModelType::Anakin);
        std::string out_str;
        std::ofstream ofs(yolo_config, std::ofstream::out);
        google::protobuf::TextFormat::PrintToString(yolo_param, &out_str);
        ofs << out_str;
        ofs.close();

        BaseCameraDetector *camera_detector =
                BaseCameraDetectorRegisterer::get_instance_by_name("YoloCameraDetector");
        CHECK(camera_detector->init());
                CHECK_EQ(camera_detector->name(), "YoloCameraDetector");
        cv::Mat frame = cv::imread("test.jpg", CV_LOAD_IMAGE_COLOR);
        CHECK((frame.data != nullptr));

        CameraDetectorOptions options;
        Timer timer;
        CHECK_EQ(camera_detector->detect(frame, options, NULL), false);
        std::vector<VisualObjectPtr> objects;
        CHECK(camera_detector->detect(frame, options, &objects));
        AINFO << "detection time: " << timer.toc() << "ms";

        // int obj_idx = 0;
        // for (const auto &obj : objects) {
        //     AINFO << "Obj-" << obj_idx++ << ": " <<
get_object_name(obj->type)
        //                << " (feat: " << obj->object_feature.size() << "-D)";
        //     if (obj->object_feature.size() > 0) {
        //         float sum_of_squares = 0.0;
        //         for (const auto &f : obj->object_feature) {
        //             sum_of_squares += f * f;
        //         }
        //         // EXPECT_LT(abs(sum_of_squares - 1.0), 1e-3);
        //     }
        // }
        // int obj_size = objects.size();
        // objects.clear();
        VisualObjectPtr obj;
        obj.reset(new VisualObject);
        obj->alpha = 0;
        obj->upper_left[0] = 0.1;
        obj->upper_left[1] = 0.2;
        obj->lower_right[0] = 0.3;
        obj->lower_right[1] = 0.4;
        obj->height = 1.6;
        obj->width = 1.4;
        obj->length = 4;
        obj->center.x() = 0;
        obj->center.y() = 0;
        obj->center.z() = 0;
        obj->theta = 1.1;
        obj->score = 0.9;
        obj->type = PEDESTRIAN;
        objects.push_back(obj);

        std::vector<VisualObjectPtr> mixed_objects;
        cv::Mat lane_map(frame.rows,frame.cols,CV_32FC1);

        CHECK(camera_detector->multitask(frame, options, &objects, &lane_map));
    }
    {
        std::string out_str;
        std::ofstream ofs(yolo_config, std::ofstream::out);
        google::protobuf::TextFormat::PrintToString(origin_yolo_param,
&out_str); ofs << out_str; ofs.close();
    }
}

TEST(YoloCameraAnakinDetectorTest, nms_test) {

    {
        std::vector<NormalizedBBox> test_objects;
        NormalizedBBox obj_ped1;
        obj_ped1.xmin = .1;
        obj_ped1.xmax = .3;
        obj_ped1.ymin = .20;
        obj_ped1.ymax = .60;
        obj_ped1.score = 0.9;
        obj_ped1.label = PEDESTRIAN;

        NormalizedBBox obj_ped2;
        obj_ped2.xmin = .10;
        obj_ped2.xmax = .25;
        obj_ped2.ymin = .30;
        obj_ped2.ymax = .60;
        obj_ped2.score = 0.8;
        obj_ped2.label = PEDESTRIAN;
        NormalizedBBox obj_ped3;
        obj_ped3.xmin = .7;
        obj_ped3.xmax = .8;
        obj_ped3.ymin = .7;
        obj_ped3.ymax = .8;
        obj_ped3.score = 0.01;
        obj_ped3.label = PEDESTRIAN;

        test_objects.push_back(obj_ped1);
        test_objects.push_back(obj_ped2);
        test_objects.push_back(obj_ped3);

        std::vector<float> scores;
        scores.push_back(obj_ped1.score);
        scores.push_back(obj_ped2.score);
        scores.push_back(obj_ped3.score);

        std::vector<int> indices;
        apply_nms_fast(test_objects, scores, 0.1, 0.5, 1, 20, &indices);
                CHECK_EQ(indices.size(), 1);
        apply_nms_fast(test_objects, scores, 0.1, 0.5, 0.7, 20, &indices);
                CHECK_EQ(indices.size(), 1);

    }
    {
        std::vector<NormalizedBBox> test_objects;
        NormalizedBBox obj_cyc;
        obj_cyc.xmin = .1;
        obj_cyc.xmax = .3;
        obj_cyc.ymin = .20;
        obj_cyc.ymax = .60;
        obj_cyc.score = 0.9;
        obj_cyc.label = BICYCLE;

        NormalizedBBox obj_ped;
        obj_ped.xmin = .10;
        obj_ped.xmax = .25;
        obj_ped.ymin = .30;
        obj_ped.ymax = .60;
        obj_ped.score = 0.95;
        obj_ped.label = PEDESTRIAN;

        test_objects.push_back(obj_cyc);
        test_objects.push_back(obj_ped);

        std::vector<int> cyc_indices;
        std::vector<int> ped_indices;
        cyc_indices.push_back(0);
        ped_indices.push_back(1);
        cross_class_merge(&cyc_indices, &ped_indices, test_objects, 0.8);
                CHECK_EQ(cyc_indices.size(), 1);
                CHECK_EQ(ped_indices.size(), 0);
    }

    std::vector<VisualObjectPtr> visual_objects;
    for (int i = 0; i < 1; i++) {
        VisualObjectPtr obj;

        obj.reset(new VisualObject);
        obj->alpha = 0;
        obj->upper_left[0] = 0.1;
        obj->upper_left[1] = 0.2;
        obj->lower_right[0] = 0.3;
        obj->lower_right[1] = 0.4;
        obj->height = 1.6;
        obj->width = 1.4;
        obj->length = 4;
        obj->center.x() = 0;
        obj->center.y() = 0;
        obj->center.z() = 0;
        obj->theta = 1.1;
        obj->score = 0.9;
        obj->type = PEDESTRIAN;
        visual_objects.push_back(obj);
    }
    recover_bbox(10, 10, 5, &visual_objects);
            CHECK_EQ(visual_objects[0]->upper_left[0], 1);
            CHECK_EQ(visual_objects[0]->upper_left[1], 7);
            CHECK_EQ(visual_objects[0]->lower_right[0], 3);
            CHECK_EQ(visual_objects[0]->lower_right[1], 9);

}

TEST(YoloCameraAnakinDetectorTest, input_tensor_test) {
    std::string yolo_config = "./data/models/yolo_camera_detector/config.pt";

    adu::perception::obstacle::yolo::YoloParam yolo_param;
    adu::perception::obstacle::yolo::YoloParam origin_yolo_param;

    load_text_proto_message_file(yolo_config, yolo_param);
    origin_yolo_param.CopyFrom(yolo_param);
    yolo_param.mutable_model_param()->set_model_type(yolo::ModelType::Anakin);
    std::cout << yolo_param.model_param().weight_file() << std::endl;
    {
        std::string out_str;
        std::ofstream ofs(yolo_config, std::ofstream::out);
        google::protobuf::TextFormat::PrintToString(yolo_param, &out_str);
        ofs << out_str;
        ofs.close();

        YoloCameraDetector camera_detector;
        CHECK(camera_detector.init());
        cv::Mat frame = cv::imread("test.jpg", CV_LOAD_IMAGE_COLOR);
        CHECK((frame.data != nullptr));
        CameraDetectorOptions options;
        std::vector<VisualObjectPtr> objects;
        // CHECK(camera_detector.detect(frame, options, &objects));
    }
    std::string out_str;
    std::ofstream ofs(yolo_config, std::ofstream::out);
    google::protobuf::TextFormat::PrintToString(origin_yolo_param, &out_str);
    ofs << out_str;
    ofs.close();
}

TEST(YoloCameraAnakinDetectorTest, recover_bbox_test) {
    std::vector<VisualObjectPtr> visual_objects;
    for (int i = 0; i < 1; i++) {
        VisualObjectPtr obj;

        obj.reset(new VisualObject);
        obj->alpha = 0;
        obj->upper_left[0] = -1;
        obj->upper_left[1] = -1;
        obj->lower_right[0] = 0.3;
        obj->lower_right[1] = 0.4;
        obj->height = 1.6;
        obj->width = 1.4;
        obj->length = 4;
        obj->center.x() = 0;
        obj->center.y() = 0;
        obj->center.z() = 0;
        obj->theta = 1.1;
        obj->score = 0.9;
        obj->type = PEDESTRIAN;
        visual_objects.push_back(obj);
    }
    recover_bbox(100, 100, 0, &visual_objects);
    visual_objects.clear();
    recover_bbox(100, 100, 0, &visual_objects);
}

TEST(YoloCameraAnakinDetectorTest, bbox_op_test) {
    {
        NormalizedBBox bbox1;
        NormalizedBBox bbox2;
        bbox1.xmin = 20;
        bbox1.ymin = 20;
        bbox1.xmax = 10;
        bbox1.ymax = 10;
        bbox2.xmin = 20;
        bbox2.ymin = 20;
        bbox2.xmax = 10;
        bbox2.ymax = 10;
        NormalizedBBox res_bbox;
        get_intersect_bbox(bbox1, bbox2, &res_bbox);
                CHECK_EQ(res_bbox.xmin, 0);
                CHECK_EQ(res_bbox.ymin, 0);
                CHECK_EQ(res_bbox.xmax, 0);
                CHECK_EQ(res_bbox.ymax, 0);
    }
    {
        NormalizedBBox bbox;
        bbox.xmin = 0.2;
        bbox.ymin = 0.2;
        bbox.xmax = 0.1;
        bbox.ymax = 0.1;
        float size = -1;
        size = get_bbox_size(bbox);
        EXPECT_FLOAT_EQ(0, size);

        bbox.xmax = 0.3;
        bbox.ymax = 0.3;
        bbox.size = 0.01;
        size = get_bbox_size(bbox);
        EXPECT_FLOAT_EQ(0.01, size);
        bbox.size = -1;
        size = get_bbox_size(bbox);
        EXPECT_FLOAT_EQ(0.01, size);
    }
    {
        NormalizedBBox bbox1;
        NormalizedBBox bbox2;
        bbox1.xmin = 0;
        bbox1.ymin = 0;
        bbox1.xmax = 0.1;
        bbox1.ymax = 0.1;
        bbox2.xmin = 0;
        bbox2.ymin = 0;
        bbox2.xmax = 0.1;
        bbox2.ymax = 0.1;
        float overlap = 0;
        overlap = get_jaccard_overlap(bbox1, bbox2);
        EXPECT_FLOAT_EQ(1, overlap);
        bbox2.xmin = 0.2;
        bbox2.ymin = 0.2;
        bbox2.xmax = 0.3;
        bbox2.ymax = 0.3;
        overlap = get_jaccard_overlap(bbox1, bbox2);
        EXPECT_FLOAT_EQ(0, overlap);
    }

}*/
}  // namespace obstacle
}  // namespace perception
}  // namespace apollo
<commit_msg>delete uni-test of yolo_camera_anakin_detector<commit_after><|endoftext|>


<commit_before>#include <stdio.h>

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main () {
    return 0;
}
<commit_msg>add poj1095 learn catalan<commit_after>#include <stdio.h>
#include <stdint.h>

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

#define N 300

const int64_t INF =33500000100;

int64_t k[N];
int n, size;

void dfs(int n, int idx) {
//    printf("%d node of %dth order\n", n, idx);
    int64_t p = 0;
    int left = 0;
    for (int i = 0; i < n; i++) {
        p += k[i] * k[n-1-i];
        if (p > idx) {
            left = i;
            break;
        }
    }
    int right = n-1-left;
    int newpos = idx-(p-k[left]*k[n-1-left]);
    if (left > 0) {
        printf("(");
        dfs(left, newpos/k[right]);
        printf(")");
    }
    printf("X");
    if (right>0) {
        printf("(");
        dfs(right, newpos%k[right]);
        printf(")");
    }
}

int main() {
    k[0] = 1;
    size = 1;
    for (int i = 0; i < N ; i++, size++) {
        k[i+1]= 2*(2*i+1)*k[i]/(i+2);
        if(k[i+1] > INF || k[i+1] < 0) { break; }
//        printf("%ld\n", k[i+1]);
    }

    while(true) {
        cin >> n;
        if (n == 0) break;
        int idx = 0;
        int64_t p = 0;
        for (int i = 0; i < size; i++) {
            p+= k[i];
            if (p > n) {
                idx = i;
                break;
            }
        }
//        printf("idx=%d size=%d\n", idx, size);
        dfs(idx, n-p+k[idx]);
        printf("\n");
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "genetic_circuit.h"

#include <vector>

#include <cassert>
#include <cstdlib>
#include <functional>  // std::hash
#include <sstream>

#include "utility.h"

GeneticCircuit::GeneticCircuit(int input_num, int output_num,
                               std::minstd_rand* rand_eng)
    : Circuit(input_num, output_num), rand_engine_ptr(rand_eng), fitness(0) {
  assert(input_num >= 2);
  // if (input_num < 2) {
  //   std::string errmsg =
  //       "GeneticCircuit::GeneticCircuit FATAL Need more than 2 inputs to "
  //       "create gate";
  //   errlog(errmsg);
  //   std::exit(EXIT_FAILURE);
  // }
  std::vector<GateType> gate_types{NOT, OR, AND};

  int num_of_gates =
      number_dist(*rand_engine_ptr);  // random number between 0 and 40
  std::uniform_int_distribution<> gate_max_dist{0, num_of_gates};
  for (int i = 0; i < num_of_gates; ++i) {
    // random number between 0 and 2
    //
    GateType rand_gate = gate_types[gate_max_dist(*rand_engine_ptr) % 2];

    if ((rand_gate == NOT) && (getNotCount() < 2)) {
      // only add a NOT if we don't have 2 already
      addGate(rand_gate, gate_max_dist(*rand_engine_ptr) % getGateCount());
    } else if ((rand_gate == OR) || (rand_gate == AND)) {
      addGate(rand_gate, gate_max_dist(*rand_engine_ptr) % getGateCount(),
              gate_max_dist(*rand_engine_ptr) % getGateCount());
    }
  }
}

GeneticCircuit::GeneticCircuit(int input_num, int output_num,
                               std::minstd_rand* rand_eng,
                               std::vector<Gate*> gates)
    : Circuit(input_num, output_num), rand_engine_ptr(rand_eng), fitness(0) {
  for (Gate* gate : gates) {
    if (gate->type == "WIRE") {
      errlog("GeneticCircuit::GeneticCircuit Wires are not added");
    } else if (gate->type == "NONE") {
      errlog("GeneticCircuit::GeneticCircuit NONE Wires are not added");
    } else if (gate->type == "NOT") {
      addGate(GateType(NOT), gate->input_1_index);
    } else if (gate->type == "AND") {
      addGate(GateType(AND), gate->input_1_index, gate->input_2_index);
    } else if (gate->type == "OR") {
      addGate(GateType(OR), gate->input_1_index, gate->input_2_index);
    } else if (gate->type == "INVALID") {
      errlog("GeneticCircuit::GeneticCircuit FATAL Invalid Gate Encountered");
      std::exit(EXIT_FAILURE);
    } else {
      errlog("GeneticCircuit::GeneticCircuit FATAL Unknown Gate Encountered");
      std::exit(EXIT_FAILURE);
    }
  }
  generateFitness();
}

int GeneticCircuit::generateFitness() {
  int score = 0;
  score += getNotCount() * 10000;
  score += getAndCount() * 10;
  score += getOrCount() * 1;
  fitness = score;
  return score;
}

void GeneticCircuit::setFitness(int f) { fitness = f; }

std::size_t GeneticCircuit::hash_circ() {
  std::string s = "";
  std::hash<std::string> hash_fn;

  BooleanTable outputs = evaluateAllInputs();

  for (std::vector<bool> row : outputs) {
    for (bool bit : row) {
      s += std::to_string((int)bit);
    }
  }

  /* std::cout << "Hashing..." << std::endl; */
  std::size_t hash = hash_fn(s);
  /* std::cout << "Done Hashing..: " << hash << std::endl; */
  if (SHOW_POPULATION_LOG) {
    std::ostringstream errstream;
    errstream << " NOT: " << getNotCount() << " AND: " << getAndCount()
              << " OR: " << getOrCount();
    errlog(errstream.str(), SHOW_POPULATION_LOG);
  }
  return hash;
}
<commit_msg>fix rand_gate mod<commit_after>#include "genetic_circuit.h"

#include <vector>

#include <cassert>
#include <cstdlib>
#include <functional>  // std::hash
#include <sstream>

#include "utility.h"

GeneticCircuit::GeneticCircuit(int input_num, int output_num,
                               std::minstd_rand* rand_eng)
    : Circuit(input_num, output_num), rand_engine_ptr(rand_eng), fitness(0) {
  assert(input_num >= 2);
  // if (input_num < 2) {
  //   std::string errmsg =
  //       "GeneticCircuit::GeneticCircuit FATAL Need more than 2 inputs to "
  //       "create gate";
  //   errlog(errmsg);
  //   std::exit(EXIT_FAILURE);
  // }
  std::vector<GateType> gate_types{NOT, OR, AND};

  int num_of_gates =
      number_dist(*rand_engine_ptr);  // random number between 0 and 40
  std::uniform_int_distribution<> gate_max_dist{0, num_of_gates};
  for (int i = 0; i < num_of_gates; ++i) {
    // random number between 0 and 2
    //
    GateType rand_gate = gate_types[gate_max_dist(*rand_engine_ptr) % 3];

    if ((rand_gate == NOT) && (getNotCount() < 2)) {
      // only add a NOT if we don't have 2 already
      addGate(rand_gate, gate_max_dist(*rand_engine_ptr) % getGateCount());
    } else if ((rand_gate == OR) || (rand_gate == AND)) {
      addGate(rand_gate, gate_max_dist(*rand_engine_ptr) % getGateCount(),
              gate_max_dist(*rand_engine_ptr) % getGateCount());
    }
  }
}

GeneticCircuit::GeneticCircuit(int input_num, int output_num,
                               std::minstd_rand* rand_eng,
                               std::vector<Gate*> gates)
    : Circuit(input_num, output_num), rand_engine_ptr(rand_eng), fitness(0) {
  for (Gate* gate : gates) {
    if (gate->type == "WIRE") {
      errlog("GeneticCircuit::GeneticCircuit Wires are not added");
    } else if (gate->type == "NONE") {
      errlog("GeneticCircuit::GeneticCircuit NONE Wires are not added");
    } else if (gate->type == "NOT") {
      addGate(GateType(NOT), gate->input_1_index);
    } else if (gate->type == "AND") {
      addGate(GateType(AND), gate->input_1_index, gate->input_2_index);
    } else if (gate->type == "OR") {
      addGate(GateType(OR), gate->input_1_index, gate->input_2_index);
    } else if (gate->type == "INVALID") {
      errlog("GeneticCircuit::GeneticCircuit FATAL Invalid Gate Encountered");
      std::exit(EXIT_FAILURE);
    } else {
      errlog("GeneticCircuit::GeneticCircuit FATAL Unknown Gate Encountered");
      std::exit(EXIT_FAILURE);
    }
  }
  generateFitness();
}

int GeneticCircuit::generateFitness() {
  int score = 0;
  score += getNotCount() * 10000;
  score += getAndCount() * 10;
  score += getOrCount() * 1;
  fitness = score;
  return score;
}

void GeneticCircuit::setFitness(int f) { fitness = f; }

std::size_t GeneticCircuit::hash_circ() {
  std::string s = "";
  std::hash<std::string> hash_fn;

  BooleanTable outputs = evaluateAllInputs();

  for (std::vector<bool> row : outputs) {
    for (bool bit : row) {
      s += std::to_string((int)bit);
    }
  }

  /* std::cout << "Hashing..." << std::endl; */
  std::size_t hash = hash_fn(s);
  /* std::cout << "Done Hashing..: " << hash << std::endl; */
  if (SHOW_POPULATION_LOG) {
    std::ostringstream errstream;
    errstream << " NOT: " << getNotCount() << " AND: " << getAndCount()
              << " OR: " << getOrCount();
    errlog(errstream.str(), SHOW_POPULATION_LOG);
  }
  return hash;
}
<|endoftext|>


<commit_before>#ifndef STREAMBUFFERR_HPP
#define STREAMBUFFERR_HPP
#include <net/stream.hpp>
#include <queue>
#include <util/timer.hpp>

namespace net {
  class StreamBuffer : public net::Stream
  {
  public:
    StreamBuffer(Timers::duration_t timeout=std::chrono::microseconds(10))
      : timer({this,&StreamBuffer::congested}),congestion_timeout(timeout) {}
    using buffer_t = os::mem::buf_ptr;
    using Ready_queue  = std::deque<buffer_t>;
    virtual ~StreamBuffer() {
      timer.stop();
    }

    void on_connect(ConnectCallback cb) override {
      m_on_connect = std::move(cb);
    }

    void on_read(size_t, ReadCallback cb) override {
      m_on_read = std::move(cb);
    }
    void on_data(DataCallback cb) override {
      m_on_data = std::move(cb);
    }
    size_t next_size() override;

    buffer_t read_next() override;

    void on_close(CloseCallback cb) override {
      m_on_close = std::move(cb);
    }
    void on_write(WriteCallback cb) override {
      m_on_write = std::move(cb);
    }

    void signal_data();

    bool read_congested() const noexcept
    { return m_read_congested; }

    bool write_congested() const noexcept
    { return m_write_congested; }

    /**
     * @brief Construct a shared read vector used by streams
     * If allocation failed congestion flag is set
     *
     * @param construction parameters
     *
     * @return nullptr on failure, shared_ptr to buffer on success
     */
    template <typename... Args>
    buffer_t construct_read_buffer(Args&&... args)
    {
      return construct_buffer_with_flag(m_read_congested,std::forward<Args> (args)...);
    }

    /**
     * @brief Construct a shared write vector used by streams
     * If allocation failed congestion flag is set
     *
     * @param construction parameters
     *
     * @return nullptr on failure, shared_ptr to buffer on success
     */
    template <typename... Args>
    buffer_t construct_write_buffer(Args&&... args)
    {
      return construct_buffer_with_flag(m_write_congested,std::forward<Args> (args)...);
    }

    virtual void handle_read_congestion() = 0;
    virtual void handle_write_congestion() = 0;
  protected:
    void closed()
    { if (m_on_close) m_on_close(); }
    void connected()
    { if (m_on_connect) m_on_connect(*this); }
    void stream_on_write(int n)
    { if (m_on_write) m_on_write(n); }
    void enqueue_data(buffer_t data)
    { m_send_buffers.push_back(data); }

    void congested();

    CloseCallback getCloseCallback() { return std::move(this->m_on_close); }

    void reset_callbacks() override
    {
      //remove queue and reset congestion flags and busy flag ??
      this->m_on_close = nullptr;
      this->m_on_connect = nullptr;
      this->m_on_read  = nullptr;
      this->m_on_write = nullptr;
      this->m_on_data = nullptr;
    }
    Timer timer;

  private:
    Timer::duration_t congestion_timeout;
    bool  m_write_congested= false;
    bool  m_read_congested = false;

    ConnectCallback  m_on_connect = nullptr;
    ReadCallback     m_on_read    = nullptr;
    DataCallback     m_on_data    = nullptr;
    WriteCallback    m_on_write   = nullptr;
    CloseCallback    m_on_close   = nullptr;
    Ready_queue      m_send_buffers;

    /**
     * @brief Construct a shared vector and set congestion flag if allocation fails
     *
     * @param flag the flag to set true or false on allocation failure
     * @param args arguments to constructing the buffer
     * @return nullptr on failure , shared pointer to buffer on success
     */

    template <typename... Args>
    buffer_t construct_buffer_with_flag(bool &flag,Args&&... args)
    {
      static buffer_t buffer;
      try
      {
        buffer = std::make_shared<os::mem::buffer>(std::forward<Args> (args)...);
        flag = false;
      }
      catch (std::bad_alloc &e)
      {
        flag = true;
        timer.start(congestion_timeout);
        return nullptr;
      }
      return buffer;
    }

  }; // < class StreamBuffer

  inline size_t StreamBuffer::next_size()
  {
    if (not m_send_buffers.empty()) {
      return m_send_buffers.front()->size();
    }
    return 0;
  }

  inline StreamBuffer::buffer_t StreamBuffer::read_next()
  {

    if (not m_send_buffers.empty()) {
      auto buf = m_send_buffers.front();
      m_send_buffers.pop_front();
      return buf;
    }
    return nullptr;
  }

  inline void StreamBuffer::congested()
  {
    if (m_read_congested)
    {
      handle_read_congestion();
    }
    if (m_write_congested)
    {
      handle_write_congestion();
    }
    //if any of the congestion states are still active make sure the timer is running
    if(m_read_congested or m_write_congested)
    {
      if (!timer.is_running())
      {
        timer.start(congestion_timeout);
      }
    }
    else
    {
      if (timer.is_running())
      {
        timer.stop();
      }
    }
  }

  inline void StreamBuffer::signal_data()
  {
    if (not m_send_buffers.empty())
    {
      if (m_on_data != nullptr){
        //on_data_callback();
        m_on_data();
        if (not m_send_buffers.empty()) {
          m_read_congested=true;
          timer.start(congestion_timeout);
        }
      }
      else if (m_on_read != nullptr)
      {
        for (auto buf : m_send_buffers) {
          // Pop each time, in case callback leads to another call here.
          m_send_buffers.pop_front();
          m_on_read(buf);
        }
      }
    }
  }
} // namespace net
#endif // STREAMBUFFERR_HPP
<commit_msg>0.13.x: if reset callbacks is called in loop exit<commit_after>#ifndef STREAMBUFFERR_HPP
#define STREAMBUFFERR_HPP
#include <net/stream.hpp>
#include <queue>
#include <util/timer.hpp>

namespace net {
  class StreamBuffer : public net::Stream
  {
  public:
    StreamBuffer(Timers::duration_t timeout=std::chrono::microseconds(10))
      : timer({this,&StreamBuffer::congested}),congestion_timeout(timeout) {}
    using buffer_t = os::mem::buf_ptr;
    using Ready_queue  = std::deque<buffer_t>;
    virtual ~StreamBuffer() {
      timer.stop();
    }

    void on_connect(ConnectCallback cb) override {
      m_on_connect = std::move(cb);
    }

    void on_read(size_t, ReadCallback cb) override {
      m_on_read = std::move(cb);
    }
    void on_data(DataCallback cb) override {
      m_on_data = std::move(cb);
    }
    size_t next_size() override;

    buffer_t read_next() override;

    void on_close(CloseCallback cb) override {
      m_on_close = std::move(cb);
    }
    void on_write(WriteCallback cb) override {
      m_on_write = std::move(cb);
    }

    void signal_data();

    bool read_congested() const noexcept
    { return m_read_congested; }

    bool write_congested() const noexcept
    { return m_write_congested; }

    /**
     * @brief Construct a shared read vector used by streams
     * If allocation failed congestion flag is set
     *
     * @param construction parameters
     *
     * @return nullptr on failure, shared_ptr to buffer on success
     */
    template <typename... Args>
    buffer_t construct_read_buffer(Args&&... args)
    {
      return construct_buffer_with_flag(m_read_congested,std::forward<Args> (args)...);
    }

    /**
     * @brief Construct a shared write vector used by streams
     * If allocation failed congestion flag is set
     *
     * @param construction parameters
     *
     * @return nullptr on failure, shared_ptr to buffer on success
     */
    template <typename... Args>
    buffer_t construct_write_buffer(Args&&... args)
    {
      return construct_buffer_with_flag(m_write_congested,std::forward<Args> (args)...);
    }

    virtual void handle_read_congestion() = 0;
    virtual void handle_write_congestion() = 0;
  protected:
    void closed()
    { if (m_on_close) m_on_close(); }
    void connected()
    { if (m_on_connect) m_on_connect(*this); }
    void stream_on_write(int n)
    { if (m_on_write) m_on_write(n); }
    void enqueue_data(buffer_t data)
    { m_send_buffers.push_back(data); }

    void congested();

    CloseCallback getCloseCallback() { return std::move(this->m_on_close); }

    void reset_callbacks() override
    {
      //remove queue and reset congestion flags and busy flag ??
      this->m_on_close = nullptr;
      this->m_on_connect = nullptr;
      this->m_on_read  = nullptr;
      this->m_on_write = nullptr;
      this->m_on_data = nullptr;
    }
    Timer timer;

  private:
    Timer::duration_t congestion_timeout;
    bool  m_write_congested= false;
    bool  m_read_congested = false;

    ConnectCallback  m_on_connect = nullptr;
    ReadCallback     m_on_read    = nullptr;
    DataCallback     m_on_data    = nullptr;
    WriteCallback    m_on_write   = nullptr;
    CloseCallback    m_on_close   = nullptr;
    Ready_queue      m_send_buffers;

    /**
     * @brief Construct a shared vector and set congestion flag if allocation fails
     *
     * @param flag the flag to set true or false on allocation failure
     * @param args arguments to constructing the buffer
     * @return nullptr on failure , shared pointer to buffer on success
     */

    template <typename... Args>
    buffer_t construct_buffer_with_flag(bool &flag,Args&&... args)
    {
      static buffer_t buffer;
      try
      {
        buffer = std::make_shared<os::mem::buffer>(std::forward<Args> (args)...);
        flag = false;
      }
      catch (std::bad_alloc &e)
      {
        flag = true;
        timer.start(congestion_timeout);
        return nullptr;
      }
      return buffer;
    }

  }; // < class StreamBuffer

  inline size_t StreamBuffer::next_size()
  {
    if (not m_send_buffers.empty()) {
      return m_send_buffers.front()->size();
    }
    return 0;
  }

  inline StreamBuffer::buffer_t StreamBuffer::read_next()
  {

    if (not m_send_buffers.empty()) {
      auto buf = m_send_buffers.front();
      m_send_buffers.pop_front();
      return buf;
    }
    return nullptr;
  }

  inline void StreamBuffer::congested()
  {
    if (m_read_congested)
    {
      handle_read_congestion();
    }
    if (m_write_congested)
    {
      handle_write_congestion();
    }
    //if any of the congestion states are still active make sure the timer is running
    if(m_read_congested or m_write_congested)
    {
      if (!timer.is_running())
      {
        timer.start(congestion_timeout);
      }
    }
    else
    {
      if (timer.is_running())
      {
        timer.stop();
      }
    }
  }

  inline void StreamBuffer::signal_data()
  {
    if (not m_send_buffers.empty())
    {
      if (m_on_data != nullptr){
        //on_data_callback();
        m_on_data();
        if (not m_send_buffers.empty()) {
          m_read_congested=true;
          timer.start(congestion_timeout);
        }
      }
      else if (m_on_read != nullptr)
      {
        for (auto buf : m_send_buffers) {
          // Pop each time, in case callback leads to another call here.
          m_send_buffers.pop_front();
          m_on_read(buf);
          if (m_on_read == nullptr) { break; } //if calling m_on_read reset the callbacks exit
        }
      }
    }
  }
} // namespace net
#endif // STREAMBUFFERR_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hd_docu.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 13:52:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "hd_docu.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/cpp/c_namesp.hxx>
#include <ary/cpp/c_class.hxx>
#include <ary/cpp/c_enum.hxx>
#include <ary/cpp/c_tydef.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_vari.hxx>
#include <ary/cpp/c_enuval.hxx>
#include <ary/info/codeinfo.hxx>
#include <ary/info/all_tags.hxx>
#include <ary/info/all_dts.hxx>
#include <adc_cl.hxx>
#include "html_kit.hxx"

using namespace ary::info;
using namespace csi;

using html::DefList;
using html::DefListTerm;
using html::DefListDefinition;
using html::Headline;
using html::Link;

const char *
C_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =
    {
        "ATTENTION!",   "Author",       "Changes",      "Collaborators",
                                                                        "Contact",  // Contact may be unused
        "Copyright",    "Deprecated",   "Description",  "Date of Documentation",
                                                                        "How to Derive from this Class",
        "Heap object - owner is responsible for deletion.",
                        "Important Instances",
                                        "Interface Only",
                                                        "Invariant",    "Lifecycle",
        "Multiplicity", "On Error",     "Persistency",  "Postcondition",
                                                                        "Precondition",
        "Responsibilities",
                        "Return",       "Summary",      "Todos",        "Version",
        "Base Classes", "Exceptions",   "Implements",   "Keywords",     "Parameters",
        "See Also",     "Template Parameters",
                                        "",             "Since "
    };

Docu_Display::Docu_Display( OuputPage_Environment & io_rEnv )
    :   HtmlDisplay_Impl(io_rEnv),
        bUseHtmlInDocuTokens(false),
        pCurClassOverwrite(0)
{
}

Docu_Display::~Docu_Display()
{
}

void
Docu_Display::Assign_Out( csi::xml::Element & o_rOut )
{
    Easy().Enter(o_rOut);
}

void
Docu_Display::Unassign_Out()
{
    Easy().Leave();
}

void
Docu_Display::Display_Namespace( const ary::cpp::Namespace & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Class( const ary::cpp::Class & i_rData )
{
    pCurClassOverwrite = &i_rData;
    i_rData.Info().StoreAt( *this );
    pCurClassOverwrite = 0;
}

void
Docu_Display::Display_Enum( const ary::cpp::Enum & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Typedef( const ary::cpp::Typedef & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Function( const ary::cpp::Function & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Variable( const ary::cpp::Variable & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

// --------------       Interface ary::info::DocuDisplay  ------------------ //

void
Docu_Display::Display_CodeInfo( const CodeInfo & i_rData )
{
    Start_DocuBlock();

    if ( i_rData.IsObsolete() )
    {
        CurOut()
            >> *new html::DefListTerm
                >> *new html::Strong
                    << "D E P R E C A T E D";

    }

    CodeInfo::TagList::const_iterator itEnd = i_rData.Tags().end();
    for ( CodeInfo::TagList::const_iterator it = i_rData.Tags().begin();
          it != itEnd;
          ++it )
    {
         (*it)->StoreAt( *this );
    }

    Finish_DocuBlock();
}

void
Docu_Display::Display_StdTag( const StdTag & i_rData )
{
    csv_assert( int(i_rData.Std_Id()) < int(ary::info::C_eAtTag_NrOfClasses) );

    const ary::info::DocuText::TokenList &
        rText = i_rData.CText().Tokens();
    typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;

    if ( rText.empty() )
        return;
    else if ( rText.size() < 3 )
    {
        bool bIsWhite = true;
        for ( TokenIterator it = rText.begin();
              it != rText.end();
              ++it )
        {
            if (bIsWhite)
                bIsWhite = (*it)->IsWhite();
        }
        if (bIsWhite)
            return;
    }

    Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );
    Write_TagContents( i_rData.CText() );
}

void
Docu_Display::Display_BaseTag( const BaseTag & )
{

}

void
Docu_Display::Display_ExceptionTag( const ExceptionTag & )
{
}

void
Docu_Display::Display_ImplementsTag( const ImplementsTag & )
{
}

void
Docu_Display::Display_KeywordTag( const KeywordTag & )
{
}

void
Docu_Display::Display_ParameterTag( const ParameterTag & i_rData )
{
    Write_TagTitle( "Parameters" );

    adcdisp::ExplanationTable
        aParams( CurOut() >> *new DefListDefinition );

    for ( const ParameterTag * pParam = &i_rData;
          pParam != 0;
          pParam = pParam->GetNext() )   // KORR_FUTURE
    {
        aParams.AddEntry( pParam->ParamName().c_str() );

        Easy().Enter( aParams.Def() );
        Write_Text( pParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_SeeTag( const SeeTag & i_rData )
{
    Write_TagTitle( "See Also" );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;
    Easy().Enter(*dpDef);

    for ( std::vector< ary::QualifiedName >::const_iterator
            it = i_rData.References().begin();
          it != i_rData.References().end();
          ++it )
    {
        Write_LinkableText( (*it) );
        CurOut() << new html::LineBreak;
    }

    Easy().Leave();
}

void
Docu_Display::Display_TemplateTag( const TemplateTag & i_rData )
{
    Write_TagTitle( "Template Parameters" );

    adcdisp::ExplanationTable
        aTplParams( CurOut() >> *new DefListDefinition );

    for ( const TemplateTag * pTplParam = &i_rData;
          pTplParam != 0;
          pTplParam = pTplParam->GetNext() )
    {
        aTplParams.AddEntry( pTplParam->TplParamName().c_str() );

        Easy().Enter( aTplParams.Def() );
        Write_Text( pTplParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_LabelTag( const LabelTag & )
{
}

void
Docu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )
{
    if ( i_rData.Version().empty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay;
    if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        sDisplay = autodoc::CommandLine::Get_()
                        .DisplayOf_SinceTagValue( i_rData.Version() );
    }
    else
    {
        sDisplay = i_rData.Version();
    }

    if (sDisplay.empty())
        return;

    Write_TagTitle( "Since " );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    CurOut() << sDisplay;
    Easy().Leave();
}

void
Docu_Display::Display_DT_Text( const DT_Text & i_rData )
{
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )
{
    // KORR_FUTURE
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )
{
    static char sSpace[300] =
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                        ";
    UINT8 nLength = i_rData.Length();
    sSpace[nLength] = NULCH;
    CurOut() << sSpace;
    sSpace[nLength] = ' ';
}

void
Docu_Display::Display_DT_Eol( const DT_Eol & )
{
    CurOut() << new html::Sbr;
}

void
Docu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )
{
    CurOut() << new xml::XmlCode( i_rData.Text() );
}

void
Docu_Display::Start_DocuBlock()
{
    DYN DefList * dpDefList = new DefList;
    CurOut() << dpDefList;
    Easy().Enter( *dpDefList );
}

void
Docu_Display::Finish_DocuBlock()
{
    Easy().Leave();
}

void
Docu_Display::Write_TagTitle( const char *        i_sText,
                              const char *        )
{
    if ( strcmp(i_sText,"ATTENTION!") == 0 )
    {
        CurOut()
            >> *new html::DefListTerm
                << new html::ClassAttr("attention")
                << i_sText;
    }
    else
    {
        CurOut()
            >> *new html::DefListTerm
                << i_sText;
    }
}

void
Docu_Display::Write_TagContents( const DocuText & i_rDocuText )
{
    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    Write_Text(i_rDocuText);
    Easy().Leave();
}

void
Docu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )
{
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("<pre>");
        bUseHtmlInDocuTokens = false;
    }
    else
    {
         bUseHtmlInDocuTokens = true;
    }
    i_rDocuText.StoreAt( *this );
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("</pre>");
    }
}

void
Docu_Display::Write_TextToken( const udmstri & i_sText )
{
     if ( bUseHtmlInDocuTokens )
        CurOut() << new xml::XmlCode(i_sText);
    else
        CurOut() << i_sText;
}

void
Docu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )
{
    const ary::CodeEntity *
        pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );
    if ( pCe != 0 )
    {
        csi::xml::Element *
            pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );
        CurOut() << pLink;
        Easy().Enter(*pLink);
        Write_QualifiedName(i_sQuName);
        Easy().Leave();
    }
    else
    {
        Write_QualifiedName(i_sQuName);
    }
    CurOut() << " ";
}

void
Docu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )
{
    if ( i_sQuName.IsAbsolute() )
        CurOut() << "::";
    for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();
          it != i_sQuName.end_namespace();
          ++it )
    {
        CurOut() <<  (*it) << "::";
    }
    CurOut() << i_sQuName.LocalName();
    if ( i_sQuName.IsFunction() )
        CurOut() << "()";
}

<commit_msg>INTEGRATION: CWS adc18 (1.10.2); FILE MERGED 2007/10/18 15:23:12 np 1.10.2.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hd_docu.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:27:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "hd_docu.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/cpp/c_gate.hxx>
#include <ary/cpp/c_namesp.hxx>
#include <ary/cpp/c_class.hxx>
#include <ary/cpp/c_enum.hxx>
#include <ary/cpp/c_tydef.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_vari.hxx>
#include <ary/cpp/c_enuval.hxx>
#include <ary/doc/d_oldcppdocu.hxx>
#include <ary/info/all_tags.hxx>
#include <ary/info/all_dts.hxx>
#include <adc_cl.hxx>
#include "html_kit.hxx"
#include "opageenv.hxx"

using namespace ary::info;
using namespace csi;

using html::DefList;
using html::DefListTerm;
using html::DefListDefinition;
using html::Headline;
using html::Link;

const char *
C_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =
    {
        "ATTENTION!",   "Author",       "Changes",      "Collaborators",
                                                                        "Contact",  // Contact may be unused
        "Copyright",    "Deprecated",   "Description",  "Date of Documentation",
                                                                        "How to Derive from this Class",
        "Heap object - owner is responsible for deletion.",
                        "Important Instances",
                                        "Interface Only",
                                                        "Invariant",    "Lifecycle",
        "Multiplicity", "On Error",     "Persistency",  "Postcondition",
                                                                        "Precondition",
        "Responsibilities",
                        "Return",       "Summary",      "Todos",        "Version",
        "Base Classes", "Exceptions",   "Implements",   "Keywords",     "Parameters",
        "See Also",     "Template Parameters",
                                        "",             "Since "
    };

Docu_Display::Docu_Display( OuputPage_Environment & io_rEnv )
    :   HtmlDisplay_Impl(io_rEnv),
        bUseHtmlInDocuTokens(false),
        pCurClassOverwrite(0)
{
}

Docu_Display::~Docu_Display()
{
}

void
Docu_Display::Assign_Out( csi::xml::Element & o_rOut )
{
    Easy().Enter(o_rOut);
}

void
Docu_Display::Unassign_Out()
{
    Easy().Leave();
}

void
Docu_Display::do_Process( const ary::cpp::Namespace & i_rData )
{
    Process(i_rData.Docu());
}

void
Docu_Display::do_Process( const ary::cpp::Class & i_rData )
{
    pCurClassOverwrite = &i_rData;
    Process(i_rData.Docu());
    pCurClassOverwrite = 0;
}

void
Docu_Display::do_Process( const ary::cpp::Enum & i_rData )
{
    Process(i_rData.Docu());
}

void
Docu_Display::do_Process( const ary::cpp::Typedef & i_rData )
{
    Process(i_rData.Docu());
}

void
Docu_Display::do_Process( const ary::cpp::Function & i_rData )
{
    Process(i_rData.Docu());
}

void
Docu_Display::do_Process( const ary::cpp::Variable & i_rData )
{
    Process(i_rData.Docu());
}

// --------------       Interface ary::info::DocuDisplay  ------------------ //

void
Docu_Display::do_Process(const ary::doc::Documentation & i_rData)
{
    if (i_rData.Data() == 0)
        return;

    const ary::doc::OldCppDocu *
        docdata = dynamic_cast< const ary::doc::OldCppDocu* >(i_rData.Data());
    csv_assert(docdata != 0);

    Start_DocuBlock();

    if ( docdata->IsObsolete() )
    {
        CurOut()
            >> *new html::DefListTerm
                >> *new html::Strong
                    << "D E P R E C A T E D";

    }

    ary::doc::OldCppDocu::TagList::const_iterator
        itEnd = docdata->Tags().end();
    for ( ary::doc::OldCppDocu::TagList::const_iterator it = docdata->Tags().begin();
          it != itEnd;
          ++it )
    {
         (*it)->StoreAt( *this );
    }

    Finish_DocuBlock();
}

void
Docu_Display::Display_StdTag( const StdTag & i_rData )
{
    csv_assert( uintt(i_rData.Std_Id()) < uintt(ary::info::C_eAtTag_NrOfClasses) );

    const ary::info::DocuText::TokenList &
        rText = i_rData.CText().Tokens();
    typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;

    if ( rText.empty() )
        return;
    else if ( rText.size() < 3 )
    {
        bool bIsWhite = true;
        for ( TokenIterator it = rText.begin();
              it != rText.end();
              ++it )
        {
            if (bIsWhite)
                bIsWhite = (*it)->IsWhite();
        }
        if (bIsWhite)
            return;
    }

    Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );
    Write_TagContents( i_rData.CText() );
}

void
Docu_Display::Display_BaseTag( const BaseTag & )
{
}

void
Docu_Display::Display_ExceptionTag( const ExceptionTag & )
{
}

void
Docu_Display::Display_ImplementsTag( const ImplementsTag & )
{
}

void
Docu_Display::Display_KeywordTag( const KeywordTag & )
{
}

void
Docu_Display::Display_ParameterTag( const ParameterTag & i_rData )
{
    Write_TagTitle( "Parameters" );

    adcdisp::ExplanationTable
        aParams( CurOut() >> *new DefListDefinition );

    for ( const ParameterTag * pParam = &i_rData;
          pParam != 0;
          pParam = pParam->GetNext() )   // KORR_FUTURE
    {
        aParams.AddEntry( pParam->ParamName().c_str() );

        Easy().Enter( aParams.Def() );
        Write_Text( pParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_SeeTag( const SeeTag & i_rData )
{
    Write_TagTitle( "See Also" );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;
    Easy().Enter(*dpDef);

    for ( std::vector< ary::QualifiedName >::const_iterator
            it = i_rData.References().begin();
          it != i_rData.References().end();
          ++it )
    {
        Write_LinkableText( (*it) );
        CurOut() << new html::LineBreak;
    }

    Easy().Leave();
}

void
Docu_Display::Display_TemplateTag( const TemplateTag & i_rData )
{
    Write_TagTitle( "Template Parameters" );

    adcdisp::ExplanationTable
        aTplParams( CurOut() >> *new DefListDefinition );

    for ( const TemplateTag * pTplParam = &i_rData;
          pTplParam != 0;
          pTplParam = pTplParam->GetNext() )
    {
        aTplParams.AddEntry( pTplParam->TplParamName().c_str() );

        Easy().Enter( aTplParams.Def() );
        Write_Text( pTplParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_LabelTag( const LabelTag & )
{
}

void
Docu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )
{
    if ( i_rData.Version().empty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay;
    if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        sDisplay = autodoc::CommandLine::Get_()
                        .DisplayOf_SinceTagValue( i_rData.Version() );
    }
    else
    {
        sDisplay = i_rData.Version();
    }

    if (sDisplay.empty())
        return;

    Write_TagTitle( "Since " );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    CurOut() << sDisplay;
    Easy().Leave();
}

void
Docu_Display::Display_DT_Text( const DT_Text & i_rData )
{
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )
{
    // KORR_FUTURE
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )
{
    static char sSpace[300] =
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                        ";
    UINT8 nLength = i_rData.Length();
    sSpace[nLength] = NULCH;
    CurOut() << sSpace;
    sSpace[nLength] = ' ';
}

void
Docu_Display::Display_DT_Eol( const DT_Eol & )
{
    CurOut() << new html::Sbr;
}

void
Docu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )
{
    CurOut() << new xml::XmlCode( i_rData.Text() );
}

const ary::cpp::Gate *
Docu_Display::inq_Get_ReFinder() const
{
    return &Env().Gate();
}

void
Docu_Display::Start_DocuBlock()
{
    DYN DefList * dpDefList = new DefList;
    CurOut() << dpDefList;
    Easy().Enter( *dpDefList );
}

void
Docu_Display::Finish_DocuBlock()
{
    Easy().Leave();
}

void
Docu_Display::Write_TagTitle( const char *        i_sText,
                              const char *        )
{
    if ( strcmp(i_sText,"ATTENTION!") == 0 )
    {
        CurOut()
            >> *new html::DefListTerm
                << new html::ClassAttr("attention")
                << i_sText;
    }
    else
    {
        CurOut()
            >> *new html::DefListTerm
                << i_sText;
    }
}

void
Docu_Display::Write_TagContents( const DocuText & i_rDocuText )
{
    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    Write_Text(i_rDocuText);
    Easy().Leave();
}

void
Docu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )
{
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("<pre>");
        bUseHtmlInDocuTokens = false;
    }
    else
    {
         bUseHtmlInDocuTokens = true;
    }
    i_rDocuText.StoreAt( *this );
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("</pre>");
    }
}

void
Docu_Display::Write_TextToken( const String & i_sText )
{
     if ( bUseHtmlInDocuTokens )
        CurOut() << new xml::XmlCode(i_sText);
    else
        CurOut() << i_sText;
}

void
Docu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )
{
    const ary::cpp::CodeEntity *
        pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );
    if ( pCe != 0 )
    {
        csi::xml::Element *
            pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );
        CurOut() << pLink;
        Easy().Enter(*pLink);
        Write_QualifiedName(i_sQuName);
        Easy().Leave();
    }
    else
    {
        Write_QualifiedName(i_sQuName);
    }
    CurOut() << " ";
}

void
Docu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )
{
    if ( i_sQuName.IsAbsolute() )
        CurOut() << "::";
    for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();
          it != i_sQuName.end_namespace();
          ++it )
    {
        CurOut() <<  (*it) << "::";
    }
    CurOut() << i_sQuName.LocalName();
    if ( i_sQuName.IsFunction() )
        CurOut() << "()";
}

<|endoftext|>


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

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

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 "itktubeTubeExtractor.h"
#include "itktubeTubeExtractorIO.h"

#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"

#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>

#include "SegmentTubesCLP.h"

#include <sstream>

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );

// Must follow include of "...CLP.h" and
//   forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  // The timeCollector is used to perform basic profiling of the components
  //   of your algorithm.
  itk::TimeProbesCollectorBase timeCollector;

  // CLIProgressReporter is used to communicate progress with the Slicer GUI
  tube::CLIProgressReporter    progressReporter( "RidgeExtractor",
    CLPProcessInformation );
  progressReporter.Start();

  typedef TPixel                                        PixelType;
  typedef itk::Image< PixelType, VDimension >           ImageType;
  typedef itk::ImageFileReader< ImageType >             ReaderType;

  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;

  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;
  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;
  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;

  typedef float                                         ScaleType;
  typedef itk::Image< ScaleType, VDimension >           ScaleImageType;
  typedef itk::ImageFileReader< ScaleImageType >        ScaleReaderType;

  typedef itk::ContinuousIndex< double, VDimension >    IndexType;
  typedef std::vector< IndexType >                      IndexListType;

  typedef std::vector< ScaleType >                      ScaleListType;

  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;

  typedef typename TubeType::TransformType              TransformType;

  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;

  timeCollector.Start("Load data");
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( inputVolume.c_str() );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Reading volume: Exception caught: "
                        + std::string(err.GetDescription()) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }
  timeCollector.Stop("Load data");
  double progress = 0.1;
  progressReporter.Report( progress );

  typename ImageType::Pointer inputImage = reader->GetOutput();

  double scaleNorm = inputImage->GetSpacing()[0];

  if( scale / scaleNorm < 0.3 )
    {
    tube::ErrorMessage( "Error: Scale < 0.3 is unsupported." );
    return EXIT_FAILURE;
    }

  typename TubeOpType::Pointer tubeOp = TubeOpType::New();

  tubeOp->SetInputImage( inputImage );
  tubeOp->SetRadius( scale / scaleNorm );

  IndexType seedIndex;
  IndexListType seedIndexList;
  seedIndexList.clear();

  ScaleListType seedScaleList;
  seedScaleList.clear();

  if( !seedI.empty() )
    {
    for( unsigned int seedINum=0; seedINum<seedI.size(); ++seedINum )
      {
      for( unsigned int i=0; i<VDimension; i++ )
        {
        seedIndex[i] = seedI[seedINum][i];
        }
      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale / scaleNorm );
      }
    }

  if( !seedP.empty() )
    {
    for(size_t seedNum=0; seedNum<seedP.size(); ++seedNum)
      {
      typename ImageType::PointType point;
      for( unsigned int i=0; i<VDimension; i++ )
        {
        point[i] = seedP[seedNum][i];
        }

      bool transformSuccess =
        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
      if (!transformSuccess)
        {
        std::cerr<<"Could not transform point #"
          <<seedNum<<" to seed index."<<std::endl;
        continue;
        }

      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale / scaleNorm );
      }
    }

  if( !seedListFile.empty() )
    {
    std::ifstream readStream;
    readStream.open( seedListFile.c_str(), std::ios::binary |
      std::ios::in );
    std::string line;
    double seedScale;
    while( std::getline( readStream, line ) )
      {
      std::istringstream iss(line);
      for( unsigned int i = 0; i < VDimension; ++i )
        {
        iss >> seedIndex[i];
        }
      iss >> seedScale;
      }
    seedIndexList.push_back( seedIndex );
    seedScaleList.push_back( seedScale );
    }

  if( !seedMask.empty() )
    {
    typename MaskReaderType::Pointer maskReader = MaskReaderType::New();
    maskReader->SetFileName( seedMask.c_str() );
    try
      {
      maskReader->Update();
      }
    catch( itk::ExceptionObject & err )
      {
      tube::ErrorMessage( "Reading mask: Exception caught: "
                          + std::string(err.GetDescription()) );
      timeCollector.Report();
      return EXIT_FAILURE;
      }
    typename MaskImageType::Pointer maskImage = maskReader->GetOutput();

    if( !scaleMask.empty() )
      {
      typename ScaleReaderType::Pointer scaleReader =
        ScaleReaderType::New();
      scaleReader->SetFileName( scaleMask.c_str() );
      try
        {
        scaleReader->Update();
        }
      catch( itk::ExceptionObject & err )
        {
        tube::ErrorMessage( "Reading scale: Exception caught: "
                            + std::string(err.GetDescription()) );
        timeCollector.Report();
        return EXIT_FAILURE;
        }
      typename ScaleImageType::Pointer scaleImage = scaleReader->GetOutput();

      itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
        maskImage->GetLargestPossibleRegion() );
      itk::ImageRegionConstIterator< ScaleImageType > iterS( scaleImage,
        scaleImage->GetLargestPossibleRegion() );
      while( !iter.IsAtEnd() )
        {
        if( iter.Get() )
          {
          seedIndexList.push_back( iter.GetIndex() );
          seedScaleList.push_back( iterS.Get() / scaleNorm );
          }
        ++iter;
        ++iterS;
        }
      }
    else
      {
      itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
        maskImage->GetLargestPossibleRegion() );
      while( !iter.IsAtEnd() )
        {
        if( iter.Get() )
          {
          seedIndexList.push_back( iter.GetIndex() );
          seedScaleList.push_back( scale / scaleNorm );
          }
        ++iter;
        }
      }
    }

  if( !parametersFile.empty() )
    {
    itk::tube::TubeExtractorIO< ImageType > teReader;
    teReader.SetTubeExtractor( tubeOp );
    teReader.Read( parametersFile.c_str() );
    }

  typename IndexListType::iterator seedIndexIter =
    seedIndexList.begin();
  ScaleListType::iterator seedScaleIter =
    seedScaleList.begin();

  tubeOp->SetDebug( false );
  tubeOp->GetRidgeOp()->SetDebug( false );
  tubeOp->GetRadiusOp()->SetDebug( false );

  if( border > 0 )
    {
    typename ImageType::IndexType minIndx = inputImage->
      GetLargestPossibleRegion().GetIndex();
    typename ImageType::SizeType size = inputImage->
      GetLargestPossibleRegion().GetSize();
    typename ImageType::IndexType maxIndx = minIndx + size;
    for( unsigned int i=0; i<VDimension; ++i )
      {
      minIndx[i] += border;
      maxIndx[i] -= border;
      }
    tubeOp->SetExtractBoundMin( minIndx );
    tubeOp->SetExtractBoundMax( maxIndx );
    }

  timeCollector.Start("Ridge Extractor");
  unsigned int count = 1;
  bool foundOneTube = false;
  tubeOp->GetRidgeOp()->SetDebug( true );
  while( seedIndexIter != seedIndexList.end() )
    {
    tubeOp->SetRadius( *seedScaleIter );

    std::cout << "Extracting from index point " << *seedIndexIter << " at radius "
      << *seedScaleIter << std::endl;
    typename TubeType::Pointer xTube =
      tubeOp->ExtractTube( *seedIndexIter, count );
    if( !xTube.IsNull() )
      {
      tubeOp->AddTube( xTube );
      std::cout << "  Extracted " << xTube->GetPoints().size() << " points."
        << std::endl;
      foundOneTube = true;
      }
    else
      {
      std::stringstream ss;
      ss << "Error: Ridge not found for seed #" << count;
      tube::Message(ss.str());
      }

    ++seedIndexIter;
    ++seedScaleIter;
    ++count;
    }

  if (!foundOneTube)
    {
    tube::ErrorMessage("No Ridge found at all");
    return EXIT_FAILURE;
    }

  // Update tubes transform
  typename TransformType::InputVectorType scaleVector;
  typename TransformType::OffsetType offsetVector;
  typename TransformType::MatrixType directionMatrix;
  typename ImageType::SpacingType spacing = inputImage->GetSpacing();
  typename ImageType::PointType origin = inputImage->GetOrigin();

  for (unsigned int i = 0; i < VDimension; ++i)
    {
    scaleVector[i] = spacing[i];
    offsetVector[i] = origin[i];
    }

  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetScale( scaleVector );
  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetOffset( offsetVector );
  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetMatrix( inputImage->GetDirection() );
  tubeOp->GetTubeGroup()->ComputeObjectToWorldTransform();

  // Save Tubes
  typename SpatialObjectWriterType::Pointer soWriter =
    SpatialObjectWriterType::New();
  soWriter->SetFileName( outputTubeFile );
  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
  soWriter->Update();

  // Save Tube Mask Image
  if( !outputTubeImage.empty() )
    {
    typename MaskWriterType::Pointer writer = MaskWriterType::New();
    writer->SetFileName( outputTubeImage );
    writer->SetInput( tubeOp->GetTubeMaskImage() );
    writer->SetUseCompression( true );
    writer->Update();
    }

  timeCollector.Stop("Ridge Extractor");

  progressReporter.Report( 1.0 );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  // You may need to update this line if, in the project's .xml CLI file,
  //   you change the variable name for the inputVolume.
  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<commit_msg>Fix scale normalization<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

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 "itktubeTubeExtractor.h"
#include "itktubeTubeExtractorIO.h"

#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"

#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>

#include "SegmentTubesCLP.h"

#include <sstream>

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );

// Must follow include of "...CLP.h" and
//   forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  // The timeCollector is used to perform basic profiling of the components
  //   of your algorithm.
  itk::TimeProbesCollectorBase timeCollector;

  // CLIProgressReporter is used to communicate progress with the Slicer GUI
  tube::CLIProgressReporter    progressReporter( "RidgeExtractor",
    CLPProcessInformation );
  progressReporter.Start();

  typedef TPixel                                        PixelType;
  typedef itk::Image< PixelType, VDimension >           ImageType;
  typedef itk::ImageFileReader< ImageType >             ReaderType;

  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;

  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;
  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;
  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;

  typedef float                                         ScaleType;
  typedef itk::Image< ScaleType, VDimension >           ScaleImageType;
  typedef itk::ImageFileReader< ScaleImageType >        ScaleReaderType;

  typedef itk::ContinuousIndex< double, VDimension >    IndexType;
  typedef std::vector< IndexType >                      IndexListType;

  typedef std::vector< ScaleType >                      ScaleListType;

  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;

  typedef typename TubeType::TransformType              TransformType;

  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;

  timeCollector.Start("Load data");
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( inputVolume.c_str() );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Reading volume: Exception caught: "
                        + std::string(err.GetDescription()) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }
  timeCollector.Stop("Load data");
  double progress = 0.1;
  progressReporter.Report( progress );

  typename ImageType::Pointer inputImage = reader->GetOutput();

  double scaleNorm = inputImage->GetSpacing()[0];
  double radius = scale * scaleNorm;
  if( radius < 0.3 )
    {
    tube::ErrorMessage( "Error: Radius (=spacing*scale = "
      <<radius<<") < 0.3 is unsupported." );
    return EXIT_FAILURE;
    }

  typename TubeOpType::Pointer tubeOp = TubeOpType::New();

  tubeOp->SetInputImage( inputImage );
  tubeOp->SetRadius( radius );

  IndexType seedIndex;
  IndexListType seedIndexList;
  seedIndexList.clear();

  ScaleListType seedScaleList;
  seedScaleList.clear();

  if( !seedI.empty() )
    {
    for( unsigned int seedINum=0; seedINum<seedI.size(); ++seedINum )
      {
      for( unsigned int i=0; i<VDimension; i++ )
        {
        seedIndex[i] = seedI[seedINum][i];
        }
      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( radius );
      }
    }

  if( !seedP.empty() )
    {
    for(size_t seedNum=0; seedNum<seedP.size(); ++seedNum)
      {
      typename ImageType::PointType point;
      for( unsigned int i=0; i<VDimension; i++ )
        {
        point[i] = seedP[seedNum][i];
        }

      bool transformSuccess =
        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
      if (!transformSuccess)
        {
        std::cerr<<"Could not transform point #"
          <<seedNum<<" to seed index."<<std::endl;
        continue;
        }

      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( radius );
      }
    }

  if( !seedListFile.empty() )
    {
    std::ifstream readStream;
    readStream.open( seedListFile.c_str(), std::ios::binary |
      std::ios::in );
    std::string line;
    double seedScale;
    while( std::getline( readStream, line ) )
      {
      std::istringstream iss(line);
      for( unsigned int i = 0; i < VDimension; ++i )
        {
        iss >> seedIndex[i];
        }
      iss >> seedScale;
      }
    seedIndexList.push_back( seedIndex );
    seedScaleList.push_back( seedScale );
    }

  if( !seedMask.empty() )
    {
    typename MaskReaderType::Pointer maskReader = MaskReaderType::New();
    maskReader->SetFileName( seedMask.c_str() );
    try
      {
      maskReader->Update();
      }
    catch( itk::ExceptionObject & err )
      {
      tube::ErrorMessage( "Reading mask: Exception caught: "
                          + std::string(err.GetDescription()) );
      timeCollector.Report();
      return EXIT_FAILURE;
      }
    typename MaskImageType::Pointer maskImage = maskReader->GetOutput();

    if( !scaleMask.empty() )
      {
      typename ScaleReaderType::Pointer scaleReader =
        ScaleReaderType::New();
      scaleReader->SetFileName( scaleMask.c_str() );
      try
        {
        scaleReader->Update();
        }
      catch( itk::ExceptionObject & err )
        {
        tube::ErrorMessage( "Reading scale: Exception caught: "
                            + std::string(err.GetDescription()) );
        timeCollector.Report();
        return EXIT_FAILURE;
        }
      typename ScaleImageType::Pointer scaleImage = scaleReader->GetOutput();

      itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
        maskImage->GetLargestPossibleRegion() );
      itk::ImageRegionConstIterator< ScaleImageType > iterS( scaleImage,
        scaleImage->GetLargestPossibleRegion() );
      while( !iter.IsAtEnd() )
        {
        if( iter.Get() )
          {
          seedIndexList.push_back( iter.GetIndex() );
          seedScaleList.push_back( iterS.Get() * scaleNorm );
          }
        ++iter;
        ++iterS;
        }
      }
    else
      {
      itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
        maskImage->GetLargestPossibleRegion() );
      while( !iter.IsAtEnd() )
        {
        if( iter.Get() )
          {
          seedIndexList.push_back( iter.GetIndex() );
          seedScaleList.push_back( radius );
          }
        ++iter;
        }
      }
    }

  if( !parametersFile.empty() )
    {
    itk::tube::TubeExtractorIO< ImageType > teReader;
    teReader.SetTubeExtractor( tubeOp );
    teReader.Read( parametersFile.c_str() );
    }

  typename IndexListType::iterator seedIndexIter =
    seedIndexList.begin();
  ScaleListType::iterator seedScaleIter =
    seedScaleList.begin();

  tubeOp->SetDebug( false );
  tubeOp->GetRidgeOp()->SetDebug( false );
  tubeOp->GetRadiusOp()->SetDebug( false );

  if( border > 0 )
    {
    typename ImageType::IndexType minIndx = inputImage->
      GetLargestPossibleRegion().GetIndex();
    typename ImageType::SizeType size = inputImage->
      GetLargestPossibleRegion().GetSize();
    typename ImageType::IndexType maxIndx = minIndx + size;
    for( unsigned int i=0; i<VDimension; ++i )
      {
      minIndx[i] += border;
      maxIndx[i] -= border;
      }
    tubeOp->SetExtractBoundMin( minIndx );
    tubeOp->SetExtractBoundMax( maxIndx );
    }

  timeCollector.Start("Ridge Extractor");
  unsigned int count = 1;
  bool foundOneTube = false;
  tubeOp->GetRidgeOp()->SetDebug( false );
  while( seedIndexIter != seedIndexList.end() )
    {
    tubeOp->SetRadius( *seedScaleIter );

    std::cout << "Extracting from index point " << *seedIndexIter << " at radius "
      << *seedScaleIter << std::endl;
    typename TubeType::Pointer xTube =
      tubeOp->ExtractTube( *seedIndexIter, count );
    if( !xTube.IsNull() )
      {
      tubeOp->AddTube( xTube );
      std::cout << "  Extracted " << xTube->GetPoints().size() << " points."
        << std::endl;
      foundOneTube = true;
      }
    else
      {
      std::stringstream ss;
      ss << "Error: Ridge not found for seed #" << count;
      tube::Message(ss.str());
      }

    ++seedIndexIter;
    ++seedScaleIter;
    ++count;
    }

  if (!foundOneTube)
    {
    tube::ErrorMessage("No Ridge found at all");
    return EXIT_FAILURE;
    }

  // Update tubes transform
  typename TransformType::InputVectorType scaleVector;
  typename TransformType::OffsetType offsetVector;
  typename TransformType::MatrixType directionMatrix;
  typename ImageType::SpacingType spacing = inputImage->GetSpacing();
  typename ImageType::PointType origin = inputImage->GetOrigin();

  for (unsigned int i = 0; i < VDimension; ++i)
    {
    scaleVector[i] = spacing[i];
    offsetVector[i] = origin[i];
    }

  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetScale( scaleVector );
  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetOffset( offsetVector );
  tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetMatrix( inputImage->GetDirection() );
  tubeOp->GetTubeGroup()->ComputeObjectToWorldTransform();

  // Save Tubes
  typename SpatialObjectWriterType::Pointer soWriter =
    SpatialObjectWriterType::New();
  soWriter->SetFileName( outputTubeFile );
  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
  soWriter->Update();

  // Save Tube Mask Image
  if( !outputTubeImage.empty() )
    {
    typename MaskWriterType::Pointer writer = MaskWriterType::New();
    writer->SetFileName( outputTubeImage );
    writer->SetInput( tubeOp->GetTubeMaskImage() );
    writer->SetUseCompression( true );
    writer->Update();
    }

  timeCollector.Stop("Ridge Extractor");

  progressReporter.Report( 1.0 );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  // You may need to update this line if, in the project's .xml CLI file,
  //   you change the variable name for the inputVolume.
  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<|endoftext|>