<commit_before>//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define THIRD_RBM_1       //One layer of RBM
//#define THIRD_RBM_2       //Two layers of RBM
//#define THIRD_RBM_3       //Three layers of RBM

//#define THIRD_CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2    //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define THIRD_CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN    //Architecture to play around

constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width  = 20;

// Data augmentation
constexpr const std::size_t elastic_augment = 1; //not ready

constexpr const std::size_t epochs       = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride  = 1;

constexpr const std::size_t NF1          = 9;
constexpr const std::size_t K1           = 8;
constexpr const std::size_t C1           = 2;
constexpr const std::size_t B1           = 128;
constexpr const dll::unit_type HT1       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;
constexpr const bool shuffle_1           = false;

constexpr const std::size_t NF2          = 3;
constexpr const std::size_t K2           = 8;
constexpr const std::size_t C2           = 2;
constexpr const std::size_t B2           = 128;
constexpr const dll::unit_type HT2       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;
constexpr const bool shuffle_2           = false;

constexpr const std::size_t NF3          = 3;
constexpr const std::size_t K3           = 48;
constexpr const std::size_t C3           = 2;
constexpr const std::size_t B3           = 64;
constexpr const dll::unit_type HT3       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3           = true;

const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };

const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };

const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };

const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };

#ifdef THIRD_CRBM_MP_2
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif

const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };

} // end of namespace third

#endif
<commit_msg>Switch to PAR values<commit_after>//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define THIRD_RBM_1       //One layer of RBM
//#define THIRD_RBM_2       //Two layers of RBM
//#define THIRD_RBM_3       //Three layers of RBM

//#define THIRD_CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2    //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define THIRD_CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN    //Architecture to play around

constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width  = 20;

// Data augmentation
constexpr const std::size_t elastic_augment = 1; //not ready

constexpr const std::size_t epochs       = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride  = 1;

constexpr const std::size_t NF1          = 9;
constexpr const std::size_t K1           = 12;
constexpr const std::size_t C1           = 2;
constexpr const std::size_t B1           = 128;
constexpr const dll::unit_type HT1       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;
constexpr const bool shuffle_1           = false;

constexpr const std::size_t NF2          = 3;
constexpr const std::size_t K2           = 12;
constexpr const std::size_t C2           = 2;
constexpr const std::size_t B2           = 128;
constexpr const dll::unit_type HT2       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;
constexpr const bool shuffle_2           = false;

constexpr const std::size_t NF3          = 3;
constexpr const std::size_t K3           = 48;
constexpr const std::size_t C3           = 2;
constexpr const std::size_t B3           = 64;
constexpr const dll::unit_type HT3       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3           = true;

const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };

const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };

const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };

const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };

#ifdef THIRD_CRBM_MP_2
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif

const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };

} // end of namespace third

#endif
<|endoftext|>


<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include <AnalogOutput.h>
#include <AnalogPotentiometer.h>
#include <Timer.h>
#include "TestBench.h"
#include "gtest/gtest.h"

static const double kScale = 270.0;
static const double kVoltage = 3.33;
static const double kAngle = 180.0;

class AnalogPotentiometerTest : public testing::Test {
 protected:
  AnalogOutput *m_fakePot;
  AnalogPotentiometer *m_pot;

  virtual void SetUp() override {
    m_fakePot = new AnalogOutput(TestBench::kAnalogOutputChannel);
    m_pot =
        new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel, kScale);
  }

  virtual void TearDown() override {
    delete m_fakePot;
    delete m_pot;
  }
};

TEST_F(AnalogPotentiometerTest, TestInitialSettings) {
  m_fakePot->SetVoltage(0.0);
  Wait(0.1);
  EXPECT_NEAR(0.0, m_pot->Get(), 5.0)
      << "The potentiometer did not initialize to 0.";
}

TEST_F(AnalogPotentiometerTest, TestRangeValues) {
  m_fakePot->SetVoltage(kVoltage);
  Wait(0.1);
  EXPECT_NEAR(kAngle, m_pot->Get(), 2.0)
      << "The potentiometer did not measure the correct angle.";
}
<commit_msg>Make C++ Analog Potentiometer test work.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include <AnalogOutput.h>
#include <AnalogPotentiometer.h>
#include <Timer.h>
#include <ControllerPower.h>
#include "TestBench.h"
#include "gtest/gtest.h"

static const double kScale = 270.0;
static const double kAngle = 180.0;

class AnalogPotentiometerTest : public testing::Test {
 protected:
  AnalogOutput *m_fakePot;
  AnalogPotentiometer *m_pot;

  virtual void SetUp() override {
    m_fakePot = new AnalogOutput(TestBench::kAnalogOutputChannel);
    m_pot =
        new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel, kScale);
  }

  virtual void TearDown() override {
    delete m_fakePot;
    delete m_pot;
  }
};

TEST_F(AnalogPotentiometerTest, TestInitialSettings) {
  m_fakePot->SetVoltage(0.0);
  Wait(0.1);
  EXPECT_NEAR(0.0, m_pot->Get(), 5.0)
      << "The potentiometer did not initialize to 0.";
}

TEST_F(AnalogPotentiometerTest, TestRangeValues) {
  m_fakePot->SetVoltage(kAngle / kScale * ControllerPower::GetVoltage5V());
  Wait(0.1);
  EXPECT_NEAR(kAngle, m_pot->Get(), 2.0)
      << "The potentiometer did not measure the correct angle.";
}
<|endoftext|>


<commit_before>#include "meanfield.h"
#include "solvers.h"
double timer;

// Catch errors
static void erfunc(char *err) {
  mexErrMsgTxt(err);
}

