Пример #1
0
bool OBJCTXT<_DOF6>::merge(const OBJCTXT &ctxt, const DOF6 &tf, std::map<typename OBJECT::Ptr,bool> &used_out, const BoundingBox::TransformedFoVBB &fov, const bool only_merge)
{
  Debug::Interface::get().sayTook("merge start");
  ROS_INFO("nextPoint ctr %d", (int)Slam_Surface::___CTR___);

  ++frames_;

  const size_t old = objs_.size();
  const float uncertainity = 0.01f;

  if(old>0 && (tf.getTranslationVariance()+tf.getRotationVariance())>0.3f )// && (tf.getSource1()->getTranslationVariance()+tf.getSource1()->getRotationVariance())>0.3 )
    return false;

  ROS_INFO("add ctxt %d", (int)used_out.size());
  std::cout<<tf<<"\n";

  Eigen::Vector3f edges[8];
  for(size_t i=0; i<objs_.size(); i++)
  {
    bool in=fov&objs_[i]->getNearestPoint();
    if(!in) {
      objs_[i]->getBB().get8Edges(edges);
      for(size_t i=0; i<8; i++)
        if(fov&edges[i]) {in=true; break;}
    }

    if(objs_[i]->getBB().extension()>2.5f)
      in=false;

    if( in ) {
#ifdef DEBUG_OUTPUT_
      ROS_INFO("FoV: in");
#endif
      objs_[i]->processed(); //TODO: check FoV
    }
    else {
#ifdef DEBUG_OUTPUT_
      ROS_INFO("FoV: out");
#endif
      objs_[i]->notProcessed(); //TODO: check FoV
    }
  }

  Debug::Interface::get().sayTook("merge 1");
  ROS_INFO("nextPoint ctr %d", (int)Slam_Surface::___CTR___);

  std::map<typename OBJECT::Ptr,std::vector<typename OBJECT::Ptr> > used;

  DOF6 tmp_link = tf.transpose();

  for(typename std::vector<SCOR>::const_iterator it = used_cors_.begin(); it!=used_cors_.end(); it++)
  {
    if(!it->a || !it->b || !it->used_) continue;

    //used_out[it->b] = true;

    typename OBJECT::Ptr o=it->b->makeShared();
    o->transform(tmp_link.getRotation(), tmp_link.getTranslation(),
                 tf.getRotationVariance()+uncertainity, tf.getTranslationVariance()+uncertainity);

    it->a->used();

    if(((*it->a) += *o)
    )
    {
      used_out[it->b] = true;

      used[it->b].push_back(it->a);
      ROS_INFO("update object");
    }
    else {
      //it->a->used();
      ROS_INFO("NOT update object");
    }
  }

  Debug::Interface::get().sayTook("merge 2");
  ROS_INFO("nextPoint ctr %d", (int)Slam_Surface::___CTR___);

  for(size_t i=0; i<ctxt.objs_.size(); i++)
  {
    typename std::map<typename OBJECT::Ptr,std::vector<typename OBJECT::Ptr> >::const_iterator it = used.find(ctxt.objs_[i]);

    if(used.end() == it)
    {
      if(used_out.find(ctxt.objs_[i])!=used_out.end())
        continue;

      if(!only_merge || (bb_.transform(tf.getRotation(), tf.getTranslation())&ctxt.objs_[i]->getNearestPoint()) ) //add to "first"/actual node or if its contained in this node
      {

        typename OBJECT::Ptr o=ctxt.objs_[i]->makeShared();
        o->transform(((Eigen::Matrix3f)tmp_link.getRotation()),tmp_link.getTranslation(),
                     tmp_link.getRotationVariance()+uncertainity, tmp_link.getTranslationVariance()+uncertainity);

        bool found = false;
        for(size_t j=0; j<objs_.size(); j++)
        {
          if( (objs_[j]->getBB()&(o->getBB()//.changeSize(0.8f)
          )) &&
          (((*objs_[j]) += *o) //&& objs_[j]->getData().isPlane()==o->getData().isPlane()
          ) )
          {
            ROS_INFO("found object");
            found = true;
            used_out[ctxt.objs_[i]] = true;
            used[ctxt.objs_[i]].push_back(objs_[j]);
          }
        }

        if(!found)
        {
          ROS_INFO("adding object");
          *this += o;
          used_out[ctxt.objs_[i]] = true;
        }
        else
          ROS_INFO("NOT adding object");
      }
    }

    it=used.find(ctxt.objs_[i]);
    if(used.end() != it && it->second.size()>1)
    {
      ROS_INFO("merging objects %d", (int)it->second.size());

      for(size_t k=1; k<it->second.size(); k++)
      {
        if(*(it->second)[0] += *(it->second)[k])
        {
          for(size_t j=0; j<objs_.size(); j++)
            if(objs_[j] == (it->second)[k] //&& objs_[j]->getData().isPlane()==(it->second)[k]->getData().isPlane()
            )
            {
              objs_.erase(objs_.begin() + j);
              --j;
              ROS_INFO("erase object");
            }
        }
      }
    }
  }
  Debug::Interface::get().sayTook("merge up2");

  if(enabled_all_merge_) {
    for(size_t i=0; i<objs_.size(); i++)
      for(size_t j=i+1; j<objs_.size(); j++)
      {
        int n=-1;
        bool b1, b2, b3;
        if( (b1=(objs_[i]->getBB().changeSize(0.7f)&(objs_[j]->getBB().setMinSize(0.05f).changeSize(0.7f))
        )) &&
        (b2=(objs_[j]->getBB().preassumption(objs_[i]->getData().getBB())>=std::cos(objs_[i]->getData().getBB().ratio()))) &&
        (((*objs_[i]).op_plus(*objs_[j],n)) //&& objs_[j]->getData().isPlane()==o->getData().isPlane()
        ) )
        {
          objs_.erase(objs_.begin() + j);
          --j;
          ROS_INFO("erase objectA23");
        }
        else if(n!=-1) {
          switch(n) {
            case 0:Debug::Interface::get().addArrow(objs_[i]->getNearestPoint(),objs_[j]->getNearestPoint(),255,0,0);break;
            case 1:Debug::Interface::get().addArrow(objs_[i]->getNearestPoint(),objs_[j]->getNearestPoint(),0,0,0);break;
            case 2:Debug::Interface::get().addArrow(objs_[i]->getNearestPoint(),objs_[j]->getNearestPoint(),0,0,255);break;
            case -1:
              if(!b1)
                Debug::Interface::get().addArrow(objs_[i]->getNearestPoint(),objs_[j]->getNearestPoint(),128,0,0);
              else if(!b2)
                Debug::Interface::get().addArrow(objs_[i]->getNearestPoint(),objs_[j]->getNearestPoint(),128,44,255);
              break;
          }
        }
      }
  }

  //  for(typename std::vector<SCOR>::const_iterator it = used_cors_.begin(); it!=used_cors_.end(); it++)
  //  {
  //    used_out[it->b] = true;
  //  }

  Debug::Interface::get().sayTook("merge up");
  ROS_INFO("nextPoint ctr %d", (int)Slam_Surface::___CTR___);

  update();

  Debug::Interface::get().sayTook("merge stop");
  ROS_INFO("nextPoint ctr %d", (int)Slam_Surface::___CTR___);
  Slam_Surface::___CTR___=0;

  return true;
}
void
AmclNode::laserReceived(const sensor_msgs::LaserScanConstPtr& laser_scan)
{
  last_laser_received_ts_ = ros::Time::now();
  if( map_ == NULL ) {
    return;
  }
  boost::recursive_mutex::scoped_lock lr(configuration_mutex_);
  int laser_index = -1;

  // Do we have the base->base_laser Tx yet?
  if(frame_to_laser_.find(laser_scan->header.frame_id) == frame_to_laser_.end())
  {
    ROS_DEBUG("Setting up laser %d (frame_id=%s)\n", (int)frame_to_laser_.size(), laser_scan->header.frame_id.c_str());
    lasers_.push_back(new AMCLLaser(*laser_));
    lasers_update_.push_back(true);
    laser_index = frame_to_laser_.size();

    tf::Stamped<tf::Pose> ident (tf::Transform(tf::createIdentityQuaternion(),
                                             tf::Vector3(0,0,0)),
                                 ros::Time(), laser_scan->header.frame_id);
    tf::Stamped<tf::Pose> laser_pose;
    try
    {
      this->tf_->transformPose(base_frame_id_, ident, laser_pose);
    }
    catch(tf::TransformException& e)
    {
      ROS_ERROR("Couldn't transform from %s to %s, "
                "even though the message notifier is in use",
                laser_scan->header.frame_id.c_str(),
                base_frame_id_.c_str());
      return;
    }

    pf_vector_t laser_pose_v;
    laser_pose_v.v[0] = laser_pose.getOrigin().x();
    laser_pose_v.v[1] = laser_pose.getOrigin().y();
    // laser mounting angle gets computed later -> set to 0 here!
    laser_pose_v.v[2] = 0;
    lasers_[laser_index]->SetLaserPose(laser_pose_v);
    ROS_DEBUG("Received laser's pose wrt robot: %.3f %.3f %.3f",
              laser_pose_v.v[0],
              laser_pose_v.v[1],
              laser_pose_v.v[2]);

    frame_to_laser_[laser_scan->header.frame_id] = laser_index;
  } else {
    // we have the laser pose, retrieve laser index
    laser_index = frame_to_laser_[laser_scan->header.frame_id];
  }

  // Where was the robot when this scan was taken?
  pf_vector_t pose;
  if(!getOdomPose(latest_odom_pose_, pose.v[0], pose.v[1], pose.v[2],
                  laser_scan->header.stamp, base_frame_id_))
  {
    ROS_ERROR("Couldn't determine robot's pose associated with laser scan");
    return;
  }


  pf_vector_t delta = pf_vector_zero();

  if(pf_init_)
  {
    // Compute change in pose
    //delta = pf_vector_coord_sub(pose, pf_odom_pose_);
    delta.v[0] = pose.v[0] - pf_odom_pose_.v[0];
    delta.v[1] = pose.v[1] - pf_odom_pose_.v[1];
    delta.v[2] = angle_diff(pose.v[2], pf_odom_pose_.v[2]);

    // See if we should update the filter
    bool update = fabs(delta.v[0]) > d_thresh_ ||
                  fabs(delta.v[1]) > d_thresh_ ||
                  fabs(delta.v[2]) > a_thresh_;
    update = update || m_force_update;
    m_force_update=false;

    // Set the laser update flags
    if(update)
      for(unsigned int i=0; i < lasers_update_.size(); i++)
        lasers_update_[i] = true;
  }

  bool force_publication = false;
  if(!pf_init_)
  {
    // Pose at last filter update
    pf_odom_pose_ = pose;

    // Filter is now initialized
    pf_init_ = true;

    // Should update sensor data
    for(unsigned int i=0; i < lasers_update_.size(); i++)
      lasers_update_[i] = true;

    force_publication = true;

    resample_count_ = 0;
  }
  // If the robot has moved, update the filter
  else if(pf_init_ && lasers_update_[laser_index])
  {
    //printf("pose\n");
    //pf_vector_fprintf(pose, stdout, "%.3f");

    AMCLOdomData odata;
    odata.pose = pose;
    // HACK
    // Modify the delta in the action data so the filter gets
    // updated correctly
    odata.delta = delta;

    // Use the action data to update the filter
    odom_->UpdateAction(pf_, (AMCLSensorData*)&odata);

    // Pose at last filter update
    //this->pf_odom_pose = pose;
  }

  bool resampled = false;
  // If the robot has moved, update the filter
  if(lasers_update_[laser_index])
  {
    AMCLLaserData ldata;
    ldata.sensor = lasers_[laser_index];
    ldata.range_count = laser_scan->ranges.size();

    // To account for lasers that are mounted upside-down, we determine the
    // min, max, and increment angles of the laser in the base frame.
    //
    // Construct min and max angles of laser, in the base_link frame.
    tf::Quaternion q;
    q.setRPY(0.0, 0.0, laser_scan->angle_min);
    tf::Stamped<tf::Quaternion> min_q(q, laser_scan->header.stamp,
                                      laser_scan->header.frame_id);
    q.setRPY(0.0, 0.0, laser_scan->angle_min + laser_scan->angle_increment);
    tf::Stamped<tf::Quaternion> inc_q(q, laser_scan->header.stamp,
                                      laser_scan->header.frame_id);
    try
    {
      tf_->transformQuaternion(base_frame_id_, min_q, min_q);
      tf_->transformQuaternion(base_frame_id_, inc_q, inc_q);
    }
    catch(tf::TransformException& e)
    {
      ROS_WARN("Unable to transform min/max laser angles into base frame: %s",
               e.what());
      return;
    }

    double angle_min = tf::getYaw(min_q);
    double angle_increment = tf::getYaw(inc_q) - angle_min;

    // wrapping angle to [-pi .. pi]
    angle_increment = fmod(angle_increment + 5*M_PI, 2*M_PI) - M_PI;

    ROS_DEBUG("Laser %d angles in base frame: min: %.3f inc: %.3f", laser_index, angle_min, angle_increment);

    // Apply range min/max thresholds, if the user supplied them
    if(laser_max_range_ > 0.0)
      ldata.range_max = std::min(laser_scan->range_max, (float)laser_max_range_);
    else
      ldata.range_max = laser_scan->range_max;
    double range_min;
    if(laser_min_range_ > 0.0)
      range_min = std::max(laser_scan->range_min, (float)laser_min_range_);
    else
      range_min = laser_scan->range_min;
    // The AMCLLaserData destructor will free this memory
    ldata.ranges = new double[ldata.range_count][2];
    ROS_ASSERT(ldata.ranges);
    for(int i=0;i<ldata.range_count;i++)
    {
      // amcl doesn't (yet) have a concept of min range.  So we'll map short
      // readings to max range.
      if(laser_scan->ranges[i] <= range_min)
        ldata.ranges[i][0] = ldata.range_max;
      else
        ldata.ranges[i][0] = laser_scan->ranges[i];
      // Compute bearing
      ldata.ranges[i][1] = angle_min +
              (i * angle_increment);
    }

    lasers_[laser_index]->UpdateSensor(pf_, (AMCLSensorData*)&ldata);

    lasers_update_[laser_index] = false;

    pf_odom_pose_ = pose;

    // Resample the particles
    if(!(++resample_count_ % resample_interval_))
    {
      pf_update_resample(pf_);
      resampled = true;
    }

    pf_sample_set_t* set = pf_->sets + pf_->current_set;
    ROS_DEBUG("Num samples: %d\n", set->sample_count);

    // Publish the resulting cloud
    // TODO: set maximum rate for publishing
    if (!m_force_update) {
      geometry_msgs::PoseArray cloud_msg;
      cloud_msg.header.stamp = ros::Time::now();
      cloud_msg.header.frame_id = global_frame_id_;
      cloud_msg.poses.resize(set->sample_count);
      for(int i=0;i<set->sample_count;i++)
      {
        tf::poseTFToMsg(tf::Pose(tf::createQuaternionFromYaw(set->samples[i].pose.v[2]),
                                 tf::Vector3(set->samples[i].pose.v[0],
                                           set->samples[i].pose.v[1], 0)),
                        cloud_msg.poses[i]);
      }
      particlecloud_pub_.publish(cloud_msg);
    }
  }

  if(resampled || force_publication)
  {
    if (!resampled)
    {
	    // re-compute the cluster statistics

        // Test!!
	    // pf_cluster_stats(pf_, pf_->sets);
        //
    }
    // Read out the current hypotheses
    double max_weight = 0.0;
    int max_weight_hyp = -1;
    std::vector<amcl_hyp_t> hyps;
    hyps.resize(pf_->sets[pf_->current_set].cluster_count);
    for(int hyp_count = 0;
        hyp_count < pf_->sets[pf_->current_set].cluster_count; hyp_count++)
    {
      double weight;
      pf_vector_t pose_mean;
      pf_matrix_t pose_cov;
      if (!pf_get_cluster_stats(pf_, hyp_count, &weight, &pose_mean, &pose_cov))
      {
        ROS_ERROR("Couldn't get stats on cluster %d", hyp_count);
        break;
      }

      hyps[hyp_count].weight = weight;
      hyps[hyp_count].pf_pose_mean = pose_mean;
      hyps[hyp_count].pf_pose_cov = pose_cov;

      if(hyps[hyp_count].weight > max_weight)
      {
        max_weight = hyps[hyp_count].weight;
        max_weight_hyp = hyp_count;
      }
    }

    if(max_weight > 0.0)
    {
      ROS_DEBUG("Max weight pose: %.3f %.3f %.3f",
                hyps[max_weight_hyp].pf_pose_mean.v[0],
                hyps[max_weight_hyp].pf_pose_mean.v[1],
                hyps[max_weight_hyp].pf_pose_mean.v[2]);

      /*
         puts("");
         pf_matrix_fprintf(hyps[max_weight_hyp].pf_pose_cov, stdout, "%6.3f");
         puts("");
       */

      geometry_msgs::PoseWithCovarianceStamped p;
      // Fill in the header
      p.header.frame_id = global_frame_id_;
      p.header.stamp = laser_scan->header.stamp;
      // Copy in the pose
      p.pose.pose.position.x = hyps[max_weight_hyp].pf_pose_mean.v[0];
      p.pose.pose.position.y = hyps[max_weight_hyp].pf_pose_mean.v[1];
      tf::quaternionTFToMsg(tf::createQuaternionFromYaw(hyps[max_weight_hyp].pf_pose_mean.v[2]),
                            p.pose.pose.orientation);
      // Copy in the covariance, converting from 3-D to 6-D
      pf_sample_set_t* set = pf_->sets + pf_->current_set;
      for(int i=0; i<2; i++)
      {
        for(int j=0; j<2; j++)
        {
          // Report the overall filter covariance, rather than the
          // covariance for the highest-weight cluster
          //p.covariance[6*i+j] = hyps[max_weight_hyp].pf_pose_cov.m[i][j];
          p.pose.covariance[6*i+j] = set->cov.m[i][j];
        }
      }
      // Report the overall filter covariance, rather than the
      // covariance for the highest-weight cluster
      //p.covariance[6*5+5] = hyps[max_weight_hyp].pf_pose_cov.m[2][2];
      p.pose.covariance[6*5+5] = set->cov.m[2][2];

      /*
         printf("cov:\n");
         for(int i=0; i<6; i++)
         {
         for(int j=0; j<6; j++)
         printf("%6.3f ", p.covariance[6*i+j]);
         puts("");
         }
       */

      pose_pub_.publish(p);
      last_published_pose = p;

      ROS_DEBUG("New pose: %6.3f %6.3f %6.3f",
               hyps[max_weight_hyp].pf_pose_mean.v[0],
               hyps[max_weight_hyp].pf_pose_mean.v[1],
               hyps[max_weight_hyp].pf_pose_mean.v[2]);

      // subtracting base to odom from map to base and send map to odom instead
      tf::Stamped<tf::Pose> odom_to_map;
      try
      {
        tf::Transform tmp_tf(tf::createQuaternionFromYaw(hyps[max_weight_hyp].pf_pose_mean.v[2]),
                             tf::Vector3(hyps[max_weight_hyp].pf_pose_mean.v[0],
                                         hyps[max_weight_hyp].pf_pose_mean.v[1],
                                         0.0));
        tf::Stamped<tf::Pose> tmp_tf_stamped (tmp_tf.inverse(),
                                              laser_scan->header.stamp,
                                              base_frame_id_);
        this->tf_->transformPose(odom_frame_id_,
                                 tmp_tf_stamped,
                                 odom_to_map);
      }
      catch(tf::TransformException)
      {
        ROS_DEBUG("Failed to subtract base to odom transform");
        return;
      }

      latest_tf_ = tf::Transform(tf::Quaternion(odom_to_map.getRotation()),
                                 tf::Point(odom_to_map.getOrigin()));
      latest_tf_valid_ = true;

      if (tf_broadcast_ == true)
      {
        // We want to send a transform that is good up until a
        // tolerance time so that odom can be used
        ros::Time transform_expiration = (laser_scan->header.stamp +
                                          transform_tolerance_);
        tf::StampedTransform tmp_tf_stamped(latest_tf_.inverse(),
                                            transform_expiration,
                                            global_frame_id_, odom_frame_id_);
        this->tfb_->sendTransform(tmp_tf_stamped);
        sent_first_transform_ = true;
      }
    }
    else
    {
      ROS_ERROR("No pose!");
    }
  }
  else if(latest_tf_valid_)
  {
    if (tf_broadcast_ == true)
    {
      // Nothing changed, so we'll just republish the last transform, to keep
      // everybody happy.
      ros::Time transform_expiration = (laser_scan->header.stamp +
                                        transform_tolerance_);
      tf::StampedTransform tmp_tf_stamped(latest_tf_.inverse(),
                                          transform_expiration,
                                          global_frame_id_, odom_frame_id_);
      this->tfb_->sendTransform(tmp_tf_stamped);
    }

    // Is it time to save our last pose to the param server
    ros::Time now = ros::Time::now();
    if((save_pose_period.toSec() > 0.0) &&
       (now - save_pose_last_time) >= save_pose_period)
    {
      this->savePoseToServer();
      save_pose_last_time = now;
    }
  }

}
void BundleAdjuster::adjustBundle(vector<CloudPoint>& pointcloud, 
								  Mat& cam_matrix,
								  const std::vector<std::vector<cv::KeyPoint> >& imgpts,
								  std::map<int ,cv::Matx34d>& Pmats
								) 
{
	int N = Pmats.size(), M = pointcloud.size(), K = Count2DMeasurements(pointcloud);
	
	cout << "N (cams) = " << N << " M (points) = " << M << " K (measurements) = " << K << endl;
	
#ifdef HAVE_SSBA
	/********************************************************************************/
	/*	Use SSBA-3.0 for sparse bundle adjustment									*/
	/********************************************************************************/
	
	
	StdDistortionFunction distortion;
	
	//conver camera intrinsics to BA datastructs
	Matrix3x3d KMat;
	makeIdentityMatrix(KMat);
	KMat[0][0] = cam_matrix.at<double>(0,0); //fx
	KMat[1][1] = cam_matrix.at<double>(1,1); //fy
	KMat[0][1] = cam_matrix.at<double>(0,1); //skew
	KMat[0][2] = cam_matrix.at<double>(0,2); //ppx
	KMat[1][2] = cam_matrix.at<double>(1,2); //ppy
	
	double const f0 = KMat[0][0];
	cout << "intrinsic before bundle = "; displayMatrix(KMat);
	Matrix3x3d Knorm = KMat;
	// Normalize the intrinsic to have unit focal length.
	scaleMatrixIP(1.0/f0, Knorm);
	Knorm[2][2] = 1.0;
	
	vector<int> pointIdFwdMap(M);
	map<int, int> pointIdBwdMap;
	
	//conver 3D point cloud to BA datastructs
	vector<Vector3d > Xs(M);
	for (int j = 0; j < M; ++j)
	{
		int pointId = j;
		Xs[j][0] = pointcloud[j].pt.x;
		Xs[j][1] = pointcloud[j].pt.y;
		Xs[j][2] = pointcloud[j].pt.z;
		pointIdFwdMap[j] = pointId;
		pointIdBwdMap.insert(make_pair(pointId, j));
	}
	cout << "Read the 3D points." << endl;
	
	vector<int> camIdFwdMap(N,-1);
	map<int, int> camIdBwdMap;
	
	//convert cameras to BA datastructs
	vector<CameraMatrix> cams(N);
	for (int i = 0; i < N; ++i)
	{
		int camId = i;
		Matrix3x3d R;
		Vector3d T;
		
		Matx34d& P = Pmats[i];
		
		R[0][0] = P(0,0); R[0][1] = P(0,1); R[0][2] = P(0,2); T[0] = P(0,3);
		R[1][0] = P(1,0); R[1][1] = P(1,1); R[1][2] = P(1,2); T[1] = P(1,3);
		R[2][0] = P(2,0); R[2][1] = P(2,1); R[2][2] = P(2,2); T[2] = P(2,3);
		
		camIdFwdMap[i] = camId;
		camIdBwdMap.insert(make_pair(camId, i));
		
		cams[i].setIntrinsic(Knorm);
		cams[i].setRotation(R);
		cams[i].setTranslation(T);
	}
	cout << "Read the cameras." << endl;
	
	vector<Vector2d > measurements;
	vector<int> correspondingView;
	vector<int> correspondingPoint;
	
	measurements.reserve(K);
	correspondingView.reserve(K);
	correspondingPoint.reserve(K);
	
	//convert 2D measurements to BA datastructs
	for (unsigned int k = 0; k < pointcloud.size(); ++k)
	{
		for (unsigned int i=0; i<pointcloud[k].imgpt_for_img.size(); i++) {
			if (pointcloud[k].imgpt_for_img[i] >= 0) {
				int view = i, point = k;
				Vector3d p, np;
				
				Point cvp = imgpts[i][pointcloud[k].imgpt_for_img[i]].pt;
				p[0] = cvp.x;
				p[1] = cvp.y;
				p[2] = 1.0;
				
				if (camIdBwdMap.find(view) != camIdBwdMap.end() &&
					pointIdBwdMap.find(point) != pointIdBwdMap.end())
				{
					// Normalize the measurements to match the unit focal length.
					scaleVectorIP(1.0/f0, p);
					measurements.push_back(Vector2d(p[0], p[1]));
					correspondingView.push_back(camIdBwdMap[view]);
					correspondingPoint.push_back(pointIdBwdMap[point]);
				}
			}
		}
	} // end for (k)
	
	K = measurements.size();
	
	cout << "Read " << K << " valid 2D measurements." << endl;
	
	showErrorStatistics(f0, distortion, cams, Xs, measurements, correspondingView, correspondingPoint);

//	V3D::optimizerVerbosenessLevel = 1;
	double const inlierThreshold = 2.0 / fabs(f0);
	
	Matrix3x3d K0 = cams[0].getIntrinsic();
	cout << "K0 = "; displayMatrix(K0);

	bool good_adjustment = false;
	{
		ScopedBundleExtrinsicNormalizer extNorm(cams, Xs);
		ScopedBundleIntrinsicNormalizer intNorm(cams,measurements,correspondingView);
		CommonInternalsMetricBundleOptimizer opt(V3D::FULL_BUNDLE_FOCAL_LENGTH_PP, inlierThreshold, K0, distortion, cams, Xs,
												 measurements, correspondingView, correspondingPoint);
//		StdMetricBundleOptimizer opt(inlierThreshold,cams,Xs,measurements,correspondingView,correspondingPoint);
		
		opt.tau = 1e-3;
		opt.maxIterations = 50;
		opt.minimize();
		
		cout << "optimizer status = " << opt.status << endl;
		
		good_adjustment = (opt.status != 2);
	}
	
	cout << "refined K = "; displayMatrix(K0);
	
	for (int i = 0; i < N; ++i) cams[i].setIntrinsic(K0);
	
	Matrix3x3d Knew = K0;
	scaleMatrixIP(f0, Knew);
	Knew[2][2] = 1.0;
	cout << "Knew = "; displayMatrix(Knew);
	
	showErrorStatistics(f0, distortion, cams, Xs, measurements, correspondingView, correspondingPoint);
	
	if(good_adjustment) { //good adjustment?
		
		//Vector3d mean(0.0, 0.0, 0.0);
		//for (unsigned int j = 0; j < Xs.size(); ++j) addVectorsIP(Xs[j], mean);
		//scaleVectorIP(1.0/Xs.size(), mean);
		//
		//vector<float> norms(Xs.size());
		//for (unsigned int j = 0; j < Xs.size(); ++j)
		//	norms[j] = distance_L2(Xs[j], mean);
		//
		//std::sort(norms.begin(), norms.end());
		//float distThr = norms[int(norms.size() * 0.9f)];
		//cout << "90% quantile distance: " << distThr << endl;
		
		//extract 3D points
		for (unsigned int j = 0; j < Xs.size(); ++j)
		{
			//if (distance_L2(Xs[j], mean) > 3*distThr) makeZeroVector(Xs[j]);
			
			pointcloud[j].pt.x = Xs[j][0];
			pointcloud[j].pt.y = Xs[j][1];
			pointcloud[j].pt.z = Xs[j][2];
		}
		
		//extract adjusted cameras
		for (int i = 0; i < N; ++i)
		{
			Matrix3x3d R = cams[i].getRotation();
			Vector3d T = cams[i].getTranslation();
			
			Matx34d P;
			P(0,0) = R[0][0]; P(0,1) = R[0][1]; P(0,2) = R[0][2]; P(0,3) = T[0];
			P(1,0) = R[1][0]; P(1,1) = R[1][1]; P(1,2) = R[1][2]; P(1,3) = T[1];
			P(2,0) = R[2][0]; P(2,1) = R[2][1]; P(2,2) = R[2][2]; P(2,3) = T[2];
			
			Pmats[i] = P;
		}
		

		//TODO: extract camera intrinsics
		cam_matrix.at<double>(0,0) = Knew[0][0];
		cam_matrix.at<double>(0,1) = Knew[0][1];
		cam_matrix.at<double>(0,2) = Knew[0][2];
		cam_matrix.at<double>(1,1) = Knew[1][1];
		cam_matrix.at<double>(1,2) = Knew[1][2];
	}
#else
	/********************************************************************************/
	/*	Use OpenCV contrib module for sparse bundle adjustment						*/
	/********************************************************************************/
	
	vector<Point3d> points(M);		// positions of points in global coordinate system (input and output)
	vector<vector<Point2d> > imagePoints(N,vector<Point2d>(M)); // projections of 3d points for every camera
	vector<vector<int> > visibility(N,vector<int>(M)); // visibility of 3d points for every camera
	vector<Mat> cameraMatrix(N);	// intrinsic matrices of all cameras (input and output)
	vector<Mat> R(N);				// rotation matrices of all cameras (input and output)
	vector<Mat> T(N);				// translation vector of all cameras (input and output)
	vector<Mat> distCoeffs(0);		// distortion coefficients of all cameras (input and output)
	
	int num_global_cams = pointcloud[0].imgpt_for_img.size();
	vector<int> global_cam_id_to_local_id(num_global_cams,-1);
	vector<int> local_cam_id_to_global_id(N,-1);
	int local_cam_count = 0;
	
	for (int pt3d = 0; pt3d < pointcloud.size(); pt3d++) {
		points[pt3d] = pointcloud[pt3d].pt;
//		imagePoints[pt3d].resize(N);
//		visibility[pt3d].resize(N);
		
		for (int pt3d_img = 0; pt3d_img < num_global_cams; pt3d_img++) {			
			if (pointcloud[pt3d].imgpt_for_img[pt3d_img] >= 0) {
				if (global_cam_id_to_local_id[pt3d_img] < 0) 
				{
					local_cam_id_to_global_id[local_cam_count] = pt3d_img;
					global_cam_id_to_local_id[pt3d_img] = local_cam_count++;
				}
				
				int local_cam_id = global_cam_id_to_local_id[pt3d_img];
				
				//2d point
				Point2d pt2d_for_pt3d_in_img = imgpts[pt3d_img][pointcloud[pt3d].imgpt_for_img[pt3d_img]].pt;
				imagePoints[local_cam_id][pt3d] = pt2d_for_pt3d_in_img;
				
				//visibility in this camera
				visibility[local_cam_id][pt3d] = 1;
			}
		}
		//2nd pass to mark not-founds
		for (int pt3d_img = 0; pt3d_img < num_global_cams; pt3d_img++) {			
			if (pointcloud[pt3d].imgpt_for_img[pt3d_img] < 0) {
				//see if this global camera is being used locally in the BA
				vector<int>::iterator local_it = std::find(local_cam_id_to_global_id.begin(),local_cam_id_to_global_id.end(),pt3d_img);
				if (local_it != local_cam_id_to_global_id.end()) {
					//this camera is used, and its local id is:
					int local_id = local_it - local_cam_id_to_global_id.begin();
					
					if (local_id >= 0) {
						//reproject
						Mat_<double> X = (Mat_<double>(4,1) << pointcloud[pt3d].pt.x, pointcloud[pt3d].pt.y, pointcloud[pt3d].pt.z, 1);
						Mat_<double> P(3,4,Pmats[pt3d_img].val);
						Mat_<double> KP = cam_matrix * P;
						Mat_<double> xPt_img = KP * X;				
						Point2d xPt_img_(xPt_img(0)/xPt_img(2),xPt_img(1)/xPt_img(2));
						
						imagePoints[local_id][pt3d] = xPt_img_; //TODO reproject point on this camera
						visibility[local_id][pt3d] = 0;
					}				
				}
			}
		}
	}
	for (int i=0; i<N; i++) {
		cameraMatrix[i] = cam_matrix;
		
		Matx34d& P = Pmats[local_cam_id_to_global_id[i]];
		
		Mat_<double> camR(3,3),camT(3,1);
		camR(0,0) = P(0,0); camR(0,1) = P(0,1); camR(0,2) = P(0,2); camT(0) = P(0,3);
		camR(1,0) = P(1,0); camR(1,1) = P(1,1); camR(1,2) = P(1,2); camT(1) = P(1,3);
		camR(2,0) = P(2,0); camR(2,1) = P(2,1); camR(2,2) = P(2,2); camT(2) = P(2,3);
		R[i] = camR;
		T[i] = camT;
		
//		distCoeffs[i] = Mat(); //::zeros(4,1, CV_64FC1);
	}
	
	cout << "Adjust bundle... \n";
	cv::LevMarqSparse::bundleAdjust(points,imagePoints,visibility,cameraMatrix,R,T,distCoeffs);
	cout << "DONE\n";
	
	//get the BAed points
	for (int pt3d = 0; pt3d < pointcloud.size(); pt3d++) {
		pointcloud[pt3d].pt = points[pt3d];
	}
	
	//get the BAed cameras
	for (int i = 0; i < N; ++i)
	{		
		Matx34d P;
		P(0,0) = R[i].at<double>(0,0); P(0,1) = R[i].at<double>(0,1); P(0,2) = R[i].at<double>(0,2); P(0,3) = T[i].at<double>(0);
		P(1,0) = R[i].at<double>(1,0); P(1,1) = R[i].at<double>(1,1); P(1,2) = R[i].at<double>(1,2); P(1,3) = T[i].at<double>(1);
		P(2,0) = R[i].at<double>(2,0); P(2,1) = R[i].at<double>(2,1); P(2,2) = R[i].at<double>(2,2); P(2,3) = T[i].at<double>(2);
		
		Pmats[local_cam_id_to_global_id[i]] = P;
	}	
	
#endif
}
Пример #4
0
void BinaryWriter::Write(std::string fname,
  std::map<std::string, std::string> parameters,
  double *positions,
  std::vector<IntField*> intFields,
  std::vector<DoubleField*> doubleFields,
  int dim,
  long numParticles
  )
{
  std::map<std::string, std::string>::iterator it;
  int progress = 1;
  int j = 0;
  int k = 0;
  double temp;

  if(numParticles == 0)
  {
    std::cout << "Error: Number of particles is 0, exiting" << std::endl;
    std::exit(1);
  }

  ProgressBar pb(intFields.size()+doubleFields.size()+parameters.size()+1,"Writing output");

  std::ofstream outfile((char*)fname.c_str(), std::ios::binary);
  if(outfile.is_open()) 
  {
    std::cout << "Writing to output file..." << std::flush;

    outfile <<  "# vtk DataFile Version 1.0" << std::endl;
    outfile <<  "vtk output" << std::endl;
    outfile <<  "BINARY" << std::endl;
    outfile <<  "DATASET POLYDATA" << std::endl;
    outfile <<  "POINTS " << numParticles << " double" << std::endl;
   for ( int i = 0; i<numParticles; i++ ) // All positions, duplicate this loop to write extra arrays
   {
    j = 3*i;

    // SwapEnd(positions[j]);
    // outfile.write((char*)&positions[j], sizeof(double));
    // SwapEnd(positions[j+1]);
    // outfile.write((char*)&positions[j+1], sizeof(double));
    // SwapEnd(positions[j+2]);
    // outfile.write((char*)&positions[j+2], sizeof(double));

    temp = std::stod(std::to_string(positions[j]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));
    temp = std::stod(std::to_string(positions[j+1]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));
    temp = std::stod(std::to_string(positions[j+2]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));

   }	

    outfile <<  std::endl; // NEW LINE

    outfile <<  "POINT_DATA " << numParticles << std::endl;

    outfile <<  "FIELD FieldData " << doubleFields.size()+intFields.size() << std::endl;

    for (long intf=0; intf < intFields.size(); intf++)
    {
      IntField *thisField = intFields[intf];

      outfile <<  thisField->name << " " << thisField->dim << " " << numParticles << " integer" << std::endl;

      for ( int i = 0; i<numParticles; i++ )
      {

        k= thisField->dim * i;

        for( int l=0; l<thisField->dim; l++)
        {

          SwapEnd(thisField->data[k+l]);
          outfile.write((char*)&thisField->data[k+l], sizeof(int));


        }
      }

      outfile <<  std::endl;
    }

    for (long intf=0; intf < doubleFields.size(); intf++)
    {
      DoubleField *thisField = doubleFields[intf];

      outfile <<  thisField->name << " " << thisField->dim << " " << numParticles << " double" << std::endl;

      for ( int i = 0; i<numParticles; i++ )
      {
        k= thisField->dim * i;
        for( int l=0; l<thisField->dim; l++)
        {

          SwapEnd(thisField->data[k+l]);
          outfile.write((char*)&thisField->data[k+l], sizeof(double));
        }
      }

      outfile <<  std::endl;
    }

    outfile.close();
  }


  std::string fname_par = fname.substr(0, fname.find(".", 0));
  fname_par = fname_par + ".par";

  std::ofstream outfile2((char*)fname_par.c_str(), std::ios::out);
  if(outfile2.is_open()) 
  {
    outfile2 <<  "numParticles=" << numParticles << std::endl; // Number of particles

    for ( it = parameters.begin(); it != parameters.end(); it++ ) // All the parameters defined int he python script
    {
      outfile2 <<  it->first << "=" << space2comma2(it->second) << std::endl;
    }

    outfile2.close();
  }

  pb.Finish();
}
Пример #5
0
void getProbsMorphs(std::map< int, std::map< int, std::string > >& sentMatrix, const lm::ngram::Model &model){

	std::vector<std::pair<float, int> > sortedOpts;

	for(int opt=0; opt<sentMatrix.size();opt++){
			//std::cerr << opt << ": ";
			std::map< int, std::string> sent = sentMatrix[opt];

			lm::ngram::State state(model.BeginSentenceState()), out_state;
			// no sentence context
			//lm::ngram::State state(model.NullContextState()), out_state;
			const lm::ngram::Vocabulary &vocab = model.GetVocabulary();


			lm::FullScoreReturn ret;
			float total =0.0;

			for(int i=0;i<sent.size();i++)
			{
				std::string w = sent[i];
				//std::cerr << "word : "<< w << "sent size: "<< sent.size() << "\n";
				// alternatives start with '/' and punctuation end with -PUNC-tag -> delete tag and leading '/'
				if(boost::starts_with(w,"/")){boost::erase_head(w,1);}

				if(boost::contains(w,"-PUNC-")){w = w.substr(0,1);}

				// proper names are marked with _NP -> use only NP for getting probs
				std::string newLem = "NP:";
				boost::regex re("^.+_NP:");
				if(boost::contains(w,"_NP:")){
					w  = boost::regex_replace(w, re, newLem);
				}

				// split word into morphs and get probabilities
				std::vector<std::string> strs;
				boost::split(strs,w,boost::is_any_of(":"));
				std::string lem = strs[0];
				std::vector<std::string> morphs;
				boost::regex morphrx("\\+[^\\+]+");
				if(strs.size() > 1){
					boost::find_all_regex(morphs, strs[1], morphrx);
				}

				//std::cerr << "lemma: " << lem << ", morph size " << morphs.size() <<"\n";
				/*for(int j=0;j<morphs.size();j++){
					std::cerr << "    morph: " << morphs[j] << "\n";
				}*/

				ret = model.FullScore(state, vocab.Index(lem), out_state);
				//std::cerr << "tested word " << w << " ,full p: " << ret.prob << " == " <<vocab.Index(w) << "\n";
				total += ret.prob;
				state = out_state;
				// get Probs for morphs
				for(int j=0;j<morphs.size();j++){
					ret = model.FullScore(state, vocab.Index(morphs[j]), out_state);
					total += ret.prob;
					//std::cerr << "tested morph " <<  morphs[j] << " ,p: " << ret.prob << " == " <<vocab.Index(morphs[j]) << "\n";
					state = out_state;
				}

			}
			ret = model.FullScore(state, model.GetVocabulary().EndSentence(), out_state);
			total += ret.prob;
			//std::cerr  <<  " total p: " << total <<'\n';
			std::pair<float,int> mypair (total, opt);
			sortedOpts.push_back(mypair);
		}
	 if(print_test_morph ==1){
		// std::cerr << "printing test morphs" << std::endl;
		 printTestMorphs(sentMatrix,sortedOpts);
	 }
	 else{
		 printSentsMorphGen(sentMatrix,sortedOpts);
		// std::cerr << "printing generated words" << std::endl;
	//std::cerr << "\n";
	 }
}
Пример #6
0
void Input::RunBefore() {

    if (inputLocked) return;
    lockCallbackMaps = true;

    for(int i = 0; i < thisState.numDevices; ++i) {
        if (thisState.devices[i])
            thisState.devices[i]->CopyInto(prevState.devices[i]); //TODO
    }


    // Set the focus to the display that has input focus (which
    // isnt necessarily the main display);
    std::vector<ViewID> dpys = ViewManager::ListViews();
    Display * focus = nullptr;
    for(uint32_t i = 0; i < dpys.size(); ++i) {
        focus = ViewManager::Get(dpys[i]);
        if (focus && focus->HasInputFocus()) {
            focusID = dpys[i];
            break;
        }
        focusID = ViewID();
        focus = nullptr;
    }
    manager->SetFocus(focus);


    bool updated = manager->HandleEvents();
    
    if (keyCallbackMap.size()) {
        for(auto i = keyCallbackMap.begin(); i != keyCallbackMap.end(); ++i) {
            if (Input::IsPressed(i->second))
                i->first->OnPress();
            if (Input::IsHeld(i->second))
                i->first->OnHold();
            if (Input::IsReleased(i->second))
                i->first->OnRelease();
        }
    }

    if (mouseCallbackMap.size()) {
        for(auto i = mouseCallbackMap.begin(); i != mouseCallbackMap.end(); ++i) {
            if (Input::IsPressed(i->second))
                i->first->OnPress();
            if (Input::IsHeld(i->second))
                i->first->OnHold();
            if (Input::IsReleased(i->second))
                i->first->OnRelease();
        }
    }
    
    /*
    // TODO: for pad support
    if (padCallbackMap.size()) {
        for(auto i = padCallbackMap.begin(); i != padCallbackMap.end(); ++i) {
            if (Input::IsPressed(i->second.first, i->second.second))
                i->first->OnPress();
            if (Input::IsHeld(i->second.first, i->second.second))
                i->first->OnHold();
            if (Input::IsReleased(i->second.first, i->second.second))
                i->first->OnRelease();
        }
    }
    */

    if (strCallbackMap.size()) {
        for(auto i = strCallbackMap.begin(); i != strCallbackMap.end(); ++i) {
            if (Input::IsPressed(i->second))
                i->first->OnPress();
            if (Input::IsHeld(i->second))
                i->first->OnHold();
            if (Input::IsReleased(i->second))
                i->first->OnRelease();
        }
    }
    lockCallbackMaps = false;
    for(uint32_t i = 0; i < deletedListeners.size(); ++i) {
        auto b = deletedListeners[i];
        auto pFind = padCallbackMap.find(b);
        if (pFind != padCallbackMap.end()) padCallbackMap.erase(pFind);

        auto mFind = mouseCallbackMap.find(b);
        if (mFind != mouseCallbackMap.end()) mouseCallbackMap.erase(mFind);

        auto kFind = keyCallbackMap.find(b);
        if (kFind != keyCallbackMap.end()) keyCallbackMap.erase(kFind);

        auto sFind = strCallbackMap.find(b);
        if (sFind != strCallbackMap.end()) strCallbackMap.erase(sFind);
    }
    deletedListeners.clear();

    if (updated) {
        getUnicode();
    }
}
Пример #7
0
 size_t operator()(const std::map<CborValue, CborValue> &map) const
 {
     return map.size();
 }
