Find the k nearest neighbors of y in the observed output data
        @see Databag.nn() for argument description
        @return  distance and indexes of found nearest neighbors.
763345
def nn_y(self, y, dims=None, k = 1, radius=np.inf, eps=0.0, p=2):
        
        if dims is None:
            assert len(y) == self.dim_y
            k_y = min(k, self.__len__())
            return self._nn(DATA_Y, y, k=k_y, radius=radius, eps=eps, p=p)
        else:
            return self.nn_y_sub(y, dims, k, radius, eps, p)
1245970
@Override
  public double getDistance(S solution, L solutionList) {
    List<Double> listOfDistances = knnDistances(solution, solutionList) ;
    listOfDistances.sort(Comparator.naturalOrder());

    int limit = Math.min(k, listOfDistances.size()) ;

    double result ;
    if (limit == 0) {
      result = 0.0 ;
    } else {
      double sum = 0.0;
      for (int i = 0; i < limit; i++) {
        sum += listOfDistances.get(i);
      }
      result = sum/limit ;
    }
    return result;
  }
1272620
public DataBuffer getIndicesOf(int i) {
        int from = underlyingRank() * i;
        int to = from + underlyingRank(); //not included

        int[] arr = new int[rank];
        int j = 0; // iterator over underlying indices
        int k = 0; //iterator over hiddenIdx
        for (int dim = 0; dim < rank; dim++) {
            if (k < hiddenDimensions().length && hiddenDimensions()[k] == j) {
                arr[dim] = 0;
                k++;
            } else {
                arr[dim] = indices.getInt(j);
                j++;
            }
        }
        return Nd4j.getDataBufferFactory().createInt(arr);
    }
192642
private ArrayDBIDs updateKNNsAndRkNNs(DBIDs ids) {
    ArrayModifiableDBIDs rkNN_ids = DBIDUtil.newArray();
    DBIDs oldids = DBIDUtil.difference(relation.getDBIDs(), ids);
    for(DBIDIter id = oldids.iter(); id.valid(); id.advance()) {
      KNNList oldkNNs = storage.get(id);
      double knnDist = oldkNNs.getKNNDistance();
      // look for new kNNs
      KNNHeap heap = null;
      for(DBIDIter newid = ids.iter(); newid.valid(); newid.advance()) {
        double dist = distanceQuery.distance(id, newid);
        if(dist <= knnDist) {
          // New id changes the kNNs of oldid.
          heap = heap != null ? heap : DBIDUtil.newHeap(oldkNNs);
          heap.insert(dist, newid);
        }
      }
      // kNNs for oldid have changed:
      if(heap != null) {
        KNNList newkNNs = heap.toKNNList();
        storage.put(id, newkNNs);

        // get the difference
        ModifiableDoubleDBIDList added = DBIDUtil.newDistanceDBIDList(),
            removed = DBIDUtil.newDistanceDBIDList();
        DoubleDBIDListIter olditer = oldkNNs.iter(), newiter = newkNNs.iter();
        while(olditer.valid() && newiter.valid()) {
          if(DBIDUtil.equal(olditer, newiter)) {
            olditer.advance();
            newiter.advance();
            continue;
          }
          double newd = newiter.doubleValue(), oldd = olditer.doubleValue();
          if(newd < oldd || (newd == oldd && !oldkNNs.contains(newiter))) {
            added.add(newiter.doubleValue(), newiter);
            newiter.advance();
          }
          else if(oldd < newd || (oldd == newd && !newkNNs.contains(olditer))) {
            removed.add(olditer.doubleValue(), olditer);
            olditer.advance();
          }
          else {
            throw new IllegalStateException("Unexpected third case, needs debug!");
          }
        }
        for(; olditer.valid(); olditer.advance()) {
          removed.add(olditer.doubleValue(), olditer);
        }
        for(; newiter.valid(); newiter.advance()) {
          added.add(newiter.doubleValue(), newiter);
        }
        // add new RkNN
        for(DoubleDBIDListIter newnn = added.iter(); newnn.valid(); newnn.advance()) {
          materialized_RkNN.get(newnn).add(DBIDUtil.newPair(newnn.doubleValue(), id));
        }
        // remove old RkNN
        for(DoubleDBIDListIter oldnn = removed.iter(); oldnn.valid(); oldnn.advance()) {
          materialized_RkNN.get(oldnn).remove(DBIDUtil.newPair(oldnn.doubleValue(), id));
        }

        rkNN_ids.add(id);
      }
    }
    return rkNN_ids;
  }
