text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
/*!
 * \file
**/
#ifndef BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_MINEXPONENT_HPP_INCLUDED

#include <boost/simd/include/functor.hpp>
#include <boost/simd/sdk/meta/int_c.hpp>
#include <boost/simd/sdk/constant/constant.hpp>

/*!
 * \ingroup boost_simd_constant
 * \defgroup boost_simd_constant_minexponent Minexponent
 *
 * \par Description
 * Constant Minexponent
 *
 * \par Header file
 *
 * \code
 * #include <nt2/include/functions/minexponent.hpp>
 * \endcode
 *
 *
 * \synopsis
 *
 * \code
 * namespace boost::simd
 * {
 *   template <class T,class A0>
 *     meta::call<tag::minexponent_(A0)>::type
 *     Minexponent();
 * }
 * \endcode
 *
 *
 * \param T template parameter of Minexponent
 *
 * \return type T value
 *
 *
**/

namespace boost { namespace simd
{
  namespace tag
  {
    /*!
     * \brief Define the tag Minexponent of functor Minexponent
     *        in namespace boost::simd::tag for toolbox boost.simd.constant
    **/
    struct Minexponent : ext::pure_constant_<Minexponent>
    {
      template<class Target, class Dummy=void>
      struct  apply : meta::int_c<typename Target::type,0> {};
    };

  template<class T, class Dummy>
  struct  Minexponent::apply<boost::dispatch::meta::single_<T>,Dummy>
        : meta::int_c<boost::simd::int32_t,-126> {};

  template<class T, class Dummy>
  struct  Minexponent::apply<boost::dispatch::meta::double_<T>,Dummy>
        : meta::int_c<boost::simd::int64_t,-1022> {};
  }

  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Minexponent, Minexponent)
} }

#include <boost/simd/sdk/constant/common.hpp>

#endif


text:
// frame/object.hpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// 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 SOLID_FRAME_OBJECT_HPP
#define SOLID_FRAME_OBJECT_HPP

#include "system/timespec.hpp"

#include "frame/common.hpp"

#include "utility/dynamictype.hpp"
#include "utility/dynamicpointer.hpp"
#include <boost/concept_check.hpp>

#ifdef HAS_STDATOMIC
#include <atomic>
#else
#include "boost/atomic.hpp"
#endif

namespace solid{

class Mutex;

namespace frame{

class Manager;
class Service;
class ObjectPointerBase;
class Message;
class SelectorBase;
class Object;

class Object: public Dynamic<Object, DynamicShared<> >{
public:
	struct ExecuteContext{
		enum RetValE{
			WaitRequest,
			WaitUntilRequest,
			RescheduleRequest,
			CloseRequest,
			LeaveRequest,
		};
		size_t eventMask()const{
			return evsmsk;
		}
		const TimeSpec& currentTime()const{
			return rcrttm;
		}
		void reschedule();
		void close();
		void leave();
		void wait();
		void waitUntil(const TimeSpec &_rtm);
		void waitFor(const TimeSpec &_rtm);
	protected:
		ExecuteContext(
			const size_t _evsmsk,
			const TimeSpec &_rcrttm
		):	evsmsk(_evsmsk), rcrttm(_rcrttm), retval(WaitRequest){}

		size_t			evsmsk;
		const TimeSpec	&rcrttm;
		RetValE			retval;
		TimeSpec		waittm;
	};

	struct ExecuteController: ExecuteContext{
		ExecuteController(
			const size_t _evsmsk,
			const TimeSpec &_rcrttm
		): ExecuteContext(_evsmsk, _rcrttm){}

		const RetValE returnValue()const{
			return this->retval;
		}
		const TimeSpec& waitTime()const{
			return this->waittm;
		}
	};

	static const TimeSpec& currentTime();

	//!Get the object associated to the current thread
	/*!
	 \see Object::associateToCurrentThread
	*/
	static Object& specific();

	//! Returns true if the object is signaled
	bool notified() const;

	bool notified(size_t _s) const;

	//! Get the id of the object
	IndexT id() const;

	/**
	 * Returns true if the signal should raise the object ASAP
	 * \param _smask The signal bitmask
	 */
	bool notify(size_t _smask);

	//! Signal the object with a signal
	virtual bool notify(DynamicPointer<Message> &_rmsgptr);

protected:
	friend class Service;
	friend class Manager;
	friend class SelectorBase;

	//! Constructor
	Object();

	//! Grab the signal mask eventually leaving some bits set- CALL this inside lock!!
	size_t grabSignalMask(size_t _leave = 0);

	//! Virtual destructor
	virtual ~Object();//only objptr base can destroy an object

	void unregister();
	bool isRegistered()const;
	virtual void doStop();
private:
	static void doSetCurrentTime(const TimeSpec *_pcrtts);

	//! Set the id
	void id(const IndexT &_fullid);
	//! Gets the id of the thread the object resides in
	IndexT threadId()const;
	//! Assigns the object to the current thread
	/*!
		This is usualy called by the pool's Selector.
	*/
	void associateToCurrentThread();

	//! Executes the objects
	/*!
		This method is calle by selectpools with support for
		events and timeouts
	*/
	virtual void execute(ExecuteContext &_rexectx);

	void stop();

	//! Set the thread id
	void threadId(const IndexT &_thrid);
private:
	IndexT						fullid;

