text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014, JSK, The University of Tokyo.
 *  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 JSK, The University of Tokyo nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Dave Coleman */

// OMPL
#include "ompl/tools/lightning/LightningDB.h"
#include "ompl/base/ScopedState.h"
#include "ompl/util/Time.h"
#include "ompl/tools/config/SelfConfig.h"
#include "ompl/base/PlannerDataStorage.h"

// Boost
#include <boost/filesystem.hpp>

ompl::tools::LightningDB::LightningDB(const base::StateSpacePtr &space)
    : numUnsavedPaths_(0)
{
    si_.reset(new base::SpaceInformation(space));

    // Set nearest neighbor type
    nn_.reset(new ompl::NearestNeighborsSqrtApprox<ompl::base::PlannerDataPtr>());

    // Use our custom distance function for nearest neighbor tree
    nn_->setDistanceFunction(std::bind(&ompl::tools::LightningDB::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));

    // Load the PlannerData instance to be used for searching
    nnSearchKey_.reset(new ompl::base::PlannerData(si_));
}

ompl::tools::LightningDB::~LightningDB()
{
    if (numUnsavedPaths_)
        OMPL_WARN("The database is being unloaded with unsaved experiences");
}

bool ompl::tools::LightningDB::load(const std::string &fileName)
{
    // Error checking
    if (fileName.empty())
    {
        OMPL_ERROR("Empty filename passed to save function");
        return false;
    }
    if ( !boost::filesystem::exists( fileName ) )
    {
        OMPL_WARN("Database file does not exist: %s", fileName.c_str());
        return false;
    }

    // Load database from file, track loading time
    time::point start = time::now();

    OMPL_INFORM("Loading database from file: %s", fileName.c_str());

    // Open a binary input stream
    std::ifstream iStream(fileName.c_str(), std::ios::binary);

    // Get the total number of paths saved
    double numPaths = 0;
    iStream >> numPaths;

    // Check that the number of paths makes sense
    if (numPaths < 0 || numPaths > std::numeric_limits<double>::max())
    {
        OMPL_WARN("Number of paths to load %d is a bad value", numPaths);
        return false;
    }

    // Start loading all the PlannerDatas
    for (std::size_t i = 0; i < numPaths; ++i)
    {
        // Create a new planner data instance
        ompl::base::PlannerDataPtr plannerData(new ompl::base::PlannerData(si_));

        // Note: the StateStorage class checks if the states match for us
        plannerDataStorage_.load(iStream, *plannerData.get());

        // Add to nearest neighbor tree
        nn_->add(plannerData);
    }

    // Close file
    iStream.close();

    double loadTime = time::seconds(time::now() - start);
    OMPL_INFORM("Loaded database from file in %f sec with %d paths", loadTime, nn_->size());
    return true;
}

void ompl::tools::LightningDB::addPath(ompl::geometric::PathGeometric& solutionPath, double &insertionTime)
{
    // Benchmark runtime
    time::point startTime = time::now();
    {
        addPathHelper(solutionPath);
    }
    insertionTime = time::seconds(time::now() - startTime);
}

void ompl::tools::LightningDB::addPathHelper(ompl::geometric::PathGeometric &solutionPath)
{
    // Create a new planner data instance
    ompl::base::PlannerDataPtr plannerData(new ompl::base::PlannerData(si_));

    // Add the states to one nodes files
    for (std::size_t i = 0; i < solutionPath.getStates().size(); ++i)
    {
        ompl::base::PlannerDataVertex vert( solutionPath.getStates()[i] ); // TODO tag?

        plannerData->addVertex(vert);
    }

    // Deep copy the states in the vertices so that when the planner goes out of scope, all data remains intact
    plannerData->decoupleFromPlanner();

    // Add to nearest neighbor tree
    nn_->add(plannerData);

    numUnsavedPaths_++;
}

bool ompl::tools::LightningDB::saveIfChanged(const std::string &fileName)
{
    if (numUnsavedPaths_)
        return save(fileName);
    else
        OMPL_INFORM("Not saving because database has not changed");
    return true;
}

bool ompl::tools::LightningDB::save(const std::string &fileName)
{
    // Error checking
    if (fileName.empty())
    {
        OMPL_ERROR("Empty filename passed to save function");
        return false;
    }

    // Save database from file, track saving time
    time::point start = time::now();

    OMPL_INFORM("Saving database to file: %s", fileName.c_str());

    // Open a binary output stream
    std::ofstream outStream(fileName.c_str(), std::ios::binary);

    // Convert the NN tree to a vector
    std::vector<ompl::base::PlannerDataPtr> plannerDatas;
    nn_->list(plannerDatas);

    // Write the number of paths we will be saving
    double numPaths = plannerDatas.size();
    outStream << numPaths;

    // Start saving each planner data object
    for (std::size_t i = 0; i < numPaths; ++i)
    {
        ompl::base::PlannerData &pd = *plannerDatas[i].get();

        // Save a single planner data
        plannerDataStorage_.store(pd, outStream);
    }

    // Close file
    outStream.close();

    // Benchmark
    double loadTime = time::seconds(time::now() - start);
    OMPL_INFORM("Saved database to file in %f sec with %d paths", loadTime, plannerDatas.size());

    numUnsavedPaths_ = 0;

    return true;
}

void ompl::tools::LightningDB::getAllPlannerDatas(std::vector<ompl::base::PlannerDataPtr> &plannerDatas) const
{
    OMPL_DEBUG("LightningDB: getAllPlannerDatas");

    // Convert the NN tree to a vector
    nn_->list(plannerDatas);

    OMPL_DEBUG("Number of paths found: %d", plannerDatas.size());
}

std::vector<ompl::base::PlannerDataPtr> ompl::tools::LightningDB::findNearestStartGoal(
    int nearestK, const base::State *start, const base::State *goal)
{
    // Fill in our pre-made PlannerData instance with the new start and goal states to be searched for
    if (nnSearchKey_->numVertices() == 2)
    {
        nnSearchKey_->getVertex(0) = ompl::base::PlannerDataVertex(start);
        nnSearchKey_->getVertex(1) = ompl::base::PlannerDataVertex(goal);
    }
    else
    {
        nnSearchKey_->addVertex(ompl::base::PlannerDataVertex(start));
        nnSearchKey_->addVertex(ompl::base::PlannerDataVertex(goal));
    }
    assert( nnSearchKey_->numVertices() == 2);

    std::vector<ompl::base::PlannerDataPtr> nearest;
    nn_->nearestK(nnSearchKey_, nearestK, nearest);

    return nearest;
}

double ompl::tools::LightningDB::distanceFunction(const ompl::base::PlannerDataPtr a, const ompl::base::PlannerDataPtr b) const
{
    // Bi-directional implementation - check path b from [start, goal] and [goal, start]
    return std::min(
        // [ a.start, b.start] + [a.goal + b.goal]
        si_->distance(a->getVertex(0).getState(), b->getVertex(0).getState()) +
        si_->distance(a->getVertex(a->numVertices()-1).getState(), b->getVertex(b->numVertices()-1).getState()),
        // [ a.start, b.goal] + [a.goal + b.start]
        si_->distance(a->getVertex(0).getState(), b->getVertex(b->numVertices()-1).getState()) +
        si_->distance(a->getVertex(a->numVertices()-1).getState(), b->getVertex(0).getState()));
}

std::size_t ompl::tools::LightningDB::getExperiencesCount() const
{
    return nn_->size();
}

