text:
/*=============================================================================
    Copyright (c) 2003 Joel de Guzman

    Use, modification and distribution is subject to 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)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_IS_SEQUENCE_HPP)
#define FUSION_SEQUENCE_IS_SEQUENCE_HPP

#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/spirit/fusion/sequence/detail/sequence_base.hpp>

namespace boost { namespace fusion
{
    ///////////////////////////////////////////////////////////////////////////
    //
    //  is_sequence metafunction
    //
    //      Given a type T, returns a value true or false if T is a
    //      fusion sequence or not. Usage:
    //
    //          is_sequence<T>::value
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct is_sequence : is_base_and_derived<sequence_root, T> {};

}}

#endif

max_stars_repo_name: dstrigl/mcotf

max_issues_repo_name: dstrigl/mcotf

max_forks_repo_name: dstrigl/mcotf


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
//==============================================================================
#ifndef NT2_TOOLBOX_LINALG_DETAILS_BLAS_MV_HPP_INCLUDED
#define NT2_TOOLBOX_LINALG_DETAILS_BLAS_MV_HPP_INCLUDED

#include <complex>
#include <boost/preprocessor/cat.hpp>
#include <nt2/toolbox/linalg/details/blas/blas2.hpp>
#include <nt2/toolbox/linalg/details/utility/f77_wrapper.hpp>

namespace nt2 { namespace details
{
#define NT2_MV(T, PX)                                                   \
inline void gemv( const char *ta                                        \
                , const long int *m, const long int *n                  \
                , const T *al                                           \
                , const T *a, const long int *lda                       \
                , const T *x, const long int *incx                      \
                , const T *be                                           \
                , T *y      , const long int *incy                      \
                )                                                       \
{                                                                       \
  NT2_F77NAME(BOOST_PP_CAT(PX,gemv))(ta,m,n,al,a,lda,x,incx,be,y,incy); \
}                                                                       \
/**/

  // INTERNAL ONLY
  // gemv binding for all types
  // _GEMV (TRANS, M, N, ALPHA, A, LDA, X, INCX, BETA,  Y, INCY )
  NT2_MV(double, d)
  NT2_MV(float,  s)
  NT2_MV(std::complex<double>, z)
  NT2_MV(std::complex<float>, c)

#undef NT2_MV

#define NT2_MV(T, PX)                                                         \
inline void gbmv( const char *ta                                              \
                , const long int *m, const long int *n                        \
                , const long int *kl, const long int *ku                      \
                , const T *al                                                 \
                , const T *a, const long int *lda                             \
                , const T *x, const long int *incx                            \
                , const T *be                                                 \
                , T *y      , const long int *incy                            \
                )                                                             \
{                                                                             \
  NT2_F77NAME(BOOST_PP_CAT(PX,gbmv))(ta,m,n,kl,ku,al,a,lda,x,incx,be,y,incy); \
}                                                                             \
/**/

  // INTERNAL ONLY
  // gbmv binding for all types
  // _GBMV(TRANS, M, N, KL, KU, ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
  NT2_MV(double, d)
  NT2_MV(float,  s)
  NT2_MV(std::complex<double>, z)
  NT2_MV(std::complex<float>, c)

#undef NT2_MV

#define NT2_MV(T, P, Q)                                                             \
inline void BOOST_PP_CAT(Q,mv)( const char *uplo, const long int *n                 \
                              , const T *al                                         \
                              , const T *a, const long int *lda                     \
                              , const T *x, const long int *incx                    \
                              , const T *be                                         \
                              , T *y      , const long int *incy                    \
                              )                                                     \
{                                                                                \
  NT2_F77NAME(BOOST_PP_CAT(P,BOOST_PP_CAT(Q,mv)))(ta,n,al,a,lda,x,incx,be,y,incy);  \
}                                                                                \
/**/

  //  INTERNAL ONLY
  // *mv binging for hermittian/symmetric cases
  // _HEMV ( UPLO, N, ALPHA, A, LDA, X, INCX, BETA,  Y, INCY )
  // _SYMV ( UPLO, N, ALPHA, A, LDA, X, INCX, BETA,  Y, INCY )
  NT2_MV(std::complex<double>, z, he)
  NT2_MV(std::complex<float>, c, he)
  NT2_MV(std::complex<double>, z, sy)
  NT2_MV(std::complex<float>, c, sy)
  NT2_MV(double, d, sy)
  NT2_MV(float,  s, sy)

#undef NT2_MV

#define NT2_MV(T, P, Q)                                                               \
inline void BOOST_PP_CAT(Q,mv)( const char *uplo                                      \
                              , const long int *n, const long int *k                  \
                              , const T *al                                           \
                              , const T *a, const long int *lda                       \
                              , const T *x, const long int *incx                      \
                              , const T *be                                           \
                              , T *y      , const long int *incy                      \
                              )                                                       \
{                                                                                \
  NT2_F77NAME(BOOST_PP_CAT(P,BOOST_PP_CAT(Q,mv)))(ta,n,k,al,a,lda,x,incx,be,y,incy);  \
}                                                                                \
/**/

  // _HBMV ( UPLO, N, K, ALPHA, A, LDA, X, INCX, BETA,  Y, INCY )
  // _SBMV ( UPLO, N, K, ALPHA, A, LDA, X, INCX, BETA,  Y, INCY )
  NT2_MV(std::complex<double>, z, hb)
  NT2_MV(std::complex<float>, c, hb)
  NT2_MV(std::complex<double>, z, sb)
  NT2_MV(std::complex<float>, c, sb)
  NT2_MV(double, d, sb)
  NT2_MV(float,  s, sb)

#undef NT2_MV

#define NT2_MV(T, P, Q)                                                         \
inline void BOOST_PP_CAT(Q,mv)( const char *uplo, const long int *n             \
                              , const T *al , const T *ap                       \
                              , const T *x  , const long int *incx              \
                              , const T *be                                     \
                              , T *y        , const long int *incy              \
                              )                                                 \
{                                                                               \
  NT2_F77NAME(BOOST_PP_CAT(P,BOOST_PP_CAT(Q,mv)))(ta,n,al,ap,x,incx,be,y,incy); \
}                                                                               \
/**/

  // _HPMV ( UPLO N, ALPHA, AP, X, INCX, BETA,  Y, INCY )
  // _SPMV ( UPLO N, ALPHA, AP, X, INCX, BETA,  Y, INCY )
  NT2_MV(std::complex<double> , z, hp )
  NT2_MV(std::complex<float>  , c, hp )
  NT2_MV(std::complex<double> , z, sp )
  NT2_MV(std::complex<float>  , c, sp )
  NT2_MV(double, d, sp)
  NT2_MV(float,  s, sp)

#undef NT2_MV

#define NT2_MV(T, P)                                                    \
inline void tpmv( const char *uplo, const char *trans, const char *diag \
                , const long int *n                                     \
                , const T *ap                                           \
                , T *x, const long int *incx                            \
                )                                                       \
{                                                                       \
  NT2_F77NAME(BOOST_PP_CAT(P,tpmv))(uplo,trans,diag,n,ap,x,incx);       \
}                                                                       \
/**/

  // _TPMV ( UPLO, TRANS, DIAG, N, A, LDA, X, INCX )
  NT2_MV(double, d)
  NT2_MV(float,  s)
  NT2_MV(std::complex<double> , z )
  NT2_MV(std::complex<float>  , c )

#undef NT2_MV

#define NT2_MV(T, P)                                                    \
inline void trmv( const char *uplo, const char *trans, const char *diag \
                , const long int *n                                     \
                , const T *a, const long int *lda                       \
                , T *x      , const long int *incx                      \
                )                                                       \
{                                                                       \
  NT2_F77NAME(BOOST_PP_CAT(P,trmv))(uplo,trans,diag,n,a,lda,x,incx);    \
}                                                                       \
/**/

  // _TRMV ( UPLO, TRANS, DIAG, N, AP, X, INCX )
  NT2_MV(double, d)
  NT2_MV(float,  s)
  NT2_MV(std::complex<double> , z )
  NT2_MV(std::complex<float>  , c )
#undef NT2_MV

#define NT2_MV(T, P)                                                    \
inline void tbmv( const char *uplo, const char *trans, const char *diag \
                , const long int *n,  const long int *k                 \
                , const T *a, const long int *lda                       \
                , T *x      , const long int *incx                      \
                )                                                       \
{                                                                       \
  NT2_F77NAME(BOOST_PP_CAT(P,tbmv))(uplo,trans,diag,n,k, a,lda,x,incx); \
}                                                                       \
/**/

  // _TBMV ( UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX )
  NT2_MV(double, d)
  NT2_MV(float,  s)
  NT2_MV(std::complex<double>, z)
  NT2_MV(std::complex<float>, c)

#undef NT2_MV
} }

#endif

ext: hpp


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_IF_MINUS_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_IF_MINUS_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-boolean
    Function object implementing if_minus capabilities

    The function returns the second entry or the difference of the
    second and third entries, according to the first entry being @ref False
    or @ref True

    @par Semantic:

    For every parameters @c c of type @c C and @c x, @c y of type @c T:

    @code
    T1 r = if_minus(c, x, y);
    @endcode

    is similar to:

    @code
    T1 r = c ? x-y : x;
    @endcode
  **/
  Value if_minus(Value const& c, Value const& x, Value const&  y);

  //@overload
  Value if_minus(LogicalValue const& c, Value const& x, Value const& y);
} }
#endif

