<commit_before>#define BOOST_TEST_MODULE "test_bond_length_interaction"

#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif

#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/interaction/local/BondLengthInteraction.hpp>
#include <mjolnir/potential/local/HarmonicPotential.hpp>
#include <mjolnir/util/make_unique.hpp>

BOOST_AUTO_TEST_CASE(BondLength_calc_force)
{
    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
    using real_type        = traits_type::real_type;
    using coord_type       = traits_type::coordinate_type;
    using boundary_type    = traits_type::boundary_type;
    using system_type      = mjolnir::System<traits_type>;
    using harmonic_type    = mjolnir::HarmonicPotential<real_type>;
    using bond_length_type = mjolnir::BondLengthInteraction<traits_type, harmonic_type>;

    constexpr real_type tol = 1e-8;

    auto normalize = [](const coord_type& v){return v / mjolnir::math::length(v);};

    const real_type k(100.);
    const real_type native(2.0);

    harmonic_type    potential(k, native);
    bond_length_type interaction("none", {{ {{0,1}}, potential}});

    system_type sys(2, boundary_type{});

    sys.at(0).mass = 1.0;
    sys.at(1).mass = 1.0;
    sys.at(0).rmass = 1.0;
    sys.at(1).rmass = 1.0;

    sys.at(0).position = coord_type(0,0,0);
    sys.at(1).position = coord_type(0,0,0);
    sys.at(0).velocity = coord_type(0,0,0);
    sys.at(1).velocity = coord_type(0,0,0);
    sys.at(0).force    = coord_type(0,0,0);
    sys.at(1).force    = coord_type(0,0,0);

    sys.at(0).name  = "X";
    sys.at(1).name  = "X";
    sys.at(0).group = "NONE";
    sys.at(1).group = "NONE";

    const real_type dr = 1e-3;
    real_type dist = 1e0;
    for(int i = 0; i < 2000; ++i)
    {
        sys[0].position = coord_type(0,0,0);
        sys[1].position = coord_type(0,0,0);
        sys[0].force    = coord_type(0,0,0);
        sys[1].force    = coord_type(0,0,0);
        sys[1].position[0] = dist;

        const real_type deriv = potential.derivative(dist);
        const real_type coef  = std::abs(deriv);

        interaction.calc_force(sys);

        const real_type force_strength1 = mjolnir::math::length(sys[0].force);
        const real_type force_strength2 = mjolnir::math::length(sys[1].force);

        // direction
        if(i == 1000) // most stable point
        {
            BOOST_TEST(force_strength1 == 0.0, boost::test_tools::tolerance(tol));
            BOOST_TEST(force_strength2 == 0.0, boost::test_tools::tolerance(tol));
        }
        else if(i < 1000) // repulsive
        {
            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));
            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));

            const real_type dir1 = mjolnir::math::dot_product(
                normalize(sys[0].force), normalize(sys[0].position - sys[1].position));
            const real_type dir2 = mjolnir::math::dot_product(
                normalize(sys[1].force), normalize(sys[1].position - sys[0].position));

            BOOST_TEST(dir1 == 1.0, boost::test_tools::tolerance(tol));
            BOOST_TEST(dir2 == 1.0, boost::test_tools::tolerance(tol));
        }
        else if(i > 1000) // attractive
        {
            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));
            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));

            const real_type dir1 = mjolnir::math::dot_product(
                normalize(sys[0].force), normalize(sys[1].position - sys[0].position));
            const real_type dir2 = mjolnir::math::dot_product(
                normalize(sys[1].force), normalize(sys[0].position - sys[1].position));

            BOOST_TEST(dir1 == 1e0, boost::test_tools::tolerance(tol));
            BOOST_TEST(dir2 == 1e0, boost::test_tools::tolerance(tol));
        }
        BOOST_TEST(mjolnir::math::length(sys[0].force + sys[1].force) == 0.0,
                   boost::test_tools::tolerance(tol));

        dist += dr;
    }
}
<commit_msg>test: add another test case for bond length<commit_after>#define BOOST_TEST_MODULE "test_bond_length_interaction"

#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif

#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/interaction/local/BondLengthInteraction.hpp>
#include <mjolnir/potential/local/HarmonicPotential.hpp>
#include <mjolnir/util/make_unique.hpp>

#include <random>

BOOST_AUTO_TEST_CASE(BondLength_calc_force)
{
    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
    using real_type        = traits_type::real_type;
    using coord_type       = traits_type::coordinate_type;
    using boundary_type    = traits_type::boundary_type;
    using system_type      = mjolnir::System<traits_type>;
    using potential_type    = mjolnir::HarmonicPotential<real_type>;
    using interaction_type = mjolnir::BondLengthInteraction<traits_type, potential_type>;

    constexpr real_type tol = 1e-8;

    auto normalize = [](const coord_type& v){return v / mjolnir::math::length(v);};

    const real_type k(100.);
    const real_type native(2.0);

    potential_type    potential(k, native);
    interaction_type interaction("none", {{ {{0,1}}, potential}});

    system_type sys(2, boundary_type{});

    sys.at(0).mass = 1.0;
    sys.at(1).mass = 1.0;
    sys.at(0).rmass = 1.0;
    sys.at(1).rmass = 1.0;

    sys.at(0).position = coord_type(0,0,0);
    sys.at(1).position = coord_type(0,0,0);
    sys.at(0).velocity = coord_type(0,0,0);
    sys.at(1).velocity = coord_type(0,0,0);
    sys.at(0).force    = coord_type(0,0,0);
    sys.at(1).force    = coord_type(0,0,0);

    sys.at(0).name  = "X";
    sys.at(1).name  = "X";
    sys.at(0).group = "NONE";
    sys.at(1).group = "NONE";

    const real_type dr = 1e-3;
    real_type dist = 1e0;
    for(int i = 0; i < 2000; ++i)
    {
        sys[0].position = coord_type(0,0,0);
        sys[1].position = coord_type(0,0,0);
        sys[0].force    = coord_type(0,0,0);
        sys[1].force    = coord_type(0,0,0);
        sys[1].position[0] = dist;

        const real_type deriv = potential.derivative(dist);
        const real_type coef  = std::abs(deriv);

        interaction.calc_force(sys);

        const real_type force_strength1 = mjolnir::math::length(sys[0].force);
        const real_type force_strength2 = mjolnir::math::length(sys[1].force);

        // direction
        if(i == 1000) // most stable point
        {
            BOOST_TEST(force_strength1 == 0.0, boost::test_tools::tolerance(tol));
            BOOST_TEST(force_strength2 == 0.0, boost::test_tools::tolerance(tol));
        }
        else if(i < 1000) // repulsive
        {
            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));
            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));

            const real_type dir1 = mjolnir::math::dot_product(
                normalize(sys[0].force), normalize(sys[0].position - sys[1].position));
            const real_type dir2 = mjolnir::math::dot_product(
                normalize(sys[1].force), normalize(sys[1].position - sys[0].position));

            BOOST_TEST(dir1 == 1.0, boost::test_tools::tolerance(tol));
            BOOST_TEST(dir2 == 1.0, boost::test_tools::tolerance(tol));
        }
        else if(i > 1000) // attractive
        {
            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));
            BOOST_TEST(coef == force_strength2, boost::test_tools::tolerance(tol));

            const real_type dir1 = mjolnir::math::dot_product(
                normalize(sys[0].force), normalize(sys[1].position - sys[0].position));
            const real_type dir2 = mjolnir::math::dot_product(
                normalize(sys[1].force), normalize(sys[0].position - sys[1].position));

            BOOST_TEST(dir1 == 1e0, boost::test_tools::tolerance(tol));
            BOOST_TEST(dir2 == 1e0, boost::test_tools::tolerance(tol));
        }
        BOOST_TEST(mjolnir::math::length(sys[0].force + sys[1].force) == 0.0,
                   boost::test_tools::tolerance(tol));

        dist += dr;
    }
}

