<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAffineTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>

#include "itkAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Matrix<double,2,2>   MatrixType;
typedef  itk::Vector<double,2>     VectorType;

namespace
{

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::Dimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}
}

int itkAffineTransformTest(int, char *[])
{

    int any = 0;       // Any errors detected in testing?

    MatrixType                   matrix2;
    MatrixType                   inverse2;
    VectorType                   vector2;

    unsigned int i, j;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */

    /* Create a 2D identity transformation and show its parameters */
    typedef itk::Point<double,12> ParametersType;
    typedef itk::Matrix<double,2,12> JacobianType;

    typedef itk::AffineTransform<double,2> Affine2DType;
    Affine2DType::Pointer id2 = Affine2DType::New();
    matrix2 = id2->GetMatrix();
    vector2 = id2->GetOffset();
    std::cout << "Matrix from instantiating an identity transform:"
              << std::endl << matrix2;
    std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    matrix2[0][0] = 1;
    matrix2[0][1] = 2;
    matrix2[1][0] = 3;
    matrix2[1][1] = 4;
    vector2[0] = 5;
    vector2[1] = 6;

    Affine2DType::Pointer aff2 = Affine2DType::New();
    aff2->SetMatrix( matrix2 );
    aff2->SetOffset( vector2 );
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:" << std::endl;
    aff2->Print( std::cout );

    inverse2 = aff2->GetInverseMatrix();
    std::cout << "Inverse matrix for the given transform:"
              << std::endl << inverse2;

    /* Set parameters of a 2D transform */
    matrix2[0][0] = 6;
    matrix2[0][1] = 5;
    matrix2[1][0] = 4;
    matrix2[1][1] = 3;
    vector2[0] = 2;
    vector2[1] = 1;
    aff2->SetMatrix(matrix2);
    aff2->SetOffset(vector2);
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    matrix2 = aff2->GetMatrix();
    vector2 = aff2->GetOffset();
    std::cout << "Setting the matrix in an existing transform:"
              << std::endl << matrix2;
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2->Compose( aff2 );
    std::cout << "Result of a composition:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2->Translate(trans);
    std::cout << "Result of a translation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an isotropic scaling */
    aff2->Scale(.3, 1);
    std::cout << "Result of isotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an anisotropic scaling */
    VectorType scale;
    scale[0] = .3;
    scale[1] = .2;
    aff2->Scale(scale);
    std::cout << "Result of anisotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a general N-D rotation */
    aff2->Rotate(0, 1, 0.57, 1);
    std::cout << "Result of general rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a 2-D rotation */
    aff2->Rotate(0, 1, -0.57, 1);
    std::cout << "Result of 2-D rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a shear */
    aff2->Shear(1, 0, .2);
    std::cout << "Result of shear:" << std::endl;
    aff2->Print( std::cout );

    /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2->TransformPoint(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Back transform a point */
    v2 = aff2->BackTransform(u2);
    std::cout << "Back transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2->TransformVector(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Back transform a vector */
    y2 = aff2->BackTransform(x2);
    std::cout << "Back transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2->TransformVector(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Back transform a vector */
    v3 = aff2->BackTransform(u3);
    std::cout << "Back transform a vector :" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2->TransformVector(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Back transform a vector */
    v4 = aff2->BackTransform(u4);
    std::cout << "Back transform a vector :" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Create a 3D transform and rotate in 3D */
    typedef itk::AffineTransform<double,3> Affine3DType;
    Affine3DType::Pointer aff3 = Affine3DType::New();
    itk::Vector<double,3> axis;
    axis[0] = .707;
    axis[1] = .707;
    axis[2] = .707;
    aff3->Rotate3D(axis, 1.0, 1);
    std::cout << "Create and rotate a 3D transform:" << std::endl;
    aff3->Print( std::cout );

    /* Generate inverse transform */
    Affine3DType::Pointer inv3 = Affine3DType::New();
    if(!aff3->GetInverse(inv3))
      {
      std::cout << "Cannot compute inverse transformation" << std::endl;
      return EXIT_FAILURE;
      }
    std::cout << "Create an inverse transformation:" << std::endl;
    inv3->Print( std::cout );

    /* Test output of GetJacobian */
    Affine3DType::Pointer jaff = Affine3DType::New();
    Affine3DType::MatrixType jaffMatrix = jaff->GetMatrix();
    Affine3DType::OffsetType jaffVector = jaff->GetOffset();

    Affine3DType::InputPointType jpoint;
    jpoint[0] = 5.0;
    jpoint[1] = 10.0;
    jpoint[2] = 15.0;
    Affine3DType::JacobianType jaffJacobian = jaff->GetJacobian( jpoint );

    std::cout << "GetJacobian: " << std::endl;
    std::cout << jaffJacobian << std::endl;

    /* Test SetParameters */
    Affine3DType::Pointer paff = Affine3DType::New();
    Affine3DType::ParametersType parameters( paff->GetNumberOfParameters() );

    /* set up a 3x3 magic square matrix */
    parameters[0] = 8;
    parameters[1] = 1;
    parameters[2] = 6;
    parameters[3] = 3;
    parameters[4] = 5;
    parameters[5] = 7;
    parameters[6] = 4;
    parameters[7] = 9;
    parameters[8] = 2;

    parameters[9] = 5;
    parameters[10] = 5;
    parameters[11] = 5;

    paff->Print( std::cout );
    paff->SetParameters( parameters );
    paff->Print( std::cout );

    paff->SetIdentity();
    paff->Print( std::cout );
    return any;
}
<commit_msg>BUG: Commented-out tests of deprecated member functions<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAffineTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>

#include "itkAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Matrix<double,2,2>   MatrixType;
typedef  itk::Vector<double,2>     VectorType;

namespace
{

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::Dimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}
}

int itkAffineTransformTest(int, char *[])
{

    int any = 0;       // Any errors detected in testing?

    MatrixType                   matrix2;
    MatrixType                   inverse2;
    VectorType                   vector2;

    unsigned int i, j;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */

    /* Create a 2D identity transformation and show its parameters */
    typedef itk::Point<double,12> ParametersType;
    typedef itk::Matrix<double,2,12> JacobianType;

    typedef itk::AffineTransform<double,2> Affine2DType;
    Affine2DType::Pointer id2 = Affine2DType::New();
    matrix2 = id2->GetMatrix();
    vector2 = id2->GetOffset();
    std::cout << "Matrix from instantiating an identity transform:"
              << std::endl << matrix2;
    std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    matrix2[0][0] = 1;
    matrix2[0][1] = 2;
    matrix2[1][0] = 3;
    matrix2[1][1] = 4;
    vector2[0] = 5;
    vector2[1] = 6;

    Affine2DType::Pointer aff2 = Affine2DType::New();
    aff2->SetMatrix( matrix2 );
    aff2->SetOffset( vector2 );
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:" << std::endl;
    aff2->Print( std::cout );

    inverse2 = aff2->GetInverseMatrix();
    std::cout << "Inverse matrix for the given transform:"
              << std::endl << inverse2;

    /* Set parameters of a 2D transform */
    matrix2[0][0] = 6;
    matrix2[0][1] = 5;
    matrix2[1][0] = 4;
    matrix2[1][1] = 3;
    vector2[0] = 2;
    vector2[1] = 1;
    aff2->SetMatrix(matrix2);
    aff2->SetOffset(vector2);
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    matrix2 = aff2->GetMatrix();
    vector2 = aff2->GetOffset();
    std::cout << "Setting the matrix in an existing transform:"
              << std::endl << matrix2;
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2->Compose( aff2 );
    std::cout << "Result of a composition:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2->Translate(trans);
    std::cout << "Result of a translation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an isotropic scaling */
    aff2->Scale(.3, 1);
    std::cout << "Result of isotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an anisotropic scaling */
    VectorType scale;
    scale[0] = .3;
    scale[1] = .2;
    aff2->Scale(scale);
    std::cout << "Result of anisotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a general N-D rotation */
    aff2->Rotate(0, 1, 0.57, 1);
    std::cout << "Result of general rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a 2-D rotation */
    aff2->Rotate(0, 1, -0.57, 1);
    std::cout << "Result of 2-D rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a shear */
    aff2->Shear(1, 0, .2);
    std::cout << "Result of shear:" << std::endl;
    aff2->Print( std::cout );

    /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2->TransformPoint(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Back transform a point */
    //v2 = aff2->BackTransform(u2);
    //std::cout << "Back transform a point:" << std::endl
              //<< v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2->TransformVector(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Back transform a vector */
    //y2 = aff2->BackTransform(x2);
    //std::cout << "Back transform a vnl_vector:" << std::endl
              //<< y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2->TransformVector(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Back transform a vector */
    //v3 = aff2->BackTransform(u3);
    //std::cout << "Back transform a vector :" << std::endl
              //<< v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2->TransformVector(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Back transform a vector */
    //v4 = aff2->BackTransform(u4);
    //std::cout << "Back transform a vector :" << std::endl
              //<< v4[0] << " , " << v4[1] << std::endl;

    /* Create a 3D transform and rotate in 3D */
    typedef itk::AffineTransform<double,3> Affine3DType;
    Affine3DType::Pointer aff3 = Affine3DType::New();
    itk::Vector<double,3> axis;
    axis[0] = .707;
    axis[1] = .707;
    axis[2] = .707;
    aff3->Rotate3D(axis, 1.0, 1);
    std::cout << "Create and rotate a 3D transform:" << std::endl;
    aff3->Print( std::cout );

    /* Generate inverse transform */
    Affine3DType::Pointer inv3 = Affine3DType::New();
    if(!aff3->GetInverse(inv3))
      {
      std::cout << "Cannot compute inverse transformation" << std::endl;
      return EXIT_FAILURE;
      }
    std::cout << "Create an inverse transformation:" << std::endl;
    inv3->Print( std::cout );

    /* Test output of GetJacobian */
    Affine3DType::Pointer jaff = Affine3DType::New();
    Affine3DType::MatrixType jaffMatrix = jaff->GetMatrix();
    Affine3DType::OffsetType jaffVector = jaff->GetOffset();

    Affine3DType::InputPointType jpoint;
    jpoint[0] = 5.0;
    jpoint[1] = 10.0;
    jpoint[2] = 15.0;
    Affine3DType::JacobianType jaffJacobian = jaff->GetJacobian( jpoint );

    std::cout << "GetJacobian: " << std::endl;
    std::cout << jaffJacobian << std::endl;

    /* Test SetParameters */
    Affine3DType::Pointer paff = Affine3DType::New();
    Affine3DType::ParametersType parameters( paff->GetNumberOfParameters() );

    /* set up a 3x3 magic square matrix */
    parameters[0] = 8;
    parameters[1] = 1;
    parameters[2] = 6;
    parameters[3] = 3;
    parameters[4] = 5;
    parameters[5] = 7;
    parameters[6] = 4;
    parameters[7] = 9;
    parameters[8] = 2;

    parameters[9] = 5;
    parameters[10] = 5;
    parameters[11] = 5;

    paff->Print( std::cout );
    paff->SetParameters( parameters );
    paff->Print( std::cout );

    paff->SetIdentity();
    paff->Print( std::cout );
    return any;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSpatialFunctionTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <stdio.h>

// Spatial function stuff
#include "itkSphereSpatialFunction.h"

int itkSpatialFunctionTest(int, char* [] )
{
  // Change this parameter (and the positions, below) to work in higher or lower dimensions
  const unsigned int dim = 3;

  //---------Create and initialize a spatial function-----------

  typedef itk::SphereSpatialFunction<dim> TFunctionType;
  typedef TFunctionType::InputType TFunctionPositionType;

  // Create and initialize a new sphere function

  TFunctionType::Pointer spatialFunc = TFunctionType::New();
  spatialFunc->SetRadius( 5 );

  TFunctionPositionType center;
  center[0]=10;
  center[1]=10;
  center[2]=10;
  spatialFunc->SetCenter(center);

  std::cout << "Sphere spatial function created\n";

  //----------------Test evaluation of funtion------------------

  // We're going to evaluate it at the center of the sphere (10,10,10)
  bool funcVal = spatialFunc->Evaluate(center);
  printf("Sphere function value is %i\n", funcVal);

  // The function should have returned a value of 1, since the center is inside
  // the sphere
  if(funcVal == 1)
    return EXIT_SUCCESS;
  else
    return EXIT_FAILURE;
}

<commit_msg>ENH: Improved coverage for Get/Set macros<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSpatialFunctionTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <stdio.h>

// Spatial function stuff
#include "itkSphereSpatialFunction.h"

int itkSpatialFunctionTest(int, char* [] )
{
  // Change this parameter (and the positions, below) to work in higher or lower dimensions
  const unsigned int dim = 3;

  //---------Create and initialize a spatial function-----------

  typedef itk::SphereSpatialFunction<dim> TFunctionType;
  typedef TFunctionType::InputType TFunctionPositionType;

  // Create and initialize a new sphere function

  TFunctionType::Pointer spatialFunc = TFunctionType::New();
  spatialFunc->SetRadius( 5 );

  TFunctionPositionType center;
  center[0]=10;
  center[1]=10;
  center[2]=10;
  spatialFunc->SetCenter(center);

  // Test the Get macros as well
  spatialFunc->GetCenter();
  spatialFunc->GetRadius();

  std::cout << "Sphere spatial function created\n";

  //----------------Test evaluation of funtion------------------

  // We're going to evaluate it at the center of the sphere (10,10,10)
  bool funcVal = spatialFunc->Evaluate(center);
  printf("Sphere function value is %i\n", funcVal);

  // The function should have returned a value of 1, since the center is inside
  // the sphere
  if(funcVal == 1)
    return EXIT_SUCCESS;
  else
    return EXIT_FAILURE;
}

<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/CardSetUtils.hpp>

#include <hspp/Actions/Draw.hpp>
#include <hspp/Cards/Cards.hpp>

using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;

TEST(CoreCardsGen, EX1_066)
{
    GameConfig config;
    config.player1Class = CardClass::WARRIOR;
    config.player2Class = CardClass::ROGUE;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));

    Task::Run(curPlayer, PlayCardTask(card1));
    EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);

    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}

