<commit_before>/*******************************************************************************
 * benchmarks/net/net_benchmark.cpp
 *
 * Network backend benchmarks:
 * - 1-factor ping pong latency benchmark
 * - 1-factor full bandwidth test
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/context.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/common/string.hpp>

#include <string>
#include <utility>
#include <vector>

std::string benchmark;

unsigned int outer_repeats = 1;
unsigned int inner_repeats = 1;

using namespace thrill;

//! perform a 1-factor ping pong latency test
void PingPongLatencyTest(api::Context& ctx) {

    // only work with first thread on this host.
    if (ctx.local_worker_id() != 0) return;

    net::Group& group = ctx.flow_control_channel().group();

    // a counter to count and match ping pongs.
    size_t counter = 0;

    for (size_t outer_repeat = 0;
         outer_repeat < outer_repeats; ++outer_repeat) {

        common::StatsTimer<true> timer;

        timer.Start();
        for (size_t inner_repeat = 0;
             inner_repeat < inner_repeats; inner_repeat++) {
            // perform 1-factor ping pongs (without barriers)
            for (size_t iter = 0; iter < ctx.num_hosts(); ++iter) {

                size_t peer = group.OneFactorPeer(iter);

                sLOG0 << "round iter" << iter
                      << "me" << ctx.host_rank() << "peer" << peer;

                if (ctx.host_rank() < peer) {
                    // send ping to peer
                    size_t value = counter++;
                    group.SendTo(peer, value);

                    // wait for ping
                    group.ReceiveFrom(peer, &value);
                    assert(value == counter);
                }
                else if (ctx.host_rank() > peer) {
                    // wait for ping
                    size_t value;
                    group.ReceiveFrom(peer, &value);
                    assert(value == counter);

                    // increment counters
                    counter++, value++;

                    // send pong
                    group.SendTo(peer, value);
                }
                else {
                    // not participating in this round
                    ++counter;
                }
            }
        }
        timer.Stop();

        size_t time = timer.Microseconds();
        // calculate maximum time.
        group.AllReduce(time, common::maximum<size_t>());

        if (ctx.my_rank() == 0) {
            LOG1 << "RESULT"
                 << " benchmark=" << benchmark
                 << " hosts=" << ctx.num_hosts()
                 << " outer_repeat=" << outer_repeat
                 << " inner_repeats=" << inner_repeats
                 << " ping_pongs=" << counter
                 << " time[us]=" << time
                 << " time_per_ping_pong[us]=" << static_cast<double>(time) / counter;
        }
    }
}

//! perform a 1-factor bandwidth test
void BandwidthTest(api::Context& ctx) {

    // only work with first thread on this host.
    if (ctx.local_worker_id() != 0) return;

    net::Group& group = ctx.flow_control_channel().group();

    // a counter to count and match messages
    size_t counter = 0;

    // data block to send or receive
    static const size_t block_count = 1024;
    static const size_t block_size = 1024 * 1024;
    std::array<size_t, block_size / sizeof(size_t)> data_block;
    std::fill(data_block.begin(), data_block.end(), 42u);

    for (size_t outer_repeat = 0;
         outer_repeat < outer_repeats; ++outer_repeat) {

        common::StatsTimer<true> timer;

        timer.Start();
        for (size_t inner_repeat = 0;
             inner_repeat < inner_repeats; inner_repeat++) {
            // perform 1-factor ping pongs (without barriers)
            for (size_t iter = 0; iter < ctx.num_hosts(); ++iter) {

                size_t peer = group.OneFactorPeer(iter);

                sLOG0 << "round iter" << iter
                      << "me" << ctx.host_rank() << "peer" << peer;

                if (ctx.host_rank() < peer) {
                    common::StatsTimer<true> bwtimer(true);
                    // send blocks to peer
                    for (size_t i = 0; i != block_count; ++i) {
                        data_block.front() = counter;
                        data_block.back() = counter;
                        ++counter;
                        group.SendTo(peer, data_block);
                    }

                    // wait for response pong
                    size_t value;
                    group.ReceiveFrom(peer, &value);
                    assert(value == counter);

                    bwtimer.Stop();

                    sLOG1 << "bandwidth" << ctx.host_rank() << "->" << peer
                          << ((block_count * block_size) / (bwtimer.Microseconds() * 1e-6)
                              / 1024.0 / 1024.0)
                          << "MiB/s"
                          << "time" << (bwtimer.Microseconds() * 1e-6);
                }
                else if (ctx.host_rank() > peer) {
                    // receive blocks from peer
                    for (size_t i = 0; i != block_count; ++i) {
                        group.ReceiveFrom(peer, &data_block);
                        die_unequal(data_block.front(), counter);
                        die_unequal(data_block.back(), counter);

                        ++counter;
                    }

                    // send ping
                    group.SendTo(peer, counter);
                }
                else {
                    // not participating in this round
                    counter += block_count;
                }
            }
        }
        timer.Stop();

        size_t time = timer.Microseconds();
        // calculate maximum time.
        group.AllReduce(time, common::maximum<size_t>());

        if (ctx.my_rank() == 0) {
            LOG1 << "RESULT"
                 << " benchmark=" << benchmark
                 << " hosts=" << ctx.num_hosts()
                 << " outer_repeat=" << outer_repeat
                 << " inner_repeats=" << inner_repeats
                 << " ping_pongs=" << counter
                 << " time[us]=" << time
                 << " time_per_ping_pong[us]=" << static_cast<double>(time) / counter;
        }
    }
}

//! Network benchmarking.
void net_test(api::Context& ctx) {
    if (benchmark == "pingpong") {
        PingPongLatencyTest(ctx);
    }
    else if (benchmark == "bandwidth") {
        BandwidthTest(ctx);
    }
    else {
        die("Unknown benchmark " + benchmark);
    }
}

int main(int argc, char** argv) {

    common::CmdlineParser clp;

    clp.SetVerboseProcess(false);

    clp.AddUInt('r', "inner_repeats", inner_repeats,
                "Repeat inner experiment a number of times.");

    clp.AddUInt('R', "outer_repeats", outer_repeats,
                "Repeat whole experiment a number of times.");

    clp.AddParamString("benchmark", benchmark,
                       "name of benchmark to run:\n"
                       "  pingpong - 1-factor latency\n"
                       "  bandwidth - 1-factor full bandwidth");

    if (!clp.Process(argc, argv)) {
        return -1;
    }

    clp.PrintResult();

    return api::Run(net_test);
}

/******************************************************************************/
<commit_msg>net/bandwidth benchmark: SyncSend directly from vector without serialization.<commit_after>/*******************************************************************************
 * benchmarks/net/net_benchmark.cpp
 *
 * Network backend benchmarks:
 * - 1-factor ping pong latency benchmark
 * - 1-factor full bandwidth test
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/context.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/common/string.hpp>

#include <string>
#include <utility>
#include <vector>

std::string benchmark;

unsigned int outer_repeats = 1;
unsigned int inner_repeats = 1;

using namespace thrill;

//! perform a 1-factor ping pong latency test
void PingPongLatencyTest(api::Context& ctx) {

    // only work with first thread on this host.
    if (ctx.local_worker_id() != 0) return;

    net::Group& group = ctx.flow_control_channel().group();

    // a counter to count and match ping pongs.
    size_t counter = 0;

    for (size_t outer_repeat = 0;
         outer_repeat < outer_repeats; ++outer_repeat) {

        common::StatsTimer<true> timer;

        timer.Start();
        for (size_t inner_repeat = 0;
             inner_repeat < inner_repeats; inner_repeat++) {
            // perform 1-factor ping pongs (without barriers)
            for (size_t iter = 0; iter < ctx.num_hosts(); ++iter) {

                size_t peer = group.OneFactorPeer(iter);

                sLOG0 << "round iter" << iter
                      << "me" << ctx.host_rank() << "peer" << peer;

                if (ctx.host_rank() < peer) {
                    // send ping to peer
                    size_t value = counter++;
                    group.SendTo(peer, value);

                    // wait for ping
                    group.ReceiveFrom(peer, &value);
                    assert(value == counter);
                }
                else if (ctx.host_rank() > peer) {
                    // wait for ping
                    size_t value;
                    group.ReceiveFrom(peer, &value);
                    assert(value == counter);

                    // increment counters
                    counter++, value++;

                    // send pong
                    group.SendTo(peer, value);
                }
                else {
                    // not participating in this round
                    ++counter;
                }
            }
        }
        timer.Stop();

        size_t time = timer.Microseconds();
        // calculate maximum time.
        group.AllReduce(time, common::maximum<size_t>());

        if (ctx.my_rank() == 0) {
            LOG1 << "RESULT"
                 << " benchmark=" << benchmark
                 << " hosts=" << ctx.num_hosts()
                 << " outer_repeat=" << outer_repeat
                 << " inner_repeats=" << inner_repeats
                 << " ping_pongs=" << counter
                 << " time[us]=" << time
                 << " time_per_ping_pong[us]=" << static_cast<double>(time) / counter;
        }
    }
}

//! perform a 1-factor bandwidth test
void BandwidthTest(api::Context& ctx) {

    // only work with first thread on this host.
    if (ctx.local_worker_id() != 0) return;

    net::Group& group = ctx.flow_control_channel().group();

    // a counter to count and match messages
    size_t counter = 0;

    // data block to send or receive
    static const size_t block_count = 1024;
    static const size_t block_size = 16 * 1024 * 1024;
    std::vector<size_t> data_block(block_size / sizeof(size_t));
    std::fill(data_block.begin(), data_block.end(), 42u);

    for (size_t outer_repeat = 0;
         outer_repeat < outer_repeats; ++outer_repeat) {

        common::StatsTimer<true> timer;

        timer.Start();
        for (size_t inner_repeat = 0;
             inner_repeat < inner_repeats; inner_repeat++) {
            // perform 1-factor ping pongs (without barriers)
            for (size_t iter = 0; iter < ctx.num_hosts(); ++iter) {

                size_t peer_id = group.OneFactorPeer(iter);
                net::Connection& peer = group.connection(peer_id);

                sLOG0 << "round iter" << iter
                      << "me" << ctx.host_rank() << "peer" << peer;

                if (ctx.host_rank() < peer_id) {
                    common::StatsTimer<true> bwtimer(true);
                    // send blocks to peer
                    for (size_t i = 0; i != block_count; ++i) {
                        data_block.front() = counter;
                        data_block.back() = counter;
                        ++counter;
                        peer.SyncSend(data_block.data(), block_size);
                    }

                    // wait for response pong
                    size_t value;
                    peer.Receive(&value);
                    assert(value == counter);

                    bwtimer.Stop();

                    sLOG1 << "bandwidth" << ctx.host_rank() << "->" << peer_id
                          << ((block_count * block_size) / (bwtimer.Microseconds() * 1e-6)
                              / 1024.0 / 1024.0)
                          << "MiB/s"
                          << "time" << (bwtimer.Microseconds() * 1e-6);
                }
                else if (ctx.host_rank() > peer_id) {
                    // receive blocks from peer
                    for (size_t i = 0; i != block_count; ++i) {
                        peer.SyncRecv(data_block.data(), block_size);
                        die_unequal(data_block.front(), counter);
                        die_unequal(data_block.back(), counter);

                        ++counter;
                    }

                    // send ping
                    peer.Send(counter);
                }
                else {
                    // not participating in this round
                    counter += block_count;
                }
            }
        }
        timer.Stop();

        size_t time = timer.Microseconds();
        // calculate maximum time.
        group.AllReduce(time, common::maximum<size_t>());

        if (ctx.my_rank() == 0) {
            LOG1 << "RESULT"
                 << " benchmark=" << benchmark
                 << " hosts=" << ctx.num_hosts()
                 << " outer_repeat=" << outer_repeat
                 << " inner_repeats=" << inner_repeats
                 << " ping_pongs=" << counter
                 << " time[us]=" << time
                 << " time_per_ping_pong[us]=" << static_cast<double>(time) / counter;
        }
    }
}

//! Network benchmarking.
void net_test(api::Context& ctx) {
    if (benchmark == "pingpong") {
        PingPongLatencyTest(ctx);
    }
    else if (benchmark == "bandwidth") {
        BandwidthTest(ctx);
    }
    else {
        die("Unknown benchmark " + benchmark);
    }
}

int main(int argc, char** argv) {

    common::CmdlineParser clp;

    clp.SetVerboseProcess(false);

    clp.AddUInt('r', "inner_repeats", inner_repeats,
                "Repeat inner experiment a number of times.");

    clp.AddUInt('R', "outer_repeats", outer_repeats,
                "Repeat whole experiment a number of times.");

    clp.AddParamString("benchmark", benchmark,
                       "name of benchmark to run:\n"
                       "  pingpong - 1-factor latency\n"
                       "  bandwidth - 1-factor full bandwidth");

    if (!clp.Process(argc, argv)) {
        return -1;
    }

    clp.PrintResult();

    return api::Run(net_test);
}

/******************************************************************************/
<|endoftext|>


