<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -shared-libgcc opencv.cpp -o opencv

#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <iostream>
#include <time.h>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    VideoCapture cap; // camera interface

    // open default 0 device if no other device as first argument was passed
    if(argc > 1){
    	cap.open(atoi(argv[1]));
    } else {
    	cap.open(0);
    }

    if(!cap.isOpened())  // check if we succeeded
    {
        cout << "Could not open default video device" << endl;
        return -1;
    } else {
    	cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
    	cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
    }

    Mat frame, bwFrame;
    namedWindow("camera",1);

    while(1) {
		if( !cap.read(frame) ){
			cout << "Camera was disconected";
			break;
		}

		cout << time(NULL) << endl;

		cvtColor(frame, bwFrame, CV_BGR2GRAY);

		imshow("camera", bwFrame);

		if(waitKey(30) >= 0)
			break;
	}

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}
<commit_msg>Using threads<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -shared-libgcc opencv.cpp -o opencv

#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <thread>

using namespace cv;
using namespace std;

void gui(); // thread

Mat bwFrame;

int main(int argc, char** argv)
{
    thread gui_thread;
    VideoCapture cap; // camera interface
    Mat frame;

    // open default 0 device if no other device as first argument was passed
    if(argc > 1){
    	cap.open(atoi(argv[1]));
    } else {
    	cap.open(0);
    }

    if(!cap.isOpened())  // check if we succeeded
    {
        cout << "Could not open default video device" << endl;
        return -1;
    } else {
    	cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
    	cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
    }

    while(1) {
		if( !cap.read(frame) ){
			cout << "Camera was disconected";
			break;
		}

		cvtColor(frame, bwFrame, CV_BGR2GRAY);

		if(!gui_thread.joinable())
			gui_thread = thread(gui);

		if(waitKey(30) >= 0)
			break;
	}

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

void gui( ){

	// startup code
	namedWindow("camera",1);

	//loop
	while(1){
		imshow("camera", bwFrame);
		cout << time(NULL) << endl;
	}
}
<|endoftext|>


<commit_before>/*
 *  qnode.cpp
 *
 *  Created on: Aug 30, 2012
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2012, Francisco Vina, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of the KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * @file /src/qnode.cpp
 *
 * @brief Ros communication central!
 *
 * @date February 2011
 **/

/*****************************************************************************
** Includes
*****************************************************************************/

#include <ros/ros.h>
#include <ros/network.h>
#include <string>
// ROS message includes
#include <std_msgs/String.h>

#include <sstream>
#include <dumbo_dashboard/qnode.hpp>

/*****************************************************************************
** Implementation
*****************************************************************************/

QNode::QNode(int argc, char** argv ) :
  init_argc(argc),
  init_argv(argv)
{
  n = ros::NodeHandle("~");
}

QNode::~QNode() {
    if(ros::isStarted()) {
      ros::shutdown(); // explicitly needed since we use ros::start();
      ros::waitForShutdown();
    }
	wait();
}

bool QNode::on_init()
{
	// Add your ros communications here.

	// subscribe to arm initialization services
	left_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/init");
	right_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/init");

    // subscribe to disconnect services
    left_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/disconnect");
    right_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/disconnect");

	// subscribe to PG70 parallel gripper initialization services
	pg70_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/init");
	sdh_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/init");

    // subscribe to PG70 parallel gripper disconnect services
    pg70_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/disconnect");
    sdh_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/shutdown");

	// subscribe to arm stop services
	left_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/stop_arm");
	right_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/stop_arm");

	// subscribe to arm recover services
	left_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/recover");
	right_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/recover");

	// subscribe to gripper recover services
	pg70_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/recover");
	sdh_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/recover");

	// subscribe to gripper pos
	pg70_pos_pub = n.advertise<brics_actuator::JointPositions>("/PG70_controller/command_pos", 1);

	// subscribe to FT sensor init service
    left_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/connect");
    left_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/disconnect");
    left_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/left_arm_ft_sensor/calibrate");
    right_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/connect");
    right_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/disconnect");
    right_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/right_arm_ft_sensor/calibrate");

	// subscribe to left gripper close service
	pg70_close_srv_client = n.serviceClient<dumbo_srvs::ClosePG70Gripper>("/PG70_controller/close_gripper");

	start();
	return true;
}

bool QNode::on_init(const std::string &master_url, const std::string &host_url) {
	std::map<std::string,std::string> remappings;
	remappings["__master"] = master_url;
	remappings["__hostname"] = host_url;
	ros::init(remappings,"test");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start(); // explicitly needed since our nodehandle is going out of scope.
	// Add your ros communications here.
	start();
	return true;
}

void QNode::run() {
	ros::Rate loop_rate(10);
	int count = 0;

	while ( ros::ok() ) {
		ros::spinOnce();
		loop_rate.sleep();
	}
	std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
	emit rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch)
}

