text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This is an example illustrating the use the general purpose non-linear
    optimization routines from the dlib C++ Library.

    The library provides implementations of many popular algorithms such as L-BFGS
    and BOBYQA.  These algorithms allow you to find the minimum or maximum of a
    function of many input variables.  This example walks though a few of the ways
    you might put these routines to use.

*/

#include <dlib/optimization.h>
#include <dlib/global_optimization.h>
#include <iostream>

using namespace std;
using namespace dlib;

// ----------------------------------------------------------------------------------------

// In dlib, most of the general purpose solvers optimize functions that take a
// column vector as input and return a double.  So here we make a typedef for a
// variable length column vector of doubles.  This is the type we will use to
// represent the input to our objective functions which we will be minimizing.
typedef matrix<double,0,1> column_vector;

// ----------------------------------------------------------------------------------------
// Below we create a few functions.  When you get down into main() you will see that
// we can use the optimization algorithms to find the minimums of these functions.
// ----------------------------------------------------------------------------------------

double rosen (const column_vector& m)
/*
    This function computes what is known as Rosenbrock's function.  It is
    a function of two input variables and has a global minimum at (1,1).
    So when we use this function to test out the optimization algorithms
    we will see that the minimum found is indeed at the point (1,1).
*/
{
    const double x = m(0);
    const double y = m(1);

    // compute Rosenbrock's function and return the result
    return 100.0*pow(y - x*x,2) + pow(1 - x,2);
}

// This is a helper function used while optimizing the rosen() function.
const column_vector rosen_derivative (const column_vector& m)
/*!
    ensures
        - returns the gradient vector for the rosen function
!*/
{
    const double x = m(0);
    const double y = m(1);

    // make us a column vector of length 2
    column_vector res(2);

    // now compute the gradient vector
    res(0) = -400*x*(y-x*x) - 2*(1-x); // derivative of rosen() with respect to x
    res(1) = 200*(y-x*x);              // derivative of rosen() with respect to y
    return res;
}

// This function computes the Hessian matrix for the rosen() fuction.  This is
// the matrix of second derivatives.
matrix<double> rosen_hessian (const column_vector& m)
{
    const double x = m(0);
    const double y = m(1);

    matrix<double> res(2,2);

    // now compute the second derivatives
    res(0,0) = 1200*x*x - 400*y + 2; // second derivative with respect to x
    res(1,0) = res(0,1) = -400*x;   // derivative with respect to x and y
    res(1,1) = 200;                 // second derivative with respect to y
    return res;
}

// ----------------------------------------------------------------------------------------

class rosen_model
{
    /*!
        This object is a "function model" which can be used with the
        find_min_trust_region() routine.
    !*/

public:
    typedef ::column_vector column_vector;
    typedef matrix<double> general_matrix;

    double operator() (
        const column_vector& x
    ) const { return rosen(x); }

    void get_derivative_and_hessian (
        const column_vector& x,
        column_vector& der,
        general_matrix& hess
    ) const
    {
        der = rosen_derivative(x);
        hess = rosen_hessian(x);
    }
};

// ----------------------------------------------------------------------------------------

#if defined(BUILD_MONOLITHIC)
#define main(cnt, arr)      dlib_optimization_ex_main(cnt, arr)
#endif

int main(int argc, const char** argv)
try
{
    // Set the starting point to (4,8).  This is the point the optimization algorithm
    // will start out from and it will move it closer and closer to the function's
    // minimum point.   So generally you want to try and compute a good guess that is
    // somewhat near the actual optimum value.
    column_vector starting_point = {4, 8};

    // The first example below finds the minimum of the rosen() function and uses the
    // analytical derivative computed by rosen_derivative().  Since it is very easy to
    // make a mistake while coding a function like rosen_derivative() it is a good idea
    // to compare your derivative function against a numerical approximation and see if
    // the results are similar.  If they are very different then you probably made a
    // mistake.  So the first thing we do is compare the results at a test point:
    cout << "Difference between analytic derivative and numerical approximation of derivative: "
         << length(derivative(rosen)(starting_point) - rosen_derivative(starting_point)) << endl;

    cout << "Find the minimum of the rosen function()" << endl;
    // Now we use the find_min() function to find the minimum point.  The first argument
    // to this routine is the search strategy we want to use.  The second argument is the
    // stopping strategy.  Below I'm using the objective_delta_stop_strategy which just
    // says that the search should stop when the change in the function being optimized
    // is small enough.

    // The other arguments to find_min() are the function to be minimized, its derivative,
    // then the starting point, and the last is an acceptable minimum value of the rosen()
    // function.  That is, if the algorithm finds any inputs to rosen() that gives an output
    // value <= -1 then it will stop immediately.  Usually you supply a number smaller than
    // the actual global minimum.  So since the smallest output of the rosen function is 0
    // we just put -1 here which effectively causes this last argument to be disregarded.

    find_min(bfgs_search_strategy(),  // Use BFGS search algorithm
             objective_delta_stop_strategy(1e-7), // Stop when the change in rosen() is less than 1e-7
             rosen, rosen_derivative, starting_point, -1);
    // Once the function ends the starting_point vector will contain the optimum point
    // of (1,1).
    cout << "rosen solution:\n" << starting_point << endl;

    // Now let's try doing it again with a different starting point and the version
    // of find_min() that doesn't require you to supply a derivative function.
    // This version will compute a numerical approximation of the derivative since
    // we didn't supply one to it.
    starting_point = {-94, 5.2};
    find_min_using_approximate_derivatives(bfgs_search_strategy(),
                                           objective_delta_stop_strategy(1e-7),
                                           rosen, starting_point, -1);
    // Again the correct minimum point is found and stored in starting_point
    cout << "rosen solution:\n" << starting_point << endl;

    // Here we repeat the same thing as above but this time using the L-BFGS
    // algorithm.  L-BFGS is very similar to the BFGS algorithm, however, BFGS
    // uses O(N^2) memory where N is the size of the starting_point vector.
    // The L-BFGS algorithm however uses only O(N) memory.  So if you have a
    // function of a huge number of variables the L-BFGS algorithm is probably
    // a better choice.
    starting_point = {0.8, 1.3};
    find_min(lbfgs_search_strategy(10),  // The 10 here is basically a measure of how much memory L-BFGS will use.
             objective_delta_stop_strategy(1e-7).be_verbose(),  // Adding be_verbose() causes a message to be
                                                                // printed for each iteration of optimization.
             rosen, rosen_derivative, starting_point, -1);

    cout << endl << "rosen solution: \n" << starting_point << endl;

    starting_point = {-94, 5.2};
    find_min_using_approximate_derivatives(lbfgs_search_strategy(10),
                                           objective_delta_stop_strategy(1e-7),
                                           rosen, starting_point, -1);
    cout << "rosen solution: \n"<< starting_point << endl;

    // dlib also supports solving functions subject to bounds constraints on
    // the variables.  So for example, if you wanted to find the minimizer
    // of the rosen function where both input variables were in the range
    // 0.1 to 0.8 you would do it like this:
    starting_point = {0.1, 0.1}; // Start with a valid point inside the constraint box.
    find_min_box_constrained(lbfgs_search_strategy(10),
                             objective_delta_stop_strategy(1e-9),
                             rosen, rosen_derivative, starting_point, 0.1, 0.8);
    // Here we put the same [0.1 0.8] range constraint on each variable, however, you
    // can put different bounds on each variable by passing in column vectors of
    // constraints for the last two arguments rather than scalars.

    cout << endl << "constrained rosen solution: \n" << starting_point << endl;

    // You can also use an approximate derivative like so:
    starting_point = {0.1, 0.1};
    find_min_box_constrained(bfgs_search_strategy(),
                             objective_delta_stop_strategy(1e-9),
                             rosen, derivative(rosen), starting_point, 0.1, 0.8);
    cout << endl << "constrained rosen solution: \n" << starting_point << endl;

    // In many cases, it is useful if we also provide second derivative information
    // to the optimizers.  Two examples of how we can do that are shown below.
    starting_point = {0.8, 1.3};
    find_min(newton_search_strategy(rosen_hessian),
             objective_delta_stop_strategy(1e-7),
             rosen,
             rosen_derivative,
             starting_point,
             -1);
    cout << "rosen solution: \n"<< starting_point << endl;

    // We can also use find_min_trust_region(), which is also a method which uses
    // second derivatives.  For some kinds of non-convex function it may be more
    // reliable than using a newton_search_strategy with find_min().
    starting_point = {0.8, 1.3};
    find_min_trust_region(objective_delta_stop_strategy(1e-7),
                          rosen_model(),
                          starting_point,
                          10 // initial trust region radius
    );
    cout << "rosen solution: \n"<< starting_point << endl;

    // Next, let's try the BOBYQA algorithm.  This is a technique specially
    // designed to minimize a function in the absence of derivative information.
    // Generally speaking, it is the method of choice if derivatives are not available
    // and the function you are optimizing is smooth and has only one local optima.  As
    // an example, consider the be_like_target function defined below:
    column_vector target = {3, 5, 1, 7};
    auto be_like_target = [&](const column_vector& x) {
        return mean(squared(x-target));
    };
    starting_point = {-4,5,99,3};
    find_min_bobyqa(be_like_target,
                    starting_point,
                    9,    // number of interpolation points
                    uniform_matrix<double>(4,1, -1e100),  // lower bound constraint
                    uniform_matrix<double>(4,1, 1e100),   // upper bound constraint
                    10,    // initial trust region radius
                    1e-6,  // stopping trust region radius
                    100    // max number of objective function evaluations
    );
    cout << "be_like_target solution:\n" << starting_point << endl;

    // Finally, let's try the find_min_global() routine.  Like find_min_bobyqa(),
    // this technique is specially designed to minimize a function in the absence
    // of derivative information.  However, it is also designed to handle
    // functions with many local optima.  Where BOBYQA would get stuck at the
    // nearest local optima, find_min_global() won't.  find_min_global() uses a
    // global optimization method based on a combination of non-parametric global
    // function modeling and BOBYQA style quadratic trust region modeling to
    // efficiently find a global minimizer.  It usually does a good job with a
    // relatively small number of calls to the function being optimized.
    //
    // You also don't have to give it a starting point or set any parameters,
    // other than defining bounds constraints.  This makes it the method of
    // choice for derivative free optimization in the presence of multiple local
    // optima.  Its API also allows you to define functions that take a
    // column_vector as shown above or to explicitly use named doubles as
    // arguments, which we do here.
    auto complex_holder_table = [](double x0, double x1)
    {
        // This function is a version of the well known Holder table test
        // function, which is a function containing a bunch of local optima.
        // Here we make it even more difficult by adding more local optima
        // and also a bunch of discontinuities.

        // add discontinuities
        double sign = 1;
        for (double j = -4; j < 9; j += 0.5)
        {
            if (j < x0 && x0 < j+0.5)
                x0 += sign*0.25;
            sign *= -1;
        }
        // Holder table function tilted towards 10,10 and with additional
        // high frequency terms to add more local optima.
        return -( std::abs(sin(x0)*cos(x1)*exp(std::abs(1-std::sqrt(x0*x0+x1*x1)/pi))) -(x0+x1)/10 - sin(x0*10)*cos(x1*10));
    };

    // To optimize this difficult function all we need to do is call
    // find_min_global()
    auto result = find_min_global(complex_holder_table,
                                  {-10,-10}, // lower bounds
                                  {10,10}, // upper bounds
                                  std::chrono::milliseconds(500) // run this long
                                  );

    cout.precision(9);
    // These cout statements will show that find_min_global() found the
    // globally optimal solution to 9 digits of precision:
    cout << "complex holder table function solution y (should be -21.9210397): " << result.y << endl;
    cout << "complex holder table function solution x:\n" << result.x << endl;
}
catch (std::exception& e)
{
    cout << e.what() << endl;
}

