text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

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.
*/

#ifndef FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP

#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "array.hpp"
#include "native_function.hpp"
#include "local_root_scope.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>

namespace flusspferd {

class native_object_base;
class function;
class native_function_base;

#ifndef IN_DOXYGEN
namespace detail {

object create_native_object(object const &proto);
object create_native_enumerable_object(object const &proto);

}
#endif

/**
 * @name Creating values
 * @addtogroup create
 */
//@{
/**
 * Create a simple object.
 *
 * Creates a new object with prototype @p proto. If proto is @c null,
 * @c Object.prototype will be used.
 *
 * @param proto The object to use as prototype.
 * @return The new object.
 */
object create_object(object const &proto = object());

/**
 * Create an array.
 *
 * @return The new array.
 */
array create_array();

/**
 * Create an array with the given contents.
 */
template<typename Range>
array create_array(Range const &r)
{
  typedef typename boost::range_iterator<Range>::type iterator;

  local_root_scope scope;

  array arr = flusspferd::create_array();

  iterator first = boost::begin(r);
  iterator last = boost::end(r);

  for (iterator it = first; it != last; ++it)
     arr.push(*it);

  return arr;
}

#ifndef IN_DOXYGEN

#define FLUSSPFERD_FN_CREATE_NATIVE_OBJECT(z, n_args, d) \
  template< \
    typename T \
    BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
  > \
  typename boost::enable_if< boost::mpl::not_<  \
    typename T::class_info::custom_enumerate >, \
  T& >::type                                    \
  create_native_object(      \
    object proto \
    BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
  ) { \
    if (proto.is_null()) \
      proto = current_context().prototype<T>(); \
    root_object obj(detail::create_native_object(proto)); \
    return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
  } \
  \
  template< \
    typename T \
    BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
  > \
  typename boost::enable_if<                          \
    typename T::class_info::custom_enumerate,         \
  T& >::type                                          \
  create_native_object(                               \
    object proto                                      \
    BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
  ) { \
    if (proto.is_null()) \
      proto = current_context().prototype<T>(); \
    root_object obj(detail::create_native_enumerable_object(proto)); \
    return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
  } \
  /* */

BOOST_PP_REPEAT(
  BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
  FLUSSPFERD_FN_CREATE_NATIVE_OBJECT,
  ~
)

#else

/**
 * Create a new native object of type @p T.
 *
 * @param T The type of the object's class.
 * @param proto The prototype to be used. If @p null, the class' default
 *          prototype will be used.
 * @param ... The parameters to the constructor of @p T.
 * @return The new object.
 */
template<typename T>
T &create_native_object(object const &proto, ...);

#endif
//@}

/**
 * @name Creating functions
 * @addtogroup create_function
 */
//@{

function create_function(
    std::string const &name,
    unsigned n_args,
    std::vector<std::string> argnames,
    flusspferd::string const &body,
    std::string const &file,
    unsigned line);

/**
 * Create a new native function.
 *
 * @p ptr will be deleted by Flusspferd.
 *
 * @param ptr The native function object.
 * @return The new function.
 */
function create_native_function(native_function_base *ptr);

/**
 * Create a new native function as method of an object.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param o The object to add the method to.
 * @param ptr The native function object.
 * @return The new method.
 */
function create_native_function(object const &o, native_function_base *ptr);

#ifndef IN_DOXYGEN

#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \
  template< \
    typename T \
    BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
  > \
  object create_native_functor_function( \
    object const &o \
    BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \
    typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \
  ) { \
    return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \
  } \
  /* */

BOOST_PP_REPEAT(
  BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
  FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,
  ~
)

#else

/**
 * Create a new native function of type @p F as method of an object.
 *
 * @p F must inherit from #native_function_base.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param F The functor type.
 * @param o The object to add the method to.
 * @param ... The parameters to pass to the constructor of @p F.
 * @return The new method.
 */
template<typename F>
object create_native_functor_function(object const &o, ...);

#endif

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fn The functor to call.
 * @param arity The function arity.
 * @return The new function.
 */
inline function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<void (call_context &)> const &fn,
  unsigned arity = 0)
{
  return create_native_functor_function<native_function<void> >(
      o, fn, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return create_native_functor_function<native_function<T,false> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return create_native_functor_function<native_function<T,true> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_function<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_method<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  void (T::*memfnptr)(call_context &),
  unsigned arity = 0)
{
  return create_native_functor_function<native_member_function<void, T> >(
    o, memfnptr, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call (also determines the function
 *                 signature).
 * @return The new function.
 */
template<typename R, typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  R T::*memfnptr)
{
  return create_native_functor_function<native_member_function<R, T> >(
    o, memfnptr, name);
}

//@}

}

#endif

max_stars_repo_name: ngoyal/flusspferd

max_issues_repo_name: ngoyal/flusspferd

max_forks_repo_name: ngoyal/flusspferd


text:
#include <Storages/System/StorageSystemRowPolicies.h>
#include <Access/AccessControlManager.h>
#include <Access/Common/AccessFlags.h>
#include <Access/RowPolicy.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnNullable.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeUUID.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeArray.h>
#include <Interpreters/Context.h>
#include <Parsers/Access/ASTRolesOrUsersSet.h>
#include <base/range.h>
#include <boost/range/algorithm_ext/push_back.hpp>

namespace DB
{
using ConditionTypeInfo = RowPolicy::ConditionTypeInfo;
constexpr auto MAX_CONDITION_TYPE = RowPolicy::MAX_CONDITION_TYPE;

NamesAndTypesList StorageSystemRowPolicies::getNamesAndTypes()
{
    NamesAndTypesList names_and_types{
        {"name", std::make_shared<DataTypeString>()},
        {"short_name", std::make_shared<DataTypeString>()},
        {"database", std::make_shared<DataTypeString>()},
        {"table", std::make_shared<DataTypeString>()},
        {"id", std::make_shared<DataTypeUUID>()},
        {"storage", std::make_shared<DataTypeString>()},
    };

    for (auto type : collections::range(MAX_CONDITION_TYPE))
    {
        const String & column_name = ConditionTypeInfo::get(type).name;
        names_and_types.push_back({column_name, std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())});
    }

    NamesAndTypesList extra_names_and_types{
        {"is_restrictive", std::make_shared<DataTypeUInt8>()},
        {"apply_to_all", std::make_shared<DataTypeUInt8>()},
        {"apply_to_list", std::make_shared<DataTypeArray>(std::make_shared<DataTypeString>())},
        {"apply_to_except", std::make_shared<DataTypeArray>(std::make_shared<DataTypeString>())}
    };

    boost::range::push_back(names_and_types, std::move(extra_names_and_types));
    return names_and_types;
}

void StorageSystemRowPolicies::fillData(MutableColumns & res_columns, ContextPtr context, const SelectQueryInfo &) const
{
    context->checkAccess(AccessType::SHOW_ROW_POLICIES);
    const auto & access_control = context->getAccessControlManager();
    std::vector<UUID> ids = access_control.findAll<RowPolicy>();

    size_t column_index = 0;
    auto & column_name = assert_cast<ColumnString &>(*res_columns[column_index++]);
    auto & column_short_name = assert_cast<ColumnString &>(*res_columns[column_index++]);
    auto & column_database = assert_cast<ColumnString &>(*res_columns[column_index++]);
    auto & column_table = assert_cast<ColumnString &>(*res_columns[column_index++]);
    auto & column_id = assert_cast<ColumnUUID &>(*res_columns[column_index++]).getData();
    auto & column_storage = assert_cast<ColumnString &>(*res_columns[column_index++]);

    ColumnString * column_condition[MAX_CONDITION_TYPE];
    NullMap * column_condition_null_map[MAX_CONDITION_TYPE];
    for (auto condition_type : collections::range(MAX_CONDITION_TYPE))
    {
        column_condition[condition_type] = &assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
        column_condition_null_map[condition_type] = &assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
    }

    auto & column_is_restrictive = assert_cast<ColumnUInt8 &>(*res_columns[column_index++]).getData();
    auto & column_apply_to_all = assert_cast<ColumnUInt8 &>(*res_columns[column_index++]).getData();
    auto & column_apply_to_list = assert_cast<ColumnString &>(assert_cast<ColumnArray &>(*res_columns[column_index]).getData());
    auto & column_apply_to_list_offsets = assert_cast<ColumnArray &>(*res_columns[column_index++]).getOffsets();
    auto & column_apply_to_except = assert_cast<ColumnString &>(assert_cast<ColumnArray &>(*res_columns[column_index]).getData());
    auto & column_apply_to_except_offsets = assert_cast<ColumnArray &>(*res_columns[column_index++]).getOffsets();

    auto add_row = [&](const String & name,
                       const RowPolicy::NameParts & name_parts,
                       const UUID & id,
                       const String & storage_name,
                       const std::array<String, MAX_CONDITION_TYPE> & conditions,
                       bool is_restrictive,
                       const RolesOrUsersSet & apply_to)
    {
        column_name.insertData(name.data(), name.length());
        column_short_name.insertData(name_parts.short_name.data(), name_parts.short_name.length());
        column_database.insertData(name_parts.database.data(), name_parts.database.length());
        column_table.insertData(name_parts.table_name.data(), name_parts.table_name.length());
        column_id.push_back(id.toUnderType());
        column_storage.insertData(storage_name.data(), storage_name.length());

        for (auto condition_type : collections::range(MAX_CONDITION_TYPE))
        {
            const String & condition = conditions[condition_type];
            if (condition.empty())
            {
                column_condition[condition_type]->insertDefault();
                column_condition_null_map[condition_type]->push_back(true);
            }
            else
            {
                column_condition[condition_type]->insertData(condition.data(), condition.length());
                column_condition_null_map[condition_type]->push_back(false);
            }
        }

        column_is_restrictive.push_back(is_restrictive);

        auto apply_to_ast = apply_to.toASTWithNames(access_control);
        column_apply_to_all.push_back(apply_to_ast->all);

        for (const auto & role_name : apply_to_ast->names)
            column_apply_to_list.insertData(role_name.data(), role_name.length());
        column_apply_to_list_offsets.push_back(column_apply_to_list.size());

        for (const auto & role_name : apply_to_ast->except_names)
            column_apply_to_except.insertData(role_name.data(), role_name.length());
        column_apply_to_except_offsets.push_back(column_apply_to_except.size());
    };

    for (const auto & id : ids)
    {
        auto policy = access_control.tryRead<RowPolicy>(id);
        if (!policy)
            continue;
        auto storage = access_control.findStorage(id);
        if (!storage)
            continue;

        add_row(policy->getName(), policy->getNameParts(), id, storage->getStorageName(), policy->conditions, policy->isRestrictive(), policy->to_roles);
    }
}
}