BOOST_AUTO_TEST_CASE(BondLength_numerical_difference)
{
    using traits_type      = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
    using real_type        = traits_type::real_type;
    using coord_type       = traits_type::coordinate_type;
    using boundary_type    = traits_type::boundary_type;
    using system_type      = mjolnir::System<traits_type>;
    using potential_type    = mjolnir::HarmonicPotential<real_type>;
    using interaction_type = mjolnir::BondLengthInteraction<traits_type, potential_type>;

    const real_type k(100.0);
    const real_type native(std::sqrt(3.0));

    potential_type   potential(k, native);
    interaction_type interaction("none", {{ {{0,1}}, potential}});

    system_type sys(2, boundary_type{});

    sys.at(0).mass  = 1.0;
    sys.at(1).mass  = 1.0;
    sys.at(0).rmass = 1.0;
    sys.at(1).rmass = 1.0;

    sys.at(0).position = coord_type( 0.0, 0.0, 0.0);
    sys.at(1).position = coord_type( 1.0, 1.0, 1.0);
    sys.at(0).velocity = coord_type( 0.0, 0.0, 0.0);
    sys.at(1).velocity = coord_type( 0.0, 0.0, 0.0);
    sys.at(0).force    = coord_type( 0.0, 0.0, 0.0);
    sys.at(1).force    = coord_type( 0.0, 0.0, 0.0);

    sys.at(0).name  = "X";
    sys.at(1).name  = "X";
    sys.at(0).group = "TEST";
    sys.at(1).group = "TEST";

    const auto init = sys;

    std::mt19937 mt(123456789);
    std::uniform_real_distribution<real_type> uni(-1.0, 1.0);

    constexpr real_type tol = 1e-4;
    constexpr real_type dr  = 1e-4;
    for(std::size_t i = 0; i < 1000; ++i)
    {
        for(std::size_t idx=0; idx<2; ++idx)
        {
            {
                // ----------------------------------------------------------------
                // reset positions
                sys = init;

                // calc U(x-dx)
                const auto E0 = interaction.calc_energy(sys);

                const auto dx = uni(mt) * dr;

                mjolnir::math::X(sys.position(idx)) += dx;

                // calc F(x)
                interaction.calc_force(sys);

                mjolnir::math::X(sys.position(idx)) += dx;

                // calc U(x+dx)
                const auto E1 = interaction.calc_energy(sys);

                // central difference
                const auto dE = (E1 - E0) * 0.5;

                BOOST_TEST(-dE == dx * mjolnir::math::X(sys.force(idx)),
                           boost::test_tools::tolerance(tol));
            }
            {
                // ----------------------------------------------------------------
                // reset positions
                sys = init;

                // calc U(x-dx)
                const auto E0 = interaction.calc_energy(sys);

                const auto dy = uni(mt) * dr;

                mjolnir::math::Y(sys.position(idx)) += dy;

                // calc F(x)
                interaction.calc_force(sys);

                mjolnir::math::Y(sys.position(idx)) += dy;

                // calc U(x+dx)
                const auto E1 = interaction.calc_energy(sys);

                // central difference
                const auto dE = (E1 - E0) * 0.5;

                BOOST_TEST(-dE == dy * mjolnir::math::Y(sys.force(idx)),
                           boost::test_tools::tolerance(tol));
            }
            {
                // ----------------------------------------------------------------
                // reset positions
                sys = init;

                // calc U(x-dx)
                const auto E0 = interaction.calc_energy(sys);

                const auto dz = uni(mt) * dr;

                mjolnir::math::Z(sys.position(idx)) += dz;

                // calc F(x)
                interaction.calc_force(sys);

                mjolnir::math::Z(sys.position(idx)) += dz;

                // calc U(x+dx)
                const auto E1 = interaction.calc_energy(sys);

                // central difference
                const auto dE = (E1 - E0) * 0.5;

                BOOST_TEST(-dE == dz * mjolnir::math::Z(sys.force(idx)),
                           boost::test_tools::tolerance(tol));
            }
        }
    }
}
<|endoftext|>


<commit_before>// implentation of functor for interpreted functions

#define MAKE_CINT_FUNCTOR

#include <Math/Functor.h>
#include <iostream>

#include "TClass.h"
#include "TMethodCall.h"
#include "TError.h"
#include "G__ci.h"

namespace ROOT {
namespace Math {

//#if defined(__MAKECINT__) || defined(G__DICTIONARY)

//Functor handler for Cint functions

template<class ParentFunctor>
class FunctorCintHandler : public ParentFunctor::Impl
{
public:
   typedef typename ParentFunctor::Impl ImplFunc;
   typedef typename ImplFunc::BaseFunc BaseFunc;

   // for 1D functor1d
   FunctorCintHandler(void * p, const char * className , const char * methodName, const char * derivName = 0 );

   // for GradFunctor1D
   FunctorCintHandler(void * p1, void * p2 );

   // for Functor
   FunctorCintHandler(void * p, unsigned int dim, const char * className , const char * methodName, const char * derivName = 0 );

   // for GradFunctor
   FunctorCintHandler(void * p1, void * p2, unsigned int dim );

   //copy ctor (need for cloning)
   FunctorCintHandler(const FunctorCintHandler<Functor> & rhs) :
      BaseFunc(),
      fDim(rhs.fDim),
      fPtr(rhs.fPtr),
      //fPtr2(0),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(0)
   {}
   FunctorCintHandler(const FunctorCintHandler<GradFunctor> & rhs) :
      BaseFunc(),
      ImplFunc(),
      fDim(rhs.fDim),
      fPtr(rhs.fPtr),
      //fPtr2(rhs.fPtr2),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(rhs.fMethodCall2)
   {}
   FunctorCintHandler(const FunctorCintHandler<Functor1D> & rhs) :
      BaseFunc(),
      fDim(1),
      fPtr(rhs.fPtr),
      //fPtr2(0),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(0)
   {}
   FunctorCintHandler(const FunctorCintHandler<GradFunctor1D> & rhs) :
      BaseFunc(),
      ImplFunc(),
      fDim(1),
      fPtr(rhs.fPtr),
      //fPtr2(rhs.fPtr2),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(rhs.fMethodCall2)
   {}

   ~FunctorCintHandler() { //no op (keep pointer to TMethodCall)
   }
   BaseFunc  * Clone() const {  return new FunctorCintHandler(*this);  }

   unsigned int NDim() const {
      return fDim;
   }

private:

   unsigned int fDim;

   void * fPtr; // pointer to callable object
   //void * fPtr2; // pointer to callable object

   // function required by interface
   inline double DoEval (double ) const;
   inline double DoDerivative (double ) const;
   inline double DoDerivative (const double *,unsigned int  ) const;
   inline double DoEval (const double * x) const;

   mutable TMethodCall *fMethodCall; // pointer to method call
   mutable TMethodCall *fMethodCall2; // pointer to second method call (for deriv)