<commit_before><commit_msg>Created NumberArray.cpp<commit_after><|endoftext|>


<commit_before>/*
 * CollisionAvoidance.cpp
 *
 *  Created on: 16 Mar 2015
 *      Author: yiming
 */
#include "kinematic_maps/CollisionAvoidance.h"

REGISTER_TASKMAP_TYPE("CollisionAvoidance", exotica::CollisionAvoidance);

void eigen2Point(const Eigen::Vector3d & eigen, geometry_msgs::Point & point)
{
	point.x = eigen(0);
	point.y = eigen(1);
	point.z = eigen(2);
}
namespace exotica
{
	CollisionAvoidance::CollisionAvoidance()
	{
#ifdef C_DEBUG
		ROS_ERROR("Running collision avoidance taskmap in debug mode");
		nh_ = ros::NodeHandle("CollisionAvoidance");
		close_pub_ = nh_.advertise<visualization_msgs::Marker>("close_marker", 100);
		centre_pub_ = nh_.advertise<visualization_msgs::Marker>("centre_marker", 100);
		close_.type = visualization_msgs::Marker::LINE_LIST;
		close_.scale.x = 0.004;
		close_.color.g = 1;
		close_.color.a = 1;

		centre_.type = visualization_msgs::Marker::SPHERE_LIST;
		centre_.scale.x = close_.scale.y = close_.scale.z = 0.05;
		centre_.color.g = 1;
		centre_.color.a = 1;
#endif
	}

    EReturn CollisionAvoidance::setObsFrame(const KDL::Frame & tf)
    {
        std::vector<double> q(4);
        tf.M.GetQuaternion(q[0], q[1], q[2], q[3]);
        fcl::Quaternion3f quat(q[3], q[0], q[1], q[2]);
        fcl::Vec3f vec(tf.p.x(), tf.p.y(), tf.p.z() + 0.05);
        obs_in_base_tf_.setTransform(quat, vec);
        return SUCCESS;
    }

	CollisionAvoidance::~CollisionAvoidance()
	{

	}

	EReturn CollisionAvoidance::initDerived(tinyxml2::XMLHandle & handle)
	{
		tinyxml2::XMLHandle tmp_handle = handle.FirstChildElement("SafetyRange");
		server_->registerParam<std_msgs::Float64>(ns_, tmp_handle, safe_range_);
		std::cout << "Collision avoidance threshold " << safe_range_->data << " m." << std::endl;
		if (!ok(scene_->getEndEffectors(object_name_, effs_)))
			return MMB_NIN;
		init_offsets_.resize(effs_.size());
		for (int i = 0; i < effs_.size(); i++)
			init_offsets_[i] = KDL::Frame::Identity();
		kin_sol_ = scene_->getSolver();
		kinematica::SolutionForm_t sol;
		sol.end_effector_segs = effs_;
		sol.end_effector_offs = std::vector<KDL::Frame>(effs_.size());
		kin_sol_.updateEndEffectors(sol);
#ifdef C_DEBUG
		centre_.header.frame_id = close_.header.frame_id = "/" + kin_sol_.getRootName();

#endif
		return FAILURE;
	}

    EReturn CollisionAvoidance::setPreUpdateCallback(boost::function<void(CollisionAvoidance*, const Eigen::VectorXd &, int)> pre_update_callback)
    {
        pre_update_callback_ = pre_update_callback;
    }

	EReturn CollisionAvoidance::taskSpaceDim(int & task_dim)
	{
		task_dim = 1;
		return SUCCESS;
	}
	EReturn CollisionAvoidance::update(const Eigen::VectorXd & x, const int t)
	{
		invalidate();
        if (pre_update_callback_) pre_update_callback_(this, x, t);
		int M = scene_->getMapSize(object_name_), N = x.rows();
		if (M != effs_.size())
		{
			INDICATE_FAILURE
			return FAILURE;
		}
		Eigen::VectorXd eff_phi(3 * M);
		Eigen::MatrixXd eff_jac(3 * M, N);
		if (!ok(scene_->getForwardMap(object_name_, eff_phi))
				|| !ok(scene_->getJacobian(object_name_, eff_jac)))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		Eigen::VectorXd phi = Eigen::VectorXd::Zero(1);
		std::vector<double> dists(M);
		std::vector<double> costs(M);
		std::vector<Eigen::Vector3d> c1s(M), c2s(M);
		KDL::Frame tip_offset, cp_offset, eff_offset;
		std::vector<Eigen::Vector3d> norms(M);
#ifdef C_DEBUG
		close_.points.clear();
		centre_.points.clear();
#endif

        for (auto& objvec : scene_->getCollisionScene()->getFCLWorld())
        {
            for (boost::shared_ptr<fcl::CollisionObject> obj : objvec.second)
            {
                obj->setTransform(obs_in_base_tf_);
            }
        }

		for (int i = 0; i < M; i++)
		{
			Eigen::Vector3d tmp1, tmp2;
			scene_->getCollisionScene()->getRobotDistance(effs_[i], false, dists[i], tmp1, tmp2, norms[i], c1s[i], c2s[i]);
			//	Compute Phi
			if (dists[i] <= 0)
			{
#ifdef C_DEBUG
				ROS_ERROR_STREAM("Robot link " << effs_[i] << " is in collision");
#endif
				costs[i] = 1;
			}
			else if (dists[i] > safe_range_->data)
				costs[i] = 0;
			else
				costs[i] = (1.0 - dists[i] / safe_range_->data);
			phi(0) += costs[i] * costs[i];

			//	Modify end-effectors

			tip_offset = KDL::Frame(KDL::Vector(eff_phi(3 * i), eff_phi(3 * i + 1), eff_phi(3 * i
					+ 2)));
			cp_offset = KDL::Frame(KDL::Vector(tmp1(0), tmp1(1), tmp1(2)));
			eff_offset = tip_offset.Inverse() * cp_offset;
			if (!kin_sol_.modifyEndEffector(effs_[i], eff_offset))
			{
				INDICATE_FAILURE
				return FAILURE;
			}
#ifdef C_DEBUG
			geometry_msgs::Point p1, p2;
			if (dists[i] > 0)
			{
				eigen2Point(tmp1, p1);
				eigen2Point(tmp2, p2);
			}
			else
			{
				eigen2Point(c1s[i], p1);
				eigen2Point(c2s[i], p2);
			}
			close_.points.push_back(p1);
			close_.points.push_back(p2);
			eigen2Point(c1s[i], p1);
			eigen2Point(c2s[i], p2);
			centre_.points.push_back(p1);
			centre_.points.push_back(p2);
#endif
		}

#ifdef C_DEBUG
		close_pub_.publish(close_);
		centre_pub_.publish(centre_);
		ros::spinOnce();
#endif

		if (!kin_sol_.updateConfiguration(x) || !kin_sol_.generateForwardMap()
				|| !kin_sol_.generateJacobian(eff_jac))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		Eigen::MatrixXd jac = Eigen::MatrixXd::Zero(1, N);
		for (int i = 0; i < M; i++)
		{
			if (dists[i] <= 0)
			{
				Eigen::Vector3d tmpnorm = c2s[i] - c1s[i];
				tmpnorm.normalize();
				jac += ((2.0 * costs[i]) / safe_range_->data)
						* (tmpnorm.transpose() * eff_jac.block(3 * i, 0, 3, N));
			}
			else if (dists[i] <= safe_range_->data)
				jac += ((2.0 * costs[i]) / safe_range_->data)
						* (norms[i].transpose() * eff_jac.block(3 * i, 0, 3, N));
		}
		if (!ok(setPhi(phi, t)) || !ok(setJacobian(jac, t)))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		//	Reset the initial end-effectors

		//ROS_ERROR_STREAM("Jac="<<jac);
		return SUCCESS;
	}
}

<commit_msg>Collision avoidance init fix<commit_after>/*
 * CollisionAvoidance.cpp
 *
 *  Created on: 16 Mar 2015
 *      Author: yiming
 */
#include "kinematic_maps/CollisionAvoidance.h"