ext: cpp

max_stars_repo_name: mrssss/ClickHouse

max_issues_repo_name: mrssss/ClickHouse

max_forks_repo_name: mrssss/ClickHouse


text:
#include <engine/Eigenmodes.hpp>
#include <engine/Vectormath.hpp>
#include <engine/Manifoldmath.hpp>

#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <SymEigsSolver.h>  // Also includes <MatOp/DenseSymMatProd.h>

#include <fmt/format.h>
#include <fmt/ostream.h>

namespace Engine
{
    namespace Eigenmodes
    {
        using Utility::Log_Level;
        using Utility::Log_Sender;

        void Check_Eigenmode_Parameters(std::shared_ptr<Data::Spin_System> system)
        {
            int nos = system->nos;
            auto& n_modes = system->ema_parameters->n_modes;
            if (n_modes > 2*nos-2)
            {
                n_modes = 2*nos-2;
                system->modes.resize(n_modes);
                system->eigenvalues.resize(n_modes);

                Log(Log_Level::Warning, Log_Sender::EMA, fmt::format("Number of eigenmodes declared in "
                    "EMA Parameters is too large. The number is set to {}", n_modes));
            }
            if (n_modes != system->modes.size())
                system->modes.resize(n_modes);

            // Initial check of selected_mode
            auto& n_mode_follow = system->ema_parameters->n_mode_follow;
            if (n_mode_follow > n_modes-1)
            {
                Log(Log_Level::Warning, Log_Sender::EMA, fmt::format("Eigenmode number {} is not "
                    "available. The largest eigenmode ({}) is used instead", n_mode_follow, n_modes-1));
                n_mode_follow = n_modes-1;
            }
        }

