Example #1
0
void search_ND(int items){
	std::vector< Rect<size> > rectangles;
	unsigned int edge_size = (unsigned int)ceil(pow((double)items, 1.0 / (double)size));
	int no_iterations = std::max(max_elements / items, 10);
	generateRectangles(items, edge_size, rectangles);

	RTree<int, unsigned int, size, float> tree;

	for (size_t i = 0; i < rectangles.size(); ++i){
		tree.Insert(rectangles[i].min, rectangles[i].max, i);
	}

	auto begin = std::chrono::high_resolution_clock::now();

	for (int i = 0; i < no_iterations; i++){
		std::vector<unsigned int> min(size, 0);

		for (unsigned int j = 0; j < edge_size; ++j){
			std::vector<unsigned int> max(size, (j + 1)*tile_size);

			Rect<size> search_rect(min, max);
			int nhits = tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);
		}

	}

	auto end = std::chrono::high_resolution_clock::now();

	of << "Running " << edge_size << "queries on " << size << "D items:" << (double)std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / (double)no_iterations << "ns" << std::endl;
}
Example #2
0
void pointQueries_ND(int items){
	std::vector< Rect<size> > rectangles;
	std::vector< Rect<size> > queries;
	unsigned int edge_size = (unsigned int)ceil(pow((double)items, 1.0 / (double)size));
	int no_iterations = std::max(max_elements / items, 10);
	generateRectangles(items, edge_size, rectangles);

	RTree<int, unsigned int, size, float> tree;

	for (size_t i = 0; i < rectangles.size(); ++i){
		tree.Insert(rectangles[i].min, rectangles[i].max, i);
		std::vector<unsigned int> min(size, i*tile_size+1);
		std::vector<unsigned int> max(size, i*tile_size+1);
		Rect<size> pointQuery(min, max);
		queries.push_back(pointQuery);
	}

	auto begin = std::chrono::high_resolution_clock::now();

	for (int i = 0; i < no_iterations; i++){
		for (size_t j = 0; j < queries.size(); j++){
			tree.Search(queries[j].min, queries[j].max, MySearchCallback, NULL);
		}
	}

	auto end = std::chrono::high_resolution_clock::now();

	of << "Running " << queries.size() << " point queries " << size << "D items:" << (double)std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / (double)no_iterations << "ns" << std::endl;
}
Example #3
0
void TestRTree::testIntersectingPairs()
{
    RTree<SharedTestClass> tree;
    tree.insert(QRect(1, 1, 1, 1), new DerivedClass(QString("foo")));
    QList< QPair<QRectF, SharedTestClass> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QVERIFY(pairs.count() == 1);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 1, 1));
    QCOMPARE(pairs[0].second->member, QString("foo"));
    QCOMPARE(pairs[0].second->type(), 1);
}
Example #4
0
void TestRTree::testRemoveRows()
{
    RTree<QString> tree;
    tree.insert(QRect(1, 1, 1, 2), QString("1"));
    tree.insert(QRect(2, 1, 1, 3), QString("2"));
    tree.insert(QRect(3, 2, 1, 4), QString("3"));
    tree.insert(QRect(4, 2, 1, 5), QString("4"));
    tree.insert(QRect(5, 3, 1, 3), QString("5"));
    tree.insert(QRect(6, 3, 1, 4), QString("6"));
    tree.insert(QRect(7, 4, 1, 2), QString("7"));
    tree.insert(QRect(8, 4, 1, 3), QString("8"));
    tree.insert(QRect(9, 6, 1, 3), QString("9"));
    QList< QPair<QRectF, QString> > undo = tree.removeRows(3, 3);
    QList< QPair<QRectF, QString> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QCOMPARE(pairs.count(), 7);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 1, 2));
    QCOMPARE(pairs[0].second, QString("1"));
    QCOMPARE(pairs[1].first, QRectF(2, 1, 1, 2));
    QCOMPARE(pairs[1].second, QString("2"));
    QCOMPARE(pairs[2].first, QRectF(3, 2, 1, 1));
    QCOMPARE(pairs[2].second, QString("3"));
    QCOMPARE(pairs[3].first, QRectF(4, 2, 1, 2));
    QCOMPARE(pairs[3].second, QString("4"));
    QCOMPARE(pairs[4].first, QRectF(6, 3, 1, 1));
    QCOMPARE(pairs[4].second, QString("6"));
    QCOMPARE(pairs[5].first, QRectF(8, 3, 1, 1));
    QCOMPARE(pairs[5].second, QString("8"));
    QCOMPARE(pairs[6].first, QRectF(9, 3, 1, 3));
    QCOMPARE(pairs[6].second, QString("9"));
    QCOMPARE(undo.count(), 2);
    QCOMPARE(undo[0].first.toRect(), QRect(5, 3, 1, 3));
    QCOMPARE(undo[0].second, QString("5"));
    QCOMPARE(undo[1].first.toRect(), QRect(7, 4, 1, 2));
    QCOMPARE(undo[1].second, QString("7"));
}
Example #5
0
void TestRTree::testInsertShiftDown()
{
    RTree<SharedTestClass> tree;
    tree.insert(QRect(2, 2, 1, 2), new DerivedClass(QString("foo")));
    tree.insertShiftDown(QRect(2, 1, 4, 3));
    QList< QPair<QRectF, SharedTestClass> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QCOMPARE(pairs.count(), 3);
    QCOMPARE(pairs[0].first, QRectF(2, 2, 1, 2));
    QCOMPARE(pairs[0].second->member, QString("foo"));
    QCOMPARE(pairs[1].first, QRectF(2, 1, 4, KS_rowMax));
    QCOMPARE(pairs[1].second->member, QString(""));
    QCOMPARE(pairs[2].first, QRectF(2, 5, 1, 2));
    QCOMPARE(pairs[2].second->member, QString("foo"));
}
Example #6
0
void TestRTree::testRemoveShiftLeft()
{
    RTree<SharedTestClass> tree;
    tree.insert(QRect(5, 2, 2, 1), new DerivedClass(QString("foo")));
    tree.removeShiftLeft(QRect(2, 1, 3, 4));
    QList< QPair<QRectF, SharedTestClass> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QCOMPARE(pairs.count(), 3);
    QCOMPARE(pairs[0].first, QRectF(5, 2, 2, 1));
    QCOMPARE(pairs[0].second->member, QString("foo"));
    QCOMPARE(pairs[1].first, QRectF(2, 1, KS_colMax - 1, 4));
    QCOMPARE(pairs[1].second->member, QString(""));
    QCOMPARE(pairs[2].first, QRectF(2, 2, 2, 1));
    QCOMPARE(pairs[2].second->member, QString("foo"));
}
Example #7
0
void main()
{
    RTree<int, int, 2, float> tree;

    int i, nhits;
    printf("nrects = %d\n", nrects);

    for(i=0; i<nrects; i++)
    {
        tree.Insert(rects[i].min, rects[i].max, i); // Note, all values including zero are fine in this version
    }

    nhits = tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);

    printf("Search resulted in %d hits\n", nhits);

    // Iterator test
    int itIndex = 0;
    RTree<int, int, 2, float>::Iterator it;
    for( tree.GetFirst(it);
            !tree.IsNull(it);
            tree.GetNext(it) )
    {
        int value = tree.GetAt(it);

        int boundsMin[2] = {0,0};
        int boundsMax[2] = {0,0};
        it.GetBounds(boundsMin, boundsMax);
        printf("it[%d] %d = (%d,%d,%d,%d)\n", itIndex++, value, boundsMin[0], boundsMin[1], boundsMax[0], boundsMax[1]);
    }

    // Iterator test, alternate syntax
    itIndex = 0;
    tree.GetFirst(it);
    while( !it.IsNull() )
    {
        int value = *it;
        ++it;
        printf("it[%d] %d\n", itIndex++, value);
    }

    getchar(); // Wait for keypress on exit so we can read console output

    // Output:
    //
    // nrects = 4
    // Hit data rect 1
    // Hit data rect 2
    // Search resulted in 2 hits
    // it[0] 0 = (0,0,2,2)
    // it[1] 1 = (5,5,7,7)
    // it[2] 2 = (8,5,9,6)
    // it[3] 3 = (7,1,9,2)
    // it[0] 0
    // it[1] 1
    // it[2] 2
    // it[3] 3
}
bool inExclusionZone(
  SPoint2 &p,
  RTree<surfacePointWithExclusionRegion *, double, 2, double> &rtree,
  std::vector<surfacePointWithExclusionRegion *> &all)
{
  // should assert that the point is inside the domain
  // OLD BGM
  if(old_algo_hexa()) {
    if(!backgroundMesh::current()->inDomain(p.x(), p.y(), 0)) return true;
  }
  else {
    // NEW BGM
    if(!BGMManager::current2D()->inDomain(p.x(), p.y(), 0)) return true;
  }

  my_wrapper w(p);
  double _min[2] = {p.x() - 1.e-1, p.y() - 1.e-1},
         _max[2] = {p.x() + 1.e-1, p.y() + 1.e-1};
  rtree.Search(_min, _max, rtree_callback, &w);

  return w._tooclose;

  for(unsigned int i = 0; i < all.size(); ++i) {
    if(all[i]->inExclusionZone(p)) {
      // printf("%g %g is in exclusion zone of %g
      //        %g\n",p.x(),p.y(),all[i]._center.x(),all[i]._center.y());
      return true;
    }
  }
  return false;
}
Example #9
0
  bool filteringCallback( PointSet *pset, void *ctx )
  {

    RTree<LabelPosition*, double, 2, double> *cdtsIndex = (( FilterContext* ) ctx )->cdtsIndex;
    double scale = (( FilterContext* ) ctx )->scale;
    Pal* pal = (( FilterContext* )ctx )->pal;

    double amin[2], amax[2];
    pset->getBoundingBox( amin, amax );

    LabelPosition::PruneCtx pruneContext;

    pruneContext.scale = scale;
    pruneContext.obstacle = pset;
    pruneContext.pal = pal;
    cdtsIndex->Search( amin, amax, LabelPosition::pruneCallback, ( void* ) &pruneContext );

    return true;
  }
