text:
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "eval.hpp"

int main(int argc, char *argv[]) {
	boost::program_options::options_description opt("Usage");
	opt.add_options()
		("help,h", "Show help messages")
		("version,v", "Show version informaion");

	boost::program_options::variables_map argmap;
	boost::program_options::store(parse_command_line(argc, argv, opt), argmap);
	boost::program_options::notify(argmap);

	evaluator _evaluator;

	std::string buf;
	while( getline(std::cin, buf) ) {
		std::vector<std::string> l;
		boost::algorithm::split(l, buf, boost::algorithm::is_any_of(","));

		if (l.size() == 3) {
			_evaluator.add( l[0], l[1], l[2] );
		}
		else {
			std::cerr << "WARN: invalid format " << buf << std::endl;
		}
	}

	_evaluator.eval();

	std::cout << "* confusion matrix" << std::endl;
	_evaluator.print_confusion_matrix();

	std::cout << "* Precision and Recall" << std::endl;
	_evaluator.print_prec_rec();

	double acc = _evaluator.accuracy();
	std::cout << "* Accuracy" << std::endl;
	std::cout << acc << std::endl;

	return true;
}

ext: cpp


text:
//
// Copyright (c) 2020 Richard Hodges (hodges.r@gmail.com)
//
// 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)
//
// Official repository: https://github.com/madmongo1/webclient
//
// This project was made possible with the generous support of:
// The C++ Alliance (https://cppalliance.org/)
// Jetbrains (https://www.jetbrains.com/)
//
// Talk to us on Slack (https://cppalliance.org/slack/)
//
// Many thanks to Vinnie Falco for continuous mentoring and support
//

#ifndef BOOST_WEBCLIENT_ASYNC_DETAIL__FUTURE_WAIT_OP__HPP
#define BOOST_WEBCLIENT_ASYNC_DETAIL__FUTURE_WAIT_OP__HPP

#include <boost/webclient/async/detail/future_invoker.hpp>
#include <boost/webclient/async/detail/future_state_impl.hpp>
#include <boost/webclient/async/future_types.hpp>
#include <boost/webclient/config.hpp>
#include <boost/webclient/polyfill/make_unique.hpp>

namespace boost { namespace webclient { namespace async { namespace detail {

template < class T >
struct future_wait_op
{
    template < class Self >
    void operator()(Self &self)
    {
        // initial operation
        shared_state_->set_invoker(polyfill::make_unique< future_invoker< T, Self > >(std::move(self)));
    }

    template < class Self >
    void operator()(Self &self, future_result_type< T > &&value)
    {
        self.complete(std::move(value));
    }

    std::shared_ptr< future_state_impl< T > > shared_state_;
};

}}}}   // namespace boost::webclient::async::detail

#endif   // BOOST_WEBCLIENT_ASYNC_DETAIL__FUTURE_WAIT_OP__HPP

ext: hpp


text:
#include <boost/numpy.hpp>
#include <cmath>
#include "mjc/core/slcp.h"
#include "macros.h"
#include <iostream>
#include "mjc/core/mj_render.h"
#include <boost/python/slice.hpp>

namespace bp = boost::python;
namespace bn = boost::numpy;

template<typename T>
bn::ndarray toNdarray1(const T* data, long dim0) {
  long dims[1] = {dim0};
  bn::ndarray out = bn::empty(1, dims, bn::dtype::get_builtin<T>());
  memcpy(out.get_data(), data, dim0*sizeof(T));
  return out;
}
template<typename T>
bn::ndarray toNdarray2(const T* data, long dim0, long dim1) {
  long dims[2] = {dim0,dim1};
  bn::ndarray out = bn::empty(2, dims, bn::dtype::get_builtin<T>());
  memcpy(out.get_data(), data, dim0*dim1*sizeof(T));
  return out;
}
template<typename T>
bn::ndarray toNdarray3(const T* data, long dim0, long dim1, long dim2) {
  long dims[3] = {dim0,dim1,dim2};
  bn::ndarray out = bn::empty(3, dims, bn::dtype::get_builtin<T>());
  memcpy(out.get_data(), data, dim0*dim1*dim2*sizeof(T));
  return out;
}

enum ContactType {
  ContactType_SPRING=0,
  ContactType_SLCP=1,
  ContactType_SPRINGTAU=2,
  ContactType_CONVEX=3
};

#define  NV (m_model->ndof)
#define  NQ (m_model->nqpos)
#define  NBODY (m_model->nbody)
#define  NL (m_model->nlmax)
#define  NC (m_model->ncmax)

const int Integrator_FWD=1;

class PyMJCWorld {

public:

    PyMJCWorld(const std::string& binfile);
    bn::ndarray Step(const bn::ndarray& x, const bn::ndarray& u);
    bn::ndarray StepMulti(const bn::ndarray& x, const bn::ndarray& u);
    bp::tuple StepMulti2(const bn::ndarray& x, const bn::ndarray& u, const bn::ndarray& done);
    bp::tuple StepJacobian(const bn::ndarray& x, const bn::ndarray& u);
    void Plot(const bn::ndarray& x);
    void SetActuatedDims(const bp::object& dims);
    void SetContactType(ContactType contactType) {
      m_contactType = contactType;
    }
    void SetTimestep(mjtNum dt) {
      m_model->timestep = dt;
    }
    bn::ndarray ComputeContacts(const bn::ndarray& x);
    bp::dict GetModel();
    void SetModel(bp::dict);
    bp::dict GetData(const bn::ndarray& x);

    bn::ndarray GetImage(const bn::ndarray& x);

    ~PyMJCWorld();
private:
    // PyMJCWorld(const PyMJCWorld&) {}

    void _PlotInit();
    mjtByte _StepLowLevel(const mjtByte flgDiff, const mjtNum* tu,
          mjtNum* contact_scratch, mjtNum *f_ctr,
          mjtNum *plam, mjtNum *pdist, mjtNum *pdebug, mjtNum *s,
          mjtNum *jac, mjtNum *f_j);

    void _PreProcess();
    mjtNum _ContactImpulse(mjtNum* contact_scratch, mjtNum *f_ctr, const mjtNum *qvel_next_user);

    void _SetState(const mjtNum* xdata) {mju_copy(m_data->qpos, (xdata), NQ); mju_copy(m_data->qvel, (xdata)+NQ, NV); }
    void _SetControl(const mjtNum* udata) {for (int i=0; i < m_actuatedDims.size(); ++i) m_u[m_actuatedDims[i]] = (udata)[i];}
    void _ComputeCOM(mjtNum* out);

    mjModel* m_model;
    mjData* m_data;
    mjRender* m_mjr;
    std::vector<mjtNum> m_u;
    std::vector<int> m_actuatedDims;
    ContactType m_contactType;
    int m_integrator;

    mjtByte m_flagPrehoc;

    mjtNum m_spring_kspring, m_spring_kdamp;
    mjtByte m_spring_scale;

    mjtNum m_st_tau, m_st_beta; // recovery time, softness

    mjtNum m_slcp_tau, m_slcp_beta, m_slcp_tau2;   // ? ? ?
    int m_slcp_iterCloud;
    int m_slcp_maxIter;
    mjtNum* m_slcp_betaVec; // XXX i'm not sure what this is.

    mjtByte m_flagPlanar;
    double *pDBG, *pXIN, *pUIN, *pXOUT, *pLAM, *pDIST, *pS, *pJAC, *pF_J;
    double *pPUSH_BODY, *pPUSH_POINT, *pPUSH_FORCE;
    int NS, NDS;
    int m_SZ_F, m_SZ_DIST, m_SZ_DISTX;
    // int FLG_CONTACT, FLG_FWD;
    double* FEAT;
    mjtNum* cscratch[1];

};

PyMJCWorld::PyMJCWorld(const std::string& binfile) :
  m_model(mj_loadModel(binfile.c_str())),
  m_data(mj_makeData(m_model)),
  m_mjr(NULL),
  m_u(NV, 0),
  m_actuatedDims(),

  m_contactType(ContactType_SPRING),
  m_integrator(Integrator_FWD),
  m_flagPrehoc(true),

  m_spring_kspring(0),
  m_spring_kdamp(0),
  m_spring_scale(false),

  m_st_tau(0.04), // depth of penetration
  m_st_beta(0.1),

  m_slcp_tau(0.04), // depth of penetration
  m_slcp_beta(0.001),
  m_slcp_tau2(0.04),
  m_slcp_iterCloud(2), // ??
  m_slcp_maxIter(10),
  m_slcp_betaVec(new mjtNum[(m_flagPlanar?2:4)*NC+NL]),

  m_flagPlanar(((m_model->jnt_type[0]==mjSLIDE)&&(m_model->jnt_type[1]==mjSLIDE)&&(m_model->jnt_type[2]==mjHINGE))),

  pDBG(NULL),
  pXIN(NULL),
  pUIN(NULL),
  pXOUT(NULL),
  pLAM(NULL),
  pDIST(NULL),
  pS(NULL),
  pJAC(NULL),
  pF_J(NULL),
  pPUSH_BODY(NULL),
  pPUSH_POINT(NULL),
  pPUSH_FORCE(NULL),

  NS(0),
  NDS(0),

  m_SZ_F(mjConDim*NC+NL),
  m_SZ_DIST(NC+NL),
  m_SZ_DISTX(4*NC+NL),

  FEAT(NULL)
{

    _PreProcess();

    printf("Damping[0]: %f\n", m_model->jnt_vel_damping[0]);
    printf("Gravity: %f %f %f\n", m_model->gravity[0], m_model->gravity[1], m_model->gravity[2]);
    printf("Viscosity: %f\n", m_model->viscosity);
    printf("Timestep: %f\n", m_model->timestep);

}

PyMJCWorld::~PyMJCWorld() {
  if (m_mjr) {
    m_mjr->Close();
    delete m_mjr;
  }
  mj_delete(m_model, m_data);
  delete[] m_slcp_betaVec;
}

#define MJTNUM_DTYPE bn::dtype::get_builtin<mjtNum>()
#define CHECK_MJTNUM_ARRAY(x,ndim) FAIL_IF_FALSE((x).get_dtype() == MJTNUM_DTYPE && (x).get_nd() == (ndim) && (x).get_flags() & bn::ndarray::C_CONTIGUOUS)
// #define ENSURE_MJTNUM_ARRAY(x) FAIL_IF_FALSE( x.get_dtype() ==  )

#define DO_STEP() do {_StepLowLevel(flgDiff, m_u.data(), cscratch[0], f_ctr, pLAM, pDIST, pDBG, s, jac, f_j);} while(0)

#define COPY_STATE(dest) do {mju_copy((dest), m_data->qpos, NQ); mju_copy((dest)+NQ, m_data->qvel, NV); } while(0)
#define INC_BY_STATE(dest) do {mju_add((dest), (dest), m_data->qpos, NQ); mju_add((dest)+NQ, (dest)+NQ, m_data->qvel, NV); } while(0)
#define DEC_BY_STATE(dest) do {mju_sub((dest), (dest), m_data->qpos, NQ); mju_sub((dest)+NQ, (dest)+NQ, m_data->qvel, NV); } while(0)
#define SCALE_INPLACE(p, scl, n) mju_scl((p), (p), (scl), (n))

#define PYPRINT(obj) do{std::string s1 = bp::extract<std::string>((obj).attr("__repr__")()); std::cout << s1 << std::endl;} while(0)

bn::ndarray PyMJCWorld::Step(const bn::ndarray& x, const bn::ndarray& u) {
  CHECK_MJTNUM_ARRAY(x, 1);
  CHECK_MJTNUM_ARRAY(u, 1);
  FAIL_IF_FALSE(u.shape(0) == m_actuatedDims.size());

  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());

  _SetState(xdata);
  _SetControl(udata);

  mjtByte flgDiff=1;
  mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;
  DO_STEP();

  bn::ndarray out = bn::empty(bp::make_tuple(NQ+NV), bn::dtype::get_builtin<mjtNum>());
  mjtNum* outdata = reinterpret_cast<mjtNum*>(out.get_data());
  COPY_STATE(outdata);
  return out;
}