        void Calculate_Eigenmodes(std::shared_ptr<Data::Spin_System> system, int idx_img, int idx_chain)
        {
            int nos = system->nos;

            Check_Eigenmode_Parameters(system);

            auto& n_modes = system->ema_parameters->n_modes;

            // vectorfield mode(nos, Vector3{1, 0, 0});
            vectorfield spins_initial = *system->spins;

            Log( Log_Level::Info, Log_Sender::EMA, fmt::format("Started calculation of {} Eigenmodes ", n_modes ),
                idx_img, idx_chain );

            // Calculate the Eigenmodes
            vectorfield gradient(nos);
            MatrixX hessian(3*nos, 3*nos);

            // The gradient (unprojected)
            system->hamiltonian->Gradient(spins_initial, gradient);
            Vectormath::set_c_a(1, gradient, gradient, system->geometry->mask_unpinned);

            // The Hessian (unprojected)
            system->hamiltonian->Hessian(spins_initial, hessian);

            // Get the eigenspectrum
            MatrixX hessian_constrained = MatrixX::Zero(2*nos, 2*nos);
            MatrixX tangent_basis = MatrixX::Zero(3*nos, 2*nos);
            VectorX eigenvalues;
            MatrixX eigenvectors;
            bool successful = Eigenmodes::Hessian_Partial_Spectrum(system->ema_parameters, spins_initial, gradient, hessian,
                n_modes, tangent_basis, hessian_constrained, eigenvalues, eigenvectors);

            if (successful)
            {
                // get every mode and save it to system->modes
                for (int i=0; i<n_modes; i++)
                {
                    // Extract the minimum mode (transform evec_lowest_2N back to 3N)
                    VectorX evec_3N = tangent_basis * eigenvectors.col(i);

                    // dynamically allocate the system->modes
                    system->modes[i] = std::shared_ptr<vectorfield>(new vectorfield(nos, Vector3{1,0,0}));

                    // Set the modes
                    for (int j=0; j<nos; j++)
                        (*system->modes[i])[j] = {evec_3N[3*j], evec_3N[3*j+1], evec_3N[3*j+2]};

                    // get the eigenvalues
                    system->eigenvalues[i] = eigenvalues(i);
                }

                Log( Log_Level::Info, Log_Sender::All, fmt::format("Finished calculation of {} Eigenmodes ", n_modes ),
                    idx_img, idx_chain );

                int ev_print = std::min(n_modes, 100);
                Log( Log_Level::Info, Log_Sender::EMA, fmt::format("Eigenvalues: {}",
                    eigenvalues.head( ev_print ).transpose() ), idx_img, idx_chain );
            }
            else
            {
                //// TODO: What to do then?
                Log( Log_Level::Warning, Log_Sender::All, "Something went wrong in eigenmode calculation...",
                    idx_img, idx_chain );
            }
        }