void QNode::initArms()
{
  cob_srvs::Trigger left_arm_init_srv;

  while(!left_arm_initsrv_client.exists())
  {
	  ROS_INFO("Waiting for left arm init service");
	  ros::Duration(1).sleep();
  }

  if(left_arm_initsrv_client.call(left_arm_init_srv))
    {
      if(left_arm_init_srv.response.success.data)
	{
	  ROS_INFO("Successfully initialized left arm...");
	  emit leftArmConnected();
	}
      else
	{
	  ROS_ERROR("Error initializing left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm init service");
    }

  // open the PG70 gripper if the left arm connected correctly
  if(left_arm_init_srv.response.success.data)
  {
	  cob_srvs::Trigger pg70_init_srv;

//	  while(!pg70_initsrv_client.exists())
//	  {
//		  ROS_INFO("Waiting for PG70 init service");
//		  ros::Duration(1).sleep();
//	  }

	  if(pg70_initsrv_client.call(pg70_init_srv))
	  {
		  if(pg70_init_srv.response.success.data)
		  {
			  ROS_INFO("Successfully initialized PG70 gripper...");
			  //		  emit rightArmConnected(); todo fix for pg70
		  }
		  else
		  {
			  ROS_ERROR("Error initializing PG70 gripper");
		  }
	  }

	  else
	  {
		  ROS_ERROR("Failed to call PG70 gripper init service");
	  }
  }

  cob_srvs::Trigger right_arm_init_srv;

  while(!right_arm_initsrv_client.exists())
  {
	  ROS_INFO("Waiting for right arm init service");
	  ros::Duration(1).sleep();
  }

  if(right_arm_initsrv_client.call(right_arm_init_srv))
  {
	  if(right_arm_init_srv.response.success.data)
	  {
		  ROS_INFO("Successfully initialized right arm...");
		  emit rightArmConnected();
	  }
	  else
	  {
		  ROS_ERROR("Error initializing right arm");
	  }
  }

  else
  {
	  ROS_ERROR("Failed to call right arm init service");
  }

  if(right_arm_init_srv.response.success.data)
  {
	  cob_srvs::Trigger sdh_init_srv;

//	  while(!sdh_initsrv_client.exists())
//	  {
//		  ROS_INFO("Waiting for SDH init service");
//		  ros::Duration(1).sleep();
//	  }

	  if(sdh_initsrv_client.call(sdh_init_srv))
	  {
		  if(sdh_init_srv.response.success.data)
		  {
			  ROS_INFO("Successfully initialized SDH gripper...");
			  //		  emit rightArmConnected(); todo fix for sdh
		  }
		  else
		  {
			  ROS_ERROR("Error initializing SDH gripper");
		  }
	  }

	  else
	  {
		  ROS_ERROR("Failed to call SDH gripper init service");
	  }
  }

}

void QNode::disconnect_robot()
{
    cob_srvs::Trigger disconnect_srv;

    pg70_disconnectsrv_client.call(disconnect_srv);
    left_arm_disconnectsrv_client.call(disconnect_srv);
    sdh_disconnectsrv_client.call(disconnect_srv);
    right_arm_disconnectsrv_client.call(disconnect_srv);

    left_arm_ft_disconnectsrv_client.call(disconnect_srv);
    right_arm_ft_disconnectsrv_client.call(disconnect_srv);
    emit leftArmDisconnected();
    emit rightArmDisconnected();
    emit left_ft_disconnected();
    emit right_ft_disconnected();
}

void QNode::stopArms()
{
  cob_srvs::Trigger left_arm_stop_srv;
  if(left_arm_stopsrv_client.call(left_arm_stop_srv))
    {
      if(left_arm_stop_srv.response.success.data)
	{
	  ROS_INFO("Successfully stopped left arm...");
	}
      else
	{
	  ROS_ERROR("Error stopping left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm stop service");
    }

  cob_srvs::Trigger right_arm_stop_srv;
  if(right_arm_stopsrv_client.call(right_arm_stop_srv))
    {
      if(right_arm_stop_srv.response.success.data)
	{
	  ROS_INFO("Successfully stopped right arm...");
	}
      else
	{
	  ROS_ERROR("Error stopping right arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call right arm stop service");
    }
}

void QNode::recoverArms()
{
  cob_srvs::Trigger left_arm_recover_srv;
  if(left_arm_recoversrv_client.call(left_arm_recover_srv))
    {
      if(left_arm_recover_srv.response.success.data==true)
	{
	  ROS_INFO("Successfully recovered left arm...");
	}
      else
	{
	  ROS_ERROR("Error recovering left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm recover service");
    }

  cob_srvs::Trigger pg70_recover_srv;
  if(pg70_recoversrv_client.call(pg70_recover_srv))
  {
	  if(pg70_recover_srv.response.success.data==true)
	  {
		  ROS_INFO("Successfully recovered PG70 parallel gripper...");
	  }
	  else
	  {
		  ROS_ERROR("Error recovering PG70 parallel gripper");
	  }
  }

  else
  {
	  ROS_ERROR("Failed to call PG70 parallel gripper recover service");
  }

  cob_srvs::Trigger right_arm_recover_srv;
  if(right_arm_recoversrv_client.call(right_arm_recover_srv))
    {
      if(right_arm_recover_srv.response.success.data==true)
	{
	  ROS_INFO("Successfully recovered right arm...");
	}
      else
	{
	  ROS_ERROR("Error recovering right arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call right arm recover service");
    }
}

void QNode::sendGripperPos(double pos)
{
  // *** hard coded...
  brics_actuator::JointPositions left_gripper_pos_command;
  left_gripper_pos_command.positions.resize(1);

  left_gripper_pos_command.positions[0].timeStamp = ros::Time::now();
  left_gripper_pos_command.positions[0].joint_uri = "left_arm_top_finger_joint";
  left_gripper_pos_command.positions[0].unit = "mm";
  left_gripper_pos_command.positions[0].value = pos;

  pg70_pos_pub.publish(left_gripper_pos_command);

}

void QNode::closeGripper(double target_vel, double current_limit)
{
	dumbo_srvs::ClosePG70Gripper gripper_close_srv;
	gripper_close_srv.request.target_vel = target_vel;
	gripper_close_srv.request.current_limit = current_limit;

	if(pg70_close_srv_client.call(gripper_close_srv))
	{
		if(gripper_close_srv.response.success)
		{
			ROS_INFO("Closing PG70 gripper");
		}

		else
		{
			ROS_ERROR("Couldn't close PG70 gripper.");
		}
	}

	else
	{
		ROS_ERROR("Couldn't close PG70 gripper.");
	}

}

void QNode::connectFT()
{

    cob_srvs::Trigger left_arm_ft_connect_srv;
    while(!left_arm_ft_connectsrv_client.exists())
	{
        ROS_INFO("Waiting for left arm F/T connect service.");
		ros::Duration(1).sleep();
	}
    if(left_arm_ft_connectsrv_client.call(left_arm_ft_connect_srv))
	{
        if(left_arm_ft_connect_srv.response.success.data)
		{
            ROS_INFO("Successfully connected to left arm F/T sensor...");
            emit left_ft_connected();
		}
		else
		{
            ROS_ERROR("Error connecting to left arm F/T sensor");
		}
	}

	else
	{
        ROS_ERROR("Failed to call left arm F/T sensor connect service");
	}

    cob_srvs::Trigger right_arm_ft_connect_srv;
    while(!right_arm_ft_connectsrv_client.exists())
	{
        ROS_INFO("Waiting for right arm F/T connect service.");
		ros::Duration(1).sleep();
	}
    if(right_arm_ft_connectsrv_client.call(right_arm_ft_connect_srv))
	{
        if(right_arm_ft_connect_srv.response.success.data)
		{
            ROS_INFO("Successfully connected to right arm F/T sensor...");
            emit right_ft_connected();
		}
		else
		{
            ROS_ERROR("Error connecting to right arm F/T sensor");
		}
	}

	else
	{
        ROS_ERROR("Failed to call right arm F/T sensor connect service");
	}

}
<commit_msg>fixed gripper position<commit_after>/*
 *  qnode.cpp
 *
 *  Created on: Aug 30, 2012
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2012, Francisco Vina, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of the KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * @file /src/qnode.cpp
 *
 * @brief Ros communication central!
 *
 * @date February 2011
 **/

/*****************************************************************************
** Includes
*****************************************************************************/

#include <ros/ros.h>
#include <ros/network.h>
#include <string>
// ROS message includes
#include <std_msgs/String.h>

#include <sstream>
#include <dumbo_dashboard/qnode.hpp>

/*****************************************************************************
** Implementation
*****************************************************************************/

QNode::QNode(int argc, char** argv ) :
  init_argc(argc),
  init_argv(argv)
{
  n = ros::NodeHandle("~");
}

QNode::~QNode() {
    if(ros::isStarted()) {
      ros::shutdown(); // explicitly needed since we use ros::start();
      ros::waitForShutdown();
    }
	wait();
}

bool QNode::on_init()
{
	// Add your ros communications here.

	// subscribe to arm initialization services
	left_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/init");
	right_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/init");

    // subscribe to disconnect services
    left_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/disconnect");
    right_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/disconnect");

	// subscribe to PG70 parallel gripper initialization services
	pg70_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/init");
	sdh_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/init");

    // subscribe to PG70 parallel gripper disconnect services
    pg70_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/disconnect");
    sdh_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/shutdown");

	// subscribe to arm stop services
	left_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/stop_arm");
	right_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/stop_arm");

	// subscribe to arm recover services
	left_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/recover");
	right_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/recover");

	// subscribe to gripper recover services
	pg70_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/recover");
	sdh_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/recover");

	// subscribe to gripper pos
	pg70_pos_pub = n.advertise<brics_actuator::JointPositions>("/PG70_controller/command_pos", 1);

	// subscribe to FT sensor init service
    left_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/connect");
    left_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/disconnect");
    left_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/left_arm_ft_sensor/calibrate");
    right_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/connect");
    right_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/disconnect");
    right_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/right_arm_ft_sensor/calibrate");

	// subscribe to left gripper close service
	pg70_close_srv_client = n.serviceClient<dumbo_srvs::ClosePG70Gripper>("/PG70_controller/close_gripper");

	start();
	return true;
}

bool QNode::on_init(const std::string &master_url, const std::string &host_url) {
	std::map<std::string,std::string> remappings;
	remappings["__master"] = master_url;
	remappings["__hostname"] = host_url;
	ros::init(remappings,"test");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start(); // explicitly needed since our nodehandle is going out of scope.
	// Add your ros communications here.
	start();
	return true;
}

void QNode::run() {
	ros::Rate loop_rate(10);
	int count = 0;

	while ( ros::ok() ) {
		ros::spinOnce();
		loop_rate.sleep();
	}
	std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
	emit rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch)
}

void QNode::initArms()
{
  cob_srvs::Trigger left_arm_init_srv;

  while(!left_arm_initsrv_client.exists())
  {
	  ROS_INFO("Waiting for left arm init service");
	  ros::Duration(1).sleep();
  }

  if(left_arm_initsrv_client.call(left_arm_init_srv))
    {
      if(left_arm_init_srv.response.success.data)
	{
	  ROS_INFO("Successfully initialized left arm...");
	  emit leftArmConnected();
	}
      else
	{
	  ROS_ERROR("Error initializing left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm init service");
    }

  // open the PG70 gripper if the left arm connected correctly
  if(left_arm_init_srv.response.success.data)
  {
	  cob_srvs::Trigger pg70_init_srv;

//	  while(!pg70_initsrv_client.exists())
//	  {
//		  ROS_INFO("Waiting for PG70 init service");
//		  ros::Duration(1).sleep();
//	  }

	  if(pg70_initsrv_client.call(pg70_init_srv))
	  {
		  if(pg70_init_srv.response.success.data)
		  {
			  ROS_INFO("Successfully initialized PG70 gripper...");
			  //		  emit rightArmConnected(); todo fix for pg70
		  }
		  else
		  {
			  ROS_ERROR("Error initializing PG70 gripper");
		  }
	  }

	  else
	  {
		  ROS_ERROR("Failed to call PG70 gripper init service");
	  }
  }

  cob_srvs::Trigger right_arm_init_srv;

  while(!right_arm_initsrv_client.exists())
  {
	  ROS_INFO("Waiting for right arm init service");
	  ros::Duration(1).sleep();
  }

  if(right_arm_initsrv_client.call(right_arm_init_srv))
  {
	  if(right_arm_init_srv.response.success.data)
	  {
		  ROS_INFO("Successfully initialized right arm...");
		  emit rightArmConnected();
	  }
	  else
	  {
		  ROS_ERROR("Error initializing right arm");
	  }
  }

  else
  {
	  ROS_ERROR("Failed to call right arm init service");
  }

  if(right_arm_init_srv.response.success.data)
  {
	  cob_srvs::Trigger sdh_init_srv;

//	  while(!sdh_initsrv_client.exists())
//	  {
//		  ROS_INFO("Waiting for SDH init service");
//		  ros::Duration(1).sleep();
//	  }

	  if(sdh_initsrv_client.call(sdh_init_srv))
	  {
		  if(sdh_init_srv.response.success.data)
		  {
			  ROS_INFO("Successfully initialized SDH gripper...");
			  //		  emit rightArmConnected(); todo fix for sdh
		  }
		  else
		  {
			  ROS_ERROR("Error initializing SDH gripper");
		  }
	  }

	  else
	  {
		  ROS_ERROR("Failed to call SDH gripper init service");
	  }
  }

}

void QNode::disconnect_robot()
{
    cob_srvs::Trigger disconnect_srv;

    pg70_disconnectsrv_client.call(disconnect_srv);
    left_arm_disconnectsrv_client.call(disconnect_srv);
    sdh_disconnectsrv_client.call(disconnect_srv);
    right_arm_disconnectsrv_client.call(disconnect_srv);

    left_arm_ft_disconnectsrv_client.call(disconnect_srv);
    right_arm_ft_disconnectsrv_client.call(disconnect_srv);
    emit leftArmDisconnected();
    emit rightArmDisconnected();
    emit left_ft_disconnected();
    emit right_ft_disconnected();
}

void QNode::stopArms()
{
  cob_srvs::Trigger left_arm_stop_srv;
  if(left_arm_stopsrv_client.call(left_arm_stop_srv))
    {
      if(left_arm_stop_srv.response.success.data)
	{
	  ROS_INFO("Successfully stopped left arm...");
	}
      else
	{
	  ROS_ERROR("Error stopping left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm stop service");
    }

  cob_srvs::Trigger right_arm_stop_srv;
  if(right_arm_stopsrv_client.call(right_arm_stop_srv))
    {
      if(right_arm_stop_srv.response.success.data)
	{
	  ROS_INFO("Successfully stopped right arm...");
	}
      else
	{
	  ROS_ERROR("Error stopping right arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call right arm stop service");
    }
}

void QNode::recoverArms()
{
  cob_srvs::Trigger left_arm_recover_srv;
  if(left_arm_recoversrv_client.call(left_arm_recover_srv))
    {
      if(left_arm_recover_srv.response.success.data==true)
	{
	  ROS_INFO("Successfully recovered left arm...");
	}
      else
	{
	  ROS_ERROR("Error recovering left arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call left arm recover service");
    }

  cob_srvs::Trigger pg70_recover_srv;
  if(pg70_recoversrv_client.call(pg70_recover_srv))
  {
	  if(pg70_recover_srv.response.success.data==true)
	  {
		  ROS_INFO("Successfully recovered PG70 parallel gripper...");
	  }
	  else
	  {
		  ROS_ERROR("Error recovering PG70 parallel gripper");
	  }
  }

  else
  {
	  ROS_ERROR("Failed to call PG70 parallel gripper recover service");
  }

  cob_srvs::Trigger right_arm_recover_srv;
  if(right_arm_recoversrv_client.call(right_arm_recover_srv))
    {
      if(right_arm_recover_srv.response.success.data==true)
	{
	  ROS_INFO("Successfully recovered right arm...");
	}
      else
	{
	  ROS_ERROR("Error recovering right arm");
	}
    }

  else
    {
      ROS_ERROR("Failed to call right arm recover service");
    }
}

void QNode::sendGripperPos(double pos)
{
  // *** hard coded...
  brics_actuator::JointPositions left_gripper_pos_command;
  left_gripper_pos_command.positions.resize(1);

  left_gripper_pos_command.positions[0].timeStamp = ros::Time::now();
  left_gripper_pos_command.positions[0].joint_uri = "left_arm_top_finger_joint";
  left_gripper_pos_command.positions[0].unit = "m";
  left_gripper_pos_command.positions[0].value = pos/1000.0;

  pg70_pos_pub.publish(left_gripper_pos_command);

}

void QNode::closeGripper(double target_vel, double current_limit)
{
	dumbo_srvs::ClosePG70Gripper gripper_close_srv;
	gripper_close_srv.request.target_vel = target_vel;
	gripper_close_srv.request.current_limit = current_limit;

	if(pg70_close_srv_client.call(gripper_close_srv))
	{
		if(gripper_close_srv.response.success)
		{
			ROS_INFO("Closing PG70 gripper");
		}

		else
		{
			ROS_ERROR("Couldn't close PG70 gripper.");
		}
	}

	else
	{
		ROS_ERROR("Couldn't close PG70 gripper.");
	}

}

void QNode::connectFT()
{

    cob_srvs::Trigger left_arm_ft_connect_srv;
    while(!left_arm_ft_connectsrv_client.exists())
	{
        ROS_INFO("Waiting for left arm F/T connect service.");
		ros::Duration(1).sleep();
	}
    if(left_arm_ft_connectsrv_client.call(left_arm_ft_connect_srv))
	{
        if(left_arm_ft_connect_srv.response.success.data)
		{
            ROS_INFO("Successfully connected to left arm F/T sensor...");
            emit left_ft_connected();
		}
		else
		{
            ROS_ERROR("Error connecting to left arm F/T sensor");
		}
	}

	else
	{
        ROS_ERROR("Failed to call left arm F/T sensor connect service");
	}

    cob_srvs::Trigger right_arm_ft_connect_srv;
    while(!right_arm_ft_connectsrv_client.exists())
	{
        ROS_INFO("Waiting for right arm F/T connect service.");
		ros::Duration(1).sleep();
	}
    if(right_arm_ft_connectsrv_client.call(right_arm_ft_connect_srv))
	{
        if(right_arm_ft_connect_srv.response.success.data)
		{
            ROS_INFO("Successfully connected to right arm F/T sensor...");
            emit right_ft_connected();
		}
		else
		{
            ROS_ERROR("Error connecting to right arm F/T sensor");
		}
	}

	else
	{
        ROS_ERROR("Failed to call right arm F/T sensor connect service");
	}

}
<|endoftext|>


<commit_before>#ifndef DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH
#define DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH

namespace Dune {
namespace Functionals {
namespace Container {

template <class ContainerImp>
class Factory
{
public:
  typedef NotImplemented AutoPtrType;
  typedef NotImplemented ContainerType;

  class NotImplemented
  {
  };

public:
  template <class DiscFuncSpace>
  static AutoPtrType create(DiscFuncSpace& dfs)
  {
    dune_static_assert("Not Implemented: Factory!");
  }

  template <class DiscFuncSpace>
  static ContainerType* createPtr(DiscFuncSpace& dfs)
  {
    dune_static_assert("Not Implemented: Factory!");
  }
}; // end of class Factory

template <class ContainerImp>
class MatrixFactory : public Factory<ContainerImp>
{
};

// specialization for BCRSMatrix
template <class T>
class MatrixFactory<Dune::BCRSMatrix<T>>
{
public:
  typedef Dune::BCRSMatrix<T> ContainerType;
  typedef std::auto_ptr<ContainerType> AutoPtrType;

public:
  template <class DiscFuncSpace>
  static AutoPtrType create(DiscFuncSpace& dfs)
  {
    return AutoPtrType(createPtr(dfs));
  }

  template <class DiscFuncSpace>
  static ContainerType* createPtr(DiscFuncSpace& dfs)
  {
    typedef DiscFuncSpace::BaseFunctionSet BFS;
    typedef DiscFuncSpace::IteratorType ItType;
    typedef ItType::Entity Entity;

    const unsigned int numDofs = dfs.size();
    typedef std::vector<std::set<unsigned int>> PatternType;
    PatternType sPattern(numDofs);

    ContainerType* matrix = new ContainerType(numDofs, numDofs, ContainerType::random);

    // compute sparsity pattern
    // \todo precompile this in linear subspace
    // \todo use constraints for sparsity pattern
    ItType it = dfs.begin();
    for (; it != dfs.end(); it++) {
      const Entity& en = *it;
      const BFS& bfs   = dfs.baseFunctionSet(en);

      for (unsigned int i = 0; i < bfs.numBaseFunctions(); i++) {
        ii = dfs.mapToGlobal(en, i);
        for (unsigned int j = 0; j < bfs.numBaseFunctions(); j++) {
          jj = dfs.mapToGlobal(en, j);
          sPattern[ii].insert(jj);
        }
      }
    }

    for (unsigned int i = 0; i < sPattern.size(); i++) {
      matrix->setRowSize(i, sPattern[i].size());
    }
    matrix->endrowsizes();

    for (unsigned int i = 0; i < sPattern.size(); ++i) {
      typedef std::set<unsigned int>::const_iterator SetIterator;
      SetIterator sit = sPattern[i].begin();
      for (; sit != sPattern[i].end(); sit++) {
        matrix->addindex(i, *sit);
      }
    }
    matrix->endindices();

    return matrix;
  }

}; // end of MatrixFactory<BCRSMatrix<T> >

template <class ContainerImp>
class VectorFactory : public Factory<ContainerImp>
{
};

// specialization for BlockVector<T>
template <class T>
class VectorFactory<Dune::BlockVector<T>>
{
public:
  typedef Dune::BlockVector<T> ContainerType;
  typedef std::auto_ptr<ContainerType> AutoPtrType;

public:
  template <class DFSType>
  static ContainerType* createPtr(DFSType& dfs)
  {
    const unsigned int numDofs = dfs.size();
    ContainerType* bv          = new ContainerType(numDofs);
    return bv;
  }

  static AutoPtrType create(DFSType& dfs)
  {
    return AutoPtrType(createPtr(dfs));
  }
}; // end of VectorFactory<BlockVector<T> >

} // end of namespace Container

} // end of namespace Functionals

} // end of namespace Dune

#endif /* end of include guard: DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH */
<commit_msg>added documentation to container::factory<commit_after>#ifndef DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH
#define DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH

namespace Dune {
namespace Functionals {
namespace Container {

/** @brief interface of static factory class for matrix and vector classes
 */
template <class ContainerImp>
class Factory
{
public:
  //! return type for create() method
  typedef NotImplemented AutoPtrType;
  //! wrapped container type
  typedef NotImplemented ContainerType;

private:
  class NotImplemented
  {
  };

public:
  /** @brief creates a new matrix/vector object and returns an auto_ptr
   * pointing to the allocated object
   *
   * - Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number
   * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$.
   * The matrices' sparsity pattern is determined by the discrete function
   * space's basefunction overlap.
   * - Vectors have @f$ H @f$ components
   *
   * @param dfs the discrete function space @f$ { \cal X }_H @f$.
   */
  template <class DiscFuncSpace>
  static AutoPtrType create(DiscFuncSpace& dfs)
  {
    dune_static_assert("Not Implemented: Factory!");
  }

  /** @brief creates a new matrix/vector object and returns a pointer to the
   * allocated object
   *
   * - Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number
   * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$.
   * The matrices' sparsity pattern is determined by the discrete function
   * space's basefunction overlap.
   * - Vectors have @f$ H @f$ components
   *
   * @param dfs the discrete function space @f$ { \cal X }_H @f$.
   */
  template <class DiscFuncSpace>
  static ContainerType* createPtr(DiscFuncSpace& dfs)
  {
    dune_static_assert("Not Implemented: Factory!");
  }
}; // end of class Factory

/** @brief interface of static factory class for matrix classes
 */
template <class ContainerImp>
class MatrixFactory : public Factory<ContainerImp>
{
};

// specialization for BCRSMatrix
template <class T>
class MatrixFactory<Dune::BCRSMatrix<T>>
{
public:
  typedef Dune::BCRSMatrix<T> ContainerType;
  typedef std::auto_ptr<ContainerType> AutoPtrType;

public:
  /** @brief creates a new BCRSMatrix object and returns an auto_ptr pointing
   * to the allocated object
   *
   * Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number
   * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$.
   * The matrices' sparsity pattern is determined by the discrete function
   * space's basefunction overlap.
   *
   * @param dfs the discrete function space @f$ { \cal X }_H @f$.
   */
  template <class DiscFuncSpace>
  static AutoPtrType create(DiscFuncSpace& dfs)
  {
    return AutoPtrType(createPtr(dfs));
  }

  /** @brief creates a new BCRSMatrix object and returns a pointer to the
   * allocated object
   *
   * Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number
   * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$.
   * The matrices' sparsity pattern is determined by the discrete function
   * space's basefunction overlap.
   *
   * @param dfs the discrete function space @f$ { \cal X }_H @f$.
   */
  template <class DiscFuncSpace>
  static ContainerType* createPtr(DiscFuncSpace& dfs)
  {
    typedef DiscFuncSpace::BaseFunctionSet BFS;
    typedef DiscFuncSpace::IteratorType ItType;
    typedef ItType::Entity Entity;

    const unsigned int numDofs = dfs.size();
    typedef std::vector<std::set<unsigned int>> PatternType;
    PatternType sPattern(numDofs);

    ContainerType* matrix = new ContainerType(numDofs, numDofs, ContainerType::random);

    // compute sparsity pattern
    // \todo precompile this in linear subspace
    // \todo use constraints for sparsity pattern
    ItType it = dfs.begin();
    for (; it != dfs.end(); it++) {
      const Entity& en = *it;
      const BFS& bfs   = dfs.baseFunctionSet(en);

      for (unsigned int i = 0; i < bfs.numBaseFunctions(); i++) {
        ii = dfs.mapToGlobal(en, i);
        for (unsigned int j = 0; j < bfs.numBaseFunctions(); j++) {
          jj = dfs.mapToGlobal(en, j);
          sPattern[ii].insert(jj);
        }
      }
    }

    for (unsigned int i = 0; i < sPattern.size(); i++) {
      matrix->setRowSize(i, sPattern[i].size());
    }
    matrix->endrowsizes();

    for (unsigned int i = 0; i < sPattern.size(); ++i) {
      typedef std::set<unsigned int>::const_iterator SetIterator;
      SetIterator sit = sPattern[i].begin();
      for (; sit != sPattern[i].end(); sit++) {
        matrix->addindex(i, *sit);
      }
    }
    matrix->endindices();

    return matrix;
  }

}; // end of MatrixFactory<BCRSMatrix<T> >

/** @brief interface of static factory class for vector classes
 */
template <class ContainerImp>
class VectorFactory : public Factory<ContainerImp>
{
};

/** @brief static factory class for vector classes of type Dune::BlockVector
 */
template <class T>
class VectorFactory<Dune::BlockVector<T>>
{
public:
  //! \copydoc Factory::ContainerType
  typedef Dune::BlockVector<T> ContainerType;
  //! \copydoc Factory::AutoPtrType;
  typedef std::auto_ptr<ContainerType> AutoPtrType;

public:
  /** @brief creates a new vector object and returns an auto_ptr pointing to
   * the allocated object
   *
   * The vector has @f$ H @f$ components which is the number of degrees of
   * freedom of the given discrete function space @f$ {\cal X}_H @f$.
   *
   * @param dfs the discrete function space @f$ { \cal X }_H @f$.
   */
  template <class DFSType>
  static ContainerType* createPtr(DFSType& dfs)
  {
    const unsigned int numDofs = dfs.size();
    ContainerType* bv          = new ContainerType(numDofs);
    return bv;
  }

  static AutoPtrType create(DFSType& dfs)
  {
    return AutoPtrType(createPtr(dfs));
  }
}; // end of VectorFactory<BlockVector<T> >

} // end of namespace Container

} // end of namespace Functionals

} // end of namespace Dune

#endif /* end of include guard: DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH */
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cassert>

template <typename T>
inline T Factorial(T n)
{
    assert(n<21); /* overflows 64-bit integer */

    T r=1;
    for (T i=1; i<=n; ++i) r *= i;
    return r;
}

template <typename T>
inline double InverseFactorial(T n)
{
    double r=1.0;
    for (T i=1; i<=n; ++i) r /= i;
    return r;
}

template <typename T>
inline T DoubleFactorial(T n)
{
    //assert(n<21); /* overflows 64-bit integer */

    T r=1;
    for (T i=1; i<=n; ++i) r *= (2*i - 1);
    return r;
}

template <typename T>
inline double InverseDoubleFactorial(T n)
{
    //assert(n<21); /* overflows 64-bit integer */

    double r=1.0;
    for (T i=1; i<=n; ++i) r /= (2*i - 1);
    return r;
}

template <typename T>
inline T Sign(T k)
{
    return ( k>0 ? T(1) : T(-1) );
}

template <typename T>
inline T SignPow(T k)
{
    // return ( k%2==0 ? T(1) : T(-1) );
    // return ( k%2>0 ? T(-1) : T(1) );
    return ( T( 1-2*(k%2) ) );
}

template <typename T, typename F>
inline F BoysAsymp(T n, F x)
{
    return DoubleFactorial(2*n-1)/pow(2,n+1) * sqrt( M_PI / pow(x,2*n+1) );
}

template <typename T, typename F>
inline F BoysTerm(T n, T k, F x)
{
    //return pow(-x,k) / ( Factorial(k) * (2*k + 2*n + 1) );
    return pow(-x,k) * InverseFactorial(k) / (2*k + 2*n + 1);
}

int main(int argc, char* argv[])
{
    int n = ( argc>1 ? atoi(argv[1]) : 0 );
    double x  = ( argc>2 ? atof(argv[2]) : 0.0 );

    printf("n = %d x = %lf \n", n, x );

    int k;
    double xpower;
    double invkfact;
    double knsum;
    double bterm_even;
    double bterm_odd;
    double fast;

#if DEBUG
    fflush(stdout);
    printf("===================================================\n");

    //printf("%4s %2s %10s %14s %14s %14s %14s %2s \n", "n", "k", "x", "1/k!", "x^k", "k,BoysTerm(n,k,x)", "sum" );
    if (x<10.0) printf("%3s %3s %10s %14s %14s %14s %14s      \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum" );
    else        printf("%3s %3s %10s %14s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum", "BoysAsymp(n,x)" );
    double b = 0.0, s = 0.0;
    k = 0;
    while( (k<200) && (fabs(b=BoysTerm(n,k,x))>1.0e-16) && (fabs(b)<1.0e10))
    {
        //b = BoysTerm(n,k,x);
        s += b;
        //printf("%4ld %2ld %10.5lf %18ld %14.7e %14.7e %14.7e %2ld %c \n", n, k, x, Factorial(k), pow(-x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' );
        if (x<10.0) printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %3d %c \n",
                            n, k, x, InverseFactorial(k), pow(x,k), b, s, k+1,
                            fabs(b)<1.0e-14 ? '*' : ' ' );
        else        printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %14.7e %3d %c %s \n",
                            n, k, x, InverseFactorial(k), pow(x,k), b, s, BoysAsymp(n,x), k+1,
                            fabs(b)<1.0e-14 ? '*' : ' ' , fabs(BoysAsymp(n,x)-s)<1.0e-10 ? "**" : "  " );
        k++;
    }

    fflush(stdout);
    printf("===================================================\n");

    printf("%4s %2s %10s %12s %12s %14s %14s %14s %14s %14s %14s %14s %14s \n", "n", "k", "x", "2n+2k+1", "fast 2n+2k+1", "1/k!", "fast 1/k!","x^k", "fast x^k", "BoysTerm", "BoysTermFast", "sum", "fast sum" );

    k = 0;

    double sum;

    xpower      = 1.0;
    invkfact    = 1.0;
    knsum       = 2*n+1;
    bterm_even  = 1/knsum;
    bterm_odd   = 0.0;
    sum         = BoysTerm(n,k,x);
    fast        = 1/knsum;

    printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
            n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast);

    for (k=1; k<20; ++k)
    {
        sum      += BoysTerm(n,k,x);

        xpower    *= x;
        invkfact  /= k;                           /* use table lookup for division by integers on PPC */
        knsum     += 2;                           /* cast should be done by compiler */
        bterm_odd  = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        fast      += bterm_odd;
        printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
                n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_odd, sum, fast);

        ++k;

        sum      += BoysTerm(n,k,x);

        xpower    *= x;
        invkfact  /= k;                           /* use table lookup for division by integers on PPC */
        knsum     += 2;                           /* cast should be done by compiler */
        bterm_even =  xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        fast      += bterm_even;

        printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
                n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast);
    }
    printf("===================================================\n");
    fflush(stdout);
#endif

    printf("%4s %20s %20s \n", "k", "term", "sum" );
    printf("===================================================\n");

    k           = 0;
    xpower      = 1.0;
    invkfact    = 1.0;
    knsum       = 2*n+1;
    bterm_even  = 1.0/knsum;
    bterm_odd   = 0.0;

    double * fast_vec = (double *) malloc( 1001*sizeof(double) );
    fast_vec[0] = bterm_even;

    for (k=1; k<1000; ++k )
    {
        xpower      *= x;
        invkfact    /= k;                           /* use table lookup for division by integers on PPC */
        knsum       += 2;                           /* cast should be done by compiler */
        fast_vec[k]  = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        ++k;
        xpower      *= x;
        invkfact    /= k;                           /* use table lookup for division by integers on PPC */
        knsum       += 2;                           /* cast should be done by compiler */
        fast_vec[k]  =  xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
    }

    fast = 0.0;
    k = 0;
    while ( (k<1000) && (fabs(fast_vec[k])>1e-14) )
    {
        fast += fast_vec[k];
        printf("%4d %24.14e %24.14e \n",k, fast_vec[k], fast );
        ++k;
        if (fast > 1.0e12 ) break;
    }

    if (fast > 1.0/(2*n+1) )
        printf("%lf cannot be greater than %lf \n", fast, 1.0/(2*n+1) );

    printf("===================================================\n");
    fflush(stdout);

    return(0);
}
<commit_msg>add usage info<commit_after>#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cassert>

template <typename T>
inline T Factorial(T n)
{
    assert(n<21); /* overflows 64-bit integer */

    T r=1;
    for (T i=1; i<=n; ++i) r *= i;
    return r;
}

template <typename T>
inline double InverseFactorial(T n)
{
    double r=1.0;
    for (T i=1; i<=n; ++i) r /= i;
    return r;
}

template <typename T>
inline T DoubleFactorial(T n)
{
    //assert(n<21); /* overflows 64-bit integer */

    T r=1;
    for (T i=1; i<=n; ++i) r *= (2*i - 1);
    return r;
}

template <typename T>
inline double InverseDoubleFactorial(T n)
{
    //assert(n<21); /* overflows 64-bit integer */

    double r=1.0;
    for (T i=1; i<=n; ++i) r /= (2*i - 1);
    return r;
}

template <typename T>
inline T Sign(T k)
{
    return ( k>0 ? T(1) : T(-1) );
}

template <typename T>
inline T SignPow(T k)
{
    // return ( k%2==0 ? T(1) : T(-1) );
    // return ( k%2>0 ? T(-1) : T(1) );
    return ( T( 1-2*(k%2) ) );
}

template <typename T, typename F>
inline F BoysAsymp(T n, F x)
{
    return DoubleFactorial(2*n-1)/pow(2,n+1) * sqrt( M_PI / pow(x,2*n+1) );
}

template <typename T, typename F>
inline F BoysTerm(T n, T k, F x)
{
    //return pow(-x,k) / ( Factorial(k) * (2*k + 2*n + 1) );
    return pow(-x,k) * InverseFactorial(k) / (2*k + 2*n + 1);
}

int main(int argc, char* argv[])
{
    if (argc==1)
        printf("Usage: ./boys.x n x\n");

    int n     = ( argc>1 ? atoi(argv[1]) : 0 );
    double x  = ( argc>2 ? atof(argv[2]) : 0.0 );

    printf("n = %d x = %lf \n", n, x );

    int k;
    double xpower;
    double invkfact;
    double knsum;
    double bterm_even;
    double bterm_odd;
    double fast;

#if DEBUG
    fflush(stdout);
    printf("===================================================\n");

    //printf("%4s %2s %10s %14s %14s %14s %14s %2s \n", "n", "k", "x", "1/k!", "x^k", "k,BoysTerm(n,k,x)", "sum" );
    if (x<10.0) printf("%3s %3s %10s %14s %14s %14s %14s      \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum" );
    else        printf("%3s %3s %10s %14s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum", "BoysAsymp(n,x)" );
    double b = 0.0, s = 0.0;
    k = 0;
    while( (k<200) && (fabs(b=BoysTerm(n,k,x))>1.0e-16) && (fabs(b)<1.0e10))
    {
        //b = BoysTerm(n,k,x);
        s += b;
        //printf("%4ld %2ld %10.5lf %18ld %14.7e %14.7e %14.7e %2ld %c \n", n, k, x, Factorial(k), pow(-x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' );
        if (x<10.0) printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %3d %c \n",
                            n, k, x, InverseFactorial(k), pow(x,k), b, s, k+1,
                            fabs(b)<1.0e-14 ? '*' : ' ' );
        else        printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %14.7e %3d %c %s \n",
                            n, k, x, InverseFactorial(k), pow(x,k), b, s, BoysAsymp(n,x), k+1,
                            fabs(b)<1.0e-14 ? '*' : ' ' , fabs(BoysAsymp(n,x)-s)<1.0e-10 ? "**" : "  " );
        k++;
    }

    fflush(stdout);
    printf("===================================================\n");

    printf("%4s %2s %10s %12s %12s %14s %14s %14s %14s %14s %14s %14s %14s \n", "n", "k", "x", "2n+2k+1", "fast 2n+2k+1", "1/k!", "fast 1/k!","x^k", "fast x^k", "BoysTerm", "BoysTermFast", "sum", "fast sum" );

    k = 0;

    double sum;

    xpower      = 1.0;
    invkfact    = 1.0;
    knsum       = 2*n+1;
    bterm_even  = 1/knsum;
    bterm_odd   = 0.0;
    sum         = BoysTerm(n,k,x);
    fast        = 1/knsum;

    printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
            n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast);

    for (k=1; k<20; ++k)
    {
        sum      += BoysTerm(n,k,x);

        xpower    *= x;
        invkfact  /= k;                           /* use table lookup for division by integers on PPC */
        knsum     += 2;                           /* cast should be done by compiler */
        bterm_odd  = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        fast      += bterm_odd;
        printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
                n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_odd, sum, fast);

        ++k;

        sum      += BoysTerm(n,k,x);

        xpower    *= x;
        invkfact  /= k;                           /* use table lookup for division by integers on PPC */
        knsum     += 2;                           /* cast should be done by compiler */
        bterm_even =  xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        fast      += bterm_even;

        printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n",
                n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast);
    }
    printf("===================================================\n");
    fflush(stdout);