max_stars_repo_name: GerHobbelt/dlib

max_issues_repo_name: GerHobbelt/dlib

max_forks_repo_name: GerHobbelt/dlib


text:
//          Copyright Erle Carrara 2017.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <pybind11/pybind11.h>

using namespace boost::accumulators;
namespace py = pybind11;

using accumulator_set_type = accumulator_set<double, stats<tag::mean>>;

PYBIND11_PLUGIN(accumulators) {
    py::module m("accumulators");

    py::class_<accumulator_set_type>(m, "Accumulator")
        .def(py::init())
        .def("__call__", [](accumulator_set_type &acc, double v) {
            return acc(v);
        }, py::is_operator())
        .def("mean", [](const accumulator_set_type &acc) {
        return mean(acc);
    });

    return m.ptr();
}

ext: cpp

max_stars_repo_name: ecarrara/accumulators-py

max_issues_repo_name: ecarrara/accumulators-py

max_forks_repo_name: ecarrara/accumulators-py


text:
#ifndef slic3r_Line_hpp_
#define slic3r_Line_hpp_

#include <myinit.h>
#include "Point.hpp"
#include <boost/polygon/polygon.hpp>

namespace Slic3r {

class Line;
class Polyline;

class Line
{
    public:
    Point a;
    Point b;
    Line() {};
    explicit Line(Point _a, Point _b): a(_a), b(_b) {};
    std::string wkt() const;
    operator Polyline() const;
    void scale(double factor);
    void translate(double x, double y);
    void rotate(double angle, Point* center);
    void reverse();
    double length() const;
    Point* midpoint() const;
    void point_at(double distance, Point* point) const;
    Point point_at(double distance) const;
    bool coincides_with(const Line* line) const;
    double distance_to(const Point* point) const;
    double atan2_() const;
    double direction() const;
    Vector vector() const;

    #ifdef SLIC3RXS
    void from_SV(SV* line_sv);
    void from_SV_check(SV* line_sv);
    SV* to_AV();
    SV* to_SV_ref();
    SV* to_SV_clone_ref() const;
    SV* to_SV_pureperl() const;
    #endif
};

typedef std::vector<Line> Lines;

}

// start Boost
namespace boost { namespace polygon {
    template <>
    struct geometry_concept<Line> { typedef segment_concept type; };

    template <>
    struct segment_traits<Line> {
        typedef coord_t coordinate_type;
        typedef Point point_type;

        static inline point_type get(const Line& line, direction_1d dir) {
            return dir.to_int() ? line.b : line.a;
        }
    };
} }
// end Boost

#endif

ext: hpp


text:
/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <vector>
#include <sstream>
#include <iostream>
#include <boost/thread/thread.hpp>

// Internet/Socket stuff
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>

#include "power_comm.h"
#include "power_node.h"
#include "diagnostic_msgs/DiagnosticMessage.h"
#include "diagnostic_updater/DiagnosticStatusWrapper.h"
#include "rosconsole/macros_generated.h"
#include "ros/console.h"

using namespace std;

// Keep a pointer to the last message recieved for
// Each board.
static std::vector<Device*> Devices;
static PowerBoard *myBoard;

void processSentMessage(CommandMessage *cmd);

