text:
// Copyright (c) 2019, Tom Westerhout
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include "config.hpp"
#include "errors.hpp"
#include <boost/align/aligned_allocator.hpp>
#include <mkl.h>
// #include <sleef.h>
#include <torch/extension.h>
#include <immintrin.h>

#if defined(TCM_GCC)
#    pragma GCC diagnostic push
// #    pragma GCC diagnostic ignored "-Wsign-conversion"
// #    pragma GCC diagnostic ignored "-Wsign-promo"
// #    pragma GCC diagnostic ignored "-Wswitch-default"
// #    pragma GCC diagnostic ignored "-Wctor-dtor-privacy"
// #    pragma GCC diagnostic ignored "-Wstrict-overflow"
#    pragma GCC diagnostic ignored "-Wold-style-cast"
#    pragma GCC diagnostic ignored "-Wshadow"
#elif defined(TCM_CLANG)
#    pragma clang diagnostic push
#    pragma clang diagnostic ignored "-Wmissing-noreturn"
#    pragma clang diagnostic ignored "-Wsign-conversion"
#    pragma clang diagnostic ignored "-Wswitch-enum"
#    pragma clang diagnostic ignored "-Wundefined-func-template"
#endif
#include <pybind11/pybind11.h>
#if defined(TCM_GCC)
#    pragma GCC diagnostic pop
#elif defined(TCM_CLANG)
#    pragma clang diagnostic pop
#endif

TCM_NAMESPACE_BEGIN

// ----------------------------- [Activations] ----------------------------- {{{
/// ReLU activation function
struct ReLU {
    auto operator()(float const x) const noexcept -> float
    {
        return std::max(x, 0.0f);
    }

    auto operator()(__m128 const x) const noexcept -> __m128
    {
        return _mm_max_ps(x, _mm_set1_ps(0.0f));
    }

    auto operator()(__m256 const x) const noexcept -> __m256
    {
        return _mm256_max_ps(x, _mm256_set1_ps(0.0f));
    }

    auto operator()(torch::Tensor const& input) const -> torch::Tensor
    {
        return torch::relu(input);
    }
};

/// Softplus activation function
struct Softplus {
    auto operator()(float const x) const noexcept -> float
    {
        return std::log(1.0f + std::exp(x));
    }

    auto operator()(torch::Tensor const& input) const -> torch::Tensor
    {
        return torch::softplus(input);
    }
};

/// Tanh activation function
struct Tanh {
    auto operator()(float const x) const noexcept -> float
    {
        // return Sleef_tanhf_u10(x);
        return std::tanh(x);
    }

#if 0
    auto operator()(__m128 const x) const noexcept -> __m128
    {
        return Sleef_tanhf4_u10sse4(x);
    }

    auto operator()(__m256 const x) const noexcept -> __m256
    {
        return Sleef_tanhf8_u10avx(x);
    }
#endif

    auto operator()(torch::Tensor const& input) const -> torch::Tensor
    {
        return torch::tanh(input);
    }
};

/// Identity activation function
struct Identity {
    template <class T> constexpr decltype(auto) operator()(T&& x) const noexcept
    {
        return std::forward<T>(x);
    }
};
// ----------------------------- [Activations] ----------------------------- }}}

namespace detail {
struct Gemm {
    sgemm_jit_kernel_t func;
    void*              jitter;

    auto operator()(float const* a, float const* b, float* c) const noexcept
        -> void
    {
        (*func)(jitter, const_cast<float*>(a), const_cast<float*>(b), c);
    }
};

template <class Activation>
auto bias_and_activation(size_t batch_size, size_t out_features, float* out,
                         size_t ldim, float const* bias, Activation&& func)
    -> void;
} // namespace detail

// ------------------------- [DisableConversions] -------------------------- {{{
class DisableConversions : public torch::nn::Module {
  public:
    using torch::nn::Module::Module;

    DisableConversions(DisableConversions const&)     = default;
    DisableConversions(DisableConversions&&) noexcept = default;
    DisableConversions& operator=(DisableConversions const&) = default;
    DisableConversions& operator=(DisableConversions&&) noexcept = default;

    // to() functions just throw. We override them to "fail fast".
    virtual void to(torch::Device, torch::Dtype,
                    bool non_blocking = false) override;
    virtual void to(torch::Dtype, bool non_blocking = false) override;
    virtual void to(torch::Device, bool non_blocking = false) override;
};
// ------------------------- [DisableConversions] -------------------------- }}}

// --------------------------- [DenseLayerImpl] ---------------------------- {{{
class DenseLayerImpl : public DisableConversions {
  public:
    using buffer_type =
        std::vector<float, boost::alignment::aligned_allocator<float, 64>>;

  protected:
    buffer_type                   _weight;
    buffer_type                   _bias;
    buffer_type                   _dst;
    int64_t                       _in_features;
    int64_t                       _out_features;
    int64_t                       _batch_size;
    bool                          _with_bias;
    std::shared_ptr<detail::Gemm> _gemm;
    torch::Tensor                 _weight_tensor;
    torch::Tensor                 _bias_tensor;
    torch::Tensor                 _dst_tensor;

  private:
    auto init_buffers() -> void;
    auto init_parameters() -> void;
    auto init_gemm() -> void;

  public:
    DenseLayerImpl(size_t in_features, size_t out_features, size_t batch_size,
                   bool with_bias = true);

    DenseLayerImpl(DenseLayerImpl const& other);
    DenseLayerImpl(DenseLayerImpl&&) = delete;
    DenseLayerImpl& operator=(DenseLayerImpl const&) = delete;
    DenseLayerImpl& operator=(DenseLayerImpl&&) = delete;

    auto           reset() -> void;
    auto           check_input(torch::Tensor const& input) const -> void;
    auto           batch_size(size_t batch_size) -> void;
    constexpr auto batch_size() const noexcept -> size_t;
    constexpr auto weight_tensor() const noexcept -> torch::Tensor const&;
    constexpr auto bias_tensor() const noexcept -> torch::Tensor const&;
};

constexpr auto DenseLayerImpl::weight_tensor() const noexcept
    -> torch::Tensor const&
{
    return _weight_tensor;
}

constexpr auto DenseLayerImpl::bias_tensor() const noexcept
    -> torch::Tensor const&
{
    return _bias_tensor;
}

constexpr auto DenseLayerImpl::batch_size() const noexcept -> size_t
{
    return static_cast<size_t>(_batch_size);
}
// --------------------------- [DenseLayerImpl] ---------------------------- }}}

// ----------------------------- [DenseLayer] ------------------------------ {{{
template <class Activation>
class DenseLayer
    : private Activation
    , public DenseLayerImpl {
  public:
    using DenseLayerImpl::DenseLayerImpl;

  private:
    inline auto apply_bias_and_activation() -> void;
    inline auto forward_fast(torch::Tensor const& input) -> torch::Tensor;
    inline auto forward_slow(torch::Tensor const& input) -> torch::Tensor;

  public:
    inline auto forward(torch::Tensor const& input) -> torch::Tensor;
    inline auto operator()(torch::Tensor const& input) -> torch::Tensor;
};

template <class Activation>
auto DenseLayer<Activation>::apply_bias_and_activation() -> void
{
    TCM_ASSERT(_with_bias || _bias.data() == nullptr, "");
    detail::bias_and_activation(
        static_cast<size_t>(_batch_size), static_cast<size_t>(_out_features),
        _dst.data(), static_cast<size_t>(_out_features), _bias.data(),
        static_cast<Activation const&>(*this));
}

template <class Activation>
auto DenseLayer<Activation>::forward_slow(torch::Tensor const& input)
    -> torch::Tensor
{
    TCM_ASSERT(!_with_bias || _bias_tensor.defined(), "");
    return static_cast<Activation const&>(*this)(
        torch::linear(input, _weight_tensor, _bias_tensor));
}

template <class Activation>
auto DenseLayer<Activation>::forward_fast(torch::Tensor const& input)
    -> torch::Tensor
{
    if (input.dim() == 2) {
        // cblas_sgemm(
        //     /*layout=*/CblasRowMajor, /*transa=*/CblasNoTrans,
        //     /*transb=*/CblasTrans, /*m=*/_batch_size, /*n=*/_out_features,
        //     /*k=*/_in_features,
        //     /*alpha=*/1.0f, /*a=*/input.data<float>(), /*lda=*/_in_features,
        //     /*b=*/_weight.data(), /*ldb=*/_in_features, /*beta=*/0.0f,
        //     /*c=*/_dst.data(), /*ldc=*/_out_features);
        (*_gemm)(static_cast<float const*>(input.data_ptr()), _weight.data(),
                 _dst.data());
        apply_bias_and_activation();
        return _dst_tensor;
    }
    else {
        TCM_ASSERT(input.dim() == 1, "");
        cblas_sgemv(/*layout=*/CblasRowMajor, /*trans=*/CblasNoTrans,
                    /*m=*/_out_features, /*n=*/_in_features,
                    /*alpha=*/1.0f, /*a=*/_weight.data(), /*lda=*/_in_features,
                    /*x=*/input.data<float>(), /*incx=*/1, /*beta*/ 0.0f,
                    /*y=*/_dst.data(), /*incy=*/1);
        detail::bias_and_activation(
            1, static_cast<size_t>(_out_features), _dst.data(),
            static_cast<size_t>(_out_features), _bias.data(),
            static_cast<Activation const&>(*this));
        return torch::from_blob(_dst.data(), {_out_features},
                                torch::TensorOptions{torch::kFloat32});
    }
}

template <class Activation>
auto DenseLayer<Activation>::forward(torch::Tensor const& input)
    -> torch::Tensor
{
    return torch::nn::Module::is_training() ? forward_slow(input)
                                            : forward_fast(input);
}

template <class Activation>
auto DenseLayer<Activation>::operator()(torch::Tensor const& input)
    -> torch::Tensor
{
    return forward(input);
}
// ----------------------------- [DenseLayer] ------------------------------ }}}

// ---------------------------- [AmplitudeNet] ----------------------------- {{{
class AmplitudeNet : public DisableConversions {
    std::shared_ptr<DenseLayer<ReLU>>     _layer_1;
    std::shared_ptr<DenseLayer<ReLU>>     _layer_2;
    std::shared_ptr<DenseLayer<Softplus>> _layer_3;

  public:
    AmplitudeNet(std::array<size_t, 3> sizes, size_t batch_size);
    AmplitudeNet(AmplitudeNet const&);
    AmplitudeNet(AmplitudeNet&&) noexcept = default;
    AmplitudeNet& operator=(AmplitudeNet const&) = delete;
    AmplitudeNet& operator=(AmplitudeNet&&) = delete;

    inline auto batch_size() const noexcept -> size_t;
    auto        operator()(torch::Tensor const& input) const -> torch::Tensor;
};

auto AmplitudeNet::batch_size() const noexcept -> size_t
{
    return _layer_1->batch_size();
}
// ---------------------------- [AmplitudeNet] ----------------------------- }}}

// ------------------------------ [PhaseNet] ------------------------------- {{{
class PhaseNet : public DisableConversions {
    std::shared_ptr<DenseLayer<Tanh>>     _layer_1;
    std::shared_ptr<DenseLayer<Identity>> _layer_2;

  public:
    PhaseNet(std::array<size_t, 2> sizes, size_t batch_size);
    PhaseNet(PhaseNet const& other);
    PhaseNet(PhaseNet&&) noexcept = default;
    PhaseNet& operator=(PhaseNet const& other) = delete;
    PhaseNet& operator=(PhaseNet&&) noexcept = delete;

    inline auto batch_size() const noexcept -> size_t;
    auto        operator()(torch::Tensor input) const -> torch::Tensor;
};

inline auto PhaseNet::batch_size() const noexcept -> size_t
{
    return _layer_1->batch_size();
}
// ------------------------------ [PhaseNet] ------------------------------- }}}

