int main(){
	node *root        = newNode(1);
    root->left               = newNode(2);
    root->right              = newNode(3);
    root->right->left        = newNode(4);
    root->right->right       = newNode(5);
    root->right->left->left  = newNode(6);
    root->right->left->left->left  = newNode(7);
    root->right->left->left->right = newNode(8);
    root->right->right->right      = newNode(9);
    root->right->right->right->left = newNode(10);

    int k = 8;
    cout<<findClosestDown(root);
    cout << "Distace of the closest key from " << k << " is "
         << findClosest(root, k) << endl;
    k = 3;
    cout << "Distace of the closest key from " << k << " is "
         << findClosest(root, k) << endl;
    k = 5;
    cout << "Distace of the closest key from " << k << " is "
         << findClosest(root, k) << endl;
    k = 2;
    cout << "Distace of the closest key from " << k << " is "
         << findClosest(root, k) << endl;
	return 0;
}
Exemplo n.º 2
0
void readLeavesToPal(octNode **leaves,int gotLeaves,uint8 *palette,int palEntries)
{
octNode **leavesPtr;
uint8 *palPtr;
int R,G,B;
int i,palGot;
int distance,minDistance;

	palPtr = palette; palGot = 0;
	for(minDistance=256;minDistance>=0 && palGot < palEntries;minDistance>>=1)
	{
		leavesPtr = leaves;
		for(i=0;i<gotLeaves;i++)
		{
			R = (*leavesPtr)->R;
			G = (*leavesPtr)->G;
			B = (*leavesPtr)->B;
			leavesPtr++;
			distance = findClosest(R,G,B,palette,palGot,NULL);
			if ( distance >= minDistance )
			{
				*palPtr++ = R;
				*palPtr++ = G;
				*palPtr++ = B;
				palGot ++;
				if ( palGot == palEntries )
					break;
			}
		}
	}
}
Exemplo n.º 3
0
ClosestPolygonPoint findClosest(Point from, Polygons& polygons)
{

    Polygon emptyPoly;
    ClosestPolygonPoint none(from, -1, emptyPoly);
    
    if (polygons.size() == 0) return none;
    PolygonRef aPolygon = polygons[0];
    if (aPolygon.size() == 0) return none;
    Point aPoint = aPolygon[0];

    ClosestPolygonPoint best(aPoint, 0, aPolygon);

    int64_t closestDist = vSize2(from - best.location);
    
    for (unsigned int ply = 0; ply < polygons.size(); ply++)
    {
        PolygonRef poly = polygons[ply];
        if (poly.size() == 0) continue;
        ClosestPolygonPoint closestHere = findClosest(from, poly);
        int64_t dist = vSize2(from - closestHere.location);
        if (dist < closestDist)
        {
            best = closestHere;
            closestDist = dist;
        }

    }

    return best;
}
Exemplo n.º 4
0
const ColorRGB Scene3D::traceRay(const Ray& ray, int depth) const
{

	float closest_t_value = NO_INTERSECT;
	const SceneObject* closest_object = findClosest(ray, closest_t_value);

	if (closest_object == 0)
		return ColorRGB(0,0,0);

	ColorRGB retColor(0,0,0);


	for (int i = 0; i < lights.size(); i++)
	{
		Vector3D normL = ((*lights[i]).get_position()-ray.getPointAt(closest_t_value)).normalize();
		Vector3D normN = (*closest_object).surface_normal(ray.getPointAt(closest_t_value));

		retColor += (*lights[i]).get_color()*(*closest_object).get_color()*std::max((normL*normN),float(0));
		
		if (depth < 6 && (*closest_object).get_reflectivity() > 0)
		{
				Ray reflected_ray = ray.reflect(ray.getPointAt(closest_t_value), (*closest_object).surface_normal(ray.getPointAt(closest_t_value)));
				ColorRGB reflection_color = traceRay(reflected_ray, depth+1);
				retColor+= (*closest_object).get_reflectivity()*reflection_color;
		}
		
	}	


	return retColor;
}
void FaceDetectorFilter::facesCallback(const pcl::PointCloud<pcl::PointXYZL>::ConstPtr& msg)
{
	tf::Transform cameraTransform;
	try {
		tf::StampedTransform tr;
		transformListener.lookupTransform ( "odom","camera_link2",ros::Time(0),tr);
		cameraTransform=tr;
	} catch(...) {
		return;
	}
	std::set<unsigned int> usedUsers = deleteOld();
	std::list<Point> incomingUsers;
	fillList(incomingUsers, msg,cameraTransform);

	while(1) {
		std::pair<unsigned int,std::list<Point>::iterator> match = findClosest(incomingUsers);
		if(match.first == 0)
			break;
		float distance = getDistance(users[match.first],*match.second);
		if(distance> MAX_SPEED)
			break;

		if(usedUsers.find(match.first) == usedUsers.end()) {
			users[match.first] = *match.second;
			usedUsers.insert(match.first);
			std::cerr<<"user updated: "<<match.first<<", distance:" <<distance<<std::endl;
		} else {
			std::cerr<<"user ignored: "<<match.first<<", distance:" <<distance<<std::endl;

		}
		incomingUsers.erase(match.second);
	}

	for(std::list<Point>::iterator it = incomingUsers.begin(); it!=incomingUsers.end(); ++it) {
		unsigned int newId = getAvailableId(usedUsers);
		users[newId] = *it;
		std::cerr<<"added user: "******"camera_link2";
	pmsg->height = 1;
	for(std::map<unsigned int,Point>::iterator it = users.begin(); it != users.end(); ++it) {
		pcl::PointXYZL point;
		Point p(it->second);
		transformPoint(p,cameraTransform,true);
		
		point.label = it->first;
		point.x=p.x;
		point.y=p.y;
		point.z = p.z;
		pmsg->points.push_back(point);
	}
	pmsg->width = pmsg->points.size();
	facePublisher.publish(pmsg);

}
Exemplo n.º 6
0
Arquivo: main.cpp Projeto: turu/mikro
 void appendToExisting(std::vector<std::vector<cv::Point> > & contours) {
     for (std::deque<Trackable*>::iterator it = objects.begin(); it != objects.end(); it++) {
         Trackable * trackable = *it;
         std::vector<std::vector<cv::Point > >::iterator closest = findClosest(trackable->getLastLocalization(), contours);
         if (closest != contours.end()) {
             std::vector<cv::Point> contour = *closest;
             cv::Point cog = getCOG(contour);
             if (getDistance(cog, trackable->getLastLocalization()) < distanceThreshold) {
                 trackable->signal(cog);
                 contours.erase(closest);
             }
         }
     }
 }
Exemplo n.º 7
0
void Weaver::connect_polygons(Polygons& supporting, int z0, Polygons& supported, int z1, WeaveConnection& result)
{
 
    if (supporting.size() < 1)
    {
        DEBUG_PRINTLN("lower layer has zero parts!");
        return;
    }
    
    result.z0 = z0;
    result.z1 = z1;
    
    std::vector<WeaveConnectionPart>& parts = result.connections;
        
    for (unsigned int prt = 0 ; prt < supported.size(); prt++)
    {
        
        const PolygonRef upperPart = supported[prt];
        
        
        parts.emplace_back(prt);
        WeaveConnectionPart& part = parts.back();
        PolyLine3& connection = part.connection;
        
        Point3 last_upper;
        bool firstIter = true;
        
        for (const Point& upper_point : upperPart)
        {
            
            ClosestPolygonPoint lowerPolyPoint = findClosest(upper_point, supporting);
            Point& lower = lowerPolyPoint.location;
            
            Point3 lower3 = Point3(lower.X, lower.Y, z0);
            Point3 upper3 = Point3(upper_point.X, upper_point.Y, z1);
            
            
            if (firstIter)
                connection.from = lower3;
            else
                connection.segments.emplace_back<>(lower3, WeaveSegmentType::DOWN);
            
            connection.segments.emplace_back<>(upper3, WeaveSegmentType::UP);
            last_upper = upper3;
            
            firstIter = false;
        }
    }
}
Exemplo n.º 8
0
std::vector<int> getPath(const Locations& input)
{
    if(input.empty())
        return {};

    Locations locations(input);
    std::vector<int> results;
    Locations::iterator current = locations.begin();
    do {
        Position curPos = current->second;
        results.push_back(current->first);
        locations.erase(current);

        current = findClosest(curPos, locations);

    } while(!locations.empty());

    return results;
}
Exemplo n.º 9
0
  void RegionMerger::fillPriorityQueue(){
    currentTime=0;

    queue_vector.clear();

    Region *r;

    map<int,Region>::iterator rit;
    for(rit=regionList.begin();rit!=regionList.end();rit++){

      r=&(rit->second);
	r->timestamp=0;
	// updateFeatureValues(i);

// 	set<int>::iterator it;
// 	for(it=r->nList.begin(); it != r->nList.end(); it++)
// 	  if(*it > i){
// 	    regionDiff d;
// 	    d.timestamp=0;
// 	    d.r1=i;
// 	    d.r2=*it;
// 	    d.dist=-regionDist(i,*it);
// 	    queue.push(d);
// 	  }

	r->closestNeighbour=findClosest(rit->first);

	regionDiff d;
	d.timestamp=0;
	d.r1=rit->first;
	d.r2=r->closestNeighbour;
	d.dist=-regionDist(rit->first,r->closestNeighbour);
	//queue.push(d);

	//	cout << "Initial merge: " << d.print() << endl;

	queue_vector.push_back(d);

    }
    make_heap(queue_vector.begin(),queue_vector.end());
  }
Exemplo n.º 10
0
int main(void) {
	clockSetup();
	ioSetup();
	adcSetup();

	while (1) {
		adcSample();
		avg_adc = ((adc[0]+adc[1]+adc[2]+adc[3]+adc[4]+adc[5]+adc[6]+adc[7]+adc[8]+adc[9]) / 10);;
		findClosest();
		if (distance < 20) {
			if (alarm_state == STATE_DISARMED) state = 0;
			else {
				if (state == 0) {
					alarm_state = STATE_ALERT;
					memset(txString, 0, 80);
					sprintf(txString, "%s%sSystem Status: %s", clear_screen, line_1, ALERT);
					i = 0;
					state = STATE_CHANGE;
					UC0IE |= UCA0TXIE; // Enable USCI_A0 TX interrupt
					UCA0TXBUF = txString[i++];
				}
				P2OUT |= ALERTLED;
				P2OUT &= ~(SAFELED + WARNLED);
				change_lights = 1;
			}

		} else if (change_lights == 1) {
			if (alarm_state == STATE_ARMED) {
				P2OUT |= SAFELED;
				P2OUT &= ~(ALERTLED + WARNLED);
			} else if (alarm_state == STATE_DISARMED) {
				P2OUT |= WARNLED;
				P2OUT &= ~(ALERTLED + SAFELED);
			}
		}
	}
}
Exemplo n.º 11
0
void Weaver::chainify_polygons(Polygons& parts1, Point start_close_to, Polygons& result, bool include_last)
{
    
        
    for (unsigned int prt = 0 ; prt < parts1.size(); prt++)
    {
        const PolygonRef upperPart = parts1[prt];
        
        ClosestPolygonPoint closestInPoly = findClosest(start_close_to, upperPart);

        
        PolygonRef part_top = result.newPoly();
        
        GivenDistPoint next_upper;
        bool found = true;
        int idx = 0;
        
        for (Point upper_point = upperPart[closestInPoly.pos]; found; upper_point = next_upper.location)
        {
            found = getNextPointWithDistance(upper_point, nozzle_top_diameter, upperPart, idx, closestInPoly.pos, next_upper);

            
            if (!found) 
            {
                break;
            }
            
            part_top.add(upper_point);
            
            idx = next_upper.pos;
        }
        if (part_top.size() > 0)
            start_close_to = part_top.back();
        else
            result.remove(result.size()-1);
    }
}
Exemplo n.º 12
0
int main(int argc, char* argv[]){
  FILE *inputFile; //done
  int breakMe = 0, lastRead = 0;
  char *buffer, *tmpChar; //done
  long i=0, j=0, n=0, l=0, colAmt=0, rowAmt=0, fileSize=0, k=atoi(argv[2]);
  long closePoint = 0;
  long iterCount = 0;
  double *M, *centers1, *centers2, *tmpCenters, *centerWeights; //done
//Variable allocation and initialization
  inputFile = fopen(argv[1], "r");
  buffer = malloc(memBlock);
  M = malloc(memBlock);
  srand(time(NULL));
  fgets(buffer, memBlock, inputFile);
  tmpChar = strtok(buffer, delims);
  while(tmpChar != NULL){
    ++colAmt;
    tmpChar = strtok(NULL, delims);
  }
  rowAmt = memBlock/(sizeof(double)*colAmt);
  fseek(inputFile, 0, SEEK_END);
  fileSize = ftell(inputFile);
  rewind(inputFile);
  centers1 = (double*) malloc(sizeof(double)*k*colAmt);
  centers2 = (double*) malloc(sizeof(double)*k*colAmt);
  centerWeights = (double*) malloc(sizeof(double)*k);
/*******SEEDING**********************/
  tmpChar = NULL;
  lastRead = 0;
  do{
    fillBuffer(inputFile, fileSize, buffer);
    for(i=0;i<(rowAmt*colAmt); ++i){
      if(tmpChar == NULL){
        if(lastRead){
          breakMe=1;
          break;
        }
        else{
          lastRead  = fillBuffer(inputFile, fileSize, buffer);
          tmpChar = strtok(buffer, delims);
        }
      }
      M[i] = atof(tmpChar);
      tmpChar = strtok(NULL, delims);
    }
  }while(i<(rowAmt*colAmt) && !breakMe);
  breakMe = 0;
  for(j=0; j<k; ++j){
    centerWeights[j] = 0;
    memmove(centers1+(j*colAmt), M+((rand()%(i/colAmt))*colAmt), sizeof(double)*colAmt);
    memmove(centers2+(j*colAmt), centers1+(j*colAmt), sizeof(double)*colAmt);
  }

/********CLUSTERING**********************/  
  rewind(inputFile);
  tmpChar = NULL;
  lastRead = 0;
  breakMe = 0;
  iterCount = 0;
  for(n=0; n<10; ++n){
    do{
      do{
        for(i=0;i<(rowAmt*colAmt); ++i){
          if(tmpChar == NULL){
            if(lastRead){
              breakMe=1;
              break;
            }
            else{
              printf("%zu : %lu\r", ftell(inputFile), fileSize);
              lastRead  = fillBuffer(inputFile, fileSize, buffer);
              tmpChar = strtok(buffer, delims);
            }
          }
          M[i] = atof(tmpChar);
          tmpChar = strtok(NULL, delims);
        }
        for(j=0; j<(i/colAmt); ++j){
          closePoint = findClosest(M+(j*colAmt), centers1, colAmt, k);
          for(l=0; l<colAmt; ++l){
            centers2[closePoint*colAmt+l] = ((centers2[closePoint*colAmt+l]
                * centerWeights[closePoint]) + M[j*colAmt + l]) / (centerWeights[closePoint] +1);
          }
          ++centerWeights[closePoint];
        }
      }while(!breakMe);
/*******PRINT CENTERS************************
      printf("---CENTERS---\n");
      for(j=0;j<k; ++j){
        printf("%lu: ", j+1);
        for(l=0; l<colAmt; ++l)
          printf("%f ", centers2[j*colAmt + l]);
        printf("\n");
      }  
********************************************/
      for(i=0;i<k;++i)
        centerWeights[i] = 0;
      tmpCenters = centers1;
      centers1 = centers2;
      centers2 = tmpCenters;
      breakMe = 0;
      lastRead = 0;
      rewind(inputFile);
      ++iterCount;
      if(iterCount > iterLimit){
        printf("ITERLIMITBREAK\n");
        break;
      }
    }while(centerDiff(centers1, centers2, .0001, k, colAmt));
  }
  printf("---CENTERS---\n");
  for(j=0;j<k; ++j){
    printf("%lu: ", j+1);
    for(l=0; l<colAmt; ++l)
      printf("%f ", centers2[j*colAmt + l]);
    printf("\n");
  }

  fclose(inputFile);
  free(buffer);
  free(M);
  free(centers1);
  free(centers2);
  free(centerWeights);
  return 1;
}
Exemplo n.º 13
0
  void RegionMerger::mergeTopRegions(){
    
    //regionDiff d=queue.top();
    //queue.pop();

    pop_heap(queue_vector.begin(),queue_vector.end());
    regionDiff d=queue_vector.back();
    queue_vector.pop_back();

    if(regionList.count(d.r1)==0 ||regionList.count(d.r2)==0){
      // cout << "popped inexistent merge" << endl;
      return;
    }

    if(d.r1>d.r2){
      int tmp=d.r1;
      d.r1=d.r2;
      d.r2=tmp;
    }
    
    Region *r1=&(regionList[d.r1]);
    Region *r2=&(regionList[d.r2]);

    if(d.timestamp < r1->timestamp || d.timestamp < r2->timestamp) return;

    currentTime++;

    int i=d.r1,i2=d.r2;

    //     cout << "Merging regions " << d.r1 <<" and " << d.r2 
    //       << " w\\ d=" << d.dist << endl;

//     cout << "Feature vectors:" << endl << " r1: ";
//     Feature::printFeatureVector(cout,r1->fV);
//     cout << endl << " r2: ";
//     Feature::printFeatureVector(cout,r2->fV);


//     cout << "Neighbours of r1: " << endl;
    set<int>::iterator it;

  //   for(it=r1->nList.begin(); it != r1->nList.end(); it++){
//       if(regionList[*it].count){
// 	cout << "     #"<<*it<<" (size "<<regionList[*it].count<<"):";
//       Feature::printFeatureVector(cout,regionList[*it].fV);
//       cout << endl;
//       }
//     }

//     cout << "Neighbours of r2: " << endl;
//     for(it=r2->nList.begin(); it != r2->nList.end(); it++){
//       if(regionList[*it].count){
// 	cout << "     #"<<*it<<" (size "<<regionList[*it].count<<"):";
// 	Feature::printFeatureVector(cout,regionList[*it].fV);
// 	cout << endl;
//       }
//     }

    mergeRegions(d.r1,d.r2,full_update);

    // now pointer r2 becomes invalid

    for(it=r1->nList.begin(); it != r1->nList.end(); it++){
      Region *r=&(regionList[*it]);
      bool otherBefore = (r->closestNeighbour != i && r->closestNeighbour != i2); 
      r->closestNeighbour=findClosest(*it);
      if(r->closestNeighbour != i && otherBefore) continue; 
      // other relevant merges remain in the queue

      regionDiff d;
      d.timestamp=currentTime;
      d.r1=*it;
      d.r2=r->closestNeighbour;
      d.dist = -regionDist(d.r1,d.r2);
      //queue.push(d);
      //    cout << "pushed merge: " << d.print() << endl;
      queue_vector.push_back(d);
      push_heap(queue_vector.begin(),queue_vector.end());

    }
    if(r1->nList.size()){

      r1->closestNeighbour=findClosest(i);
    
      regionDiff dn;
      dn.timestamp=currentTime;
      dn.r1=i;
      dn.r2=r1->closestNeighbour;
      dn.dist = -regionDist(dn.r1,dn.r2);
      //queue.push(d);
      queue_vector.push_back(dn);
      //cout << "pushed merge: " << dn.print() << endl;
      push_heap(queue_vector.begin(),queue_vector.end());
      
      r1->timestamp=currentTime;
      //r2->timestamp=currentTime;
    }
    // dumpRegionList();
    
    
  }
Exemplo n.º 14
0
void geotag_worker(wc_work_queue &wq, std::vector<GPXPoint> &gpxData) {
    std::string fname;
    // Grab a file from the work queue
    while ((fname = wq.getFile()) != "") {
        try {
            Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fname.c_str());
            if (image.get() == 0) continue;
            image->readMetadata();

            Exiv2::ExifData &exifData = image->exifData();
            if (exifData.empty()) {
                std::string error = fname;
                error += ": No Exif data found in the file";
                throw Exiv2::Error(1, error);
            }
            std::string tmpTime = exifData["Exif.Photo.DateTimeOriginal"].toString();
            auto tstamp = getImageTimeStamp(tmpTime);

            size_t idx = 0;
            bool foundIt = findClosest(gpxData, tstamp, idx);

            if (!foundIt) {
                std::cout << fname << " is not on the GPX track!\n";
                continue;
            } else {
                std::cout << fname << " was at ("  << std::setprecision(10) << gpxData[idx].lat << ", " << std::setprecision(10) << gpxData[idx].lon << ")\n";
            }
            clearGPSFields(exifData);

            exifData["Exif.GPSInfo.GPSMapDatum"] = "WGS-84";

            exifData["Exif.GPSInfo.GPSAltitude"] = Exiv2::Rational(gpxData[idx].ele * 1000, 1000);
            exifData["Exif.GPSInfo.GPSAltitudeRef"] = Exiv2::byte(0);

            // Convert the latitude to DDD*MM'SS.SSS" and set
            int dd, mm;
            double ss;
            convertToDDMMSS(gpxData[idx].lat, dd, mm, ss);
            if (gpxData[idx].lat<0) {
                exifData["Exif.GPSInfo.GPSLatitudeRef"] = "S";
            } else {
                exifData["Exif.GPSInfo.GPSLatitudeRef"] = "N";
            }

            Exiv2::URationalValue::AutoPtr latitude(new Exiv2::URationalValue);
            latitude->value_.push_back(std::make_pair(dd,1));
            latitude->value_.push_back(std::make_pair(mm,1));
            latitude->value_.push_back(std::make_pair(std::trunc(ss*10000)-1,10000));
            auto latKey = Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude");
            exifData.add(latKey, latitude.get());

            convertToDDMMSS(gpxData[idx].lon, dd, mm, ss);
            Exiv2::URationalValue::AutoPtr longitude(new Exiv2::URationalValue);
            if (gpxData[idx].lon<0) {
                exifData["Exif.GPSInfo.GPSLongitudeRef"] = "W";
            } else {
                exifData["Exif.GPSInfo.GPSLongitudeRef"] = "E";
            }
            longitude->value_.push_back(std::make_pair(dd,1));
            longitude->value_.push_back(std::make_pair(mm,1));
            longitude->value_.push_back(std::make_pair(int(ss*10000)-1,10000));
            auto longKey = Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude");
            exifData.add(longKey, longitude.get());


            Exiv2::URationalValue::AutoPtr timestamp(new Exiv2::URationalValue);
            timestamp->value_.push_back(std::make_pair(gpxData[idx].hour,1));
            timestamp->value_.push_back(std::make_pair(gpxData[idx].minute,1));
            timestamp->value_.push_back(std::make_pair(gpxData[idx].second,1));

            auto timeKey = Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp");
            exifData.add(timeKey, timestamp.get());
            
            exifData["Exif.GPSInfo.GPSDateStamp"] = gpxData[idx].dateStamp.c_str();

            image->setExifData(exifData);
            image->writeMetadata();
        }
        catch (Exiv2::AnyError& e) {
            std::cout << "Caught Exiv2 exception '" << e.what() << "'\n";
            continue;
        }
    }
}
Exemplo n.º 15
0
  void RegionMerger::initialApproximateMerge(){

    // const int batchSize=40;
    const int initialStop=400;


    int batchnr=0;

    while((int)regionList.size() > initialStop){

//         cout << "beginning batch of initialApproximateMerge" << endl;
//         cout <<"regionCount="<<regionList.size() << endl;
      
      set<int> region;
      set<int> neighbours;
      set<regionDiff> joins;
      
      int batchSize=(regionList.size()-numberOfRegions)/2;
      //int batchSize=500;

      const int l=regionList.size();
	vector<int> labelsInRL;
	map<int,Region>::iterator rit;

	for(rit=regionList.begin();rit!=regionList.end();rit++)
	  labelsInRL.push_back(rit->first);

 // 	cout << labelsInRL.size() << " labels collected:( l=" << l<<")"<<endl;

//  	for(size_t i=0;i<labelsInRL.size();i++)
//  	  cout<<labelsInRL[i]<<endl;
	  

	
      for(int i=0;i<batchSize;i++){
	int j;

	int r=random(l-1);

	//cout << "r="<<r<<endl;

	j=labelsInRL[r];
	if(region.count(j)||neighbours.count(j)) continue;

	//cout << "region set: "<<formVirtualSegmentLabel(region)<<endl;
	//cout << "neighbours: "<<formVirtualSegmentLabel(neighbours)<<endl;

	region.insert(j);

	//char jstr[80];
	//sprintf(jstr,"%d",j);

	//if(regionList.count(j)==0) 
	//  throw string("accepted region ")+jstr+ " not in regionlist";

	const set<int> &nbr=regionList[j].nList;

	//cout << "accepted region "<<j<<" w/ neighbours " << endl
	//     <<"  "<< formVirtualSegmentLabel(nbr)<<endl;

	neighbours.insert(nbr.begin(),nbr.end());
	regionDiff tmp;
	tmp.r1=j;
	tmp.r2=findClosest(j);

	//cout << "closest region: "<<tmp.r2<<endl;
	tmp.dist=regionList[j].count*regionDist(tmp.r1,tmp.r2);
	tmp.dist=regionDist(tmp.r1,tmp.r2);
	joins.insert(tmp);
      }
      
      // cout <<"joins.size()="<<joins.size()<<endl;

      // sort(joins.begin(),joins.end());
      int i=0;
      map<int,int> joinedTo;
      int njoins=joins.size()/2; // arbitrary choice, quite aggressive
      if(njoins<1) njoins=1;

      for(set<regionDiff>::iterator it=joins.begin();i<njoins;
	  i++,it++){
	regionDiff d=*it;
	//cout << "i= "<<i<<" dist="<<it->dist<<endl;
	while(joinedTo.count(d.r1)) d.r1=joinedTo[d.r1];
	while(joinedTo.count(d.r2)) d.r2=joinedTo[d.r2];

	if(d.r1==d.r2) continue;

	mergeRegions(d.r1,d.r2,full_update);
	//	if(regionList.size() != countRegions()){
	//  cout << "batch nr " << batchnr << endl;
	//  cout << "joined regions "<<d.r1<<" and "<<d.r2<<endl;
	//  cout << "regionList.size()="<<regionList.size()<<" (real="<<countRegions()
	//     << ") -> batchSize="<<batchSize<<endl;
	//}

	if(d.r1<d.r2) joinedTo[d.r2]=d.r1;
	else joinedTo[d.r1]=d.r2;
      }  
      batchnr++;
    }

  }