bn::ndarray PyMJCWorld::StepMulti(const bn::ndarray& x, const bn::ndarray& u) {
  CHECK_MJTNUM_ARRAY(x, 2);
  CHECK_MJTNUM_ARRAY(u, 2);

  int n_steps = x.shape(0);
  FAIL_IF_FALSE (u.shape(0) == x.shape(0));

  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());

  const int NX = NQ + NV, NU = m_actuatedDims.size();

  bn::ndarray out = bn::empty(bp::make_tuple(n_steps,NX), bn::dtype::get_builtin<mjtNum>());
  mjtNum* outdata = reinterpret_cast<mjtNum*>(out.get_data());

  for (int i=0; i < n_steps; ++i) {
    _SetState(xdata + NX*i);
    _SetControl(udata + NU*i);

    mjtByte flgDiff=1;
    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;
    DO_STEP();
    COPY_STATE(outdata + NX*i);
  }

  return out;
}

bp::tuple PyMJCWorld::StepMulti2(const bn::ndarray& x, const bn::ndarray& u, const bn::ndarray& done) {
  CHECK_MJTNUM_ARRAY(x, 2);
  CHECK_MJTNUM_ARRAY(u, 2);

  const int xcols = NQ+NV,
               ucols = m_actuatedDims.size(),
               ycols = NQ+NV,
               fcols=m_model->ndof,
               dcomcols = 3,
               distcols = m_model->nbody,
               kincols = m_model->ndof*7 + m_model->nbody*28;
  int n_steps = x.shape(0);

  // kincols is cdof thru qfrc_bias inclusive

  FAIL_IF_FALSE (u.shape(0) == x.shape(0));
  FAIL_IF_FALSE(u.shape(1) == ucols);
  FAIL_IF_FALSE(x.shape(1) == xcols);

  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
  mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());

  uint8_t* donedata = reinterpret_cast<uint8_t*>(done.get_data());

  bn::ndarray yarray = bn::zeros(bp::make_tuple(n_steps,ycols), bn::dtype::get_builtin<mjtNum>());
  bn::ndarray farray = bn::zeros(bp::make_tuple(n_steps,fcols), bn::dtype::get_builtin<mjtNum>());
  bn::ndarray dcomarray = bn::zeros(bp::make_tuple(n_steps,dcomcols), bn::dtype::get_builtin<mjtNum>());
  bn::ndarray distarray = bn::zeros(bp::make_tuple(n_steps,distcols), bn::dtype::get_builtin<mjtNum>());
  bn::ndarray kinarray = bn::zeros(bp::make_tuple(n_steps,kincols), bn::dtype::get_builtin<mjtNum>());

  mjtNum* ydata = reinterpret_cast<mjtNum*>(yarray.get_data());
  mjtNum* fdata = reinterpret_cast<mjtNum*>(farray.get_data());
  mjtNum* dcomdata = reinterpret_cast<mjtNum*>(dcomarray.get_data());
  mjtNum* distdata = reinterpret_cast<mjtNum*>(distarray.get_data());
  mjtNum* kindata =  reinterpret_cast<mjtNum*>(kinarray.get_data());

  for (int i=0; i < n_steps; ++i) {

    if (donedata[i]) continue;

    _SetState(xdata + xcols*i);
    _SetControl(udata + ucols*i);

    mjtByte flgDiff=1;
    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;

    mjtNum *plam = fdata + fcols*i; // note mju_copy(plam, d->lc_f, m->ndof);
    mjtNum *pdist = distdata + distcols*i;

    mjtNum comBefore[3];
    mj_kinematics(m_model, m_data);
    _ComputeCOM(comBefore); // XXX extra calculation

    _StepLowLevel(flgDiff, m_u.data(), cscratch[0], f_ctr, plam, pdist, pDBG, s, jac, f_j);

    COPY_STATE(ydata + ycols*i); // y
    mju_copy(kindata + kincols*i, m_data->cdof, kincols);
    // f is handled by steplowlevel
    mjtNum comAfter[3]; // dcom
    mj_kinematics(m_model, m_data);
    _ComputeCOM(comAfter); // XXX extra calculation
    mju_sub(dcomdata + dcomcols*i, comAfter, comBefore, 3);
    // dist is handled by steplowlevel

  }

  return bp::make_tuple(yarray, farray, dcomarray, distarray, kinarray);
}

void PyMJCWorld::_ComputeCOM(mjtNum* com) {
	 // XXX is idx 0 always the ground?
  mjtNum tot=0;
  com[0] = com[1] = com[2] = tot = 0;
  for(int i=1; i<m_model->nbody; i++ )
  {
    if( m_model->geom_type[i]==mjPLANE ) continue;
    com[0] += m_data->xpos[3*i+0]*m_model->body_mass[i];
    com[1] += m_data->xpos[3*i+1]*m_model->body_mass[i];
    com[2] += m_data->xpos[3*i+2]*m_model->body_mass[i];
    tot += m_model->body_mass[i];
  }
  com[0] /= tot;
  com[1] /= tot;
  com[2] /= tot;
}

bp::tuple PyMJCWorld::StepJacobian(const bn::ndarray& x, const bn::ndarray& u) {
    CHECK_MJTNUM_ARRAY(x, 1);
    CHECK_MJTNUM_ARRAY(u, 1);
    FAIL_IF_FALSE(u.shape(0) == m_actuatedDims.size());

    mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
    mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());

    for (int i=0; i < m_actuatedDims.size(); ++i) {
      m_u[m_actuatedDims[i]] = udata[i];
    }

    mjtByte flgDiff=1;
    mjtNum *s=0, *jac=0, *f_j=0, *f_ctr=0;

    const int NX = NQ+NV, NU = m_actuatedDims.size();
    bn::ndarray y =    bn::zeros(bp::make_tuple(NX), bn::dtype::get_builtin<mjtNum>());
    bn::ndarray dydx = bn::zeros(bp::make_tuple(NX, NX), bn::dtype::get_builtin<mjtNum>());
    bn::ndarray dydu = bn::zeros(bp::make_tuple(NU, NX), bn::dtype::get_builtin<mjtNum>());

    mjtNum* py = reinterpret_cast<mjtNum*>(y.get_data());
    mjtNum* pdydx = reinterpret_cast<mjtNum*>(dydx.get_data());
    mjtNum* pdydu = reinterpret_cast<mjtNum*>(dydu.get_data());

    mjtNum eps=1e-6;

    _SetState(xdata);
    _SetControl(udata);
    DO_STEP();
    COPY_STATE(py);
    for (int i=0; i < NX; ++i) { // XXX LOL using the fact that qpos and qvel are stored next to each other continguously

      _SetState(xdata);
      m_data->qpos[i] += eps;
      DO_STEP();
      INC_BY_STATE(pdydx+i*NX);

      _SetState(xdata);
      m_data->qpos[i] -= eps;
      DO_STEP();
      DEC_BY_STATE(pdydx+i*NX);

      SCALE_INPLACE(pdydx + i*NX, 1./(2.*eps), NX);

    }

    for (int i=0; i < NU; ++i) {

      _SetState(xdata);
      m_u[m_actuatedDims[i]] = udata[i] + eps;
      DO_STEP();
      INC_BY_STATE(pdydu + i*NX);

      _SetState(xdata);
      m_u[m_actuatedDims[i]] = udata[i] - eps;
      DO_STEP();
      DEC_BY_STATE(pdydu + i*NX);

      m_u[m_actuatedDims[i]] = udata[i];

      SCALE_INPLACE(pdydu + i*NX, 1./(2.*eps), NX);

    }

  return bp::make_tuple(y, dydx.transpose(), dydu.transpose());
}

void PyMJCWorld::Plot(const bn::ndarray& x) {
    CHECK_MJTNUM_ARRAY(x, 1);
    if (!m_mjr) _PlotInit();

    mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
    // mjtNum* udata = reinterpret_cast<mjtNum*>(u.get_data());

    _SetState(xdata);
    mj_kinematics(m_model, m_data);
    mj_global(m_model, m_data);

    m_mjr->Update(m_model, m_data);

}

bn::ndarray PyMJCWorld::GetImage(const bn::ndarray& x) {
  long dims[3]={480,640,4};
  bn::ndarray out = bn::empty(3, dims, bn::dtype::get_builtin<uint8_t>());
  Plot(x);
  m_mjr->SaveImage(out.get_data());
  using bp::_;
  using bp::slice;
  // using bp::slice;
  // return out;
  out = bp::extract<bn::ndarray>(out[bp::make_tuple(slice(_,_,-1),slice(),bp::make_tuple(2,1,0))].attr("copy")());
  return out;
}

void PyMJCWorld::SetActuatedDims(const bp::object& dims) {
  m_u.assign(NV, 0);
  int ndims = bp::len(dims);
  m_actuatedDims.clear();
  for (int i=0; i < ndims; ++i) {
    m_actuatedDims.push_back(bp::extract<int>(dims[i]));
  }
}

void PyMJCWorld::_PlotInit() {
  m_mjr = new mjRender();
  int x        = 0;
  int y        = 0;
  int width    = 640;
  int height   = 480;
  m_mjr->Open(m_model->name, x, y, width, height);
  m_mjr->Set(m_model, m_data);
}

void PyMJCWorld::_PreProcess() {

  // Original code:
  mj_solve1(m_model, m_data);
  mj_contactPrepare(m_model, m_data, 0);
  mj_solve2(m_model, m_data);
  m_data->nlim=m_model->nlmax;
  m_data->ncon=m_model->ncmax;

  // for (int i=0; i < sz_pyramid; ++i) m_slcp_betaVec[i] = 0; // siminit.m line 72
}

mjtNum PyMJCWorld::_ContactImpulse(mjtNum* contact_scratch, mjtNum *f_ctr, const mjtNum * /*qvel_next_user*/) {
  mjModel* m=m_model;
  mjData* d = m_data;

  mjtNum dbg, mu;
  int j, stepDbg;

  #if 0
  mjtNum *alpha, *kappaN, *kappaT, *kappaV, *contact_buffer, *P
  int sz_dist = nl+nc;
  #endif

  mjtNum *J, *A, *f, *v, *scratch;
  mjtByte inCloud;
  int nl    = d->nlim;
  int nc    = d->ncon;
  int sz = nl+mjConDim*nc;
  int sz_pyramid = (m_flagPlanar?2:4)*nc+nl;

   //no need to zero - contactPrepare did that already
   //mju_zero(d->lc_f, SZ_F);

   switch( m_contactType ) {
      case ContactType_SPRING:
         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);
         mj_impulseSpring(m, d, m_spring_kspring, m_spring_kdamp, 1, 1, m_spring_scale);
         return 0;
      case ContactType_SPRINGTAU:
      case ContactType_SLCP:
         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);
     if (m_contactType == ContactType_SPRINGTAU)
      mj_impulseTau(m, d, m_st_tau, m_st_beta);
     else
      mj_impulseTau2(m, d, m_slcp_tau, m_slcp_tau2, m_slcp_beta, m_slcp_maxIter);
     return 0; // This is a little hack - in this formulation, SLCP no longer exists, there is only springtau
         //if( FLG_CONTACT==CF_SPRINGTAU && !ITER_CLOUD ) return 0; //otherwise, continue with slcp
         f       = contact_scratch;
         v       = contact_scratch + sz_pyramid;
         J       = contact_scratch + sz_pyramid*2;
         A       = contact_scratch + sz_pyramid*2 + sz_pyramid*NV;
         scratch = contact_scratch + sz_pyramid*2 + sz_pyramid*NV + sz_pyramid*sz_pyramid;
         mju_mulMatVec(v, J, d->qvel_next, sz_pyramid, NV);
         sz_pyramid = convexify(m, d, m_flagPlanar, f, v, J, A);

         if( m_contactType==ContactType_SLCP ) { //if we came here from springTau, lc_f is already initialized
#ifdef _WIN32
            inCloud= (f_ctr && !_isnan(f_ctr[0]));
#else
            inCloud= (f_ctr && !std::isnan(f_ctr[0]));
#endif
            if (!inCloud) {
               // tol = 1e-15
               dbg=slcp_solve(sz_pyramid, A, v, f, m_slcp_betaVec, 1E-15, m_slcp_maxIter, scratch);
               if( dbg<0 )
                  return dbg;
               if (f_ctr) mju_copy(f_ctr, f, sz_pyramid);
            } else {
               mju_copy(f, f_ctr, sz_pyramid);
            }
         }
         for (j=0;j<m_slcp_iterCloud;j++) {
            mu=-1; //a small regularizing term to deal with rank-deficient A
            stepDbg = slcp_step(sz_pyramid, A, v, f, m_slcp_betaVec, scratch, scratch+sz_pyramid, &mu);
            if( stepDbg<0 ) return stepDbg-0.1234567;
         }
         deconvexify(m, d, m_flagPlanar, f); // assigns into d->lc_f

         //test: J*f should be equal to lc_J*lc_f:
         //mju_mulMatTVec(ds,J,f,LOCAL_sz_cl,NV);
         //mju_mulMatTVec(ds+SZ_F,d->lc_J,d->lc_f,SZ_F,NV);
         return dbg;

      case ContactType_CONVEX:
        NOTIMPLEMENTED;
        #if 0
         kappaN = contact_scratch;
         kappaT = contact_scratch + sz_dist;
         kappaV = contact_scratch + sz_dist*2;
         alpha  = contact_scratch + sz_dist*3;
         makeKappa(pkappal[0],pkappac[0], kappaN, d->lc_A, nl, nc);
         makeKappa(0         ,pkappac[1], kappaT, d->lc_A, nl, nc);
         makeKappa(pkappal[1],pkappac[2], kappaV, d->lc_A, nl, nc);