	ATOMIC_NS::atomic<size_t>	smask;
	ATOMIC_NS::atomic<IndexT>	thrid;
};

inline IndexT Object::id()	const {
	return fullid;
}

#ifndef NINLINES
#include "frame/object.ipp"
#endif

}//namespace frame
}//namespace solid

#endif

ext: hpp

max_stars_repo_name: joydit/solidframe

max_issues_repo_name: joydit/solidframe

max_forks_repo_name: joydit/solidframe


text:
// nvcc -O3 CholeskyDecomp_t.cu --expt-relaxed-constexpr -gencode arch=compute_61,code=sm_61 --compiler-options="-Ofast -march=native"
// add -DDOPROF to run  nvprof --metrics all

#include <algorithm>
#include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <random>

#include <Eigen/Core>
#include <Eigen/Eigenvalues>

#include "DataFormats/Math/interface/choleskyInversion.h"

constexpr int stride() { return 5 * 1024; }
template <int DIM>
using MXN = Eigen::Matrix<double, DIM, DIM>;
template <int DIM>
using MapMX = Eigen::Map<MXN<DIM>, 0, Eigen::Stride<DIM * stride(), stride()> >;

// generate matrices
template <class M>
void genMatrix(M& m) {
  using T = typename std::remove_reference<decltype(m(0, 0))>::type;
  int n = M::ColsAtCompileTime;
  std::mt19937 eng;
  // std::mt19937 eng2;
  std::uniform_real_distribution<T> rgen(0., 1.);

  // generate first diagonal elemets
  for (int i = 0; i < n; ++i) {
    double maxVal = i * 10000 / (n - 1) + 1;  // max condition is 10^4
    m(i, i) = maxVal * rgen(eng);
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < i; ++j) {
      double v = 0.3 * std::sqrt(m(i, i) * m(j, j));  // this makes the matrix pos defined
      m(i, j) = v * rgen(eng);
      m(j, i) = m(i, j);
    }
  }
}

template <int N>
void go(bool soa) {
  constexpr unsigned int DIM = N;
  using MX = MXN<DIM>;
  std::cout << "testing Matrix of dimension " << DIM << " size " << sizeof(MX) << " in " << (soa ? "SOA" : "AOS")
            << " mode" << std::endl;

  auto start = std::chrono::high_resolution_clock::now();
  auto delta = start - start;

  constexpr unsigned int SIZE = 4 * 1024;

  alignas(128) MX mm[stride()];  // just storage in case of SOA
  double* __restrict__ p = (double*)__builtin_assume_aligned(mm, 128);

  if (soa) {
    for (unsigned int i = 0; i < SIZE; ++i) {
      MapMX<N> m(p + i);
      genMatrix(m);
    }
  } else {
    for (auto& m : mm)
      genMatrix(m);
  }

  std::cout << mm[SIZE / 2](1, 1) << std::endl;

  if (soa)
    for (unsigned int i = 0; i < SIZE; ++i) {
      MapMX<N> m(p + i);
      math::cholesky::invert(m, m);
      math::cholesky::invert(m, m);
    }
  else
    for (auto& m : mm) {
      math::cholesky::invert(m, m);
      math::cholesky::invert(m, m);
    }

  std::cout << mm[SIZE / 2](1, 1) << std::endl;

  constexpr int NKK =
#ifdef DOPROF
      2;
#else
      1000;
#endif
  for (int kk = 0; kk < NKK; ++kk) {
    delta -= (std::chrono::high_resolution_clock::now() - start);
    if (soa)
#ifdef USE_VECTORIZATION_PRAGMA
#pragma GCC ivdep
#ifdef __clang__
#pragma clang loop vectorize(enable) interleave(enable)
#endif
#endif
      for (unsigned int i = 0; i < SIZE; ++i) {
        MapMX<N> m(p + i);
        math::cholesky::invert(m, m);
      }
    else
#ifdef USE_VECTORIZATION_PRAGMA
#pragma GCC ivdep
#ifdef __clang__
#pragma clang loop vectorize(enable) interleave(enable)
#endif
#endif
      for (auto& m : mm) {
        math::cholesky::invert(m, m);
      }

    delta += (std::chrono::high_resolution_clock::now() - start);
  }

  std::cout << mm[SIZE / 2](1, 1) << std::endl;

  double DNNK = NKK;
  std::cout << "x86 computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() / DNNK
            << ' ' << " ms" << std::endl;
}

int main() {
  go<2>(false);
  go<3>(false);
  go<4>(false);
  go<5>(false);
  go<6>(false);

  go<2>(true);
  go<3>(true);
  go<4>(true);
  go<5>(true);
  go<6>(true);

  // go<10>();
  return 0;
}

ext: cpp

max_stars_repo_name: Purva-Chaudhari/cmssw

max_issues_repo_name: Purva-Chaudhari/cmssw

max_forks_repo_name: Purva-Chaudhari/cmssw


text:
#ifndef wali_BOOST_HEAP_PRIORITY_WORKLIST_GUARD
#define wali_BOOST_HEAP_PRIORITY_WORKLIST_GUARD 1

/*!
 * @author Nicholas Kidd
 */

#include "wali/Common.hpp"
#include "wali/Worklist.hpp"
#include "wali/wfa/Trans.hpp"
#include <map>
#include <set>
#include <functional>

#include <boost/heap/fibonacci_heap.hpp>
#include <boost/heap/d_ary_heap.hpp>