   mutable Long_t fArgs[2]; // for the address
};

//implementation of Functor methods
Functor::Functor(void * p, unsigned int dim, const char * className , const char * methodName ) :
   fImpl(new FunctorCintHandler<Functor>(p,dim,className,methodName) )
{}

Functor1D::Functor1D(void * p, const char * className , const char * methodName ) :
   fImpl(new FunctorCintHandler<Functor1D>(p,className,methodName) )
{}

GradFunctor1D::GradFunctor1D(void * p, const char * className , const char * methodName, const char * derivName ) :
   fImpl(new FunctorCintHandler<GradFunctor1D>(p,className,methodName,derivName) )
{}

GradFunctor1D::GradFunctor1D(void * p1, void * p2 ) :
   fImpl(new FunctorCintHandler<GradFunctor1D>(p1,p2) )
{}

GradFunctor::GradFunctor(void * p, unsigned int dim, const char * className , const char * methodName, const char * derivName ) :
   fImpl(new FunctorCintHandler<GradFunctor>(p,dim,className,methodName,derivName) )
{}

GradFunctor::GradFunctor(void * p1, void * p2, unsigned int dim ) :
   fImpl(new FunctorCintHandler<GradFunctor>(p1,p2,dim) )
{}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p, const char * className , const char * methodName, const char * derivMethodName ):    fDim(1)  {

   //constructor for non-grad 1D functions
   fPtr = p;
   fMethodCall2 = 0;

   //std::cout << "creating Cint functor" << std::endl;
   fMethodCall = new TMethodCall();

   if (className == 0) {
      char *funcname = G__p2f2funcname((void *) fPtr);

      if (funcname)
         fMethodCall->InitWithPrototype(funcname,"double");
   }
   else {

      TClass *cl = TClass::GetClass(className);

      if (cl) {

         if (methodName)
            fMethodCall->InitWithPrototype(cl,methodName,"double");
         else {
            fMethodCall->InitWithPrototype(cl,"operator()","double");
         }
         if (derivMethodName) {
            fMethodCall2 = new TMethodCall();
            fMethodCall2->InitWithPrototype(cl,derivMethodName,"double");
         }

         if (! fMethodCall->IsValid() ) {
            if (methodName)
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(double ) ",className,methodName);
            else
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature operator() ( double ) ",className);
         }

         if (fMethodCall2 && ! fMethodCall2->IsValid() ) {
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(double ) ",className,derivMethodName);
         }
      } else {
         Error("ROOT::Math::FunctorCintHandler","can not find any class with name %s at the address 0x%x",className,fPtr);
      }
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p1, void * p2 ) :    fDim(1) {
   //constructor for grad 1D functions
   fPtr = 0;

   //std::cout << "creating Grad Cint functor" << std::endl;
   fMethodCall = new TMethodCall();
   fMethodCall2 = new TMethodCall();

   char *funcname = G__p2f2funcname((void *) p1);

   if (funcname)
      fMethodCall->InitWithPrototype(funcname,"double");

   char *funcname2 = G__p2f2funcname((void *) p2);

   if (funcname2)
      fMethodCall2->InitWithPrototype(funcname2,"double");

   if (! fMethodCall->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No function %s found with the signature double () ( double ) at the address 0x%x",funcname,fPtr);
   }
   if (! fMethodCall2->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () ( double )",funcname2);
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p, unsigned int ndim, const char * className , const char * methodName, const char * derivMethodName ) :    fDim(ndim) {
   // for multi-dim functions
   fPtr = p;
   fMethodCall2 = 0;

   //std::cout << "creating Cint functor" << std::endl;
   fMethodCall = new TMethodCall();

   if (className == 0) {
      char *funcname = G__p2f2funcname((void *) fPtr);

      if (funcname)
         fMethodCall->InitWithPrototype(funcname,"const double*");
   }
   else {

      TClass *cl = TClass::GetClass(className);

      if (cl) {

         if (methodName)
            fMethodCall->InitWithPrototype(cl,methodName,"const double*");
         else {
            fMethodCall->InitWithPrototype(cl,"operator()","const double*");
         }
         if (derivMethodName) {
            fMethodCall2 = new TMethodCall();
            fMethodCall2->InitWithPrototype(cl,derivMethodName,"const double*,unsigned int");
         }

         if (! fMethodCall->IsValid() ) {
            if (methodName)
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(const double *) ",className,methodName);
            else
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature operator() (const double * ) ",className);
         }

         if (fMethodCall2 && ! fMethodCall2->IsValid() ) {
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(const double *, unsigned int ) ",className,derivMethodName);
         }
      } else {
         Error("ROOT::Math::FunctorCintHandler","can not find any class with name %s at the address 0x%x",className,fPtr);
      }
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p1, void * p2, unsigned int dim ) :    fDim(dim) {
   //constructor for grad 1D functions

   fPtr = 0;

   //std::cout << "creating Grad Cint functor" << std::endl;
   fMethodCall = new TMethodCall();
   fMethodCall2 = new TMethodCall();

   char *funcname = G__p2f2funcname((void *) p1);

   if (funcname)
      fMethodCall->InitWithPrototype(funcname,"const double *");

   char *funcname2 = G__p2f2funcname((void *) p2);

   if (funcname2)
      fMethodCall2->InitWithPrototype(funcname2,"const double *,UInt_t");

   if (! fMethodCall->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () (const double * ) ",funcname);
   }
   if (! fMethodCall2->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () (const double *, unsigned int) ",funcname2);
   }
}

template<class PF>
inline double FunctorCintHandler<PF>::DoEval (double x) const {
   //fArgs[0] = (Long_t)&x;
   fMethodCall->ResetParam();
   fMethodCall->SetParam(x);
   double result = 0;
   // distinguish the case of free functions
   if (fPtr)
      fMethodCall->Execute(fPtr,result);
   else
      fMethodCall->Execute(result);
   //std::cout << "execute doeval for x = " << x << " on " << fPtr << "  result " << result << std::endl;
   return result;
}
template<class PF>
inline double FunctorCintHandler<PF>::DoDerivative (double x) const {
   if (!fMethodCall2) return 0;

   fMethodCall2->ResetParam();
   fMethodCall2->SetParam(x);
   double result = 0;

   // distinguish the case of free functions
   if (fPtr) {
      fMethodCall2->Execute(fPtr,result);
      //std::cout << "execute doDerivative for x = " << x << " on " << fPtr2 << "  result " << result << std::endl;
   }
   else {
      fMethodCall2->Execute(result);
   }
   return result;
}

template<class PF>
inline double FunctorCintHandler<PF>::DoEval (const double *x) const {
   // for multi-dim functions
   //fArgs[0] = (Long_t)&x;
   fMethodCall->ResetParam();
   fArgs[0] = (Long_t)x;
   fMethodCall->SetParamPtrs(fArgs);
   double result = 0;
   // distinguish the case of free functions (fPtr ==0)
   if (fPtr)
      fMethodCall->Execute(fPtr,result);
   else
      fMethodCall->Execute(result);
   //std::cout << "execute doeval for x = " << x << " on " << fPtr << "  result " << result << std::endl;
   return result;
}

template<class PF>
inline double FunctorCintHandler<PF>::DoDerivative (const double *x, unsigned int ipar) const {
   // derivative for multi-dim functions
   //fMethodCall2->ResetParam();
//    fArgs[0] = (Long_t)x;
//    fArgs[1] = (Long_t)&ipar;
   char * params = Form(" %p ,  %d",x,ipar);
   //fMethodCall2->SetParamPtrs(fArgs);

   double result = 0;
   // distinguish the case of free functions
   if (fPtr) {
      fMethodCall2->Execute(fPtr,params,result);
   }
   else {
      //std::cout << "execute doDerivative for x = " << *x <<  "  result " << result << std::endl;
      fMethodCall2->Execute(params,result);
   }
   return result;
}

} //end namespace Math

} //end namespace ROOT

#undef MAKE_CINT_FUNCTOR
<commit_msg>fixes for Solaris forgot in previous commit<commit_after>// implentation of functor for interpreted functions

#define MAKE_CINT_FUNCTOR

#include <Math/Functor.h>
#include <iostream>

#include "TClass.h"
#include "TMethodCall.h"
#include "TError.h"
#include "G__ci.h"

namespace ROOT {
namespace Math {

//#if defined(__MAKECINT__) || defined(G__DICTIONARY)

//Functor handler for Cint functions

template<class ParentFunctor>
class FunctorCintHandler : public ParentFunctor::Impl
{
public:
   typedef typename ParentFunctor::Impl ImplFunc;
   typedef typename ImplFunc::BaseFunc BaseFunc;

   // for 1D functor1d
   FunctorCintHandler(void * p, const char * className , const char * methodName, const char * derivName = 0 );

   // for GradFunctor1D
   FunctorCintHandler(void * p1, void * p2 );

   // for Functor
   FunctorCintHandler(void * p, unsigned int dim, const char * className , const char * methodName, const char * derivName = 0 );

   // for GradFunctor
   FunctorCintHandler(void * p1, void * p2, unsigned int dim );

   //copy ctor (need for cloning)
   FunctorCintHandler(const FunctorCintHandler<Functor> & rhs) :
      BaseFunc(),
      fDim(rhs.fDim),
      fPtr(rhs.fPtr),
      //fPtr2(0),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(0)
   {}
   FunctorCintHandler(const FunctorCintHandler<GradFunctor> & rhs) :
      BaseFunc(),
      ImplFunc(),
      fDim(rhs.fDim),
      fPtr(rhs.fPtr),
      //fPtr2(rhs.fPtr2),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(rhs.fMethodCall2)
   {}
   FunctorCintHandler(const FunctorCintHandler<Functor1D> & rhs) :
      BaseFunc(),
      fDim(1),
      fPtr(rhs.fPtr),
      //fPtr2(0),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(0)
   {}
   FunctorCintHandler(const FunctorCintHandler<GradFunctor1D> & rhs) :
      BaseFunc(),
      ImplFunc(),
      fDim(1),
      fPtr(rhs.fPtr),
      //fPtr2(rhs.fPtr2),
      fMethodCall(rhs.fMethodCall),
      fMethodCall2(rhs.fMethodCall2)
   {}

   ~FunctorCintHandler() { //no op (keep pointer to TMethodCall)
   }
   BaseFunc  * Clone() const {  return new FunctorCintHandler(*this);  }

   unsigned int NDim() const {
      return fDim;
   }

private:

   unsigned int fDim;

   void * fPtr; // pointer to callable object
   //void * fPtr2; // pointer to callable object

   // function required by interface
   inline double DoEval (double x) const;
   inline double DoDerivative (double x) const;
   inline double DoDerivative (const double * x,unsigned int ipar ) const;
   inline double DoEval (const double * x) const;

   mutable TMethodCall *fMethodCall; // pointer to method call
   mutable TMethodCall *fMethodCall2; // pointer to second method call (for deriv)

   mutable Long_t fArgs[2]; // for the address
};

//implementation of Functor methods
Functor::Functor(void * p, unsigned int dim, const char * className , const char * methodName ) :
   fImpl(new FunctorCintHandler<Functor>(p,dim,className,methodName) )
{}

Functor1D::Functor1D(void * p, const char * className , const char * methodName ) :
   fImpl(new FunctorCintHandler<Functor1D>(p,className,methodName) )
{}

GradFunctor1D::GradFunctor1D(void * p, const char * className , const char * methodName, const char * derivName ) :
   fImpl(new FunctorCintHandler<GradFunctor1D>(p,className,methodName,derivName) )
{}

GradFunctor1D::GradFunctor1D(void * p1, void * p2 ) :
   fImpl(new FunctorCintHandler<GradFunctor1D>(p1,p2) )
{}

GradFunctor::GradFunctor(void * p, unsigned int dim, const char * className , const char * methodName, const char * derivName ) :
   fImpl(new FunctorCintHandler<GradFunctor>(p,dim,className,methodName,derivName) )
{}

GradFunctor::GradFunctor(void * p1, void * p2, unsigned int dim ) :
   fImpl(new FunctorCintHandler<GradFunctor>(p1,p2,dim) )
{}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p, const char * className , const char * methodName, const char * derivMethodName ):    fDim(1)  {

   //constructor for non-grad 1D functions
   fPtr = p;
   fMethodCall2 = 0;

   //std::cout << "creating Cint functor" << std::endl;
   fMethodCall = new TMethodCall();

   if (className == 0) {
      char *funcname = G__p2f2funcname((void *) fPtr);

      if (funcname)
         fMethodCall->InitWithPrototype(funcname,"double");
   }
   else {

      TClass *cl = TClass::GetClass(className);

      if (cl) {

         if (methodName)
            fMethodCall->InitWithPrototype(cl,methodName,"double");
         else {
            fMethodCall->InitWithPrototype(cl,"operator()","double");
         }
         if (derivMethodName) {
            fMethodCall2 = new TMethodCall();
            fMethodCall2->InitWithPrototype(cl,derivMethodName,"double");
         }

         if (! fMethodCall->IsValid() ) {
            if (methodName)
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(double ) ",className,methodName);
            else
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature operator() ( double ) ",className);
         }

         if (fMethodCall2 && ! fMethodCall2->IsValid() ) {
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(double ) ",className,derivMethodName);
         }
      } else {
         Error("ROOT::Math::FunctorCintHandler","can not find any class with name %s at the address 0x%x",className,fPtr);
      }
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p1, void * p2 ) :    fDim(1) {
   //constructor for grad 1D functions
   fPtr = 0;

   //std::cout << "creating Grad Cint functor" << std::endl;
   fMethodCall = new TMethodCall();
   fMethodCall2 = new TMethodCall();

   char *funcname = G__p2f2funcname((void *) p1);

   if (funcname)
      fMethodCall->InitWithPrototype(funcname,"double");

   char *funcname2 = G__p2f2funcname((void *) p2);

   if (funcname2)
      fMethodCall2->InitWithPrototype(funcname2,"double");

   if (! fMethodCall->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No function %s found with the signature double () ( double ) at the address 0x%x",funcname,fPtr);
   }
   if (! fMethodCall2->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () ( double )",funcname2);
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p, unsigned int ndim, const char * className , const char * methodName, const char * derivMethodName ) :    fDim(ndim) {
   // for multi-dim functions
   fPtr = p;
   fMethodCall2 = 0;

   //std::cout << "creating Cint functor" << std::endl;
   fMethodCall = new TMethodCall();

   if (className == 0) {
      char *funcname = G__p2f2funcname((void *) fPtr);

      if (funcname)
         fMethodCall->InitWithPrototype(funcname,"const double*");
   }
   else {

      TClass *cl = TClass::GetClass(className);

      if (cl) {

         if (methodName)
            fMethodCall->InitWithPrototype(cl,methodName,"const double*");
         else {
            fMethodCall->InitWithPrototype(cl,"operator()","const double*");
         }
         if (derivMethodName) {
            fMethodCall2 = new TMethodCall();
            fMethodCall2->InitWithPrototype(cl,derivMethodName,"const double*,unsigned int");
         }

         if (! fMethodCall->IsValid() ) {
            if (methodName)
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(const double *) ",className,methodName);
            else
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature operator() (const double * ) ",className);
         }

         if (fMethodCall2 && ! fMethodCall2->IsValid() ) {
               Error("ROOT::Math::FunctorCintHandler","No function found in class %s with the signature %s(const double *, unsigned int ) ",className,derivMethodName);
         }
      } else {
         Error("ROOT::Math::FunctorCintHandler","can not find any class with name %s at the address 0x%x",className,fPtr);
      }
   }
}

template<class PF>
FunctorCintHandler<PF>::FunctorCintHandler(void * p1, void * p2, unsigned int dim ) :    fDim(dim) {
   //constructor for grad 1D functions

   fPtr = 0;

   //std::cout << "creating Grad Cint functor" << std::endl;
   fMethodCall = new TMethodCall();
   fMethodCall2 = new TMethodCall();

   char *funcname = G__p2f2funcname((void *) p1);

   if (funcname)
      fMethodCall->InitWithPrototype(funcname,"const double *");

   char *funcname2 = G__p2f2funcname((void *) p2);

   if (funcname2)
      fMethodCall2->InitWithPrototype(funcname2,"const double *,UInt_t");

   if (! fMethodCall->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () (const double * ) ",funcname);
   }
   if (! fMethodCall2->IsValid() ) {
      Error("ROOT::Math::FunctorCintHandler","No free function %s found with the signature double () (const double *, unsigned int) ",funcname2);
   }
}

template<class PF>
inline double FunctorCintHandler<PF>::DoEval (double x) const {
   //fArgs[0] = (Long_t)&x;
   fMethodCall->ResetParam();
   fMethodCall->SetParam(x);
   double result = 0;
   // distinguish the case of free functions
   if (fPtr)
      fMethodCall->Execute(fPtr,result);
   else
      fMethodCall->Execute(result);
   //std::cout << "execute doeval for x = " << x << " on " << fPtr << "  result " << result << std::endl;
   return result;
}
template<class PF>
inline double FunctorCintHandler<PF>::DoDerivative (double x) const {
   if (!fMethodCall2) return 0;

   fMethodCall2->ResetParam();
   fMethodCall2->SetParam(x);
   double result = 0;

   // distinguish the case of free functions
   if (fPtr) {
      fMethodCall2->Execute(fPtr,result);
      //std::cout << "execute doDerivative for x = " << x << " on " << fPtr2 << "  result " << result << std::endl;
   }
   else {
      fMethodCall2->Execute(result);
   }
   return result;
}

template<class PF>
inline double FunctorCintHandler<PF>::DoEval (const double *x) const {
   // for multi-dim functions
   //fArgs[0] = (Long_t)&x;
   fMethodCall->ResetParam();
   fArgs[0] = (Long_t)x;
   fMethodCall->SetParamPtrs(fArgs);
   double result = 0;
   // distinguish the case of free functions (fPtr ==0)
   if (fPtr)
      fMethodCall->Execute(fPtr,result);
   else
      fMethodCall->Execute(result);
   //std::cout << "execute doeval for x = " << x << " on " << fPtr << "  result " << result << std::endl;
   return result;
}

template<class PF>
inline double FunctorCintHandler<PF>::DoDerivative (const double *x, unsigned int ipar) const {
   // derivative for multi-dim functions
   //fMethodCall2->ResetParam();
//    fArgs[0] = (Long_t)x;
//    fArgs[1] = (Long_t)&ipar;
   char * params = Form(" %p ,  %d",x,ipar);
   //fMethodCall2->SetParamPtrs(fArgs);

   double result = 0;
   // distinguish the case of free functions
   if (fPtr) {
      fMethodCall2->Execute(fPtr,params,result);
   }
   else {
      //std::cout << "execute doDerivative for x = " << *x <<  "  result " << result << std::endl;
      fMethodCall2->Execute(params,result);
   }
   return result;
}

} //end namespace Math

} //end namespace ROOT

#undef MAKE_CINT_FUNCTOR
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "activemq/test/openwire/OpenwireAsyncSenderTest.h"
#include "activemq/test/openwire/OpenwireCmsTemplateTest.h"
#include "activemq/test/openwire/OpenwireDurableTest.h"
#include "activemq/test/openwire/OpenwireExpirationTest.h"
#include "activemq/test/openwire/OpenwireSimpleRollbackTest.h"
#include "activemq/test/openwire/OpenwireSimpleTest.h"
#include "activemq/test/openwire/OpenwireTransactionTest.h"
#include "activemq/test/openwire/OpenwireTempDestinationTest.h"
#include "activemq/test/openwire/OpenwireSlowListenerTest.h"
#include "activemq/test/openwire/OpenwireJmsMessageGroupsTest.h"

//#include "activemq/test/stomp/StompAsyncSenderTest.h"
//#include "activemq/test/stomp/StompCmsTemplateTest.h"
//#include "activemq/test/stomp/StompDurableTest.h"
//#include "activemq/test/stomp/StompExpirationTest.h"
//#include "activemq/test/stomp/StompSimpleRollbackTest.h"
//#include "activemq/test/stomp/StompSimpleTest.h"
//#include "activemq/test/stomp/StompSlowListenerTest.h"
//#include "activemq/test/stomp/StompTransactionTest.h"
//#include "activemq/test/stomp/StompJmsMessageGroupsTest.h"

// Openwire Tests
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireAsyncSenderTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireCmsTemplateTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireDurableTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireExpirationTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSimpleRollbackTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSimpleTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireTransactionTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSlowListenerTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireTempDestinationTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireJmsMessageGroupsTest );

// Stomp Tests
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompAsyncSenderTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompCmsTemplateTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompDurableTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompExpirationTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSimpleRollbackTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSimpleTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompTransactionTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSlowListenerTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompJmsMessageGroupsTest );
<commit_msg>Enable the tests that are known to work right now, disable the one's that segfault.  This will allow the suite to at least run to completion.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "activemq/test/openwire/OpenwireAsyncSenderTest.h"
#include "activemq/test/openwire/OpenwireCmsTemplateTest.h"
#include "activemq/test/openwire/OpenwireDurableTest.h"
#include "activemq/test/openwire/OpenwireExpirationTest.h"
#include "activemq/test/openwire/OpenwireSimpleRollbackTest.h"
#include "activemq/test/openwire/OpenwireSimpleTest.h"
#include "activemq/test/openwire/OpenwireTransactionTest.h"
#include "activemq/test/openwire/OpenwireTempDestinationTest.h"
#include "activemq/test/openwire/OpenwireSlowListenerTest.h"
#include "activemq/test/openwire/OpenwireJmsMessageGroupsTest.h"

//#include "activemq/test/stomp/StompAsyncSenderTest.h"
//#include "activemq/test/stomp/StompCmsTemplateTest.h"
//#include "activemq/test/stomp/StompDurableTest.h"
//#include "activemq/test/stomp/StompExpirationTest.h"
//#include "activemq/test/stomp/StompSimpleRollbackTest.h"
//#include "activemq/test/stomp/StompSimpleTest.h"
//#include "activemq/test/stomp/StompSlowListenerTest.h"
//#include "activemq/test/stomp/StompTransactionTest.h"
//#include "activemq/test/stomp/StompJmsMessageGroupsTest.h"

// Openwire Tests
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireAsyncSenderTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireCmsTemplateTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireDurableTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireExpirationTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSimpleRollbackTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSimpleTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireTransactionTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireSlowListenerTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireTempDestinationTest );
CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::openwire::OpenwireJmsMessageGroupsTest );