REGISTER_TASKMAP_TYPE("CollisionAvoidance", exotica::CollisionAvoidance);

void eigen2Point(const Eigen::Vector3d & eigen, geometry_msgs::Point & point)
{
	point.x = eigen(0);
	point.y = eigen(1);
	point.z = eigen(2);
}
namespace exotica
{
	CollisionAvoidance::CollisionAvoidance()
	{
#ifdef C_DEBUG
		ROS_ERROR("Running collision avoidance taskmap in debug mode");
		nh_ = ros::NodeHandle("CollisionAvoidance");
		close_pub_ = nh_.advertise<visualization_msgs::Marker>("close_marker", 100);
		centre_pub_ = nh_.advertise<visualization_msgs::Marker>("centre_marker", 100);
		close_.type = visualization_msgs::Marker::LINE_LIST;
		close_.scale.x = 0.004;
		close_.color.g = 1;
		close_.color.a = 1;

		centre_.type = visualization_msgs::Marker::SPHERE_LIST;
		centre_.scale.x = close_.scale.y = close_.scale.z = 0.05;
		centre_.color.g = 1;
		centre_.color.a = 1;
#endif
	}

    EReturn CollisionAvoidance::setObsFrame(const KDL::Frame & tf)
    {
        std::vector<double> q(4);
        tf.M.GetQuaternion(q[0], q[1], q[2], q[3]);
        fcl::Quaternion3f quat(q[3], q[0], q[1], q[2]);
        fcl::Vec3f vec(tf.p.x(), tf.p.y(), tf.p.z() + 0.05);
        obs_in_base_tf_.setTransform(quat, vec);
        return SUCCESS;
    }

	CollisionAvoidance::~CollisionAvoidance()
	{

	}

	EReturn CollisionAvoidance::initDerived(tinyxml2::XMLHandle & handle)
	{
		tinyxml2::XMLHandle tmp_handle = handle.FirstChildElement("SafetyRange");
		server_->registerParam<std_msgs::Float64>(ns_, tmp_handle, safe_range_);
		std::cout << "Collision avoidance threshold " << safe_range_->data << " m." << std::endl;
		if (!ok(scene_->getEndEffectors(object_name_, effs_)))
			return MMB_NIN;
		init_offsets_.resize(effs_.size());
		for (int i = 0; i < effs_.size(); i++)
			init_offsets_[i] = KDL::Frame::Identity();
		kin_sol_ = scene_->getSolver();
		kinematica::SolutionForm_t sol;
		sol.end_effector_segs = effs_;
		sol.end_effector_offs = std::vector<KDL::Frame>(effs_.size());
		kin_sol_.updateEndEffectors(sol);
#ifdef C_DEBUG
		centre_.header.frame_id = close_.header.frame_id = "/" + kin_sol_.getRootName();
#endif
        return SUCCESS;
	}

    EReturn CollisionAvoidance::setPreUpdateCallback(boost::function<void(CollisionAvoidance*, const Eigen::VectorXd &, int)> pre_update_callback)
    {
        pre_update_callback_ = pre_update_callback;
    }

	EReturn CollisionAvoidance::taskSpaceDim(int & task_dim)
	{
		task_dim = 1;
		return SUCCESS;
	}
	EReturn CollisionAvoidance::update(const Eigen::VectorXd & x, const int t)
	{
		invalidate();
        if (pre_update_callback_) pre_update_callback_(this, x, t);
		int M = scene_->getMapSize(object_name_), N = x.rows();
		if (M != effs_.size())
		{
			INDICATE_FAILURE
			return FAILURE;
		}
		Eigen::VectorXd eff_phi(3 * M);
		Eigen::MatrixXd eff_jac(3 * M, N);
		if (!ok(scene_->getForwardMap(object_name_, eff_phi))
				|| !ok(scene_->getJacobian(object_name_, eff_jac)))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		Eigen::VectorXd phi = Eigen::VectorXd::Zero(1);
		std::vector<double> dists(M);
		std::vector<double> costs(M);
		std::vector<Eigen::Vector3d> c1s(M), c2s(M);
		KDL::Frame tip_offset, cp_offset, eff_offset;
		std::vector<Eigen::Vector3d> norms(M);
#ifdef C_DEBUG
		close_.points.clear();
		centre_.points.clear();
#endif

        for (auto& objvec : scene_->getCollisionScene()->getFCLWorld())
        {
            for (boost::shared_ptr<fcl::CollisionObject> obj : objvec.second)
            {
                obj->setTransform(obs_in_base_tf_);
            }
        }

		for (int i = 0; i < M; i++)
		{
			Eigen::Vector3d tmp1, tmp2;
			scene_->getCollisionScene()->getRobotDistance(effs_[i], false, dists[i], tmp1, tmp2, norms[i], c1s[i], c2s[i]);
			//	Compute Phi
			if (dists[i] <= 0)
			{
#ifdef C_DEBUG
				ROS_ERROR_STREAM("Robot link " << effs_[i] << " is in collision");
#endif
				costs[i] = 1;
			}
			else if (dists[i] > safe_range_->data)
				costs[i] = 0;
			else
				costs[i] = (1.0 - dists[i] / safe_range_->data);
			phi(0) += costs[i] * costs[i];

			//	Modify end-effectors

			tip_offset = KDL::Frame(KDL::Vector(eff_phi(3 * i), eff_phi(3 * i + 1), eff_phi(3 * i
					+ 2)));
			cp_offset = KDL::Frame(KDL::Vector(tmp1(0), tmp1(1), tmp1(2)));
			eff_offset = tip_offset.Inverse() * cp_offset;
			if (!kin_sol_.modifyEndEffector(effs_[i], eff_offset))
			{
				INDICATE_FAILURE
				return FAILURE;
			}
#ifdef C_DEBUG
			geometry_msgs::Point p1, p2;
			if (dists[i] > 0)
			{
				eigen2Point(tmp1, p1);
				eigen2Point(tmp2, p2);
			}
			else
			{
				eigen2Point(c1s[i], p1);
				eigen2Point(c2s[i], p2);
			}
			close_.points.push_back(p1);
			close_.points.push_back(p2);
			eigen2Point(c1s[i], p1);
			eigen2Point(c2s[i], p2);
			centre_.points.push_back(p1);
			centre_.points.push_back(p2);
#endif
		}

#ifdef C_DEBUG
		close_pub_.publish(close_);
		centre_pub_.publish(centre_);
		ros::spinOnce();
#endif

		if (!kin_sol_.updateConfiguration(x) || !kin_sol_.generateForwardMap()
				|| !kin_sol_.generateJacobian(eff_jac))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		Eigen::MatrixXd jac = Eigen::MatrixXd::Zero(1, N);
		for (int i = 0; i < M; i++)
		{
			if (dists[i] <= 0)
			{
				Eigen::Vector3d tmpnorm = c2s[i] - c1s[i];
				tmpnorm.normalize();
				jac += ((2.0 * costs[i]) / safe_range_->data)
						* (tmpnorm.transpose() * eff_jac.block(3 * i, 0, 3, N));
			}
			else if (dists[i] <= safe_range_->data)
				jac += ((2.0 * costs[i]) / safe_range_->data)
						* (norms[i].transpose() * eff_jac.block(3 * i, 0, 3, N));
		}
		if (!ok(setPhi(phi, t)) || !ok(setJacobian(jac, t)))
		{
			INDICATE_FAILURE
			return FAILURE;
		}

		//	Reset the initial end-effectors

		//ROS_ERROR_STREAM("Jac="<<jac);
		return SUCCESS;
	}
}

<|endoftext|>


<commit_before>// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out

#include <assert.h>
#include <wchar.h>

#include <sanitizer/msan_interface.h>

int main() {
  const wchar_t *s = L"abc";
  assert(wcslen(s) == 3);

  wchar_t s2[5];
  assert(wcsncpy(s2, s, 3) == s2);
  assert(__msan_test_shadow(&s2, 5 * sizeof(wchar_t)) == 3 * sizeof(wchar_t));
  assert(wcsncpy(s2, s, 5) == s2);
  assert(__msan_test_shadow(&s2, 5 * sizeof(wchar_t)) == -1);

  wchar_t s3[5];
  assert(wcsncpy(s3, s, 2) == s3);
  assert(__msan_test_shadow(&s3, 5 * sizeof(wchar_t)) == 2 * sizeof(wchar_t));

  __msan_allocated_memory(&s2[1], sizeof(wchar_t));
  wchar_t s4[5];
  assert(wcsncpy(s4, s2, 3) == s4);
  __msan_check_mem_is_initialized(&s4, sizeof(s4));
}
// CHECK:  Uninitialized bytes in __msan_check_mem_is_initialized
// CHECK:  WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK:    in main {{.*}}wcsncpy.cc:26

// CHECK:  Uninitialized value was stored to memory at
// CHECK:    in {{[^\s]*}}wcsncpy
// CHECK:    in main {{.*}}wcsncpy.cc:25

// CHECK:  Memory was marked as uninitialized
// CHECK:    in __msan_allocated_memory
// CHECK:    in main {{.*}}wcsncpy.cc:23
<commit_msg>mips] XFAIL wcsncpy.cc test.<commit_after>// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out

// XFAIL: mips

#include <assert.h>
#include <wchar.h>

#include <sanitizer/msan_interface.h>

int main() {
  const wchar_t *s = L"abc";
  assert(wcslen(s) == 3);

  wchar_t s2[5];
  assert(wcsncpy(s2, s, 3) == s2);
  assert(__msan_test_shadow(&s2, 5 * sizeof(wchar_t)) == 3 * sizeof(wchar_t));
  assert(wcsncpy(s2, s, 5) == s2);
  assert(__msan_test_shadow(&s2, 5 * sizeof(wchar_t)) == -1);

  wchar_t s3[5];
  assert(wcsncpy(s3, s, 2) == s3);
  assert(__msan_test_shadow(&s3, 5 * sizeof(wchar_t)) == 2 * sizeof(wchar_t));

  __msan_allocated_memory(&s2[1], sizeof(wchar_t));
  wchar_t s4[5];
  assert(wcsncpy(s4, s2, 3) == s4);
  __msan_check_mem_is_initialized(&s4, sizeof(s4));
}
// CHECK:  Uninitialized bytes in __msan_check_mem_is_initialized
// CHECK:  WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK:    in main {{.*}}wcsncpy.cc:26

// CHECK:  Uninitialized value was stored to memory at
// CHECK:    in {{[^\s]*}}wcsncpy
// CHECK:    in main {{.*}}wcsncpy.cc:25