namespace wali
{
  namespace details
  {
    template<typename Compare>
    struct binary_negate_with_default_constructor : std::binary_negate<Compare>
    {
      binary_negate_with_default_constructor()
        : std::binary_negate<Compare>(Compare())
      {}

      binary_negate_with_default_constructor(Compare const & cmp)
        : std::binary_negate<Compare>(cmp)
      {}

      binary_negate_with_default_constructor(binary_negate_with_default_constructor const & cmp)
        : std::binary_negate<Compare>(cmp)
      {}
    };

    template<typename Compare>
    class BoostHeapPriorityWorklist : public Worklist<wfa::ITrans>
    {
      // Boost implements max-heaps, not min-heaps. We want to hide this
      // pecularity, so negate the comparison functor.
      typedef binary_negate_with_default_constructor<Compare> NotCompare;

    public:

#if 1
      typedef boost::heap::d_ary_heap< wfa::ITrans*,
                                       boost::heap::compare<NotCompare>,
                                       boost::heap::mutable_<true>,
                                       boost::heap::arity<3> > pwl_t;
#else
      typedef boost::heap::fibonacci_heap< wfa::ITrans*,
                                           boost::heap::compare<NotCompare> > pwl_t;
#endif

    public:
      BoostHeapPriorityWorklist();

      virtual ~BoostHeapPriorityWorklist();

      virtual bool put( wfa::ITrans *t );

      virtual wfa::ITrans * get();

      virtual bool empty() const;

      virtual void clear();

      virtual size_t size() const;

    protected:
      pwl_t workset;

    private:

      struct HeapHandleData : wali::wfa::ITrans::WorklistData
      {
        typedef typename pwl_t::handle_type Handle;

        Handle handle;

        HeapHandleData(Handle const & h) : handle(h) {}
      };

    }; // class BoostHeapPriorityWorklist

  } // namespace details
} // namespace wali

#include "wali/details/PriorityWorklist.boost_heap.cpp"

// Yo, Emacs!
// Local Variables:
//   c-file-style: "ellemtel"
//   c-basic-offset: 2
// End:

#endif  // wali_BOOST_HEAP_PRIORITY_WORKLIST_GUARD

max_stars_repo_name: WaliDev/WALi-OpenNWA

max_issues_repo_name: WaliDev/WALi-OpenNWA

max_forks_repo_name: WaliDev/WALi-OpenNWA


text:
#ifndef BOOST_MPL_MIN_ELEMENT_HPP_INCLUDED
#define BOOST_MPL_MIN_ELEMENT_HPP_INCLUDED

// Copyright David Abrahams 2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source$
// $Date: 2008-03-22 17:45:55 -0400 (Sat, 22 Mar 2008) $
// $Revision: 43798 $

#include <boost/mpl/max_element.hpp>
#include <boost/mpl/not.hpp>

namespace boost { namespace mpl {

BOOST_MPL_AUX_COMMON_NAME_WKND(min_element)

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    , typename Predicate = less<_,_>
    >
struct min_element
    : max_element<
          Sequence
        , mpl::not_<Predicate>
        >
{
};

BOOST_MPL_AUX_NA_SPEC(1, min_element)

}}

#endif // BOOST_MPL_MIN_ELEMENT_HPP_INCLUDED

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
#ifndef INVERT_MATRIX_HPP
#define INVERT_MATRIX_HPP

 // REMEMBER to update "lu.hpp" header includes from boost-CVS
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;
/* Matrix inversion routine.
   Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */

bool InvertMatrix (const ublas::matrix<double>& input, ublas::matrix<double>& inverse);
bool InvertMatrixGen(const ublas::matrix<double>& input, ublas::matrix<double>& inverse);
#endif //INVERT_MATRIX_HPP


text:
/*
Copyright © 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC.  See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/

#include "helics/application_api/CombinationFederate.hpp"
#include "helics/application_api/Endpoints.hpp"
#include "helics/application_api/Publications.hpp"
#include "helics/core/BrokerFactory.hpp"
#include "helics/core/Core.hpp"
#include "helics/core/CoreFactory.hpp"
#include "helics/core/core-exceptions.hpp"
#include "testFixtures.hpp"
#include <future>
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/floating_point_comparison.hpp>

namespace bdata = boost::unit_test::data;
namespace utf = boost::unit_test;

BOOST_FIXTURE_TEST_SUITE (combo_federate_tests, FederateTestFixture)

// const std::string core_types[] = {"udp" };
/** test simple creation and destruction*/
BOOST_DATA_TEST_CASE (combo_federate_initialize_tests, bdata::make (core_types_single), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 1);
    auto vFed1 = GetFederateAs<helics::ValueFederate> (0);

    vFed1->enterExecutingMode ();

    BOOST_CHECK (vFed1->getCurrentMode () == helics::Federate::modes::executing);

    vFed1->finalize ();

    BOOST_CHECK (vFed1->getCurrentMode () == helics::Federate::modes::finalize);
}