void mexFunction(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[]		/* mxArray input pointer array */)
{
    startTime();

    // Parsing data from MATLAB
    if (nrhs != 4)
        mexErrMsgTxt("Expected 3 inputs");

    const matrix<unsigned char> im_matrix(prhs[0]);
    const matrix<float>  unary_matrix(prhs[1]);
    const matrix<unsigned int> im_size(prhs[2]);

    //Structure to hold and parse additional parameters
    MexParams params(1, prhs+3);

    // Weights used to define the energy function
    PairwiseWeights pairwiseWeights(params);
    const bool debug = params.get<bool>("debug", false);
    const int iterations = params.get<int>("iterations", 20);

    // Used only for TRW-S
    const double min_pairwise_cost = params.get<double>("min_pairwise_cost", 0);
    string solver = params.get<string>("solver", "Not set");

    // The image
    const int M = im_size(0);
    const int N = im_size(1);
    const int C = im_size(2);
    const int numVariables = M*N;

    // Calculate number of labels
    const int UC = unary_matrix.numel();
    const int numberOfLabels = UC/(M*N);

    // Read image and unary
    const unsigned char * image  = im_matrix.data;
    float * unary_array  = unary_matrix.data;

    assert(M > 0);
    assert(N > 0);

    if (solver.compare("mean_field") && solver.compare("trws") && solver.compare("mean_field_explicit")) {
        mexErrMsgTxt("Unknown solver");
    }

    // Oracle function to get cost
    LinearIndex unaryLinearIndex(M,N, numberOfLabels);
    LinearIndex imageLinearIndex(M,N, C);

    Linear2sub linear2sub(M,N);
    UnaryCost unaryCost(unary_array, unaryLinearIndex);

    if (debug)
    {
      mexPrintf("min_pairwise_cost: %g \n", min_pairwise_cost);
      mexPrintf("Problem size: %d x %d \n", M,N);

      endTime("Reading data.");
    }

    matrix<double> result(M,N);
    matrix<double> energy(1);
    matrix<double> bound(1);

    plhs[0] = result;
    plhs[1] = energy;
    plhs[2] = bound;

    PairwiseCost pairwiseCost(image, pairwiseWeights, imageLinearIndex);
    EnergyFunctor energyFunctor(unaryCost, pairwiseCost, M,N, numberOfLabels);

    // Mean field
    if(!solver.compare("mean_field"))
    {
      if (debug)
        endTime("Solving using mean field approximation and approximate gaussian filters.");

      // Setup the CRF model
      extendedDenseCRF2D crf(M,N,numberOfLabels);
      Map<MatrixXf> unary(unary_array, numberOfLabels, numVariables);

      crf.setUnaryEnergy( unary );

      KernelType kerneltype = CONST_KERNEL;
      NormalizationType normalizationtype = parseNormalizationType(params);

      // Setup  pairwise cost
      crf.addPairwiseGaussian(pairwiseWeights.gaussian_x_stddev,
                              pairwiseWeights.gaussian_y_stddev,
                              new PottsCompatibility(pairwiseWeights.gaussian_weight),
                              kerneltype,
                              normalizationtype);

      crf.addPairwiseBilateral(pairwiseWeights.bilateral_x_stddev,
                               pairwiseWeights.bilateral_y_stddev,
                               pairwiseWeights.bilateral_r_stddev,
                               pairwiseWeights.bilateral_g_stddev,
                               pairwiseWeights.bilateral_b_stddev,
                               image,
                               new PottsCompatibility(pairwiseWeights.bilateral_weight),
                               kerneltype,
                               normalizationtype);

      // Do map inference
      VectorXs map = crf.map(iterations);

      //Packing data in the same way as input
      for (int i = 0; i < numVariables; i++ ) {
           result(i) = (double)map[i];
      }

      energy(0) = crf.energy(map);
      bound(0) = lowestUnaryCost( unary_array, M,N,numberOfLabels );

      return;
    }

    if(!solver.compare("mean_field_explicit"))
    {
      if (debug)
        endTime("Solving using mean field approximation by explicit summation");
      // Init
      matrix<double> Q(M,N,numberOfLabels);
      matrix<double> addative_sum(M,N,numberOfLabels);

      for (int x = 0; x < M; x++) {
      for (int y = 0; y < N; y++) {
      for (int l = 0; l < numberOfLabels; l++) {
        Q(x,y,l) = exp(-unaryCost(x,y,l));
      }}}

      normalize(Q);

      for (int i = 0; i < iterations; i++)
      {
        // Pairwise count negative when equal (faster)
        for (int label = 0; label < numberOfLabels; label++) {
          for (int x = 0; x < M; x++) {
          for (int y = 0; y < N; y++) {

            addative_sum(x,y,label) = unaryCost(x,y,label);

            for (int x_target = 0; x_target < M; x_target++) {
            for (int y_target = 0; y_target < N; y_target++) {

              addative_sum(x,y,label) -=
                pairwiseCost(x, y, x_target, y_target)*
                Q( x_target, y_target, label );
            }
            }
          }
          }
        }

        for (int i = 0; i < Q.numel(); i++)
          Q(i) = exp( - addative_sum(i) );

        normalize(Q);
      }

      matrix<double> result(M,N);
      matrix<double> energy(1);
      matrix<double> bound(1);

      double max_prob;
      for (int x = 0; x < M; x++) {
      for (int y = 0; y < N; y++) {
        max_prob = Q(x,y,0);
        result(x,y) = 0;

        for (int l = 1; l < numberOfLabels; l++)
        {
          if (Q(x,y,l) > max_prob)
          {
            max_prob = Q(x,y,l);
            result(x,y) = l;
          }
        }
      }
      }

      energy(0) = std::numeric_limits<double>::quiet_NaN();
      bound(0) = std::numeric_limits<double>::quiet_NaN();

      plhs[0] = result;
      plhs[1] = energy;
      plhs[2] = bound;

      return;
    }

    if(!solver.compare("trws"))
    {

      if (debug)
        endTime("Convergent Tree-reweighted Message Passing");

      TypePotts::REAL TRWSenergy, TRWSlb;
      TRWSOptions options;
      options.m_iterMax = iterations;
      options.m_eps = 0;

      if (!debug)
        options.m_printMinIter = iterations+2;

      TRWS * mrf = new TRWS(TypePotts::GlobalSize(numberOfLabels),erfunc);
      TRWSNodes * nodes = new TRWSNodes[numVariables];

      std::vector<TypePotts::REAL> D(numberOfLabels);

      for (int i = 0; i < numVariables; i++)
      {
        for(int s = 0; s < numberOfLabels; ++s)
        {
          std::pair<int,int> p = linear2sub(i);
          D[s] = unaryCost( p, s );
        }

        nodes[i] = mrf->AddNode(TypePotts::LocalSize(),
                                TypePotts::NodeData(&D[0]));
      }

      // Pairwise cost
      for (int i = 0; i < numVariables; i++) {
      for (int j = i+1; j < numVariables; j++) {
        std::pair<int,int> p0 = linear2sub(i);
        std::pair<int,int> p1 = linear2sub(j);

        double pcost = pairwiseCost( p0, p1 );

        if (pcost >= min_pairwise_cost)
            mrf->AddEdge(nodes[i], nodes[j], TypePotts::EdgeData(pcost));
      }
      }

      mrf->Minimize_TRW_S(options, TRWSlb, TRWSenergy);

      for (int i = 0; i < numVariables; i++)
        result(i) = mrf->GetSolution(nodes[i]);

      energy(0) = TRWSenergy;
      bound(0) = TRWSlb;

      delete mrf;
      delete nodes;

      return;
    }
}<commit_msg>Removing unnecessary code<commit_after>#include "meanfield.h"
#include "solvers.h"
double timer;

// Catch errors
static void erfunc(char *err) {
  mexErrMsgTxt(err);
}

void mexFunction(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[]		/* mxArray input pointer array */)
{
    startTime();

    // Parsing data from MATLAB
    if (nrhs != 4)
        mexErrMsgTxt("Expected 3 inputs");

    const matrix<unsigned char> im_matrix(prhs[0]);
    const matrix<float>  unary_matrix(prhs[1]);
    const matrix<unsigned int> im_size(prhs[2]);

    //Structure to hold and parse additional parameters
    MexParams params(1, prhs+3);

    // Weights used to define the energy function
    PairwiseWeights pairwiseWeights(params);
    const bool debug = params.get<bool>("debug", false);
    const int iterations = params.get<int>("iterations", 20);

    // Used only for TRW-S
    const double min_pairwise_cost = params.get<double>("min_pairwise_cost", 0);
    string solver = params.get<string>("solver", "Not set");

    // The image
    const int M = im_size(0);
    const int N = im_size(1);
    const int C = im_size(2);
    const int numVariables = M*N;

    // Calculate number of labels
    const int UC = unary_matrix.numel();
    const int numberOfLabels = UC/(M*N);

    // Read image and unary
    const unsigned char * image  = im_matrix.data;
    float * unary_array  = unary_matrix.data;

    assert(M > 0);
    assert(N > 0);

    if (solver.compare("mean_field") && solver.compare("trws") && solver.compare("mean_field_explicit")) {
        mexErrMsgTxt("Unknown solver");
    }

    // Oracle function to get cost
    LinearIndex unaryLinearIndex(M,N, numberOfLabels);
    LinearIndex imageLinearIndex(M,N, C);

    Linear2sub linear2sub(M,N);
    UnaryCost unaryCost(unary_array, unaryLinearIndex);

    if (debug)
    {
      mexPrintf("min_pairwise_cost: %g \n", min_pairwise_cost);
      mexPrintf("Problem size: %d x %d \n", M,N);

      endTime("Reading data.");
    }

    matrix<double> result(M,N);
    matrix<double> energy(1);
    matrix<double> bound(1);

    plhs[0] = result;
    plhs[1] = energy;
    plhs[2] = bound;

    PairwiseCost pairwiseCost(image, pairwiseWeights, imageLinearIndex);
    EnergyFunctor energyFunctor(unaryCost, pairwiseCost, M,N, numberOfLabels);

    // Mean field
    if(!solver.compare("mean_field"))
    {
      if (debug)
        endTime("Solving using mean field approximation and approximate gaussian filters.");

      // Setup the CRF model
      extendedDenseCRF2D crf(M,N,numberOfLabels);
      Map<MatrixXf> unary(unary_array, numberOfLabels, numVariables);

      crf.setUnaryEnergy( unary );

      KernelType kerneltype = CONST_KERNEL;
      NormalizationType normalizationtype = parseNormalizationType(params);

      // Setup  pairwise cost
      crf.addPairwiseGaussian(pairwiseWeights.gaussian_x_stddev,
                              pairwiseWeights.gaussian_y_stddev,
                              new PottsCompatibility(pairwiseWeights.gaussian_weight),
                              kerneltype,
                              normalizationtype);

      crf.addPairwiseBilateral(pairwiseWeights.bilateral_x_stddev,
                               pairwiseWeights.bilateral_y_stddev,
                               pairwiseWeights.bilateral_r_stddev,
                               pairwiseWeights.bilateral_g_stddev,
                               pairwiseWeights.bilateral_b_stddev,
                               image,
                               new PottsCompatibility(pairwiseWeights.bilateral_weight),
                               kerneltype,
                               normalizationtype);

      // Do map inference
      VectorXs map = crf.map(iterations);

      //Packing data in the same way as input
      for (int i = 0; i < numVariables; i++ ) {
           result(i) = (double)map[i];
      }

      energy(0) = crf.energy(map);
      bound(0) = lowestUnaryCost( unary_array, M,N,numberOfLabels );

      return;
    }

    if(!solver.compare("mean_field_explicit"))
    {
      if (debug)
        endTime("Solving using mean field approximation by explicit summation");
      // Init
      matrix<double> Q(M,N,numberOfLabels);
      matrix<double> addative_sum(M,N,numberOfLabels);

      for (int x = 0; x < M; x++) {
      for (int y = 0; y < N; y++) {
      for (int l = 0; l < numberOfLabels; l++) {
        Q(x,y,l) = exp(-unaryCost(x,y,l));
      }}}

      normalize(Q);

      for (int i = 0; i < iterations; i++)
      {
        // Pairwise count negative when equal (faster)
        for (int label = 0; label < numberOfLabels; label++) {
          for (int x = 0; x < M; x++) {
          for (int y = 0; y < N; y++) {

            addative_sum(x,y,label) = unaryCost(x,y,label);

            for (int x_target = 0; x_target < M; x_target++) {
            for (int y_target = 0; y_target < N; y_target++) {

              addative_sum(x,y,label) -=
                pairwiseCost(x, y, x_target, y_target)*
                Q( x_target, y_target, label );
            }
            }
          }
          }
        }

        for (int i = 0; i < Q.numel(); i++)
          Q(i) = exp( - addative_sum(i) );

        normalize(Q);
      }

      matrix<double> result(M,N);
      matrix<double> energy(1);
      matrix<double> bound(1);

      double max_prob;
      for (int x = 0; x < M; x++) {
      for (int y = 0; y < N; y++) {
        max_prob = Q(x,y,0);
        result(x,y) = 0;

        for (int l = 1; l < numberOfLabels; l++)
        {
          if (Q(x,y,l) > max_prob)
          {
            max_prob = Q(x,y,l);
            result(x,y) = l;
          }
        }
      }
      }

      energy(0) = std::numeric_limits<double>::quiet_NaN();
      bound(0) = std::numeric_limits<double>::quiet_NaN();

      return;
    }

    if(!solver.compare("trws"))
    {

      if (debug)
        endTime("Convergent Tree-reweighted Message Passing");

      TypePotts::REAL TRWSenergy, TRWSlb;
      TRWSOptions options;
      options.m_iterMax = iterations;
      options.m_eps = 0;

      if (!debug)
        options.m_printMinIter = iterations+2;

      TRWS * mrf = new TRWS(TypePotts::GlobalSize(numberOfLabels),erfunc);
      TRWSNodes * nodes = new TRWSNodes[numVariables];

      std::vector<TypePotts::REAL> D(numberOfLabels);

      for (int i = 0; i < numVariables; i++)
      {
        for(int s = 0; s < numberOfLabels; ++s)
        {
          std::pair<int,int> p = linear2sub(i);
          D[s] = unaryCost( p, s );
        }

        nodes[i] = mrf->AddNode(TypePotts::LocalSize(),
                                TypePotts::NodeData(&D[0]));
      }

      // Pairwise cost
      for (int i = 0; i < numVariables; i++) {
      for (int j = i+1; j < numVariables; j++) {
        std::pair<int,int> p0 = linear2sub(i);
        std::pair<int,int> p1 = linear2sub(j);

        double pcost = pairwiseCost( p0, p1 );

        if (pcost >= min_pairwise_cost)
            mrf->AddEdge(nodes[i], nodes[j], TypePotts::EdgeData(pcost));
      }
      }

      mrf->Minimize_TRW_S(options, TRWSlb, TRWSenergy);

      for (int i = 0; i < numVariables; i++)
        result(i) = mrf->GetSolution(nodes[i]);

      energy(0) = TRWSenergy;
      bound(0) = TRWSlb;

      delete mrf;
      delete nodes;

      return;
    }
}<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/Future.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/types/DiscoveryScope.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/vehicle/GpsProxy.h"
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/utils/PtrUtils.h"
#include "tests/utils/TestLibJoynrWebSocketRuntime.h"

