text:
//
// Test for BOOST_TEST_GT, BOOST_TEST_GE
//
// Copyright 2017 Kohei Takahashi
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/core/lightweight_test.hpp>

int main()
{
    int x = 0;

    BOOST_TEST_GT( x, -1 );
    BOOST_TEST_GT( ++x, 0 );
    BOOST_TEST_GT( x++, 0 );

    BOOST_TEST_GE( x, 2 );
    BOOST_TEST_GE( ++x, 3 );
    BOOST_TEST_GE( x++, 3 );

    int y = 5;

    BOOST_TEST_GT( ++y, ++x );
    BOOST_TEST_GT( y++, x++ );

    BOOST_TEST_GE( ++y, x );
    BOOST_TEST_GE( y++, x++ );

    return boost::report_errors();
}

ext: cpp


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

#include <miopen/conv/invokers/ocl_wrw_rdc.hpp>

#include <miopen/conv/wrw_invoke_params.hpp>
#include <miopen/handle.hpp>
#include <miopen/kernel.hpp>
#include <miopen/tensor.hpp>
#include <miopen/visit_float.hpp>

#include <boost/any.hpp>

namespace miopen {
namespace conv {

InvokerFactory MakeOclWrWRdcInvokerFactory(bool twoKernels, size_t workspaceSize)
{
    if(twoKernels)
    {
        return [workspaceSize](const std::vector<Kernel>& kernels) {
            return [=](Handle& handle, const boost::any& primitive_params) {
                const auto main_kernel   = handle.Run(kernels[0]);
                const auto rdc_kernel    = handle.Run(kernels[1]);
                const auto invoke_params = boost::any_cast<conv::WrWInvokeParams>(primitive_params);
                const auto& tensors      = invoke_params.tensors;
                const auto padding_val   = 0.f;
                auto elapsed             = 0.f;

                if(invoke_params.workSpaceSize < workspaceSize)
                    MIOPEN_THROW("Not enough workspace for invoker");

                visit_float(tensors.dyDesc.GetType(), [&](auto as_float) {
                    main_kernel(
                        tensors.dy, tensors.x, invoke_params.workSpace, as_float(padding_val));
                });
                if(handle.IsProfilingEnabled())
                    elapsed = handle.GetKernelTime();

                rdc_kernel(invoke_params.workSpace, tensors.dw); // reduction
                if(handle.IsProfilingEnabled())
                {
                    elapsed += handle.GetKernelTime();
                    handle.ResetKernelTime();
                    handle.AccumKernelTime(elapsed);
                };
            };
        };
    }
    else
    {
        return [](const std::vector<Kernel>& kernels) {
            return [=](Handle& handle, const boost::any& primitive_params) {
                const auto main_kernel   = handle.Run(kernels[0]);
                const auto invoke_params = boost::any_cast<conv::WrWInvokeParams>(primitive_params);
                const auto& tensors      = invoke_params.tensors;
                const auto padding_val   = 0.f;
                visit_float(tensors.dyDesc.GetType(), [&](auto as_float) {
                    main_kernel(tensors.dy, tensors.x, tensors.dw, as_float(padding_val));
                });
            };
        };
    }
}

} // namespace conv
} // namespace miopen

max_stars_repo_name: nelsonc-amd/MIOpen

max_issues_repo_name: nelsonc-amd/MIOpen

max_forks_repo_name: nelsonc-amd/MIOpen


text:
//  Copyright (c) 2014 Grant Mercer
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx_init.hpp>
#include <hpx/hpx.hpp>
#include <hpx/include/parallel_numeric.hpp>
#include <hpx/include/parallel_algorithm.hpp>
#include <hpx/include/iostreams.hpp>

#include <boost/iterator/counting_iterator.hpp>

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

///////////////////////////////////////////////////////////////////////////////
int hpx_main()
{
    // lets say we have two vectors that simulate.. 10007D
    std::vector<double> xvalues(10007);
    std::vector<double> yvalues(10007);
    std::fill(std::begin(xvalues), std::end(xvalues), 1.0);
    std::fill(std::begin(yvalues), std::end(yvalues), 1.0);

    double result =
        hpx::parallel::transform_reduce(
            hpx::parallel::execution::par,
            boost::counting_iterator<size_t>(0),
            boost::counting_iterator<size_t>(10007),
            0.0,
            std::plus<double>(),
            [&xvalues, &yvalues](size_t i)
            {
                return xvalues[i] * yvalues[i];
            }
        );
    // print the result
    hpx::cout << result << hpx::endl;

    return hpx::finalize();
}