#include <boost/simd/function/scalar/if_minus.hpp>
#include <boost/simd/function/simd/if_minus.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text: #include <boost/hana/cartesian_product.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright Louis Dionne 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#ifndef DYNO_EXPERIMENTAL_UNROLLED_VTABLE_HPP
#define DYNO_EXPERIMENTAL_UNROLLED_VTABLE_HPP

#include <dyno/concept.hpp>
#include <dyno/detail/erase_function.hpp>
#include <dyno/detail/erase_signature.hpp>

#include <boost/hana/functional/on.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/type.hpp>
#include <boost/hana/unpack.hpp>

namespace dyno { namespace experimental {

namespace detail {
  template <typename ...Mappings>
  struct unrolled_vtable_impl;
}

template <typename Concept>
using unrolled_vtable = typename decltype(
  boost::hana::unpack(dyno::clauses(Concept{}),
    boost::hana::template_<detail::unrolled_vtable_impl> ^boost::hana::on^ boost::hana::decltype_
  )
)::type;

/*
What follows is a script to generate the specializations of `unrolled_vtable_impl`.
Run the script as

  awk '/SCRIPTBEGIN/{flag=1;next}/SCRIPTEND/{flag=0}flag' ${thisfile} | erb

SCRIPTBEGIN
<% (0..10).each do |n| %>
template <
  <%= (0...n).map {|i| "typename Name#{i}, typename Sig#{i}" }.join(",\n  ") %>
> struct unrolled_vtable_impl<
  <%= (0...n).map {|i| "boost::hana::pair<Name#{i}, boost::hana::basic_type<Sig#{i}>>" }.join(",\n  ") %>
> {
  template <typename ConceptMap>
  constexpr explicit unrolled_vtable_impl(ConceptMap map)
    <%= ": " unless n == 0 %><%= (0...n).map {|i| "fptr#{i}_(dyno::detail::erase_function<Sig#{i}>(map[Name#{i}{}]))" }.join("\n    , ") %>
  { }
  <%= (0...n).map {|i| "constexpr auto operator[](Name#{i}) const { return fptr#{i}_; };" }.join("\n  ") %>

private:
  <%= (0...n).map {|i| "typename detail::erase_signature<Sig#{i}>::type* fptr#{i}_;" }.join("\n  ") %>
};
<% end %>
SCRIPTEND */

namespace detail {
  ////////////////////////////////////////////////////////////////////////////
  // BEGIN GENERATED CODE
  ////////////////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////////////////
  // END GENERATED CODE
  ////////////////////////////////////////////////////////////////////////////
} // end namespace detail

}} // end namespace dyno::experimental

#endif // DYNO_EXPERIMENTAL_UNROLLED_VTABLE_HPP

max_stars_repo_name: BRevzin/dyno

max_issues_repo_name: BRevzin/dyno

max_forks_repo_name: BRevzin/dyno


text:
//| This file is a part of the sferes2 framework.
//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)
//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr
//|
//| This software is a computer program whose purpose is to facilitate
//| experiments in evolutionary computation and evolutionary robotics.
//|
//| This software is governed by the CeCILL license under French law
//| and abiding by the rules of distribution of free software.  You
//| can use, modify and/ or redistribute the software under the terms
//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the
//| following URL "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and rights to
//| copy, modify and redistribute granted by the license, users are
//| provided only with a limited warranty and the software's author,
//| the holder of the economic rights, and the successive licensors
//| have only limited liability.
//|
//| In this respect, the user's attention is drawn to the risks
//| associated with loading, using, modifying and/or developing or
//| reproducing the software by the user in light of its specific
//| status of free software, that may mean that it is complicated to
//| manipulate, and that also therefore means that it is reserved for
//| developers and experienced professionals having in-depth computer
//| knowledge. Users are therefore encouraged to load and test the
//| software's suitability as regards their requirements in conditions
//| enabling the security of their systems and/or data to be ensured
//| and, more generally, to use and operate it in the same conditions
//| as regards security.
//|
//| The fact that you are presently reading this means that you have
//| had knowledge of the CeCILL license and that you accept its terms.

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE dnn

#include <boost/test/unit_test.hpp>
#include <iostream>
#include <sferes/fit/fitness.hpp>
#include <sferes/phen/parameters.hpp>

#include "gen_dnn.hpp"
#include "gen_hyper_nn.hpp"
#include "phen_hyper_nn.hpp"

using namespace sferes;
using namespace sferes::gen::dnn;
using namespace sferes::gen::evo_float;

struct Params1
{
  struct dnn
  {
    SFERES_CONST size_t nb_inputs = 3;
    SFERES_CONST size_t nb_outputs = 1;

    SFERES_CONST float m_rate_add_conn = 1.0f;
    SFERES_CONST float m_rate_del_conn = 0.3f;
    SFERES_CONST float m_rate_change_conn = 1.0f;
    SFERES_CONST float m_rate_add_neuron = 1.0f;
    SFERES_CONST float m_rate_del_neuron = 0.2f;

    SFERES_CONST init_t init = ff;
  };
  struct evo_float
  {
    SFERES_CONST float mutation_rate = 0.1f;
    SFERES_CONST float cross_rate = 0.1f;
    SFERES_CONST mutation_t mutation_type = polynomial;
    SFERES_CONST cross_over_t cross_over_type = sbx;
    SFERES_CONST float eta_m = 15.0f;
    SFERES_CONST float eta_c = 15.0f;
  };
  struct parameters
  {
    SFERES_CONST float min = -2.0f;
    SFERES_CONST float max = 2.0f;
  };

  struct cppn
  {
     // params of the CPPN
    struct sampled
    {
      SFERES_ARRAY(float, values, 0, 1, 2);
      SFERES_CONST float mutation_rate = 0.1f;
      SFERES_CONST float cross_rate = 0.25f;
      SFERES_CONST bool ordered = false;
    };
    struct evo_float
    {
      SFERES_CONST float mutation_rate = 0.1f;
      SFERES_CONST float cross_rate = 0.1f;
      SFERES_CONST mutation_t mutation_type = polynomial;
      SFERES_CONST cross_over_t cross_over_type = sbx;
      SFERES_CONST float eta_m = 15.0f;
      SFERES_CONST float eta_c = 15.0f;
    };
  };
};

struct Params2
{
  struct dnn
  {
    SFERES_CONST size_t nb_inputs = 4;
    SFERES_CONST size_t nb_outputs = 1;

    SFERES_CONST float m_rate_add_conn = 1.0f;
    SFERES_CONST float m_rate_del_conn = 0.3f;
    SFERES_CONST float m_rate_change_conn = 1.0f;
    SFERES_CONST float m_rate_add_neuron = 1.0f;
    SFERES_CONST float m_rate_del_neuron = 0.2f;

    SFERES_CONST float weight_sigma = 0.5f;
    SFERES_CONST float vect_sigma = 0.5f;
    SFERES_CONST float m_rate_weight = 1.0f;
    SFERES_CONST float m_rate_fparams = 1.0f;
    SFERES_CONST init_t init = ff;
  };
  struct evo_float
  {
    SFERES_CONST float mutation_rate = 0.1f;
    SFERES_CONST float cross_rate = 0.1f;
    SFERES_CONST mutation_t mutation_type = polynomial;
    SFERES_CONST cross_over_t cross_over_type = sbx;
    SFERES_CONST float eta_m = 15.0f;
    SFERES_CONST float eta_c = 15.0f;
  };
  struct parameters
  {
    SFERES_CONST float min = -2.0f;
    SFERES_CONST float max = 2.0f;
  };

  struct cppn
  {
     // params of the CPPN
    struct sampled
    {
      SFERES_ARRAY(float, values, 0, 1, 2);
      SFERES_CONST float mutation_rate = 0.1f;
      SFERES_CONST float cross_rate = 0.25f;
      SFERES_CONST bool ordered = false;
    };
    struct evo_float
    {
      SFERES_CONST float mutation_rate = 0.1f;
      SFERES_CONST float cross_rate = 0.1f;
      SFERES_CONST mutation_t mutation_type = polynomial;
      SFERES_CONST cross_over_t cross_over_type = sbx;
      SFERES_CONST float eta_m = 15.0f;
      SFERES_CONST float eta_c = 15.0f;
    };
  };
  struct hyper_nn
  {
    SFERES_ARRAY(float, substrate,
                 0.2f, 0.2f, // in 1
                 0.2f, 0.8f, // in 2
                 0.5f, 0.5f, // out 1
                 0.8f, 0.8f, // hidden 1
                 0.8f, 0.2f, // hidden 2
                 0.2f, 0.5f, // hidden 3
                 0.5f, 0.2f  // hidden 4
                 );
    SFERES_ARRAY(float, weights, -1, 0, 1);
    SFERES_ARRAY(float, bias, -1, 0, 1);
    SFERES_CONST size_t nb_inputs = 2;
    SFERES_CONST size_t nb_outputs = 1;
    SFERES_CONST size_t nb_hidden = 4;
    SFERES_CONST size_t nb_pfparams = 0;
    SFERES_CONST size_t nb_afparams = 1;
    SFERES_CONST float conn_threshold = 0.2f;
    SFERES_CONST float max_y = 10.0f;
    typedef nn::Neuron<nn::PfWSum<>,
                       nn::AfTanh<nn::params::Vectorf<1> > > neuron_t;
    typedef nn::Connection<> connection_t;
  };
};