void Device::setTransitionMessage(const TransitionMessage &newtmsg)
{
  if (tmsgset)
  {
#define PRINT_IF_CHANGED(val)                                                                                \
for (int counter = 0; counter < 3; counter++)                                                                 \
{                                                                                \
  if (tmsg.cb[counter].val##_count != newtmsg.cb[counter].val##_count)                                        \
  {                                                                                \
    ROS_INFO("Power board: CB%i "#val" event count changed to %i.", counter, newtmsg.cb[counter].val##_count);\
  }                                                                                \
}

  PRINT_IF_CHANGED(stop);
  PRINT_IF_CHANGED(estop);
  PRINT_IF_CHANGED(trip);
  PRINT_IF_CHANGED(fail_18V);
  PRINT_IF_CHANGED(disable);
  PRINT_IF_CHANGED(start);
  PRINT_IF_CHANGED(pump_fail);
  PRINT_IF_CHANGED(reset);

#undef PRINT_IF_CHANGED
  }
  else
    tmsgset = 1;

  tmsg = newtmsg;
}

void Device::setPowerMessage(const PowerMessage &newpmsg)
{
  if (pmsgset)
  {
#define PRINT_IF_CHANGED(val)                                                            \
if (pmsg.status.val##_status != newpmsg.status.val##_status)                             \
{                                                                                \
  ROS_INFO("Power board: status of "#val" changed to %i.", newpmsg.status.val##_status); \
}

  PRINT_IF_CHANGED(CB0);
  PRINT_IF_CHANGED(CB1);
  PRINT_IF_CHANGED(CB2);
  PRINT_IF_CHANGED(estop_button);
  PRINT_IF_CHANGED(estop);

#undef PRINT_IF_CHANGED
  }
  else
    pmsgset = 1;

  pmsg = newpmsg;
}

int PowerBoard::send_command(unsigned int serial_number, int circuit_breaker, const std::string &command, unsigned flags)
{
  if (Devices.size() == 0) {
    fprintf(stderr,"No devices to send command to\n");
    return -1;
  }

  int selected_device = -1;
  // Look for device serial number in list of devices...
  for (unsigned i = 0; i<Devices.size(); ++i) {
    if (Devices[i]->getPowerMessage().header.serial_num == serial_number) {
      selected_device = i;
      break;
    }
  }

  if ((selected_device < 0) || (selected_device >= (int)Devices.size())) {
    fprintf(stderr, "Device number must be between 0 and %u\n", Devices.size()-1);
    return -1;
  }

  Device* device = Devices[selected_device];
  assert(device != NULL);

  if ((circuit_breaker < 0) || (circuit_breaker > 2)) {
    fprintf(stderr, "Circuit breaker number must be between 0 and 2\n");
    return -1;
  }

  ROS_DEBUG("circuit=%d command=%s flags=%x\n", circuit_breaker, command.c_str(), flags);

  // Determine what command to send
  char command_enum = NONE;
  if (command == "start") {
    command_enum = COMMAND_START;
  }
  else if (command ==  "stop") {
    command_enum = COMMAND_STOP;
  }
  else if (command == "reset") {
    command_enum = COMMAND_RESET;
  }
  else if (command == "disable") {
    command_enum = COMMAND_DISABLE;
  }
  else if (command == "none") {
    command_enum = NONE;
  }
  /*else if (command == "terrible_hack_shutdown") {
    exit(0);
  }*/
  else {
    ROS_ERROR("invalid command '%s'", command.c_str());
    return -1;
  }
  //" -c : command to send to device : 'start', 'stop', 'reset', 'disable'\n"

  // Build command message
  CommandMessage cmdmsg;
  memset(&cmdmsg, 0, sizeof(cmdmsg));
  cmdmsg.header.message_revision = CURRENT_MESSAGE_REVISION;
  cmdmsg.header.message_id = MESSAGE_ID_COMMAND;
  cmdmsg.header.serial_num = device->getPowerMessage().header.serial_num;
  //cmdmsg.header.serial_num = 0x12345678;
  strncpy(cmdmsg.header.text, "power command message", sizeof(cmdmsg.header.text));
  cmdmsg.command.CB0_command = NONE;
  cmdmsg.command.CB1_command = NONE;
  cmdmsg.command.CB2_command = NONE;
  if (circuit_breaker==0) {
    cmdmsg.command.CB0_command = command_enum;
  }
  else if (circuit_breaker==1) {
    cmdmsg.command.CB1_command = command_enum;
  }
  else if (circuit_breaker==2) {
    cmdmsg.command.CB2_command = command_enum;
  }
  else if (circuit_breaker==-1) {
    cmdmsg.command.CB0_command = command_enum;
    cmdmsg.command.CB1_command = command_enum;
    cmdmsg.command.CB2_command = command_enum;
  }

  cmdmsg.command.flags = flags;

  errno = 0;

  processSentMessage(&cmdmsg);

  ROS_DEBUG("Send to Serial=%u, revision=%u", cmdmsg.header.serial_num, cmdmsg.header.message_revision);
  ROS_DEBUG("Sent command %s(%d) to device %d, circuit %d",
         command.c_str(), command_enum, selected_device, circuit_breaker);

  return 0;
}

const char* PowerBoard::cb_state_to_str(char state)
{
  //enum CB_State { STATE_NOPOWER, STATE_STANDBY, STATE_PUMPING, STATE_ON, STATE_DISABLED };
  switch(state) {
  case STATE_NOPOWER:
    return "no-power";
  case STATE_STANDBY:
    return "Standby";
  case STATE_PUMPING:
    return "pumping";
  case STATE_ON:
    return "On";
  case STATE_DISABLED:
    return "Disabled";
  }
  return "???";
}

const char* PowerBoard::master_state_to_str(char state)
{
  //enum CB_State { STATE_NOPOWER, STATE_STANDBY, STATE_PUMPING, STATE_ON, STATE_DISABLED };
  switch(state) {
  case MASTER_NOPOWER:
    return "no-power";
  case MASTER_STANDBY:
    return "stand-by";
  case MASTER_ON:
    return "on";
  case MASTER_OFF:
    return "off";
  }
  return "???";
}

// Determine if a record of the device already exists...
// If it does use newest message a fill in pointer to old one .
// If it does not.. use
int PowerBoard::process_message(const PowerMessage *msg)
{
  if (msg->header.message_revision != CURRENT_MESSAGE_REVISION) {
    ROS_WARN("Got message with incorrect message revision %u\n", msg->header.message_revision);
    return -1;
  }

  // Look for device serial number in list of devices...
  for (unsigned i = 0; i<Devices.size(); ++i) {
    if (Devices[i]->getPowerMessage().header.serial_num == msg->header.serial_num) {
      boost::mutex::scoped_lock(library_lock_);
      Devices[i]->message_time = ros::Time::now();
      Devices[i]->setPowerMessage(*msg);
      return 0;
    }
  }

  // Add new device to list
  Device *newDevice = new Device();
  Devices.push_back(newDevice);
  newDevice->message_time = ros::Time::now();
  newDevice->setPowerMessage(*msg);
  return 0;
}

int PowerBoard::process_transition_message(const TransitionMessage *msg)
{
  if (msg->header.message_revision != CURRENT_MESSAGE_REVISION) {
    ROS_WARN("Got message with incorrect message revision %u\n", msg->header.message_revision);
    return -1;
  }

  // Look for device serial number in list of devices...
  for (unsigned i = 0; i<Devices.size(); ++i) {
    if (Devices[i]->getPowerMessage().header.serial_num == msg->header.serial_num) {
      boost::mutex::scoped_lock(library_lock_);
      Devices[i]->setTransitionMessage(*msg);
      return 0;
    }
  }

  // Add new device to list
  Device *newDevice = new Device();
  Devices.push_back(newDevice);
  newDevice->setTransitionMessage(*msg);
  return 0;
}

PowerBoard::PowerBoard( unsigned int serial_number ): ros::Node ("pr2_power_board")
{

  ROSCONSOLE_AUTOINIT;
  log4cxx::LoggerPtr my_logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME);

  if( my_logger->getLevel() == 0 )    //has anyone set our level??
  {
    // Set the ROS logger
    my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Info]);
  }

  advertiseService("power_board_control", &PowerBoard::commandCallback);
  advertise<diagnostic_msgs::DiagnosticMessage>("/diagnostics", 2);
}

bool PowerBoard::commandCallback(pr2_power_board::PowerBoardCommand::Request &req_,
                     pr2_power_board::PowerBoardCommand::Response &res_)
{
  res_.retval = send_command( req_.serial_number, req_.breaker_number, req_.command, req_.flags);

  return true;
}

void PowerBoard::sendDiagnostic()
{
  ros::Rate r(1);
  while(node_handle.ok())
  {
    r.sleep();
    //ROS_DEBUG("-");
    boost::mutex::scoped_lock(library_lock_);

    for (unsigned i = 0; i<Devices.size(); ++i)
    {
      diagnostic_msgs::DiagnosticArray msg_out;
      diagnostic_updater::DiagnosticStatusWrapper stat;

      Device *device = Devices[i];
      const PowerMessage *pmesg = &device->getPowerMessage();

      ostringstream ss;
      ss << "Power board " << pmesg->header.serial_num;
      stat.name = ss.str();

      if( (ros::Time::now() - device->message_time) > TIMEOUT )
      {
        stat.summary(2, "No Updates");
      }
      else
      {
        stat.summary(0, "Running");
      }
      const StatusStruct *status = &pmesg->status;

      ROS_DEBUG("Device %u", i);
      ROS_DEBUG(" Serial       = %u", pmesg->header.serial_num);

      stat.add("Serial Number", pmesg->header.serial_num);

      ROS_DEBUG(" Current      = %f", status->input_current);
      stat.add("Input Current", status->input_current);

      ROS_DEBUG(" Voltages:");
      ROS_DEBUG("  Input       = %f", status->input_voltage);
      stat.add("Input Voltage", status->input_voltage);

      ROS_DEBUG("  DCDC 12     = %f", status->DCDC_12V_out_voltage);
      stat.add("DCDC12", status->DCDC_12V_out_voltage);

      ROS_DEBUG("  DCDC 15     = %f", status->DCDC_19V_out_voltage);
      stat.add("DCDC 15", status->DCDC_19V_out_voltage);

      ROS_DEBUG("  CB0 (Base)  = %f", status->CB0_voltage);
      stat.add("Breaker 0 Voltage", status->CB0_voltage);

      ROS_DEBUG("  CB1 (R-arm) = %f", status->CB1_voltage);
      stat.add("Breaker 1 Voltage", status->CB1_voltage);

      ROS_DEBUG("  CB2 (L-arm) = %f", status->CB2_voltage);
      stat.add("Breaker 2 Voltage", status->CB2_voltage);

      ROS_DEBUG(" Board Temp   = %f", status->ambient_temp);
      stat.add("Board Temperature", status->ambient_temp);

      ROS_DEBUG(" Fan Speeds:");
      ROS_DEBUG("  Fan 0       = %u", status->fan0_speed);
      stat.add("Fan 0 Speed", status->fan0_speed);

      ROS_DEBUG("  Fan 1       = %u", status->fan1_speed);
      stat.add("Fan 1 Speed", status->fan1_speed);

      ROS_DEBUG("  Fan 2       = %u", status->fan2_speed);
      stat.add("Fan 2 Speed", status->fan2_speed);

      ROS_DEBUG("  Fan 3       = %u", status->fan3_speed);
      stat.add("Fan 3 Speed", status->fan3_speed);

      ROS_DEBUG(" State:");
      ROS_DEBUG("  CB0 (Base)  = %s", cb_state_to_str(status->CB0_state));
      stat.add("Breaker 0 State", cb_state_to_str(status->CB0_state));

      ROS_DEBUG("  CB1 (R-arm) = %s", cb_state_to_str(status->CB1_state));
      stat.add("Breaker 1 State", cb_state_to_str(status->CB1_state));

      ROS_DEBUG("  CB2 (L-arm) = %s", cb_state_to_str(status->CB2_state));
      stat.add("Breaker 2 State", cb_state_to_str(status->CB2_state));

      ROS_DEBUG("  DCDC        = %s", master_state_to_str(status->DCDC_state));
      stat.add("DCDC state", master_state_to_str(status->DCDC_state));

      ROS_DEBUG(" Status:");
      ROS_DEBUG("  CB0 (Base)  = %s", (status->CB0_status) ? "On" : "Off");
      stat.add("Breaker 0 Status", (status->CB0_status) ? "On" : "Off");

      ROS_DEBUG("  CB1 (R-arm) = %s", (status->CB1_status) ? "On" : "Off");
      stat.add("Breaker 1 Status", (status->CB1_status) ? "On" : "Off");

      ROS_DEBUG("  CB2 (L-arm) = %s", (status->CB2_status) ? "On" : "Off");
      stat.add("Breaker 2 Status", (status->CB2_status) ? "On" : "Off");

      ROS_DEBUG("  estop_button= %x", (status->estop_button_status));
      stat.add("RunStop Button Status", status->estop_button_status);

      ROS_DEBUG("  estop_status= %x", (status->estop_status));
      stat.add("RunStop Status", status->estop_status);

      ROS_DEBUG(" Revisions:");
      ROS_DEBUG("         PCA = %c", status->pca_rev);
      stat.add("PCA", status->pca_rev);

      ROS_DEBUG("         PCB = %c", status->pcb_rev);
      stat.add("PCB", status->pcb_rev);

      ROS_DEBUG("       Major = %c", status->major_rev);
      stat.add("Major Revision", status->major_rev);

      ROS_DEBUG("       Minor = %c", status->minor_rev);
      stat.add("Minor Revision", status->minor_rev);

      stat.add("Min Voltage", status->min_input_voltage);
      stat.add("Max Current", status->max_input_current);

      const TransitionMessage *tmsg = &device->getTransitionMessage();
      for(int cb_index=0; cb_index < 3; ++cb_index)
      {
        const TransitionCount *trans = &tmsg->cb[cb_index];
        ROS_DEBUG("Transition: CB%d", cb_index);
        ss.str("");
        ss << "CB" << cb_index << " Stop Count";
        stat.add(ss.str(), trans->stop_count);

        ss.str("");
        ss << "CB" << cb_index << " E-Stop Count";
        stat.add(ss.str(), trans->estop_count);

        ss.str("");
        ss << "CB" << cb_index << " Trip Count";
        stat.add(ss.str(), trans->trip_count);

        ss.str("");
        ss << "CB" << cb_index << " 18V Fail Count";
        stat.add(ss.str(), trans->fail_18V_count);

        ss.str("");
        ss << "CB" << cb_index << " Disable Count";
        stat.add(ss.str(), trans->disable_count);

        ss.str("");
        ss << "CB" << cb_index << " Start Count";
        stat.add(ss.str(), trans->start_count);

        ss.str("");
        ss << "CB" << cb_index << " Pump Fail Count";
        stat.add(ss.str(), trans->pump_fail_count);

        ss.str("");
        ss << "CB" << cb_index << " Reset Count";
        stat.add(ss.str(), trans->reset_count);
      }

      msg_out.status.push_back(stat);

      //ROS_DEBUG("Publishing ");
      pub.publish(msg_out);
    }

  }
}

void sendMessages()
{
  myBoard->sendDiagnostic();
}

void CloseAllDevices(void) {
  for (unsigned i=0; i<Devices.size(); ++i){
    if (Devices[i] != NULL) {
      delete Devices[i];
    }
  }
}

// Build list of interfaces
int CreateAllInterfaces(void)
{
  return 0;
}

void generateDeviceMessages()
{
  static PowerMessage pm;

  pm.header.message_revision = CURRENT_MESSAGE_REVISION; //32 bit
  pm.header.serial_num = 0xDADABABA;       //32 bit  Unique ID number
  //pm.header.text[32];         //Description identifier
  pm.header.message_id = MESSAGE_ID_POWER;
  pm.header.data_length = sizeof(pm.status);      //Length of the following structure

  /*pm.status.CB0_state;   // CB_State enum
  pm.status.CB1_state;
  pm.status.CB2_state;
  pm.status.DCDC_state;  // Master_State enum

  pm.status.input_voltage;
  pm.status.input_current;
  pm.status.DCDC_12V_out_voltage;
  pm.status.DCDC_19V_out_voltage;
  pm.status.CB0_voltage;
  pm.status.CB1_voltage;
  pm.status.CB2_voltage;
  pm.status.ambient_temp;
  pm.status.fan0_speed;
  pm.status.fan1_speed;
  pm.status.fan2_speed;
  pm.status.fan3_speed;
  pm.status.CB0_status;  //0-off 1-on
  pm.status.CB1_status;
  pm.status.CB2_status;
  pm.status.estop_button_status;
  pm.status.estop_status;
  pm.status.pca_rev;
  pm.status.pcb_rev;
  pm.status.major_rev;
  pm.status.minor_rev;
  pm.status.min_input_voltage;
  pm.status.max_input_current;*/

  int i = 0;
  while (myBoard->ok())
  {
    i++;
    if (i % 200 < 100) // Alternate between sending and not sending messages to test the display.
    {
      myBoard->process_message(&pm);
      ROS_INFO("Sent message");
    }
    else
      ROS_INFO("Idling");
    ros::Duration(0,1e8).sleep();
  }
}

void processSentMessage(CommandMessage *cmd)
{
  ROS_DEBUG("processSentMessage");
}

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

  CreateAllInterfaces();
  myBoard = new PowerBoard();

  boost::thread sendThread( &sendMessages );
  boost::thread fakeDeviceThread( &generateDeviceMessages );

  myBoard->spin(); //wait for ros to shut us down

  sendThread.join();

  CloseAllDevices();

  delete myBoard;
  return 0;

}


text: #include <boost/phoenix/object/reinterpret_cast.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2014 Erik Erlandson
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_BASE_UNITS_INFORMATION_SHANNON_HPP_INCLUDED
#define BOOST_UNITS_BASE_UNITS_INFORMATION_SHANNON_HPP_INCLUDED

#include <boost/units/scaled_base_unit.hpp>
#include <boost/units/static_rational.hpp>
#include <boost/units/scale.hpp>
#include <boost/units/units_fwd.hpp>
#include <boost/units/base_units/information/bit.hpp>

namespace boost {
namespace units {
namespace information {

typedef scaled_base_unit<boost::units::information::bit_base_unit, scale<1, static_rational<1> > > shannon_base_unit;

} // namespace information

template<>
struct base_unit_info<information::shannon_base_unit> {
    static BOOST_CONSTEXPR const char* name()   { return("shannon"); }
    static BOOST_CONSTEXPR const char* symbol() { return("Sh"); }
};

} // namespace units
} // namespace boost

#endif // BOOST_UNITS_BASE_UNITS_INFORMATION_SHANNON_HPP_INCLUDED


text:
#include "pcl/pcl_base.h"
#include "pcl/point_types.h"
#include "jsk_pcl_ros/color_converter.h"

#include "pcl/kdtree/tree_types.h"
#include "pcl/kdtree/kdtree.h"
#include "pcl/kdtree/kdtree_flann.h"
#include "pcl/kdtree/impl/kdtree_flann.hpp"

#include <boost/smart_ptr/make_shared.hpp>