int main(int argc, char* argv[])
{
    // By default this should run on all available cores
    std::vector<std::string> const cfg = {
        "hpx.os_threads=all"
    };

    // Initialize and run HPX
    return hpx::init(argc, argv, cfg);
}

max_forks_repo_name: biddisco/hpx


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2::meta::upgrade"

#include <nt2/sdk/config/types.hpp>
#include <nt2/sdk/meta/upgrade.hpp>
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>

////////////////////////////////////////////////////////////////////////////////
// Test that upgrade is correct for middle-sized types
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(upgrade_ints)
{
  using nt2::meta::upgrade;
  using boost::is_same;

  NT2_TEST( (is_same<upgrade<double  			>::type,double 				>::value ));
  NT2_TEST( (is_same<upgrade<float   			>::type,double 				>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int32_t >::type,nt2::int64_t 	>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int16_t >::type,nt2::int32_t 	>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int8_t 	>::type,nt2::int16_t 	>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint32_t>::type,nt2::uint64_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint16_t>::type,nt2::uint32_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint8_t	>::type,nt2::uint16_t	>::value ));
}

////////////////////////////////////////////////////////////////////////////////
// Test that upgrade is correct w/r to forced sign
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(upgrade_ints_forced_signed)
{
  using nt2::meta::upgrade;
  using boost::is_same;

  NT2_TEST( (is_same<upgrade<double  			,signed>::type,double				>::value ));
  NT2_TEST( (is_same<upgrade<float   			,signed>::type,double				>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int32_t ,signed>::type,nt2::int64_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::int16_t ,signed>::type,nt2::int32_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::int8_t 	,signed>::type,nt2::int16_t	>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint32_t,signed>::type,nt2::int64_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint16_t,signed>::type,nt2::int32_t >::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint8_t	,signed>::type,nt2::int16_t	>::value ));

  NT2_TEST( (is_same<upgrade<double  			,unsigned>::type,double				>::value ));
  NT2_TEST( (is_same<upgrade<float   			,unsigned>::type,double				>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int32_t ,unsigned>::type,nt2::uint64_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int16_t ,unsigned>::type,nt2::uint32_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::int8_t 	,unsigned>::type,nt2::uint16_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint32_t,unsigned>::type,nt2::uint64_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint16_t,unsigned>::type,nt2::uint32_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint8_t	,unsigned>::type,nt2::uint16_t>::value ));
}

////////////////////////////////////////////////////////////////////////////////
// Test that upgrade is correct w/r to tpye of sizeof == 8
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(upgrade_sizeof_8)
{
  using nt2::meta::upgrade;
  using boost::is_same;

  NT2_TEST( (is_same<upgrade<nt2::uint64_t					>::type,nt2::uint64_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint64_t					>::type,nt2::uint64_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint64_t,signed		>::type,nt2::int64_t>::value 	));
  NT2_TEST( (is_same<upgrade<nt2::uint64_t,signed		>::type,nt2::int64_t>::value 	));
  NT2_TEST( (is_same<upgrade<nt2::uint64_t,unsigned	>::type,nt2::uint64_t>::value ));
  NT2_TEST( (is_same<upgrade<nt2::uint64_t,unsigned	>::type,nt2::uint64_t>::value ));
}


text:
//----------------------------------*-C++-*----------------------------------//
/**
 *  @file   Material.hh
 *  @author Jeremy Roberts
 *  @brief  Material class definition.
 */
//---------------------------------------------------------------------------//

#ifndef detran_material_MATERIAL_HH_
#define detran_material_MATERIAL_HH_

#include "material/material_export.hh"
#include "utilities/Definitions.hh"
#include "utilities/SP.hh"
#include <string>
#ifdef DETRAN_ENABLE_BOOST
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#endif

namespace detran_material
{

//---------------------------------------------------------------------------//
/**
 *  @class Material
 *  @brief Simple cross section container.
 *
 *  All data is stored with the material index changing fastest.  This
 *  appears to be the best storage scheme with respect to memory access.
 */
//---------------------------------------------------------------------------//
class MATERIAL_EXPORT Material
{

public:

  //-------------------------------------------------------------------------//
  // TYPEDEFS
  //-------------------------------------------------------------------------//

