<commit_before>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#pragma once

/**
 * UAVCAN version definition
 * // TODO: Use git short hash as build id
 */
#define UAVCAN_VERSION_MAJOR    0
#define UAVCAN_VERSION_MINOR    1
#define UAVCAN_VERSION_BUILD    0

/**
 * UAVCAN can be compiled in C++11 mode.
 * This macro allows to detect which version of the C++ standard is being used.
 */
#define UAVCAN_CPP11    2011
#define UAVCAN_CPP03    2003

#ifndef UAVCAN_CPP_VERSION
# if __cplusplus > 201200
#  error Unsupported C++ standard
# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#  define UAVCAN_CPP_VERSION    UAVCAN_CPP11
# else
#  define UAVCAN_CPP_VERSION    UAVCAN_CPP03
# endif
#endif

/**
 * UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.
 */
#ifndef UAVCAN_EXCEPTIONS
# if __EXCEPTIONS || _HAS_EXCEPTIONS
#  define UAVCAN_EXCEPTIONS  1
# else
#  define UAVCAN_EXCEPTIONS  0
# endif
#endif

/**
 * Struct layout control.
 * Define UAVCAN_PACK_STRUCTS = 1 to reduce memory usage.
 */
#ifndef UAVCAN_PACK_STRUCTS
# define UAVCAN_PACK_STRUCTS    0
#endif
#ifndef UAVCAN_PACKED_BEGIN
# define UAVCAN_PACKED_BEGIN
#endif
#ifndef UAVCAN_PACKED_END
# define UAVCAN_PACKED_END
#endif

/**
 * Declaration visibility
 * http://gcc.gnu.org/wiki/Visibility
 */
#ifndef UAVCAN_EXPORT
# define UAVCAN_EXPORT
#endif

/**
 * Trade-off between ROM/RAM usage and functionality/determinism.
 * Note that this feature is not well tested and should be avoided.
 * Use code search for UAVCAN_TINY to find what functionality will be disabled.
 * This is particularly useful for embedded systems with less than 40kB of ROM.
 */
#ifndef UAVCAN_TINY
# define UAVCAN_TINY 0
#endif

/**
 * It might make sense to remove toString() methods for an embedded system
 */
#ifndef UAVCAN_TOSTRING
// Objective is to make sure that we're NOT on a resource constrained platform
# if __linux__ || __linux || __APPLE__ || _WIN64 || _WIN32
#  define UAVCAN_TOSTRING 1
# else
#  define UAVCAN_TOSTRING 0
# endif
#endif

#if UAVCAN_TOSTRING
# include <string>
# include <cstdio>
#endif

/**
 * Some C++ implementations are half-broken and do not implement the placement new operator.
 * Setting this preprocessor symbol to 1 makes libuavcan implement its own operator new (std::size_t, void*),
 * and its delete counterpart.
 * This option may be removed in future.
 */
#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW
# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0
#endif

namespace uavcan
{

/**
 * Should be OK for any target arch up to AMD64 and any compiler.
 * The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation
 * fit this size; otherwise compilation fails.
 */
#if UAVCAN_MEM_POOL_BLOCK_SIZE
/// Explicitly specified by the user.
static const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;
#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)
/// Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.
static const unsigned MemPoolBlockSize = 56;
#else
/// Safe default that should be OK for any platform.
static const unsigned MemPoolBlockSize = 64;
#endif

#ifdef __BIGGEST_ALIGNMENT__
static const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;
#else
static const unsigned MemPoolAlignment = 16;
#endif

typedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];

template <typename T>
struct UAVCAN_EXPORT IsDynamicallyAllocatable
{
    static void check()
    {
        char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1];
        (void)dummy;
    }
};

}
<commit_msg>Macro UAVCAN_ASSERT() instead of assert() (not used yet, see the next commit)<commit_after>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#pragma once

/**
 * UAVCAN version definition
 * // TODO: Use git short hash as build id
 */
#define UAVCAN_VERSION_MAJOR    0
#define UAVCAN_VERSION_MINOR    1
#define UAVCAN_VERSION_BUILD    0

/**
 * UAVCAN can be compiled in C++11 mode.
 * This macro allows to detect which version of the C++ standard is being used.
 */
#define UAVCAN_CPP11    2011
#define UAVCAN_CPP03    2003

#ifndef UAVCAN_CPP_VERSION
# if __cplusplus > 201200
#  error Unsupported C++ standard
# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#  define UAVCAN_CPP_VERSION    UAVCAN_CPP11
# else
#  define UAVCAN_CPP_VERSION    UAVCAN_CPP03
# endif
#endif

/**
 * UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.
 */
#ifndef UAVCAN_EXCEPTIONS
# if __EXCEPTIONS || _HAS_EXCEPTIONS
#  define UAVCAN_EXCEPTIONS  1
# else
#  define UAVCAN_EXCEPTIONS  0
# endif
#endif

/**
 * Struct layout control.
 * Define UAVCAN_PACK_STRUCTS = 1 to reduce memory usage.
 */
#ifndef UAVCAN_PACK_STRUCTS
# define UAVCAN_PACK_STRUCTS    0
#endif
#ifndef UAVCAN_PACKED_BEGIN
# define UAVCAN_PACKED_BEGIN
#endif
#ifndef UAVCAN_PACKED_END
# define UAVCAN_PACKED_END
#endif

/**
 * Declaration visibility
 * http://gcc.gnu.org/wiki/Visibility
 */
#ifndef UAVCAN_EXPORT
# define UAVCAN_EXPORT
#endif

/**
 * Trade-off between ROM/RAM usage and functionality/determinism.
 * Note that this feature is not well tested and should be avoided.
 * Use code search for UAVCAN_TINY to find what functionality will be disabled.
 * This is particularly useful for embedded systems with less than 40kB of ROM.
 */
#ifndef UAVCAN_TINY
# define UAVCAN_TINY 0
#endif

/**
 * It might make sense to remove toString() methods for an embedded system
 */
#ifndef UAVCAN_TOSTRING
// Objective is to make sure that we're NOT on a resource constrained platform
# if __linux__ || __linux || __APPLE__ || _WIN64 || _WIN32
#  define UAVCAN_TOSTRING 1
# else
#  define UAVCAN_TOSTRING 0
# endif
#endif

#if UAVCAN_TOSTRING
# include <string>
# include <cstdio>
#endif

/**
 * Some C++ implementations are half-broken and do not implement the placement new operator.
 * Setting this preprocessor symbol to 1 makes libuavcan implement its own operator new (std::size_t, void*),
 * and its delete counterpart.
 * This option may be removed in future.
 */
#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW
# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0
#endif

/**
 * Run time checks.
 * Resolves to the standard assert() by default.
 * Can be disabled completely.
 */
#ifndef UAVCAN_ASSERT
# if UAVCAN_NO_ASSERTIONS
#  define UAVCAN_ASSERT(x)
# else
#  define UAVCAN_ASSERT(x) assert(x)
# endif
#endif

namespace uavcan
{

/**
 * Should be OK for any target arch up to AMD64 and any compiler.
 * The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation
 * fit this size; otherwise compilation fails.
 */
#if UAVCAN_MEM_POOL_BLOCK_SIZE
/// Explicitly specified by the user.
static const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;
#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)
/// Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.
static const unsigned MemPoolBlockSize = 56;
#else
/// Safe default that should be OK for any platform.
static const unsigned MemPoolBlockSize = 64;
#endif

#ifdef __BIGGEST_ALIGNMENT__
static const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;
#else
static const unsigned MemPoolAlignment = 16;
#endif

typedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];