BOOST_AUTO_TEST_CASE(gen_cppn)
{
  srand(time(0));
  typedef phen::Parameters<gen::EvoFloat<1, Params1>, fit::FitDummy<>, Params1> weight_t;
  typedef gen::HyperNn<weight_t, Params1> cppn_t;

  cppn_t gen1, gen2, gen3, gen4;

  gen1.random();
  for (size_t i = 0; i < 20; ++i)
    gen1.mutate();
  gen1.init();
  BOOST_CHECK(gen1.get_depth() >= 1);
  std::ofstream ofs2("/tmp/nn.dot");
  gen1.write(ofs2);

   //  generate a picture
  char*pic = new char[256 * 256];
  std::vector<float> in(3);
  in[0] = 1;
  for (size_t i = 0; i < 256; ++i)
    for (size_t j = 0; j < 256; ++j)
    {
      in[1] = i / 128.0f - 1.0;
      in[2] = j / 128.0f - 1.0;
      for (size_t k = 0; k < gen1.get_depth(); ++k)
        gen1.step(in);
      pic[256 * i + j] = (int)(gen1.get_outf(0) * 256 + 255);
    }
  std::ofstream ofs("/tmp/pic.pgm");
  ofs << "P5" << std::endl;
  ofs << "256 256" << std::endl;
  ofs << "255" << std::endl;
  ofs.write(pic, 256 * 256);
}

BOOST_AUTO_TEST_CASE(phen_hyper_nn)
{
  srand(time(0));
  typedef fit::FitDummy<> fit_t;
  typedef phen::Parameters<gen::EvoFloat<1, Params2>, fit::FitDummy<>, Params2> weight_t;
  typedef gen::HyperNn<weight_t, Params2> gen_t;
  typedef phen::HyperNn<gen_t, fit_t, Params2> phen_t;

  phen_t indiv;
  indiv.random();
  for (size_t i = 0; i < 5; ++i)
    indiv.mutate();
  std::ofstream ofs("/tmp/nn_substrate.svg");
  indiv.develop();
  indiv.show(ofs);
  // BOOST_CHECK_EQUAL(indiv.nn().get_nb_neurons(), 7);

}

ext: cpp

max_stars_repo_name: Evolving-AI-Lab/innovation-engine

max_issues_repo_name: Evolving-AI-Lab/innovation-engine

max_forks_repo_name: Evolving-AI-Lab/innovation-engine


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * 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 <cstddef>
#include <string>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/utility.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes/constant.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
#include <boost/log/attributes/attribute_value_impl.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/manipulators/add_value.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;

BOOST_LOG_ATTRIBUTE_KEYWORD(line_id, "LineID", unsigned int)
BOOST_LOG_ATTRIBUTE_KEYWORD(remote_address, "RemoteAddress", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(received_size, "ReceivedSize", std::size_t)
BOOST_LOG_ATTRIBUTE_KEYWORD(sent_size, "SentSize", std::size_t)

//[ example_sources_network_connection
class network_connection
{
    src::logger m_logger;
    logging::attribute_set::iterator m_remote_addr;

public:
    void on_connected(std::string const& remote_addr)
    {
        // Put the remote address into the logger to automatically attach it
        // to every log record written through the logger
        m_remote_addr = m_logger.add_attribute("RemoteAddress",
            attrs::constant< std::string >(remote_addr)).first;

        // The straightforward way of logging
        if (logging::record rec = m_logger.open_record())
        {
            rec.attribute_values().insert("Message",
                attrs::make_attribute_value(std::string("Connection established")));
            m_logger.push_record(boost::move(rec));
        }
    }
    void on_disconnected()
    {
        // The simpler way of logging: the above "if" condition is wrapped into a neat macro
        BOOST_LOG(m_logger) << "Connection shut down";

        // Remove the attribute with the remote address
        m_logger.remove_attribute(m_remote_addr);
    }
    void on_data_received(std::size_t size)
    {
        // Put the size as an additional attribute
        // so it can be collected and accumulated later if needed.
        // The attribute will be attached only to this log record.
        BOOST_LOG(m_logger) << logging::add_value("ReceivedSize", size) << "Some data received";
    }
    void on_data_sent(std::size_t size)
    {
        BOOST_LOG(m_logger) << logging::add_value("SentSize", size) << "Some data sent";
    }
};
//]

int main(int, char*[])
{
    // Construct the sink
    typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
    boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

    // Add a stream to write log to
    sink->locked_backend()->add_stream(
        boost::make_shared< std::ofstream >("sample.log"));

    // Set the formatter
    sink->set_formatter
    (
        expr::stream
            << line_id
            << ": [" << remote_address << "] "
            << expr::if_(expr::has_attr(received_size))
               [
                    expr::stream << "[Received: " << received_size << "] "
               ]
            << expr::if_(expr::has_attr(sent_size))
               [
                    expr::stream << "[Sent: " << sent_size << "] "
               ]
            << expr::smessage
    );

    // Register the sink in the logging core
    logging::core::get()->add_sink(sink);

    // Register other common attributes, such as time stamp and record counter
    logging::add_common_attributes();

    // Emulate network activity
    network_connection conn;

    conn.on_connected("11.22.33.44");
    conn.on_data_received(123);
    conn.on_data_sent(321);
    conn.on_disconnected();

    return 0;
}

max_issues_repo_name: graehl/boost

max_forks_repo_name: graehl/boost


text:
#pragma once

#include <bunsan/curl/detail/easy.hpp>
#include <bunsan/curl/detail/static_range.hpp>
#include <bunsan/curl/error.hpp>

#include <curl/curl.h>

#include <boost/range/iterator_range.hpp>
#include <boost/scope_exit.hpp>

namespace bunsan {
namespace curl {
namespace options {
namespace wrapper {

template <CURLoption DataId, CURLoption SizeId, typename Wrapper>
class wrapped_bytes : public Wrapper {
 public:
  using retention_policy = typename Wrapper::retention_policy;

  using Wrapper::Wrapper;

  constexpr CURLoption data_id() const { return DataId; }
  constexpr CURLoption size_id() const { return SizeId; }

  curl::detail::static_range<CURLoption> ids() const {
    return curl::detail::make_static_range<CURLoption, DataId, SizeId>();
  }

  void setopt(CURL *const curl) const {
    try {
      curl::detail::easy::setopt(curl, size_id(), Wrapper::size());
      curl::detail::easy::setopt(curl, data_id(), Wrapper::data());
    } catch (...) {
      unsetopt(curl);
      throw;
    }
  }

  void unsetopt(CURL *const curl) const noexcept {
    // see Curl_init_userdefined()
    constexpr decltype(Wrapper::size()) unknown_size = -1;

    ::curl_easy_setopt(curl, size_id(), unknown_size);
    ::curl_easy_setopt(curl, data_id(), nullptr);
  }
};

}  // namespace wrapper
}  // namespace options
}  // namespace curl
}  // namespace bunsan

#define BUNSAN_CURL_BYTES_WRAPPED(NAME, DATA, SIZE, ...)        \
  using NAME = ::bunsan::curl::options::wrapper::wrapped_bytes< \
      DATA, SIZE, ::bunsan::curl::options::wrapper::__VA_ARGS__>;


text:
#ifndef QPWBC_H_INCLUDED
#define QPWBC_H_INCLUDED

#include "qrw/InvKin.hpp" // For pseudoinverse
#include "qrw/Params.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <limits>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Dense>
#include "osqp.h"
#include "other/st_to_cc.hpp"

class QPWBC {
 private:

  Params* params_;  // Object that stores parameters

  int cpt_ML = 0;
  int cpt_P = 0;

  // Set to True after the creation of the QP problem during the first call of the solver
  bool initialized = false;

  // Weight matrices of initial QP
  Eigen::Matrix<double, 6, 6> Q1 = Eigen::Matrix<double, 6, 6>::Identity();
  Eigen::Matrix<double, 12, 12> Q2 = Eigen::Matrix<double, 12, 12>::Identity();

  // Friction coefficient
  const double mu = 0.9;

  // Generatrix of the linearized friction cone
  Eigen::Matrix<double, 20, 12> G = Eigen::Matrix<double, 20, 12>::Zero();

  // Transformation matrices
  Eigen::Matrix<double, 6, 6> Y = Eigen::Matrix<double, 6, 6>::Zero();
  Eigen::Matrix<double, 6, 12> X = Eigen::Matrix<double, 6, 12>::Zero();
  Eigen::Matrix<double, 6, 6> Yinv = Eigen::Matrix<double, 6, 6>::Zero();
  Eigen::Matrix<double, 6, 12> A = Eigen::Matrix<double, 6, 12>::Zero();
  Eigen::Matrix<double, 6, 1> gamma = Eigen::Matrix<double, 6, 1>::Zero();
  Eigen::Matrix<double, 12, 12>  H = Eigen::Matrix<double, 12, 12>::Zero();
  Eigen::Matrix<double, 12, 1> g = Eigen::Matrix<double, 12, 1>::Zero();

  // Results
  // Eigen::Matrix<double, 12, 1> lambdas = Eigen::Matrix<double, 12, 1>::Zero();
  Eigen::MatrixXd f_res = Eigen::MatrixXd::Zero(12, 1);
  Eigen::MatrixXd ddq_res = Eigen::MatrixXd::Zero(12, 1);

  // Matrix ML
  const static int size_nz_ML = 20*12; //4 * (4 * 2 + 1);
  csc *ML;  // Compressed Sparse Column matrix

  // Matrix NK
  const static int size_nz_NK = 20;
  double v_NK_up[size_nz_NK] = {};   // matrix NK (upper bound)
  double v_NK_low[size_nz_NK] = {};  // matrix NK (lower bound)
  double v_warmxf[size_nz_NK] = {};  // matrix NK (lower bound)

  // Matrix P
  const static int size_nz_P = 6*13; // 6*13; // 12*13/2;
  csc *P;  // Compressed Sparse Column matrix

  // Matrix Q
  const static int size_nz_Q = 12;
  double Q[size_nz_Q] = {};  // Q is full of zeros

  // OSQP solver variables
  OSQPWorkspace *workspce = new OSQPWorkspace();
  OSQPData *data;
  OSQPSettings *settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));

 public:

  QPWBC(); // Constructor
  void initialize(Params& params);

  // Functions
  inline void add_to_ML(int i, int j, double v, int *r_ML, int *c_ML, double *v_ML); // function to fill the triplet r/c/v
  inline void add_to_P(int i, int j, double v, int *r_P, int *c_P, double *v_P); // function to fill the triplet r/c/v
  int create_matrices();
  int create_ML();
  int create_weight_matrices();
  void compute_matrices(const Eigen::MatrixXd &M, const Eigen::MatrixXd &Jc, const Eigen::MatrixXd &f_cmd, const Eigen::MatrixXd &RNEA);
  void update_PQ();
  int call_solver();
  int retrieve_result(const Eigen::MatrixXd &f_cmd);
  int run(const Eigen::MatrixXd &M, const Eigen::MatrixXd &Jc, const Eigen::MatrixXd &f_cmd, const Eigen::MatrixXd &RNEA, const Eigen::MatrixXd &k_contact);

  // Getters
  Eigen::MatrixXd get_f_res();
  Eigen::MatrixXd get_ddq_res();
  Eigen::MatrixXd get_H();

  // Utils
  void my_print_csc_matrix(csc *M, const char *name);
  void save_csc_matrix(csc *M, std::string filename);
  void save_dns_matrix(double *M, int size, std::string filename);

};