// Stomp Tests
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompAsyncSenderTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompCmsTemplateTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompDurableTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompExpirationTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSimpleRollbackTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSimpleTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompTransactionTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompSlowListenerTest );
//CPPUNIT_TEST_SUITE_REGISTRATION( activemq::test::stomp::StompJmsMessageGroupsTest );
<|endoftext|>


<commit_before>#include "xchainer/python/array.h"

#include <algorithm>

#include <pybind11/numpy.h>

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"

namespace xchainer {

namespace py = pybind11;

Dtype NumpyDtypeToDtype(py::dtype npdtype) {
    switch (npdtype.kind()) {
        case 'b':
            return Dtype::kBool;
        case 'i':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kInt8;
                case 2:
                    return Dtype::kInt16;
                case 4:
                    return Dtype::kInt32;
                case 8:
                    return Dtype::kInt64;
                default:
                    break;
            }
            break;
        case 'u':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kUInt8;
                default:
                    break;
            }
            break;
        case 'f':
            switch (npdtype.itemsize()) {
                case 4:
                    return Dtype::kFloat32;
                case 8:
                    return Dtype::kFloat64;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    throw DtypeError("unsupported NumPy dtype");
}

Array MakeArrayFromList(const Shape& shape, Dtype dtype, py::list list) {
    auto total_size = shape.total_size();
    auto bytes = GetElementSize(dtype) * total_size;
    if (static_cast<size_t>(total_size) != list.size()) {
        throw DimensionError("Invalid data length");
    }

    std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
    auto func = [&](auto dummy) {
        using T = decltype(dummy);
        std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
    };
    switch (dtype) {
        case Dtype::kBool:
            func(static_cast<bool>(0));
            break;
        case Dtype::kInt8:
            func(static_cast<int8_t>(0));
            break;
        case Dtype::kInt16:
            func(static_cast<int16_t>(0));
            break;
        case Dtype::kInt32:
            func(static_cast<int32_t>(0));
            break;
        case Dtype::kInt64:
            func(static_cast<int64_t>(0));
            break;
        case Dtype::kUInt8:
            func(static_cast<uint8_t>(0));
            break;
        case Dtype::kFloat32:
            func(static_cast<float>(0));
            break;
        case Dtype::kFloat64:
            func(static_cast<double>(0));
            break;
        default:
            assert(0);
    }
    return Array{shape, dtype, ptr};
}

std::unique_ptr<Array> MakeArrayFromNumpyArray(py::array array) {
    if (!(array.flags() & py::array::c_style)) {
        throw DimensionError("cannot convert non-contiguous NumPy array to Array");
    }

    // TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
    Dtype dtype = NumpyDtypeToDtype(array.dtype());
    py::buffer_info info = array.request();
    Shape shape(info.shape);

    // Assuming pybind increases the reference count to the underlying NumPy object, we choose not to copy the data
    std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());