#endif

    printf("%4s %20s %20s \n", "k", "term", "sum" );
    printf("===================================================\n");

    k           = 0;
    xpower      = 1.0;
    invkfact    = 1.0;
    knsum       = 2*n+1;
    bterm_even  = 1.0/knsum;
    bterm_odd   = 0.0;

    double * fast_vec = (double *) malloc( 1001*sizeof(double) );
    fast_vec[0] = bterm_even;

    for (k=1; k<1000; ++k )
    {
        xpower      *= x;
        invkfact    /= k;                           /* use table lookup for division by integers on PPC */
        knsum       += 2;                           /* cast should be done by compiler */
        fast_vec[k]  = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
        ++k;
        xpower      *= x;
        invkfact    /= k;                           /* use table lookup for division by integers on PPC */
        knsum       += 2;                           /* cast should be done by compiler */
        fast_vec[k]  =  xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */
    }

    fast = 0.0;
    k = 0;
    while ( (k<1000) && (fabs(fast_vec[k])>1e-14) )
    {
        fast += fast_vec[k];
        printf("%4d %24.14e %24.14e \n",k, fast_vec[k], fast );
        ++k;
        if (fast > 1.0e12 ) break;
    }

    if (fast > 1.0/(2*n+1) )
        printf("%lf cannot be greater than %lf \n", fast, 1.0/(2*n+1) );

    printf("===================================================\n");
    fflush(stdout);

    return(0);
}
<|endoftext|>