#endif  // QPWBC_H_INCLUDED

max_stars_repo_name: FannyRis/quadruped-reactive-walking

max_issues_repo_name: FannyRis/quadruped-reactive-walking

max_forks_repo_name: FannyRis/quadruped-reactive-walking


text:
/*******************************************************************************
 * Copyright (c) 2014, 2015  IBM Corporation and others
 *
 * 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 <Eigen/SparseCore>
#include <boost/bimap.hpp>
#include "ImageHolder.hpp"
#include "LocException.hpp"
#include <opencv2/flann/flann.hpp>
#include <opencv2/opencv.hpp>

namespace loc{

    double ImageHolder::Point::distance(const Point& left, const Point& right){
        double x1 = left.x;
        double y1 = left.y;
        double x2 = right.x;
        double y2 = right.y;
        double sq = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
        double dist = std::sqrt(sq);
        return dist;
    }

    ImageHolderMode ImageHolder::mode_ = light;
    bool ImageHolder::precomputesIndex = false;

    Color::Color(uint8_t r, uint8_t g, uint8_t b){
        r_ = r;
        g_ = g;
        b_ = b;
    }

    static const std::vector<Color> colorList{
        color::white,
        color::black,
        color::red,
        color::lime,
        color::blue,
        color::yellow,
        color::green

        /*
        color::olive,
        color::fuchsia,
        color::silver,
        color::aqua,
        color::gray,
        color::purple,
        color::navy,
        color::teal,
        color::maroon
        */
    };

    static const std::vector<Color> colorsToIndices{
        color::red,
        color::lime,
        color::blue,
        color::yellow,
        color::green
    };

    bool Color::equals(const Color& c)const{
        if( this->b_ == c.b_
           && this->g_ == c.g_
           && this->r_ == c.r_
           ){
            return true;
        }else{
            return false;
        }
    }

    bool Color::operator==(const Color& right) const{
        return this->equals(right);
    }

    int Color::rgbcode() const{
        int t = 65536*this->r_ + 256*this->g_ + this->b_;
        return t;
    }

    bool Color::operator<(const Color& right) const{
        return this->rgbcode() < right.rgbcode();
    }

    bool ImageHolder::checkValid(int y, int x) const
    {
        if(0<=y && y<rows() && 0<=x && x<cols()){
            return true;
        }else{
            return false;
        }
    }

    class IndexWrapper: public cv::flann::Index{
    public:
        IndexWrapper(const IndexWrapper& idx) : Index(idx){};
        IndexWrapper(): Index(){}
        IndexWrapper(cv::InputArray data,
                     const cv::flann::IndexParams& params,
                     cvflann::flann_distance_t distType):
                    Index(data, params, distType){}
        ~IndexWrapper(){};
    };

    class ImageHolder::Impl{
    protected:
        std::map<Color, ImageHolder::Points> mColorPointsMap;

        std::map<Color, cv::Mat> mColorDataMap;
        mutable std::mutex mtx_;
        mutable std::map<Color, std::shared_ptr<IndexWrapper>> mColorIndexMap;

    public:
        virtual ~Impl() = default;
        virtual int rows() const = 0;
        virtual int cols() const = 0;
        virtual Color get(int y, int x) const = 0;
        virtual std::vector<Point> getPoints(const Color& c) const = 0;

        virtual void setUpIndices(){
            for(const Color& c: colorsToIndices){
                this->setUpIndexForColor(c);
            }
        }

        virtual void setUpIndexForColor(const Color& c){
            std::lock_guard<std::mutex> lock(mtx_);
            if(mColorPointsMap.count(c)==0){
                auto points = getPoints(c);
                int n = static_cast<int>(points.size());
                mColorPointsMap[c] = points;
                if(n>0){
                    cv::Mat data = cv::Mat::zeros(n, 2, CV_32FC1);
                    for(int j=0; j<n; j++){
                        data.at<float>(j,0) = points.at(j).x;
                        data.at<float>(j,1) = points.at(j).y;
                    }
                    mColorDataMap[c] = data;
                    if(ImageHolder::precomputesIndex){
                        mColorIndexMap[c] = std::make_shared<IndexWrapper>(mColorDataMap[c], cv::flann::KDTreeIndexParams(), cvflann::FLANN_DIST_EUCLIDEAN);
                    }
                }
            }
        }

        virtual Points findClosestPoints(const Color& c, const ImageHolder::Point& p, int k = 1) const{

            std::lock_guard<std::mutex> lock(mtx_);

            if(mColorPointsMap.count(c)==0){
                LocException ex("Index is not set for the input color");
                BOOST_THROW_EXCEPTION(ex);
            }

            const Points& points = mColorPointsMap.at(c);
            if(points.size()==0){
                return Points(0);
            }

            cv::Mat query = (cv::Mat_<float>(1,2) << p.x , p.y);
            std::vector<int> indices;
            std::vector<float> dists;

            {
                if(ImageHolder::precomputesIndex){
                    if(mColorIndexMap.count(c)==0){
                        cv::Mat data = mColorDataMap.at(c);
                        mColorIndexMap[c] = std::make_shared<IndexWrapper>(data, cv::flann::KDTreeIndexParams(), cvflann::FLANN_DIST_EUCLIDEAN);
                    }else{
                        mColorIndexMap.at(c)->knnSearch(query, indices, dists, k);
                    }
                }else{
                    cv::Mat data = mColorDataMap.at(c);
                    cv::flann::Index idx(data, cv::flann::KDTreeIndexParams(), cvflann::FLANN_DIST_EUCLIDEAN);
                    idx.knnSearch(query, indices, dists, k);
                }
            }

            Points psRet(k);
            for(int i=0; i<k; i++){
                int index = indices.at(0);
                Point pret = points.at(index);
                psRet[i] = pret;
            }
            return psRet;
        }
    };

    class ImageHolder::ImplHeavy : public ImageHolder::Impl{
        std::string name_;
        cv::Mat mat_;

    public:
        ImplHeavy(){}
        ImplHeavy(const std::string& filepath, const std::string& name){
            name_ = name;
            mat_ = cv::imread(filepath);
            if(mat_.empty()){
                LocException ex("Failed to read the image file at " + filepath);
                BOOST_THROW_EXCEPTION(ex);
            }

            this->setUpIndices();
        }
        ~ImplHeavy() = default;

        int rows() const{
            return mat_.rows;
        }
        int cols() const{
            return mat_.rows;
        }
        Color get(int y, int x) const{
            cv::Vec3b vec = mat_.at<cv::Vec3b>(y, x);
            uint8_t b = vec[0];
            uint8_t g = vec[1];
            uint8_t r = vec[2];
            Color color(r,g,b);
            return color;
        }

        std::vector<Point> getPoints(const Color& c) const{
            cv::Mat binary;
            cv::inRange(mat_, cv::Scalar(c.b_, c.g_, c.r_), cv::Scalar(c.b_, c.g_, c.r_), binary);
            cv::Mat idx;
            cv::findNonZero(binary, idx);
            std::vector<Point> points;
            for(int i=0; i<idx.total(); i++){
                Point p;
                p.x = idx.at<cv::Point>(i).x;
                p.y = idx.at<cv::Point>(i).y;
                points.push_back(p);
            }
            return points;
        }
    };

    class ImageHolder::ImplLight : public ImageHolder::Impl{
        std::string name_;
        Eigen::SparseMatrix<uint8_t> mat_;
        boost::bimap<Color, uint8_t> colorIntBM;
    public:
        ImplLight(){
            using bm_type = boost::bimap<Color, uint8_t>;
            for(int i=0; i<colorList.size(); i++){
                const Color& c = colorList.at(i);
                colorIntBM.insert( bm_type::value_type(c, i));
            }
        }

        ImplLight(const std::string& filepath, const std::string& name) : ImplLight(){

            typedef Eigen::Triplet<uint8_t> Triplet;

            name_ = name;
            int rows, cols;
            std::vector<Triplet> tripletList;
            {
                cv::Mat image = cv::imread(filepath);
                cols = image.cols;
                rows = image.rows;
                for(int y=0; y<image.rows; y++){
                    for(int x=0; x<image.cols; x++){
                        cv::Vec3b vec = image.at<cv::Vec3b>(y, x);
                        int b = vec[0];
                        int g = vec[1];
                        int r = vec[2];
                        Color color(r,g,b);
                        uint8_t code = colorToUint8(color);
                        if(code!=0){
                            tripletList.push_back(Triplet(y,x,code));
                        }
                    }
                }
                mat_ = Eigen::SparseMatrix<uint8_t>(rows, cols);
                image.release();
            }

            mat_.setFromTriplets(tripletList.begin(), tripletList.end());

            this->setUpIndices();
        }
        ~ImplLight() = default;

        uint8_t colorToUint8(const Color& color) const{
            for(int i=0; i<colorList.size(); i++){
                const Color& c = colorList.at(i);
                if(color.equals(c)){
                    return i;
                }
            }
            return 0;
        }

        Color uint8ToColor(uint8_t i) const{
            if(i<colorList.size()){
                return colorList.at(i);
            }else{
                return colorList.at(0);
            }
        }

        uint8_t colorToUint8BM(const Color& color) const{
            if(colorIntBM.left.count(color) != 0){
                return colorIntBM.left.at(color);
            }else{
                return colorIntBM.left.at(color::white);
            }
        }

        Color uint8ToColorBM(uint8_t i) const{
            if(colorIntBM.right.count(i) != 0){
                return colorIntBM.right.at(0);
            }else{
                return colorIntBM.right.at(i);
            }
        }

        int rows() const{
            return mat_.rows();
        }
        int cols() const{
            return mat_.cols();
        }

        Color get(int y, int x) const{
            uint8_t code = mat_.coeff(y,x);
            Color color = uint8ToColor(code);
            return color;
        }

        std::vector<Point> getPoints(const Color& c) const{
            Points points;
            uint8_t code_q = colorToUint8(c);
            for(int k=0; k<mat_.outerSize(); k++){
                auto iter = Eigen::SparseMatrix<uint8_t>::InnerIterator(mat_, k);
                for(; iter; ++iter){
                    uint8_t code = iter.value();
                    if(code == code_q){
                        Point p;
                        p.x = iter.col();
                        p.y = iter.row();
                        points.push_back(p);
                    }
                }
            }
            return points;
        }
    };

    ImageHolder::ImageHolder(){
        if(mode_ == light){
            impl.reset(new ImplLight());
        }else if (mode_ == heavy){
            impl.reset(new ImplHeavy());
        }else{
            BOOST_THROW_EXCEPTION(LocException("Unknown ImageHolderMode."));
        }
    }

    ImageHolder::ImageHolder(const std::string& filepath, const std::string& name){
        if(mode_ == light){
            std::cout << "ImageHolder::ImplLight is instantiated." << std::endl;
            impl.reset(new ImplLight(filepath, name));
        }else if (mode_ == heavy){
            std::cout << "ImageHolder::ImplHeavy is instantiated." << std::endl;
            impl.reset(new ImplHeavy(filepath, name));
        }else{
            BOOST_THROW_EXCEPTION(LocException("Unknown ImageHolderMode."));
        }
    }

    ImageHolder::~ImageHolder(){}

    void ImageHolder::setMode(ImageHolderMode mode){
        mode_ = mode;
    }

    int ImageHolder::rows() const{
        return impl->rows();
    }

    int ImageHolder::cols() const{
        return impl->cols();
    }

    Color ImageHolder::get(int y, int x) const{
        return impl->get(y, x);
    }

    void ImageHolder::setUpIndexForColor(const loc::Color &c){
        impl->setUpIndexForColor(c);
    }

    std::vector<ImageHolder::Point> ImageHolder::getPoints(const Color& c) const{
        return impl->getPoints(c);
    }

    ImageHolder::Points ImageHolder::findClosestPoints(const Color& c, const ImageHolder::Point& p, int k) const{
        return impl->findClosestPoints(c, p, k);
    }

    void ImageHolder::setPrecomputesIndex(bool precomputesIdx){
        ImageHolder::precomputesIndex = precomputesIdx;
    }
}