template <typename T>
struct UAVCAN_EXPORT IsDynamicallyAllocatable
{
    static void check()
    {
        char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1];
        (void)dummy;
    }
};

}
<|endoftext|>


<commit_before>
#include <constrained_ik/collision_robot_fcl_detailed.h>
#include <ros/ros.h>
#include <ctime>

namespace constrained_ik
{
  using namespace collision_detection;

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, NULL);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, NULL);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const std::set<const robot_model::LinkModel*> &active_components_only) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, &active_components_only);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm, const std::set<const robot_model::LinkModel*> &active_components_only) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, &active_components_only);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm, const std::set<const robot_model::LinkModel*> *active_components_only) const
  {
    double duration;
    std::clock_t start = std::clock();

    FCLManager manager;
    CollisionRobotFCLDetailed::allocSelfCollisionBroadPhase(state, manager);

    DistanceResultDetailed drd(acm, active_components_only);

    manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);
    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
    ROS_INFO("Duration: %f", duration);
    return drd.distance_detailed_;
  }

  bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)
  {
    DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);

    const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());
    const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());

    // If active components are specified
    if (cdata->active_components_only_)
    {
      const robot_model::LinkModel *l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);
      const robot_model::LinkModel *l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);

      // If neither of the involved components is active
      if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&
          (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))
      {
        return false;
      }
    }

    // use the collision matrix (if any) to avoid certain distance checks
    bool always_allow_collision = false;
    if (cdata->acm_)
    {
      AllowedCollision::Type type;

      bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);
      if (found)
      {
        // if we have an entry in the collision matrix, we read it
        if (type == AllowedCollision::ALWAYS)
        {
          always_allow_collision = true;
          if (!cdata->verbose)
            logDebug("Collision between '%s' and '%s' is always allowed. No contacts are computed.",
                     cd1->getID().c_str(), cd2->getID().c_str());
        }
      }
    }

    // check if a link is touching an attached object
    if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)
    {
      const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();
      if (tl.find(cd1->getID()) != tl.end())
      {
        always_allow_collision = true;
        if (!cdata->verbose)
          logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
                   cd1->getID().c_str(), cd2->getID().c_str());
      }
    }
    else
    {
      if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)
      {
        const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();
        if (tl.find(cd2->getID()) != tl.end())
        {
          always_allow_collision = true;
          if (!cdata->verbose)
            logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
                     cd2->getID().c_str(), cd1->getID().c_str());
        }
      }
    }

    if(always_allow_collision)
    {
      return false;
    }

    if (!cdata->verbose)
      logDebug("Actually checking collisions between %s and %s", cd1->getID().c_str(), cd2->getID().c_str());

    fcl::DistanceResult dist_result;
    dist_result.min_distance = 0.1;
    //dist_result.update(0.1, NULL, NULL, fcl::DistanceResult::NONE, fcl::DistanceResult::NONE);
    double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);

    // Check if either object is already in the map. If not add it or if present
    // check to see if the new distance is closer. If closer remove the existing
    // one and add the new distance information.
    if (d < 0.1)
    {
      std::map<std::string, fcl::DistanceResult>::iterator it;
      it = cdata->distance_detailed_.find(cd1->ptr.obj->id_);
      if (it == cdata->distance_detailed_.end())
      {
        cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
      }
      else
      {
        if (dist_result.min_distance < it->second.min_distance)
        {
          cdata->distance_detailed_.erase(cd1->ptr.obj->id_);
          cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
        }
      }

      it = cdata->distance_detailed_.find(cd2->ptr.obj->id_);
      if (it == cdata->distance_detailed_.end())
      {
        cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
      }
      else
      {
        if (dist_result.min_distance < it->second.min_distance)
        {
          cdata->distance_detailed_.erase(cd2->ptr.obj->id_);
          cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
        }
      }
    }
    return false;
  }

  bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)
  {
    std::map<std::string, fcl::DistanceResult>::const_iterator it;
    it = distance_detailed.find(link_name);

    if (it != distance_detailed.end())
    {
      fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);
      const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());
      const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());
      if (cd1->ptr.link->getName() == link_name)
      {
        dist_info.nearest_obsticle = cd2->ptr.link->getName();
        dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
        dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
        dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);
        dist_info.avoidance_vector.norm();
        dist_info.distance = dist.min_distance;
      }
      else if (cd2->ptr.link->getName() == link_name)
      {
        dist_info.nearest_obsticle = cd1->ptr.link->getName();
        dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
        dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
        dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);
        dist_info.avoidance_vector.norm();
        dist_info.distance = dist.min_distance;
      }
      else
      {
        ROS_ERROR("getDistanceInfo was unable to find link after match!");
        return false;
      }
      return true;
    }
    else
    {
      ROS_DEBUG("couldn't find link with that name %s", link_name.c_str());
      for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)
      {
        ROS_DEBUG("name: %s", it->first.c_str());
      }
      return false;
    }
  }

  void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)
  {
    if (kmodel->hasJointModelGroup(group_name))
      active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();
    else
      active_components_only_ = NULL;
  }
}//namespace constrained_ik

<commit_msg>Add active_link_only functionaly<commit_after>
#include <constrained_ik/collision_robot_fcl_detailed.h>
#include <ros/ros.h>
#include <ctime>