TEST(CoreCardsGen, EX1_306)
{
    GameConfig config;
    config.player1Class = CardClass::WARLOCK;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
    Generic::DrawCard(curPlayer,
                      Cards::GetInstance().FindCardByName("Stonetusk Boar"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
    Generic::DrawCard(opPlayer,
                      Cards::GetInstance().FindCardByName("Fiery War Axe"));

    Task::Run(curPlayer, PlayCardTask(card1));
    EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);

    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}

TEST(CoreCardsGen, CS2_041)
{
    GameConfig config;
    config.player1Class = CardClass::SHAMAN;
    config.player2Class = CardClass::ROGUE;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    auto& curField = curPlayer.GetField();
    const auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));

    Task::Run(curPlayer, PlayCardTask(card1));
    Task::Run(opPlayer, PlayCardTask(card3));

    Task::Run(opPlayer, CombatTask(card3, card1));
    EXPECT_EQ(curField.GetMinion(0)->health, 1);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);

    Task::Run(curPlayer, PlayCardTask(card2, -1, card1));
    EXPECT_EQ(curField.GetMinion(0)->health, 2);
    EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}

TEST(CoreCardsGen, CS2_088)
{
    GameConfig config;
    config.player1Class = CardClass::DRUID;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;
    opPlayer.GetHero()->health = 24;

    const auto card1 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));

    Task::Run(opPlayer, PlayCardTask(card1));
    EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}

TEST(CoreCardsGen, CS1_112)
{
    GameConfig config;
    config.player1Class = CardClass::PRIEST;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;
    curPlayer.GetHero()->health = 26;

    auto& curField = curPlayer.GetField();
    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
    const auto card5 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));

    Task::Run(curPlayer, PlayCardTask(card1));
    curPlayer.currentMana = 10;
    Task::Run(curPlayer, PlayCardTask(card2));
    curPlayer.currentMana = 10;
    Task::Run(opPlayer, PlayCardTask(card4));
    Task::Run(opPlayer, PlayCardTask(card5));

    Task::Run(curPlayer, EndTurnTask());

    Task::Run(curPlayer, CombatTask(card1, card4));
    EXPECT_EQ(curField.GetMinion(0)->health, 4);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);

    Task::Run(curPlayer, PlayCardTask(card3));
    EXPECT_EQ(curPlayer.GetHero()->health, 28);
    EXPECT_EQ(opPlayer.GetHero()->health, 28);
    EXPECT_EQ(curField.GetMinion(0)->health, 5);
    EXPECT_EQ(curField.GetMinion(1)->health, 7);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}

TEST(CoreCardsGen, CS1_113)
{
    GameConfig config;
    config.player1Class = CardClass::PRIEST;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto& curField = curPlayer.GetField();
    const auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));

    Task::Run(curPlayer, PlayCardTask(card1));
    curPlayer.currentMana = 10;
    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(curField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);

    Task::Run(curPlayer, PlayCardTask(card3, -1, card2));
    EXPECT_EQ(curField.GetNumOfMinions(), 2u);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);

    opPlayer.currentMana = 10;
    auto result =
        Task::Run(opPlayer, PlayCardTask(card4, -1, curPlayer.GetHero()));
    EXPECT_EQ(result, TaskStatus::PLAY_CARD_INVALID_TARGET);
}<commit_msg>fix: Change PlayCardTask test code<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/CardSetUtils.hpp>

