Find the k nearest neighbors of x in the observed input data
        @see Databag.nn() for argument description
        @return  distance and indexes of found nearest neighbors.
3267
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2):
        
        assert len(x) == self.dim_x
        k_x = min(k, self.size)
        # Because linear models requires x vector to be extended to [1.0]+x
        # to accomodate a constant, we store them that way.
        return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)
265640
def _find_neighbors(self, inst, avg_dist):
        
        NN = []
        min_indicies = []

        for i in range(self._datalen):
            if inst != i:
                locator = [inst, i]
                if i > inst:
                    locator.reverse()
                d = self._distance_array[locator[0]][locator[1]]
                if d < avg_dist:  # Defining the neighborhood with an average distance radius.
                    min_indicies.append(i)
        for i in range(len(min_indicies)):
            NN.append(min_indicies[i])
        return np.array(NN, dtype=np.int32)
183425
@Override
    public DataBuffer getVectorCoordinates() {
        int idx;
        if (isRowVector()) {
            idx = 1;
        } else if (isColumnVector()) {
            idx = 0;
        } else {
            throw new UnsupportedOperationException();
        }

        // FIXME: int cast
        int[] temp = new int[(int) length()];
        for (int i = 0; i < length(); i++) {
            temp[i] = getUnderlyingIndicesOf(i).getInt(idx);
        }
        return Nd4j.createBuffer(temp);
    }
12424
def _sparse_neighbor_graph(X, k, binary=False, metric='l2'):
  ''''''
  knn = NearestNeighbors(n_neighbors=k, metric=metric).fit(X)
  mode = 'connectivity' if binary else 'distance'
  try:
    adj = knn.kneighbors_graph(None, mode=mode)
  except IndexError:
    # XXX: we must be running an old (<0.16) version of sklearn
    #  We have to hack around an old bug:
    if binary:
      adj = knn.kneighbors_graph(X, k+1, mode=mode)
      adj.setdiag(0)
    else:
      adj = knn.kneighbors_graph(X, k, mode=mode)
  return Graph.from_adj_matrix(adj)
957566
public static KmeansResult classify(KmeansPoint targetPoint, KmeansDataSet dataSet)
    {
        // KMeanクラスタリング結果を算出
        int nearestCentroidIndex = 0;
        Double minDistance = Double.MAX_VALUE;
        double[] currentCentroid = null;
        Double currentDistance;
        for (int index = 0; index < dataSet.getCentroids().length; index++)
        {
            currentCentroid = dataSet.getCentroids()[index];
            if (currentCentroid != null)
            {
                currentDistance = MathUtils.distance(targetPoint.getDataPoint(), currentCentroid);
                if (currentDistance < minDistance)
                {
                    minDistance = currentDistance;
                    nearestCentroidIndex = index;
                }
            }
        }

        currentCentroid = dataSet.getCentroids()[nearestCentroidIndex];

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

        return result;
    }
1305888
protected void linearScanBatchKNN(List<O> objs, List<KNNHeap> heaps) {
    final PrimitiveDistanceFunction<? super O> rawdist = this.rawdist;
    final Relation<? extends O> relation = getRelation();
    final int size = objs.size();
    // Linear scan style KNN.
    for(DBIDIter iter = relation.getDBIDs().iter(); iter.valid(); iter.advance()) {
      O candidate = relation.get(iter);
      for(int index = 0; index < size; index++) {
        final KNNHeap heap = heaps.get(index);
        final double dist = rawdist.distance(objs.get(index), candidate);
        if(dist <= heap.getKNNDistance()) {
          heap.insert(dist, iter);
        }
      }
    }
  }
457893
public IntegerDataStore getPositions() {
    if(positions != null) {
      return positions; // Return cached.
    }
    final ArrayDBIDs order = topologicalSort();
    WritableIntegerDataStore siz = computeSubtreeSizes(order);
    WritableIntegerDataStore pos = DataStoreUtil.makeIntegerStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_DB, -1);
    WritableIntegerDataStore ins = DataStoreUtil.makeIntegerStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, -1);

    int defins = 0; // Next root insertion position.
    DBIDVar v1 = DBIDUtil.newVar();
    // Place elements based on their successor
    for(DBIDArrayIter it = order.iter().seek(order.size() - 1); it.valid(); it.retract()) {
      final int size = siz.intValue(it);
      parent.assignVar(it, v1); // v1 = parent
      final int ipos = ins.intValue(v1); // Position of parent
      if(ipos < 0 || DBIDUtil.equal(it, v1)) {
        // Root: use interval [defins; defins + size]
        ins.putInt(it, defins);
        pos.putInt(it, defins + size - 1);
        defins += size;
        continue;
      }
      // Insertion position of parent = leftmost
      pos.putInt(it, ipos + size - 1);
      ins.putInt(it, ipos);
      ins.increment(v1, size);
    }
    siz.destroy();
    ins.destroy();
    return positions = pos;
  }
1133904
private int[][] computeSortAndUniqueMapping(String[] keyList, int size)
      throws IOException {
    if (!closed) {
      if (size > 0) {
        SortedMap<String, int[]> sortedMap = new TreeMap<>();
        for (int i = 0; i < size; i++) {
          if (sortedMap.containsKey(keyList[i])) {
            int[] previousList = sortedMap.get(keyList[i]);
            int[] newList = new int[previousList.length + 1];
            System.arraycopy(previousList, 0, newList, 0, previousList.length);
            newList[previousList.length] = i;
            sortedMap.put(keyList[i], newList);
          } else {
            sortedMap.put(keyList[i], new int[] { i });
          }
        }
        Collection<int[]> values = sortedMap.values();
        int[][] result = new int[sortedMap.size()][];
        return values.toArray(result);
      } else {
        return null;
      }
    } else {
      throw new IOException("already closed");
    }
  }