// --------------------------- [CombiningState] ---------------------------- {{{
inline auto combine_amplitude_and_phase(torch::Tensor&       amplitude,
                                        torch::Tensor const& phase)
{
    if (amplitude.dim() == 1) {
        auto amplitude_accessor = amplitude.accessor<float, 1>();
        auto phase_accessor     = phase.accessor<float, 1>();
        TCM_CHECK_SHAPE(amplitude_accessor.size(0), 1);
        TCM_CHECK_SHAPE(phase_accessor.size(0), 2);
        auto const flag = phase_accessor[0] < phase_accessor[1];
        if (flag) { amplitude_accessor[0] *= -1.0f; }
        return;
    }
    auto amplitude_accessor = amplitude.accessor<float, 2>();
    auto phase_accessor     = phase.accessor<float, 2>();
    TCM_CHECK_SHAPE(amplitude_accessor.size(0), phase_accessor.size(0));
    TCM_CHECK_SHAPE(phase_accessor.size(1), 2);
    TCM_CHECK_SHAPE(amplitude_accessor.size(1), 1);
    for (auto i = int64_t{0}; i < amplitude_accessor.size(0); ++i) {
        auto const flag = phase_accessor[i][0] < phase_accessor[i][1];
        if (flag) { amplitude_accessor[i][0] *= -1.0f; }
    }
}

class CombiningState {
    std::shared_ptr<AmplitudeNet> _amplitude;
    std::shared_ptr<PhaseNet>     _phase;

  public:
    CombiningState(std::shared_ptr<AmplitudeNet> amplitude,
                   std::shared_ptr<PhaseNet>     phase)
        : _amplitude{std::move(amplitude)}, _phase{std::move(phase)}
    {}

    CombiningState(CombiningState const& other)
        : _amplitude{std::make_shared<AmplitudeNet>(*other._amplitude)}
        , _phase{std::make_shared<PhaseNet>(*other._phase)}
    {}
    CombiningState(CombiningState&&) noexcept = default;
    CombiningState& operator=(CombiningState const&) = delete;
    CombiningState& operator=(CombiningState&&) noexcept = default;

    auto amplitude() const noexcept -> std::shared_ptr<AmplitudeNet>
    {
        return _amplitude;
    }

    auto phase() const noexcept -> std::shared_ptr<PhaseNet> { return _phase; }

    auto operator()(torch::Tensor const& input) const -> torch::Tensor
    {
        auto       amplitude = (*_amplitude)(input);
        auto const phase     = (*_phase)(input);
        combine_amplitude_and_phase(amplitude, phase);
        return amplitude;
    }
};
// --------------------------- [CombiningState] ---------------------------- }}}

auto bind_networks(py::module m) -> void;

TCM_NAMESPACE_END

namespace pybind11 {
namespace detail {
    template <class Key, class Value>
    struct type_caster<::torch::OrderedDict<Key, Value>> {
      public:
        using type       = ::torch::OrderedDict<Key, Value>;
        using key_conv   = make_caster<Key>;
        using value_conv = make_caster<Value>;

        PYBIND11_TYPE_CASTER(type, _("Dict[") + key_conv::name + _(", ")
                                       + value_conv::name + _("]"));

        auto load(handle src, bool convert) -> bool
        {
            if (!isinstance<dict>(src)) { return false; }
            auto d = reinterpret_borrow<dict>(src);
            value.clear();
            for (auto it : d) {
                key_conv   kconv;
                value_conv vconv;
                if (!kconv.load(it.first.ptr(), convert)
                    || !vconv.load(it.second.ptr(), convert)) {
                    return false;
                }
                value.insert(cast_op<Key&&>(std::move(kconv)),
                             cast_op<Value&&>(std::move(vconv)));
            }
            return true;
        }

        template <typename T>
        static handle cast(T&& src, return_value_policy policy, handle parent)
        {
            dict d;
            auto policy_key   = policy;
            auto policy_value = policy;
            if (!std::is_lvalue_reference<T>::value) {
                policy_key =
                    return_value_policy_override<Key>::policy(policy_key);
                policy_value =
                    return_value_policy_override<Value>::policy(policy_value);
            }
            for (auto&& kv : src) {
                auto key   = reinterpret_steal<object>(key_conv::cast(
                    forward_like<T>(kv.key()), policy_key, parent));
                auto value = reinterpret_steal<object>(value_conv::cast(
                    forward_like<T>(kv.value()), policy_value, parent));
                if (!key || !value) { return handle(); }
                d[key] = value;
            }
            return d.release();
        }
    };
} // namespace detail
} // namespace pybind11

max_stars_repo_name: BagrovAndrey/nqs-playground

max_issues_repo_name: BagrovAndrey/nqs-playground

max_forks_repo_name: BagrovAndrey/nqs-playground


text:
#include "utility/runtime/runtime_helper.h"

#include <sstream>
#include <vector>

#include <deal.II/base/mpi.h>

#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;
using ::testing::HasSubstr;

class UtilityRuntimeHelperTest : public ::testing::Test {
 public:
  const std::string version_{"7.6.9"}, filename{"testfile.input"};
  utility::runtime::RuntimeHelper test_helper{version_};

  void MakeArgv(std::string to_convert);

  std::vector<std::string> arguments_;
  std::vector<char*> argv_vector_;
  char** argv_;
  int argc_;
};

void UtilityRuntimeHelperTest::MakeArgv(std::string to_convert) {
  std::istringstream iss(to_convert);
  std::vector<std::string> arguments(std::istream_iterator<std::string>{iss},
                                     std::istream_iterator<std::string>());
  arguments_ = arguments;
  for (auto& arg : arguments_) {
    argv_vector_.push_back(const_cast<char*>(arg.data()));
  }
  argv_vector_.push_back(nullptr);

  argv_ = const_cast<char**>(argv_vector_.data());
  argc_ = argv_vector_.size() - 1;
}

TEST_F(UtilityRuntimeHelperTest, Version) {
  EXPECT_EQ(test_helper.version(), version_);
}

TEST_F(UtilityRuntimeHelperTest, ProgramHeader) {
  auto header = test_helper.ProgramHeader();
  EXPECT_THAT(header, HasSubstr(version_));
}

TEST_F(UtilityRuntimeHelperTest, HelpMessage) {
  auto help_message = test_helper.HelpMessage();
  EXPECT_NE(help_message, "");
}

TEST_F(UtilityRuntimeHelperTest, PauseProgram) {
  MakeArgv("bart -p " + filename);
  EXPECT_FALSE(test_helper.do_pause());
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.do_pause());
  EXPECT_FALSE(test_helper.show_help());
  EXPECT_EQ(test_helper.filename(), filename);
}

TEST_F(UtilityRuntimeHelperTest, PauseProgramLong) {
  MakeArgv("bart --pause " + filename);
  EXPECT_FALSE(test_helper.do_pause());
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.do_pause());
  EXPECT_FALSE(test_helper.show_help());
  EXPECT_EQ(test_helper.filename(), filename);
}

TEST_F(UtilityRuntimeHelperTest, NoFileName) {
  MakeArgv("bart --pause");
  EXPECT_FALSE(test_helper.do_pause());
  EXPECT_FALSE(test_helper.show_help());
  EXPECT_ANY_THROW({
                     test_helper.ParseArguments(argc_, argv_);
                   });
}

TEST_F(UtilityRuntimeHelperTest, HelpLong) {
  MakeArgv("bart --help");
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.show_help());
}

TEST_F(UtilityRuntimeHelperTest, Help) {
  MakeArgv("bart -h");
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.show_help());
}

TEST_F(UtilityRuntimeHelperTest, UnknownOption) {
  MakeArgv("bart -k " + filename);
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.show_help());
}

TEST_F(UtilityRuntimeHelperTest, UnknownLongOption) {
  MakeArgv("bart --kill " + filename);
  EXPECT_FALSE(test_helper.show_help());
  test_helper.ParseArguments(argc_, argv_);
  EXPECT_TRUE(test_helper.show_help());
}

} // namespace

ext: cc

max_stars_repo_name: SlaybaughLab/Transport

max_issues_repo_name: jsrehak/BART

max_forks_repo_name: jsrehak/BART


text:
#ifndef GIFS_SH_BOMD_CORE_H
#define GIFS_SH_BOMD_CORE_H

#include <armadillo>
#include "qm_interface.hpp"
#include "configreader.hpp"

class BOMD
{
public:
  explicit BOMD(arma::mat& qm_grd, arma::mat& mm_grd);
  virtual ~BOMD() {delete qm;}

  virtual double update_gradient(void);
  virtual bool rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double total_energy);
  // setup from user input
  void setup(FileHandle& fh,
             const arma::uvec& atomicnumbers,
	         arma::mat& qm_crd,
	         arma::mat& mm_crd,
	         arma::vec& mm_chg
          );
  //
protected:
  inline arma::uword NQM(void) const { return qm_grd.n_cols; }
  inline arma::uword NMM(void) const { return mm_grd.n_cols; }
  inline int call_idx() const noexcept { return md_call_idx; };

  /* Config for keys common to all dynamics classes */
  void add_common_keys(ConfigBlockReader& reader);

  /* Child classes will override these methods for own setup */
  virtual ConfigBlockReader setup_reader(void);
  virtual void get_reader_data(ConfigBlockReader& reader);

  QMInterface* qm{nullptr};
  // fixed size
  arma::mat& qm_grd;
  // flexible size
  arma::mat& mm_grd;
  arma::vec energy{};

  // On which surface are we running?
  size_t active_state;

  // To track energy drift from GMX
  double elast = 0, edrift = 0;

private:
  int md_call_idx = 0; // tracks each call to rescale_velocities();
};

class PrintBomd:
    public BOMD
{
public:
  virtual ~PrintBomd() {};
  explicit PrintBomd(arma::mat& qm_grd,
                     arma::mat& mm_grd) : BOMD(qm_grd, mm_grd) {}

  double update_gradient(void) {
    double e = BOMD::update_gradient();
    qm->crd_qm.t().print("qm_crd: ");
    qm->crd_mm.t().print("mm_crd: ");
    qm_grd.t().print("qm_grd");
    mm_grd.t().print("mm_grd");
    return e;
  }

  bool rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double total_energy) {
    BOMD::rescale_velocities(velocities, masses, total_gradient, total_energy);
    velocities.t().print("Velocities:");
    masses.t().print("Masses:");
    total_gradient.t().print("Total Gradient");
    return true;
  }
};

#endif

ext: hpp


text:
#include <boost/algorithm/string.hpp>
#include <Strategy/strategyFactory.h>

namespace StarQuant
{
	std::unique_ptr<StrategyBase> strategyFactory(const string& _algo) {
		/*if (boost::iequals(_algo, "simplecross")) {
			//return make_unique<SimpleCross>();
		}*/
		return nullptr;
	}
}

ext: cpp

max_issues_repo_name: synasy/starquant

max_forks_repo_name: synasy/starquant