max_stars_repo_name: harsh-agarwal/blelocpp

max_issues_repo_name: harsh-agarwal/blelocpp

max_forks_repo_name: harsh-agarwal/blelocpp


text:
#pragma once

#include <polyfem/Common.hpp>
#include <polyfem/ElasticityUtils.hpp>

#include <polyfem/ElementAssemblyValues.hpp>
#include <polyfem/ElementBases.hpp>

#include <polyfem/AutodiffTypes.hpp>

#include <Eigen/Dense>
#include <functional>

//local assembler for incompressible model, pressure is separate (see Stokes)
namespace polyfem
{

	//displacement assembler
	class IncompressibleLinearElasticityDispacement
	{
	public:
		// res is R^{dim²}
		Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1>
		assemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const;

		Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>
		compute_rhs(const AutodiffHessianPt &pt) const;

		void set_size(const int size);
		inline int size() const { return size_; }

		void set_parameters(const json &params);
		void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus);

		void compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const;
		void compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const;

	private:
		int size_ = -1;

		LameParameters params_;

		void assign_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, const int all_size, Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const;
	};

	//mixed, displacement and pressure
	class IncompressibleLinearElasticityMixed
	{
	public:
		// res is R^{dim}
		Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>
		assemble(const ElementAssemblyValues &psi_vals, const ElementAssemblyValues &phi_vals, const int i, const int j, const QuadratureVector &da) const;

		Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>
		compute_rhs(const AutodiffHessianPt &pt) const;

		void set_size(const int size);

		inline int rows() const { return size_; }
		inline int cols() const { return 1; }

		void set_parameters(const json &params);
		void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus);

	private:
		int size_ = -1;
	};

	//pressure only part
	class IncompressibleLinearElasticityPressure
	{
	public:
		// res is R^{1}
		Eigen::Matrix<double, 1, 1>
		assemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const;

		Eigen::Matrix<double, 1, 1>
		compute_rhs(const AutodiffHessianPt &pt) const
		{
			assert(false);
			return Eigen::Matrix<double, 1, 1>::Zero(1, 1);
		}

		inline int size() const { return 1; }

		void set_parameters(const json &params);
		void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus);

	private:
		int size_ = -1;
		LameParameters params_;
	};
} // namespace polyfem

max_stars_repo_name: danielepanozzo/polyfem

max_issues_repo_name: danielepanozzo/polyfem

max_forks_repo_name: danielepanozzo/polyfem


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test

// Copyright (c) 2015-2021, Oracle and/or its affiliates.
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE test_promote_integral
#endif

#include <climits>
#include <cstddef>
#include <algorithm>
#include <limits>
#include <iostream>
#include <string>
#include <sstream>

#include <boost/test/included/unit_test.hpp>

#include <boost/config.hpp>

#include <geometry_test_common.hpp>

#include <boost/geometry/util/condition.hpp>
#include <boost/geometry/util/promote_integral.hpp>

#if !defined(BOOST_GEOMETRY_NO_MULTIPRECISION_INTEGER)
#include <boost/multiprecision/cpp_int.hpp>
#endif

#if defined(BOOST_GEOMETRY_TEST_DEBUG)
#if defined(BOOST_HAS_INT128) && defined(BOOST_GEOMETRY_ENABLE_INT128)
void print_uint128_t(std::ostream& os, boost::uint128_type i)
{
    if (i == 0)
    {
        os << "0";
        return;
    }

    std::stringstream stream;
    while (i > 0)
    {
        stream << static_cast<int>(i % 10);
        i /= 10;
    }
    std::string str = stream.str();
    std::reverse(str.begin(), str.end());
    os << str;
}