std::size_t ompl::tools::LightningDB::getStatesCount() const
{
    // Loop through every PlannerData and sum the number of states
    std::size_t statesCount = 0;

    // Convert the NN tree to a vector
    std::vector<ompl::base::PlannerDataPtr> plannerDatas;
    nn_->list(plannerDatas);

    // Start saving each planner data object
    for (std::size_t i = 0; i < plannerDatas.size(); ++i)
    {
        statesCount += plannerDatas[i]->numVertices();
    }

    return statesCount;
}

ext: cpp

max_stars_repo_name: wzxd/project-ompl


text:
/**
 * \file boost/numeric/ublasx/operation/exp.hpp
 *
 * \brief Apply the \c std::exp function to each element of a vector or
 *  matrix expression.
 *
 * Copyright (c) 2011, Marco Guazzone
 *
 * 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)
 *
 * \author Marco Guazzone, marco.guazzone@gmail.com
 */

#ifndef BOOST_NUMERIC_UBLASX_OPERATION_EXP_HPP
#define BOOST_NUMERIC_UBLASX_OPERATION_EXP_HPP

#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>
#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>
#include <cmath>

namespace boost { namespace numeric { namespace ublasx {

using namespace ::boost::numeric::ublas;

namespace detail {

template <typename VectorExprT>
struct vector_exp_functor_traits
{
	typedef VectorExprT input_expression_type;
	typedef typename vector_traits<input_expression_type>::value_type signature_argument_type;
	typedef signature_argument_type signature_result_type;
	typedef vector_unary_functor_traits<
				input_expression_type,
				signature_result_type (signature_argument_type)
			> unary_functor_expression_type;
	typedef typename unary_functor_expression_type::result_type result_type;
	typedef typename unary_functor_expression_type::expression_type expression_type;
};

template <typename MatrixExprT>
struct matrix_exp_functor_traits
{
	typedef MatrixExprT input_expression_type;
	typedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;
	typedef signature_argument_type signature_result_type;
	typedef matrix_unary_functor_traits<
				input_expression_type,
				signature_result_type (signature_argument_type)
			> unary_functor_expression_type;
	typedef typename unary_functor_expression_type::result_type result_type;
	typedef typename unary_functor_expression_type::expression_type expression_type;
};

namespace /*<unnamed>*/ {

/// Auxiliary function used to replace ::std::exp2 when that is not available.
template <typename T>
BOOST_UBLAS_INLINE
T exp(T x)
{
	return ::std::exp(x);
}

} // Namespace <unnamed>

} // Namespace detail

/**
 * \brief Applies the \c std::exp function to each element of a given vector
 *  expression.
 *
 * \tparam VectorExprT The type of the input vector expression.
 *
 * \param ve The input vector expression.
 * \return A vector expression representing the application of \c std::exp to
 *  each element of \a ve.
 *
 * \author Marco Guazzone, marco.guazzone@gmail.com
 */
template <typename VectorExprT>
BOOST_UBLAS_INLINE
typename detail::vector_exp_functor_traits<VectorExprT>::result_type exp(vector_expression<VectorExprT> const& ve)
{
	typedef typename detail::vector_exp_functor_traits<VectorExprT>::expression_type expression_type;
	typedef typename detail::vector_exp_functor_traits<VectorExprT>::signature_result_type signature_result_type;

	return expression_type(ve(), detail::exp<signature_result_type>);
}

/**
 * \brief Applies the \c std::exp function to each element of a given matrix
 *  expression.
 *
 * \tparam MatrixExprT The type of the input matrix expression.
 *
 * \param me The input matrix expression.
 * \return A matrix expression representing the application of \c std::exp to
 *  each element of \a me.
 *
 * \author Marco Guazzone, marco.guazzone@gmail.com
 */
template <typename MatrixExprT>
BOOST_UBLAS_INLINE
typename detail::matrix_exp_functor_traits<MatrixExprT>::result_type exp(matrix_expression<MatrixExprT> const& me)
{
	typedef typename detail::matrix_exp_functor_traits<MatrixExprT>::expression_type expression_type;
	typedef typename detail::matrix_exp_functor_traits<MatrixExprT>::signature_result_type signature_result_type;

	return expression_type(me(), detail::exp<signature_result_type>);
}

}}} // Namespace boost::numeric::ublasx

#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOG_HPP

ext: hpp


text:
//  boost/chrono/process_cpu_clocks.hpp  -----------------------------------------------------------//

//  Copyright 2009-2010 Vicente J. Botet Escriba

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  See http://www.boost.org/libs/system for documentation.

#ifndef BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP
#define BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP

#include <boost/chrono/duration.hpp>
#include <boost/chrono/time_point.hpp>
#include <boost/system/error_code.hpp>
#include <boost/operators.hpp>
#include <boost/chrono/detail/system.hpp>
#include <iostream>

#ifndef BOOST_CHRONO_HEADER_ONLY
#include <boost/config/abi_prefix.hpp> // must be the last #include
#endif

namespace boost { namespace chrono {

    class BOOST_CHRONO_DECL process_real_cpu_clock {
    public:
        typedef nanoseconds                          duration;
        typedef duration::rep                        rep;
        typedef duration::period                     period;
        typedef chrono::time_point<process_real_cpu_clock>    time_point;
        BOOST_CHRONO_STATIC_CONSTEXPR bool is_steady =             true;

        static BOOST_CHRONO_INLINE time_point now(
                system::error_code & ec = BOOST_CHRONO_THROWS );
    };

    class BOOST_CHRONO_DECL process_user_cpu_clock {
    public:
        typedef nanoseconds                          duration;
        typedef duration::rep                        rep;
        typedef duration::period                     period;
        typedef chrono::time_point<process_user_cpu_clock>    time_point;
        BOOST_CHRONO_STATIC_CONSTEXPR bool is_steady =             true;

        static BOOST_CHRONO_INLINE time_point now(
                system::error_code & ec = BOOST_CHRONO_THROWS );
    };

    class BOOST_CHRONO_DECL process_system_cpu_clock {
    public:
        typedef nanoseconds                          duration;
        typedef duration::rep                        rep;
        typedef duration::period                     period;
        typedef chrono::time_point<process_system_cpu_clock>    time_point;
        BOOST_CHRONO_STATIC_CONSTEXPR bool is_steady =             true;

        static BOOST_CHRONO_INLINE time_point now(
                system::error_code & ec = BOOST_CHRONO_THROWS );
    };