text:
/**
 * @file plotting.cpp
 * @brief Tesseract ROS plotting functions.
 *
 * @author Levi Armstrong
 * @date April 15, 2018
 * @version TODO
 * @bug No known bugs
 *
 * @copyright Copyright (c) 2013, Southwest Research Institute
 *
 * @par License
 * Software License Agreement (Apache License)
 * @par
 * 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
 * @par
 * 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 <tesseract_common/macros.h>
TESSERACT_COMMON_IGNORE_WARNINGS_PUSH
#include <future>
#include <thread>
#include <ros/console.h>
#include <Eigen/Geometry>
#include <ros/ros.h>
#include <geometry_msgs/PoseArray.h>
TESSERACT_COMMON_IGNORE_WARNINGS_POP

#include <tesseract_rosutils/plotting.h>
#include <tesseract_rosutils/utils.h>
#include <tesseract_rosutils/conversions.h>

#include <tesseract_command_language/utils/flatten_utils.h>
#include <tesseract_command_language/utils/filter_functions.h>
#include <tesseract_environment/core/environment.h>
#include <tesseract_command_language/command_language.h>

namespace tesseract_rosutils
{
ROSPlotting::ROSPlotting(std::string root_link, std::string topic_namespace)
  : root_link_(root_link), topic_namespace_(topic_namespace)
{
  ros::NodeHandle nh;

  trajectory_pub_ =
      nh.advertise<tesseract_msgs::Trajectory>(topic_namespace + "/display_tesseract_trajectory", 1, true);
  collisions_pub_ = nh.advertise<visualization_msgs::MarkerArray>(topic_namespace + "/display_collisions", 1, true);
  arrows_pub_ = nh.advertise<visualization_msgs::MarkerArray>(topic_namespace + "/display_arrows", 1, true);
  axes_pub_ = nh.advertise<visualization_msgs::MarkerArray>(topic_namespace + "/display_axes", 1, true);
  tool_path_pub_ = nh.advertise<geometry_msgs::PoseArray>(topic_namespace + "/display_tool_path", 1, true);
}

bool ROSPlotting::init(tesseract_environment::Environment::ConstPtr env)
{
  env_ = env;
  return true;
}

bool ROSPlotting::isConnected() const { return true; }

void ROSPlotting::waitForConnection(long seconds) const
{
  const ros::WallTime start_time = ros::WallTime::now();
  const ros::WallDuration wall_timeout{ static_cast<double>(seconds) };
  while (ros::ok())
  {
    if (isConnected())
      return;

    if (wall_timeout >= ros::WallDuration(0))
    {
      const ros::WallTime current_time = ros::WallTime::now();
      if ((current_time - start_time) >= wall_timeout)
        return;
    }

    ros::WallDuration(0.02).sleep();
    ros::spinOnce();
  }

  return;
}

void ROSPlotting::plotEnvironment(tesseract_environment::Environment::ConstPtr /*env*/) {}

void ROSPlotting::plotEnvironmentState(tesseract_environment::EnvState::ConstPtr /*state*/) {}

void ROSPlotting::plotTrajectory(const tesseract_msgs::Trajectory& traj)
{
  trajectory_pub_.publish(traj);
  ros::spinOnce();
}

void ROSPlotting::plotTrajectory(const std::vector<std::string>& joint_names,
                                 const Eigen::Ref<const tesseract_common::TrajArray>& traj)
{
  tesseract_msgs::Trajectory msg;
  tesseract_common::JointTrajectory trajectory;
  trajectory.joint_names = joint_names;
  trajectory.trajectory = traj;

  // Set the joint trajectory message
  toMsg(msg.joint_trajectory, trajectory);

  plotTrajectory(msg);
}

void ROSPlotting::plotTrajectory(const tesseract_common::JointTrajectory& traj)
{
  tesseract_msgs::Trajectory msg;

  // Set the joint trajectory message
  toMsg(msg.joint_trajectory, traj);

  plotTrajectory(msg);
}

void ROSPlotting::plotTrajectory(const tesseract_planning::Instruction& instruction)
{
  tesseract_msgs::Trajectory msg;

  // Set tesseract state information
  if (env_ != nullptr)
    toMsg(msg.tesseract_state, *(env_));

  // Set the joint trajectory message
  toJointTrajectory(msg.joint_trajectory, instruction);

  plotTrajectory(msg);
}

void ROSPlotting::plotTrajectory(const std::vector<std::string>& joint_names,
                                 const Eigen::Ref<const tesseract_common::TrajArray>& traj,
                                 const tesseract_environment::Environment::ConstPtr& env)
{
  tesseract_msgs::Trajectory msg;

  // Set tesseract state information
  toMsg(msg.tesseract_state, *env);

  // Set the joint trajectory message
  toMsg(msg.joint_trajectory, *(env->getCurrentState()), joint_names, traj);

  plotTrajectory(msg);
}

void ROSPlotting::plotToolPath(const tesseract_planning::Instruction& instruction)
{
  using namespace tesseract_planning;

  if (env_ == nullptr)
  {
    ROS_ERROR("plotToolPath: requires that the plotter be initialized with a tesseract!");
    return;
  }

  geometry_msgs::PoseArray tool_path;
  tool_path.header.frame_id = env_->getRootLinkName();
  tesseract_environment::StateSolver::Ptr state_solver = env_->getStateSolver();
  if (isCompositeInstruction(instruction))
  {
    const auto* ci = instruction.cast_const<CompositeInstruction>();

    // Assume all the plan instructions have the same manipulator as the composite
    assert(!ci->getManipulatorInfo().empty());
    const ManipulatorInfo& composite_mi = ci->getManipulatorInfo();

    auto composite_mi_fwd_kin = env_->getManipulatorManager()->getFwdKinematicSolver(composite_mi.manipulator);
    if (composite_mi_fwd_kin == nullptr)
    {
      ROS_ERROR_STREAM("plotToolPath: Manipulator: " << composite_mi.manipulator << " does not exist!");
      return;
    }
    const std::string& tip_link = composite_mi_fwd_kin->getTipLinkName();

    std::vector<std::reference_wrapper<const Instruction>> fi = tesseract_planning::flatten(*ci, planFilter);
    if (fi.empty())
      fi = tesseract_planning::flatten(*ci, moveFilter);

    for (const auto& i : fi)
    {
      ManipulatorInfo manip_info;

      // Check for updated manipulator information and get waypoint
      Waypoint wp = NullWaypoint();
      if (isPlanInstruction(i.get()))
      {
        const auto* pi = i.get().cast_const<PlanInstruction>();
        manip_info = composite_mi.getCombined(pi->getManipulatorInfo());
        wp = pi->getWaypoint();
      }
      else if (isMoveInstruction(i.get()))
      {
        const auto* mi = i.get().cast_const<MoveInstruction>();
        manip_info = composite_mi.getCombined(mi->getManipulatorInfo());
        wp = mi->getWaypoint();
      }

      // Extract TCP
      Eigen::Isometry3d tcp = env_->findTCP(manip_info);

      if (isStateWaypoint(wp))
      {
        const auto* swp = wp.cast_const<StateWaypoint>();
        assert(static_cast<long>(swp->joint_names.size()) == swp->position.size());
        tesseract_environment::EnvState::Ptr state = state_solver->getState(swp->joint_names, swp->position);
        geometry_msgs::Pose p;
        tesseract_rosutils::toMsg(p, state->link_transforms[tip_link] * tcp);
        tool_path.poses.push_back(p);
      }
      else if (isJointWaypoint(wp))
      {
        const auto* jwp = wp.cast_const<JointWaypoint>();
        assert(static_cast<long>(jwp->joint_names.size()) == jwp->size());
        tesseract_environment::EnvState::Ptr state = state_solver->getState(jwp->joint_names, *jwp);
        geometry_msgs::Pose p;
        tesseract_rosutils::toMsg(p, state->link_transforms[tip_link] * tcp);
        tool_path.poses.push_back(p);
      }
      else if (isCartesianWaypoint(wp))
      {
        const auto* cwp = wp.cast_const<CartesianWaypoint>();
        if (manip_info.working_frame.empty())
        {
          geometry_msgs::Pose p;
          tesseract_rosutils::toMsg(p, (*cwp));
          tool_path.poses.push_back(p);
        }
        else
        {
          tesseract_environment::EnvState::ConstPtr state = env_->getCurrentState();
          geometry_msgs::Pose p;
          tesseract_rosutils::toMsg(p, state->link_transforms.at(manip_info.working_frame) * (*cwp));
          tool_path.poses.push_back(p);
        }
      }
      else
      {
        ROS_ERROR("plotTrajectoy: Unsupported Waypoint Type!");
      }
    }
  }
  else if (isPlanInstruction(instruction))
  {
    assert(isPlanInstruction(instruction));
    const auto* pi = instruction.cast_const<PlanInstruction>();

    // Assume all the plan instructions have the same manipulator as the composite
    assert(!pi->getManipulatorInfo().empty());
    const ManipulatorInfo& composite_mi = pi->getManipulatorInfo();
    ManipulatorInfo manip_info = composite_mi.getCombined(pi->getManipulatorInfo());

    auto composite_mi_fwd_kin = env_->getManipulatorManager()->getFwdKinematicSolver(manip_info.manipulator);
    if (composite_mi_fwd_kin == nullptr)
    {
      ROS_ERROR_STREAM("plotToolPath: Manipulator: " << manip_info.manipulator << " does not exist!");
      return;
    }
    const std::string& tip_link = composite_mi_fwd_kin->getTipLinkName();

    // Extract TCP
    Eigen::Isometry3d tcp = env_->findTCP(manip_info);

    if (isStateWaypoint(pi->getWaypoint()))
    {
      const auto* swp = pi->getWaypoint().cast_const<StateWaypoint>();
      assert(static_cast<long>(swp->joint_names.size()) == swp->position.size());
      tesseract_environment::EnvState::Ptr state = state_solver->getState(swp->joint_names, swp->position);
      geometry_msgs::Pose p;
      tesseract_rosutils::toMsg(p, state->link_transforms[tip_link] * tcp);
      tool_path.poses.push_back(p);
    }
    else if (isJointWaypoint(pi->getWaypoint()))
    {
      const auto* jwp = pi->getWaypoint().cast_const<JointWaypoint>();
      assert(static_cast<long>(jwp->joint_names.size()) == jwp->size());
      tesseract_environment::EnvState::Ptr state = state_solver->getState(jwp->joint_names, *jwp);
      geometry_msgs::Pose p;
      tesseract_rosutils::toMsg(p, state->link_transforms[tip_link] * tcp);
      tool_path.poses.push_back(p);
    }
    else if (isCartesianWaypoint(pi->getWaypoint()))
    {
      const auto* cwp = pi->getWaypoint().cast_const<CartesianWaypoint>();
      if (manip_info.working_frame.empty())
      {
        geometry_msgs::Pose p;
        tesseract_rosutils::toMsg(p, (*cwp));
        tool_path.poses.push_back(p);
      }
      else
      {
        tesseract_environment::EnvState::ConstPtr state = env_->getCurrentState();
        geometry_msgs::Pose p;
        tesseract_rosutils::toMsg(p, state->link_transforms.at(manip_info.working_frame) * (*cwp));
        tool_path.poses.push_back(p);
      }
    }
    else
    {
      ROS_ERROR("plotTrajectoy: Unsupported Waypoint Type!");
    }
  }
  else
  {
    ROS_ERROR("plotTrajectoy: Unsupported Instruction Type!");
  }

  tool_path_pub_.publish(tool_path);
  ros::spinOnce();
}

void ROSPlotting::plotContactResults(const std::vector<std::string>& link_names,
                                     const tesseract_collision::ContactResultVector& dist_results,
                                     const Eigen::Ref<const Eigen::VectorXd>& safety_distances)
{
  visualization_msgs::MarkerArray msg = getContactResultsMarkerArrayMsg(
      marker_counter_, root_link_, topic_namespace_, ros::Time::now(), link_names, dist_results, safety_distances);
  if (!dist_results.empty())
  {
    collisions_pub_.publish(msg);
    ros::spinOnce();
  }
}

void ROSPlotting::plotArrow(const Eigen::Ref<const Eigen::Vector3d>& pt1,
                            const Eigen::Ref<const Eigen::Vector3d>& pt2,
                            const Eigen::Ref<const Eigen::Vector4d>& rgba,
                            double scale)
{
  visualization_msgs::MarkerArray msg;
  auto marker =
      getMarkerArrowMsg(marker_counter_, root_link_, topic_namespace_, ros::Time::now(), pt1, pt2, rgba, scale);
  msg.markers.push_back(marker);
  arrows_pub_.publish(msg);
  ros::spinOnce();
}

void ROSPlotting::plotAxis(const Eigen::Isometry3d& axis, double scale)
{
  visualization_msgs::MarkerArray msg;
  Eigen::Vector3d x_axis = axis.matrix().block<3, 1>(0, 0);
  Eigen::Vector3d y_axis = axis.matrix().block<3, 1>(0, 1);
  Eigen::Vector3d z_axis = axis.matrix().block<3, 1>(0, 2);
  Eigen::Vector3d position = axis.matrix().block<3, 1>(0, 3);

  auto marker = getMarkerCylinderMsg(marker_counter_,
                                     root_link_,
                                     topic_namespace_,
                                     ros::Time::now(),
                                     position,
                                     position + x_axis,
                                     Eigen::Vector4d(1, 0, 0, 1),
                                     scale);
  msg.markers.push_back(marker);

  marker = getMarkerCylinderMsg(marker_counter_,
                                root_link_,
                                topic_namespace_,
                                ros::Time::now(),
                                position,
                                position + y_axis,
                                Eigen::Vector4d(0, 1, 0, 1),
                                scale);
  msg.markers.push_back(marker);

  marker = getMarkerCylinderMsg(marker_counter_,
                                root_link_,
                                topic_namespace_,
                                ros::Time::now(),
                                position,
                                position + z_axis,
                                Eigen::Vector4d(0, 0, 1, 1),
                                scale);
  msg.markers.push_back(marker);

  axes_pub_.publish(msg);
}

