コード例 #1
0
ファイル: AverageLinkage.cpp プロジェクト: OpenMS/OpenMS
  void AverageLinkage::operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold /*=1*/) const
  {
    // input MUST have >= 2 elements!
    if (original_distance.dimensionsize() < 2)
    {
      throw ClusterFunctor::InsufficientInput(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Distance matrix to start from only contains one element");
    }

    std::vector<std::set<Size> > clusters(original_distance.dimensionsize());
    for (Size i = 0; i < original_distance.dimensionsize(); ++i)
    {
      clusters[i].insert(i);
    }

    cluster_tree.clear();
    cluster_tree.reserve(original_distance.dimensionsize() - 1);

    // Initial minimum-distance pair
    original_distance.updateMinElement();
    std::pair<Size, Size> min = original_distance.getMinElementCoordinates();

    Size overall_cluster_steps(original_distance.dimensionsize());
    startProgress(0, original_distance.dimensionsize(), "clustering data");

    while (original_distance(min.second, min.first) < threshold)
    {
      //grow the tree
      cluster_tree.push_back(BinaryTreeNode(*(clusters[min.second].begin()), *(clusters[min.first].begin()), original_distance(min.first, min.second)));
      if (cluster_tree.back().left_child > cluster_tree.back().right_child)
      {
        std::swap(cluster_tree.back().left_child, cluster_tree.back().right_child);
      }

      if (original_distance.dimensionsize() > 2)
      {
        //pick minimum-distance pair i,j and merge them

        //calculate parameter for lance-williams formula
        float alpha_i = (float)(clusters[min.first].size() / (float)(clusters[min.first].size() + clusters[min.second].size()));
        float alpha_j = (float)(clusters[min.second].size() / (float)(clusters[min.first].size() + clusters[min.second].size()));
        //~ std::cout << alpha_i << '\t' << alpha_j << std::endl;

        //pushback elements of second to first (and then erase second)
        clusters[min.second].insert(clusters[min.first].begin(), clusters[min.first].end());
        // erase first one
        clusters.erase(clusters.begin() + min.first);

        //update original_distance matrix
        //average linkage: new distance between clusters is the minimum distance between elements of each cluster
        //lance-williams update for d((i,j),k): (m_i/m_i+m_j)* d(i,k) + (m_j/m_i+m_j)* d(j,k) ; m_x is the number of elements in cluster x
        for (Size k = 0; k < min.second; ++k)
        {
          float dik = original_distance.getValue(min.first, k);
          float djk = original_distance.getValue(min.second, k);
          original_distance.setValueQuick(min.second, k, (alpha_i * dik + alpha_j * djk));
        }
        for (Size k = min.second + 1; k < original_distance.dimensionsize(); ++k)
        {
          float dik = original_distance.getValue(min.first, k);
          float djk = original_distance.getValue(min.second, k);
          original_distance.setValueQuick(k, min.second, (alpha_i * dik + alpha_j * djk));
        }

        //reduce
        original_distance.reduce(min.first);

        //update minimum-distance pair
        original_distance.updateMinElement();

        //get min-pair from triangular matrix
        min = original_distance.getMinElementCoordinates();
      }
      else
      {
        break;
      }
      setProgress(overall_cluster_steps - original_distance.dimensionsize());

      //repeat until only two cluster remains, last step skips matrix operations
    }
    //fill tree with dummy nodes
    Size sad(*clusters.front().begin());
    for (Size i = 1; (i < clusters.size()) && (cluster_tree.size() < cluster_tree.capacity()); ++i)
    {
      cluster_tree.push_back(BinaryTreeNode(sad, *clusters[i].begin(), -1.0));
    }

    endProgress();
  }
コード例 #2
0
ファイル: iMesh.hpp プロジェクト: vibraphone/meshkit
inline iMesh::Error
iMesh::getAdjEntIndices( EntitySetHandle set,
                         EntityType requestor_type,
                         EntityTopology requestor_topo,
                         EntityType type_requested,
                         std::vector<EntityHandle>& entities_out,
                         std::vector<EntityHandle>& adj_entities_out,
                         std::vector<int>& adj_indices_out,
                         std::vector<int>& offsets_out ) const
{
    // if input vects have no allocated space, allocate some so
    // we don't accidentally ask the impl to allocate an array
  if (entities_out.capacity() == 0) {
    Error err2;
    int count;
    if (requestor_topo == iMesh_ALL_TOPOLOGIES)
      err2 = getNumOfType( set, requestor_type, count );
    else
      err2 = getNumOfTopo( set, requestor_topo, count );
    if (err2 != iBase_SUCCESS)
      return err2;
    entities_out.resize( count );
  }
  else
    entities_out.resize( entities_out.capacity() );
    
  if (adj_entities_out.capacity() == 0)
    adj_entities_out.resize( 12*entities_out.size() );
  else
    adj_entities_out.resize( adj_entities_out.capacity() );
    
  if (adj_indices_out.capacity() == 0)
    adj_indices_out.resize( 12*entities_out.size() );
  else
    adj_indices_out.resize( adj_indices_out.capacity() );
    
  if (offsets_out.capacity() == 0)
    offsets_out.resize( entities_out.size() + 1 );
  else
    offsets_out.resize( offsets_out.capacity() );

  int err;
  int     entities_size = 0,     entities_alloc =     entities_out.size();
  int adj_entities_size = 0, adj_entities_alloc = adj_entities_out.size();
  int  adj_indices_size = 0,  adj_indices_alloc =  adj_indices_out.size();
  int      offsets_size = 0,      offsets_alloc =      offsets_out.size();
  EntityHandle*     entities_ptr = &    entities_out[0];
  EntityHandle* adj_entities_ptr = &adj_entities_out[0];
  int         *  adj_indices_ptr = & adj_indices_out[0];
  int         *      offsets_ptr = &     offsets_out[0];
  
  iMesh_getAdjEntIndices( mInstance, 
                          set, requestor_type, requestor_topo,
                          type_requested,
                          &    entities_ptr, &    entities_alloc, &    entities_size,
                          &adj_entities_ptr, &adj_entities_alloc, &adj_entities_size,
                          & adj_indices_ptr, & adj_indices_alloc, & adj_indices_size,
                          &     offsets_ptr, &     offsets_alloc, &     offsets_size,
                          &err );
  
      entities_out.resize(     entities_size );
  adj_entities_out.resize( adj_entities_size );
   adj_indices_out.resize(  adj_indices_size );
       offsets_out.resize(      offsets_size );
  
  if (iBase_BAD_ARRAY_DIMENSION == err || iBase_BAD_ARRAY_SIZE == err) {
        entities_alloc =     entities_out.size();
    adj_entities_alloc = adj_entities_out.size();
     adj_indices_alloc =  adj_indices_out.size();
         offsets_alloc =      offsets_out.size();
        entities_ptr = &    entities_out[0];
    adj_entities_ptr = &adj_entities_out[0];
     adj_indices_ptr = & adj_indices_out[0];
         offsets_ptr = &     offsets_out[0];

    iMesh_getAdjEntIndices( mInstance, 
                            set, requestor_type, requestor_topo,
                            type_requested,
                            &    entities_ptr, &    entities_alloc, &    entities_size,
                            &adj_entities_ptr, &adj_entities_alloc, &adj_entities_size,
                            & adj_indices_ptr, & adj_indices_alloc, & adj_indices_size,
                            &     offsets_ptr, &     offsets_alloc, &     offsets_size,
                            &err );
  }
  
  return (Error)err;
}
コード例 #3
0
uint8_t ucp::pop_RxdQue_()
{
	static std::vector<char> temp;
	uint16_t tempsize = temp.size();
	
#if 1
	if (ucp_Usart.Get_cbInQue() > 0)
	{		
		temp.resize(tempsize + Usart_->Get_cbInQue(), 0);
		ucp_Usart.PopRxdQueue(&(temp[0]) + tempsize);
	}
#else
	if (Usart_->Get_cbInQue() > 0)
	{
		//temp.resize(tempsize + Usart_->Get_cbInQue(), 0);
		//Usart_->PopRxdQueue(&(temp[0]) + tempsize);
		Usart_->PopRxdQueue((char*)RxdBuf_);
		for (int i = 0; i < min(test, 20); i++)
		{
			std::cout << std::hex << (uint16_t)(uint8_t)RxdBuf_[i] << " ";
		}
		std::cout << std::endl;
	}
#endif
	

	RxdPkgTyp tempPack;
	if (temp.size() < sizeof(tempPack))
		return 0;

	while (true)
	{
		if ((uint8_t)temp[0] == 0x55 &&
			(uint8_t)temp[1] == 0xAA &&
			(uint8_t)temp[sizeof(tempPack)-1] == 0x00)
		{
			/* copy full pack data */
			for (uint16_t i = 0; i < sizeof(tempPack); i++)
			{
				((uint8_t*)&tempPack)[i] = temp[i];
			}
			temp.erase(temp.begin(), temp.begin() + sizeof(tempPack) - 1);

			/* execute */
			Registry_[tempPack.DataIdx]->set(tempPack.Data);
		}
		if (temp.size() <= sizeof(tempPack))
		{
			break;
			// unpack finished
		}
		
		temp.erase(temp.begin());	// pop front
	}

	if (temp.capacity() > 1)
	{
		std::vector<char> rls = temp; //release the memory that allocated by temp
		temp.swap(rls);
#if 0
		if (temp.size() > 0)
		{
			std::cout << (int)&temp[0] << std::endl;
		}
#endif
	}
	return 1;
}
コード例 #4
0
bool GetFileString::GetTString(std::vector<T>& From, std::vector<T>& To, bool bBigEndian)
{
	typedef eol<T> eol;

	bool ExitCode = true;
	T* ReadBufPtr = ReadPos < ReadSize ? From.data() + ReadPos / sizeof(T) : nullptr;

	To.clear();

	// Обработка ситуации, когда у нас пришёл двойной \r\r, а потом не было \n.
	// В этом случаем считаем \r\r двумя MAC окончаниями строк.
	if (bCrCr)
	{
		To.emplace_back(T(eol::cr));
		bCrCr = false;
	}
	else
	{
		EolType Eol = FEOL_NONE;
		for (;;)
		{
			if (ReadPos >= ReadSize)
			{
				if (!(SrcFile.Read(From.data(), ReadBufCount*sizeof(T), ReadSize) && ReadSize))
				{
					if (To.empty())
					{
						ExitCode = false;
					}
					break;
				}

				if (bBigEndian && sizeof(T) != 1)
				{
					_swab(reinterpret_cast<char*>(From.data()), reinterpret_cast<char*>(From.data()), ReadSize);
				}

				ReadPos = 0;
				ReadBufPtr = From.data();
			}
			if (Eol == FEOL_NONE)
			{
				// UNIX
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_UNIX;
				}
				// MAC / Windows? / Notepad?
				else if (*ReadBufPtr == eol::cr)
				{
					Eol = FEOL_MAC;
				}
			}
			else if (Eol == FEOL_MAC)
			{
				// Windows
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_WINDOWS;
				}
				// Notepad?
				else if (*ReadBufPtr == eol::cr)
				{
					Eol = FEOL_MAC2;
				}
				else
				{
					break;
				}
			}
			else if (Eol == FEOL_WINDOWS || Eol == FEOL_UNIX)
			{
				break;
			}
			else if (Eol == FEOL_MAC2)
			{
				// Notepad
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_NOTEPAD;
				}
				else
				{
					// Пришёл \r\r, а \n не пришёл, поэтому считаем \r\r двумя MAC окончаниями строк
					To.pop_back();
					bCrCr = true;
					break;
				}
			}
			else
			{
				break;
			}

			ReadPos += sizeof(T);

			if (To.size() == To.capacity())
				To.reserve(To.size() * 2);

			To.emplace_back(*ReadBufPtr);
			ReadBufPtr++;
		}
	}
	To.push_back(0);
	return ExitCode;
}
コード例 #5
0
ファイル: Bucket.cpp プロジェクト: willmlam/CVO2
int32_t BucketElimination::Bucket::CreateMBPartitioning(int32_t iBound, bool CreateTables, bool doMomentMatching, bool & AbandonIfActualPartitioning, std::vector<int32_t> & key, std::vector<int64_t> & data, std::vector<int32_t> & helperArray)
{
	bool abandonIfActualPartitioning = AbandonIfActualPartitioning ;
	AbandonIfActualPartitioning = false ;

//INT64 tB = ARE::GetTimeInMilliseconds() ;

	// sort functions in the order of decreasing scope size
	int32_t nF = nOriginalFunctions() + nAugmentedFunctions() ;
	if (key.capacity() < nF) { key.reserve(nF) ; if (key.capacity() < nF) goto failed ; }
	if (data.capacity() < nF) { data.reserve(nF) ; if (data.capacity() < nF) goto failed ; }
	key.clear() ; data.clear() ;
	for (int32_t j = _nOriginalFunctions - 1 ; j >= 0 ; j--) {
		ARE::Function *f = _OriginalFunctions[j] ;
		key.push_back(-f->N()) ;
		data.push_back((INT64) f) ;
		if (data.size() != key.size()) {
			fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : data_size!=key_size(1); i=%d, v=%d, nMBs=%d", (int32_t) _IDX, (int32_t) _V, (int32_t) _MiniBuckets.size()) ;
			::fflush(ARE::fpLOG) ;
			goto failed ;
			}
		}
	for (int32_t j = _nAugmentedFunctions - 1 ; j >= 0 ; j--) {
		ARE::Function *f = _AugmentedFunctions[j] ;
		key.push_back(-f->N()) ;
		data.push_back((INT64) f) ;
		if (data.size() != key.size()) {
			fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : data_size!=key_size(2); i=%d, v=%d, nMBs=%d", (int32_t) _IDX, (int32_t) _V, (int32_t) _MiniBuckets.size()) ;
			::fflush(ARE::fpLOG) ;
			goto failed ;
			}
		}
	int32_t left[32], right[32] ;
	QuickSortLong_i64(key.data(), key.size(), data.data(), left, right) ;

/*
INT64 tS = ARE::GetTimeInMilliseconds() ;
if (_IDX < 2000) {
INT64 dt = tS - tB ;
fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning; i=%d, v=%d, iBound=%d, nFNs=%d, sorting time=%lld[msec]", (int32_t) _IDX, (int32_t) _V, (int32_t) iBound, (int32_t) data.size(), dt) ;
::fflush(ARE::fpLOG) ; }*/

#ifdef _DEBUG
		if (_MiniBuckets.size() > 0) {
			int32_t error = 1 ;
			}
		_MiniBuckets.clear() ;
#endif

//INT64 dtSUM1 = 0, dtSUM2 = 0, dtSUM3 = 0 ; ;

		// process functions, one at a time; for each fn, try to add to an existing MB.
		for (int32_t j = 0 ; j < key.size() ; j++) {
			ARE::Function *f = (ARE::Function*) data[j] ;
			bool placed = false ;
			for (MiniBucket *mb : _MiniBuckets) {
//INT64 t1 = ARE::GetTimeInMilliseconds() ;
				int32_t res = mb->AllowsFunction(*f, iBound, helperArray) ;
//INT64 t2 = ARE::GetTimeInMilliseconds() ;
//dtSUM1 += t2 - t1 ;
				if (res < 0) 
					goto failed ;
				if (res > 0) {
					placed = true ;
//INT64 t1_ = ARE::GetTimeInMilliseconds() ;
					if (0 != mb->AddFunction(*f, helperArray)) 
						goto failed ;
//INT64 t2_ = ARE::GetTimeInMilliseconds() ;
//dtSUM2 += t2_ - t1_ ;
					break ;
					}
				}
			if (! placed) {
				if (_MiniBuckets.size() > 0 && abandonIfActualPartitioning) {
					AbandonIfActualPartitioning = true ;
					goto failed ;
					}
//INT64 t3 = ARE::GetTimeInMilliseconds() ;
				MiniBucket *mb = new MiniBucket ;
				if (NULL == mb) 
					goto failed ;
				int32_t existing_size = _MiniBuckets.size() ;
				_MiniBuckets.push_back(mb) ;
				if (_MiniBuckets.size() != (1+existing_size)) 
					{ delete mb ; goto failed ; }
				mb->Initalize(*this, existing_size) ;
				for (int32_t idxV = 0 ; idxV < _nVars ; idxV++) 
					mb->AddVar(_Vars[idxV]) ;
				if (0 != mb->AddFunction(*f, helperArray)) 
					goto failed ;
//INT64 t4 = ARE::GetTimeInMilliseconds() ;
//dtSUM3 += t4 - t3 ;
				}
			}

/*INT64 tMB = ARE::GetTimeInMilliseconds() ;
int32_t div = _IDX%1000 ;
if (_IDX < 2000) {
	INT64 dt = tMB - tS ;
	fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning; i=%d, v=%d, nMBs=%d, nFNs=%d, MB partitioning time=%lld(check=%lld, addfn=%lld, new=%lld)", (int32_t) _IDX, (int32_t) _V, (int32_t) _MiniBuckets.size(), (int32_t) data.size(), dt, dtSUM1, dtSUM2, dtSUM3) ;
	::fflush(ARE::fpLOG) ;
	}*/

	// minibuckets for current bucket are now ready, process each and place resulting function
//dtSUM1 = dtSUM2 = dtSUM3 = 0 ; ;
	for (MiniBucket *mb : _MiniBuckets) {
		ARE::Function & f = mb->OutputFunction() ;
//INT64 t1 = ARE::GetTimeInMilliseconds() ;
		if (0 != mb->ComputeOutputFunctionWithScopeWithoutTable()) {
			fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : mb->ComputeOutputFunctionWithScopeWithoutTable() failed ...") ;
			::fflush(ARE::fpLOG) ;
			goto failed ;
			}
//INT64 t2 = ARE::GetTimeInMilliseconds() ;
//dtSUM1 += t2 - t1 ;
		Bucket *target_bucket = f.Bucket() ; // note target_bucket may be NULL (i.e. when 0==f.N())
		for (Bucket *mb_b = ParentBucket() ; mb_b != target_bucket && NULL != mb_b ; mb_b = mb_b->ParentBucket()) {
//t1 = ARE::GetTimeInMilliseconds() ;
//dtSUM1 += t2 - t1 ;
			if (0 != mb_b->AddIntermediateFunction(f)) {
				fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : mb_b->AddIntermediateFunction() failed ...") ;
				::fflush(ARE::fpLOG) ;
				goto failed ;
				}
//t2 = ARE::GetTimeInMilliseconds() ;
//dtSUM2 += t2 - t1 ;
			}
		if (NULL != target_bucket) {
//t1 = ARE::GetTimeInMilliseconds() ;
			if (0 != target_bucket->AddAugmentedFunction(f)) {
				fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : target_bucket->AddAugmentedFunction() failed ...") ;
				::fflush(ARE::fpLOG) ;
				goto failed ;
				}
//t2 = ARE::GetTimeInMilliseconds() ;
//dtSUM3 += t2 - t1 ;
			}
		}

/*INT64 tE = ARE::GetTimeInMilliseconds() ;
if (_IDX < 2000) {
INT64 dt = tE - tMB ;
fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning; i=%d, v=%d, MB placing  time=%lld[msec] compOFN=%lld +IFN=%lld +AFN=%lld", (int32_t) _IDX, (int32_t) _V, dt, dtSUM1, dtSUM2, dtSUM3) ;
::fflush(ARE::fpLOG) ; }*/

	// if requested, do moment-matching
	if (CreateTables) {
//INT64 t1 = ARE::GetTimeInMilliseconds() ;
		if (0 != ComputeOutputFunctions(doMomentMatching)) {
			fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : mb->ComputeOutputFunction() failed ...") ;
			::fflush(ARE::fpLOG) ;
			goto failed ;
			}
/*INT64 t2 = ARE::GetTimeInMilliseconds() ;
INT64 dt = t2 - t1 ;
if (_IDX < 2000) {
INT64 dt = t2 - t1 ;
fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning; i=%d, v=%d, ComputeOutputFunctions doMomentMatching=%c time=%lld[msec]", (int32_t) _IDX, (int32_t) _V, doMomentMatching ? 'Y' : 'N', dt) ;
::fflush(ARE::fpLOG) ; }*/
		}

	return 0 ;
failed :
	fprintf(ARE::fpLOG, "\n   BucketElimination::Bucket::CreateMBPartitioning ERROR : failed label reached (AbandonIfActualPartitioning=%c) ...", AbandonIfActualPartitioning ? 'Y' : 'N') ;
	::fflush(ARE::fpLOG) ;
	DestroyPartitioning() ;
	return 1 ;
}
コード例 #6
0
ファイル: memory_buffer.cpp プロジェクト: TWhidden/libuvxx
 size_t capacity_get() const
 {
     return _buffer.capacity();
 }