Example #10
0
void read(const cv::FileNode& node, RTree &f, const RTree& default_value)
{
	if (node.empty())
	{
		f = default_value;
		cout << "! One default Regressor." << endl;
	}
	else
		f.read(node);
}
Example #11
0
bool filteringCallback( FeaturePart *featurePart, void *ctx )
{

  RTree<LabelPosition *, double, 2, double> *cdtsIndex = ( reinterpret_cast< FilterContext * >( ctx ) )->cdtsIndex;
  Pal *pal = ( reinterpret_cast< FilterContext * >( ctx ) )->pal;

  if ( pal->isCanceled() )
    return false; // do not continue searching

  double amin[2], amax[2];
  featurePart->getBoundingBox( amin, amax );

  LabelPosition::PruneCtx pruneContext;
  pruneContext.obstacle = featurePart;
  pruneContext.pal = pal;
  cdtsIndex->Search( amin, amax, LabelPosition::pruneCallback, static_cast< void * >( &pruneContext ) );

  return true;
}
Example #12
0
void insert_ND(int items){
	std::vector< Rect<size> > rectangles;
	int no_iterations = std::max(max_elements / items, 10);
	unsigned int edge_size = (unsigned int)ceil(pow((double)items, 1.0 / (double)size));
	generateRectangles(items, edge_size, rectangles);

	auto begin = std::chrono::high_resolution_clock::now();

	for (int i = 0; i < no_iterations; i++){
		RTree<unsigned int, unsigned int, size, float> tree;

		for (size_t j = 0; j < rectangles.size(); ++j){
			tree.Insert(rectangles[j].min, rectangles[j].max, j);
		}
	}

	auto end = std::chrono::high_resolution_clock::now();

	of << "Inserting " << rectangles.size() << " " << size << "D items:" << (double)std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / (double)no_iterations << "ns" << std::endl;
}
Example #13
0
void TestRTree::testPrimitive()
{
    RTree<bool> tree;
    tree.insert(QRect(2, 5, 1, 2), true);
    QCOMPARE(tree.contains(QPoint(2, 2)).isEmpty(), true);
    QCOMPARE(tree.contains(QPoint(2, 5)).first(), true);
    QCOMPARE(tree.contains(QPoint(3, 5)).isEmpty(), true);
    QCOMPARE(tree.contains(QPoint(2, 6)).first(), true);
    const QList< QPair<QRectF, bool> > pairs = tree.intersectingPairs(QRect(2, 5, 1, 2)).values();
    QCOMPARE(pairs.count(), 1);
    QCOMPARE(pairs.first().first.toRect(), QRect(2, 5, 1, 2));
    QCOMPARE(pairs.first().second, true);
}
Example #14
0
void search_ND_All(int items){
	std::vector< Rect<size> > rectangles;
	unsigned int edge_size = (unsigned int)ceil(pow((double)items, 1.0 / (double)size));
	int no_iterations = std::max(max_elements / items, 10);
	generateRectangles(items, edge_size, rectangles);

	RTree<int, unsigned int, size, float> tree;

	for (size_t i = 0; i < rectangles.size(); ++i){
		tree.Insert(rectangles[i].min, rectangles[i].max, i);
	}

	auto begin = std::chrono::high_resolution_clock::now();

	for (int i = 0; i < no_iterations; i++){
		for (size_t j = 0; j < rectangles.size(); j++){
			tree.Search(rectangles[j].min, rectangles[j].max, MySearchCallback, NULL);
		}
	}

	auto end = std::chrono::high_resolution_clock::now();

	of << "Querying tree with " << rectangles.size() << " tiles using " << items << " queries over " << size << "D items:" << (double)std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / (double)no_iterations << "ns" << std::endl;
}
Example #15
0
int main()
{
	RTree tree;
	
	for(int i = 0;i < DATA_NUMBER; ++i)
	{
		double min[2],max[2];
		min[0] = rand() % MAP_SIZE;
		max[0] = min[0];
		min[1] = rand() % MAP_SIZE;
		max[1] = min[1];
		tree.Insert(min, max, i);  //Insert (x,y,id)
	}
	outFileData(&tree);
	//tree.fileInsert("data.txt");
	//tree.printRec(tree.getMBR(tree.getRoot()));

	RTree::Iterator it;
	for( tree.GetFirst(it); 
       !tree.IsNull(it);
       tree.GetNext(it) )
	{
		int value = tree.GetAt(it);
    
		double x,y;
		it.GetCard(&x,&y);
		cout << "ID " << value << " : " << "(" << x << "," << y << ")" << endl;
	}

	Table1 table1;
	Table2 table2;
	Table3 table3;
	generateTable(&tree,&table1,&table2,&table3);
	printTable(&table1,&table2,&table3);
	outFileTable(&table1,&table2,&table3);

	TimeCounter tc;
	double CreateTime = 0.0;
	tc.StartTime();
	cout << QueryPlan(&tree,K_NEAREST) << endl;
	CreateTime = tc.EndTime();
	cout << "QueryPlan Time: " << CreateTime << " ms" << endl;

//	outFileRect(&tree);

	system("pause");
	return 0;
}
Example #16
0
void TestRTree::testInsertColumns()
{
    // RTree::InsertMode = RTree::CopyPrevious
    RTree<QString> tree;
    tree.insert(QRect(1, 1, 2, 1), QString("1"));
    tree.insert(QRect(1, 2, 3, 1), QString("2"));
    tree.insert(QRect(2, 3, 4, 1), QString("3"));
    tree.insert(QRect(2, 4, 5, 1), QString("4"));
    tree.insert(QRect(3, 5, 3, 1), QString("5"));
    tree.insert(QRect(3, 6, 4, 1), QString("6"));
    tree.insert(QRect(4, 7, 2, 1), QString("7"));
    tree.insert(QRect(4, 8, 3, 1), QString("8"));
    tree.insert(QRect(6, 9, 3, 1), QString("9"));
    QList< QPair<QRectF, QString> > undo = tree.insertColumns(3, 3);
    QList< QPair<QRectF, QString> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QCOMPARE(pairs.count(), 9);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 5, 1));
    QCOMPARE(pairs[0].second, QString("1"));
    QCOMPARE(pairs[1].first, QRectF(1, 2, 6, 1));
    QCOMPARE(pairs[1].second, QString("2"));
    QCOMPARE(pairs[2].first, QRectF(2, 3, 7, 1));
    QCOMPARE(pairs[2].second, QString("3"));
    QCOMPARE(pairs[3].first, QRectF(2, 4, 8, 1));
    QCOMPARE(pairs[3].second, QString("4"));
    QCOMPARE(pairs[4].first, QRectF(6, 5, 3, 1));
    QCOMPARE(pairs[4].second, QString("5"));
    QCOMPARE(pairs[5].first, QRectF(6, 6, 4, 1));
    QCOMPARE(pairs[5].second, QString("6"));
    QCOMPARE(pairs[6].first, QRectF(7, 7, 2, 1));
    QCOMPARE(pairs[6].second, QString("7"));
    QCOMPARE(pairs[7].first, QRectF(7, 8, 3, 1));
    QCOMPARE(pairs[7].second, QString("8"));
    QCOMPARE(pairs[8].first, QRectF(9, 9, 3, 1));
    QCOMPARE(pairs[8].second, QString("9"));
    QCOMPARE(undo.count(), 0);
#if 0
    // RTree::InsertMode = RTree::CopyCurrent
    tree.clear();
    tree.insert(QRect(1, 1, 2, 1), QString("1"));
    tree.insert(QRect(1, 2, 3, 1), QString("2"));
    undo = tree.insertColumns(3, 3, RTree<QString>::CopyCurrent);
    pairs = tree.intersectingPairs(QRect(1, 1, 10, 10));
    QCOMPARE(pairs.count(), 2);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 2, 1));
    QCOMPARE(pairs[1].first, QRectF(1, 2, 6, 1));
    QCOMPARE(undo.count(), 0);

    // RTree::InsertMode = RTree::CopyNone
    tree.clear();
    tree.insert(QRect(1, 1, 2, 1), QString("1"));
    tree.insert(QRect(1, 2, 3, 1), QString("2"));
    undo = tree.insertColumns(3, 3, RTree<QString>::CopyNone);
    pairs = tree.intersectingPairs(QRect(1, 1, 10, 10));
    QCOMPARE(pairs.count(), 3);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 2, 1));
    QCOMPARE(pairs[1].first, QRectF(1, 2, 2, 1));
    QCOMPARE(pairs[2].first, QRectF(6, 2, 1, 1));
    QCOMPARE(undo.count(), 0);