void ROSPlotting::clear()
{
  // Remove old arrows
  marker_counter_ = 0;
  visualization_msgs::MarkerArray msg;
  visualization_msgs::Marker marker;
  marker.header.frame_id = root_link_;
  marker.header.stamp = ros::Time();
  marker.ns = topic_namespace_;
  marker.id = 0;
  marker.type = visualization_msgs::Marker::ARROW;
  marker.action = visualization_msgs::Marker::DELETEALL;
  msg.markers.push_back(marker);
  collisions_pub_.publish(msg);
  arrows_pub_.publish(msg);
  axes_pub_.publish(msg);
  ros::spinOnce();
}

static void waitForInputAsync()
{
  ROS_ERROR("Hit enter key to step optimization!");
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

void ROSPlotting::waitForInput()
{
  std::chrono::microseconds timeout(1);
  std::future<void> future = std::async(std::launch::async, waitForInputAsync);
  while (future.wait_for(timeout) != std::future_status::ready)
    ros::spinOnce();
}

const std::string& ROSPlotting::getRootLink() const { return root_link_; }

visualization_msgs::Marker ROSPlotting::getMarkerArrowMsg(int& id_counter,
                                                          const std::string& frame_id,
                                                          const std::string& ns,
                                                          const ros::Time& time_stamp,
                                                          const Eigen::Ref<const Eigen::Vector3d>& pt1,
                                                          const Eigen::Ref<const Eigen::Vector3d>& pt2,
                                                          const Eigen::Ref<const Eigen::Vector4d>& rgba,
                                                          double scale)
{
  visualization_msgs::Marker marker;
  marker.header.frame_id = frame_id;
  marker.header.stamp = time_stamp;
  marker.ns = ns;
  marker.id = ++id_counter;
  marker.type = visualization_msgs::Marker::ARROW;
  marker.action = visualization_msgs::Marker::ADD;

  Eigen::Vector3d x, y, z;
  x = (pt2 - pt1).normalized();
  marker.pose.position.x = pt1(0);
  marker.pose.position.y = pt1(1);
  marker.pose.position.z = pt1(2);

  y = x.unitOrthogonal();
  z = (x.cross(y)).normalized();
  Eigen::Matrix3d rot;
  rot.col(0) = x;
  rot.col(1) = y;
  rot.col(2) = z;
  Eigen::Quaterniond q(rot);
  q.normalize();
  marker.pose.orientation.x = q.x();
  marker.pose.orientation.y = q.y();
  marker.pose.orientation.z = q.z();
  marker.pose.orientation.w = q.w();

  marker.scale.x = std::abs((pt2 - pt1).norm());
  marker.scale.y = scale;
  marker.scale.z = scale;

  marker.color.r = static_cast<float>(rgba(0));
  marker.color.g = static_cast<float>(rgba(1));
  marker.color.b = static_cast<float>(rgba(2));
  marker.color.a = static_cast<float>(rgba(3));

  return marker;
}

visualization_msgs::Marker ROSPlotting::getMarkerCylinderMsg(int& id_counter,
                                                             const std::string& frame_id,
                                                             const std::string& ns,
                                                             const ros::Time& time_stamp,
                                                             const Eigen::Ref<const Eigen::Vector3d>& pt1,
                                                             const Eigen::Ref<const Eigen::Vector3d>& pt2,
                                                             const Eigen::Ref<const Eigen::Vector4d>& rgba,
                                                             double scale)
{
  visualization_msgs::Marker marker;
  marker.header.frame_id = frame_id;
  marker.header.stamp = time_stamp;
  marker.ns = ns;
  marker.id = ++id_counter;
  marker.type = visualization_msgs::Marker::CYLINDER;
  marker.action = visualization_msgs::Marker::ADD;

  double length = scale * std::abs((pt2 - pt1).norm());
  Eigen::Vector3d x, y, z, center;
  z = (pt2 - pt1).normalized();
  center = pt1 + (length / 2.0) * z;
  marker.pose.position.x = center(0);
  marker.pose.position.y = center(1);
  marker.pose.position.z = center(2);

  y = z.unitOrthogonal();
  x = (y.cross(z)).normalized();
  Eigen::Matrix3d rot;
  rot.col(0) = x;
  rot.col(1) = y;
  rot.col(2) = z;
  Eigen::Quaterniond q(rot);
  q.normalize();
  marker.pose.orientation.x = q.x();
  marker.pose.orientation.y = q.y();
  marker.pose.orientation.z = q.z();
  marker.pose.orientation.w = q.w();

  marker.scale.x = length / 20.0;
  marker.scale.y = length / 20.0;
  marker.scale.z = length;

  marker.color.r = static_cast<float>(rgba(0));
  marker.color.g = static_cast<float>(rgba(1));
  marker.color.b = static_cast<float>(rgba(2));
  marker.color.a = static_cast<float>(rgba(3));

  return marker;
}

visualization_msgs::MarkerArray
ROSPlotting::getContactResultsMarkerArrayMsg(int& id_counter,
                                             const std::string& frame_id,
                                             const std::string& ns,
                                             const ros::Time& time_stamp,
                                             const std::vector<std::string>& link_names,
                                             const tesseract_collision::ContactResultVector& dist_results,
                                             const Eigen::Ref<const Eigen::VectorXd>& safety_distances)
{
  visualization_msgs::MarkerArray msg;
  for (unsigned i = 0; i < dist_results.size(); ++i)
  {
    const tesseract_collision::ContactResult& dist = dist_results[i];
    const double& safety_distance = safety_distances[i];

    Eigen::Vector4d rgba;
    if (dist.distance < 0)
    {
      rgba << 1.0, 0.0, 0.0, 1.0;
    }
    else if (dist.distance < safety_distance)
    {
      rgba << 1.0, 1.0, 0.0, 1.0;
    }
    else
    {
      rgba << 0.0, 1.0, 0.0, 1.0;
    }

    if (dist.cc_type[0] == tesseract_collision::ContinuousCollisionType::CCType_Between)
    {
      Eigen::Vector4d cc_rgba;
      cc_rgba << 0.0, 0.0, 1.0, 1.0;
      auto marker = getMarkerArrowMsg(id_counter,
                                      frame_id,
                                      ns,
                                      time_stamp,
                                      dist.transform[0] * dist.nearest_points_local[0],
                                      dist.cc_transform[0] * dist.nearest_points_local[0],
                                      cc_rgba,
                                      0.01);
      msg.markers.push_back(marker);
    }

    if (dist.cc_type[1] == tesseract_collision::ContinuousCollisionType::CCType_Between)
    {
      Eigen::Vector4d cc_rgba;
      cc_rgba << 0.0, 0.0, 0.5, 1.0;
      auto marker = getMarkerArrowMsg(id_counter,
                                      frame_id,
                                      ns,
                                      time_stamp,
                                      dist.transform[1] * dist.nearest_points_local[1],
                                      dist.cc_transform[1] * dist.nearest_points_local[1],
                                      cc_rgba,
                                      0.01);
      msg.markers.push_back(marker);
    }

    auto it0 = std::find(link_names.begin(), link_names.end(), dist.link_names[0]);
    auto it1 = std::find(link_names.begin(), link_names.end(), dist.link_names[1]);

    if (it0 != link_names.end() && it1 != link_names.end())
    {
      auto marker0 = getMarkerArrowMsg(
          id_counter, frame_id, ns, time_stamp, dist.nearest_points[0], dist.nearest_points[1], rgba, 0.01);
      msg.markers.push_back(marker0);

      auto marker1 = getMarkerArrowMsg(
          id_counter, frame_id, ns, time_stamp, dist.nearest_points[1], dist.nearest_points[0], rgba, 0.01);
      msg.markers.push_back(marker1);
    }
    else if (it0 != link_names.end())
    {
      auto marker = getMarkerArrowMsg(
          id_counter, frame_id, ns, time_stamp, dist.nearest_points[1], dist.nearest_points[0], rgba, 0.01);
      msg.markers.push_back(marker);
    }
    else
    {
      auto marker = getMarkerArrowMsg(
          id_counter, frame_id, ns, time_stamp, dist.nearest_points[0], dist.nearest_points[1], rgba, 0.01);
      msg.markers.push_back(marker);
    }
  }

  return msg;
}

}  // namespace tesseract_rosutils


text:
// Construct python objects from shared pointers in the context

#ifndef ICETRAY_PYTHON_CONTEXT_SUITE_HPP_INCLUDED_SUITE_HPP_INCLUDED
#define ICETRAY_PYTHON_CONTEXT_SUITE_HPP_INCLUDED_SUITE_HPP_INCLUDED

#include <boost/python/def_visitor.hpp>
#include <icetray/I3Context.h>
#include <icetray/name_of.h>

namespace icetray { namespace python {

template <typename ServiceType>
class context_suite : public boost::python::def_visitor<context_suite<ServiceType > > {
public:

	template <typename Class>
	static void
	visit (Class& cl)
	{
		cl
			.def("from_context", &context_suite<ServiceType>::GetFromContext)
			.staticmethod("from_context")
			.def("put_in_context", &context_suite<ServiceType>::PutInContext)
			;
	}

private:

	typedef boost::shared_ptr<ServiceType> ServicePtr;

	static ServicePtr
	GetFromContext(const I3Context &ctx, const std::string &name)
	{
		ServicePtr service = ctx.Get<ServicePtr>(name);
		if (!service) {
			std::string mesg("The context contains no object of type '");
			mesg += icetray::name_of<ServiceType>();
			mesg += "' at key '";
			mesg += name;
			mesg += "'.";
			PyErr_SetString(PyExc_KeyError, mesg.c_str());
			throw boost::python::error_already_set();
		}

		return service;
	}

	static bool
	PutInContext(ServicePtr self, I3Context &ctx, const std::string &name)
	{
		return ctx.Put(self, name);
	}

};

}} // namespace icetray::python

#endif


text:
#include <Eigen/Core>

#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<boost::uint8_t, 6, 2> test_uchar_6_2(const Eigen::Matrix<boost::uint8_t, 6, 2> & M)
{
	return M;
}
void export_uchar_6_2()
{
	boost::python::def("test_uchar_6_2",test_uchar_6_2);
}

max_stars_repo_name: PushyamiKaveti/kalibr

max_issues_repo_name: PushyamiKaveti/kalibr

max_forks_repo_name: PushyamiKaveti/kalibr


text:
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ros/ros.h>
#include <sensor_msgs/CompressedImage.h>
#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <boost/thread/mutex.hpp>

#include "et7/GazeCoordinates.h"
#include "et7/GazeDirection.h"
#include "ecsam_definitions.h"

#define VISUALISE
//#define SIMULATE_EYE_GAZE
#define PUBLISH_GAZE_COORDINATES

#define ADDRESS_ET7   "169.254.181.51"
#define PORT_ET7      51000
#define SAMPLING_RATE (1/29.97) // 29.97 hz

#define SCENE_CAMERA_FRAME "et7_scene_camera_frame"

#define SCENE_CAMERA_RESOLUTION_HORIZONTAL 640
#define SCENE_CAMERA_RESOLUTION_VERTICAL   480
#define SCENE_CAMERA_FOV_HORIZONTAL        (52.5939786 *M_PI/180.0) // must be less than 180 deg
#define SCENE_CAMERA_FOV_VERTICAL          (44.397125  *M_PI/180.0) // must be less than 180 deg