        struct process_cpu_clock_times
            : arithmetic<process_cpu_clock_times,
            multiplicative<process_cpu_clock_times, process_real_cpu_clock::rep,
            less_than_comparable<process_cpu_clock_times> > >
        {
            typedef process_real_cpu_clock::rep rep;
            process_cpu_clock_times()
                : real(0)
                , user(0)
                , system(0){}
            process_cpu_clock_times(
                process_real_cpu_clock::rep r,
                process_user_cpu_clock::rep   u,
                process_system_cpu_clock::rep s)
                : real(r)
                , user(u)
                , system(s){}

            process_real_cpu_clock::rep   real;    // real (i.e wall clock) time
            process_user_cpu_clock::rep   user;    // user cpu time
            process_system_cpu_clock::rep system;  // system cpu time

            bool operator==(process_cpu_clock_times const& rhs) {
                return (real==rhs.real &&
                        user==rhs.user &&
                        system==rhs.system);
            }

            process_cpu_clock_times operator+=(
                    process_cpu_clock_times const& rhs)
            {
                real+=rhs.real;
                user+=rhs.user;
                system+=rhs.system;
                return *this;
            }
            process_cpu_clock_times operator-=(
                    process_cpu_clock_times const& rhs)
            {
                real-=rhs.real;
                user-=rhs.user;
                system-=rhs.system;
                return *this;
            }
            process_cpu_clock_times operator*=(
                    process_cpu_clock_times const& rhs)
            {
                real*=rhs.real;
                user*=rhs.user;
                system*=rhs.system;
                return *this;
            }
            process_cpu_clock_times operator*=(rep const& rhs)
            {
                real*=rhs;
                user*=rhs;
                system*=rhs;
                return *this;
            }
            process_cpu_clock_times operator/=(process_cpu_clock_times const& rhs)
            {
                real/=rhs.real;
                user/=rhs.user;
                system/=rhs.system;
                return *this;
            }
            process_cpu_clock_times operator/=(rep const& rhs)
            {
                real/=rhs;
                user/=rhs;
                system/=rhs;
                return *this;
            }
            bool operator<(process_cpu_clock_times const & rhs) const
            {
                if (real < rhs.real) return true;
                if (real > rhs.real) return false;
                if (user < rhs.user) return true;
                if (user > rhs.user) return false;
                if (system < rhs.system) return true;
                else return false;
            }

            template <class CharT, class Traits>
            void print(std::basic_ostream<CharT, Traits>& os) const
            {
                os <<  "{"<< real <<";"<< user <<";"<< system << "}";
            }

            template <class CharT, class Traits>
            void read(std::basic_istream<CharT, Traits>& is) const
            {
                typedef std::istreambuf_iterator<CharT, Traits> in_iterator;
                in_iterator i(is);
                in_iterator e;
                if (i == e || *i != '{')  // mandatory '{'
                {
                    is.setstate(is.failbit | is.eofbit);
                    return;
                }
                CharT x,y,z;
                is >> real >> x >> user >> y >> system >> z;
                if (!is.good() || (x != ';')|| (y != ';')|| (z != '}'))
                {
                    is.setstate(is.failbit);
                }
            }
        };

    class BOOST_CHRONO_DECL process_cpu_clock
    {
    public:

        typedef process_cpu_clock_times times;
        typedef boost::chrono::duration<times,  nano>                duration;
        typedef duration::rep                       rep;
        typedef duration::period                    period;
        typedef chrono::time_point<process_cpu_clock>  time_point;
        BOOST_CHRONO_STATIC_CONSTEXPR bool is_steady =           true;

        static BOOST_CHRONO_INLINE time_point now(
                system::error_code & ec = BOOST_CHRONO_THROWS );
    };

    template <class CharT, class Traits>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
            process_cpu_clock_times const& rhs)
    {
        rhs.print(os);
        return os;
    }

    template <class CharT, class Traits>
    std::basic_istream<CharT, Traits>&
    operator>>(std::basic_istream<CharT, Traits>& is,
            process_cpu_clock_times const& rhs)
    {
        rhs.read(is);
        return is;
    }

    template <>
    struct duration_values<process_cpu_clock_times>
    {
        typedef process_cpu_clock_times Rep;
    public:
        static Rep zero()
        {
            return Rep();
        }
        static Rep max BOOST_PREVENT_MACRO_SUBSTITUTION ()
        {
          return Rep((std::numeric_limits<process_real_cpu_clock::rep>::max)(),
                      (std::numeric_limits<process_user_cpu_clock::rep>::max)(),
                      (std::numeric_limits<process_system_cpu_clock::rep>::max)());
        }
        static Rep min BOOST_PREVENT_MACRO_SUBSTITUTION ()
        {
          return Rep((std::numeric_limits<process_real_cpu_clock::rep>::min)(),
                      (std::numeric_limits<process_user_cpu_clock::rep>::min)(),
                      (std::numeric_limits<process_system_cpu_clock::rep>::min)());
        }
    };

} // namespace chrono
} // namespace boost

namespace std {

    template <>
    class numeric_limits<boost::chrono::process_cpu_clock::times>
    {
        typedef boost::chrono::process_cpu_clock::times Rep;

        public:
        static const bool is_specialized = true;
        static Rep min BOOST_PREVENT_MACRO_SUBSTITUTION ()
        {
          return Rep((std::numeric_limits<boost::chrono::process_real_cpu_clock::rep>::min)(),
                      (std::numeric_limits<boost::chrono::process_user_cpu_clock::rep>::min)(),
                      (std::numeric_limits<boost::chrono::process_system_cpu_clock::rep>::min)());
        }
        static Rep max BOOST_PREVENT_MACRO_SUBSTITUTION ()
        {
          return Rep((std::numeric_limits<boost::chrono::process_real_cpu_clock::rep>::max)(),
                      (std::numeric_limits<boost::chrono::process_user_cpu_clock::rep>::max)(),
                      (std::numeric_limits<boost::chrono::process_system_cpu_clock::rep>::max)());
        }
        static Rep lowest() throw()
        {
            return (min)();
        }
        static const int digits = std::numeric_limits<boost::chrono::process_real_cpu_clock::rep>::digits+
                        std::numeric_limits<boost::chrono::process_user_cpu_clock::rep>::digits+
                        std::numeric_limits<boost::chrono::process_system_cpu_clock::rep>::digits;
        static const int digits10 = std::numeric_limits<boost::chrono::process_real_cpu_clock::rep>::digits10+
                        std::numeric_limits<boost::chrono::process_user_cpu_clock::rep>::digits10+
                        std::numeric_limits<boost::chrono::process_system_cpu_clock::rep>::digits10;
        //~ static const int max_digits10 = std::numeric_limits<boost::chrono::process_real_cpu_clock::rep>::max_digits10+
                        //~ std::numeric_limits<boost::chrono::process_user_cpu_clock::rep>::max_digits10+
                        //~ std::numeric_limits<boost::chrono::process_system_cpu_clock::rep>::max_digits10;
        static const bool is_signed = false;
        static const bool is_integer = true;
        static const bool is_exact = true;
        static const int radix = 0;
        //~ static Rep epsilon() throw() { return 0; }
        //~ static Rep round_error() throw() { return 0; }
        //~ static const int min_exponent = 0;
        //~ static const int min_exponent10 = 0;
        //~ static const int max_exponent = 0;
        //~ static const int max_exponent10 = 0;
        //~ static const bool has_infinity = false;
        //~ static const bool has_quiet_NaN = false;
        //~ static const bool has_signaling_NaN = false;
        //~ static const float_denorm_style has_denorm = denorm_absent;
        //~ static const bool has_denorm_loss = false;
        //~ static Rep infinity() throw() { return 0; }
        //~ static Rep quiet_NaN() throw() { return 0; }
        //~ static Rep signaling_NaN() throw() { return 0; }
        //~ static Rep denorm_min() throw() { return 0; }
        //~ static const bool is_iec559 = false;
        //~ static const bool is_bounded = true;
        //~ static const bool is_modulo = false;
        //~ static const bool traps = false;
        //~ static const bool tinyness_before = false;
        //~ static const float_round_style round_style = round_toward_zero;

    };
}

#ifndef BOOST_CHRONO_HEADER_ONLY
#include <boost/config/abi_suffix.hpp> // pops abi_prefix.hpp pragmas
#else
#include <boost/chrono/detail/inlined/process_cpu_clocks.hpp>
#endif

#endif  // BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP

max_stars_repo_name: zigaosolin/Raytracer

max_issues_repo_name: zigaosolin/Raytracer

max_forks_repo_name: zigaosolin/Raytracer


text:
//
// Copyright Jason Rice 2016
// 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 <mpdef/justify_type.hpp>

#include <boost/hana.hpp>
#include <type_traits>

namespace hana = boost::hana;