std::ostream& operator<<(std::ostream& os, boost::int128_type i)
{
    if (i < 0)
    {
        os << "-";
        print_uint128_t(os, static_cast<boost::uint128_type>(-i));
    }
    else
    {
        print_uint128_t(os, static_cast<boost::uint128_type>(i));
    }
    return os;
}

std::ostream& operator<<(std::ostream& os, boost::uint128_type i)
{
    print_uint128_t(os, i);
    return os;
}
#endif // BOOST_HAS_INT128 && BOOST_GEOMETRY_ENABLE_INT128
#endif // BOOST_GEOMETRY_TEST_DEBUG

namespace bg = boost::geometry;

template
<
    typename T,
    bool Signed = std::is_fundamental<T>::value
    && ! std::is_unsigned<T>::value
>
struct absolute_value
{
    static inline T apply(T const& t)
    {
        return t < 0 ? -t : t;
    }
};

template <typename T>
struct absolute_value<T, false>
{
    static inline T apply(T const& t)
    {
        return t;
    }
};

template
<
    typename Integral,
    typename Promoted,
    bool Signed = ! std::is_unsigned<Promoted>::value
>
struct test_max_values
{
    static inline void apply()
    {
        Promoted min_value = (std::numeric_limits<Integral>::min)();
        min_value *= min_value;
        BOOST_CHECK(absolute_value<Promoted>::apply(min_value) == min_value);
        Promoted max_value = (std::numeric_limits<Integral>::max)();
        max_value *= max_value;
        BOOST_CHECK(absolute_value<Promoted>::apply(max_value) == max_value);

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "integral min_value^2: " << min_value << std::endl;
        std::cout << "promoted max_value:   "
                  << (std::numeric_limits<Promoted>::max)() << std::endl;
#endif
    }
};

template <typename Integral, typename Promoted>
struct test_max_values<Integral, Promoted, false>
{
    static inline void apply()
    {
        Promoted max_value = (std::numeric_limits<Integral>::max)();
        Promoted max_value_sqr = max_value * max_value;
        BOOST_CHECK(max_value_sqr < (std::numeric_limits<Promoted>::max)()
                    &&
                    max_value_sqr > max_value);

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "integral max_value^2: " << max_value_sqr << std::endl;
        std::cout << "promoted max_value:   "
                  << (std::numeric_limits<Promoted>::max)() << std::endl;
#endif
    }
};

// helper function that returns the bit size of a type
template
<
    typename T,
    bool IsFundamental = std::is_fundamental<T>::value
>
struct bit_size_impl : std::integral_constant<std::size_t, 0>
{};

template <typename T>
struct bit_size_impl<T, true> : bg::detail::promote_integral::bit_size<T>::type
{};

#if !defined(BOOST_GEOMETRY_NO_MULTIPRECISION_INTEGER)
template
<
    typename Backend,
    boost::multiprecision::expression_template_option ExpressionTemplates
>
struct bit_size_impl
    <
        boost::multiprecision::number<Backend, ExpressionTemplates>,
        false
    > : bg::detail::promote_integral::bit_size
        <
            boost::multiprecision::number<Backend, ExpressionTemplates>
        >
{};
#endif

template <typename T>
std::size_t bit_size()
{
    return bit_size_impl<T>::type::value;
}

template <bool PromoteUnsignedToUnsigned>
struct test_promote_integral
{
    template <typename Type, typename ExpectedPromotedType>
    static inline void apply(std::string const& case_id)
    {
        typedef typename bg::promote_integral
            <
                Type, PromoteUnsignedToUnsigned
            >::type promoted_integral_type;

        bool const same_types = std::is_same
            <
                promoted_integral_type, ExpectedPromotedType
            >::value;

        BOOST_CHECK_MESSAGE(same_types,
                            "case ID: " << case_id
                            << "input type: " << typeid(Type).name()
                            << "; detected: "
                            << typeid(promoted_integral_type).name()
                            << "; expected: "
                            << typeid(ExpectedPromotedType).name());

        if (BOOST_GEOMETRY_CONDITION((! std::is_same
                <
                    Type, promoted_integral_type
                >::value)))
        {
            test_max_values<Type, promoted_integral_type>::apply();
        }

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "case ID: " << case_id << std::endl
                  << "type : " << typeid(Type).name()
                  << ", sizeof (bits): " << bit_size<Type>()
                  << ", min value: "
                  << (std::numeric_limits<Type>::min)()
                  << ", max value: "
                  << (std::numeric_limits<Type>::max)()
                  << std::endl;
        std::cout << "detected promoted type : "
                  << typeid(promoted_integral_type).name()
                  << ", sizeof (bits): " << bit_size<promoted_integral_type>()
                  << ", min value: "
                  << (std::numeric_limits<promoted_integral_type>::min)()
                  << ", max value: "
                  << (std::numeric_limits<promoted_integral_type>::max)()
                  << std::endl;
        std::cout << "expected promoted type : "
                  << typeid(ExpectedPromotedType).name()
                  << ", sizeof (bits): " << bit_size<ExpectedPromotedType>()
                  << ", min value: "
                  << (std::numeric_limits<ExpectedPromotedType>::min)()
                  << ", max value: "
                  << (std::numeric_limits<ExpectedPromotedType>::max)()
                  << std::endl;
        std::cout << std::endl;
#endif
    }
};

template
<
    typename T,
    bool PromoteUnsignedToUnsigned = false,
    bool IsSigned = ! std::is_unsigned<T>::value
>
struct test_promotion
{
    static inline void apply(std::string case_id)
    {
#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "*** "
                  << (IsSigned ? "signed" : "unsigned")
                  << " -> signed ***" << std::endl;
#endif

        typedef test_promote_integral<PromoteUnsignedToUnsigned> tester;

        case_id += (PromoteUnsignedToUnsigned ? "-t" : "-f");

        std::size_t min_size = 2 * bit_size<T>() - 1;
        if (BOOST_GEOMETRY_CONDITION(! IsSigned))
        {
            min_size += 2;
        }

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "min size: " << min_size << std::endl;
#endif

        if (bit_size<short>() >= min_size)
        {
            tester::template apply<T, short>(case_id);
        }
        else if (bit_size<int>() >= min_size)
        {
            tester::template apply<T, int>(case_id);
        }
        else if (bit_size<long>() >= min_size)
        {
            tester::template apply<T, long>(case_id);
        }
        else if (bit_size<long long>() >= min_size)
        {
            tester::template apply<T, long long>(case_id);
        }
#if defined(BOOST_HAS_INT128) && defined(BOOST_GEOMETRY_ENABLE_INT128)
        else if (bit_size<boost::int128_type>() >= min_size)
        {
            tester::template apply<T, boost::int128_type>(case_id);
        }
#endif
        else
        {
#if !defined(BOOST_GEOMETRY_NO_MULTIPRECISION_INTEGER)
            namespace bm = boost::multiprecision;
            typedef bm::number
                <
                    bm::cpp_int_backend
                    <
                        2 * CHAR_BIT * sizeof(T) + (IsSigned ? -1 : 1),
                        2 * CHAR_BIT * sizeof(T) + (IsSigned ? -1 : 1),
                        bm::signed_magnitude,
                        bm::unchecked,
                        void
                    >
                > multiprecision_integer_type;

            tester::template apply<T, multiprecision_integer_type>(case_id);
#else
            tester::template apply<T, T>(case_id);
#endif
        }
    }
};

template <typename T>
struct test_promotion<T, true, false>
{
    static inline void apply(std::string case_id)
    {
#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "*** unsigned -> unsigned ***" << std::endl;
#endif
        case_id += "-t";

        typedef test_promote_integral<true> tester;

        std::size_t min_size = 2 * bit_size<T>();

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "min size: " << min_size << std::endl;
#endif

        if (bit_size<unsigned short>() >= min_size)
        {
            tester::apply<T, unsigned short>(case_id);
        }
        else if (bit_size<unsigned int>() >= min_size)
        {
            tester::apply<T, unsigned int>(case_id);
        }
        else if (bit_size<unsigned long>() >= min_size)
        {
            tester::apply<T, unsigned long>(case_id);
        }
        else if (bit_size<std::size_t>() >= min_size)
        {
            tester::apply<T, std::size_t>(case_id);
        }
        else if (bit_size<unsigned long long>() >= min_size)
        {
            tester::template apply<T, unsigned long long>(case_id);
        }
#if defined(BOOST_HAS_INT128) && defined(BOOST_GEOMETRY_ENABLE_INT128)
        else if (bit_size<boost::uint128_type>() >= min_size)
        {
            tester::template apply<T, boost::uint128_type>(case_id);
        }
#endif
        else
        {
#if !defined(BOOST_GEOMETRY_NO_MULTIPRECISION_INTEGER)
            namespace bm = boost::multiprecision;
            typedef bm::number
                <
                    bm::cpp_int_backend
                    <
                        2 * CHAR_BIT * sizeof(T),
                        2 * CHAR_BIT * sizeof(T),
                        bm::unsigned_magnitude,
                        bm::unchecked,
                        void
                    >
                > multiprecision_integer_type;

            tester::apply<T, multiprecision_integer_type>(case_id);
#else
            tester::apply<T, T>(case_id);
#endif
        }
    }
};