// CHECK:  Memory was marked as uninitialized
// CHECK:    in __msan_allocated_memory
// CHECK:    in main {{.*}}wcsncpy.cc:23
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "test/util.hpp"

//m.option("textds").templated<text_t, TextDS<>>();
//template<typename text_t>

/////////////////////////////////
#include <tudocomp/tudocomp.hpp>
class BWTComp : public Compressor {
  public: static Meta meta() {
    Meta m("compressor", "bwt");
    m.option("ds").templated<TextDS<>>();
    m.needs_sentinel_terminator();
    return m; }
  using Compressor::Compressor;
  void compress(Input& in, Output& out) {
    auto o = out.as_stream();
    auto i = in.as_view();
    TextDS<> t(env().env_for_option("ds"),i);
    const auto& sa = t.require_sa();
    for(size_t j = 0; j < t.size(); ++j)
      o << ((sa[j] != 0) ? t[sa[j] - 1]
                         : t[t.size() - 1]);
  }
  void decompress(Input&, Output&){/*[...]*/}
};
/////////////////////////////////
TEST(SEA17, Bwt) {
    auto i = test::compress_input("aaababaaabaababa");
    auto o = test::compress_output();
    auto c = tdc::builder<BWTComp>().instance();
    c.compress(i, o);
    ASSERT_EQ(o.result(), "abb\0ababbaaaaaaaa"_v);
}

/////////////////////////////////
template<class text_t>
class MaxHeapStrategy : public Algorithm {
 public: static Meta meta() {
  Meta m("lcpcomp_strategy", "heap");
  return m; }
 using Algorithm::Algorithm;
 void create_factor(size_t pos,size_t src,size_t len);
 void factorize(text_t& text, const size_t t) {
  text.require(text_t::SA | text_t::ISA | text_t::LCP);
  auto& sa = text.require_sa();
  auto& isa = text.require_isa();
  auto lcpp = text.release_lcp()->relinquish();
  auto& lcp = *lcpp;
  ArrayMaxHeap<typename text_t::lcp_type::data_type> heap(lcp, lcp.size(), lcp.size());
  for(size_t i = 1; i < lcp.size(); ++i)
   if(lcp[i] >= t) heap.insert(i);
  while(heap.size() > 0) {
   size_t i = heap.top(), fpos = sa[i],
       fsrc = sa[i-1], flen = heap.key(i);
   create_factor(fpos, fsrc, flen);
   for(size_t k=0; k < flen; k++)
    heap.remove(isa[fpos + k]);
   for(size_t k=0; k < flen && fpos > k; k++) {
    size_t s = fpos - k - 1;
    size_t j = isa[s];
    if(heap.contains(j)) {
     if(s + lcp[j] > fpos) {
      size_t l = fpos - s;
      if(l >= t)
       heap.decrease_key(j, l);
      else heap.remove(j);
}}}}}};
/////////////////////////////////
template<class T>
void MaxHeapStrategy<T>::create_factor(size_t pos, size_t src, size_t len){ /* [...] */ }

TEST(SEA17, MaxHeap) {
    auto text_ds = builder<TextDS<>>().instance("abc\0"_v);
    auto maxheap = builder<MaxHeapStrategy<TextDS<>>>().instance();
    maxheap.factorize(text_ds, 1);
}
/////////////////////////////////
void factorize(TextDS<>& T, SuffixTree& ST, std::function<void(size_t begin, size_t end, size_t ref)> output){
 typedef SuffixTree::node_type node_t;
 sdsl::int_vector<> R(ST.internal_nodes,0,bits_for(T.size() * bits_for(ST.cst.csa.sigma) / bits_for(T.size())));
 size_t pos = 0, z = 0;
 while(pos < T.size() - 1) {
  node_t l = ST.select_leaf(ST.cst.csa.isa[pos]);
  size_t leaflabel = pos;
  if(ST.parent(l) == ST.root || R[ST.nid(ST.parent(l))] != 0) {
   size_t parent_strdepth = ST.str_depth(ST.parent(l));
   output(pos + parent_strdepth, pos + parent_strdepth + 1, R[ST.nid(ST.parent(l))]);
   pos += parent_strdepth+1;
   ++z;
   continue;
  }
  size_t d = 1;
  node_t parent = ST.root;
  node_t node = ST.level_anc(l, d);
  while(R[ST.nid(node)] != 0) {
   parent = node;
   node = ST.level_anc(l, ++d);
  }
  pos += ST.str_depth(parent);
  size_t begin = leaflabel + ST.str_depth(parent);
  size_t end = leaflabel + ST.str_depth(node);
  output(begin, end, R[ST.nid(ST.parent(node))]);
  R[ST.nid(node)] = ++z;
  pos += end - begin;
 }
}
/////////////////////////////////
TEST(SEA17, factorize) {
    auto T = "aaababaaabaababa\0"_v;
    auto text_ds = builder<TextDS<>>().instance(T);
    std::vector<size_t> v;
    auto f = [&](size_t begin, size_t end, size_t ref) {
        v.push_back(begin);
        v.push_back(end);
        v.push_back(ref);
    };
    SuffixTree::cst_t backing_cst;
    {
        std::string bad_copy_1 = T.slice(0, T.size() - 1);
        construct_im(backing_cst, bad_copy_1, 1);
    }
    SuffixTree ST(backing_cst);

    factorize(text_ds, ST,f);

    ASSERT_EQ(v, (std::vector<size_t> {
        0,   1,   0,
        2,   3,   1,
        3,   5,   0,
        7,   8,   3,
        9,  11,   1,
        14, 16,   5,
        // 16, 17,   0,
    }));
}
<commit_msg>make code fit latex rendering better<commit_after>#include "gtest/gtest.h"
#include "test/util.hpp"

//m.option("textds").templated<text_t, TextDS<>>();
//template<typename text_t>

/////////////////////////////////
#include <tudocomp/tudocomp.hpp>
class BWTComp : public Compressor {
  public: static Meta meta() {
    Meta m("compressor", "bwt");
    m.option("ds").templated<TextDS<>>();
    m.needs_sentinel_terminator();
    return m; }
  using Compressor::Compressor;
  void compress(Input& in, Output& out) {
    auto o = out.as_stream();
    auto i = in.as_view();
    TextDS<> t(env().env_for_option("ds"),i);
    const auto& sa = t.require_sa();
    for(size_t j = 0; j < t.size(); ++j)
      o << ((sa[j] != 0) ? t[sa[j] - 1]
                         : t[t.size() - 1]);
  }
  void decompress(Input&, Output&){/*[...]*/}
};
/////////////////////////////////
TEST(SEA17, Bwt) {
    auto i = test::compress_input("aaababaaabaababa");
    auto o = test::compress_output();
    auto c = tdc::builder<BWTComp>().instance();
    c.compress(i, o);
    ASSERT_EQ(o.result(), "abb\0ababbaaaaaaaa"_v);
}

/////////////////////////////////
template<class text_t>
class MaxHeapStrategy : public Algorithm {
 public: static Meta meta() {
  Meta m("lcpcomp_strategy", "heap");
  return m; }
 using Algorithm::Algorithm;
 void create_factor(size_t pos, size_t src, size_t len);
 void factorize(text_t& text, size_t t) {
  text.require(text_t::SA | text_t::ISA | text_t::LCP);
  auto& sa = text.require_sa();
  auto& isa = text.require_isa();
  auto lcpp = text.release_lcp()->relinquish();
  auto& lcp = *lcpp;
  ArrayMaxHeap<typename text_t::lcp_type::data_type> heap(lcp, lcp.size(), lcp.size());
  for(size_t i = 1; i < lcp.size(); ++i)
   if(lcp[i] >= t) heap.insert(i);
  while(heap.size() > 0) {
   size_t i = heap.top(), fpos = sa[i],
       fsrc = sa[i-1], flen = heap.key(i);
   create_factor(fpos, fsrc, flen);
   for(size_t k=0; k < flen; k++)
    heap.remove(isa[fpos + k]);
   for(size_t k=0;k < flen && fpos > k;k++) {
    size_t s = fpos - k - 1;
    size_t j = isa[s];
    if(heap.contains(j)) {
     if(s + lcp[j] > fpos) {
      size_t l = fpos - s;
      if(l >= t)
       heap.decrease_key(j, l);
      else heap.remove(j);
}}}}}};
/////////////////////////////////
template<class T>
void MaxHeapStrategy<T>::create_factor(size_t pos, size_t src, size_t len){ /* [...] */ }