int main()
{
  {
    // I used void to show that we aren't instantiating anything.
    // (An optional<void> doesn't really make sense though.)
    BOOST_HANA_CONSTANT_ASSERT(
      mpdef::justify_type(hana::decltype_(hana::just(hana::type_c<void>)))
        ==
      hana::type_c<hana::optional<void>>
    );

    BOOST_HANA_CONSTANT_ASSERT(
      mpdef::justify_type(hana::decltype_(hana::optional<>{}))
        ==
      hana::type_c<decltype(hana::nothing)>
    );
  }
  {
    // test `const hana::optional<int>`
    constexpr auto x = hana::just(hana::type_c<int>);
    BOOST_HANA_CONSTANT_ASSERT(
      mpdef::justify_type(hana::decltype_(x))
        ==
      hana::type_c<hana::optional<int>>
    );

    // test `const hana::optional<>`
    BOOST_HANA_CONSTANT_ASSERT(
      mpdef::justify_type(hana::decltype_(hana::nothing))
        ==
      hana::type_c<decltype(hana::nothing)>
    );
  }

}

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
/**
 * @file   log_target.cpp
 * @author Gordon "Lee" Morgan (valk.erie.fod.der+logxx@gmail.com)
 * @copyright Copyright © Gordon "Lee" Morgan May 2016. This project is released under the [MIT License](license.md)
 * @date   May 2016
 * @brief  log back end interface and provided log back ends.
 */

#include <iostream>
#include <string>
#include <sstream>
#include <cstdint>
#include <chrono>
#include <memory>
#include <mutex>
#include <system_error>
#include <queue>
#include <condition_variable>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>

#include "log_target.h"

max_stars_repo_name: static-neurotoxin/LoggerXX

max_issues_repo_name: static-neurotoxin/LoggerXX

max_forks_repo_name: static-neurotoxin/LoggerXX


text:
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"

#include <boost/test/unit_test.hpp>

#include "test_utils/DependencyProvider.hpp"
#include "test_utils/ElementUtils.hpp"

using namespace utymap::entities;

namespace {
    struct Counter : public ElementVisitor
    {
        int nodes, ways, areas, relations;

        Counter() : nodes(0), ways(0), areas(0), relations(0) {}

        void visitNode(const Node&) override { nodes++; }
        void visitWay(const Way&) override { ways++; }
        void visitArea(const Area&) override { areas++; }
        void visitRelation(const Relation&) override { relations++; }
    };

    struct Entities_ElementFixture
    {
        DependencyProvider dependencyProvider;
    };
}

BOOST_FIXTURE_TEST_SUITE(Entities_Element, Entities_ElementFixture)

BOOST_AUTO_TEST_CASE(GivenNode_WhenVisit_ThenIncrementsCounter)
{
    Counter counter;
    Node node;

    node.accept(counter);

    BOOST_CHECK_EQUAL(counter.nodes, 1);
    BOOST_CHECK_EQUAL(counter.ways, 0);
    BOOST_CHECK_EQUAL(counter.areas, 0);
    BOOST_CHECK_EQUAL(counter.relations, 0);
}

BOOST_AUTO_TEST_CASE(GivenNodeWithTwoTags_WhenToString_ThenReturnsValidRepresentation)
{
    Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 1,
    { {"key1", "value1"}, {"key2", "value2"} });

    std::string result = node.toString(*dependencyProvider.getStringTable());

    BOOST_CHECK_EQUAL(result, "[1]{key1:value1,key2:value2,}");
}

BOOST_AUTO_TEST_CASE(GivenWay_WhenVisit_ThenIncrementsCounter)
{
    Counter counter;
    Way way;

    way.accept(counter);

    BOOST_CHECK_EQUAL(counter.nodes, 0);
    BOOST_CHECK_EQUAL(counter.ways, 1);
    BOOST_CHECK_EQUAL(counter.areas, 0);
    BOOST_CHECK_EQUAL(counter.relations, 0);
}

BOOST_AUTO_TEST_CASE(GivenArea_WhenVisit_ThenIncrementsCounter)
{
    Counter counter;
    Area area;

    area.accept(counter);

    BOOST_CHECK_EQUAL(counter.nodes, 0);
    BOOST_CHECK_EQUAL(counter.ways, 0);
    BOOST_CHECK_EQUAL(counter.areas, 1);
    BOOST_CHECK_EQUAL(counter.relations, 0);
}