<commit_before>// ***********************************************************************
// Filename         : check_is_class.hpp
// Author           : LIZHENG
// Created          : 2014-06-09
// Description      : жһǷͣע⣬std::is_classǸù
//
// Last Modified By : LIZHENG
// Last Modified On : 2014-06-09
//
// Copyright (c) lizhenghn@gmail.com. All rights reserved.
// ***********************************************************************
#ifndef ZL_CHECKISCLASS_H
#define ZL_CHECKISCLASS_H

namespace ZL
{
	template <typename T>
	class is_class
	{
		typedef char one;
		typedef struct { char a[2]; } two;

		template <typename C>
		static one test(int C::*);

		template <typename C>
		static two test(...);
	public:
		enum { value = sizeof(test<T>(0)) == sizeof(one) };
	};

} /* namespace ZL */

#endif /* ZL_CHECKISCLASS_H */<commit_msg>Update check_is_class.hpp<commit_after>// ***********************************************************************
// Filename         : check_is_class.hpp
// Author           : LIZHENG
// Created          : 2014-06-09
// Description      : 判断一个类型是否是类类型，注意，std::is_class即是该功能
//
// Last Modified By : LIZHENG
// Last Modified On : 2014-06-09
//
// Copyright (c) lizhenghn@gmail.com. All rights reserved.
// ***********************************************************************
#ifndef ZL_CHECKISCLASS_H
#define ZL_CHECKISCLASS_H