  typedef detran_utilities::SP<Material> SP_material;
  typedef detran_utilities::vec_dbl      vec_dbl;
  typedef detran_utilities::vec2_dbl     vec2_dbl;
  typedef detran_utilities::vec3_dbl     vec3_dbl;
  typedef detran_utilities::vec_int      vec_int;
  typedef detran_utilities::vec2_int     vec2_int;
  typedef detran_utilities::vec_size_t   vec_size_t;
  typedef detran_utilities::vec2_size_t  vec2_size_t;
  typedef detran_utilities::size_t       size_t;

  //-------------------------------------------------------------------------//
  // PUBLIC INTERFACE
  //-------------------------------------------------------------------------//

  /**
   *  @brief Constructor.
   *  @param    number_materials    Number of materials.
   *  @param    number_groups       Number of energy groups.
   *  @param    downscatter         Switch on to use only downscatter.
   */
  Material(const size_t number_materials,
           const size_t number_groups,
           std::string  name = "no name given");

  /// Virtual destructor
  virtual ~Material(){}

  /// SP constructor
  static SP_material Create(const size_t number_materials,
                            const size_t number_groups,
                            std::string  name = "no name given");

  //--------------------------------------------------------------------------//
  // Setters
  //--------------------------------------------------------------------------//

  /**
   *  @brief Explicitly turn on downscatter-only
   */
  void set_downscatter(bool v, bool tran = false)
  {
    if (tran) d_downscatter[1] = v;
    d_downscatter[0] = v;
    if (d_finalized) finalize();
  }

  void set_sigma_t(size_t m, size_t g, double v);
  void set_sigma_a(size_t m, size_t g, double v);
  void set_nu_sigma_f(size_t m, size_t g, double v);
  void set_sigma_f(size_t m, size_t g, double v);
  void set_nu(size_t m, size_t g, double v);
  void set_chi(size_t m, size_t g, double v);
  void set_sigma_s(size_t m, size_t g, size_t gp, double v);
  void set_diff_coef(size_t m, size_t g, double v);

  // Vectorized setters

  void set_sigma_t(size_t m, vec_dbl &v);
  void set_sigma_a(size_t m, vec_dbl &v);
  void set_nu_sigma_f(size_t m, vec_dbl &v);
  void set_sigma_f(size_t m, vec_dbl &v);
  void set_nu(size_t m, vec_dbl &v);
  void set_chi(size_t m, vec_dbl &v);
  void set_sigma_s(size_t m, size_t g, vec_dbl &v);
  void set_diff_coef(size_t m, vec_dbl &v);

  //------------------------------------------------------------------------//
  // Getters
  //------------------------------------------------------------------------//

  virtual double sigma_t(size_t m, size_t g) const;
  virtual double sigma_a(size_t m, size_t g) const;
  virtual double nu_sigma_f(size_t m, size_t g) const;
  virtual double sigma_f(size_t m, size_t g) const;
  virtual double nu(size_t m, size_t g) const;
  virtual double chi(size_t m, size_t g) const;
  virtual double sigma_s(size_t m, size_t g, size_t gp) const;
  virtual double diff_coef(size_t m, size_t g) const;

  // Vectorized getters

  virtual vec_dbl sigma_t(size_t m) const;
  virtual vec_dbl sigma_a(size_t m) const;
  virtual vec_dbl nu_sigma_f(size_t m) const;
  virtual vec_dbl sigma_f(size_t m) const;
  virtual vec_dbl nu(size_t m) const;
  virtual vec_dbl chi(size_t m) const;
  virtual vec2_dbl sigma_s(size_t m) const;
  virtual vec_dbl diff_coef(size_t m) const;

  //------------------------------------------------------------------------//
  // OTHER ACCESSORS
  //------------------------------------------------------------------------//

  size_t number_groups() const
  {
    return d_number_groups;
  }

  size_t number_materials() const
  {
    return d_number_materials;
  }

  /**
   *  @brief Lower scatter group bound.
   *
   *  This is the *lowest* index (highest energy) \f$ g' \f$
   *  that leads to downscatter for a given outgoing group \f$ g \f$.
   *
   *  @param g        Row of the scattering matrix
   *  @param tran     Flag for accessing transpose of S
   */
  size_t lower(size_t g, bool tran = false) const;

  /**
   *  @brief Upper scatter group bound.
   *
   *  This is the *highest* index (lowest energy) \f$ g' \f$
   *  that upscatters size_to the outgoing group \f$ g \f$.
   *
   *  @param g        Row of the scattering matrix
   *  @param tran     Flag for accessing transpose of S
   */
  size_t upper(size_t g, bool tran = false) const;

  /// Do we do only downscatter?
  bool downscatter(bool tran = false) const;