BOOST_AUTO_TEST_CASE(GivenRelation_WhenVisit_ThenIncrementsCounter)
{
    Counter counter;
    Relation relation;

    relation.accept(counter);

    BOOST_CHECK_EQUAL(counter.nodes, 0);
    BOOST_CHECK_EQUAL(counter.ways, 0);
    BOOST_CHECK_EQUAL(counter.areas, 0);
    BOOST_CHECK_EQUAL(counter.relations, 1);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lonnibesancon/utymap

max_issues_repo_name: daeilkim/utymap

max_forks_repo_name: daeilkim/utymap


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 BOOST_SIMD_MEMORY_DYNARRAY_HPP_INCLUDED
#define BOOST_SIMD_MEMORY_DYNARRAY_HPP_INCLUDED

#include <boost/simd/memory/details/new_allocator.hpp>
#include <boost/config.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/assert.hpp>
#include <algorithm>
#include <iterator>
#include <cstddef>
#include <memory>

namespace boost { namespace simd
{
  /*!
    @brief Runtime sized array

    Similar to std::vector, but without the ability to change the
    size and without allocators.

    @tparam T     Type of the stored element
  **/
  template<class T>
  struct dynarray
       : boost::iterator_range<T*>
  {
    dynarray(std::size_t n)
    {
      T* ptr = new T[n];
      *static_cast<boost::iterator_range<T*>*>(this) = boost::iterator_range<T*>(ptr, ptr+n);
    }

    dynarray(dynarray const& other)
    {
      void* mem = details::new_array_allocate_impl<T>(other.size()*sizeof(T), 0);
      T* ptr = static_cast<T*>(mem);
      *static_cast<boost::iterator_range<T*>*>(this) = boost::iterator_range<T*>(ptr, ptr+other.size());
      #ifndef BOOST_NO_EXCEPTIONS
      try
      {
      #endif

      #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && BOOST_WORKAROUND(BOOST_MSVC, < 1600)
        stdext::unchecked_uninitialized_copy(other.begin(), other.end(), this->begin());
      #elif BOOST_WORKAROUND(BOOST_MSVC, > 1500)
        std::uninitialized_copy(other.begin(), other.end(), stdext::make_unchecked_array_iterator(this->begin()));
      #else
        std::uninitialized_copy(other.begin(), other.end(), this->begin());
      #endif

      #ifndef BOOST_NO_EXCEPTIONS
      }
      catch(...)
      {
        details::new_array_deallocate_impl<T>(mem);
        throw;
      }
      #endif
    }

    dynarray& operator=(dynarray const& other)
    {
      BOOST_ASSERT_MSG( this->size() == other.size(), "assignment between dynarrays of different sizes" );

    #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && BOOST_WORKAROUND(BOOST_MSVC, < 1600)
      stdext::unchecked_copy(other.begin(), other.end(), this->begin());
    #elif BOOST_WORKAROUND(BOOST_MSVC, > 1500)
      std::copy(other.begin(), other.end(), stdext::make_unchecked_array_iterator(this->begin()));
    #else
      std::copy(other.begin(), other.end(), this->begin());
    #endif

      return *this;
    }

    // cast because of boost bug #8061
    std::size_t size() const
    {
      return (std::size_t)static_cast<boost::iterator_range<T*> const*>(this)->size();
    }

    ~dynarray()
    {
      delete[] this->begin();
    }
  };
} }

#endif


text:
#ifndef SLAM3D_POINTCLOUDMAPPER_TASK_HPP
#define SLAM3D_POINTCLOUDMAPPER_TASK_HPP

#include <slam3d/PointcloudMapperBase.hpp>
#include <slam3d/core/Mapper.hpp>
#include <slam3d/sensor/pcl/PointCloudSensor.hpp>

#include <envire_core/items/Item.hpp>
#include <maps/grid/MLSMap.hpp>

#include <queue>
#include <boost/thread/shared_mutex.hpp>

#include "GridConfiguration.hpp"

namespace slam3d
{
	class RockOdometry;

	class PointcloudMapper : public PointcloudMapperBase
	{
	friend class PointcloudMapperBase;
	protected:

		// Operations
		virtual bool generate_cloud();
		virtual bool generate_map();
		virtual bool optimize();
		virtual bool force_add();
		virtual bool write_graph();
		virtual bool write_envire();
		virtual bool write_ply(const std::string& folder);

		// Callbacks
		virtual bool setLog_level(boost::int32_t value);
		void transformerCallback(const base::Time &time);

		// Internal methods
		PointCloud::Ptr buildPointcloud(const VertexObjectList& vertices);
		void sendPointcloud(const VertexObjectList& vertices);
		virtual void handleNewScan(const VertexObject& scan);
		virtual void addScanToMap(PointCloudMeasurement::Ptr scan, const Transform& pose);
		virtual void clearMap();
		virtual void rebuildMap(const VertexObjectList& vertices);
		virtual void sendMap();
		bool loadPLYMap(const std::string& path);

		// Members
		slam3d::Clock* mClock;
		slam3d::Logger* mLogger;
		slam3d::Graph* mGraph;
		slam3d::Mapper* mMapper;
		slam3d::PointCloudSensor* mPclSensor;
		slam3d::Solver* mSolver;
		RockOdometry* mOdometry;
		boost::shared_mutex mGraphMutex;
		boost::shared_mutex mMapMutex;

		std::string mRobotName;
		std::string mRobotFrame;
		std::string mOdometryFrame;
		std::string mMapFrame;

		int mScansAdded;
		bool mForceAdd;

		// Parameters for creation of map-pcl
		double mScanResolution;

		// Parameters for creation of MLS
		envire::core::Item<maps::grid::MLSMapKalman> mMultiLayerMap;
		GridConfiguration mGridConf;

		// Current state of transformations
		Eigen::Affine3d mCurrentOdometry;
		Eigen::Affine3d mCurrentDrift;
		base::Time mCurrentTime;

	public:
		PointcloudMapper(std::string const& name = "slam3d::PointcloudMapper");
		PointcloudMapper(std::string const& name, RTT::ExecutionEngine* engine);
		~PointcloudMapper();

		slam3d::PointCloud::Ptr createFromRockMessage(const base::samples::Pointcloud& cloud);
		void createFromPcl(slam3d::PointCloud::ConstPtr pcl_cloud, base::samples::Pointcloud& base_cloud);
		PointCloudMeasurement::Ptr castToPointcloud(Measurement::Ptr m);

		bool configureHook();
		bool startHook();
		void updateHook();
		void errorHook();
		void stopHook();
		void cleanupHook();
	};
}

#endif


text:
#include <Eigen/Core>
#include <iostream>
#include <mathtoolbox/acquisition-functions.hpp>
#include <mathtoolbox/gaussian-process-regression.hpp>
#include <mathtoolbox/probability-distributions.hpp>
#include <timer.hpp>

using Eigen::Matrix2d;
using Eigen::MatrixXd;
using Eigen::Vector2d;
using Eigen::VectorXd;

double CalcFunc(const Vector2d& x)
{
    return mathtoolbox::GetNormalDist(3.0 * x, Vector2d::Zero(), Matrix2d::Identity(), 1.0);
}

int main(int argc, char** argv)
{
    // Define the scene setting
    constexpr int    num_samples     = 10;
    constexpr double noise_intensity = 1e-04;

    // Generate scattered data
    MatrixXd X(2, num_samples);
    VectorXd y(num_samples);
    for (int i = 0; i < num_samples; ++i)
    {
        X.col(i) = Vector2d::Random();
        y(i)     = CalcFunc(X.col(i)) + noise_intensity * (VectorXd::Random(1))(0);
    }

    // Define the kernel type
    const auto kernel_type = mathtoolbox::GaussianProcessRegressor::KernelType::ArdMatern52;

    // Instantiate the interpolation object
    mathtoolbox::GaussianProcessRegressor regressor(X, y, kernel_type);

    // Perform hyperparameter estimation
    const Eigen::Vector3d default_kernel_hyperparams(0.50, 0.50, 0.50);
    regressor.PerformMaximumLikelihood(default_kernel_hyperparams, 1e-04);

    // Calculate EI values and their derivatives
    for (int i = 0; i < 100; ++i)
    {
        constexpr int    num_dims = 2;
        constexpr double epsilon  = 1e-06;

        const VectorXd x_plus = [&]() {
            int index;
            y.maxCoeff(&index);
            return X.col(index);
        }();

        const VectorXd x = Vector2d::Random();

        const VectorXd acquisition_deriv = mathtoolbox::GetExpectedImprovementDerivative(
            x,
            [&](const VectorXd& x) { return regressor.PredictMean(x); },
            [&](const VectorXd& x) { return regressor.PredictStdev(x); },
            x_plus,
            [&](const VectorXd& x) { return regressor.PredictMeanDeriv(x); },
            [&](const VectorXd& x) { return regressor.PredictStdevDeriv(x); });

        VectorXd acquisition_numerical_deriv(num_dims);
        for (int d = 0; d < num_dims; ++d)
        {
            VectorXd delta = VectorXd::Zero(num_dims);
            delta(d)       = epsilon;

            const double value_plus = mathtoolbox::GetExpectedImprovement(
                x + delta,
                [&](const VectorXd& x) { return regressor.PredictMean(x); },
                [&](const VectorXd& x) { return regressor.PredictStdev(x); },
                x_plus);

            const double value_minus = mathtoolbox::GetExpectedImprovement(
                x - delta,
                [&](const VectorXd& x) { return regressor.PredictMean(x); },
                [&](const VectorXd& x) { return regressor.PredictStdev(x); },
                x_plus);

            acquisition_numerical_deriv(d) = value_plus - value_minus;
        }
        acquisition_numerical_deriv /= 2.0 * epsilon;

        const auto scale     = acquisition_deriv.norm();
        const auto abs_error = (acquisition_deriv - acquisition_numerical_deriv).norm();
        const auto rel_error = abs_error / scale;

        if (scale > 1e-06 && rel_error > 1e-02)
        {
            std::cout << "point location: " << x.transpose() << std::endl;
            std::cout << "analytic      : " << acquisition_deriv.transpose() << std::endl;
            std::cout << "numerical     : " << acquisition_numerical_deriv.transpose() << std::endl;
            std::cout << "error         : " << abs_error << std::endl;

            exit(1);
        }
    }

    // Calculate GP-UCB values and their derivatives
    for (int i = 0; i < 100; ++i)
    {
        constexpr int    num_dims = 2;
        constexpr double epsilon  = 1e-06;

        const double hyperparam = 1.0 + (Eigen::VectorXd::Random(1))(0);

        const VectorXd x = Vector2d::Random();

        const VectorXd acquisition_deriv = mathtoolbox::GetGaussianProcessUpperConfidenceBoundDerivative(
            x,
            [&](const VectorXd& x) { return regressor.PredictMean(x); },
            [&](const VectorXd& x) { return regressor.PredictStdev(x); },
            hyperparam,
            [&](const VectorXd& x) { return regressor.PredictMeanDeriv(x); },
            [&](const VectorXd& x) { return regressor.PredictStdevDeriv(x); });

        VectorXd acquisition_numerical_deriv(num_dims);
        for (int d = 0; d < num_dims; ++d)
        {
            VectorXd delta = VectorXd::Zero(num_dims);
            delta(d)       = epsilon;

            const double value_plus = mathtoolbox::GetGaussianProcessUpperConfidenceBound(
                x + delta,
                [&](const VectorXd& x) { return regressor.PredictMean(x); },
                [&](const VectorXd& x) { return regressor.PredictStdev(x); },
                hyperparam);

            const double value_minus = mathtoolbox::GetGaussianProcessUpperConfidenceBound(
                x - delta,
                [&](const VectorXd& x) { return regressor.PredictMean(x); },
                [&](const VectorXd& x) { return regressor.PredictStdev(x); },
                hyperparam);

            acquisition_numerical_deriv(d) = value_plus - value_minus;
        }
        acquisition_numerical_deriv /= 2.0 * epsilon;

        const auto scale     = acquisition_deriv.norm();
        const auto abs_error = (acquisition_deriv - acquisition_numerical_deriv).norm();
        const auto rel_error = abs_error / scale;

        if (scale > 1e-06 && rel_error > 1e-02)
        {
            std::cout << "point location: " << x.transpose() << std::endl;
            std::cout << "analytic      : " << acquisition_deriv.transpose() << std::endl;
            std::cout << "numerical     : " << acquisition_numerical_deriv.transpose() << std::endl;
            std::cout << "error         : " << abs_error << std::endl;

            exit(1);
        }
    }

    return 0;
}

max_stars_repo_name: yuki-koyama/mathtoolbox

max_issues_repo_name: yuki-koyama/mathtoolbox

max_forks_repo_name: yuki-koyama/mathtoolbox


text:
/*=============================================================================
    Copyright (c) 2014 Paul Fultz II
    pack.h
    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)
==============================================================================*/

#ifndef BOOST_HOF_GUARD_FUNCTION_PACK_H
#define BOOST_HOF_GUARD_FUNCTION_PACK_H

/// pack
/// ====
///
/// Description
/// -----------
///
/// The `pack` function returns a higher order function object that takes a
/// function that will be passed the initial elements. The function object is
/// a sequence that can be unpacked with `unpack_adaptor` as well. Also,
/// `pack_join` can be used to join multiple packs together.
///
/// Synopsis
/// --------
///
///     // Decay everything before capturing
///     template<class... Ts>
///     constexpr auto pack(Ts&&... xs);
///
///     // Capture lvalues by reference and rvalue reference by reference
///     template<class... Ts>
///     constexpr auto pack_forward(Ts&&... xs);
///
///     // Capture lvalues by reference and rvalues by value.
///     template<class... Ts>
///     constexpr auto pack_basic(Ts&&... xs);
///
///     // Join multiple packs together
///     template<class... Ts>
///     constexpr auto pack_join(Ts&&... xs);
///
/// Semantics
/// ---------
///
///     assert(pack(xs...)(f) == f(xs...));
///     assert(unpack(f)(pack(xs...)) == f(xs...));
///
///     assert(pack_join(pack(xs...), pack(ys...)) == pack(xs..., ys...));
///
///
/// Example
/// -------
///
///     #include <boost/hof.hpp>
///     #include <cassert>
///     using namespace boost::hof;
///
///     struct sum
///     {
///         template<class T, class U>
///         T operator()(T x, U y) const
///         {
///             return x+y;
///         }
///     };
///
///     int main() {
///         int r = pack(3, 2)(sum());
///         assert(r == 5);
///     }
///
/// See Also
/// --------
///
/// * [unpack](unpack)
///

#include <boost/hof/detail/seq.hpp>
#include <boost/hof/detail/delegate.hpp>
#include <boost/hof/detail/remove_rvalue_reference.hpp>
#include <boost/hof/detail/unwrap.hpp>
#include <boost/hof/detail/static_const_var.hpp>
#include <boost/hof/unpack_sequence.hpp>
#include <boost/hof/returns.hpp>
#include <boost/hof/alias.hpp>
#include <boost/hof/decay.hpp>

namespace boost { namespace hof { namespace detail {

template<class...>
struct pack_tag
{};

template<class T, class Tag>
struct pack_holder
: detail::alias_empty<T, Tag>
{};

template<class Seq, class... Ts>
struct pack_base;

template<class T>
struct is_copyable
: std::integral_constant<bool, (
    BOOST_HOF_IS_CONSTRUCTIBLE(T, const T&)
)>
{};

template<class T>
struct is_copyable<T&>
: std::true_type
{};

template<class T>
struct is_copyable<T&&>
: std::true_type
{};

template<class T, class Tag, class X, class... Ts, typename std::enable_if<
    is_copyable<T>::value && !std::is_lvalue_reference<T>::value
, int>::type = 0>
constexpr T pack_get(X&& x, Ts&&... xs) noexcept(BOOST_HOF_IS_NOTHROW_COPY_CONSTRUCTIBLE(T))
{
    return static_cast<T>(boost::hof::alias_value<Tag, T>(BOOST_HOF_FORWARD(X)(x), xs...));
}

template<class T, class Tag, class X, class... Ts, typename std::enable_if<
    std::is_lvalue_reference<T>::value
, int>::type = 0>
constexpr T pack_get(X&& x, Ts&&... xs) noexcept
{
    return boost::hof::alias_value<Tag, T>(x, xs...);
}

template<class T, class Tag, class X, class... Ts, typename std::enable_if<
    !is_copyable<T>::value
, int>::type = 0>
constexpr auto pack_get(X&& x, Ts&&... xs) BOOST_HOF_RETURNS
(
    boost::hof::alias_value<Tag, T>(BOOST_HOF_FORWARD(X)(x), xs...)
);

#if (defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7) || defined(_MSC_VER)
template<class... Ts>
struct pack_holder_base
: Ts::type...
{
    template<class... Xs, class=typename std::enable_if<(sizeof...(Xs) == sizeof...(Ts))>::type>
    constexpr pack_holder_base(Xs&&... xs)
    BOOST_HOF_NOEXCEPT(BOOST_HOF_AND_UNPACK(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(typename Ts::type, Xs&&)))
    : Ts::type(BOOST_HOF_FORWARD(Xs)(xs))...
    {}
#ifndef _MSC_VER
    // BOOST_HOF_INHERIT_DEFAULT(pack_holder_base, typename std::remove_cv<typename std::remove_reference<typename Ts::type>::type>::type...)
    BOOST_HOF_INHERIT_DEFAULT(pack_holder_base, typename Ts::type...)
#endif
};

template<class T>
struct pack_holder_base<T>
: T::type
{
    typedef typename T::type base;
    BOOST_HOF_INHERIT_CONSTRUCTOR(pack_holder_base, base);
};

template<class... Ts>
struct pack_holder_builder
{
    template<class T, std::size_t N>
    struct apply
    : pack_holder<T, pack_tag<seq<N>, Ts...>>
    {};
};

template<std::size_t... Ns, class... Ts>
struct pack_base<seq<Ns...>, Ts...>
: pack_holder_base<typename pack_holder_builder<Ts...>::template apply<Ts, Ns>...>
{
    typedef pack_holder_base<typename pack_holder_builder<Ts...>::template apply<Ts, Ns>...> base;
    template<class X1, class X2, class... Xs>
    constexpr pack_base(X1&& x1, X2&& x2, Xs&&... xs)
    BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(base, X1&&, X2&&, Xs&...))
    : base(BOOST_HOF_FORWARD(X1)(x1), BOOST_HOF_FORWARD(X2)(x2), BOOST_HOF_FORWARD(Xs)(xs)...)
    {}

    template<class X1, typename std::enable_if<(BOOST_HOF_IS_CONSTRUCTIBLE(base, X1)), int>::type = 0>
    constexpr pack_base(X1&& x1)
    BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(base, X1&&))
    : base(BOOST_HOF_FORWARD(X1)(x1))
    {}

    // BOOST_HOF_INHERIT_DEFAULT(pack_base, typename std::remove_cv<typename std::remove_reference<Ts>::type>::type...);
    BOOST_HOF_INHERIT_DEFAULT(pack_base, Ts...);

    BOOST_HOF_RETURNS_CLASS(pack_base);

    template<class F>
    constexpr auto operator()(F&& f) const BOOST_HOF_RETURNS
    (
        f(boost::hof::detail::pack_get<Ts, pack_tag<seq<Ns>, Ts...>>(*BOOST_HOF_CONST_THIS, f)...)
    );

    typedef std::integral_constant<std::size_t, sizeof...(Ts)> fit_function_param_limit;

    template<class F>
    struct apply
    : F::template apply<Ts...>
    {};
};

template<class T>
struct pack_base<seq<0>, T>
: pack_holder_base<pack_holder<T, pack_tag<seq<0>, T>>>
{
    typedef pack_holder_base<pack_holder<T, pack_tag<seq<0>, T>>> base;

    template<class X1, typename std::enable_if<(BOOST_HOF_IS_CONSTRUCTIBLE(base, X1)), int>::type = 0>
    constexpr pack_base(X1&& x1)
    BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(base, X1&&))
    : base(BOOST_HOF_FORWARD(X1)(x1))
    {}

    BOOST_HOF_INHERIT_DEFAULT(pack_base, T);

    BOOST_HOF_RETURNS_CLASS(pack_base);

    template<class F>
    constexpr auto operator()(F&& f) const BOOST_HOF_RETURNS
    (
        f(boost::hof::detail::pack_get<T, pack_tag<seq<0>, T>>(*BOOST_HOF_CONST_THIS, f))
    );

    typedef std::integral_constant<std::size_t, 1> fit_function_param_limit;

    template<class F>
    struct apply
    : F::template apply<T>
    {};
};

#else

template<std::size_t... Ns, class... Ts>
struct pack_base<seq<Ns...>, Ts...>
: pack_holder<Ts, pack_tag<seq<Ns>, Ts...>>::type...
{
    // BOOST_HOF_INHERIT_DEFAULT(pack_base, typename std::remove_cv<typename std::remove_reference<Ts>::type>::type...);
    BOOST_HOF_INHERIT_DEFAULT(pack_base, Ts...);

    template<class... Xs, BOOST_HOF_ENABLE_IF_CONVERTIBLE_UNPACK(Xs&&, typename pack_holder<Ts, pack_tag<seq<Ns>, Ts...>>::type)>
    constexpr pack_base(Xs&&... xs)
    BOOST_HOF_NOEXCEPT(BOOST_HOF_AND_UNPACK(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(typename pack_holder<Ts, pack_tag<seq<Ns>, Ts...>>::type, Xs&&)))
    : pack_holder<Ts, pack_tag<seq<Ns>, Ts...>>::type(BOOST_HOF_FORWARD(Xs)(xs))...
    {}

    // typedef pack_base<seq<Ns...>, Ts...> self_t;

    BOOST_HOF_RETURNS_CLASS(pack_base);

    template<class F>
    constexpr auto operator()(F&& f) const BOOST_HOF_RETURNS
    (
        f(boost::hof::detail::pack_get<Ts, pack_tag<seq<Ns>, Ts...>>(*BOOST_HOF_CONST_THIS, f)...)
    );

    typedef std::integral_constant<std::size_t, sizeof...(Ts)> fit_function_param_limit;

    template<class F>
    struct apply
    : F::template apply<Ts...>
    {};
};

#endif

template<>
struct pack_base<seq<> >
{
    template<class F>
    constexpr auto operator()(F&& f) const BOOST_HOF_RETURNS
    (f());

    typedef std::integral_constant<std::size_t, 0> fit_function_param_limit;

    template<class F>
    struct apply
    : F::template apply<>
    {};
};

#define BOOST_HOF_DETAIL_UNPACK_PACK_BASE(ref, move) \
template<class F, std::size_t... Ns, class... Ts> \
constexpr auto unpack_pack_base(F&& f, pack_base<seq<Ns...>, Ts...> ref x) \
BOOST_HOF_RETURNS(f(boost::hof::alias_value<pack_tag<seq<Ns>, Ts...>, Ts>(move(x), f)...))
BOOST_HOF_UNARY_PERFECT_FOREACH(BOOST_HOF_DETAIL_UNPACK_PACK_BASE)

template<class P1, class P2>
struct pack_join_base;

// TODO: Extend to join more than two packs at a time
template<std::size_t... Ns1, class... Ts1, std::size_t... Ns2, class... Ts2>
struct pack_join_base<pack_base<seq<Ns1...>, Ts1...>, pack_base<seq<Ns2...>, Ts2...>>
{
    static constexpr long total_size = sizeof...(Ts1) + sizeof...(Ts2);
    typedef pack_base<typename detail::gens<total_size>::type, Ts1..., Ts2...> result_type;

    template<class P1, class P2>
    static constexpr result_type call(P1&& p1, P2&& p2)
    BOOST_HOF_RETURNS_DEDUCE_NOEXCEPT(
        result_type(
            boost::hof::detail::pack_get<Ts1, pack_tag<seq<Ns1>, Ts1...>>(BOOST_HOF_FORWARD(P1)(p1))...,
            boost::hof::detail::pack_get<Ts2, pack_tag<seq<Ns2>, Ts2...>>(BOOST_HOF_FORWARD(P2)(p2))...)
    )
    {
        return result_type(
            boost::hof::detail::pack_get<Ts1, pack_tag<seq<Ns1>, Ts1...>>(BOOST_HOF_FORWARD(P1)(p1))...,
            boost::hof::detail::pack_get<Ts2, pack_tag<seq<Ns2>, Ts2...>>(BOOST_HOF_FORWARD(P2)(p2))...);
    }
};

template<class P1, class P2>
struct pack_join_result
: pack_join_base<
    typename std::remove_cv<typename std::remove_reference<P1>::type>::type,
    typename std::remove_cv<typename std::remove_reference<P2>::type>::type
>
{};

struct pack_basic_f
{
    template<class... Ts>
    constexpr auto operator()(Ts&&... xs) const BOOST_HOF_RETURNS
    (
        pack_base<typename gens<sizeof...(Ts)>::type, typename remove_rvalue_reference<Ts>::type...>(BOOST_HOF_FORWARD(Ts)(xs)...)
    );
};

struct pack_forward_f
{
    template<class... Ts>
    constexpr auto operator()(Ts&&... xs) const BOOST_HOF_RETURNS
    (
        pack_base<typename gens<sizeof...(Ts)>::type, Ts&&...>(BOOST_HOF_FORWARD(Ts)(xs)...)
    );
};

struct pack_f
{
    template<class... Ts>
    constexpr auto operator()(Ts&&... xs) const BOOST_HOF_RETURNS
    (
        pack_basic_f()(boost::hof::decay(BOOST_HOF_FORWARD(Ts)(xs))...)
    );
};

template<class P1, class P2>
constexpr typename pack_join_result<P1, P2>::result_type make_pack_join_dual(P1&& p1, P2&& p2)
BOOST_HOF_RETURNS_DEDUCE_NOEXCEPT(pack_join_result<P1, P2>::call(BOOST_HOF_FORWARD(P1)(p1), BOOST_HOF_FORWARD(P2)(p2)))
{
    return pack_join_result<P1, P2>::call(BOOST_HOF_FORWARD(P1)(p1), BOOST_HOF_FORWARD(P2)(p2));
}

// Manually compute join return type to make older gcc happy
template<class... Ts>
struct join_type;

template<class T>
struct join_type<T>
{
    typedef T type;
};

template<class T, class... Ts>
struct join_type<T, Ts...>
{
    typedef typename pack_join_result<T, typename join_type<Ts...>::type>::result_type type;
};

template<class P1>
constexpr P1 make_pack_join(P1&& p1) BOOST_HOF_NOEXCEPT_CONSTRUCTIBLE(P1, P1&&)
{
    return BOOST_HOF_FORWARD(P1)(p1);
}

template<class P1, class... Ps>
constexpr typename join_type<P1, Ps...>::type make_pack_join(P1&& p1, Ps&&... ps)
BOOST_HOF_RETURNS_DEDUCE_NOEXCEPT(make_pack_join_dual(BOOST_HOF_FORWARD(P1)(p1), make_pack_join(BOOST_HOF_FORWARD(Ps)(ps)...)))
{
    return make_pack_join_dual(BOOST_HOF_FORWARD(P1)(p1), make_pack_join(BOOST_HOF_FORWARD(Ps)(ps)...));
}

struct pack_join_f
{

    template<class... Ps>
    constexpr auto operator()(Ps&&... ps) const BOOST_HOF_RETURNS
    (
        make_pack_join(BOOST_HOF_FORWARD(Ps)(ps)...)
    );
};

}