        bool Hessian_Full_Spectrum(const std::shared_ptr<Data::Parameters_Method> parameters,
            const vectorfield & spins, const vectorfield & gradient, const MatrixX & hessian,
            MatrixX & tangent_basis, MatrixX & hessian_constrained, VectorX & eigenvalues, MatrixX & eigenvectors)
        {
            int nos = spins.size();

            // Calculate the final Hessian to use for the minimum mode
            // TODO: add option to choose different Hessian calculation
            hessian_constrained = MatrixX::Zero(2*nos, 2*nos);
            tangent_basis       = MatrixX::Zero(3*nos, 2*nos);
            Manifoldmath::hessian_bordered(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_projected(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_weingarten(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_spherical(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_covariant(spins, gradient, hessian, tangent_basis, hessian_constrained);

            // Create and initialize a Eigen solver. Note: the hessian matrix should be symmetric!
            Eigen::SelfAdjointEigenSolver<MatrixX> hessian_spectrum(hessian_constrained);

            // Extract real eigenvalues
            eigenvalues = hessian_spectrum.eigenvalues().real();
            // Retrieve the real eigenvectors
            eigenvectors = hessian_spectrum.eigenvectors().real();

            // Return whether the calculation was successful
            return true;
        }

        bool Hessian_Partial_Spectrum(const std::shared_ptr<Data::Parameters_Method> parameters,
            const vectorfield & spins, const vectorfield & gradient, const MatrixX & hessian, int n_modes,
            MatrixX & tangent_basis, MatrixX & hessian_constrained, VectorX & eigenvalues, MatrixX & eigenvectors)
        {
            int nos = spins.size();

            // Restrict number of calculated modes to [1,2N)
            n_modes = std::max(1, std::min(2*nos-2, n_modes));

            // If we have only one spin, we can only calculate the full spectrum
            if (n_modes == nos)
                return Hessian_Full_Spectrum(parameters, spins, gradient, hessian, tangent_basis, hessian_constrained, eigenvalues, eigenvectors);

            // Calculate the final Hessian to use for the minimum mode
            // TODO: add option to choose different Hessian calculation
            hessian_constrained = MatrixX::Zero(2*nos, 2*nos);
            tangent_basis       = MatrixX::Zero(3*nos, 2*nos);
            Manifoldmath::hessian_bordered(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_projected(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_weingarten(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_spherical(spins, gradient, hessian, tangent_basis, hessian_constrained);
            // Manifoldmath::hessian_covariant(spins, gradient, hessian, tangent_basis, hessian_constrained);

            // Remove degrees of freedom of pinned spins
            #ifdef SPIRIT_ENABLE_PINNING
                for (int i=0; i<nos; ++i)
                {
                    // TODO: pinning is now in Data::Geometry
                    // if (!parameters->pinning->mask_unpinned[i])
                    // {
                    //     // Remove interaction block
                    //     for (int j=0; j<nos; ++j)
                    //     {
                    //         hessian_constrained.block<2,2>(2*i,2*j).setZero();
                    //         hessian_constrained.block<2,2>(2*j,2*i).setZero();
                    //     }
                    //     // Set diagonal matrix entries of pinned spins to a large value
                    //     hessian_constrained.block<2,2>(2*i,2*i).setZero();
                    //     hessian_constrained.block<2,2>(2*i,2*i).diagonal().setConstant(nos*1e5);
                    // }
                }
            #endif // SPIRIT_ENABLE_PINNING

            // Create the Spectra Matrix product operation
            Spectra::DenseSymMatProd<scalar> op(hessian_constrained);
            // Create and initialize a Spectra solver
            Spectra::SymEigsSolver< scalar, Spectra::SMALLEST_ALGE, Spectra::DenseSymMatProd<scalar> > hessian_spectrum(&op, n_modes, 2*nos);
            hessian_spectrum.init();

            // Compute the specified spectrum, sorted by smallest real eigenvalue
            int nconv = hessian_spectrum.compute(1000, 1e-10, int(Spectra::SMALLEST_ALGE));

            // Extract real eigenvalues
            eigenvalues = hessian_spectrum.eigenvalues().real();

            // Retrieve the real eigenvectors
            eigenvectors = hessian_spectrum.eigenvectors().real();

            // Return whether the calculation was successful
            return (hessian_spectrum.info() == Spectra::SUCCESSFUL) && (nconv > 0);
        }
    }
}

max_stars_repo_name: ddkn/spirit

max_issues_repo_name: ddkn/spirit

max_forks_repo_name: ddkn/spirit


text:
#include "modprop/compo/AdditiveWrapper.hpp"
#include "modprop/neural/LinearLayer.hpp"
#include "modprop/neural/FullyConnectedNet.hpp"

#include "modprop/neural/HingeActivation.hpp"
#include "modprop/neural/SigmoidActivation.hpp"
#include "modprop/neural/NullActivation.hpp"
#include "modprop/neural/NetworkTypes.h"

#include "modprop/optim/SquaredLoss.hpp"
#include "modprop/optim/StochasticMeanCost.hpp"
#include "modprop/optim/ParameterL2Cost.hpp"

#include "optim/Optimizers.h"

#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/mersenne_twister.hpp>

#include "modprop/utils/Derivatives.hpp"
#include "modprop/utils/Randomization.hpp"

#include <deque>
#include <cstdlib>
#include <iostream>

using namespace percepto;

// Comment the above and uncomment below to use Rectified Linear Units instead
typedef PerceptronNet TestNet;
// typedef ReLUNet TestNet;

unsigned int inputDim = 1;
unsigned int outputDim = 1;
unsigned int numHiddenLayers = 3;
unsigned int layerWidth = 20;
unsigned int batchSize = 20;

struct Regressor
{
	TerminalSource<VectorType> netInput;
	TestNet net;
	SquaredLoss<VectorType> loss;

	Regressor()
	: net( inputDim, outputDim, numHiddenLayers, layerWidth,
	       SigmoidActivation(), TestNet::OUTPUT_UNRECTIFIED )
	{
		net.SetSource( &netInput );
		loss.SetSource( &net.GetOutputSource() );
	}

	Regressor( const Regressor& other )
	: net( other.net )
	{
		net.SetSource( &netInput );
		loss.SetSource( &net.GetOutputSource() );
	}

	void Foreprop()
	{
		netInput.Foreprop();
	}

	double GetOutput()
	{
		return net.GetOutput()(0);
	}

	void Invalidate()
	{
		netInput.Invalidate();
	}
};

struct RegressionProblem
: public NaturalOptimizationProblem
{
	std::deque<Regressor> regressors;
	StochasticMeanCost<double> losses;
	ParameterL2Cost regularizer;
	AdditiveWrapper<double> objective;

	Parameters::Ptr params;

	RegressionProblem( Parameters::Ptr p,
	                   unsigned int batchSize,
	                   double l2Weight )
	{
		params = p;
		losses.SetBatchSize( batchSize );
		regularizer.SetWeight( l2Weight );
		regularizer.SetParameters( params );
		objective.SetSourceA( &losses );
		objective.SetSourceB( &regularizer );
	}

	virtual bool IsMinimization() const { return true; }

	virtual void Resample()
	{
		losses.Resample();
	}

	virtual double ComputeObjective()
	{
		Invalidate();
		Foreprop();
		return objective.GetOutput();
	}

	virtual VectorType ComputeGradient()
	{
		Invalidate();
		Foreprop();
		Backprop();
		return params->GetDerivs();
	}

	virtual VectorType ComputeNaturalGradient()
	{
		Invalidate();
		Foreprop();
		BackpropNatural();
		return params->GetDerivs();
	}

	virtual VectorType GetParameters() const
	{
		return params->GetParamsVec();
	}

	virtual void SetParameters( const VectorType& p )
	{
		params->SetParamsVec( p );
	}

	void Invalidate()
	{
		for( unsigned int i = 0; i < regressors.size(); i++ )
		{
			regressors[i].Invalidate();
		}
		regularizer.Invalidate();
		params->ResetAccumulators();
	}

	void Foreprop()
	{
		const std::vector<unsigned int>& inds = losses.GetActiveInds();
		BOOST_FOREACH( unsigned int i, inds )
		{
			regressors[i].Foreprop();
		}
		regularizer.Foreprop();
	}

	void ForepropAll()
	{
		for( unsigned int i = 0; i < regressors.size(); i++ )
		{
			regressors[i].Foreprop();
		}
		regularizer.Foreprop();
	}

	void Backprop()
	{
		objective.Backprop( MatrixType::Identity(1,1) );
	}

	void BackpropNatural()
	{
		const std::vector<unsigned int>& inds = losses.GetActiveInds();
		MatrixType dodw = MatrixType::Identity( 1, 1 ) / inds.size();
		BOOST_FOREACH( unsigned int i, inds )
		{
			regressors[i].loss.Backprop( dodw );
		}
	}
};

// The highly nonlinear function we will try to fit
double f( double x )
{
	return 8 * std::cos( x ) + 2.5 * x * sin( x ) + 2.8 * x;
}

// Generate a specified number of random xs and corresponding ys
void generate_data( std::vector<VectorType>& xs,
                    std::vector<VectorType>& ys,
                    unsigned int num_data )
{
	boost::random::mt19937 generator;
	boost::random::random_device rng;
	generator.seed( rng );
	boost::random::uniform_real_distribution<> xDist( -5.0, 5.0 );

	xs.clear();
	ys.clear();
	xs.reserve( num_data );
	ys.reserve( num_data );

	VectorType x(1,1);
	VectorType y(1,1);
	for( unsigned int i = 0; i < num_data; i++ )
	{
		x(0) = xDist( generator );
		y(0) = f( x(0) );
		xs.push_back( x );
		ys.push_back( y );
	}
}

int main( int argc, char** argv )
{
	unsigned int numTrain = 150;
	unsigned int numTest = 200;
	double l2Weight = 1E-3;

	std::vector<VectorType> xTest, yTest, xTrain, yTrain;
	generate_data( xTest, yTest, numTest );
	generate_data( xTrain, yTrain, numTrain );

	std::cout << "Initializing net..." << std::endl;
	std::cout << "Creating linear layers..." << std::endl;

	// // ReLU initialization
	Regressor reg;
	Parameters::Ptr params = reg.net.CreateParameters();

	// Randomize parameters
	VectorType p( params->ParamDim() );
	randomize_vector( p, -0.2, 0.2 );
	params->SetParamsVec( p );
	std::cout << "Initial net: " << std::endl << reg.net << std::endl;

	// Create the loss functions
	std::cout << "Generating losses..." << std::endl;
	RegressionProblem trainProblem( params, batchSize, l2Weight );
	RegressionProblem testProblem( params, batchSize, l2Weight );

	// NOTE If we don't reserve, the vector resizing and moving may
	// invalidate the references. Alternatively we can use a deque
	for( unsigned int i = 0; i < numTrain; i++ )
	{
		trainProblem.regressors.emplace_back( reg );
		trainProblem.regressors[i].netInput.SetOutput( xTrain[i] );
		trainProblem.regressors[i].loss.SetTarget( yTrain[i] );
		trainProblem.losses.AddSource( &trainProblem.regressors[i].loss );
	}

	for( unsigned int i = 0; i < numTest; i++ )
	{
		testProblem.regressors.emplace_back( reg );
		testProblem.regressors[i].netInput.SetOutput( xTest[i] );
		testProblem.regressors[i].loss.SetTarget( yTest[i] );
		testProblem.losses.AddSource( &testProblem.regressors[i].loss );
	}

	ModularOptimizer optimizer;

	// AdamSearchDirector::Ptr director = std::make_shared<AdamSearchDirector>();
	// GradientSearchDirector::Ptr director = std::make_shared<GradientSearchDirector>();
	NaturalSearchDirector::Ptr director = std::make_shared<NaturalSearchDirector>();
	optimizer.SetSearchDirector( director );

	BacktrackingSearchStepper::Ptr stepper = std::make_shared<BacktrackingSearchStepper>();
	stepper->SetInitialStep( 1E-1 );
	stepper->SetBacktrackingRatio( 0.5 );
	stepper->SetMaxBacktracks( 20 );
	stepper->SetImprovementRatio( 0.75 );

	// L1ConstrainedSearchStepper::Ptr stepper = std::make_shared<L1ConstrainedSearchStepper>();
	// stepper->SetMaxL1Norm( 1E-1 );
	// stepper->SetStepSize( 1E-2 );
	optimizer.SetSearchStepper( stepper );

	RuntimeTerminationChecker::Ptr runtimeChecker = std::make_shared<RuntimeTerminationChecker>();
	runtimeChecker->SetMaxRuntime( 20 );
	optimizer.AddTerminationChecker( runtimeChecker );

	// GradientTerminationChecker::Ptr gradientChecker = std::make_shared<GradientTerminationChecker>();
	// gradientChecker->SetMinGradientNorm( 1E-9 );
	// optimizer.AddTerminationChecker( gradientChecker );

	// IterationTerminationChecker::Ptr iterationChecker = std::make_shared<IterationTerminationChecker>();
	// iterationChecker->SetMaxIterations( 1e3 );
	// optimizer.AddTerminationChecker( iterationChecker );

	trainProblem.Invalidate();
	testProblem.Invalidate();
	trainProblem.ForepropAll();
	testProblem.ForepropAll();
	trainProblem.losses.ParentCost::Foreprop();
	testProblem.losses.ParentCost::Foreprop();
	std::cout << "initial train avg loss: " << trainProblem.losses.ParentCost::GetOutput() << std::endl;
	std::cout << "initial train max loss: " << trainProblem.losses.ParentCost::ComputeMax() << std::endl;
	std::cout << "initial test avg loss: " << testProblem.losses.ParentCost::GetOutput() << std::endl;
	std::cout << "initial test max loss: " << testProblem.losses.ParentCost::ComputeMax() << std::endl;

	std::cout << "Beginning optimization..." << std::endl;
	optimizer.ResetAll();
	trainProblem.Resample();
	OptimizationResults result = optimizer.Optimize( trainProblem );
	std::cout << "Terminated with condition: " << result.status << std::endl;
	std::cout << "Final net: " << std::endl << reg.net << std::endl;

	trainProblem.Invalidate();
	testProblem.Invalidate();
	trainProblem.ForepropAll();
	testProblem.ForepropAll();
	trainProblem.losses.ParentCost::Foreprop();
	testProblem.losses.ParentCost::Foreprop();
	std::cout << "train avg loss: " << trainProblem.losses.ParentCost::GetOutput() << std::endl;
	std::cout << "train max loss: " << trainProblem.losses.ParentCost::ComputeMax() << std::endl;
	std::cout << "test avg loss: " << testProblem.losses.ParentCost::GetOutput() << std::endl;
	std::cout << "test max loss: " << testProblem.losses.ParentCost::ComputeMax() << std::endl;

	for( unsigned int i = 0; i < numTest; i++ )
	{
		std::cout << "xtest: " << xTest[i] << " ytest: " << yTest[i]
		          << " regout: " << testProblem.regressors[i].GetOutput() << std::endl;
	}

	return 0;
}

max_stars_repo_name: Humhu/percepto

max_issues_repo_name: Humhu/percepto

max_forks_repo_name: Humhu/percepto


text:
//  Copyright John Maddock 2007.
//  Copyright Paul A. Bristow 2010
//  Use, modification and distribution are 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)

// Note that this file contains quickbook mark-up as well as code
// and comments, don't change any of the special comment mark-ups!

#include <iostream>
using std::cout;  using std::endl;
#include <cerrno> // for ::errno

//[policy_eg_7

#include <boost/math/distributions.hpp> // All distributions.
// using boost::math::normal; // Would create an ambiguity between
// boost::math::normal_distribution<RealType> boost::math::normal and
// 'anonymous-namespace'::normal'.

namespace
{ // anonymous or unnamed (rather than named as in policy_eg_6.cpp).

  using namespace boost::math::policies;
   // using boost::math::policies::errno_on_error; // etc.
  typedef policy<
     // return infinity and set errno rather than throw:
     overflow_error<errno_on_error>,
     // Don't promote double -> long double internally:
     promote_double<false>,
     // Return the closest integer result for discrete quantiles:
     discrete_quantile<integer_round_nearest>
  > my_policy;

  BOOST_MATH_DECLARE_DISTRIBUTIONS(double, my_policy)

} // close namespace my_namespace

int main()
{
   // Construct distribution with something we know will overflow.
   normal norm(10, 2); // using 'anonymous-namespace'::normal
   errno = 0;
   cout << "Result of quantile(norm, 0) is: "
      << quantile(norm, 0) << endl;
   cout << "errno = " << errno << endl;
   errno = 0;
   cout << "Result of quantile(norm, 1) is: "
      << quantile(norm, 1) << endl;
   cout << "errno = " << errno << endl;
   //
   // Now try a discrete distribution:
   binomial binom(20, 0.25);
   cout << "Result of quantile(binom, 0.05) is: "
      << quantile(binom, 0.05) << endl;
   cout << "Result of quantile(complement(binom, 0.05)) is: "
      << quantile(complement(binom, 0.05)) << endl;
}

//] //[/policy_eg_7]

/*

Output:

  Result of quantile(norm, 0) is: -1.#INF
  errno = 34
  Result of quantile(norm, 1) is: 1.#INF
  errno = 34
  Result of quantile(binom, 0.05) is: 1
  Result of quantile(complement(binom, 0.05)) is: 8

*/

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#include "stratton-chu/distorted-surface.hpp"

#include <boost/math/special_functions/legendre.hpp>

using namespace boost::math;

double legendre(int num, double arg)
{
    if (arg > 1.0)
        return legendre_p(num, 1.0);
    if (arg < -1.0)
        return legendre_p(num, -1.0);
    return legendre_p(num, arg);
}

double legendre_derivative(int num, double arg)
{
    if (arg > 1.0)
        return 0.0;
    if (arg < -1.0)
        return 0.0;
    return legendre_p_prime(num, arg);
}

SurfaceDistortionHarmonic::SurfaceDistortionHarmonic(
        const ISurface& pure_surface,
        const Vector& v,
        const std::vector<DistortionHarmonic>& harmonics) :  // v - unit vector
    m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v)
{}

Position SurfaceDistortionHarmonic::point(const Vector2D& pos) const
{
    Position result = m_pure_surface.point(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = m_harmonics[i].ampl * cos(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);
        Vector delta = m_v * shift;
        result += delta;
    }

    return result;
}

Vector SurfaceDistortionHarmonic::tau1(const Vector2D& pos) const
{
    Vector result = m_pure_surface.tau1(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = - m_harmonics[i].ampl * m_harmonics[i].kx * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);
        Vector delta =  m_v * shift;
        result += delta;
    }
    return result;
}

Vector SurfaceDistortionHarmonic::tau2(const Vector2D& pos) const
{
    Vector result = m_pure_surface.tau2(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = - m_harmonics[i].ampl * m_harmonics[i].ky * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);
        Vector delta = m_v * shift;
        result += delta;
    }
    return result;
}

SurfaceDistortionLegendre::DistortionPolinom::DistortionPolinom(double ampl, double alpha, int number) :
    ampl(ampl), direction(cos(alpha), sin(alpha)), number(number)
{
}

SurfaceDistortionLegendre::SurfaceDistortionLegendre(
        const ISurface& pure_surface,
        const Vector& v,
        double radius,
        Vector2D center,
        const std::vector<DistortionPolinom>& harmonics) :  // v - unit vector
    m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v), m_center(center), m_radius(radius)
{
}

Position SurfaceDistortionLegendre::point(const Vector2D& pos) const
{
    Position result = m_pure_surface.point(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = m_harmonics[i].ampl * legendre(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);
        Vector delta = m_v * shift;
        result += delta;
    }

    return result;
}

Vector SurfaceDistortionLegendre::tau1(const Vector2D& pos) const
{
    Vector result = m_pure_surface.tau1(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = m_harmonics[i].ampl * m_harmonics[i].direction[0] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);
        Vector delta =  m_v * shift;
        result += delta;
    }
    return result;
}

Vector SurfaceDistortionLegendre::tau2(const Vector2D& pos) const
{
    Vector result = m_pure_surface.tau2(pos);
    for (size_t i = 0; i < m_harmonics.size(); i++)
    {
        double shift = m_harmonics[i].ampl * m_harmonics[i].direction[1] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);
        Vector delta =  m_v * shift;
        result += delta;
    }
    return result;
}


text:
/*
 * 	gesture_client.hpp
 *
 *	Author(s): Tamas D. Nagy
 *	Created on: 2017-07-20
 *
 *	Single arm, ROS actions interface to the surgeme server. This objects are
 *  planned to be used as members of subtask-level logic.
 *
 */

#ifndef SURGEME_CLIENT_HPP_
#define SURGEME_CLIENT_HPP_

#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ros/ros.h>
#include <ros/package.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/Float32.h>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <irob_utils/pose.hpp>
#include <irob_utils/trajectory.hpp>
#include <irob_utils/utils.hpp>
#include <irob_utils/irob_action_client.hpp>

#include <actionlib/server/simple_action_server.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>

#include <irob_msgs/ToolPoseStamped.h>

#include <irob_msgs/SurgemeAction.h>
#include <irob_msgs/InstrumentInfo.h>
#include <irob_msgs/InstrumentJawPart.h>

namespace saf {

class SurgemeClient {

public:

protected:
  const std::string arm_name;
  ros::NodeHandle nh;