Exemplo n.º 16
0
void Convert2Tlv::buildInks(TRasterCM32P &rout, const TRaster32P &rin)
{
	std::map<TPixel, int>::const_iterator it;
	TPixel curColor = TPixel::Transparent;
	int i, j;
	int curIndex;

	//prima passata: identifico i colori di inchiostro e metto in rout i pixel di inchiostro puro
	for (i = 0; i < rin->getLy(); i++) {
		TPixel *pixin = rin->pixels(i);
		TPixelCM32 *pixout = rout->pixels(i);
		for (j = 0; j < rin->getLx(); j++, pixin++, pixout++) {
			TPixel colorIn;

			if (pixin->m != 255)
				continue;

			if (curColor != *pixin) {
				curColor = *pixin;
				if ((it = m_colorMap.find(curColor)) == m_colorMap.end()) {
					if (m_colorTolerance > 0)
						it = findNearestColor(curColor);
					//if (it==colorMap.end() && (int)colorMap.size()>origColorCount)
					//	it  = findNearestColor(curColor, colorMap, colorTolerance, origColorCount, colorMap.size()-1);
					if (it == m_colorMap.end() && m_lastIndex < 4095) {
						m_colorMap[curColor] = ++m_lastIndex;
						curIndex = m_lastIndex;
					} else if (it != m_colorMap.end()) {
						m_colorMap[curColor] = it->second;
						curIndex = it->second;
					}
				} else
					curIndex = it->second;
			}
			*pixout = TPixelCM32(curIndex, 0, 0);
		}
	}

	//seconda  passata: metto gli inchiostri di antialiasing
	curColor = TPixel::Transparent;

	for (i = 0; i < rin->getLy(); i++) {
		TPixel *pixin = rin->pixels(i);
		TPixelCM32 *pixout = rout->pixels(i);
		for (j = 0; j < rin->getLx(); j++, pixin++, pixout++) {
			TPixel colorIn;
			if (pixin->m == 255) //gia' messo nel ciclo precedente
				continue;
			if (pixin->m == 0)
				continue;

			colorIn = unmultiply(*pixin); //findClosestOpaque(rin, i, j);

			if (curColor != colorIn) {
				curColor = colorIn;
				if ((it = m_colorMap.find(curColor)) != m_colorMap.end())
					curIndex = it->second;
				else
					curIndex = findClosest(m_colorMap, curColor);
			}
			*pixout = TPixelCM32(curIndex, 0, 255 - pixin->m);
		}
	}
}
Exemplo n.º 17
0
//***************************************************************************************************************
int Ccode::getChimeras(Sequence* query) {
	try {
	
		closest.clear();
		refCombo = 0;
		sumRef.clear(); 
		varRef.clear(); 
		varQuery.clear(); 
		sdRef.clear(); 
		sdQuery.clear();     
		sumQuery.clear();
		sumSquaredRef.clear(); 
		sumSquaredQuery.clear(); 
		averageRef.clear();
		averageQuery.clear();
		anova.clear();
		isChimericConfidence.clear();
		isChimericTStudent.clear();
		isChimericANOVA.clear();
		trim.clear();
		spotMap.clear();
		windowSizes = window;
		windows.clear();

	
		querySeq = query;
		
		//find closest matches to query
		closest = findClosest(query, numWanted);
		
		if (m->control_pressed) {  return 0;  }
		
		//initialize spotMap
		for (int i = 0; i < query->getAligned().length(); i++) {	spotMap[i] = i;		}
	
		//mask sequences if the user wants to 
		if (seqMask != "") {
			decalc->setMask(seqMask);
			
			decalc->runMask(query);
			
			//mask closest
			for (int i = 0; i < closest.size(); i++) {	decalc->runMask(closest[i].seq);	}
			
			spotMap = decalc->getMaskMap();
		}
		
		if (filter) {
			vector<Sequence*> temp;
			for (int i = 0; i < closest.size(); i++) { temp.push_back(closest[i].seq);  }
			temp.push_back(query);  
			
			createFilter(temp, 0.5);
		
			for (int i = 0; i < temp.size(); i++) { 
				if (m->control_pressed) {  return 0;  }
				runFilter(temp[i]);  
			}
			
			//update spotMap
			map<int, int> newMap;
			int spot = 0;
			
			for (int i = 0; i < filterString.length(); i++) {
				if (filterString[i] == '1') {
					//add to newMap
					newMap[spot] = spotMap[i];
					spot++;  
				}
			}
			spotMap = newMap;
		}

		//trim sequences - this follows ccodes remove_extra_gaps 
		trimSequences(query);
		if (m->control_pressed) {  return 0;  }
		
		//windows are equivalent to words - ccode paper recommends windows are between 5% and 20% on alignment length().  
		//Our default will be 10% and we will warn if user tries to use a window above or below these recommendations
		windows = findWindows();  
		if (m->control_pressed) {  return 0;  }

		//remove sequences that are more than 20% different and less than 0.5% different - may want to allow user to specify this later 
		removeBadReferenceSeqs(closest);
		if (m->control_pressed) {  return 0;  }
		
		//find the averages for each querys references
		getAverageRef(closest);  //fills sumRef, averageRef, sumSquaredRef and refCombo.
		getAverageQuery(closest, query);  //fills sumQuery, averageQuery, sumSquaredQuery.
		if (m->control_pressed) {  return 0;  }			
		
		//find the averages for each querys references 
		findVarianceRef();  //fills varRef and sdRef also sets minimum error rate to 0.001 to avoid divide by 0.
		if (m->control_pressed) {  return 0;  }	
			
		//find the averages for the query 
		findVarianceQuery();  //fills varQuery and sdQuery also sets minimum error rate to 0.001 to avoid divide by 0.
		if (m->control_pressed) {  return 0;  }
					
		determineChimeras();  //fills anova, isChimericConfidence, isChimericTStudent and isChimericANOVA. 
		if (m->control_pressed) {  return 0;  }
		
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "Ccode", "getChimeras");
		exit(1);
	}
}
Exemplo n.º 18
0
int putIntoTour(int length, int **adjacencyMatrix, const int &n, int vertex) {
	tour.insert(findClosest(vertex, adjacencyMatrix),vertex);
	return 0;
}
Exemplo n.º 19
0
  bool RegionMerger::joinSmallRegions()
  {
    
    // first look for small regions that have only one neighbour
    int nregions=0;
    // dumpRegionList();
    map<int,Region>::iterator rit=regionList.begin();



    bool first=true;

    while(rit!=regionList.end()&&(int)regionList.size()>numberOfRegions){
      if((int)rit->second.count<=sizeThreshold ){
	nregions++;
	if((int)rit->second.nList.size()==1){
	  
	  // some tricks to avoid iterators going invalid
	  
	  if(first){
	    mergeRegions(rit->first,*rit->second.nList.begin(),no_update);
	    rit=regionList.begin();
	    continue;
	  }
	  else{
	    const map<int,Region>::iterator ritwas=rit;
	    rit--;
	    mergeRegions(ritwas->first,
			 *ritwas->second.nList.begin(),no_update);
	  }
	}
      }
      rit++;
      first=false;
    } // while    

    if(Verbose()>1){
      cout << nregions <<" small regions." << endl;
      cout << "regions w/ one neighbour joined." << endl;
      cout << "region count now " << regionList.size() << endl;
    }

    // then merge all small regions to their closest neighbours
  
      int smallmerges=0;

      bool approx_update=!useAveraging;

      bool fromFirst=false;

      rit=regionList.begin();
      while(rit!=regionList.end()&&(int)regionList.size()>numberOfRegions){
	  while((int)rit->second.count<=sizeThreshold){

	    const int n=findClosest(rit->first);
	    bool isInvalidated= rit->first > n;

	    fromFirst= isInvalidated && (rit==regionList.begin());
	    const map<int,Region>::iterator ritwas=rit;
	    if(isInvalidated) rit--;
	    mergeRegions(ritwas->first,n,
			 approx_update?choose_larger:full_update);
	    smallmerges++;
	    if(Verbose()>1 && smallmerges%100==0)
	      cout << smallmerges <<" small regions merged." << endl;
	    if(isInvalidated) break;
	  } // while

	if(fromFirst){
	  rit=regionList.begin();
	  fromFirst=false;
	}
	else{
	  rit++;
	}

      } // while
	
      if(approx_update){
	// all merges done, update remaining feature vectors
	for(rit=regionList.begin();rit!=regionList.end();rit++)
	    updateFeatureValues(rit->first);
      }

      // cout << "small regions joined" << endl;

      return true;
    
    }