namespace ZL
{
	template <typename T>
	class is_class
	{
		typedef char YES;
		typedef struct { char a[2]; } NO;

		template <typename C>
		static YES test_t(int C::*);

		template <typename C>
		static NO test_t(...);
	public:
		enum { value = sizeof(test_t<T>(0)) == sizeof(YES) };
	};

} /* namespace ZL */

#endif /* ZL_CHECKISCLASS_H */
<|endoftext|>


<commit_before>/*
 * align_main.cpp
 *
 *  Created on: 2013/10/24
 *      Author: shu
 */

#include "align_main.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <tr1/memory>
#include <sstream>
#include <cstdio>
#include "protein_type.h"
#include "dna_type.h"
#include "logger.h"
#include "score_matrix_reader.h"
#include "reduced_alphabet_file_reader.h"
#include "aligner.h"
#include "aligner_gpu.h"

using namespace std;

AlignMain::AlignMain() {

}

AlignMain::~AlignMain() {

}

int AlignMain::Run(int argc, char* argv[]) {
	Logger *logger = Logger::GetInstance();
	logger->Log("searching...");

	AlignerCommon::AligningCommonParameters parameters;
	string queries_filename;
	string database_filename;
	string output_filename;

	//try {
	bool ret = BuildParameters(argc, argv, queries_filename, database_filename,
			output_filename, parameters);
	if (ret) {
#ifndef GPU
		Aligner aligner;
		aligner.Align(queries_filename, database_filename, output_filename,
				parameters);
#else
		if (parameters.number_gpus == 0) {
			Aligner aligner;
			aligner.Align(queries_filename, database_filename, output_filename,
					parameters);
		} else {
			AlignerGpu aligner;
			aligner.Align(queries_filename, database_filename, output_filename,
					parameters);
		}
#endif
		logger->Log("finished");
		return 0;
	}

	/*
	 } catch (exception &e) {
	 logger->ErrorLog(e.what());
	 }*/

	return 1;
}