using namespace ::testing;

using namespace joynr;

class End2EndProxyBuilderRobustnessTest : public Test {
public:
    End2EndProxyBuilderRobustnessTest() :
        domain("cppEnd2EndProxyBuilderRobustnessTest" + util::createUuid()),
        discoveryTimeoutMs(5000),
        retryIntervalMs(500),
        consumerRuntime(),
        providerRuntime(),
        ccRuntime(),
        discoveryQos()
    {
        auto settings = std::make_unique<Settings>();
        consumerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));

        settings = std::make_unique<Settings>();
        providerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));

        settings = std::make_unique<Settings>();
        MessagingSettings ccSettings(*settings);
        // use wrong broker-url to prevent global communication
        BrokerUrl brokerUrl("mqtt://localhost:12347");
        ccSettings.setBrokerUrl(brokerUrl);
        ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings));

        ccRuntime->init();
        ccRuntime->start();

        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(discoveryTimeoutMs);
        discoveryQos.setCacheMaxAgeMs(discoveryTimeoutMs);
    }

    // Sets up the test fixture.
    void SetUp() override
    {
        ASSERT_TRUE(consumerRuntime->connect(std::chrono::milliseconds(10000)));
        ASSERT_TRUE(providerRuntime->connect(std::chrono::milliseconds(10000)));
    }

    ~End2EndProxyBuilderRobustnessTest() override {

        ccRuntime->shutdown();
        consumerRuntime->shutdown();
        providerRuntime->shutdown();

        test::util::resetAndWaitUntilDestroyed(ccRuntime);
        test::util::resetAndWaitUntilDestroyed(consumerRuntime);
        test::util::resetAndWaitUntilDestroyed(providerRuntime);

        // Delete persisted files
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
        std::this_thread::sleep_for(std::chrono::milliseconds(550));
    }

protected:
    std::string domain;
    const std::int64_t discoveryTimeoutMs;
    const std::int64_t retryIntervalMs;
    std::shared_ptr<TestLibJoynrWebSocketRuntime> consumerRuntime;
    std::shared_ptr<TestLibJoynrWebSocketRuntime> providerRuntime;
    std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
    joynr::DiscoveryQos discoveryQos;

    void buildProxyBeforeProviderRegistration(const bool expectSuccess);

private:
    DISALLOW_COPY_AND_ASSIGN(End2EndProxyBuilderRobustnessTest);
};

void End2EndProxyBuilderRobustnessTest::buildProxyBeforeProviderRegistration(const bool expectSuccess)
{
    Semaphore semaphore(0);
    // prepare provider
    auto mockProvider = std::make_shared<MockGpsProvider>();
    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);

    // build proxy
    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
            consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);

    auto onSuccess = [&semaphore, expectSuccess](std::shared_ptr<vehicle::GpsProxy> gpsProxy) {
        if (!expectSuccess) {
            ADD_FAILURE() << "proxy building succeeded unexpectedly";
            semaphore.notify();
            return;
        }
        // call proxy method
        auto calculateOnSuccess = [&semaphore](int value) {
            const int expectedValue = 42; // as defined in MockGpsProvider
            EXPECT_EQ(expectedValue, value);
            semaphore.notify();
        };
        gpsProxy->calculateAvailableSatellitesAsync(calculateOnSuccess);
    };

    auto onError = [&semaphore, expectSuccess] (const exceptions::DiscoveryException& exception) {
        if (expectSuccess) {
            ADD_FAILURE() << "proxy building failed unexpectedly, exception: " << exception.getMessage();
        }
        semaphore.notify();
    };

    std::int64_t qosRoundTripTTL = 10000;
    gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onError);

    // wait some time so that the lookup request is likely to be processed at the cluster controller
    // and make sure that no retry attempt has been started
    std::this_thread::sleep_for(std::chrono::milliseconds(retryIntervalMs / 2));

    // register provider
    std::string participantId = providerRuntime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);

    EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(qosRoundTripTTL + discoveryTimeoutMs)));

    // unregister provider
    providerRuntime->unregisterProvider(participantId);
}

// as soon as the provider gets registered, the lookup returns successful
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithoutRetry)
{
    const bool expectedSuccess = true;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithRetry)
{
    const bool expectedSuccess = true;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithRetry)
{
    const bool expectedSuccess = false;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalOnly_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalOnly_succeedsWithRetry)
{
    const bool expectedSuccess = true;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_GlobalOnly_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_GlobalOnly_failsWithRetry)
{
    const bool expectedSuccess = false;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

class End2EndProxyBuild : public End2EndProxyBuilderRobustnessTest {
protected:
    void SetUp() override {
        End2EndProxyBuilderRobustnessTest::SetUp();

        auto mockProvider = std::make_shared<MockGpsProvider>();
        types::ProviderQos providerQos;
        std::chrono::milliseconds millisSinceEpoch =
            std::chrono::duration_cast<std::chrono::milliseconds>(
                    std::chrono::system_clock::now().time_since_epoch());
        providerQos.setPriority(millisSinceEpoch.count());
        providerQos.setScope(joynr::types::ProviderScope::GLOBAL);

        providerParticipantId = providerRuntime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
        gpsProxyBuilder = consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
    }

    void TearDown() override {
        providerRuntime->unregisterProvider(providerParticipantId);
    }

    std::string providerParticipantId;
    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder;
};

TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQos) {
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setDiscoveryQos(discoveryQos)
                                                    ->build());
    ASSERT_TRUE(gpsProxy);
}