#include <hspp/Actions/Draw.hpp>
#include <hspp/Cards/Cards.hpp>

using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;

TEST(CoreCardsGen, EX1_066)
{
    GameConfig config;
    config.player1Class = CardClass::WARRIOR;
    config.player2Class = CardClass::ROGUE;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));

    Task::Run(curPlayer, PlayCardTask(card1));
    EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);

    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}

TEST(CoreCardsGen, EX1_306)
{
    GameConfig config;
    config.player1Class = CardClass::WARLOCK;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
    Generic::DrawCard(curPlayer,
                      Cards::GetInstance().FindCardByName("Stonetusk Boar"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
    Generic::DrawCard(opPlayer,
                      Cards::GetInstance().FindCardByName("Fiery War Axe"));

    Task::Run(curPlayer, PlayCardTask(card1));
    EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);

    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}

TEST(CoreCardsGen, CS2_041)
{
    GameConfig config;
    config.player1Class = CardClass::SHAMAN;
    config.player2Class = CardClass::ROGUE;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    auto& curField = curPlayer.GetField();
    const auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));

    Task::Run(curPlayer, PlayCardTask(card1));
    Task::Run(opPlayer, PlayCardTask(card3));

    Task::Run(opPlayer, CombatTask(card3, card1));
    EXPECT_EQ(curField.GetMinion(0)->health, 1);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);

    Task::Run(curPlayer, PlayCardTask(card2, -1, card1));
    EXPECT_EQ(curField.GetMinion(0)->health, 2);
    EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}

TEST(CoreCardsGen, CS2_088)
{
    GameConfig config;
    config.player1Class = CardClass::DRUID;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;
    opPlayer.GetHero()->health = 24;

    const auto card1 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));

    Task::Run(opPlayer, PlayCardTask(card1));
    EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}

TEST(CoreCardsGen, CS1_112)
{
    GameConfig config;
    config.player1Class = CardClass::PRIEST;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;
    curPlayer.GetHero()->health = 26;

    auto& curField = curPlayer.GetField();
    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
    const auto card5 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));

    Task::Run(curPlayer, PlayCardTask(card1));
    curPlayer.currentMana = 10;
    Task::Run(curPlayer, PlayCardTask(card2));
    curPlayer.currentMana = 10;
    Task::Run(opPlayer, PlayCardTask(card4));
    Task::Run(opPlayer, PlayCardTask(card5));

    Task::Run(curPlayer, EndTurnTask());

    Task::Run(curPlayer, CombatTask(card1, card4));
    EXPECT_EQ(curField.GetMinion(0)->health, 4);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);

    Task::Run(curPlayer, PlayCardTask(card3));
    EXPECT_EQ(curPlayer.GetHero()->health, 28);
    EXPECT_EQ(opPlayer.GetHero()->health, 28);
    EXPECT_EQ(curField.GetMinion(0)->health, 5);
    EXPECT_EQ(curField.GetMinion(1)->health, 7);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}

TEST(CoreCardsGen, CS1_113)
{
    GameConfig config;
    config.player1Class = CardClass::PRIEST;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
    curPlayer.maximumMana = 10;
    curPlayer.currentMana = 10;
    opPlayer.maximumMana = 10;
    opPlayer.currentMana = 10;

    const auto& curField = curPlayer.GetField();
    const auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));

    Task::Run(curPlayer, PlayCardTask(card1));
    curPlayer.currentMana = 10;
    Task::Run(opPlayer, PlayCardTask(card2));
    EXPECT_EQ(curField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);

    Task::Run(curPlayer, PlayCardTask(card3, -1, card2));
    EXPECT_EQ(curField.GetNumOfMinions(), 2u);
    EXPECT_EQ(opField.GetNumOfMinions(), 0u);

    opPlayer.currentMana = 10;
    Task::Run(opPlayer, PlayCardTask(card4, -1, curPlayer.GetHero()));
    EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}<|endoftext|>


<commit_before>// Copyright 2014 kloudkl@github

#include <cuda_runtime.h>
#include <google/protobuf/text_format.h>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"

using namespace caffe;

template<typename Dtype>
inline int sign(const Dtype val) {
  return (Dtype(0) < val) - (val < Dtype(0));
}

template<typename Dtype>
void binarize(const int n, const Dtype* real_valued_feature,
              Dtype* binary_code);

template<typename Dtype>
void binarize(const shared_ptr<Blob<Dtype> > real_valued_features,
              shared_ptr<Blob<Dtype> > binary_codes);

template<typename Dtype>
int features_binarization_pipeline(int argc, char** argv);

int main(int argc, char** argv) {
  return features_binarization_pipeline<float>(argc, argv);
//  return features_binarization_pipeline<double>(argc, argv);
}

template<typename Dtype>
int features_binarization_pipeline(int argc, char** argv) {
  const int num_required_args = 4;
  if (argc < num_required_args) {
    LOG(ERROR)<<
        "This program compresses real valued features into compact binary codes."
        "Usage: demo_binarize_features  data_prototxt  data_layer_name"
        "  save_binarized_feature_binaryproto_file  [CPU/GPU]  [DEVICE_ID=0]";
    return 1;
  }
  int arg_pos = num_required_args;

  arg_pos = num_required_args;
  if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
    LOG(ERROR)<< "Using GPU";
    uint device_id = 0;
    if (argc > arg_pos + 1) {
      device_id = atoi(argv[arg_pos + 1]);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }
  Caffe::set_phase(Caffe::TEST);

  NetParameter pretrained_net_param;

  arg_pos = 0;  // the name of the executable

  // Expected prototxt contains at least one data layer as the real valued features.
  /*
   layers {
   layer {
   name: "real_valued_features"
   type: "data"
   source: "/path/to/your/real/valued/features_leveldb"
   batchsize: 256
   }
   top: "real_valued_features"
   top: "label"
   }
   */
  string data_prototxt(argv[++arg_pos]);
  string data_layer_name(argv[++arg_pos]);
  NetParameter data_net_param;
  ReadProtoFromTextFile(data_prototxt.c_str(), &data_net_param);
  LayerParameter data_layer_param;
  int num_layer;
  for (num_layer = 0; num_layer < data_net_param.layers_size(); ++num_layer) {
    if (data_layer_name == data_net_param.layers(num_layer).layer().name()) {
      data_layer_param = data_net_param.layers(num_layer).layer();
      break;
    }
  }
  if (num_layer = data_net_param.layers_size()) {
    LOG(ERROR) << "Unknow data layer name " << data_layer_name <<
        " in prototxt " << data_prototxt;
  }

  string save_binarized_feature_binaryproto_file(argv[++arg_pos]);

  LOG(ERROR)<< "Binarizing features";
  DataLayer<Dtype> data_layer(data_layer_param);
  vector<Blob<Dtype>*> bottom_vec_that_data_layer_does_not_need_;
  vector<Blob<Dtype>*> top_vec;
  data_layer.Forward(bottom_vec_that_data_layer_does_not_need_, &top_vec);
  shared_ptr<Blob<Dtype> > feature_binary_codes;
  BlobProtoVector blob_proto_vector;
  int batch_index = 0;
  // TODO: DataLayer seem to rotate from the last record to the first
  // how to judge that all the data record have been enumerated?
  while (top_vec.size()) { // data_layer still outputs data
    LOG(ERROR)<< "Batch " << batch_index << " feature binarization";
    const shared_ptr<Blob<Dtype> > feature_blob(top_vec[0]);
    binarize<Dtype>(feature_blob, feature_binary_codes);

    LOG(ERROR) << "Batch " << batch_index << " save binarized features";
    feature_binary_codes->ToProto(blob_proto_vector.add_blobs());

    data_layer.Forward(bottom_vec_that_data_layer_does_not_need_, &top_vec);
    ++batch_index;
  } //  while (top_vec.size()) {

  WriteProtoToBinaryFile(blob_proto_vector, save_binarized_feature_binaryproto_file);
  LOG(ERROR)<< "Successfully ended!";
  return 0;
}