#endif
}
    Status MultiIndexBlock::init(const std::vector<BSONObj>& indexSpecs) {
        WriteUnitOfWork wunit(_txn);

        invariant(_indexes.empty());
        _txn->recoveryUnit()->registerChange(new CleanupIndexesVectorOnRollback(this));

        const string& ns = _collection->ns().ns();

        Status status = _collection->getIndexCatalog()->checkUnfinished();
        if ( !status.isOK() )
            return status;

        for ( size_t i = 0; i < indexSpecs.size(); i++ ) {
            BSONObj info = indexSpecs[i];

            string pluginName = IndexNames::findPluginName( info["key"].Obj() );
			//log() << "PLUGIN IS " << pluginName;
			
			// CUSTOM
			if (pluginName == "test") {
				// YOU SHOULD BE ABLE TO MAKE TE INDEX HERE
				//log() << "INX_CREATE NUM REC:" << _collection->numRecords(_txn);
				RecordIterator* ri = _collection->getIterator(_txn);

				std::vector<Entry*> initialEntries;

				while (!ri->isEOF()) {
					//log() << "SEE ITEM";
					RecordData recordData = ri->dataFor(ri->curr());
					//log() << "VALU IS " << recordData.toBson();

					std::vector<double> lower; std::vector<double> upper;
					bool foundOK = false;

					if (recordData.toBson().getFieldDotted("loc")["lng"].ok()) {
						// A POINT
						log() << "ELE IS A POINT: " << recordData.toBson().getFieldDotted("loc")["lng"].Double() << " AND " << recordData.toBson().getFieldDotted("loc")["lat"].Double();

						lower.push_back(recordData.toBson().getFieldDotted("loc")["lng"].Double()); lower.push_back(recordData.toBson().getFieldDotted("loc")["lat"].Double());
						upper.push_back(recordData.toBson().getFieldDotted("loc")["lng"].Double()); upper.push_back(recordData.toBson().getFieldDotted("loc")["lat"].Double());
						foundOK = true;
					}
					else { 
						//log() << "NOT OK LINE!"; 
					}
					if (recordData.toBson().getFieldDotted("loc")["type"].ok()) {
						if (recordData.toBson().getFieldDotted("loc")["type"].String() == "Polygon") {
							//log() << "ITS A POLY"; // << recordData.toBson().getFieldDotted("loc")["rew"].Double();

							lower.push_back(recordData.toBson().getFieldDotted("loc")["coordinates"].Array().at(0).Array().at(0).Array().at(0).Double());
							lower.push_back(recordData.toBson().getFieldDotted("loc")["coordinates"].Array().at(0).Array().at(0).Array().at(1).Double());
							upper.push_back(recordData.toBson().getFieldDotted("loc")["coordinates"].Array().at(0).Array().at(2).Array().at(0).Double());
							upper.push_back(recordData.toBson().getFieldDotted("loc")["coordinates"].Array().at(0).Array().at(2).Array().at(1).Double());

							foundOK = true;
						}
					}
					else { 
						//log() << "NOT OK POLY!"; 
					}

					if (foundOK) {
						std::unordered_map<int, std::string> newDoc;
						BoundingBox I = BoundingBox(lower, upper);
						Entry* myEnt = new Entry(I, newDoc);
						initialEntries.push_back(myEnt);
					}

					ri->getNext();
				}

				int dimensions = 2;
				int max = 6;
				int min = 3;

				log() << "RTRee creation has begun!";
				//create a new Node, this will be the root node
				std::vector<Entry*> newV;
				Node* R = new Node(dimensions, newV, max, min, true);
				//create a new RTree
				RTree myIndex = RTree(dimensions, R, max, min);
				//insert the entries we created into myIndex RTree
				for (int i = 0; i<initialEntries.size(); i++){
					//log() << "started inserting entry " << i << " which has lat ";
					Entry* current = initialEntries.at(i);
					//log() << "started inserting entry " << i << " which has lat " << current->getI().get_ithLower(0) << "," << current->getI().get_ithLower(1);
					//log() << "started inserting entry " << i << " which has lat " << current->getI().get_ithUpper(0) << "," << current->getI().get_ithUpper(1);
					myIndex.insert(current);
					//log() << "finished inserting entry " << i;
				}
				log() << "inserted all initial entries!";
				
				myIndex.theTree = &myIndex;
				
				
				
				double rand1 = -100;//0;//-2.0;// 2.0;//
				double rand2 = -100;//0;//-3.0;// 1.0;//
				double rand3 = 100;//50;//2.0;// 4.0;//
				double rand4 = 100;//50;//3.0;// 4.0;//
				std::vector<double> lowerBB;
				lowerBB.push_back(rand1);
				lowerBB.push_back(rand2);
				std::vector<double> upperBB;
				upperBB.push_back(rand3);
				upperBB.push_back(rand4);
				BoundingBox* IBB = new BoundingBox(lowerBB, upperBB);//this is the bounding box we will be searching for

				std::vector<Entry*> overlapping = myIndex.search(IBB); // just leave this for now
				//cout << "found: " << overlapping.size() << " search results when searching for I = ";
				//cout << "lower bounds: " << I.getLower() << endl;
				//cout << "upper bounds: " << I.getUpper() << endl;
				/*log() << "SEARCH FOUND " << overlapping.size() << " RESULTS" << endl;
				for(int i=0; i<overlapping.size();i++){
					log() << "Entry " << i << endl;
					//TODO print Entry
					log() << overlapping.at(i)->getI().get_ithLower(0)<< " "<< overlapping.at(i)->getI().get_ithLower(1) << endl;
					
					log() << overlapping.at(i)->getI().get_ithUpper(0)<< " " << overlapping.at(i)->getI().get_ithUpper(1) << endl;
					
				}*/
				
				
				

				return Status::OK();
			}
			// CUSTOM
			
            if ( pluginName.size() ) {
                Status s =
                    _collection->getIndexCatalog()->_upgradeDatabaseMinorVersionIfNeeded(_txn, pluginName);
                if ( !s.isOK() )
                    return s;
            }

            // Any foreground indexes make all indexes be built in the foreground.
            _buildInBackground = (_buildInBackground && info["background"].trueValue());
        }

        for ( size_t i = 0; i < indexSpecs.size(); i++ ) {
            BSONObj info = indexSpecs[i];
            StatusWith<BSONObj> statusWithInfo =
                _collection->getIndexCatalog()->prepareSpecForCreate( _txn, info );
            Status status = statusWithInfo.getStatus();
            if ( !status.isOK() )
                return status;
            info = statusWithInfo.getValue();

            IndexToBuild index;
            index.block = boost::make_shared<IndexCatalog::IndexBuildBlock>(_txn,
                                                                            _collection,
                                                                            info);
            status = index.block->init();
            if ( !status.isOK() )
                return status;

            index.real = index.block->getEntry()->accessMethod();
            status = index.real->initializeAsEmpty(_txn);
            if ( !status.isOK() )
                return status;

            if (!_buildInBackground) {
                // Bulk build process requires foreground building as it assumes nothing is changing
                // under it.
                index.bulk.reset(index.real->initiateBulk(_txn));
            }

            const IndexDescriptor* descriptor = index.block->getEntry()->descriptor();

            index.options.logIfError = false; // logging happens elsewhere if needed.
            index.options.dupsAllowed = !descriptor->unique()
                                     || _ignoreUnique
                                     || repl::getGlobalReplicationCoordinator()
                                                    ->shouldIgnoreUniqueIndex(descriptor);

            log() << "build index on: " << ns << " properties: " << descriptor->toString();
            if (index.bulk)
                log() << "\t building index using bulk method";

            // TODO SERVER-14888 Suppress this in cases we don't want to audit.
            audit::logCreateIndex(_txn->getClient(), &info, descriptor->indexName(), ns);

            _indexes.push_back( index );
        }

        // this is so that operations examining the list of indexes know there are more keys to look
        // at when doing things like in place updates, etc...
        _collection->infoCache()->addedIndex(_txn);

        if (_buildInBackground)
            _backgroundOperation.reset(new BackgroundOperation(ns));

        wunit.commit();
        return Status::OK();
    }