TEST_F(End2EndProxyBuild, buildProxyWithoutSetDiscoveryQos) {
    const std::int64_t qosRoundTripTTL = 10000;
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
                                                    ->build());
    ASSERT_TRUE(gpsProxy);
}

TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQosAndWithoutSetDiscoveryQos) {
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->build());
    ASSERT_TRUE(gpsProxy);
}
<commit_msg>[C++] format End2EndProxyBuilderRobustnessTest.cpp<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/Future.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/types/DiscoveryScope.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/vehicle/GpsProxy.h"
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/utils/PtrUtils.h"
#include "tests/utils/TestLibJoynrWebSocketRuntime.h"

using namespace ::testing;

using namespace joynr;

class End2EndProxyBuilderRobustnessTest : public Test
{
public:
    End2EndProxyBuilderRobustnessTest()
            : domain("cppEnd2EndProxyBuilderRobustnessTest" + util::createUuid()),
              discoveryTimeoutMs(5000),
              retryIntervalMs(500),
              consumerRuntime(),
              providerRuntime(),
              ccRuntime(),
              discoveryQos()
    {
        auto settings = std::make_unique<Settings>();
        consumerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));

        settings = std::make_unique<Settings>();
        providerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));

        settings = std::make_unique<Settings>();
        MessagingSettings ccSettings(*settings);
        // use wrong broker-url to prevent global communication
        BrokerUrl brokerUrl("mqtt://localhost:12347");
        ccSettings.setBrokerUrl(brokerUrl);
        ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings));

        ccRuntime->init();
        ccRuntime->start();

        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(discoveryTimeoutMs);
        discoveryQos.setCacheMaxAgeMs(discoveryTimeoutMs);
    }

    // Sets up the test fixture.
    void SetUp() override
    {
        ASSERT_TRUE(consumerRuntime->connect(std::chrono::milliseconds(10000)));
        ASSERT_TRUE(providerRuntime->connect(std::chrono::milliseconds(10000)));
    }

    ~End2EndProxyBuilderRobustnessTest() override
    {

        ccRuntime->shutdown();
        consumerRuntime->shutdown();
        providerRuntime->shutdown();

        test::util::resetAndWaitUntilDestroyed(ccRuntime);
        test::util::resetAndWaitUntilDestroyed(consumerRuntime);
        test::util::resetAndWaitUntilDestroyed(providerRuntime);

        // Delete persisted files
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
        std::this_thread::sleep_for(std::chrono::milliseconds(550));
    }

protected:
    std::string domain;
    const std::int64_t discoveryTimeoutMs;
    const std::int64_t retryIntervalMs;
    std::shared_ptr<TestLibJoynrWebSocketRuntime> consumerRuntime;
    std::shared_ptr<TestLibJoynrWebSocketRuntime> providerRuntime;
    std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
    joynr::DiscoveryQos discoveryQos;

    void buildProxyBeforeProviderRegistration(const bool expectSuccess);

private:
    DISALLOW_COPY_AND_ASSIGN(End2EndProxyBuilderRobustnessTest);
};

void End2EndProxyBuilderRobustnessTest::buildProxyBeforeProviderRegistration(
        const bool expectSuccess)
{
    Semaphore semaphore(0);
    // prepare provider
    auto mockProvider = std::make_shared<MockGpsProvider>();
    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
            std::chrono::duration_cast<std::chrono::milliseconds>(
                    std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);

    // build proxy
    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
            consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);

    auto onSuccess = [&semaphore, expectSuccess](std::shared_ptr<vehicle::GpsProxy> gpsProxy) {
        if (!expectSuccess) {
            ADD_FAILURE() << "proxy building succeeded unexpectedly";
            semaphore.notify();
            return;
        }
        // call proxy method
        auto calculateOnSuccess = [&semaphore](int value) {
            const int expectedValue = 42; // as defined in MockGpsProvider
            EXPECT_EQ(expectedValue, value);
            semaphore.notify();
        };
        gpsProxy->calculateAvailableSatellitesAsync(calculateOnSuccess);
    };

    auto onError = [&semaphore, expectSuccess](const exceptions::DiscoveryException& exception) {
        if (expectSuccess) {
            ADD_FAILURE() << "proxy building failed unexpectedly, exception: "
                          << exception.getMessage();
        }
        semaphore.notify();
    };

    std::int64_t qosRoundTripTTL = 10000;
    gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->buildAsync(onSuccess, onError);

    // wait some time so that the lookup request is likely to be processed at the cluster controller
    // and make sure that no retry attempt has been started
    std::this_thread::sleep_for(std::chrono::milliseconds(retryIntervalMs / 2));

    // register provider
    std::string participantId = providerRuntime->registerProvider<vehicle::GpsProvider>(
            domain, mockProvider, providerQos);

    EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(qosRoundTripTTL + discoveryTimeoutMs)));

    // unregister provider
    providerRuntime->unregisterProvider(participantId);
}

// as soon as the provider gets registered, the lookup returns successful
TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithoutRetry)
{
    const bool expectedSuccess = true;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithRetry)
{
    const bool expectedSuccess = true;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithRetry)
{
    const bool expectedSuccess = false;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalOnly_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_LocalOnly_succeedsWithRetry)
{
    const bool expectedSuccess = true;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_GlobalOnly_failsWithoutRetry)
{
    const bool expectedSuccess = false;
    // disable retries for provider lookup
    discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest,
       buildProxyBeforeProviderRegistration_GlobalOnly_failsWithRetry)
{
    const bool expectedSuccess = false;
    discoveryQos.setRetryIntervalMs(retryIntervalMs);
    discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
    buildProxyBeforeProviderRegistration(expectedSuccess);
}

class End2EndProxyBuild : public End2EndProxyBuilderRobustnessTest
{
protected:
    void SetUp() override
    {
        End2EndProxyBuilderRobustnessTest::SetUp();

        auto mockProvider = std::make_shared<MockGpsProvider>();
        types::ProviderQos providerQos;
        std::chrono::milliseconds millisSinceEpoch =
                std::chrono::duration_cast<std::chrono::milliseconds>(
                        std::chrono::system_clock::now().time_since_epoch());
        providerQos.setPriority(millisSinceEpoch.count());
        providerQos.setScope(joynr::types::ProviderScope::GLOBAL);

        providerParticipantId = providerRuntime->registerProvider<vehicle::GpsProvider>(
                domain, mockProvider, providerQos);
        gpsProxyBuilder = consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
    }

    void TearDown() override
    {
        providerRuntime->unregisterProvider(providerParticipantId);
    }

    std::string providerParticipantId;
    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder;
};

TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQos)
{
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setDiscoveryQos(discoveryQos)->build());
    ASSERT_TRUE(gpsProxy);
}

TEST_F(End2EndProxyBuild, buildProxyWithoutSetDiscoveryQos)
{
    const std::int64_t qosRoundTripTTL = 10000;
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(
            gpsProxy = gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))->build());
    ASSERT_TRUE(gpsProxy);
}

TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQosAndWithoutSetDiscoveryQos)
{
    std::shared_ptr<vehicle::GpsProxy> gpsProxy;
    JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->build());
    ASSERT_TRUE(gpsProxy);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include "I2PEndian.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "base64.h"
#include "Timestamp.h"
#include "Log.h"
#include "RouterInfo.h"
#include "RouterContext.h"

namespace i2p
{
namespace data
{
	RouterInfo::RouterInfo (const char * filename):
		m_IsUpdated (false), m_IsUnreachable (false)
	{
		ReadFromFile (filename);
	}

	RouterInfo::RouterInfo (const uint8_t * buf, int len):
		m_IsUpdated (true)
	{
		memcpy (m_Buffer, buf, len);
		m_BufferLen = len;
		ReadFromBuffer ();
	}

	void RouterInfo::SetRouterIdentity (const Identity& identity)
	{
		m_RouterIdentity = identity;
		m_IdentHash = CalculateIdentHash (m_RouterIdentity);
		UpdateIdentHashBase64 ();
		UpdateRoutingKey ();
		m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
	}