namespace constrained_ik
{
  using namespace collision_detection;

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, NULL);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, NULL);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const std::set<const robot_model::LinkModel*> &active_components_only) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL, &active_components_only);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm, const std::set<const robot_model::LinkModel*> &active_components_only) const
  {
    return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm, &active_components_only);
  }

  CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm, const std::set<const robot_model::LinkModel*> *active_components_only) const
  {
    FCLManager manager;
    CollisionRobotFCLDetailed::allocSelfCollisionBroadPhase(state, manager);
    DistanceResultDetailed drd(acm, active_components_only);

    manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);

    return drd.distance_detailed_;
  }

  bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)
  {
    DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);

    const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());
    const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());
    const robot_model::LinkModel *l1, *l2;
    bool active1 = true, active2 = true;

    // If active components are specified
    if (cdata->active_components_only_)
    {
      l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);
      l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);

      // If neither of the involved components is active
      if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&
          (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))
      {
        return false;
      }
      else
      {
        if (!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end())
          active1 = false;

        if (!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end())
          active2 = false;
      }
    }

    // use the collision matrix (if any) to avoid certain distance checks
    bool always_allow_collision = false;
    if (cdata->acm_)
    {
      AllowedCollision::Type type;

      bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);
      if (found)
      {
        // if we have an entry in the collision matrix, we read it
        if (type == AllowedCollision::ALWAYS)
        {
          always_allow_collision = true;
          if (!cdata->verbose)
            logDebug("Collision between '%s' and '%s' is always allowed. No contacts are computed.",
                     cd1->getID().c_str(), cd2->getID().c_str());
        }
      }
    }

    // check if a link is touching an attached object
    if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)
    {
      const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();
      if (tl.find(cd1->getID()) != tl.end())
      {
        always_allow_collision = true;
        if (!cdata->verbose)
          logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
                   cd1->getID().c_str(), cd2->getID().c_str());
      }
    }
    else
    {
      if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)
      {
        const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();
        if (tl.find(cd2->getID()) != tl.end())
        {
          always_allow_collision = true;
          if (!cdata->verbose)
            logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
                     cd2->getID().c_str(), cd1->getID().c_str());
        }
      }
    }

    if(always_allow_collision)
    {
      return false;
    }

    if (!cdata->verbose)
      logDebug("Actually checking collisions between %s and %s", cd1->getID().c_str(), cd2->getID().c_str());

    fcl::DistanceResult dist_result;
    double dist_threshold = std::numeric_limits<double>::max();
    std::map<std::string, fcl::DistanceResult>::iterator it1, it2;

    it1 = cdata->distance_detailed_.find(cd1->ptr.obj->id_);
    it2 = cdata->distance_detailed_.find(cd2->ptr.obj->id_);
    if (cdata->active_components_only_)
    {
      if (active1 && active2)
      {
        if (it1 != cdata->distance_detailed_.end() && it2 != cdata->distance_detailed_.end())
          dist_threshold = std::max(it1->second.min_distance, it2->second.min_distance);
      }
      else if (active1 && !active2)
      {
        if (it1 != cdata->distance_detailed_.end())
          dist_threshold = it1->second.min_distance;
      }
      else if (!active1 && active2)
      {
        if (it2 != cdata->distance_detailed_.end())
          dist_threshold = it2->second.min_distance;
      }
    }
    else
    {
      if (it1 != cdata->distance_detailed_.end() && it2 != cdata->distance_detailed_.end())
        dist_threshold = std::max(it1->second.min_distance, it2->second.min_distance);
    }

    dist_result.min_distance = dist_threshold;
    double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);

    // Check if either object is already in the map. If not add it or if present
    // check to see if the new distance is closer. If closer remove the existing
    // one and add the new distance information.
    if (d < dist_threshold)
    {
      if (it1 == cdata->distance_detailed_.end())
      {
        cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
      }
      else
      {
        if (dist_result.min_distance < it1->second.min_distance)
        {
          cdata->distance_detailed_.erase(cd1->ptr.obj->id_);
          cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
        }
      }

      if (it2 == cdata->distance_detailed_.end())
      {
        cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
      }
      else
      {
        if (dist_result.min_distance < it2->second.min_distance)
        {
          cdata->distance_detailed_.erase(cd2->ptr.obj->id_);
          cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
        }
      }
    }
    return false;
  }

  bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)
  {
    std::map<std::string, fcl::DistanceResult>::const_iterator it;
    it = distance_detailed.find(link_name);

    if (it != distance_detailed.end())
    {
      fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);
      const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());
      const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());
      if (cd1->ptr.link->getName() == link_name)
      {
        dist_info.nearest_obsticle = cd2->ptr.link->getName();
        dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
        dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
        dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);
        dist_info.avoidance_vector.norm();
        dist_info.distance = dist.min_distance;
      }
      else if (cd2->ptr.link->getName() == link_name)
      {
        dist_info.nearest_obsticle = cd1->ptr.link->getName();
        dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
        dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
        dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);
        dist_info.avoidance_vector.norm();
        dist_info.distance = dist.min_distance;
      }
      else
      {
        ROS_ERROR("getDistanceInfo was unable to find link after match!");
        return false;
      }
      return true;
    }
    else
    {
      ROS_DEBUG("couldn't find link with that name %s", link_name.c_str());
      for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)
      {
        ROS_DEBUG("name: %s", it->first.c_str());
      }
      return false;
    }
  }

  void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)
  {
    if (kmodel->hasJointModelGroup(group_name))
      active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();
    else
      active_components_only_ = NULL;
  }
}//namespace constrained_ik

<|endoftext|>


<commit_before>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;

void
TerminalConfigUnix__handleAbortSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleAbortSignal(signum);

}

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}

TerminalConfigUnix::~TerminalConfigUnix() {
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleAbortSignal(int signum) {
  Detach();
  if (fPrevAbortHandler) fPrevAbortHandler(signum);
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
  fIsAttached = false;
}

#endif // ndef WIN32
<commit_msg>Solaris puts signal only into std::.<commit_after>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;
using std::signal;

void
TerminalConfigUnix__handleAbortSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleAbortSignal(signum);

}

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}

TerminalConfigUnix::~TerminalConfigUnix() {
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleAbortSignal(int signum) {
  Detach();
  if (fPrevAbortHandler) fPrevAbortHandler(signum);
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
  fIsAttached = false;
}

#endif // ndef WIN32
<|endoftext|>


<commit_before><commit_msg>remove this stuff. See comment in code for more information<commit_after><|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 <memory>
#include <vector>

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

#include "arrow/testing/gtest_common.h"
#include "arrow/testing/gtest_util.h"

#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/compute/kernels/util-internal.h"
#include "arrow/compute/test-util.h"

namespace arrow {
namespace compute {
namespace detail {

using ::testing::_;
using ::testing::AllOf;
using ::testing::Each;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::IsNull;
using ::testing::Ne;
using ::testing::NotNull;
using ::testing::Return;

TEST(PropagateNulls, UnknownNullCountWithNullsZeroCopies) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);
}

TEST(PropagateNulls, UnknownNullCountWithoutNullsLeavesNullptr) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  EXPECT_THAT(output.null_count, Eq(0));
  EXPECT_THAT(output.buffers, ElementsAre(IsNull())) << output.buffers[0]->data()[0];
}

TEST(PropagateNulls, OffsetAndHasNulls) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount,  // slice off the first 8
                  /*offset=*/7);
  constexpr uint8_t validity_bitmap[8] = {0, 1, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  // Copy is made.
  EXPECT_THAT(output.null_count, Eq(15));
  ASSERT_THAT(output.buffers, ElementsAre(AllOf(Ne(nulls), NotNull())));
  const auto& output_buffer = *output.buffers[0];
  // the slice shifts the bit one over
  ASSERT_THAT(std::vector<uint8_t>(output_buffer.data(),
                                   output_buffer.data() + output_buffer.size()),
              ElementsAreArray({2, 0}));
  ASSERT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),
                                   output_buffer.data() + output_buffer.capacity()),
              Each(0));
}

TEST(AssignNullIntersection, ZeroCopyWhenZeroNullsOnOneInput) {
  ArrayData some_nulls(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  some_nulls.buffers.push_back(nulls);

  ArrayData no_nulls(boolean(), /* length= */ 16, /*null_count=*/0);

  FunctionContext ctx(default_memory_pool());
  ArrayData output;
  output.length = 16;

  ASSERT_OK(AssignNullIntersection(&ctx, some_nulls, no_nulls, &output));
  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);

  output.buffers[0] = nullptr;
  ASSERT_OK(AssignNullIntersection(&ctx, no_nulls, some_nulls, &output));
  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);
}

