text:
#include "DynamicAllocationTroubleshooter.h"

#include <boost/stacktrace.hpp>
#include <boost/scope_exit.hpp>

#include <iostream>

namespace
{
    const size_t framesToSkipDefaultValue = 0;
    const size_t maxDepthDefaultValue = 100;
    std::atomic<bool> insideNewDelete = false;
}

DynamicAllocationTroubleshooter::DynamicAllocationTroubleshooter() : m_framesToSkip(framesToSkipDefaultValue), m_framesMaxDepth(maxDepthDefaultValue)
{
}

void DynamicAllocationTroubleshooter::setFramesToSkip(size_t framesToSkip)
{
    m_framesToSkip = framesToSkip;
}

size_t DynamicAllocationTroubleshooter::getFramesToSkip() const
{
    return m_framesToSkip;
}

void DynamicAllocationTroubleshooter::setFramesMaxDepth(size_t framesMaxDepth)
{
    m_framesMaxDepth = framesMaxDepth;
}

size_t DynamicAllocationTroubleshooter::getFramesMaxDepth() const
{
    return m_framesMaxDepth;
}

size_t DynamicAllocationTroubleshooter::getStackTraceCacheSize() const
{
    std::lock_guard lck(m_mutex);
    return m_stackTraceCache.size();
}

void DynamicAllocationTroubleshooter::addToStackTraceCache(const std::pair<const void*, std::string> traceRecord)
{
    std::lock_guard lck(m_mutex);
    m_stackTraceCache.emplace(traceRecord);
}

void DynamicAllocationTroubleshooter::removeFromStackTraceCache(const void* traceKey)
{
    std::lock_guard lck(m_mutex);
    m_stackTraceCache.erase(traceKey);
}

void DynamicAllocationTroubleshooter::enableMonitoring()
{
    m_monitorAllocations = true;
}

void DynamicAllocationTroubleshooter::disableMonitoring()
{
    m_monitorAllocations = false;
}

bool DynamicAllocationTroubleshooter::isMonitoringEnabled() const
{
    return m_monitorAllocations;
}

void DynamicAllocationTroubleshooter::setLogLevel(DynamicAllocationTroubleshooter::LogLevel logLevel)
{
    m_logLevel = logLevel;
}

DynamicAllocationTroubleshooter::LogLevel DynamicAllocationTroubleshooter::getLogLevel() const
{
    return m_logLevel;
}

void* operator new(size_t requestedSize)
{
    void* allocationAddress = std::malloc(requestedSize);
    if (allocationAddress)
    {
        auto& allocationTroubleshooter = DynamicAllocationTroubleshooter::getInstance();
        if (allocationTroubleshooter.isMonitoringEnabled() && !insideNewDelete)
        {
            insideNewDelete = true;
            BOOST_SCOPE_EXIT(&insideNewDelete) {
                insideNewDelete = false;
            } BOOST_SCOPE_EXIT_END

            auto stackTrace = boost::stacktrace::stacktrace(allocationTroubleshooter.getFramesToSkip(), allocationTroubleshooter.getFramesMaxDepth());
            const auto& traceString = boost::stacktrace::detail::to_string(&stackTrace.as_vector()[0], stackTrace.size());
            allocationTroubleshooter.addToStackTraceCache(std::pair(allocationAddress, traceString));

            switch(allocationTroubleshooter.getLogLevel())
            {
                case DynamicAllocationTroubleshooter::LogLevel::Debug:
                {
                }
                break;
                case DynamicAllocationTroubleshooter::LogLevel::LogFullStackTrace:
                {
                }
                break;
                case DynamicAllocationTroubleshooter::LogLevel::LogCallerLines:
                {
                }
                break;
                case DynamicAllocationTroubleshooter::LogLevel::LogOnlyCounting:
                {
                    std::cout << "Operator new is called (+) " << std::endl;
                }
                break;
                case DynamicAllocationTroubleshooter::LogLevel::NoLogs:
                {
                }
                break;
                default:
                {
                    assert(!"New Log level is added and is unhandled");
                }
                break;
            }
        }

        return allocationAddress;
    }
    else
    {
        throw std::bad_alloc{};
    }
}

void operator delete(void* ptr) noexcept
{
    auto& allocationTroubleshooter = DynamicAllocationTroubleshooter::getInstance();
    if (allocationTroubleshooter.isMonitoringEnabled() && !insideNewDelete)
    {
        insideNewDelete = true;
        BOOST_SCOPE_EXIT(&insideNewDelete) {
            insideNewDelete = false;
        } BOOST_SCOPE_EXIT_END

        auto stackTrace = boost::stacktrace::stacktrace(allocationTroubleshooter.getFramesToSkip(), allocationTroubleshooter.getFramesMaxDepth());
        const auto& traceString = boost::stacktrace::detail::to_string(&stackTrace.as_vector()[0], stackTrace.size());
        allocationTroubleshooter.removeFromStackTraceCache(ptr);

        switch(allocationTroubleshooter.getLogLevel())
        {
            case DynamicAllocationTroubleshooter::LogLevel::Debug:
            {
            }
            break;
            case DynamicAllocationTroubleshooter::LogLevel::LogFullStackTrace:
            {
            }
            break;
            case DynamicAllocationTroubleshooter::LogLevel::LogCallerLines:
            {
            }
            break;
            case DynamicAllocationTroubleshooter::LogLevel::LogOnlyCounting:
            {
                std::cout << "Operator delete is called (-)\nstackTraceCache.size() is "
                          << allocationTroubleshooter.getStackTraceCacheSize() << std::endl;
            }
            break;
            case DynamicAllocationTroubleshooter::LogLevel::NoLogs:
            {
            }
            break;
            default:
            {
                assert(!"New Log level is added and is unhandled");
            }
            break;
        }
    }
    std::free(ptr);
}

max_stars_repo_name: Tuxedo-Mask/CallStackTracer

max_issues_repo_name: Tuxedo-Mask/CallStackTracer

max_forks_repo_name: Tuxedo-Mask/CallStackTracer


text:
//==================================================================================================
/*!
  @file
  @copyright 2016 NumScale SAS

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

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

 /*!
  @ingroup group-euler
    Function object implementing erfc capabilities

  Computes the complementary error function
   \f$\displaystyle \frac{2}{\sqrt\pi}\int_{x}^{\infty} e^{-t^2}\mbox{d}t\f$

  @par Semantic:

  For every parameter of floating type T

  @code
  T r = erfc(x);
  @endcode

  is similar to:

  @code
  T0 r = oneminus(erf(x));
  @endcode

  @par Decorators

  std_ for floating entries provides access to @c std::erfc

  @see erf, erfcx, oneminus

  **/
  Value erfc(Value const & v0);
} }
#endif

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

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef PERSISTENTMAP_HPP
#define PERSISTENTMAP_HPP

#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/set.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <functional>
#include <utility>

using namespace boost::interprocess;

// From the boost documentation.
typedef allocator<char, managed_mapped_file::segment_manager> CharAllocator;
typedef basic_string<char, std::char_traits<char>, CharAllocator> MyShmString;
typedef allocator<MyShmString, managed_mapped_file::segment_manager>
  StringAllocator;

template <typename ValueType>
class PersistentVector {
  typedef allocator<ValueType, managed_mapped_file::segment_manager>
    PersistentVectorAllocator;
  typedef set<ValueType, std::less<ValueType>, PersistentVectorAllocator>
    InnerPersistentVector;
  public:
  PersistentVector(
    const std::string& vectorname, std::shared_ptr<managed_mapped_file>& segment,
    bool create) :
    vectorname_(vectorname),
    segment_(segment),
    allocator_(segment_->get_segment_manager()) {
    Init(create);
  }

  void Init(bool create) {
    if (create) {
      vector_ = segment_->construct<InnerPersistentVector>(vectorname_.c_str())
        (std::less<ValueType>(), allocator_);
    } else {
      vector_ = segment_->find<InnerPersistentVector>(vectorname_.c_str()).first;
    }
  }
  InnerPersistentVector* getVector() const { return vector_; };

private:
  std::string vectorname_;
  std::shared_ptr<managed_mapped_file> segment_;
  PersistentVectorAllocator allocator_;
  vector<ValueType, PersistentVectorAllocator>* vector_;
};

template <typename ValueType>
class PersistentSet {
  typedef allocator<ValueType, managed_mapped_file::segment_manager>
    PersistentSetAllocator;
  typedef set<ValueType, std::less<ValueType>, PersistentSetAllocator>
    InnerPersistentSet;

public:
  PersistentSet(
    const std::string& setname, std::shared_ptr<managed_mapped_file>& segment,
    bool create) :
    setname_(setname),
    segment_(segment),
    allocator_(segment_->get_segment_manager()) {
    Init(create);
  }

  void Init(bool create) {
    if (create) {
      set_ = segment_->construct<InnerPersistentSet>(setname_.c_str())
        (std::less<ValueType>(), allocator_);
    } else {
      set_ = segment_->find<InnerPersistentSet>(setname_.c_str()).first;
    }
  }
  InnerPersistentSet* getSet() const { return set_; };

private:
  std::string setname_;
  std::shared_ptr<managed_mapped_file> segment_;
  PersistentSetAllocator allocator_;
  set<ValueType, std::less<ValueType>, PersistentSetAllocator>* set_;
};

template <typename KeyType, typename ValueType>
class PersistentMap {
  typedef std::pair<const KeyType, ValueType> PairType;
  typedef allocator<PairType, managed_mapped_file::segment_manager>
    PersistentMapAllocator;
  typedef map<KeyType, ValueType, std::less<KeyType>, PersistentMapAllocator>
    InnerPersistentMap;
public:
  PersistentMap(const std::string& filename, bool create) :
    filename_(filename),
    mapname_("map"),
    segment_(new managed_mapped_file(open_or_create, filename.c_str(),
      1ul << 24)),
    allocator_(segment_->get_segment_manager()) {
    Init(create);
  }

  PersistentMap(
    const std::string& mapname, std::shared_ptr<managed_mapped_file>& segment,
      bool create) :
      filename_(""),
      mapname_(mapname),
      segment_(segment),
      allocator_(segment_->get_segment_manager()) {
    Init(create);
  }

  void Init(bool create) {
    if (create) {
      map_ = segment_->construct<InnerPersistentMap>(mapname_.c_str())
        (std::less<KeyType>(), allocator_);
    } else {
      map_ = segment_->find<InnerPersistentMap>(mapname_.c_str()).first;
    }
  }

  InnerPersistentMap* getMap() const { return map_; }

  std::shared_ptr<managed_mapped_file>& getSegment() { return segment_; }
private:
  std::string filename_;
  std::string mapname_;
  std::shared_ptr<managed_mapped_file> segment_;
  PersistentMapAllocator allocator_;
  map<KeyType, ValueType, std::less<KeyType>,
    PersistentMapAllocator>* map_;
};

#endif // PERSISTENTMAP_HPP

max_stars_repo_name: wmkhoo/functionsimsearch

max_issues_repo_name: wmkhoo/functionsimsearch

max_forks_repo_name: wmkhoo/functionsimsearch


text:
//    Copyright 2017 Rainer Gemulla
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
/** \file
 *
 * Illustrates matrix factorization with alternating least squares. We first creates factors and
 * then a data matrix
 * from these factors. THis process ensures that we know the best factorization of the input.
 * We then try to reconstruct the factors.
 */
#include <iostream>

#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <boost/random/uniform_real.hpp>

#include <util/evaluation.h>
#include <util/io.h>

#include <mf/mf.h>

#include <mf/loss/nzsl.h>
#include <mf/loss/l2.h>

using namespace std;
using namespace mf;
using namespace rg;
using namespace boost::numeric::ublas;

log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));