271297
@Override
    public int predict(double[] x) {
        double minDist = Double.MAX_VALUE;
        int bestCluster = 0;

        for (int i = 0; i < k; i++) {
            double dist = Math.squaredDistance(x, centroids[i]);
            if (dist < minDist) {
                minDist = dist;
                bestCluster = i;
            }
        }

        return bestCluster;
    }
921060
private KNNHeap linearScan(Relation<? extends O> relation, DBIDIter iter, final O obj, KNNHeap heap) {
    final PrimitiveDistanceFunction<? super O> rawdist = this.rawdist;
    double max = Double.POSITIVE_INFINITY;
    while(iter.valid()) {
      final double dist = rawdist.distance(obj, relation.get(iter));
      if(dist <= max) {
        max = heap.insert(dist, iter);
      }
      iter.advance();
    }
    return heap;
  }
539765
public List<Map.Entry<K, Float>> nearest(Vector vector)
    {
        return nearest(vector, 10);
    }
261613
def nearest_keys(self, key):
        """"""
        if not isinstance(key, tuple):
            _key = (key,)
        if self.__stale:
            self.generate_tree()
        d, idx = self.__tree.query(
            _key, self.k_neighbors, distance_upper_bound=self.distance_upper_bound)

        try:
            return [self.__keys[id][0] for id in idx if id < len(self.__keys)]
        except TypeError:
            # if k_neighbors = 1 query is not returnng arrays
            return self.__keys[idx]
535648
public int getNextRangeIndex() {
        int length = rangeIndexList.size();
        if (length > 0) {
            Integer rindex = rangeIndexList.get(length - 1);
            return rindex.intValue();
        }
        return 0;
    }
342264
def knn_impute_reference(
        X,
        missing_mask,
        k,
        verbose=False,
        print_interval=100):
    
    n_rows, n_cols = X.shape
    X_result, D, effective_infinity = \
        knn_initialize(X, missing_mask, verbose=verbose)

    for i in range(n_rows):
        for j in np.where(missing_mask[i, :])[0]:
            distances = D[i, :].copy()

            # any rows that don't have the value we're currently trying
            # to impute are set to infinite distances
            distances[missing_mask[:, j]] = effective_infinity
            neighbor_indices = np.argsort(distances)
            neighbor_distances = distances[neighbor_indices]

            # get rid of any infinite distance neighbors in the top k
            valid_distances = neighbor_distances < effective_infinity
            neighbor_distances = neighbor_distances[valid_distances][:k]
            neighbor_indices = neighbor_indices[valid_distances][:k]

            weights = 1.0 / neighbor_distances
            weight_sum = weights.sum()

            if weight_sum > 0:
                column = X[:, j]
                values = column[neighbor_indices]
                X_result[i, j] = np.dot(values, weights) / weight_sum
    return X_result
270230
@Override
	public ClusteringTreeNode nearestChild(double[] pointA) {
		assert (this.projections.size() > 0 &&
				this.projections.get(0).length == pointA.length);
		int minBucketProjection = -1;
		int minSize = Integer.MAX_VALUE;
		Iterator<double[]> iIterProjections = this.projections.iterator();
		Iterator<CuckooHashing<List<ClusteringTreeNode>>> iIterBuckets = this.buckets
				.iterator();
		int size = this.projections.size();
		for (int i = 0; i < size; i++) {
			long bucketNumber = calcBucketNumber(project(pointA,
					iIterProjections.next()));
			List<ClusteringTreeNode> currentBucket = iIterBuckets.next().get(
					bucketNumber);
			int bucketSize;
			if (currentBucket != null
					&& (bucketSize = currentBucket.size()) <= minSize) {
				minBucketProjection = i;
				minSize = bucketSize;
			}
		}
		if (minBucketProjection == -1) {
			return null;
		}

		long bucketNumber = calcBucketNumber(project(pointA,
				minBucketProjection));
		double minDistance = Double.POSITIVE_INFINITY;
		ClusteringTreeNode min = null;
		// for (int i = -1; i <= 1; i++) {
		List<ClusteringTreeNode> currentBucket = this.buckets.get(
				minBucketProjection).get(bucketNumber);// + i);
		if (currentBucket != null) {
			for (ClusteringTreeNode node : currentBucket) {
				double d = Metric.distance(pointA, node.getCenter());
				if (d < minDistance) {
					minDistance = d;
					min = node;
				}
			}
		}
		// }
		return min;
	}
782708
@Override
    public int predict(T x) {
        double minDist = Double.MAX_VALUE;
        int bestCluster = 0;

        for (int i = 0; i < k; i++) {
            double dist = distance.d(x, medoids[i]);
            if (dist < minDist) {
                minDist = dist;
                bestCluster = i;
            }
        }

        return bestCluster;
    }
668561
public int[] partition(int k) {
        int n = width * height;
        double[][] units = new double[n][d];
        for (int i = 0, l = 0; i < height; i++) {
            for (int j = 0; j < width; j++, l++) {
                units[l] = neurons[i][j];
            }
        }

        double[][] proximity = new double[n][];
        for (int i = 0; i < n; i++) {
            proximity[i] = new double[i + 1];
            for (int j = 0; j < i; j++) {
                proximity[i][j] = Math.distance(units[i], units[j]);
            }
        }

        Linkage linkage = new UPGMALinkage(proximity);
        HierarchicalClustering hc = new HierarchicalClustering(linkage);
        y = hc.partition(k);

        int[] cluster = new int[bmu.length];
        for (int i = 0; i < cluster.length; i++) {
            cluster[i] = y[bmu[i][0] * width + bmu[i][1]];
        }
        
        return cluster;
    }