template<typename Dtype>
void binarize(const int n, const Dtype* real_valued_feature,
              Dtype* binary_codes) {
  // TODO: more advanced binarization algorithm such as bilinear projection
  // Yunchao Gong, Sanjiv Kumar, Henry A. Rowley, and Svetlana Lazebnik.
  // Learning Binary Codes for High-Dimensional Data Using Bilinear Projections.
  // In IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2013.
  // http://www.unc.edu/~yunchao/bpbc.htm
  int size_of_code = sizeof(Dtype) * 8;
  CHECK_EQ(n % size_of_code, 0);
  int num_binary_codes = n / size_of_code;
  uint64_t code;
  int offset;
  for (int i = 0; i < num_binary_codes; ++i) {
    code = 0;
    offset = i * size_of_code;
    for (int j = 0; j < size_of_code; ++j) {
      code |= sign(real_valued_feature[offset + j]);
      code << 1;
    }
    binary_codes[i] = static_cast<Dtype>(code);
  }
}

template<typename Dtype>
void binarize(const shared_ptr<Blob<Dtype> > real_valued_features,
              shared_ptr<Blob<Dtype> > binary_codes) {
  int num = real_valued_features->num();
  int dim = real_valued_features->count() / num;
  int size_of_code = sizeof(Dtype) * 8;
  CHECK_EQ(dim % size_of_code, 0);
  binary_codes->Reshape(num, dim / size_of_code, 1, 1);
  const Dtype* real_valued_features_data = real_valued_features->cpu_data();
  Dtype* binary_codes_data = binary_codes->mutable_cpu_data();
  for (int n = 0; n < num; ++n) {
    binarize<Dtype>(dim,
                    real_valued_features_data + real_valued_features->offset(n),
                    binary_codes_data + binary_codes->offset(n));
  }
}
<commit_msg>Fix bugs of the feature binarization example<commit_after>// Copyright 2014 kloudkl@github

#include <cuda_runtime.h>
#include <google/protobuf/text_format.h>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"

using namespace caffe;

// TODO: Replace this with caffe_sign after the PR #159 is merged
template<typename Dtype>
inline int sign(const Dtype val) {
  return (Dtype(0) < val) - (val < Dtype(0));
}

template<typename Dtype>
void binarize(const int n, const Dtype* real_valued_feature,
              Dtype* binary_code);

template<typename Dtype>
void binarize(const shared_ptr<Blob<Dtype> > real_valued_features,
              shared_ptr<Blob<Dtype> > binary_codes);

template<typename Dtype>
int features_binarization_pipeline(int argc, char** argv);

int main(int argc, char** argv) {
  return features_binarization_pipeline<float>(argc, argv);
//  return features_binarization_pipeline<double>(argc, argv);
}

template<typename Dtype>
int features_binarization_pipeline(int argc, char** argv) {
  const int num_required_args = 5;
  if (argc < num_required_args) {
    LOG(ERROR)<<
    "This program compresses real valued features into compact binary codes.\n"
    "Usage: demo_binarize_features  real_valued_feature_prototxt  feature_blob_name"
    "  save_binarized_feature_binaryproto_file  num_mini_batches  [CPU/GPU]  [DEVICE_ID=0]";
    return 1;
  }
  int arg_pos = num_required_args;

  arg_pos = num_required_args;
  if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
    LOG(ERROR)<< "Using GPU";
    uint device_id = 0;
    if (argc > arg_pos + 1) {
      device_id = atoi(argv[arg_pos + 1]);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }
  Caffe::set_phase(Caffe::TEST);

  NetParameter pretrained_net_param;

  arg_pos = 0;  // the name of the executable

  // Expected prototxt contains at least one data layer as the real valued features.
  /*
   layers {
   layer {
   name: "real_valued_features"
   type: "data"
   source: "/path/to/your/real/valued/features_leveldb"
   batchsize: 256
   }
   top: "real_valued_features"
   top: "label"
   }
   */
  string real_valued_feature_prototxt(argv[++arg_pos]);
  NetParameter real_valued_feature_net_param;
  ReadProtoFromTextFile(real_valued_feature_prototxt,
                        &real_valued_feature_net_param);
  shared_ptr<Net<Dtype> > real_valued_feature_net(
      new Net<Dtype>(real_valued_feature_net_param));

  string feature_blob_name(argv[++arg_pos]);
  CHECK(real_valued_feature_net->HasBlob(feature_blob_name))
      << "Unknown feature blob name " << feature_blob_name << " in the network "
      << real_valued_feature_prototxt;

  string save_binarized_feature_binaryproto_file(argv[++arg_pos]);

  int num_mini_batches = atoi(argv[++arg_pos]);

  LOG(ERROR)<< "Binarizing features";
  vector<Blob<Dtype>*> input_vec;
  shared_ptr<Blob<Dtype> > feature_binary_codes(new Blob<Dtype>());
  BlobProtoVector blob_proto_vector;
  int num_features = 0;
  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {
    real_valued_feature_net->Forward(input_vec);
    const shared_ptr<Blob<Dtype> > feature_blob = real_valued_feature_net
        ->GetBlob(feature_blob_name);
    binarize<Dtype>(feature_blob, feature_binary_codes);
    num_features += feature_binary_codes->num();
    feature_binary_codes->ToProto(blob_proto_vector.add_blobs());
  }  //  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)
  WriteProtoToBinaryFile(blob_proto_vector,
                         save_binarized_feature_binaryproto_file);
  LOG(ERROR)<< "Successfully binarized " << num_features << " features!";
  return 0;
}

template<typename Dtype>
void binarize(const int n, const Dtype* real_valued_feature,
              Dtype* binary_codes) {
  // TODO: more advanced binarization algorithm such as bilinear projection
  // Yunchao Gong, Sanjiv Kumar, Henry A. Rowley, and Svetlana Lazebnik.
  // Learning Binary Codes for High-Dimensional Data Using Bilinear Projections.
  // In IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2013.
  // http://www.unc.edu/~yunchao/bpbc.htm
  int size_of_code = sizeof(Dtype) * 8;
  int num_binary_codes = (n + size_of_code - 1) / size_of_code;
  uint64_t code;
  int offset;
  int count = 0;
  for (int i = 0; i < num_binary_codes; ++i) {
    offset = i * size_of_code;
    int j = 0;
    code = 0;
    for (; j < size_of_code && count++ < n; ++j) {
      code |= sign(real_valued_feature[offset + j]);
      code << 1;
    }
    code << (size_of_code - j);
    binary_codes[i] = static_cast<Dtype>(code);
  }
}

template<typename Dtype>
void binarize(const shared_ptr<Blob<Dtype> > real_valued_features,
              shared_ptr<Blob<Dtype> > binary_codes) {
  int num = real_valued_features->num();
  int dim = real_valued_features->count() / num;
  int size_of_code = sizeof(Dtype) * 8;
  binary_codes->Reshape(num, (dim + size_of_code - 1) / size_of_code, 1, 1);
  const Dtype* real_valued_features_data = real_valued_features->cpu_data();
  Dtype* binary_codes_data = binary_codes->mutable_cpu_data();
  for (int n = 0; n < num; ++n) {
    binarize<Dtype>(dim,
                    real_valued_features_data + real_valued_features->offset(n),
                    binary_codes_data + binary_codes->offset(n));
  }
}
<|endoftext|>