int main(int argc, char* argv[]) {
#ifndef NDEBUG
	LOG4CXX_WARN(logger, "Warning: Debug mode activated (runtimes may be slow).");
#endif

	// parameters for the factorization
	mf_size_type size1 = 10000;
	mf_size_type size2 = 10000;
	mf_size_type nnz = 1000000;
	double sigma = 1; // standard deviation
	double lambda = 1/sigma/sigma;
	mf_size_type r = 10;

	// parameters for ALS
	unsigned epochs = 20;
	AlsRegularizer regularizer = ALS_L2;
	typedef SumLoss<NzslLoss, L2Loss> Loss;
	typedef NzRmseLoss TestLoss;
	Loss loss((NzslLoss()), L2Loss(lambda));
	TestLoss testLoss;
	mf_size_type testNnz = nnz/100;

	BalanceType type = BALANCE_L2;;
	BalanceMethod method = BALANCE_SIMPLE;

	// generate original factors by sampling from a normal(0,sigma) distribution
	Random32 random; // note: this takes a default seed (not randomized!)
	DenseMatrix wIn(size1, r);
	DenseMatrixCM hIn(r, size2);
	generateRandom(wIn, random, boost::normal_distribution<>(0, sigma));
	generateRandom(hIn, random, boost::normal_distribution<>(0, sigma));

	// generate a sparse matrix by selecting random entries from the generated factors
	// and add small Gaussian noise
	SparseMatrix v;
	generateRandom(v, nnz, wIn, hIn, random);
	addRandom(v, random, boost::normal_distribution<>(0, 0.1));
	LOG4CXX_INFO(logger, "Data matrix: "
		<< v.size1() << " x " << v.size2() << ", " << v.nnz() << " nonzeros");
	v.sort();
	LOG4CXX_INFO(logger, "Loss with original factors: " << loss((FactorizationData<>(v, wIn, hIn))));
	SparseMatrixCM vc;
	copyCm(v, vc);

	// create a test matrix (without noise)
	SparseMatrix vTest;
	generateRandom(vTest, testNnz, wIn, hIn, random);
	LOG4CXX_INFO(logger, "Test matrix: "
		<< v.size1() << " x " << v.size2() << ", " << vTest.nnz() << " nonzeros");

	// generate initial factors by sampling from a uniform[-0.5,0.5] distribution
	DenseMatrix w(size1, r);
	DenseMatrixCM h(r, size2);
	generateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));
	generateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));

	// print the test loss
	LOG4CXX_INFO(logger, "Initial test loss: "
			<< testLoss(FactorizationData<>(vTest,w,h)));

	FactorizationData<> testJob(vTest,w,h);

	// initialize
	FactorizationData<> data(v, w, h, 1, &vc);
	Trace trace;
	// here add fields to Trace
	//trace.addField("balancing-type", type);
	//trace.addField("balancing-method", method);
	Timer t;

	// run ALS to try to reconstruct the original factors
	t.start();
//	alsNzsl(data, epochs, trace, lambda, regularizer, rescale);
	alsNzsl(data, epochs, trace, lambda, regularizer, type, method ,&testJob);
	t.stop();
	LOG4CXX_INFO(logger, "Total time: " << t);

	// print the test loss
	LOG4CXX_INFO(logger, "Final test loss: "
			<< testLoss(FactorizationData<>(vTest,w,h)));

	// write trace to an R file
	string typeString, methodString;
	switch (type) {
	case BALANCE_NONE:
		typeString = "None";
		break;
	case BALANCE_L2:
		typeString = "L2";
		break;
	case BALANCE_NZL2:
		typeString = "Nzl2";
		break;
	}
	switch (method) {
	case BALANCE_SIMPLE:
		methodString = "Simple";
		break;
	case BALANCE_OPTIMAL:
		methodString = "Optimal";
		break;
	}
	string filename = "/tmp/als-trace.R";
	LOG4CXX_INFO(logger, "Writing trace to " << filename);
	trace.toRfile(filename, "als");

	return 0;
}

ext: cc

max_stars_repo_name: Hui-Li/DSGDPP

max_issues_repo_name: Hui-Li/DSGDPP

max_forks_repo_name: Hui-Li/DSGDPP


text:
/**
 * Copyright (c) 2019 Melown Technologies SE
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "gdaldriversmodule.hpp"

#include <ogr_core.h>

#include <sstream>
#include <string>
#include <vector>
#include <type_traits>
#include <cstdint>

#include <boost/python.hpp>
#include <boost/python/scope.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "dbglog/dbglog.hpp"

#include "geo/geodataset.hpp"
#include "geo/gdal.hpp"
#include "geo/cv.hpp"

#include "imgproc/python/numpy.hpp"

#undef PYSUPPORT_MODULE_IMPORT_API
#define PYSUPPORT_MODULE_IMPORT_API 2
#include "pysupport/package.hpp"
#undef PYSUPPORT_MODULE_IMPORT_API

#include "pysupport/class.hpp"
#include "pysupport/enum.hpp"
#include "pysupport/converters.hpp"

#include "../register.hpp"
#include "../blender.hpp"

namespace bp = boost::python;
namespace bpc = boost::python::converter;
namespace fs = boost::filesystem;

namespace gdal_drivers { namespace py {

struct BlendingDataset {
    using Config = gdal_drivers::BlendingDataset::Config;

    BlendingDataset(const Config &config)
        : dset(geo::GeoDataset::use
               (gdal_drivers::BlendingDataset::create(config)))
    {}

    geo::GeoDataset dset;
};

template <typename Enum>
typename std::underlying_type<Enum>::type rawEnumValue(Enum value)
{
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

bp::object openGdal(const BlendingDataset::Config &config)
{
    auto gdal(bp::import("osgeo.gdal"));

    const auto version
        (bp::extract<std::string>(gdal.attr("__version__"))());

    if (version != GDAL_RELEASE_NAME) {
        ::PyErr_SetString
            (::PyExc_RuntimeError
             , "osgeo.gdal links against different gdal library version");
        bp::throw_error_already_set();
    }

    std::ostringstream os;
    os << "blender:ptr=" << static_cast<const void*>(&config);
    return gdal.attr("OpenEx")
        (os.str().c_str(), rawEnumValue(GA_ReadOnly)
         , std::vector<std::string>{"Blender"});
}

bp::object openRasterio(const BlendingDataset::Config &config)
{
    auto rasterio(bp::import("rasterio"));

    const auto version
        (bp::extract<std::string>(rasterio.attr("gdal_version")())());
    if (version != GDAL_RELEASE_NAME) {
        ::PyErr_SetString
            (::PyExc_RuntimeError
             , "rasterio links against different gdal library version");
        bp::throw_error_already_set();
    }

    std::ostringstream os;
    os << "blender:ptr=" << static_cast<const void*>(&config);
    return rasterio.attr("open")(os.str().c_str(), "r", "Blender");
}

bp::object fetch(const geo::GeoDataset &dset
                 , const boost::optional< ::GDALDataType> &type
                 , bool withMask = false)
{
    /** Load all data from underlying dataset as-is and wrap in ND array
     *  Do not reorder channels.
     */
    geo::GeoDataset::ReadOptions options;
    options.channelsAsIs = true;

    /** Use native dataset's data type or requested one.
     */
    const int depth(type ? geo::gdal2cv(*type) : -1);

    auto data(imgproc::py::asNumpyArray(dset.readData(depth, 0, options)));
    if (!withMask) { return data; }

    auto mask(imgproc::py::asNumpyArray(dset.fetchMask()));
    return bp::make_tuple(data, mask);
}

inline geo::OptionalNodataValue asOptNodata(const geo::NodataValue &nodata)
{
    if (nodata) { return nodata; }
    return boost::none;
}

bp::object readDataset(const BlendingDataset &ds
                       , const boost::optional< ::GDALDataType> &type
                       , bool withMask)
{
    return fetch(ds.dset, type, withMask);
}

const char *readDoc(R"R(Returns whole content of dataset as a single ndarray.

Dimensions are in C-style row-major order:
    * multi-channel datasets: (row, columns, channel)
    * single-channel datasets: (row, column)

Channel order is kept as in the original dataset. If data type is not specified
the the native datatype is used.

If withMask keyword argument is False (default) only content array is
returned. If withMask keyword argument is set to True the tuple of (content,
mask) is retuned instead where mask is Byte ndarray containing validity
information.

Arguments:
    * geo.GDALDataType type: output data type (defaults to source data type
    * withMask: validity mask is read as well (defaults to False)

Returns:
    ndarray or (ndarray, ndarray)
)R");

bp::object warpDataset(const BlendingDataset &ds
                       , const math::Extents2 &extents
                       , const boost::optional<geo::SrsDefinition> &srs
                       , const boost::optional<math::Size2i> &size
                       , const boost::optional< ::GDALDataType> &warpType
                       , const boost::optional< ::GDALDataType> &type
                       , const boost::optional
                       <geo::GeoDataset::Resampling> &resampling
                       , const boost::optional<double> &nodata
                       , bool withMask)
{
    // warp and output types
    const auto wt(warpType ? warpType : type);
    boost::optional< ::GDALDataType> ot;
    if (warpType != type) { ot = type; }

    auto warped(geo::GeoDataset::deriveInMemory
                (ds.dset, srs ? srs.value() : ds.dset.srs()
                 , size, extents, wt, asOptNodata(nodata)));

    ds.dset.warpInto(warped, resampling);
    return fetch(warped, ot, withMask);
}

const char *warpDoc(R"R(Returns whole content of warped dataset

See read() method documentation for output properties.

Data type of the warp result is either warpType or type or dataset's type. Type
of the read result is the same as warp result unless type and warp types are
different.

Arguments:
    * math.Extents2 extents: extents of warped dataset
    * geo.SrsDefinition srs: SRS of warped dataset (defaults to source SRS)
    * math.Size2i size: pixel size of warped dataset (computed if not set)
    * geo.GDALDataType warpType: warp data type (if different from output)
    * geo.GDALDataType type: output data type (defaults to source data type
    * geo.GeoDataset.Resampling resampling: resampling method
                                            (defaults to nerest neighbor)
    * double nodata: override nodata value in output (defaults to
                     source nodata value)
    * withMask: see read() method documentation (default to False)

Returns:
    ndarray or (ndarray, ndarray)
)R");

template <typename T> boost::optional<T> opt() { return boost::optional<T>(); }

std::string Config_repr(const gdal_drivers::BlendingDataset::Config &config)
{
    std::ostringstream os;
    os << std::fixed;
    gdal_drivers::writeConfig(os, config);
    return os.str();
}

} } // namespace gdal_drivers::py