TEST(AssignNullIntersection, IntersectsNullsWhenSomeOnBoth) {
  ArrayData left(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t left_validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> left_nulls = std::make_shared<Buffer>(left_validity_bitmap, 8);
  left.buffers.push_back(left_nulls);

  ArrayData right(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t right_validity_bitmap[8] = {127, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> right_nulls =
      std::make_shared<Buffer>(right_validity_bitmap, 8);
  right.buffers.push_back(right_nulls);

  FunctionContext ctx(default_memory_pool());
  ArrayData output;
  output.length = 16;

  ASSERT_OK(AssignNullIntersection(&ctx, left, right, &output));

  EXPECT_THAT(output.null_count, 10);
  ASSERT_THAT(output.buffers, ElementsAre(NotNull()));
  const auto& output_buffer = *output.buffers[0];
  EXPECT_THAT(std::vector<uint8_t>(output_buffer.data(),
                                   output_buffer.data() + output_buffer.size()),
              ElementsAreArray({126, 0}));
  EXPECT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),
                                   output_buffer.data() + output_buffer.capacity()),
              Each(0));
}

TEST(PrimitiveAllocatingUnaryKernel, BooleanFunction) {
  MockUnaryKernel mock;
  EXPECT_CALL(mock, out_type).WillRepeatedly(Return(boolean()));
  EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingUnaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(2));
  EXPECT_THAT(value_buffer->capacity(), Ge(2));
  // Booleans should have this always zeroed out.
  EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));
}

TEST(PrimitiveAllocatingUnaryKernel, NonBoolean) {
  MockUnaryKernel mock;
  EXPECT_CALL(mock, out_type).WillRepeatedly(Return(int32()));
  EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingUnaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(64));
  EXPECT_THAT(value_buffer->capacity(), Ge(64));
}

TEST(PrimitiveAllocatingBinaryKernel, BooleanFunction) {
  MockBinaryKernel mock;
  EXPECT_CALL(mock, out_type).WillRepeatedly(Return(boolean()));
  EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingBinaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(2));
  EXPECT_THAT(value_buffer->capacity(), Ge(2));
  // Booleans should have this always zeroed out.
  EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));
}

TEST(PrimitiveAllocatingBinaryKernel, NonBoolean) {
  MockBinaryKernel mock;
  EXPECT_CALL(mock, out_type).WillRepeatedly(Return(int32()));
  EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingBinaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(64));
  EXPECT_THAT(value_buffer->capacity(), Ge(64));
}

}  // namespace detail
}  // namespace compute
}  // namespace arrow
<commit_msg>ARROW-4869: [C++] Fix gmock usage in compute/kernels/util-internal-test.cc<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 <memory>
#include <vector>

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

#include "arrow/testing/gtest_common.h"
#include "arrow/testing/gtest_util.h"

#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/compute/kernels/util-internal.h"
#include "arrow/compute/test-util.h"

namespace arrow {
namespace compute {
namespace detail {

using ::testing::_;
using ::testing::AllOf;
using ::testing::Each;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::IsNull;
using ::testing::Ne;
using ::testing::NotNull;
using ::testing::Return;

TEST(PropagateNulls, UnknownNullCountWithNullsZeroCopies) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);
}

TEST(PropagateNulls, UnknownNullCountWithoutNullsLeavesNullptr) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  EXPECT_THAT(output.null_count, Eq(0));
  EXPECT_THAT(output.buffers, ElementsAre(IsNull())) << output.buffers[0]->data()[0];
}

TEST(PropagateNulls, OffsetAndHasNulls) {
  ArrayData input(boolean(), /*length=*/16, kUnknownNullCount,  // slice off the first 8
                  /*offset=*/7);
  constexpr uint8_t validity_bitmap[8] = {0, 1, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  input.buffers.push_back(nulls);
  FunctionContext ctx(default_memory_pool());
  ArrayData output;

  ASSERT_OK(PropagateNulls(&ctx, input, &output));

  // Copy is made.
  EXPECT_THAT(output.null_count, Eq(15));
  ASSERT_THAT(output.buffers, ElementsAre(AllOf(Ne(nulls), NotNull())));
  const auto& output_buffer = *output.buffers[0];
  // the slice shifts the bit one over
  ASSERT_THAT(std::vector<uint8_t>(output_buffer.data(),
                                   output_buffer.data() + output_buffer.size()),
              ElementsAreArray({2, 0}));
  ASSERT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),
                                   output_buffer.data() + output_buffer.capacity()),
              Each(0));
}

TEST(AssignNullIntersection, ZeroCopyWhenZeroNullsOnOneInput) {
  ArrayData some_nulls(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> nulls = std::make_shared<Buffer>(validity_bitmap, 8);
  some_nulls.buffers.push_back(nulls);

  ArrayData no_nulls(boolean(), /* length= */ 16, /*null_count=*/0);

  FunctionContext ctx(default_memory_pool());
  ArrayData output;
  output.length = 16;

  ASSERT_OK(AssignNullIntersection(&ctx, some_nulls, no_nulls, &output));
  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);

  output.buffers[0] = nullptr;
  ASSERT_OK(AssignNullIntersection(&ctx, no_nulls, some_nulls, &output));
  ASSERT_THAT(output.buffers, ElementsAre(Eq(nulls)));
  ASSERT_THAT(output.null_count, 9);
}

TEST(AssignNullIntersection, IntersectsNullsWhenSomeOnBoth) {
  ArrayData left(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t left_validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> left_nulls = std::make_shared<Buffer>(left_validity_bitmap, 8);
  left.buffers.push_back(left_nulls);

  ArrayData right(boolean(), /* length= */ 16, kUnknownNullCount);
  constexpr uint8_t right_validity_bitmap[8] = {127, 0, 0, 0, 0, 0, 0, 0};
  std::shared_ptr<Buffer> right_nulls =
      std::make_shared<Buffer>(right_validity_bitmap, 8);
  right.buffers.push_back(right_nulls);

  FunctionContext ctx(default_memory_pool());
  ArrayData output;
  output.length = 16;

  ASSERT_OK(AssignNullIntersection(&ctx, left, right, &output));

  EXPECT_THAT(output.null_count, 10);
  ASSERT_THAT(output.buffers, ElementsAre(NotNull()));
  const auto& output_buffer = *output.buffers[0];
  EXPECT_THAT(std::vector<uint8_t>(output_buffer.data(),
                                   output_buffer.data() + output_buffer.size()),
              ElementsAreArray({126, 0}));
  EXPECT_THAT(std::vector<uint8_t>(output_buffer.data() + output_buffer.size(),
                                   output_buffer.data() + output_buffer.capacity()),
              Each(0));
}

TEST(PrimitiveAllocatingUnaryKernel, BooleanFunction) {
  MockUnaryKernel mock;
  EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(boolean()));
  EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingUnaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(2));
  EXPECT_THAT(value_buffer->capacity(), Ge(2));
  // Booleans should have this always zeroed out.
  EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));
}

TEST(PrimitiveAllocatingUnaryKernel, NonBoolean) {
  MockUnaryKernel mock;
  EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(int32()));
  EXPECT_CALL(mock, Call(_, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingUnaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(64));
  EXPECT_THAT(value_buffer->capacity(), Ge(64));
}

TEST(PrimitiveAllocatingBinaryKernel, BooleanFunction) {
  MockBinaryKernel mock;
  EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(boolean()));
  EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingBinaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(2));
  EXPECT_THAT(value_buffer->capacity(), Ge(2));
  // Booleans should have this always zeroed out.
  EXPECT_THAT(*(value_buffer->data() + value_buffer->size() - 1), Eq(0));
}