BOOST_AUTO_TEST_CASE( test_char )
{
    test_promotion<char>::apply("char");
    test_promotion<char, true>::apply("char");
    test_promotion<signed char>::apply("schar");
    test_promotion<signed char, true>::apply("schar");
    test_promotion<unsigned char>::apply("uchar");
    test_promotion<unsigned char, true>::apply("uchar");
}

BOOST_AUTO_TEST_CASE( test_short )
{
    test_promotion<short>::apply("short");
    test_promotion<short, true>::apply("short");
    test_promotion<unsigned short>::apply("ushort");
    test_promotion<unsigned short, true>::apply("ushort");
}

BOOST_AUTO_TEST_CASE( test_int )
{
    test_promotion<int>::apply("int");
    test_promotion<int, true>::apply("int");
    test_promotion<unsigned int>::apply("uint");
    test_promotion<unsigned int, true>::apply("uint");
}

BOOST_AUTO_TEST_CASE( test_long )
{
    test_promotion<long>::apply("long");
    test_promotion<long, true>::apply("long");
    test_promotion<unsigned long>::apply("ulong");
    test_promotion<unsigned long, true>::apply("ulong");
}

BOOST_AUTO_TEST_CASE( test_std_size_t )
{
    test_promotion<std::size_t>::apply("size_t");
    test_promotion<std::size_t, true>::apply("size_t");
}

BOOST_AUTO_TEST_CASE( test_long_long )
{
    test_promotion<long long>::apply("long long");
    test_promotion<long long, true>::apply("long long");
    test_promotion<unsigned long long>::apply("ulong long");
    test_promotion<unsigned long long, true>::apply("ulong long");
}

#if defined(BOOST_HAS_INT128) && defined(BOOST_GEOMETRY_ENABLE_INT128)
BOOST_AUTO_TEST_CASE( test_int128 )
{
    test_promotion<boost::int128_type>::apply("int128_t");
    test_promotion<boost::int128_type, true>::apply("int128_t");
    test_promotion<boost::uint128_type>::apply("uint128_t");
    test_promotion<boost::uint128_type, true>::apply("uint128_t");
}
#endif

#if !defined(BOOST_GEOMETRY_NO_MULTIPRECISION_INTEGER)
BOOST_AUTO_TEST_CASE( test_user_types )
{
    namespace bm = boost::multiprecision;
    typedef bm::number
        <
            bm::cpp_int_backend
                <
                    17,
                    17,
                    bm::signed_magnitude,
                    bm::unchecked,
                    void
                >
        > user_signed_type1;

    typedef bm::number
        <
            bm::cpp_int_backend
                <
                    17,
                    17,
                    bm::unsigned_magnitude,
                    bm::unchecked,
                    void
                >
        > user_unsigned_type1;

    typedef bm::number
        <
            bm::cpp_int_backend
                <
                    500,
                    500,
                    bm::signed_magnitude,
                    bm::unchecked,
                    void
                >
        > user_signed_type2;

    typedef bm::number
        <
            bm::cpp_int_backend
                <
                    500,
                    500,
                    bm::unsigned_magnitude,
                    bm::unchecked,
                    void
                >
        > user_unsigned_type2;

    // for user defined number types we do not do any promotion
    typedef test_promote_integral<true> tester1;
    typedef test_promote_integral<false> tester2;
    tester1::apply<user_signed_type1, user_signed_type1>("u1s");
    tester1::apply<user_signed_type2, user_signed_type2>("u2s");
    tester1::apply<user_unsigned_type1, user_unsigned_type1>("u1u");
    tester1::apply<user_unsigned_type2, user_unsigned_type2>("u2u");

    tester2::apply<user_signed_type1, user_signed_type1>("u1s");
    tester2::apply<user_signed_type2, user_signed_type2>("u2s");
    tester2::apply<user_unsigned_type1, user_unsigned_type1>("u1u");
    tester2::apply<user_unsigned_type2, user_unsigned_type2>("u1u");
}
#endif

BOOST_AUTO_TEST_CASE( test_floating_point )
{
    typedef test_promote_integral<true> tester1;
    typedef test_promote_integral<false> tester2;

    // for floating-point types we do not do any promotion
    tester1::apply<float, float>("fp-f");
    tester1::apply<double, double>("fp-d");
    tester1::apply<long double, long double>("fp-ld");

    tester2::apply<float, float>("fp-f");
    tester2::apply<double, double>("fp-d");
    tester2::apply<long double, long double>("fp-ld");
}


text:
//
// io_threads.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Whale Mo (ncwhale at gmail dot com)
//

#ifndef ASIO_FIBER_IO_THREADS
#define ASIO_FIBER_IO_THREADS

#include <boost/asio.hpp>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>

namespace asio_fiber {

typedef std::shared_ptr<boost::asio::io_context> context_ptr;
typedef boost::asio::executor_work_guard<boost::asio::io_context::executor_type> context_work;
typedef std::unique_ptr<context_work> fake_work_ptr;

class ContextThreads {
 public:
  ContextThreads(context_ptr ctx_);

  void start(std::size_t);
  void stop();

 private:
  context_ptr ctx;
  // A fake work will keep io_context run.
  fake_work_ptr fake_work;
  std::vector<std::thread> threads;
};

}  // namespace asio_fiber

#endif  // ASIO_FIBER_IO_THREADS


text: #include <boost/lockfree/stack.hpp>


text:
/**
 * \file test_parameters_parser.C
 * \author Justin Too <too1@llnl.gov>
 *
 * TODO: refactor to accept command line arguments that specify
 *       parameters expectations.
 */

#include <iostream>
#include <map>

#include <boost/foreach.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/assign.hpp>

#include "rose.h"
#include "compass2/compass.h"

void test_basic_indexing (Compass::Parameters parameters);
void test_regex_indexing (Compass::Parameters parameters);

int
main(int argc, char** argv)
  {
    SgProject* sageProject = frontend (argc, argv);

    Compass::Xml::ParametersParser parser;
    Compass::Parameters parameters = parser.parse_parameters ();

    test_basic_indexing (parameters);
    test_regex_indexing (parameters);

    return 0;
  }

void test_basic_indexing(Compass::Parameters a_parameters)
  {
    static const char* param_name = "general::RuleSelection";
    static const char* expected_value = "/home/too1/local/workspace/rose/compass2/build/projects/compass2/src/compassSupport/RULE_SELECTION.in";

    Compass::ParameterValues parameters = a_parameters[param_name];
    ROSE_ASSERT (parameters.size () == 1);

    Compass::ParameterValues::iterator it;
    for (it = parameters.begin (); it != parameters.end (); ++it)
    {
        std::string value = *it;
        std::cout << value << std::endl;
        ROSE_ASSERT (value == expected_value);
    }
  }

void test_regex_indexing (Compass::Parameters a_parameters)
  {
    static const boost::regex expression("allowed.*::");

    typedef std::map<std::string, std::string> ExpectedValuesMap;
    static const ExpectedValuesMap expected_values =
        boost::assign::map_list_of
            ("allowedFunctions::boost", "join")
            ("allowedFunctions::std", "push")
            ("allowedVariableNames::variable1", "foo,bar")
            ("allowedVariableNames::variable2", "xyz");

    Compass::ParametersMap parameters  = a_parameters[expression];
    ROSE_ASSERT (parameters.size() == 4);

    BOOST_FOREACH (const Compass::ParametersMap::value_type& pair, parameters)
    {
        std::string param_name = pair.first;
        Compass::ParameterValues values = pair.second;
        std::string values_str = boost::algorithm::join(values, ",");
        std::cout << param_name << "=" << values_str << std::endl;

        ExpectedValuesMap::const_iterator f = expected_values.find (param_name);
        ROSE_ASSERT (f != expected_values.end ());
        ROSE_ASSERT (f->first == param_name);
        ROSE_ASSERT (f->second == values_str);
    }
  }


text:
// Copyright © 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors.
#include <cassert>
#include <boost/cstdint.hpp>
#include <boost/integer/static_log2.hpp>

void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);

class Tiles;

template<int Ntiles> class PackedTiles {
	friend class Tiles;

	enum {
		Nbits = boost::static_log2<Ntiles>::value,
		Nbytes = (int) ((Nbits / 8.0) * Ntiles),
	};

	unsigned char bytes[Nbytes];

public:

	void pack(Tiles::Tile ts[]) {
		fatal("Tiles::pack is unimplemented");
	}

	Tiles::Pos unpack(Tiles::Tile ts[]) {
		fatal("Tiles::unpack is unimplemented");
		return 0;
	}

	Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *h) {
		*h = 0;
		fatal("Tiles::unpack_md is unimplemented");
		return 0;
	}

	unsigned long hash(const void*) {
		return hashbytes(bytes, sizeof(bytes));
	}

	bool eq(const void*, PackedTiles &o) const {
		return memcmp(bytes, o.bytes, sizeof(bytes)) == 0;
	}
};