BOOST_PYTHON_MODULE(melown_gdaldrivers)
{
    using namespace bp;
    namespace py = gdal_drivers::py;
    using py::opt;

    // blender
    auto BlendingDataset = class_<py::BlendingDataset, boost::noncopyable>
        ("BlendingDataset", init<const py::BlendingDataset::Config&>())

        .def("read", &py::readDataset
             , (bp::arg("type") = opt< ::GDALDataType>()
                , bp::arg("withMask") = false
             )
             , py::readDoc)
        .def("warp", &py::warpDataset
             , (bp::arg("extents")
                , bp::arg("srs") = opt<geo::SrsDefinition>()
                , bp::arg("size") = opt<math::Size2i>()
                , bp::arg("warpType") = opt< ::GDALDataType>()
                , bp::arg("type") = opt< ::GDALDataType>()
                , bp::arg("resampling") = opt<geo::GeoDataset::Resampling>()
                , bp::arg("nodata") = opt<double>()
                , bp::arg("withMask") = false
                )
             , py::warpDoc)

        .def("gdal", &py::openGdal
             , "Opens blending dataset as an osgeo.gdal.Dataset.")
        .staticmethod("gdal")

        .def("rasterio", &py::openRasterio
             , "Opens blending dataset as a rasterio.DatasetReader.")
        .staticmethod("rasterio")
        ;

    {
        bp::scope scope(BlendingDataset);

        auto Config = class_<py::BlendingDataset::Config>
            ("Config", init<const py::BlendingDataset::Config&>())
            .def(init<>())
            .def_readwrite("extents", &py::BlendingDataset::Config::extents)
            .def_readwrite("overlap", &py::BlendingDataset::Config::overlap)
            .add_property("srs"
                          , bp::make_getter
                          (&py::BlendingDataset::Config::srs
                           , bp::return_value_policy<bp::return_by_value>())
                          , bp::make_setter
                          (&py::BlendingDataset::Config::srs
                           , bp::return_value_policy<bp::return_by_value>()))
            .add_property("resolution"
                          , bp::make_getter
                          (&py::BlendingDataset::Config::resolution
                           , bp::return_value_policy<bp::return_by_value>())
                          , bp::make_setter
                          (&py::BlendingDataset::Config::resolution
                           , bp::return_value_policy<bp::return_by_value>()))
            .add_property("nodata"
                          , bp::make_getter
                          (&py::BlendingDataset::Config::nodata
                           , bp::return_value_policy<bp::return_by_value>())
                          , bp::make_setter
                          (&py::BlendingDataset::Config::nodata
                           , bp::return_value_policy<bp::return_by_value>()))
            .def_readwrite("datasets", &py::BlendingDataset::Config::datasets)

            .def("__repr__", &py::Config_repr)
            ;

        {
            bp::scope scope(Config);

            auto Dataset = class_<py::BlendingDataset::Config::Dataset>
                ("Dataset"
                 , init<const py::BlendingDataset::Config::Dataset&>())
                .def(init<>())
                .def(init<const fs::path&, const math::Extents2&>())
                .add_property
                ("path"
                 , bp::make_getter
                 (&py::BlendingDataset::Config::Dataset::path
                  , bp::return_value_policy<bp::return_by_value>())
                 , bp::make_setter
                 (&py::BlendingDataset::Config::Dataset::path
                  , bp::return_value_policy<bp::return_by_value>()))
                .def_readwrite("valid"
                               , &py::BlendingDataset::Config::Dataset::valid)
                ;

            {
                bp::scope scope(Dataset);
                class_<py::BlendingDataset::Config::Dataset::list>("list")
                    .def(bp::vector_indexing_suite
                         <py::BlendingDataset::Config::Dataset::list>())
                ;
            }
        }
    }

    // register all custom gdal drivers
    gdal_drivers::registerAll();
}

namespace gdal_drivers { namespace py {
PYSUPPORT_MODULE_IMPORT(gdaldrivers)
} } // namespace gdal_drivers::py

ext: cpp

max_stars_repo_name: Melown/gdal-drivers

max_issues_repo_name: Melown/gdal-drivers

max_forks_repo_name: Melown/gdal-drivers


text:
#include <onrobot_gazebo/gripper_plugin.h>

#include <boost/tokenizer.hpp>

namespace gazebo
{
void GripperPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf)
{
  std::string joint_name, mimic_name, tip_name, palm_name, ns;

  _sdf->Get("name", name_, std::string{ "gripper_plugin" });
  _sdf->Get("robotNamespace", ns, std::string{});
  _sdf->Get("fixGrasp", fix_grasp_, false);
  _sdf->Get("maxEffort", max_effort_, 1.0);
  _sdf->Get("publishRate", publish_rate_, 50.0);
  _sdf->Get("monitorRate", monitor_rate_, 20.0);
  _sdf->Get("jointName", joint_name, std::string{});
  _sdf->Get("mimicName", mimic_name, std::string{});
  _sdf->Get("tipName", tip_name, std::string{});
  _sdf->Get("palmName", palm_name, std::string{});

  // Parse model
  model_ = _parent;
  world_ = model_->GetWorld();

  boost::char_separator<char> sep(", ");
  using tokenizer = boost::tokenizer<boost::char_separator<char>>;

  auto joint_name_tok = tokenizer{ joint_name, sep };
  for (auto it = joint_name_tok.begin(); it != joint_name_tok.end(); ++it)
  {
    joints_.push_back(model_->GetJoint(*it));
  }
  auto mimic_name_tok = tokenizer{ mimic_name, sep };
  for (auto it = mimic_name_tok.begin(); it != mimic_name_tok.end(); ++it)
  {
    mimics_.push_back(model_->GetJoint(*it));
  }
  auto tip_name_tok = tokenizer{ tip_name, sep };
  for (auto it = tip_name_tok.begin(); it != tip_name_tok.end(); ++it)
  {
    tip_links_.push_back(model_->GetLink(*it));
  }
  palm_link_ = model_->GetLink(palm_name);

  lower_limit_ = joints_[0]->LowerLimit(0);
  upper_limit_ = joints_[0]->UpperLimit(0);

  // ROS node
  rosnode_ = new ros::NodeHandle(ns);

  // ROS API: Joint state publisher
  joint_state_publisher_ = rosnode_->advertise<sensor_msgs::JointState>("joint_states", 100);
  next_publish_time_ = world_->SimTime();

  // ROS API: Gripper action server
  action_server_.reset(new ActionServer(*rosnode_, "gripper_controller/gripper_cmd", false));
  action_server_->start();
  next_monitor_time_ = world_->SimTime();

  // Listen to the update event. This event is broadcast every simulation iteration.
  update_conn_ = event::Events::ConnectWorldUpdateBegin(  //
      boost::bind(&GripperPlugin::OnUpdate, this));

  ROS_INFO_STREAM_NAMED(name_, "The \"" << name_ << "\" plugin is loaded.");
}

void GripperPlugin::OnUpdate()
{
  if (action_server_->isNewGoalAvailable())
  {
    auto goal = action_server_->acceptNewGoal();
    command_position_ = goal->command.position;
    command_effort_ = goal->command.max_effort;
    counter_ = int(monitor_rate_) * 2;
  }

  position_ = joints_[0]->Position(0);

  auto direction = command_position_ > 1e-3 ? 1 : -1;
  auto effort = max_effort_ * direction;
  auto margin = 0.1;

  if (direction < 0 && position_ < lower_limit_ + margin)
  {
    effort *= (position_ - lower_limit_) / margin;
  }
  else if (direction > 0 && position_ > upper_limit_ - margin)
  {
    effort *= (upper_limit_ - position_) / margin;
  }

  for (std::size_t i = 0; i < joints_.size(); ++i)
  {
    joints_[i]->SetForce(0, effort);

    if (i < mimics_.size())
    {
      auto position = joints_[i]->Position(0);
      mimics_[i]->SetPosition(0, position, true);
    }
  }

  joints_[0]->SetForce(0, effort);
  joints_[1]->SetForce(0, effort);

  auto current_time = this->world_->SimTime();
  if (current_time > next_monitor_time_)
  {
    CheckForSuccess();
    next_monitor_time_ += common::Time(1.0 / monitor_rate_);
  }
  if (current_time > next_publish_time_)
  {
    PublishJointStates();
    next_publish_time_ += common::Time(1.0 / publish_rate_);
  }
}

void GripperPlugin::CheckForSuccess()
{
  if (!action_server_->isActive())
    return;

  if (counter_-- == 0)
  {
    control_msgs::GripperCommandResult result;
    result.effort = max_effort_;
    result.position = position_;
    result.reached_goal = true;
    result.stalled = false;
    action_server_->setSucceeded(result);
  }
}

void GripperPlugin::PublishJointStates()
{
  joint_state_.header.stamp = ros::Time::now();
  joint_state_.name.resize(joints_.size());
  joint_state_.position.resize(joints_.size());
  joint_state_.velocity.resize(joints_.size());

  for (int i = 0; i < joints_.size(); i++)
  {
    physics::JointPtr joint = joints_[i];
    double velocity = joint->GetVelocity(0);
    double position = joint->Position(0);
    joint_state_.name[i] = joint->GetName();
    joint_state_.position[i] = position;
    joint_state_.velocity[i] = velocity;
  }
  joint_state_publisher_.publish(joint_state_);
}

GripperPlugin::~GripperPlugin()
{
  update_conn_.reset();
  action_server_.reset();

  if (rosnode_)
  {
    rosnode_->shutdown();
  }
}

GZ_REGISTER_MODEL_PLUGIN(GripperPlugin);
}  // namespace gazebo


text:
#define BOOST_TEST_MODULE "YukariMathsTest"

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

max_stars_repo_name: DanNixon/Yukari

max_issues_repo_name: DanNixon/Yukari

max_forks_repo_name: DanNixon/Yukari


text:
//------------------------------------------------------------------------------
// \file BitSet_test.cpp
//------------------------------------------------------------------------------
#include "Cpp/Utilities/SuperBitSet.h"

#include <bitset>
#include <boost/test/unit_test.hpp>
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
// https://stackoverflow.com/questions/20731/how-do-you-clear-a-stringstream-variable
#include <sstream>

using Cpp::Utilities::SuperBitSet;
using Cpp::Utilities::number_of_bits_in_a_byte;