int main (int argc, char** argv) {
    pcl::PointCloud<pcl::PointXYZRGB> p_rgb, p_rgb2;
    pcl::PointCloud<pcl::PointXYZHSV> p_hsv;
    // create RGB pointcloud
    for(int r=0;r < 10; r++) {
        for(int g=0;g < 10; g++) {
            for(int b=0;b < 10; b++) {
                pcl::PointXYZRGB pt;
                pcl::RGBValue v;
                pt.x = r*25;
                pt.y = g*25;
                pt.z = b*25;
                v.Blue = r*25;
                v.Green = g*25;
                v.Red = b*25;
                pt.rgb = v.float_value;
                p_rgb.points.push_back(pt);
            }}}
    // create cv::Mat 1x1000!

    p_rgb.is_dense = true;
    p_rgb.width = 1000;
    p_rgb.height = 1;

    pcl::RGB2HSVConverter<pcl::PointXYZRGB, pcl::PointXYZHSV> rgb2hsv;
    pcl::HSV2RGBConverter<pcl::PointXYZHSV, pcl::PointXYZRGB> hsv2rgb;

    pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree
        = boost::make_shared<pcl::KdTreeFLANN<pcl::PointXYZRGB> > ();

    pcl::KdTreeFLANN<pcl::PointXYZHSV>::Ptr tree2
        = boost::make_shared<pcl::KdTreeFLANN<pcl::PointXYZHSV> > ();

    rgb2hsv.setSearchMethod (tree); // dummy
    rgb2hsv.setKSearch (50);        // dummy

    hsv2rgb.setSearchMethod (tree2); // dummy
    hsv2rgb.setKSearch (50);         // dummy

    rgb2hsv.setInputCloud(boost::make_shared<pcl::PointCloud<pcl::PointXYZRGB> > (p_rgb));
    rgb2hsv.compute(p_hsv);

    hsv2rgb.setInputCloud(boost::make_shared<pcl::PointCloud<pcl::PointXYZHSV> > (p_hsv));
    hsv2rgb.compute(p_rgb2);

    for(int i = 0 ; i < 1000; i++ )
    {
        pcl::PointXYZRGB rgb_p= p_rgb.points[i];
        pcl::PointXYZRGB rgb2_p= p_rgb2.points[i];
        pcl::PointXYZHSV hsv_p= p_hsv.points[i];

        pcl::RGBValue v, v2;
        v.float_value = rgb_p.rgb;
        v2.float_value = rgb2_p.rgb;

        std::cout << "[" << (int)v.Red << ", " << (int)v.Green << ", " << (int)v.Blue << "] -> "
                  << "[" << hsv_p.hue << ", " << hsv_p.saturation << ", "
                  << hsv_p.value << "] -> "
                  << "[" << (int)v2.Red << ", "
                  << (int)v2.Green << ", "
                  << (int)v2.Blue << "]"
                  << std::endl;
    }
}


text:
#include "Gaussian.h"
#include <iostream>
#include <stdexcept>
#include <cmath>
#include "../Utils.h"
//#include <boost/math/special_functions/erf.hpp>

namespace DNest4
{

Gaussian::Gaussian(double center, double width)
:center(center)
,width(width)
{
    if(width <= 0.0)
        throw std::domain_error("Gaussian distribution must have positive width.");
}

double Gaussian::cdf(double x) const
{
    return normal_cdf((x-center)/width);
}

double Gaussian::cdf_inverse(double x) const
{
    if(x < 0.0 || x > 1.0)
        throw std::domain_error("Input to cdf_inverse must be in [0, 1].");
    return center + width*normal_inverse_cdf(x);
    //return center + width * sqrt(2) * boost::math::erf_inv(2*x - 1);
}

double Gaussian::log_pdf(double x) const
{
	double r = (x - center)/width;
    return -0.5*r*r - _norm_pdf_logC;
}

TruncatedGaussian::TruncatedGaussian(double center, double width, double lower, double upper)
:center(center)
,width(width)
,lower(lower)
,upper(upper)
{
    if(width <= 0.0)
        throw std::domain_error("TruncatedGaussian distribution must have positive width.");
    if(lower >= upper)
        throw std::domain_error("TruncatedGaussian: lower bound should be less than upper bound.");
    // the original, untruncated, Gaussian distribution
    unG = Gaussian(center, width);
    c = unG.cdf(upper) - unG.cdf(lower);
}

double TruncatedGaussian::cdf(double x) const
{
    double up = std::max(std::min(x,upper), lower);
    return (unG.cdf(up) - unG.cdf(lower)) / c;
}

double TruncatedGaussian::cdf_inverse(double x) const
{
    if(x < 0.0 || x > 1.0)
        throw std::domain_error("Input to cdf_inverse must be in [0, 1].");
    double xx = unG.cdf(lower) + x * c;
    return unG.cdf_inverse(xx);
}

double TruncatedGaussian::log_pdf(double x) const
{
    if(x<lower or x>upper) return -std::numeric_limits<double>::infinity();
    return unG.log_pdf(x) - log(c);
}

} // namespace DNest4


text:
/// \file test.cpp
/// Main entry for cxxmv test suite

#define BOOST_TEST_MODULE "cxxmvtest"
#include <boost/test/included/unit_test.hpp>

max_stars_repo_name: psina-im/libcxxmv

max_issues_repo_name: psina-im/libcxxmv

max_forks_repo_name: psina-im/libcxxmv


text:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/lexical_cast.hpp>
using namespace std;
int main() {
    string s; cin >> s;
    if (s.length() == 3) {
        string a = s.substr(0, 1), b = s.substr(2, 1);
        int x = boost::lexical_cast<int>(b);
        if (0 <= x && x <= 2) cout << a << '-' << endl;
        else if (3 <= x && x <= 6) cout << a << endl;
        else cout << a << '+' << endl;
    }
    else {
        string a = s.substr(0, 2), b = s.substr(3, 1);
        int x = boost::lexical_cast<int>(b);
        if (0 <= x && x <= 2) cout << a << '-' << endl;
        else if (3 <= x && x <= 6) cout << a << endl;
        else cout << a << '+' << endl;
    }
}


text:
#include "include/hm/system/File.h"

#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

namespace hm {
  std::string File::base_path;
  fs::path path;

  File::File(std::string p) : relative_path(p)
  {
    path = File::base_path + relative_path;
    setFileName();
    setExtension();
  }

  File::~File(){}

  std::string File::getPath(){ return path.string();}
  std::string File::getExtension(){ return ext;}
  std::string File::getFileName(){ return filename; }

  std::ios_base::openmode File::getMode(int m)
  {
    switch (m) {
    case 1: return std::fstream::app;   break;
    case 2: return std::fstream::ate;   break;
    case 3: return std::fstream::in;    break;
    case 4: return std::fstream::out;   break;
    case 5: return std::fstream::trunc; break;
    default: return std::fstream::in;   break;
    }
  }

  std::string File::getFileNameNoExtension()
  {
    return boost::filesystem::change_extension(filename, "").string();
  }

  void File::setFileName()
  {
    filename = path.has_filename() ? path.filename().string() : path.string();
  }

  void File::setExtension()
  {
    ext = path.has_extension() ? path.extension().string() : path.string();
  }
}

max_stars_repo_name: hugomarquez/cpp-toolkit

max_issues_repo_name: hugomarquez/cpp-toolkit

max_forks_repo_name: hugomarquez/cpp-toolkit


text:
#include <boost/align/aligned_alloc.hpp>

int main()
{
	void* p = boost::alignment::aligned_alloc(16, 100);
	if (p)
	{
		boost::alignment::aligned_free(p);
	}
	return 0;
}

max_stars_repo_name: zzragida/CppExamples

max_issues_repo_name: zzragida/CppExamples

max_forks_repo_name: zzragida/CppExamples


text:
#ifndef N2O_MODULE_HPP_INCLUDED_
#define N2O_MODULE_HPP_INCLUDED_

#include <boost/bind.hpp>
#include <node.h>

#include <n2o/object.hpp>

#define N2O_MODULE(args) N2O_NAMED_MODULE( N2O_MODULE_NAME, args )