BOOST_DATA_TEST_CASE (combo_federate_publication_registration, bdata::make (core_types_single), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 1);
    auto vFed1 = GetFederateAs<helics::ValueFederate> (0);

    auto &pubid = vFed1->registerPublication<std::string> ("pub1");
    auto &pubid2 = vFed1->registerGlobalPublication<int> ("pub2");

    auto &pubid3 = vFed1->registerPublication ("pub3", "double", "V");
    vFed1->enterExecutingMode ();

    BOOST_CHECK (vFed1->getCurrentMode () == helics::Federate::modes::executing);

    auto &sv = vFed1->getInterfaceName (pubid);
    auto &sv2 = vFed1->getInterfaceName (pubid2);
    BOOST_CHECK_EQUAL (sv, "fed0/pub1");
    BOOST_CHECK_EQUAL (sv2, "pub2");
    auto &pub3name = vFed1->getInterfaceName (pubid3);
    BOOST_CHECK_EQUAL (pub3name, "fed0/pub3");

    BOOST_CHECK_EQUAL (vFed1->getExtractionType (pubid3), "double");
    BOOST_CHECK_EQUAL (vFed1->getInterfaceUnits (pubid3), "V");

    BOOST_CHECK (vFed1->getPublication ("pub1").getHandle () == pubid.getHandle ());
    BOOST_CHECK (vFed1->getPublication ("pub2").getHandle () == pubid2.getHandle ());
    BOOST_CHECK (vFed1->getPublication ("fed0/pub1").getHandle () == pubid.getHandle ());
    vFed1->finalize ();

    BOOST_CHECK (vFed1->getCurrentMode () == helics::Federate::modes::finalize);
}

BOOST_DATA_TEST_CASE (combo_federate_single_transfer, bdata::make (core_types_single), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 1);
    auto vFed1 = GetFederateAs<helics::ValueFederate> (0);

    // register the publications
    auto &pubid = vFed1->registerGlobalPublication<std::string> ("pub1");

    auto &subid = vFed1->registerSubscription ("pub1");
    vFed1->setProperty (helics_property_time_delta, 1.0);
    vFed1->enterExecutingMode ();
    // publish string1 at time=0.0;
    vFed1->publish (pubid, "string1");
    auto gtime = vFed1->requestTime (1.0);

    BOOST_CHECK_EQUAL (gtime, 1.0);
    // get the value
    std::string s = vFed1->getString (subid);
    // make sure the string is what we expect
    BOOST_CHECK_EQUAL (s, "string1");
    // publish a second string
    vFed1->publish (pubid, "string2");
    // make sure the value is still what we expect
    s = vFed1->getString (subid);

    BOOST_CHECK_EQUAL (s, "string1");
    // advance time
    gtime = vFed1->requestTime (2.0);
    // make sure the value was updated
    BOOST_CHECK_EQUAL (gtime, 2.0);
    s = vFed1->getString (subid);

    BOOST_CHECK_EQUAL (s, "string2");
}

BOOST_DATA_TEST_CASE (combo_federate_endpoint_registration, bdata::make (core_types_single), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 1);
    auto mFed1 = GetFederateAs<helics::MessageFederate> (0);

    auto &epid = mFed1->registerEndpoint ("ep1");
    auto &epid2 = mFed1->registerGlobalEndpoint ("ep2", "random");

    mFed1->enterExecutingMode ();

    BOOST_CHECK (mFed1->getCurrentMode () == helics::Federate::modes::executing);

    auto &sv = mFed1->getInterfaceName (epid);
    auto &sv2 = mFed1->getInterfaceName (epid2);
    BOOST_CHECK_EQUAL (sv, "fed0/ep1");
    BOOST_CHECK_EQUAL (sv2, "ep2");

    BOOST_CHECK_EQUAL (mFed1->getExtractionType (epid), "");
    BOOST_CHECK_EQUAL (mFed1->getInjectionType (epid2), "random");

    BOOST_CHECK (mFed1->getEndpoint ("ep1").getHandle () == epid.getHandle ());
    BOOST_CHECK (mFed1->getEndpoint ("fed0/ep1").getHandle () == epid.getHandle ());
    BOOST_CHECK (mFed1->getEndpoint ("ep2").getHandle () == epid2.getHandle ());
    mFed1->finalize ();

    BOOST_CHECK (mFed1->getCurrentMode () == helics::Federate::modes::finalize);
}

BOOST_DATA_TEST_CASE (combination_federate_send_receive_2fed, bdata::make (core_types), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 2);
    auto mFed1 = GetFederateAs<helics::CombinationFederate> (0);
    auto mFed2 = GetFederateAs<helics::CombinationFederate> (1);

    auto &epid = mFed1->registerEndpoint ("ep1");
    auto &epid2 = mFed2->registerGlobalEndpoint ("ep2", "random");

    mFed1->setProperty (helics_property_time_delta, 1.0);
    mFed2->setProperty (helics_property_time_delta, 1.0);

    auto f1finish = std::async (std::launch::async, [&]() { mFed1->enterExecutingMode (); });
    mFed2->enterExecutingMode ();
    f1finish.wait ();

    BOOST_CHECK (mFed1->getCurrentMode () == helics::Federate::modes::executing);
    BOOST_CHECK (mFed2->getCurrentMode () == helics::Federate::modes::executing);

    helics::data_block data (500, 'a');
    helics::data_block data2 (400, 'b');

    mFed1->sendMessage (epid, "ep2", data);
    mFed2->sendMessage (epid2, "fed0/ep1", data2);
    // move the time to 1.0
    auto f1time = std::async (std::launch::async, [&]() { return mFed1->requestTime (1.0); });
    auto gtime = mFed2->requestTime (1.0);

    BOOST_CHECK_EQUAL (gtime, 1.0);
    BOOST_CHECK_EQUAL (f1time.get (), 1.0);

    auto res = mFed1->hasMessage ();
    BOOST_CHECK (res);
    res = mFed1->hasMessage (epid);
    BOOST_CHECK (res);
    res = mFed2->hasMessage (epid2);
    BOOST_CHECK (res);

    auto M1 = mFed1->getMessage (epid);
    BOOST_REQUIRE_EQUAL (M1->data.size (), data2.size ());

    BOOST_CHECK_EQUAL (M1->data[245], data2[245]);

    auto M2 = mFed2->getMessage (epid2);
    BOOST_REQUIRE_EQUAL (M2->data.size (), data.size ());

    BOOST_CHECK_EQUAL (M2->data[245], data[245]);
    mFed1->finalize ();
    mFed2->finalize ();

    BOOST_CHECK (mFed1->getCurrentMode () == helics::Federate::modes::finalize);
    BOOST_CHECK (mFed2->getCurrentMode () == helics::Federate::modes::finalize);
}

