Returns the index of the closest centroid to the sample
197424
def _closest_centroid(self, x):
        
        closest_centroid = 0
        distance = 10^9

        for i in range(self.n_clusters):
            current_distance = linalg.norm(x - self.centroids[i])
            if current_distance < distance:
                closest_centroid = i
                distance = current_distance

        return closest_centroid
613964
def simple_nearest_indices(xs,res):
    '''
    
    '''
    maxs = [max(a) for a in xs]
    mins = [min(a) for a in xs]
    XS = [np.linspace(mn, mx, r) for mn,mx,r in zip(mins,maxs,res)];
    XS = tuple(np.meshgrid(*XS,indexing='ij'));
    if type(xs) != tuple:
        xs = tuple(xs);
    return nearest_indices(xs,XS);
1345339
def get_indices(self, src, ridx, mag):
        
        centroids = src.get_centroids(ridx)
        mindistance = min_geodetic_distance(
            (centroids[:, 0], centroids[:, 1]), self.sitecol.xyz)
        idist = self.integration_distance(DEFAULT_TRT, mag)
        indices, = (mindistance <= idist).nonzero()
        return indices
93645
def _retain_centroids(numbers, thres):
    """"""
    numbers.sort()
    prev = -1
    ret = []
    for n in numbers:
        if prev < 0 or n - prev > thres:
            ret.append(n)
            prev = n
    return ret
1355869
function quantile_sorted(sample, p) {
        var idx = (sample.length) * p;
        if (p < 0 || p > 1) {
            return null;
        } else if (p === 1) {
            // If p is 1, directly return the last element
            return sample[sample.length - 1];
        } else if (p === 0) {
            // If p is 0, directly return the first element
            return sample[0];
        } else if (idx % 1 !== 0) {
            // If p is not integer, return the next element in array
            return sample[Math.ceil(idx) - 1];
        } else if (sample.length % 2 === 0) {
            // If the list has even-length, we'll take the average of this number
            // and the next value, if there is one
            return (sample[idx - 1] + sample[idx]) / 2;
        } else {
            // Finally, in the simple case of an integer value
            // with an odd-length list, return the sample value at the index.
            return sample[idx];
        }
    }
1176021
def closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union["Unit", "Point2"]:
        
        assert ps
        if len(ps) == 1:
            return ps[0]
        closest_distance_squared = math.inf
        for p2 in ps:
            p2pos = p2
            if not isinstance(p2pos, Point2):
                p2pos = p2.position
            distance = (self[0] - p2pos[0]) ** 2 + (self[1] - p2pos[1]) ** 2
            if distance < closest_distance_squared:
                closest_distance_squared = distance
                closest_element = p2
        return closest_element
1041939
private static int[] seed(SparseDataset data, int k) {
        int n = data.size();

        int[] y = new int[n];
        SparseArray centroid = data.get(Math.randomInt(n)).x;

        double[] D = new double[n];
        for (int i = 0; i < n; i++) {
            D[i] = Double.MAX_VALUE;
        }

        // pick the next center
        for (int i = 1; i < k; i++) {
            for (int j = 0; j < n; j++) {
                double dist = Math.JensenShannonDivergence(data.get(j).x, centroid);
                if (dist < D[j]) {
                    D[j] = dist;
                    y[j] = i - 1;
                }
            }

            double cutoff = Math.random() * Math.sum(D);
            double cost = 0.0;
            int index = 0;
            for (; index < n; index++) {
                cost += D[index];
                if (cost >= cutoff) {
                    break;
                }
            }

            centroid = data.get(index).x;
        }

        for (int j = 0; j < n; j++) {
            // compute the distance between this sample and the current center
            double dist = Math.JensenShannonDivergence(data.get(j).x, centroid);
            if (dist < D[j]) {
                D[j] = dist;
                y[j] = k - 1;
            }
        }

        return y;
    }
594401
def _find_indices(self, x):
        
        # find relevant edges between which xi are situated
        index_vecs = []
        # compute distance to lower edge in unity units
        norm_distances = []

        # iterate through dimensions
        for xi, cvec in zip(x, self.coord_vecs):
            idcs = np.searchsorted(cvec, xi) - 1

            idcs[idcs < 0] = 0
            idcs[idcs > cvec.size - 2] = cvec.size - 2
            index_vecs.append(idcs)

            norm_distances.append((xi - cvec[idcs]) /
                                  (cvec[idcs + 1] - cvec[idcs]))

        return index_vecs, norm_distances
800857
function closestPoint0d(a, x, result) {
  var d = 0.0;
  for(var i=0; i<x.length; ++i) {
    result[i] = a[i];
    var t = a[i] - x[i];
    d += t * t;
  }
  return d;
}
1133448
function centroidOf(points, dimension) {
    var centroid = new Float32Array(dimension);
    for (var i = 0; i < centroid.length; i++) {
      var sum = 0;
      var count = 0;
      for (var pointIndex = 0; pointIndex < points.length; pointIndex++) {
        var p = points[pointIndex];
        var point = p.getPoint();
        var val = point.getValue(i);
        if (!isNaN(val)) {
          sum += val;
          count++;
        }
      }
      centroid[i] = (sum / count);
    }
    return new PointWrapper(morpheus.VectorUtil.arrayAsVector(centroid));
  }
937336
def closestNonZeroIndex(pt, arr, kSize=21):
    
    assert kSize % 2 == 1, 'need odd kernel size'

    hk = int(kSize / 2)
    ipt = np.asarray(pt, dtype=int)
    # array slice of shape kSize around ipt:
    r = [slice(max(0, p - hk),
               min(s, p + hk + 1)) for p, s in zip(ipt, arr.shape)]

    # sliced array:
    arrr = arr[tuple(r)]
    # all indices that are non zero:
    ind = np.transpose(np.nonzero(arrr))
    if not len(ind):
        # nothing found
        return None
    # pos of ipt within array slice:
    center = [p - s.start for p, s in zip(ipt, r)]
    ind -= center
    # index of minimum distance:
    m = np.argmin(norm(ind, axis=-1))
    return ipt + ind[m]
935037
def get_closest_clusters(cluster_id, cluster_ids, sim_func, max_n=None):
    """"""
    l = [(_as_scalar(candidate), _as_scalar(sim_func(cluster_id, candidate)))
         for candidate in _as_scalars(cluster_ids)]
    l = sorted(l, key=itemgetter(1), reverse=True)
    max_n = None or len(l)
    return l[:max_n]
1182645
def centroid(coo):
    
    return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo]))))
12936
def _get_index(self):
        
        contour = self.contour
        value = contour.bPoints.index(self)
        return value
694847
def getCenter(self):
        '''
        
        '''

        (left, top), (right, bottom) = self.getCoords()
        x = left + (right - left) / 2
        y = top + (bottom - top) / 2
        return (x, y)
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]
859871
def cdx_sort_closest(closest, cdx_iter, limit=10):
    
    closest_cdx = []
    closest_keys = []
    closest_sec = timestamp_to_sec(closest)

    for cdx in cdx_iter:
        sec = timestamp_to_sec(cdx[TIMESTAMP])
        key = abs(closest_sec - sec)

        # create tuple to sort by key
        #bisect.insort(closest_cdx, (key, cdx))

        i = bisect.bisect_right(closest_keys, key)
        closest_keys.insert(i, key)
        closest_cdx.insert(i, cdx)

        if len(closest_cdx) == limit:
            # assuming cdx in ascending order and keys have started increasing
            if key > closest_keys[-1]:
                break

        if len(closest_cdx) > limit:
            closest_cdx.pop()

    for cdx in closest_cdx:
        yield cdx