#define N2O_NAMED_MODULE(name, args)                                          \
    void n2o_init_ ## name(args);                                             \
    void n2o_node_init_ ## name(v8::Handle<v8::Object> exports) {             \
        v8::HandleScope scope(v8::Isolate::GetCurrent());                     \
        n2o::handle_exception(                                                \
                boost::bind(n2o_init_ ## name, n2o::object(exports)));        \
    }                                                                         \
    NODE_MODULE(name, n2o_node_init_ ## name);                                \
    void n2o_init_ ## name( args )

#endif // N2O_MODULE_HPP_INCLUDED_


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

#ifndef GDBSYSTEM_HPP
#define GDBSYSTEM_HPP

#include <boost/foreach.hpp>
#include <string>
#include <map>
#include <vector>

#include "../defs.hpp"
#include "../BaseSystem.hpp"
#include "cpus/GdbCpu.hpp"
#include "Transport.hpp"

struct DebuggerOptions;

/**
 * The GDB System class is a connection class for the debug client that
 * allows connections to a gdbserver through various transport modes.
 */
class GdbSystem : public BaseSystem, IEventCallback {
#ifdef UNITTESTING
public:
#else
 private:
#endif
  // Description of the target CPU the target program runs on.
  GdbCpu* cpu;

  // The active threads in the current debugging session.
  std::vector<Thread> knownThreads;

  unsigned int threadFromBreakpointMessage(const std::string& message);

  NaviError processBreakpointMessage(const std::string& msg);

  // Parses instruction pointer from a stop-reply packet
  NaviError getInstructionPointerFromStopMessage(const std::string& msg,
                                                 unsigned int index,
                                                 CPUADDRESS& address) const;

  void synchronizeThreadState();

#ifdef UNITTESTING
public:
#else
 protected:
#endif
  // Attaches to a running process
  NaviError attachToProcess();

  // We do not support starting a process via Gdb
  NaviError startProcess(const NATIVE_STRING path,
                         const std::vector<const NATIVE_STRING>& commands);

  // Detaches from the target process
  NaviError detach();

  // Terminates the target process
  NaviError terminateProcess();

  // Stores the original data that is replaced by a breakpoint
  NaviError storeOriginalData(const BREAKPOINT& bp);

  // Sets a breakpoint in the target process
  NaviError setBreakpoint(const BREAKPOINT& breakpoint,
                          bool moreToCome = false);

  // Removes a breakpoint from the target process
  NaviError removeBreakpoint(const BREAKPOINT& bp, bool moreToCome = false);

  // Executes the next instruction in thread of the target process
  NaviError doSingleStep(unsigned int& tid, CPUADDRESS& address);

  NaviError suspendThread(unsigned int tid);

  NaviError resumeProcess();

  // Resumes a thread in the target process
  NaviError resumeThread(unsigned int tid);

  // Halts the target process
  NaviError halt();

  // Returns the current instruction pointer of a thread of the target process
  NaviError getInstructionPointer(unsigned int tid, CPUADDRESS& addr);

  // Sets the instruction pointer of a thread in the target process
  NaviError setInstructionPointer(unsigned int tid, CPUADDRESS address);

  // Reads the register values of a thread
  NaviError readRegisters(RegisterContainer& registers);

  // Sets the value of a register in the target process
  NaviError setRegister(unsigned int tid, unsigned int index,
                        CPUADDRESS address);

  // Reads a part of the target process memory
  NaviError readMemoryData(char* buffer, CPUADDRESS from, CPUADDRESS to);

  NaviError writeMemory(CPUADDRESS address, const std::vector<char>& data);

  NaviError readProcessList(ProcessListContainer& processList);

  NaviError getFileSystems(std::vector<boost::filesystem::path>& roots) const;

  NaviError getSystemRoot(boost::filesystem::path& root) const;

  // Finds the memory region an offset belongs to
  NaviError getValidMemory(CPUADDRESS start, CPUADDRESS& from, CPUADDRESS& to);

  // Find all allocated memory sections of the target process
  NaviError getMemmap(std::vector<CPUADDRESS>& addresses);

  // Handles a breakpoint hit
  NaviError handleBreakpointHit(CPUADDRESS address);

  DebugExceptionContainer getPlatformExceptions() const;

 public:

  /**
   * Creates a new GDB system object
   *
   * @param pid The process ID of the target process.
   */
  GdbSystem(unsigned int pid)
      : BaseSystem(pid) {
  }

  /**
   * Creates a new GDB System object
   *
   * @param path The path to the target process executable
   */
  GdbSystem(const char* path, const std::vector<const char*>& commands)
      : BaseSystem(path, commands) {
  }

  GdbCpu* getCpu() const {
    return cpu;
  }

  // Reads new debug events from the target process
  NaviError readDebugEvents();

  // Returns the register names that are available on the target architecture
  std::vector<RegisterDescription> getRegisterNames() const;

  // Returns the address size of the target architecture
  unsigned int getAddressSize() const;

  // Returns the debugger options that are supported by the debug client
  DebuggerOptions getDebuggerOptions() const;

  // Initializes the CPU-specific objects
  NaviError initTarget(const std::string& connection, const std::string& cpu);

  // Processes a stop-reply packet
  NaviError processMessage(const std::string& message);

};

#endif

max_issues_repo_name: Jason-Cooke/binnavi

max_forks_repo_name: Jason-Cooke/binnavi


text:
/**
 * \file
 * \copyright
 * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)
 *            Distributed under a Modified BSD License.
 *              See accompanying file LICENSE.txt or
 *              http://www.opengeosys.org/project/license
 */

#include <gtest/gtest.h>

#include <Eigen/Eigen>
#include <boost/math/constants/constants.hpp>
#include <cmath>
#include <memory>
#include <numeric>
#include <random>

#include "MeshLib/Elements/Element.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshGenerators/MeshGenerator.h"
#include "MeshLib/MeshQuality/ElementQualityInterface.h"
#include "MeshLib/Node.h"

class TetElementQuality : public ::testing::Test
{
public:
    TetElementQuality()
    {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> distrib(1, 10);

        lengths = {1, 1, 1};
        n_subdivisions = {distrib(gen), distrib(gen), distrib(gen)};
    }

    std::vector<double> getElementQualityVectorFromRegularTetMesh(
        MeshLib::MeshQualityType const type)
    {
        std::vector<std::unique_ptr<BaseLib::ISubdivision>> vec_div;
        for (int i = 0; i < 3; ++i)
        {
            vec_div.emplace_back(
                new BaseLib::UniformSubdivision(lengths[i], n_subdivisions[i]));
        }

        std::unique_ptr<MeshLib::Mesh> mesh(
            MeshLib::MeshGenerator::generateRegularTetMesh(
                *vec_div[0], *vec_div[1], *vec_div[2]));
        MeshLib::ElementQualityInterface element_quality(*mesh, type);
        return element_quality.getQualityVector();
    }

    std::array<int, 3> lengths;
    std::array<int, 3> n_subdivisions;
};

TEST_F(TetElementQuality, ElementSize)
{
    auto const type = MeshLib::MeshQualityType::ELEMENTSIZE;
    auto const element_quality_vector =
        getElementQualityVectorFromRegularTetMesh(type);
    auto const expected_value =
        1.0 / (6 * std::accumulate(n_subdivisions.begin(), n_subdivisions.end(),
                                   1, std::multiplies<int>()));
    for (auto const element_quality : element_quality_vector)
    {
        ASSERT_NEAR(expected_value, element_quality,
                    std::numeric_limits<double>::epsilon());
    }
}

TEST_F(TetElementQuality, SizeDifference)
{
    auto const type = MeshLib::MeshQualityType::SIZEDIFFERENCE;
    auto const element_quality_vector =
        getElementQualityVectorFromRegularTetMesh(type);
    // all elements have the same size, the quality value has to be 1.0
    auto constexpr expected_value = 1.0;
    for (auto const element_quality : element_quality_vector)
    {
        ASSERT_NEAR(expected_value, element_quality,
                    10 * std::numeric_limits<double>::epsilon());
    }
}

TEST_F(TetElementQuality, EdgeRatio)
{
    auto const type = MeshLib::MeshQualityType::EDGERATIO;
    auto const element_quality_vector =
        getElementQualityVectorFromRegularTetMesh(type);
    std::array const d = {1.0 / n_subdivisions[0], 1.0 / n_subdivisions[1],
                          1.0 / n_subdivisions[2]};
    std::array const d2 = {std::pow(d[0], 2), std::pow(d[1], 2),
                           std::pow(d[2], 2)};
    auto const& min_max = std::minmax_element(d.begin(), d.end());
    auto const diagonal_length = std::sqrt(d2[0] + d2[1] + d2[2]);
    auto const expected_value_tet0 = *min_max.first / diagonal_length;
    auto const min_x_z = std::min(d[0], d[2]);
    auto const expected_value_tet1 = min_x_z / diagonal_length;
    auto const expected_value_tet2 =
        *min_max.first /
        std::max({std::sqrt(d2[0] + d2[1]), std::sqrt(d2[1] + d2[2]),
                  std::sqrt(d2[0] + d2[2])});
    auto const expected_value_tet3 = expected_value_tet2;
    auto const expected_value_tet4 = expected_value_tet1;
    auto const expected_value_tet5 = expected_value_tet0;

    for (std::size_t i = 0; i < element_quality_vector.size(); i = i + 6)
    {
        ASSERT_NEAR(expected_value_tet0, element_quality_vector[i],
                    10 * std::numeric_limits<double>::epsilon());
        ASSERT_NEAR(expected_value_tet1, element_quality_vector[i + 1],
                    10 * std::numeric_limits<double>::epsilon());
        ASSERT_NEAR(expected_value_tet2, element_quality_vector[i + 2],
                    10 * std::numeric_limits<double>::epsilon());
        ASSERT_NEAR(expected_value_tet3, element_quality_vector[i + 3],
                    10 * std::numeric_limits<double>::epsilon());
        ASSERT_NEAR(expected_value_tet4, element_quality_vector[i + 4],
                    10 * std::numeric_limits<double>::epsilon());
        ASSERT_NEAR(expected_value_tet5, element_quality_vector[i + 5],
                    10 * std::numeric_limits<double>::epsilon());
    }
}

// compute angle formed by (n0, n1, n2)
double getAngleFromTriangle(Eigen::Vector3d n0, Eigen::Vector3d n1,
                            Eigen::Vector3d n2)
{
    auto const u = n1 - n0;
    auto const v = n1 - n2;
    return std::acos(((u.transpose() * v) / (u.norm() * v.norm()))(0, 0));
}

// get min and max angle from triangle
std::pair<double, double> getMinMaxAngleFromTriangle(Eigen::Vector3d n0,
                                                     Eigen::Vector3d n1,
                                                     Eigen::Vector3d n2)
{
    std::array const angles = {getAngleFromTriangle(n0, n1, n2),
                               getAngleFromTriangle(n1, n2, n0),
                               getAngleFromTriangle(n2, n0, n1)};
    auto const pair = std::minmax_element(angles.begin(), angles.end());
    return {*pair.first, *pair.second};
}

double computeCriterionForTet(Eigen::Vector3d n0, Eigen::Vector3d n1,
                              Eigen::Vector3d n2, Eigen::Vector3d n3)
{
    using namespace boost::math::double_constants;
    auto const alpha0 = getMinMaxAngleFromTriangle(n0, n2, n1);
    auto const alpha1 = getMinMaxAngleFromTriangle(n0, n1, n3);
    auto const alpha2 = getMinMaxAngleFromTriangle(n1, n2, n3);
    auto const alpha3 = getMinMaxAngleFromTriangle(n2, n0, n3);
    auto const min =
        std::min({alpha0.first, alpha1.first, alpha2.first, alpha3.first});
    auto const max =
        std::max({alpha0.second, alpha1.second, alpha2.second, alpha3.second});
    return std::max((max - third_pi) / two_thirds_pi,
                    (third_pi - min) / third_pi);
}

TEST_F(TetElementQuality, EquiAngleSkew)
{
    auto const type = MeshLib::MeshQualityType::EQUIANGLESKEW;
    auto const element_quality_vector =
        getElementQualityVectorFromRegularTetMesh(type);
    std::array d = {1.0 / n_subdivisions[0], 1.0 / n_subdivisions[1],
                    1.0 / n_subdivisions[2]};
    // 6 tets are within a hexahedron, the hex nodes are
    Eigen::Vector3d const n0(0, 0, 0);
    Eigen::Vector3d const n1(d[0], 0, 0);
    Eigen::Vector3d const n2(0, d[1], 0);
    Eigen::Vector3d const n3(d[0], d[1], 0);
    Eigen::Vector3d const n4(0, 0, d[2]);
    Eigen::Vector3d const n5(d[0], 0, d[2]);
    Eigen::Vector3d const n6(0, d[1], d[2]);
    Eigen::Vector3d const n7(d[0], d[1], d[2]);
    // tet 0 consist of nodes n0, n3, n2, n4
    auto const expected_value_tet0 = computeCriterionForTet(n0, n3, n2, n4);
    // tet 1 consist of nodes n3, n2, n4, n7
    auto const expected_value_tet1 = computeCriterionForTet(n3, n2, n4, n7);
    // tet 2 consist of nodes n2, n4, n7, n6
    auto const expected_value_tet2 = computeCriterionForTet(n2, n4, n7, n6);
    // tet 3 consist of nodes n0, n1, n3, n5
    auto const expected_value_tet3 = computeCriterionForTet(n0, n1, n3, n5);
    // tet 4 consist of nodes n0, n3, n4, n5
    auto const expected_value_tet4 = computeCriterionForTet(n0, n3, n4, n5);
    // tet 5 consist of nodes n3, n4, n5, n7
    auto const expected_value_tet5 = computeCriterionForTet(n3, n4, n5, n7);

    auto constexpr eps = 11 * std::numeric_limits<double>::epsilon();
    for (std::size_t i = 0; i < element_quality_vector.size(); i = i + 6)
    {
        ASSERT_NEAR(expected_value_tet0, element_quality_vector[i], eps);
        ASSERT_NEAR(expected_value_tet1, element_quality_vector[i + 1], eps);
        ASSERT_NEAR(expected_value_tet2, element_quality_vector[i + 2], eps);
        ASSERT_NEAR(expected_value_tet3, element_quality_vector[i + 3], eps);
        ASSERT_NEAR(expected_value_tet4, element_quality_vector[i + 4], eps);
        ASSERT_NEAR(expected_value_tet5, element_quality_vector[i + 5], eps);
    }
}

max_stars_repo_name: ufz/ogs

max_issues_repo_name: ufz/ogs

max_forks_repo_name: ufz/ogs


text:
#ifndef STAN_MATH_PRIM_ARR_FUN_COMMON_TYPE_HPP
#define STAN_MATH_PRIM_ARR_FUN_COMMON_TYPE_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/fun/common_type.hpp>
#include <boost/math/tools/promotion.hpp>
#include <vector>

namespace stan {
namespace math {
/**
 * Struct which calculates type promotion over two types.
 *
 * <p>This specialization is for vector types.
 *
 * @tparam T1 type of elements contined in std::vector<T1>
 * @tparam T2 type of elements contined in std::vector<T2>
 */
template <typename T1, typename T2>
struct common_type<std::vector<T1>, std::vector<T2> > {
  typedef std::vector<typename common_type<T1, T2>::type> type;
};

}  // namespace math
}  // namespace stan

#endif

max_stars_repo_name: alashworth/stan-monorepo

max_issues_repo_name: alashworth/stan-monorepo

max_forks_repo_name: alashworth/stan-monorepo


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

#pragma once

#include <boost/random.hpp>
#include <map>
#include <set>
#include <string>

#include "config/params/ParameterManager.hpp"
#include "entities/models/Constants.hpp"
#include "entities/roles/driver/Driver.hpp"
#include "entities/roles/driver/DriverPathMover.hpp"
#include "entities/vehicle/VehicleBase.hpp"

using namespace std;

namespace sim_mob
{
class DriverUpdateParams;
class NearestVehicle;
class Driver;

/**Abstract class which describes car following*/
class CarFollowingModel
{
public:
    /**The model name*/
    string modelName;

    /**The acceleration grade factor*/
    double accGradeFactor;

    /**The next perception size*/
    double nextPerceptionSize;

    /**Minimum speed*/
    double minSpeed;

    /**The update step sizes*/
    std::vector<double> updateStepSize;

    /**The perception sizes*/
    std::vector<double> perceptionSize;

    /**Split delimiter in the driver parameters XML file*/
    string splitDelimiter;

protected:
    /**The pointer to the driver path mover object*/
    DriverPathMover *fwdDriverMovement;

    /**
     * Calculates the step size of update state variables
     *
     * @param params
     *
     * @return
     */
    double calcNextStepSize(DriverUpdateParams &params);

public:
    CarFollowingModel(DriverPathMover *pathMover) : fwdDriverMovement(pathMover)
    {
    }
    virtual ~CarFollowingModel()
    {
        updateStepSize.clear();
        perceptionSize.clear();
    }

    /**
     * Calculates the acceleration rate based on interaction with other vehicles
     *
     * @param params the update parameters
     *
     * @return the acceleration
     */
    virtual double makeAcceleratingDecision(DriverUpdateParams &params) = 0;
};

/**
 * MITSIM version of car following model
 */
class MITSIM_CF_Model : public CarFollowingModel
{
private:
    /**Represents the container to store the normal distribution*/
    struct UpdateStepSizeParam
    {
        double mean;
        double stdev;
        double lower;
        double upper;
        double perception; //percentage of total reaction time
    };

    /**Represents the container to store the car following model parameters*/
    struct CarFollowingParams
    {
        double alpha;
        double beta;
        double gama;
        double lambda;
        double rho;
        double stddev;
    };

    /**The upper bound on the maximum acceleration*/
    int maxAccUpperBound;

    /**The upper bound on the normal deceleration*/
    int normalDecelerationUpperBound;

    /**The upper bound on the maximum deceleration*/
    int maxDecelerationUpperBound;

    /**This parameter is used to compute the desired speed based on the posted speed limit*/
    double speedFactor;

    /**The visibility distance of the traffic signal*/
    double signalVisibilityDist;

    /**The maximum value of headway a driver can have to pass a yellow light.*/
    double maxYellowLightHeadway;

    /**The minimum speed for approaching a yellow light*/
    double minYellowLightSpeed;

    /**The road slope*/
    double allGrades;

    /**
     * This is the minimum space headway between the lead and following vehicles for which the following
     * vehicle must apply some acceleration (or deceleration)
     */
    double minResponseDistance;

    /**Upper bound for the headway buffer*/
    double hBufferUpper;

    /**Lower bound for the headway buffer*/
    double hBufferLower;

    /**Defines how close the lead vehicle needs to be in order for the following vehicle to brake (in meter)*/
    double visibilityDistance;

    /**Random number generator for calculating update step sizes*/
    boost::mt19937 updateSizeRNG;

    /**The car following parameters*/
    CarFollowingParams CF_parameters[2];

    /**Merging parameters*/
    vector<double> mergingParams;

    /**Update step size while deceleration*/
    UpdateStepSizeParam decUpdateStepSize;

    /**Update step size while acceleration*/
    UpdateStepSizeParam accUpdateStepSize;

    /**Update step size when the speed is constant*/
    UpdateStepSizeParam uniformSpeedUpdateStepSize;

    /**Update step size when the vehicle has stopped*/
    UpdateStepSizeParam stoppedUpdateStepSize;

    /**Parameters to calculate the target gap acceleration*/
    vector<double> targetGapAccParm;

    /**The maximum acceleration scale*/
    vector<double> maxAccelerationScale;

    /**The normal deceleration scale*/
    vector<double> normalDecelerationScale;

    /**The maximum deceleration scale*/
    vector<double> maxDecelerationScale;

    /**The speed limit add-on distribution*/
    vector<double> speedLimitAddon;

    /**The car following acceleration add-on distribution*/
    vector<double> accelerationAddon;

    /**The car following deceleration add-on distribution*/
    vector<double> decelerationAddon;

    /**The distribution for the headway upperbound*/
    vector<double> hBufferUpperScale;

    /**The maximum acceleration indices. Key: Vehicle type, Value: Map with Key: Speed, Value: Max. Acceleration*/
    map< VehicleBase::VehicleType, map<int, double> > maxAccelerationIndex;

    /**The normal deceleration indices. Key: Vehicle type, Value: Map with Key: Speed, Value: Normal deceleration*/
    map< VehicleBase::VehicleType, map<int, double> > normalDecelerationIndex;

    /**The maximum deceleration indices. Key: Vehicle type, Value: Map with Key: Speed, Value: Normal deceleration*/
    map< VehicleBase::VehicleType, map<int, double> > maxDecelerationIndex;

    /**
     * Reads the car following model parameters from the driver parameters XML file
     *
     * @param params the drivers parameters
     */
    void readDriverParameters(DriverUpdateParams &params);

    /**
     * Creates the car following parameters from the given parameter values in string format
     *
     * @param strParams the parameter string
     * @param cfParams the car following parameters
     */
    void createCF_Params(string &strParams, CarFollowingParams &cfParams);

    /**
     * Creates the speed indices based on the speed scalars
     *
     * @param vehicleType vehicle type
     * @param speedScalerStr speed scalar
     * @param cstr the index value
     * @param idx the container holding the indices
     * @param upperBound the upper bound of the index
     */
    void createSpeedIndices(VehicleBase::VehicleType vehicleType, string &speedScalerStr, string &cstr, map< VehicleBase::VehicleType, map<int, double> > &idx,
                            int &upperBound);

    /**
     * Creates the scale indices based on the string data
     *
     * @param data the data in the format "0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5"
     * @param container the container that stores the created indices
     */
    void createScaleIndices(string &data, vector<double> &container);

    /**
     * Creates the update step size parameters from the given parameter values in string format
     * @param strParams the parameter string
     * @param stepSizeParams the container for the update step size parameters
     */
    void createUpdateSizeParams(string &strParams, UpdateStepSizeParam &stepSizeParams);

    /**
     * Builds and gets a sample from the normal distribution created from the given parameters
     *
     * @param stepSizeParams the step size parameters from which the distribution is to be created and sampled
     *
     * @return sampled value from the distribution
     */
    double sampleFromNormalDistribution(UpdateStepSizeParam &stepSizeParams);

    /**
     * Returns the maximum acceleration for the given vehicle type
     *
     * @param params the driver parameters
     * @param vhType the vehicle type
     *
     * @return max acceleration of the given vehicle type
     */
    double getMaxAcceleration(DriverUpdateParams &params, VehicleBase::VehicleType vhType = VehicleBase::CAR);

    /**
     * Returns the normal deceleration for the given vehicle type
     *
     * @param params the driver parameters
     * @param vhType the vehicle type
     *
     * @return normal deceleration of the given vehicle type
     */
    double getNormalDeceleration(DriverUpdateParams &params, VehicleBase::VehicleType vhType = VehicleBase::CAR);

    /**
     * Returns the maximum deceleration for the given vehicle type
     * @param params the driver parameters
     * @param vhType the vehicle type
     *
     * @return the maximum deceleration for the given vehicle type
     */
    double getMaxDeceleration(DriverUpdateParams &params, VehicleBase::VehicleType vhType = VehicleBase::CAR);

    /**
     * Calculates the maximum acceleration scalar
     *
     * @return maximum acceleration scalar
     */
    double getMaxAccScalar();

    /**
     * Calculates the normal deceleration scalar
     *
     * @return normal deceleration scalar
     */
    double getNormalDecScalar();

    /**
     * Calculates the maximum deceleration scalar
     *
     * @return maximum deceleration scalar
     */
    double getMaxDecScalar();

    /**
     * Calculates the acceleration based on the car-following constraints.
     *
     * CAUTION: The two vehicles concerned in this function may not necessarily be in the same lane or even the
     * same segment.
     * A modified GM model is used in this implementation.
     *
     * @param params the update parameters
     * @param nearestVehicle the nearest vehicle
     *
     * @return acceleration
     */
    double calcCarFollowingAcc(DriverUpdateParams &params, NearestVehicle &nearestVehicle);

    /**
     * Calculates the car following accelerations for 2 scenarios:
     * 1. Vehicle in front is on the same link
     * 2. Vehicle in front is on the next link (beyond the intersection)
     * and returns the lower of the two values
     *
     * @param params the update parameters
     *
     * @return acceleration
     */
    double calcCarFollowingAcc(DriverUpdateParams &params);

    /**
     * Calculate the acceleration based on the merging constraints
     *
     * @param params the update parameters
     *
     * @return acceleration
     */
    double calcMergingAcc(DriverUpdateParams &params);

    /**
     * Checks if this driver considers the gap from an incoming vehicle to be an acceptable gap for merging or crossing.
     * It depends on the speed of the coming vehicle and this driver's behaviour parameters
     *
     * @param params update parameters
     * @param nearestVehicle the incoming vehicle
     *
     * @return returns true if the gap is acceptable, or false otherwise.
     */
    bool isGapAcceptable(DriverUpdateParams &params, NearestVehicle &nearestVehicle);

    /**
     * Calculates the acceleration when the car needs to stop for a red light or needs to start moving for a
     * green light
     *
     * @param params the driver parameters
     *
     * @return acceleration
     */
    double calcTrafficSignalAcc(DriverUpdateParams &params);

    /**
     * Calculates the acceleration when performing a courtesy yielding
     * @param params the driver parameters
     * @return acceleration
     */
    double calcYieldingAcc(DriverUpdateParams &params);

    /**
     * Calculate the maximum acceleration for creating a gap to the nearest vehicle
     *
     * @param params the driver parameters
     * @param nearestVeh the vehicle to which we are trying to open a gap
     * @param gap the gap distance required
     *
     * @return acceleration
     */
    double calcAccToCreateGap(DriverUpdateParams &params, NearestVehicle &nearestVeh, float gap);

    /**
     * Calculates the acceleration while exiting a specific lane. For e.g: If a vehicle is not in the correct lane
     * close to the end of a link, it may decelerate to a stop and wait for lane changing.
     *
     * @param params
     *
     * @return acceleration
     */
    double calcWaitForLaneExitAcc(DriverUpdateParams &params);

    /**
     * Calculates the acceleration rate when current lane is incorrect and the distance is close to the
     * an incurrent lane of the segment
     *
     * @param params driver parameters
     *
     * @return acceleration
     */
    double calcWaitForAllowedLaneAcc(DriverUpdateParams& p);

    /**
     * Calculates the acceleration required to reach the forward gap
     *
     * @param params driver parameters
     * @return acceleration
     */
    double calcForwardGapAcc(DriverUpdateParams &params);

    /**
     * Calculates the desired speed
     * @param params driver parameters
     * @return desired speed (m/s)
     */
    double calcDesiredSpeed(DriverUpdateParams &params);

    /**
     * Calculates the acceleration to reach the backward gap
     *
     * @param params driver parameters
     *
     * @return acceleration
     */
    double calcBackwardGapAcc(DriverUpdateParams &params);

    /**
     * Calculates the acceleration to reach the adjacent gap
     * @param params driver parameters
     * @return acceleration
     */
    double calcAdjacentGapRate(DriverUpdateParams &params);

    /**
     * Calculates the acceleration required to stop at a stopping point
     *
     * @param params
     *
     * @return acceleration
     */
    double calcAccForStoppingPoint(DriverUpdateParams &params);

    /**
     * Calculates acceleration required to reach the desired speed
     *
     * @param params driver parameters
     *
     * @return acceleration
     */
    double calcDesiredSpeedAcc(DriverUpdateParams &params);

    /**
     * Calculates the acceleration / deceleration required to speed up / slow down to the target speed
     * with in the given distance
     *
     * @param params driver parameters
     * @param distance distance within which the target speed is to be achieved
     * @param velocity the target speed
     *
     * @return acceleration
     */
    double calcTargetSpeedAcc(DriverUpdateParams &params, double distance, double velocity);

    /**
     * Calculates the acceleration rate required to accelerate / decelerate from current speed to a full
     * stop within a given distance
     *
     * @param params driver parameters
     * @param distance distance within which we need to stop
     *
     * @return acceleration
     */
    double calcBrakeToStopAcc(DriverUpdateParams &params, double distance);

    /**
     * Calculates the acceleration required to slow down in an emergency
     * NOTE: when headway \< lower threshold, use this function
     *
     * @param params driver parameters
     *
     * @return acceleration
     */
    double calcEmergencyDeceleration(DriverUpdateParams &params);

    /**
     * Calculates the acceleration required to follow another car
     * NOTE: when lower threshold \< headway \< upper threshold, use this function
     *
     * @param params driver parameters
     *
     * @return acceleration
     */
    double calcAccOfCarFollowing(DriverUpdateParams &params);

    /**
     * Calculates the acceleration when the traffic is freely flowing
     *
     * @param params driver parameters
     * @param targetSpeed the target speed
     * @param maxLaneSpeed the speed limit of the current lane
     *
     * @return acceleration
     */
    double calcFreeFlowingAcc(DriverUpdateParams &params, double targetSpeed);

    /**
     * Calculates either the car following acceleration or the free flow acceleration depending on the gap between
     * the vehicles
     *
     * @param params driver parameters
     * @param targetSpeed the desired speed
     *
     * @return acceleration
     */
    double accOfMixOfCFandFF(DriverUpdateParams &params, double targetSpeed);

    /**
     * Calculates the distance required for the vehicle to arrive to a stop under normal circumstances
     *
     * @param params driver parameters
     */
    void calcDistanceForNormalStop(DriverUpdateParams &params);

    /**
     * Updates the variables that depend on the vehicle type and speed (i.e. the current state)
     *
     * @param params driver parameters driver parameters
     */
    void calcStateBasedVariables(DriverUpdateParams& p);

    /**
     * Calculates the step sizes for making car-following decisions
     */
    void calcUpdateStepSizes();

    /**
     * Calculates the upper bound of the headway buffer
     *
     * @return upper bound of the headway buffer
     */
    double getH_BufferUpperBound();

    /**
     * Calculates a headway buffer for a vehicle, which is a behavioural parameter that describes the aggressiveness
     * of a driver for accepting a headway gap in lane changing, merging, and car-following.
     *
     * @return headway (seconds)
     */
    double getHeadwayBuffer();

    /**
     * Calculates the add on for calculating the desired speed
     *
     * @return add on value (m/s)
     */
    double getSpeedLimitAddon();

    /**
     * Calculates the add on for the acceleration
     *
     * @return add on value (m/s^2)
     */
    double getAccelerationAddon();

    /**
     * Calculates the add on for the deceleration
     *
     * @return add on value (m/s^2)
     */
    double getDecelerationAddon();

    double upMergingArea()
    {
        return mergingParams[0];
    }

    double dnMergingArea()
    {
        return mergingParams[1];
    }

    int nVehiclesAllowedInMergingArea()
    {
        return (int) mergingParams[2];
    }

    float aggresiveRampMergeProb()
    {
        return mergingParams[3];
    }

public:
    MITSIM_CF_Model(DriverUpdateParams &params, DriverPathMover *pathMover);
    ~MITSIM_CF_Model();

    /**
     * Calculates the acceleration rate based on interaction with other vehicles. The function returns a the
     * most restrictive acceleration (deceleration if negative) rate among the rates given by several constraints.
     *
     * Car following algorithm is evaluated every stepSize seconds, or whenever some special event has set
     * reactionTimeCounter of this vehicle to 0. After each evaluation, we set the countdown clock reactionTimeCounter
     * back to nextStepSize().
     *
     * @param params driver parameters
     *
     * @return most restrictive acceleration
     */
    virtual double makeAcceleratingDecision(DriverUpdateParams &params);

    const double getHBufferUpper() const
    {
        return hBufferUpper;
    }
};
}


text:
// Copyright Nick Thompson, 2017
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MODULE Gauss Kronrod_quadrature_test

#include <complex>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>

#if !defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) && !defined(BOOST_NO_SFINAE_EXPR)

#include <boost/math/concepts/real_concept.hpp>
#include <boost/test/included/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/math/quadrature/gauss_kronrod.hpp>
#include <boost/math/special_functions/sinc.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/debug_adaptor.hpp>

#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/complex128.hpp>
#endif

#if !defined(TEST1) && !defined(TEST1A) && !defined(TEST2) && !defined(TEST3)
#  define TEST1
#  define TEST1A
#  define TEST2
#  define TEST3
#endif

#ifdef _MSC_VER
#pragma warning(disable:4127)  // Conditional expression is constant
#endif

using std::expm1;
using std::atan;
using std::tan;
using std::log;
using std::log1p;
using std::asinh;
using std::atanh;
using std::sqrt;
using std::isnormal;
using std::abs;
using std::sinh;
using std::tanh;
using std::cosh;
using std::pow;
using std::exp;
using std::sin;
using std::cos;
using std::string;
using boost::math::quadrature::gauss_kronrod;
using boost::math::constants::pi;
using boost::math::constants::half_pi;
using boost::math::constants::two_div_pi;
using boost::math::constants::two_pi;
using boost::math::constants::half;
using boost::math::constants::third;
using boost::math::constants::half;
using boost::math::constants::third;
using boost::math::constants::catalan;
using boost::math::constants::ln_two;
using boost::math::constants::root_two;
using boost::math::constants::root_two_pi;
using boost::math::constants::root_pi;
using boost::multiprecision::cpp_bin_float_quad;
using boost::multiprecision::cpp_dec_float_50;
using boost::multiprecision::debug_adaptor;
using boost::multiprecision::number;

//
// Error rates depend only on the number of points in the approximation, not the type being tested,
// define all our expected errors here:
//

enum
{
   test_ca_error_id,
   test_ca_error_id_2,
   test_three_quad_error_id,
   test_three_quad_error_id_2,
   test_integration_over_real_line_error_id,
   test_right_limit_infinite_error_id,
   test_left_limit_infinite_error_id
};

template <unsigned Points>
double expected_error(unsigned)
{
   return 0; // placeholder, all tests will fail
}

template <>
double expected_error<15>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 1e-7;
   case test_ca_error_id_2:
      return 2e-5;
   case test_three_quad_error_id:
      return 1e-8;
   case test_three_quad_error_id_2:
      return 3.5e-3;
   case test_integration_over_real_line_error_id:
      return 6e-3;
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 1e-5;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<17>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 1e-7;
   case test_ca_error_id_2:
      return 2e-5;
   case test_three_quad_error_id:
      return 1e-8;
   case test_three_quad_error_id_2:
      return 3.5e-3;
   case test_integration_over_real_line_error_id:
      return 6e-3;
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 1e-5;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<21>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 1e-12;
   case test_ca_error_id_2:
      return 3e-6;
   case test_three_quad_error_id:
      return 2e-13;
   case test_three_quad_error_id_2:
      return 2e-3;
   case test_integration_over_real_line_error_id:
      return 6e-3;  // doesn't get any better with more points!
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 5e-8;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<31>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 6e-20;
   case test_ca_error_id_2:
      return 3e-7;
   case test_three_quad_error_id:
      return 1e-19;
   case test_three_quad_error_id_2:
      return 6e-4;
   case test_integration_over_real_line_error_id:
      return 6e-3;  // doesn't get any better with more points!
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 5e-11;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<41>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 1e-26;
   case test_ca_error_id_2:
      return 1e-7;
   case test_three_quad_error_id:
      return 3e-27;
   case test_three_quad_error_id_2:
      return 3e-4;
   case test_integration_over_real_line_error_id:
      return 5e-5;  // doesn't get any better with more points!
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 1e-15;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<51>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 5e-33;
   case test_ca_error_id_2:
      return 1e-8;
   case test_three_quad_error_id:
      return 1e-32;
   case test_three_quad_error_id_2:
      return 3e-4;
   case test_integration_over_real_line_error_id:
      return 1e-14;
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 3e-19;
   }
   return 0;  // placeholder, all tests will fail
}