BOOST_DATA_TEST_CASE (combination_federate_multimode_transfer, bdata::make (core_types), core_type)
{
    SetupTest<helics::CombinationFederate> (core_type, 2);
    auto cFed1 = GetFederateAs<helics::CombinationFederate> (0);
    auto cFed2 = GetFederateAs<helics::CombinationFederate> (1);

    auto &epid = cFed1->registerEndpoint ("ep1");
    auto &epid2 = cFed2->registerGlobalEndpoint ("ep2", "random");

    // register the publications
    auto &pubid = cFed1->registerGlobalPublication<std::string> ("pub1");

    auto &subid = cFed2->registerSubscription ("pub1");

    cFed1->setProperty (helics_property_time_delta, 1.0);
    cFed2->setProperty (helics_property_time_delta, 1.0);

    auto f1finish = std::async (std::launch::async, [&]() { cFed1->enterExecutingMode (); });
    cFed2->enterExecutingMode ();
    f1finish.wait ();
    // publish string1 at time=0.0;
    cFed1->publish (pubid, "string1");

    BOOST_CHECK (cFed1->getCurrentMode () == helics::Federate::modes::executing);
    BOOST_CHECK (cFed2->getCurrentMode () == helics::Federate::modes::executing);

    helics::data_block data (500, 'a');
    helics::data_block data2 (400, 'b');

    cFed1->sendMessage (epid, "ep2", data);
    cFed2->sendMessage (epid2, "fed0/ep1", data2);
    // move the time to 1.0
    auto f1time = std::async (std::launch::async, [&]() { return cFed1->requestTime (1.0); });
    auto gtime = cFed2->requestTime (1.0);

    BOOST_CHECK_EQUAL (gtime, 1.0);
    BOOST_CHECK_EQUAL (f1time.get (), 1.0);

    std::string s = cFed2->getString (subid);
    // get the value
    // make sure the string is what we expect
    BOOST_CHECK_EQUAL (s, "string1");
    // publish a second string
    cFed1->publish (pubid, "string2");
    // make sure the value is still what we expect
    s = cFed2->getString (subid);

    BOOST_CHECK_EQUAL (s, "string1");

    auto res = cFed1->hasMessage ();
    BOOST_CHECK (res);
    res = cFed1->hasMessage (epid);
    BOOST_CHECK (res);
    res = cFed2->hasMessage (epid2);
    BOOST_CHECK (res);

    auto M1 = cFed1->getMessage (epid);
    BOOST_REQUIRE_EQUAL (M1->data.size (), data2.size ());

    BOOST_CHECK_EQUAL (M1->data[245], data2[245]);

    auto M2 = cFed2->getMessage (epid2);
    BOOST_REQUIRE_EQUAL (M2->data.size (), data.size ());

    BOOST_CHECK_EQUAL (M2->data[245], data[245]);

    // advance time
    f1time = std::async (std::launch::async, [&]() { return cFed1->requestTime (2.0); });
    gtime = cFed2->requestTime (2.0);

    BOOST_CHECK_EQUAL (gtime, 2.0);
    BOOST_CHECK_EQUAL (f1time.get (), 2.0);
    // make sure the value was updated

    auto &ns = cFed2->getString (subid);

    BOOST_CHECK_EQUAL (ns, "string2");

    cFed1->finalize ();
    cFed2->finalize ();

    BOOST_CHECK (cFed1->getCurrentMode () == helics::Federate::modes::finalize);
    BOOST_CHECK (cFed2->getCurrentMode () == helics::Federate::modes::finalize);
}

static constexpr const char *combo_config_files[] = {"example_combo_fed.json", "example_combo_fed.toml"};

BOOST_DATA_TEST_CASE (test_file_load, bdata::make (combo_config_files), file)
{
    helics::CombinationFederate cFed (std::string (TEST_DIR) + file);

    BOOST_CHECK_EQUAL (cFed.getName (), "comboFed");

    BOOST_CHECK_EQUAL (cFed.getEndpointCount (), 2);
    auto &id = cFed.getEndpoint ("ept1");
    BOOST_CHECK_EQUAL (cFed.getExtractionType (id), "genmessage");

    BOOST_CHECK_EQUAL (cFed.getInputCount (), 2);
    BOOST_CHECK_EQUAL (cFed.getPublicationCount (), 2);

    BOOST_CHECK (!cFed.getPublication (1).getInfo ().empty ());
    cFed.disconnect ();
}

BOOST_AUTO_TEST_SUITE_END ()


text:
#include <ctime>
#include <chrono>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <opencv/cv.hpp>

#include <sequence_recorder/image_sequence_recorder.h>

namespace fs = boost::filesystem;
using namespace cv;