int main() {
	tree.insert(generateBound(1, 2), 1);
	tree.insert(generateBound(1, 2), 2);
	tree.insert(generateBound(1, 2), 3);
	tree.insert(generateBound(1, 2), 4);
	tree.insert(generateBound(1, 2), 5);
	tree.insert(generateBound(1, 2), 6);
	tree.insert(generateBound(1, 2), 7);
	tree.insert(generateBound(1, 2), 8);
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.remove(generateBound(1, 2)); tree.travel();
	tree.insert(generateBound(1, 2), 1);
	tree.insert(generateBound(1, 2), 2);
	tree.insert(generateBound(1, 2), 3);
	tree.insert(generateBound(1, 2), 4);
	tree.insert(generateBound(1, 2), 5);
	tree.insert(generateBound(1, 2), 6);
	tree.insert(generateBound(1, 2), 7);
	tree.insert(generateBound(1, 2), 8);
	auto ret = tree.getPointSet(generateBound(1, 2));
	printf("%d\n", (int)ret.size());
	std::sort(ret.begin(), ret.end());
	for (auto element : ret) {
		printf("%d\n", element);
	}
	return 0;
}
Example #19
0
extern "C" _declspec(dllexport) int getsearch(int record[],char * filename )
{
	
	fstream file;
	file.open(filename, ios::in);
	RTFileStream rts;//creat a file stream with necessary check, or tree.Load directly is also ok.
	hitcount=0;
	if(havebuild==0)
		tree.Load("h:\\projectdata\\database3.rtr");
	havebuild=1;
	double value;
	int length;
	Rect searchrec;
	 file>>length;
  for(int j=0;j<length;j++)
	  file>>value;
  file>>length;
	  for(int j=0;j<length;j++)
	  {
		  
		 file>>value;
		  searchrec.min[j]=value;
		  searchrec.max[j]=value;
	  }
	  for(int i=0;i<length;i++)
	  {
		  int tempmax=-99,tempmin=99;
		  for(int j=max(i-K,0);j<=min(length-1,i+K);j++)
		  {
			  if(searchrec.min[i]<tempmin)
				  tempmin=searchrec.min[i];
			  if(searchrec.max[i]>tempmax)
				  tempmax=searchrec.max[i];
		  }
		  searchrec.max[i]=tempmax;
		  searchrec.min[i]=tempmin;
	  }
	    file.close();
 // double * searchseq=paa(des,length);
  /*Rect searchrec;
  for(int i=0;i<DIM;i++)
  {
	  searchrec.max[i]=T;
	  searchrec.min[i]=-T;
  }*/
		for(int j=0;j<length;j++)
	  {
		  
		
		  searchrec.min[j]-=T;
		  searchrec.max[j]+=T;
	  }
  tree.Search(searchrec.min,searchrec.max,MySearchCallback,NULL);
  for(int i=0;i<hitcount;i++)
	  record[i]=localrecord[i];

  return hitcount;




 
}
Example #20
0
  /**
  * \Brief Problem Factory
  * Select features from user's choice layers within
  * a specific bounding box
  * param nbLayers # wanted layers
  * param layersFactor layers importance
  * param layersName layers in problem
  * param lambda_min west bbox
  * param phi_min south bbox
  * param lambda_max east bbox
  * param phi_max north bbox
  * param scale the scale
  */
  Problem* Pal::extract( int nbLayers, char **layersName, double *layersFactor, double lambda_min, double phi_min, double lambda_max, double phi_max, double scale, std::ofstream *svgmap )
  {
    // to store obstacles
    RTree<PointSet*, double, 2, double> *obstacles = new RTree<PointSet*, double, 2, double>();

    Problem *prob = new Problem();

    int i, j;

    double bbx[4];
    double bby[4];

    double amin[2];
    double amax[2];

    int max_p = 0;

    LabelPosition* lp;

    bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = lambda_min;
    bby[0] = bby[1] = amin[1] = prob->bbox[1] = phi_min;
    bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = lambda_max;
    bby[2] = bby[3] = amax[1] = prob->bbox[3] = phi_max;


    prob->scale = scale;
    prob->pal = this;

    LinkedList<Feats*> *fFeats = new LinkedList<Feats*> ( ptrFeatsCompare );

    FeatCallBackCtx *context = new FeatCallBackCtx();
    context->fFeats = fFeats;
    context->scale = scale;
    context->obstacles = obstacles;
    context->candidates = prob->candidates;

    context->bbox_min[0] = amin[0];
    context->bbox_min[1] = amin[1];

    context->bbox_max[0] = amax[0];
    context->bbox_max[1] = amax[1];

#ifdef _EXPORT_MAP_
    context->svgmap = svgmap;
#endif

#ifdef _VERBOSE_
    std::cout <<  nbLayers << "/" << layers->size() << " layers to extract " << std::endl;
    std::cout << "scale is 1:" << scale << std::endl << std::endl;

#endif


    /* First step : extract feature from layers
     *
     * */
    int oldNbft = 0;
    Layer *layer;

    std::list<char*> *labLayers = new std::list<char*>();

    lyrsMutex->lock();
    for ( i = 0; i < nbLayers; i++ )
    {
      for ( std::list<Layer*>::iterator it = layers->begin(); it != layers->end(); it++ ) // iterate on pal->layers
      {
        layer = *it;
        // Only select those who are active and labellable (with scale constraint) or those who are active and which must be treated as obstaclewhich must be treated as obstacle
        if ( layer->active
             && ( layer->obstacle || ( layer->toLabel && layer->isScaleValid( scale ) ) ) )
        {

          // check if this selected layers has been selected by user
          if ( strcmp( layersName[i], layer->name ) == 0 )
          {
            // check for connected features with the same label text and join them
            if ( layer->getMergeConnectedLines() )
              layer->joinConnectedFeatures();

            context->layer = layer;
            context->priority = layersFactor[i];
            // lookup for feature (and generates candidates list)

#ifdef _EXPORT_MAP_
            *svgmap << "<g inkscape:label=\"" << layer->name << "\"" << std::endl
            <<  "    inkscape:groupmode=\"layer\"" << std::endl
            <<  "    id=\"" << layer->name << "\">" << std::endl << std::endl;
#endif

            context->layer->modMutex->lock();
            context->layer->rtree->Search( amin, amax, extractFeatCallback, ( void* ) context );
            context->layer->modMutex->unlock();

#ifdef _EXPORT_MAP_
            *svgmap  << "</g>" << std::endl << std::endl;
#endif

#ifdef _VERBOSE_
            std::cout << "Layer's name: " << layer->getName() << std::endl;
            std::cout << "     scale range: " << layer->getMinScale() << "->" << layer->getMaxScale() << std::endl;
            std::cout << "     active:" << layer->isToLabel() << std::endl;
            std::cout << "     obstacle:" << layer->isObstacle() << std::endl;
            std::cout << "     toLabel:" << layer->isToLabel() << std::endl;
            std::cout << "     # features: " << layer->getNbFeatures() << std::endl;
            std::cout << "     # extracted features: " << context->fFeats->size() - oldNbft << std::endl;
#endif
            if ( context->fFeats->size() - oldNbft > 0 )
            {
              char *name = new char[strlen( layer->getName() ) +1];
              strcpy( name, layer->getName() );
              labLayers->push_back( name );
            }
            oldNbft = context->fFeats->size();


            break;
          }
        }
      }
    }
    delete context;
    lyrsMutex->unlock();

    prob->nbLabelledLayers = labLayers->size();
    prob->labelledLayersName = new char*[prob->nbLabelledLayers];
    for ( i = 0; i < prob->nbLabelledLayers; i++ )
    {
      prob->labelledLayersName[i] = labLayers->front();
      labLayers->pop_front();
    }

    delete labLayers;

    if ( fFeats->size() == 0 )
    {
#ifdef _VERBOSE_
      std::cout << std::endl << "Empty problem" << std::endl;
#endif
      delete fFeats;
      delete prob;
      delete obstacles;
      return NULL;
    }

    prob->nbft = fFeats->size();
    prob->nblp = 0;
    prob->featNbLp = new int [prob->nbft];
    prob->featStartId = new int [prob->nbft];
    prob->inactiveCost = new double[prob->nbft];

    Feats *feat;

#ifdef _VERBOSE_
    std::cout << "FIRST NBFT : " << prob->nbft << std::endl;
#endif

    // Filtering label positions against obstacles
    amin[0] = amin[1] = -DBL_MAX;
    amax[0] = amax[1] = DBL_MAX;
    FilterContext filterCtx;
    filterCtx.cdtsIndex = prob->candidates;
    filterCtx.scale = prob->scale;
    filterCtx.pal = this;
    obstacles->Search( amin, amax, filteringCallback, ( void* ) &filterCtx );


    int idlp = 0;
    for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
    {
      feat = fFeats->pop_front();
#ifdef _DEBUG_FULL_
      std::cout << "Feature:" << feat->feature->layer->name << "/" << feat->feature->uid << std::endl;
#endif
      prob->featStartId[i] = idlp;
      prob->inactiveCost[i] = pow( 2, 10 - 10 * feat->priority );

      switch ( feat->feature->getGeosType() )
      {
        case GEOS_POINT:
          max_p = point_p;
          break;
        case GEOS_LINESTRING:
          max_p = line_p;
          break;
        case GEOS_POLYGON:
          max_p = poly_p;
          break;
      }

      // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
      max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

#ifdef _DEBUG_FULL_
      std::cout << "All Cost are setted" << std::endl;
#endif
      // only keep the 'max_p' best candidates
      for ( j = max_p; j < feat->nblp; j++ )
      {
        // TODO remove from index
        feat->lPos[j]->removeFromIndex( prob->candidates );
        delete feat->lPos[j];
      }
      feat->nblp = max_p;

      // update problem's # candidate
      prob->featNbLp[i] = feat->nblp;
      prob->nblp += feat->nblp;

      // add all candidates into a rtree (to speed up conflicts searching)
      for ( j = 0; j < feat->nblp; j++, idlp++ )
      {
        lp = feat->lPos[j];
        //lp->insertIntoIndex(prob->candidates);
        lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
      }
      fFeats->push_back( feat );
    }

#ifdef _DEBUG_FULL_
    std::cout << "Malloc problem...." << std::endl;
#endif


    idlp = 0;
    int nbOverlaps = 0;
    prob->labelpositions = new LabelPosition*[prob->nblp];
    //prob->feat = new int[prob->nblp];

#ifdef _DEBUG_FULL_
    std::cout << "problem malloc'd" << std::endl;
#endif


    j = 0;
    while ( fFeats->size() > 0 ) // foreach feature
    {
      feat = fFeats->pop_front();
      for ( i = 0; i < feat->nblp; i++, idlp++ )  // foreach label candidate
      {
        lp = feat->lPos[i];
        lp->resetNumOverlaps();

        // make sure that candidate's cost is less than 1
        lp->validateCost();

        prob->labelpositions[idlp] = lp;
        //prob->feat[idlp] = j;

        lp->getBoundingBox( amin, amax );

        // lookup for overlapping candidate
        prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, ( void* ) lp );

        nbOverlaps += lp->getNumOverlaps();
#ifdef _DEBUG_FULL_
        std::cout << "Nb overlap for " << idlp << "/" << prob->nblp - 1 << " : " << lp->nbOverlap << std::endl;
#endif
      }
      j++;
      delete[] feat->lPos;
      delete feat;
    }
    delete fFeats;

    //delete candidates;
    delete obstacles;


    nbOverlaps /= 2;
    prob->all_nblp = prob->nblp;
    prob->nbOverlap = nbOverlaps;


