Returns the local scale based on the k-th nearest neighbour
328103
def kscale(matrix, k=7, dists=None):
    
    dists = (kdists(matrix, k=k) if dists is None else dists)
    scale = dists.dot(dists.T)
    return scale
552327
def get_nearest_by_numeric_key(data: dict, key: int) -> Any:
    """"""
    return data.get(key, data[min(data.keys(), key=lambda k: abs(k - key))])
1303556
def nearest_base(cls, bases):
    '''
    '''
    if cls in bases:
        return cls

    dists = {base: index(mro(cls), base) for base in bases}
    dists2 = {dist: base for base, dist in dists.items() if dist is not None}
    if not dists2:
        return None
    return dists2[min(dists2)]
602089
def get_scaling_function(y_m, y_M, x_m, x_M):
    
    if x_M <= x_m:
        return lambda _: y_m
    k = (y_M - y_m) / (x_M - x_m)
    b = y_m - k * x_m
    return lambda _: int(k * _ + b)
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
769730
def fit(self, X, y):
    '''
    '''
    X, y = self._prepare_inputs(X, y, ensure_min_samples=2)
    unique_classes, y = np.unique(y, return_inverse=True)
    n, d = X.shape
    num_classes = len(unique_classes)

    if self.num_dims is None:
      dim = d
    else:
      if not 0 < self.num_dims <= d:
        raise ValueError('Invalid num_dims, must be in [1,%d]' % d)
      dim = self.num_dims

    if self.k is None:
      k = min(7, d - 1)
    elif self.k >= d:
      warnings.warn('Chosen k (%d) too large, using %d instead.' % (self.k,d-1))
      k = d - 1
    else:
      k = int(self.k)
    tSb = np.zeros((d,d))
    tSw = np.zeros((d,d))

    for c in xrange(num_classes):
      Xc = X[y==c]
      nc = Xc.shape[0]

      # classwise affinity matrix
      dist = pairwise_distances(Xc, metric='l2', squared=True)
      # distances to k-th nearest neighbor
      k = min(k, nc - 1)
      sigma = np.sqrt(np.partition(dist, k, axis=0)[:, k])

      local_scale = np.outer(sigma, sigma)
      with np.errstate(divide='ignore', invalid='ignore'):
        A = np.exp(-dist/local_scale)
        A[local_scale==0] = 0

      G = Xc.T.dot(A.sum(axis=0)[:,None] * Xc) - Xc.T.dot(A).dot(Xc)
      tSb += G/n + (1-nc/n)*Xc.T.dot(Xc) + _sum_outer(Xc)/n
      tSw += G/nc

    tSb -= _sum_outer(X)/n - tSw

    # symmetrize
    tSb = (tSb + tSb.T) / 2
    tSw = (tSw + tSw.T) / 2

    vals, vecs = _eigh(tSb, tSw, dim)
    order = np.argsort(-vals)[:dim]
    vals = vals[order].real
    vecs = vecs[:,order]

    if self.embedding_type == 'weighted':
       vecs *= np.sqrt(vals)
    elif self.embedding_type == 'orthonormalized':
       vecs, _ = np.linalg.qr(vecs)

    self.transformer_ = vecs.T
    return self
1266863
def iter_nearest_neighbours(umis, substr_idx):
    '''
    
    '''
    for i, u in enumerate(umis, 1):
        neighbours = set()
        for idx, substr_map in substr_idx.items():
            u_sub = u[slice(*idx)]
            neighbours = neighbours.union(substr_map[u_sub])
        neighbours.difference_update(umis[:i])
        for nbr in neighbours:
            yield u, nbr