template<int Ntiles> class PackedTiles64 {
	friend class Tiles;

	boost::uint64_t word;

public:

	void pack(Tiles::Tile ts[]) {
		word = 0;
		for (int i = 0; i < Ntiles; i++)
			word = (word << 4) | ts[i];
	}

	Tiles::Pos unpack(Tiles::Tile ts[]) {
		int b;
		boost::uint64_t w = word;
		for (int i = Ntiles - 1; i >= 0; i--) {
			Tiles::Tile t = w & 0xF;
			w >>= 4;
			ts[i] = t;
			if (t == 0)
				b = i;
		}
		return b;
	}

	Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *hp) {
		int b = -1;
		Tiles::Cost h = 0;
		boost::uint64_t w = word;
		for (int i = Ntiles - 1; i >= 0; i--) {
			Tiles::Tile t = w & 0xF;
			w >>= 4;
			ts[i] = t;
			if (t == 0)
				b = i;
			else
				h += md[t][i];
		}
		*hp = h;
		return b;
	}

	unsigned long hash(const void*) {
		return word;
	}

	bool eq(const void*, const PackedTiles64 &o) const {
		return word == o.word;
	}
};

template<> class PackedTiles<16> : public PackedTiles64<16> {
};

template<> class PackedTiles<9> : public PackedTiles64<9> {
};

max_stars_repo_name: skiesel/search

max_issues_repo_name: skiesel/search

max_forks_repo_name: skiesel/search


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * 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 University Osnabrück 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 University Osnabrück 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.
 */

#ifndef OPTIONS_H_
#define OPTIONS_H_

#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ostream;

namespace ascii_viewer
{

using namespace boost::program_options;

/**
 * @brief A class to parse the program options for the reconstruction
 * executable.
 */
class Options
{
public:

    /**
     * @brief Ctor. Parses the command parameters given to the main
     *     function of the program
     */
    Options(int argc, char** argv);
    virtual ~Options();

    string  inputFile() const
    {
        return (m_variables["inputFile"].as< vector<string> >())[0];
    }

private:

    /// The internally used variable map
    variables_map m_variables;

    /// The internally used option description
    options_description m_descr;

    /// The internally used positional option desription
    positional_options_description m_pdescr;

};

inline ostream& operator<<(ostream& os, const Options& o)
{
    os << "##### ASCII VIEWER settings #####" << endl;
    os << "\t mesh: " << o.inputFile() << endl;

    return os;
}

} // namespace ascii_viewer

#endif

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
#include <boost/circular_buffer.hpp>
#include <boost/units/io.hpp>
#include <numeric>

#include <goby/middleware/marshalling/protobuf.h>
// this space intentionally left blank
#include <goby/zeromq/application/single_thread.h>

#include "config.pb.h"
#include "goby/middleware/frontseat/groups.h"
#include "goby/middleware/protobuf/frontseat.pb.h"
#include "goby/time/convert.h"
#include "goby/time/system_clock.h"
#include "goby3-course/groups.h"
// #include "goby3-course/messages/command_dccl.pb.h"

using goby::glog;
namespace si = boost::units::si;
using ApplicationBase =
    goby::zeromq::SingleThreadApplication<goby3_course::config::MyHelm>;

namespace goby3_course
{
namespace apps
{
class MyHelm : public ApplicationBase
{
  public:
    MyHelm();

  private:
    void publisher();
    void update_leg();
    void send_auv_command();

  private:
    enum class Leg
    {
        EAST,
        SOUTH,
        NORTHWEST,
        RECOVER
    };
    goby::time::SystemClock::time_point leg_start_{goby::time::SystemClock::now()};
    Leg leg_{Leg::EAST};

    goby::middleware::frontseat::protobuf::NodeStatus start_position_;
    bool have_start_position_{false};
    goby::middleware::frontseat::protobuf::NodeStatus latest_position_;

    // closest distance to start
    boost::units::quantity<boost::units::si::length> min_dr_;
    // filter last 10 dr values
    boost::circular_buffer<decltype(min_dr_)> last_dr_{10};
};
} // namespace apps
} // namespace goby3_course

int main(int argc, char* argv[])
{
    return goby::run<goby3_course::apps::MyHelm>(
        goby::middleware::ProtobufConfigurator<goby3_course::config::MyHelm>(argc, argv));
}

goby3_course::apps::MyHelm::MyHelm() : ApplicationBase(1.0 * boost::units::si::hertz) {
  interprocess().subscribe<goby::middleware::frontseat::groups::node_status>(
    [this](const goby::middleware::frontseat::protobuf::NodeStatus& status) {
      latest_position_ = status;
      if (!have_start_position_){
        start_position_ = status;
        have_start_position_ = true;
      }
    });
}

void goby3_course::apps::MyHelm::publisher()
{
    using boost::units::degree::degrees;
    const auto east = 90.0 * degrees;
    const auto south = 180.0 * degrees;
    const auto northwest = -45 * degrees;

    update_leg();

    goby::middleware::frontseat::protobuf::HelmStateReport my_helm_state;
    my_helm_state.set_state(goby::middleware::frontseat::protobuf::HELM_DRIVE);
    glog.is_verbose() && glog << "Publishing Helm_Drive: " << my_helm_state.ShortDebugString() << std::endl;
    interprocess().publish<goby::middleware::frontseat::groups::helm_state>(my_helm_state);

    // generate desired course command
    goby::middleware::frontseat::protobuf::DesiredCourse course;
    course.set_time_with_units(goby::time::SystemClock::now<goby::time::MicroTime>());
    course.set_speed_with_units(cfg().speed_with_units());
    switch (leg_)
    {
        case Leg::EAST: course.set_heading_with_units(east); break;
        case Leg::SOUTH: course.set_heading_with_units(south); break;
        case Leg::NORTHWEST: course.set_heading_with_units(northwest); break;
        case Leg::RECOVER:
            course.set_speed(0);
            course.set_heading(0);
            break;
    }

    interprocess().publish<goby::middleware::frontseat::groups::desired_course>(course);

    // called at frequency passed to SingleThreadApplication (ApplicationBase)
    glog.is_verbose() && glog << "Loop!" << std::endl;
}

void goby3_course::apps::MyHelm::update_leg()
{
    auto now = goby::time::SystemClock::now();
    auto time_on_leg = now - leg_start_;
    glog.is_debug1() &&
        glog << "Time on leg: " << goby::time::convert_duration<goby::time::SITime>(time_on_leg)
             << std::endl;
    switch (leg_)
    {
        case Leg::EAST:
        {
            auto leg_duration = goby::time::convert_duration<goby::time::SystemClock::duration>(
                cfg().east_duration_with_units());
            if (now > leg_start_ + leg_duration)
            {
                leg_start_ = now;
                leg_ = Leg::SOUTH;
                glog.is_verbose() && glog << "Switched to SOUTH leg" << std::endl;
            }
            else
            {
                glog.is_debug1() && glog << "Time left on EAST leg: "
                                         << goby::time::convert_duration<goby::time::SITime>(
                                                leg_duration - time_on_leg)
                                         << std::endl;
            }
        }
        break;
        case Leg::SOUTH:
        {
            auto leg_duration = goby::time::convert_duration<goby::time::SystemClock::duration>(
                cfg().south_duration_with_units());

            if (now > leg_start_ + leg_duration)
            {
                leg_start_ = now;
                leg_ = Leg::NORTHWEST;
                glog.is_verbose() && glog << "Switched to NORTHWEST leg" << std::endl;
            }
            else
            {
                glog.is_debug1() && glog << "Time left on SOUTH leg: "
                                         << goby::time::convert_duration<goby::time::SITime>(
                                                leg_duration - time_on_leg)
                                         << std::endl;
            }
        }
        break;

        case Leg::NORTHWEST:
        {
            // compute range to start
            auto x0 = start_position_.local_fix().x_with_units();
            auto y0 = start_position_.local_fix().y_with_units();
            auto x1 = latest_position_.local_fix().x_with_units();
            auto y1 = latest_position_.local_fix().y_with_units();

            using namespace boost::units;
            auto dr = sqrt((y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0));

            if (last_dr_.empty())
                min_dr_ = dr;
            last_dr_.push_back(dr);

            // wait until buffer is full to start making decisions.
            if (!last_dr_.full())
                return;
            auto dr_avg =
                std::accumulate(last_dr_.begin(), last_dr_.end(), 0.0 * boost::units::si::meters) /
                static_cast<decltype(dr)::value_type>(last_dr_.size());

            if (dr_avg < min_dr_)
            {
                glog.is_debug1() && glog << "Getting closer, dr avg: " << dr_avg << std::endl;
                min_dr_ = dr_avg;
            }
            else
            {
                glog.is_verbose() && glog << "Getting farther away, entering recovery, dr avg: "
                                          << dr_avg << std::endl;
                leg_ = Leg::RECOVER;
                send_auv_command();
            }
        }
        break;

        case Leg::RECOVER:
            break;
    }
}

void goby3_course::apps::MyHelm::send_auv_command()
{
    // goby3_course::dccl::AUVCommand command;
    // command.set_time_with_units(goby::time::SystemClock::now<goby::time::MicroTime>());
    // command.set_desired_state(goby3_course::dccl::AUVCommand::RECOVER);
    // intervehicle().publish<goby3_course::groups::auv_command>(command);
    glog.is_verbose() && glog << "Would send AUV recovery command here";
}