#ifdef _VERBOSE_
    std::cout << "nbOverlap: " << prob->nbOverlap << std::endl;
    std::cerr << scale << "\t"
              << prob->nbft << "\t"
              << prob->nblp << "\t"
              << prob->nbOverlap << "\t";
#endif

    return prob;
  }
Example #21
0
void Filler2D::pointInsertion2D(GFace* gf,  vector<MVertex*> &packed,
                                vector<SMetric3> &metrics)
{
  // NB/ do not use the mesh in GFace, use the one in backgroundMesh2D!

  //  if(debug) cout << " ------------------   OLD -------------------" << endl;
  //  stringstream ssa;
  ////  ssa << "oldbgm_angles_" << gf->tag() << ".pos";
  ////  backgroundMesh::current()->print(ssa.str(),gf,1);
  //  ssa << "oldbgm_sizes_" << gf->tag() << ".pos";
  //  backgroundMesh::current()->print(ssa.str(),gf,0);
  //
  //
  //
  //
  //  if(debug) cout << " ------------------   NEW -------------------" << endl;
  //  backgroundMesh2D *bgm2 = dynamic_cast<backgroundMesh2D*>(BGMManager::get(gf));
  //  stringstream ss2;
  //  ss2 << "basebg_sizefield_" << gf->tag() << ".pos";
  //  bgm2->exportSizeField(ss2.str());
  //
  //
  //
  //  return;
  //

  BGMManager::set_use_cross_field(true);

  const bool goNonLinear = true;
  const bool debug=false;
  const bool export_stuff=true;

  if (debug) cout << "ENTERING POINTINSERTION2D" << endl;

  double a;

  // acquire background mesh
  if(debug) cout << "pointInsertion2D: recover BGM" << endl;
  a=Cpu();
  frameFieldBackgroundMesh2D *bgm =
    dynamic_cast<frameFieldBackgroundMesh2D*>(BGMManager::get(gf));
  time_bgm_and_smoothing += (Cpu() - a);

  if (!bgm){
    Msg::Error("BGM dynamic cast failed in filler2D::pointInsertion2D");
    return;
  }

  // export BGM size field
  if(export_stuff){
    cout << "pointInsertion2D: export size field " << endl;
    stringstream ss;
    ss << "bg2D_sizefield_" << gf->tag() << ".pos";
    bgm->exportSizeField(ss.str());

    cout << "pointInsertion2D : export crossfield " << endl;
    stringstream sscf;
    sscf << "bg2D_crossfield_" << gf->tag() << ".pos";
    bgm->exportCrossField(sscf.str());

    cout << "pointInsertion2D : export smoothness " << endl;
    stringstream sss;
    sss << "bg2D_smoothness_" << gf->tag() << ".pos";
    bgm->exportSmoothness(sss.str());
  }



  // point insertion algorithm:
  a=Cpu();

  // for debug check...
  int priority_counter=0;
  map<MVertex*,int> vert_priority;

  // get all the boundary vertices
  if(debug) cout << "pointInsertion2D : get bnd vertices " << endl;
  set<MVertex*> bnd_vertices = bgm->get_vertices_of_maximum_dim(1);

  // put boundary vertices in a fifo queue
  set<smoothness_point_pair, compareSurfacePointWithExclusionRegionPtr_Smoothness> fifo;
  vector<surfacePointWithExclusionRegion*> vertices;

  // initiate the rtree
  if(debug) cout << "pointInsertion2D : initiate RTree " << endl;
  RTree<surfacePointWithExclusionRegion*,double,2,double> rtree;
  SMetric3 metricField(1.0);
  SPoint2 newp[4][NUMDIR];
  set<MVertex*>::iterator it = bnd_vertices.begin() ;

  for (; it !=  bnd_vertices.end() ; ++it){
    SPoint2 midpoint;
    computeFourNeighbors(bgm,*it, midpoint, goNonLinear, newp, metricField);
    surfacePointWithExclusionRegion *sp = new surfacePointWithExclusionRegion
      (*it, newp, midpoint,metricField);

    smoothness_point_pair mp;
    mp.ptr = sp;
    mp.rank=(1.-bgm->get_smoothness(midpoint[0],midpoint[1]));
    fifo.insert(mp);

    vertices.push_back(sp);
    double _min[2],_max[2];
    sp->minmax(_min,_max);
    rtree.Insert(_min,_max,sp);
  }

  // ---------- main loop -----------------
  while(!fifo.empty()){
    if(debug) cout << " -------- fifo.size() = " << fifo.size() << endl;
    int count_nbaddedpt = 0;

    surfacePointWithExclusionRegion * parent = (*fifo.begin()).ptr;
    fifo.erase(fifo.begin());

    for (int dir=0;dir<NUMDIR;dir++){
      for (int i=0;i<4;i++){
        if (!inExclusionZone (parent->_p[i][dir], rtree, vertices) ){

          GPoint gp = gf->point(parent->_p[i][dir]);
          MFaceVertex *v = new MFaceVertex(gp.x(),gp.y(),gp.z(),gf,gp.u(),gp.v());
          SPoint2 midpoint;
          computeFourNeighbors(bgm,v, midpoint, goNonLinear, newp, metricField);
          surfacePointWithExclusionRegion *sp = new surfacePointWithExclusionRegion
            (v, newp, midpoint, metricField, parent);
          smoothness_point_pair mp;mp.ptr = sp;mp.rank=(1.-bgm->get_smoothness(gp.u(),gp.v()));

          if (debug) vert_priority[v] = priority_counter++;

          fifo.insert(mp);
          vertices.push_back(sp);
          double _min[2],_max[2];
          sp->minmax(_min,_max);
          rtree.Insert(_min,_max,sp);

          if (debug){
            cout << "  adding node (" << sp->_v->x() << "," << sp->_v->y()
                 << "," << sp->_v->z() << ")" << endl;
            cout << "    ----------------------------- sub --- fifo.size() = "
                 << fifo.size() << endl;
          }
          count_nbaddedpt++;
        }
      }
    }
    if(debug) cout << "////////// nbre of added point: " << count_nbaddedpt << endl;
  }
  time_insertion += (Cpu() - a);

  if (debug){
    stringstream ss;
    ss << "priority_" << gf->tag() << ".pos";
    print_nodal_info(ss.str().c_str(),vert_priority);
    ss.clear();
  }

  // add the vertices as additional vertices in the
  // surface mesh
  char ccc[256]; sprintf(ccc,"points%d.pos",gf->tag());
  FILE *f = Fopen(ccc,"w");
  if(f){
    fprintf(f,"View \"\"{\n");
    for (unsigned int i=0;i<vertices.size();i++){
      vertices[i]->print(f,i);
      if(vertices[i]->_v->onWhat() == gf) {
        packed.push_back(vertices[i]->_v);
        metrics.push_back(vertices[i]->_meshMetric);
        SPoint2 midpoint;
        reparamMeshVertexOnFace(vertices[i]->_v, gf, midpoint);
      }
      delete  vertices[i];
    }
    fprintf(f,"};");
    fclose(f);
  }
}
Example #22
0
bool Filler3D::treat_region(GRegion *gr)
{
  BGMManager::set_use_cross_field(true);

  bool use_vectorial_smoothness;
  bool use_fifo;
  string algo;

  // readValue("param.dat","SMOOTHNESSALGO",algo);
  algo.assign("SCALAR");

  if (!algo.compare("SCALAR")){
    use_vectorial_smoothness = false;
    use_fifo = false;
  }
  else if (!algo.compare("FIFO")){
    use_vectorial_smoothness = false;
    use_fifo = true;
  }
  else{
    cout << "unknown SMOOTHNESSALGO !" << endl;
    throw;
  }

  const bool debug=false;
  const bool export_stuff=true;
  double a;

  cout << "ENTERING POINTINSERTION3D" << endl;

  // acquire background mesh
  cout << "pointInsertion3D: recover BGM" << endl;
  a = Cpu();
  frameFieldBackgroundMesh3D *bgm =
    dynamic_cast<frameFieldBackgroundMesh3D*>(BGMManager::get(gr));
  time_smoothing += (Cpu() - a);

  if (!bgm){
    cout << "pointInsertion3D:: BGM dynamic cast failed ! " << endl;
    throw;
  }

  // export BGM fields
  if(export_stuff){
    cout << "pointInsertion3D: export size field " << endl;
    stringstream ss;
    ss << "bg3D_sizefield_" << gr->tag() << ".pos";
    bgm->exportSizeField(ss.str());

    cout << "pointInsertion3D : export crossfield " << endl;
    stringstream sscf;
    sscf << "bg3D_crossfield_" << gr->tag() << ".pos";
    bgm->exportCrossField(sscf.str());

    cout << "pointInsertion3D : export smoothness " << endl;
    stringstream sss;
    sss << "bg3D_smoothness_" << gr->tag() << ".pos";
    bgm->exportSmoothness(sss.str());

    if (use_vectorial_smoothness){
      cout << "pointInsertion3D : export vectorial smoothness " << endl;
      stringstream ssvs;
      ssvs << "bg3D_vectorial_smoothness_" << gr->tag() << ".pos";
      bgm->exportVectorialSmoothness(ssvs.str());
    }
  }

  // ---------------- START FILLING NEW POINTS ----------------
  cout << "pointInsertion3D : inserting points in region " << gr->tag()  << endl;

  //ProfilerStart("/home/bernard/profile");
  a = Cpu();

  // ----- initialize fifo list -----

  RTree<MVertex*,double,3,double> rtree;
  listOfPoints *fifo;
  if (use_fifo)
    fifo = new listOfPointsFifo();
  else if (use_vectorial_smoothness)
    fifo = new listOfPointsVectorialSmoothness();
  else
    fifo = new listOfPointsScalarSmoothness();

  set<MVertex*> temp;
  vector<MVertex*> boundary_vertices;
  map<MVertex*,int> vert_priority;
  map<MVertex*,double> smoothness_forplot;
  MElement *element;
  MVertex *vertex;
  list<GFace*> faces = gr->faces();
  for(list<GFace*>::iterator it=faces.begin();it!=faces.end();it++){// for all faces
    GFace *gf = *it;
    // int limit = code_kesskessai(gf->tag());
    for(unsigned int i=0;i<gf->getNumMeshElements();i++){
      element = gf->getMeshElement(i);
      for(int j=0;j<element->getNumVertices();j++){// for all vertices
        vertex = element->getVertex(j);
        temp.insert(vertex);
        // limits.insert(make_pair(vertex,limit));
      }
    }
  }

  int geodim;
  for(set<MVertex*>::iterator it=temp.begin();it!=temp.end();it++){
    geodim = (*it)->onWhat()->dim();
    if ((geodim==0) || (geodim==1) || (geodim==2)) boundary_vertices.push_back(*it);
  }

  double min[3],max[3],x,y,z,h;
  for(unsigned int i=0;i<boundary_vertices.size();i++){

    x = boundary_vertices[i]->x();
    y = boundary_vertices[i]->y();
    z = boundary_vertices[i]->z();

    // "on boundary since working on boundary_vertices ...
    MVertex *closest = bgm->get_nearest_neighbor_on_boundary(boundary_vertices[i]);
    h = bgm->size(closest);// get approximate size, closest vertex, faster ?!

    fill_min_max(x,y,z,h,min,max);

    rtree.Insert(min,max,boundary_vertices[i]);

    if (!use_vectorial_smoothness){
      smoothness_vertex_pair *svp = new smoothness_vertex_pair();
      svp->v = boundary_vertices[i];
      svp->rank = bgm->get_smoothness(x,y,z);
      svp->dir = 0;
      svp->layer = 0;
      svp->size = h;
      bgm->eval_approximate_crossfield(closest, svp->cf);

      fifo->insert(svp);
      if (debug){
        smoothness_forplot[svp->v] = svp->rank;
      }
    }
    else{
      STensor3 temp;
      bgm->eval_approximate_crossfield(closest, temp);
      for (int idir=0;idir<3;idir++){
        smoothness_vertex_pair *svp = new smoothness_vertex_pair();
        svp->v = boundary_vertices[i];
        svp->rank = bgm->get_vectorial_smoothness(idir,x,y,z);
        svp->dir = idir;
        svp->layer = 0;
        svp->size = h;
        svp->cf = temp;
        for (int k=0;k<3;k++) svp->direction(k) = temp(k,idir);

        // cout << "fifo size=" << fifo->size() << " inserting   "  ;
        fifo->insert(svp);
        // cout << " ->  fifo size=" << fifo->size() << endl;
      }
    }
  }

  // TODO: si fifo était list of *PTR -> pas de copies, gain temps ?
  Wrapper3D wrapper;
  wrapper.set_bgm(bgm);
  MVertex *parent,*individual;
  new_vertices.clear();
  bool spawn_created;
  int priority_counter=0;
  STensor3 crossfield;
  int parent_layer;

  while(!fifo->empty()){

    parent =  fifo->get_first_vertex();
    //    parent_limit = fifo->get_first_limit();
    parent_layer = fifo->get_first_layer();

    //    if(parent_limit!=-1 && parent_layer>=parent_limit()){
    //      continue;
    //    }

    vector<MVertex*> spawns;
    if (!use_vectorial_smoothness){
      spawns.resize(6);
      computeSixNeighbors(bgm,parent,spawns,fifo->get_first_crossfield(),
                          fifo->get_first_size());
    }
    else{
      spawns.resize(2);
      computeTwoNeighbors(bgm,parent,spawns,fifo->get_first_direction(),
                          fifo->get_first_size());
    }
    fifo->erase_first();

    //    cout << "while, fifo->size()=" << fifo->size() << " parent=(" <<
    //    parent->x() << "," << parent->y() << "," << parent->z() << ")" <<
    //    endl;

    for(unsigned int i=0;i<spawns.size();i++){
      spawn_created = false;
      individual = spawns[i];
      x = individual->x();
      y = individual->y();
      z = individual->z();
      //      cout << " working on candidate " << "(" << individual->x() << ","
      //      << individual->y() << "," << individual->z() << ")" << endl;

      if(bgm->inDomain(x,y,z)){
        //        cout << "   spawn " << i << " in domain" << endl;

        MVertex *closest = bgm->get_nearest_neighbor(individual);
        h = bgm->size(closest);// get approximate size, closest vertex, faster ?!

        if(far_from_boundary_3D(bgm,individual,h)){
          //        cout << "   spawn " << i << " far from bnd" << endl;
          bgm->eval_approximate_crossfield(closest, crossfield);
          wrapper.set_ok(true);
          wrapper.set_individual(individual);
          wrapper.set_parent(parent);
          wrapper.set_size(&h);
          wrapper.set_crossfield(&crossfield);

          fill_min_max(x,y,z,h,min,max);

          rtree.Search(min,max,rtree_callback_3D,&wrapper);

          if(wrapper.get_ok()){
            //        cout << "   spawn " << i << " wrapper OK" << endl;

            if (!use_vectorial_smoothness){
              smoothness_vertex_pair *svp = new smoothness_vertex_pair();
              svp->v = individual;
              svp->rank=bgm->get_smoothness(individual->x(),individual->y(),individual->z());
              svp->dir = 0;
              svp->layer = parent_layer+1;
              svp->size = h;
              svp->cf = crossfield;
              fifo->insert(svp);
              if (debug){
                smoothness_forplot[svp->v] = svp->rank;
                vert_priority[individual] = priority_counter++;
              }

            }
            else{
              if (debug) vert_priority[individual] = priority_counter++;
              for (int idir=0;idir<3;idir++){
                smoothness_vertex_pair *svp = new smoothness_vertex_pair();
                svp->v = individual;
                svp->rank = bgm->get_vectorial_smoothness(idir,x,y,z);
                svp->dir = idir;
                svp->layer = parent_layer+1;
                svp->size = h;
                for (int k=0;k<3;k++) svp->direction(k) = crossfield(k,idir);
                svp->cf = crossfield;
                fifo->insert(svp);
              }
            }

            rtree.Insert(min,max,individual);
            new_vertices.push_back(individual);
            spawn_created = true;

          }
        }
      }
      if(!spawn_created){
        delete individual;
      }
    }// end loop on spawns
  }

  //ProfilerStop();

  time_insert_points += (Cpu() - a);

  // --- output ---
  if (debug){
    stringstream ss;
    ss << "priority_3D_" << gr->tag() << ".pos";
    print_nodal_info(ss.str().c_str(),vert_priority);
    ss.clear();

    stringstream sss;
    sss << "smoothness_3D_" << gr->tag() << ".pos";
    print_nodal_info(sss.str().c_str(),smoothness_forplot);
    sss.clear();
  }

  // ------- meshing using new points
  cout << "tets in gr before= " << gr->tetrahedra.size() << endl;
  cout << "nb new vertices= " << new_vertices.size() << endl;
  a=Cpu();

  int option = CTX::instance()->mesh.algo3d;
  CTX::instance()->mesh.algo3d = ALGO_3D_DELAUNAY;

  deMeshGRegion deleter;
  deleter(gr);
  std::vector<GRegion*> regions;
  regions.push_back(gr);
  meshGRegion mesher(regions); //?
  mesher(gr); //?
  MeshDelaunayVolume(regions);
  time_meshing += (Cpu() - a);

  cout << "tets in gr after= " << gr->tetrahedra.size() << endl;
  cout << "gr tag=" << gr->tag() << endl;

  CTX::instance()->mesh.algo3d = option;

  delete fifo;
  for(unsigned int i=0;i<new_vertices.size();i++) delete new_vertices[i];
  new_vertices.clear();
  rtree.RemoveAll();

  return true;
}
Example #23
0
void Filler::treat_region(GRegion* gr){

  int NumSmooth = CTX::instance()->mesh.smoothCrossField;
  std::cout << "NumSmooth = " << NumSmooth << std::endl ;
  if(NumSmooth && (gr->dim() == 3)){
    double scale = gr->bounds().diag()*1e-2;
    Frame_field::initRegion(gr,NumSmooth);
    Frame_field::saveCrossField("cross0.pos",scale);

    Frame_field::smoothRegion(gr,NumSmooth);
    Frame_field::saveCrossField("cross1.pos",scale);
  }

#if defined(HAVE_RTREE)
  unsigned int i;
  int j;
  int count;
  int limit;
  bool ok2;
  double x,y,z;
  SPoint3 point;
  Node *node,*individual,*parent;
  MVertex* vertex;
  MElement* element;
  MElementOctree* octree;
  deMeshGRegion deleter;
  Wrapper wrapper;
  GFace* gf;
  std::queue<Node*> fifo;
  std::vector<Node*> spawns;
  std::vector<Node*> garbage;
  std::vector<MVertex*> boundary_vertices;
  std::set<MVertex*> temp;
  std::list<GFace*> faces;
  std::map<MVertex*,int> limits;
  std::set<MVertex*>::iterator it;
  std::list<GFace*>::iterator it2;
  std::map<MVertex*,int>::iterator it3;
  RTree<Node*,double,3,double> rtree;
  
  Frame_field::init_region(gr);
  Size_field::init_region(gr);
  Size_field::solve(gr);
  octree = new MElementOctree(gr->model());
  garbage.clear();
  boundary_vertices.clear();
  temp.clear();
  new_vertices.clear();
  faces.clear();
  limits.clear();

  faces = gr->faces();	
  for(it2=faces.begin();it2!=faces.end();it2++){
    gf = *it2;
	limit = code(gf->tag());
	for(i=0;i<gf->getNumMeshElements();i++){
	  element = gf->getMeshElement(i);
      for(j=0;j<element->getNumVertices();j++){
	    vertex = element->getVertex(j);
		temp.insert(vertex);
		limits.insert(std::pair<MVertex*,int>(vertex,limit));
	  }
	}
  }
		
  /*for(i=0;i<gr->getNumMeshElements();i++){
    element = gr->getMeshElement(i);
    for(j=0;j<element->getNumVertices();j++){
      vertex = element->getVertex(j);
      temp.insert(vertex);
    }
  }*/

  for(it=temp.begin();it!=temp.end();it++){
    if((*it)->onWhat()->dim()==0){
	  boundary_vertices.push_back(*it);
	}
  }
	
  for(it=temp.begin();it!=temp.end();it++){
    if((*it)->onWhat()->dim()==1){
	  boundary_vertices.push_back(*it);
	}
  }
	
  for(it=temp.begin();it!=temp.end();it++){
    if((*it)->onWhat()->dim()==2){
	  boundary_vertices.push_back(*it);
	}
  }
	
  /*for(it=temp.begin();it!=temp.end();it++){
    if((*it)->onWhat()->dim()<3){
      boundary_vertices.push_back(*it);
    }
  }*/
  //std::ofstream file("nodes.pos");
  //file << "View \"test\" {\n";	

  for(i=0;i<boundary_vertices.size();i++){
    x = boundary_vertices[i]->x();
    y = boundary_vertices[i]->y();
    z = boundary_vertices[i]->z();
    
    node = new Node(SPoint3(x,y,z));
    compute_parameters(node,gr);
	node->set_layer(0);
	
	it3 = limits.find(boundary_vertices[i]);
	node->set_limit(it3->second);
	
	rtree.Insert(node->min,node->max,node);
	fifo.push(node);
    //print_node(node,file);
  }
  
  count = 1;
  while(!fifo.empty()){
    parent = fifo.front();
	fifo.pop();
	garbage.push_back(parent);
	  
	if(parent->get_limit()!=-1 && parent->get_layer()>=parent->get_limit()){
	  continue;
	}
	  
	spawns.clear();
	spawns.resize(6);
	  
	for(i=0;i<6;i++){
	  spawns[i] = new Node();
	}
	
	create_spawns(gr,octree,parent,spawns);
	
	for(i=0;i<6;i++){
	  ok2 = 0;
	  individual = spawns[i];
	  point = individual->get_point();
	  x = point.x();
	  y = point.y();
	  z = point.z();
	  
	  if(inside_domain(octree,x,y,z)){
		compute_parameters(individual,gr);
		individual->set_layer(parent->get_layer()+1);
		individual->set_limit(parent->get_limit());
		
		if(far_from_boundary(octree,individual)){
		  wrapper.set_ok(1);
		  wrapper.set_individual(individual);
		  wrapper.set_parent(parent);
		  rtree.Search(individual->min,individual->max,rtree_callback,&wrapper);
			
		  if(wrapper.get_ok()){
		    fifo.push(individual);
		    rtree.Insert(individual->min,individual->max,individual);
			vertex = new MVertex(x,y,z,gr,0);
			new_vertices.push_back(vertex);
			ok2 = 1;
			//print_segment(individual->get_point(),parent->get_point(),file);
		  }
	    }
	  }
		
	  if(!ok2) delete individual;
	}
	
	if(count%100==0){
	  printf("%d\n",count);
	}
	count++;
  }
  
  //file << "};\n";

  int option = CTX::instance()->mesh.algo3d;
  CTX::instance()->mesh.algo3d = ALGO_3D_DELAUNAY;

  deleter(gr);
  std::vector<GRegion*> regions;
  regions.push_back(gr);
  meshGRegion mesher(regions); //?
  mesher(gr); //?
  MeshDelaunayVolume(regions);

  CTX::instance()->mesh.algo3d = option;
	
  for(i=0;i<garbage.size();i++) delete garbage[i];
  for(i=0;i<new_vertices.size();i++) delete new_vertices[i];
  new_vertices.clear();
  delete octree;
  rtree.RemoveAll();
  Size_field::clear();
  Frame_field::clear();
#endif
}
Example #24
0
std::unique_ptr<Problem> Pal::extract( const QgsRectangle &extent, const QgsGeometry &mapBoundary )
{
  // to store obstacles
  RTree<FeaturePart *, double, 2, double> *obstacles = new RTree<FeaturePart *, double, 2, double>();

  std::unique_ptr< Problem > prob = qgis::make_unique< Problem >();

  int i, j;

  double bbx[4];
  double bby[4];

  double amin[2];
  double amax[2];

  int max_p = 0;

  LabelPosition *lp = nullptr;

  bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = extent.xMinimum();
  bby[0] = bby[1] = amin[1] = prob->bbox[1] = extent.yMinimum();
  bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = extent.xMaximum();
  bby[2] = bby[3] = amax[1] = prob->bbox[3] = extent.yMaximum();

  prob->pal = this;

  QLinkedList<Feats *> *fFeats = new QLinkedList<Feats *>;

  FeatCallBackCtx context;

  // prepare map boundary
  geos::unique_ptr mapBoundaryGeos( QgsGeos::asGeos( mapBoundary ) );
  geos::prepared_unique_ptr mapBoundaryPrepared( GEOSPrepare_r( QgsGeos::getGEOSHandler(), mapBoundaryGeos.get() ) );

  context.fFeats = fFeats;
  context.obstacles = obstacles;
  context.candidates = prob->candidates;
  context.mapBoundary = mapBoundaryPrepared.get();

  ObstacleCallBackCtx obstacleContext;
  obstacleContext.obstacles = obstacles;
  obstacleContext.obstacleCount = 0;

  // first step : extract features from layers

  int previousFeatureCount = 0;
  int previousObstacleCount = 0;

  QStringList layersWithFeaturesInBBox;

  mMutex.lock();
  const auto constMLayers = mLayers;
  for ( Layer *layer : constMLayers )
  {
    if ( !layer )
    {
      // invalid layer name
      continue;
    }

    // only select those who are active
    if ( !layer->active() )
      continue;

    // check for connected features with the same label text and join them
    if ( layer->mergeConnectedLines() )
      layer->joinConnectedFeatures();

    layer->chopFeaturesAtRepeatDistance();

    layer->mMutex.lock();

    // find features within bounding box and generate candidates list
    context.layer = layer;
    layer->mFeatureIndex->Search( amin, amax, extractFeatCallback, static_cast< void * >( &context ) );
    // find obstacles within bounding box
    layer->mObstacleIndex->Search( amin, amax, extractObstaclesCallback, static_cast< void * >( &obstacleContext ) );

    layer->mMutex.unlock();

    if ( context.fFeats->size() - previousFeatureCount > 0 || obstacleContext.obstacleCount > previousObstacleCount )
    {
      layersWithFeaturesInBBox << layer->name();
    }
    previousFeatureCount = context.fFeats->size();
    previousObstacleCount = obstacleContext.obstacleCount;
  }
  mMutex.unlock();

  prob->nbLabelledLayers = layersWithFeaturesInBBox.size();
  prob->labelledLayersName = layersWithFeaturesInBBox;

  if ( fFeats->isEmpty() )
  {
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  prob->nbft = fFeats->size();
  prob->nblp = 0;
  prob->featNbLp = new int [prob->nbft];
  prob->featStartId = new int [prob->nbft];
  prob->inactiveCost = new double[prob->nbft];

  Feats *feat = nullptr;

  // Filtering label positions against obstacles
  amin[0] = amin[1] = std::numeric_limits<double>::lowest();
  amax[0] = amax[1] = std::numeric_limits<double>::max();
  FilterContext filterCtx;
  filterCtx.cdtsIndex = prob->candidates;
  filterCtx.pal = this;
  obstacles->Search( amin, amax, filteringCallback, static_cast< void * >( &filterCtx ) );

  if ( isCanceled() )
  {
    const auto constFFeats = *fFeats;
    for ( Feats *feat : constFFeats )
    {
      qDeleteAll( feat->lPos );
      feat->lPos.clear();
    }

    qDeleteAll( *fFeats );
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  int idlp = 0;
  for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
  {
    feat = fFeats->takeFirst();

    prob->featStartId[i] = idlp;
    prob->inactiveCost[i] = std::pow( 2, 10 - 10 * feat->priority );

    switch ( feat->feature->getGeosType() )
    {
      case GEOS_POINT:
        max_p = point_p;
        break;
      case GEOS_LINESTRING:
        max_p = line_p;
        break;
      case GEOS_POLYGON:
        max_p = poly_p;
        break;
    }

    // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
    max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

    // only keep the 'max_p' best candidates
    while ( feat->lPos.count() > max_p )
    {
      // TODO remove from index
      feat->lPos.last()->removeFromIndex( prob->candidates );
      delete feat->lPos.takeLast();
    }

    // update problem's # candidate
    prob->featNbLp[i] = feat->lPos.count();
    prob->nblp += feat->lPos.count();

    // add all candidates into a rtree (to speed up conflicts searching)
    for ( j = 0; j < feat->lPos.count(); j++, idlp++ )
    {
      lp = feat->lPos.at( j );
      //lp->insertIntoIndex(prob->candidates);
      lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
    }
    fFeats->append( feat );
  }

  int nbOverlaps = 0;

  while ( !fFeats->isEmpty() ) // foreach feature
  {
    if ( isCanceled() )
    {
      const auto constFFeats = *fFeats;
      for ( Feats *feat : constFFeats )
      {
        qDeleteAll( feat->lPos );
        feat->lPos.clear();
      }

      qDeleteAll( *fFeats );
      delete fFeats;
      delete obstacles;
      return nullptr;
    }

    feat = fFeats->takeFirst();
    while ( !feat->lPos.isEmpty() ) // foreach label candidate
    {
      lp = feat->lPos.takeFirst();
      lp->resetNumOverlaps();

      // make sure that candidate's cost is less than 1
      lp->validateCost();

      prob->addCandidatePosition( lp );
      //prob->feat[idlp] = j;

      lp->getBoundingBox( amin, amax );

      // lookup for overlapping candidate
      prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, static_cast< void * >( lp ) );

      nbOverlaps += lp->getNumOverlaps();
    }
    delete feat;
  }
  delete fFeats;

  //delete candidates;
  delete obstacles;

  nbOverlaps /= 2;
  prob->all_nblp = prob->nblp;
  prob->nbOverlap = nbOverlaps;

  return prob;
}
Example #25
0
void TestRTree::testInsertRows()
{
    // RTree::InsertMode = RTree::CopyPrevious
    RTree<QString> tree;
    tree.insert(QRect(1, 1, 1, 2), QString("1"));
    tree.insert(QRect(2, 1, 1, 3), QString("2"));
    tree.insert(QRect(3, 2, 1, 4), QString("3"));
    tree.insert(QRect(4, 2, 1, 5), QString("4"));
    tree.insert(QRect(5, 3, 1, 3), QString("5"));
    tree.insert(QRect(6, 3, 1, 4), QString("6"));
    tree.insert(QRect(7, 4, 1, 2), QString("7"));
    tree.insert(QRect(8, 4, 1, 3), QString("8"));
    tree.insert(QRect(9, 6, 1, 3), QString("9"));
    QList< QPair<QRectF, QString> > undo = tree.insertRows(3, 3);
    QList< QPair<QRectF, QString> > pairs = tree.intersectingPairs(QRect(1, 1, 10, 10)).values();
    QCOMPARE(pairs.count(), 9);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 1, 2));
    QCOMPARE(pairs[0].second, QString("1"));
    QCOMPARE(pairs[1].first, QRectF(2, 1, 1, 6));
    QCOMPARE(pairs[1].second, QString("2"));
    QCOMPARE(pairs[2].first, QRectF(3, 2, 1, 7));
    QCOMPARE(pairs[2].second, QString("3"));
    QCOMPARE(pairs[3].first, QRectF(4, 2, 1, 8));
    QCOMPARE(pairs[3].second, QString("4"));
    QCOMPARE(pairs[4].first, QRectF(5, 6, 1, 3));
    QCOMPARE(pairs[4].second, QString("5"));
    QCOMPARE(pairs[5].first, QRectF(6, 6, 1, 4));
    QCOMPARE(pairs[5].second, QString("6"));
    QCOMPARE(pairs[6].first, QRectF(7, 7, 1, 2));
    QCOMPARE(pairs[6].second, QString("7"));
    QCOMPARE(pairs[7].first, QRectF(8, 7, 1, 3));
    QCOMPARE(pairs[7].second, QString("8"));
    QCOMPARE(pairs[8].first, QRectF(9, 9, 1, 3));
    QCOMPARE(pairs[8].second, QString("9"));
    QCOMPARE(undo.count(), 0);