287749
def despeckle_local(M, stds=2, width=2):
    

    N = np.array(M, dtype=np.float64)
    n, m = M.shape
    for i, j in itertools.product(range(width, n - width),
                                  range(width, m - width)):
        square = M[i - width:i + width, j - width:j + width]
        avg = np.average(square)
        std = np.std(square)
        if M[i, j] >= avg + stds * std:
            N[i, j] = avg
    return (N + N.T) / 2
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)
1214087
function getNeighbourhood (dimensionNumber) {
    var neighbourhood = moore(2, dimensionNumber),
        origin = [],
        dimension;

    for (dimension = 0; dimension < dimensionNumber; dimension++) {
        origin.push(0);
    }

    neighbourhood.push(origin);

    // sort by ascending distance to optimize proximity checks
    // see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008
    // http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1
    neighbourhood.sort(function (n1, n2) {
        var squareDist1 = 0,
            squareDist2 = 0;

        for (var dimension = 0; dimension < dimensionNumber; dimension++) {
            squareDist1 += Math.pow(n1[dimension], 2);
            squareDist2 += Math.pow(n2[dimension], 2);
        }

        if (squareDist1 < squareDist2) {
            return -1;
        } else if(squareDist1 > squareDist2) {
            return 1;
        } else {
            return 0;
        }
    });

    return neighbourhood;
}
1152763
def _compute_distance_scaling(self, C, rrup, mag):
        
        rscale1 = rrup + C["c2"] * (10.0 ** (C["c3"] * mag))
        return -np.log10(rscale1) - (C["c4"] * rrup)
11969
def epsilon_net(points, close_distance):
  ''''''
  num_points = points.shape[0]
  indices = set(range(num_points))
  selected = []
  while indices:
    idx = indices.pop()
    nn_inds, = nearest_neighbors(points[idx], points, epsilon=close_distance)
    indices.difference_update(nn_inds)
    selected.append(idx)
  return selected
761638
def vq_nearest_neighbor(x, hparams):
  """"""
  bottleneck_size = 2**hparams.bottleneck_bits
  means = hparams.means
  x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
  means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
  scalar_prod = tf.matmul(x, means, transpose_b=True)
  dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod
  if hparams.bottleneck_kind == "em":
    x_means_idx = tf.multinomial(-dist, num_samples=hparams.num_samples)
    x_means_hot = tf.one_hot(
        x_means_idx, depth=bottleneck_size)
    x_means_hot = tf.reduce_mean(x_means_hot, axis=1)
  else:
    x_means_idx = tf.argmax(-dist, axis=-1)
    x_means_hot = tf.one_hot(x_means_idx, depth=bottleneck_size)
  x_means = tf.matmul(x_means_hot, means)
  e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means)))
  return x_means_hot, e_loss
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)
1033904
def interpolate_nearest(self, lons, lats, data):
        
        return self.interpolate(lons, lats, data, order=0)
777607
public static void equalizeLocalNaive( GrayU8 input , int radius , GrayU8 output ,
										   IWorkArrays workArrays )
	{
		int width = 2*radius+1;
		int maxValue = workArrays.length()-1;

		//CONCURRENT_BELOW BoofConcurrency.loopBlocks(0,input.height,(idx0,idx1)->{
		int idx0 = 0, idx1 = input.height;
		int[] histogram = workArrays.pop();
		for( int y = idx0; y < idx1; y++ ) {
			// make sure it's inside the image bounds
			int y0 = y-radius;
			int y1 = y+radius+1;
			if( y0 < 0 ) {
				y0 = 0; y1 = width;
				if( y1 > input.height )
					y1 = input.height;
			} else if( y1 > input.height ) {
				y1 = input.height;
				y0 = y1 - width;
				if( y0 < 0 )
					y0 = 0;
			}

			// pixel indexes
			int indexIn = input.startIndex + y*input.stride;
			int indexOut = output.startIndex + y*output.stride;

			for( int x = 0; x < input.width; x++ ) {
				// make sure it's inside the image bounds
				int x0 = x-radius;
				int x1 = x+radius+1;
				if( x0 < 0 ) {
					x0 = 0; x1 = width;
					if( x1 > input.width )
						x1 = input.width;
				} else if( x1 > input.width ) {
					x1 = input.width;
					x0 = x1 - width;
					if( x0 < 0 )
						x0 = 0;
				}

				// compute the local histogram
				localHistogram(input,x0,y0,x1,y1,histogram);

				// only need to compute up to the value of the input pixel
				int inputValue =  input.data[indexIn++] & 0xFF;
				int sum = 0;
				for( int i = 0; i <= inputValue; i++ ) {
					sum += histogram[i];
				}

				int area = (y1-y0)*(x1-x0);
				output.data[indexOut++] = (byte)((sum*maxValue)/area);
			}
		}
		workArrays.recycle(histogram);
		//CONCURRENT_ABOVE });
	}
555727
def scale(self, scalar):
        ''''''
        return self.__class__([self.coefficients[i] * scalar for i in _range(len(self))])