Пример #8
0
void AbsDef::construct_compose( FirstOrderModelAbs * m, TNode q, TNode n, AbsDef * f,
                                std::map< unsigned, AbsDef * >& children,
                                std::map< unsigned, int >& bchildren, std::map< unsigned, int >& vchildren,
                                std::vector< unsigned >& entry, std::vector< bool >& entry_def ) {
  if( n.getKind()==OR || n.getKind()==AND ){
    // short circuiting
    for( std::map< unsigned, AbsDef * >::iterator it = children.begin(); it != children.end(); ++it ){
      if( ( it->second->d_value==0 && n.getKind()==AND ) ||
          ( it->second->d_value==1 && n.getKind()==OR ) ){
        //std::cout << "Short circuit " << it->second->d_value << " " << entry.size() << "/" << q[0].getNumChildren() << std::endl;
        unsigned count = q[0].getNumChildren() - entry.size();
        for( unsigned i=0; i<count; i++ ){
          entry.push_back( m->d_domain[m->getVariable( q, entry.size() ).getType()] );
          entry_def.push_back( true );
        }
        construct_entry( entry, entry_def, it->second->d_value );
        for( unsigned i=0; i<count; i++ ){
          entry.pop_back();
          entry_def.pop_back();
        }
        return;
      }
    }
  }
  if( entry.size()==q[0].getNumChildren() ){
    if( f ){
      if( Trace.isOn("ambqi-check-debug2") ){
        for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
        Trace("ambqi-check-debug2") << "Evaluate uninterpreted function entry..." << std::endl;
      }
      //we are composing with an uninterpreted function
      std::vector< int > values;
      values.resize( n.getNumChildren(), val_none );
      for( std::map< unsigned, AbsDef * >::iterator it = children.begin(); it != children.end(); ++it ){
        values[it->first] = it->second->d_value;
      }
      for( std::map< unsigned, int >::iterator it = bchildren.begin(); it != bchildren.end(); ++it ){
        values[it->first] = it->second;
      }
      //look up value(s)
      f->apply_ucompose( m, q, entry, entry_def, values, vchildren, this );
    }else{
      bool incomplete = false;
      //we are composing with an interpreted function
      std::vector< TNode > values;
      values.resize( n.getNumChildren(), TNode::null() );
      for( std::map< unsigned, AbsDef * >::iterator it = children.begin(); it != children.end(); ++it ){
        Trace("ambqi-check-debug2") << "composite : " << it->first << " : " << it->second->d_value;
        if( it->second->d_value>=0 ){
          if( it->second->d_value>=(int)m->d_rep_set.d_type_reps[n[it->first].getType()].size() ){
            std::cout << it->second->d_value << " " << n[it->first] << " " << n[it->first].getType() << " " << m->d_rep_set.d_type_reps[n[it->first].getType()].size() << std::endl;
          }
          Assert( it->second->d_value<(int)m->d_rep_set.d_type_reps[n[it->first].getType()].size() );
          values[it->first] = m->d_rep_set.d_type_reps[n[it->first].getType()][it->second->d_value];
        }else{
          incomplete = true;
        }
        Trace("ambqi-check-debug2") << " ->> " << values[it->first] << std::endl;
      }
      for( std::map< unsigned, int >::iterator it = bchildren.begin(); it != bchildren.end(); ++it ){
        Trace("ambqi-check-debug2") << "   basic :  " << it->first << " : " << it->second;
        if( it->second>=0 ){
          Assert( it->second<(int)m->d_rep_set.d_type_reps[n[it->first].getType()].size() );
          values[it->first] = m->d_rep_set.d_type_reps[n[it->first].getType()][it->second];
        }else{
          incomplete = true;
        }
        Trace("ambqi-check-debug2") << " ->> " << values[it->first] << std::endl;
      }
      Assert( vchildren.empty() );
      if( incomplete ){
        Trace("ambqi-check-debug2") << "Construct incomplete entry." << std::endl;

        //if a child is unknown, we must return unknown
        construct_entry( entry, entry_def, val_unk );
      }else{
        if( Trace.isOn("ambqi-check-debug2") ){
          for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
          Trace("ambqi-check-debug2") << "Evaluate interpreted function entry ( ";
          for( unsigned i=0; i<values.size(); i++ ){
            Assert( !values[i].isNull() );
            Trace("ambqi-check-debug2") << values[i] << " ";
          }
          Trace("ambqi-check-debug2") << ")..." << std::endl;
        }
        //evaluate
        Node vv = NodeManager::currentNM()->mkNode( n.getKind(), values );
        vv = Rewriter::rewrite( vv );
        int v = m->getRepresentativeId( vv );
        construct_entry( entry, entry_def, v );
      }
    }
  }else{
    //take product of arguments
    TypeNode tn = m->getVariable( q, entry.size() ).getType();
    Assert( m->isValidType( tn ) );
    unsigned def = m->d_domain[tn];
    if( Trace.isOn("ambqi-check-debug2") ){
      for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
      Trace("ambqi-check-debug2") << "Take product of arguments" << std::endl;
    }
    for( std::map< unsigned, AbsDef * >::iterator it = children.begin(); it != children.end(); ++it ){
      Assert( it->second!=NULL );
      //process each child
      for( std::map< unsigned, AbsDef >::iterator itd = it->second->d_def.begin(); itd != it->second->d_def.end(); ++itd ){
        if( itd->first!=it->second->d_default && ( def & itd->first )!=0 ){
          def &= ~( itd->first );
          //process this value
          std::map< unsigned, AbsDef * > cchildren;
          for( std::map< unsigned, AbsDef * >::iterator it2 = children.begin(); it2 != children.end(); ++it2 ){
            Assert( it2->second!=NULL );
            std::map< unsigned, AbsDef >::iterator itdf = it2->second->d_def.find( itd->first );
            if( itdf!=it2->second->d_def.end() ){
              cchildren[it2->first] = &itdf->second;
            }else{
              Assert( it2->second->getDefault()!=NULL );
              cchildren[it2->first] = it2->second->getDefault();
            }
          }
          if( Trace.isOn("ambqi-check-debug2") ){
            for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
            Trace("ambqi-check-debug2") << "...process : ";
            debugPrintUInt("ambqi-check-debug2", m->d_rep_set.d_type_reps[tn].size(), itd->first );
            Trace("ambqi-check-debug2") << " " << children.size() << " " << cchildren.size() << std::endl;
          }
          entry.push_back( itd->first );
          entry_def.push_back( def==0 );
          construct_compose( m, q, n, f, cchildren, bchildren, vchildren, entry, entry_def );
          entry_def.pop_back();
          entry.pop_back();
          if( def==0 ){
            break;
          }
        }
      }
      if( def==0 ){
        break;
      }
    }
    if( def!=0 ){
      if( Trace.isOn("ambqi-check-debug2") ){
        for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
        Trace("ambqi-check-debug2") << "Make default argument" << std::endl;
      }
      std::map< unsigned, AbsDef * > cdchildren;
      for( std::map< unsigned, AbsDef * >::iterator it = children.begin(); it != children.end(); ++it ){
        Assert( it->second->getDefault()!=NULL );
        cdchildren[it->first] = it->second->getDefault();
      }
      if( Trace.isOn("ambqi-check-debug2") ){
        for( unsigned i=0; i<entry.size(); i++ ){ Trace("ambqi-check-debug2") << "  "; }
        Trace("ambqi-check-debug2") << "...process default : ";
        debugPrintUInt("ambqi-check-debug2", m->d_rep_set.getNumRepresentatives( tn ), def );
        Trace("ambqi-check-debug2") << " " << children.size() << " " << cdchildren.size() << std::endl;
      }
      entry.push_back( def );
      entry_def.push_back( true );
      construct_compose( m, q, n, f, cdchildren, bchildren, vchildren, entry, entry_def );
      entry_def.pop_back();
      entry.pop_back();
    }
  }
}
Пример #9
0
void CDeskBand::Rename(HWND hwnd, const std::map<std::wstring, ULONG>& items)
{
    // fill the list of selected file/foldernames
    m_filelist.clear();
    if (items.size() > 1)
    {
        for (std::map<std::wstring, ULONG>::const_iterator it = items.begin(); it != items.end(); ++it)
        {
            size_t pos = it->first.find_last_of('\\');
            if (pos != std::wstring::npos)
            {
                m_filelist.insert(it->first.substr(pos+1));
            }
        }
    }
    else if (items.size() == 1)
    {
        for (std::map<std::wstring, ULONG>::const_iterator it = items.begin(); it != items.end(); ++it)
        {
            size_t pos = it->first.find_last_of('\\');
            if (pos != std::wstring::npos)
            {
                m_filelist.insert(it->first.substr(pos+1));
            }
        }
    }
    else
    {
        // no files or only one file were selected.
        // use all files and folders in the current folder instead
        IServiceProvider * pServiceProvider = NULL;
        if (SUCCEEDED(GetIServiceProvider(hwnd, &pServiceProvider)))
        {
            IShellBrowser * pShellBrowser;
            if (SUCCEEDED(pServiceProvider->QueryService(SID_SShellBrowser, IID_IShellBrowser, (LPVOID*)&pShellBrowser)))
            {
                IShellView * pShellView;
                if (SUCCEEDED(pShellBrowser->QueryActiveShellView(&pShellView)))
                {
                    IFolderView * pFolderView;
                    if (SUCCEEDED(pShellView->QueryInterface(IID_IFolderView, (LPVOID*)&pFolderView)))
                    {
                        // hooray! we got the IFolderView interface!
                        // that means the explorer is active and well :)

                        // but we also need the IShellFolder interface because
                        // we need its GetCurFolder() method
                        IPersistFolder2 * pPersistFolder;
                        if (SUCCEEDED(pFolderView->GetFolder(IID_IPersistFolder2, (LPVOID*)&pPersistFolder)))
                        {
                            LPITEMIDLIST folderpidl;
                            if (SUCCEEDED(pPersistFolder->GetCurFolder(&folderpidl)))
                            {
                                // we have the current folder
                                TCHAR buf[MAX_PATH] = {0};
                                // find the path of the folder
                                if (SHGetPathFromIDList(folderpidl, buf))
                                {
                                    m_currentDirectory = buf;
                                }
                                // if m_currentDirectory is empty here, that means
                                // the current directory is a virtual path

                                IShellFolder * pShellFolder;
                                if (SUCCEEDED(pPersistFolder->QueryInterface(IID_IShellFolder, (LPVOID*)&pShellFolder)))
                                {
                                    // find all selected items
                                    IEnumIDList * pEnum;
                                    if (SUCCEEDED(pFolderView->Items(SVGIO_ALLVIEW, IID_IEnumIDList, (LPVOID*)&pEnum)))
                                    {
                                        LPITEMIDLIST pidl;
                                        WCHAR buf[MAX_PATH] = {0};
                                        ULONG fetched = 0;
                                        ULONG attribs = 0;
                                        do
                                        {
                                            pidl = NULL;
                                            if (SUCCEEDED(pEnum->Next(1, &pidl, &fetched)))
                                            {
                                                if (fetched)
                                                {
                                                    // the pidl we get here is relative!
                                                    attribs = SFGAO_FILESYSTEM|SFGAO_FOLDER;
                                                    if (SUCCEEDED(pShellFolder->GetAttributesOf(1, (LPCITEMIDLIST*)&pidl, &attribs)))
                                                    {
                                                        if (attribs & SFGAO_FILESYSTEM)
                                                        {
                                                            // create an absolute pidl with the pidl we got above
                                                            LPITEMIDLIST abspidl = CPidl::Append(folderpidl, pidl);
                                                            if (abspidl)
                                                            {
                                                                if (SHGetPathFromIDList(abspidl, buf))
                                                                {
                                                                    std::wstring p = buf;
                                                                    size_t pos = p.find_last_of('\\');
                                                                    if (pos != std::wstring::npos)
                                                                    {
                                                                        m_filelist.insert(p.substr(pos+1));
                                                                    }
                                                                }
                                                                CoTaskMemFree(abspidl);
                                                            }
                                                        }
                                                    }
                                                }
                                                CoTaskMemFree(pidl);
                                            }
                                        } while(fetched);
                                        pEnum->Release();
                                    }
                                    pShellFolder->Release();
                                }
                                CoTaskMemFree(folderpidl);
                            }
                            pPersistFolder->Release();
                        }
                        pFolderView->Release();
                    }
                    pShellView->Release();
                }
                pShellBrowser->Release();
            }
            pServiceProvider->Release();
        }
    }

    // show the rename dialog
    m_bDialogShown = TRUE;
    CRenameDlg dlg(hwnd);
    dlg.SetFileList(m_filelist);
    if (dlg.DoModal(g_hInst, IDD_RENAMEDLG, hwnd, NULL) == IDOK)
    {
        try
        {
            const std::tr1::wregex regCheck(dlg.GetMatchString(), dlg.GetRegexFlags());
            NumberReplaceHandler handler(dlg.GetReplaceString());

            // start renaming the files
            IServiceProvider * pServiceProvider = NULL;
            if (SUCCEEDED(GetIServiceProvider(hwnd, &pServiceProvider)))
            {
                IShellBrowser * pShellBrowser;
                if (SUCCEEDED(pServiceProvider->QueryService(SID_SShellBrowser, IID_IShellBrowser, (LPVOID*)&pShellBrowser)))
                {
                    IShellView * pShellView;
                    if (SUCCEEDED(pShellBrowser->QueryActiveShellView(&pShellView)))
                    {
                        IFolderView * pFolderView;
                        if (SUCCEEDED(pShellView->QueryInterface(IID_IFolderView, (LPVOID*)&pFolderView)))
                        {
                            // hooray! we got the IFolderView interface!
                            // that means the explorer is active and well :)

                            // but we also need the IShellFolder interface because
                            // we need its GetDisplayNameOf() method
                            IPersistFolder2 * pPersistFolder;
                            if (SUCCEEDED(pFolderView->GetFolder(IID_IPersistFolder2, (LPVOID*)&pPersistFolder)))
                            {
                                IShellFolder * pShellFolder;
                                if (SUCCEEDED(pPersistFolder->QueryInterface(IID_IShellFolder, (LPVOID*)&pShellFolder)))
                                {
                                    // our next task is to enumerate all the
                                    // items in the folder view and select those
                                    // which match the text in the edit control

                                    int nCount = 0;
                                    if (SUCCEEDED(pFolderView->ItemCount(SVGIO_ALLVIEW, &nCount)))
                                    {
                                        for (int i=0; i<nCount; ++i)
                                        {
                                            LPITEMIDLIST pidl;
                                            if (SUCCEEDED(pFolderView->Item(i, &pidl)))
                                            {
                                                STRRET str;
                                                if (SUCCEEDED(pShellFolder->GetDisplayNameOf(pidl,
                                                    // SHGDN_FORPARSING needed to get the extensions even if they're not shown
                                                    SHGDN_INFOLDER|SHGDN_FORPARSING,
                                                    &str)))
                                                {
                                                    TCHAR dispname[MAX_PATH];
                                                    StrRetToBuf(&str, pidl, dispname, _countof(dispname));

                                                    std::wstring replaced;
                                                    try
                                                    {
                                                        std::wstring sDispName = dispname;
                                                        // check if the item is in the list of selected items
                                                        if (m_filelist.find(sDispName) != m_filelist.end())
                                                        {
                                                            replaced = std::tr1::regex_replace(sDispName, regCheck, dlg.GetReplaceString());
                                                            replaced = handler.ReplaceCounters(replaced);
                                                            if (replaced.compare(sDispName))
                                                            {
                                                                ITEMIDLIST * pidlrenamed;
                                                                pShellFolder->SetNameOf(NULL, pidl, replaced.c_str(), SHGDN_FORPARSING|SHGDN_INFOLDER, &pidlrenamed);
                                                                // if the rename was successful, select the renamed item
                                                                if (pidlrenamed)
                                                                    pFolderView->SelectItem(i, SVSI_CHECK|SVSI_SELECT);
                                                            }
                                                        }
                                                    }
                                                    catch (std::exception)
                                                    {
                                                    }
                                                }
                                                CoTaskMemFree(pidl);
                                            }
                                        }
                                    }
                                    pShellFolder->Release();
                                }
                                pPersistFolder->Release();
                            }
                            pFolderView->Release();
                        }
                        pShellView->Release();
                    }
                    pShellBrowser->Release();
                }
                pServiceProvider->Release();
            }
        }
        catch (std::exception)
        {
        }
    }
    m_bDialogShown = FALSE;
}
Пример #10
0
MyGUI::KeyCode MYGUIManager::convertKeyCode( int key ) const
{
    static std::map<int, MyGUI::KeyCode> s_keyCodeMap;
    if ( !s_keyCodeMap.size() )
    {
		s_keyCodeMap['1'] = MyGUI::KeyCode::One;
		s_keyCodeMap['2'] = MyGUI::KeyCode::Two;
		s_keyCodeMap['3'] = MyGUI::KeyCode::Three;
		s_keyCodeMap['4'] = MyGUI::KeyCode::Four;
		s_keyCodeMap['5'] = MyGUI::KeyCode::Five;
		s_keyCodeMap['6'] = MyGUI::KeyCode::Six;
		s_keyCodeMap['7'] = MyGUI::KeyCode::Seven;
		s_keyCodeMap['8'] = MyGUI::KeyCode::Eight;
		s_keyCodeMap['9'] = MyGUI::KeyCode::Nine;
		s_keyCodeMap['0'] = MyGUI::KeyCode::Zero;

		s_keyCodeMap['a'] = MyGUI::KeyCode::A;
		s_keyCodeMap['b'] = MyGUI::KeyCode::B;
		s_keyCodeMap['c'] = MyGUI::KeyCode::C;
		s_keyCodeMap['d'] = MyGUI::KeyCode::D;
		s_keyCodeMap['e'] = MyGUI::KeyCode::E;
		s_keyCodeMap['f'] = MyGUI::KeyCode::F;
		s_keyCodeMap['g'] = MyGUI::KeyCode::G;
		s_keyCodeMap['h'] = MyGUI::KeyCode::H;
		s_keyCodeMap['i'] = MyGUI::KeyCode::I;
		s_keyCodeMap['j'] = MyGUI::KeyCode::J;
		s_keyCodeMap['k'] = MyGUI::KeyCode::K;
		s_keyCodeMap['l'] = MyGUI::KeyCode::L;
		s_keyCodeMap['m'] = MyGUI::KeyCode::M;
		s_keyCodeMap['n'] = MyGUI::KeyCode::N;
		s_keyCodeMap['o'] = MyGUI::KeyCode::O;
		s_keyCodeMap['p'] = MyGUI::KeyCode::P;
		s_keyCodeMap['q'] = MyGUI::KeyCode::Q;
		s_keyCodeMap['r'] = MyGUI::KeyCode::R;
		s_keyCodeMap['s'] = MyGUI::KeyCode::S;
		s_keyCodeMap['t'] = MyGUI::KeyCode::T;
		s_keyCodeMap['u'] = MyGUI::KeyCode::U;
		s_keyCodeMap['v'] = MyGUI::KeyCode::V;
		s_keyCodeMap['w'] = MyGUI::KeyCode::W;
		s_keyCodeMap['x'] = MyGUI::KeyCode::X;
		s_keyCodeMap['y'] = MyGUI::KeyCode::Y;
		s_keyCodeMap['z'] = MyGUI::KeyCode::Z;

		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F1] = MyGUI::KeyCode::F1;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F2] = MyGUI::KeyCode::F2;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F3] = MyGUI::KeyCode::F3;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F4] = MyGUI::KeyCode::F4;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F5] = MyGUI::KeyCode::F5;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F6] = MyGUI::KeyCode::F6;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F7] = MyGUI::KeyCode::F7;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F8] = MyGUI::KeyCode::F8;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F9] = MyGUI::KeyCode::F9;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_F10] = MyGUI::KeyCode::F10;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Escape] = MyGUI::KeyCode::Escape;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Tab] = MyGUI::KeyCode::Tab;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Return] = MyGUI::KeyCode::Return;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Space] = MyGUI::KeyCode::Space;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Minus] = MyGUI::KeyCode::Minus;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Equals] = MyGUI::KeyCode::Equals;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Backslash] = MyGUI::KeyCode::Backslash;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Slash] = MyGUI::KeyCode::Slash;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Semicolon] = MyGUI::KeyCode::Semicolon;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Comma] = MyGUI::KeyCode::Comma;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Period] = MyGUI::KeyCode::Period;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Insert] = MyGUI::KeyCode::Insert;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Delete] = MyGUI::KeyCode::Delete;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Home] = MyGUI::KeyCode::Home;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_End] = MyGUI::KeyCode::End;

		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Num_Lock] = MyGUI::KeyCode::NumLock;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Scroll_Lock] = MyGUI::KeyCode::ScrollLock;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Caps_Lock] = MyGUI::KeyCode::Capital;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_BackSpace] = MyGUI::KeyCode::Backspace;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Page_Down] = MyGUI::KeyCode::PageDown;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Page_Up] = MyGUI::KeyCode::PageUp;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Leftbracket] = MyGUI::KeyCode::LeftBracket;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Rightbracket] = MyGUI::KeyCode::RightBracket;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Quotedbl] = MyGUI::KeyCode::Apostrophe;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Left] = MyGUI::KeyCode::ArrowLeft;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Right] = MyGUI::KeyCode::ArrowRight;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Up] = MyGUI::KeyCode::ArrowUp;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Down] = MyGUI::KeyCode::ArrowDown;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_1] = MyGUI::KeyCode::Numpad1;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_2] = MyGUI::KeyCode::Numpad2;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_3] = MyGUI::KeyCode::Numpad3;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_4] = MyGUI::KeyCode::Numpad4;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_5] = MyGUI::KeyCode::Numpad5;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_6] = MyGUI::KeyCode::Numpad6;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_7] = MyGUI::KeyCode::Numpad7;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_8] = MyGUI::KeyCode::Numpad8;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_9] = MyGUI::KeyCode::Numpad9;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_0] = MyGUI::KeyCode::Numpad0;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_KP_Enter] = MyGUI::KeyCode::NumpadEnter;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Control_L] = MyGUI::KeyCode::LeftControl;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Control_R] = MyGUI::KeyCode::RightControl;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Alt_L] = MyGUI::KeyCode::LeftAlt;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Alt_R] = MyGUI::KeyCode::RightAlt;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Shift_L] = MyGUI::KeyCode::LeftShift;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Shift_R] = MyGUI::KeyCode::RightShift;
		s_keyCodeMap[osgGA::GUIEventAdapter::KEY_Num_Lock] = MyGUI::KeyCode::NumLock;
    }
    
    std::map<int, MyGUI::KeyCode>::iterator itr = s_keyCodeMap.find(key);
    if ( itr!=s_keyCodeMap.end() ) return itr->second;
    return MyGUI::KeyCode::None;
}
Пример #11
0
int read_matrix_and_rhs(char *file_name, int &n, int &nnz,
  std::map<unsigned int, MatrixEntry> &mat, std::map<unsigned int, double> &rhs, bool &cplx_2_real)
{
  FILE *file = fopen(file_name, "r");
  if (file == NULL)
    return TEST_FAILURE;

  enum EState {
    STATE_N,
    STATE_MATRIX,
    STATE_RHS,
    STATE_NNZ
  }
  state = STATE_N;

  // Variables needed to turn complex matrix into real.
  int k = 0;
  int l = 0;
  double* rhs_buffer = NULL;

  double buffer[4];
  char row[MAX_ROW_LEN];
  while (fgets(row, MAX_ROW_LEN, file) != NULL) {
    switch (state) {
    case STATE_N:
      if (read_n_nums(row, 1, buffer)) {
        if (cplx_2_real) {
          n = 2*((int) buffer[0]);
          rhs_buffer = new double[n];
          for (int i = 0; i < n; i++) {
            rhs_buffer[i] = 0.0;
          }
        }
        else
          n = (int) buffer[0];

        state = STATE_NNZ;
      }
      break;

    case STATE_NNZ:
      if (read_n_nums(row, 1, buffer))
        nnz = (int) buffer[0];

      state = STATE_MATRIX;
      break;

    case STATE_MATRIX:
      if (cplx_2_real) {
        if (read_n_nums(row, 4, buffer)) {
          mat.insert(std::pair<unsigned int, MatrixEntry>(k,   MatrixEntry ((int) buffer[0],     (int) buffer[1],     buffer[2])));
          mat.insert(std::pair<unsigned int, MatrixEntry>(k + 1, MatrixEntry ((int) buffer[0] + n/2, (int) buffer[1],     buffer[3])));
          mat.insert(std::pair<unsigned int, MatrixEntry>(k + 2*nnz, MatrixEntry ((int) buffer[0],     (int) buffer[1] + n/2, (-1)*buffer[3])));
          mat.insert(std::pair<unsigned int, MatrixEntry>(k + 2*nnz + 1, MatrixEntry ((int) buffer[0] + n/2, (int) buffer[1] + n/2, buffer[2])));
          k = k + 2;
        }
        else
          state = STATE_RHS;
      }
      else { // if cplx_2_real is false.
        if (read_n_nums(row, 3, buffer))
          mat[mat.size()] = (MatrixEntry ((int) buffer[0], (int) buffer[1], buffer[2]));

        else
          state = STATE_RHS;
      }
      break; //case STATE_MATRIX break.

    case STATE_RHS:
      if (cplx_2_real) {
        if (read_n_nums(row, 3, buffer)) {

          if (buffer[0] != (int) n/2-1) // Then this is not the last line in the input file
          {
            rhs[((int) buffer[0])] = (double) buffer[1];
            rhs_buffer[l] = (double) buffer[2];
            l = l + 1;
          }

          else // This is last line in the file.
          {
            // First read last line entry
            rhs[((int) buffer[0])] = (double) buffer[1];
            rhs_buffer[l] = (double) buffer[2];
            l = l + 1;
            // Take imaginary parts you saved,
            // and fill the rest of the rhs vector.
            for (int i = 0; i < l; i++)
            {
              rhs[rhs.size()] = rhs_buffer[i];
            }
          }
        }
      }
      else { // if cplx_2_real is false.
        if (read_n_nums(row, 2, buffer))
          rhs[(int) buffer[0]] = (double) buffer[1];
      }
      break;
    }
  }

  fclose(file);

  // Free memory
  delete [] rhs_buffer;

  // Clear pointer.
  rhs_buffer = NULL;

  return TEST_SUCCESS;
}
Пример #12
0
static std::string key2symbol(SDLKey k, Uint16 unicode) {
  if(0==s_key2symbol.size()) {
    s_key2symbol[SDLK_BACKSPACE]="BackSpace";
    s_key2symbol[SDLK_TAB]="Tab";
    s_key2symbol[SDLK_CLEAR]="Clear";
    s_key2symbol[SDLK_RETURN]="Return";
    s_key2symbol[SDLK_PAUSE]="Pause";
    s_key2symbol[SDLK_ESCAPE]="Escape";
    s_key2symbol[SDLK_SPACE]="Space";
    s_key2symbol[SDLK_EXCLAIM]="!";
    s_key2symbol[SDLK_QUOTEDBL]="\"";
    s_key2symbol[SDLK_HASH]="#";
    s_key2symbol[SDLK_DOLLAR]="$";
    s_key2symbol[SDLK_AMPERSAND]="&";
    s_key2symbol[SDLK_QUOTE]="'";
    s_key2symbol[SDLK_LEFTPAREN]="(";
    s_key2symbol[SDLK_RIGHTPAREN]=")";
    s_key2symbol[SDLK_ASTERISK]="*";
    s_key2symbol[SDLK_PLUS]="+";
    s_key2symbol[SDLK_COMMA]=",";
    s_key2symbol[SDLK_MINUS]="-";
    s_key2symbol[SDLK_PERIOD]=".";
    s_key2symbol[SDLK_SLASH]="/";
    s_key2symbol[SDLK_0]="0";
    s_key2symbol[SDLK_1]="1";
    s_key2symbol[SDLK_2]="2";
    s_key2symbol[SDLK_3]="3";
    s_key2symbol[SDLK_4]="4";
    s_key2symbol[SDLK_5]="5";
    s_key2symbol[SDLK_6]="6";
    s_key2symbol[SDLK_7]="7";
    s_key2symbol[SDLK_8]="8";
    s_key2symbol[SDLK_9]="9";
    s_key2symbol[SDLK_COLON]=":";
    s_key2symbol[SDLK_SEMICOLON]=";";
    s_key2symbol[SDLK_LESS]="<";
    s_key2symbol[SDLK_EQUALS]="=";
    s_key2symbol[SDLK_GREATER]=">";
    s_key2symbol[SDLK_QUESTION]="?";
    s_key2symbol[SDLK_AT]="@";
    s_key2symbol[SDLK_LEFTBRACKET]="]";
    s_key2symbol[SDLK_BACKSLASH]="\\";
    s_key2symbol[SDLK_RIGHTBRACKET]="]";
    s_key2symbol[SDLK_CARET]="^";
    s_key2symbol[SDLK_UNDERSCORE]="_";
    s_key2symbol[SDLK_BACKQUOTE]="`";
    s_key2symbol[SDLK_a]="a";
    s_key2symbol[SDLK_b]="b";
    s_key2symbol[SDLK_c]="c";
    s_key2symbol[SDLK_d]="d";
    s_key2symbol[SDLK_e]="e";
    s_key2symbol[SDLK_f]="f";
    s_key2symbol[SDLK_g]="g";
    s_key2symbol[SDLK_h]="h";
    s_key2symbol[SDLK_i]="i";
    s_key2symbol[SDLK_j]="j";
    s_key2symbol[SDLK_k]="k";
    s_key2symbol[SDLK_l]="l";
    s_key2symbol[SDLK_m]="m";
    s_key2symbol[SDLK_n]="n";
    s_key2symbol[SDLK_o]="o";
    s_key2symbol[SDLK_p]="p";
    s_key2symbol[SDLK_q]="q";
    s_key2symbol[SDLK_r]="r";
    s_key2symbol[SDLK_s]="s";
    s_key2symbol[SDLK_t]="t";
    s_key2symbol[SDLK_u]="u";
    s_key2symbol[SDLK_v]="v";
    s_key2symbol[SDLK_w]="w";
    s_key2symbol[SDLK_x]="x";
    s_key2symbol[SDLK_y]="y";
    s_key2symbol[SDLK_z]="z";
    s_key2symbol[SDLK_DELETE]="Delete";

    s_worldkey2symbol[SDLK_WORLD_0]="World_0";
    s_worldkey2symbol[SDLK_WORLD_1]="World_1";
    s_worldkey2symbol[SDLK_WORLD_2]="World_2";
    s_worldkey2symbol[SDLK_WORLD_3]="World_3";
    s_worldkey2symbol[SDLK_WORLD_4]="World_4";
    s_worldkey2symbol[SDLK_WORLD_5]="World_5";
    s_worldkey2symbol[SDLK_WORLD_6]="World_6";
    s_worldkey2symbol[SDLK_WORLD_7]="World_7";
    s_worldkey2symbol[SDLK_WORLD_8]="World_8";
    s_worldkey2symbol[SDLK_WORLD_9]="World_9";
    s_worldkey2symbol[SDLK_WORLD_10]="World_10";
    s_worldkey2symbol[SDLK_WORLD_11]="World_11";
    s_worldkey2symbol[SDLK_WORLD_12]="World_12";
    s_worldkey2symbol[SDLK_WORLD_13]="World_13";
    s_worldkey2symbol[SDLK_WORLD_14]="World_14";
    s_worldkey2symbol[SDLK_WORLD_15]="World_15";
    s_worldkey2symbol[SDLK_WORLD_16]="World_16";
    s_worldkey2symbol[SDLK_WORLD_17]="World_17";
    s_worldkey2symbol[SDLK_WORLD_18]="World_18";
    s_worldkey2symbol[SDLK_WORLD_19]="World_19";
    s_worldkey2symbol[SDLK_WORLD_20]="World_20";
    s_worldkey2symbol[SDLK_WORLD_21]="World_21";
    s_worldkey2symbol[SDLK_WORLD_22]="World_22";
    s_worldkey2symbol[SDLK_WORLD_23]="World_23";
    s_worldkey2symbol[SDLK_WORLD_24]="World_24";
    s_worldkey2symbol[SDLK_WORLD_25]="World_25";
    s_worldkey2symbol[SDLK_WORLD_26]="World_26";
    s_worldkey2symbol[SDLK_WORLD_27]="World_27";
    s_worldkey2symbol[SDLK_WORLD_28]="World_28";
    s_worldkey2symbol[SDLK_WORLD_29]="World_29";
    s_worldkey2symbol[SDLK_WORLD_30]="World_30";
    s_worldkey2symbol[SDLK_WORLD_31]="World_31";
    s_worldkey2symbol[SDLK_WORLD_32]="World_32";
    s_worldkey2symbol[SDLK_WORLD_33]="World_33";
    s_worldkey2symbol[SDLK_WORLD_34]="World_34";
    s_worldkey2symbol[SDLK_WORLD_35]="World_35";
    s_worldkey2symbol[SDLK_WORLD_36]="World_36";
    s_worldkey2symbol[SDLK_WORLD_37]="World_37";
    s_worldkey2symbol[SDLK_WORLD_38]="World_38";
    s_worldkey2symbol[SDLK_WORLD_39]="World_39";
    s_worldkey2symbol[SDLK_WORLD_40]="World_40";
    s_worldkey2symbol[SDLK_WORLD_41]="World_41";
    s_worldkey2symbol[SDLK_WORLD_42]="World_42";
    s_worldkey2symbol[SDLK_WORLD_43]="World_43";
    s_worldkey2symbol[SDLK_WORLD_44]="World_44";
    s_worldkey2symbol[SDLK_WORLD_45]="World_45";
    s_worldkey2symbol[SDLK_WORLD_46]="World_46";
    s_worldkey2symbol[SDLK_WORLD_47]="World_47";
    s_worldkey2symbol[SDLK_WORLD_48]="World_48";
    s_worldkey2symbol[SDLK_WORLD_49]="World_49";
    s_worldkey2symbol[SDLK_WORLD_50]="World_50";
    s_worldkey2symbol[SDLK_WORLD_51]="World_51";
    s_worldkey2symbol[SDLK_WORLD_52]="World_52";
    s_worldkey2symbol[SDLK_WORLD_53]="World_53";
    s_worldkey2symbol[SDLK_WORLD_54]="World_54";
    s_worldkey2symbol[SDLK_WORLD_55]="World_55";
    s_worldkey2symbol[SDLK_WORLD_56]="World_56";
    s_worldkey2symbol[SDLK_WORLD_57]="World_57";
    s_worldkey2symbol[SDLK_WORLD_58]="World_58";
    s_worldkey2symbol[SDLK_WORLD_59]="World_59";
    s_worldkey2symbol[SDLK_WORLD_60]="World_60";
    s_worldkey2symbol[SDLK_WORLD_61]="World_61";
    s_worldkey2symbol[SDLK_WORLD_62]="World_62";
    s_worldkey2symbol[SDLK_WORLD_63]="World_63";
    s_worldkey2symbol[SDLK_WORLD_64]="World_64";
    s_worldkey2symbol[SDLK_WORLD_65]="World_65";
    s_worldkey2symbol[SDLK_WORLD_66]="World_66";
    s_worldkey2symbol[SDLK_WORLD_67]="World_67";
    s_worldkey2symbol[SDLK_WORLD_68]="World_68";
    s_worldkey2symbol[SDLK_WORLD_69]="World_69";
    s_worldkey2symbol[SDLK_WORLD_70]="World_70";
    s_worldkey2symbol[SDLK_WORLD_71]="World_71";
    s_worldkey2symbol[SDLK_WORLD_72]="World_72";
    s_worldkey2symbol[SDLK_WORLD_73]="World_73";
    s_worldkey2symbol[SDLK_WORLD_74]="World_74";
    s_worldkey2symbol[SDLK_WORLD_75]="World_75";
    s_worldkey2symbol[SDLK_WORLD_76]="World_76";
    s_worldkey2symbol[SDLK_WORLD_77]="World_77";
    s_worldkey2symbol[SDLK_WORLD_78]="World_78";
    s_worldkey2symbol[SDLK_WORLD_79]="World_79";
    s_worldkey2symbol[SDLK_WORLD_80]="World_80";
    s_worldkey2symbol[SDLK_WORLD_81]="World_81";
    s_worldkey2symbol[SDLK_WORLD_82]="World_82";
    s_worldkey2symbol[SDLK_WORLD_83]="World_83";
    s_worldkey2symbol[SDLK_WORLD_84]="World_84";
    s_worldkey2symbol[SDLK_WORLD_85]="World_85";
    s_worldkey2symbol[SDLK_WORLD_86]="World_86";
    s_worldkey2symbol[SDLK_WORLD_87]="World_87";
    s_worldkey2symbol[SDLK_WORLD_88]="World_88";
    s_worldkey2symbol[SDLK_WORLD_89]="World_89";
    s_worldkey2symbol[SDLK_WORLD_90]="World_90";
    s_worldkey2symbol[SDLK_WORLD_91]="World_91";
    s_worldkey2symbol[SDLK_WORLD_92]="World_92";
    s_worldkey2symbol[SDLK_WORLD_93]="World_93";
    s_worldkey2symbol[SDLK_WORLD_94]="World_94";
    s_worldkey2symbol[SDLK_WORLD_95]="World_95";

    s_key2symbol[SDLK_KP0]="KeyPad_0";
    s_key2symbol[SDLK_KP1]="KeyPad_1";
    s_key2symbol[SDLK_KP2]="KeyPad_2";
    s_key2symbol[SDLK_KP3]="KeyPad_3";
    s_key2symbol[SDLK_KP4]="KeyPad_4";
    s_key2symbol[SDLK_KP5]="KeyPad_5";
    s_key2symbol[SDLK_KP6]="KeyPad_6";
    s_key2symbol[SDLK_KP7]="KeyPad_7";
    s_key2symbol[SDLK_KP8]="KeyPad_8";
    s_key2symbol[SDLK_KP9]="KeyPad_9";
    s_key2symbol[SDLK_KP_PERIOD]="KeyPad_.";
    s_key2symbol[SDLK_KP_DIVIDE]="KeyPad_/";
    s_key2symbol[SDLK_KP_MULTIPLY]="KeyPad_*";
    s_key2symbol[SDLK_KP_MINUS]="KeyPad_-";
    s_key2symbol[SDLK_KP_PLUS]="KeyPad_+";
    s_key2symbol[SDLK_KP_ENTER]="KeyPad_Enter";
    s_key2symbol[SDLK_KP_EQUALS]="KeyPad_=";
    s_key2symbol[SDLK_UP]="Up";
    s_key2symbol[SDLK_DOWN]="Down";
    s_key2symbol[SDLK_RIGHT]="Right";
    s_key2symbol[SDLK_LEFT]="Left";
    s_key2symbol[SDLK_INSERT]="Insert";
    s_key2symbol[SDLK_HOME]="Home";
    s_key2symbol[SDLK_END]="End";
    s_key2symbol[SDLK_PAGEUP]="Prior";
    s_key2symbol[SDLK_PAGEDOWN]="Next";
    s_key2symbol[SDLK_F1]="F1";
    s_key2symbol[SDLK_F2]="F2";
    s_key2symbol[SDLK_F3]="F3";
    s_key2symbol[SDLK_F4]="F4";
    s_key2symbol[SDLK_F5]="F5";
    s_key2symbol[SDLK_F6]="F6";
    s_key2symbol[SDLK_F7]="F7";
    s_key2symbol[SDLK_F8]="F8";
    s_key2symbol[SDLK_F9]="F9";
    s_key2symbol[SDLK_F10]="F10";
    s_key2symbol[SDLK_F11]="F11";
    s_key2symbol[SDLK_F12]="F12";
    s_key2symbol[SDLK_F13]="F13";
    s_key2symbol[SDLK_F14]="F14";
    s_key2symbol[SDLK_F15]="F15";
    s_key2symbol[SDLK_NUMLOCK]="Num_Lock";
    s_key2symbol[SDLK_CAPSLOCK]="Caps_Lock";
    s_key2symbol[SDLK_SCROLLOCK]="Scroll_Lock";
    s_key2symbol[SDLK_RSHIFT]="Shift_R";
    s_key2symbol[SDLK_LSHIFT]="Shift_L";
    s_key2symbol[SDLK_RCTRL]="Control_R";
    s_key2symbol[SDLK_LCTRL]="Control_L";
    s_key2symbol[SDLK_RALT]="AltGr";
    s_key2symbol[SDLK_LALT]="Alt_L";
    s_key2symbol[SDLK_RMETA]="Meta_R";
    s_key2symbol[SDLK_LMETA]="Meta_L";
    s_key2symbol[SDLK_LSUPER]="Super_L";
    s_key2symbol[SDLK_RSUPER]="Super_R";
    s_key2symbol[SDLK_MODE]="Mode";
    s_key2symbol[SDLK_COMPOSE]="Compose";
    s_key2symbol[SDLK_HELP]="Help";
    s_key2symbol[SDLK_PRINT]="Print";
    s_key2symbol[SDLK_SYSREQ]="SysRq";
    s_key2symbol[SDLK_BREAK]="Break";
    s_key2symbol[SDLK_MENU]="Menu";
    s_key2symbol[SDLK_POWER]="Power";
    s_key2symbol[SDLK_EURO]="€";
    s_key2symbol[SDLK_UNDO]="Undo";
  }
  std::string s = s_key2symbol[k];
  if(s.empty()) {
    if(unicode) {
      s_worldkey2symbol[k]=unicode;
      s=unicode;
    } else {
      s=s_worldkey2symbol[k];
    }
  }
  if(s.empty()) {
    s="<unknown>";
  }

  return s;
}
Пример #13
0
void NETWORK::load_network2(std::map<std::pair<std::string , std::string>,float> network, bool _weighted, int edges )
{
  // message file
  //std::string msg_file = _output + ".msg";
  //FILE *pMsg = NULL;

  // reset network
  for(int i=0; i<Order; i++)
    delete Nodes[i];
  Nodes.clear();
  Order = 0;
  Size = 0;

  // read edges
 // FILE_HANDLER f( _input_file.c_str(), "r" );
  //int edges = f.rows();
  //char line[1024] = {""};
  std::map<std::string, int> hash_table;
  int source, target;
  double weight;
  //char source_label[128] = {""};
  //char target_label[128] = {""};
  int source_id = 0;
  int target_id = 0;
  int columns;
  if (network.size() !=0)
  {
  std::map<std::pair<std::string , std::string>,float>::iterator it;
  for (std::map<std::pair<std::string , std::string>,float>::iterator it=network.begin(); it!=network.end(); ++it)
   {
    //f.get_text_line( line, sizeof(line) );
    //// check if line is valid (two or threee columns)
    //weight = 1.0;
    //columns = sscanf( line, "%s %s %lf", source_label, target_label, &weight );
    //if( (!_weighted && columns < 2) || (_weighted && columns != 3) )
    //{
    //  pMsg = fopen( msg_file.c_str(), "w" );
    //  fprintf( pMsg, "Error\nMissing column in line %i.", n+1 );
    //  fclose( pMsg );
    //  exit( 0 );
    //}
    std::pair< std::map<std::string, int>::iterator, bool> added;

    // source node
    added = hash_table.insert( std::pair<std::string, int>(std::string(it->first.first), (int)Nodes.size()) );
    if( added.second )
    {
      source_id = (int)Nodes.size();
	  add_node( it->first.first.c_str() );
    }
    else
      source_id = added.first->second;

    // target node
    added = hash_table.insert( std::pair<std::string, float>(std::string(it->first.second), (int)Nodes.size()) );
    if( added.second )
    {
      target_id = (int)Nodes.size();
      add_node( it->first.second.c_str());
    }
    else
      target_id = added.first->second;

    // add edge
    if( is_there_edge(source_id, target_id) )
    {
      weight += get_edge_weight( source_id, target_id );
      remove_edge(source_id, target_id);
      add_edge( source_id, target_id, abs(it->second)  );
    }
    else
      add_edge( source_id, target_id, abs(it->second) );
  }
}

  // if size limitazion is on, check network size
  //if( _size_limit != 0 && Order > _size_limit )
  //{
  //  pMsg = fopen( msg_file.c_str(), "w" );
  //  fprintf( pMsg, "Error\nNetwork is too large." );
  //  fclose( pMsg );
  //  exit(0);
  //}

  // normalize weights
  // uncomment this part for normal hierarchy computation
  // this commented out for no weight hierarchy computation
  /*int deg;
  double max_weight = Nodes[0]->outweight(0);
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
    {
      if( Nodes[i]->outweight(j) > max_weight )
        max_weight = Nodes[i]->outweight(j);
    }
  }
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
      Nodes[i]->setOutWeight( j, Nodes[i]->outweight(j)/max_weight );
  }*/

  // print network properties
  //pMsg = fopen( msg_file.c_str(), "w" );
  //fprintf( pMsg, "Success\n%i\n%i", Order, Size );
  //fclose( pMsg );
}
Пример #14
0
BOOL CBitmap::LoadBitmap(LPCTSTR lpszResourceName)
{
    if (g_mapResBitMaps.size() == 0)
    {
        QString resPath = QDir::currentPath();
        QDomDocument doc;
        QFile file(resPath + "\\Resources.xml");
        int errorLine, errorColumn;
        QString errorMsg;

        if (!file.open(QIODevice::ReadOnly))
        {
           return FALSE;
        }

        if (!doc.setContent(&file, &errorMsg, &errorLine, &errorColumn))
        {
            file.close();
            return FALSE;
        }

        file.close();

        /*
         *
         *<BITMAPTABLE>
        <BITMAP IDSTR="IDR_MAINFRAME" ID="128" NAME="Toolbar.bmp"/>
      </BITMAPTABLE>
      */

        QDomElement docElem = doc.documentElement();

        QDomElement bitmapTable = docElem.firstChildElement("BITMAPTABLE");

        while(!bitmapTable.isNull())
        {
            QDomElement bitmapTableItem = bitmapTable.firstChildElement("BITMAP");

            while(!bitmapTableItem.isNull())
            {
                QDomNamedNodeMap attrs = bitmapTableItem.attributes();

                QDomNode idAttr = attrs.namedItem("ID");
                QDomNode idStrAttr = attrs.namedItem("IDSTR");
                QDomNode nameAttr = attrs.namedItem("NAME");

                QString resPath = QDir::currentPath();
                QString imagePath = resPath + "\\" + nameAttr.nodeValue();
                QPixmap *image = new QPixmap;

                if (image->load(imagePath))
                {
                    if (!idAttr.isNull())
                    {
                        g_mapResBitMaps[idAttr.nodeValue()] = image;
                    }
                    else
                    if (!idStrAttr.isNull())
                    {
                        g_mapResBitMaps[idStrAttr.nodeValue()] = image;
                    }
                }
                else
                {
                    delete image;
                }

                bitmapTableItem = bitmapTableItem.nextSiblingElement("BITMAP");
            }

            bitmapTable = bitmapTable.nextSiblingElement("BITMAPTABLE");
        }
    }

    if (mBitMap)
    {
        QPixmap *bitmap = (QPixmap *)mBitMap;
        delete bitmap;
    }

    if (g_mapResBitMaps.find(QString::fromWCharArray(lpszResourceName)) != g_mapResBitMaps.end())
    {
        mBitMap = new QPixmap(*(g_mapResBitMaps[QString::fromWCharArray(lpszResourceName)]));
    }

    return mBitMap != NULL;
}
void OpenCLConfig::apply(std::string &_devTy, std::map<cl_device_id, cl_context>& _devices)
{
    _devicesPtr=&_devices;
    //Auto-enable CUDA if it was not done before
   if (!_enableOpenCL) {
       //ompss_uses_opencl pointer will be null (is extern) if the compiler did not fill it
      _enableOpenCL=((&ompss_uses_opencl)!=0);
   }
   if( _forceDisableOpenCL || !_enableOpenCL ) 
     return;

   cl_int errCode;

   // Get the number of available platforms.
   cl_uint numPlats;
   if( clGetPlatformIDs( 0, NULL, &numPlats ) != CL_SUCCESS )
      fatal0( "Cannot detect the number of available OpenCL platforms" );

   if ( numPlats == 0 )
      fatal0( "No OpenCL platform available" );

   // Read all platforms.
   cl_platform_id *plats = new cl_platform_id[numPlats];
   if( clGetPlatformIDs( numPlats, plats, NULL ) != CL_SUCCESS )
      fatal0( "Cannot load OpenCL platforms" );

   // Is platform available?
   if( !numPlats )
      fatal0( "No OpenCL platform available" );

   std::vector<cl_platform_id> _plats;
   // Save platforms.
   _plats.assign(plats, plats + numPlats);
   delete [] plats;

   cl_device_type devTy;

   // Parse the requested device type.
   if( _devTy == "" || _devTy == "ALL" )
      devTy = CL_DEVICE_TYPE_ALL;
   else if( _devTy == "CPU" )
      devTy = CL_DEVICE_TYPE_CPU;
   else if( _devTy == "GPU" )
      devTy = CL_DEVICE_TYPE_GPU;
   else if( _devTy == "ACCELERATOR" )
      devTy = CL_DEVICE_TYPE_ACCELERATOR;
   else
      fatal0( "Unable to parse device type" );

   // Read all devices.
   for( std::vector<cl_platform_id>::iterator i = _plats.begin(),
                                              e = _plats.end();
                                              i != e;
                                              ++i ) {
      #ifndef NANOS_DISABLE_ALLOCATOR
         char buffer[200];
         clGetPlatformInfo(*i, CL_PLATFORM_VENDOR, 200, buffer, NULL);
         if (std::string(buffer)=="Intel(R) Corporation" || std::string(buffer)=="ARM"){
            debug0("Intel or ARM OpenCL don't work correctly when using nanox allocator, "
                    "please configure and reinstall nanox with --disable-allocator in case you want to use it, skipping Intel OpenCL devices");
            continue;
         }
      #endif
      // Get the number of available devices.
      cl_uint numDevices;
      errCode = clGetDeviceIDs( *i, devTy, 0, NULL, &numDevices );

      if( errCode != CL_SUCCESS )
         continue;

      // Read all matching devices.
      cl_device_id *devs = new cl_device_id[numDevices];
      errCode = clGetDeviceIDs( *i, devTy, numDevices, devs, NULL );
      if( errCode != CL_SUCCESS )
         continue;

      int devicesToUse=0;   
      cl_device_id *avaiableDevs = new cl_device_id[numDevices];
      // Get all avaiable devices
      for( cl_device_id *j = devs, *f = devs + numDevices; j != f; ++j )
      {
         cl_bool available;

         errCode = clGetDeviceInfo( *j,
                                      CL_DEVICE_AVAILABLE,
                                      sizeof( cl_bool ),
                                      &available,
                                      NULL );
         if( errCode != CL_SUCCESS )
           continue;

         if( available && _devices.size()+devicesToUse<_devNum){
             avaiableDevs[devicesToUse++]=*j;
         }
      }
      
      cl_context_properties props[] =
      {  CL_CONTEXT_PLATFORM,
         reinterpret_cast<cl_context_properties>(*i),
         0
      };

      //Cant instrument here
      //NANOS_OPENCL_CREATE_IN_OCL_RUNTIME_EVENT( ext::NANOS_OPENCL_CREATE_CONTEXT_EVENT );
      cl_context ctx = clCreateContext( props, devicesToUse, avaiableDevs, NULL, NULL, &errCode );
      //NANOS_OPENCL_CLOSE_IN_OCL_RUNTIME_EVENT;
      // Put all available devices inside the vector.
      for( cl_device_id *j = avaiableDevs, *f = avaiableDevs + devicesToUse; j != f; ++j )
      {
          _devices.insert(std::make_pair( *j , ctx) );
      }
	  _currNumDevices=_devices.size();

      delete [] devs;
   }
}
Пример #16
0
void load_interface_lane_map()
{
    SWSS_LOG_ENTER();

    if (g_interface_lane_map_file == NULL)
    {
        SWSS_LOG_NOTICE("no interface lane map");
        return;
    }

    std::ifstream lanemap(g_interface_lane_map_file);

    if (!lanemap.is_open())
    {
        SWSS_LOG_ERROR("failed to open lane map file: %s", g_interface_lane_map_file);
        return;
    }

    std::string line;

    while(getline(lanemap, line))
    {
        if (line.size() > 0 && (line[0] == '#' || line[0] == ';'))
        {
            continue;
        }

        auto tokens = swss::tokenize(line, ':');

        if (tokens.size() != 2)
        {
            SWSS_LOG_ERROR("expected 2 tokens in line %s, got %zu", line.c_str(), tokens.size());
            continue;
        }

        auto ifname = tokens.at(0);
        auto lanes = tokens.at(1);

        if (!check_ifname(ifname))
        {
            continue;
        }

        if (g_ifname_to_lanes.find(ifname) != g_ifname_to_lanes.end())
        {
            SWSS_LOG_ERROR("interface %s was already defined", ifname.c_str());
            continue;
        }

        tokens = swss::tokenize(lanes,',');

        size_t n = tokens.size();

        if (n != 1 && n != 2 && n != 4)
        {
            SWSS_LOG_ERROR("invalid number of lanes (%zu) assigned to interface %s", n, ifname.c_str());
            continue;
        }

        std::vector<uint32_t> lanevec;

        for (auto l: tokens)
        {
            uint32_t lanenumber;
            if (sscanf(l.c_str(), "%u", &lanenumber) != 1)
            {
                SWSS_LOG_ERROR("failed to parse lane number: %s", l.c_str());
                continue;
            }

            if (g_lane_to_ifname.find(lanenumber) != g_lane_to_ifname.end())
            {
                SWSS_LOG_ERROR("lane number %u used on %s was already defined on %s",
                        lanenumber,
                        ifname.c_str(),
                        g_lane_to_ifname.at(lanenumber).c_str());
                continue;
            }

            lanevec.push_back(lanenumber);
            g_lane_order.push_back(lanenumber);

            g_lane_to_ifname[lanenumber] = ifname;
        }

        g_ifname_to_lanes[ifname] = lanevec;
        g_laneMap.push_back(lanevec);
    }

    SWSS_LOG_NOTICE("loaded %zu lanes and %zu interfaces", g_lane_to_ifname.size(), g_ifname_to_lanes.size());
}
Пример #17
0
int NumberOfKnownResidues()
{
    InitializeAtomicPropertyMaps();

    return residuename_to_number.size();
}
Пример #18
0
/**
 * Make a map of the conversion factors between tof and D-spacing
 * for all pixel IDs in a workspace.
 * map vulcan should contain the module/module and stack/stack offset
 *
 * @param vulcan :: map between detector ID and vulcan correction factor.
 * @param offsetsWS :: OffsetsWorkspace to be filled.
 */