#ifdef _WIN32
         inCloud= (f_ctr && !_isnan(f_ctr[0]));
#else
         inCloud= (f_ctr && !std::isnan(f_ctr[0]));
#endif

         //initialize:
         mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);
         mj_impulseTau(m, d, TAU_SPRING, BETA_SPRING);

         if (FLG_FWD>0) {
            contact_buffer = contact_scratch + sz_dist*3 + sz;
            if (!inCloud) {
               dbg=mj_impulseConvex(d->lc_f, m, d, kappaN, kappaT, kappaV,
                       dmax, amin, amaxl, amaxc, marginF, marginV, 1e-15, MAX_ITER, contact_buffer);
               if( dbg<0 )
                  return dbg;
               if (f_ctr) mju_copy(f_ctr, d->lc_f, sz);
            } else {
               mju_copy(d->lc_f, f_ctr, sz);
            }
            makeAlpha(alpha, d->lc_dist, amin, amaxl, amaxc, dmax, d->lc_A, nl, nc);
            for (j=0;j<ITER_CLOUD;j++) {
               contact_buffer[sz]=0;
               stepDbg = convex_fwdIter(d->lc_f, m, nl, nc,
                       alpha, kappaN, kappaT, kappaV,
                       d->con_friction, d->lc_A, d->lc_v0, d->lc_vmin,
                       marginF, marginV, contact_buffer, contact_buffer+sz);
               if( stepDbg ) return stepDbg+0.7654321;
            }
         } else { //inv dyn
            P              = contact_scratch + sz_dist*3 + sz;
            contact_buffer = contact_scratch + sz_dist*3 + sz*2;
            mju_copy(d->qvel_next, qvel_next_user, NV);
            mju_mulMatVec(d->lc_v0, d->lc_J, d->qvel_next, sz, NV);
            if (!inCloud) {
               dbg=mj_impulseConvexInv(d->lc_f, m, d, kappaN, kappaT, kappaV,
                       dmax, amin, amaxl, amaxc, marginF, marginV, 1e-15, MAX_ITER, contact_buffer);
               if( dbg<0 )
                  return dbg;
               if (f_ctr) mju_copy(f_ctr, d->lc_f, sz);
            } else {
               mju_copy(d->lc_f, f_ctr, sz);
            }
            mju_zero(alpha, sz);
            makeP(P, d->lc_A, alpha, d->lc_v0, d->lc_vmin, nl, nc, kappaV, marginV);
            makeAlpha(alpha, d->lc_dist, amin, amaxl, amaxc, dmax, d->lc_A, nl, nc);
            for (j=0;j<ITER_CLOUD;j++) {
               contact_buffer[sz]=0;
               stepDbg=convex_invIter(d->lc_f, m, nl, nc,
                       alpha, kappaN, kappaT,
                       d->con_friction, d->lc_A, P,
                       marginF, contact_buffer, contact_buffer+sz);
               if( stepDbg ) return stepDbg+0.7654321;
            }
         }
         return dbg;
         #endif
   }

   PRINT_AND_THROW("UNREACHABLE");
   return 0;
}

mjtByte PyMJCWorld::_StepLowLevel(const mjtByte flgDiff, const mjtNum* tu,
        mjtNum* contact_scratch, mjtNum *f_ctr,
        mjtNum *plam, mjtNum *pdist, mjtNum *pdebug, mjtNum *s,
        mjtNum *jac, mjtNum *f_j) {

  mjModel* m=m_model;
  mjData* d=m_data;
   int i, j, k, n;
   mjtNum *ds = d->scratch;
   mjtNum dbg, total_mass;
   mjtByte needCoM;

   if (flgDiff) {
      // run kinematic computations
      mj_kinematics(m, d);
      mj_global(m, d);
      mj_crb(m, d);
      mj_factorM(m, d);
      if (m_SZ_F) {
         mj_contactPrepare(m, d, (tu?0:2));//(FLG_CONTACT==CF_SPRINGTAU && !ITER_CLOUD));
      }
   } else {
      // global does this, so if we're not running global, we should manually zero it out
      mju_zero(d->qfrc_ext, NV);
      // contactPrepare does this
      mju_zero(d->lc_f, m_SZ_F);
   }
   mj_rne(m, d, 0);
   mj_passive(m, d);

   if( s ) {
      needCoM = 0;
      i=0;
      // start with CoM:

      // CoM quat space:
      if( FEAT[0] ) i+=4;
      // CoM position:
      for( k=0; k<3; k++ ) {
         if( FEAT[1+k] != 0.0 ) {
            s[i]=d->com[k];
            i++;
            needCoM++;
         }
      }
      // CoM velocities:
      for( k=0; k<6; k++ ) {
         if( FEAT[4+k] != 0.0 ) {
            s[i]=d->cvel[k];
            i++;
         }
      }

      for (j=1;j<NBODY;j++) {
         // quaternion
         if( FEAT[10*j] != 0.0 ) {
            for( k=0; k<4; k++ ) {
               s[i]=d->xquat[4*j+k];
               i++;
            }
         }
         // position
         for( k=0; k<3; k++ ) {
            if( FEAT[10*j+1+k] != 0.0 ) {
         if ( FEAT[10*j+1+k] == 2.0 ) // Use xanchor
                  s[i]=d->xanchor[3*m->body_jnt_adr[j]+k];
         else // Use regular position
          s[i]=d->xpos[3*j+k];
               i++;
            }
         }
         // velocities
         for( k=0; k<6; k++ ) {
            if( FEAT[10*j+4+k] != 0.0 ) {
               s[i]=d->cvel[6*j+k];
               i++;
            }
         }
      }
    //test:
      //if( i!=NS ) s[0]=sqrt((double)-1.0);
      if( jac ) { //need to compute jacs as well
         total_mass=0;
         i=needCoM; //save room for the CoM's jac, which will be created last
         if( FEAT[0] != 0.0 ) i+=3; //save useless room for the CoM's nonexistent quat's jac
         for( j=1; j<NBODY; j++ ) {
            if( FEAT[10*j] != 0.0 ) {
               mj_jac(m, d, 0, ds, 0, j, 1);
               for( k=0; k<3; k++ ) {
                  mju_copy(jac+i*NV, ds+k*NV, NV);
                  i++;
               }
            }
            if( needCoM || FEAT[10*j+1] != 0.0 || FEAT[10*j+2] != 0.0 || FEAT[10*j+3] != 0.0 ) {
               mj_jac(m, d, ds, 0, 0, j, 1);
               for( k=0; k<3; k++ ) {
                  if( FEAT[10*j+1+k] != 0.0 ) {// keep this body's jac:
                     mju_copy(jac+i*NV, ds+k*NV, NV);
                     i++;
                  }
               }
               if( needCoM ) { // building the CoM's jac:
                  n=0;
                  total_mass+=m->body_mass[j];
                  mju_scl(ds, ds, m->body_mass[j], 3*NV);  //scale by body mass
                  for( k=0; k<3; k++ ){
                     if( FEAT[1+k] != 0.0 ) {
                        mju_addTo(jac+n*NV, ds+k*NV, NV);
                        n++;
                     }
                  }
               }
            }
         }
         if( needCoM ) mju_scl(jac, jac, 1/total_mass, needCoM*NV);
      }
   }

   if( f_j ) mju_copy(f_j, d->lc_J, (d->nlim+mjConDim*d->ncon)*NV);

   if( pdist )  {
    // store the smallest contact distance for each body.
      // first, set all contact distances to the maximum value.
      for (i = 0; i < NBODY; i++)
      pdist[i] = 1000.0;
    for (j = 0; j < d->ncon; j++)
    {
      // Address of bodies.
      if (d->con_pair[j] >= m->ncpair) continue;
      int b1 = m->geom_body_id[m->pair_geom1[d->con_pair[j]]];
      int b2 = m->geom_body_id[m->pair_geom2[d->con_pair[j]]];
      double pen = d->lc_dist[d->nlim+j];
      if (pdist[b1] > pen)
        pdist[b1] = pen;
      if (pdist[b2] > pen)
        pdist[b2] = pen;
      // Make sure the ground is one of the bodies -- otherwise we need some special handling.
      //if (b1 != 0 && b2 != 0)
      //  mexErrMsgTxt("Returning X distance and detected collision not with the ground -- consider adding some code to handle this!");
    }
      //min2full_dist(d, d->lc_dist, pdist);
      //min2full_xpos(d, d->con_xpos, pdist+SZ_DIST);
   }

   if( !tu ) return 0;

   if (m_SZ_F && m_flagPrehoc==0) {
      mj_solve2(m, d);
   }
   else {
      if (m_integrator>0) {
        mju_addTo(d->qfrc_ext, tu, NV);
      }
      mj_solve2(m, d);
   }
   if (m_SZ_F) {
      dbg = _ContactImpulse(contact_scratch, f_ctr, tu); //we give tu to contact because
   }

   if (m_integrator>0) {
      if (m_flagPrehoc==0) {
         mj_backsubM(m, d, d->qacc, tu);
         mju_scl(d->qacc, d->qacc, m->timestep, NV);
         mju_addTo(d->qvel_next, d->qacc, NV);
      }
      mj_solve3(m, d);
      mj_integrate(m, d);
   } else {
      mju_mulMatTVec(d->scratch, d->lc_JP, d->lc_f, m_SZ_F, NV);
      mju_sub(d->qvel_next, tu, d->scratch, NV);
      mju_sub(d->qvel_next, d->qvel_next, d->qvel, NV);
      mju_scl(d->qacc, d->qvel_next, 1/m->timestep, NV);
      mj_fullM(m, d, d->scratch, d->qM);
      mju_mulMatVec(d->qvel_next, d->scratch, d->qacc, NV, NV);
      //first i multiplied by JP, then mult by fullM;
      //alternatively, maybe mult by J and not mult that piece by M?
      mju_sub(d->qvel_next, d->qvel_next, d->qfrc_bias, NV);
      mju_sub(d->qvel_next, d->qvel_next, d->qfrc_ext, NV);
   }

   if( plam ) { // return contact forces.
    int sz = d->nlim + mjConDim*d->ncon;
    //mju_mulMatTVec(d->scratch, d->lc_JP, d->lc_f, sz, m->ndof); // This version computes accelerations.
    mju_mulMatTVec(d->scratch, d->lc_J, d->lc_f, sz, m->ndof); // This version computes forces.
    mju_copy(plam, d->scratch, m->ndof);
    //min2full_lam(d, d->lc_f, plam);
   }
   if( pdebug ) pdebug[0]=dbg;
   return 0;
}