  /**
   *  @brief Index below which upscatter doesn't occur for any material.
   *
   *  For adjoint problems, this is the group above which
   */
  size_t upscatter_cutoff(bool tran = false) const;

  /**
   *  @brief Compute the absorption cross section from total and scattering.
   *  @note this overwrites any data for \f$ \Sigma_a \f$ already stored.
   */
  void compute_sigma_a();

  /**
   *  @brief Compute the diffusion coefficient from \f$ \Sigma_t \f$.
   *
   *  Assuming isotropic scattering in the LAB, the diffusion
   *  coefficient is simply \f$ D = 1/3\Sigma_t \f$.
   *
   *  @todo Update diffusion definition if anisotropic scattering
   *        is added.
   *  @note This overwrites any data for \f$ D \f$ already stored.
   */
  void compute_diff_coef();

  /// Computes scattering bounds and absorption cross section.
  void finalize();

  /// Pretty print the material database.
  virtual void display();

protected:

  //-------------------------------------------------------------------------//
  // DATA
  //-------------------------------------------------------------------------//

  /// Material name
  std::string d_name;
  /// Number of groups
  size_t d_number_groups;
  /// Number of materials
  size_t d_number_materials;
  /// Downscatter switch (when true, upscatter ignored)
  bool d_downscatter[2];
  /// Total cross section [material, group]
  vec2_dbl d_sigma_t;
  /// Absorption cross section [material, group]
  vec2_dbl d_sigma_a;
  /// nu * Fission [material, group]
  vec2_dbl d_nu_sigma_f;
  /// Fission [material, group]
  vec2_dbl d_sigma_f;
  /// nu [material, group]
  vec2_dbl d_nu;
  /// Fission spectrum [material, group]
  vec2_dbl d_chi;
  /// Scatter [material, group<-, group']
  vec3_dbl d_sigma_s;
  /// Diffusion coefficient [material, group]
  vec2_dbl d_diff_coef;
  /// Scatter bounds applied to all materials [group, 2]
  vec2_size_t d_scatter_bounds;
  /// Groups equal to or above cutoff are subject to upscatter iterations
  size_t d_upscatter_cutoff[2];
  /// Are we ready to be used?
  bool d_finalized;

  //-------------------------------------------------------------------------//
  // IMPLEMENTATION
  //-------------------------------------------------------------------------//

  void material_display();

#ifdef DETRAN_ENABLE_BOOST

  /// Default constructor needed for serialization
  Material(){}

  friend class boost::serialization::access;

  template<class Archive>
  void serialize(Archive & ar, const unsigned int version)
  {
    ar & d_number_groups;
    ar & d_number_materials;
    ar & d_downscatter;
    ar & d_sigma_t;
    ar & d_sigma_a;
    ar & d_nu_sigma_f;
    ar & d_sigma_f;
    ar & d_nu;
    ar & d_chi;
    ar & d_sigma_s;
    ar & d_diff_coef;
    ar & d_scatter_bounds;
    ar & d_upscatter_cutoff;
    ar & d_finalized;
  }

#endif

};

MATERIAL_TEMPLATE_EXPORT(detran_utilities::SP<Material>)

} // end namespace detran_material

//---------------------------------------------------------------------------//
// INLINE FUNCTIONS
//---------------------------------------------------------------------------//

#include "Material.i.hh"

#endif /* detran_material_MATERIAL_HH_ */

ext: hh

max_stars_repo_name: baklanovp/libdetran

max_issues_repo_name: baklanovp/libdetran

max_forks_repo_name: baklanovp/libdetran


text:
#pragma once

#include <cstdint>

#include <array>
#include <memory>
#include <gsl/span>

#include <boost/asio/ip/tcp.hpp>

#include <albert/bt/bt.hpp>
#include <albert/bt/transport.hpp>
#include <albert/krpc/krpc.hpp>
#include <albert/u160/u160.hpp>
#include <albert/bt/ring_buffer.hpp>