#ifdef VISUALISE

#include <visualization_msgs/Marker.h>

#define VISUALISATION_MARKER_COLOUR_R    0
#define VISUALISATION_MARKER_COLOUR_G    1
#define VISUALISATION_MARKER_COLOUR_B    0.75
#define VISUALISATION_MARKER_LENGTH      100 // length in the direction of camera Z-axis
//    #define VISUALISATION_MARKER_FIXED_WIDTH 0.005 // keep undefined to use correlation distances
#endif

#define FLUSH_BUFFER_SIZE 1000000

#define COMMAND_SEND_BUFFER_SIZE    20
#define MSG_ASL_SIGNATURE_0         0x20 // " "
#define MSG_ASL_SIGNATURE_1         0x41 // "A"
#define MSG_ASL_SIGNATURE_2         0x53 // "S"
#define MSG_ASL_SIGNATURE_3         0x4C // "L"
#define CMD_SET_CONNECT_TYPE        0x07
#define SOCKET_TYPE_SVIDEO_TCP      0x07
#define REPLY_DATA_BEGINNING        56
#define REPLY_DATA_SIZE             9 // 5 for system data + 2 horizontal coordinate + 2 vertical coordinate

class ET7SceneVideoSteamTcpClass
{
 public:
  ET7SceneVideoSteamTcpClass();

  ~ET7SceneVideoSteamTcpClass();

 private:
  // Variables
  int command_socket_, video_socket_;
  struct sockaddr_in server_et7_;
  uint32_t reply_msg_size_;
  bool first_reply_;

  ros::NodeHandle n_;
#ifdef PUBLISH_GAZE_COORDINATES
  ros::Publisher pub_gaze_coordinates_;
#endif
  ros::Subscriber sub_ecsam_user_command_;
  ros::Publisher pub_gaze_direction_;
  ros::Publisher pub_blinking_;
  ros::Publisher pub_scene_video_;
  ros::Timer reply_callback_timer_;
  sensor_msgs::CompressedImage scene_image_;
  boost::mutex mutex_user_command_;

  bool previous_blink_state_, command_received_;
  std::string command_;

  // Methods
  void requestVideoConnection();

  void replyCallback(const ros::TimerEvent &);

  void publishGazeDirection(const float &horizontal_coordinate, const float &vertical_coordinate);

  void userCommandCallback(const std_msgs::StringConstPtr &command);

#ifdef VISUALISE
  ros::Publisher pub_marker_;
  visualization_msgs::Marker marker_;

  void gazeMarkerSetup();

  void visualiseGazeDirection(const double &x, const double &y);

#endif
};

ET7SceneVideoSteamTcpClass::ET7SceneVideoSteamTcpClass()
{
  // Definitions of gaze publishers
#ifdef PUBLISH_GAZE_COORDINATES
  pub_gaze_coordinates_ = n_.advertise<et7::GazeCoordinates>("et7/gaze_coordinates", 1);
#endif
  sub_ecsam_user_command_ = n_.subscribe<std_msgs::String>(std::string(ECSAM_TOPIC_COMMAND), 1,
                                                           &ET7SceneVideoSteamTcpClass::userCommandCallback, this);
  pub_gaze_direction_ = n_.advertise<et7::GazeDirection>("et7/gaze_direction", 1);
  pub_blinking_ = n_.advertise<std_msgs::Bool>("et7/blinking", 10);

#ifdef VISUALISE
  gazeMarkerSetup();
  pub_marker_ = n_.advertise<visualization_msgs::Marker>("visualization_marker", 1);
  command_ = ECSAM_COMMAND_PLACE;
#endif

#ifdef SIMULATE_EYE_GAZE
  ros::AsyncSpinner simulation_spinner(2);
  simulation_spinner.start();
      while(ros::ok()) {
//            for (int vertical_coordinate = 0; vertical_coordinate < SCENE_CAMERA_RESOLUTION_VERTICAL + 1; vertical_coordinate = vertical_coordinate + SCENE_CAMERA_RESOLUTION_VERTICAL/20.0)
//            {
//                for (int horizontal_coordinate = 0; horizontal_coordinate < SCENE_CAMERA_RESOLUTION_HORIZONTAL + 1; horizontal_coordinate = horizontal_coordinate + SCENE_CAMERA_RESOLUTION_HORIZONTAL/20.0)
//                {

//            int START_VERTICAL = 0;
//            int START_HORIZONTAL = 150;
//            int END_VERTICAL = 100;
//            int END_HORIZONTAL = 200;
//            int STEP_VERTICAL = 3;
//            int STEP_HORIZONTAL = 2;
//            for (int vertical_coordinate = START_VERTICAL; vertical_coordinate < END_VERTICAL + 1; vertical_coordinate = vertical_coordinate + STEP_VERTICAL)
//            {
//                for (int horizontal_coordinate = START_HORIZONTAL; horizontal_coordinate < END_HORIZONTAL + 1; horizontal_coordinate = horizontal_coordinate + STEP_HORIZONTAL)
//                {
////                    std_msgs::Bool blinking_msg;
////                    blinking_msg.data = random() % 101 > 90;
////                    pub_blinking_.publish(blinking_msg);
//                    #ifdef PUBLISH_GAZE_COORDINATES
//                        et7::GazeCoordinates gaze_coordinates_msg;
//                        gaze_coordinates_msg.horizontal = horizontal_coordinate;
//                        gaze_coordinates_msg.vertical = vertical_coordinate;
//                        pub_gaze_coordinates_.publish(gaze_coordinates_msg);
//                    #endif
//                    publishGazeDirection(horizontal_coordinate, vertical_coordinate);
//
//                    ros::Duration(SAMPLING_RATE).sleep();
//                    if (!ros::ok())
//                    {
//                        exit(0);
//                    }
//                }
//            }
          publishGazeDirection(400, 125);
          ros::Duration(SAMPLING_RATE).sleep();
      }
      exit(0);
#endif

  //Video setup
  pub_scene_video_ = n_.advertise<sensor_msgs::CompressedImage>("et7/scene_camera/image_raw/compressed", 1);
  scene_image_.header.frame_id = std::string(SCENE_CAMERA_FRAME);
  scene_image_.format = "JPEG";

  //TCP connections
  server_et7_.sin_addr.s_addr = inet_addr(ADDRESS_ET7);
  server_et7_.sin_family = AF_INET;
  server_et7_.sin_port = htons(PORT_ET7);

  command_socket_ = socket(AF_INET, SOCK_STREAM, 0);
  if (command_socket_ == -1)
  {
    ROS_ERROR_STREAM("et7 - Could not create \"Command\" socket");
    exit(-1);
  }

  video_socket_ = socket(AF_INET, SOCK_STREAM, 0);
  if (video_socket_ == -1)
  {
    ROS_ERROR_STREAM("et7 - Could not create \"Data\" socket");
    exit(-1);
  }

  if (connect(command_socket_, (struct sockaddr *) &server_et7_, sizeof(server_et7_)) < 0)
  {
    ROS_ERROR_STREAM("et7 - \"Command\" socket connection failed");
    exit(-1);
  }

  requestVideoConnection();

  reply_msg_size_ = FLUSH_BUFFER_SIZE; //initial size
  first_reply_ = previous_blink_state_ = command_received_ = false;

  if (connect(video_socket_, (struct sockaddr *) &server_et7_, sizeof(server_et7_)) < 0)
  {
    ROS_ERROR_STREAM("et7 - \"Data\" socket connection failed");
    exit(-1);
  }

  reply_callback_timer_ = n_.createTimer(ros::Duration(SAMPLING_RATE), &ET7SceneVideoSteamTcpClass::replyCallback,
                                         this);

  ros::AsyncSpinner spinner(2);
  spinner.start();
  ros::waitForShutdown();
}

ET7SceneVideoSteamTcpClass::~ET7SceneVideoSteamTcpClass()
{
  close(video_socket_);
}

void ET7SceneVideoSteamTcpClass::requestVideoConnection()
{
  unsigned char command_message[COMMAND_SEND_BUFFER_SIZE];
  command_message[0] = MSG_ASL_SIGNATURE_3; // " ASL"
  command_message[1] = MSG_ASL_SIGNATURE_2;
  command_message[2] = MSG_ASL_SIGNATURE_1;
  command_message[3] = MSG_ASL_SIGNATURE_0;
  command_message[4] = 0x14; // Length
  command_message[5] = 0x00;
  command_message[6] = 0x00;
  command_message[7] = 0x00;
  command_message[8] = CMD_SET_CONNECT_TYPE; // Command type
  command_message[9] = 0x00;
  command_message[10] = 0x00;
  command_message[11] = 0x00;
  command_message[12] = 0xDE; // Checksum
  command_message[13] = 0x00;
  command_message[14] = 0x00;
  command_message[15] = 0x00;
  command_message[16] = SOCKET_TYPE_SVIDEO_TCP; // Argument
  command_message[17] = 0x00;
  command_message[18] = 0x00;
  command_message[19] = 0x00;
  if (send(command_socket_, command_message, COMMAND_SEND_BUFFER_SIZE, 0) < 0)
  {
    ROS_ERROR_STREAM("et7 - \"Command\" socket could not initialise \"Data\"");
    exit(-1);
  }
  ros::Duration(0.25).sleep();
  close(command_socket_);
}

void ET7SceneVideoSteamTcpClass::replyCallback(const ros::TimerEvent &)
{
  uint8_t data_reply[reply_msg_size_];

  if (recv(video_socket_, data_reply, reply_msg_size_, 0) < 0)
  {
    ROS_INFO_STREAM("et7 - No \"Data\" packet available yet");
    return;
  }

  scene_image_.header.stamp = ros::Time::now();

  if (data_reply[0] != MSG_ASL_SIGNATURE_3 ||
      data_reply[1] != MSG_ASL_SIGNATURE_2 ||
      data_reply[2] != MSG_ASL_SIGNATURE_1 ||
      data_reply[3] != MSG_ASL_SIGNATURE_0)
  {
    ROS_WARN_STREAM("et7 - \"Data\" packet header does not match");
    reply_msg_size_ = FLUSH_BUFFER_SIZE; //initial size
    first_reply_ = true;
    return;
  }

  if (first_reply_)
  {
    reply_msg_size_ = data_reply[4] + (data_reply[5] << 8) + (data_reply[6] << 16) + (data_reply[7] << 24);
    first_reply_ = false;
  }

  std_msgs::Bool blinking_msg;
  blinking_msg.data = (data_reply[REPLY_DATA_BEGINNING + 1] & 0b00110000) != 0b00110000; // Status byte

  et7::GazeCoordinates gaze_coordinates_msg;
  gaze_coordinates_msg.horizontal =
      0.1 * (data_reply[REPLY_DATA_BEGINNING + 6] << 8 | data_reply[REPLY_DATA_BEGINNING + 5]);
  gaze_coordinates_msg.vertical =
      0.1 * (data_reply[REPLY_DATA_BEGINNING + 8] << 8 | data_reply[REPLY_DATA_BEGINNING + 7]);

  scene_image_.data.resize(reply_msg_size_ - (REPLY_DATA_BEGINNING + REPLY_DATA_SIZE));
  for (int i = 0; i < reply_msg_size_ - (REPLY_DATA_BEGINNING + REPLY_DATA_SIZE); ++i)
  {
    scene_image_.data[i] = data_reply[i + (REPLY_DATA_BEGINNING + REPLY_DATA_SIZE)];
  }

  if (previous_blink_state_ != blinking_msg.data) // In order to publish only the blinking's change of state
  {
    previous_blink_state_ = blinking_msg.data;
    pub_blinking_.publish(blinking_msg);
  }

  pub_scene_video_.publish(scene_image_);

  {
    boost::mutex::scoped_lock lock(mutex_user_command_);
    if (command_received_)
    {
      publishGazeDirection(gaze_coordinates_msg.horizontal, gaze_coordinates_msg.vertical);
#ifdef PUBLISH_GAZE_COORDINATES
      pub_gaze_coordinates_.publish(gaze_coordinates_msg);
#endif
      pub_scene_video_.publish(scene_image_);
      command_received_ = false;
    }
  }
}