1292746
public DoubleDataStore computeAverageDistInSet() {
    WritableDoubleDataStore davg = DataStoreUtil.makeDoubleStorage(points.getDBIDs(), DataStoreFactory.HINT_HOT);
    WritableIntegerDataStore nDists = DataStoreUtil.makeIntegerStorage(points.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
    FiniteProgress splitp = LOG.isVerbose() ? new FiniteProgress("Processing splits for density estimation", splitsets.size(), LOG) : null;
    DBIDVar v = DBIDUtil.newVar();
    for(Iterator<ArrayDBIDs> it1 = splitsets.iterator(); it1.hasNext();) {
      ArrayDBIDs pinSet = it1.next();
      final int len = pinSet.size();
      final int indoff = len >> 1;
      pinSet.assignVar(indoff, v);
      V midpoint = points.get(v);
      for(DBIDArrayIter it = pinSet.iter(); it.getOffset() < len; it.advance()) {
        if(DBIDUtil.equal(it, v)) {
          continue;
        }
        double dist = EuclideanDistanceFunction.STATIC.distance(points.get(it), midpoint);
        ++distanceComputations;
        davg.increment(v, dist);
        nDists.increment(v, 1);
        davg.increment(it, dist);
        nDists.increment(it, 1);
      }
      LOG.incrementProcessed(splitp);
    }
    LOG.ensureCompleted(splitp);
    for(DBIDIter it = points.getDBIDs().iter(); it.valid(); it.advance()) {
      // it might be that a point does not occur for a certain size of a
      // projection (likely if do few projections, in this case there is no avg
      // distance)
      int count = nDists.intValue(it);
      double val = (count == 0) ? FastOPTICS.UNDEFINED_DISTANCE : (davg.doubleValue(it) / count);
      davg.put(it, val);
    }
    nDists.destroy(); // No longer needed after normalization
    return davg;
  }
345235
public Collection<String> nearestLabels(INDArray labelVector, int topN) {
        if (labelsMatrix == null || labelsList == null || labelsList.isEmpty())
            extractLabels();

        List<BasicModelUtils.WordSimilarity> result = new ArrayList<>();

        // if list still empty - return empty collection
        if (labelsMatrix == null || labelsList == null || labelsList.isEmpty()) {
            log.warn("Labels list is empty!");
            return new ArrayList<>();
        }

        if (!normalizedLabels) {
            synchronized (this) {
                if (!normalizedLabels) {
                    labelsMatrix.diviColumnVector(labelsMatrix.norm1(1));
                    normalizedLabels = true;
                }
            }
        }

        INDArray similarity = Transforms.unitVec(labelVector).mmul(labelsMatrix.transpose());
        List<Double> highToLowSimList = getTopN(similarity, topN + 20);

        for (int i = 0; i < highToLowSimList.size(); i++) {
            String word = labelsList.get(highToLowSimList.get(i).intValue()).getLabel();
            if (word != null && !word.equals("UNK") && !word.equals("STOP")) {
                INDArray otherVec = lookupTable.vector(word);
                double sim = Transforms.cosineSim(labelVector, otherVec);

                result.add(new BasicModelUtils.WordSimilarity(word, sim));
            }
        }

        Collections.sort(result, new BasicModelUtils.SimilarityComparator());

        return BasicModelUtils.getLabels(result, topN);
    }
1099110
private double getRandomNeighbor(T[] data, T[] medoids, int[] y, double[] d) {
        int n = data.length;

        int index = Math.randomInt(k);
        T medoid = null;
        boolean dup;
        do {
            dup = false;
            medoid = data[Math.randomInt(n)];
            for (int i = 0; i < k; i++) {
                if (medoid == medoids[i]) {
                    dup = true;
                    break;
                }
            }
        } while (dup);

        medoids[index] = medoid;

        for (int i = 0; i < n; i++) {
            double dist = distance.d(data[i], medoid);
            if (d[i] > dist) {
                y[i] = index;
                d[i] = dist;
            } else if (y[i] == index) {
                d[i] = dist;
                y[i] = index;
                for (int j = 0; j < k; j++) {
                    if (j != index) {
                        dist = distance.d(data[i], medoids[j]);
                        if (d[i] > dist) {
                            y[i] = j;
                            d[i] = dist;
                        }
                    }
                }
            }
        }

        return Math.sum(d);
    }
542195
def classify_nearest(self, partial_labels):
    '''
    '''
    labels = np.array(partial_labels, copy=True)
    unlabeled = labels == -1
    # compute geodesic distances from unlabeled vertices
    D_unlabeled = self.shortest_path(weighted=True)[unlabeled]
    # set distances to other unlabeled vertices to infinity
    D_unlabeled[:,unlabeled] = np.inf
    # find shortest distances to labeled vertices
    idx = D_unlabeled.argmin(axis=1)
    # apply the label of the closest vertex
    labels[unlabeled] = labels[idx]
    return labels
162001
def near(self, x, y, max_distance=None):
        
        expr = {
            self : {'$near' : [x, y]}
        }
        if max_distance is not None:
            expr[self]['$maxDistance'] = max_distance
        # if bucket_size is not None:
        #     expr['$bucketSize'] = max_distance
        return QueryExpression(expr)
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;
    }