template <>
double expected_error<61>(unsigned id)
{
   switch (id)
   {
   case test_ca_error_id:
      return 5e-34;
   case test_ca_error_id_2:
      return 5e-9;
   case test_three_quad_error_id:
      return 4e-34;
   case test_three_quad_error_id_2:
      return 1e-4;
   case test_integration_over_real_line_error_id:
      return 1e-16;
   case test_right_limit_infinite_error_id:
   case test_left_limit_infinite_error_id:
      return 3e-23;
   }
   return 0;  // placeholder, all tests will fail
}

template<class Real, unsigned Points>
void test_linear()
{
    std::cout << "Testing linear functions are integrated properly by gauss_kronrod on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = boost::math::tools::epsilon<Real>() * 10;
    Real error;
    auto f = [](const Real& x)->Real
    {
       return 5*x + 7;
    };
    Real L1;
    Real Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 0, (Real) 1, 0, 0, &error, &L1);
    BOOST_CHECK_CLOSE_FRACTION(Q, 9.5, tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);

    Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 1, (Real) 0, 0, 0, &error, &L1);
    BOOST_CHECK_CLOSE_FRACTION(Q, -9.5, tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);

    Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 0, (Real) 0, 0, 0, &error, &L1);
    BOOST_CHECK_CLOSE(Q, Real(0), tol);
}