	void RouterInfo::ReadFromFile (const char * filename)
	{
		std::ifstream s(filename, std::ifstream::binary);
		if (s.is_open ())
		{
			s.seekg (0,std::ios::end);
			m_BufferLen = s.tellg ();
			s.seekg(0, std::ios::beg);
			s.read(m_Buffer,m_BufferLen);
			ReadFromBuffer ();
		}
		else
			LogPrint ("Can't open file ", filename);
	}

	void RouterInfo::ReadFromBuffer ()
	{
		std::stringstream str (std::string (m_Buffer, m_BufferLen));
		ReadFromStream (str);
		// verify signature
		CryptoPP::DSA::PublicKey pubKey;
		pubKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag, CryptoPP::Integer (m_RouterIdentity.signingKey, 128));
		CryptoPP::DSA::Verifier verifier (pubKey);
		int l = m_BufferLen - 40;
		if (!verifier.VerifyMessage ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l, 40))
		{
			LogPrint ("signature verification failed");
		}
	}

	void RouterInfo::ReadFromStream (std::istream& s)
	{
		s.read ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
		m_Timestamp = be64toh (m_Timestamp);
		// read addresses
		uint8_t numAddresses;
		s.read ((char *)&numAddresses, sizeof (numAddresses));
		for (int i = 0; i < numAddresses; i++)
		{
			Address address;
			s.read ((char *)&address.cost, sizeof (address.cost));
			s.read ((char *)&address.date, sizeof (address.date));
			char transportStyle[5];
			ReadString (transportStyle, s);
			if (!strcmp (transportStyle, "NTCP"))
				address.transportStyle = eTransportNTCP;
			else if (!strcmp (transportStyle, "SSU"))
				address.transportStyle = eTransportSSU;
			else
				address.transportStyle = eTransportUnknown;
			uint16_t size, r = 0;
			s.read ((char *)&size, sizeof (size));
			size = be16toh (size);
			while (r < size)
			{
				char key[500], value[500];
				r += ReadString (key, s);
				s.seekg (1, std::ios_base::cur); r++; // =
				r += ReadString (value, s);
				s.seekg (1, std::ios_base::cur); r++; // ;
				if (!strcmp (key, "host"))
				{
					boost::system::error_code ecode;
					address.host = boost::asio::ip::address::from_string (value, ecode);
					if (ecode)
					{
						// TODO: we should try to resolve address here
						LogPrint ("Unexpected address ", value);
						SetUnreachable (true);
					}
				}
				else if (!strcmp (key, "port"))
					address.port = boost::lexical_cast<int>(value);
			}
			m_Addresses.push_back(address);
		}
		// read peers
		uint8_t numPeers;
		s.read ((char *)&numPeers, sizeof (numPeers));
		s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
		// read properties
		uint16_t size, r = 0;
		s.read ((char *)&size, sizeof (size));
		size = be16toh (size);
		while (r < size)
		{
			char key[500], value[500];
			r += ReadString (key, s);
			s.seekg (1, std::ios_base::cur); r++; // =
			r += ReadString (value, s);
			s.seekg (1, std::ios_base::cur); r++; // ;
			m_Properties[key] = value;
		}

		CryptoPP::SHA256().CalculateDigest(m_IdentHash, (uint8_t *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		UpdateIdentHashBase64 ();
		UpdateRoutingKey ();
	}

	void RouterInfo::UpdateIdentHashBase64 ()
	{
		size_t l = i2p::data::ByteStreamToBase64 (m_IdentHash, 32, m_IdentHashBase64, 48);
		m_IdentHashBase64[l] = 0;
		memcpy (m_IdentHashAbbreviation, m_IdentHashBase64, 4);
		m_IdentHashAbbreviation[4] = 0;
	}

	void RouterInfo::UpdateRoutingKey ()
	{
		m_RoutingKey = CreateRoutingKey (m_IdentHash);
	}

	void RouterInfo::WriteToStream (std::ostream& s)
	{
		s.write ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		uint64_t ts = htobe64 (m_Timestamp);
		s.write ((char *)&ts, sizeof (ts));

		// addresses
		uint8_t numAddresses = m_Addresses.size ();
		s.write ((char *)&numAddresses, sizeof (numAddresses));
		for (auto& address : m_Addresses)
		{
			s.write ((char *)&address.cost, sizeof (address.cost));
			s.write ((char *)&address.date, sizeof (address.date));
			if (address.transportStyle == eTransportNTCP)
				WriteString ("NTCP", s);
			else if (address.transportStyle == eTransportSSU)
				WriteString ("SSU", s);
			else
				WriteString ("", s);

			std::stringstream properties;
			WriteString ("host", properties);
			properties << '=';
			WriteString (address.host.to_string (), properties);
			properties << ';';
			WriteString ("port", properties);
			properties << '=';
			WriteString (boost::lexical_cast<std::string>(address.port), properties);
			properties << ';';

			uint16_t size = htobe16 (properties.str ().size ());
			s.write ((char *)&size, sizeof (size));
			s.write (properties.str ().c_str (), properties.str ().size ());
		}

		// peers
		uint8_t numPeers = 0;
		s.write ((char *)&numPeers, sizeof (numPeers));

		// properties
		std::stringstream properties;
		for (auto& p : m_Properties)
		{
			WriteString (p.first, properties);
			properties << '=';
			WriteString (p.second, properties);
			properties << ';';
		}
		uint16_t size = htobe16 (properties.str ().size ());
		s.write ((char *)&size, sizeof (size));
		s.write (properties.str ().c_str (), properties.str ().size ());
	}

	void RouterInfo::CreateBuffer ()
	{
		m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); // refresh timstamp
		std::stringstream s;
		WriteToStream (s);
		m_BufferLen = s.str ().size ();
		memcpy (m_Buffer, s.str ().c_str (), m_BufferLen);
		// signature
		i2p::context.Sign ((uint8_t *)m_Buffer, m_BufferLen, (uint8_t *)m_Buffer + m_BufferLen);
		m_BufferLen += 40;
	}

	size_t RouterInfo::ReadString (char * str, std::istream& s)
	{
		uint8_t len;
		s.read ((char *)&len, 1);
		s.read (str, len);
		str[len] = 0;
		return len+1;
	}

	void RouterInfo::WriteString (const std::string& str, std::ostream& s)
	{
		uint8_t len = str.size ();
		s.write ((char *)&len, 1);
		s.write (str.c_str (), len);
	}

	void RouterInfo::AddNTCPAddress (const char * host, int port)
	{
		Address addr;
		addr.host = boost::asio::ip::address::from_string (host);
		addr.port = port;
		addr.transportStyle = eTransportNTCP;
		addr.cost = 2;
		addr.date = 0;
		m_Addresses.push_back(addr);
	}

	void RouterInfo::SetProperty (const char * key, const char * value)
	{
		m_Properties[key] = value;
	}

	const char * RouterInfo::GetProperty (const char * key) const
	{
		auto it = m_Properties.find (key);
		if (it != m_Properties.end ())
			return it->second.c_str ();
		return 0;
	}

	bool RouterInfo::IsFloodfill () const
	{
		const char * caps = GetProperty ("caps");
		if (caps)
			return strchr (caps, 'f');
		return false;
	}

	bool RouterInfo::IsNTCP (bool v4only) const
	{
		for (auto& address : m_Addresses)
		{
			if (address.transportStyle == eTransportNTCP)
			{
				if (!v4only || address.host.is_v4 ())
					return true;
			}
		}
		return false;
	}

	RouterInfo::Address * RouterInfo::GetNTCPAddress (bool v4only)
	{
		for (auto& address : m_Addresses)
		{
			if (address.transportStyle == eTransportNTCP)
			{
				if (!v4only || address.host.is_v4 ())
					return &address;
			}
		}
		return nullptr;
	}
}
}
<commit_msg>bigger buffer size temporary for win32<commit_after>#include <stdio.h>
#include <string.h>
#include "I2PEndian.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "base64.h"
#include "Timestamp.h"
#include "Log.h"
#include "RouterInfo.h"
#include "RouterContext.h"

namespace i2p
{
namespace data
{
	RouterInfo::RouterInfo (const char * filename):
		m_IsUpdated (false), m_IsUnreachable (false)
	{
		ReadFromFile (filename);
	}

	RouterInfo::RouterInfo (const uint8_t * buf, int len):
		m_IsUpdated (true)
	{
		memcpy (m_Buffer, buf, len);
		m_BufferLen = len;
		ReadFromBuffer ();
	}