TEST(PrimitiveAllocatingBinaryKernel, NonBoolean) {
  MockBinaryKernel mock;
  EXPECT_CALL(mock, out_type()).WillRepeatedly(Return(int32()));
  EXPECT_CALL(mock, Call(_, _, _, _)).WillOnce(Return(Status::OK()));
  PrimitiveAllocatingBinaryKernel kernel(&mock);

  auto input =
      std::make_shared<ArrayData>(boolean(), /* length= */ 16, kUnknownNullCount);
  FunctionContext ctx(default_memory_pool());
  Datum output;
  output.value = ArrayData::Make(kernel.out_type(), input->length);
  ASSERT_OK(kernel.Call(&ctx, input, input, &output));

  ASSERT_THAT(output.array()->buffers, ElementsAre(IsNull(), NotNull()));
  auto value_buffer = output.array()->buffers[1];
  EXPECT_THAT(value_buffer->size(), Eq(64));
  EXPECT_THAT(value_buffer->capacity(), Ge(64));
}

}  // namespace detail
}  // namespace compute
}  // namespace arrow
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH
#define DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH

#include <memory>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/geometry/genericgeometry/topologytypes.hh>

#if HAVE_DUNE_PDELAB
# include <dune/pdelab/finiteelementmap/qkdg.hh>
# include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
# include <dune/pdelab/constraints/conforming.hh>
#endif // HAVE_DUNE_PDELAB

#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/la/container/istl.hh>

#include <dune/gdt/spaces/parallel.hh>

#include "../../../mapper/pdelab.hh"
#include "../../../basefunctionset/pdelab.hh"

#include "../../../spaces/interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {
namespace DG {

#if HAVE_DUNE_PDELAB

// forward, to be used in the traits and to allow for specialization
template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBased
{
  static_assert(Dune::AlwaysFalse< GridViewImp >::value, "Untested for this combination of dimensions!");
}; //class PdelabBased

template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBasedTraits
{
public:
  typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
  typedef GridViewImp                   GridViewType;
  static const int                      polOrder = polynomialOrder;
  // using this space for the QuadraticSpaces in test/products_l2weighted.cc results in a test failure
  static_assert(polOrder == 1, "This space is known to fail for higher polynomial orders!");
private:
  typedef typename GridViewType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridViewType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
private:
  template< class G, bool single_geom, bool is_simplex, bool is_cube >
  struct FeMap
  {
    static_assert(Dune::AlwaysFalse< G >::value,
                  "This space is only implemented for either fully simplicial or fully cubic grids!");
  };
  template< class G >
  struct FeMap< G, true, true, false >
  {
    static_assert(Dune::AlwaysFalse< G >::value,
                  "Not yet implemented for simplicial grids!");
  };
  template< class G >
  struct FeMap< G, true, false, true >
  {
    typedef PDELab::QkDGLocalFiniteElementMap< DomainFieldType, RangeFieldType, polOrder, dimDomain > Type;
  };
  typedef typename GridViewType::Grid GridType;
  static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType< GridType >::v;
  static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId
                                   == GenericGeometry::SimplexTopology< dimDomain >::type::id);
  static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId
                              == GenericGeometry::CubeTopology< dimDomain >::type::id);
  typedef typename FeMap< GridType, single_geom_, simplicial_, cubic_ >::Type FEMapType;
public:
  typedef PDELab::GridFunctionSpace< GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints >
      BackendType;
  typedef Mapper::DiscontinuousPdelabWrapper< BackendType > MapperType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
  typedef BaseFunctionSet::PdelabWrapper
      < BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols >
    BaseFunctionSetType;
  static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
  static const bool needs_grid_view = true;
  typedef CommunicationChooser< GridViewType >    CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;
private:
  friend class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >;
}; // class PdelabBasedTraits