コード例 #7
0
 void add( const entry& p )
 {
     if( points.size() == points.capacity() ) { points.reserve( 2048 ); } // quick and dirty
     points.push_back( p );
 }
コード例 #8
0
ファイル: SmartWindowing.cpp プロジェクト: flyfj/RGBDMaze
void GetWindows(const cv::Mat& integral_image, std::vector<Shape::Rectangle>& rectangles, const float threshold, const float dist_threshold, std::vector<Shape::Rectangle>& windows, bool append)
{
  // Init windows.
  if (windows.capacity() < rectangles.size()) windows.reserve(rectangles.size());
  if (!append) windows.clear();

  // Create disjoint set vector.
  DisjointSetVector<Shape::Rectangle> disjoint_set(rectangles);

  // Compute edges.
  std::vector<Edge > edges;
  GetEdges<integral_type, mean_type>(integral_image, disjoint_set, edges);

  // Sort edges.
  std::sort(edges.begin(), edges.end());

  // Merge nodes.
  for (std::vector<Edge >::iterator edge = edges.begin(); edge != edges.end(); edge++)
  {
    edge->Union((Edge::weight_type)threshold);
  }

  // Get segments.
  std::vector<std::vector<std::vector<Shape::Rectangle>::iterator> > sparse_segments(disjoint_set.size());
  for (DisjointSetVector<Shape::Rectangle>::iterator node = disjoint_set.begin(); node != disjoint_set.end(); node++)
  {
    DisjointSetVector<Shape::Rectangle>::pointer root = node->FindRoot();
    const size_t id = root - &*disjoint_set.begin();
    sparse_segments[id].push_back(node->value());
  }

  size_t min_area = (integral_image.rows - 1) * (integral_image.cols - 1) / 400;
  for (std::vector<std::vector<std::vector<Shape::Rectangle>::iterator> >::iterator sparse_segment = sparse_segments.begin(); sparse_segment != sparse_segments.end(); sparse_segment++)
  {
    if (!sparse_segment->size() || (sparse_segment->size() == 1 && RectangleArea(*(*sparse_segment)[0]) < min_area)) continue;
    Shape::Rectangle window = {integral_image.cols, integral_image.rows, 0, 0};
    for (std::vector<std::vector<Shape::Rectangle>::iterator>::iterator rectangle = sparse_segment->begin(); rectangle != sparse_segment->end(); rectangle++)
    {
      const Shape::Rectangle& r = **rectangle;
      window.x1 = std::min(window.x1, r.x1);
      window.y1 = std::min(window.y1, r.y1);
      window.x2 = std::max(window.x2, r.x2);
      window.y2 = std::max(window.y2, r.y2);
    }
    windows.push_back(window);
  }

  // Also include nearby windows.
  if (dist_threshold <= 0) return;
  const int end = windows.size();
  for (int i1 = 0; i1 < end; i1++)
  {
    for (int i2 = i1 + 1; i2 < end; i2++)
    {
      const Shape::Rectangle& window1 = windows[i1];
      const Shape::Rectangle& window2 = windows[i2];

      // No need to merge inside windows.
      if (IsRectangleInside(window1, window2) || IsRectangleInside(window2, window1) || NormalizedRectangleDist(window2, window1) > 0.5) continue;
      Shape::Rectangle window = {std::min(window1.x1, window2.x1), std::min(window1.y1, window2.y1), std::max(window1.x2, window2.x2), std::max(window1.y2, window2.y2)};
      windows.push_back(window);
    }
  }
}
コード例 #9
0
ファイル: SmartWindowing.cpp プロジェクト: flyfj/RGBDMaze
void GetWindows(const cv::Mat& integral_image, std::vector<Shape::Rectangle>& rectangles, std::vector<float>& thresholds, const float dist_threshold, std::vector<Shape::Rectangle>& windows)
{
  // Init windows.
  if (windows.capacity() < rectangles.size()) windows.reserve(rectangles.size());
  windows.clear();

  // Create disjoint set vector.
  DisjointSetVector<Shape::Rectangle> disjoint_set(rectangles);

  // Compute edges.
  std::vector<Edge > edges;
  GetEdges<integral_type, mean_type>(integral_image, disjoint_set, edges);

  // Sort edges.
  std::sort(edges.begin(), edges.end());

  // Sort threshold.
  std::sort(thresholds.begin(), thresholds.end());

  // Merge nodes.
  std::vector<std::vector<std::vector<Shape::Rectangle>::iterator> > sparse_segments(disjoint_set.size());
  std::vector<size_t> sparse_segment_sizes(disjoint_set.size(), 0);
  std::vector<Edge > unmerged_edges;
  unmerged_edges.reserve(edges.size());
  const size_t min_area = (integral_image.rows - 1) * (integral_image.cols - 1) / 400;

  std::vector<Shape::Rectangle> small_windows;
  if (dist_threshold > 0) small_windows.reserve(rectangles.size());
  for (int k = 0; k < thresholds.size(); k++)
  {
    const float threshold = thresholds[k];
    std::vector<Edge >& merging = k & 1 ? unmerged_edges : edges;
    std::vector<Edge >& unmerged = k & 1 ? edges : unmerged_edges;
    unmerged.clear();
    for (std::vector<Edge >::iterator edge = merging.begin(); edge != merging.end(); edge++)
    {
      if (!edge->Union((Edge::weight_type)threshold))
      {
        unmerged.push_back(*edge);
      }
    }

    // Get segments.
    for (DisjointSetVector<Shape::Rectangle>::iterator node = disjoint_set.begin(); node != disjoint_set.end(); node++)
    {
      DisjointSetVector<Shape::Rectangle>::pointer root = node->FindRoot();
      const size_t id = root - &*disjoint_set.begin();
      sparse_segments[id].push_back(node->value());
    }

    // Get windows.
    std::vector<size_t>::iterator sparse_segment_size = sparse_segment_sizes.begin();
    for (std::vector<std::vector<std::vector<Shape::Rectangle>::iterator> >::iterator sparse_segment = sparse_segments.begin(); sparse_segment != sparse_segments.end(); sparse_segment++, sparse_segment_size++)
    {
      if (sparse_segment->size() && sparse_segment->size() != *sparse_segment_size)
      {
        if (sparse_segment->size() != 1 || RectangleArea(*(*sparse_segment)[0]) > min_area)
        {
          Shape::Rectangle window = {integral_image.cols, integral_image.rows, 0, 0};
          for (std::vector<std::vector<Shape::Rectangle>::iterator>::iterator rectangle = sparse_segment->begin(); rectangle != sparse_segment->end(); rectangle++)
          {
            const Shape::Rectangle& r = **rectangle;
            window.x1 = std::min(window.x1, r.x1);
            window.y1 = std::min(window.y1, r.y1);
            window.x2 = std::max(window.x2, r.x2);
            window.y2 = std::max(window.y2, r.y2);
          }
          windows.push_back(window);
        }
        else if (!k && dist_threshold > 0)
        {
          Shape::Rectangle window = {integral_image.cols, integral_image.rows, 0, 0};
          for (std::vector<std::vector<Shape::Rectangle>::iterator>::iterator rectangle = sparse_segment->begin(); rectangle != sparse_segment->end(); rectangle++)
          {
            const Shape::Rectangle& r = **rectangle;
            window.x1 = std::min(window.x1, r.x1);
            window.y1 = std::min(window.y1, r.y1);
            window.x2 = std::max(window.x2, r.x2);
            window.y2 = std::max(window.y2, r.y2);
          }
          small_windows.push_back(window);
        }
      }
      *sparse_segment_size = sparse_segment->size();
      sparse_segment->clear();
    }
  }

  // Also include nearby windows.
  if (dist_threshold <= 0) return;
  const int end = windows.size();
  for (int i1 = 0; i1 < end; i1++)
  {
    for (int i2 = i1 + 1; i2 < end; i2++)
    {
      const Shape::Rectangle& window1 = windows[i1];
      const Shape::Rectangle& window2 = windows[i2];

      // No need to merge inside windows.
      if (IsRectangleInside(window1, window2) || IsRectangleInside(window2, window1) || NormalizedRectangleDist(window2, window1) > dist_threshold) continue;
      Shape::Rectangle window = {std::min(window1.x1, window2.x1), std::min(window1.y1, window2.y1), std::max(window1.x2, window2.x2), std::max(window1.y2, window2.y2)};
      windows.push_back(window);
    }

    for (std::vector<Shape::Rectangle>::iterator small_window = small_windows.begin(); small_window != small_windows.end(); small_window++)
    {
      const Shape::Rectangle& window1 = windows[i1];
      const Shape::Rectangle& window2 = *small_window;

      // No need to merge inside windows.
      if (IsRectangleInside(window1, window2) || IsRectangleInside(window2, window1) || NormalizedRectangleDist(window2, window1) > dist_threshold) continue;
      Shape::Rectangle window = {std::min(window1.x1, window2.x1), std::min(window1.y1, window2.y1), std::max(window1.x2, window2.x2), std::max(window1.y2, window2.y2)};
      windows.push_back(window);
    }
  }
}
コード例 #10
0
ファイル: RegistrationTools.cpp プロジェクト: eile/trunk
int FPCSRegistrationTools::FindCongruentBases(KDTree* tree,
												ScalarType delta,
												const CCVector3* base[4],
												std::vector<Base>& results)
{
    //Compute reference base invariants (r1, r2)
    PointCoordinateType r1, r2, d1, d2;
	{
		const CCVector3* p0 = base[0];
		const CCVector3* p1 = base[1];
		const CCVector3* p2 = base[2];
		const CCVector3* p3 = base[3];

		d1 = (*p1-*p0).norm();
		d2 = (*p3-*p2).norm();

		CCVector3 inter;
		if (!LinesIntersections(*p0, *p1, *p2, *p3, inter, r1, r2))
			return 0;
	}

	GenericIndexedCloud* cloud = tree->getAssociatedCloud();

	//Find all pairs which are d1-appart and d2-appart
    std::vector<IndexPair> pairs1, pairs2;
	{
		unsigned count = (unsigned)cloud->size();
		std::vector<unsigned> pointsIndexes;
		try
		{
			pointsIndexes.reserve(count);
		}
		catch(...)
		{
			//not enough memory
			return -1;
		}

		for (unsigned i=0; i<count; i++)
		{
			const CCVector3 *q0 = cloud->getPoint(i);
			IndexPair idxPair;
			idxPair.first = i;
			//Extract all points from the cloud which are d1-appart (up to delta) from q0
			pointsIndexes.clear();
			tree->findPointsLyingToDistance(q0->u, static_cast<ScalarType>(d1), delta, pointsIndexes);
			{
				for(size_t j=0; j<pointsIndexes.size(); j++)
				{
					//As ||pi-pj|| = ||pj-pi||,  we only take care of pairs that verify i<j
					if (pointsIndexes[j]>i)
					{
						idxPair.second = pointsIndexes[j];
						pairs1.push_back(idxPair);
					}
				}
			}
			//Extract all points from the cloud which are d2-appart (up to delta) from q0
			pointsIndexes.clear();
			tree->findPointsLyingToDistance(q0->u, static_cast<ScalarType>(d2), delta, pointsIndexes);
			{
				for(size_t j=0; j<pointsIndexes.size(); j++)
				{
					if (pointsIndexes[j]>i)
					{
						idxPair.second = pointsIndexes[j];
						pairs2.push_back(idxPair);
					}
				}
			}
		}
	}

    //Select among the pairs the ones that can be congruent to the base "base"
	std::vector<IndexPair> match;
	{
		SimpleCloud tmpCloud1,tmpCloud2;
		{
			unsigned count = (unsigned)pairs1.size();
			if (!tmpCloud1.reserve(count*2)) //not enough memory
				return -2;
			for(unsigned i=0; i<count; i++)
			{
				//generate the two intermediate points from r1 in pairs1[i]
				const CCVector3 *q0 = cloud->getPoint(pairs1[i].first);
				const CCVector3 *q1 = cloud->getPoint(pairs1[i].second);
				CCVector3 P1 = *q0 + r1*(*q1-*q0);
				tmpCloud1.addPoint(P1);
				CCVector3 P2 = *q1 + r1*(*q0-*q1);
				tmpCloud1.addPoint(P2);
			}
		}
	
		{
			unsigned count = (unsigned)pairs2.size();
			if (!tmpCloud2.reserve(count*2)) //not enough memory
				return -3;
			for(unsigned i=0; i<count; i++)
			{
				//generate the two intermediate points from r2 in pairs2[i]
				const CCVector3 *q0 = cloud->getPoint(pairs2[i].first);
				const CCVector3 *q1 = cloud->getPoint(pairs2[i].second);
				CCVector3 P1 = *q0 + r2*(*q1-*q0);
				tmpCloud2.addPoint(P1);
				CCVector3 P2 = *q1 + r2*(*q0-*q1);
				tmpCloud2.addPoint(P2);
			}
		}

		//build kdtree for nearest neighbour fast research
		KDTree intermediateTree;
		if (!intermediateTree.buildFromCloud(&tmpCloud1))
			return -4;

		//Find matching (up to delta) intermediate points in tmpCloud1 and tmpCloud2
		{
			unsigned count = (unsigned)tmpCloud2.size();
			match.reserve(count);
			if (match.capacity() < count)  //not enough memory
				return -5;
		
			for(unsigned i=0; i<count; i++)
			{
				const CCVector3 *q0 = tmpCloud2.getPoint(i);
				unsigned a;
				if (intermediateTree.findNearestNeighbour(q0->u, a, delta))
				{
					IndexPair idxPair;
					idxPair.first = i;
					idxPair.second = a;
					match.push_back(idxPair);
				}
			}
		}
	}

    //Find bases from matching intermediate points indexes
	{
		results.clear();
		size_t count = match.size();
		if (count>0)
		{
			results.reserve(count);
			if (results.capacity() < count)  //not enough memory
				return -6;
			for(size_t i=0; i<count; i++)
			{
				Base quad;
				unsigned b = match[i].second / 2;
				if ((match[i].second % 2) == 0)
				{
					quad.a = pairs1[b].first;
					quad.b = pairs1[b].second;
				}
				else
				{
					quad.a = pairs1[b].second;
					quad.b = pairs1[b].first;
				}
            
				unsigned a = match[i].first / 2;
				if ((match[i].first % 2) == 0)
				{
					quad.c = pairs2[a].first;
					quad.d = pairs2[a].second;
				}
				else
				{
					quad.c = pairs2[a].second;
					quad.d = pairs2[a].first;
				}
				results.push_back(quad);
			}
		}
	}

    return (int)results.size();
}
コード例 #11
0
ファイル: 09.38.cpp プロジェクト: charlie-lee/cpp_primer
void PrintCapNSize(const std::vector<int> &vi)
{
    std::cout << "size: " << vi.size()
              << ", capacity: " << vi.capacity()
              << std::endl;
}
コード例 #12
0
ファイル: RegistrationTools.cpp プロジェクト: eile/trunk
bool FPCSRegistrationTools::FilterCandidates(
        GenericIndexedCloud *modelCloud,
        GenericIndexedCloud *dataCloud,
        Base& reference,
        std::vector<Base>& candidates,
        unsigned nbMaxCandidates,
        std::vector<ScaledTransformation>& transforms)
{
    std::vector<Base> table;
    std::vector<float> scores, sortedscores;
    const CCVector3 *p[4], *q;
    unsigned i, j;
    ScaledTransformation t;
    std::vector<ScaledTransformation> tarray;
    SimpleCloud referenceBaseCloud, dataBaseCloud;

	unsigned candidatesCount = (unsigned)candidates.size();
    if (candidatesCount == 0)
        return false;

    bool filter = (nbMaxCandidates>0 && candidatesCount>nbMaxCandidates);
	try
	{
		table.resize(candidatesCount);
	}
	catch (.../*const std::bad_alloc&*/) //out of memory
	{
		return false;
	}
    for(i=0; i<candidatesCount; i++)
        table[i].copy(candidates[i]);

    if (!referenceBaseCloud.reserve(4)) //we never know ;)
		return false;

    for(j=0; j<4; j++)
    {
        p[j] = modelCloud->getPoint(reference.getIndex(j));
        referenceBaseCloud.addPoint(*p[j]);
    }

	try
	{
		scores.reserve(candidatesCount);
		sortedscores.reserve(candidatesCount);
		tarray.reserve(candidatesCount);
		transforms.reserve(candidatesCount);
	}
	catch (.../*const std::bad_alloc&*/) //out of memory
	{
		return false;
	}

	//enough memory?
	if (scores.capacity() < candidatesCount 
		|| sortedscores.capacity() < candidatesCount 
		|| tarray.capacity() < candidatesCount 
		|| transforms.capacity() < candidatesCount)
	{
		return false;
	}

    for(i=0; i<table.size(); i++)
    {
        dataBaseCloud.clear();
        if (!dataBaseCloud.reserve(4)) //we never know ;)
			return false;
        for(j=0; j<4; j++)
            dataBaseCloud.addPoint(*dataCloud->getPoint(table[i].getIndex(j)));

        if (!RegistrationTools::RegistrationProcedure(&dataBaseCloud, &referenceBaseCloud, t, false))
            return false;

        tarray.push_back(t);
        if (filter)
        {
            float score = 0;
			GenericIndexedCloud* b = PointProjectionTools::applyTransformation(&dataBaseCloud, t);
			if (!b)
				return false; //not enough memory
            for (j=0; j<4; j++)
            {
                q = b->getPoint(j);
                score += static_cast<float>((*q - *(p[j])).norm());
            }
            delete b;
            scores.push_back(score);
            sortedscores.push_back(score);
        }
    }

    if (filter)
    {
        transforms.clear();
        candidates.clear();
		try
		{
			candidates.resize(nbMaxCandidates);
		}
		catch (.../*const std::bad_alloc&*/) //out of memory
		{
			return false;
		}
		candidatesCount=nbMaxCandidates;

        //Sort the scores in ascending order and only keep the nbMaxCandidates smallest scores
        sort(sortedscores.begin(), sortedscores.end());
        float score = sortedscores[nbMaxCandidates-1];
        j = 0;
        for(i=0; i<scores.size(); i++)
        {
            if (scores[i]<=score && j<nbMaxCandidates)
            {
                candidates[i].copy(table[i]);
                transforms.push_back(tarray[i]);
                j++;
            }
        }
    }
    else
	{
        transforms = tarray;
	}

    return true;
}
コード例 #13
0
bool ParallelIsAMatch(compat_classad::ClassAd *ad1, std::vector<compat_classad::ClassAd*> &candidates, std::vector<compat_classad::ClassAd*> &matches, int threads, bool halfMatch)
{
	int adCount = candidates.size();
	static int cpu_count = 0;
	int current_cpu_count = threads;
	int iterations = 0;
	size_t matched = 0;

	if(cpu_count != current_cpu_count)
	{
		cpu_count = current_cpu_count;
		if(match_pool)
		{
			delete[] match_pool;
			match_pool = NULL;
		}
		if(target_pool)
		{
			delete[] target_pool;
			target_pool = NULL;
		}
		if(matched_ads)
		{
			delete[] matched_ads;
			matched_ads = NULL;
		}
	}

	if(!match_pool)
		match_pool = new classad::MatchClassAd[cpu_count];
	if(!target_pool)
		target_pool = new compat_classad::ClassAd[cpu_count];
	if(!matched_ads)
		matched_ads = new std::vector<compat_classad::ClassAd*>[cpu_count];

	if(!candidates.size())
		return false;

	for(int index = 0; index < cpu_count; index++)
	{
		target_pool[index].CopyFrom(*ad1);
		match_pool[index].ReplaceLeftAd(&(target_pool[index]));
		matched_ads[index].clear();
	}

	iterations = ((candidates.size() - 1) / cpu_count) + 1;

#ifdef _OPENMP
	omp_set_num_threads(cpu_count);
#endif

#pragma omp parallel
	{

#ifdef _OPENMP
		int omp_id = omp_get_thread_num();
#else
		int omp_id = 0;
#endif
		for(int index = 0; index < iterations; index++)
		{
			bool result = false;
			int offset = omp_id + index * cpu_count;
			if(offset >= adCount)
				break;
			compat_classad::ClassAd *ad2 = candidates[offset];

/*
			if(halfMatch)
			{
				char const *my_target_type = target_pool[omp_id].GetTargetTypeName();
				char const *target_type = ad2->GetMyTypeName();
				if( !my_target_type ) {
					my_target_type = "";
				}
				if( !target_type ) {
					target_type = "";
				}
				if( strcasecmp(target_type,my_target_type) &&
					strcasecmp(my_target_type,ANY_ADTYPE) )
				{
					result = false;
					continue;
				}
			}
*/


			match_pool[omp_id].ReplaceRightAd(ad2);
			if ( !compat_classad::ClassAd::m_strictEvaluation )
			{
				target_pool[omp_id].alternateScope = ad2;
				ad2->alternateScope = &(target_pool[omp_id]);
			}
		
			if(halfMatch)
				result = match_pool[omp_id].rightMatchesLeft();
			else
				result = match_pool[omp_id].symmetricMatch();

			match_pool[omp_id].RemoveRightAd();

			if(result)
			{
				matched_ads[omp_id].push_back(ad2);
			}
		}
	}

	for(int index = 0; index < cpu_count; index++)
	{
		match_pool[index].RemoveLeftAd();
		matched += matched_ads[index].size();
	}

	if(matches.capacity() < matched)
		matches.reserve(matched);

	for(int index = 0; index < cpu_count; index++)
	{
		if(matched_ads[index].size())
			matches.insert(matches.end(), matched_ads[index].begin(), matched_ads[index].end());
	}

	return matches.size() > 0;
}
コード例 #14
0
/*
 * ExampleTest.cpp
 *
 *  Created on: Nov 12, 2015
 *      Author: mobile
 */