	void RouterInfo::SetRouterIdentity (const Identity& identity)
	{
		m_RouterIdentity = identity;
		m_IdentHash = CalculateIdentHash (m_RouterIdentity);
		UpdateIdentHashBase64 ();
		UpdateRoutingKey ();
		m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
	}

	void RouterInfo::ReadFromFile (const char * filename)
	{
		std::ifstream s(filename, std::ifstream::binary);
		if (s.is_open ())
		{
			s.seekg (0,std::ios::end);
			m_BufferLen = s.tellg ();
			s.seekg(0, std::ios::beg);
			s.read(m_Buffer,m_BufferLen);
			ReadFromBuffer ();
		}
		else
			LogPrint ("Can't open file ", filename);
	}

	void RouterInfo::ReadFromBuffer ()
	{
		std::stringstream str (std::string (m_Buffer, m_BufferLen));
		ReadFromStream (str);
		// verify signature
		CryptoPP::DSA::PublicKey pubKey;
		pubKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag, CryptoPP::Integer (m_RouterIdentity.signingKey, 128));
		CryptoPP::DSA::Verifier verifier (pubKey);
		int l = m_BufferLen - 40;
		if (!verifier.VerifyMessage ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l, 40))
		{
			LogPrint ("signature verification failed");
		}
	}

	void RouterInfo::ReadFromStream (std::istream& s)
	{
		s.read ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
		m_Timestamp = be64toh (m_Timestamp);
		// read addresses
		uint8_t numAddresses;
		s.read ((char *)&numAddresses, sizeof (numAddresses));
		for (int i = 0; i < numAddresses; i++)
		{
			Address address;
			s.read ((char *)&address.cost, sizeof (address.cost));
			s.read ((char *)&address.date, sizeof (address.date));
			char transportStyle[5];
			ReadString (transportStyle, s);
			if (!strcmp (transportStyle, "NTCP"))
				address.transportStyle = eTransportNTCP;
			else if (!strcmp (transportStyle, "SSU"))
				address.transportStyle = eTransportSSU;
			else
				address.transportStyle = eTransportUnknown;
			uint16_t size, r = 0;
			s.read ((char *)&size, sizeof (size));
			size = be16toh (size);
			while (r < size)
			{
				char key[500], value[500];
				r += ReadString (key, s);
				s.seekg (1, std::ios_base::cur); r++; // =
				r += ReadString (value, s);
				s.seekg (1, std::ios_base::cur); r++; // ;
				if (!strcmp (key, "host"))
				{
					boost::system::error_code ecode;
					address.host = boost::asio::ip::address::from_string (value, ecode);
					if (ecode)
					{
						// TODO: we should try to resolve address here
						LogPrint ("Unexpected address ", value);
						SetUnreachable (true);
					}
				}
				else if (!strcmp (key, "port"))
					address.port = boost::lexical_cast<int>(value);
			}
			m_Addresses.push_back(address);
		}
		// read peers
		uint8_t numPeers;
		s.read ((char *)&numPeers, sizeof (numPeers));
		s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
		// read properties
		uint16_t size, r = 0;
		s.read ((char *)&size, sizeof (size));
		size = be16toh (size);
		while (r < size)
		{
#ifdef _WIN32
			char key[500], value[500];
			// TODO: investigate why properties get read as one long string under Windows
			// length should not be more than 44
#else
			char key[50], value[50];
#endif
			r += ReadString (key, s);
			s.seekg (1, std::ios_base::cur); r++; // =
			r += ReadString (value, s);
			s.seekg (1, std::ios_base::cur); r++; // ;
			m_Properties[key] = value;
		}

		CryptoPP::SHA256().CalculateDigest(m_IdentHash, (uint8_t *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		UpdateIdentHashBase64 ();
		UpdateRoutingKey ();
	}

	void RouterInfo::UpdateIdentHashBase64 ()
	{
		size_t l = i2p::data::ByteStreamToBase64 (m_IdentHash, 32, m_IdentHashBase64, 48);
		m_IdentHashBase64[l] = 0;
		memcpy (m_IdentHashAbbreviation, m_IdentHashBase64, 4);
		m_IdentHashAbbreviation[4] = 0;
	}

	void RouterInfo::UpdateRoutingKey ()
	{
		m_RoutingKey = CreateRoutingKey (m_IdentHash);
	}

	void RouterInfo::WriteToStream (std::ostream& s)
	{
		s.write ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
		uint64_t ts = htobe64 (m_Timestamp);
		s.write ((char *)&ts, sizeof (ts));

		// addresses
		uint8_t numAddresses = m_Addresses.size ();
		s.write ((char *)&numAddresses, sizeof (numAddresses));
		for (auto& address : m_Addresses)
		{
			s.write ((char *)&address.cost, sizeof (address.cost));
			s.write ((char *)&address.date, sizeof (address.date));
			if (address.transportStyle == eTransportNTCP)
				WriteString ("NTCP", s);
			else if (address.transportStyle == eTransportSSU)
				WriteString ("SSU", s);
			else
				WriteString ("", s);

			std::stringstream properties;
			WriteString ("host", properties);
			properties << '=';
			WriteString (address.host.to_string (), properties);
			properties << ';';
			WriteString ("port", properties);
			properties << '=';
			WriteString (boost::lexical_cast<std::string>(address.port), properties);
			properties << ';';

			uint16_t size = htobe16 (properties.str ().size ());
			s.write ((char *)&size, sizeof (size));
			s.write (properties.str ().c_str (), properties.str ().size ());
		}

		// peers
		uint8_t numPeers = 0;
		s.write ((char *)&numPeers, sizeof (numPeers));

		// properties
		std::stringstream properties;
		for (auto& p : m_Properties)
		{
			WriteString (p.first, properties);
			properties << '=';
			WriteString (p.second, properties);
			properties << ';';
		}
		uint16_t size = htobe16 (properties.str ().size ());
		s.write ((char *)&size, sizeof (size));
		s.write (properties.str ().c_str (), properties.str ().size ());
	}

	void RouterInfo::CreateBuffer ()
	{
		m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); // refresh timstamp
		std::stringstream s;
		WriteToStream (s);
		m_BufferLen = s.str ().size ();
		memcpy (m_Buffer, s.str ().c_str (), m_BufferLen);
		// signature
		i2p::context.Sign ((uint8_t *)m_Buffer, m_BufferLen, (uint8_t *)m_Buffer + m_BufferLen);
		m_BufferLen += 40;
	}

	size_t RouterInfo::ReadString (char * str, std::istream& s)
	{
		uint8_t len;
		s.read ((char *)&len, 1);
		s.read (str, len);
		str[len] = 0;
		return len+1;
	}

	void RouterInfo::WriteString (const std::string& str, std::ostream& s)
	{
		uint8_t len = str.size ();
		s.write ((char *)&len, 1);
		s.write (str.c_str (), len);
	}

	void RouterInfo::AddNTCPAddress (const char * host, int port)
	{
		Address addr;
		addr.host = boost::asio::ip::address::from_string (host);
		addr.port = port;
		addr.transportStyle = eTransportNTCP;
		addr.cost = 2;
		addr.date = 0;
		m_Addresses.push_back(addr);
	}

	void RouterInfo::SetProperty (const char * key, const char * value)
	{
		m_Properties[key] = value;
	}

	const char * RouterInfo::GetProperty (const char * key) const
	{
		auto it = m_Properties.find (key);
		if (it != m_Properties.end ())
			return it->second.c_str ();
		return 0;
	}

	bool RouterInfo::IsFloodfill () const
	{
		const char * caps = GetProperty ("caps");
		if (caps)
			return strchr (caps, 'f');
		return false;
	}

	bool RouterInfo::IsNTCP (bool v4only) const
	{
		for (auto& address : m_Addresses)
		{
			if (address.transportStyle == eTransportNTCP)
			{
				if (!v4only || address.host.is_v4 ())
					return true;
			}
		}
		return false;
	}

	RouterInfo::Address * RouterInfo::GetNTCPAddress (bool v4only)
	{
		for (auto& address : m_Addresses)
		{
			if (address.transportStyle == eTransportNTCP)
			{
				if (!v4only || address.host.is_v4 ())
					return &address;
			}
		}
		return nullptr;
	}
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 CNRS
// Authors: Joseph Mirabel
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_SPLINE_HH
# define HPP_CORE_PATH_SPLINE_HH

# include <hpp/core/path.hh>

# include <hpp/pinocchio/device.hh>

# include <hpp/constraints/matrix-view.hh>

# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>

namespace hpp {
  namespace core {
    namespace path {
      /// \addtogroup path
      /// \{

      enum PolynomeBasisType {
        CanonicalPolynomeBasis,
        BernsteinBasis
      };

      /// \cond
      namespace internal {
        template <int SplineType, int Degree> struct spline_basis_function;
        template <int SplineType, int Degree> struct sbf_traits {
          enum { NbCoeffs = Degree + 1 };
          typedef Eigen::Matrix<value_type, NbCoeffs, 1> Coeffs_t;
          typedef Eigen::Matrix<value_type, NbCoeffs, NbCoeffs> IntegralCoeffs_t;
        };
      }
      /// \endcond

      /// Base class for spline paths
      template <int _PolynomeBasis, int _Order>
      class HPP_CORE_DLLAPI Spline : public Path
      {
        public:
          enum {
            PolynomeBasis = _PolynomeBasis,
            Order = _Order,
            NbCoeffs = _Order + 1,
            NbPowerOfT = 2 * NbCoeffs + 1
          };

          typedef internal::sbf_traits<PolynomeBasis, Order> sbf_traits;
          typedef internal::spline_basis_function<PolynomeBasis, Order> BasisFunction_t;
          typedef Eigen::Matrix<value_type, NbPowerOfT, 1> PowersOfT_t;
          typedef typename sbf_traits::Coeffs_t BasisFunctionVector_t;
          typedef typename sbf_traits::IntegralCoeffs_t BasisFunctionIntegralMatrix_t;

          typedef Eigen::Matrix<value_type, NbCoeffs, Eigen::Dynamic, Eigen::RowMajor> ParameterMatrix_t;
          typedef Eigen::Map<const vector_t, Eigen::Aligned> ConstParameterVector_t;
          typedef Eigen::Map<      vector_t, Eigen::Aligned>      ParameterVector_t;

          typedef boost::shared_ptr<Spline> Ptr_t;
          typedef boost::weak_ptr<Spline> WkPtr_t;

          size_type parameterSize () const
          {
            return parameterSize_;
          }

          /** The partial derivative with respects to the parameters is of the form
          /// \f{eqnarray*}{
          /// \frac{\partial S}{\partial p_{k}} (q, p, t)    &=& B_k(t) \times I \\
          /// \frac{\partial S}{\partial q_{base}} (q, p, t) &=& I
          /// \f}
          /// This method returns the coefficients \f$ (B_k(t))_{k} \f$
          **/
          void parameterDerivativeCoefficients (vectorOut_t res, const value_type& t) const
          {
            assert (res.size() == NbCoeffs);
            impl_paramDerivative (res, t);
          }

          void parameterIntegrate (vectorIn_t dParam)
          {
            assert (dParam.size() == NbCoeffs * parameterSize_);
            impl_paramIntegrate (dParam);
          }

          value_type squaredNormIntegral (const size_type order);

          void squaredNormIntegralDerivative (const size_type order, vectorOut_t res);

          void basisFunctionDerivative (const size_type order, const value_type& u, BasisFunctionVector_t& res) const;

          void basisFunctionDerivative (const size_type order, const value_type& u, vectorOut_t res) const
          {
            assert (res.size() == NbCoeffs);
            BasisFunctionVector_t tmp;
            basisFunctionDerivative(order, u, tmp);
            res = tmp;
          }

          void maxVelocity (vectorOut_t res) const;

          void squaredNormBasisFunctionIntegral (const size_type order, BasisFunctionIntegralMatrix_t& res) const;

          void squaredNormBasisFunctionIntegral (const size_type order, matrixOut_t res) const
          {
            // assert (res.size() == NbCoeffs);
            BasisFunctionIntegralMatrix_t tmp;
            squaredNormBasisFunctionIntegral (order, tmp);
            res = tmp;
          }

          Configuration_t initial () const
          {
            Configuration_t q (outputSize());
            bool res = operator() (q, timeRange().first);
            assert(res);
            return q;
          }

          Configuration_t end () const
          {
            Configuration_t q (outputSize());
            bool res = operator() (q, timeRange().second);
            assert(res);
            return q;
          }

          const Configuration_t& base () const
          {
            return base_;
          }

          void base (const Configuration_t& q)
          {
            base_ = q;
          }

          /// Each row corresponds to a velocity of the robot.
          const ParameterMatrix_t& parameters () const
          {
            return parameters_;
          }

          void parameters (const ParameterMatrix_t& m)
          {
            parameters_ = m;
          }

          ConstParameterVector_t rowParameters () const
          {
            return ConstParameterVector_t (parameters_.data(), parameters_.size());
          }

          void rowParameters (vectorIn_t p)
          {
            ParameterVector_t(parameters_.data(), parameters_.size()) = p;
          }

          PathPtr_t copy () const
          {
            Ptr_t other (new Spline (*this));
            other->initCopy(other);
            return other;
          }

          PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
          {
            Ptr_t other (new Spline (*this, constraints));
            other->initCopy(other);
            return other;
          }

          virtual ~Spline () throw () {}

          static Ptr_t create (const DevicePtr_t& robot,
              const interval_t& interval,
              const ConstraintSetPtr_t& constraints)
          {
            Ptr_t shPtr (new Spline(robot, interval, constraints));
            shPtr->init(shPtr);
            return shPtr;
          }

        protected:
          Spline (const DevicePtr_t& robot,
              const interval_t& interval,
              const ConstraintSetPtr_t& constraints)
            : Path (interval, robot->configSize(), robot->numberDof(), constraints),
            parameterSize_ (robot->numberDof()),
            robot_ (robot),
            base_ (outputSize()),
            parameters_ ((int)NbCoeffs, parameterSize_)
          {
            powersOfT_(0) = 1;
            for (size_type i = 1; i < NbPowerOfT; ++i)
              powersOfT_(i) = powersOfT_(i - 1) * length();
          }

          Spline (const Spline& path);

          Spline (const Spline& path, const ConstraintSetPtr_t& constraints);

          void init (const Ptr_t& self) { Path::init(self); weak_ = self; }

          void initCopy (const Ptr_t& self) { Path::initCopy(self); weak_ = self; }

          std::ostream& print (std::ostream &os) const;

          bool impl_compute (ConfigurationOut_t configuration, value_type t) const;

          void impl_derivative (vectorOut_t res, const value_type& t, size_type order) const;

          void impl_paramDerivative (vectorOut_t res, const value_type& t) const;

          void impl_paramIntegrate (vectorIn_t dParam);

          size_type parameterSize_;
          DevicePtr_t robot_;
          Configuration_t base_;
          ParameterMatrix_t parameters_;

        private:
          WkPtr_t weak_;

          mutable vector_t velocity_;
          mutable PowersOfT_t powersOfT_;
      }; // class Spline
      /// \}
    } //   namespace path
  } //   namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_SPLINE_HH
<commit_msg>Remove compilation warning in release mode.<commit_after>// Copyright (c) 2017 CNRS
// Authors: Joseph Mirabel
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_SPLINE_HH
# define HPP_CORE_PATH_SPLINE_HH

# include <hpp/core/path.hh>

# include <hpp/pinocchio/device.hh>

# include <hpp/constraints/matrix-view.hh>

# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>

namespace hpp {
  namespace core {
    namespace path {
      /// \addtogroup path
      /// \{

      enum PolynomeBasisType {
        CanonicalPolynomeBasis,
        BernsteinBasis
      };

      /// \cond
      namespace internal {
        template <int SplineType, int Degree> struct spline_basis_function;
        template <int SplineType, int Degree> struct sbf_traits {
          enum { NbCoeffs = Degree + 1 };
          typedef Eigen::Matrix<value_type, NbCoeffs, 1> Coeffs_t;
          typedef Eigen::Matrix<value_type, NbCoeffs, NbCoeffs> IntegralCoeffs_t;
        };
      }
      /// \endcond

      /// Base class for spline paths
      template <int _PolynomeBasis, int _Order>
      class HPP_CORE_DLLAPI Spline : public Path
      {
        public:
          enum {
            PolynomeBasis = _PolynomeBasis,
            Order = _Order,
            NbCoeffs = _Order + 1,
            NbPowerOfT = 2 * NbCoeffs + 1
          };

          typedef internal::sbf_traits<PolynomeBasis, Order> sbf_traits;
          typedef internal::spline_basis_function<PolynomeBasis, Order> BasisFunction_t;
          typedef Eigen::Matrix<value_type, NbPowerOfT, 1> PowersOfT_t;
          typedef typename sbf_traits::Coeffs_t BasisFunctionVector_t;
          typedef typename sbf_traits::IntegralCoeffs_t BasisFunctionIntegralMatrix_t;

          typedef Eigen::Matrix<value_type, NbCoeffs, Eigen::Dynamic, Eigen::RowMajor> ParameterMatrix_t;
          typedef Eigen::Map<const vector_t, Eigen::Aligned> ConstParameterVector_t;
          typedef Eigen::Map<      vector_t, Eigen::Aligned>      ParameterVector_t;

          typedef boost::shared_ptr<Spline> Ptr_t;
          typedef boost::weak_ptr<Spline> WkPtr_t;

          size_type parameterSize () const
          {
            return parameterSize_;
          }

          /** The partial derivative with respects to the parameters is of the form
          /// \f{eqnarray*}{
          /// \frac{\partial S}{\partial p_{k}} (q, p, t)    &=& B_k(t) \times I \\
          /// \frac{\partial S}{\partial q_{base}} (q, p, t) &=& I
          /// \f}
          /// This method returns the coefficients \f$ (B_k(t))_{k} \f$
          **/
          void parameterDerivativeCoefficients (vectorOut_t res, const value_type& t) const
          {
            assert (res.size() == NbCoeffs);
            impl_paramDerivative (res, t);
          }

          void parameterIntegrate (vectorIn_t dParam)
          {
            assert (dParam.size() == NbCoeffs * parameterSize_);
            impl_paramIntegrate (dParam);
          }

          value_type squaredNormIntegral (const size_type order);

          void squaredNormIntegralDerivative (const size_type order, vectorOut_t res);

          void basisFunctionDerivative (const size_type order, const value_type& u, BasisFunctionVector_t& res) const;

          void basisFunctionDerivative (const size_type order, const value_type& u, vectorOut_t res) const
          {
            assert (res.size() == NbCoeffs);
            BasisFunctionVector_t tmp;
            basisFunctionDerivative(order, u, tmp);
            res = tmp;
          }

          void maxVelocity (vectorOut_t res) const;

          void squaredNormBasisFunctionIntegral (const size_type order, BasisFunctionIntegralMatrix_t& res) const;

          void squaredNormBasisFunctionIntegral (const size_type order, matrixOut_t res) const
          {
            // assert (res.size() == NbCoeffs);
            BasisFunctionIntegralMatrix_t tmp;
            squaredNormBasisFunctionIntegral (order, tmp);
            res = tmp;
          }

          Configuration_t initial () const
          {
            Configuration_t q (outputSize());
            bool res = operator() (q, timeRange().first);
            assert(res); (void)res;
            return q;
          }

          Configuration_t end () const
          {
            Configuration_t q (outputSize());
            bool res = operator() (q, timeRange().second);
            assert(res); (void)res;
            return q;
          }

          const Configuration_t& base () const
          {
            return base_;
          }

          void base (const Configuration_t& q)
          {
            base_ = q;
          }

          /// Each row corresponds to a velocity of the robot.
          const ParameterMatrix_t& parameters () const
          {
            return parameters_;
          }

          void parameters (const ParameterMatrix_t& m)
          {
            parameters_ = m;
          }

          ConstParameterVector_t rowParameters () const
          {
            return ConstParameterVector_t (parameters_.data(), parameters_.size());
          }

          void rowParameters (vectorIn_t p)
          {
            ParameterVector_t(parameters_.data(), parameters_.size()) = p;
          }

          PathPtr_t copy () const
          {
            Ptr_t other (new Spline (*this));
            other->initCopy(other);
            return other;
          }

          PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
          {
            Ptr_t other (new Spline (*this, constraints));
            other->initCopy(other);
            return other;
          }

          virtual ~Spline () throw () {}

          static Ptr_t create (const DevicePtr_t& robot,
              const interval_t& interval,
              const ConstraintSetPtr_t& constraints)
          {
            Ptr_t shPtr (new Spline(robot, interval, constraints));
            shPtr->init(shPtr);
            return shPtr;
          }

        protected:
          Spline (const DevicePtr_t& robot,
              const interval_t& interval,
              const ConstraintSetPtr_t& constraints)
            : Path (interval, robot->configSize(), robot->numberDof(), constraints),
            parameterSize_ (robot->numberDof()),
            robot_ (robot),
            base_ (outputSize()),
            parameters_ ((int)NbCoeffs, parameterSize_)
          {
            powersOfT_(0) = 1;
            for (size_type i = 1; i < NbPowerOfT; ++i)
              powersOfT_(i) = powersOfT_(i - 1) * length();
          }

          Spline (const Spline& path);

          Spline (const Spline& path, const ConstraintSetPtr_t& constraints);

          void init (const Ptr_t& self) { Path::init(self); weak_ = self; }

          void initCopy (const Ptr_t& self) { Path::initCopy(self); weak_ = self; }

          std::ostream& print (std::ostream &os) const;

          bool impl_compute (ConfigurationOut_t configuration, value_type t) const;

          void impl_derivative (vectorOut_t res, const value_type& t, size_type order) const;

          void impl_paramDerivative (vectorOut_t res, const value_type& t) const;

          void impl_paramIntegrate (vectorIn_t dParam);

          size_type parameterSize_;
          DevicePtr_t robot_;
          Configuration_t base_;
          ParameterMatrix_t parameters_;

        private:
          WkPtr_t weak_;

          mutable vector_t velocity_;
          mutable PowersOfT_t powersOfT_;
      }; // class Spline
      /// \}
    } //   namespace path
  } //   namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_SPLINE_HH
<|endoftext|>


<commit_before>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#ifndef HTTPP_HTTP_PROTOCOL_HPP_
# define HTTPP_HTTP_PROTOCOL_HPP_

# include <string>

namespace HTTPP
{
namespace HTTP
{

using KV = std::pair<std::string, std::string>;
using Header = KV;

static char const HEADER_BODY_SEP[] = { '\r', '\n', '\r', '\n' };

enum class Method
{
    HEAD,
    GET,
    POST,
    PUT,
    DELETE_, // '_' for msvc workaround
    OPTIONS,
    TRACE,
    CONNECT
};

std::string to_string(Method method);

enum class HttpCode : unsigned int
{
    Continue = 100,

    Ok = 200,
    Created = 201,
    Accepted = 202,
    NoContent = 204,

    MultipleChoice = 300,
    MovedPermentaly = 301,
    MovedTemporarily = 302,
    NotModified = 304,

    BadRequest = 400,
    Unauthorized = 401,
    Forbidden = 403,
    NotFound = 404,

    InternalServerError = 500,
    NotImplemented = 501,
    BadGateway = 502,
    ServiceUnavailable = 503,
    HttpVersionNotSupported = 505
};

std::string getDefaultMessage(HttpCode code);

} // namespace HTTP
} // namespace HTTPP

#endif // !HTTPP_HTTP_PROTOCOL_HPP_

<commit_msg>Add Http code<commit_after>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#ifndef HTTPP_HTTP_PROTOCOL_HPP_
# define HTTPP_HTTP_PROTOCOL_HPP_

# include <string>

namespace HTTPP
{
namespace HTTP
{

using KV = std::pair<std::string, std::string>;
using Header = KV;

static char const HEADER_BODY_SEP[] = { '\r', '\n', '\r', '\n' };

enum class Method
{
    HEAD,
    GET,
    POST,
    PUT,
    DELETE_, // '_' for msvc workaround
    OPTIONS,
    TRACE,
    CONNECT
};

std::string to_string(Method method);

enum class HttpCode : unsigned int
{
    Continue = 100,

    Ok = 200,
    Created = 201,
    Accepted = 202,
    NoContent = 204,

    MultipleChoice = 300,
    MovedPermentaly = 301,
    MovedTemporarily = 302,
    NotModified = 304,

    BadRequest = 400,
    Unauthorized = 401,
    Forbidden = 403,
    NotFound = 404,

    InternalServerError = 500,
    NotImplemented = 501,
    BadGateway = 502,
    ServiceUnavailable = 503,
    GatewayTimeOut = 504,
    HttpVersionNotSupported = 505
};

std::string getDefaultMessage(HttpCode code);

} // namespace HTTP
} // namespace HTTPP

#endif // !HTTPP_HTTP_PROTOCOL_HPP_

<|endoftext|>


<commit_before>#ifndef __BIGNUMS_HH_
#define __BIGNUMS_HH_

/// Extra support for bignums
#include <ikos_domains/bignums.hpp>

namespace llvm_ikos
{
  using namespace ikos;

  std::string toStr (z_number n)
  {
    std::ostringstream s;
    s << n;
    return s.str ();
  }

}

#endif
<commit_msg>[FIX] mark toStr() inline<commit_after>#ifndef __BIGNUMS_HH_
#define __BIGNUMS_HH_

/// Extra support for bignums
#include <ikos_domains/bignums.hpp>

namespace llvm_ikos
{
  using namespace ikos;

  inline std::string toStr (z_number n)
  {
    std::ostringstream s;
    s << n;
    return s.str ();
  }

}

#endif
<|endoftext|>