bn::ndarray PyMJCWorld::ComputeContacts(const bn::ndarray& x) {

  CHECK_MJTNUM_ARRAY(x, 1);
  mjtNum* xdata = reinterpret_cast<mjtNum*>(x.get_data());
  _SetState(xdata);
  mj_kinematics(m_model, m_data);
  mj_global(m_model, m_data);

  bn::ndarray dists = bn::empty(bp::make_tuple(m_model->nbody), bn::dtype::get_builtin<mjtNum>());
  mjtNum* distsdata = reinterpret_cast<mjtNum*>(dists.get_data());
  for (int i=0; i < m_model->nbody; ++i) {
    // printf("body %i parent id %i\n", i, m_model->body_parent_id[i]);
    distsdata[i] = 1000;
  }

  // Code copied from mj_contactPrepare
  mjContact con[mjMaxConPair];
  mjModel* m=m_model;

  for(int i=0; i<m->ncpair; i++ )
    if( m->pair_enable[i] )
    {
      // get geom ids
      int gid1 = m->pair_geom1[i];
      int gid2 = m->pair_geom2[i];

      int num = conFunction[m->pair_type[i]](con, m->mindist[0],
        m_data->geom_xpos+3*gid1, m_data->geom_xmat+9*gid1, m->geom_size+mjNumSize*gid1,
        m_data->geom_xpos+3*gid2, m_data->geom_xmat+9*gid2, m->geom_size+mjNumSize*gid2);

      if( num > conInfo[m->pair_type[i]][0] )
        mju_error("too many contacts in geom pair");

      // process all returned contacts
      for(int j=0; j<num; j++ )
      {
        mjtNum dist = -con[j].depth;
        int bid1 = m_model->geom_body_id[gid1];
        int bid2 = m_model->geom_body_id[gid2];
        distsdata[bid1] = fmin(dist, distsdata[bid1]);
        distsdata[bid2] = fmin(dist, distsdata[bid2]);
      }
    }
  return dists;

}

int _ndarraysize(const bn::ndarray& arr) {
  int prod = 1;
  for (int i=0; i < arr.get_nd(); ++i) {
    prod *= arr.shape(i);
  }
  return prod;
}
template<class T>
void _copyscalardata(const bp::object& from, T& to) {
  to = bp::extract<T>(from);
}
template <short ndim,typename T>
void _copyarraydata(const bn::ndarray& from, T* to) {
  FAIL_IF_FALSE(from.get_dtype() == bn::dtype::get_builtin<T>() && from.get_nd() == ndim && from.get_flags() & bn::ndarray::C_CONTIGUOUS);
  memcpy(to, from.get_data(), _ndarraysize(from)*sizeof(T));
}

template<typename T>
void _csdihk(bp::dict d, const char* key, T& to) {
  // copy scalar data if has_key
  if (d.has_key(key)) _copyscalardata(d[key], to);
}
template<short ndim, typename T>
void _cadihk(bp::dict d, const char* key, T* to) {
  // copy array data if has_key
  if (d.has_key(key)) {
    bn::ndarray arr = bp::extract<bn::ndarray>(d[key]);
    _copyarraydata<ndim,T>(arr, to);
  }
}

void PyMJCWorld::SetModel(bp::dict d) {
  _cadihk<1>(d, "dof_armature", m_model->dof_armature);
  _cadihk<2>(d, "jnt_limit", m_model->jnt_limit);
}

bp::dict PyMJCWorld::GetModel() {
  bp::dict out;
  out["nqpos"] = m_model->nqpos;
  out["ndof"] = m_model->ndof;
  out["njnt"] = m_model->njnt;
  out["nbody"] = m_model->nbody;
  out["ngeom"] = m_model->ngeom;
  out["neqmax"] = m_model->neqmax;
  out["nlmax"] = m_model->nlmax;
  out["ncpair"] = m_model->ncpair;
  out["ncmax"] = m_model->ncmax;
  out["name"] = bp::str(m_model->name);
  out["timestep"] = m_model->timestep;
  out["gravity"] = toNdarray1<mjtNum>(m_model->gravity,3);
  out["viscosity"] = m_model->viscosity;
  out["mindist"] = toNdarray1<mjtNum>(m_model->mindist,2);
  out["erreduce"] = toNdarray1<mjtNum>(m_model->errreduce, 3);

  out["body_mass"] = toNdarray1<mjtNum>(m_model->body_mass, m_model->nbody);
  out["body_inertia"] = toNdarray2<mjtNum>(m_model->body_inertia, m_model->nbody,3);
  out["body_pos"] = toNdarray2<mjtNum>(m_model->body_pos, m_model->nbody,3);
  out["body_quat"] = toNdarray2<mjtNum>(m_model->body_quat, m_model->nbody,4);
  out["body_viscoef"] = toNdarray1<mjtNum>(m_model->body_viscoef, m_model->nbody);
  out["body_parent_id"] = toNdarray1<int>(m_model->body_parent_id, m_model->nbody);
  out["body_jnt_num"] = toNdarray1<int>(m_model->body_jnt_num, m_model->nbody);
  out["body_dof_num"] = toNdarray1<int>(m_model->body_dof_num, m_model->nbody);
  out["body_root_id"] = toNdarray1<int>(m_model->body_root_id, m_model->nbody);

  out["jnt_type"] = toNdarray1<int>((int*)m_model->jnt_type, m_model->njnt);
  out["jnt_pos"] = toNdarray2<mjtNum>(m_model->jnt_pos, m_model->njnt,3);
  out["jnt_axis"] = toNdarray2<mjtNum>(m_model->jnt_axis, m_model->njnt,3);
  out["jnt_spring"] = toNdarray1<mjtNum>(m_model->jnt_spring, m_model->njnt);
  out["jnt_damping"] = toNdarray1<mjtNum>(m_model->jnt_damping, m_model->njnt);
  out["jnt_vel_damping"] = toNdarray1<mjtNum>(m_model->jnt_vel_damping, m_model->njnt);
  out["jnt_body_id"] = toNdarray1<int>(m_model->jnt_body_id, m_model->njnt);
  out["jnt_limit"] = toNdarray2<mjtNum>(m_model->jnt_limit, m_model->njnt,2);
  out["jnt_islimited"] = toNdarray1<mjtByte>(m_model->jnt_islimited, m_model->njnt);

  out["dof_armature"] = toNdarray1<mjtNum>(m_model->dof_armature, m_model->ndof);
  out["dof_body_id"] = toNdarray1<int>(m_model->dof_body_id, m_model->ndof);
  out["dof_jnt_id"] = toNdarray1<int>(m_model->dof_jnt_id, m_model->ndof);
  out["dof_parent_id"] = toNdarray1<int>(m_model->dof_parent_id, m_model->ndof);

  out["geom_type"] = toNdarray1<int>((int*)m_model->geom_type, m_model->ngeom);
  out["geom_size"] = toNdarray2<mjtNum>(m_model->geom_size, m_model->ngeom, mjNumSize);
  out["geom_pos"] = toNdarray2<mjtNum>(m_model->geom_pos, m_model->ngeom,3);
  out["geom_quat"] = toNdarray2<mjtNum>(m_model->geom_quat, m_model->ngeom,4);
  out["geom_color"] = toNdarray2<mjtNum>(m_model->geom_color, m_model->ngeom,3);
  out["geom_body_id"] = toNdarray1<int>(m_model->geom_body_id, m_model->ngeom);
  out["geom_isoffset"] = toNdarray1<mjtByte>(m_model->geom_isoffset, m_model->ngeom);

  out["eq_body1"] = toNdarray1<int>(m_model->eq_body1, m_model->neqmax);
  out["eq_body2"] = toNdarray1<int>(m_model->eq_body2, m_model->neqmax);
  out["eq_pos1"] = toNdarray2<mjtNum>(m_model->eq_pos1, m_model->neqmax, 3);
  out["eq_pos2"] = toNdarray2<mjtNum>(m_model->eq_pos2, m_model->neqmax, 3);
  out["eq_enable"] = toNdarray1<mjtByte>(m_model->eq_enable, m_model->neqmax);

  out["pair_type"] = toNdarray1<int>((int*)m_model->pair_type, m_model->ncpair);
  out["pair_friction"] = toNdarray1<mjtNum>(m_model->pair_friction, m_model->ncpair);
  out["pair_geom1"] = toNdarray1<int>(m_model->pair_geom1, m_model->ncpair);
  out["pair_geom2"] = toNdarray1<int>(m_model->pair_geom2, m_model->ncpair);
  out["pair_enable"] = toNdarray1<mjtByte>(m_model->pair_enable, m_model->ncpair);

  return out;
}

bp::dict PyMJCWorld::GetData(const bn::ndarray& x) {
  NOTIMPLEMENTED;
}

BOOST_PYTHON_MODULE(mjcpy) {
    bn::initialize();

    bp::enum_<ContactType>("ContactType")
      .value("NONE",ContactType_SPRING)
      .value("SLCP",ContactType_SLCP)
      .value("SPRING",ContactType_SPRINGTAU)
      .value("CONVEX",ContactType_CONVEX)
      ;

    bp::class_<PyMJCWorld,boost::noncopyable>("MJCWorld","docstring here", bp::init<const std::string&>())

        .def("Step",&PyMJCWorld::Step)
        .def("StepMulti",&PyMJCWorld::StepMulti)
        .def("StepMulti2",&PyMJCWorld::StepMulti2)
        .def("StepJacobian", &PyMJCWorld::StepJacobian)
        .def("Plot",&PyMJCWorld::Plot)
        .def("SetActuatedDims",&PyMJCWorld::SetActuatedDims)
        .def("ComputeContacts", &PyMJCWorld::ComputeContacts)
        .def("SetTimestep",&PyMJCWorld::SetTimestep)
        .def("SetContactType",&PyMJCWorld::SetContactType)
        .def("GetModel",&PyMJCWorld::GetModel)
        .def("SetModel",&PyMJCWorld::SetModel)
        .def("GetData",&PyMJCWorld::GetData)
        .def("GetImage",&PyMJCWorld::GetImage)
        ;
}

max_stars_repo_name: sfpd/rlreloaded

max_issues_repo_name: sfpd/rlreloaded

max_forks_repo_name: sfpd/rlreloaded