<commit_before>using namespace GeFiCa;
// draw V, E distributions saved in an input ROOT file
void drawFields(const char *input="ppc.root")
{
   // Get data from input file
   TFile *file = new TFile(input, "update"); // "update" allows creation of TH3
   PointContactDZ *detector = (PointContactDZ*) file->Get("pcdz");
   TTree *t = detector->GetTree(true);
   const int n = t->GetEntries();

   // fine tune margins, etc.
   gStyle->SetTitleOffset(0.75,"Y");
   gStyle->SetPadRightMargin(0.12);
   gStyle->SetPadLeftMargin(0.08);

   // generate plots
   t->Draw("c1:(v)","c2>2&&c2<2.01","");
   //t->Draw("c1:c2:log(v)","","goff");
   //TGraph2D *gv = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
   //gv->SetName("gv"); gv->SetNpx(500); gv->SetNpy(500); // fine bin histogram
   //TH2D *hv = gv->GetHistogram();
   //hv->SetTitle(";Radius [cm];Height [cm];Potential [V]");
   //hv->GetZaxis()->CenterTitle();
   //hv->Draw("colz");

   // draw E field lines
   const int np=12;
   TGraph *gl[np];
   double x[np] = {-25, 0.01, 25, -4, -3, -2, -1, 0.01, 1, 2, 3, 4};
   double y[np] = {49.9, 24.9, 49.9, 2, 2, 2, 2, 2, 2, 2, 2, 2};
   bool positive[np] = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
   for (int i=0; i<np; i++) {
      gDebug=1;
      gl[i] = detector->GetFieldLineFrom(x[i]*mm, y[i]*mm, positive[i]);
      gDebug=0;
      gl[i]->Draw("l");
   }

   TCanvas *ce = new TCanvas;
   ce->SetLogz();
   t->Draw("c1:c2:e","","goff");
   TGraph2D *ge = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
   ge->SetName("ge"); ge->SetNpx(500); ge->SetNpy(500); // fine bin histogram
   TH2D *he = ge->GetHistogram();
   he->SetTitle(";Radius [cm];Height [cm];E [V/cm]");
   he->GetZaxis()->CenterTitle();
   he->Draw("colz");
   for (int i=0; i<np; i++) gl[i]->Draw("p");
}
<commit_msg>removed miscommited stuff<commit_after>using namespace GeFiCa;
// draw V, E distributions saved in an input ROOT file
void drawFields(const char *input="ppc.root")
{
   // Get data from input file
   TFile *file = new TFile(input, "update"); // "update" allows creation of TH3
   PointContactDZ *detector = (PointContactDZ*) file->Get("pcdz");
   TTree *t = detector->GetTree(true);
   const int n = t->GetEntries();

   // fine tune margins, etc.
   gStyle->SetTitleOffset(0.75,"Y");
   gStyle->SetPadRightMargin(0.12);
   gStyle->SetPadLeftMargin(0.08);

   // generate plots
   t->Draw("c1:c2:log(v)","","goff");
   TGraph2D *gv = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
   gv->SetName("gv"); gv->SetNpx(500); gv->SetNpy(500); // fine bin histogram
   TH2D *hv = gv->GetHistogram();
   hv->SetTitle(";Radius [cm];Height [cm];Potential [V]");
   hv->GetZaxis()->CenterTitle();
   hv->Draw("colz");

   // draw E field lines
   const int np=12;
   TGraph *gl[np];
   double x[np] = {-25, 0.01, 25, -4, -3, -2, -1, 0.01, 1, 2, 3, 4};
   double y[np] = {49.9, 24.9, 49.9, 2, 2, 2, 2, 2, 2, 2, 2, 2};
   bool positive[np] = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
   for (int i=0; i<np; i++) {
      gDebug=1;
      gl[i] = detector->GetFieldLineFrom(x[i]*mm, y[i]*mm, positive[i]);
      gDebug=0;
      gl[i]->Draw("l");
   }

   TCanvas *ce = new TCanvas;
   ce->SetLogz();
   t->Draw("c1:c2:e","","goff");
   TGraph2D *ge = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
   ge->SetName("ge"); ge->SetNpx(500); ge->SetNpy(500); // fine bin histogram
   TH2D *he = ge->GetHistogram();
   he->SetTitle(";Radius [cm];Height [cm];E [V/cm]");
   he->GetZaxis()->CenterTitle();
   he->Draw("colz");
   for (int i=0; i<np; i++) gl[i]->Draw("p");
}
<|endoftext|>


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

#include <string>

#include <cpr.h>

#include "server.h"

static Server* server = new Server();
auto base = server->GetBaseUrl();

TEST(DeleteTests, DeleteTest) {
    auto url = Url{base + "/delete.html"};
    auto response = cpr::Delete(url);
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, DeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    auto response = cpr::Delete(url);
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteTest) {
    auto url = Url{base + "/delete.html"};
    Session session;
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    Session session;
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterGetTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Get();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterGetTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Get();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterHeadTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Head();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterHeadTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Head();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterPostTest) {
    Session session;
    {
        auto url = Url{base + "/url_post.html"};
        auto payload = Payload{{"x", "5"}};
        session.SetUrl(url);
        auto response = session.Post();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterPostTest) {
    Session session;
    {
        auto url = Url{base + "/url_post.html"};
        auto payload = Payload{{"x", "5"}};
        session.SetUrl(url);
        auto response = session.Post();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, HttpbinDeleteTest) {
    auto url = Url{"http://www.httpbin.org/delete"};
    auto response = cpr::Delete(url);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, BadDeleteTest) {
    auto url = Url{"http://www.httpbin.org/get"};
    auto response = cpr::Delete(url);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, AsyncDeleteTest) {
    auto url = Url{base + "/delete.html"};
    auto future_response = cpr::DeleteAsync(url);
    auto response = future_response.get();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, AsyncDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    auto future_response = cpr::DeleteAsync(url);
    auto response = future_response.get();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, AsyncMultipleDeleteTest) {
    auto url = Url{base + "/delete.html"};
    std::vector<AsyncResponse> responses;
    for (int i = 0; i < 10; ++i) {
        responses.emplace_back(cpr::DeleteAsync(url));
    }
    for (auto& future_response : responses) {
        auto response = future_response.get();
        auto expected_text = std::string{"Delete success"};
        EXPECT_EQ(expected_text, response.text);
        EXPECT_EQ(url, response.url);
        EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
        EXPECT_EQ(200, response.status_code);
    }
}

TEST(DeleteTests, AsyncMultipleDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    std::vector<AsyncResponse> responses;
    for (int i = 0; i < 10; ++i) {
        responses.emplace_back(cpr::DeleteAsync(url));
    }
    for (auto& future_response : responses) {
        auto response = future_response.get();
        auto expected_text = std::string{"Method unallowed"};
        EXPECT_EQ(expected_text, response.text);
        EXPECT_EQ(url, response.url);
        EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
        EXPECT_EQ(405, response.status_code);
    }
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(server);
    return RUN_ALL_TESTS();
}
<commit_msg>Remove httpbin tests References #22<commit_after>#include <gtest/gtest.h>

#include <string>

#include <cpr.h>

#include "server.h"

static Server* server = new Server();
auto base = server->GetBaseUrl();

TEST(DeleteTests, DeleteTest) {
    auto url = Url{base + "/delete.html"};
    auto response = cpr::Delete(url);
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, DeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    auto response = cpr::Delete(url);
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteTest) {
    auto url = Url{base + "/delete.html"};
    Session session;
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    Session session;
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterGetTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Get();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterGetTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Get();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterHeadTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Head();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterHeadTest) {
    Session session;
    {
        auto url = Url{base + "/get.html"};
        session.SetUrl(url);
        auto response = session.Head();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, SessionDeleteAfterPostTest) {
    Session session;
    {
        auto url = Url{base + "/url_post.html"};
        auto payload = Payload{{"x", "5"}};
        session.SetUrl(url);
        auto response = session.Post();
    }
    auto url = Url{base + "/delete.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, SessionDeleteUnallowedAfterPostTest) {
    Session session;
    {
        auto url = Url{base + "/url_post.html"};
        auto payload = Payload{{"x", "5"}};
        session.SetUrl(url);
        auto response = session.Post();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, AsyncDeleteTest) {
    auto url = Url{base + "/delete.html"};
    auto future_response = cpr::DeleteAsync(url);
    auto response = future_response.get();
    auto expected_text = std::string{"Delete success"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(200, response.status_code);
}

TEST(DeleteTests, AsyncDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    auto future_response = cpr::DeleteAsync(url);
    auto response = future_response.get();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
}

TEST(DeleteTests, AsyncMultipleDeleteTest) {
    auto url = Url{base + "/delete.html"};
    std::vector<AsyncResponse> responses;
    for (int i = 0; i < 10; ++i) {
        responses.emplace_back(cpr::DeleteAsync(url));
    }
    for (auto& future_response : responses) {
        auto response = future_response.get();
        auto expected_text = std::string{"Delete success"};
        EXPECT_EQ(expected_text, response.text);
        EXPECT_EQ(url, response.url);
        EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
        EXPECT_EQ(200, response.status_code);
    }
}

TEST(DeleteTests, AsyncMultipleDeleteUnallowedTest) {
    auto url = Url{base + "/delete_unallowed.html"};
    std::vector<AsyncResponse> responses;
    for (int i = 0; i < 10; ++i) {
        responses.emplace_back(cpr::DeleteAsync(url));
    }
    for (auto& future_response : responses) {
        auto response = future_response.get();
        auto expected_text = std::string{"Method unallowed"};
        EXPECT_EQ(expected_text, response.text);
        EXPECT_EQ(url, response.url);
        EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
        EXPECT_EQ(405, response.status_code);
    }
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(server);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandintegration.h"

#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"

#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
#include <QtPlatformSupport/private/qgenericunixthemes_p.h>

#include <QtGui/private/qguiapplication_p.h>

#include <QtGui/QWindowSystemInterface>
#include <qpa/qplatformcursor.h>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QOpenGLContext>

#include <qpa/qplatforminputcontextfactory_p.h>
#include <qpa/qplatformaccessibility.h>
#include <qpa/qplatforminputcontext.h>

#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif

QWaylandIntegration::QWaylandIntegration()
    : mFontDb(new QGenericUnixFontDatabase())
    , mEventDispatcher(createUnixEventDispatcher())
    , mNativeInterface(new QWaylandNativeInterface(this))
    , mAccessibility(new QPlatformAccessibility())
{
    QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
    mDisplay = new QWaylandDisplay();
    mClipboard = new QWaylandClipboard(mDisplay);
    mDrag = new QWaylandDrag(mDisplay);

    foreach (QPlatformScreen *screen, mDisplay->screens())
        screenAdded(screen);

    mInputContext = QPlatformInputContextFactory::create();
}

QWaylandIntegration::~QWaylandIntegration()
{
    delete mDrag;
    delete mClipboard;
    delete mAccessibility;
    delete mNativeInterface;
    delete mDisplay;
}

QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
    return mNativeInterface;
}

bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
    switch (cap) {
    case ThreadedPixmaps: return true;
    case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return true;
#else
        return false;
#endif
    case ThreadedOpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return mDisplay->eglIntegration()->supportsThreadedOpenGL();
#else
        return false;
#endif
    case BufferQueueingOpenGL:
        return true;
    default: return QPlatformIntegration::hasCapability(cap);
    }
}

QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    if (window->surfaceType() == QWindow::OpenGLSurface)
        return mDisplay->eglIntegration()->createEglWindow(window);
#endif
    return new QWaylandShmWindow(window);
}

QPlatformOpenGLContext *QWaylandIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    return mDisplay->eglIntegration()->createPlatformOpenGLContext(context->format(), context->shareHandle());
#else
    Q_UNUSED(context);
    return 0;
#endif
}

QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
    return new QWaylandShmBackingStore(window);
}

QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
    return mEventDispatcher;
}

QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
    return mFontDb;
}