BOOST_AUTO_TEST_SUITE(Cpp)
BOOST_AUTO_TEST_SUITE(Utilities)
BOOST_AUTO_TEST_SUITE(SuperBitSet_tests)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(NumberOfBitsInAByteIs8)
{
  BOOST_TEST(number_of_bits_in_a_byte == 8);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(BitSetWorks)
// cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_3-429h.pdf
{
  BOOST_TEST_REQUIRE(sizeof(unsigned short) == 2); // 2 bytes long
  BOOST_TEST_REQUIRE(std::pow(2, 2*8) == 65536); // 2 bytes long, 8 bits in a byte

  std::bitset<sizeof(unsigned short) * 8> unsigned_short_bitset {15213};

  constexpr unsigned short x_0 {15213};
  constexpr short x_1 {15213};
  constexpr short y {-15213};

  //std::cout << unsigned_short_bitset.to_string() << '\n';
  BOOST_TEST(unsigned_short_bitset.to_string() == "0011101101101101");
  unsigned_short_bitset = x_0;
  BOOST_TEST(unsigned_short_bitset.to_string() == "0011101101101101");
  unsigned_short_bitset = x_1;
  BOOST_TEST(unsigned_short_bitset.to_string() == "0011101101101101");
  unsigned_short_bitset = y;
  BOOST_TEST(unsigned_short_bitset.to_string() == "1100010010010011");
}

// cf. https://www.geeksforgeeks.org/c-bitset-and-its-application/
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(DemonstrateStdBitSet)
{
  {
    // Setup
    std::stringstream string_stream;

    constexpr std::size_t M {32};
    // default constructor initializes with all bits 0
    std::bitset<M> bset1;

    // bset2 is initialized with bits of 20
    std::bitset<M> bset2 {20};

    // bset3 is initialized with bits of specified binary string
    std::bitset<M> bset3 {std::string{"1100"}};

    // std::cout prints exact bits representation of bitset
    std::cout << bset1 << std::endl; // 00000000000000000000000000000000
    std::cout << bset2 << std::endl; // 00000000000000000000000000010100
    std::cout << bset3 << std::endl; // 00000000000000000000000000001100

    // declaring set8 with capacity of 8 bits
    std::bitset<8> set8; // 00000000

    // setting first bit (or 6th index)
    set8[1] = 1; // 00000010
    set8[4] = set8[1]; // 00010010
    std::cout << set8 << std::endl;

    // count function returns number of set bits in bitset
    int numberof1 = set8.count();
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(DemonstrateSuperBitSet)
{
  {
    SuperBitSet<2> bits2 {1};
    BOOST_TEST(bits2.to_string() == "01");
  }

  BOOST_TEST(true);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SuperBitSetIsLittleEndian)
{
  {
    // initializing 1st M=5 (rightmost, least significant) bit position
    SuperBitSet<5> bits {"11010"};
    BOOST_TEST(bits.to_string() == "11010");
    BOOST_TEST(bits[0] == 0);
    BOOST_TEST(bits[1] == 1);
    BOOST_TEST(bits[2] == 0);
    BOOST_TEST(bits[3] == 1);
    BOOST_TEST(bits[4] == 1);
  }
  {
    SuperBitSet<8> bits {0};
    BOOST_TEST(bits[0] == 0);
    BOOST_TEST(bits[1] == 0);
    BOOST_TEST(bits[2] == 0);
    BOOST_TEST(bits[3] == 0);
    BOOST_TEST(bits[4] == 0);
    BOOST_TEST(bits[5] == 0);
    BOOST_TEST(bits[6] == 0);
    BOOST_TEST(bits[7] == 0);
  }
  {
    SuperBitSet<8> bits {1};
    BOOST_TEST(bits[0] == 1);
    BOOST_TEST(bits[1] == 0);
    BOOST_TEST(bits[2] == 0);
    BOOST_TEST(bits[3] == 0);
    BOOST_TEST(bits[4] == 0);
    BOOST_TEST(bits[5] == 0);
    BOOST_TEST(bits[6] == 0);
    BOOST_TEST(bits[7] == 0);
  }
  {
    SuperBitSet<8> bits {2};
    BOOST_TEST(bits[0] == 0);
    BOOST_TEST(bits[1] == 1);
    BOOST_TEST(bits[2] == 0);
    BOOST_TEST(bits[3] == 0);
    BOOST_TEST(bits[4] == 0);
    BOOST_TEST(bits[5] == 0);
    BOOST_TEST(bits[6] == 0);
    BOOST_TEST(bits[7] == 0);
  }
  {
    SuperBitSet<8> bits {std::numeric_limits<uint8_t>::max() - 1};
    BOOST_TEST(bits[0] == 0);
    BOOST_TEST(bits[1] == 1);
    BOOST_TEST(bits[2] == 1);
    BOOST_TEST(bits[3] == 1);
    BOOST_TEST(bits[4] == 1);
    BOOST_TEST(bits[5] == 1);
    BOOST_TEST(bits[6] == 1);
    BOOST_TEST(bits[7] == 1);
  }
  {
    SuperBitSet<8> bits {std::numeric_limits<uint8_t>::max()};
    BOOST_TEST(bits[0] == 1);
    BOOST_TEST(bits[1] == 1);
    BOOST_TEST(bits[2] == 1);
    BOOST_TEST(bits[3] == 1);
    BOOST_TEST(bits[4] == 1);
    BOOST_TEST(bits[5] == 1);
    BOOST_TEST(bits[6] == 1);
    BOOST_TEST(bits[7] == 1);
  }
  {
    SuperBitSet<8> bits {std::numeric_limits<uint8_t>::max() + 1};
    BOOST_TEST(bits[0] == 0);
    BOOST_TEST(bits[1] == 0);
    BOOST_TEST(bits[2] == 0);
    BOOST_TEST(bits[3] == 0);
    BOOST_TEST(bits[4] == 0);
    BOOST_TEST(bits[5] == 0);
    BOOST_TEST(bits[6] == 0);
    BOOST_TEST(bits[7] == 0);
  }

  BOOST_TEST(true);
}

// Use examples from wikipedia, "Bitwise operation"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// NOT is also called the complement, or negation
BOOST_AUTO_TEST_CASE(SuperBitSetWorksWithBitwiseNot)
{
  // bitwise complement = two's complement of the value - 1. If 2's complement
  // arithmetic used, then NOT x = -x - 1
  // TODO: explore and understand the previous statement.
  {
    SuperBitSet<4> bits {7};
    BOOST_TEST(bits.to_string() == "0111");
    BOOST_TEST(bits.to_ulong() == 7);
    BOOST_TEST((~bits).to_string() == "1000");
    BOOST_TEST((~bits).to_ulong() == 8);
  }
  {
    SuperBitSet<8> bits {171};
    BOOST_TEST(bits.to_string() == "10101011");
    BOOST_TEST(bits.to_ulong() == 171);
    BOOST_TEST((~bits).to_string() == "01010100");
    BOOST_TEST((~bits).to_ulong() == 84);
  }
  // For unsigned ints, bitwise complement of number is "mirror reflection" of
  // number across half-way point of unsigned int's range;
  // e.g. for 8-bit unsigned int, NOT x = 255 - x, "flips" increasing range from
  // 0 to 255, to decreasing range from 255 to 0.
}

// cf. https://en.wikipedia.org/wiki/Bitwise_operation Arithmetic shift section.

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SuperBitSetWorksWithLeftShift)
{
  {
    SuperBitSet<8> bits {"00010111"};
    BOOST_TEST_REQUIRE(bits.to_string() == "00010111");
    BOOST_TEST(bits.to_ulong() == 23);
    BOOST_TEST((bits << 1).to_string() == "00101110");
    BOOST_TEST((bits << 1).to_ulong() == 46);
    BOOST_TEST((bits << 2).to_string() == "01011100");
    BOOST_TEST((bits << 2).to_ulong() == 92);
  }
}

// cf. https://en.wikipedia.org/wiki/Bitwise_operation Arithmetic shift section.
// In a right arithmetic shift, sign bit (MSB in two's complement) is shifted in
// on left, preserves sign of operand. If MSB is 1, new 1 is copied into
// leftmost position.
// Logical right-shift inserts 0 into most significant bit, instead of copying
// sign bit; it's ideal for unsigned binary numbers, while
// arithmetic right-shift ideal for signed two's complement binary numbers.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SuperBitSetWorksWithRightShiftAsLogicalShift)
{
  {
    SuperBitSet<8> bits {"10010111"};
    BOOST_TEST_REQUIRE(bits.to_string() == "10010111");
    BOOST_TEST(bits.to_ulong() == 151);
    BOOST_TEST((bits >> 1).to_string() == "01001011");
    BOOST_TEST((bits >> 1).to_ulong() == 75);
    BOOST_TEST((bits >> 2).to_string() == "00100101");
    BOOST_TEST((bits >> 2).to_ulong() == 37);
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(UseBitwiseLeftShiftToGetMax)
{
  // unsigned long long is 64 bits or 8 bytes.
  SuperBitSet<64> bits {1ull};
  BOOST_TEST(sizeof(unsigned long long) == 8);
  {
    BOOST_TEST_REQUIRE(
      bits.to_string() ==
        "0000000000000000000000000000000000000000000000000000000000000001");
    BOOST_TEST(bits.to_ullong() == 1ull);

    BOOST_TEST((bits << 0).to_string() ==
      "0000000000000000000000000000000000000000000000000000000000000001");
    BOOST_TEST((bits << 0).to_ullong() == 1);
    BOOST_TEST((bits << 1).to_string() ==
      "0000000000000000000000000000000000000000000000000000000000000010");
    BOOST_TEST((bits << 1).to_ullong() == 2);
    BOOST_TEST((bits << 4).to_string() ==
      "0000000000000000000000000000000000000000000000000000000000010000");
    BOOST_TEST((bits << 4).to_ullong() == 16);

    BOOST_TEST(SuperBitSet<8>{(bits << 0).to_ullong() - 1}.to_string() ==
      "00000000");
    BOOST_TEST(SuperBitSet<8>{(bits << 0).to_ullong() - 1}.to_ulong() == 0);
    BOOST_TEST(SuperBitSet<8>{(bits << 1).to_ullong() - 1}.to_string() ==
      "00000001");
    BOOST_TEST(SuperBitSet<8>{(bits << 1).to_ullong() - 1}.to_ulong() == 1);
    BOOST_TEST(SuperBitSet<8>{(bits << 4).to_ullong() - 1}.to_string() ==
      "00001111");
    BOOST_TEST(SuperBitSet<8>{(bits << 4).to_ullong() - 1}.to_ulong() == 15);
  }
}

BOOST_AUTO_TEST_SUITE_END() // SuperBitSet_tests
BOOST_AUTO_TEST_SUITE_END() // Utilities
BOOST_AUTO_TEST_SUITE_END() // Cpp

max_stars_repo_name: ernestyalumni/HrdwCCppCUDA

max_issues_repo_name: ernestyalumni/HrdwCCppCUDA

max_forks_repo_name: ernestyalumni/HrdwCCppCUDA


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman

    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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_ERROR_HANDLER_APR_29_2007_1042PM)
#define BOOST_SPIRIT_ERROR_HANDLER_APR_29_2007_1042PM

#include <boost/spirit/home/qi/nonterminal/virtual_component_base.hpp>
#include <boost/spirit/home/qi/nonterminal/error_handler_result.hpp>
#include <boost/spirit/home/qi/operator/expect.hpp>
#include <boost/fusion/include/vector.hpp>

namespace boost { namespace spirit { namespace qi { namespace detail
{
    template <
        typename Iterator, typename Context
      , typename Skipper, typename F, error_handler_result action
    >
    struct error_handler : virtual_component_base<Iterator, Context, Skipper>
    {
        typedef virtual_component_base<Iterator, Context, Skipper> base_type;
        typedef intrusive_ptr<base_type> pointer_type;
        typedef typename base_type::skipper_type skipper_type;

        error_handler(pointer_type subject, F f)
          : subject(subject)
          , f(f)
        {
        }

        template <typename Skipper_>
        bool parse_main(
            Iterator& first
          , Iterator const& last
          , Context& context
          , Skipper_ const& skipper)
        {
            while (true)
            {
                try
                {
                    Iterator i = first;
                    bool r = subject->parse(i, last, context, skipper);
                    if (r)
                        first = i;
                    return r;
                }
                catch (expectation_failure<Iterator> const& x)
                {
                    typedef
                        fusion::vector<
                            Iterator&
                          , Iterator const&
                          , Iterator const&
                          , std::string>
                    params;
                    error_handler_result r = action;
                    params args(first, last, x.first, x.what);
                    f(args, context, r);

                    switch (r)
                    {
                        case fail: return false;
                        case retry: continue;
                        case accept: return true;
                        case rethrow: throw x;
                    }
                }
            }
            return false;
        }

        virtual bool
        parse(
            Iterator& first
          , Iterator const& last
          , Context& context
          , skipper_type const& skipper)
        {
            return parse_main(first, last, context, skipper);
        }

        virtual bool
        parse(
            Iterator& first
          , Iterator const& last
          , Context& context
          , no_skipper)
        {
            return parse_main(first, last, context, unused);
        }

        pointer_type subject;
        F f;
    };
}}}}

#endif

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
/*
 * Copyright (c) 2016 Andreas Pohl
 * Licensed under MIT (see COPYING)
 *
 * Author: Andreas Pohl
 */

#include "file_cache.h"
#include "asio_post.h"
#include "branch.h"
#include "make_unique.h"

#include <boost/filesystem.hpp>
#include <chrono>
#include <fstream>

using namespace boost::filesystem;

namespace petrel {

thread_local std::unique_ptr<file_cache::file_map_type> file_cache::m_file_map_local;

file_cache::file::file(const std::string& name, bool read_from_disk) {
    path p(name);
    if (exists(p)) {
        if (is_regular_file(p)) {
            m_size = file_size(p);
            m_time = last_write_time(p);
            if (read_from_disk) {
                std::ifstream is(name, std::ifstream::binary);
                if (is) {
                    m_data.reserve(m_size);
                    std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(),
                              std::back_inserter(m_data));
                    m_good = true;
                } else {
                    log_err("can't open file " << name);
                }
            }
        } else {
            log_err(name << " is no file");
        }
    } else {
        log_err(name << " does not exists");
    }
}

file_cache::file_cache(int refresh_time) {
    m_thread = std::thread([this, refresh_time] {
        while (!m_stop) {
            // relax
            std::this_thread::sleep_for(std::chrono::seconds(refresh_time));
            // look for new objects
            std::unordered_set<std::string> dirs;
            {
                std::lock_guard<std::mutex> lock(m_dir_mtx);
                dirs = m_directories;
            }
            for (auto& dir : dirs) {
                scan_directory(dir);
            }
            // update/remove existing objects
            std::vector<std::string> to_remove;
            std::vector<std::string> to_add;
            {
                std::lock_guard<std::mutex> lock(m_file_mtx);
                for (auto& pair : m_file_map) {
                    path p(pair.first);
                    if (exists(p)) {
                        if (*pair.second != file(pair.first)) {
                            // changed file
                            to_add.push_back(pair.first);
                        }
                    } else {
                        // file does not exists, remove it
                        to_remove.push_back(pair.first);
                    }
                }
            }
            for (auto& f : to_add) {
                add_file(f);
            }
            for (auto& f : to_remove) {
                remove_file(f);
            }
        }
    });
}

file_cache::~file_cache() {
    m_stop = true;
    m_thread.join();
}

void file_cache::register_io_service(ba::io_service* iosvc) {
    m_iosvcs.push_back(iosvc);
    iosvc->post([] { m_file_map_local = std::make_unique<file_map_type>(); });
}

void file_cache::unregister_io_service(ba::io_service* iosvc) {
    for (auto it = m_iosvcs.begin(); it != m_iosvcs.end(); it++) {
        if (*it == iosvc) {
            m_iosvcs.erase(it);
            break;
        }
    }
    io_service_post_wait(iosvc, [] { m_file_map_local.reset(); });
}

bool file_cache::scan_directory(const std::string& name) {
    path p(name);
    if (exists(p) && is_directory(p)) {
        for (directory_entry& entry : directory_iterator(p)) {
            if (is_directory(entry.status())) {
                scan_directory(entry.path().string());
            } else {
                std::shared_ptr<file> f = get_file_main(entry.path().string());
                if (nullptr == f) {
                    // new file
                    add_file(entry.path().string());
                }
            }
        }
        return true;
    }
    log_debug(name << " is no direcotory or does not exists");
    return false;
}

bool file_cache::add_directory(const std::string& name) {
    if (scan_directory(name)) {
        log_debug("added directory " << name);
        std::lock_guard<std::mutex> lock(m_dir_mtx);
        m_directories.insert(name);
        return true;
    }
    log_err(name << " not added");
    return false;
}

bool file_cache::add_file(const std::string& name) {
    auto f = std::make_shared<file>(name, true);
    log_debug("loaded object " << name << " (" << f->size() << " bytes)");
    if (f->good()) {
        // update the local caches
        for (auto* iosvc : m_iosvcs) {
            iosvc->post([this, name, f] { (*m_file_map_local)[name] = f; });
        }
        // update the main map
        std::lock_guard<std::mutex> lock(m_file_mtx);
        m_file_map[name] = f;
        return true;
    }
    return false;
}

void file_cache::remove_file(const std::string& name) {
    log_debug("removing object " << name);
    // update the local caches
    for (auto* iosvc : m_iosvcs) {
        iosvc->post([name] {
            auto it = m_file_map_local->find(name);
            if (m_file_map_local->end() != it) {
                m_file_map_local->erase(it);
            }
        });
    }
    // update the main map
    std::lock_guard<std::mutex> lock(m_file_mtx);
    auto it = m_file_map.find(name);
    if (m_file_map.end() != it) {
        m_file_map.erase(it);
    }
}

std::shared_ptr<file_cache::file> file_cache::get_file(const std::string& name) {
    // thread local lookup
    bool update_local_map = false;
    if (likely(nullptr != m_file_map_local)) {
        auto it = m_file_map_local->find(name);
        if (m_file_map_local->end() != it) {
            return it->second;
        }
        update_local_map = true;
    }
    // falling back to main map
    auto file = get_file_main(name);
    if (nullptr != file && update_local_map) {
        // update the local cache
        (*m_file_map_local)[name] = file;
    }
    return file;
}

std::shared_ptr<file_cache::file> file_cache::get_file_main(const std::string& name) {
    std::lock_guard<std::mutex> lock(m_file_mtx);
    auto it = m_file_map.find(name);
    if (m_file_map.end() != it) {
        return it->second;
    }
    return nullptr;
}

}  // petrel


text: #include <boost/graph/vector_as_graph.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <stdio.h>
#include <inttypes.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <signal.h>
#include <getopt.h>

#include <lcm/lcm.h>
#include <bot_core/bot_core.h>
#include <bot_lcmgl_client/lcmgl.h>
#include <GL/gl.h>

#include <Eigen/Dense>

#include <lcmtypes/bot_core_pose_t.h>
#include <lcmtypes/bot_core_image_t.h>

namespace rv{

void draw_line_lcmgl(bot_lcmgl_t* lcmgl_, Eigen::Vector3d st_pt, Eigen::Vector3d end_pt,
        float r, float g, float b){

    // position

    bot_lcmgl_line_width(lcmgl_, 4.0f);
    bot_lcmgl_point_size(lcmgl_, 7.0f);
    bot_lcmgl_color3f(lcmgl_, r, g, b);

    bot_lcmgl_begin(lcmgl_, GL_LINE_STRIP);
    bot_lcmgl_vertex3d(lcmgl_, st_pt[0], st_pt[1], st_pt[2]);
    bot_lcmgl_vertex3d(lcmgl_,end_pt[0], end_pt[1], end_pt[2]);
    bot_lcmgl_end(lcmgl_);

}

void draw_pose_lcmgl(bot_lcmgl_t* lcmgl_, Eigen::Matrix4d pose,
			float r, float g, float b){

	float normal_length = 0.4;

	bot_lcmgl_translated(lcmgl_, 0, 0, 0);
	bot_lcmgl_line_width(lcmgl_, 2.0f);
	bot_lcmgl_point_size(lcmgl_, 7.0f);
	bot_lcmgl_color3f(lcmgl_, r, g, b);

	Eigen::Vector3d pt;
	pt << pose(0, 3), pose(1, 3), pose(2, 3);

	Eigen::Matrix4d M_fd, M_left, M_up;
	Eigen::Matrix4d T_fd, T_left, T_up;
	T_fd << 1, 0, 0, normal_length,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1;
	M_fd = pose * T_fd;

	T_left << 	1, 0, 0, 0,
			0, 1, 0, normal_length/2,
			0, 0, 1, 0,
			0, 0, 0, 1;
	M_left = pose * T_left;

	T_up << 1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, normal_length/2,
			0, 0, 0, 1;
	M_up = pose * T_up;

	Eigen::Vector3d pt_fd, pt_left, pt_up;
	pt_fd << M_fd(0, 3), M_fd(1, 3), M_fd(2, 3);
	pt_left << M_left(0, 3), M_left(1, 3), M_left(2, 3);
	pt_up << M_up(0, 3), M_up(1, 3), M_up(2, 3);

	bot_lcmgl_begin(lcmgl_, GL_LINE_STRIP);
	bot_lcmgl_vertex3f(lcmgl_, pt[0], pt[1], pt[2]);
	bot_lcmgl_vertex3f(lcmgl_, pt_fd[0], pt_fd[1], pt_fd[2]);
	bot_lcmgl_end(lcmgl_);

	bot_lcmgl_begin(lcmgl_, GL_LINE_STRIP);
	bot_lcmgl_vertex3f(lcmgl_, pt[0], pt[1], pt[2]);
	bot_lcmgl_vertex3f(lcmgl_, pt_left[0], pt_left[1], pt_left[2]);
	bot_lcmgl_end(lcmgl_);

	bot_lcmgl_begin(lcmgl_, GL_LINE_STRIP);
	bot_lcmgl_vertex3f(lcmgl_, pt[0], pt[1], pt[2]);
	bot_lcmgl_vertex3f(lcmgl_, pt_up[0], pt_up[1], pt_up[2]);
	bot_lcmgl_end(lcmgl_);

	bot_lcmgl_begin(lcmgl_, GL_POINTS);
	bot_lcmgl_vertex3f(lcmgl_, pt[0], pt[1], pt[2]);
	bot_lcmgl_end(lcmgl_);
}

} // end of namespace rv

static void
usage(const char *name)
{
    fprintf(
            stderr,
            "usage: %s [options]\n"
            "\n"
            "  -h, --help                            Shows this help text and exits\n"
            "\n",
            name);

    exit(1);
}

int main(int argc, char** argv)
{

    const char *optstring = "h";
    int c;
    struct option long_opts[] =
    {
        { "help", no_argument, 0, 'h' },
        { 0, 0, 0, 0 }
    };

    while ((c = getopt_long(argc, argv, optstring, long_opts, 0)) >= 0) {
        switch (c){
            case 'h':
                usage(argv[0]);
                break;
        }
    }

    lcm_t* lcm_ = lcm_create(NULL);
    bot_lcmgl_t* lcmgl_pose = bot_lcmgl_init(lcm_, "LCMGL_POSE_DEMO");

    // Draw a pose at origin
    Eigen::Matrix4d P_o;
	P_o <<  1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1;
	rv::draw_pose_lcmgl(lcmgl_pose, P_o, 1, 0, 0);

	// Do a forward (at X axis)
	// and 90 degree yaw transformation
	Eigen::Matrix4d T_x;
	T_x <<  0,-1, 0, 1,
			1, 0, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1;
	Eigen::Matrix4d P_1;
	P_1 = P_o * T_x;
	rv::draw_pose_lcmgl(lcmgl_pose, P_1, 0, 1, 0);

    bot_lcmgl_switch_buffer(lcmgl_pose);

    return 0;
}

max_stars_repo_name: hchengwang/rv-lcm-demo

max_issues_repo_name: hchengwang/rv-lcm-demo

max_forks_repo_name: hchengwang/rv-lcm-demo


text:
//  Copyright John Maddock 2006.
//  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)

//
// MSVC-7.1 has a problem with our tests: sometimes when a
// function is used via a function pointer, it does *not*
// instantiate the template, leading to unresolved externals
// at link time.  Therefore we create a small library that
// instantiates "everything", and link all our tests against
// it for msvc-7.1 only.  Note that due to some BBv2 limitations
// we can not place this in a sub-folder of the test directory
// as that would lead to recursive project dependencies...
//

#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false
#define BOOST_MATH_INSTANTIATE_MINIMUM
#include <boost/math/concepts/real_concept.hpp>
#include "../test/compile_test/instantiate.hpp"

void some_proc()
{
   instantiate(float(0));
   instantiate(double(0));
   instantiate(static_cast<long double>(0));
   instantiate(static_cast<boost::math::concepts::real_concept>(0));
}


text:
//          Copyright Oliver Kowalke 2014.
// 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_COROUTINES2_DETAIL_PUSH_COROUTINE_IPP
#define BOOST_COROUTINES2_DETAIL_PUSH_COROUTINE_IPP

#include <utility>

#include <boost/assert.hpp>
#include <boost/config.hpp>

#include <boost/coroutine2/detail/config.hpp>
#include <boost/coroutine2/detail/create_control_block.ipp>
#include <boost/coroutine2/detail/disable_overload.hpp>
#include <boost/coroutine2/fixedsize_stack.hpp>
#include <boost/coroutine2/segmented_stack.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines2 {
namespace detail {

// push_coroutine< T >

template< typename T >
push_coroutine< T >::push_coroutine( control_block * cb) noexcept :
    cb_{ cb } {
}

template< typename T >
template< typename Fn,
          typename
>
push_coroutine< T >::push_coroutine( Fn && fn) :
    push_coroutine{ default_stack(), std::forward< Fn >( fn) } {
}

template< typename T >
template< typename StackAllocator, typename Fn >
push_coroutine< T >::push_coroutine( StackAllocator && salloc, Fn && fn) :
    cb_{ create_control_block< control_block >( std::forward< StackAllocator >( salloc), std::forward< Fn >( fn) ) } {
}

template< typename T >
push_coroutine< T >::~push_coroutine() {
    if ( nullptr != cb_) {
        cb_->deallocate();
    }
}

template< typename T >
push_coroutine< T >::push_coroutine( push_coroutine && other) noexcept :
    cb_{ other.cb_ } {
    other.cb_ = nullptr;
}

template< typename T >
push_coroutine< T > &
push_coroutine< T >::operator()( T const& t) {
    cb_->resume( t);
    return * this;
}

template< typename T >
push_coroutine< T > &
push_coroutine< T >::operator()( T && t) {
    cb_->resume( std::forward< T >( t) );
    return * this;
}

template< typename T >
push_coroutine< T >::operator bool() const noexcept {
    return nullptr != cb_ && cb_->valid();
}

template< typename T >
bool
push_coroutine< T >::operator!() const noexcept {
    return nullptr == cb_ || ! cb_->valid();
}

// push_coroutine< T & >

template< typename T >
push_coroutine< T & >::push_coroutine( control_block * cb) noexcept :
    cb_{ cb } {
}

template< typename T >
template< typename Fn,
          typename
>
push_coroutine< T & >::push_coroutine( Fn && fn) :
    push_coroutine{ default_stack(), std::forward< Fn >( fn) } {
}

template< typename T >
template< typename StackAllocator, typename Fn >
push_coroutine< T & >::push_coroutine( StackAllocator && salloc, Fn && fn) :
    cb_{ create_control_block< control_block >( std::forward< StackAllocator >( salloc), std::forward< Fn >( fn) ) } {
}

template< typename T >
push_coroutine< T & >::~push_coroutine() {
    if ( nullptr != cb_) {
        cb_->deallocate();
    }
}

template< typename T >
push_coroutine< T & >::push_coroutine( push_coroutine && other) noexcept :
    cb_{ other.cb_ } {
    other.cb_ = nullptr;
}

template< typename T >
push_coroutine< T & > &
push_coroutine< T & >::operator()( T & t) {
    cb_->resume( t);
    return * this;
}

template< typename T >
push_coroutine< T & >::operator bool() const noexcept {
    return nullptr != cb_ && cb_->valid();
}

template< typename T >
bool
push_coroutine< T & >::operator!() const noexcept {
    return nullptr == cb_ || ! cb_->valid();
}

// push_coroutine< void >

inline
push_coroutine< void >::push_coroutine( control_block * cb) noexcept :
    cb_{ cb } {
}

template< typename Fn,
          typename
>
push_coroutine< void >::push_coroutine( Fn && fn) :
    push_coroutine{ default_stack(), std::forward< Fn >( fn) } {
}

template< typename StackAllocator, typename Fn >
push_coroutine< void >::push_coroutine( StackAllocator && salloc, Fn && fn) :
    cb_{ create_control_block< control_block >( std::forward< StackAllocator >( salloc), std::forward< Fn >( fn) ) } {
}

inline
push_coroutine< void >::~push_coroutine() {
    if ( nullptr != cb_) {
        cb_->deallocate();
    }
}

inline
push_coroutine< void >::push_coroutine( push_coroutine && other) noexcept :
    cb_{ other.cb_ } {
    other.cb_ = nullptr;
}

inline
push_coroutine< void > &
push_coroutine< void >::operator()() {
    cb_->resume();
    return * this;
}

inline
push_coroutine< void >::operator bool() const noexcept {
    return nullptr != cb_ && cb_->valid();
}

inline
bool
push_coroutine< void >::operator!() const noexcept {
    return nullptr == cb_ || ! cb_->valid();
}

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES2_DETAIL_PUSH_COROUTINE_IPP

ext: ipp

max_stars_repo_name: SnailTowardThesun/face-detect

max_issues_repo_name: SnailTowardThesun/face-detect

max_forks_repo_name: gradinkov/nheqminer-gradinkov


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

#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <geometry_msgs/PoseArray.h>
#include <visualization_msgs/MarkerArray.h>
//#include <pcl_ros/point_cloud.h>
//#include <pcl/point_types.h>
//#include <pcl/point_cloud.h>
#include <opencv2/core/core.hpp>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/photo/photo.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>

#include <dynamic_reconfigure/server.h>
//#include <rfs_slam/rfs_pkgConfig.h>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>

// #include "contour_blob_detector/contour_blob_detector.h"

using namespace std;

class RockDetectionServer {

private:

    ros::NodeHandle n;
    ros::Subscriber sub;
    ros::Publisher pub;
    ros::Publisher shape_pub;
    ros::Publisher detections_pub;
    tf::StampedTransform tf_base_fls_;
    string base_frame_;
    string fls_frame_;

//    dynamic_reconfigure::Server<rfs_slam::rfs_pkgConfig> server_;
//    dynamic_reconfigure::Server<rfs_slam::rfs_pkgConfig>::CallbackType f_;
    boost::mutex shared_mutex_;

    double grid_size;
    double max_radius;
    int blur_x_;
    int blur_y_;
    float min_area_;
    float max_area_;
    float min_circ_;

public:

    void callback(const sensor_msgs::Image::ConstPtr& image_msg)
    {

        cv_bridge::CvImagePtr cv_ptr;
        try {
            cv_ptr = cv_bridge::toCvCopy(*image_msg, sensor_msgs::image_encodings::TYPE_32FC1);
        }
        catch (cv_bridge::Exception& e) {
            ROS_ERROR("cv_bridge exception: %s", e.what());
            exit(-1);
        }

        cv::Mat image8, smoothed;
        cv_ptr->image.convertTo(image8, CV_8UC1, 255.0);
        cv::GaussianBlur(image8, smoothed, cv::Size(blur_x_ ,blur_y_), blur_x_);

        // Setup SimpleBlobDetector parameters.
        cv::SimpleBlobDetector::Params params;

        // Change thresholds
        params.minDistBetweenBlobs = 100.0f;

        params.filterByInertia = false;
        params.filterByConvexity = false;
        params.filterByColor = false;

        // Filter by Circularity
        params.filterByCircularity = true;
        params.minCircularity = min_circ_;

        // Filter by Area.
        params.filterByArea = true;
        params.minArea = min_area_;
        params.maxArea = max_area_;

        // Set up the detector with default parameters.
        cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params);

        // Detect blobs.
        std::vector<cv::KeyPoint> keypoints;
        detector->detect(smoothed, keypoints);

        // Draw detected blobs as red circles.
        // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures the size of the circle corresponds to the size of blob
        cv::Mat im_with_keypoints;
        drawKeypoints(smoothed, keypoints, im_with_keypoints, cv::Scalar(0,0,255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

        geometry_msgs::PoseArray detections_msg;
        detections_msg.header.frame_id = fls_frame_;
        detections_msg.header.stamp = ros::Time::now();
        for(const cv::KeyPoint& k : keypoints){

            // Transform keypoints to fls frame
            tf::Vector3 lm_fls = tf::Vector3(image8.rows - k.pt.y - 1,
                                             k.pt.x - image8.cols/2,
                                             0);

            geometry_msgs::Pose pose_msg;
            pose_msg.position.x = lm_fls.getX();
            pose_msg.position.y = lm_fls.getY();
            pose_msg.position.z = lm_fls.getZ();

            pose_msg.orientation.x = 0.0f;
            pose_msg.orientation.y = 0.0f;
            pose_msg.orientation.z = 1.0f;
            pose_msg.orientation.w = 0.0f;

            detections_msg.poses.push_back(pose_msg);
        }
        // Publish only if sth has been detected
        if(!detections_msg.poses.empty()){
            detections_pub.publish(detections_msg);
        }

        cv_bridge::CvImagePtr cv_pub_ptr(new cv_bridge::CvImage);
        cv_pub_ptr->encoding = "rgb8";
        cv_pub_ptr->image = im_with_keypoints;
        sensor_msgs::Image ros_image = *cv_pub_ptr->toImageMsg();
        pub.publish(ros_image);

//        ROS_INFO("Published image");
    }

//    void dynParamsCB(rfs_slam::rfs_pkgConfig &config, uint32_t)
//    {
//        blur_x_ = config.blur_size_x;
//        blur_y_ = config.blur_size_y;
//        min_circ_ = config.min_circ;
//        min_area_ = config.min_area;
//        max_area_ = config.max_area;
//    }

    RockDetectionServer(const std::string& name)
    {

        ros::NodeHandle pn("~");
        pn.param<double>("grid_size", grid_size, 0.2);
        pn.param<double>("max_radius", max_radius, 20.0);

        string detections_topic;
        string sonar_img_topic;

        // Init dynamic params
        blur_x_ = 3;
        blur_y_ = 13;
        min_area_ = 600.0;
        max_area_ = 5000.0;
        min_circ_ = 0.1;

//        f_ = boost::bind(&RockDetectionServer::dynParamsCB, this, _1, _2);
//        server_.setCallback(f_);

        n.param<std::string>((name + "/base_frame"), base_frame_, "/base_frame");
        n.param<std::string>((name + "/fls_frame"), fls_frame_, "/fls_frame");
        n.param<std::string>((name + "/lm_detect_topic"), detections_topic, "/velodyne_detections");
        n.param<std::string>((name + "/image_raw_sonar"), sonar_img_topic, "/depth/image_raw_raw_sonar");

        detections_pub = n.advertise<geometry_msgs::PoseArray>(detections_topic, 1);
        sub = n.subscribe(sonar_img_topic, 1, &RockDetectionServer::callback, this);
        pub = n.advertise<sensor_msgs::Image>("/velodyne_blobs", 1);
//        shape_pub = n.advertise<visualization_msgs::MarkerArray>("/velodyne_outlines", 1);

        tf::TransformListener tf_listener;
        try{
            tf_listener.waitForTransform(base_frame_, fls_frame_, ros::Time(0), ros::Duration(100));
            tf_listener.lookupTransform(base_frame_, fls_frame_, ros::Time(0), tf_base_fls_);
            ROS_INFO_STREAM(name <<  ": Locked transform fls --> base");
        }
        catch(tf::TransformException &exception){
            ROS_ERROR("%s", exception.what());
            ros::Duration(1.0).sleep();
        }
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "fls_rock_detector");

    RockDetectionServer rds(ros::this_node::getName());

    ros::spin();

    return 0;
}


text:
// Copyright 2018-2019 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NETKET_SR_HPP
#define NETKET_SR_HPP

#include <complex>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <Eigen/Dense>
#include <Eigen/IterativeLinearSolvers>
#include <nonstd/optional.hpp>

#include "Utils/exceptions.hpp"
#include "Utils/messages.hpp"
#include "Utils/parallel_utils.hpp"
#include "Utils/random_utils.hpp"
#include "common_types.hpp"
#include "matrix_replacement.hpp"

namespace netket {

/**
 * Stochastic reconfiguration solver.
 */
class SR {
 public:
  using OkRef = Eigen::Ref<const RowMatrixXcd>;
  using GradRef = Eigen::Ref<const VectorXcd>;
  using OutputRef = Eigen::Ref<VectorXcd>;

  enum LSQSolver { LLT = 0, LDLT = 1, ColPivHouseholder = 2, BDCSVD = 3 };

  static nonstd::optional<LSQSolver> SolverFromString(const std::string& name);
  static const char* SolverAsString(LSQSolver solver);

  explicit SR(LSQSolver solver, double diagshift = 0.01,
              bool use_iterative = false, bool is_holomorphic = true,
              nonstd::optional<double> svd_threshold = nonstd::nullopt)
      : solver_(solver),
        sr_diag_shift_(diagshift),
        use_iterative_(use_iterative),
        is_holomorphic_(is_holomorphic),
        svd_threshold_(svd_threshold) {
    if (svd_threshold.has_value()) {
      if (use_iterative || solver != BDCSVD) {
        throw InvalidInputError{
            "svd_threshold option only available for BDCSVD solver"};
      }
    }
  }

  explicit SR(double diagshift = 0.01, bool use_iterative = false,
              bool use_cholesky = true, bool is_holomorphic = true)
      __attribute__((deprecated))
      : SR(use_cholesky ? LLT : ColPivHouseholder, diagshift, use_iterative,
           is_holomorphic) {}

  /**
   * Solves the SR flow equation for the parameter update ẋ.
   *
   * The SR update is computed by solving the linear euqation
   *    Sẋ = f
   * where S is the covariance matrix of the partial derivatives
   * O_i(v_j) = ∂/∂x_i log Ψ(v_j) and f is a generalized force (the loss
   * gradient).
   *
   * @param Oks The matrix 𝕆 of centered log-derivatives,
   *    𝕆_ij = O_i(v_j) - ⟨O_i⟩.
   * @param grad The loss gradient f.
   * @param deltaP Output parameter for the update ẋ.
   */
  void ComputeUpdate(OkRef Oks, GradRef grad, OutputRef deltaP);

  void SetParameters(LSQSolver solver, double diagshift = 0.01,
                     bool use_iterative = false, bool is_holomorphic = true);
  void SetParameters(double diagshift = 0.01, bool use_iterative = false,
                     bool use_cholesky = true, bool is_holomorphic = true)
      __attribute__((deprecated));

  /**
   * Returns a string describing the current parameters of the SR class.
   */
  std::string LongDesc(Index depth = 0) const;
  std::string ShortDesc() const;

  /**
   * Becca and Sorella (2017), pp. 143-144.
   */
  void SetScaleInvariantRegularization(bool enabled) {
    if (use_iterative_ && enabled) {
      // TODO: implement
      throw std::runtime_error{
          "Scale-invariant regularization is not implemented "
          "for iterative solvers at the moment."};
    }
    if (enabled) {
      InfoMessage() << "Using scale-invariant preconditioning." << std::endl;
    }
    scale_invariant_pc_ = enabled;
  }
  bool ScaleInvariantRegularizationEnabled() const {
    return scale_invariant_pc_;
  }

  /**
   * Returns the rank of the S matrix computed during the last call to
   * `ComputeUpdate` or `nullopt`, in case storing the rank is not enabled
   * and before the first call to `ComputeUpdate`.
   *
   * Storing the rank is enabled and disabled by `SetStoreRank` below.
   */
  nonstd::optional<Index> LastRank() { return last_rank_; }
  bool StoreRankEnabled() const { return store_rank_; }
  void SetStoreRank(bool enabled);

  /**
   * Returns the S matrix computed during the last call to
   * `ComputeUpdate` or `nullopt`, in case storing the S matrix is not enabled
   * and before the first call to `ComputeUpdate`.
   *
   * Storing the S matrix is enabled and disabled by `SetStoreFullSMatrix`
   * below.
   */
  const nonstd::optional<MatrixXcd>& LastSMatrix() const { return last_S_; }
  bool StoreFullSMatrixEnabled() const { return store_full_S_matrix_; }
  void SetStoreFullSMatrix(bool enabled);

  /**
   * Returns the is_holomorphic parameter
   * @return
   */
  bool IsHolomorphic() { return is_holomorphic_; };
  void SetIsHolomorphic(bool is_holomorphic) {is_holomorphic_ = is_holomorphic;};

 private:
  LSQSolver solver_;
  double sr_diag_shift_;
  bool use_iterative_;
  bool is_holomorphic_;
  nonstd::optional<double> svd_threshold_;

  bool scale_invariant_pc_ = false;
  VectorXd diag_S_;

  Eigen::MatrixXd Sreal_;
  Eigen::MatrixXcd Scomplex_;

  bool store_rank_ = false;
  bool store_full_S_matrix_ = false;

  nonstd::optional<Index> last_rank_;
  nonstd::optional<MatrixXcd> last_S_;

  template <class Mat>
  void BuildSMatrix(Eigen::Ref<const Mat> S_local, Mat& S_out, double nsamp) {
    static_assert(std::is_same<Mat, MatrixXd>::value ||
                      std::is_same<Mat, MatrixXcd>::value,
                  "S_out must be of type MatrixXd or MatrixXcd");

    S_out = S_local;
    SumOnNodes(S_out);
    S_out /= nsamp;
  }

  template <class Mat, class Vec>
  void ApplyPreconditioning(Mat& S, Vec& grad) {
    if (scale_invariant_pc_) {
      // Even if S is complex, its diagonal elements should be real since it
      // is Hermitian.
      diag_S_ = S.diagonal().real().cwiseSqrt();

      static const double CUTOFF = 1e-10;
      for (Index i = 0; i < diag_S_.rows(); i++) {
        if (diag_S_(i) <= CUTOFF) {
          diag_S_(i) = 1.0;
          S.col(i).setZero();
          S.row(i).setZero();
          S(i, i) = 1.0;
        }
      }

      S.array() /= (diag_S_ * diag_S_.transpose()).array();
      grad.array() /= diag_S_.array();
    }
    // Apply diagonal shift
    S.diagonal().array() += sr_diag_shift_;
  }

  void RevertPreconditioning(OutputRef solution) {
    if (scale_invariant_pc_) {
      solution.array() /= diag_S_.array();
    }
  }

  template <class Vec>
  void SolveIterative(OkRef Oks, Eigen::Ref<const Vec> grad, OutputRef deltaP,
                      double nsamp) {
    // Use SrMatrixReal iff Vec is a real vector, else SrMatrixComplex
    using IsReal = std::is_same<typename Vec::Scalar, double>;
    using SrMatrixType = typename std::conditional<IsReal::value, SrMatrixReal,
                                                   SrMatrixComplex>::type;
    // Make sure this code does not compile by accident if grad is a different
    // type
    static_assert(std::is_same<typename Vec::Scalar, double>::value ||
                      std::is_same<typename Vec::Scalar, Complex>::value,
                  "grad must be a real or complex vector");

    SrMatrixType S;
    S.attachMatrix(Oks);
    S.setShift(sr_diag_shift_);
    S.setScale(1. / nsamp);

    using SolverType =
        Eigen::ConjugateGradient<SrMatrixType, Eigen::Lower | Eigen::Upper,
                                 Eigen::IdentityPreconditioner>;
    SolverType it_solver(S);
    it_solver.setTolerance(1.0e-3);
    deltaP = it_solver.solve(grad);
  }

  template <class Mat, class Vec, class Out>
  void SolveLeastSquares(Mat& A, Eigen::Ref<const Vec> b, Out&& deltaP) {
    if (store_full_S_matrix_) {
      last_S_.emplace(A);
    }

    if (solver_ == LLT) {
      Eigen::LLT<Mat> llt(A);
      deltaP = llt.solve(b);
    } else if (solver_ == LDLT) {
      Eigen::LDLT<Mat> ldlt(A);
      deltaP = ldlt.solve(b);
    } else if (solver_ == ColPivHouseholder) {
      Eigen::ColPivHouseholderQR<Mat> qr(A);
      deltaP = qr.solve(A);
      if (store_rank_) {
        last_rank_ = qr.rank();
      }
    } else if (solver_ == BDCSVD) {
      const constexpr auto options = Eigen::ComputeThinU | Eigen::ComputeThinV;
      Eigen::BDCSVD<Mat> bdcsvd(A.rows(), A.cols(), options);
      if (svd_threshold_.has_value()) {
        bdcsvd.setThreshold(*svd_threshold_);
      }
      bdcsvd.compute(A);
      deltaP = bdcsvd.solve(b);
      if (store_rank_) {
        last_rank_ = bdcsvd.rank();
      }
    } else {
      throw std::runtime_error{
          "Unknown LSQSolver enum value in SR. This should never happen."};
    }
  }

  static void CheckSolverCompatibility(bool use_iterative, LSQSolver solver,
                                       bool rank_enabled) {
    if (!rank_enabled) {
      return;
    }
    if (use_iterative) {
      throw std::logic_error{
          "SR cannot store matrix rank with interactive solver."};
    }
    if (solver == LLT || solver == LDLT) {
      std::stringstream str;
      str << "SR cannot store matrix rank: Solver " << SolverAsString(solver)
          << " is not rank-revealing.";
      throw std::logic_error{str.str()};
    }
  }
};

}  // namespace netket

#endif

max_stars_repo_name: vigsterkr/netket

max_issues_repo_name: vigsterkr/netket

max_forks_repo_name: vigsterkr/netket


text:
// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.

// Boost Software License - Version 1.0 - August 17th, 2003

// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:

// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.

// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//  Authors: Thejaka Kanewala
//           Andrew Lumsdaine

#ifndef BOOST_GRAPH_KLA_SSSP_THREAD_HPP
#define BOOST_GRAPH_KLA_SSSP_THREAD_HPP

#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif

#include <am++/counter_coalesced_message_type.hpp>
#include <am++/detail/thread_support.hpp>

#include <boost/parallel/append_buffer.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/parallel/algorithm.hpp> // for all_reduce
#include <boost/graph/parallel/thread_support.hpp> // for compare_and_swap
#include <algorithm> // for std::min, std::max
#include <boost/format.hpp>
#include <iostream>
#include <atomic>
#include "boost/tuple/tuple.hpp"
//#include <tuple>

namespace boost { namespace graph { namespace distributed {

template<typename Graph,
         typename DistanceMap,
         typename EdgeWeightMap,
	 typename WorkStats,
	 typename PriorityQueueGenerator = thread_priority_queue_gen,
         typename MessageGenerator =
           amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> >
class kla_shortest_paths_thread {
  typedef kla_shortest_paths_thread<Graph, DistanceMap, EdgeWeightMap, PriorityQueueGenerator>
    self_type;

  typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;

  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
  typedef typename graph_traits<Graph>::degree_size_type Degree;
  typedef typename property_traits<EdgeWeightMap>::value_type Dist;

  typedef std::pair<Vertex, std::pair<Dist, size_t> > vertex_distance_data;

  struct default_comparer {
    bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) const {
      return vd1.second.first > vd2.second.first;
    }
  };

  typedef typename PriorityQueueGenerator::template queue<vertex_distance_data,
							  default_comparer>::type Bucket;
  typedef typename std::vector<Bucket*>::size_type BucketIndex;

  struct vertex_distance_handler;

  struct minimum_pair_first
  {
    template<typename T>
    const T& operator()(const T& x, const T& y) const { return x.first < y.first ? x : y; }

    template<typename F>
    struct result {
      typedef typename boost::function_traits<F>::arg1_type type;
    };
  };

  typedef typename MessageGenerator::template call_result<vertex_distance_data, vertex_distance_handler, owner_from_pair<OwnerMap, vertex_distance_data>, amplusplus::idempotent_combination_t<minimum_pair_first > >::type
    RelaxMessage;

public:

  kla_shortest_paths_thread(Graph& g,
                            DistanceMap distance,
                            EdgeWeightMap weight,
                            amplusplus::transport &t,
                            size_t k_level,
                            int offs,
                            WorkStats& stats,
			    int freq,
                            MessageGenerator message_gen =
			    MessageGenerator(amplusplus::counter_coalesced_message_type_gen(1 << 12)))
    : dummy_first_member_for_init_order((amplusplus::register_mpi_datatype<vertex_distance_data>(), 0)),
      g(g), transport(t),
      distance(distance),
      weight(weight),
      owner(get(vertex_owner, g)),
      level_sync(false),
      current_level(0),
      buckets_processed(0),
      current_bucket(0),
      k_level(k_level),
      core_offset(offs),
      work_stats(stats),
      relax_msg(message_gen, transport, owner_from_pair<OwnerMap, vertex_distance_data>(owner),
	      amplusplus::idempotent_combination(minimum_pair_first())),
      flushFrequency(freq)
  {
    initialize();
  }

#ifdef AMPLUSPLUS_PRINT_HIT_RATES
  typedef std::pair<unsigned long long, unsigned long long> cache_stats;
  cache_stats
  get_cache_stats() {
    cache_stats stats(0, 0);
    for(size_t i = 0; i < relax_msg.counters.hits.size(); ++i) {
      stats.first += relax_msg.counters.hits[i];
      stats.second += relax_msg.counters.tests[i];
    }
    return stats;
  }
#endif // AMPLUSPLUS_PRINT_HIT_RATES

  void set_source(Vertex s) { source = s; } // for threaded execution
  void set_level_sync() { level_sync = true; } // force level-synchronized exploration
  void operator() (int tid) { run(source, tid); }

  void run(Vertex s, int tid = 0);

  void initialize_threaded_buckets(int tid);
  void allocate_pqs();

  BucketIndex get_num_levels() { return buckets_processed; }
  time_type get_start_time() { return start_time; }

protected:
  void initialize();

  // Relax the edge (u, v), creating a new best path of distance x.
  void relax(const vertex_distance_data& data);

  void find_next_bucket();

  const int dummy_first_member_for_init_order; // Unused

  const Graph& g;
  amplusplus::transport& transport;
  DistanceMap distance;
  EdgeWeightMap weight;
  OwnerMap owner;
  Vertex source;
  bool level_sync;
  size_t k_level;
  int core_offset;
  WorkStats& work_stats;
  size_t k_current_level;

  // Bucket data structure. The ith bucket contains all local vertices
  std::vector<shared_ptr<Bucket> > buckets;

  // Bucket to hold vertices deleted at each level
  shared_ptr<Bucket> deleted_vertices;
  BucketIndex current_level; // How many buckets have we processed?
  BucketIndex buckets_processed; // Stats tracking
  BucketIndex num_buckets;

  // Shared thread state to make sure we're all on the same page
  BucketIndex current_bucket;
  shared_ptr<amplusplus::detail::barrier> t_bar;
  RelaxMessage relax_msg;
  time_type start_time;
  int flushFrequency;
};

#define KLA_SHORTEST_PATHS_THREAD_PARMS                                   \
      typename Graph, typename DistanceMap, typename EdgeWeightMap, typename WorkStats, typename Bucket, typename MessageGenerator

#define KLA_SHORTEST_PATHS_THREAD_TYPE                                    \
      kla_shortest_paths_thread<Graph, DistanceMap, EdgeWeightMap, WorkStats, Bucket, MessageGenerator>

template<KLA_SHORTEST_PATHS_THREAD_PARMS>
void
KLA_SHORTEST_PATHS_THREAD_TYPE::initialize()
{
  int nthreads = transport.get_nthreads();

  relax_msg.set_handler(vertex_distance_handler(*this));

  // Setup distance map
  distance.set_consistency_model(0);
  set_property_map_role(vertex_distance, distance);

  // Set the currently processing k-level
  k_current_level = k_level;

  // Initialize buckets data structure
  //

  // Extra bucket is so we don't try to insert into the bucket we're processing
  // when the index wraps
  num_buckets = 2;

  // Declare bucket data structure and index variable
  buckets.resize(num_buckets);
  for (BucketIndex i = 0 ; i < buckets.size() ; ++i) {
    shared_ptr<Bucket> p(new Bucket(nthreads));
    buckets[i].swap(p);
  }

  // Initialize distance labels
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    put(distance, v, (std::numeric_limits<Dist>::max)());
  }
}

template<KLA_SHORTEST_PATHS_THREAD_PARMS>
void
KLA_SHORTEST_PATHS_THREAD_TYPE::run(Vertex s, int tid)
{

  int doFlushCounter = 0;
  //int debugwait = 1;
  //if(transport.rank()==0)
  //if(tid==0)
  //while (debugwait) ;
  int count_epoch = 0 ;
  AMPLUSPLUS_WITH_THREAD_ID(tid) {
    int nthreads = transport.get_nthreads();

    if (tid == 0)
      t_bar.reset(new amplusplus::detail::barrier(nthreads));

    // This barrier acts as a temporary barrier until we can be sure t_bar is initialized
    { amplusplus::scoped_epoch epoch(transport); }

    t_bar->wait();

    // if two processes are running on the same node, core_offset
    // is important to achieve thread affinity
    if (pin(tid+core_offset) != 0) {
      std::cerr << "[ERROR] Unable to pin current thread to "
		<< "core : " << tid << std::endl;
      assert(false);
    }

    // wait till all threads are pinned
    t_bar->wait();
    { amplusplus::scoped_epoch epoch(transport); }

    validate_thread_core_relation();

    start_time = get_time();
    // Push the source onto the bucket
    {
      amplusplus::scoped_epoch epoch(transport);

      if (get(owner, s) == transport.rank() && tid == 0) {
	relax(vertex_distance_data(s,std::make_pair(0,0)));
      }
    }

    t_bar->wait();

    while(current_bucket != (std::numeric_limits<BucketIndex>::max)()) {
      unsigned long all_process_bucket_empty = 1;
      unsigned long p_bucket_full = 0;
      count_epoch = 0;

      // process current bucket
      while(all_process_bucket_empty != 0) {
	// wait till all threads reach here
	// before checking whether queue is empty we need to make sure
	// none of the threads are pushing elements to the queue.
	// Therefore make sure all threads reach here before checking whether queue is
	// empty
	t_bar->wait();

	if (!buckets[current_bucket]->empty(tid))
	  p_bucket_full = 1;
	else
	  p_bucket_full = 0;

	{
	  amplusplus::scoped_epoch_value epoch(transport,
					       p_bucket_full,
					       all_process_bucket_empty);

	  vertex_distance_data vd;
	  while(buckets[current_bucket]->pop(vd, tid)) {
	    assert(all_process_bucket_empty != 0);

	    Vertex v = vd.first;
	    Dist dist = vd.second.first;
	    size_t v_level = vd.second.second;
	    Dist dv = get(distance, v);

	    //if we already have a better distance in the distance map
            if (dv < dist) {
	      continue;
            }

	    //Otherwise we got  a better distance.  Relax edges
	    BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
	      Vertex u = target(e, g);
	      Dist we = get(weight, e);
	      vertex_distance_data new_vd(u, std::make_pair(dist + we, v_level+1));
	      relax_msg.send(new_vd);
	    }

	    doFlushCounter++;
	    if(doFlushCounter == flushFrequency) {
	      doFlushCounter = 0;
	      transport.get_scheduler().run_one();
	    }
	  }

	} // end of epoch
	count_epoch += 1;
      } // end of while(all_process_bucket_empty != 0)

      assert(buckets[current_bucket]->empty(tid));
      // If all processes are done with the current bucket:
      // 1. clear the current bucket
      // 2. increase current level
      // 3. find the next bucket to work on
      buckets[current_bucket]->clear(tid);
      t_bar->wait();

#ifdef PRINT_DEBUG
      std::cerr << tid << "@" << transport.rank() << ": Current bucket " << current_bucket
		<< " size " << buckets[current_bucket]->size() << std::endl;
#endif
      assert(buckets[current_bucket]->size(tid) == 0);

      // find next bucket with work and update current_level
      BucketIndex old_bucket = current_bucket;

      t_bar->wait();
      if (tid == 0) {
	find_next_bucket();

	if (current_bucket != (std::numeric_limits<BucketIndex>::max)()) {
	  current_level += current_bucket - old_bucket;
	  ++buckets_processed;
	}

	// update k_current_level
	k_current_level += k_level;
      }
      t_bar->wait();
    } // end of current_bucket != (std::numeric_limits<BucketIndex>::max)()
  }
}

template<KLA_SHORTEST_PATHS_THREAD_PARMS>
void
KLA_SHORTEST_PATHS_THREAD_TYPE::relax(const vertex_distance_data& data)
{

#ifdef PBGL2_PRINT_WORK_STATS
  work_stats.increment_edges(amplusplus::detail::get_thread_id());
#endif

  Vertex v = data.first;
  Dist d = data.second.first;
  size_t k_vertex = data.second.second;
  using boost::parallel::val_compare_and_swap;

  Dist old_dist = get(distance, v), last_old_dist;
  while (d < old_dist) {
    last_old_dist = old_dist;
    old_dist = val_compare_and_swap(&distance[v], old_dist, d);
    if (last_old_dist == old_dist) {
#ifdef PBGL2_PRINT_WORK_STATS
      int tid = amplusplus::detail::get_thread_id();
      if(old_dist < std::numeric_limits<Dist>::max()) {
	work_stats.increment_invalidated(tid);
      } else {
	work_stats.increment_useful(tid);
      }
#endif

      // We got a better distance. If current
      // k-level is less than or equal to vertex k-level
      // straight a way relax it
      if (k_vertex <= k_current_level) {
	assert((k_current_level-k_level) < k_vertex <= k_current_level);

	BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
	  Vertex u = target(e, g);
	  Dist we = get(weight, e);
	  vertex_distance_data new_vd(u, std::make_pair(d + we, k_vertex+1));
	  relax_msg.send(new_vd);
	}
      } else { // otherwise we put vertex to next bucket
	int tid = amplusplus::detail::get_thread_id();
	buckets[(current_bucket+1)%2]->put(data, tid);
      }

      break; // No need to insert into current bucket now
    }
  }
#ifdef PBGL2_PRINT_WORK_STATS
  work_stats.increment_rejected(amplusplus::detail::get_thread_id());
#endif
  return;
}

template<KLA_SHORTEST_PATHS_THREAD_PARMS>
void
KLA_SHORTEST_PATHS_THREAD_TYPE::find_next_bucket()
{
  using boost::parallel::all_reduce;
  using boost::parallel::minimum;

  BucketIndex old_bucket = current_bucket;
  BucketIndex max_bucket = (std::numeric_limits<BucketIndex>::max)();

  current_bucket = (current_bucket + 1) % buckets.size();
  while (current_bucket != old_bucket && buckets[current_bucket]->empty())
    current_bucket = (current_bucket + 1) % buckets.size();

  if (current_bucket == old_bucket)
    current_bucket = max_bucket;

  // If we wrapped, project index past end of buckets to use min()
  if (current_bucket < old_bucket) current_bucket += buckets.size();

  all_reduce<BucketIndex, minimum<BucketIndex> > r(transport, minimum<BucketIndex>());
  current_bucket = r(current_bucket);

  // Map index back into range of buckets
  if (current_bucket != max_bucket)
    current_bucket %= buckets.size();
}

template<KLA_SHORTEST_PATHS_THREAD_PARMS>
struct KLA_SHORTEST_PATHS_THREAD_TYPE::
vertex_distance_handler {

  vertex_distance_handler() : self(NULL) {}
  vertex_distance_handler(kla_shortest_paths_thread& self) : self(&self) {}

  void operator() (const vertex_distance_data& data) const {
    self->relax(data);
  }

protected:
  kla_shortest_paths_thread* self;
};

} } } // end namespace boost::graph::distributed

#endif // BOOST_GRAPH_KLA_SHORTEST_PATHS_THREAD_HPP

max_stars_repo_name: thejkane/AGM

max_issues_repo_name: thejkane/AGM

max_forks_repo_name: thejkane/AGM