text:
/*
 * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     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.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE qmstate_test

// Standard includes
#include <fstream>

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/xtp/qmstate.h"

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(qmstate_test)

BOOST_AUTO_TEST_CASE(QMStatetype_test) {
  QMStateType type;
  type.FromString("S");

  BOOST_CHECK_EQUAL(type.Type() == QMStateType::Singlet, true);
  BOOST_CHECK_EQUAL(type.ToString(), "s");
  BOOST_CHECK_EQUAL(type.ToLongString(), "singlet");

  QMStateType type2;
  type2.FromString("Singlet");
  BOOST_CHECK_EQUAL(type2.Type() == QMStateType::Singlet, true);

  BOOST_CHECK_EQUAL(type == type2, true);

  QMStateType type3;
  type3.FromString("N");
  BOOST_CHECK_EQUAL(type3 == type2, false);
  BOOST_CHECK_EQUAL(type3 == QMStateType::Gstate, true);

  QMStateType type4 = QMStateType(QMStateType::KSstate);
  BOOST_CHECK_EQUAL(type4 == QMStateType::KSstate, true);
}

BOOST_AUTO_TEST_CASE(QMState_test) {
  QMState state;
  state.FromString("S1");
  BOOST_CHECK_EQUAL(state.Type() == QMStateType::Singlet, true);
  BOOST_CHECK_EQUAL(state.StateIdx(), 0);

  QMState state2;
  state.FromString("N");
  BOOST_CHECK_EQUAL(state.StateIdx(), -1);

  QMState state3;
  state3.FromString("n2s12");
  BOOST_CHECK_EQUAL(state3.isTransition(), true);

  BOOST_CHECK_EQUAL(state3.Type() == QMStateType::Singlet, true);
  BOOST_CHECK_EQUAL(state3.StateIdx(), 11);

  QMState state4;
  state4.FromString("n2s16");
  QMState state5;
  state5.FromString("groundstate to singlet 16");

  BOOST_CHECK_EQUAL(state4 == state5, true);
  std::string result = state4.ToLongString();
  BOOST_CHECK_EQUAL(result, "Groundstate to singlet 16");

  QMState state6 = QMState(QMStateType::Singlet, 15, true);
  BOOST_CHECK_EQUAL(state6 == state5, true);

  QMState hole;
  hole.FromString("h1");
  BOOST_CHECK_EQUAL(hole.StateIdx(), 0);
  QMState hole2;
  hole2.FromString("h");
  BOOST_CHECK_EQUAL(hole2.StateIdx(), 0);
  QMState electron;
  electron.FromString("e1");
  BOOST_CHECK_EQUAL(electron.StateIdx(), 0);
  QMState electron2;
  electron2.FromString("e");
  BOOST_CHECK_EQUAL(electron2.StateIdx(), 0);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: fossabot/xtp

max_issues_repo_name: fossabot/xtp

max_forks_repo_name: fossabot/xtp


text:
//==============================================================================
//
//	IRC.cpp:
//
//
//
//
//
//==============================================================================

#include "IrcParser.hpp"

//	System dependencies ...
#include <iostream>
#include <functional>
#include <sstream>

//	Boost dependencies ...
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

//	Project dependencies ...

namespace irclib
{

    IrcParser::IrcParser()
        : m_Handles()
        , m_CommandHandlers()
    {
        // Run selftests
        selftest();

        using std::placeholders::_1;

        addIrcReadHandler(std::bind(&IrcParser::doCommandDispatch, this, _1));
    }

    IrcParser::~IrcParser()
    {
    }

    bool IrcParser::selftest()
    {
        //////////////////////////////////////////////////////////////////////////
        //
        //  OK
        //
        //////////////////////////////////////////////////////////////////////////

        std::vector<std::string> tests =
        {
            "PING",									// Command
            "PING :server",							// Command + trail
            "PING param1 :server",					// Command + param + trail
            ":origin PING",							// Prefix + command
            ":origin PING :server",					// Prefix + command + trail
            ":origin PING param1 param2",			// Prefix + command + params
            ":origin PING param1 param2 :server",	// Prefix + command + params + trail

            // Broken msgs
            ":",
            ": PING"
            //":server 001 beta2 :Hi, welcome to IRC",
            //":server 002 beta2 :Your host is server, running version miniircd-0.4",
            //":server 003 beta2 :This server was created sometime",
            //":server 004 beta2 :server miniircd-0.4 o o",
            //":server 251 beta2 :There are 2 users and 0 services on 1 server",
            //":server 422 beta2 :MOTD File is missing",
            //":beta2!beta2@10.0.0.34 JOIN #chan",
            //":server 331 beta2 #chan :No topic is set",
            //":server 353 beta2 = #chan :beta2 nd",
            //":server 366 beta2 #chan :End of NAMES list",
            //":beta2!beta2@10.0.0.34 JOIN #chan2",
            //":server 331 beta2 #chan2 :No topic is set",
            //":server 353 beta2 = #chan2 :beta2",
            //":server 366 beta2 #chan2 :End of NAMES list"
        };

        std::vector<IrcMessage> results =
        {
            IrcMessage("PING"),
            IrcMessage("PING","", {}, "server"),
            IrcMessage("PING", "", {"param1"}, "server"),
            IrcMessage("PING", "origin"),
            IrcMessage("PING", "origin", {}, "server"),
            IrcMessage("PING", "origin", {"param1","param2"}, ""),
            IrcMessage("PING", "origin", {"param1","param2"}, "server"),
            IrcMessage(),
            IrcMessage()
        };

        size_t i=0;

        for (const auto & msg : tests)
        {
            IrcMessage ircmsg = parseLine(msg);

            const IrcMessage & res = results[i++];

            if (ircmsg != res)
            {
                int breakpointhere=0;
                IrcMessage secondtest = parseLine(msg);

                (void*)breakpointhere;
            }

        }

        return true;
    }

    IrcMessage IrcParser::parseLine(const std::string & message)
    {
        if (message.empty())
        {
            // Garbage in, garbage out
            return IrcMessage();
        }

        // https://tools.ietf.org/html/rfc1459	-- Original specification
        // https://tools.ietf.org/html/rfc2810	-- Architecture specfication
        // https://tools.ietf.org/html/rfc2811	-- Channel specification
        // https://tools.ietf.org/html/rfc2812	-- Client specification
        // https://tools.ietf.org/html/rfc2813	-- Server specification
        //
        // <message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
        // <prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
        // <command>  ::= <letter> { <letter> } | <number> <number> <number>
        // <SPACE>    ::= ' ' { ' ' }
        // <params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
        //
        // <middle>   ::= <Any *non-empty* sequence of octets not including SPACE
        //                or NUL or CR or LF, the first of which may not be ':'>
        // <trailing> ::= <Any, possibly *empty*, sequence of octets not including
        //                  NUL or CR or LF>
        //
        // <crlf>     ::= CR LF

        // Parameters are between command and trail
        auto trailDivider = message.find(" :");
        bool haveTrailDivider = trailDivider != message.npos;

        // Assemble outputs
        std::vector<std::string> parts;
        std::string prefix;
        std::string command;
        ParamType parameters;
        std::string trail;

        // With or without trail
        if (haveTrailDivider)
        {
            // Have trail, split by trail
            std::string uptotrail = message.substr(0, trailDivider);
            trail = message.substr(trailDivider + 2);
            boost::split(parts, uptotrail, boost::is_any_of(" "));
        }
        else
        {
            // No trail, everything are parameters
            boost::split(parts, message, boost::is_any_of(" "));
        }

        enum class DecoderState
        {
            PREFIX,
            COMMAND,
            PARAMETER
        } state;

        bool first = true;
        state = DecoderState::PREFIX;

        for (const std::string & part : parts)
        {

            switch (state)
            {
                // Prefix, or command... have to be decided
                case DecoderState::PREFIX:
                case DecoderState::COMMAND:
                {
                    // Prefix, aka origin of message
                    bool havePrefix = part[0] == ':';

                    if (havePrefix && first)
                    {
                        // Oh the sanity
                        if (part.size() < 2)
                        {
                            return IrcMessage();
                        }

                        // Have prefix
                        state = DecoderState::COMMAND;
                        prefix = part.substr(1);
                        first = false;
                    }
                    else
                    {
                        // Have command
                        state = DecoderState::PARAMETER;
                        command = part;
                    }

                    break;
                }
                case DecoderState::PARAMETER:
                {
                    parameters.push_back(part);
                    break;
                }
            }

        }

        // Construct an IrcMessage
        IrcMessage ircmsg(command, prefix, std::move(parameters), trail);
        m_Handles(ircmsg);

        return ircmsg;
    }

    std::string IrcParser::parseMessage(const IrcMessage & message)
    {
        std::stringstream ss;

        bool havePrefix         = ! message.origin().empty();
        bool haveTrail          = ! message.trail().empty();

        if (havePrefix)
        {
            ss << message.origin() << " ";
        }

        ss << message.command();

        for (const auto & param : message.params())
        {
            ss << " " << param;
        }

        if (haveTrail)
        {
            ss << " :" << message.trail();
        }

        const std::string output = ss.str();

        return output;
    }

    void IrcParser::addIrcReadHandler(const IrcMessageHandle & handle)
    {
        m_Handles.addHandle(handle);
    }

    void IrcParser::addIrcCommandHandler(const std::string & cmd, const IrcMessageHandle & handler)
    {
        m_CommandHandlers[cmd].addHandle(handler);
    }

    void IrcParser::doCommandDispatch(const IrcMessage & msg) const
    {
        const auto & it = m_CommandHandlers.find(msg.command());

        if (it != m_CommandHandlers.end())
        {
            const auto & handles = it->second;

            // Call each handler
            handles(msg);
        }
    }
}

max_stars_repo_name: Studiofreya/smartass

max_issues_repo_name: Studiofreya/smartass

max_forks_repo_name: Studiofreya/smartass


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_shared_ptr.cpp

// (C) Copyright 2002 Robert Ramey- http://www.rrsd.com - David Tonge  .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//  See http://www.boost.org for updates, documentation, and revision history.

#include <cstddef> // NULL
#include <fstream>

#include <cstdio> // remove
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
    using ::remove;
}
#endif

#include "test_tools.hpp"

#include <boost/serialization/shared_ptr_132.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/weak_ptr.hpp>
#include <boost/serialization/split_member.hpp>

#include <boost/preprocessor/stringize.hpp>

#include <boost/serialization/nvp.hpp>
#include <boost/serialization/export.hpp>
#include <boost/type_traits/broken_compiler_spec.hpp>

// This is a simple class.  It contains a counter of the number
// of objects of this class which have been instantiated.
class A
{
private:
    friend class boost::serialization::access;
    int x;
    template<class Archive>
    void save(Archive & ar, const unsigned int /* file_version */) const {
        ar << BOOST_SERIALIZATION_NVP(x);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int /* file_version */) {
        ar >> BOOST_SERIALIZATION_NVP(x);
    }
    BOOST_SERIALIZATION_SPLIT_MEMBER()
public:
    static int count;
    bool operator==(const A & rhs) const {
        return x == rhs.x;
    }
    A(){++count;}    // default constructor
    virtual ~A(){--count;}   // default destructor
};

BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(A)
BOOST_SERIALIZATION_SHARED_PTR(A)

// B is a subclass of A
class B : public A
{
private:
    friend class boost::serialization::access;
    int y;
    template<class Archive>
    void save(Archive & ar, const unsigned int /* file_version */ )const {
        ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(A);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int /* file_version */){
        ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(A);
    }
    BOOST_SERIALIZATION_SPLIT_MEMBER()
public:
    static int count;
    B() : A() {};
    virtual ~B() {};
};

// B needs to be exported because its serialized via a base class pointer
BOOST_SHARED_POINTER_EXPORT(B)
BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(B)
BOOST_SERIALIZATION_SHARED_PTR(B)

int A::count = 0;

template<class T>
void save(const char * testfile, const T & spa)
{
    test_ostream os(testfile, TEST_STREAM_FLAGS);
    test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
    oa << BOOST_SERIALIZATION_NVP(spa);
}

template<class T>
void load(const char * testfile, T & spa)
{
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
    ia >> BOOST_SERIALIZATION_NVP(spa);
}

// trivial test
template<class T>
void save_and_load(const T & spa)
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);
    save(testfile, spa);

    // note that we're loading to a current version of shared_ptr
    // regardless of the orignal saved type - this tests backward
    // archive compatibility
    boost::shared_ptr<A> spa1;
    load(testfile, spa1);

    BOOST_CHECK(
        (spa.get() == NULL && spa1.get() == NULL)
        || * spa == * spa1
    );
    std::remove(testfile);
}

template<class T>
void save2(
    const char * testfile,
    const T & first,
    const T & second
){
    test_ostream os(testfile, TEST_STREAM_FLAGS);
    test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
    oa << BOOST_SERIALIZATION_NVP(first);
    oa << BOOST_SERIALIZATION_NVP(second);
}

template<class T>
void load2(
    const char * testfile,
    T & first,
    T & second)
{
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
    ia >> BOOST_SERIALIZATION_NVP(first);
    ia >> BOOST_SERIALIZATION_NVP(second);
}

// Run tests by serializing two shared_ptrs into an archive,
// clearing them (deleting the objects) and then reloading the
// objects back from an archive.
template<class T>
void save_and_load2(T & first, T & second)
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    save2(testfile, first, second);

    // Clear the pointers, thereby destroying the objects they contain
    first.reset();
    second.reset();

    boost::shared_ptr<A> first1, second1;
    load2(testfile, first1, second1);

    BOOST_CHECK(first1 == second1);
    std::remove(testfile);
}

template<class T>
void save3(
    const char * testfile,
    const T & first,
    const T & second,
    const T & third
){
    test_ostream os(testfile, TEST_STREAM_FLAGS);
    test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
    oa << BOOST_SERIALIZATION_NVP(third);
    oa << BOOST_SERIALIZATION_NVP(first);
    oa << BOOST_SERIALIZATION_NVP(second);
}

template<class T>
void load3(
    const char * testfile,
    T & first,
    T & second,
    T & third
){
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
    // note that we serialize the weak pointer first
    ia >> BOOST_SERIALIZATION_NVP(third);
    // inorder to test that a temporarily solitary weak pointer
    // correcttly restored.
    ia >> BOOST_SERIALIZATION_NVP(first);
    ia >> BOOST_SERIALIZATION_NVP(second);
}

