Returns the indices of the k coarse centroids which are closer to the given vector.

@param vector
The vector
@param k
The number of nearest centroids to return
@return The indices of the k nearest coarse centroids
500809
protected int[] computeNearestCoarseIndices(double[] vector, int k) {
		BoundedPriorityQueue<Result> bpq = new BoundedPriorityQueue<Result>(new Result(), k);

		double lowest = Double.MAX_VALUE;
		for (int i = 0; i < numCoarseCentroids; i++) {
			boolean skip = false;
			double l2distance = 0;
			for (int j = 0; j < vectorLength; j++) {
				l2distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]);
				if (l2distance > lowest) {
					skip = true;
					break;
				}
			}
			if (!skip) {
				bpq.offer(new Result(i, l2distance));
				if (i >= k) {
					lowest = bpq.last().getDistance();
				}
			}
		}
		int[] nn = new int[k];
		for (int i = 0; i < k; i++) {
			nn[i] = bpq.poll().getId();
		}
		return nn;
	}
797160
public static double vectorLength(double[] vector) {
        double ret = 0;
        if (vector == null)
            return ret;
        else {
            for (int i = 0; i < vector.length; i++) {
                ret += Math.pow(vector[i], 2);
            }

        }
        return ret;
    }
1065778
private Vector3 middleOfCell(int x_index, int y_index) {
        float middleXCell = (float) (indexRegion.minX() + x_index * x_size + x_size / 2);
        float middleYCell = (float) (indexRegion.minY() + y_index * y_size + y_size / 2);
        return new Vector3(middleXCell, middleYCell, 0);
    }
1083960
public void setK(final int K)
    {
        if(K < 2)
            throw new IllegalArgumentException("At least 2 topics must be learned");
        this.K = K;
        gammaLocal = new ThreadLocal<Vec>()
        {
            @Override
            protected Vec initialValue()
            {
                return new DenseVector(K);
            }
        };
        logThetaLocal  = new ThreadLocal<Vec>()
        {
            @Override
            protected Vec initialValue()
            {
                return new DenseVector(K);
            }
        };
        expLogThetaLocal = new ThreadLocal<Vec>()
        {
            @Override
            protected Vec initialValue()
            {
                return new DenseVector(K);
            }
        };
        
        lambda = null;
    }
1128843
private HashSparseVector calculateCentroid (ArrayList<Instance> insts) {
		HashSparseVector centroid = new HashSparseVector();
		
		
		Iterator i = insts.iterator();

		while (i.hasNext()) {
			Instance d = (Instance) i.next();

			centroid.plus((HashSparseVector) d.getData());
		}
		centroid.scaleDivide(insts.size());

		return centroid;
	}
612142
protected static List<CentroidMapping> calculateDistances(double[][] baseCentroids,
            double[][] targetCentroids, int centroidNum)
    {
        // ベース中心点配列とマージ対象中心点配列の各々のユークリッド距離を算出
        List<CentroidMapping> allDistance = new ArrayList<>();

        for (int baseIndex = 0; baseIndex < centroidNum; baseIndex++)
        {
            for (int targetIndex = 0; targetIndex < centroidNum; targetIndex++)
            {
                CentroidMapping centroidMapping = new CentroidMapping();
                centroidMapping.setBaseIndex(baseIndex);
                centroidMapping.setTargetIndex(targetIndex);
                double distance = MathUtils.distance(baseCentroids[baseIndex],
                        targetCentroids[targetIndex]);
                centroidMapping.setEuclideanDistance(distance);
                allDistance.add(centroidMapping);
            }
        }
        return allDistance;
    }
889650
public Vector3D getCorner(int index) {
        Vector3D v = new Vector3D();
        if (index <= 0)
            v.set(x1, y1, z1);
        else
            v.set(x2, y2, z2);
        return v;
    }
1148927
public static KmeansResult nearestCentroid(double[] targetPoint, double[][] centroids)
    {
        int nearestCentroidIndex = 0;
        Double minDistance = Double.MAX_VALUE;
        double[] currentCentroid = null;
        Double currentDistance;
        for (int index = 0; index < centroids.length; index++)
        {
            currentCentroid = centroids[index];
            if (currentCentroid != null)
            {
                currentDistance = MathUtils.distance(targetPoint, currentCentroid);
                if (currentDistance < minDistance)
                {
                    minDistance = currentDistance;
                    nearestCentroidIndex = index;
                }
            }
        }

        currentCentroid = centroids[nearestCentroidIndex];

        KmeansResult result = new KmeansResult();
        result.setDataPoint(targetPoint);
        result.setCentroidIndex(nearestCentroidIndex);
        result.setCentroid(currentCentroid);
        result.setDistance(minDistance);

        return result;
    }
1352614
public static List<double[]> generatekMeansPlusPlusCentroids(int k,
			List<double[]> input, Random random) {
		int n = input.size();
		assert (n > 0);
		int d = input.get(0).length - 1;
		assert (k <= n);

		List<double[]> centerValue = new ArrayList<double[]>(k);
		// Selects and copies the first centroid
		double[] lastCenter = new double[d];
		System.arraycopy(input.get(random.nextInt(n)), 1, lastCenter, 0, d);
		centerValue.add(lastCenter);

		double[] distance = new double[n];
		for (int j = 0; j < n; j++) {
			distance[j] = Double.POSITIVE_INFINITY;
		}
		for (int i = 1; i < k; i++) {
			// Selects the next centroid
			double sum = 0.0;
			Iterator<double[]> jIter = input.iterator();
			for (int j = 0; j < n; j++) {
				double[] point = jIter.next();
				distance[j] = Math
						.min(distance[j],
								point[0]
										* Metric.distanceSquared(lastCenter,
												point, 1));
				sum += distance[j];

			}
			int candidate = 0;
			if (sum > 0) {
				double nextCenterValue = sum * random.nextDouble();
				double currentValue = distance[0];
				while (!(nextCenterValue < currentValue)) {
					currentValue += distance[++candidate];
				}
			}
			// Copies the selected centroid
			lastCenter = new double[d];
			System.arraycopy(input.get(candidate), 1, lastCenter, 0, d);
			centerValue.add(lastCenter);
		}

		return centerValue;
	}