bool AlignMain::BuildParameters(int argc, char* argv[], string &input_filename,
		string &database_filename, string &output_filename,
		Aligner::AligningParameters &parameters) {
	int c;
	extern char *optarg;
	extern int optind;
	optind = 1;
	string score_matrix_filename;
	Logger *logger = Logger::GetInstance();
	const string default_protein_matrix_name = "BLOSUM62";
	const string default_protein_matrix =
			"   A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V  B  Z  X  *\nA  4 -1 -2 -2  0 -1 -1  0 -2 -1 -1 -1 -1 -2 -1  1  0 -3 -2  0 -2 -1  0 -4\n R -1  5  0 -2 -3  1  0 -2  0 -3 -2  2 -1 -3 -2 -1 -1 -3 -2 -3 -1  0 -1 -4\n N -2  0  6  1 -3  0  0  0  1 -3 -3  0 -2 -3 -2  1  0 -4 -2 -3  3  0 -1 -4\n D -2 -2  1  6 -3  0  2 -1 -1 -3 -4 -1 -3 -3 -1  0 -1 -4 -3 -3  4  1 -1 -4\n C  0 -3 -3 -3  9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4\n Q -1  1  0  0 -3  5  2 -2  0 -3 -2  1  0 -3 -1  0 -1 -2 -1 -2  0  3 -1 -4\n E -1  0  0  2 -4  2  5 -2  0 -3 -3  1 -2 -3 -1  0 -1 -3 -2 -2  1  4 -1 -4\n G  0 -2  0 -1 -3 -2 -2  6 -2 -4 -4 -2 -3 -3 -2  0 -2 -2 -3 -3 -1 -2 -1 -4\n H -2  0  1 -1 -3  0  0 -2  8 -3 -3 -1 -2 -1 -2 -1 -2 -2  2 -3  0  0 -1 -4\n I -1 -3 -3 -3 -1 -3 -3 -4 -3  4  2 -3  1  0 -3 -2 -1 -3 -1  3 -3 -3 -1 -4\n L -1 -2 -3 -4 -1 -2 -3 -4 -3  2  4 -2  2  0 -3 -2 -1 -2 -1  1 -4 -3 -1 -4\n K -1  2  0 -1 -3  1  1 -2 -1 -3 -2  5 -1 -3 -1  0 -1 -3 -2 -2  0  1 -1 -4\n M -1 -1 -2 -3 -1  0 -2 -3 -2  1  2 -1  5  0 -2 -1 -1 -1 -1  1 -3 -1 -1 -4\n F -2 -3 -3 -3 -2 -3 -3 -3 -1  0  0 -3  0  6 -4 -2 -2  1  3 -1 -3 -3 -1 -4\n P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4  7 -1 -1 -4 -3 -2 -2 -1 -2 -4\n S  1 -1  1  0 -1  0  0  0 -1 -2 -2  0 -1 -2 -1  4  1 -3 -2 -2  0  0  0 -4\n T  0 -1  0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1  1  5 -2 -2  0 -1 -1  0 -4\n W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1  1 -4 -3 -2 11  2 -3 -4 -3 -2 -4\n Y -2 -2 -2 -3 -2 -1 -2 -3  2 -1 -1 -2 -1  3 -3 -2 -2  2  7 -1 -3 -2 -1 -4\n V  0 -3 -3 -3 -1 -2 -2 -3 -3  3  1 -2  1 -1 -2 -2  0 -3 -1  4 -3 -2 -1 -4\n B -2 -1  3  4 -3  0  1 -1  0 -3 -4  0 -3 -3 -2  0 -1 -4 -3 -3  4  1 -1 -4\n Z -1  0  0  1 -3  3  4 -2  0 -3 -3  1 -1 -3 -1  0 -1 -3 -2 -2  1  4 -1 -4\n X  0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2  0  0 -2 -1 -1 -1 -1 -1 -4\n * -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4  1\n";

	parameters.number_threads = 1;
	parameters.filter = true;
	parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<
			SequenceType>(new ProteinType());
	parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(
			new ProteinType());
	parameters.queries_chunk_size = 1 << 27;
	ScoreMatrixReader score_matrix_reader;
	vector<int> matrix;
	unsigned int number_letters;
	istringstream default_protein_score_matrix_is(default_protein_matrix);
	score_matrix_reader.Read(default_protein_score_matrix_is,
			*(parameters.aligning_sequence_type_ptr), matrix, number_letters);
	parameters.score_matrix = ScoreMatrix(default_protein_matrix_name,
			&matrix[0], number_letters);
	parameters.gap_open = 11;
	parameters.gap_extension = 1;
	parameters.number_gpus = -1;
	parameters.normalized_presearched_ungapped_extension_cutoff = 7.0;
	parameters.normalized_presearched_gapped_extension_trigger = 22.0;
	parameters.normalized_presearched_gapped_extension_cutoff = 15.0;
	parameters.normalized_result_gapped_extension_cutoff = 25.0;
	parameters.max_number_results = 10;
	parameters.max_number_one_subject_results = 1;
	while ((c = getopt(argc, argv, "a:b:d:F:g:h:l:i:o:q:t:v:")) != -1) {
		switch (c) {
		case 'a':
			parameters.number_threads = atoi(optarg);
			break;
		case 'b':
			parameters.max_number_results = atoi(optarg);
			break;
		case 'd':
			database_filename = optarg;
			break;
		case 'F':
			if (optarg[0] == 'T') {
				parameters.filter = true;
			} else if (optarg[0] == 'F') {
				parameters.filter = false;
			} else {
				logger->ErrorLog("invalid option, -F is T or F.");
				return false;
			}
			break;
		case 'g':
			parameters.number_gpus = atoi(optarg);
			break;
		case 'l':
			parameters.queries_chunk_size = atoi(optarg);
			break;
		case 'i':
			input_filename = optarg;
			break;
		case 'o':
			output_filename = optarg;
			break;
		case 'q':
			if (optarg[0] == 'p') {
				parameters.queries_file_sequence_type_ptr =
						std::tr1::shared_ptr<SequenceType>(new ProteinType());
			} else if (optarg[0] == 'd') {
				parameters.queries_file_sequence_type_ptr =
						std::tr1::shared_ptr<SequenceType>(new DnaType());
			} else {
				logger->ErrorLog("invalid option, -q is p or d.");
				return false;
			}
			break;
		case 't':
			if (optarg[0] == 'p') {
				parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<
						SequenceType>(new ProteinType());
			} else if (optarg[0] == 'd') {
				parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<
						SequenceType>(new DnaType());
			} else {
				logger->ErrorLog("invalid option, -q is p or d.");
				return false;
			}
			break;
		case 'v':
			parameters.max_number_one_subject_results = atoi(optarg);
			break;
		default:
			logger->ErrorLog("\nTry `ghostz --help' for more information.");
			return false;
		}
	}
	return true;
}