namespace sequence_recorder
{

ImageSequenceRecorder::ImageSequenceRecorder(ros::NodeHandle &nh) :
    n_(nh), is_recording_(false)
{
  n_.param<int>("capture_device", capture_device_, 0);
  n_.param<std::string>("output_directory", output_directory_, "/tmp/recordings");
  n_.param<int>("image_width", image_width_, 640);
  n_.param<int>("image_height", image_height_, 480);
  n_.param<int>("framerate", framerate_, 15);
  n_.param<bool>("grayscale", grayscale_, false);

  joystick_sub_ = n_.subscribe<sensor_msgs::Joy>(
      "/joy", 10, &ImageSequenceRecorder::JoyCallback, this);
  wheel_velocity_sub_ = n_.subscribe<r0vert_msgs::WheelVelocity>(
      "/wheel_velocity", 10, &ImageSequenceRecorder::WheelVelocityCallback, this);

  fs::path output_path(output_directory_);
  fs::create_directories(output_path);
}

void ImageSequenceRecorder::JoyCallback(const sensor_msgs::Joy::ConstPtr &ptr)
{
  if (ptr->buttons[14])
  {
    StartRecording();
  }
  else if (ptr->buttons[15])
  {
    StopRecording();
  }
}

void ImageSequenceRecorder::StartRecording()
{
  if (is_recording_)
  {
    return;
  }
  recording_thread_ = std::thread(&ImageSequenceRecorder::Record, this);
  ROS_INFO("Recording started");
}

void ImageSequenceRecorder::StopRecording()
{
  if (not is_recording_)
  {
    return;
  }
  is_recording_ = false;
  recording_thread_.join();
  ROS_INFO("Recording stopped");
}

void ImageSequenceRecorder::Record()
{
  is_recording_ = true;

  sequence_ = std::make_unique<Sequence>(output_directory_, grayscale_);

  std::string gst_pipeline = "v4l2src ! video/x-raw,width=320,height=240,framerate=%d/1,format=RGB ! videoconvert ! appsink";
  VideoCapture capture(boost::str(boost::format(gst_pipeline) % framerate_));
  assert(capture.isOpened());

  start_time_ = system_clock::now();
  frame_time_min_ = milliseconds::max();
  frame_time_max_ = milliseconds::min();
  unsigned long frame_count = 0;
  Mat frame;
  while (is_recording_)
  {
    capture >> frame;
    system_clock::time_point new_frame_time = system_clock::now();

    try
    {
      sequence_->AddFrame(frame);
    }
    catch (std::runtime_error &e)
    {
      ROS_ERROR("Error: exception while writing image: ", e.what());
    }

    milliseconds diff = duration_cast<milliseconds>(new_frame_time - last_frame_time_);
    if (diff < frame_time_min_)
    {
      frame_time_min_ = diff;
    }
    else if (diff > frame_time_max_)
    {
      frame_time_max_ = diff;
    }
    last_frame_time_ = new_frame_time;
    frame_count += 1;
  };

  milliseconds total_time = duration_cast<milliseconds>(system_clock::now() - start_time_);
  milliseconds frame_time_avg = total_time / frame_count;
  ROS_INFO("FPS avg: %.2f, min: %.2f, max: %.2f",
           1000.0 / frame_time_avg.count(),
           1000.0 / frame_time_max_.count(),
           1000.0 / frame_time_min_.count());

  sequence_->WriteMetadata();
}

void ImageSequenceRecorder::WheelVelocityCallback(const r0vert_msgs::WheelVelocity::ConstPtr &ptr)
{
  if (is_recording_)
  {
    sequence_->AddWheelVelocity(ptr);
  }
}

} // namespace sequence_recorder