void
ET7SceneVideoSteamTcpClass::publishGazeDirection(const float &horizontal_coordinate, const float &vertical_coordinate)
{
  et7::GazeDirection gaze_direction_msg;
  gaze_direction_msg.x = tan(((horizontal_coordinate - SCENE_CAMERA_RESOLUTION_HORIZONTAL / 2.0) /
                              (SCENE_CAMERA_RESOLUTION_HORIZONTAL / 2.0)) * SCENE_CAMERA_FOV_HORIZONTAL / 2.0);
  gaze_direction_msg.y = tan(((vertical_coordinate - SCENE_CAMERA_RESOLUTION_VERTICAL / 2.0) /
                              (SCENE_CAMERA_RESOLUTION_VERTICAL / 2.0)) * SCENE_CAMERA_FOV_VERTICAL / 2.0);

#ifdef VISUALISE
  visualiseGazeDirection(gaze_direction_msg.x, gaze_direction_msg.y);
#endif

  pub_gaze_direction_.publish(gaze_direction_msg);
}

void ET7SceneVideoSteamTcpClass::userCommandCallback(const std_msgs::StringConstPtr &command)
{
  if (command->data == ECSAM_COMMAND_PICK || command->data == ECSAM_COMMAND_PLACE)
  {
    boost::mutex::scoped_lock lock(mutex_user_command_);
    command_received_ = true;
    command_ = command->data;
  }
}

#ifdef VISUALISE

void ET7SceneVideoSteamTcpClass::gazeMarkerSetup()
{
  marker_.header.frame_id = std::string(SCENE_CAMERA_FRAME);
  marker_.lifetime = ros::Duration(5);
  marker_.id = 0;
  marker_.ns = "et7_gaze";
  marker_.type = visualization_msgs::Marker::ARROW;
  marker_.action = visualization_msgs::Marker::ADD;

  marker_.scale.z = 1;

  marker_.color.r = VISUALISATION_MARKER_COLOUR_R;
  marker_.color.g = VISUALISATION_MARKER_COLOUR_G;
  marker_.color.b = VISUALISATION_MARKER_COLOUR_B;
  marker_.color.a = 1.0;

  marker_.points.resize(2);
  marker_.points[0].x = 0;
  marker_.points[0].y = 0;
  marker_.points[0].z = 0;
  marker_.points[1].z = VISUALISATION_MARKER_LENGTH;
}

void ET7SceneVideoSteamTcpClass::visualiseGazeDirection(const double &x, const double &y)
{

#ifndef VISUALISATION_MARKER_FIXED_WIDTH
  if (command_ == ECSAM_COMMAND_PICK)
  {
    marker_.scale.x = marker_.scale.y = PICK_CORRELATION_LINE_POINT_DISTANCE_THRESHOLD;
  }
  else if (command_ == ECSAM_COMMAND_PLACE)
  {
    marker_.scale.x = marker_.scale.y = PLACE_CORRELATION_LINE_POINT_DISTANCE_THRESHOLD;
  }
#else
  marker_.scale.x = marker_.scale.y = VISUALISATION_MARKER_FIXED_WIDTH;
#endif

  marker_.header.stamp = ros::Time::now();
  marker_.points[1].x = VISUALISATION_MARKER_LENGTH * x;
  marker_.points[1].y = VISUALISATION_MARKER_LENGTH * y;
  pub_marker_.publish(marker_);
}

#endif

int main(int argc, char **argv)
{
  ros::init(argc, argv, "et7_gaze_and_scene_video_stream_tcp");
  ET7SceneVideoSteamTcpClass et7_gaze_and_scene_video_stream_tcp;
  return (0);
}


text:
/* ----------------------------------------------------------------------
 *
 *                    *** Smooth Mach Dynamics ***
 *
 * This file is part of the USER-SMD package for LAMMPS.
 * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de
 * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,
 * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.
 *
 * ----------------------------------------------------------------------- */

/* ----------------------------------------------------------------------
 LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
 http://lammps.sandia.gov, Sandia National Laboratories
 Steve Plimpton, sjplimp@sandia.gov

 Copyright (2003) Sandia Corporation.  Under the terms of Contract
 DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
 certain rights in this software.  This software is distributed under
 the GNU General Public License.

 See the README file in the top-level LAMMPS directory.
 ------------------------------------------------------------------------- */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <Eigen/Eigen>
#include "compute_smd_tlsph_strain.h"
#include "atom.h"
#include "update.h"
#include "modify.h"
#include "comm.h"
#include "force.h"
#include "memory.h"
#include "error.h"
#include "pair.h"

using namespace Eigen;
using namespace std;
using namespace LAMMPS_NS;

/* ---------------------------------------------------------------------- */

ComputeSMDTLSPHstrain::ComputeSMDTLSPHstrain(LAMMPS *lmp, int narg, char **arg) :
                Compute(lmp, narg, arg) {
        if (narg != 3)
                error->all(FLERR, "Illegal compute smd/tlsph_strain command");

        peratom_flag = 1;
        size_peratom_cols = 6;

        nmax = 0;
        strainVector = NULL;
}

/* ---------------------------------------------------------------------- */

ComputeSMDTLSPHstrain::~ComputeSMDTLSPHstrain() {
        memory->sfree(strainVector);
}

/* ---------------------------------------------------------------------- */

void ComputeSMDTLSPHstrain::init() {

        int count = 0;
        for (int i = 0; i < modify->ncompute; i++)
                if (strcmp(modify->compute[i]->style, "smd/tlsph_strain") == 0)
                        count++;
        if (count > 1 && comm->me == 0)
                error->warning(FLERR, "More than one compute smd/tlsph_strain");
}

/* ---------------------------------------------------------------------- */

void ComputeSMDTLSPHstrain::compute_peratom() {
        double **defgrad0 = atom->smd_data_9;

        invoked_peratom = update->ntimestep;

        // grow vector array if necessary

        if (atom->nmax > nmax) {
                memory->destroy(strainVector);
                nmax = atom->nmax;
                memory->create(strainVector, nmax, size_peratom_cols, "strainVector");
                array_atom = strainVector;
        }

        // copy data to output array
        int itmp = 0;
        Matrix3d *Fincr = (Matrix3d *) force->pair->extract("smd/tlsph/Fincr_ptr", itmp);
        if (Fincr == NULL) {
                error->all(FLERR, "compute smd/tlsph_strain failed to access Fincr array");
        }

        int *mask = atom->mask;
        int nlocal = atom->nlocal;
        Matrix3d E, eye, Ftotal, F0;
        eye.setIdentity();

        for (int i = 0; i < nlocal; i++) {
                if (mask[i] & groupbit) {

                        // old deformation gradient
                        F0(0, 0) = defgrad0[i][0];
                        F0(0, 1) = defgrad0[i][1];
                        F0(0, 2) = defgrad0[i][2];
                        F0(1, 0) = defgrad0[i][3];
                        F0(1, 1) = defgrad0[i][4];
                        F0(1, 2) = defgrad0[i][5];
                        F0(2, 0) = defgrad0[i][6];
                        F0(2, 1) = defgrad0[i][7];
                        F0(2, 2) = defgrad0[i][8];

                        // compute current total deformation gradient
                        Ftotal = F0 * Fincr[i]; // this is the total deformation gradient: reference deformation times incremental deformation

                        E = 0.5 * (Ftotal.transpose() * Ftotal - eye); // Green-Lagrange strain
                        strainVector[i][0] = E(0, 0);
                        strainVector[i][1] = E(1, 1);
                        strainVector[i][2] = E(2, 2);
                        strainVector[i][3] = E(0, 1);
                        strainVector[i][4] = E(0, 2);
                        strainVector[i][5] = E(1, 2);
                } else {
                        for (int j = 0; j < size_peratom_cols; j++) {
                                strainVector[i][j] = 0.0;
                        }
                }
        }
}

/* ----------------------------------------------------------------------
 memory usage of local atom-based array
 ------------------------------------------------------------------------- */

double ComputeSMDTLSPHstrain::memory_usage() {
        double bytes = size_peratom_cols * nmax * sizeof(double);
        return bytes;
}


text:
#include <iostream>
#include <stdexcept>

#include <boost/pool/object_pool.hpp>

#include "Messaging/Message.h"
#include "Messaging/KeyMessage.h"
#include "Messaging/MouseMessage.h"

static boost::object_pool<Message> messagePool;

void* Message::operator new(std::size_t s)
{
//	if(s != sizeof(Message))
//		throw std::logic_error("Attempted to allocate a different object with Message operator new overload! All subclasses of Message should have an operator new overload");
//	std::cout << "Allocating Message" << std::endl;
	return messagePool.malloc();
}

void Message::operator delete(void *ptr)
{
	messagePool.free(static_cast<Message*>(ptr));
//	std::cout << "Freed Message" << std::endl;
}

static boost::object_pool<KeyMessage> keyMessagePool;

void* KeyMessage::operator new(std::size_t s)
{
//	if(s != sizeof(KeyMessage))
//		throw std::logic_error("Attempted to allocate a different object with KeyMessage operator new overload! All subclasses of KeyMessage should have an operator new overload");
//	std::cout << "Allocating KeyMessage" << std::endl;
	return keyMessagePool.malloc();
}

void KeyMessage::operator delete(void *ptr)
{
	keyMessagePool.free(static_cast<KeyMessage*>(ptr));
//	std::cout << "Freed KeyMessage" << std::endl;
}

static boost::object_pool<MouseMessage> mouseMessagePool;

void* MouseMessage::operator new(std::size_t s)
{
//	if(s != sizeof(MouseMessage))
//		throw std::logic_error("Attempted to allocate a different object with KeyMessage operator new overload! All subclasses of KeyMessage should have an operator new overload");
//	std::cout << "Allocating MouseMessage" << std::endl;
	return mouseMessagePool.malloc();
}

void MouseMessage::operator delete(void *ptr)
{
	mouseMessagePool.free(static_cast<MouseMessage*>(ptr));
//	std::cout << "Freed MouseMessage" << std::endl;
}


text:
#pragma once

#include "generator/feature_builder.hpp"
#include "generator/key_value_storage.hpp"
#include "generator/osm_element.hpp"
#include "generator/regions/region_info_getter.hpp"

#include "coding/reader.hpp"

#include "geometry/point2d.hpp"

#include "base/geo_object_id.hpp"

#include <memory>
#include <ostream>
#include <stdint.h>
#include <string>
#include <unordered_map>

#include <boost/optional.hpp>

namespace generator
{
namespace streets
{
class StreetsBuilder
{
public:
  explicit StreetsBuilder(regions::RegionInfoGetter const & regionInfoGetter);

  void AssembleStreets(std::string const & pathInStreetsTmpMwm);
  void AssembleBindings(std::string const & pathInGeoObjectsTmpMwm);
  void SaveStreetsKv(std::ostream & streamStreetsKv);

  static bool IsStreet(OsmElement const & element);
  static bool IsStreet(FeatureBuilder1 const & fb);

private:
  using RegionStreets = std::unordered_map<std::string, base::GeoObjectId>;

  void SaveRegionStreetsKv(std::ostream & streamStreetsKv, uint64_t regionId,
                           RegionStreets const & streets);

  void AddStreet(FeatureBuilder1 & fb);
  void AddStreetBinding(std::string && streetName, FeatureBuilder1 & fb);
  boost::optional<KeyValue> FindStreetRegionOwner(FeatureBuilder1 & fb);
  boost::optional<KeyValue> FindStreetRegionOwner(m2::PointD const & point);
  bool InsertStreet(KeyValue const & region, std::string && streetName, base::GeoObjectId id);
  bool InsertSurrogateStreet(KeyValue const & region, std::string && streetName);
  std::unique_ptr<char, JSONFreeDeleter> MakeStreetValue(uint64_t regionId, base::Json const regionObject,
                                                         std::string const & streetName);
  base::GeoObjectId NextOsmSurrogateId();