53752
public static <S extends Solution<?>> double[][] distanceMatrix(List<S> solutionSet) {
    double[][] distance = new double[solutionSet.size()][solutionSet.size()];
    for (int i = 0; i < solutionSet.size(); i++) {
      distance[i][i] = 0.0;
      for (int j = i + 1; j < solutionSet.size(); j++) {
        distance[i][j] = SolutionUtils.distanceBetweenObjectives(solutionSet.get(i), solutionSet.get(j));
        distance[j][i] = distance[i][j];
      }
    }
    return distance;
  }
933648
int[][] findNeighborIndices() {

		// looking at a typical protein case, number of neighbours are from ~10 to ~50, with an average of ~30
		int initialCapacity = 60;

		int[][] nbsIndices = new int[atomCoords.length][];

		for (int k=0; k<atomCoords.length; k++) {
			double radius = radii[k] + probe + probe;

			List<Integer> thisNbIndices = new ArrayList<>(initialCapacity);

			for (int i = 0; i < atomCoords.length; i++) {
				if (i == k) continue;

				double dist = atomCoords[i].distance(atomCoords[k]);

				if (dist < radius + radii[i]) {
					thisNbIndices.add(i);
				}
			}

			int[] indicesArray = new int[thisNbIndices.size()];
			for (int i=0;i<thisNbIndices.size();i++) indicesArray[i] = thisNbIndices.get(i);
			nbsIndices[k] = indicesArray;
		}
		return nbsIndices;
	}
872472
public function nearest(array $sample, int $k = 1) : array
    {
        if ($k < 1) {
            throw new InvalidArgumentException('The number of nearest'
                . " neighbors must be greater than 0, $k given.");
        }

        $neighborhood = $this->search($sample);

        if (!$neighborhood) {
            return [[], []];
        }

        $distances = $labels = [];

        $visited = new SplObjectStorage();

        $stack = [$neighborhood];

        while ($stack) {
            $current = array_pop($stack);

            if ($visited->contains($current)) {
                continue 1;
            }

            $visited->attach($current);

            $parent = $current->parent();

            if ($parent) {
                $stack[] = $parent;
            }

            if ($current instanceof Neighborhood) {
                foreach ($current->samples() as $neighbor) {
                    $distances[] = $this->kernel->compute($sample, $neighbor);
                }

                $labels = array_merge($labels, $current->labels());

                array_multisort($distances, $labels);

                continue 1;
            }

            $target = $distances[$k - 1] ?? INF;

            foreach ($current->children() as $child) {
                if ($visited->contains($child)) {
                    continue 1;
                }

                if ($child instanceof Box) {
                    foreach ($child->sides() as $side) {
                        $distance = $this->kernel->compute($sample, $side);

                        if ($distance < $target) {
                            $stack[] = $child;

                            continue 2;
                        }
                    }
                }

                $visited->attach($child);
            }
        }

        $distances = array_slice($distances, 0, $k);
        $labels = array_slice($labels, 0, $k);

        return [$labels, $distances];
    }