template< class GridViewImp, int polynomialOrder, class RangeFieldImp >
class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,
                           GridViewImp::dimension, 1, 1 >
{
  typedef SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,
                          GridViewImp::dimension, 1, 1 >                                   BaseType;
  typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >                          ThisType;
public:
  typedef PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridViewType GridViewType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridViewType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = BaseType::dimDomain;
private:
  static_assert(GridViewType::dimension == dimDomain, "Dimension of GridView has to match dimDomain");
public:
  typedef FieldVector< DomainFieldType, dimDomain > DomainType;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = BaseType::dimRange;
  static const unsigned int               dimRangeCols = BaseType::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;
  typedef typename Traits::CommunicatorType         CommunicatorType;

private:
  typedef typename Traits::FEMapType FEMapType;

public:
  typedef typename BaseType::IntersectionType  IntersectionType;
  typedef typename BaseType::EntityType        EntityType;
  typedef typename BaseType::PatternType       PatternType;
  typedef typename BaseType::BoundaryInfoType  BoundaryInfoType;

  PdelabBased(GridViewType gV)
    : grid_view_(gV)
    , fe_map_()
    , backend_(const_cast< GridViewType& >(grid_view_), fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridViewImp>::create(grid_view_))
    , communicator_prepared_(false)
  {}

  /**
   * \brief Copy ctor.
   * \note  Manually implemented bc of the std::mutex + communicator_  unique_ptr
   */
  PdelabBased(const ThisType& other)
    : grid_view_(other.grid_view_)
    , fe_map_(other.fe_map_)
    , backend_(other.backend_)
    , mapper_(other.mapper_)
    , communicator_(CommunicationChooser< GridViewImp >::create(grid_view_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& DUNE_UNUSED(comm) = this->communicator();
  }

  /**
   * \brief Move ctor.
   * \note  Manually implemented bc of the std::mutex.
   */
  PdelabBased(ThisType&& source)
    : grid_view_(source.grid_view_)
    , fe_map_(source.fe_map_)
    , backend_(source.backend_)
    , mapper_(source.mapper_)
    , communicator_(std::move(source.communicator_))
    , communicator_prepared_(source.communicator_prepared_)
  {}

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  using BaseType::compute_pattern;

  template< class G, class S, int d, int r, int rC >
  PatternType compute_pattern(const GridView< G >& local_grid_view,
                              const SpaceInterface< S, d, r, rC >& ansatz_space) const
  {
    return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    std::lock_guard< std::mutex > DUNE_UNUSED(gg)(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

private:
  const GridViewType grid_view_;
  const FEMapType fe_map_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable std::unique_ptr< CommunicatorType > communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >

#else // HAVE_DUNE_PDELAB

template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBased
{
  static_assert(Dune::AlwaysFalse< GridViewImp >::value, "You are missing dune-pdelab!");
};

#endif // HAVE_DUNE_PDELAB

} // namespace DG
namespace DiscontinuousLagrange {

template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class
  DUNE_DEPRECATED_MSG("Use DG::PdelabBased instead (21.11.2014)!")
      PdelabBased
  : public DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >
{
public:
  template< class... Args >
  PdelabBased(Args&& ...args)
    : DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >(std::forward< Args >(args)...)
  {}
};

} // namespace DiscontinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH
<commit_msg>[playground.spaces.dg.pdelab] remove static_assert, refs #25<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH
#define DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH

#include <memory>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/geometry/genericgeometry/topologytypes.hh>

#if HAVE_DUNE_PDELAB
# include <dune/pdelab/finiteelementmap/qkdg.hh>
# include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
# include <dune/pdelab/constraints/conforming.hh>
#endif // HAVE_DUNE_PDELAB

#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/la/container/istl.hh>

#include <dune/gdt/spaces/parallel.hh>

#include "../../../mapper/pdelab.hh"
#include "../../../basefunctionset/pdelab.hh"

#include "../../../spaces/interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {
namespace DG {

#if HAVE_DUNE_PDELAB

// forward, to be used in the traits and to allow for specialization
template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBased
{
  static_assert(Dune::AlwaysFalse< GridViewImp >::value, "Untested for this combination of dimensions!");
}; //class PdelabBased

template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBasedTraits
{
public:
  typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
  typedef GridViewImp                   GridViewType;
  static const int                      polOrder = polynomialOrder;
private:
  typedef typename GridViewType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridViewType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
private:
  template< class G, bool single_geom, bool is_simplex, bool is_cube >
  struct FeMap
  {
    static_assert(Dune::AlwaysFalse< G >::value,
                  "This space is only implemented for either fully simplicial or fully cubic grids!");
  };
  template< class G >
  struct FeMap< G, true, true, false >
  {
    static_assert(Dune::AlwaysFalse< G >::value,
                  "Not yet implemented for simplicial grids!");
  };
  template< class G >
  struct FeMap< G, true, false, true >
  {
    typedef PDELab::QkDGLocalFiniteElementMap< DomainFieldType, RangeFieldType, polOrder, dimDomain > Type;
  };
  typedef typename GridViewType::Grid GridType;
  static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType< GridType >::v;
  static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId
                                   == GenericGeometry::SimplexTopology< dimDomain >::type::id);
  static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId
                              == GenericGeometry::CubeTopology< dimDomain >::type::id);
  typedef typename FeMap< GridType, single_geom_, simplicial_, cubic_ >::Type FEMapType;
public:
  typedef PDELab::GridFunctionSpace< GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints >
      BackendType;
  typedef Mapper::DiscontinuousPdelabWrapper< BackendType > MapperType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
  typedef BaseFunctionSet::PdelabWrapper
      < BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols >
    BaseFunctionSetType;
  static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
  static const bool needs_grid_view = true;
  typedef CommunicationChooser< GridViewType >    CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;
private:
  friend class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >;
}; // class PdelabBasedTraits

template< class GridViewImp, int polynomialOrder, class RangeFieldImp >
class PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,
                           GridViewImp::dimension, 1, 1 >
{
  typedef SpaceInterface< PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >,
                          GridViewImp::dimension, 1, 1 >                                   BaseType;
  typedef PdelabBased< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 >                          ThisType;
public:
  typedef PdelabBasedTraits< GridViewImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridViewType GridViewType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridViewType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = BaseType::dimDomain;
private:
  static_assert(GridViewType::dimension == dimDomain, "Dimension of GridView has to match dimDomain");
public:
  typedef FieldVector< DomainFieldType, dimDomain > DomainType;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = BaseType::dimRange;
  static const unsigned int               dimRangeCols = BaseType::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;
  typedef typename Traits::CommunicatorType         CommunicatorType;

private:
  typedef typename Traits::FEMapType FEMapType;

public:
  typedef typename BaseType::IntersectionType  IntersectionType;
  typedef typename BaseType::EntityType        EntityType;
  typedef typename BaseType::PatternType       PatternType;
  typedef typename BaseType::BoundaryInfoType  BoundaryInfoType;

  PdelabBased(GridViewType gV)
    : grid_view_(gV)
    , fe_map_()
    , backend_(const_cast< GridViewType& >(grid_view_), fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridViewImp>::create(grid_view_))
    , communicator_prepared_(false)
  {}

  /**
   * \brief Copy ctor.
   * \note  Manually implemented bc of the std::mutex + communicator_  unique_ptr
   */
  PdelabBased(const ThisType& other)
    : grid_view_(other.grid_view_)
    , fe_map_(other.fe_map_)
    , backend_(other.backend_)
    , mapper_(other.mapper_)
    , communicator_(CommunicationChooser< GridViewImp >::create(grid_view_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& DUNE_UNUSED(comm) = this->communicator();
  }

  /**
   * \brief Move ctor.
   * \note  Manually implemented bc of the std::mutex.
   */
  PdelabBased(ThisType&& source)
    : grid_view_(source.grid_view_)
    , fe_map_(source.fe_map_)
    , backend_(source.backend_)
    , mapper_(source.mapper_)
    , communicator_(std::move(source.communicator_))
    , communicator_prepared_(source.communicator_prepared_)
  {}

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  using BaseType::compute_pattern;

  template< class G, class S, int d, int r, int rC >
  PatternType compute_pattern(const GridView< G >& local_grid_view,
                              const SpaceInterface< S, d, r, rC >& ansatz_space) const
  {
    return BaseType::compute_face_and_volume_pattern(local_grid_view, ansatz_space);
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    std::lock_guard< std::mutex > DUNE_UNUSED(gg)(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

private:
  const GridViewType grid_view_;
  const FEMapType fe_map_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable std::unique_ptr< CommunicatorType > communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >

#else // HAVE_DUNE_PDELAB

template< class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class PdelabBased
{
  static_assert(Dune::AlwaysFalse< GridViewImp >::value, "You are missing dune-pdelab!");
};

#endif // HAVE_DUNE_PDELAB

} // namespace DG
namespace DiscontinuousLagrange {

template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class
  DUNE_DEPRECATED_MSG("Use DG::PdelabBased instead (21.11.2014)!")
      PdelabBased
  : public DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >
{
public:
  template< class... Args >
  PdelabBased(Args&& ...args)
    : DG::PdelabBased< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols >(std::forward< Args >(args)...)
  {}
};

} // namespace DiscontinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_DG_PDELAB_HH
<|endoftext|>


<commit_before>class crb_tc_markers {
        title = "TCells Insurgency Style Markers";
        values[]= {0,1};
        texts[]= {"Off","On"};
        default = 1;
};

class crb_tc_intensity {
        title = "TCells Recruitment Intensity per Hour";
        values[]= {0.25,0.5,1,2,3};
        texts[]= {"4 Recruits","2 Recruits","1 Recruit","0.5 Recruit","0.33 Recruit"};
        default = 1;
};

<commit_msg>- Renamed parameters<commit_after>class crb_tc_markers {
        title = "Enemy - TCells Insurgency Style Markers";
        values[]= {0,1};
        texts[]= {"Off","On"};
        default = 1;
};

class crb_tc_intensity {
        title = "Enemy - TCells Recruitment per Hour";
        values[]= {0.25,0.5,1,2,3};
        texts[]= {"4 Recruits","2 Recruits","1 Recruit","0.5 Recruit","0.33 Recruit"};
        default = 1;
};

<|endoftext|>


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

#include "esnpapi.h"
#include "proxyImpl.h"

#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeWebDatabaseMetaData()
{
    ProxyControl::registerMetaData(webdatabase::DatabaseCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::Database::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::Database_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::DatabaseSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseSync_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLError::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLError_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLResultSet::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSet_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLResultSetRowList::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSetRowList_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLStatementCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLStatementErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementErrorCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionErrorCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransaction::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransaction_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionSyncCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSyncCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSync_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance);
}
<commit_msg>(initializeWebDatabaseMetaData) : Register 'VoidCallback' as 'SQLVoidCallback' for WebKit.<commit_after>/*
 * Copyright 2008-2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "esnpapi.h"
#include "proxyImpl.h"

#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeWebDatabaseMetaData()
{
    ProxyControl::registerMetaData(webdatabase::DatabaseCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::Database::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::Database_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::DatabaseSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::DatabaseSync_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLError::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLError_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLResultSet::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSet_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLResultSetRowList::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLResultSetRowList_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLStatementCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLStatementErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLStatementErrorCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionErrorCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionErrorCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransaction::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransaction_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionSyncCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSyncCallback_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLTransactionSync::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLTransactionSync_Bridge<Any, invoke> >::createInstance);
    ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance);

    //
    // Workaround for WebKit
    //
    ProxyControl::registerMetaData(webdatabase::SQLVoidCallback::getMetaData(), Proxy_Impl<ProxyObject, webdatabase::SQLVoidCallback_Bridge<Any, invoke> >::createInstance,
                                   "VoidCallback");
}
<|endoftext|>


<commit_before>#include <math.h>
#include "semanticcomposefunctions.h"
#include "kwindow.h"

string ComposeAsIs::name = "As Is";
TSemanticValue ComposeAsIs::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  return myInfo->values[ 0 ];
}

string ComposeSign::name = "Sign";
TSemanticValue ComposeSign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  if ( myInfo->values[ 0 ] != 0 )
    return 1;
  return 0;
}

string ComposeUnsign::name = "1-Sign";
TSemanticValue ComposeUnsign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp;

  if ( myInfo->values[ 0 ] != 0 )
    tmp = 1;
  else
    tmp = 0;

  return 1 - tmp;
}

string ComposeMod::name = "Mod";
TSemanticValue ComposeMod::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue remainder = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    divider = parameters[ DIVIDER ][ 0 ];
  else
    divider = 1;

  remainder = fmod( myInfo->values[ 0 ], divider );

  return remainder;
}

string ComposeModPlus1::name = "Mod+1";
TSemanticValue ComposeModPlus1::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue remainder = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    divider = parameters[ DIVIDER ][ 0 ];
  else
    divider = 1;

  remainder = fmod( myInfo->values[ 0 ], divider );

  return remainder + 1;
}

string ComposeDivide::name = "Div";
TSemanticValue ComposeDivide::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue quotient = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    quotient = myInfo->values[ 0 ] / parameters[ DIVIDER ][ 0 ];
  else
  {
    divider = 1;
    quotient = fmod( myInfo->values[ 0 ], divider );
  }
  return quotient;
}

string ComposeProduct::name = "Prod";
TSemanticValue ComposeProduct::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] * parameters[ FACTOR ][ 0 ];
}

string ComposeAdding::name = "Add";
TSemanticValue ComposeAdding::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] + parameters[ FACTOR ][ 0 ];
}

string ComposeSubstract::name = "Subs";
TSemanticValue ComposeSubstract::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] - parameters[ FACTOR ][ 0 ];
}

string ComposeSelectRange::name = "Select Range";
TSemanticValue ComposeSelectRange::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = myInfo->values[ 0 ];
  else
    tmp = 0;

  return tmp;
}

string ComposeSelectRangeOpen::name = "Select Range [)";
TSemanticValue ComposeSelectRangeOpen::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = myInfo->values[ 0 ];
  else
    tmp = 0;

  return tmp;
}

string ComposeIsInRange::name = "Is In Range";
TSemanticValue ComposeIsInRange::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = 1;
  else
    tmp = 0;

  return tmp;
}

string ComposeIsInRangeOpen::name = "Is In Range [)";
TSemanticValue ComposeIsInRangeOpen::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = 1;
  else
    tmp = 0;

  return tmp;
}

string ComposeIsEqual::name = "Is Equal";
TSemanticValue ComposeIsEqual::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )
  {
    if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )
    {
      tmp = myInfo->values[ 0 ];
      break;
    }
  }

  return tmp;
}

string ComposeIsEqualSign::name = "Is Equal (Sign)";
TSemanticValue ComposeIsEqualSign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )
  {
    if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )
    {
      tmp = 1;
      break;
    }
  }

  return tmp;
}

void ComposeStackedValue::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
}

string ComposeStackedValue::name = "Stacked Val";
TSemanticValue ComposeStackedValue::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );
  else
  {
    if ( !myStack[ tmpOrder ].empty() )
      myStack[ tmpOrder ].pop_back();
  }

  if ( myStack[ tmpOrder ].empty() )
    return 0;

  return myStack[ tmpOrder ].back();
}

void ComposeInStackedValue::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
}

string ComposeInStackedValue::name = "In Stacked Val";
TSemanticValue ComposeInStackedValue::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );
  else
  {
    if ( !myStack[ tmpOrder ].empty() )
      myStack[ tmpOrder ].pop_back();
  }

  if ( myStack[ tmpOrder ].empty() )
    return 0;

  return myStack[ tmpOrder ].back() == parameters[ VALUE ][ 0 ] ?
         myStack[ tmpOrder ].back() : 0;
}

void ComposeNestingLevel::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( 0 );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( 0 );
  }
}

string ComposeNestingLevel::name = "Nesting Level";
TSemanticValue ComposeNestingLevel::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ]++;
  else
    myStack[ tmpOrder ]--;

  return myStack[ tmpOrder ];
}

void ComposeDelta::init( KWindow *whichWindow )
{
  prevValue.clear();
  semPrevValue.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    prevValue.reserve( whichWindow->getTrace()->totalThreads() );
    semPrevValue.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
    {
      prevValue.push_back( 0 );
      semPrevValue.push_back( 0 );
    }
  }
  else
  {
    prevValue.reserve( whichWindow->getTrace()->totalCPUs() );
    semPrevValue.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
    {
      prevValue.push_back( 0 );
      semPrevValue.push_back( 0 );
    }
  }
}

string ComposeDelta::name = "Delta";
TSemanticValue ComposeDelta::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();
  TSemanticValue result = 0;

  if ( myInfo->values[ 0 ] > semPrevValue[ tmpOrder ] )
    result = myInfo->values[ 0 ] - semPrevValue[ tmpOrder ];
  else if ( myInfo->values[ 0 ] == semPrevValue[ tmpOrder ] )
    result = prevValue[ tmpOrder ];

  semPrevValue[ tmpOrder ] = myInfo->values[ 0 ];
  prevValue[ tmpOrder ] = result;

  return result;
}

string ComposeBurstTime::name = "Burst Time";
TSemanticValue ComposeBurstTime::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  TSemanticValue result = myInfo->callingInterval->getEnd()->getTime() -
                          myInfo->callingInterval->getBegin()->getTime();
  result = myInfo->callingInterval->getWindow()->traceUnitsToWindowUnits( result );
  return result;
}

string ComposeJoinBursts::name = "Join Bursts";
TSemanticValue ComposeJoinBursts::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ];
}
<commit_msg>*** empty log message ***<commit_after>#include <math.h>
#include "semanticcomposefunctions.h"
#include "kwindow.h"

string ComposeAsIs::name = "As Is";
TSemanticValue ComposeAsIs::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  return myInfo->values[ 0 ];
}

string ComposeSign::name = "Sign";
TSemanticValue ComposeSign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  if ( myInfo->values[ 0 ] != 0 )
    return 1;
  return 0;
}

string ComposeUnsign::name = "1-Sign";
TSemanticValue ComposeUnsign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp;

  if ( myInfo->values[ 0 ] != 0 )
    tmp = 1;
  else
    tmp = 0;

  return 1 - tmp;
}

string ComposeMod::name = "Mod";
TSemanticValue ComposeMod::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue remainder = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    divider = parameters[ DIVIDER ][ 0 ];
  else
    divider = 1;

  remainder = fmod( myInfo->values[ 0 ], divider );

  return remainder;
}

string ComposeModPlus1::name = "Mod+1";
TSemanticValue ComposeModPlus1::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue remainder = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    divider = parameters[ DIVIDER ][ 0 ];
  else
    divider = 1;

  remainder = fmod( myInfo->values[ 0 ], divider );

  return remainder + 1;
}

string ComposeDivide::name = "Div";
TSemanticValue ComposeDivide::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue quotient = 0, divider;

  if ( parameters[ DIVIDER ][ 0 ] != 0 )
    quotient = myInfo->values[ 0 ] / parameters[ DIVIDER ][ 0 ];
  else
  {
    divider = 1;
    quotient = fmod( myInfo->values[ 0 ], divider );
  }
  return quotient;
}

string ComposeProduct::name = "Prod";
TSemanticValue ComposeProduct::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] * parameters[ FACTOR ][ 0 ];
}

string ComposeAdding::name = "Add";
TSemanticValue ComposeAdding::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] + parameters[ FACTOR ][ 0 ];
}

string ComposeSubstract::name = "Subs";
TSemanticValue ComposeSubstract::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ] - parameters[ FACTOR ][ 0 ];
}

string ComposeSelectRange::name = "Select Range";
TSemanticValue ComposeSelectRange::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = myInfo->values[ 0 ];
  else
    tmp = 0;

  return tmp;
}

string ComposeSelectRangeOpen::name = "Select Range [)";
TSemanticValue ComposeSelectRangeOpen::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = myInfo->values[ 0 ];
  else
    tmp = 0;

  return tmp;
}

string ComposeIsInRange::name = "Is In Range";
TSemanticValue ComposeIsInRange::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] <= parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = 1;
  else
    tmp = 0;

  return tmp;
}

string ComposeIsInRangeOpen::name = "Is In Range [)";
TSemanticValue ComposeIsInRangeOpen::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  if ( myInfo->values[ 0 ] < parameters[ MAXVALUE ][ 0 ] &&
       myInfo->values[ 0 ] >= parameters[ MINVALUE ][ 0 ] )
    tmp = 1;
  else
    tmp = 0;

  return tmp;
}

string ComposeIsEqual::name = "Is Equal";
TSemanticValue ComposeIsEqual::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )
  {
    if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )
    {
      tmp = myInfo->values[ 0 ];
      break;
    }
  }

  return tmp;
}

string ComposeIsEqualSign::name = "Is Equal (Sign)";
TSemanticValue ComposeIsEqualSign::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TSemanticValue tmp = 0;

  for ( TParamIndex i = 0; i < parameters[ VALUES ].size(); i++ )
  {
    if ( myInfo->values[ 0 ] == parameters[ VALUES ][ i ] )
    {
      tmp = 1;
      break;
    }
  }

  return tmp;
}

void ComposeStackedValue::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
}

string ComposeStackedValue::name = "Stacked Val";
TSemanticValue ComposeStackedValue::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );
  else
  {
    if ( !myStack[ tmpOrder ].empty() )
      myStack[ tmpOrder ].pop_back();
  }

  if ( myStack[ tmpOrder ].empty() )
    return 0;

  return myStack[ tmpOrder ].back();
}

void ComposeInStackedValue::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( vector<TSemanticValue>() );
  }
}

string ComposeInStackedValue::name = "In Stacked Val";
TSemanticValue ComposeInStackedValue::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ].push_back( myInfo->values[ 0 ] );
  else
  {
    if ( !myStack[ tmpOrder ].empty() )
      myStack[ tmpOrder ].pop_back();
  }

  if ( myStack[ tmpOrder ].empty() )
    return 0;

  return myStack[ tmpOrder ].back() == parameters[ VALUE ][ 0 ] ?
         myStack[ tmpOrder ].back() : 0;
}

void ComposeNestingLevel::init( KWindow *whichWindow )
{
  myStack.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    myStack.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
      myStack.push_back( 0 );
  }
  else
  {
    myStack.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
      myStack.push_back( 0 );
  }
}

string ComposeNestingLevel::name = "Nesting level";
TSemanticValue ComposeNestingLevel::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();

  if ( myInfo->values[ 0 ] != 0 )
    myStack[ tmpOrder ]++;
  else
    myStack[ tmpOrder ]--;

  return myStack[ tmpOrder ];
}

void ComposeDelta::init( KWindow *whichWindow )
{
  prevValue.clear();
  semPrevValue.clear();

  if ( whichWindow->getTrace()->totalThreads() >
       whichWindow->getTrace()->totalCPUs() )
  {
    prevValue.reserve( whichWindow->getTrace()->totalThreads() );
    semPrevValue.reserve( whichWindow->getTrace()->totalThreads() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalThreads(); i++ )
    {
      prevValue.push_back( 0 );
      semPrevValue.push_back( 0 );
    }
  }
  else
  {
    prevValue.reserve( whichWindow->getTrace()->totalCPUs() );
    semPrevValue.reserve( whichWindow->getTrace()->totalCPUs() );
    for ( TThreadOrder i = 0; i < whichWindow->getTrace()->totalCPUs(); i++ )
    {
      prevValue.push_back( 0 );
      semPrevValue.push_back( 0 );
    }
  }
}

string ComposeDelta::name = "Delta";
TSemanticValue ComposeDelta::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  TObjectOrder tmpOrder = myInfo->callingInterval->getOrder();
  TSemanticValue result = 0;

  if ( myInfo->values[ 0 ] > semPrevValue[ tmpOrder ] )
    result = myInfo->values[ 0 ] - semPrevValue[ tmpOrder ];
  else if ( myInfo->values[ 0 ] == semPrevValue[ tmpOrder ] )
    result = prevValue[ tmpOrder ];

  semPrevValue[ tmpOrder ] = myInfo->values[ 0 ];
  prevValue[ tmpOrder ] = result;

  return result;
}

string ComposeBurstTime::name = "Burst Time";
TSemanticValue ComposeBurstTime::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;
  TSemanticValue result = myInfo->callingInterval->getEnd()->getTime() -
                          myInfo->callingInterval->getBegin()->getTime();
  result = myInfo->callingInterval->getWindow()->traceUnitsToWindowUnits( result );
  return result;
}

string ComposeJoinBursts::name = "Join Bursts";
TSemanticValue ComposeJoinBursts::execute( const SemanticInfo *info )
{
  const SemanticHighInfo *myInfo = ( const SemanticHighInfo * ) info;

  return myInfo->values[ 0 ];
}
<|endoftext|>