namespace albert::bt::peer {
class Peer;

constexpr uint8_t MessageTypeChoke = 0;
constexpr uint8_t MessageTypeUnchoke = 1;
constexpr uint8_t MessageTypeInterested = 2;
constexpr uint8_t MessageTypeNotInterested = 3;
constexpr uint8_t MessageTypeHave = 4;
constexpr uint8_t MessageTypeBitfield = 5;
constexpr uint8_t MessageTypeRequest = 6;
constexpr uint8_t MessageTypePiece = 7;
constexpr uint8_t MessageTypeCancel = 8;
constexpr uint8_t MessageTypePort = 9;
constexpr uint8_t MessageTypeExtended = 20;
constexpr uint8_t ExtendedMessageTypeRequest = 0;
constexpr uint8_t ExtendedMessageTypeData = 1;
constexpr uint8_t ExtendedMessageTypeReject = 2;
constexpr size_t MetadataPieceSize = 16 * 1024;

constexpr size_t MCU = 65536;

class InvalidPeerMessage :public std::runtime_error {
 public:
  InvalidPeerMessage(const std::string &s) :runtime_error(s) { }
};
class InvalidStatus :public std::runtime_error {
 public:
  InvalidStatus(const std::string &s) :runtime_error(s) { }
};

#pragma pack(1)
struct Handshake {
  char magic[20] = {19,'B','i','t','T','o','r','r','e','n','t',' ','p','r','o','t','o','c','o','l'};
  /**
   * Enabled bits:
   * BEP-10 extension bit
   * DHT bit
   */
  uint8_t reserved[8]{0, 0, 0, 0, 0, 0x10, 0, 0x01};
  uint8_t info_hash[20]{};
  uint8_t sender_id[20]{};
};
#pragma pack()

constexpr const char *MetadataMessage = "ut_metadata";

enum class ConnectionStatus {
  Connecting,
  Connected,
  Disconnected,
};
class PeerConnection :public std::enable_shared_from_this<PeerConnection> {
  static std::mutex pointers_lock_;
  static std::set<PeerConnection*> pointers_;
 public:
  static std::set<PeerConnection*> get_pointers() {
    std::unique_lock _(pointers_lock_);
    return pointers_;
  }
  static size_t get_pointers_size() {
    std::unique_lock _(pointers_lock_);
    return pointers_.size();
  }
  PeerConnection(
      boost::asio::io_context &io_context,
      const u160::U160 &self,
      const u160::U160 &target,
      uint32_t bind_ip,
      uint16_t bind_port,
      uint32_t ip,
      uint16_t port,
      bool use_utp);
  ~PeerConnection();
  PeerConnection(const PeerConnection &) = delete;
  PeerConnection &operator=(const PeerConnection &) = delete;
  void connect(
      std::function<void(const boost::system::error_code &)> connect_handler = [](const boost::system::error_code&) { },
      std::function<void(int, size_t)> extended_handshake_handler = [](int, size_t) { }
  );
  ConnectionStatus status() const { return connection_status_; }
  std::string failed_reason() const { return failed_reason_; }
  void close();

  void interest(std::function<void()> unchoke_handler);
  bool has_piece(size_t piece) const;
  size_t next_valid_piece(size_t piece) const;

  void set_block_handler(std::function<void(size_t piece, size_t offset, gsl::span<uint8_t> data)> block_handler) { block_handler_ = block_handler; }
  void request(size_t index, size_t begin, size_t length);

  const Peer &peer() const { return *peer_; }
  const u160::U160 &peer_id() const { return peer_id_; }

  void start_metadata_transfer(
      std::function<void(
          int piece,
          const std::vector<uint8_t> &piece_data
      )> piece_data_handler
  );

  size_t memory_size() const;
 private:
  /**
   * Handlers
   */
  void handle_connect(const boost::system::error_code& ec);
  void handle_receive(const boost::system::error_code &err, size_t bytes_transferred);

  void handle_message(uint8_t type, const gsl::span<uint8_t> data);
  void handle_extended_message(
      uint8_t extended_id,
      std::shared_ptr<bencoding::DictNode> msg,
      const std::vector<uint8_t> &appended_data);
  void handle_keep_alive();
  /**
   * Send helpers
   */
  void send_handshake();
  void send_metadata_request(int64_t piece);
  void send_peer_message(uint8_t type, std::vector<uint8_t> data);

  void continue_receive();

  uint32_t read_size() {
    uint32_t ret;
    read_ring_.pop_data(&ret, sizeof(uint32_t));
    return utils::network_to_host(ret);
  }

  void set_peer_has_piece(size_t piece);

  uint8_t has_peer_extended_message(const std::string &message_name) const;
  uint8_t get_peer_extended_message_id(const std::string &message_name);
 private:
  // boost asio stuff
//  boost::asio::ip::tcp::socket socket_;
  std::shared_ptr<transport::Socket> socket_;

  Handshake sent_handshake_;
  Handshake received_handshake_;

  u160::U160 self_;
  u160::U160 target_;
  u160::U160 peer_id_;

  // buffers
  std::array<uint8_t, 65536> write_buffer_{};
  ring_buffer::RingBuffer<65536 * 2> read_ring_;