TEST(SEA17, MaxHeap) {
    auto text_ds = builder<TextDS<>>().instance("abc\0"_v);
    auto maxheap = builder<MaxHeapStrategy<TextDS<>>>().instance();
    maxheap.factorize(text_ds, 1);
}
/////////////////////////////////
void factorize(TextDS<>& T, SuffixTree& ST, std::function<void(size_t begin, size_t end, size_t ref)> output){
 typedef SuffixTree::node_type node_t;
 sdsl::int_vector<> R(ST.internal_nodes,0,bits_for(T.size() * bits_for(ST.cst.csa.sigma) / bits_for(T.size())));
 size_t pos = 0, z = 0;
 while(pos < T.size() - 1) {
  node_t l = ST.select_leaf(ST.cst.csa.isa[pos]);
  size_t leaflabel = pos;
  if(ST.parent(l) == ST.root || R[ST.nid(ST.parent(l))] != 0) {
   size_t parent_strdepth = ST.str_depth(ST.parent(l));
   output(pos + parent_strdepth, pos + parent_strdepth + 1, R[ST.nid(ST.parent(l))]);
   pos += parent_strdepth+1;
   ++z;
   continue;
  }
  size_t d = 1;
  node_t parent = ST.root;
  node_t node = ST.level_anc(l, d);
  while(R[ST.nid(node)] != 0) {
   parent = node;
   node = ST.level_anc(l, ++d);
  }
  pos += ST.str_depth(parent);
  size_t begin = leaflabel + ST.str_depth(parent);
  size_t end = leaflabel + ST.str_depth(node);
  output(begin, end, R[ST.nid(ST.parent(node))]);
  R[ST.nid(node)] = ++z;
  pos += end - begin;
 }
}
/////////////////////////////////
TEST(SEA17, factorize) {
    auto T = "aaababaaabaababa\0"_v;
    auto text_ds = builder<TextDS<>>().instance(T);
    std::vector<size_t> v;
    auto f = [&](size_t begin, size_t end, size_t ref) {
        v.push_back(begin);
        v.push_back(end);
        v.push_back(ref);
    };
    SuffixTree::cst_t backing_cst;
    {
        std::string bad_copy_1 = T.slice(0, T.size() - 1);
        construct_im(backing_cst, bad_copy_1, 1);
    }
    SuffixTree ST(backing_cst);

    factorize(text_ds, ST,f);

    ASSERT_EQ(v, (std::vector<size_t> {
        0,   1,   0,
        2,   3,   1,
        3,   5,   0,
        7,   8,   3,
        9,  11,   1,
        14, 16,   5,
        // 16, 17,   0,
    }));
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 <Python.h>
#include <fstream>
#include <vector>

#include "paddle/framework/backward.h"
#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/op_registry.h"
#include "paddle/operators/cond_op.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
#include "paddle/platform/enforce.h"
#include "paddle/platform/place.h"
#include "paddle/pybind/pybind.h"
#include "paddle/pybind/tensor_py.h"
#include "paddle/string/to_string.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"

namespace py = pybind11;

namespace paddle {
namespace framework {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

static size_t UniqueIntegerGenerator() {
  static std::atomic<size_t> generator;
  return generator.fetch_add(1);
}

bool IsCompileGPU() {
#ifdef PADDLE_ONLY_CPU
  return false;
#else
  return true;
#endif
}

PYBIND11_PLUGIN(core) {
  py::module m("core", "C++ core of PaddlePaddle");

  py::class_<Tensor>(m, "Tensor", py::buffer_protocol())
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def("get_dims",
           [](const Tensor &self) { return vectorize(self.dims()); })
      .def("set_dims",
           [](Tensor &self, const std::vector<int64_t> &dim) {
             self.Resize(make_ddim(dim));
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("set", PyCPUTensorSetFromArray<float>)
      .def("set", PyCPUTensorSetFromArray<int>)
#ifndef PADDLE_ONLY_CPU
      .def("set", PyCUDATensorSetFromArray<float>)
      .def("set", PyCUDATensorSetFromArray<int>)
#endif
      .def("shape", [](Tensor &self) { return vectorize(self.dims()); })
      .def("set_float_element",
           [](Tensor &self, size_t offset, float f) {
             // TODO(yuyang18): Only support GPU now.
             self.data<float>()[offset] = f;
           })
      .def("get_float_element", [](Tensor &self, size_t offset) -> float {
        // TODO(yuyang18): Only support GPU now.
        return self.data<float>()[offset];
      });

  py::class_<LoDTensor, Tensor>(m, "LoDTensor")
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def(
          "__init__",
          [](LoDTensor &instance, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
            new (&instance) LoDTensor(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             new (&instance) LoDTensor(new_lod);
#endif
          })
      .def("set_lod",
           [](LoDTensor &self, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
             self.set_lod(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             self.set_lod(new_lod);
#endif
           })
      .def("lod", [](LoDTensor &self) -> std::vector<std::vector<size_t>> {
#ifdef PADDLE_ONLY_CPU
        return self.lod();
#else
           auto lod = self.lod();
           std::vector<std::vector<size_t>> new_lod;
           new_lod.reserve(lod.size());
           std::transform(lod.begin(), lod.end(), std::back_inserter(new_lod),
               [](paddle::framework::Vector<size_t> item) ->
                   std::vector<size_t> {
                 std::vector<size_t> v;
                 v.reserve(item.size());
                 std::copy(item.begin(), item.end(), std::back_inserter(v));
                 return v;
               });
           return new_lod;
#endif
      });

  py::class_<Variable>(m, "Variable", R"DOC(Variable Class.

All parameter, weight, gradient are variables in Paddle.
)DOC")
      .def("is_int", [](const Variable &var) { return var.IsType<int>(); })
      .def("set_int",
           [](Variable &var, int val) -> void { *var.GetMutable<int>() = val; })
      .def("get_int", [](const Variable &var) -> int { return var.Get<int>(); })
      .def("get_tensor",
           [](Variable &self) -> LoDTensor * {
             return self.GetMutable<LoDTensor>();
           },
           py::return_value_policy::reference)
      .def("get_net",
           [](Variable &self) -> operators::NetOp * {
             return self.GetMutable<operators::NetOp>();
           },
           py::return_value_policy::reference);

  py::class_<Scope>(m, "Scope", "")
      .def("new_var",
           [](Scope &self, const std::string &name) -> Variable * {
             return self.NewVar(name);
           },
           py::return_value_policy::reference)
      .def("find_var", &Scope::FindVar, py::return_value_policy::reference)
      .def(py::init<>())
      .def("new_scope",
           [](Scope &self) -> Scope * { return &self.NewScope(); },
           py::return_value_policy::reference)
      .def("drop_kids", &Scope::DropKids);

  //! @note: Be careful! PyBind will return std::string as an unicode, not
  //! Python str. If you want a str object, you should cast them in Python.
  m.def("get_all_op_protos", []() -> std::vector<py::bytes> {
    std::vector<py::bytes> ret_values;

    OpInfoMap::Instance().IterAllInfo([&ret_values](const std::string &type,
                                                    const OpInfo &info) {
      if (!info.HasOpProtoAndChecker()) return;
      std::string str;
      PADDLE_ENFORCE(info.Proto().SerializeToString(&str),
                     "Serialize OpProto Error. This could be a bug of Paddle.");
      ret_values.emplace_back(str);
    });
    return ret_values;
  });
  m.def_submodule(
       "var_names",
       "The module will return special predefined variable name in Paddle")
      .def("empty", []() { return kEmptyVarName; })
      .def("temp", []() { return kTempVarName; });
  // clang-format off
  py::class_<paddle::platform::DeviceContext>(m, "DeviceContext")
      .def_static("create",
                  [](paddle::platform::CPUPlace& place)
                      -> paddle::platform::DeviceContext* {
                    return new paddle::platform::CPUDeviceContext();
                  })
      .def_static("create",
                  [](paddle::platform::GPUPlace& place)
                      -> paddle::platform::DeviceContext* {
#ifdef PADDLE_ONLY_CPU
                    PADDLE_THROW("GPUPlace is not supported in CPU device.");
#else
                    return new paddle::platform::CUDADeviceContext(place);
#endif
                  });
  // clang-format on

  py::class_<platform::GPUPlace>(m, "GPUPlace")
      .def(py::init<int>())
      .def("__str__", string::to_string<const platform::GPUPlace &>);

  py::class_<paddle::platform::CPUPlace>(m, "CPUPlace")
      .def(py::init<>())
      .def("__str__", string::to_string<const platform::CPUPlace &>);

  py::class_<OperatorBase>(m, "Operator")
      .def_static("create",
                  [](py::bytes protobin) {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    return OpRegistry::CreateOp(desc);
                  })
      .def("backward",
           [](const OperatorBase &forwardOp,
              const std::unordered_set<std::string> &no_grad_vars) {
             return Backward(forwardOp, no_grad_vars).release();
           })
      .def("infer_shape", &OperatorBase::InferShape)
      .def("run", &OperatorBase::Run)
      .def("type",
           [](const OperatorBase &op) -> std::string { return op.Type(); })
      .def("outputs",
           [](const OperatorBase &op)
               -> std::map<std::string, std::vector<std::string>> {
                 return op.Outputs();
               })
      .def("output_vars",
           [](const OperatorBase &op) { return op.OutputVars(true); })
      .def("inputs", [](const OperatorBase &op) { return op.Inputs(); })
      .def("input_vars", [](const OperatorBase &op) { return op.InputVars(); })
      .def("__str__", &OperatorBase::DebugString)
      .def("no_intermediate_outputs",
           [](const OperatorBase &op) { return op.OutputVars(false); })
      .def("support_gpu", &OperatorBase::SupportGPU);

  py::class_<operators::NetOp, OperatorBase>(m, "Net")
      .def_static("create",
                  []() -> operators::NetOp * {
                    auto *retv = new operators::NetOp;
                    retv->SetType("plain_net");
                    return retv;
                  })
      .def("append_op",
           [](operators::NetOp &self, const OperatorBase &op) {
             self.AppendOp(op);
           })
      .def("complete_add_op", &operators::NetOp::CompleteAddOp)
      .def("complete_add_op", [](std::shared_ptr<operators::NetOp> &self) {
        self->CompleteAddOp();
      });

  // recurrent_op
  py::class_<operators::RecurrentOp, OperatorBase>(m, "RecurrentOp")
      .def_static(
          "create",
          [](py::bytes protobin) -> operators::RecurrentOp * {
            OpDesc desc;
            PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                           "Cannot parse user input to OpDesc");
            PADDLE_ENFORCE(desc.IsInitialized(),
                           "User OpDesc is not initialized, reason %s",
                           desc.InitializationErrorString());
            auto rnn_op = OpRegistry::CreateOp(desc);
            return static_cast<operators::RecurrentOp *>(rnn_op.release());
          })
      .def("set_stepnet",
           [](operators::RecurrentOp &self, const operators::NetOp &net)
               -> void { self.set_stepnet(net.Clone()); });

  // cond_op
  py::class_<operators::CondOp, OperatorBase>(m, "CondOp")
      .def_static("create",
                  [](py::bytes protobin) -> operators::CondOp * {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    auto cond_op = OpRegistry::CreateOp(desc);
                    return static_cast<operators::CondOp *>(cond_op.release());
                  })
      .def("set_truenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_truenet(net.Clone());
           })
      .def("set_falsenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_falsenet(net.Clone());
           });

  m.def("unique_integer", UniqueIntegerGenerator);

  m.def("is_compile_gpu", IsCompileGPU);

  return m.ptr();
}
}  // namespace framework
}  // namespace paddle
<commit_msg>Init commit<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 <Python.h>
#include <fstream>
#include <vector>

#include "paddle/framework/backward.h"
#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/op_registry.h"
#include "paddle/operators/cond_op.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
#include "paddle/platform/enforce.h"
#include "paddle/platform/place.h"
#include "paddle/pybind/pybind.h"
#include "paddle/pybind/tensor_py.h"
#include "paddle/string/to_string.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"

namespace py = pybind11;

namespace paddle {
namespace framework {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

static size_t UniqueIntegerGenerator() {
  static std::atomic<size_t> generator;
  return generator.fetch_add(1);
}

bool IsCompileGPU() {
#ifdef PADDLE_ONLY_CPU
  return false;
#else
  return true;
#endif
}

PYBIND11_PLUGIN(core) {
  py::module m("core", "C++ core of PaddlePaddle");

  py::class_<Tensor>(m, "Tensor", py::buffer_protocol())
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def("get_dims",
           [](const Tensor &self) { return vectorize(self.dims()); })
      .def("set_dims",
           [](Tensor &self, const std::vector<int64_t> &dim) {
             self.Resize(make_ddim(dim));
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("set", PyCPUTensorSetFromArray<float>)
      .def("set", PyCPUTensorSetFromArray<int>)
#ifndef PADDLE_ONLY_CPU
      .def("set", PyCUDATensorSetFromArray<float>)
      .def("set", PyCUDATensorSetFromArray<int>)
#endif
      .def("shape", [](Tensor &self) { return vectorize(self.dims()); })
      .def("set_float_element",
           [](Tensor &self, size_t offset, float f) {
             // TODO(yuyang18): Only support GPU now.
             self.data<float>()[offset] = f;
           })
      .def("get_float_element", [](Tensor &self, size_t offset) -> float {
        // TODO(yuyang18): Only support GPU now.
        return self.data<float>()[offset];
      });

  py::class_<LoDTensor, Tensor>(m, "LoDTensor")
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def(
          "__init__",
          [](LoDTensor &instance, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
            new (&instance) LoDTensor(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             new (&instance) LoDTensor(new_lod);
#endif
          })
      .def("set_lod",
           [](LoDTensor &self, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
             self.set_lod(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             self.set_lod(new_lod);
#endif
           })
      .def("lod", [](LoDTensor &self) -> std::vector<std::vector<size_t>> {
#ifdef PADDLE_ONLY_CPU
        return self.lod();
#else
           auto lod = self.lod();
           std::vector<std::vector<size_t>> new_lod;
           new_lod.reserve(lod.size());
           std::transform(lod.begin(), lod.end(), std::back_inserter(new_lod),
               [](paddle::framework::Vector<size_t> item) ->
                   std::vector<size_t> {
                 std::vector<size_t> v;
                 v.reserve(item.size());
                 std::copy(item.begin(), item.end(), std::back_inserter(v));
                 return v;
               });
           return new_lod;
#endif
      });

  py::class_<Variable>(m, "Variable", R"DOC(Variable Class.

All parameter, weight, gradient are variables in Paddle.
)DOC")
      .def("is_int", [](const Variable &var) { return var.IsType<int>(); })
      .def("set_int",
           [](Variable &var, int val) -> void { *var.GetMutable<int>() = val; })
      .def("get_int", [](const Variable &var) -> int { return var.Get<int>(); })
      .def("get_tensor",
           [](Variable &self) -> LoDTensor * {
             return self.GetMutable<LoDTensor>();
           },
           py::return_value_policy::reference)
      .def("get_net",
           [](Variable &self) -> operators::NetOp * {
             return self.GetMutable<operators::NetOp>();
           },
           py::return_value_policy::reference);

  py::class_<Scope>(m, "Scope", "")
      .def("new_var",
           [](Scope &self, const std::string &name) -> Variable * {
             return self.NewVar(name);
           },
           py::return_value_policy::reference)
      .def("find_var", &Scope::FindVar, py::return_value_policy::reference)
      .def(py::init<>())
      .def("new_scope",
           [](Scope &self) -> Scope * { return &self.NewScope(); },
           py::return_value_policy::reference)
      .def("drop_kids", &Scope::DropKids);

  //! @note: Be careful! PyBind will return std::string as an unicode, not
  //! Python str. If you want a str object, you should cast them in Python.
  m.def("get_all_op_protos", []() -> std::vector<py::bytes> {
    std::vector<py::bytes> ret_values;

    OpInfoMap::Instance().IterAllInfo([&ret_values](const std::string &type,
                                                    const OpInfo &info) {
      if (!info.HasOpProtoAndChecker()) return;
      std::string str;
      PADDLE_ENFORCE(info.Proto().SerializeToString(&str),
                     "Serialize OpProto Error. This could be a bug of Paddle.");
      ret_values.emplace_back(str);
    });
    return ret_values;
  });
  m.def_submodule(
       "var_names",
       "The module will return special predefined variable name in Paddle")
      .def("empty", []() { return kEmptyVarName; })
      .def("temp", []() { return kTempVarName; });
  // clang-format off
  py::class_<paddle::platform::DeviceContext>(m, "DeviceContext")
      .def_static("create",
                  [](paddle::platform::CPUPlace& place)
                      -> paddle::platform::DeviceContext* {
                    return new paddle::platform::CPUDeviceContext();
                  })
      .def_static("create",
                  [](paddle::platform::GPUPlace& place)
                      -> paddle::platform::DeviceContext* {
#ifdef PADDLE_ONLY_CPU
                    PADDLE_THROW("GPUPlace is not supported in CPU device.");
#else
                    return new paddle::platform::CUDADeviceContext(place);
#endif
                  });
  // clang-format on

  py::class_<platform::GPUPlace>(m, "GPUPlace")
      .def(py::init<int>())
      .def("__str__", string::to_string<const platform::GPUPlace &>);

  py::class_<paddle::platform::CPUPlace>(m, "CPUPlace")
      .def(py::init<>())
      .def("__str__", string::to_string<const platform::CPUPlace &>);

  py::class_<OperatorBase>(m, "Operator")
      .def_static("create",
                  [](py::bytes protobin) {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    return OpRegistry::CreateOp(desc);
                  })
      .def("backward",
           [](const OperatorBase &forwardOp,
              const std::unordered_set<std::string> &no_grad_vars) {
             return Backward(forwardOp, no_grad_vars).release();
           })
      .def("infer_shape", &OperatorBase::InferShape)
      .def("run", &OperatorBase::Run)
      .def("type",
           [](const OperatorBase &op) -> std::string { return op.Type(); })
      .def("outputs",
           [](const OperatorBase &op)
               -> std::map<std::string, std::vector<std::string>> {
                 return op.Outputs();
               })
      .def("output_vars",
           [](const OperatorBase &op) { return op.OutputVars(true); })
      .def("inputs", [](const OperatorBase &op) { return op.Inputs(); })
      .def("input_vars", [](const OperatorBase &op) { return op.InputVars(); })
      .def("__str__", &OperatorBase::DebugString)
      .def("no_intermediate_outputs",
           [](const OperatorBase &op) { return op.OutputVars(false); })
      .def("support_gpu", &OperatorBase::SupportGPU);

  py::class_<operators::NetOp, OperatorBase>(m, "Net")
      .def_static("create",
                  []() -> operators::NetOp * {
                    auto *retv = new operators::NetOp;
                    retv->SetType("plain_net");
                    return retv;
                  })
      .def("append_op",
           [](operators::NetOp &self, const OperatorBase &op) {
             self.AppendOp(op);
           })
      .def("complete_add_op", &operators::NetOp::CompleteAddOp)
      .def("complete_add_op", [](std::shared_ptr<operators::NetOp> &self) {
        self->CompleteAddOp();
      });

  // recurrent_op
  py::class_<operators::RecurrentOp, OperatorBase>(m, "RecurrentOp")
      .def_static(
          "create",
          [](py::bytes protobin) -> operators::RecurrentOp * {
            OpDesc desc;
            PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                           "Cannot parse user input to OpDesc");
            PADDLE_ENFORCE(desc.IsInitialized(),
                           "User OpDesc is not initialized, reason %s",
                           desc.InitializationErrorString());
            auto rnn_op = OpRegistry::CreateOp(desc);
            return static_cast<operators::RecurrentOp *>(rnn_op.release());
          })
      .def("set_stepnet",
           [](operators::RecurrentOp &self, const operators::NetOp &net)
               -> void { self.set_stepnet(net.Clone()); });

  // cond_op
  py::class_<operators::CondOp, OperatorBase>(m, "CondOp")
      .def_static("create",
                  [](py::bytes protobin) -> operators::CondOp * {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    auto cond_op = OpRegistry::CreateOp(desc);
                    return static_cast<operators::CondOp *>(cond_op.release());
                  })
      .def("set_truenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_truenet(net.Clone());
           })
      .def("set_falsenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_falsenet(net.Clone());
           });

  m.def("unique_integer", UniqueIntegerGenerator);

  m.def("is_compile_gpu", IsCompileGPU);

  py::class_<ProgramDesc>(m, "ProgramDesc", "")
      .def_static("instance", [] { return &GetProgramDesc(); })
      .def("append_block", [](ProgramDesc &self) {
        auto desc = self.mutable_blocks()->Add();
        desc->set_idx(self.mutable_blocks()->size() - 1);
        return desc;
      });
  py::class_<BlockDesc>(m, "BlockDesc", "")
      .def("idx", [](BlockDesc &self) { return self.idx(); })
      .def("set_parent",
           [](BlockDesc &self, int32_t idx) { self.set_parent_idx(idx); })
      .def("parent", [](BlockDesc &self) { return self.parent_idx(); });

  py::class_<VarDesc>(m, "VarDesc", "");

  py::class_<OpDesc>(m, "OpDesc", "");

  return m.ptr();
}
}  // namespace framework
}  // namespace paddle
<|endoftext|>


<commit_before>#include "touchSupportManager.h"

#include <QtWidgets/QPinchGesture>
#include <QtWidgets/QApplication>

#include "view/editorView.h"

using namespace qReal::view::details;

TouchSupportManager::TouchSupportManager(EditorView *editorView)
	: mEditorView(editorView)
	, mGestureIsRunning(false)
{
	mEditorView->grabGesture(Qt::TapGesture);
	mEditorView->grabGesture(Qt::PanGesture);
	mEditorView->grabGesture(Qt::PinchGesture);
	mEditorView->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);

	mEditorView->installEventFilter(this);
	mEditorView->viewport()->installEventFilter(this);

	mScroller.enableKineticScrollFor(mEditorView);
}

bool TouchSupportManager::isGestureRunning() const
{
	return mGestureIsRunning;
}

bool TouchSupportManager::eventFilter(QObject *object, QEvent *event)
{
	QEvent::Type const eventType = event->type();
	bool const isMouseAction = QEvent::MouseButtonPress == eventType || QEvent::MouseButtonRelease == eventType;
	bool const isMouseEvent = isMouseAction || QEvent::MouseMove == eventType;

	if (!isMouseEvent && event->type() != QEvent::Gesture) {
		return false;
	}

	if (isMouseAction && mScroller.shouldIgnoreMouseAction()) { // don't filter simulated click
		return false;
	}

	QMouseEvent * const mouseEvent = static_cast<QMouseEvent *>(event);

	switch (eventType) {
		case QEvent::Gesture:
			return handleGesture(static_cast<QGestureEvent *>(event));
		case QEvent::MouseButtonPress:
			mScroller.onMousePress(mouseEvent);
			break;
		case QEvent::MouseMove:
			mScroller.onMouseMove(mouseEvent);
			break;
		case QEvent::MouseButtonRelease:
			mScroller.onMouseRelease(object, mouseEvent);
			break;
		// For some reason touch events can`t be processed here and must be
		// processed in scroll area`s viewport event
		default:
			break;
	}

	return false;
}

void TouchSupportManager::simulateMouse(QObject *reciever, QEvent::Type event, QPointF const &pos
		, Qt::MouseButtons buttons)
{
	QMouseEvent *mouseEvent = new QMouseEvent(event, pos, mButton, buttons, Qt::NoModifier);
	QApplication::postEvent(reciever, mouseEvent);
}

void TouchSupportManager::simulatePress(QTouchEvent *event, Qt::MouseButton button)
{
	mButton = button;
	simulateMouse(event->target(), QEvent::MouseButtonPress, event->touchPoints()[0].pos(), mButton);
}

void TouchSupportManager::simulateMove(QTouchEvent *event)
{
	simulateMouse(event->target(), QEvent::MouseMove, event->touchPoints()[0].pos(), mButton);
}

void TouchSupportManager::simulateRelease(QTouchEvent *event)
{
	simulateMouse(event->target(), QEvent::MouseButtonRelease, event->touchPoints()[0].pos(), Qt::NoButton);
}

void TouchSupportManager::simulateDoubleClick(QTouchEvent *event)
{
	mButton = Qt::LeftButton;
	simulateMouse(event->target(), QEvent::MouseButtonDblClick, event->touchPoints()[0].pos(), mButton);
}

bool TouchSupportManager::isElementUnder(QPointF const &pos)
{
	return mEditorView->itemAt(pos.toPoint());
}

bool TouchSupportManager::handleGesture(QGestureEvent *gestureEvent)
{
	if (gestureEvent->gesture(Qt::TapGesture)) {
		mScroller.onTap();
	} else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) {
		processGestureState(pan);
		mScroller.onPan(pan);
	} else if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) {
		processGestureState(pinch);
		QPinchGesture *pinchGesture = static_cast<QPinchGesture *>(pinch);
		mEditorView->zoom(pinchGesture->scaleFactor());
	}
	return true;
}