  std::unordered_map<uint64_t, RegionStreets> m_regions;
  regions::RegionInfoGetter const & m_regionInfoGetter;
  uint64_t m_osmSurrogateCounter{0};
};
}  // namespace streets
}  // namespace generator

max_stars_repo_name: letko-dmitry/omim

max_issues_repo_name: Mahmoudabdelmobdy/omim

max_forks_repo_name: Mahmoudabdelmobdy/omim


text:
#ifndef DOUBLE_BUFFER_HPP
#define DOUBLE_BUFFER_HPP

#include <vector>
#include <string>
#include <array>
#include <boost/asio.hpp>

namespace asio = boost::asio;

/**
 * This type provide functionality for scatter-gether I/O.
 * It wrapped two buffer sequences and switched between them updating
 * view buffer sequence which is used by write/write_some/async_write/async_write_some
 * operations as data source const buffers.
 *
 * Not thread safe.
 */
class Buffers final {
public:

    Buffers(std::size_t reserved = 10);

    /**
     * Queue data to passibe buffer.
     */
    void Enque(std::string&& data);

    /**
     * Swap buffers and update @m_bufferSequence.
     */
    void SwapBuffers();

    std::size_t GetQueueSize() const noexcept {
        return m_buffers[m_activeBuffer ^ 1].size();
    }

    const std::vector<asio::const_buffer>& GetBufferSequence() const noexcept {
        return m_bufferSequence;
    }

private:

    using DoubleBuffer = std::array<std::vector<std::string>, 2>;

    /**
     * Represent two sequences of some buffers
     * One sequence is active, another one is passive.
     * They can be swapped when needed.
     **/
    DoubleBuffer m_buffers;

    /**
     * View const buffer sequence used by write operations.
     */
    std::vector<asio::const_buffer> m_bufferSequence;

    std::size_t m_activeBuffer { 0 };
};

#endif // DOUBLE_BUFFER_HPP

max_stars_repo_name: Roout/char

max_issues_repo_name: Roout/char

max_forks_repo_name: Roout/char


text:
#include "mesh_reader.hpp"
#include "newton_raphson.hpp"
#include "constants.hpp"

#include <tuple>
#include <iostream>
#include <math.h>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/operation_blocked.hpp>
#include <chrono>

using namespace boost::numeric::ublas;

/* Configure boost-numeric-bindings in /usr/local to be able to use the compile statement on the next line. */
/* COMPILE WITH: g++ -Wall -std=c++14 -O3 -lstdc++ -o fem.o fem.cpp
mesh_reader.hpp needs those two flags for reading files */

class F {
  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */

  private:
    matrix<double> Au_;
    matrix<double> Av_;
    matrix<double> B_;
    matrix<double> C_;
    vector<double> D_;

  public:
    F(matrix<double> Au, matrix<double> Av, matrix<double> B, matrix<double> C, vector<double> D)
    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)
    {

    }

    vector<double> operator()(vector<double> x) {
      /* x = [uT vT]T */
      int n = Au_.size1();
      vector<double> u = project(x,range(0,n));
      vector<double> v = project(x,range(n,2*n));
      vector<double> func(2*n);
      project(func,range(0,n)) = prod(Au_,u) + prod(B_,Ru(u,v)) + hu*(prod(C_,u) - D_*uamb);
      project(func,range(n,2*n)) = -prod(Av_,v) + prod(B_,Rv(u,v)) - hv*(prod(C_,v) - D_*vamb);
      return func;
    }
};

class J {
  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */

  private:
    matrix<double> Au_;
    matrix<double> Av_;
    matrix<double> B_;
    matrix<double> C_;
    vector<double> D_;

  public:
    J(matrix<double> Au, matrix<double> Av, matrix<double> B, matrix<double> C, vector<double> D)
    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)
    {

    }

    matrix<double> operator()(vector<double> x) {
      /* x = [uT vT]T */
      int n = Au_.size1();
      vector<double> u = project(x,range(0,n));
      vector<double> v = project(x,range(n,2*n));
      matrix<double> JAC(2*n, 2*n);
      project(JAC,range(0,n),range(0, n)) = Au_ + prod(B_,dRudu(u,v)) + hu*C_;
      project(JAC,range(n,2*n),range(0,n)) = prod(B_,dRudv(u,v));
      project(JAC,range(n,2*n),range(0,n)) = prod(B_,dRvdu(u,v));
      project(JAC,range(n,2*n),range(n,2*n)) = -1*Av_ + prod(B_,dRvdv(u,v)) - hv*C_;
      return JAC;
    }
};

int main() {
  /* Read and store mesh information */
  auto t1 = std::chrono::high_resolution_clock::now();
  matrix<double> vertices = mesh::read_vertices();
  matrix<double> triangles = mesh::read_triangles(vertices);
  matrix<int> boundaries = mesh::read_boundaries(vertices);
  auto t2 = std::chrono::high_resolution_clock::now();
  std::cout << "Input data successfully read:" << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;

  /* Calculate righthand side vector integrals */
  t1 = std::chrono::high_resolution_clock::now();
  matrix<double> init_B(vertices.size1(), vertices.size1());
  symmetric_adaptor<matrix<double>, lower> B(init_B);
  B = set_zero(B);
  for (unsigned t = 0; t < triangles.size1(); ++t) {
    int a = triangles(t, 0);
    int b = triangles(t, 1);
    int c = triangles(t, 2);
    double area = triangles(t, 3);
    //std::cout << std::endl;
    B(a, a) += area*(6.*vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));
    //std::cout<< B(a,a) << std::endl;
    B(b, a) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + vertices(c, 0));
    B(c, a) += area*(2.*vertices(a, 0) + vertices(b, 0) + 2.*vertices(c, 0));
    B(b, b) += area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0));
    //std::cout << "B(b,c): " << B(b,c) << "deel1: "<< area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0)) << std::endl;
    B(b, c) += area*(vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));
    B(c, c) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + 6.*vertices(c, 0));
    //std::cout << B << std::endl;
  }
  //std::cout << "before division: " << B << std::endl;
  B *= (1./60.);
  //std::cout << "after divison: " << B << std::endl;
  t2 = std::chrono::high_resolution_clock::now();
  std::cout << "B matrix successfully assembled" << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;

  /* Calculate first part of stiffness matrix A */
  t1 = std::chrono::high_resolution_clock::now();
  matrix<double> init_A_U(vertices.size1(), vertices.size1());
  matrix<double> init_A_V(vertices.size1(), vertices.size1());
  matrix<double> I_U(2,2);
  matrix<double> I_V(2,2);
  matrix<double> G(3, 2);
  matrix<double> GGT_U(3, 3);
  matrix<double> GGT_V(3, 3);
  matrix<double> temp(3, 3);
  symmetric_adaptor<matrix<double>, lower> A_U(init_A_U);
  symmetric_adaptor<matrix<double>, lower> A_V(init_A_V);
  I_U = set_zero(I_U);
  I_V = set_zero(I_V);
  A_U = set_zero(A_U);
  A_V = set_zero(A_V);
  I_U(0,0) = DU_R;
  I_U(1,1) = DU_Z;
  I_V(0,0) = DV_R;
  I_V(1,1) = DV_Z;
  for (unsigned t = 0; t < triangles.size1(); ++t) {
    int a = triangles(t, 0);
    int b = triangles(t, 1);
    int c = triangles(t, 2);
    double area = triangles(t, 3);
    G(0, 0) = (vertices(b, 1) - vertices(c, 1));
    G(1, 0) = (vertices(c, 1) - vertices(a, 1));
    G(2, 0) = (vertices(a, 1) - vertices(b, 1));
    G(0, 1) = (vertices(c, 0) - vertices(b, 0));
    G(1, 1) = (vertices(a, 0) - vertices(c, 0));
    G(2, 1) = (vertices(b, 0) - vertices(a, 0));
    temp = prod(G,I_U);
    GGT_U = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*prod(temp, trans(G));
    temp = prod(G,I_V);
    GGT_V = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*prod(temp, trans(G));
    // std::cout << "factor: " << (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6) << std::endl;
    // std::cout << "G: " << G << std::endl;
    // std::cout << "temp: " << temp << std::endl;
    // std::cout << "tempGT: " << prod(temp, trans(G)) << std::endl;
    // std::cout << "GGT_V: " << GGT_V << std::endl;
    A_U(a, a) += GGT_U(0, 0);
    A_U(b, a) += GGT_U(1, 0);
    A_U(c, a) += GGT_U(2, 0);
    A_U(b, b) += GGT_U(1, 1);
    A_U(b, c) += GGT_U(1, 2);
    A_U(c, c) += GGT_U(2, 2);
    A_V(a, a) += GGT_V(0, 0);
    A_V(b, a) += GGT_V(1, 0);
    A_V(c, a) += GGT_V(2, 0);
    A_V(b, b) += GGT_V(1, 1);
    A_V(b, c) += GGT_V(1, 2);
    A_V(c, c) += GGT_V(2, 2);
  }

  t2 = std::chrono::high_resolution_clock::now();
  std::cout << "A matrices assembled." << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;

  /* Boundary condition integrals: second part of A and a constant vector term */
  t1 = std::chrono::high_resolution_clock::now();
  matrix<double> init_C(vertices.size1(), vertices.size1());
  symmetric_adaptor<matrix<double>, lower> C(init_C);
  C = set_zero(C);
  vector<double> D(vertices.size1());
  D = set_zero(D);
  // std::cout << std::endl;
  // std::cout << std::endl;
  // std::cout << std::endl;
  for (unsigned b = 0; b < boundaries.size1(); ++b) {
    double len = sqrt(pow(vertices(boundaries(b, 0), 0) - vertices(boundaries(b, 1), 0), 2) +
      pow(vertices(boundaries(b, 0), 1) - vertices(boundaries(b, 1), 1), 2));
    C(boundaries(b, 0), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/4 + vertices(boundaries(b, 1), 0)/12);
    C(boundaries(b, 0), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);
    C(boundaries(b, 1), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/4);
    // Nakijken -> 1 vergeten
    D(boundaries(b,0)) += len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.);
    // std::cout << "D(boundaries(b,0)): " << len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.) << std::endl;
    // std::cout << "b: " << b << std::endl;
    D(boundaries(b,1)) += len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.);
    // std::cout << "D(boundaries(b,1)): " << len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.) << std::endl;
    // std::cout << "b: " << len << std::endl;
  }
  // std::cout << "C: "<< C << std::endl;
  // std::cout << std::endl;
  // std::cout << std::endl;
  // std::cout << std::endl;
  t2 = std::chrono::high_resolution_clock::now();
  std::cout << "C matrix and D vector assembled." << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;

  /* Root finding for nonlinear system of equations */
  t1 = std::chrono::high_resolution_clock::now();
  F F_funct(A_U, A_V, B, C, D);
  J J_funct(A_U, A_V, B, C, D);
  t2 = std::chrono::high_resolution_clock::now();
  std::cout << "Functors are created" << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;
  t1 = std::chrono::high_resolution_clock::now();

  std::cout << "A_U: " << A_U << std::endl;
  std::cout << std::endl;
  std::cout << "A_V: " << A_V << std::endl;
  std::cout << std::endl;
  std::cout << "B: " << B << std::endl;
  std::cout << std::endl;
  std::cout << "C: " << C << std::endl;
  std::cout << std::endl;
  std::cout << "D: " << D << std::endl;
  std::cout << std::endl;
  vector<double> guess = vector<double>(vertices.size1()*2,5.);
  matrix<double> inverse_u_0 (vertices.size1(),vertices.size1());
  inverse_u_0 = set_zero(inverse_u_0);
  InvertMatrix<double>(A_U+(Vmu/Kmu)*B+hu*C, inverse_u_0);
  std::cout << "V/K" << Vmu/Kmu << std::endl;
  std::cout << std::endl;
  std::cout << "hu" << hu << std::endl;
  std::cout << std::endl;
  vector<double> u_0 = prod(inverse_u_0, hu*D*uamb);

  std::cout << std::endl;
  std::cout << std::endl;
  matrix<double> inverse_v_0 (vertices.size1(),vertices.size1());
  inverse_v_0 = set_zero(inverse_v_0);
  InvertMatrix<double>(A_V+hv*C, inverse_v_0);
  vector<double> v_0 = prod(inverse_v_0, rq*(Vmu/Kmu)*prod(B,u_0)+hv*vamb*D);
  std::cout << "v_0" << v_0 << std::endl;
  std::cout << std::endl;
  std::cout << "inverse_v_0" << inverse_v_0 << std::endl;
  std::cout << std::endl;
  std::cout << "second factor" << rq*(Vmu/Kmu)*prod(B,u_0)+hv*vamb*D << std::endl;
  std::cout << std::endl;
  std::cout << std::endl;
  std::cout << "uamb: " << uamb << std::endl;
  std::cout << std::endl;
  std::cout << std::endl;

  project(guess,range(0,vertices.size1())) = u_0;
  project(guess,range(vertices.size1(),2*vertices.size1())) = v_0;
  std::cout << "Initial guess" << guess << std::endl;
  t2 = std::chrono::high_resolution_clock::now();
  std::cout<< "Initial guess calculated" << std::endl;
  std::cout << "This took: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
            << " milliseconds" << std::endl;
  newton_raphson(F_funct,J_funct,guess,pow(10,-15));
  std::cout << guess << std::endl;

  return 0;
}