template<class Real, unsigned Points>
void test_quadratic()
{
    std::cout << "Testing quadratic functions are integrated properly by Gauss Kronrod on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = boost::math::tools::epsilon<Real>() * 10;
    Real error;

    auto f = [](const Real& x)->Real { return 5*x*x + 7*x + 12; };
    Real L1;
    Real Q = gauss_kronrod<Real, Points>::integrate(f, 0, 1, 0, 0, &error, &L1);
    BOOST_CHECK_CLOSE_FRACTION(Q, (Real) 17 + half<Real>()*third<Real>(), tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, (Real) 17 + half<Real>()*third<Real>(), tol);
}

// Examples taken from
//http://crd-legacy.lbl.gov/~dhbailey/dhbpapers/quadrature.pdf
template<class Real, unsigned Points>
void test_ca()
{
    std::cout << "Testing integration of C(a) on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = expected_error<Points>(test_ca_error_id);
    Real L1;
    Real error;

    auto f1 = [](const Real& x)->Real { return atan(x)/(x*(x*x + 1)) ; };
    Real Q = gauss_kronrod<Real, Points>::integrate(f1, 0, 1, 0, 0, &error, &L1);
    Real Q_expected = pi<Real>()*ln_two<Real>()/8 + catalan<Real>()*half<Real>();
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);

    auto f2 = [](Real x)->Real { Real t0 = x*x + 1; Real t1 = sqrt(t0); return atan(t1)/(t0*t1); };
    Q = gauss_kronrod<Real, Points>::integrate(f2, 0 , 1, 0, 0, &error, &L1);
    Q_expected = pi<Real>()/4 - pi<Real>()/root_two<Real>() + 3*atan(root_two<Real>())/root_two<Real>();
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);

    tol = expected_error<Points>(test_ca_error_id_2);
    auto f5 = [](Real t)->Real { return t*t*log(t)/((t*t - 1)*(t*t*t*t + 1)); };
    Q = gauss_kronrod<Real, Points>::integrate(f5, 0, 1, 0);
    Q_expected = pi<Real>()*pi<Real>()*(2 - root_two<Real>())/32;
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);
}