<commit_msg>add filecheck<commit_after>/*
 * align_main.cpp
 *
 *  Created on: 2013/10/24
 *      Author: shu
 */

#include "align_main.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <tr1/memory>
#include <sstream>
#include <cstdio>
#include "protein_type.h"
#include "dna_type.h"
#include "logger.h"
#include "score_matrix_reader.h"
#include "reduced_alphabet_file_reader.h"
#include "aligner.h"
#include "aligner_gpu.h"
#include <sys/stat.h>
using namespace std;

AlignMain::AlignMain() {

}

AlignMain::~AlignMain() {

}

int AlignMain::Run(int argc, char* argv[]) {
	Logger *logger = Logger::GetInstance();
	logger->Log("searching...");

	AlignerCommon::AligningCommonParameters parameters;
	string queries_filename;
	string database_filename;
	string output_filename;

	//try {
	bool ret = BuildParameters(argc, argv, queries_filename, database_filename,
			output_filename, parameters);
	if (ret) {
	  {//check query
	    struct stat st;
	    if(stat(queries_filename.c_str(),&st)==-1){
	      cerr<<"Query file does not exist."<<endl;
	      exit(1);
	    }
	  }
	  {//check database
	    struct stat st;
	    string inf_database= database_filename+".inf";
	    if(stat(inf_database.c_str(),&st)==-1){
	      cerr<<"Database file does not exist."<<endl;
	      exit(1);
	    }
	  }

#ifndef GPU
		Aligner aligner;
		aligner.Align(queries_filename, database_filename, output_filename,
				parameters);
#else
		if (parameters.number_gpus == 0) {
			Aligner aligner;
			aligner.Align(queries_filename, database_filename, output_filename,
					parameters);
		} else {
			AlignerGpu aligner;
			aligner.Align(queries_filename, database_filename, output_filename,
					parameters);
		}
#endif
		logger->Log("finished");
		return 0;
	}

	/*
	 } catch (exception &e) {
	 logger->ErrorLog(e.what());
	 }*/

	return 1;
}

bool AlignMain::BuildParameters(int argc, char* argv[], string &input_filename,
		string &database_filename, string &output_filename,
		Aligner::AligningParameters &parameters) {
	int c;
	extern char *optarg;
	extern int optind;
	optind = 1;
	string score_matrix_filename;
	Logger *logger = Logger::GetInstance();
	const string default_protein_matrix_name = "BLOSUM62";
	const string default_protein_matrix =
			"   A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V  B  Z  X  *\nA  4 -1 -2 -2  0 -1 -1  0 -2 -1 -1 -1 -1 -2 -1  1  0 -3 -2  0 -2 -1  0 -4\n R -1  5  0 -2 -3  1  0 -2  0 -3 -2  2 -1 -3 -2 -1 -1 -3 -2 -3 -1  0 -1 -4\n N -2  0  6  1 -3  0  0  0  1 -3 -3  0 -2 -3 -2  1  0 -4 -2 -3  3  0 -1 -4\n D -2 -2  1  6 -3  0  2 -1 -1 -3 -4 -1 -3 -3 -1  0 -1 -4 -3 -3  4  1 -1 -4\n C  0 -3 -3 -3  9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4\n Q -1  1  0  0 -3  5  2 -2  0 -3 -2  1  0 -3 -1  0 -1 -2 -1 -2  0  3 -1 -4\n E -1  0  0  2 -4  2  5 -2  0 -3 -3  1 -2 -3 -1  0 -1 -3 -2 -2  1  4 -1 -4\n G  0 -2  0 -1 -3 -2 -2  6 -2 -4 -4 -2 -3 -3 -2  0 -2 -2 -3 -3 -1 -2 -1 -4\n H -2  0  1 -1 -3  0  0 -2  8 -3 -3 -1 -2 -1 -2 -1 -2 -2  2 -3  0  0 -1 -4\n I -1 -3 -3 -3 -1 -3 -3 -4 -3  4  2 -3  1  0 -3 -2 -1 -3 -1  3 -3 -3 -1 -4\n L -1 -2 -3 -4 -1 -2 -3 -4 -3  2  4 -2  2  0 -3 -2 -1 -2 -1  1 -4 -3 -1 -4\n K -1  2  0 -1 -3  1  1 -2 -1 -3 -2  5 -1 -3 -1  0 -1 -3 -2 -2  0  1 -1 -4\n M -1 -1 -2 -3 -1  0 -2 -3 -2  1  2 -1  5  0 -2 -1 -1 -1 -1  1 -3 -1 -1 -4\n F -2 -3 -3 -3 -2 -3 -3 -3 -1  0  0 -3  0  6 -4 -2 -2  1  3 -1 -3 -3 -1 -4\n P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4  7 -1 -1 -4 -3 -2 -2 -1 -2 -4\n S  1 -1  1  0 -1  0  0  0 -1 -2 -2  0 -1 -2 -1  4  1 -3 -2 -2  0  0  0 -4\n T  0 -1  0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1  1  5 -2 -2  0 -1 -1  0 -4\n W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1  1 -4 -3 -2 11  2 -3 -4 -3 -2 -4\n Y -2 -2 -2 -3 -2 -1 -2 -3  2 -1 -1 -2 -1  3 -3 -2 -2  2  7 -1 -3 -2 -1 -4\n V  0 -3 -3 -3 -1 -2 -2 -3 -3  3  1 -2  1 -1 -2 -2  0 -3 -1  4 -3 -2 -1 -4\n B -2 -1  3  4 -3  0  1 -1  0 -3 -4  0 -3 -3 -2  0 -1 -4 -3 -3  4  1 -1 -4\n Z -1  0  0  1 -3  3  4 -2  0 -3 -3  1 -1 -3 -1  0 -1 -3 -2 -2  1  4 -1 -4\n X  0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2  0  0 -2 -1 -1 -1 -1 -1 -4\n * -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4  1\n";

	parameters.number_threads = 1;
	parameters.filter = true;
	parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<
			SequenceType>(new ProteinType());
	parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(
			new ProteinType());
	parameters.queries_chunk_size = 1 << 27;
	ScoreMatrixReader score_matrix_reader;
	vector<int> matrix;
	unsigned int number_letters;
	istringstream default_protein_score_matrix_is(default_protein_matrix);
	score_matrix_reader.Read(default_protein_score_matrix_is,
			*(parameters.aligning_sequence_type_ptr), matrix, number_letters);
	parameters.score_matrix = ScoreMatrix(default_protein_matrix_name,
			&matrix[0], number_letters);
	parameters.gap_open = 11;
	parameters.gap_extension = 1;
	parameters.number_gpus = -1;
	parameters.normalized_presearched_ungapped_extension_cutoff = 7.0;
	parameters.normalized_presearched_gapped_extension_trigger = 22.0;
	parameters.normalized_presearched_gapped_extension_cutoff = 15.0;
	parameters.normalized_result_gapped_extension_cutoff = 25.0;
	parameters.max_number_results = 10;
	parameters.max_number_one_subject_results = 1;
	while ((c = getopt(argc, argv, "a:b:d:F:g:h:l:i:o:q:t:v:")) != -1) {
		switch (c) {
		case 'a':
			parameters.number_threads = atoi(optarg);
			break;
		case 'b':
			parameters.max_number_results = atoi(optarg);
			break;
		case 'd':
			database_filename = optarg;
			break;
		case 'F':
			if (optarg[0] == 'T') {
				parameters.filter = true;
			} else if (optarg[0] == 'F') {
				parameters.filter = false;
			} else {
				logger->ErrorLog("invalid option, -F is T or F.");
				return false;
			}
			break;
		case 'g':
			parameters.number_gpus = atoi(optarg);
			break;
		case 'l':
			parameters.queries_chunk_size = atoi(optarg);
			break;
		case 'i':
			input_filename = optarg;
			break;
		case 'o':
			output_filename = optarg;
			break;
		case 'q':
			if (optarg[0] == 'p') {
				parameters.queries_file_sequence_type_ptr =
						std::tr1::shared_ptr<SequenceType>(new ProteinType());
			} else if (optarg[0] == 'd') {
				parameters.queries_file_sequence_type_ptr =
						std::tr1::shared_ptr<SequenceType>(new DnaType());
			} else {
				logger->ErrorLog("invalid option, -q is p or d.");
				return false;
			}
			break;
		case 't':
			if (optarg[0] == 'p') {
				parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<
						SequenceType>(new ProteinType());
			} else if (optarg[0] == 'd') {
				parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<
						SequenceType>(new DnaType());
			} else {
				logger->ErrorLog("invalid option, -q is p or d.");
				return false;
			}
			break;
		case 'v':
			parameters.max_number_one_subject_results = atoi(optarg);
			break;
		default:
			logger->ErrorLog("\nTry `ghostz --help' for more information.");
			return false;
		}
	}
	return true;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync
<commit_msg>Stop uploading unrecoverable errors to breakpad in preparation for beta.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/clear_browser_data_handler.h"

#include "base/basictypes.h"
#include "base/string16.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/common/notification_details.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"

ClearBrowserDataHandler::ClearBrowserDataHandler() : remover_(NULL) {
}

ClearBrowserDataHandler::~ClearBrowserDataHandler() {
  if (remover_)
    remover_->RemoveObserver(this);
}

void ClearBrowserDataHandler::Initialize() {
  clear_plugin_lso_data_enabled_.Init(prefs::kClearPluginLSODataEnabled,
                                      g_browser_process->local_state(),
                                      NULL);
}

void ClearBrowserDataHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);
  RegisterTitle(localized_strings, "clearBrowserDataOverlay",
                IDS_CLEAR_BROWSING_DATA_TITLE);

  localized_strings->SetString("clearBrowserDataLabel",
      l10n_util::GetStringUTF16(IDS_CLEAR_BROWSING_DATA_LABEL));
  localized_strings->SetString("deleteBrowsingHistoryCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_BROWSING_HISTORY_CHKBOX));
  localized_strings->SetString("deleteDownloadHistoryCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX));
  localized_strings->SetString("deleteCacheCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_CACHE_CHKBOX));
  localized_strings->SetString("deleteCookiesCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_COOKIES_CHKBOX));
  localized_strings->SetString("deleteCookiesFlashCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_COOKIES_FLASH_CHKBOX));
  localized_strings->SetString("deletePasswordsCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_PASSWORDS_CHKBOX));
  localized_strings->SetString("deleteFormDataCheckbox",
      l10n_util::GetStringUTF16(IDS_DEL_FORM_DATA_CHKBOX));
  localized_strings->SetString("clearBrowserDataCommit",
      l10n_util::GetStringUTF16(IDS_CLEAR_BROWSING_DATA_COMMIT));
  localized_strings->SetString("flashStorageSettings",
      l10n_util::GetStringUTF16(IDS_FLASH_STORAGE_SETTINGS));
  localized_strings->SetString("flash_storage_url",
      l10n_util::GetStringUTF16(IDS_FLASH_STORAGE_URL));
  localized_strings->SetString("clearDataDeleting",
      l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DELETING));

  ListValue* time_list = new ListValue;
  for (int i = 0; i < 5; i++) {
    string16 label_string;
    switch (i) {
      case 0:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_HOUR);
        break;
      case 1:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DAY);
        break;
      case 2:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_WEEK);
        break;
      case 3:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_4WEEKS);
        break;
      case 4:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_EVERYTHING);
        break;
    }
    ListValue* option = new ListValue();
    option->Append(Value::CreateIntegerValue(i));
    option->Append(Value::CreateStringValue(label_string));
    time_list->Append(option);
  }
  localized_strings->Set("clearBrowserDataTimeList", time_list);
}