void TouchSupportManager::processGestureState(QGesture *gesture)
{
	if (gesture->state() == Qt::GestureStarted) {
		emit gestureStarted();
	} else if (gesture->state() == Qt::GestureFinished) {
		emit gestureFinished();
	}
}

bool TouchSupportManager::processTouchEvent(QTouchEvent *event)
{
	event->accept();
	mGestureIsRunning = event->type() != QEvent::TouchEnd;
	mEditorView->setDragMode(QGraphicsView::NoDrag);
	mFingersInGesture = event->touchPoints().count();
	if (mFingersInGesture == 1) {
		handleOneFingerTouch(event);
	}
	return true;
}

void TouchSupportManager::handleOneFingerTouch(QTouchEvent *event)
{
	switch(event->type()) {
	case QEvent::TouchBegin: {
		mEditorView->scene()->clearSelection();
		bool const elementUnder = isElementUnder(event->touchPoints()[0].pos());

		if (QDateTime::currentMSecsSinceEpoch() - mLastTapTimestamp <= QApplication::doubleClickInterval()) {
			if (elementUnder) {
				// Simulating regular left button click
				simulatePress(event);
			} else {
				// Simulating double-click
				simulateDoubleClick(event);
			}
		} else {
			if (elementUnder) {
				// Simulating right button click for links gesture
				simulatePress(event, Qt::RightButton);
			} else {
				// Simulating right button click for mouse gestures drawing or left button click
				// for clearing selection
				simulatePress(event, mEditorView->scene()->selectedItems().isEmpty()
						? Qt::RightButton : Qt::LeftButton);
			}
		}

		mEditorView->scene()->update();
		mLastTapTimestamp = QDateTime::currentMSecsSinceEpoch();
		break;
	}
	case QEvent::TouchEnd:
		// This will not show context menu when we just tap on scene
		if (mButton == Qt::RightButton) {
			simulateMove(event);
		}

		simulateRelease(event);
		mEditorView->scene()->update();
		break;
	case QEvent::TouchUpdate:
		simulateMove(event);
		break;
	default:
		break;
	}
}
<commit_msg>Added double-click edit triggering on titles in touch mdoe<commit_after>#include "touchSupportManager.h"