// This does the tests
int test_main(int /* argc */, char * /* argv */[])
{
    // These are our shared_ptrs
    boost_132::shared_ptr<A> spa;

    // trivial test 1
    save_and_load(spa);

    //trivial test 2
    spa.reset();
    spa = boost_132::shared_ptr<A>(new A);
    save_and_load(spa);

    // Try to save and load pointers to As, to a text archive
    spa = boost_132::shared_ptr<A>(new A);
    boost_132::shared_ptr<A> spa1 = spa;
    save_and_load2(spa, spa1);

    // Try to save and load pointers to Bs, to a text archive
    spa = boost_132::shared_ptr<A>(new B);
    save_and_load(spa);

    spa1 = spa;
    save_and_load2(spa, spa1);

    // obj of type B gets destroyed
    // as smart_ptr goes out of scope
    return EXIT_SUCCESS;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
#include "onlineforest.h"

#include "forest.h"
#include <string.h>
#include <fstream>
#include <boost/foreach.hpp>

OnlineForest::OnlineForest(const HyperParameters &hp)
{
  m_hp = &hp;
}

void OnlineForest::initialize(const int numSamples)
{

    m_confidences.resize(numSamples, m_hp->numClasses);
    m_predictions.resize(numSamples);

    for (int n = 0; n < numSamples; n++)
    {
        for (int m = 0; m < m_hp->numClasses; m++)
        {
            m_confidences(n, m) = 0;
        }
    }
}

void OnlineForest::train(const matrix<float>& data, const std::vector<int>& labels, bool use_gpu)
{
    // Initialize
    initialize(data.size1());

    if (m_hp->useGPU || use_gpu)
    {
        cerr << "ERROR: No GPU Implementation available for online forests!" << endl;
        //std::vector<double> weights(labels.size(),1);
        //trainByGPU(data,labels, weights);
    }
    else
    {
        trainByCPU(data,labels);
    }
}

OnlineForest::~OnlineForest()
{
    m_trees.clear();
}

void OnlineForest::eval(const matrix<float>& data, const std::vector<int>& labels, bool use_gpu)
{
    if (m_hp->useGPU || use_gpu)
    {
        cerr << "ERROR: No GPU Implementation available for online forests!" << endl;
        //evalByGPU(data, labels);
    }
    else
    {
        evalByCPU(data, labels);
    }
}

void OnlineForest::load(const std::string &name)
{
    std::string loadName;
    loadName = (name == "default") ? m_hp->loadName : name;
    // now load that stuff
}

// CPU penne code only below this line

int poisson(double A)
{
    int k = 0;
    int maxK = 10;
    while(1) {
        double U_k = _rand();
        A *= U_k;
        if( k > maxK || A < exp(-1.0) ) {
            break;
        }
        k++;
    }
    return k;
}

void OnlineForest::trainByCPU(const matrix<float>& data, const std::vector<int>& labels)
{
    HyperParameters tmpHP = *m_hp;
    tmpHP.verbose = false;

    m_trees.clear();
    // Create trees
    for (int tree = 0; tree < m_hp->numTrees; tree++)
    {
        m_trees.push_back(OnlineTree(tmpHP,(int)data.size2()));
    }

    if (m_hp->verbose)
    {
        cout << "Training a random forest with " << m_hp->numTrees << " , grab a coffee ... " << endl;
        cout << "\tEpoch #: ";
    }

    // Train Forest
    std::vector<int> randperm;
    for (int round = 0; round < m_hp->numOnlineEpochs; round++)
    {
        if (m_hp->verbose)
        {
            cout << round + 1 << " " << flush;
        }
        //randperm = randPerm(data.size1());
        randperm = randPerm(m_hp->numLabeled);
        for ( int s = 0; s < m_hp->numLabeled; s++)
        {
            std::vector<float> sample(data.size2(),0);
            for ( int feature = 0; feature < (int)data.size2(); feature++)
            {
                sample[feature] = data(randperm[s],feature);
            }
            std::vector<OnlineTree>::iterator treeIt(m_trees.begin());
            std::vector<OnlineTree>::iterator treeEnd(m_trees.end());
            while ( treeIt != treeEnd )
            {
                double k = poisson(1.0);
                for(int curK = 0; curK < k; curK++) {
                    treeIt->train(sample,labels[randperm[s]]);
                }
                ++treeIt;
            }
        }
        //cout << "bla" << endl;
    }
    if (m_hp->verbose)
    {
        cout << " Done." << endl;
    }

    // Eval Forest
    double error = 0.0;
    for ( int s = 0; s < m_hp->numLabeled;s++)
    {
        std::vector<float> sample(data.size2(),0);
        for ( int feature = 0; feature < (int)data.size2(); feature++)
        {
            sample[feature] = data(s,feature);
        }

        std::vector<int> predictions(m_hp->numClasses,0.0);
        std::vector<OnlineTree>::iterator treeIt(m_trees.begin());
        std::vector<OnlineTree>::iterator treeEnd(m_trees.end());
        while ( treeIt != treeEnd )
        {
            int prediction = (int)treeIt->eval(sample,labels[s]);
            predictions[prediction]++;
            ++treeIt;
        }

        int maxPrediction = 0;
        int bestClass = 0;
        int c = 0;
        BOOST_FOREACH(int pred,predictions){
            if(pred > maxPrediction){
                maxPrediction = pred;
                bestClass = c;
            }
            c++;
        }
        if (bestClass != labels[s])
        {
            error++;
        }
    }

    if (m_hp->verbose)
    {
        cout << "\tTraining Error: " << error/(double)m_hp->numLabeled << endl;
    }

}

void OnlineForest::evalByCPU(const matrix<float>& data, const std::vector<int>& labels)
{
   // Eval Forest
    double error = 0.0;
    for ( int s = 0; s < (int) data.size1();s++)
    {
        std::vector<float> sample(data.size2(),0);
        for ( int feature = 0; feature < (int)data.size2(); feature++)
        {
            sample[feature] = data(s,feature);
        }

        std::vector<int> predictions(m_hp->numClasses,0.0);
        std::vector<OnlineTree>::iterator treeIt(m_trees.begin());
        std::vector<OnlineTree>::iterator treeEnd(m_trees.end());
        while ( treeIt != treeEnd )
        {
            int prediction = (int)treeIt->eval(sample,labels[s]);
            predictions[prediction]++;
            ++treeIt;
        }

        int maxPrediction = 0;
        int bestClass = 0;
        int c = 0;
        BOOST_FOREACH(int pred,predictions){
            if(pred > maxPrediction){
                maxPrediction = pred;
                bestClass = c;
            }
            c++;
        }
        if (bestClass != labels[s])
        {
            error++;
        }
    }
    if(m_hp->verbose) {
        cout << "\tTest Error: " << error/(double) data.size1() << endl;
    }
}

double OnlineForest::computeError(const std::vector<int>& labels)
{
    int bestClass, nSamp = 0;
    float bestConf;
    double error = 0;
    BOOST_FOREACH(int pre, m_predictions)
    {
        bestClass = 0;
        bestConf = 0;
        for (int nClass = 0; nClass < (int) m_hp->numClasses; nClass++)
        {
            if (m_confidences(nSamp, nClass) > bestConf)
            {
                bestClass = nClass;
                bestConf = m_confidences(nSamp, nClass);
            }
        }

        pre = bestClass;
        if (bestClass != labels[nSamp])
        {
            error++;
        }

        nSamp++;
    }
    error /= (double) m_predictions.size();

    return error;
}

double OnlineForest::computeError(const std::vector<int>& labels, const matrix<float>& confidences,
                                  const std::vector<int>& voteNum)
{
    double error = 0, bestConf;
    int sampleNum = 0, bestClass;
    for (int nSamp = 0; nSamp < (int) confidences.size1(); nSamp++)
    {
        bestClass = 0;
        bestConf = 0;
        if (voteNum[nSamp])
        {
            sampleNum++;
            for (int nClass = 0; nClass < (int) m_hp->numClasses; nClass++)
            {
                if (confidences(nSamp, nClass) > bestConf)
                {
                    bestClass = nClass;
                    bestConf = confidences(nSamp, nClass);
                }
            }

            if (bestClass != labels[nSamp])
            {
                error++;
            }
        }
    }
    error /= (double) sampleNum;

    return error;
}

void OnlineForest::writeError(const std::string& fileName, double error)
{
    std::ofstream myfile;
    myfile.open(fileName.c_str(), std::ios::app);
    myfile << error << endl;
    myfile.flush();
    myfile.close();
}

max_stars_repo_name: tschuls/ETH-SegReg-DLL

max_issues_repo_name: tschuls/ETH-SegReg-DLL

max_forks_repo_name: tschuls/ETH-SegReg-DLL


text:
#include "library/strings.h"
#include "library/strings_format.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/locale/encoding_utf.hpp>
#include <boost/locale/message.hpp>
#include <cctype>

namespace OpenApoc
{

UString tr(const UString &str, const UString domain)
{
	return UString(boost::locale::translate(str).str(domain));
}

U32String to_u32string(const UStringView str)
{
	// FIXME: Boost api doesn't work with string views yet?
	auto string_copy = UString(str);
	return boost::locale::conv::utf_to_utf<char32_t>(string_copy);
}

UString to_ustring(const std::u32string_view str)
{
	auto string_copy = U32String(str);
	return boost::locale::conv::utf_to_utf<char>(string_copy);
}

char32_t to_char32(const char c)
{
	// All the codepoints <=127 are the same as ascii
	return static_cast<char32_t>(c);
}

UString to_upper(const UStringView str)
{
	/* Only change the case on ascii range characters (codepoint <=0x7f)
	 * As we know the top bit is set for any bytes outside this range no matter the position in the
	 * utf8 stream, we can cheat a bit here */
	auto upper_string = UString(str);
	for (size_t i = 0; i < upper_string.length(); i++)
	{
		if ((upper_string[i] & 0b10000000) == 0)
			upper_string[i] = toupper(upper_string[i]);
	}
	return upper_string;
}

UString to_lower(const UStringView str)
{
	/* Only change the case on ascii range characters (codepoint <=0x7f)
	 * As we know the top bit is set for any bytes outside this range no matter the position in the
	 * utf8 stream, we can cheat a bit here */
	auto lower_string = UString(str);
	for (size_t i = 0; i < lower_string.length(); i++)
	{
		if ((lower_string[i] & 0b10000000) == 0)
			lower_string[i] = tolower(lower_string[i]);
	}
	return lower_string;
}

bool ends_with(const UStringView str, const UStringView ending)
{
	return boost::ends_with(str, ending);
}

UString remove(const UStringView str, size_t offset, size_t count)
{
	auto u32str = to_u32string(str);

	u32str.erase(offset, count);

	return to_ustring(u32str);
}

U32String remove(const U32StringView str, size_t offset, size_t count)
{
	auto str_copy = U32String(str);
	return str_copy.erase(offset, count);
}

std::vector<UString> split(const UStringView str, const UStringView delims)
{
	// FIXME: Probably won't work if any of 'delims' is outside the ASCII range
	std::vector<UString> strings;
	size_t pos = 0;
	size_t prev = pos;
	while ((pos = str.find_first_of(delims, prev)) != std::string::npos)
	{
		if (pos > prev)
			strings.push_back(UString(str.substr(prev, pos - prev)));
		prev = pos + 1;
	}
	strings.push_back(UString(str.substr(prev, pos)));
	return strings;
}

UString insert_codepoints(const UStringView str, size_t offset, const UStringView insert)
{
	auto u32str = to_u32string(str);
	auto u32insert = to_u32string(insert);
	u32str.insert(offset, u32insert);
	return to_ustring(u32str);
}

int Strings::toInteger(const UStringView s)
{
	auto u8str = UString(s);
	return static_cast<int>(strtol(u8str.c_str(), NULL, 0));
}

float Strings::toFloat(const UStringView s)
{
	auto u8str = UString(s);
	return static_cast<float>(strtod(u8str.c_str(), NULL));
}

uint8_t Strings::toU8(const UStringView s) { return static_cast<uint8_t>(toInteger(s)); }

bool Strings::isInteger(const UStringView s)
{
	auto u8str = UString(s);
	char *endpos;
	std::ignore = strtol(u8str.c_str(), &endpos, 0);
	return (endpos != u8str.c_str());
}

bool Strings::isFloat(const UStringView s)
{
	auto u8str = UString(s);
	char *endpos;
	std::ignore = strtod(u8str.c_str(), &endpos);
	return (endpos != u8str.c_str());
}

UString Strings::fromInteger(int i) { return format("%d", i); }

UString Strings::fromFloat(float f) { return format("%f", f); }

bool Strings::isWhiteSpace(char32_t c)
{
	// FIXME: Only works on ASCII whitespace
	return isspace(c) != 0;
}

UString Strings::fromU64(uint64_t i) { return format("%llu", i); }

}; // namespace OpenApoc

max_stars_repo_name: Jarskih/OpenApoc

max_issues_repo_name: Jarskih/OpenApoc

max_forks_repo_name: Jarskih/OpenApoc


text:
/* Copyright (c) 2012 Cheese and Bacon Games, LLC */
/* This file is licensed under the MIT License. */
/* See the file docs/LICENSE.txt for the full license text. */

#include "sound.h"
#include "world.h"

#include <boost/algorithm/string.hpp>

using namespace std;

void Sound::load_sounds(){
    //Look through all of the files in the directory.
    for(File_IO_Directory_Iterator it("data/sounds");it.evaluate();it.iterate()){
        //If the file is not a directory.
        if(it.is_regular_file()){
            string file_name=it.get_file_name();

            boost::algorithm::trim(file_name);

            sound_names.push_back(file_name);
        }
    }

    for(int i=0;i<sound_names.size();i++){
        sounds.push_back(Sound_Data());

        sounds[sounds.size()-1].load_sound("data/sounds/"+sound_names[i]);

        sound_names[i].erase(sound_names[i].end()-4,sound_names[i].end());
    }
}

void Sound::unload_sounds(){
    for(int i=0;i<sounds.size();i++){
        sounds[i].unload_sound();
    }

    sounds.clear();
    sound_names.clear();
}

int Sound::modify_sound_volume(int volume){
    //If either the global mute or the sound effects mute is enabled.
    if(engine_interface.option_mute_global || engine_interface.option_mute_sound){
        return 0;
    }

    double new_volume=volume;

    new_volume*=engine_interface.option_volume_sound;

    new_volume*=engine_interface.option_volume_global;

    return (int)new_volume;
}

int Sound::get_free_channel(){
    int allocated_channels=Mix_AllocateChannels(-1);

    for(int i=0;i<allocated_channels;i++){
        //Check through all music tracks currently loaded.
        bool channel_taken_by_music_track=false;
        for(int n=0;n<music.tracks.size();n++){
            //If this channel is equal to this track's channel, then this channel is taken.
            if(i==music.tracks[n].channel){
                channel_taken_by_music_track=true;
            }
        }

        //If the channel is already playing.
        if(Mix_Playing(i)==1){
        }
        //If this channel is already reserved by a music track.
        else if(channel_taken_by_music_track){
        }
        //All tests were passed, and this channel is currently free, so return it.
        else{
            return i;
        }
    }

    return -1;
}

void Sound::play_sound(string sound_name){
    Sound_Data* ptr_sound=get_sound(sound_name);

    int volume=128;

    volume=modify_sound_volume(volume);

    _play_sound(ptr_sound,volume);
}

void Sound::play_sound(string sound_name,double sound_x,double sound_y,double falloff){
    Sound_Data* ptr_sound=get_sound(sound_name);

    int volume=128;

    if(falloff<0.0){
        falloff=engine_interface.sound_falloff;
    }

    falloff*=game.camera_zoom;

    double sound_center_x=game.camera.center_x();
    double sound_center_y=game.camera.center_y();

    if(game.in_progress){
        /**sound_center_x=game.world.example_player.circle.x;
        sound_center_y=game.world.example_player.circle.y;*/
    }

    double sound_position_x=sound_x*game.camera_zoom;
    double sound_position_y=sound_y*game.camera_zoom;

    double sound_distance=distance_between_points(sound_center_x,sound_center_y,sound_position_x,sound_position_y);
    if(sound_distance<1.0){
        sound_distance=0.0;
    }

    if(sound_distance==0.0){
        volume=128;
    }
    else{
        volume=(int)floor((falloff/sound_distance)*falloff);
    }

    if(volume>128){
        volume=128;
    }

    volume=modify_sound_volume(volume);

    _play_sound(ptr_sound,volume);
}

void Sound::_play_sound(Sound_Data* ptr_sound,int volume){
    if(ptr_sound!=0 && ptr_sound->chunk!=0){
        if(volume!=0){
            int channel=get_free_channel();

            if(channel!=-1){
                Mix_Volume(channel,volume);
                Mix_PlayChannel(channel,ptr_sound->chunk,0);
            }
        }
    }
}

Sound_Data* Sound::get_sound(string sound_name){
    Sound_Data* ptr_sound=0;

    for(int i=0;i<sound_names.size();i++){
        if(sound_names[i]==sound_name){
            ptr_sound=&sounds[i];

            break;
        }
    }

    if(ptr_sound==0){
        message_log.add_error("Error accessing sound '"+sound_name+"'");
    }

    return ptr_sound;
}

max_stars_repo_name: darkoppressor/particles

max_issues_repo_name: darkoppressor/particles

max_forks_repo_name: darkoppressor/particles


text:
//
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "Mesh_Remesh.h"

#include <assert.h>

#include <iostream>
#include <vector>

#include <Eigen/Core>

#pragma warning(push, 0)
#include <igl/adjacency_list.h>
#pragma warning(pop)

#include "ConversionUtilities.h"
#include "TriMesh.h"
#include "Geomlib_TriMeshAverageEdgeLength.h"
#include "Geomlib_TriMeshEdgeSplit.h"
#include "Geomlib_TriMeshEdgeCollapse.h"

using namespace Urho3D;

String Mesh_Remesh::iconTexture = "";

Mesh_Remesh::Mesh_Remesh(Context* context) : IoComponentBase(context, 4, 1)
{
	SetName("Remesh");
	SetFullName("Remesh");
	SetDescription("Perform basic remeshing on a TriMesh");

	inputSlots_[0]->SetName("TriMesh");
	inputSlots_[0]->SetVariableName("TriMesh");
	inputSlots_[0]->SetDescription("TriMesh");
	inputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);
	inputSlots_[0]->SetDataAccess(DataAccess::ITEM);

	inputSlots_[1]->SetName("TargetEdgeLength");
	inputSlots_[1]->SetVariableName("Target");
	inputSlots_[1]->SetDescription("Target average edge length (optional)");
	inputSlots_[1]->SetVariantType(VariantType::VAR_FLOAT);
	inputSlots_[1]->SetDataAccess(DataAccess::ITEM);

	inputSlots_[2]->SetName("Tolerance");
	inputSlots_[2]->SetVariableName("Tolerance");
	inputSlots_[2]->SetDescription("Tolerance from average length to split/collapse");
	inputSlots_[2]->SetVariantType(VariantType::VAR_FLOAT);
	inputSlots_[2]->SetDataAccess(DataAccess::ITEM);
	inputSlots_[2]->SetDefaultValue(Variant(0.33f));
	inputSlots_[2]->DefaultSet();

	inputSlots_[3]->SetName("NumSteps");
	inputSlots_[3]->SetVariableName("NumSteps");
	inputSlots_[3]->SetDescription("Number of split/collapse steps to perform");
	inputSlots_[3]->SetVariantType(VariantType::VAR_FLOAT);
	inputSlots_[3]->SetDataAccess(DataAccess::ITEM);
	inputSlots_[3]->SetDefaultValue(Variant(2));
	inputSlots_[3]->DefaultSet();

	outputSlots_[0]->SetName("TriMesh");
	outputSlots_[0]->SetVariableName("TriMesh");
	outputSlots_[0]->SetDescription("TriMesh after remeshing");
	outputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);
	outputSlots_[0]->SetDataAccess(DataAccess::ITEM);
}