void LoadDspacemap::CalculateOffsetsFromVulcanFactors(
    std::map<detid_t, double> &vulcan,
    Mantid::DataObjects::OffsetsWorkspace_sptr offsetsWS) {
  // Get a pointer to the instrument contained in the workspace
  // At this point, instrument VULCAN has been created?
  Instrument_const_sptr instrument = offsetsWS->getInstrument();

  g_log.notice() << "Name of instrument = " << instrument->getName()
                 << std::endl;
  g_log.notice() << "Input map (dict):  size = " << vulcan.size() << std::endl;

  // To get all the detector ID's
  detid2det_map allDetectors;
  instrument->getDetectors(allDetectors);

  detid2det_map::const_iterator it;
  int numfinds = 0;
  g_log.notice() << "Input number of detectors = " << allDetectors.size()
                 << std::endl;

  // Get detector information
  double l1, beamline_norm;
  Kernel::V3D beamline, samplePos;
  instrument->getInstrumentParameters(l1, beamline, beamline_norm, samplePos);

  /*** A survey of parent detector
  std::map<detid_t, bool> parents;
  for (it = allDetectors.begin(); it != allDetectors.end(); it++){
    int32_t detid = it->first;

    // def boost::shared_ptr<const Mantid::Geometry::IDetector>
  IDetector_const_sptr;

    std::string parentname =
  it->second->getParent()->getComponentID()->getName();
    g_log.notice() << "Name = " << parentname << std::endl;
    // parents.insert(parentid, true);
  }
  ***/

  /*** Here some special configuration for VULCAN is hard-coded here!
   *   Including (1) Super-Parent Information
   ***/
  Kernel::V3D referencePos;
  detid_t anydetinrefmodule = 21 * 1250 + 5;

  std::map<detid_t, Geometry::IDetector_const_sptr>::iterator det_iter =
      allDetectors.find(anydetinrefmodule);

  if (det_iter == allDetectors.end()) {
    throw std::invalid_argument("Any Detector ID is Instrument's detector");
  }
  referencePos = det_iter->second->getParent()->getPos();
  double refl2 = referencePos.norm();
  double halfcosTwoThetaRef =
      referencePos.scalar_prod(beamline) / (refl2 * beamline_norm);
  double sinThetaRef = sqrt(0.5 - halfcosTwoThetaRef);
  double difcRef = sinThetaRef * (l1 + refl2) / CONSTANT;

  // Loop over all detectors in instrument to find the offset
  for (it = allDetectors.begin(); it != allDetectors.end(); ++it) {
    int detectorID = it->first;
    Geometry::IDetector_const_sptr det = it->second;
    double offset = 0.0;

    // Find the vulcan factor;
    double vulcan_factor = 0.0;
    std::map<detid_t, double>::const_iterator vulcan_iter =
        vulcan.find(detectorID);
    if (vulcan_iter != vulcan.end()) {
      vulcan_factor = vulcan_iter->second;
      numfinds++;
    }

    // g_log.notice() << "Selected Detector with ID = " << detectorID << "  ID2
    // = " << id2 << std::endl; proved to be same

    double intermoduleoffset = 0;
    double interstackoffset = 0;

    detid_t intermoduleid = detid_t(detectorID / 1250) * 1250 + 1250 - 2;
    vulcan_iter = vulcan.find(intermoduleid);
    if (vulcan_iter == vulcan.end()) {
      g_log.error() << "Cannot find inter-module offset ID = " << intermoduleid
                    << std::endl;
    } else {
      intermoduleoffset = vulcan_iter->second;
    }

    detid_t interstackid = detid_t(detectorID / 1250) * 1250 + 1250 - 1;
    vulcan_iter = vulcan.find(interstackid);
    if (vulcan_iter == vulcan.end()) {
      g_log.error() << "Cannot find inter-module offset ID = " << intermoduleid
                    << std::endl;
    } else {
      interstackoffset = vulcan_iter->second;
    }

    /***  This is the previous way to correct upon DIFC[module center pixel]
    // The actual factor is 10^(-value_in_the_file)
    vulcan_factor = pow(10.0,-vulcan_factor);
    // At this point, tof_corrected = vulcan_factor * tof_input
    // So this is the offset
    offset = vulcan_factor - 1.0;
    ***/

    /*** New approach to correct based on DIFC of each pixel
     *   Equation:  offset = DIFC^(pixel)/DIFC^(parent)*(1+vulcan_offset)-1
     *   offset should be close to 0
     ***/
    // 1. calculate DIFC
    Kernel::V3D detPos;
    detPos = det->getPos();

    // Now detPos will be set with respect to samplePos
    detPos -= samplePos;
    double l2 = detPos.norm();
    double halfcosTwoTheta =
        detPos.scalar_prod(beamline) / (l2 * beamline_norm);
    double sinTheta = sqrt(0.5 - halfcosTwoTheta);
    double difc_pixel = sinTheta * (l1 + l2) / CONSTANT;

    // Kernel::V3D parentPos = det->getParent()->getPos();
    // parentPos -= samplePos;
    // double l2parent = parentPos.norm();
    // double halfcosTwoThetaParent = parentPos.scalar_prod(beamline)/(l2 *
    // beamline_norm);
    // double sinThetaParent = sqrt(0.5 - halfcosTwoThetaParent);
    // double difc_parent = sinThetaParent*(l1+l2parent)/CONSTANT;

    /*** Offset Replicate Previous Result
    offset = difc_pixel/difc_parent*(pow(10.0, -vulcan_factor))-1.0;
    ***/

    offset =
        difc_pixel / difcRef * (pow(10.0, -(vulcan_factor + intermoduleoffset +
                                            interstackoffset))) -
        1.0;

    // Save in the map
    try {
      offsetsWS->setValue(detectorID, offset);

      if (intermoduleid != 27498 && intermoduleid != 28748 &&
          intermoduleid != 29998 && intermoduleid != 33748 &&
          intermoduleid != 34998 && intermoduleid != 36248) {
        g_log.error() << "Detector ID = " << detectorID
                      << "  Inter-Module ID = " << intermoduleid << std::endl;
        throw std::invalid_argument("Indexing error!");
      }

    } catch (std::invalid_argument &) {
      g_log.notice() << "Misses Detector ID = " << detectorID << std::endl;
    }
  } // for

  g_log.notice() << "Number of matched detectors =" << numfinds << std::endl;
}
 int MidiInstrumentMapper::GetMapCount() {
     midiMapsMutex.Lock();
     int i = midiMaps.size();
     midiMapsMutex.Unlock();
     return i;
 }