BOOST_HOF_DECLARE_STATIC_VAR(pack_basic, detail::pack_basic_f);
BOOST_HOF_DECLARE_STATIC_VAR(pack_forward, detail::pack_forward_f);
BOOST_HOF_DECLARE_STATIC_VAR(pack, detail::pack_f);

BOOST_HOF_DECLARE_STATIC_VAR(pack_join, detail::pack_join_f);

template<class T, class... Ts>
struct unpack_sequence<detail::pack_base<T, Ts...>>
{
    template<class F, class P>
    constexpr static auto apply(F&& f, P&& p) BOOST_HOF_RETURNS
    (
        boost::hof::detail::unpack_pack_base(BOOST_HOF_FORWARD(F)(f), BOOST_HOF_FORWARD(P)(p))
    );
};

}} // namespace boost::hof

#endif


text:
#ifndef SHASTA_ASSEMBLER_OPTIONS_HPP
#define SHASTA_ASSEMBLER_OPTIONS_HPP

// Boost libraries.
#include <boost/program_options.hpp>

// Standard library.
#include "iostream.hpp"
#include "string.hpp"
#include "vector.hpp"

namespace shasta {
    class AssemblerOptions;
}

// Class AssemblyOptions contains one nested class
// corresponding to each group of options.
class shasta::AssemblerOptions {
public:

    // Options only allowed on the command line and not in the configuration file.
    class CommandLineOnlyOptions {
    public:
        string configFileName;
        vector <string> inputFileNames;
        string assemblyDirectory;
        string command;
        string memoryMode;
        string memoryBacking;
        uint32_t threadCount;
        bool useGpu;
#ifdef SHASTA_HTTP_SERVER
        string exploreAccess;
        uint16_t port;
#endif
    };
    CommandLineOnlyOptions commandLineOnlyOptions;

    // Options in the [Reads] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "Reads.".
    class ReadsOptions {
    public:
        int minReadLength;
        class PalindromicReadOptions {
        public:
            int maxSkip;
            int maxDrift;
            int maxMarkerFrequency;
            double alignedFractionThreshold;
            double nearDiagonalFractionThreshold;
            int deltaThreshold;
            void write(ostream&) const;
        };
        PalindromicReadOptions palindromicReads;

        void write(ostream&) const;
    };
    ReadsOptions readsOptions;

    // Options in the [Kmers] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "Kmers.".
    class KmersOptions {
    public:
        int k;
        double probability;
        bool suppressHighFrequencyMarkers;
        double enrichmentThreshold;
        void write(ostream&) const;
    };
    KmersOptions kmersOptions;

    // Options in the [MinHash] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "MinHash.".
    class MinHashOptions {
    public:
        int version;
        int m;
        double hashFraction;
        int minHashIterationCount;
        int minBucketSize;
        int maxBucketSize;
        int minFrequency;
        bool allPairs;
        void write(ostream&) const;
    };
    MinHashOptions minHashOptions;