void Mesh_Remesh::SolveInstance(
	const Vector<Variant>& inSolveInstance,
	Vector<Variant>& outSolveInstance
)
{
	assert(inSolveInstance.Size() == inputSlots_.Size());
	assert(outSolveInstance.Size() == outputSlots_.Size());

	///////////////////
	// VERIFY & EXTRACT

	// Verify input slot 0
	Variant inMesh = inSolveInstance[0];
	if (!TriMesh_Verify(inMesh)) {
		URHO3D_LOGWARNING("Mesh_Remesh -- invalid TriMesh");
		SetAllOutputsNull(outSolveInstance);
		return;
	}

	// get input slot 1 (optional)
	Variant target_var = inSolveInstance[1];
	//float target = Geomlib::TriMeshAverageEdgeLength(inMesh);
	//if (target_var.GetType() == VAR_FLOAT)
	//	target = target_var.GetFloat();

	// Verify input slot 0
	float tol = inSolveInstance[2].GetFloat();
	if (tol < 0.0f || tol >= 1.0f) {
		URHO3D_LOGWARNING("Mesh_Remesh -- Tolerance must be in range 0 <= Tolerance < 1.0f");
		SetAllOutputsNull(outSolveInstance);
		return;
	}
	// Verify input slot 1
	int steps = inSolveInstance[3].GetInt();
	if (steps < 0) {
		URHO3D_LOGWARNING("Mesh_Remesh -- NumSteps must be non-negative");
		SetAllOutputsNull(outSolveInstance);
		return;
	}

	///////////////////
	// COMPONENT'S WORK

	Variant curMesh = inMesh;
	for (int i = 0; i < steps; ++i) {

		float avg_edge_length = Geomlib::TriMeshAverageEdgeLength(curMesh);
		if (target_var.GetType() == VAR_FLOAT)
			avg_edge_length = target_var.GetFloat();
		float split_threshold = (1.0f + tol) * avg_edge_length;
		Variant splitMesh = Geomlib::TriMesh_SplitLongEdges(curMesh, split_threshold);
		//avg_edge_length = Geomlib::TriMeshAverageEdgeLength(splitMesh);
		float collapse_threshold = (1.0f - tol) * avg_edge_length;
		curMesh = Geomlib::TriMesh_CollapseShortEdges(splitMesh, collapse_threshold);
	}

	/////////////////
	// ASSIGN OUTPUTS

	outSolveInstance[0] = curMesh;
}


text:
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/locks.hpp>

// Including this will cause ambiguous errors in boost::move
#include <boost/unordered_map.hpp>

using namespace boost;

typedef upgrade_lock<shared_mutex> auto_upgrade_lock;
typedef upgrade_to_unique_lock<shared_mutex> auto_upgrade_unique_lock;

void testUpgrade(void)
{
	shared_mutex		mtx;
	auto_upgrade_lock	lock(mtx);
	// Do some read-only stuff

	auto_upgrade_unique_lock writeLock(lock);
	// Do some write-only stuff with the upgraded lock
}

int main()
{
  testUpgrade();
  return 0;
}


text:
#include <Eigen/Core>

#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<boost::int64_t, 6, 4> test_long_6_4(const Eigen::Matrix<boost::int64_t, 6, 4>& M) { return M; }
void export_long_6_4() { boost::python::def("test_long_6_4", test_long_6_4); }

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
#include <bio/sequence.h>
#include <bio/biobase_db.h>
#include <bio/biobase_data_traits.h>
#include <bio/biobase_parse_spirit.h>
USING_BIO_NS;
using namespace BIO_NS::spirit;

#include <boost/progress.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost;
using boost::unit_test::test_suite;

#include <fstream>
using namespace std;

//#define VERBOSE_CHECKING

BOOST_TEST_DONT_PRINT_LOG_VALUE( Matrix::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Site::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Factor::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Fragment::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Molecule::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Pathway::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Compel::map_t );
BOOST_TEST_DONT_PRINT_LOG_VALUE( Evidence::map_t );