    return std::make_unique<Array>(shape, dtype, data);
}

void InitXchainerArray(pybind11::module& m) {
    py::class_<Array>{m, "Array"}
        .def(py::init(&MakeArrayFromList))
        .def(py::init(&MakeArrayFromNumpyArray))
        .def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
        .def_property_readonly("dtype", &Array::dtype)
        .def_property_readonly("shape", &Array::shape)
        .def_property_readonly("is_contiguous", &Array::is_contiguous)
        .def_property_readonly("total_size", &Array::total_size)
        .def_property_readonly("element_bytes", &Array::element_bytes)
        .def_property_readonly("total_bytes", &Array::total_bytes)
        .def_property_readonly("offset", &Array::offset)
        .def_property_readonly("debug_flat_data",
                               [](const Array& self) {  // This method is a stub for testing
                                   py::list list;
                                   auto size = self.total_size();
                                   auto func = [&](auto dummy) {
                                       using T = decltype(dummy);
                                       const T& data = *std::static_pointer_cast<const T>(self.data());
                                       for (int64_t i = 0; i < size; ++i) {
                                           list.append((&data)[i]);
                                       }
                                   };
                                   switch (self.dtype()) {
                                       case Dtype::kBool:
                                           func(static_cast<bool>(0));
                                           break;
                                       case Dtype::kInt8:
                                           func(static_cast<int8_t>(0));
                                           break;
                                       case Dtype::kInt16:
                                           func(static_cast<int16_t>(0));
                                           break;
                                       case Dtype::kInt32:
                                           func(static_cast<int32_t>(0));
                                           break;
                                       case Dtype::kInt64:
                                           func(static_cast<int64_t>(0));
                                           break;
                                       case Dtype::kUInt8:
                                           func(static_cast<uint8_t>(0));
                                           break;
                                       case Dtype::kFloat32:
                                           func(static_cast<float>(0));
                                           break;
                                       case Dtype::kFloat64:
                                           func(static_cast<double>(0));
                                           break;
                                       default:
                                           assert(0);
                                   }
                                   return list;
                               })
        .def("__add__", static_cast<Array (Array::*)(const Array&) const>(&Array::Add))
        .def("__iadd__", static_cast<Array& (Array::*)(const Array&)>(&Array::IAdd))
        .def("__mul__", static_cast<Array (Array::*)(const Array&) const>(&Array::Mul))
        .def("__imul__", static_cast<Array& (Array::*)(const Array&)>(&Array::IMul));
}

}  // namespace xchainer
<commit_msg>Fix Array comment<commit_after>#include "xchainer/python/array.h"

#include <algorithm>

#include <pybind11/numpy.h>

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"

namespace xchainer {

namespace py = pybind11;

Dtype NumpyDtypeToDtype(py::dtype npdtype) {
    switch (npdtype.kind()) {
        case 'b':
            return Dtype::kBool;
        case 'i':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kInt8;
                case 2:
                    return Dtype::kInt16;
                case 4:
                    return Dtype::kInt32;
                case 8:
                    return Dtype::kInt64;
                default:
                    break;
            }
            break;
        case 'u':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kUInt8;
                default:
                    break;
            }
            break;
        case 'f':
            switch (npdtype.itemsize()) {
                case 4:
                    return Dtype::kFloat32;
                case 8:
                    return Dtype::kFloat64;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    throw DtypeError("unsupported NumPy dtype");
}

Array MakeArrayFromList(const Shape& shape, Dtype dtype, py::list list) {
    auto total_size = shape.total_size();
    auto bytes = GetElementSize(dtype) * total_size;
    if (static_cast<size_t>(total_size) != list.size()) {
        throw DimensionError("Invalid data length");
    }

    std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
    auto func = [&](auto dummy) {
        using T = decltype(dummy);
        std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
    };
    switch (dtype) {
        case Dtype::kBool:
            func(static_cast<bool>(0));
            break;
        case Dtype::kInt8:
            func(static_cast<int8_t>(0));
            break;
        case Dtype::kInt16:
            func(static_cast<int16_t>(0));
            break;
        case Dtype::kInt32:
            func(static_cast<int32_t>(0));
            break;
        case Dtype::kInt64:
            func(static_cast<int64_t>(0));
            break;
        case Dtype::kUInt8:
            func(static_cast<uint8_t>(0));
            break;
        case Dtype::kFloat32:
            func(static_cast<float>(0));
            break;
        case Dtype::kFloat64:
            func(static_cast<double>(0));
            break;
        default:
            assert(0);
    }
    return Array{shape, dtype, ptr};
}

std::unique_ptr<Array> MakeArrayFromNumpyArray(py::array array) {
    if (!(array.flags() & py::array::c_style)) {
        throw DimensionError("cannot convert non-contiguous NumPy array to Array");
    }

    // TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
    Dtype dtype = NumpyDtypeToDtype(array.dtype());
    py::buffer_info info = array.request();
    Shape shape(info.shape);

    // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
    std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());

    return std::make_unique<Array>(shape, dtype, data);
}