  // connection status
  std::unique_ptr<Peer> peer_;
  ConnectionStatus connection_status_ = ConnectionStatus::Connecting;
  std::string failed_reason_;
  bool handshake_completed_ = false;
  bool message_segmented = false;

  // Peer status
  bool peer_interested_ = false;
  bool peer_choke_ = true;
  std::vector<uint8_t> peer_bitfield_;
  std::shared_ptr<bencoding::DictNode> extended_handshake_;
  std::map<std::string, std::shared_ptr<bencoding::Node>> m_dict_;
  std::map<uint8_t, std::string> extended_message_id_ = {
      {2, MetadataMessage}
  };

  // stats
  uint32_t last_message_size_ = 0;
  size_t piece_count_ = 0;

  // handlers
  std::function<void(
      int piece,
      const std::vector<uint8_t> &piece_data
  )> piece_data_handler_;
  std::function<void(int total_pieces, size_t total_size)> extended_handshake_handler_;
  std::function<void(const boost::system::error_code &)> connect_handler_;

  std::function<void()> unchoke_handler_;
  std::function<void(size_t piece, size_t offset, gsl::span<uint8_t> data)> block_handler_;
};

}

ext: hpp


text:
/** MIT License

Copyright (c) 2018 Benjamin Bercovici and Jay McMahon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

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

  Class derived from VTK's vtkPolyDataAlgorithm by Benjamin Bercovici

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include <SBGATObsRadar.hpp>
// #include <vtkObjectFactory.h>
#include <vtkCell.h>
#include <vtkDataObject.h>
#include <vtkIdList.h>
#include <vtkMath.h>
#include <vtkSmartPointer.h>
#include <RigidBodyKinematics.hpp>
#include <vtkExtractHistogram2D.h>
#include <vtkFloatArray.h>
#include <vtkTable.h>
#include <vtkPNGWriter.h>
#include <vtkImageCast.h>
#include <vtkPointData.h>

#include <boost/progress.hpp>

vtkStandardNewMacro(SBGATObsRadar);

SBGATObsRadar::SBGATObsRadar() : SBGATObs(){

}

SBGATObsRadar::~SBGATObsRadar(){
}

void SBGATObsRadar::CollectMeasurements(SBGATRadarObsSequence & measurements_sequence,
  const double & time,
  const int & N,
  const arma::vec & radar_dir,
  const std::vector<arma::vec> & positions_vec,
  const std::vector<arma::vec> & velocities_vec,
  const std::vector<arma::vec> & mrps_vec,
  const std::vector<arma::vec> & omegas_vec,
  const bool & penalize_indicence){

  if(positions_vec.size() != omegas_vec.size() || positions_vec.size() != velocities_vec.size()|| positions_vec.size() != mrps_vec.size())
    throw(std::runtime_error("Incompatible input dimensions"));

  // Containers
  std::vector<std::vector<int> > facets_in_view;
  std::vector<arma::mat> BN_dcms_vec ;

  // Pre-allocating for all inputs
  for (int i = 0; i < this -> number_of_bodies; ++i){
    facets_in_view.push_back(std::vector<int>());
    BN_dcms_vec.push_back(RBK::mrp_to_dcm(mrps_vec[i]));
  }

  // First, only facets that are in view of the radar (based on their normal orientation) are kept
  // Then, the facets that are potentially in view are ray-traced to the observer,
  // checking with potential intersects with all bodies

  std::vector<arma::vec> dir_to_check_vec = {radar_dir};

  for (int i = 0; i < this -> number_of_bodies; ++i){
    this -> prefind_facets_inview(facets_in_view[i],i,dir_to_check_vec,BN_dcms_vec,positions_vec);
  }

  // The vector holding the kept-facets is initialized
  std::vector<std::array<double, 3> > measurements_temp;

  this -> reverse_ray_trace(measurements_sequence,facets_in_view,radar_dir,N,penalize_indicence,
    BN_dcms_vec,positions_vec,velocities_vec,omegas_vec);

}

void SBGATObsRadar::reverse_ray_trace(SBGATRadarObsSequence & measurements_sequence,
  const std::vector<std::vector<int> > & facets_in_view,
  const arma::vec & radar_dir,
  const int N,
  const bool penalize_indicence,
  const std::vector<arma::mat> & BN_dcms_vec,
  const std::vector<arma::vec> & positions_vec,
  const std::vector<arma::vec> & velocities_vec,
  const std::vector<arma::vec> & omegas_vec){

  std::vector<std::array<double, 3> > measurements;

  // Ray-tracing tolerance
  double tol = this -> polydata_vec[0] -> GetLength()/1E6;

  // The radar is positionned with respect to the primary
  arma::vec radar_pos = this -> center_of_mass_vec[0] + this -> polydata_vec[0] -> GetLength() * 1E6 * radar_dir;

  for (int body_index = 0; body_index < this -> number_of_bodies; ++body_index){

    vtkPolyData * input = this -> polydata_vec[body_index];

    vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New();
    ptIds -> Allocate(VTK_CELL_SIZE);

    arma::vec target_to_radar_dir_body_frame = BN_dcms_vec[body_index] * radar_dir;

  // The kept facets are then sampled and reverse ray-traced
    for (unsigned int facet_index = 0; facet_index != facets_in_view[body_index].size(); ++facet_index){

      double p0[3];
      double p1[3];
      double p2[3];

      input -> GetCellPoints(facets_in_view[body_index][facet_index],ptIds);
      input -> GetPoint(ptIds->GetId(0), p0);
      input -> GetPoint(ptIds->GetId(1), p1);
      input -> GetPoint(ptIds->GetId(2), p2);

      arma::vec P0 = {p0[0],p0[1],p0[2]};
      arma::vec P1 = {p1[0],p1[1],p1[2]};
      arma::vec P2 = {p2[0],p2[1],p2[2]};

      arma::vec n = arma::cross(P1 - P0, P2 - P0);

    // The number of points sampled from this facet is determined based on
    // the relative size of this facet compared to the largest one in all the considered shapes
      int N_samples = int( N * arma::norm(n /2) / this -> min_area);

    // only need unit normal vector from here
      n = arma::normalise(arma::cross(P1 - P0, P2 - P0));

      double cosi_radar ;

    // Computing the ray incidence at impact if needed
      if (penalize_indicence){
        cosi_radar = vtkMath::Dot(n.colptr(0),target_to_radar_dir_body_frame.colptr(0));
      }
      else{
        cosi_radar = 1;
      }

    // A maximum of N points are sampled from this facet
    // #pragma omp parallel for
      for (int i = 0; i < N_samples; ++i){

      // A random origin point is uniformly drawn from this facet
        arma::vec random = arma::randu<arma::vec>(2);
        double u = random(0);
        double v = random(1);
        arma::vec origin = (1 - std::sqrt(u)) * P0 + std::sqrt(u) * ( 1 - v ) * P1 + std::sqrt(u) * v * P2 ;

      arma::vec point_above_surface = origin + 3 * tol * n; // the origin of the ray is moved 3*tol above the surface

      bool has_intersected = this -> check_line_for_intersect(body_index,point_above_surface,radar_pos,BN_dcms_vec,positions_vec,tol);

      // If this point was not obscured, the return is weighed by the incidence on the inbound and outbout rays

      if (!has_intersected){

        // origin is the sampled point, expressed in the body reference frame
        // Its actual position should be in the inertial frame, accounting for the assigned position of the body

        arma::vec origin_cm = BN_dcms_vec[body_index].t() * (origin - this -> center_of_mass_vec[body_index]);
        arma::vec origin_inertial = origin_cm + positions_vec[body_index];

        // Range
        double range = arma::norm(origin_inertial - radar_pos);

        // The velocity at the impact point is a combination of the orbital and rotational velocities
        arma::vec velocity = velocities_vec[body_index] + arma::cross(omegas_vec[body_index],origin_cm);

        double range_rate = arma::dot(origin_inertial - radar_pos,velocity) / range;

        std::array<double, 3> measurement = {{range,range_rate,std::pow(cosi_radar,2)}};
        measurements.push_back(measurement);
      }

    }
  }
}

measurements_sequence.push_back(measurements);

}

void SBGATObsRadar::BinObservations(
  const SBGATRadarObsSequence & measurements_sequence,
  const double & r_bin,
  const double & rr_bin){

  // The container holding the images is pre-allocated
  this -> images.clear();
  this -> max_value = -1;

  for (unsigned int i = 0; i < measurements_sequence.size(); ++i){

    auto measurements = measurements_sequence[i];

    this -> images.push_back(vtkSmartPointer<vtkImageData>::New());

  // Using arma::vec to get statistics
    arma::vec ranges(measurements.size());
    arma::vec range_rates(measurements.size());

    for (unsigned int i = 0; i < measurements.size(); ++i){
      ranges(i) = measurements[i][0];
      range_rates(i) = measurements[i][1];
    }

  // Subtracting the mean range
    ranges -= arma::mean(ranges);

  // The extent of the data is extracted
    double r_extent = std::abs(ranges.max() - ranges.min()) * this -> scaleFactor;
    double rr_extent = std::abs(range_rates.max() - range_rates.min()) * this -> scaleFactor;

  // The bin counts are determined from the specified bin sizes and data extent
    int n_bin_r = (int)(r_extent / r_bin);
    int n_bin_rr = (int)(rr_extent / rr_bin);

    // Checking if one dimension is "empty" (i.e has zero bins)
    if (n_bin_r == 0 || n_bin_rr == 0){
      throw(std::runtime_error("The prescribed bin sizes yielded " + std::to_string(n_bin_r) + " range bins and " + std::to_string(n_bin_rr) + " range-rate bins. "));
    }

    // The image is formed by "binning in" the measurements

    this -> images[i] -> SetExtent(0, n_bin_rr - 1, 0, n_bin_r - 1, 0, 0);
    this -> images[i] -> AllocateScalars(VTK_DOUBLE, 1);

    double *dPtr = static_cast<double *>(this -> images[i]->GetScalarPointer(0, 0, 0));

    // The image is initialized
    #pragma omp parallel for
    for (int row = 0; row < n_bin_r; ++row){
      for (int col = 0; col < n_bin_rr; ++col){
        int k = col + row * n_bin_rr;
        dPtr[k] = 0;
      }
    }

    double max_range = ranges.max();
    double max_range_rate = range_rates.max();

    // The histogram is built
    #pragma omp parallel for
    for (unsigned int mes = 0; mes < measurements.size(); ++mes){

      // Flipping the image
      int row = int( ( - ranges(mes) +  max_range)/ r_bin );
      int col = int( ( - range_rates(mes) + max_range_rate )/ rr_bin );

      // The last bin is inclusive
      if (row == n_bin_r){
        --row;
      }
      if (col == n_bin_rr){
        --col;
      }

      int k = col + row * n_bin_rr;

      // Adding the cosine of the incidence
      // If the incidence is 0 then measurements[mes][2] == 1.
      // if the incidence is 90 deg then measurements[mes][2] == 0
      // if the incidence is not used then measurements[mes][2] == 1 always
      dPtr[k] += measurements[mes][2];

    }

    // The maximum image value is extracted
    vtkDataArray * scalars = this -> images[i] -> GetPointData() -> GetScalars();

    for (vtkIdType tupleIdx = 0; tupleIdx < scalars -> GetNumberOfTuples(); ++tupleIdx){
     this -> max_value = std::max(max_value,scalars -> GetTuple1(tupleIdx));
   }

 }

}

void SBGATObsRadar::SaveImages( std::string savepath){

  vtkSmartPointer<vtkImageCast> cast = vtkSmartPointer<vtkImageCast>::New();
  vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter> ::New();

  for (unsigned int i = 0; i < this -> images.size(); ++i){

   // Each image is normalized before being saved
   vtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New();
   image -> DeepCopy(this -> images[i]);

   vtkDataArray * scalars = image -> GetPointData() -> GetScalars();

   for (vtkIdType tupleIdx = 0; tupleIdx < scalars -> GetNumberOfTuples(); ++tupleIdx){
    scalars -> SetTuple1(tupleIdx,scalars -> GetTuple1(tupleIdx) * 255 / this -> max_value );
  }

  cast -> SetInputData(image);
  cast -> SetOutputScalarTypeToUnsignedChar();
  std::string complete_save_path = savepath + "image_" + std::to_string(i) + ".png";

  writer -> SetFileName(complete_save_path.c_str());
  writer -> SetInputConnection(cast->GetOutputPort());
  writer -> Write();
}

}

std::vector<vtkSmartPointer<vtkImageData>> SBGATObsRadar::GetImages() const{
  return this -> images;

}

void SBGATObsRadar::PrintHeader(ostream& os, vtkIndent indent) {

}
void SBGATObsRadar::PrintTrailer(ostream& os, vtkIndent indent) {

}

//----------------------------------------------------------------------------
void SBGATObsRadar::PrintSelf(std::ostream& os, vtkIndent indent){

  vtkPolyData *input = vtkPolyData::SafeDownCast(this->GetInput(0));
  if (!input)
  {
    return;
  }

}

max_stars_repo_name: bbercovici/SBGAT

max_issues_repo_name: bbercovici/SBGAT

max_forks_repo_name: bbercovici/SBGAT