template <TransData type>
void
check_biobase_table_parse()
{
	typedef DataTraits<type> traits_t;

	cout << "******* check_parsing(): " << traits_t::get_name() << endl;

	//parse the biobase file
	typename traits_t::entry_t::map_t map;
	{
#ifdef VERBOSE_CHECKING
		cout << "Parsing " << traits_t::get_name() << " entries from " << traits_t::get_biobase_file() << endl;
		progress_timer timer;
#endif

		parse<type>(map);

#ifdef VERBOSE_CHECKING
		cout << "Parsed " << map.size() << " entries" << endl;
#endif

	}
	BOOST_CHECK_EQUAL(map.size(), traits_t::get_num_data());
}

//make sure the template functions are instantiated
void check_parse_all_tables()
{
	check_biobase_table_parse< SITE_DATA >();
	check_biobase_table_parse< MATRIX_DATA >();
	check_biobase_table_parse< FACTOR_DATA >();
	check_biobase_table_parse< FRAGMENT_DATA >();
	check_biobase_table_parse< COMPEL_DATA >();
	check_biobase_table_parse< EVIDENCE_DATA >();
	check_biobase_table_parse< PATHWAY_DATA >();
	check_biobase_table_parse< MOLECULE_DATA >();
}

void check_biobase_load_all()
{
	cout << "******* check_biobase_load_all()\n";

	BiobaseDb::singleton().load_all();
}

void
register_biobase_parse_tests(boost::unit_test::test_suite * test)
{
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< MATRIX_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< FACTOR_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< SITE_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< FRAGMENT_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< COMPEL_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< EVIDENCE_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< PATHWAY_DATA > ), 0);
	test->add( BOOST_TEST_CASE( &check_biobase_table_parse< MOLECULE_DATA > ), 0);

	test->add( BOOST_TEST_CASE( &check_biobase_load_all ), 0);

#if 0
#endif
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
// ----------------------------------------------------------------------------
// Copyright (C) 2020 Apoapse
// Copyright (C) 2020 Guillaume Puyal
//
// 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
//
// For more information visit https://github.com/apoapse/
// And https://apoapse.space/
// ----------------------------------------------------------------------------

#pragma once
#include "TypeDefs.hpp"
#include <array>
#include "Range.hpp"
#include <sstream>
#include <iomanip>

// #ifdef _WIN32
// #define BOOST_LITTLE_ENDIAN 1
// #else
// #define BOOST_ENDIAN_DEPRECATED_NAMES
// #include <boost/endian/endian.hpp>
// #endif

enum class Endianness
{
	AP_LITTLE_ENDIAN,
	AP_BIG_ENDIAN
};

template <typename T>
inline std::array<byte, sizeof(T)> ToBytes(T data, Endianness endianness = Endianness::AP_LITTLE_ENDIAN)
{
	static_assert(std::is_trivially_copyable<T>::value, "The type provided is not trivially copyable");
	std::array<byte, sizeof(T)> bytes{};

	const byte* it = static_cast<const byte*>(static_cast<void*>(std::addressof(data)));

	if (endianness == Endianness::AP_LITTLE_ENDIAN)
		std::copy(it, it + sizeof(T), bytes.begin());
	else
		std::reverse_copy(it, it + sizeof(T), bytes.begin());

	return bytes;
}

template <typename T>
inline T FromBytes(std::array<byte, sizeof(T)>& byteArray, Endianness endianness = Endianness::AP_LITTLE_ENDIAN)
{
	static_assert(std::is_trivially_copyable<T>::value, "The type provided is not trivially copyable");

	T output;

	if (endianness == Endianness::AP_LITTLE_ENDIAN)
		std::copy(byteArray.begin(), byteArray.end(), static_cast<byte*>(static_cast<void*>(std::addressof(output))));
	else
		std::reverse_copy(byteArray.begin(), byteArray.end(), static_cast<byte*>(static_cast<void*>(std::addressof(output))));

	return output;
}

template <typename T, typename RANGE_TYPE>
inline T FromBytes(Range<RANGE_TYPE>& bytes, Endianness endianness = Endianness::AP_LITTLE_ENDIAN)
{
	static_assert(std::is_trivially_copyable<T>::value, "The type provided is not trivially copyable");

	T output;

	if (endianness == Endianness::AP_LITTLE_ENDIAN)
		std::copy(bytes.begin(), bytes.begin() + sizeof(T), static_cast<byte*>(static_cast<void*>(std::addressof(output))));
	else
		std::reverse_copy(bytes.begin(), bytes.begin() + sizeof(T), static_cast<byte*>(static_cast<void*>(std::addressof(output))));

	return output;
}

template <typename T>
std::string BytesToHexString(const T& bytesArray)
{
	static_assert(std::is_same<typename T::value_type, byte>::value, "The array provided do not contain bytes");

	std::stringstream ss;
	ss << std::hex << std::setfill('0');

	for (const auto& byte : bytesArray)
	{
		ss << static_cast<Int16>(byte);
	}

	return ss.str();
}

max_stars_repo_name: apoapse/ApoapseProtocol

max_issues_repo_name: apoapse/ApoapseProtocol

max_forks_repo_name: apoapse/ApoapseProtocol


text:
/* This file is part of the Tomographer project, which is distributed under the
 * terms of the MIT license.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
 * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <cmath>

#include <string>
#include <iostream>
#include <random>

#include <boost/math/constants/constants.hpp>

// definitions for Tomographer test framework -- this must be included before any
// <Eigen/...> or <tomographer/...> header
#include "test_tomographer.h"

#include <tomographer/multiproc.h>

#include <tomographer/tools/boost_test_logger.h>

#include "test_multi_tasks_common.h"

// -----------------------------------------------------------------------------
// fixture(s)

// -----------------------------------------------------------------------------
// test suites

BOOST_AUTO_TEST_SUITE(test_multiproc)
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(sequential_dispatcher)

BOOST_FIXTURE_TEST_CASE(runs, test_task_dispatcher_fixture)
{
  Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::LONGDEBUG);
  Tomographer::MultiProc::Sequential::TaskDispatcher<TestTask, TestBasicCData,
                                                     Tomographer::Logger::BoostTestLogger, long>
      task_dispatcher(&cData, logger, num_runs);

  BOOST_MESSAGE("About to run tasks");

  task_dispatcher.run();

  check_correct_results_collected(task_dispatcher);
}

BOOST_FIXTURE_TEST_SUITE(status_reporting, test_task_dispatcher_status_reporting_fixture) ;

BOOST_AUTO_TEST_CASE(status_report_periodic)
{
  Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::LONGDEBUG);
  Tomographer::MultiProc::Sequential::TaskDispatcher<StatusRepTestTask, StatusRepTestBasicCData,
                                                     Tomographer::Logger::BoostTestLogger, long>
      task_dispatcher(&cData, logger, num_runs);

  perform_test_status_report_periodic(task_dispatcher, logger) ;
}
BOOST_AUTO_TEST_CASE(interrupt_tasks_withthread)
{
  Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::LONGDEBUG);

  Tomographer::MultiProc::Sequential::TaskDispatcher<StatusRepTestTask, StatusRepTestBasicCData,
                                                     Tomographer::Logger::BoostTestLogger, long>
      task_dispatcher(&cData, logger, num_runs);

  perform_test_interrupt_tasks_withthread(task_dispatcher, logger) ;

}
BOOST_AUTO_TEST_CASE(status_report_withthread)
{
  Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::LONGDEBUG);

  Tomographer::MultiProc::Sequential::TaskDispatcher<StatusRepTestTask, StatusRepTestBasicCData,
                                              Tomographer::Logger::BoostTestLogger, long>
      task_dispatcher(&cData, logger, num_runs);

  perform_test_status_report_withthread(task_dispatcher, logger);
}
BOOST_AUTO_TEST_CASE(status_report_withsigalrm)
{
  Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::LONGDEBUG);

  Tomographer::MultiProc::Sequential::TaskDispatcher<StatusRepTestTask, StatusRepTestBasicCData,
                                                     Tomographer::Logger::BoostTestLogger, long>
      task_dispatcher(&cData, logger, num_runs);

  perform_test_status_report_withsigalrm(task_dispatcher, logger);
}

BOOST_AUTO_TEST_SUITE_END() ; // status_reporting

BOOST_AUTO_TEST_SUITE_END() ; // sequential_dispatcher

// -----------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END() ; // test_multiproc

ext: cxx

max_stars_repo_name: Tomographer/tomographer

max_issues_repo_name: Tomographer/tomographer

max_forks_repo_name: Tomographer/tomographer


text: #include <boost/preprocessor/comparison/less_equal.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/mpl/aux_/has_type.hpp>


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "lapack_common.h"
#include <Eigen/SVD>

// computes the singular values/vectors a general M-by-N matrix A using divide-and-conquer
EIGEN_LAPACK_FUNC(gesdd,(char *jobz, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int * /*iwork*/, int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if(*jobz!='A' && *jobz!='S' && *jobz!='O' && *jobz!='N')  *info = -1;
  else  if(*m<0)                                                  *info = -2;
  else  if(*n<0)                                                  *info = -3;
  else  if(*lda<std::max(1,*m))                                   *info = -5;
  else  if(*lda<std::max(1,*m))                                   *info = -8;
  else  if(*ldu <1 || (*jobz=='A' && *ldu <*m)
                   || (*jobz=='O' && *m<*n && *ldu<*m))           *info = -8;
  else  if(*ldvt<1 || (*jobz=='A' && *ldvt<*n)
                   || (*jobz=='S' && *ldvt<diag_size)
                   || (*jobz=='O' && *m>=*n && *ldvt<*n))         *info = -10;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESDD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = *jobz=='A' ? ComputeFullU|ComputeFullV
             : *jobz=='S' ? ComputeThinU|ComputeThinV
             : *jobz=='O' ? ComputeThinU|ComputeThinV
             : 0;

  BDCSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);

  if(*jobz=='A')
  {
    matrix(u,*m,*m,*ldu)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='S')
  {
    matrix(u,*m,diag_size,*ldu)   = svd.matrixU();
    matrix(vt,diag_size,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O' && *m>=*n)
  {
    matrix(a,*m,*n,*lda)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O')
  {
    matrix(u,*m,*m,*ldu)        = svd.matrixU();
    matrix(a,diag_size,*n,*lda) = svd.matrixV().adjoint();
  }

  return 0;
}

// computes the singular values/vectors a general M-by-N matrix A using two sided jacobi algorithm
EIGEN_LAPACK_FUNC(gesvd,(char *jobu, char *jobv, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if( *jobu!='A' && *jobu!='S' && *jobu!='O' && *jobu!='N') *info = -1;
  else  if((*jobv!='A' && *jobv!='S' && *jobv!='O' && *jobv!='N')
           || (*jobu=='O' && *jobv=='O'))                         *info = -2;
  else  if(*m<0)                                                  *info = -3;
  else  if(*n<0)                                                  *info = -4;
  else  if(*lda<std::max(1,*m))                                   *info = -6;
  else  if(*ldu <1 || ((*jobu=='A' || *jobu=='S') && *ldu<*m))    *info = -9;
  else  if(*ldvt<1 || (*jobv=='A' && *ldvt<*n)
                   || (*jobv=='S' && *ldvt<diag_size))            *info = -11;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESVD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = (*jobu=='A' ? ComputeFullU : *jobu=='S' || *jobu=='O' ? ComputeThinU : 0)
             | (*jobv=='A' ? ComputeFullV : *jobv=='S' || *jobv=='O' ? ComputeThinV : 0);

  JacobiSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);
  {
        if(*jobu=='A') matrix(u,*m,*m,*ldu)           = svd.matrixU();
  else  if(*jobu=='S') matrix(u,*m,diag_size,*ldu)    = svd.matrixU();
  else  if(*jobu=='O') matrix(a,*m,diag_size,*lda)    = svd.matrixU();
  }
  {
        if(*jobv=='A') matrix(vt,*n,*n,*ldvt)         = svd.matrixV().adjoint();
  else  if(*jobv=='S') matrix(vt,diag_size,*n,*ldvt)  = svd.matrixV().adjoint();
  else  if(*jobv=='O') matrix(a,diag_size,*n,*lda)    = svd.matrixV().adjoint();
  }
  return 0;
}