void ClearBrowserDataHandler::RegisterMessages() {
  // Setup handlers specific to this panel.
  DCHECK(web_ui_);
  web_ui_->RegisterMessageCallback("performClearBrowserData",
      NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData));
}

void ClearBrowserDataHandler::HandleClearBrowserData(const ListValue* value) {
  Profile* profile = web_ui_->GetProfile();
  PrefService* prefs = profile->GetPrefs();

  int remove_mask = 0;
  if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory))
    remove_mask |= BrowsingDataRemover::REMOVE_HISTORY;
  if (prefs->GetBoolean(prefs::kDeleteDownloadHistory))
    remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (prefs->GetBoolean(prefs::kDeleteCache))
    remove_mask |= BrowsingDataRemover::REMOVE_CACHE;
  if (prefs->GetBoolean(prefs::kDeleteCookies)) {
    remove_mask |= BrowsingDataRemover::REMOVE_COOKIES;
    if (*clear_plugin_lso_data_enabled_)
      remove_mask |= BrowsingDataRemover::REMOVE_LSO_DATA;
  }
  if (prefs->GetBoolean(prefs::kDeletePasswords))
    remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (prefs->GetBoolean(prefs::kDeleteFormData))
    remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA;

  int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod);

  FundamentalValue state(true);
  web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.setClearingState",
                                  state);

  // If we are still observing a previous data remover, we need to stop
  // observing.
  if (remover_)
    remover_->RemoveObserver(this);

  // BrowsingDataRemover deletes itself when done.
  remover_ = new BrowsingDataRemover(profile,
      static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
      base::Time());
  remover_->AddObserver(this);
  remover_->Remove(remove_mask);
}

void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() {
  // No need to remove ourselves as an observer as BrowsingDataRemover deletes
  // itself after we return.
  remover_ = NULL;
  DCHECK(web_ui_);
  web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.doneClearing");
}
<commit_msg>webui/options: More localized string declaration cleanup.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/clear_browser_data_handler.h"

#include "base/basictypes.h"
#include "base/string16.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/common/notification_details.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"

ClearBrowserDataHandler::ClearBrowserDataHandler() : remover_(NULL) {
}

ClearBrowserDataHandler::~ClearBrowserDataHandler() {
  if (remover_)
    remover_->RemoveObserver(this);
}

void ClearBrowserDataHandler::Initialize() {
  clear_plugin_lso_data_enabled_.Init(prefs::kClearPluginLSODataEnabled,
                                      g_browser_process->local_state(),
                                      NULL);
}

void ClearBrowserDataHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static OptionsStringResource resources[] = {
    { "clearBrowserDataLabel", IDS_CLEAR_BROWSING_DATA_LABEL },
    { "deleteBrowsingHistoryCheckbox", IDS_DEL_BROWSING_HISTORY_CHKBOX },
    { "deleteDownloadHistoryCheckbox", IDS_DEL_DOWNLOAD_HISTORY_CHKBOX },
    { "deleteCacheCheckbox", IDS_DEL_CACHE_CHKBOX },
    { "deleteCookiesCheckbox", IDS_DEL_COOKIES_CHKBOX },
    { "deleteCookiesFlashCheckbox", IDS_DEL_COOKIES_FLASH_CHKBOX },
    { "deletePasswordsCheckbox", IDS_DEL_PASSWORDS_CHKBOX },
    { "deleteFormDataCheckbox", IDS_DEL_FORM_DATA_CHKBOX },
    { "clearBrowserDataCommit", IDS_CLEAR_BROWSING_DATA_COMMIT },
    { "flashStorageSettings", IDS_FLASH_STORAGE_SETTINGS },
    { "flash_storage_url", IDS_FLASH_STORAGE_URL },
    { "clearDataDeleting", IDS_CLEAR_DATA_DELETING },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "clearBrowserDataOverlay",
                IDS_CLEAR_BROWSING_DATA_TITLE);

  ListValue* time_list = new ListValue;
  for (int i = 0; i < 5; i++) {
    string16 label_string;
    switch (i) {
      case 0:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_HOUR);
        break;
      case 1:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DAY);
        break;
      case 2:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_WEEK);
        break;
      case 3:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_4WEEKS);
        break;
      case 4:
        label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_EVERYTHING);
        break;
    }
    ListValue* option = new ListValue();
    option->Append(Value::CreateIntegerValue(i));
    option->Append(Value::CreateStringValue(label_string));
    time_list->Append(option);
  }
  localized_strings->Set("clearBrowserDataTimeList", time_list);
}

void ClearBrowserDataHandler::RegisterMessages() {
  // Setup handlers specific to this panel.
  DCHECK(web_ui_);
  web_ui_->RegisterMessageCallback("performClearBrowserData",
      NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData));
}

void ClearBrowserDataHandler::HandleClearBrowserData(const ListValue* value) {
  Profile* profile = web_ui_->GetProfile();
  PrefService* prefs = profile->GetPrefs();

  int remove_mask = 0;
  if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory))
    remove_mask |= BrowsingDataRemover::REMOVE_HISTORY;
  if (prefs->GetBoolean(prefs::kDeleteDownloadHistory))
    remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (prefs->GetBoolean(prefs::kDeleteCache))
    remove_mask |= BrowsingDataRemover::REMOVE_CACHE;
  if (prefs->GetBoolean(prefs::kDeleteCookies)) {
    remove_mask |= BrowsingDataRemover::REMOVE_COOKIES;
    if (*clear_plugin_lso_data_enabled_)
      remove_mask |= BrowsingDataRemover::REMOVE_LSO_DATA;
  }
  if (prefs->GetBoolean(prefs::kDeletePasswords))
    remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (prefs->GetBoolean(prefs::kDeleteFormData))
    remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA;

  int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod);

  FundamentalValue state(true);
  web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.setClearingState",
                                  state);

  // If we are still observing a previous data remover, we need to stop
  // observing.
  if (remover_)
    remover_->RemoveObserver(this);

  // BrowsingDataRemover deletes itself when done.
  remover_ = new BrowsingDataRemover(profile,
      static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
      base::Time());
  remover_->AddObserver(this);
  remover_->Remove(remove_mask);
}

void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() {
  // No need to remove ourselves as an observer as BrowsingDataRemover deletes
  // itself after we return.
  remover_ = NULL;
  DCHECK(web_ui_);
  web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.doneClearing");
}
<|endoftext|>