  // Action clients
  IrobActionClient<irob_msgs::SurgemeAction> ac;

  // States
  irob_msgs::ToolPoseStamped position_cartesian_current;
  irob_msgs::InstrumentInfo instrument_info;

  // Subscribers
  ros::Subscriber position_cartesian_current_sub;
  ros::Subscriber instrument_info_sub;

  // Publishers
  ros::Publisher position_cartesian_current_pub;
  ros::Publisher instrument_info_pub;

  void subscribeTopics();
  void advertiseTopics();
  void startActionClients();
  void waitForActionServer();

public:
  SurgemeClient(ros::NodeHandle, std::string);
  ~SurgemeClient();

  // Callbacks

  void positionCartesianCurrentCB(
      const irob_msgs::ToolPoseStampedConstPtr&);

  void instrumentInfoCB(
      const irob_msgs::InstrumentInfoConstPtr&);

  Pose getPoseCurrent();
  irob_msgs::InstrumentInfo getInstrumentInfo();
  std::string getName();

  // Robot motions
  void stop();
  void nav_to_pos(Pose,
                  double,
                  std::vector<Pose> = std::vector<Pose>(),
                  InterpolationMethod = InterpolationMethod::LINEAR);
  void grasp(Pose, Pose, double,	double,
             double,
             double,
             std::vector<Pose> = std::vector<Pose>(),
             InterpolationMethod = InterpolationMethod::LINEAR);
  void cut(Pose, Pose,double,
           double,
           double,
           std::vector<Pose> = std::vector<Pose>(),
           InterpolationMethod = InterpolationMethod::LINEAR);
  void release(Pose,	double,
               double,
               double);
  void place(Pose, Pose,
             double,
             std::vector<Pose> = std::vector<Pose>(),
             InterpolationMethod = InterpolationMethod::LINEAR);
  void push(Pose, Pose,
            Eigen::Vector3d,
            double,
            double,
            std::vector<Pose> = std::vector<Pose>(),
            InterpolationMethod = InterpolationMethod::LINEAR);
  void dissect(Pose, Pose,
               Eigen::Vector3d,
               double,
               double,
               double,
               std::vector<Pose> = std::vector<Pose>(),
               InterpolationMethod = InterpolationMethod::LINEAR);