    // Options in the [Align] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "Align.".
    class AlignOptions {
    public:
        int maxSkip;
        int maxDrift;
        int maxTrim;
        int maxMarkerFrequency;
        int minAlignedMarkerCount;
        void write(ostream&) const;
    };
    AlignOptions alignOptions;

    // Options in the [ReadGraph] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "ReadGraph.".
    class ReadGraphOptions {
    public:
        int maxAlignmentCount;
        int minComponentSize;
        int maxChimericReadDistance;
        void write(ostream& ) const;
    };
    ReadGraphOptions readGraphOptions;

    // Options in the [MarkerGraph] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "MarkerGraph.".
    class MarkerGraphOptions {
    public:
        int minCoverage;
        int maxCoverage;
        int lowCoverageThreshold;
        int highCoverageThreshold;
        int maxDistance;
        int edgeMarkerSkipThreshold;
        int pruneIterationCount;
        string simplifyMaxLength;
        vector<size_t> simplifyMaxLengthVector;
        void parseSimplifyMaxLength();
        void write(ostream&) const;
    };
    MarkerGraphOptions markerGraphOptions;

    // Options in the [Assembly] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "Assembly.".
    class AssemblyOptions {
    public:
        int strategy;   // 0: bubble removal, 1: phasing
        int crossEdgeCoverageThreshold;
        int markerGraphEdgeLengthThresholdForConsensus;
        string consensusCaller;
        bool useMarginPhase;
        bool storeCoverageData;
        int storeCoverageDataCsvLengthThreshold;
        void write(ostream&) const;
    };
    AssemblyOptions assemblyOptions;

    // Options in the [Phasing] section of the configuration file.
    // Can also be entered on the command line with option names
    // beginning with "Phasing.".
    class PhasingOptions {
    public:
        double phasingSimilarityThreshold;
        int maxNeighborCount;
        void write(ostream& ) const;
    };
    PhasingOptions phasingOptions;

    // Constructor.
    AssemblerOptions(int argumentCount, const char** arguments);

    // Add configurable options to the Boost option description object.
    void addCommandLineOnlyOptions();
    void addConfigurableOptions();

    // Write the options as a config file.
    void write(ostream&) const;

    // Boost program_options library objects.
    boost::program_options::options_description commandLineOnlyOptionsDescription;
    boost::program_options::options_description configurableOptionsDescription;
    boost::program_options::options_description allOptionsDescription;

    // This one is the same as allOptionsDescription, with
    // "--invalidOption" added to capture invalid positional options.
    vector<string> invalidPositionalOptions;
    boost::program_options::options_description allOptionsIncludingInvalidDescription;

    // Function to convert a bool to True or False for better
    // compatibility with Python scripts.
    static string convertBoolToPythonString(bool);

};

#endif

max_stars_repo_name: tijyojwad/shasta

max_issues_repo_name: tijyojwad/shasta

max_forks_repo_name: tijyojwad/shasta