#include "catch.hpp"

TEST_CASE( "vectors can be sized and resized", "[vector]" ) {

    std::vector<int> v( 5 );

    REQUIRE( v.size() == 5 );
    REQUIRE( v.capacity() >= 5 );

    SECTION( "resizing bigger changes size and capacity" ) {
        v.resize( 10 );

        REQUIRE( v.size() == 10 );
        REQUIRE( v.capacity() >= 10 );
    }
    SECTION( "resizing smaller changes size but not capacity" ) {
        v.resize( 0 );

        REQUIRE( v.size() == 0 );
        REQUIRE( v.capacity() >= 5 );
    }
    SECTION( "reserving bigger changes capacity but not size" ) {
        v.reserve( 10 );
コード例 #15
0
ファイル: main.cpp プロジェクト: renmaoting/616
void printStats(const std::vector<int>& vec) {
  std::cout << "size: " << vec.size() << ", ";
  std::cout << "cap: " << vec.capacity() << std::endl;
}
コード例 #16
0
ファイル: HTTPStream.cpp プロジェクト: apache/nifi-minifi-cpp
int HttpStream::writeData(std::vector<uint8_t> &buf, int buflen) {
  if ((int) buf.capacity() < buflen) {
    return -1;
  }
  return writeData(reinterpret_cast<uint8_t *>(&buf[0]), buflen);
}
コード例 #17
0
 uint64_t Capacity() { return v.capacity(); }
コード例 #18
0
static inline void shrinkVecToFit(std::vector<Ty_>& vec) {
	if (vec.capacity() != vec.size())
		std::vector<Ty_>(vec).swap(vec);
}