template<class Real, unsigned Points>
void test_three_quadrature_schemes_examples()
{
    std::cout << "Testing integral in 'A Comparison of Three High Precision Quadrature Schemes' on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = expected_error<Points>(test_three_quad_error_id);
    Real Q;
    Real Q_expected;

    // Example 1:
    auto f1 = [](const Real& t)->Real { return t*boost::math::log1p(t); };
    Q = gauss_kronrod<Real, Points>::integrate(f1, 0 , 1, 0);
    Q_expected = half<Real>()*half<Real>();
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);

    // Example 2:
    auto f2 = [](const Real& t)->Real { return t*t*atan(t); };
    Q = gauss_kronrod<Real, Points>::integrate(f2, 0 , 1, 0);
    Q_expected = (pi<Real>() -2 + 2*ln_two<Real>())/12;
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 2 * tol);

    // Example 3:
    auto f3 = [](const Real& t)->Real { return exp(t)*cos(t); };
    Q = gauss_kronrod<Real, Points>::integrate(f3, 0, half_pi<Real>(), 0);
    Q_expected = boost::math::expm1(half_pi<Real>())*half<Real>();
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);

    // Example 4:
    auto f4 = [](Real x)->Real { Real t0 = sqrt(x*x + 2); return atan(t0)/(t0*(x*x+1)); };
    Q = gauss_kronrod<Real, Points>::integrate(f4, 0 , 1, 0);
    Q_expected = 5*pi<Real>()*pi<Real>()/96;
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);

    tol = expected_error<Points>(test_three_quad_error_id_2);
    // Example 5:
    auto f5 = [](const Real& t)->Real { return sqrt(t)*log(t); };
    Q = gauss_kronrod<Real, Points>::integrate(f5, 0 , 1, 0);
    Q_expected = -4/ (Real) 9;
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);

    // Example 6:
    auto f6 = [](const Real& t)->Real { return sqrt(1 - t*t); };
    Q = gauss_kronrod<Real, Points>::integrate(f6, 0 , 1, 0);
    Q_expected = pi<Real>()/4;
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);
}

template<class Real, unsigned Points>
void test_integration_over_real_line()
{
    std::cout << "Testing integrals over entire real line in 'A Comparison of Three High Precision Quadrature Schemes' on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = expected_error<Points>(test_integration_over_real_line_error_id);
    Real Q;
    Real Q_expected;
    Real L1;
    Real error;

    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};
    Q = gauss_kronrod<Real, Points>::integrate(f1, -boost::math::tools::max_value<Real>(), boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);
    Q_expected = pi<Real>();
    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);
    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);
}

template<class Real, unsigned Points>
void test_right_limit_infinite()
{
    std::cout << "Testing right limit infinite for Gauss Kronrod in 'A Comparison of Three High Precision Quadrature Schemes' on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = expected_error<Points>(test_right_limit_infinite_error_id);
    Real Q;
    Real Q_expected;
    Real L1;
    Real error;

    // Example 11:
    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};
    Q = gauss_kronrod<Real, Points>::integrate(f1, 0, boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);
    Q_expected = half_pi<Real>();
    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);

    auto f4 = [](const Real& t)->Real { return 1/(1+t*t); };
    Q = gauss_kronrod<Real, Points>::integrate(f4, 1, boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);
    Q_expected = pi<Real>()/4;
    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);
}

template<class Real, unsigned Points>
void test_left_limit_infinite()
{
    std::cout << "Testing left limit infinite for Gauss Kronrod in 'A Comparison of Three High Precision Quadrature Schemes' on type " << boost::typeindex::type_id<Real>().pretty_name() << "\n";
    Real tol = expected_error<Points>(test_left_limit_infinite_error_id);
    Real Q;
    Real Q_expected;

    // Example 11:
    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};
    Q = gauss_kronrod<Real, Points>::integrate(f1, -boost::math::tools::max_value<Real>(), Real(0), 0);
    Q_expected = half_pi<Real>();
    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);
}

template<class Complex>
void test_complex_lambert_w()
{
    std::cout << "Testing that complex-valued integrands are integrated correctly by Gaussian quadrature on type " << boost::typeindex::type_id<Complex>().pretty_name() << "\n";
    typedef typename Complex::value_type Real;
    Real tol = 10e-9;
    using boost::math::constants::pi;
    Complex z{2, 3};
    auto lw = [&z](Real v)->Complex {
      using std::cos;
      using std::sin;
      using std::exp;
      Real sinv = sin(v);
      Real cosv = cos(v);

      Real cotv = cosv/sinv;
      Real cscv = 1/sinv;
      Real t = (1-v*cotv)*(1-v*cotv) + v*v;
      Real x = v*cscv*exp(-v*cotv);
      Complex den = z + x;
      Complex num = t*(z/pi<Real>());
      Complex res = num/den;
      return res;
    };

    //N[ProductLog[2+3*I], 150]
    boost::math::quadrature::gauss_kronrod<Real, 61> integrator;
    Complex Q = integrator.integrate(lw, (Real) 0, pi<Real>());
    BOOST_CHECK_CLOSE_FRACTION(Q.real(), boost::lexical_cast<Real>("1.09007653448579084630177782678166964987102108635357778056449870727913321296238687023915522935120701763447787503167111962008709116746523970476893277703"), tol);
    BOOST_CHECK_CLOSE_FRACTION(Q.imag(), boost::lexical_cast<Real>("0.530139720774838801426860213574121741928705631382703178297940568794784362495390544411799468140433404536019992695815009036975117285537382995180319280835"), tol);
}

BOOST_AUTO_TEST_CASE(gauss_quadrature_test)
{
#ifdef TEST1
    std::cout << "Testing 15 point approximation:\n";
    test_linear<double, 15>();
    test_quadratic<double, 15>();
    test_ca<double, 15>();
    test_three_quadrature_schemes_examples<double, 15>();
    test_integration_over_real_line<double, 15>();
    test_right_limit_infinite<double, 15>();
    test_left_limit_infinite<double, 15>();

    //  test one case where we do not have pre-computed constants:
    std::cout << "Testing 17 point approximation:\n";
    test_linear<double, 17>();
    test_quadratic<double, 17>();
    test_ca<double, 17>();
    test_three_quadrature_schemes_examples<double, 17>();
    test_integration_over_real_line<double, 17>();
    test_right_limit_infinite<double, 17>();
    test_left_limit_infinite<double, 17>();
    test_complex_lambert_w<std::complex<double>>();
    test_complex_lambert_w<std::complex<long double>>();
#endif
#ifdef TEST1A
    std::cout << "Testing 21 point approximation:\n";
    test_linear<cpp_bin_float_quad, 21>();
    test_quadratic<cpp_bin_float_quad, 21>();
    test_ca<cpp_bin_float_quad, 21>();
    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 21>();
    test_integration_over_real_line<cpp_bin_float_quad, 21>();
    test_right_limit_infinite<cpp_bin_float_quad, 21>();
    test_left_limit_infinite<cpp_bin_float_quad, 21>();

    std::cout << "Testing 31 point approximation:\n";
    test_linear<cpp_bin_float_quad, 31>();
    test_quadratic<cpp_bin_float_quad, 31>();
    test_ca<cpp_bin_float_quad, 31>();
    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 31>();
    test_integration_over_real_line<cpp_bin_float_quad, 31>();
    test_right_limit_infinite<cpp_bin_float_quad, 31>();
    test_left_limit_infinite<cpp_bin_float_quad, 31>();
#endif
#ifdef TEST2
    std::cout << "Testing 41 point approximation:\n";
    test_linear<cpp_bin_float_quad, 41>();
    test_quadratic<cpp_bin_float_quad, 41>();
    test_ca<cpp_bin_float_quad, 41>();
    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 41>();
    test_integration_over_real_line<cpp_bin_float_quad, 41>();
    test_right_limit_infinite<cpp_bin_float_quad, 41>();
    test_left_limit_infinite<cpp_bin_float_quad, 41>();

    std::cout << "Testing 51 point approximation:\n";
    test_linear<cpp_bin_float_quad, 51>();
    test_quadratic<cpp_bin_float_quad, 51>();
    test_ca<cpp_bin_float_quad, 51>();
    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 51>();
    test_integration_over_real_line<cpp_bin_float_quad, 51>();
    test_right_limit_infinite<cpp_bin_float_quad, 51>();
    test_left_limit_infinite<cpp_bin_float_quad, 51>();
#endif
#ifdef TEST3
    // Need at least one set of tests with expression templates turned on:
    std::cout << "Testing 61 point approximation:\n";
    test_linear<cpp_dec_float_50, 61>();
    test_quadratic<cpp_dec_float_50, 61>();
    test_ca<cpp_dec_float_50, 61>();
    test_three_quadrature_schemes_examples<cpp_dec_float_50, 61>();
    test_integration_over_real_line<cpp_dec_float_50, 61>();
    test_right_limit_infinite<cpp_dec_float_50, 61>();
    test_left_limit_infinite<cpp_dec_float_50, 61>();
#ifdef BOOST_HAS_FLOAT128
    test_complex_lambert_w<boost::multiprecision::complex128>();
#endif
#endif
}

#else

int main() { return 0; }

#endif

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: qingkouwei/mediaones


text:
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include "../gaussian_smoother_2D.h"

using namespace boost::python;

namespace dials { namespace refinement { namespace boost_python {

  void export_gaussian_smoother_2D() {
    class_<GaussianSmoother2D>("GaussianSmoother2D", no_init)
      .def(init<vec2<double>, std::size_t, vec2<double>, std::size_t>(
        (arg("x_range"),
         arg("num_x_intervals"),
         arg("y_range"),
         arg("num_y_intervals"))))
      .def("set_smoothing", &GaussianSmoother2D::set_smoothing)
      .def("num_x_values", &GaussianSmoother2D::num_x_values)
      .def("num_y_values", &GaussianSmoother2D::num_y_values)
      .def("num_x_samples", &GaussianSmoother2D::num_x_samples)
      .def("num_y_samples", &GaussianSmoother2D::num_y_samples)
      .def("num_x_average", &GaussianSmoother2D::num_x_average)
      .def("num_y_average", &GaussianSmoother2D::num_y_average)
      .def("sigma", &GaussianSmoother2D::sigma)
      .def("x_spacing", &GaussianSmoother2D::x_spacing)
      .def("y_spacing", &GaussianSmoother2D::y_spacing)
      .def("x_positions", &GaussianSmoother2D::x_positions)
      .def("y_positions", &GaussianSmoother2D::y_positions)
      .def("value_weight", &GaussianSmoother2D::value_weight)
      .def("multi_value_weight", &GaussianSmoother2D::multi_value_weight);
  }

}}}  // namespace dials::refinement::boost_python

ext: cc

max_stars_repo_name: TiankunZhou/dials

max_issues_repo_name: TiankunZhou/dials

max_forks_repo_name: TiankunZhou/dials