Пример #20
0
int str2vkey(String s)
{
	if(strvkeymap.size()==0)
	{
		strvkeymap["[SPACE]"] = VK_SPACE;
		strvkeymap["[F1]"] = VK_F1;
		strvkeymap["[F2]"] = VK_F2;
		strvkeymap["[F3]"] = VK_F3;
		strvkeymap["[F4]"] = VK_F4;
		strvkeymap["[F5]"] = VK_F5;
		strvkeymap["[F6]"] = VK_F6;
		strvkeymap["[F7]"] = VK_F7;
		strvkeymap["[F8]"] = VK_F8;
		strvkeymap["[F9]"] = VK_F9;
		strvkeymap["[F10]"] = VK_F10;
		strvkeymap["[F11]"] = VK_F11;
		strvkeymap["[F12]"] = VK_F12;

		strvkeymap["[ESC]"] = VK_ESCAPE;
		strvkeymap["[TAB]"] = VK_TAB;
		strvkeymap["[DEL]"] = VK_DELETE;
		strvkeymap["[INS]"] = VK_INSERT;
		strvkeymap["[HOME]"] = VK_HOME;
		strvkeymap["[END]"] = VK_END;
		strvkeymap["[PGUP]"] = VK_PRIOR;
		strvkeymap["[PGDN]"] = VK_NEXT;
		strvkeymap["[PAUSE]"] = VK_PAUSE;

		strvkeymap["[ENTER]"] = VK_RETURN;

		strvkeymap["[SHIFT]"] = VK_SHIFT;
		strvkeymap["[CONTROL]"] = VK_CONTROL;
		strvkeymap["[ALT]"] = 0xa4;
		strvkeymap["[BACK]"] = VK_BACK;

		strvkeymap["[LEFT]"] = VK_LEFT;
		strvkeymap["[UP]"] = VK_UP;
		strvkeymap["[RIGHT]"] = VK_RIGHT;
		strvkeymap["[DOWN]"] = VK_DOWN;

		strvkeymap["[NUMLOCK]"] = VK_NUMLOCK;

		strvkeymap["[0]"] = 0x60;
		strvkeymap["[1]"] = 0x61;
		strvkeymap["[2]"] = 0x62;
		strvkeymap["[3]"] = 0x63;
		strvkeymap["[4]"] = 0x64;
		strvkeymap["[5]"] = 0x65;
		strvkeymap["[6]"] = 0x66;
		strvkeymap["[7]"] = 0x67;
		strvkeymap["[8]"] = 0x68;
		strvkeymap["[9]"] = 0x69;

		strvkeymap["[+]"] = 0x6b;
		strvkeymap["[-]"] = 0x6d;

		strvkeymap["[=]"] = 0xbb;
	}

	std::map<String,int>::iterator it = strvkeymap.find(s);
	if(it==strvkeymap.end()) return 0;
    return it->second;
}
Пример #21
0
void CIMIContext::getCandidates (unsigned frIdx, CCandidates& result)
{
    TCandiPair cp;
    static std::map<wstring, TCandiPair> map;
    std::map<wstring, TCandiPair>::iterator it_map;

    map.clear();
    result.clear();

    std::vector<unsigned> st;
    getBestSentence (st, frIdx);

    cp.m_candi.m_start = m_candiStarts = frIdx++;

    for (;frIdx < m_tailIdx; ++frIdx)  {
        CLatticeFrame &fr = m_lattice[frIdx];

        if (!fr.isSyllableFrame ())
            continue;

        cp.m_candi.m_end = frIdx;
        if (fr.m_bwType != CLatticeFrame::NO_BESTWORD && fr.m_bestWord.m_start == m_candiStarts) {
            cp.m_candi = fr.m_bestWord;
            cp.m_Rank = TCandiRank(fr.m_bwType & CLatticeFrame::USER_SELECTED,
                                   fr.m_bwType & CLatticeFrame::BESTWORD,
                                   0, false, 0);
            map [cp.m_candi.m_cwstr] = cp;
        }

        bool found = false;
        CLexiconStates::iterator it  = fr.m_lexiconStates.begin();
        CLexiconStates::iterator ite = fr.m_lexiconStates.end();
        for (; it != ite; ++it) {
            TLexiconState & lxst = *it;

            if (lxst.m_start != m_candiStarts)
                continue;

            int len = lxst.m_syls.size() - lxst.m_num_of_inner_fuzzies;
            if (0 == len) len = 1;

            found = true;
            unsigned word_num;
            const CPinyinTrie::TWordIdInfo *words = lxst.getWords (word_num);

            for (unsigned i=0; i<word_num; ++i) {
                if (m_csLevel < words[i].m_csLevel)
                    continue;

                cp.m_candi.m_wordId = words[i].m_id;
                cp.m_candi.m_cwstr = _getWstr (cp.m_candi.m_wordId);
                cp.m_candi.m_pLexiconState = &lxst;
                if (!cp.m_candi.m_cwstr)
                    continue;

                //sorting according to the order in PinYinTire
                cp.m_Rank = TCandiRank(false, st.front() == cp.m_candi.m_wordId, len, false, i);
                it_map = map.find(cp.m_candi.m_cwstr);
                if (it_map == map.end() || cp.m_Rank < it_map->second.m_Rank || cp.m_candi.m_wordId > INI_USRDEF_WID)
                    map [cp.m_candi.m_cwstr] = cp;
            }
        }

        if (!found) continue; // FIXME: need better solution later

        if (m_bDynaCandiOrder) {
            CLatticeStates::iterator it  = fr.m_latticeStates.begin();
            CLatticeStates::iterator ite = fr.m_latticeStates.end();
            for (; it != ite; ++it) {
                TLatticeState & ltst = *it;

                if (ltst.m_pBackTraceNode->m_frIdx != m_candiStarts)
                    continue;

                cp.m_candi.m_wordId = ltst.m_backTraceWordId;
                cp.m_candi.m_cwstr = _getWstr (cp.m_candi.m_wordId);
                cp.m_candi.m_pLexiconState = ltst.m_pLexiconState;
                if (!cp.m_candi.m_cwstr)
                    continue;

                int len = cp.m_candi.m_pLexiconState->m_syls.size() -
                          cp.m_candi.m_pLexiconState->m_num_of_inner_fuzzies;
                if (0 == len) len = 1;
                cp.m_Rank = TCandiRank(false, st.front() == cp.m_candi.m_wordId, len, true, ltst.m_score/ltst.m_pBackTraceNode->m_score);
                it_map = map.find(cp.m_candi.m_cwstr);
                if (it_map == map.end() || cp.m_Rank < it_map->second.m_Rank || cp.m_candi.m_wordId > INI_USRDEF_WID)
                    map[cp.m_candi.m_cwstr] = cp;
            }
        }

        m_candiEnds = frIdx;
    }

    std::vector<TCandiPairPtr> vec;

    vec.reserve(map.size());
    std::map<wstring, TCandiPair>::iterator it_mapE = map.end();
    for (it_map = map.begin(); it_map != it_mapE; ++it_map)
        vec.push_back(TCandiPairPtr(&(it_map->second)));
    std::make_heap(vec.begin(), vec.end());
    std::sort_heap(vec.begin(), vec.end());

    for (int i=0, sz=vec.size(); i < sz; ++i)
        result.push_back(vec[i].m_Ptr->m_candi);
}
Пример #22
0
Double_t CalibTree::Loop(int loop, TFile *fout, bool useweight, int nMin,
			 bool inverse, double rmin, double rmax, int ietaMax,
			 int applyL1Cut, double l1Cut, bool last, 
			 double fraction, bool writeHisto, bool debug) {

  if (fChain == 0) return 0;
  Long64_t nbytes(0), nb(0), kprint(0);
  Long64_t nentryTot = fChain->GetEntriesFast();
  Long64_t nentries = (fraction > 0.01 && fraction < 0.99) ? 
    (Long64_t)(fraction*nentryTot) : nentryTot;
  if (detIds.size() == 0) {
    for (Long64_t jentry=0; jentry<nentries; jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // Find DetIds contributing to the track
      bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		     ((t_Run < runlo_) || (t_Run > runhi_)));
      if (selRun && (t_nVtx >= nvxlo_) && (t_nVtx <= nvxhi_)) {
	bool isItRBX = (cSelect_ && exclude_ && cSelect_->isItRBX(t_DetIds));
	++kprint;
	if (!isItRBX) {
	  for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	    if (selectPhi((*t_DetIds)[idet])) {
	      unsigned int detid = truncateId((*t_DetIds)[idet],
					      truncateFlag_,debug);
	      if (debug && (kprint<=10)) {
		std::cout << "DetId[" << idet << "] Original " << std::hex 
			  << (*t_DetIds)[idet] << " truncated " << detid 
			  << std::dec;
	      }
	      if (std::find(detIds.begin(),detIds.end(),detid) == detIds.end()){
		detIds.push_back(detid);
		if (debug && (kprint<=10)) std::cout << " new";
	      }
	      if (debug && (kprint<=10)) std::cout << std::endl;
	    }
	  }
	  // Also look at the neighbouring cells if available
	  if (t_DetIds3 != 0) {
	    for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	      if (selectPhi((*t_DetIds3)[idet])) {
		unsigned int detid = truncateId((*t_DetIds3)[idet],
						truncateFlag_,debug);
		if (std::find(detIds.begin(),detIds.end(),detid)==detIds.end()){
		  detIds.push_back(detid);
		}
	      }
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "Total of " << detIds.size() << " detIds and " 
	      << histos.size() << " histos found" << std::endl;
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    for (unsigned int k=0; k<detIds.size(); ++k) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << k << "] " << subdet << ":" << zside*ieta << ":"
		<< depth << ":" << iphi << "  " << std::hex << detIds[k] 
		<< std::dec << std::endl;
    }
  }
  unsigned int k(0);
  for (std::map<unsigned int, TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++k) {
    if (debug) {
      std::cout << "histos[" << k << "] " << std::hex << itr->first 
		<< std::dec << " " << itr->second;
      if (itr->second != 0) std::cout << " " << itr->second->GetTitle();
      std::cout << std::endl;
    }
    if (itr->second != 0) itr->second->Delete();
  }

  for (unsigned int k=0; k<detIds.size(); ++k) {
    char name[20], title[100];
    sprintf (name, "Hist%d_%d", detIds[k], loop);
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
    sprintf (title, "Correction for Subdet %d #eta %d depth %d (Loop %d)", subdet, zside*ieta, depth, loop);
    TH1D* hist = new TH1D(name,title,100, 0.0, 5.0);
    hist->Sumw2();
    if (debug) {
      std::cout << "Book Histo " << k << " " << title << std::endl;
    }
    histos[detIds[k]] = hist;
  }
  std::cout << "Total of " << detIds.size() << " detIds and " << histos.size() 
	    << " found in " << nentries << std::endl;

  nbytes = nb = 0;
  std::map<unsigned int, myEntry > SumW;
  std::map<unsigned int, double  > nTrks;

  int ntkgood(0);
  for (Long64_t jentry=0; jentry<nentries; jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0)                               break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if (std::find(entries.begin(),entries.end(),jentry) !=
	entries.end())                            continue;
    bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		   ((t_Run < runlo_) || (t_Run > runhi_)));
    if (!selRun)                                  continue;
    if ((t_nVtx < nvxlo_) || (t_nVtx > nvxhi_))   continue;
    if (cSelect_ != nullptr) {
      if (exclude_) {
	if (cSelect_->isItRBX(t_DetIds))          continue;
      } else {
	if (!(cSelect_->isItRBX(t_ieta,t_iphi)))  continue;
      }
    }

    if (debug) {
      std::cout << "***Entry (Track) Number : " << ientry << std::endl;
      std::cout << "p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal << "/"
		<< t_eMipDR << "/" << (*t_DetIds).size() << std::endl;
    }
    double pmom = (useGen_ && (t_gentrackP > 0)) ? t_gentrackP : t_p;
    if (goodTrack()) {
      ++ntkgood;
      double Etot(0), Etot2(0);
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	if (selectPhi((*t_DetIds)[idet])) {
	  unsigned int id = (*t_DetIds)[idet];
	  double hitEn(0);
	  unsigned int detid = truncateId(id,truncateFlag_,false);
	  if (Cprev.find(detid) != Cprev.end()) 
	    hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	  else 
	    hitEn = (*t_HitEnergies)[idet];
	  if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	  Etot  += hitEn;
	  Etot2 += ((*t_HitEnergies)[idet]);
	}
      }
      // Now the outer cone 
      double Etot1(0), Etot3(0);
      if (t_DetIds1 != 0 && t_DetIds3 != 0) {
	for (unsigned int idet=0; idet<(*t_DetIds1).size(); idet++) { 
	  if (selectPhi((*t_DetIds1)[idet])) {
	    unsigned int id    = (*t_DetIds1)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies1)[idet];
	    else 
	      hitEn = (*t_HitEnergies1)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot1  += hitEn;
	  }
	}
	for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	  if (selectPhi((*t_DetIds3)[idet])) {
	    unsigned int id    = (*t_DetIds3)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies3)[idet];
	    else 
	      hitEn = (*t_HitEnergies3)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot3  += hitEn;
	  }
	}
      }
      eHcalDelta_ = Etot3-Etot1;
      double evWt = (useweight) ? t_EventWeight : 1.0; 
      // PU correction only for loose isolation cut
      double ehcal = ((puCorr_ == 0) ? Etot : 
		      ((puCorr_ < 0) ? (Etot*puFactor(-puCorr_,t_ieta,pmom,Etot,eHcalDelta_)) :
		       puFactorRho(puCorr_,t_ieta,t_rhoh,Etot)));
      double pufac = (Etot > 0) ? (ehcal/Etot) : 1.0;
      double ratio = ehcal/(pmom-t_eMipDR);
      if (debug) std::cout << " Weights " << evWt << ":" << pufac << " Energy "
			   << Etot2 << ":" << Etot << ":" << pmom << ":" 
			   << t_eMipDR << ":" << t_eHcal << ":" << ehcal 
			   << " ratio " << ratio  << std::endl;
      if (loop==0) {
	h_pbyE->Fill(ratio, evWt);
        h_Ebyp_bfr->Fill(t_ieta, ratio, evWt);
      }
      if (last){
        h_Ebyp_aftr->Fill(t_ieta, ratio, evWt);
      }
      bool l1c(true);
      if (applyL1Cut != 0) l1c = ((t_mindR1 >= l1Cut) || 
				  ((applyL1Cut == 1) && (t_DataType == 1)));
      if ((rmin >=0 && ratio > rmin) && (rmax >= 0 && ratio < rmax) && l1c) {
	for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	  if (selectPhi((*t_DetIds)[idet])) {
	    unsigned int id    = (*t_DetIds)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn=0.0;
	    if (debug) {
	      std::cout << "idet " << idet << " detid/hitenergy : " 
			<< std::hex << (*t_DetIds)[idet] << ":" << detid 
			<< "/" << (*t_HitEnergies)[idet] << std::endl;
	    }
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	    else 
	      hitEn = (*t_HitEnergies)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    double Wi  = evWt * hitEn/Etot;
	    double Fac = (inverse) ? (ehcal/(pmom-t_eMipDR)) : 
	      ((pmom-t_eMipDR)/ehcal);
	    double Fac2= Wi*Fac*Fac;
	    TH1D* hist(0);
	    std::map<unsigned int,TH1D*>::const_iterator itr = histos.find(detid);
	    if (itr != histos.end()) hist = itr->second;
	    if (debug) {
	      std::cout << "Det Id " << std::hex << detid << std::dec 
			<< " " << hist << std::endl;
	    }
	    if (hist != 0) hist->Fill(Fac, Wi);//////histola
	    Fac       *= Wi;
	    if (SumW.find(detid) != SumW.end() ) {
	      Wi  += SumW[detid].fact0;
	      Fac += SumW[detid].fact1;
	      Fac2+= SumW[detid].fact2;
	      int kount = SumW[detid].kount + 1;
	      SumW[detid]   = myEntry(kount,Wi,Fac,Fac2); 
	      nTrks[detid] += evWt;
	    } else {
	      SumW.insert(std::pair<unsigned int,myEntry>(detid,myEntry(1,Wi,Fac,Fac2)));
	      nTrks.insert(std::pair<unsigned int,unsigned int>(detid, evWt));
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "# of Good Tracks " << ntkgood << " out of " << nentries 
	      << std::endl;
  }
  if (loop==0) {
    h_pbyE->Write("h_pbyE");
    h_Ebyp_bfr->Write("h_Ebyp_bfr");
  }
  if (last) {
    h_Ebyp_aftr->Write("h_Ebyp_aftr");
  }

  std::map<unsigned int, std::pair<double,double> > cfactors;
  unsigned int kount(0), kountus(0);
  double       sumfactor(0);
  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr) {
    if (writeHisto) {
      std::pair<double,double> result_write = fitMean(itr->second, 0);
      (itr->second)->Write();
    }
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "DETID :" << subdet << "  IETA :" << ieta 
		<< " HIST ENTRIES :" << (itr->second)->GetEntries()
		<< std::endl;
    }
  }

  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++kount) {
    std::pair<double,double> result = fitMean(itr->second, 0);
    double factor = (inverse) ? (2.-result.first) : result.first;
    if (debug) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << kount << "] " << subdet << ":" << zside*ieta 
		<< ":" << depth << " Factor " << factor << " +- " 
		<< result.second << std::endl;
    }
    if (!useMean_) {
      cfactors[itr->first] = std::pair<double,double>(factor,result.second);
      if (itr->second->GetEntries() > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }
  
  std::map<unsigned int, myEntry>::const_iterator SumWItr = SumW.begin();
  for (; SumWItr != SumW.end(); SumWItr++) {
    unsigned int detid = SumWItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "Detid|kount|SumWi|SumFac|myId : " << subdet << ":" 
		<< zside*ieta << ":" << depth << " | " 
		<< (SumWItr->second).kount << " | " << (SumWItr->second).fact0
		<< "|" << (SumWItr->second).fact1 << "|" 
		<< (SumWItr->second).fact2 << std::endl;
    }
    double factor = (SumWItr->second).fact1/(SumWItr->second).fact0;
    double dfac1  = ((SumWItr->second).fact2/(SumWItr->second).fact0-factor*factor);
    if (dfac1 < 0) dfac1 = 0;
    double dfac   = sqrt(dfac1/(SumWItr->second).kount);
    if (debug) {
      std::cout << "Factor " << factor << " " << dfac1 << " " << dfac
		<< std::endl;
    }
    if (inverse) factor = 2.-factor;
    if (useMean_) {
      cfactors[detid] = std::pair<double,double>(factor,dfac);
      if ((SumWItr->second).kount > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }

  double dets[150], cfacs[150], wfacs[150], myId[150], nTrk[150];
  kount = 0;
  std::map<unsigned int,std::pair<double,double> >::const_iterator itr=cfactors.begin();
  for (; itr !=cfactors.end(); ++itr,++kount) {
    unsigned int detid = itr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    double id  = ieta*zside + 0.25*(depth-1);
    double factor = (itr->second).first;
    double dfac   = (itr->second).second;
    if (ieta > ietaMax) {
      factor = 1;
      dfac   = 0;
    }
    std::pair<double,double> cfac(factor,dfac);
    if (Cprev.find(detid) != Cprev.end()) {
      dfac        /= factor;
      factor      *= Cprev[detid].first;
      dfac        *= factor;
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    } else {
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    }
    wfacs[kount]= factor;
    dets[kount] = detid;
    myId[kount] = id;
    nTrk[kount] = nTrks[detid];
  }
  if (higheta_ > 0) highEtaFactors(ietaMax, debug);

  std::cout << kountus << " detids out of " << kount << " have tracks > "
	    << nMin << std::endl;

  char fname[50];
  fout->cd();
  TGraph *g_fac1 = new TGraph(kount, dets, cfacs); 
  sprintf (fname, "Cfacs%d", loop);
  g_fac1->SetMarkerStyle(7);
  g_fac1->SetMarkerSize(5.0);
  g_fac1->Draw("AP");
  g_fac1->Write(fname);
  TGraph *g_fac2 = new TGraph(kount, dets, wfacs); 
  sprintf (fname, "Wfacs%d", loop);
  g_fac2->SetMarkerStyle(7);
  g_fac2->SetMarkerSize(5.0);
  g_fac2->Draw("AP");
  g_fac2->Write(fname);
  TGraph *g_fac3 = new TGraph(kount, myId, cfacs); 
  sprintf (fname, "CfacsVsMyId%d", loop);
  g_fac3->SetMarkerStyle(7);
  g_fac3->SetMarkerSize(5.0);
  g_fac3->Draw("AP");
  g_fac3->Write(fname);
  TGraph *g_fac4 = new TGraph(kount, myId, wfacs); 
  sprintf (fname, "WfacsVsMyId%d", loop);
  g_fac4->SetMarkerStyle(7);
  g_fac4->SetMarkerSize(5.0);
  g_fac4->Draw("AP");
  g_fac4->Write(fname);
  TGraph *g_nTrk = new TGraph(kount, myId, nTrk); 
  sprintf (fname, "nTrk");
  if(loop==0){
    g_nTrk->SetMarkerStyle(7);
    g_nTrk->SetMarkerSize(5.0);
    g_nTrk->Draw("AP");
    g_nTrk->Write(fname);
  }
  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, std::pair<double,double> >::const_iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (; CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") (nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second.first << " +- "
	      << CprevItr->second.second << std::endl;
  }
  double mean = (kountus > 0) ? (sumfactor/kountus) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << kountus 
	    << " DetIds" << std::endl;
  h_cvg->SetBinContent(loop+1,mean);
  if (last) h_cvg->Write("Cvg0");
  return mean;
}
Пример #23
0
void halo_impl::unrender(std::set<map_location> invalidated_locations)
{
	if(preferences::show_haloes() == false || haloes.empty()) {
		return;
	}
	//assert(invalidated_haloes.empty());

	// Remove expired haloes
	std::map<int, effect>::iterator itor = haloes.begin();
	for(; itor != haloes.end(); ++itor ) {
		if(itor->second.expired()) {
			deleted_haloes.insert(itor->first);
		}
	}

	// Add the haloes marked for deletion to the invalidation set
	std::set<int>::const_iterator set_itor = deleted_haloes.begin();
	for(;set_itor != deleted_haloes.end(); ++set_itor) {
		invalidated_haloes.insert(*set_itor);
		haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
	}

	// Test the multi-frame haloes whether they need an update
	for(set_itor = changing_haloes.begin();
			set_itor != changing_haloes.end(); ++set_itor) {
		if(haloes.find(*set_itor)->second.need_update()) {
			invalidated_haloes.insert(*set_itor);
			haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
		}
	}

	// Find all halo's in a the invalidated area
	size_t halo_count;

	// Repeat until set of haloes in the invalidated area didn't change
	// (including none found) or all existing haloes are found.
	do {
		halo_count = invalidated_haloes.size();
		for(itor = haloes.begin(); itor != haloes.end(); ++itor) {
			// Test all haloes not yet in the set
			// which match one of the locations
			if(invalidated_haloes.find(itor->first) == invalidated_haloes.end() &&
					itor->second.on_location(invalidated_locations)) {

				// If found, add all locations which the halo invalidates,
				// and add it to the set
				itor->second.add_overlay_location(invalidated_locations);
				invalidated_haloes.insert(itor->first);
			}
		}
	} while (halo_count != invalidated_haloes.size() && halo_count != haloes.size());

	if(halo_count == 0) {
		return;
	}

	// Render the haloes:
	// iterate through all the haloes and invalidate if in set
	for(std::map<int, effect>::reverse_iterator ritor = haloes.rbegin(); ritor != haloes.rend(); ++ritor) {
		if(invalidated_haloes.find(ritor->first) != invalidated_haloes.end()) {
			ritor->second.unrender();
		}
	}

	// Really delete the haloes marked for deletion
	for(set_itor = deleted_haloes.begin(); set_itor != deleted_haloes.end(); ++set_itor) {
		// It can happen a deleted halo hasn't been rendered yet, invalidate them as well
		new_haloes.erase(*set_itor);

		changing_haloes.erase(*set_itor);
		invalidated_haloes.erase(*set_itor);
		haloes.erase(*set_itor);
	}

	deleted_haloes.clear();
}
Пример #24
0
UINT CIniFile::GetAllKeyWordsAndValues(const wchar_t *const pwchSection, std::map<std::wstring, std::wstring> &mKeyWordsAndValues)
{
	assert(NULL != pwchSection);

	// 清空map
	mKeyWordsAndValues.erase(mKeyWordsAndValues.begin(), mKeyWordsAndValues.end());

	const DWORD dwMaxSize(MAX_PATH*5);
	wchar_t wchAllKeyWordsAndValues[dwMaxSize];
	wchar_t wchKeyWordAndValue[dwMaxSize];
	wmemset(wchAllKeyWordsAndValues, L'\0', _countof(wchAllKeyWordsAndValues));
	wmemset(wchKeyWordAndValue, L'\0', _countof(wchKeyWordAndValue));

	DWORD dwReturn = GetSection(pwchSection, wchAllKeyWordsAndValues, dwMaxSize);

	if (L'\0' == wchAllKeyWordsAndValues[0])
	{
		// 第一个等于L'\0'
		// 无该Section
	}
	else
	{
		// 第一个不等于L'\0'
		// 有该Section

		// 分离出有用信息
		// 因为Section在数组中的存放形式为“KeyWord1=Value1”,“\0”,“KeyWord2=Value2”,“\0”,“\0”。
		// 所以如果检测到连续两个0,则break
		int i(0);
		for (i=0; i<dwMaxSize; i++)
		{
			if (wchAllKeyWordsAndValues[i] == L'\0')
			{
				if (wchAllKeyWordsAndValues[i] == wchAllKeyWordsAndValues[i+1])
				{
					break;
				}
			}
		}
		i++;

		// 将有用信息进行分解
		const int nActualSize(i);
		int j(0);
		int nPos(0);
		for(j=0; j<nActualSize; j++)
		{
			wchKeyWordAndValue[nPos++] = wchAllKeyWordsAndValues[j];
			if (wchAllKeyWordsAndValues[j] == L'\0')
			{
				std::wstring wstrKeyWord;
				std::wstring wstrValue;

				const wchar_t *pwchEqualSign = wcschr(wchKeyWordAndValue, L'=');
				const int nCopySize = pwchEqualSign - wchKeyWordAndValue;
				wchar_t *pwch = new wchar_t[nCopySize+1]();
				wmemcpy(pwch, wchKeyWordAndValue, nCopySize);
				wstrKeyWord = pwch;
				wstrValue = ++pwchEqualSign;
				if (NULL != pwch)
				{
					delete[] pwch;
					pwch = NULL;
				}

				mKeyWordsAndValues.insert(std::map<std::wstring, std::wstring>::value_type(wstrKeyWord, wstrValue));

				wmemset(wchKeyWordAndValue, L'\0', _countof(wchKeyWordAndValue));
				nPos = 0;
			}
		}
	}

	return mKeyWordsAndValues.size();
}
Пример #25
0
int main(int argc, char* argv[]) 
{
	srand(time(NULL));
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		printf("%s\n", strerror(errno));
	}

	struct sockaddr_in servaddr;
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(11000);
	inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);

	int ret = connect(fd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr));

	if (ret == -1) {
		printf("%s", strerror(errno));
		return 0;
	}

	int epfd = epoll_create(1024);
	if (epfd == -1) {
		printf("create failed");
		return 0;
	}

	set_io_nonblock(fd, 1);

	struct epoll_event event;
	event.data.fd = fd;
	event.events = EPOLLIN | EPOLLET;
	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
	struct epoll_event *evs = (struct epoll_event *)malloc(sizeof(struct epoll_event) * 200);	
	int done = 0;

	
	while (!done) {
		int i;
recv_again:
		int n = epoll_wait(epfd, evs, 1024, 100);
		if (n == -1 && errno != EINTR) {
			printf("%s", strerror(errno));
			return 0;
		}


		for (i = 0; i < n; ++i) {
			int fd = evs[i].data.fd;
			printf("fd=%u type=%u\n", fd, evs[i].events);
			if (evs[i].events && EPOLLIN) {
				char recvbuf[102400];
				int ret = safe_tcp_recv_n(fd, recvbuf, 102400);
				if (ret == 0) {
					printf("fd closed");
					return 0;
				} else if (ret > 0) {
					printf("recvbuf len=%d\n", ret);
					int len = ret;
					int readlen = 0;
					struct timeval end;
					struct timeval start; 
					while (readlen < len) {
						gettimeofday(&end, NULL);
						char*  ptr = recvbuf;
						proto_pkg_t *msg = (proto_pkg_t *)(ptr + readlen);
						start = seq_time_map[msg->seq];
						printf("recv: %d,%d,%d,%d,%d,%s:%lu,%lu\n", 
								msg->id, 
								msg->cmd, 
								msg->seq,
								msg->ret, 
								msg->len,
								msg->data,
								msg->len - sizeof(proto_pkg_t), 
								(end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec)
							  );
						readlen += msg->len;
						seq_time_map.erase(msg->seq);
					}
				} else {
					printf("recv error");
					return 0;
				}
			} else if (evs[i].events && EPOLLOUT) {

			}
		}
		if (seq_time_map.size()) {
			goto recv_again;
		}

		sleep(1);
		//getchar();
		char input[200] = {'\0'};
		int num = rand() % 200+ 1;
		//int num = 30;
		gen_str(input, num);
		//		scanf("%s", input);
		char buf[1024];
		for (i = 0; i < 200; ++i) {
			proto_pkg_t *pkg = (proto_pkg_t *)buf;	
			pkg->id =  i;
			pkg->cmd = i + 1;
			pkg->ret = i + 2;
			pkg->seq = ++seq;

			struct timeval start;
			gettimeofday(&start, NULL);
			seq_time_map[pkg->seq] = start;

			pkg->len = sizeof(proto_pkg_t) + strlen(input) + 1;
			input[strlen(input)] = '\0';
			memcpy(pkg->data, input, strlen(input) + 1);

			send(fd, buf, pkg->len, 0);
			printf("send: id=%u,cmd=%u,seq=%u,ret=%u,%s:%lu\n\n", pkg->id, pkg->cmd, pkg->seq, pkg->ret, input, strlen(input) + 1);

			//			getchar();
		}
		//		sleep(1);
		//if (rand() % 2) {
		//}
	}

	free(evs);
	close(epfd);
	close(fd);

	return 0;
}
Пример #26
0
bool func1(std::map<int, double> i, std::map<int, double> j) {
  return i.size() < j.size();
};
Пример #27
0
bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock) {
    LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());

    CLevelDBBatch batch;
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        BatchWriteCoins(batch, it->first, it->second);
    if (hashBlock != uint256(0))
        BatchWriteHashBestChain(batch, hashBlock);

    return db.WriteBatch(batch);
}
Пример #28
0
//Добавляет часть речи в полный список частей речи
int POS_add(char* strPOS)
{
	int i = POS_map.size() + 1;
	POS_map[strPOS] = i;
	return i;
}
Пример #29
0
void BVH_balancing::Solve( const std::map<int, std::set<int> > &compatibility, size_t no_bones,
                           std::map<int, int>& assignments ){
    std::map<int, int> Bn_to_index, index_to_Bn;
    size_t index = 0;
    size_t no_branchings 	= compatibility.size();

    assert( no_bones > 0 );
    assert( no_branchings > 0 );

    for( const auto& item : compatibility ){
        if( Bn_to_index.count(item.first) > 0 ) { continue; } // skip if alredy mapped
        Bn_to_index[item.first] = index;
        index_to_Bn[index] = item.first;
        ++index;
    }
    // entire optimization goes inside a try catch statement.
    // in case of errors, I want it to crash!
    try{
        GRBEnv env;
        GRBModel model = GRBModel( env );

        /* CREATE VARIABLES */
        std::vector<GRBVar> vars( no_bones * no_branchings );
        for( size_t r = 0; r < no_bones; ++r ){
            for( size_t c = 0; c < no_branchings; ++c ){
                size_t idx = matIndex( r, c, no_branchings );
                std::stringstream var_name;
                var_name << "A( " << r << ", " << c << " )";
                assert( compatibility.count( index_to_Bn[c] ) > 0 );
                bool is_connected = compatibility.at( index_to_Bn[c] ).count( r );
                vars[idx] = model.addVar( 0.0, ( is_connected > 0 ? 1.0 : 0.0 ), 1.0, GRB_BINARY, var_name.str());
            }
        }
        model.update();

        // Create Objective Function.
        // for each branching node i : #bones( Bn_i )^2
        // hence I need to sum the number of bones assigned to each branching node
        GRBQuadExpr obj;
        std::vector<GRBLinExpr> cols( no_branchings );

        for( size_t c = 0; c < no_branchings; ++c ){
            for( size_t r = 0; r < no_bones; ++r ){
                size_t idx = matIndex( r, c, no_branchings );
                cols[c] += vars[idx];
            }
        }
        for( size_t c = 0; c < no_branchings; ++c ){ obj += cols[c] * cols[c]; }

        model.setObjective( obj );
        model.update();

        // create constraint : each bone can be assigned to only one branching node.
        // this means that the summation of each row's values must be equal to 1.0
        for( size_t r = 0; r < no_bones; ++r ){
            GRBLinExpr row_sum;
            for( size_t c = 0; c < no_branchings; ++c ){
                size_t idx = matIndex( r, c, no_branchings );
                row_sum += vars[idx];
            }
            model.addConstr( row_sum == 1.0 );
        }
        model.update();

        // Optimize
        model.optimize();
        int status = model.get(GRB_IntAttr_Status);

        if (status == GRB_OPTIMAL) {
          std::cout << "The optimal objective is " << model.get(GRB_DoubleAttr_ObjVal) << std::endl;
          // return results!
//          printResults(vars, no_bones, no_branchings );
          getResults( index_to_Bn, vars, assignments, no_bones, no_branchings );
          return;
        }

        /************************************/
        /*          ERROR HANDLING          */
        /************************************/
        if (status == GRB_UNBOUNDED){
          std::cout << "The model cannot be solved because it is unbounded" << std::endl;
          assert(false);
        }

        if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE)) {
          std::cout << "Optimization was stopped with status " << status << std::endl;
          assert( false );
        }
        GRBConstr* c = 0;
        // do IIS
        std::cout << "The model is infeasible; computing IIS" << std::endl;
        model.computeIIS();
        std::cout << "\nThe following constraint(s) cannot be satisfied:" << std::endl;
        c = model.getConstrs();
        for (int i = 0; i < model.get(GRB_IntAttr_NumConstrs); ++i){
          if (c[i].get(GRB_IntAttr_IISConstr) == 1) {
            std::cout << c[i].get(GRB_StringAttr_ConstrName) << std::endl;
          }
        }
    }
    /*          EXCEPTION HANDLING          */
    catch (GRBException e) {
        std::cout << "Error code = " << e.getErrorCode() << std::endl;
        std::cout << e.getMessage() << std::endl;
        assert( false );
    }
    catch (...){
        std::cout << "Exception during optimization" << std::endl;
        assert( false );
    }

}
Пример #30
0
 /// return the number of entries in the store
 int size(void)
 throw() {
     return mapMJD_EOP.size();
 }