QPlatformClipboard *QWaylandIntegration::clipboard() const
{
    return mClipboard;
}

QPlatformDrag *QWaylandIntegration::drag() const
{
    return mDrag;
}

QPlatformInputContext *QWaylandIntegration::inputContext() const
{
    return mInputContext;
}

QVariant QWaylandIntegration::styleHint(StyleHint hint) const
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    if (hint == ShowIsFullScreen && mDisplay->windowManagerIntegration())
        return mDisplay->windowManagerIntegration()->showIsFullScreen();
#endif
    return QPlatformIntegration::styleHint(hint);
}

QPlatformAccessibility *QWaylandIntegration::accessibility() const
{
    return mAccessibility;
}

QPlatformServices *QWaylandIntegration::services() const
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    return mDisplay->windowManagerIntegration();
#else
    return QWaylandIntegration::services();
#endif
}

QWaylandDisplay *QWaylandIntegration::display() const
{
    return mDisplay;
}

QStringList QWaylandIntegration::themeNames() const
{
    return QGenericUnixTheme::themeNames();
}

QPlatformTheme *QWaylandIntegration::createPlatformTheme(const QString &name) const
{
    return QGenericUnixTheme::createUnixTheme(name);
}
<commit_msg>Fix qtwayland build with QT_NO_ACCESSIBILITY<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandintegration.h"

#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"

#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
#include <QtPlatformSupport/private/qgenericunixthemes_p.h>

#include <QtGui/private/qguiapplication_p.h>

#include <QtGui/QWindowSystemInterface>
#include <qpa/qplatformcursor.h>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QOpenGLContext>

#include <qpa/qplatforminputcontextfactory_p.h>
#include <qpa/qplatformaccessibility.h>
#include <qpa/qplatforminputcontext.h>

#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif

QWaylandIntegration::QWaylandIntegration()
    : mFontDb(new QGenericUnixFontDatabase())
    , mEventDispatcher(createUnixEventDispatcher())
    , mNativeInterface(new QWaylandNativeInterface(this))
#ifndef QT_NO_ACCESSIBILITY
    , mAccessibility(new QPlatformAccessibility())
#else
    , mAccessibility(0)
#endif
{
    QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
    mDisplay = new QWaylandDisplay();
    mClipboard = new QWaylandClipboard(mDisplay);
    mDrag = new QWaylandDrag(mDisplay);

    foreach (QPlatformScreen *screen, mDisplay->screens())
        screenAdded(screen);

    mInputContext = QPlatformInputContextFactory::create();
}

QWaylandIntegration::~QWaylandIntegration()
{
    delete mDrag;
    delete mClipboard;
#ifndef QT_NO_ACCESSIBILITY
    delete mAccessibility;
#endif
    delete mNativeInterface;
    delete mDisplay;
}

QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
    return mNativeInterface;
}

bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
    switch (cap) {
    case ThreadedPixmaps: return true;
    case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return true;
#else
        return false;
#endif
    case ThreadedOpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return mDisplay->eglIntegration()->supportsThreadedOpenGL();
#else
        return false;
#endif
    case BufferQueueingOpenGL:
        return true;
    default: return QPlatformIntegration::hasCapability(cap);
    }
}

QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    if (window->surfaceType() == QWindow::OpenGLSurface)
        return mDisplay->eglIntegration()->createEglWindow(window);
#endif
    return new QWaylandShmWindow(window);
}

QPlatformOpenGLContext *QWaylandIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    return mDisplay->eglIntegration()->createPlatformOpenGLContext(context->format(), context->shareHandle());
#else
    Q_UNUSED(context);
    return 0;
#endif
}

QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
    return new QWaylandShmBackingStore(window);
}

QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
    return mEventDispatcher;
}

QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
    return mFontDb;
}

QPlatformClipboard *QWaylandIntegration::clipboard() const
{
    return mClipboard;
}

QPlatformDrag *QWaylandIntegration::drag() const
{
    return mDrag;
}

QPlatformInputContext *QWaylandIntegration::inputContext() const
{
    return mInputContext;
}

QVariant QWaylandIntegration::styleHint(StyleHint hint) const
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    if (hint == ShowIsFullScreen && mDisplay->windowManagerIntegration())
        return mDisplay->windowManagerIntegration()->showIsFullScreen();
#endif
    return QPlatformIntegration::styleHint(hint);
}

QPlatformAccessibility *QWaylandIntegration::accessibility() const
{
    return mAccessibility;
}

QPlatformServices *QWaylandIntegration::services() const
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    return mDisplay->windowManagerIntegration();
#else
    return QWaylandIntegration::services();
#endif
}

QWaylandDisplay *QWaylandIntegration::display() const
{
    return mDisplay;
}

QStringList QWaylandIntegration::themeNames() const
{
    return QGenericUnixTheme::themeNames();
}

QPlatformTheme *QWaylandIntegration::createPlatformTheme(const QString &name) const
{
    return QGenericUnixTheme::createUnixTheme(name);
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>

#include <franka/exception.h>
#include <franka/robot.h>

/**
 * @example joint_point_to_point_motion.cpp
 * An example showing how to generate a joint pose motion to a goal position. Adapted from:
 * Wisama Khalil and Etienne Dombre. 2002. Modeling, Identification and Control of Robots
 * (Kogan Page Science Paper edition).
 *
 * @warning Before executing this example, make sure there is enough space in front of the robot.
 */

constexpr double kDeltaQMotionFinished = 1e-6;

inline int sgn(double x) {
  if (x == 0) {
    return 0;
  }
  return (x > 0) ? 1 : -1;
}

std::array<double, 7> add(const std::array<double, 7>& a, const std::array<double, 7>& b) {
  std::array<double, 7> result;
  for (size_t i = 0; i < a.size(); i++) {
    result[i] = a[i] + b[i];
  }
  return result;
}

std::array<double, 7> subtract(const std::array<double, 7>& a, const std::array<double, 7>& b) {
  std::array<double, 7> result;
  for (size_t i = 0; i < a.size(); i++) {
    result[i] = a[i] - b[i];
  }
  return result;
}

bool calculateDesiredValues(double t,
                            const std::array<double, 7>& delta_q,
                            const std::array<double, 7>& dq_max,
                            const std::array<double, 7>& t_1,
                            const std::array<double, 7>& t_2,
                            const std::array<double, 7>& t_f,
                            const std::array<double, 7>& q_1,
                            std::array<double, 7>* delta_q_d);

void calculateSynchronizedValues(const std::array<double, 7>& delta_q,
                                 const std::array<double, 7>& dq_max,
                                 const std::array<double, 7>& ddq_max_start,
                                 const std::array<double, 7>& ddq_max_goal,
                                 std::array<double, 7>* dq_max_sync,
                                 std::array<double, 7>* t_1_sync,
                                 std::array<double, 7>* t_2_sync,
                                 std::array<double, 7>* t_f_sync,
                                 std::array<double, 7>* q_1);

int main(int argc, char** argv) {
  if (argc != 10) {
    std::cerr << "Usage: ./generate_joint_pose_motion <robot-hostname> <goal_position> <speed "
                 "factor"
              << std::endl
              << "speed-factor must be between zero and one." << std::endl;
    return -1;
  }

  try {
    franka::Robot robot(argv[1]);
    std::array<double, 7> q_goal;
    for (size_t i = 0; i < 7; i++) {
      q_goal[i] = std::stod(argv[i + 2]);
    }
    double speed_factor = std::stod(argv[9]);

    // Set additional parameters always before the control loop, NEVER in the
    // control loop
    // Set collision behavior
    robot.setCollisionBehavior(
        {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},
        {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}},
        {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},
        {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}});

    std::array<double, 7> q_start = robot.readOnce().q_d;

    std::array<double, 7> dq_max{{2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5}};
    std::array<double, 7> ddq_max_start{{5, 5, 5, 5, 5, 5, 5}};
    std::array<double, 7> ddq_max_goal{{5, 5, 5, 5, 5, 5, 5}};
    for (size_t i = 0; i < 7; i++) {
      dq_max[i] = speed_factor * dq_max[i];
      ddq_max_start[i] = speed_factor * ddq_max_start[i];
      ddq_max_goal[i] = speed_factor * ddq_max_goal[i];
    }

    double time = 0.0;

    std::array<double, 7> dq_max_sync{};
    std::array<double, 7> t_1_sync{};
    std::array<double, 7> t_2_sync{};
    std::array<double, 7> t_f_sync{};
    std::array<double, 7> q_1{};
    std::array<double, 7> delta_q = subtract(q_goal, q_start);

    calculateSynchronizedValues(delta_q, dq_max, ddq_max_start, ddq_max_goal, &dq_max_sync,
                                &t_1_sync, &t_2_sync, &t_f_sync, &q_1);
    robot.control([=, &time](const franka::RobotState&,
                             franka::Duration time_step) -> franka::JointPositions {
      time += time_step.toSec();

      std::array<double, 7> delta_q_d;
      bool motion_finished = calculateDesiredValues(time, delta_q, dq_max_sync, t_1_sync, t_2_sync,
                                                    t_f_sync, q_1, &delta_q_d);

      if (motion_finished) {
        return franka::Stop;
      }

      return add(q_start, delta_q_d);
    });
    std::cout << std::endl << "Motion finished" << std::endl;
  } catch (const franka::Exception& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}