void InitXchainerArray(pybind11::module& m) {
    py::class_<Array>{m, "Array"}
        .def(py::init(&MakeArrayFromList))
        .def(py::init(&MakeArrayFromNumpyArray))
        .def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
        .def_property_readonly("dtype", &Array::dtype)
        .def_property_readonly("shape", &Array::shape)
        .def_property_readonly("is_contiguous", &Array::is_contiguous)
        .def_property_readonly("total_size", &Array::total_size)
        .def_property_readonly("element_bytes", &Array::element_bytes)
        .def_property_readonly("total_bytes", &Array::total_bytes)
        .def_property_readonly("offset", &Array::offset)
        .def_property_readonly("debug_flat_data",
                               [](const Array& self) {  // This method is a stub for testing
                                   py::list list;
                                   auto size = self.total_size();
                                   auto func = [&](auto dummy) {
                                       using T = decltype(dummy);
                                       const T& data = *std::static_pointer_cast<const T>(self.data());
                                       for (int64_t i = 0; i < size; ++i) {
                                           list.append((&data)[i]);
                                       }
                                   };
                                   switch (self.dtype()) {
                                       case Dtype::kBool:
                                           func(static_cast<bool>(0));
                                           break;
                                       case Dtype::kInt8:
                                           func(static_cast<int8_t>(0));
                                           break;
                                       case Dtype::kInt16:
                                           func(static_cast<int16_t>(0));
                                           break;
                                       case Dtype::kInt32:
                                           func(static_cast<int32_t>(0));
                                           break;
                                       case Dtype::kInt64:
                                           func(static_cast<int64_t>(0));
                                           break;
                                       case Dtype::kUInt8:
                                           func(static_cast<uint8_t>(0));
                                           break;
                                       case Dtype::kFloat32:
                                           func(static_cast<float>(0));
                                           break;
                                       case Dtype::kFloat64:
                                           func(static_cast<double>(0));
                                           break;
                                       default:
                                           assert(0);
                                   }
                                   return list;
                               })
        .def("__add__", static_cast<Array (Array::*)(const Array&) const>(&Array::Add))
        .def("__iadd__", static_cast<Array& (Array::*)(const Array&)>(&Array::IAdd))
        .def("__mul__", static_cast<Array (Array::*)(const Array&) const>(&Array::Mul))
        .def("__imul__", static_cast<Array& (Array::*)(const Array&)>(&Array::IMul));
}

}  // namespace xchainer
<|endoftext|>


<commit_before>//
//  yas_ui_color.cpp
//

#include "yas_ui_color.h"

using namespace yas;

bool ui::color::operator==(ui::color const &rhs) const {
    return red == rhs.red && green == rhs.green && blue == rhs.blue;
}

bool ui::color::operator!=(ui::color const &rhs) const {
    return red != rhs.red || green != rhs.green || blue != rhs.blue;
}

ui::color ui::color::operator*(ui::color const &rhs) const {
    return {.red = this->red * rhs.red, .green = this->green * rhs.green, .blue = this->blue * rhs.blue};
}

ui::color ui::color::operator*(float const &rhs) const {
    return {.red = this->red * rhs, .green = this->green * rhs, .blue = this->blue * rhs};
}

ui::color::operator bool() const {
    return red != 0 || green != 0 || blue != 0;
}

simd::float4 yas::to_float4(ui::color const &color, float alpha) {
    return simd::float4{color.red, color.green, color.blue, alpha};
}

std::string yas::to_string(ui::color const &color) {
    return "{" + std::to_string(color.red) + ", " + std::to_string(color.green) + ", " + std::to_string(color.blue) +
           "}";
}

std::ostream &operator<<(std::ostream &os, yas::ui::color const &color) {
    os << to_string(color);
    return os;
}

#pragma mark - static colors