152516
public Set<E> getSubSet(int k) {
        int from = -1;
        //TODO: very bad. Bounds should be memorized
        for (int x = 0; x < values.size(); x++) {
            int cIdx = index.get(values.get(x).id());
            if (cIdx == k && from == -1) {
                from = x;
            }
            if (from >= 0 && cIdx > k) {
                return new ElementSubSet<>(this, k, from, x);
            }
        }
        if (from >= 0) {
            return new ElementSubSet<>(this, k, from, values.size());
        }
        return Collections.emptySet();
    }
1298790
public int distanceSquared(Vector4ic v) {
        return distanceSquared(v.x(), v.y(), v.z(), v.w());
    }
893472
private int reverseIndex(int k) {
    if (reverseIndexMap == null) {
      reverseIndexMap = new int[attributes.getLength()];
      for (int i = 0, len = indexSet.size(); i < len; i++)
        reverseIndexMap[indexSet.get(i)] = i + 1;
    }
    return reverseIndexMap[k] - 1;
  }
652078
private int computeNearestCoarseIndex(double[] vector) {
		int centroidIndex = -1;
		double minDistance = Double.MAX_VALUE;
		for (int i = 0; i < numCoarseCentroids; i++) {
			double distance = 0;
			for (int j = 0; j < vectorLength; j++) {
				distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]);
				if (distance >= minDistance) {
					break;
				}
			}
			if (distance < minDistance) {
				minDistance = distance;
				centroidIndex = i;
			}
		}
		return centroidIndex;
	}
997108
def k_closest(points, k, origin=(0, 0)):
    # Time: O(k+(n-k)logk)
    # Space: O(k)
    
    heap = [(-distance(p, origin), p) for p in points[:k]]
    heapify(heap)

    """
    For every point p in points[k:],
    check if p is smaller than the root of the max heap;
    if it is, add p to heap and remove root. Reheapify.
    """
    for p in points[k:]:
        d = distance(p, origin)

        heappushpop(heap, (-d, p))  # heappushpop does conditional check
        """Same as:
            if d < -heap[0][0]:
                heappush(heap, (-d,p))
                heappop(heap)

        Note: heappushpop is more efficient than separate push and pop calls.
        Each heappushpop call takes O(logk) time.
        """

    return [p for nd, p in heap]
1333047
public Vector4f getRow(int row, Vector4f dest) throws IndexOutOfBoundsException {
        switch (row) {
        case 0:
            dest.x = m00;
            dest.y = m10;
            dest.z = m20;
            dest.w = m30;
            break;
        case 1:
            dest.x = m01;
            dest.y = m11;
            dest.z = m21;
            dest.w = m31;
            break;
        case 2:
            dest.x = m02;
            dest.y = m12;
            dest.z = m22;
            dest.w = m32;
            break;
        case 3:
            dest.x = m03;
            dest.y = m13;
            dest.z = m23;
            dest.w = m33;
            break;
        default:
            throw new IndexOutOfBoundsException();
        }
        return dest;
    }
614637
protected static Clustering kMeans(int k, Cluster[] centers, List<? extends Cluster> data) {
		assert (centers.length == k);
		assert (k > 0);

		int dimensions = centers[0].getCenter().length;

		ArrayList<ArrayList<Cluster>> clustering = new ArrayList<ArrayList<Cluster>>();
		for (int i = 0; i < k; i++) {
			clustering.add(new ArrayList<Cluster>());
		}

		while (true) {
			// Assign points to clusters
			for (Cluster point : data) {
				double minDistance = distance(point.getCenter(), centers[0].getCenter());
				int closestCluster = 0;
				for (int i = 1; i < k; i++) {
					double distance = distance(point.getCenter(), centers[i].getCenter());
					if (distance < minDistance) {
						closestCluster = i;
						minDistance = distance;
					}
				}

				clustering.get(closestCluster).add(point);
			}

			// Calculate new centers and clear clustering lists
			SphereCluster[] newCenters = new SphereCluster[centers.length];
			for (int i = 0; i < k; i++) {
				newCenters[i] = calculateCenter(clustering.get(i), dimensions);
				clustering.get(i).clear();
			}
			
			// Convergence check
			boolean converged = true;
			for (int i = 0; i < k; i++) {
				if (!Arrays.equals(centers[i].getCenter(), newCenters[i].getCenter())) {
					converged = false;
					break;
				}
			}
			
			if (converged) {
				break;
			} else {
				centers = newCenters;
			}
		}

		return new Clustering(centers);
	}
1304888
public final int getIndex( int coordinate[] ) {
		int index = coordinate[0]*strides[0];
		for (int i = 1; i < coordinate.length; i++) {
			index += strides[i]*coordinate[i];
		}

		return index;
	}