bool calculateDesiredValues(double t,
                            const std::array<double, 7>& delta_q,
                            const std::array<double, 7>& dq_max,
                            const std::array<double, 7>& t_1,
                            const std::array<double, 7>& t_2,
                            const std::array<double, 7>& t_f,
                            const std::array<double, 7>& q_1,
                            std::array<double, 7>* delta_q_d) {
  std::array<int, 7> sign_delta_q;
  std::array<double, 7> t_d = subtract(t_2, t_1);
  std::array<double, 7> delta_t_2 = subtract(t_f, t_2);
  std::array<bool, 7> joint_motion_finished{};

  for (size_t i = 0; i < 7; i++) {
    sign_delta_q[i] = sgn(delta_q[i]);
    if (std::abs(delta_q[i]) < kDeltaQMotionFinished) {
      (*delta_q_d)[i] = 0;
      joint_motion_finished[i] = true;
    } else {
      if (t < t_1[i]) {
        (*delta_q_d)[i] = -1.0 / std::pow(t_1[i], 3) * dq_max[i] * sign_delta_q[i] *
                          (0.5 * t - t_1[i]) * std::pow(t, 3);
      } else if (t >= t_1[i] && t < t_2[i]) {
        (*delta_q_d)[i] = q_1[i] + (t - t_1[i]) * dq_max[i] * sign_delta_q[i];
      } else if (t >= t_2[i] && t < t_f[i]) {
        (*delta_q_d)[i] =
            delta_q[i] +
            0.5 * (1.0 / std::pow(delta_t_2[i], 3) * (t - t_1[i] - 2 * delta_t_2[i] - t_d[i]) *
                       std::pow((t - t_1[i] - t_d[i]), 3) +
                   (2.0 * t - 2.0 * t_1[i] - delta_t_2[i] - 2.0 * t_d[i])) *
                dq_max[i] * sign_delta_q[i];
      } else {
        (*delta_q_d)[i] = delta_q[i];
        joint_motion_finished[i] = true;
      }
    }
  }
  return std::all_of(joint_motion_finished.cbegin(), joint_motion_finished.cend(),
                     [](bool x) { return x; });
}

void calculateSynchronizedValues(const std::array<double, 7>& delta_q,
                                 const std::array<double, 7>& dq_max,
                                 const std::array<double, 7>& ddq_max_start,
                                 const std::array<double, 7>& ddq_max_goal,
                                 std::array<double, 7>* dq_max_sync,
                                 std::array<double, 7>* t_1_sync,
                                 std::array<double, 7>* t_2_sync,
                                 std::array<double, 7>* t_f_sync,
                                 std::array<double, 7>* q_1) {
  std::array<double, 7> dq_max_reach = dq_max;
  std::array<double, 7> t_f{};
  std::array<double, 7> delta_t_2{};
  std::array<double, 7> t_1{};
  std::array<double, 7> delta_t_2_sync{};
  int sign_delta_q[7];
  for (size_t i = 0; i < 7; i++) {
    sign_delta_q[i] = sgn(delta_q[i]);
    if (std::abs(delta_q[i]) > kDeltaQMotionFinished) {
      if (std::abs(delta_q[i]) < (3.0 / 4.0 * (std::pow(dq_max[i], 2) / ddq_max_start[i]) +
                                  3.0 / 4.0 * (std::pow(dq_max[i], 2) / ddq_max_goal[i]))) {
        dq_max_reach[i] =
            std::sqrt(4.0 / 3.0 * delta_q[i] * sign_delta_q[i] *
                      (ddq_max_start[i] * ddq_max_goal[i]) / (ddq_max_start[i] + ddq_max_goal[i]));
      }
      t_1[i] = 1.5 * dq_max_reach[i] / ddq_max_start[i];
      delta_t_2[i] = 1.5 * dq_max_reach[i] / ddq_max_goal[i];
      t_f[i] = t_1[i] / 2.0 + delta_t_2[i] / 2.0 + std::abs(delta_q[i]) / dq_max_reach[i];
    }
  }

  double max_t_f = *std::max_element(t_f.begin(), t_f.end());
  for (size_t i = 0; i < 7; i++) {
    if (std::abs(delta_q[i]) > kDeltaQMotionFinished) {
      double a = 1.5 / 2.0 * (ddq_max_goal[i] + ddq_max_start[i]);
      double b = -1.0 * max_t_f * ddq_max_goal[i] * ddq_max_start[i];
      double c = std::abs(delta_q[i]) * ddq_max_goal[i] * ddq_max_start[i];
      double delta = b * b - 4.0 * a * c;
      (*dq_max_sync)[i] = (-1.0 * b - std::sqrt(delta)) / (2.0 * a);
      (*t_1_sync)[i] = 1.5 * (*dq_max_sync)[i] / ddq_max_start[i];
      delta_t_2_sync[i] = 1.5 * (*dq_max_sync)[i] / ddq_max_goal[i];
      (*t_f_sync)[i] =
          (*t_1_sync)[i] / 2 + delta_t_2_sync[i] / 2 + std::abs(delta_q[i] / (*dq_max_sync)[i]);
      (*t_2_sync)[i] = (*t_f_sync)[i] - delta_t_2_sync[i];
      (*q_1)[i] = (*dq_max_sync)[i] * sign_delta_q[i] * (0.5 * (*t_1_sync)[i]);
    }
  }
}
<commit_msg>Minor fixes.<commit_after>#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>

#include <franka/exception.h>
#include <franka/robot.h>

/**
 * @example joint_point_to_point_motion.cpp
 * An example showing how to generate a joint pose motion to a goal position. Adapted from:
 * Wisama Khalil and Etienne Dombre. 2002. Modeling, Identification and Control of Robots
 * (Kogan Page Science Paper edition).
 *
 * @warning Before executing this example, make sure there is enough space in front of the robot.
 */

constexpr double kDeltaQMotionFinished = 1e-6;

inline int sgn(double x) {
  if (x == 0) {
    return 0;
  }
  return (x > 0) ? 1 : -1;
}

std::array<double, 7> add(const std::array<double, 7>& a, const std::array<double, 7>& b) {
  std::array<double, 7> result;
  for (size_t i = 0; i < a.size(); i++) {
    result[i] = a[i] + b[i];
  }
  return result;
}

std::array<double, 7> subtract(const std::array<double, 7>& a, const std::array<double, 7>& b) {
  std::array<double, 7> result;
  for (size_t i = 0; i < a.size(); i++) {
    result[i] = a[i] - b[i];
  }
  return result;
}