#include <QtWidgets/QPinchGesture>
#include <QtWidgets/QApplication>

#include "view/editorView.h"

using namespace qReal::view::details;

TouchSupportManager::TouchSupportManager(EditorView *editorView)
	: mEditorView(editorView)
	, mGestureIsRunning(false)
{
	mEditorView->grabGesture(Qt::TapGesture);
	mEditorView->grabGesture(Qt::PanGesture);
	mEditorView->grabGesture(Qt::PinchGesture);
	mEditorView->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);

	mEditorView->installEventFilter(this);
	mEditorView->viewport()->installEventFilter(this);

	mScroller.enableKineticScrollFor(mEditorView);
}

bool TouchSupportManager::isGestureRunning() const
{
	return mGestureIsRunning;
}

bool TouchSupportManager::eventFilter(QObject *object, QEvent *event)
{
	QEvent::Type const eventType = event->type();
	bool const isMouseAction = QEvent::MouseButtonPress == eventType || QEvent::MouseButtonRelease == eventType;
	bool const isMouseEvent = isMouseAction || QEvent::MouseMove == eventType;

	if (!isMouseEvent && event->type() != QEvent::Gesture) {
		return false;
	}

	if (isMouseAction && mScroller.shouldIgnoreMouseAction()) { // don't filter simulated click
		return false;
	}

	QMouseEvent * const mouseEvent = static_cast<QMouseEvent *>(event);

	switch (eventType) {
		case QEvent::Gesture:
			return handleGesture(static_cast<QGestureEvent *>(event));
		case QEvent::MouseButtonPress:
			mScroller.onMousePress(mouseEvent);
			break;
		case QEvent::MouseMove:
			mScroller.onMouseMove(mouseEvent);
			break;
		case QEvent::MouseButtonRelease:
			mScroller.onMouseRelease(object, mouseEvent);
			break;
		// For some reason touch events can`t be processed here and must be
		// processed in scroll area`s viewport event
		default:
			break;
	}

	return false;
}

void TouchSupportManager::simulateMouse(QObject *reciever, QEvent::Type event, QPointF const &pos
		, Qt::MouseButtons buttons)
{
	QMouseEvent *mouseEvent = new QMouseEvent(event, pos, mButton, buttons, Qt::NoModifier);
	QApplication::postEvent(reciever, mouseEvent);
}

void TouchSupportManager::simulatePress(QTouchEvent *event, Qt::MouseButton button)
{
	mButton = button;
	simulateMouse(event->target(), QEvent::MouseButtonPress, event->touchPoints()[0].pos(), mButton);
}

void TouchSupportManager::simulateMove(QTouchEvent *event)
{
	simulateMouse(event->target(), QEvent::MouseMove, event->touchPoints()[0].pos(), mButton);
}

void TouchSupportManager::simulateRelease(QTouchEvent *event)
{
	simulateMouse(event->target(), QEvent::MouseButtonRelease, event->touchPoints()[0].pos(), Qt::NoButton);
}

void TouchSupportManager::simulateDoubleClick(QTouchEvent *event)
{
	mButton = Qt::LeftButton;
	simulateMouse(event->target(), QEvent::MouseButtonDblClick, event->touchPoints()[0].pos(), mButton);
}

bool TouchSupportManager::isElementUnder(QPointF const &pos)
{
	return dynamic_cast<Element *>(mEditorView->itemAt(pos.toPoint()));
}

bool TouchSupportManager::handleGesture(QGestureEvent *gestureEvent)
{
	if (gestureEvent->gesture(Qt::TapGesture)) {
		mScroller.onTap();
	} else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) {
		processGestureState(pan);
		mScroller.onPan(pan);
	} else if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) {
		processGestureState(pinch);
		QPinchGesture *pinchGesture = static_cast<QPinchGesture *>(pinch);
		mEditorView->zoom(pinchGesture->scaleFactor());
	}
	return true;
}

void TouchSupportManager::processGestureState(QGesture *gesture)
{
	if (gesture->state() == Qt::GestureStarted) {
		emit gestureStarted();
	} else if (gesture->state() == Qt::GestureFinished) {
		emit gestureFinished();
	}
}

bool TouchSupportManager::processTouchEvent(QTouchEvent *event)
{
	event->accept();
	mGestureIsRunning = event->type() != QEvent::TouchEnd;
	mEditorView->setDragMode(QGraphicsView::NoDrag);
	mFingersInGesture = event->touchPoints().count();
	if (mFingersInGesture == 1) {
		handleOneFingerTouch(event);
	}
	return true;
}