text:
/*
 * Copyright (c) 2018 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef LIBBIO_CONSECUTIVE_ALPHABET_HH
#define LIBBIO_CONSECUTIVE_ALPHABET_HH

#include <array>
#include <boost/sort/sort.hpp>
#include <cstdint>
#include <iostream>
#include <libbio/assert.hh>
#include <libbio/dispatch.hh>
#include <libbio/utility.hh>
#include <map>
#include <vector>

namespace libbio {
	template <typename t_char, template <typename> typename t_map>
	class consecutive_alphabet_mt;
}

// Forward declaration needed for template friends.
namespace boost { namespace serialization {
	template <typename t_archive, typename t_char, template <typename> typename t_map>
	void serialize(t_archive &, libbio::consecutive_alphabet_mt <t_char, t_map> &, unsigned int const);
}}

namespace libbio { namespace detail {

	// Map characters to consecutive integers using arrays.
	struct consecutive_alphabet_as_helper
	{
		// Use a helper class to add a static assertion.
		template <typename t_char>
		struct map_type_helper
		{
			static_assert(std::is_unsigned_v <t_char>);

			using map_type = std::array <
				t_char,
				1 + std::numeric_limits <t_char>::max()
			>;
		};

		// Declare the map type.
		template <typename t_char>
		using map_type = typename map_type_helper <t_char>::map_type;
	};

	// Map characters to consecutive integers using std::map.
	struct consecutive_alphabet_map_helper
	{
		template <typename t_char>
		using map_type = std::map <t_char, t_char>;
	};

	template <bool t_parallel>
	struct consecutive_alphabet_as_parallel_builder_helper
	{
		template <typename t_iterator>
		void sort(t_iterator begin, t_iterator end);

		template <typename t_builder, typename t_forward_iterable>
		void prepare(t_builder &builder, t_forward_iterable const &text);
	};

	template <>
	struct consecutive_alphabet_as_parallel_builder_helper <false>
	{
		template <typename t_iterator>
		void sort(t_iterator begin, t_iterator end);

		template <typename t_builder, typename t_forward_iterable>
		void prepare(t_builder &builder, t_forward_iterable const &text);
	};
}}

namespace libbio {

	template <typename t_alphabet>
	class consecutive_alphabet_mt_builder
	{
	protected:
		typedef typename t_alphabet::map_type map_type;

	protected:
		t_alphabet					m_alphabet;

	public:
		t_alphabet &alphabet() { return m_alphabet; }
		t_alphabet const &alphabet() const { return m_alphabet; }

	protected:
		map_type &to_comp() { return m_alphabet.m_to_comp; }
		map_type &to_char() { return m_alphabet.m_to_char; }
	};

	// Map characters to consecutive integers using the given map type.
	template <typename t_char, template <typename> typename t_map>
	class consecutive_alphabet_mt
	{
		template <typename>
		friend class consecutive_alphabet_mt_builder;

		template <typename t_archive, typename t_tpl_char, template <typename> typename t_tpl_map>
		friend void boost::serialization::serialize(t_archive &ar, consecutive_alphabet_mt <t_tpl_char, t_tpl_map> &alphabet, unsigned int const version);

	public:
		enum { ALPHABET_MAX = std::numeric_limits <t_char>::max() };

	protected:
		typedef t_map <t_char>	map_type;

	protected:
		map_type				m_to_comp;
		map_type				m_to_char;

	public:
		consecutive_alphabet_mt() = default;
		inline std::size_t sigma() const { return m_to_char.size(); }	// Nul character is always considered.
		inline t_char char_to_comp(t_char const c) const { return m_to_comp[c]; }
		inline t_char comp_to_char(t_char const c) const { return m_to_char[c]; }

		// For debugging.
		void print();

		void swap(consecutive_alphabet_mt &other);

	protected:
		template <typename t_archive>
		void boost_serialize(t_archive &ar, unsigned int const version);
	};

	// Map with std::arrays.
	template <typename t_char, typename t_builder = void>
	using consecutive_alphabet_as = consecutive_alphabet_mt <t_char, detail::consecutive_alphabet_as_helper::map_type>;

	// Map with std::maps.
	template <typename t_char, typename t_builder = void>
	using consecutive_alphabet_map = consecutive_alphabet_mt <t_char, detail::consecutive_alphabet_map_helper::map_type>;

	// Create a compressed alphabet.
	template <typename t_char>
	class consecutive_alphabet_as_builder final : public consecutive_alphabet_mt_builder <consecutive_alphabet_as <t_char>>
	{
	protected:
		typedef consecutive_alphabet_as <t_char>	alphabet_type;

	protected:
		std::vector <bool>				m_seen;
		std::vector <t_char>			m_found_characters;

	public:
		consecutive_alphabet_as_builder() = default;

		void init();

		template <typename t_forward_iterable>
		void prepare(t_forward_iterable const &text);

		void compress();
	};

	// Create a compressed alphabet, parallelize where possible.
	template <typename t_char>
	class consecutive_alphabet_as_parallel_builder final : public consecutive_alphabet_mt_builder <consecutive_alphabet_as <t_char>>
	{
		template <bool>
		friend struct detail::consecutive_alphabet_as_parallel_builder_helper;

	protected:
		typedef consecutive_alphabet_as <t_char>								alphabet_type;
		typedef std::atomic <smallest_unsigned_lockfree_type_gte_t <t_char>>	counter_type;

	protected:
		std::vector <std::atomic_flag>	m_flags;
		std::vector <t_char>			m_found_characters;
		counter_type					m_found_char_idx{1}; // Consider the NUL character.

	public:
		consecutive_alphabet_as_parallel_builder() = default;

		void init();

		// Map the characters in the given text to consecutive integers.
		// May be called multiple times; the text may be passed in multiple buffers.
		template <typename t_forward_iterable, bool t_parallel = true>
		void prepare(t_forward_iterable const &text);

		template <bool t_parallel = true>
		void compress();

		// Non-template variant.
		void compress();
	};
}

namespace libbio {

	template <typename t_char, template <typename> typename t_map>
	void swap(
		consecutive_alphabet_mt <t_char, t_map> &lhs,
		consecutive_alphabet_mt <t_char, t_map> &rhs
	)
	{
		lhs.swap(rhs);
	}

	template <typename t_char, template <typename> typename t_map>
	void consecutive_alphabet_mt <t_char, t_map>::swap(consecutive_alphabet_mt &other)
	{
		using std::swap;
		swap(m_to_comp, other.m_to_comp);
		swap(m_to_char, other.m_to_char);
	}

	template <typename t_char, template <typename> typename t_map>
	void consecutive_alphabet_mt <t_char, t_map>::print()
	{
		for (std::size_t i(0), count(m_to_char.size()); i < count; ++i)
		{
			t_char const c(m_to_char[i]);
			std::cerr << "[" << i << "]: '" << c << "' ("
			<< std::hex << +c << std::dec << ")\n";

#ifndef LIBBIO_NDEBUG
			auto const comp(m_to_comp[c]);
			libbio_assert(comp == i);
#endif
		}
	}

	template <typename t_char, template <typename> typename t_map>
	template <typename t_archive>
	void consecutive_alphabet_mt <t_char, t_map>::boost_serialize(t_archive &ar, unsigned int const version)
	{
		ar & m_to_comp;
		ar & m_to_char;
	}

	template <typename t_char>
	void consecutive_alphabet_as_builder <t_char>::init()
	{
		m_seen.resize(1 + alphabet_type::ALPHABET_MAX, 0);
		m_seen[0] = 1;
		m_found_characters.push_back('\0');
	}

	template <typename t_char>
	void consecutive_alphabet_as_parallel_builder <t_char>::init()
	{
		m_found_characters.resize(1 + alphabet_type::ALPHABET_MAX, '\0');

		std::vector <std::atomic_flag> temp_flags(1 + alphabet_type::ALPHABET_MAX);
		for (auto &flag : temp_flags)
			flag.clear();
		temp_flags[0].test_and_set();

		m_flags = std::move(temp_flags);
	}

	template <typename t_char>
	template <typename t_forward_iterable>
	void consecutive_alphabet_as_builder <t_char>::prepare(t_forward_iterable const &text)
	{
		for (auto const c : text)
		{
			if (false == m_seen[c])
			{
				// Mark the character as listed.
				m_seen[c] = true;
				m_found_characters.push_back(c);
			}
		}
	}

	// Map the characters in the given text to consecutive integers.
	// May be called multiple times; the text may be passed in multiple buffers.
	template <typename t_char>
	template <typename t_forward_iterable, bool t_parallel>
	void consecutive_alphabet_as_parallel_builder <t_char>::prepare(t_forward_iterable const &text)
	{
		detail::consecutive_alphabet_as_parallel_builder_helper <t_parallel> helper;
		helper.prepare(*this, text);
	}

	template <typename t_char>
	void consecutive_alphabet_as_builder <t_char>::compress()
	{
		// Use O(σ log σ) time to sort the characters.
		std::sort(m_found_characters.begin(), m_found_characters.end());

		auto &to_comp(this->to_comp());
		auto &to_char(this->to_char());

		std::size_t char_idx(0);
		for (auto const c : m_found_characters)
		{
			libbio_assert(1 == m_seen[c]);

			to_comp[c] = char_idx;
			to_char[char_idx] = c;
			++char_idx;
		}
	}

	template <typename t_char>
	template <bool t_parallel>
	void consecutive_alphabet_as_parallel_builder <t_char>::compress()
	{
		// Use O(σ log σ) time to sort the characters.
		// Parallel likely not needed unless t_char is uint16_t.
		std::size_t const count(m_found_char_idx);
		std::size_t char_idx(0);

		detail::consecutive_alphabet_as_parallel_builder_helper <t_parallel> helper;
		helper.sort(m_found_characters.begin(), count + m_found_characters.begin());

		auto &to_comp(this->to_comp());
		auto &to_char(this->to_char());

		for (std::size_t i(0); i < count; ++i)
		{
			auto const c(m_found_characters[i]);
			libbio_assert(m_flags[c].test_and_set());
			to_comp[c] = char_idx;
			to_char[char_idx] = c;
			++char_idx;
		}
	}

	template <typename t_char>
	void consecutive_alphabet_as_parallel_builder <t_char>::compress()
	{
		std::size_t const count(m_found_char_idx);
		if (count < 64) // FIXME: better threshold?
			compress <false>();
		else
			compress <true>();
	}
}

namespace libbio { namespace detail {

	template <bool t_parallel>
	template <typename t_iterator>
	void consecutive_alphabet_as_parallel_builder_helper <t_parallel>::sort(t_iterator begin, t_iterator end)
	{
#if LIBBIO_USE_STD_PARALLEL_FOR_EACH
		std::sort(std::execution::par, begin, end);
#else
		boost::sort::block_indirect_sort(begin, end);
#endif
	}

	template <typename t_iterator>
	void consecutive_alphabet_as_parallel_builder_helper <false>::sort(t_iterator begin, t_iterator end)
	{
		std::sort(begin, end);
	}

	template <bool t_parallel>
	template <typename t_builder, typename t_forward_iterable>
	void consecutive_alphabet_as_parallel_builder_helper <t_parallel>::prepare(t_builder &builder, t_forward_iterable const &text)
	{
		parallel_for_each(
			text,
			[this, &builder](auto const c) {
				if (0 == builder.m_flags[c].test_and_set())
				{
					// Mark the character as listed.
					builder.m_found_characters[builder.m_found_char_idx++] = c;
				}
			}
		);
	}

	template <typename t_builder, typename t_forward_iterable>
	void consecutive_alphabet_as_parallel_builder_helper <false>::prepare(t_builder &builder, t_forward_iterable const &text)
	{
		for (auto const c : text)
		{
			if (0 == builder.m_flags[c].test_and_set())
			{
				// Mark the character as listed.
				builder.m_found_characters[builder.m_found_char_idx++] = c;
			}
		}
	}
}}

namespace boost { namespace serialization {

	template <typename t_archive, typename t_char, template <typename> typename t_map>
	void serialize(t_archive &ar, libbio::consecutive_alphabet_mt <t_char, t_map> &alphabet, unsigned int const version)
	{
		alphabet.boost_serialize(ar, version);
	}
}}

#endif

ext: hh

max_stars_repo_name: tsnorri/libbio

max_issues_repo_name: tsnorri/libbio

max_forks_repo_name: tsnorri/libbio