Exemplo n.º 20
0
void BuddyPlayer::act( vector< Object * > * others, World * world, vector< Object * > * add ){
    Character::act(others, world, add);

    if (show_life > getHealth()){
        show_life--;
    }

    if (show_life < getHealth()){
        show_life++;
    }

    vector<Object *> enemies;

    if (getStatus() != Status_Ground && getStatus() != Status_Jumping){
        return;
    }

    filterEnemies(enemies, others);

    if (animation_current->Act()){
        animation_current->reset();
        // nextTicket();
        // animation_current = movements[ "idle" ];
        animation_current = getMovement("idle");
        animation_current->reset();
    }

    if (animation_current == getMovement("idle") ||
        animation_current == getMovement("walk") ){
        if (enemies.empty() && want_x == -1 && want_z == -1 && Util::rnd(15) == 0){
            // want_x = Util::rnd( 100 ) - 50 + furthestFriend( others, getAlliance(), this );
            want_x = Util::rnd(100) - 50 + (int) leader->getX();
            want_z = Util::rnd(world->getMinimumZ(), world->getMaximumZ());
        } else if (! enemies.empty()){
            const Object * main_enemy = findClosest(enemies);
            if ( main_enemy->getX() > getX() ){
                want_x = (int)(main_enemy->getX() - 20 - Util::rnd(20));
            } else {
                want_x = (int)(main_enemy->getX() + 20 + Util::rnd(20));
            }
            if (want_x < 1){
                want_x = Util::rnd(100) - 50 + (int) leader->getX();
            }
            want_z = (int)(Util::rnd(3) - 1 + main_enemy->getZ());
            faceObject(main_enemy);

            if (Util::rnd(35) == 0){
                vector<Util::ReferenceCount<Animation> > attacks;
                for (map<string, Util::ReferenceCount<Animation> >::const_iterator it = getMovements().begin(); it != getMovements().end(); it++){
                    Util::ReferenceCount<Animation> maybe = (*it).second;
                    if (maybe->isAttack() && maybe->getStatus() == Status_Ground && maybe->getName() != "special"){
                        attacks.push_back(maybe);
                    }
                }

                double attack_range = fabs( getX() - main_enemy->getX() );
                double zdistance = ZDistance( main_enemy );
                for (vector<Util::ReferenceCount<Animation> >::iterator it = attacks.begin(); it != attacks.end(); /**/){
                    Util::ReferenceCount<Animation> maybe = *it;
                    if (attack_range > maybe->getRange() || zdistance > maybe->getMinZDistance()){
                        it = attacks.erase(it);
                    } else {
                        it++;
                    }
                }

                if (!attacks.empty()){
                    animation_current = attacks[Util::rnd(attacks.size())];
                    world->addMessage(animationMessage());
                    nextTicket();
                    animation_current->reset();
                    return;
                } else {
                }
            }
        }

        if (want_x != -1 && want_z != -1){
            bool walk = false;
            if (want_x < 1){
                want_x = 1;
            }
            if (want_z < world->getMinimumZ()){
                want_z = world->getMinimumZ() + 1;
            }
            if (want_z >= world->getMaximumZ()){
                want_z = world->getMaximumZ() - 1;
            }
            if (getX() - want_x < -2){
                moveX(getSpeed());
                setFacing(FACING_RIGHT);
                walk = true;
            } else if (getX() - want_x > 2){
                setFacing(FACING_LEFT);
                moveX(getSpeed());
                walk = true;
            }

            if (getZ() < want_z){
                moveZ(getSpeed());
                walk = true;
            } else if (getZ() > want_z){
                moveZ(-getSpeed());
                walk = true;
            }

            if (walk){
                animation_current = getMovement("walk");
            }

            if (fabs(getX() - want_x) <= 2 &&
                fabs(getZ() - want_z) <= 2){
                want_x = -1;
                want_z = -1;
                animation_current = getMovement("idle");
            }
        }
    }
}
Exemplo n.º 21
0
bool Comb::calc(Point startPoint, Point endPoint, CombPaths& combPaths)
{
    if (shorterThen(endPoint - startPoint, max_comb_distance_ignored))
    {
        return true;
    }
    
    
    bool startInside = true;
    bool endInside = true;
    
    //Move start and end point inside the comb boundary
    unsigned int start_inside_poly = boundary_inside.findInside(startPoint, true);
    if (start_inside_poly == NO_INDEX)
    {
        start_inside_poly = moveInside(boundary_inside, startPoint, offset_extra_start_end, max_moveInside_distance2);
        if (start_inside_poly == NO_INDEX)    //If we fail to move the point inside the comb boundary we need to retract.
        {   
            startInside = false;
        }
    }
    unsigned int end_inside_poly = boundary_inside.findInside(endPoint, true);
    if (end_inside_poly == NO_INDEX)
    {
        end_inside_poly = moveInside(boundary_inside, endPoint, offset_extra_start_end, max_moveInside_distance2);
        if (end_inside_poly == NO_INDEX)    //If we fail to move the point inside the comb boundary we need to retract.
        {
            endInside = false;
        }
    }
    

    
    unsigned int start_part_boundary_poly_idx;
    unsigned int end_part_boundary_poly_idx;
    unsigned int start_part_idx = partsView_inside.getPartContaining(start_inside_poly, &start_part_boundary_poly_idx);
    unsigned int end_part_idx = partsView_inside.getPartContaining(end_inside_poly, &end_part_boundary_poly_idx);
    
    if (startInside && endInside && start_part_idx == end_part_idx)
    { // normal combing within part
        PolygonsPart part = partsView_inside.assemblePart(start_part_idx);
        combPaths.emplace_back();
        LinePolygonsCrossings::comb(part, startPoint, endPoint, combPaths.back(), -offset_dist_to_get_from_on_the_polygon_to_outside);
        return true;
    }
    else 
    { // comb inside part to edge (if needed) >> move through air avoiding other parts >> comb inside end part upto the endpoint (if needed) 
        Point middle_from;
        Point middle_to;
        
        if (startInside && endInside)
        {
            ClosestPolygonPoint middle_from_cp = findClosest(endPoint, boundary_inside[start_part_boundary_poly_idx]);
            ClosestPolygonPoint middle_to_cp = findClosest(middle_from_cp.location, boundary_inside[end_part_boundary_poly_idx]);
//             walkToNearestSmallestConnection(middle_from_cp, middle_to_cp); // TODO: perform this optimization?
            middle_from = middle_from_cp.location;
            middle_to = middle_to_cp.location;
        }
        else 
        {
            if (!startInside && !endInside) 
            { 
                middle_from = startPoint; 
                middle_to = endPoint; 
            }
            else if (!startInside && endInside)
            {
                middle_from = startPoint;
                ClosestPolygonPoint middle_to_cp = findClosest(middle_from, boundary_inside[end_part_boundary_poly_idx]);
                middle_to = middle_to_cp.location;
            }
            else if (startInside && !endInside)
            {
                middle_to = endPoint;
                ClosestPolygonPoint middle_from_cp = findClosest(middle_to, boundary_inside[start_part_boundary_poly_idx]);
                middle_from = middle_from_cp.location;
            }
        }
        
        if (startInside)
        {
            // start to boundary
            PolygonsPart part_begin = partsView_inside.assemblePart(start_part_idx); // comb through the starting part only
            combPaths.emplace_back();
            LinePolygonsCrossings::comb(part_begin, startPoint, middle_from, combPaths.back(), -offset_dist_to_get_from_on_the_polygon_to_outside);
        }
        
        // throught air from boundary to boundary
        if (avoid_other_parts)
        {
            Polygons& middle = *getBoundaryOutside(); // comb through all air, since generally the outside consists of a single part
            Point from_outside = middle_from;
            if (startInside || middle.inside(from_outside, true))
            { // move outside
                moveInside(middle, from_outside, -offset_extra_start_end, max_moveOutside_distance2);
            }
            Point to_outside = middle_to;
            if (endInside || middle.inside(to_outside, true))
            { // move outside
                moveInside(middle, to_outside, -offset_extra_start_end, max_moveOutside_distance2);
            }
            combPaths.emplace_back();
            combPaths.back().throughAir = true;
            if ( vSize(middle_from - middle_to) < vSize(middle_from - from_outside) + vSize(middle_to - to_outside) )
            { // via outside is a detour
                combPaths.back().push_back(middle_from);
                combPaths.back().push_back(middle_to);
            }
            else
            {
                LinePolygonsCrossings::comb(middle, from_outside, to_outside, combPaths.back(), offset_dist_to_get_from_on_the_polygon_to_outside);
            }
        }
        else 
        { // directly through air (not avoiding other parts)
            combPaths.emplace_back();
            combPaths.back().throughAir = true;
            combPaths.back().cross_boundary = true; // TODO: calculate whether we cross a boundary!
            combPaths.back().push_back(middle_from);
            combPaths.back().push_back(middle_to);
        }
        
        if (endInside)
        {
            // boundary to end
            PolygonsPart part_end = partsView_inside.assemblePart(end_part_idx); // comb through end part only
            combPaths.emplace_back();
            LinePolygonsCrossings::comb(part_end, middle_to, endPoint, combPaths.back(), -offset_dist_to_get_from_on_the_polygon_to_outside);
        }
        
        return true;
    }
}