void TouchSupportManager::handleOneFingerTouch(QTouchEvent *event)
{
	switch(event->type()) {
	case QEvent::TouchBegin: {
		mEditorView->scene()->clearSelection();
		bool const elementUnder = isElementUnder(event->touchPoints()[0].pos());

		if (QDateTime::currentMSecsSinceEpoch() - mLastTapTimestamp <= QApplication::doubleClickInterval()) {
			if (elementUnder) {
				// Simulating regular left button click
				simulatePress(event);
			} else {
				// Simulating double-click
				simulateDoubleClick(event);
			}
		} else {
			if (elementUnder) {
				// Simulating right button click for links gesture
				simulatePress(event, Qt::RightButton);
			} else {
				// Simulating right button click for mouse gestures drawing or left button click
				// for clearing selection
				simulatePress(event, mEditorView->scene()->selectedItems().isEmpty()
						? Qt::RightButton : Qt::LeftButton);
			}
		}

		mEditorView->scene()->update();
		mLastTapTimestamp = QDateTime::currentMSecsSinceEpoch();
		break;
	}
	case QEvent::TouchEnd:
		// This will not show context menu when we just tap on scene
		if (mButton == Qt::RightButton) {
			simulateMove(event);
		}

		simulateRelease(event);
		mEditorView->scene()->update();
		break;
	case QEvent::TouchUpdate:
		simulateMove(event);
		break;
	default:
		break;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include "MainWindow.hpp"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    go_(new GameOptions) {
    ui->setupUi(this);
}

MainWindow::~MainWindow() {
    delete ui;
}

int MainWindow::getDeskSize_impl() const {
    return ui->boardsSize->value();
}

int MainWindow::getWinNumber_impl() const {
    return ui->scoreNumber->value();
}

int MainWindow::getTimeNumber_impl() const {
    return ui->timeNumber->value();
}

void MainWindow::finish_impl(bool fail, int score,
                             int steps_number) const {
    QString result = (fail) ? "You're loser..." :
                     "You're winner!";
    QString score_str = "Your score is " + score;
    QString steps = "You've completed the game in " +
                    steps_number;
    ui->resultLabel->setText(result);
    ui->scoreLabel->setText(score_str);
    ui->stepLabel->setText(steps);
}

void MainWindow::sendHelpMessage_impl() const {
    QMessageBox help;
    help.setText("Some useful help information.");
    help.setInformativeText("");
    help.exec();
}

void MainWindow::startGame_impl(int row_number) {
    configureBoard();
    game_ = GuiGame::make(this, row_number);
    game_->controller->initialStateOfBoard();
    setBoardsModel();
}

void MainWindow::errorHandling_impl(std::exception& e) const {
    QString what = QString::fromStdString(e.what());
    QString error = "The error occurred."
                    "

Contact developers! "
                    "pdolgov99@gmail.com";
    what = what.replace("&", "&");
    what = what.replace("'", "'");
    what = what.replace("<", "<");
    what = what.replace(">", ">");
    what = what.replace("\"", """);
    QString m = error + "

" + what;
    QErrorMessage::qtHandler()->resize(400, 300);
    QErrorMessage::qtHandler()->showMessage(m);
}

void MainWindow::setBoardsModel() {
    ui->gameBoard->setModel(game_->t_model.data());
}

void MainWindow::configureBoard() {
    ui->gameBoard
    ->setSelectionMode(QAbstractItemView::NoSelection);
    ui->gameBoard->horizontalHeader()
    ->setResizeMode(QHeaderView::Stretch);
    ui->gameBoard->verticalHeader()
    ->setResizeMode(QHeaderView::Stretch);
}

void MainWindow::preparingToPlay() {
    int boards_size = getDeskSize_impl();
    startGame_impl(boards_size);
}

void MainWindow::finishActions(int steps_number) {
    const GameDesk* desk = game_->desk.data();
    finish_impl(checkFail(*desk), score(*desk),
                steps_number);
    ui->stackedWidget->setCurrentWidget(ui->resultpage);
}

bool MainWindow::endOfGame() const {
    const GameDesk* desk = game_->desk.data();
    if (go_->game_type_ == SCORE_MODE) {
        return checkFail(*desk);
    } else if (go_->game_type_ == WIN_MODE) {
        return checkFail(*desk) || checkWin(*desk,
                                            go_->win_number_);
    } else {
        int current_time = time(NULL);
        bool time_is_up =
            (current_time - go_->starting_time_) >= go_->time_number_ * 60;
        return checkFail(*desk) || time_is_up;
    }
}

void MainWindow::tryToMove() {
    try {
        game_->controller->replace(go_->current_step_);
    } catch (...) {
    }
}

void MainWindow::on_quitButton_clicked() {
    QApplication::quit();
}

void MainWindow::on_winButton_clicked() {
    go_->game_type_ = WIN_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_timeButton_clicked() {
    go_->game_type_ = TIME_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_scoreButton_clicked() {
    go_->game_type_ = SCORE_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_startButton_clicked() {
    try {
        preparingToPlay();
        if (go_->game_type_ == SCORE_MODE) {
            go_->steps_number_ = 0;
            go_->first_click_ = true;
            ui->stackedWidget
            ->setCurrentWidget(ui->gamepage);
        } else if (go_->game_type_ == WIN_MODE) {
            ui->stackedWidget
            ->setCurrentWidget(ui->winInputpage);
        } else {
            ui->stackedWidget
            ->setCurrentWidget(ui->timeInputpage);
        }
    } catch (std::exception& e) {
        errorHandling_impl(e);
    }
}

void MainWindow::on_playButton_clicked() {
    go_->time_number_ = getTimeNumber_impl();
    go_->starting_time_ = time(NULL);
    go_->steps_number_ = 0;
    go_->first_click_ = true;
    ui->stackedWidget->setCurrentWidget(ui->gamepage);
}

void MainWindow::on_playButton2_clicked() {
    go_->win_number_ = getWinNumber_impl();
    go_->steps_number_ = 0;
    go_->first_click_ = true;
    ui->stackedWidget->setCurrentWidget(ui->gamepage);
}

void MainWindow::on_gameBoard_clicked(const QModelIndex&
                                      index) {
    Point p;
    p.col = index.column();
    p.row = index.row();
    if (go_->first_click_) {
        go_->first_click_ = false;
        go_->current_step_.p1 = p;
    } else {
        if (endOfGame()) {
            finishActions(go_->steps_number_);
        } else {
            go_->current_step_.p2 = p;
            tryToMove();
            game_->t_model->updateData();
            go_->steps_number_++;
            go_->first_click_ = true;
        }
    }
}

void MainWindow::on_endButton_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->startpage);
}
<commit_msg>Convert number to string before concatenation<commit_after>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include "MainWindow.hpp"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    go_(new GameOptions) {
    ui->setupUi(this);
}

MainWindow::~MainWindow() {
    delete ui;
}

int MainWindow::getDeskSize_impl() const {
    return ui->boardsSize->value();
}

int MainWindow::getWinNumber_impl() const {
    return ui->scoreNumber->value();
}

int MainWindow::getTimeNumber_impl() const {
    return ui->timeNumber->value();
}

void MainWindow::finish_impl(bool fail, int score,
                             int steps_number) const {
    QString result = (fail) ? "You're loser..." :
                     "You're winner!";
    QString score_str = "Your score is " +
                        QString::number(score);
    QString steps = "You've completed the game in " +
                    QString::number(steps_number);
    ui->resultLabel->setText(result);
    ui->scoreLabel->setText(score_str);
    ui->stepLabel->setText(steps);
}

void MainWindow::sendHelpMessage_impl() const {
    QMessageBox help;
    help.setText("Some useful help information.");
    help.setInformativeText("");
    help.exec();
}

void MainWindow::startGame_impl(int row_number) {
    configureBoard();
    game_ = GuiGame::make(this, row_number);
    game_->controller->initialStateOfBoard();
    setBoardsModel();
}

void MainWindow::errorHandling_impl(std::exception& e) const {
    QString what = QString::fromStdString(e.what());
    QString error = "The error occurred."
                    "

Contact developers! "
                    "pdolgov99@gmail.com";
    what = what.replace("&", "&");
    what = what.replace("'", "'");
    what = what.replace("<", "<");
    what = what.replace(">", ">");
    what = what.replace("\"", """);
    QString m = error + "

" + what;
    QErrorMessage::qtHandler()->resize(400, 300);
    QErrorMessage::qtHandler()->showMessage(m);
}

void MainWindow::setBoardsModel() {
    ui->gameBoard->setModel(game_->t_model.data());
}

void MainWindow::configureBoard() {
    ui->gameBoard
    ->setSelectionMode(QAbstractItemView::NoSelection);
    ui->gameBoard->horizontalHeader()
    ->setResizeMode(QHeaderView::Stretch);
    ui->gameBoard->verticalHeader()
    ->setResizeMode(QHeaderView::Stretch);
}

void MainWindow::preparingToPlay() {
    int boards_size = getDeskSize_impl();
    startGame_impl(boards_size);
}

void MainWindow::finishActions(int steps_number) {
    const GameDesk* desk = game_->desk.data();
    finish_impl(checkFail(*desk), score(*desk),
                steps_number);
    ui->stackedWidget->setCurrentWidget(ui->resultpage);
}

bool MainWindow::endOfGame() const {
    const GameDesk* desk = game_->desk.data();
    if (go_->game_type_ == SCORE_MODE) {
        return checkFail(*desk);
    } else if (go_->game_type_ == WIN_MODE) {
        return checkFail(*desk) || checkWin(*desk,
                                            go_->win_number_);
    } else {
        int current_time = time(NULL);
        bool time_is_up =
            (current_time - go_->starting_time_) >= go_->time_number_ * 60;
        return checkFail(*desk) || time_is_up;
    }
}

void MainWindow::tryToMove() {
    try {
        game_->controller->replace(go_->current_step_);
    } catch (...) {
    }
}

void MainWindow::on_quitButton_clicked() {
    QApplication::quit();
}

void MainWindow::on_winButton_clicked() {
    go_->game_type_ = WIN_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_timeButton_clicked() {
    go_->game_type_ = TIME_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_scoreButton_clicked() {
    go_->game_type_ = SCORE_MODE;
    ui->stackedWidget->setCurrentWidget(ui->inputpage);
}

void MainWindow::on_startButton_clicked() {
    try {
        preparingToPlay();
        if (go_->game_type_ == SCORE_MODE) {
            go_->steps_number_ = 0;
            go_->first_click_ = true;
            ui->stackedWidget
            ->setCurrentWidget(ui->gamepage);
        } else if (go_->game_type_ == WIN_MODE) {
            ui->stackedWidget
            ->setCurrentWidget(ui->winInputpage);
        } else {
            ui->stackedWidget
            ->setCurrentWidget(ui->timeInputpage);
        }
    } catch (std::exception& e) {
        errorHandling_impl(e);
    }
}

void MainWindow::on_playButton_clicked() {
    go_->time_number_ = getTimeNumber_impl();
    go_->starting_time_ = time(NULL);
    go_->steps_number_ = 0;
    go_->first_click_ = true;
    ui->stackedWidget->setCurrentWidget(ui->gamepage);
}

void MainWindow::on_playButton2_clicked() {
    go_->win_number_ = getWinNumber_impl();
    go_->steps_number_ = 0;
    go_->first_click_ = true;
    ui->stackedWidget->setCurrentWidget(ui->gamepage);
}

void MainWindow::on_gameBoard_clicked(const QModelIndex&
                                      index) {
    Point p;
    p.col = index.column();
    p.row = index.row();
    if (go_->first_click_) {
        go_->first_click_ = false;
        go_->current_step_.p1 = p;
    } else {
        if (endOfGame()) {
            finishActions(go_->steps_number_);
        } else {
            go_->current_step_.p2 = p;
            tryToMove();
            game_->t_model->updateData();
            go_->steps_number_++;
            go_->first_click_ = true;
        }
    }
}

void MainWindow::on_endButton_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->startpage);
}
<|endoftext|>