bool calculateDesiredValues(double t,
                            const std::array<double, 7>& delta_q,
                            const std::array<double, 7>& dq_max,
                            const std::array<double, 7>& t_1,
                            const std::array<double, 7>& t_2,
                            const std::array<double, 7>& t_f,
                            const std::array<double, 7>& q_1,
                            std::array<double, 7>* delta_q_d);

void calculateSynchronizedValues(const std::array<double, 7>& delta_q,
                                 const std::array<double, 7>& dq_max,
                                 const std::array<double, 7>& ddq_max_start,
                                 const std::array<double, 7>& ddq_max_goal,
                                 std::array<double, 7>* dq_max_sync,
                                 std::array<double, 7>* t_1_sync,
                                 std::array<double, 7>* t_2_sync,
                                 std::array<double, 7>* t_f_sync,
                                 std::array<double, 7>* q_1);

int main(int argc, char** argv) {
  if (argc != 10) {
    std::cerr << "Usage: ./generate_joint_pose_motion "
              << "<robot-hostname> <goal-position> <speed-factor>" << std::endl
              << "speed-factor must be between zero and one." << std::endl;
    return -1;
  }

  try {
    franka::Robot robot(argv[1]);
    std::array<double, 7> q_goal;
    for (size_t i = 0; i < 7; i++) {
      q_goal[i] = std::stod(argv[i + 2]);
    }
    double speed_factor = std::stod(argv[9]);

    // Set additional parameters always before the control loop, NEVER in the control loop!
    // Set collision behavior.
    robot.setCollisionBehavior(
        {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},
        {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}},
        {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},
        {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}});

    std::array<double, 7> q_start = robot.readOnce().q_d;

    std::array<double, 7> dq_max{{2.0, 2.0, 2.0, 2.0, 2.5, 2.5, 2.5}};
    std::array<double, 7> ddq_max_start{{5, 5, 5, 5, 5, 5, 5}};
    std::array<double, 7> ddq_max_goal{{5, 5, 5, 5, 5, 5, 5}};
    for (size_t i = 0; i < 7; i++) {
      dq_max[i] = speed_factor * dq_max[i];
      ddq_max_start[i] = speed_factor * ddq_max_start[i];
      ddq_max_goal[i] = speed_factor * ddq_max_goal[i];
    }

    double time = 0.0;

    std::array<double, 7> dq_max_sync{};
    std::array<double, 7> t_1_sync{};
    std::array<double, 7> t_2_sync{};
    std::array<double, 7> t_f_sync{};
    std::array<double, 7> q_1{};
    std::array<double, 7> delta_q = subtract(q_goal, q_start);

    calculateSynchronizedValues(delta_q, dq_max, ddq_max_start, ddq_max_goal, &dq_max_sync,
                                &t_1_sync, &t_2_sync, &t_f_sync, &q_1);
    robot.control([=, &time](const franka::RobotState&,
                             franka::Duration time_step) -> franka::JointPositions {
      time += time_step.toSec();

      std::array<double, 7> delta_q_d;
      bool motion_finished = calculateDesiredValues(time, delta_q, dq_max_sync, t_1_sync, t_2_sync,
                                                    t_f_sync, q_1, &delta_q_d);

      if (motion_finished) {
        return franka::Stop;
      }

      return add(q_start, delta_q_d);
    });
    std::cout << std::endl << "Motion finished" << std::endl;
  } catch (const franka::Exception& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}

bool calculateDesiredValues(double t,
                            const std::array<double, 7>& delta_q,
                            const std::array<double, 7>& dq_max,
                            const std::array<double, 7>& t_1,
                            const std::array<double, 7>& t_2,
                            const std::array<double, 7>& t_f,
                            const std::array<double, 7>& q_1,
                            std::array<double, 7>* delta_q_d) {
  std::array<int, 7> sign_delta_q;
  std::array<double, 7> t_d = subtract(t_2, t_1);
  std::array<double, 7> delta_t_2 = subtract(t_f, t_2);
  std::array<bool, 7> joint_motion_finished{};

  for (size_t i = 0; i < 7; i++) {
    sign_delta_q[i] = sgn(delta_q[i]);
    if (std::abs(delta_q[i]) < kDeltaQMotionFinished) {
      (*delta_q_d)[i] = 0;
      joint_motion_finished[i] = true;
    } else {
      if (t < t_1[i]) {
        (*delta_q_d)[i] = -1.0 / std::pow(t_1[i], 3) * dq_max[i] * sign_delta_q[i] *
                          (0.5 * t - t_1[i]) * std::pow(t, 3);
      } else if (t >= t_1[i] && t < t_2[i]) {
        (*delta_q_d)[i] = q_1[i] + (t - t_1[i]) * dq_max[i] * sign_delta_q[i];
      } else if (t >= t_2[i] && t < t_f[i]) {
        (*delta_q_d)[i] =
            delta_q[i] +
            0.5 * (1.0 / std::pow(delta_t_2[i], 3) * (t - t_1[i] - 2 * delta_t_2[i] - t_d[i]) *
                       std::pow((t - t_1[i] - t_d[i]), 3) +
                   (2.0 * t - 2.0 * t_1[i] - delta_t_2[i] - 2.0 * t_d[i])) *
                dq_max[i] * sign_delta_q[i];
      } else {
        (*delta_q_d)[i] = delta_q[i];
        joint_motion_finished[i] = true;
      }
    }
  }
  return std::all_of(joint_motion_finished.cbegin(), joint_motion_finished.cend(),
                     [](bool x) { return x; });
}

void calculateSynchronizedValues(const std::array<double, 7>& delta_q,
                                 const std::array<double, 7>& dq_max,
                                 const std::array<double, 7>& ddq_max_start,
                                 const std::array<double, 7>& ddq_max_goal,
                                 std::array<double, 7>* dq_max_sync,
                                 std::array<double, 7>* t_1_sync,
                                 std::array<double, 7>* t_2_sync,
                                 std::array<double, 7>* t_f_sync,
                                 std::array<double, 7>* q_1) {
  std::array<double, 7> dq_max_reach = dq_max;
  std::array<double, 7> t_f{};
  std::array<double, 7> delta_t_2{};
  std::array<double, 7> t_1{};
  std::array<double, 7> delta_t_2_sync{};
  int sign_delta_q[7];
  for (size_t i = 0; i < 7; i++) {
    sign_delta_q[i] = sgn(delta_q[i]);
    if (std::abs(delta_q[i]) > kDeltaQMotionFinished) {
      if (std::abs(delta_q[i]) < (3.0 / 4.0 * (std::pow(dq_max[i], 2) / ddq_max_start[i]) +
                                  3.0 / 4.0 * (std::pow(dq_max[i], 2) / ddq_max_goal[i]))) {
        dq_max_reach[i] =
            std::sqrt(4.0 / 3.0 * delta_q[i] * sign_delta_q[i] *
                      (ddq_max_start[i] * ddq_max_goal[i]) / (ddq_max_start[i] + ddq_max_goal[i]));
      }
      t_1[i] = 1.5 * dq_max_reach[i] / ddq_max_start[i];
      delta_t_2[i] = 1.5 * dq_max_reach[i] / ddq_max_goal[i];
      t_f[i] = t_1[i] / 2.0 + delta_t_2[i] / 2.0 + std::abs(delta_q[i]) / dq_max_reach[i];
    }
  }

  double max_t_f = *std::max_element(t_f.begin(), t_f.end());
  for (size_t i = 0; i < 7; i++) {
    if (std::abs(delta_q[i]) > kDeltaQMotionFinished) {
      double a = 1.5 / 2.0 * (ddq_max_goal[i] + ddq_max_start[i]);
      double b = -1.0 * max_t_f * ddq_max_goal[i] * ddq_max_start[i];
      double c = std::abs(delta_q[i]) * ddq_max_goal[i] * ddq_max_start[i];
      double delta = b * b - 4.0 * a * c;
      (*dq_max_sync)[i] = (-1.0 * b - std::sqrt(delta)) / (2.0 * a);
      (*t_1_sync)[i] = 1.5 * (*dq_max_sync)[i] / ddq_max_start[i];
      delta_t_2_sync[i] = 1.5 * (*dq_max_sync)[i] / ddq_max_goal[i];
      (*t_f_sync)[i] =
          (*t_1_sync)[i] / 2 + delta_t_2_sync[i] / 2 + std::abs(delta_q[i] / (*dq_max_sync)[i]);
      (*t_2_sync)[i] = (*t_f_sync)[i] - delta_t_2_sync[i];
      (*q_1)[i] = (*dq_max_sync)[i] * sign_delta_q[i] * (0.5 * (*t_1_sync)[i]);
    }
  }
}
<|endoftext|>