max_stars_repo_name: PieterAppeltans/ProjectWIT

max_issues_repo_name: PieterAppeltans/ProjectWIT

max_forks_repo_name: PieterAppeltans/ProjectWIT


text:
#include <Common/config.h>
#include <Interpreters/Context.h>
#include <DataStreams/NativeBlockInputStream.h>
#include <DataStreams/NativeBlockOutputStream.h>
#include <DataStreams/TabSeparatedRowInputStream.h>
#include <DataStreams/TabSeparatedRowOutputStream.h>
#include <DataStreams/TabSeparatedRawRowOutputStream.h>
#include <DataStreams/BinaryRowInputStream.h>
#include <DataStreams/BinaryRowOutputStream.h>
#include <DataStreams/ValuesRowInputStream.h>
#include <DataStreams/ValuesRowOutputStream.h>
#include <DataStreams/PrettyBlockOutputStream.h>
#include <DataStreams/PrettyCompactBlockOutputStream.h>
#include <DataStreams/PrettySpaceBlockOutputStream.h>
#include <DataStreams/VerticalRowOutputStream.h>
#include <DataStreams/NullBlockOutputStream.h>
#include <DataStreams/BlockInputStreamFromRowInputStream.h>
#include <DataStreams/BlockOutputStreamFromRowOutputStream.h>
#include <DataStreams/JSONRowOutputStream.h>
#include <DataStreams/JSONCompactRowOutputStream.h>
#include <DataStreams/JSONEachRowRowOutputStream.h>
#include <DataStreams/JSONEachRowRowInputStream.h>
#include <DataStreams/XMLRowOutputStream.h>
#include <DataStreams/TSKVRowOutputStream.h>
#include <DataStreams/TSKVRowInputStream.h>
#include <DataStreams/ODBCDriverBlockOutputStream.h>
#include <DataStreams/CSVRowInputStream.h>
#include <DataStreams/CSVRowOutputStream.h>
#include <DataStreams/MaterializingBlockOutputStream.h>
#include <DataStreams/FormatFactory.h>
#include <DataStreams/SquashingBlockOutputStream.h>
#include <DataTypes/FormatSettingsJSON.h>
#if USE_CAPNP
#include <DataStreams/CapnProtoRowInputStream.h>
#endif

#include <boost/algorithm/string.hpp>

namespace DB
{

namespace ErrorCodes
{
    extern const int FORMAT_IS_NOT_SUITABLE_FOR_INPUT;
    extern const int UNKNOWN_FORMAT;
}

BlockInputStreamPtr FormatFactory::getInput(const String & name, ReadBuffer & buf,
    const Block & sample, const Context & context, size_t max_block_size) const
{
    const Settings & settings = context.getSettingsRef();

    auto wrap_row_stream = [&](auto && row_stream)
    {
        return std::make_shared<BlockInputStreamFromRowInputStream>(std::move(row_stream), sample, max_block_size,
            settings.input_format_allow_errors_num, settings.input_format_allow_errors_ratio);
    };

    if (name == "Native")
    {
        return std::make_shared<NativeBlockInputStream>(buf, sample, 0);
    }
    else if (name == "RowBinary")
    {
        return wrap_row_stream(std::make_shared<BinaryRowInputStream>(buf, sample));
    }
    else if (name == "TabSeparated" || name == "TSV") /// TSV is a synonym/alias for the original TabSeparated format
    {
        return wrap_row_stream(std::make_shared<TabSeparatedRowInputStream>(buf, sample));
    }
    else if (name == "TabSeparatedWithNames" || name == "TSVWithNames")
    {
        return wrap_row_stream(std::make_shared<TabSeparatedRowInputStream>(buf, sample, true));
    }
    else if (name == "TabSeparatedWithNamesAndTypes" || name == "TSVWithNamesAndTypes")
    {
        return wrap_row_stream(std::make_shared<TabSeparatedRowInputStream>(buf, sample, true, true));
    }
    else if (name == "Values")
    {
        return wrap_row_stream(std::make_shared<ValuesRowInputStream>(buf, sample, context, settings.input_format_values_interpret_expressions));
    }
    else if (name == "CSV")
    {
        return wrap_row_stream(std::make_shared<CSVRowInputStream>(buf, sample, ','));
    }
    else if (name == "CSVWithNames")
    {
        return wrap_row_stream(std::make_shared<CSVRowInputStream>(buf, sample, ',', true));
    }
    else if (name == "TSKV")
    {
        return wrap_row_stream(std::make_shared<TSKVRowInputStream>(buf, sample, settings.input_format_skip_unknown_fields));
    }
    else if (name == "JSONEachRow")
    {
        return wrap_row_stream(std::make_shared<JSONEachRowRowInputStream>(buf, sample, settings.input_format_skip_unknown_fields));
    }
#if USE_CAPNP
    else if (name == "CapnProto")
    {
        std::vector<String> tokens;
        auto schema_and_root = settings.format_schema.toString();
        boost::split(tokens, schema_and_root, boost::is_any_of(":"));
        if (tokens.size() != 2)
            throw Exception("Format CapnProto requires 'format_schema' setting to have a schema_file:root_object format, e.g. 'schema.capnp:Message'");

        const String & schema_dir = context.getFormatSchemaPath();
        return wrap_row_stream(std::make_shared<CapnProtoRowInputStream>(buf, sample, schema_dir, tokens[0], tokens[1]));
    }
#endif
    else if (name == "TabSeparatedRaw"
        || name == "TSVRaw"
        || name == "Pretty"
        || name == "PrettyCompact"
        || name == "PrettyCompactMonoBlock"
        || name == "PrettySpace"
        || name == "PrettyNoEscapes"
        || name == "PrettyCompactNoEscapes"
        || name == "PrettySpaceNoEscapes"
        || name == "Vertical"
        || name == "VerticalRaw"
        || name == "Null"
        || name == "JSON"
        || name == "JSONCompact"
        || name == "XML"
        || name == "ODBCDriver")
    {
        throw Exception("Format " + name + " is not suitable for input", ErrorCodes::FORMAT_IS_NOT_SUITABLE_FOR_INPUT);
    }
    else
        throw Exception("Unknown format " + name, ErrorCodes::UNKNOWN_FORMAT);
}

static BlockOutputStreamPtr getOutputImpl(const String & name, WriteBuffer & buf,
    const Block & sample, const Context & context)
{
    const Settings & settings = context.getSettingsRef();
    FormatSettingsJSON json_settings(settings.output_format_json_quote_64bit_integers, settings.output_format_json_quote_denormals);

    if (name == "Native")
        return std::make_shared<NativeBlockOutputStream>(buf, 0, sample);
    else if (name == "RowBinary")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<BinaryRowOutputStream>(buf), sample);
    else if (name == "TabSeparated" || name == "TSV")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<TabSeparatedRowOutputStream>(buf, sample), sample);
    else if (name == "TabSeparatedWithNames" || name == "TSVWithNames")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<TabSeparatedRowOutputStream>(buf, sample, true), sample);
    else if (name == "TabSeparatedWithNamesAndTypes" || name == "TSVWithNamesAndTypes")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<TabSeparatedRowOutputStream>(buf, sample, true, true), sample);
    else if (name == "TabSeparatedRaw" || name == "TSVRaw")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<TabSeparatedRawRowOutputStream>(buf, sample), sample);
    else if (name == "CSV")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<CSVRowOutputStream>(buf, sample), sample);
    else if (name == "CSVWithNames")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<CSVRowOutputStream>(buf, sample, true), sample);
    else if (name == "Pretty")
        return std::make_shared<PrettyBlockOutputStream>(buf, sample, false, settings.output_format_pretty_max_rows, context);
    else if (name == "PrettyCompact")
        return std::make_shared<PrettyCompactBlockOutputStream>(buf, sample, false, settings.output_format_pretty_max_rows, context);
    else if (name == "PrettyCompactMonoBlock")
    {
        BlockOutputStreamPtr dst = std::make_shared<PrettyCompactBlockOutputStream>(buf, sample, false, settings.output_format_pretty_max_rows, context);
        auto res = std::make_shared<SquashingBlockOutputStream>(dst, settings.output_format_pretty_max_rows, 0);
        res->disableFlush();
        return res;
    }
    else if (name == "PrettySpace")
        return std::make_shared<PrettySpaceBlockOutputStream>(buf, sample, false, settings.output_format_pretty_max_rows, context);
    else if (name == "PrettyNoEscapes")
        return std::make_shared<PrettyBlockOutputStream>(buf, sample, true, settings.output_format_pretty_max_rows, context);
    else if (name == "PrettyCompactNoEscapes")
        return std::make_shared<PrettyCompactBlockOutputStream>(buf, sample, true, settings.output_format_pretty_max_rows, context);
    else if (name == "PrettySpaceNoEscapes")
        return std::make_shared<PrettySpaceBlockOutputStream>(buf, sample, true, settings.output_format_pretty_max_rows, context);
    else if (name == "Vertical")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<VerticalRowOutputStream>(
            buf, sample, settings.output_format_pretty_max_rows), sample);
    else if (name == "VerticalRaw")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<VerticalRawRowOutputStream>(
            buf, sample, settings.output_format_pretty_max_rows), sample);
    else if (name == "Values")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<ValuesRowOutputStream>(buf), sample);
    else if (name == "JSON")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<JSONRowOutputStream>(
            buf, sample, settings.output_format_write_statistics, json_settings), sample);
    else if (name == "JSONCompact")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<JSONCompactRowOutputStream>(
            buf, sample, settings.output_format_write_statistics, json_settings), sample);
    else if (name == "JSONEachRow")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<JSONEachRowRowOutputStream>(
            buf, sample, json_settings), sample);
    else if (name == "XML")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<XMLRowOutputStream>(buf, sample,
            settings.output_format_write_statistics), sample);
    else if (name == "TSKV")
        return std::make_shared<BlockOutputStreamFromRowOutputStream>(std::make_shared<TSKVRowOutputStream>(buf, sample), sample);
    else if (name == "ODBCDriver")
        return std::make_shared<ODBCDriverBlockOutputStream>(buf, sample);
    else if (name == "Null")
        return std::make_shared<NullBlockOutputStream>(sample);
    else
        throw Exception("Unknown format " + name, ErrorCodes::UNKNOWN_FORMAT);
}

BlockOutputStreamPtr FormatFactory::getOutput(const String & name, WriteBuffer & buf,
    const Block & sample, const Context & context) const
{
    /** Materialization is needed, because formats can use the functions `IDataType`,
      *  which only work with full columns.
      */
    return std::make_shared<MaterializingBlockOutputStream>(getOutputImpl(name, buf, materializeBlock(sample), context), sample);
}

}

max_stars_repo_name: ywandy/ClickHouse

max_issues_repo_name: ywandy/ClickHouse

max_forks_repo_name: ywandy/ClickHouse