ui::color const &yas::ui::white_color() {
    static ui::color const _color{.red = 1.0f, .green = 1.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::gray_color() {
    static ui::color const _color{.red = 0.5f, .green = 0.5f, .blue = 0.5f};
    return _color;
}

ui::color const &yas::ui::dark_gray_color() {
    static ui::color const _color{.red = 0.333f, .green = 0.333f, .blue = 0.333f};
    return _color;
}

ui::color const &yas::ui::light_gray_color() {
    static ui::color const _color{.red = 0.667f, .green = 0.667f, .blue = 0.667f};
    return _color;
}

ui::color const &yas::ui::black_color() {
    static ui::color const _color{.red = 0.0f, .green = 0.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::red_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::green_color() {
    static ui::color const _color{.red = 0.0f, .green = 1.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::blue_color() {
    static ui::color const _color{.red = 0.0f, .green = 0.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::cyan_color() {
    static ui::color const _color{.red = 0.0f, .green = 1.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::yellow_color() {
    static ui::color const _color{.red = 1.0f, .green = 1.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::magenta_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::orange_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.5f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::purple_color() {
    static ui::color const _color{.red = 0.5f, .green = 0.0f, .blue = 0.5f};
    return _color;
}

ui::color const &yas::ui::brown_color() {
    static ui::color const _color{.red = 0.6f, .green = 0.4f, .blue = 0.2f};
    return _color;
}
<commit_msg>color this<commit_after>//
//  yas_ui_color.cpp
//

#include "yas_ui_color.h"

using namespace yas;

bool ui::color::operator==(ui::color const &rhs) const {
    return this->red == rhs.red && this->green == rhs.green && this->blue == rhs.blue;
}

bool ui::color::operator!=(ui::color const &rhs) const {
    return this->red != rhs.red || this->green != rhs.green || this->blue != rhs.blue;
}

ui::color ui::color::operator*(ui::color const &rhs) const {
    return {.red = this->red * rhs.red, .green = this->green * rhs.green, .blue = this->blue * rhs.blue};
}

ui::color ui::color::operator*(float const &rhs) const {
    return {.red = this->red * rhs, .green = this->green * rhs, .blue = this->blue * rhs};
}

ui::color::operator bool() const {
    return this->red != 0 || this->green != 0 || this->blue != 0;
}

simd::float4 yas::to_float4(ui::color const &color, float alpha) {
    return simd::float4{color.red, color.green, color.blue, alpha};
}

std::string yas::to_string(ui::color const &color) {
    return "{" + std::to_string(color.red) + ", " + std::to_string(color.green) + ", " + std::to_string(color.blue) +
           "}";
}

std::ostream &operator<<(std::ostream &os, yas::ui::color const &color) {
    os << to_string(color);
    return os;
}

#pragma mark - static colors

ui::color const &yas::ui::white_color() {
    static ui::color const _color{.red = 1.0f, .green = 1.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::gray_color() {
    static ui::color const _color{.red = 0.5f, .green = 0.5f, .blue = 0.5f};
    return _color;
}

ui::color const &yas::ui::dark_gray_color() {
    static ui::color const _color{.red = 0.333f, .green = 0.333f, .blue = 0.333f};
    return _color;
}

ui::color const &yas::ui::light_gray_color() {
    static ui::color const _color{.red = 0.667f, .green = 0.667f, .blue = 0.667f};
    return _color;
}

ui::color const &yas::ui::black_color() {
    static ui::color const _color{.red = 0.0f, .green = 0.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::red_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::green_color() {
    static ui::color const _color{.red = 0.0f, .green = 1.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::blue_color() {
    static ui::color const _color{.red = 0.0f, .green = 0.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::cyan_color() {
    static ui::color const _color{.red = 0.0f, .green = 1.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::yellow_color() {
    static ui::color const _color{.red = 1.0f, .green = 1.0f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::magenta_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.0f, .blue = 1.0f};
    return _color;
}

ui::color const &yas::ui::orange_color() {
    static ui::color const _color{.red = 1.0f, .green = 0.5f, .blue = 0.0f};
    return _color;
}

ui::color const &yas::ui::purple_color() {
    static ui::color const _color{.red = 0.5f, .green = 0.0f, .blue = 0.5f};
    return _color;
}

ui::color const &yas::ui::brown_color() {
    static ui::color const _color{.red = 0.6f, .green = 0.4f, .blue = 0.2f};
    return _color;
}
<|endoftext|>


<commit_before>#include "xchainer/python/array.h"

#include <algorithm>
#include <cstdint>

#include <pybind11/numpy.h>
#include <pybind11/operators.h>

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;

Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
    switch (npdtype.kind()) {
        case 'b':
            return Dtype::kBool;
        case 'i':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kInt8;
                case 2:
                    return Dtype::kInt16;
                case 4:
                    return Dtype::kInt32;
                case 8:
                    return Dtype::kInt64;
                default:
                    break;
            }
            break;
        case 'u':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kUInt8;
                default:
                    break;
            }
            break;
        case 'f':
            switch (npdtype.itemsize()) {
                case 4:
                    return Dtype::kFloat32;
                case 8:
                    return Dtype::kFloat64;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    throw DtypeError("unsupported NumPy dtype");
}

Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
    auto total_size = shape.total_size();
    auto bytes = GetElementSize(dtype) * total_size;
    if (static_cast<size_t>(total_size) != list.size()) {
        throw DimensionError("Invalid data length");
    }

    // Allocate a buffer and copy data
    std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
    VisitDtype(dtype, [&](auto pt) {
        using T = typename decltype(pt)::type;
        std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
    });
    return Array::FromBuffer(shape, dtype, ptr);
}

Array MakeArray(py::array array) {
    if ((array.flags() & py::array::c_style) == 0) {
        throw DimensionError("cannot convert non-contiguous NumPy array to Array");
    }

    Dtype dtype = NumpyDtypeToDtype(array.dtype());
    py::buffer_info info = array.request();
    Shape shape(info.shape);

    // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
    std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());

    return Array::FromBuffer(shape, dtype, data);
}

py::buffer_info MakeNumpyArrayFromArray(Array& self) {
    if (!self.is_contiguous()) {
        throw DimensionError("cannot convert non-contiguous Array to NumPy array");
    }

    int64_t itemsize{GetElementSize(self.dtype())};
    const Shape& shape = self.shape();

    // compute C-contiguous strides
    size_t ndim = self.ndim();
    std::vector<size_t> strides(ndim);
    if (ndim > 0) {
        std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
        strides.back() = 1;
        std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
    }

    return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}

void InitXchainerArray(pybind11::module& m) {
    py::class_<Array>{m, "Array", py::buffer_protocol()}
        .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
        .def(py::init(py::overload_cast<py::array>(&MakeArray)))
        .def_buffer(&MakeNumpyArrayFromArray)
        .def("view", &Array::MakeView)
        .def(py::self += py::self)
        .def(py::self *= py::self)
        .def(py::self + py::self)
        .def(py::self * py::self)
        .def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
        .def("copy", &Array::Copy)
        // .def_property("requires_grad", &Array::requires_grad, &Array::set_requires_grad)
        .def_property("requires_grad", [](Array& self) -> bool { return self.RequiresGrad(); },
                      [](Array& self, bool requires_grad) {
                          if (requires_grad) {
                              self.RequireGrad();
                          } else {
                              //  TODO(hvy): Not yet implemented
                          }
                      })
        .def_property("grad",
                      [](Array& self) -> nonstd::optional<Array> {
                          if (self.RequiresGrad()) {
                              return self.Grad()->MakeView();
                          } else {
                              return nonstd::nullopt;
                          }
                      },
                      [](Array& self, Array* grad) {
                          if (grad) {
                              if (!self.RequiresGrad()) {
                                  // Create the ArrayNode required in order to set the gradient
                                  self.RequireGrad();
                              }
                              self.SetGrad(grad->MakeView());
                          } else {
                              self.ClearGrad();
                          }
                      })
        .def_property_readonly("dtype", &Array::dtype)
        .def_property_readonly("element_bytes", &Array::element_bytes)
        .def_property_readonly("is_contiguous", &Array::is_contiguous)
        .def_property_readonly("ndim", &Array::ndim)
        .def_property_readonly("offset", &Array::offset)
        .def_property_readonly("shape", &Array::shape)
        .def_property_readonly("total_bytes", &Array::total_bytes)
        .def_property_readonly("total_size", &Array::total_size)
        .def_property_readonly("_debug_data_memory_address",  // These methods starting with `_debug_` are stubs for testing
                               [](const Array& self) { return reinterpret_cast<std::uintptr_t>(self.data().get()); })
        .def_property_readonly("_debug_flat_data", [](const Array& self) {
            py::list list;
            auto size = self.total_size();

            // Copy data into the list
            VisitDtype(self.dtype(), [&](auto pt) {
                using T = typename decltype(pt)::type;
                const T& data = *std::static_pointer_cast<const T>(self.data());
                for (int64_t i = 0; i < size; ++i) {
                    list.append((&data)[i]);
                }
            });

            return list;
        });
}

}  // namespace xchainer
<commit_msg>Remove comment<commit_after>#include "xchainer/python/array.h"

#include <algorithm>
#include <cstdint>

#include <pybind11/numpy.h>
#include <pybind11/operators.h>

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;

Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
    switch (npdtype.kind()) {
        case 'b':
            return Dtype::kBool;
        case 'i':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kInt8;
                case 2:
                    return Dtype::kInt16;
                case 4:
                    return Dtype::kInt32;
                case 8:
                    return Dtype::kInt64;
                default:
                    break;
            }
            break;
        case 'u':
            switch (npdtype.itemsize()) {
                case 1:
                    return Dtype::kUInt8;
                default:
                    break;
            }
            break;
        case 'f':
            switch (npdtype.itemsize()) {
                case 4:
                    return Dtype::kFloat32;
                case 8:
                    return Dtype::kFloat64;
                default:
                    break;
            }
            break;
        default:
            break;
    }
    throw DtypeError("unsupported NumPy dtype");
}

Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
    auto total_size = shape.total_size();
    auto bytes = GetElementSize(dtype) * total_size;
    if (static_cast<size_t>(total_size) != list.size()) {
        throw DimensionError("Invalid data length");
    }

    // Allocate a buffer and copy data
    std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
    VisitDtype(dtype, [&](auto pt) {
        using T = typename decltype(pt)::type;
        std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
    });
    return Array::FromBuffer(shape, dtype, ptr);
}

Array MakeArray(py::array array) {
    if ((array.flags() & py::array::c_style) == 0) {
        throw DimensionError("cannot convert non-contiguous NumPy array to Array");
    }

    Dtype dtype = NumpyDtypeToDtype(array.dtype());
    py::buffer_info info = array.request();
    Shape shape(info.shape);

    // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
    std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());

    return Array::FromBuffer(shape, dtype, data);
}

py::buffer_info MakeNumpyArrayFromArray(Array& self) {
    if (!self.is_contiguous()) {
        throw DimensionError("cannot convert non-contiguous Array to NumPy array");
    }

    int64_t itemsize{GetElementSize(self.dtype())};
    const Shape& shape = self.shape();

    // compute C-contiguous strides
    size_t ndim = self.ndim();
    std::vector<size_t> strides(ndim);
    if (ndim > 0) {
        std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
        strides.back() = 1;
        std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
    }

    return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}

void InitXchainerArray(pybind11::module& m) {
    py::class_<Array>{m, "Array", py::buffer_protocol()}
        .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
        .def(py::init(py::overload_cast<py::array>(&MakeArray)))
        .def_buffer(&MakeNumpyArrayFromArray)
        .def("view", &Array::MakeView)
        .def(py::self += py::self)
        .def(py::self *= py::self)
        .def(py::self + py::self)
        .def(py::self * py::self)
        .def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
        .def("copy", &Array::Copy)
        .def_property("requires_grad", [](Array& self) -> bool { return self.RequiresGrad(); },
                      [](Array& self, bool requires_grad) {
                          if (requires_grad) {
                              self.RequireGrad();
                          } else {
                              //  TODO(hvy): Not yet implemented
                          }
                      })
        .def_property("grad",
                      [](Array& self) -> nonstd::optional<Array> {
                          if (self.RequiresGrad()) {
                              return self.Grad()->MakeView();
                          } else {
                              return nonstd::nullopt;
                          }
                      },
                      [](Array& self, Array* grad) {
                          if (grad) {
                              if (!self.RequiresGrad()) {
                                  // Create the ArrayNode required in order to set the gradient
                                  self.RequireGrad();
                              }
                              self.SetGrad(grad->MakeView());
                          } else {
                              self.ClearGrad();
                          }
                      })
        .def_property_readonly("dtype", &Array::dtype)
        .def_property_readonly("element_bytes", &Array::element_bytes)
        .def_property_readonly("is_contiguous", &Array::is_contiguous)
        .def_property_readonly("ndim", &Array::ndim)
        .def_property_readonly("offset", &Array::offset)
        .def_property_readonly("shape", &Array::shape)
        .def_property_readonly("total_bytes", &Array::total_bytes)
        .def_property_readonly("total_size", &Array::total_size)
        .def_property_readonly("_debug_data_memory_address",  // These methods starting with `_debug_` are stubs for testing
                               [](const Array& self) { return reinterpret_cast<std::uintptr_t>(self.data().get()); })
        .def_property_readonly("_debug_flat_data", [](const Array& self) {
            py::list list;
            auto size = self.total_size();

            // Copy data into the list
            VisitDtype(self.dtype(), [&](auto pt) {
                using T = typename decltype(pt)::type;
                const T& data = *std::static_pointer_cast<const T>(self.data());
                for (int64_t i = 0; i < size; ++i) {
                    list.append((&data)[i]);
                }
            });

            return list;
        });
}

}  // namespace xchainer
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Red Hat, Inc.
 * Portions created by the Initial Developer are Copyright (C) 2010 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s): David Tardon <dtardon@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

namespace detail
{

template<typename T>
struct has_clone
{
    template<typename U, U x>
    struct test;

    typedef char yes;
    typedef struct { char a[2]; } no;

    template<typename U>
    static yes check_sig(U*, test<U* (U::*)() const, &U::clone>* = 0);
    template<typename U>
    static no check_sig(...);

    enum
    {
        value = sizeof(has_clone<T>::template check_sig<T>(0)) == sizeof(yes)
    };
};

template<typename T, bool HasClone>
struct cloner
{
    static T* clone(T* const other)
    {
        return new T(*other);
    }
};

template<typename T>
struct cloner<T, true>
{
    static T* clone(T* const other)
    {
        return other->clone();
    }
};

}

/** Creates a new copy of the passed object.
    If other is 0, just returns 0. Otherwise, if other has function
    named clone with signature T* (T::*)() const, the function is called.
    Otherwise, copy constructor is used.

    @returns 0 or newly allocated object
 */
template<typename T>
T* clone(T* const other)
{
    return other ? ::detail::cloner<T, ::detail::has_clone<T>::value>::clone(other) : 0;
}

// vim: set sts=4 sw=4 et:
<commit_msg>tweak this to build under windows<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Red Hat, Inc.
 * Portions created by the Initial Developer are Copyright (C) 2010 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s): David Tardon <dtardon@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

namespace detail
{

template<typename T>
struct has_clone
{
    template<typename U, U x>
    struct test;

    typedef char yes;
    typedef struct { char a[2]; } no;

    template<typename U>
    static yes& check_sig(U*, test<U* (U::*)() const, &U::clone>* = 0);
    template<typename U>
    static no& check_sig(...);

    enum
    {
        value = sizeof(check_sig<T>(0)) == sizeof(yes)
    };
};

template<typename T, bool HasClone>
struct cloner
{
    static T* clone(T* const other)
    {
        return new T(*other);
    }
};

template<typename T>
struct cloner<T, true>
{
    static T* clone(T* const other)
    {
        return other->clone();
    }
};

}

/** Creates a new copy of the passed object.
    If other is 0, just returns 0. Otherwise, if other has function
    named clone with signature T* (T::*)() const, the function is called.
    Otherwise, copy constructor is used.

    @returns 0 or newly allocated object
 */
template<typename T>
T* clone(T* const other)
{
    return other ? ::detail::cloner<T, ::detail::has_clone<T>::value>::clone(other) : 0;
}

// vim: set sts=4 sw=4 et:
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkTreeRingPointLayout.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkTreeRingPointLayout.h"

#include "vtkDataArray.h"
#include "vtkIntArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkTree.h"
#include "vtkTreeLevelsFilter.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

vtkCxxRevisionMacro(vtkTreeRingPointLayout, "1.1");
vtkStandardNewMacro(vtkTreeRingPointLayout);

vtkTreeRingPointLayout::vtkTreeRingPointLayout()
{
  this->SectorsFieldName = 0;
  this->SetSectorsFieldName("sectors");
  this->ExteriorRadius = 1.;
}

vtkTreeRingPointLayout::~vtkTreeRingPointLayout()
{
  this->SetSectorsFieldName(0);
}

int vtkTreeRingPointLayout::RequestData( vtkInformation *vtkNotUsed(request),
                                         vtkInformationVector **inputVector,
                                         vtkInformationVector *outputVector)
{
  if (this->SectorsFieldName == NULL)
    {
    vtkErrorMacro(<< "Sector field name must be non-null.");
    return 0;
    }

  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // Storing the inputTree and outputTree handles
  vtkTree *inputTree = vtkTree::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkTree *outputTree = vtkTree::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkDataArray* sectorsArray = inputTree->GetVertexData()->GetArray(this->SectorsFieldName);
  if( sectorsArray == NULL )
  {
    vtkErrorMacro(<< "SectorsArray must be non-NULL.");
    return 0;
  }

  VTK_CREATE(vtkTreeLevelsFilter, levelFilter);
  VTK_CREATE(vtkTree, newTree);
  newTree->ShallowCopy( inputTree );
  levelFilter->SetInput( newTree );
  levelFilter->Update();
  vtkTree* levelTree = levelFilter->GetOutput();
  outputTree->ShallowCopy( levelTree );

  vtkIntArray* levelArray = vtkIntArray::SafeDownCast( levelTree->GetVertexData()->GetAbstractArray("level") );
  vtkIntArray* leafArray = vtkIntArray::SafeDownCast( levelTree->GetVertexData()->GetAbstractArray("leaf") );

  int max_level = 0;
  for( int i = 0; i < outputTree->GetNumberOfVertices(); i++ )
  {
    int level = levelArray->GetValue(i);
    if( level > max_level )
    {
      max_level = level;
    }
  }

  double spacing = this->ExteriorRadius / (double)max_level;

  vtkPoints* points = vtkPoints::New();
  vtkIdType numVerts = outputTree->GetNumberOfVertices();
  points->SetNumberOfPoints(numVerts);
  for( vtkIdType i = 0; i < numVerts; i++ )
  {
    if( i == 0 )
    {
      points->SetPoint( i, 0, 0, 0 );
      continue;
    }

    double sector_coords[4];
    sectorsArray->GetTuple( i, sector_coords );

    double r;
    if( leafArray->GetValue(i) == 1 )
    {
      r = sector_coords[0];
    }
    else
    {
      int current_level = levelArray->GetValue(i);
      r = spacing*current_level;
    }

      //double r = (0.5*(sector_coords[1] - sector_coords[0])) + sector_coords[0];
    double theta = sector_coords[2] + (0.5*(sector_coords[3]-sector_coords[2]));
    double x = r*cos(vtkMath::DegreesToRadians()*theta);
    double y = r*sin(vtkMath::DegreesToRadians()*theta);
    double z = 0.;
    points->SetPoint(i, x, y, z);
  }
  outputTree->SetPoints(points);
  points->Delete();

  return 1;
}

void vtkTreeRingPointLayout::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "SectorsFieldName: " << (this->SectorsFieldName ? this->SectorsFieldName : "(none)") << endl;
}
<commit_msg>COMP:Removed old-style cast warning by removing useless cast.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTreeRingPointLayout.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkTreeRingPointLayout.h"

#include "vtkDataArray.h"
#include "vtkIntArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkTree.h"
#include "vtkTreeLevelsFilter.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

vtkCxxRevisionMacro(vtkTreeRingPointLayout, "1.2");
vtkStandardNewMacro(vtkTreeRingPointLayout);

vtkTreeRingPointLayout::vtkTreeRingPointLayout()
{
  this->SectorsFieldName = 0;
  this->SetSectorsFieldName("sectors");
  this->ExteriorRadius = 1.;
}

vtkTreeRingPointLayout::~vtkTreeRingPointLayout()
{
  this->SetSectorsFieldName(0);
}

int vtkTreeRingPointLayout::RequestData( vtkInformation *vtkNotUsed(request),
                                         vtkInformationVector **inputVector,
                                         vtkInformationVector *outputVector)
{
  if (this->SectorsFieldName == NULL)
    {
    vtkErrorMacro(<< "Sector field name must be non-null.");
    return 0;
    }

  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // Storing the inputTree and outputTree handles
  vtkTree *inputTree = vtkTree::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkTree *outputTree = vtkTree::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkDataArray* sectorsArray = inputTree->GetVertexData()->GetArray(this->SectorsFieldName);
  if( sectorsArray == NULL )
  {
    vtkErrorMacro(<< "SectorsArray must be non-NULL.");
    return 0;
  }

  VTK_CREATE(vtkTreeLevelsFilter, levelFilter);
  VTK_CREATE(vtkTree, newTree);
  newTree->ShallowCopy( inputTree );
  levelFilter->SetInput( newTree );
  levelFilter->Update();
  vtkTree* levelTree = levelFilter->GetOutput();
  outputTree->ShallowCopy( levelTree );

  vtkIntArray* levelArray = vtkIntArray::SafeDownCast( levelTree->GetVertexData()->GetAbstractArray("level") );
  vtkIntArray* leafArray = vtkIntArray::SafeDownCast( levelTree->GetVertexData()->GetAbstractArray("leaf") );

  int max_level = 0;
  for( int i = 0; i < outputTree->GetNumberOfVertices(); i++ )
  {
    int level = levelArray->GetValue(i);
    if( level > max_level )
    {
      max_level = level;
    }
  }

  double spacing = this->ExteriorRadius / max_level;

  vtkPoints* points = vtkPoints::New();
  vtkIdType numVerts = outputTree->GetNumberOfVertices();
  points->SetNumberOfPoints(numVerts);
  for( vtkIdType i = 0; i < numVerts; i++ )
  {
    if( i == 0 )
    {
      points->SetPoint( i, 0, 0, 0 );
      continue;
    }

    double sector_coords[4];
    sectorsArray->GetTuple( i, sector_coords );

    double r;
    if( leafArray->GetValue(i) == 1 )
    {
      r = sector_coords[0];
    }
    else
    {
      int current_level = levelArray->GetValue(i);
      r = spacing*current_level;
    }

      //double r = (0.5*(sector_coords[1] - sector_coords[0])) + sector_coords[0];
    double theta = sector_coords[2] + (0.5*(sector_coords[3]-sector_coords[2]));
    double x = r*cos(vtkMath::DegreesToRadians()*theta);
    double y = r*sin(vtkMath::DegreesToRadians()*theta);
    double z = 0.;
    points->SetPoint(i, x, y, z);
  }
  outputTree->SetPoints(points);
  points->Delete();

  return 1;
}

void vtkTreeRingPointLayout::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "SectorsFieldName: " << (this->SectorsFieldName ? this->SectorsFieldName : "(none)") << endl;
}
<|endoftext|>


<commit_before><commit_msg>FastJNI for android.os.Trace<commit_after><|endoftext|>