  void manipulate(Eigen::Vector3d,
                  double);

  bool isSurgemeDone(bool = true);
  actionlib::SimpleClientGoalState getState();

  irob_msgs::SurgemeFeedback getFeedback(bool = true);
  irob_msgs::SurgemeResult getResult(bool = true);

};

}
#endif /* SURGEME_SERVER_HPP_ */

ext: hpp

max_stars_repo_name: BenGab/irob-saf

max_issues_repo_name: BenGab/irob-saf

max_forks_repo_name: BenGab/irob-saf


text:
//  (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
//  (C) Copyright Eric Friedman 2002-2003.
//  (C) Copyright Antony Polukhin 2013.
//  Use, modification and distribution are 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).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_HAS_TRIVIAL_MOVE_CONSTRUCTOR_HPP_INCLUDED
#define BOOST_TT_HAS_TRIVIAL_MOVE_CONSTRUCTOR_HPP_INCLUDED

#include <cstddef> // size_t
#include <boost/type_traits/intrinsics.hpp>
#include <boost/type_traits/integral_constant.hpp>

#ifdef BOOST_HAS_TRIVIAL_MOVE_CONSTRUCTOR

#if defined(BOOST_MSVC) || defined(BOOST_INTEL)
#include <boost/type_traits/is_pod.hpp>
#include <boost/type_traits/is_volatile.hpp>
#endif

#if defined(__GNUC__) || defined(__clang)
#include <boost/type_traits/is_constructible.hpp>
#include <boost/type_traits/is_volatile.hpp>
#endif

namespace boost {

template <typename T> struct has_trivial_move_constructor : public integral_constant<bool, BOOST_HAS_TRIVIAL_MOVE_CONSTRUCTOR(T)>{};

#else

#ifdef __SUNPRO_CC
#include <boost/type_traits/is_constructible.hpp>
#include <boost/type_traits/remove_const.hpp>
#if __cplusplus >= 201103
#define SOLARIS_EXTRA_CHECK && is_constructible<typename remove_const<T>::type, typename remove_const<T>::type&&>::value
#endif
#endif

#ifndef SOLARIS_EXTRA_CHECK
#define SOLARIS_EXTRA_CHECK
#endif

#include <boost/type_traits/is_pod.hpp>
#include <boost/type_traits/is_volatile.hpp>

namespace boost {

template <typename T> struct has_trivial_move_constructor
   : public integral_constant<bool, ::boost::is_pod<T>::value && !::boost::is_volatile<T>::value SOLARIS_EXTRA_CHECK>{};

#undef SOLARIS_EXTRA_CHECK

#endif

template <> struct has_trivial_move_constructor<void> : public false_type{};
#ifndef BOOST_NO_CV_VOID_SPECIALIZATIONS
template <> struct has_trivial_move_constructor<void const> : public false_type{};
template <> struct has_trivial_move_constructor<void volatile> : public false_type{};
template <> struct has_trivial_move_constructor<void const volatile> : public false_type{};
#endif
// What should we do with reference types??? The standard seems to suggest these are trivial, even if the thing they reference is not:
template <class T> struct has_trivial_move_constructor<T&> : public true_type{};
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T> struct has_trivial_move_constructor<T&&> : public true_type{};
#endif
// Arrays can not be explicitly copied:
template <class T, std::size_t N> struct has_trivial_move_constructor<T[N]> : public false_type{};
template <class T> struct has_trivial_move_constructor<T[]> : public false_type{};

} // namespace boost

#endif // BOOST_TT_HAS_TRIVIAL_MOVE_CONSTRUCTOR_HPP_INCLUDED


text:
#include <iostream>
#include <boost/accumulators/statistics/weighted_sum.hpp>
#include <boost/accumulators/statistics/sum.hpp>
#include <boost/accumulators/accumulators.hpp>

using namespace boost::accumulators;

int main()
{
	//accumulator_set<int, features<tag::weight_sum> , int> acc;
	accumulator_set<int, features<tag::sum> , int> acc;

	acc(1, weight = 2);acc(2, weight = 4);
	acc(3, weight = 4);acc(5, weight = 6);

	//std::cout<< weight_sum(acc) << std::endl;
	std::cout<< sum(acc) << std::endl;
}

ext: cc


text:
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#ifndef NIX_CHECKS_H
#define NIX_CHECKS_H

#include <nix/util/util.hpp>
#include <nix/valid/helper.hpp>

#include <nix/base/IDimensions.hpp>

#include <nix/types.hpp>

#include <boost/optional.hpp>
#include <boost/any.hpp>

namespace nix {
namespace valid {