#if 0
    // RTree::InsertMode = RTree::CopyCurrent
    tree.clear();
    tree.insert(QRect(1, 1, 1, 2), QString("1"));
    tree.insert(QRect(2, 1, 1, 3), QString("2"));
    undo = tree.insertColumns(3, 3, RTree<QString>::CopyCurrent);
    pairs = tree.intersectingPairs(QRect(1, 1, 10, 10));
    QCOMPARE(pairs.count(), 2);
    QCOMPARE(pairs[0].first, QRectF(1, 1, 1, 2));
    QCOMPARE(pairs[1].first, QRectF(2, 1, 1, 6));
    QCOMPARE(undo.count(), 0);
#endif

    RTree<bool> boolTree;
    boolTree.insert(QRect(1, 2, 2, 1), true);
    boolTree.insert(QRect(1, 3, 1, 2), true);
    boolTree.insertRows(6, 1);
    QList< QPair<QRectF, bool> > boolPairs = boolTree.intersectingPairs(QRect(1, 2, 1, 1)).values();
    QCOMPARE(boolPairs.count(), 1);
    QCOMPARE(boolPairs[0].first, QRectF(1, 2, 2, 1));
    QCOMPARE(boolPairs[0].second, true);
    boolPairs = boolTree.intersectingPairs(QRect(1, 3, 1, 1)).values();
    QCOMPARE(boolPairs.count(), 1);
    QCOMPARE(boolPairs[0].first, QRectF(1, 3, 1, 2));
    QCOMPARE(boolPairs[0].second, true);
}