717607
@SuppressWarnings({ "cast", "unchecked" })
  public static <O extends SpatialComparable> KNNQuery<O> getKNNQuery(AbstractRStarTree<?, ?, ?> tree, SpatialDistanceQuery<O> distanceQuery, Object... hints) {
    // Can we support this distance function - spatial distances only!
    SpatialPrimitiveDistanceFunction<? super O> df = distanceQuery.getDistanceFunction();
    if(EuclideanDistanceFunction.STATIC.equals(df)) {
      return (KNNQuery<O>) new EuclideanRStarTreeKNNQuery<>(tree, (Relation<NumberVector>) distanceQuery.getRelation());
    }
    return new RStarTreeKNNQuery<>(tree, distanceQuery.getRelation(), df);
  }
554718
@Override
	public Clustering getClusteringResult() {
		List<double[]> microClustering;
		// If the buffer phase is active then the buffer (without duplicates) is
		// equal to the micro clustering
		if (this.bufferPhase) {
			microClustering = new ArrayList<double[]>(this.buffer.size());
			for (double[] pointA : this.buffer) {
				// Searches for a duplicate of the current point
				boolean duplicate = false;
				for (double[] pointB : microClustering) {
					int i;
					for (i = 0; i < pointA.length; i++) {
						if (pointA[i] != pointB[i + 1]) {
							break;
						}
					}
					if (i == pointA.length) {
						duplicate = true;
						pointB[0] += 1;
						break;
					}
				}

				if (!duplicate) {
					// Copies the point to an array with the weight in the first
					// element
					double[] pointWeighted = new double[pointA.length + 1];
					pointWeighted[0] = 1;
					System.arraycopy(pointA, 0, pointWeighted, 1, pointA.length);
					microClustering.add(pointWeighted);
				}
			}
		} else {
			// Collects all nodes as arrays with the weight in the first element
			microClustering = this.root
					.addToClusteringCenters(new ArrayList<double[]>(this.rootCount));
		}
		// Runs the k-means algorithm five times on the micro clustering
		List<double[]> result = null;
		double minValue = Double.POSITIVE_INFINITY;
		for (int i = 0; i < 5; i++) {
			// Creates the starting centroids
			List<double[]> newResult = CoresetKMeans
					.generatekMeansPlusPlusCentroids(this.numClusters,
							microClustering, this.clustererRandom);
			// Runs the k-means algorithm with changing the starting centroids
			double newValue = CoresetKMeans.kMeans(newResult, microClustering);
			// Selects the result with minimum costs
			if (newValue < minValue) {
				result = newResult;
				minValue = newValue;
			}
		}

		// Prepares the points for the clustering result
		AutoExpandVector<Cluster> resultClustering = new AutoExpandVector<Cluster>(
				result.size());
		for (double[] point : result) {
			resultClustering.add(new SphereCluster(point, 0.0));
		}
		return new Clustering(resultClustering);
	}
267767
private List<Point2D> getNeighbors(final Point2D point, KDTree<Point2D> points) {
    	double[] key = {point.x, point.y};
        final List<Point2D> neighbors = new ArrayList<Point2D>();
        
        neighbors.addAll(points.nearestEuclidean(key, eps));
        
        return neighbors; 
    }
453196
public List<Map.Entry<K, Float>> nearest(K key, int size)
    {
        Vector vector = storage.get(key);
        if (vector == null)
        {
            return Collections.emptyList();
        }
        return nearest(key, vector, size);
    }