    /**
     * @brief Check if later given not greater than initally defined value.
     *
     * One Check struct that checks whether the given value is not greater
     * than the initially given other value, both of which have to be
     * convertible to double.
     */
    struct notGreater {
        const double value;

        template<typename T>
        notGreater(T value) : value(static_cast<double>(value)) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return !(static_cast<double>(val) > value);
        }
    };

    /**
     * @brief Check if later given greater than initally defined value.
     *
     * One Check struct that checks whether the given value is greater than
     * the initially given other value, both of which have to be
     * convertible to double.
     */
    struct isGreater {
        const double value;

        template<typename T>
        isGreater(T value) : value(static_cast<double>(value)) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return static_cast<double>(val) > value;
        }
    };

    /**
     * @brief Check if later given not smaller than initally defined value.
     *
     * One Check struct that checks whether the given value is not smaller
     * than the initially given other value, both of which have to be
     * convertible to double.
     */
    struct notSmaller {
        const double value;

        template<typename T>
        notSmaller(T value) : value(static_cast<double>(value)) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return !(static_cast<double>(val) < value);
        }
    };

    /**
     * @brief Check if later given smaller than initally defined value.
     *
     * One Check struct that checks whether the given value is smaller than
     * the initially given other value, both of which have to be
     * convertible to double.
     */
    struct isSmaller {
        const double value;

