TileSphere* TileSphere::_getPreciserSphere(TileSphere* referenceSphere, float closestDistance) 
{
    ML_TRACE_IN("TileSphere* TileSphere::_getPreciserSphere(TileSphere* referenceSphere, float closestDistance) ");

    bool unInit   = true;
    bool firstRun = false;

    if (closestDistance == -1){
        firstRun = true;
    }

    TileSphere *closestTileSphere = NULL, *tmpSphere = NULL;
    float tmpDistance=0;

    unsigned int counter=0;

    // Traverse each sub sphere.

    for (counter = 0; counter < _cubicPartition; counter++) {

        // Only examine further if the sphere contains more details.        
        if ((_tileSpheres[counter]._getRadius() != -1) &&
            !_minimalDistance->getHashTable()->existPair(&_tileSpheres[counter], referenceSphere))
        {
            if (unInit) {
                // Initialize variables once if they are yet uninitialized.
                tmpDistance = _distance(&_tileSpheres[counter], referenceSphere);
                if (firstRun) {
                    unInit = false;
                    closestTileSphere = &_tileSpheres[counter];
                    closestDistance = tmpDistance;
                } else {                
                    if ((tmpDistance * (1 + _error)) < closestDistance) {
                        unInit = false;
                        closestTileSphere = &_tileSpheres[counter];
                        closestDistance = tmpDistance;
                    }
                }
            } else {
                tmpSphere = &_tileSpheres[counter];
                tmpDistance = _distance(tmpSphere, referenceSphere);
                if (firstRun) {
                    if (tmpDistance < closestDistance) {
                        closestDistance = tmpDistance;
                        closestTileSphere = tmpSphere;
                    }
                } else {
                    if ((tmpDistance * (1 + _error)) < closestDistance) {
                        closestDistance = tmpDistance;
                        closestTileSphere = tmpSphere;
                    }
                }
            }
        }
    }

    return closestTileSphere;
}
void
GeometryFeatureExtractor::computeFeatures(const ContinuationSegment& continuation, std::vector<double>& features) {

	const util::point<double>& sourceCenter = continuation.getSourceSlice()->getComponent()->getCenter();
	const util::point<double>& targetCenter = continuation.getTargetSlice()->getComponent()->getCenter();

	unsigned int sourceSize = continuation.getSourceSlice()->getComponent()->getSize();
	unsigned int targetSize = continuation.getTargetSlice()->getComponent()->getSize();

	util::point<double> difference = sourceCenter - targetCenter;

	double distance = difference.x*difference.x + difference.y*difference.y;

	double setDifference = _setDifference(*continuation.getSourceSlice(), *continuation.getTargetSlice(), false, false);

	double setDifferenceRatio = setDifference/(sourceSize + targetSize);

	double alignedSetDifference = _setDifference(*continuation.getSourceSlice(), *continuation.getTargetSlice(), false, true);

	double alignedSetDifferenceRatio = setDifference/(sourceSize + targetSize);

	double overlap = _overlap(*continuation.getSourceSlice(), *continuation.getTargetSlice());

	double overlapRatio = overlap/(sourceSize + targetSize - overlap);

	double alignedOverlap = _alignedOverlap(*continuation.getSourceSlice(), *continuation.getTargetSlice());

	double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize - overlap);

	features[0] = distance;
	features[1] = setDifference;
	features[2] = setDifferenceRatio;
	features[3] = alignedSetDifference;
	features[4] = alignedSetDifferenceRatio;
	features[5] =
			(continuation.getSourceSlice()->getComponent()->getSize() +
			 continuation.getTargetSlice()->getComponent()->getSize())*0.5;
	features[6] = overlap;
	features[7] = overlapRatio;
	features[8] = alignedOverlap;
	features[9] = alignedOverlapRatio;

	if (!_noSliceDistance) {

		double averageSliceDistance, maxSliceDistance;

		_distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, false, averageSliceDistance, maxSliceDistance);

		double alignedAverageSliceDistance, alignedMaxSliceDistance;

		_distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance);

		features[10] = averageSliceDistance;
		features[11] = maxSliceDistance;
		features[12] = alignedAverageSliceDistance;
		features[13] = alignedMaxSliceDistance;
	}
}
float TileSphere::_distance(TileSphere* tileSphere1, TileSphere* tileSphere2) 
{   
    ML_TRACE_IN("float TileSphere::_distance(TileSphere* tileSphere1, TileSphere* tileSphere2)");

    float radiusSum = tileSphere1->_getRadius() + tileSphere2->_getRadius();

    float result = _distance(tileSphere1->_getPosition(), tileSphere2->_getPosition()) - radiusSum;

    return (result>=0)?result:0; 
}
Exemple #4
0
void util::Clustering::Cluster::updateScore() {
	score = 0.0;
	for (auto it = data.begin(); it != data.end(); ++it) {
		score += _distance(*it, position);
	}
// 	if (data.size()) {
// 		score /= data.size();
// 	} else {
// 		score = 1e20;
// 	}
}
int main(){
    UL l,c,r1,r2,dist,maxx;
    while(scanf("%lu %lu %lu %lu",&l,&c,&r1,&r2) && (l!=0 || c!=0 || r1!= 0 || r2 != 0)){
        //printf("%lu %lu %lu %lu\n",l,c,r1,r2);
        if((r2*2 <=l && r2*2 <=c) && (r1*2 <=l && r1*2 <=c)&& (_distance(r1,r1,l-r2,c-r2)>= (r1+r2)*(r1+r2) || _distance(r1,r1,c-r2,l-r2)>= (r1+r2)*(r1+r2))){
            puts("S");
        }else{
            puts("N");
        }
    }
    return 0;
}
int16_t xyForGamutID(point_t *xy, int16_t gamutID, point_t *xy_r)
{
   point_t triangle[3];
  
   _triangleForGamutID(gamutID, triangle);

   if(_isPointInTriangle(xy, triangle)) {
      memcpy(xy_r,xy,sizeof(point_t));
      return 0;
   }
   
   point_t pAB, pAC, pBC;
   _closestPointOnLine(&triangle[RED],   &triangle[GREEN], xy, &pAB);
   _closestPointOnLine(&triangle[BLUE],  &triangle[RED],   xy, &pAC);
   _closestPointOnLine(&triangle[GREEN], &triangle[BLUE],  xy, &pBC);

   float dAB = _distance(xy, &pAB);
   float dAC = _distance(xy, &pAC);
   float dBC = _distance(xy, &pBC);
   
   float lowest = dAB;
   point_t *closestPoint = &pAB;
   
   if(dAC < lowest)
   {
      lowest = dAC;
      closestPoint = &pAC;
   }
   if(dBC < lowest)
   {
//      lowest = dBC;
      closestPoint = &pBC;
   }
  
   xy_r->x = closestPoint->x;
   xy_r->y = closestPoint->y;
   
   return 0;
}
Exemple #7
0
double Track::GetXTE( double fm1Lat, double fm1Lon, double fm2Lat, double fm2Lon, double toLat, double toLon  )
{
    vector2D v, w, p;

    // First we get the cartesian coordinates to the line endpoints, using
    // the current position as origo.

    double brg1, dist1, brg2, dist2;
    DistanceBearingMercator( toLat, toLon, fm1Lat, fm1Lon, &brg1, &dist1 );
    w.x = dist1 * sin( brg1 * PI / 180. );
    w.y = dist1 * cos( brg1 * PI / 180. );

    DistanceBearingMercator( toLat, toLon, fm2Lat, fm2Lon, &brg2, &dist2 );
    v.x = dist2 * sin( brg2 * PI / 180. );
    v.y = dist2 * cos( brg2 * PI / 180. );

    p.x = 0.0; p.y = 0.0;

    const double lengthSquared = _distance2( v, w );
    if ( lengthSquared == 0.0 ) {
        // v == w case
        return _distance( p, v );
    }

    // Consider the line extending the segment, parameterized as v + t (w - v).
    // We find projection of origo onto the line.
    // It falls where t = [(p-v) . (w-v)] / |w-v|^2

    vector2D a = p - v;
    vector2D b = w - v;

    double t = vDotProduct( &a, &b ) / lengthSquared;

    if (t < 0.0) return _distance(p, v);       // Beyond the 'v' end of the segment
    else if (t > 1.0) return _distance(p, w);  // Beyond the 'w' end of the segment
    vector2D projection = v + t * (w - v);     // Projection falls on the segment
    return _distance(p, projection);
}
int main(){
    int n;
    Point gopher,dog,p;
    double gDist,dDist;
    bool escape;
    while(scanf("%d %lf %lf %lf %lf",&n,&gopher.x,&gopher.y,&dog.x,&dog.y) == 5){
        escape = false;
        for(int i = 0;i<n;++i){
            scanf("%lf %lf",&p.x,&p.y);
            if(!escape){
                gDist = _distance(p,gopher);
                dDist = _distance(p,dog);
                if((gDist*2)<=dDist){
                    escape = true;
                    printf("The gopher can escape through the hole at (%.3lf,%.3lf).\n",p.x,p.y);
                }
            }
        }
        if(!escape){
            puts("The gopher cannot escape.");
        }
    }
    return 0;
}
float TileSphere::computeDistance(TileSphere* tileSphere, float*& point1, float*& point2) 
{
    ML_TRACE_IN("float TileSphere::computeDistance(TileSphere* tileSphere, float*& point1, float*& point2)");

    float distance = -1;
    // Determine current distance
    if ((point1 != NULL) && (point2 != NULL)){
        distance = _distance(point1, point2);
    }

    if (tileSphere != NULL) {

        // Register this call in the hash table
        _minimalDistance->getHashTable()->addPair(this, tileSphere);

        // Distance can not be less..
        if (fabs(distance) < FLT_EPSILON){
            return 0;
        }

        // Descend recursively in both sets until leafs are reached.
        // On the way, split the sphere with the largest radius.

        if ((_radius > tileSphere->_getRadius()) && _hasSubSpheresFlag) {
            distance = tileSphere->computeDistance(this->_getPreciserSphere(tileSphere, distance), point2, point1);
        } else {
            if ((_radius < tileSphere->_getRadius()) && tileSphere->_hasSubSpheres()) {
                distance = this->computeDistance(tileSphere->_getPreciserSphere(this, distance), point1, point2);
            } else {
                // This branch is active if the one sphere was smaller,
                // but the other did not contain any sub spheres.
                if (_hasSubSpheresFlag) {
                    distance = tileSphere->computeDistance(this->_getPreciserSphere(tileSphere, distance), point2, point1);
                }
                if (tileSphere->_hasSubSpheres()) {
                    distance = this->computeDistance(tileSphere->_getPreciserSphere(this, distance), point1, point2);
                }
            }
        }

        if (!_hasSubSpheresFlag && !tileSphere->_hasSubSpheres()) {
            // Compute direct distance between two sets of points.

            float** otherSubset = NULL;
            unsigned int otherSize = 0;            
            float tmpDistance   = 0;
            float tmpDistance2  = 0;
            float *tmpPoint1    = NULL;
            float *tmpPoint2    = NULL;

            int otherSizeParameter=0;
            tileSphere->_getSubset(otherSubset, otherSizeParameter);
            otherSize = static_cast<unsigned int>(otherSizeParameter);

            if (distance == -1) {
                distance = _distance(_subset[0], otherSubset[0]);
                point1   = _subset[0];
                point2   = otherSubset[0];
            }

            tmpDistance2 = _fastDistance(_subset[0], otherSubset[0]);
            tmpPoint1    = _subset[0];
            tmpPoint2    = otherSubset[0];

            unsigned int counter=0, otherCounter=0;

            // Test all points pairwise
            for (otherCounter = 0; otherCounter < otherSize; otherCounter++) {
                for (counter = 0; counter < _numEntries; counter++) {
                    tmpDistance = _fastDistance(_subset[counter], otherSubset[otherCounter]);
                    if (tmpDistance2 > tmpDistance) {
                        tmpDistance2 = tmpDistance;
                        tmpPoint1 = _subset[counter];
                        tmpPoint2 = otherSubset[otherCounter];
                    }
                }
            }

            tmpDistance2 = sqrtf(tmpDistance2);
            if (distance > tmpDistance2) {
                distance = tmpDistance2;
                point1 = tmpPoint1;
                point2 = tmpPoint2;
            }
        }
        if (_hasSubSpheresFlag) {
            // Compare the distance with all distances to other spheres
            // and test if there are other spheres within the same range.
            TileSphere* tmp = this->_getPreciserSphere(tileSphere, distance);
            while (tmp != NULL) {
                distance = tileSphere->computeDistance(tmp, point1, point2);
                tmp = this->_getPreciserSphere(tileSphere, distance);
            }
        }
        if (tileSphere->_hasSubSpheres()) {
            // Compare the distance with all distances to each other spheres
            // and test if there are other spheres within the same range.
            TileSphere* tmp = tileSphere->_getPreciserSphere(this, distance);
            while (tmp != NULL) {
                distance = this->computeDistance(tmp, point1, point2);
                tmp = tileSphere->_getPreciserSphere(this, distance);
            }
        }
    }

    return distance;
}
void TileSphere::getDeFactoSize() 
{
    ML_TRACE_IN("void TileSphere::getDeFactoSize()");

    // Computes the central point of the BB and acquire the farthest 
    // sub sphere/point of the sub spheres/pointset for the radius
    float minX=0, maxX=0, minY=0, maxY=0, minZ=0, maxZ=0;
    bool  unInit = true;

    unsigned int counter=0;

    if (_hasSubSpheresFlag) {
        // Computes the BB of the contained spheres
        float buffer=0;
        for (counter = 0; counter < _cubicPartition; counter++) {
            _tileSpheres[counter].getDeFactoSize();
            // not every sphere has
            if (_tileSpheres[counter]._radius != -1) {
                if (unInit) {
                    minX = _tileSpheres[counter]._position[0] - _tileSpheres[counter]._radius;
                    maxX = _tileSpheres[counter]._position[0] + _tileSpheres[counter]._radius;
                    minY = _tileSpheres[counter]._position[1] - _tileSpheres[counter]._radius;
                    maxY = _tileSpheres[counter]._position[1] + _tileSpheres[counter]._radius;
                    minZ = _tileSpheres[counter]._position[2] - _tileSpheres[counter]._radius;
                    maxZ = _tileSpheres[counter]._position[2] + _tileSpheres[counter]._radius;
                    unInit = false;
                } else {
                    buffer = _tileSpheres[counter]._position[0] - _tileSpheres[counter]._radius;
                    if (minX > buffer) { minX = buffer; }
                    buffer = _tileSpheres[counter]._position[0] + _tileSpheres[counter]._radius;
                    if (maxX < buffer) { maxX = buffer; }
                    buffer = _tileSpheres[counter]._position[1] - _tileSpheres[counter]._radius;
                    if (minY > buffer) { minY = buffer; }
                    buffer = _tileSpheres[counter]._position[1] + _tileSpheres[counter]._radius;
                    if (maxY < buffer) { maxY = buffer; }
                    buffer = _tileSpheres[counter]._position[2] - _tileSpheres[counter]._radius;
                    if (minZ > buffer) { minZ = buffer; }
                    buffer = _tileSpheres[counter]._position[2] + _tileSpheres[counter]._radius;
                    if (maxZ < buffer) { maxZ = buffer; }
                }
            }
        }
    } else {
        if (_numEntries != 0) {
            unInit = false;
            float* pointPos = _subset[0];
            minX = maxX = * pointPos;
            minY = maxY = *(pointPos + 1);
            minZ = maxZ = *(pointPos + 2);

            for (counter = 1; counter < _numEntries; counter++) {
                pointPos = _subset[counter];
                if (minX > *pointPos) { minX = *pointPos; }
                if (maxX < *pointPos) { maxX = *pointPos; }
                pointPos++;
                if (minY > *pointPos) { minY = *pointPos; }
                if (maxY < *pointPos) { maxY = *pointPos; }
                pointPos++;
                if (minZ > *pointPos) { minZ = *pointPos; }
                if (maxZ < *pointPos) { maxZ = *pointPos; }
            }
        }
    }
    if (!unInit) {
        _position[0] = (maxX + minX) * 0.5f;
        _position[1] = (maxY + minY) * 0.5f;
        _position[2] = (maxZ + minZ) * 0.5f;
        if (_hasSubSpheresFlag) {
            bool init = true;
            float tmpDist=0;
            for (counter = 0; counter < _cubicPartition; counter++) {
                if (_tileSpheres[counter]._getRadius() != -1) {
                    if (init) {                        
                        _radius = _distance(_position, _tileSpheres[counter]._getPosition()) + _tileSpheres[counter]._getRadius();
                        init = false;
                    } else {
                        tmpDist = _distance(_position, _tileSpheres[counter]._getPosition()) + _tileSpheres[counter]._getRadius();
                        if (tmpDist > _radius){
                            _radius = tmpDist;
                        }
                    }
                }
            }
        } else {
            float tmpDist;
            _radius = _distance(_position, _subset[0]);
            for (counter = 1; counter < _numEntries; counter++) {
                tmpDist = _distance(_position, _subset[counter]);
                if (tmpDist > _radius){
                    _radius = tmpDist;
                }
            }
        }
    } else {
        _radius = -1;
    }
}
void
GeometryFeatureExtractor::computeFeatures(const BranchSegment& branch, std::vector<double>& features) {

	const util::point<double>& sourceCenter  = branch.getSourceSlice()->getComponent()->getCenter();
	const util::point<double>& targetCenter1 = branch.getTargetSlice1()->getComponent()->getCenter();
	const util::point<double>& targetCenter2 = branch.getTargetSlice2()->getComponent()->getCenter();

	unsigned int sourceSize  = branch.getSourceSlice()->getComponent()->getSize();
	unsigned int targetSize1 = branch.getTargetSlice1()->getComponent()->getSize();
	unsigned int targetSize2 = branch.getTargetSlice2()->getComponent()->getSize();

	util::point<double> difference = sourceCenter - (targetCenter1*targetSize1 + targetCenter2*targetSize2)/((double)(targetSize1 + targetSize2));

	double distance = difference.x*difference.x + difference.y*difference.y;

	double setDifference = _setDifference(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), false, false);

	double setDifferenceRatio = setDifference/(sourceSize + targetSize1 + targetSize2);

	double alignedSetDifference = _setDifference(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), false, true);

	double alignedSetDifferenceRatio = alignedSetDifference/(sourceSize + targetSize1 + targetSize2);

	double overlap = _overlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice());

	double overlapRatio = overlap/(sourceSize + targetSize1 + targetSize2 - overlap);

	double alignedOverlap = _alignedOverlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice());

	double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize1 + targetSize2 - alignedOverlap);

	features[0] = distance;
	features[1] = setDifference;
	features[2] = setDifferenceRatio;
	features[3] = alignedSetDifference;
	features[4] = alignedSetDifferenceRatio;
	features[5] =
			(branch.getSourceSlice()->getComponent()->getSize() +
			 branch.getTargetSlice1()->getComponent()->getSize() +
			 branch.getTargetSlice2()->getComponent()->getSize())/3.0;
	features[6] = overlap;
	features[7] = overlapRatio;
	features[8] = alignedOverlap;
	features[9] = alignedOverlapRatio;

	if (!_noSliceDistance) {

		double averageSliceDistance, maxSliceDistance;

		_distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, false, averageSliceDistance, maxSliceDistance);

		double alignedAverageSliceDistance, alignedMaxSliceDistance;

		_distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance);

		features[10] = averageSliceDistance;
		features[11] = maxSliceDistance;
		features[12] = alignedAverageSliceDistance;
		features[13] = alignedMaxSliceDistance;
	}
}
Exemple #12
0
util::Clustering::ClusterResult util::Clustering::_kmeans(unsigned k) {
	if (k == 0) {
		return ClusterResult();
	}
	
	const double threshold = 0.001;
	const unsigned maxIterations = 5000;
	srand((int)(*m_data.begin()));
	
	double delta = 0.0;
	unsigned iteration = 0;
	
	typedef std::vector< short > Membership;
	Membership membership(m_data.size(), -1);
	
	typedef std::vector< float > Distances;
	Distances distances(k, 0.0);
	
	ClusterVector clusters;
	clusters.resize(k);
	for (unsigned i = 0; i < k; i++) {
		clusters[i].position = m_data[rand() % m_data.size()];
	}
	
	// clustering main loop
	do {
		delta = 0.0;
		for (unsigned i = 0; i < k; i++) {
			clusters[i].data.clear();
		}
		
		for (unsigned i = 0; i < m_data.size(); i++) {
			float value = m_data[i];
			
			// compute which cluster lies at minimum distance to data point
			float dist = 0.0, minDist = 1e20;
			unsigned minIdx = 0;
			for (unsigned j = 0; j < k; j++) {
				if ((dist = _distance(value, clusters[j].position)) < minDist) {
					minDist = dist;
					minIdx = j;
				};
			}
			clusters[minIdx].data.push_back(value);
			
			// check if membership changed
			if (membership[i] != minIdx) {
				delta += 1.0;
				membership[i] = minIdx;
			}
		}
		
		for (unsigned i = 0; i < k; i++) {
			clusters[i].updatePosition();
		}
		
		delta /= m_data.size();
		iteration++;
	} while (delta > threshold && iteration < maxIterations);
	
	// compute score for the clustering
	for (unsigned i = 0; i < k; i++) {
		clusters[i].updateScore();
	}
	
	ClusterResult result;
	for (auto it = clusters.begin(); it != clusters.end(); ++it) {
		result.add(*it);
	}
	return result;
}
size_t LZHLCompressor::compress( uint8_t* dst, const uint8_t* src, size_t sz ) {
  LZHLEncoder coder( &stat, dst );
  // (unused) const uint8_t* srcBegin = src;
  const uint8_t* srcEnd = src + sz;

  LZHASH hash = 0;

  if ( sz >= LZMATCH ) {
    const uint8_t* pEnd = src + LZMATCH;

    for ( const uint8_t* p=src; p < pEnd ; ) {
      UPDATE_HASH( hash, *p++ );
    }
  }

  for (;;) {
    ptrdiff_t srcLeft = srcEnd - src;
    if ( srcLeft < LZMATCH ) {
      if ( srcLeft ) {
        _toBuf( src, srcLeft );
        coder.putRaw( src, srcLeft );
      }

      break;  //forever
    }

    ptrdiff_t nRaw = 0;
    ptrdiff_t maxRaw = std::min( srcLeft - LZMATCH, (ptrdiff_t)LZHLEncoder::maxRaw );

#ifdef LZLAZYMATCH
    int    lazyMatchLen = 0;
    int    lazyMatchHashPos = 0;
    LZPOS  lazyMatchBufPos = 0;
    ptrdiff_t    lazyMatchNRaw = 0;
    LZHASH lazyMatchHash = 0;
    bool   lazyForceMatch = false;
#endif
    for (;;) {
      LZHASH hash2 = HASH_POS( hash );

      LZPOS hashPos = table[ hash2 ];
      LZPOS wrapBufPos = _wrap( bufPos );
      table[ hash2 ] = (LZTableItem)wrapBufPos;

      int matchLen = 0;
      if ( hashPos != (LZTABLEINT)(-1) && hashPos != wrapBufPos )
      {
        int matchLimit = std::min( std::min( _distance( wrapBufPos - hashPos ), (int)(srcLeft - nRaw) ), LZMIN + LZHLEncoder::maxMatchOver );
        matchLen = _nMatch( hashPos, src + nRaw, matchLimit );

#ifdef LZOVERLAP
        if ( _wrap( hashPos + matchLen ) == wrapBufPos )
        {
          assert( matchLen != 0 );
          ptrdiff_t xtraMatchLimit = std::min( LZMIN + (ptrdiff_t)LZHLEncoder::maxMatchOver - matchLen, srcLeft - nRaw - matchLen );
          int xtraMatch;
          for ( xtraMatch = 0; xtraMatch < xtraMatchLimit ; ++xtraMatch )
          {
            if ( src[ nRaw + xtraMatch ] != src[ nRaw + xtraMatch + matchLen ] )
              break;//for ( xtraMatch )
          }

          matchLen += xtraMatch;
        }
#endif

#ifdef LZBACKWARDMATCH
        if ( matchLen >= LZMIN - 1 )//to ensure that buf will be overwritten
        {
          int xtraMatchLimit = (int)std::min( LZMIN + LZHLEncoder::maxMatchOver - (ptrdiff_t)matchLen, nRaw );
          int d = (int)_distance( bufPos - hashPos );
          xtraMatchLimit = std::min( std::min( xtraMatchLimit, d - matchLen ), LZBUFSIZE - d );
          int xtraMatch;
          for ( xtraMatch = 0; xtraMatch < xtraMatchLimit ; ++xtraMatch )
          {
            if ( buf[ _wrap( hashPos - xtraMatch - 1 ) ] != src[ nRaw - xtraMatch - 1 ] )
              break;//for ( xtraMatch )
          }

          if ( xtraMatch > 0 ) {
            assert( matchLen + xtraMatch >= LZMIN );
            assert( matchLen + xtraMatch <= _distance( bufPos - hashPos ) );

            nRaw -= xtraMatch;
            bufPos -= xtraMatch;
            hashPos -= xtraMatch;
            matchLen += xtraMatch;
            wrapBufPos = _wrap( bufPos );
            hash = _calcHash( src + nRaw );

#ifdef LZLAZYMATCH
            lazyForceMatch = true;
#endif
          }
        }
#endif
      }

#ifdef LZLAZYMATCH
      if ( lazyMatchLen >= LZMIN ) {
        if ( matchLen > lazyMatchLen ) {
          coder.putMatch( src, nRaw, matchLen - LZMIN, _distance( wrapBufPos - hashPos ) );
          hash = _updateTable( hash, src + nRaw, bufPos + 1, std::min( (ptrdiff_t)matchLen - 1, srcEnd - (src + nRaw + 1) - LZMATCH ) );
          _toBuf( src + nRaw, matchLen );
          src += nRaw + matchLen;
          break;//for ( nRaw )

        } else {
          nRaw = lazyMatchNRaw;
          bufPos = lazyMatchBufPos;

          hash = lazyMatchHash;
          UPDATE_HASH_EX( hash, src + nRaw );
          coder.putMatch( src, nRaw, lazyMatchLen - LZMIN, _distance( bufPos - lazyMatchHashPos ) );
          hash = _updateTable( hash, src + nRaw + 1, bufPos + 2, std::min( (ptrdiff_t)lazyMatchLen - 2, srcEnd - (src + nRaw + 2) - LZMATCH ) );
          _toBuf( src + nRaw, lazyMatchLen );
          src += nRaw + lazyMatchLen;

          break;//for ( nRaw )
        }
      }
#endif

      if ( matchLen >= LZMIN ) {

#ifdef LZLAZYMATCH
        if ( !lazyForceMatch ) {
          lazyMatchLen = matchLen;
          lazyMatchHashPos = hashPos;
          lazyMatchNRaw = nRaw;
          lazyMatchBufPos = bufPos;
          lazyMatchHash = hash;
        } else
#endif
        {
          coder.putMatch( src, nRaw, matchLen - LZMIN, _distance( wrapBufPos - hashPos ) );
          hash = _updateTable( hash, src + nRaw, bufPos + 1, std::min( (ptrdiff_t)matchLen - 1, srcEnd - (src + nRaw + 1) - LZMATCH ) );
          _toBuf( src + nRaw, matchLen );
          src += nRaw + matchLen;

          break;//for ( nRaw )
        }
      }

#ifdef LZLAZYMATCH
      assert( !lazyForceMatch );
#endif

      if ( nRaw + 1 > maxRaw )
      {
#ifdef LZLAZYMATCH
        if ( lazyMatchLen >= LZMIN )
        {
          coder.putMatch( src, nRaw, lazyMatchLen - LZMIN, _distance( bufPos - lazyMatchHashPos ) );
          hash = _updateTable( hash, src + nRaw, bufPos + 1, std::min( (ptrdiff_t)lazyMatchLen - 1, srcEnd - (src + nRaw + 1) - LZMATCH ) );
          _toBuf( src + nRaw, lazyMatchLen );
          src += nRaw + lazyMatchLen;
          break;//for ( nRaw )
        }
#endif

        if ( nRaw + LZMATCH >= srcLeft && srcLeft <= LZHLEncoder::maxRaw )
        {
          _toBuf( src + nRaw, srcLeft - nRaw );
          nRaw = srcLeft;
        }

        coder.putRaw( src, nRaw );
        src += nRaw;
        break;//for ( nRaw )
      }

      UPDATE_HASH_EX( hash, src + nRaw );
      _toBuf( src[ nRaw++ ] );
    }//for ( nRaw )
  }//forever

  return coder.flush();
}
Exemple #14
0
double _distance(HDesign& hd, HPin p1, double x2, double y2)
{
  return _distance(hd.GetDouble<HPin::X>(p1), hd.GetDouble<HPin::Y>(p1), x2, y2);
}
Exemple #15
0
double _distance(HDesign& hd, HPin p1, HPin p2)
{
  return _distance(hd.GetDouble<HPin::X>(p1), hd.GetDouble<HPin::Y>(p1), hd.GetDouble<HPin::X>(p2), hd.GetDouble<HPin::Y>(p2));
}
Exemple #16
0
void Cluster::Kmeans(int q, int iterations) {
  vector<int> id_list;  
  vector<int> seeds;
  time_t start, end;
  //container of centroids (large docs), centroid is a doc - unordered_string_map
  //centroid id => "doc"

  //cluster collection: map of cluster id => set of vector ids
  //typedef boost::unordered_map<int, boost::unordered_set<int> > cluster_set_map;
  //cluster_set_map cluster_map;

  int K = (int) sqrt(this->N); 
  seeds =  _selectRandomSeeds( K );

  //set initial centroid seeds
  for (int k = 0; k < K; k++) {
    centroid_map.insert( unordered_int_string_map::value_type( k, doc_term_index[ seeds[k] ] ));
  }


  int I = iterations;
  int j = 0;
  //foreach cluster (set to new cluster map each iteration) (declared in header)
  //stopping condition.
  cout << "Starting iterations" <<endl;
  while (j < I) {
    cout << "Iteration: " << j << endl;


    cluster_map.clear();
    for (int k = 0; k < K; k++) {
      //cluster = {}      
      boost::unordered_set<int> cluster_list;  //vector members in cluster
      cluster_map.insert(cluster_set_map::value_type( k, cluster_list ) );
    }

    //foreach item..
    //reassignment of vectors to a cluster
    //for (int n = 0; n < N; n++) {
    int n = 0;
    for (unordered_int_string_map::iterator i_doc_term = doc_term_index.begin(); i_doc_term != doc_term_index.end(); ++i_doc_term) {
	//j = min |uj - xn|
	double min_score = 1000.0;
	double cluster_score;
	int min_cluster;


	for (int z = 0; z < K; z++) {

	  if(min_score > (cluster_score = _distance(centroid_map[z], i_doc_term->second)  )) {

	    min_score = cluster_score;
	    min_cluster = z;
	  }

	  //cout << "score: " << double( _distance(centroid_map[z], doc_term_index[n])) << endl;
	  //cout << "doc: " << n << " Cluster score: " << cluster_score << endl;
	}

	//cout << "doc: " << n << " goes in cluster: " << min_cluster << " score: " << min_score << endl;

	//cluster = cluster U xn
	cluster_map[min_cluster].insert( i_doc_term->first );
	//cout << "inserting cluster: " << min_cluster << "item: " << i_doc_term->first <<endl;
	n++;
    }

    //recompute centroid from members of cluster
    //foreach cluster
    cout << "Recomputing Clusters . . ." <<endl;
    for (int z = 0; z < K; z++) {
      //uk = 1/|clusterk| sum( vectors in cluster k)
      centroid_map[z] = _centroid( cluster_map[z] );
    }


    j++;
  }


  //print centroids    
  /*  
  for (unordered_int_string_map::iterator icentroid = centroid_map.begin(); icentroid != centroid_map.end(); ++icentroid) {
    cout << icentroid->first << " : " << endl;
    for (unordered_string_map::iterator ivec = (icentroid->second).begin(); ivec != (icentroid->second).end(); ++ivec) {
      cout << "\t" << ivec->first << ":" << ivec->second << endl;
    }      
  }
  */
    
  //print cluster memebership
  /*
  for (cluster_set_map::iterator i_set = cluster_map.begin(); i_set != cluster_map.end(); ++i_set) {
    cout << i_set->first << "\t" << endl;
    for (boost::unordered_set<int>::iterator i_list = i_set->second.begin(); i_list != i_set->second.end(); ++i_list) {

      cout << " " << *i_list;
    }
    cout <<endl;
  }
  */

}