        template<typename T>
        isSmaller(T value) : value(static_cast<double>(value)) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return static_cast<double>(val) < value;
        }
    };

    /**
     * @brief Check for un-equality of initally defined and later given value.
     *
     * One Check struct that checks whether the given value is not equal
     * to the initially given other value.
     */
    template<typename T>
    struct notEqual {
        const T value;

        notEqual(T value) : value(value) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return value != val;
        }
    };

    /**
     * @brief Check for equality of initally defined and later given value.
     *
     * One Check struct that checks whether the given value is equal to
     * the initially given other value.
     */
    template<typename T>
    struct isEqual {
        const T value;

        isEqual(T value) : value(value) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return value == val;
        }
    };
    // needed because: for bizarre reasons bool converts to int when compared to boost::optional
    template<>
    struct isEqual<bool> {
        const bool value;

        isEqual(bool value) : value(value) {}

        template<typename T2>
        bool operator()(const T2 &val) const {
            return value ? !!val : !val;
        }
    };

    /**
     * @brief Check if given value casts to boolean true
     *
     * One Check struct that checks whether the given value casts to true
     * or to false.
     * T can be: boost::optional, boost::none, nix-entity
     * and any basic type.
     */
    struct notFalse {
        // WARNING: enum will convert via int, which means 0 = false !
        template<typename T>
        bool operator()(const T &val) const {
            return !!val;
        }
    };

    /**
     * @brief Check if given value casts to boolean false
     *
     * One Check struct that checks whether the given value casts to false
     * or to true.
     * T can be: boost::optional, boost::none, nix-entity
     * and any basic type.
     */
    struct isFalse {
        // WARNING: enum will convert via int, which means 0 = false !
        template<typename T>
        bool operator()(const T &val) const {
            return !val;
        }
    };

    /**
     * @brief Check if given class/struct returns "empty() == false"
     *
     * One Check struct that checks whether the given value is not empty
     * or is empty.
     * T can be: any STL container.
     */
    struct notEmpty {
        template<typename T>
        bool operator()(const T &val) const {
            return !(val.empty());
        }
    };

    /**
     * @brief Check if given class/struct returns "empty() == true"
     *
     * One Check struct that checks whether the given value is empty or
     * not.
     * T can be: any STL container.
     */
    struct isEmpty {
        template<typename T>
        bool operator()(const T &val) const {
            return val.empty();
        }
    };

    /**
     * @brief Check if given class represents valid SI unit string(s)
     *
     * Base struct to be inherited by the {@link isValidUnit}, {@link
     * isAtomicUnit}, {@link isCompoundUnit}. Not viable on its own!
     */
    struct isUnit {
        typedef std::function<bool(std::string)> TPRED;

        virtual bool operator()(const std::string &u) const = 0;

        bool operator()(const boost::optional<std::string> &u) const {
            // note: relying on short-curcuiting here
            return u && (*this)(*u);
        }

        bool operator()(const std::vector<std::string> &u, TPRED obj) const {
            // if test succeeds find_if_not will not find anything & return it == end
            return std::find_if_not(u.begin(), u.end(), obj) == u.end();
        }

        virtual ~isUnit() { }
    };

    /**
     * @brief Check if given class represents valid SI unit string(s)
     *
     * One Check struct that checks whether the given string(s) represent(s)
     * a valid atomic or compound SI unit.
     * Parameter can be of type boost optional (containing nothing or
     * string) or of type string or a vector of strings.
     */
    struct isValidUnit : public isUnit {
        bool operator()(const std::string &u) const {
            return (util::isSIUnit(u) || util::isCompoundSIUnit(u));
        }
        bool operator()(const boost::optional<std::string> &u) const {
            return isUnit::operator()(u);
        }
        bool operator()(const std::vector<std::string> &u) const {
            return isUnit::operator()(u, *this);
        }
    };

    /**
     * @brief Check if given class represents valid atomic SI unit string(s)
     *
     * One Check struct that checks whether the given string(s) represent(s)
     * a valid atomic SI unit.
     * Parameter can be of type boost optional (containing nothing or
     * string) or of type string or a vector of strings.
     */
    struct isAtomicUnit : public isUnit {
        bool operator()(const std::string &u) const {
            return util::isSIUnit(u);
        }
        bool operator()(const boost::optional<std::string> &u) const {
            return isUnit::operator()(u);
        }
        bool operator()(const std::vector<std::string> &u) const {
            return isUnit::operator()(u, *this);
        }
    };

    /**
     * @brief Check if given class represents valid compound SI unit string(s)
     *
     * One Check struct that checks whether the given string(s) represent(s)
     * a valid compound SI unit.
     * Parameter can be of type boost optional (containing nothing or
     * string) or of type string or a vector of strings.
     */
    struct isCompoundUnit : public isUnit {
        bool operator()(const std::string &u) const {
            return util::isCompoundSIUnit(u);
        }
        bool operator()(const boost::optional<std::string> &u) const {
            return isUnit::operator()(u);
        }
        bool operator()(const std::vector<std::string> &u) const {
            return isUnit::operator()(u, *this);
        }
    };

    /**
     * @brief Check if given value can be regarded as being set
     *
     * One Check struct that checks whether the given value can be
     * considered set, by applying {@link notFalse} and {@link notEmpty}
     * checks. Value thus is set if: STL cotnainer not empty OR
     * bool is true OR boost optional is set OR number is not 0.
     * Parameter can be of above types or even boost none_t.
     * NOTE: use this if you don't know wheter a type has and "empty"
     * method.
     */
    struct isSet {
        template<typename T>
        bool operator()(const T &val) const {
            typedef typename std::conditional<hasEmpty<T>::value, notEmpty, notFalse>::type subCheck;
            return subCheck(val);
        }
    };

    /**
     * @brief Check if given container is sorted using std::is_sorted
     *
     * One Check struct that checks whether the given container is sorted
     * according to std::is_sorted. Thus supports types that are
     * supported by std::is_sorted.
     */
    struct isSorted {
        template<typename T>
        bool operator()(const T &container) const {
            return std::is_sorted(container.begin(), container.end());
        }
    };

    /**
     * @brief Check if given DataArray has given dimensionality
     *
     * One Check struct that checks whether the given DataArray entity
     * has a dimensionality of the given uint value by getting its'
     * NDSize class via the "dataExtent" method and checking its' size
     * via "size" the method.
     */
    struct NIXAPI dimEquals {
        size_t value;

        dimEquals(const size_t &value) : value(value) {}

        bool operator()(const DataArray &array) const;
    };

    /**
     * @brief Checks if units of the passed DataArray dimensions matches those
     * defined in the Tag
     *
     * Struct to check whether the units defined in the Tag match with the units
     * specified in the referenced DataArray dimensions. The check tests for
     * scalability of the tag-provided units and the ones of the DataArrays.
     *
     */
    struct NIXAPI tagUnitsMatchRefsUnits {
        std::vector<std::string> units;

        tagUnitsMatchRefsUnits(const std::vector<std::string> &units) : units(units) {}

        bool operator()(const std::vector<DataArray> &references) const;
    };

    /**
     * @brief Check if range dimension specifics ticks match data
     *
     * One Check struct that checks whether the dimensions of type
     * "Range" in the given dimensions vector have ticks that match
     * the given DataArray's data: number of ticks == number of entries
     * along the corresponding dimension in the data.
     */
    struct NIXAPI dimTicksMatchData {
        const DataArray &data;

        dimTicksMatchData(const DataArray &data) : data(data) {}

        bool operator()(const std::vector<Dimension> &dims) const;
    };

    /**
     * @brief Check if set dimension specifics labels match data
     *
     * One Check struct that checks whether the dimensions of type
     * "Set" in the given dimensions vector have labels that match
     * the given DataArray's data: number of labels == number of entries
     * along the corresponding dimension in the data.
     */
    struct NIXAPI dimLabelsMatchData {
        const DataArray &data;

        dimLabelsMatchData(const DataArray &data) : data(data) {}

        bool operator()(const std::vector<Dimension> &dims) const;
    };

    /**
     * @brief Check if DataFrame dimension specifics ticks match data
     *
     * Struct for checking whether the number of rows in the dimensions of type
     * "DataFrame" in the given dimensions vector matches the given DataArray's
     * data extent in the respective dimension: number of rows in DataFrame == number of
     * entries along the corresponding dimension in the data.
     */
    struct NIXAPI dimDataFrameTicksMatchData {
        const DataArray &data;

        dimDataFrameTicksMatchData(const DataArray &data) : data(data) {}

        bool operator()(const std::vector<Dimension> &dims) const;
    };

} // namespace valid
} // namespace nix

#endif // NIX_CHECKS_H

max_stars_repo_name: mpsonntag/nix

max_issues_repo_name: mpsonntag/nix

max_forks_repo_name: mpsonntag/nix