Cuts a tree into several groups by specifying the desired number.
@param k the number of clusters.
@return the cluster label of each sample.
423896
public int[] partition(int k) {
        int n = merge.length + 1;
        int[] membership = new int[n];

        IntHeapSelect heap = new IntHeapSelect(k);
        for (int i = 2; i <= k; i++) {
            heap.add(merge[n - i][0]);
            heap.add(merge[n - i][1]);
        }

        for (int i = 0; i < k; i++) {
            bfs(membership, heap.get(i), i);
        }

        return membership;
    }
319812
public Set<Label> getLabels() {
        Set<Label> r = new TreeSet<>();
        for (Label l : labels.values()) {
            if(!l.isEmpty())
                r.add(l);
        }
        return r;
    }
154308
public List<Set<K>> kmeans(int nclusters)
    {
        Cluster<K> cluster = new Cluster<K>();
        for (Document<K> document : documents_.values())
        {
            cluster.add_document(document);
        }
        cluster.section(nclusters);
        refine_clusters(cluster.sectioned_clusters());
        List<Cluster<K>> clusters_ = new ArrayList<Cluster<K>>(nclusters);
        for (Cluster<K> s : cluster.sectioned_clusters())
        {
            s.refresh();
            clusters_.add(s);
        }
        return toResult(clusters_);
    }
656156
public static String stringFor(int k)
    {
        switch (k)
        {
            case cudaMemAdviseSetReadMostly : return "cudaMemAdviseSetReadMostly";
            case cudaMemAdviseUnsetReadMostly : return "cudaMemAdviseUnsetReadMostly";
            case cudaMemAdviseSetPreferredLocation : return "cudaMemAdviseSetPreferredLocation";
            case cudaMemAdviseUnsetPreferredLocation : return "cudaMemAdviseUnsetPreferredLocation";
            case cudaMemAdviseSetAccessedBy : return "cudaMemAdviseSetAccessedBy";
            case cudaMemAdviseUnsetAccessedBy : return "cudaMemAdviseUnsetAccessedBy";
        }
        return "INVALID cudaMemoryAdvise: "+k;
    }
75997
def _tree_to_labels(X, single_linkage_tree, min_cluster_size=10,
                    cluster_selection_method='eom',
                    allow_single_cluster=False,
                    match_reference_implementation=False):
    
    condensed_tree = condense_tree(single_linkage_tree,
                                   min_cluster_size)
    stability_dict = compute_stability(condensed_tree)
    labels, probabilities, stabilities = get_clusters(condensed_tree,
                                                      stability_dict,
                                                      cluster_selection_method,
                                                      allow_single_cluster,
                                                      match_reference_implementation)

    return (labels, probabilities, stabilities, condensed_tree,
            single_linkage_tree)
1343260
public IntWritable getGroupingIntWritable(String label) {
        HadoopObject o = getHadoopObject(KEY, label, ObjectUtil.INTEGER, "Integer");
        if (o == null) {
            return null;
        }
        return (IntWritable) o.getObject();
    }
537054
public static SortedMap<Short, List<MappeableContainer>> groupByKey(
          ImmutableRoaringBitmap... bitmaps) {
    Map<Short, List<MappeableContainer>> grouped = new HashMap<>();
    for (ImmutableRoaringBitmap bitmap : bitmaps) {
      MappeableContainerPointer it = bitmap.highLowContainer.getContainerPointer();
      while (null != it.getContainer()) {
        MappeableContainer container = it.getContainer();
        Short key = it.key();
        List<MappeableContainer> slice = grouped.get(key);
        if (null == slice) {
          slice = new ArrayList<>();
          grouped.put(key, slice);
        }
        slice.add(container);
        it.advance();
      }
    }
    SortedMap<Short, List<MappeableContainer>> sorted = new TreeMap<>(BufferUtil::compareUnsigned);
    sorted.putAll(grouped);
    return sorted;
  }
931329
protected Entry<K, V> get(K k) {
        Entry<K, V> currentNode = mStart;
        while (currentNode != null) {
            if (currentNode.mKey.equals(k)) {
                break;
            }
            currentNode = currentNode.mNext;
        }
        return currentNode;
    }
634120
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions) {
        return cluster(matrix, numClusters, numRepetitions,
                       new RandomSeed(), new I1Function());
    }
985389
private Node<K, V> cutChildren(Node<K, V> n) {
        Node<K, V> child = n.o_c;
        n.o_c = null;
        if (child != null) {
            child.o_s = null;
        }
        return child;
    }
681429
public static KNN<double[]> learn(double[][] x, int[] y, int k) {
        if (x.length != y.length) {
            throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
        }

        if (k < 1) {
            throw new IllegalArgumentException("Illegal k = " + k);
        }

        KNNSearch<double[], double[]> knn = null;
        if (x[0].length < 10) {
            knn = new KDTree<>(x, x);
        } else {
            knn = new CoverTree<>(x, new EuclideanDistance());
        }
        
        return new KNN<>(knn, y, k);
    }
666583
public static Double smallest(Iterator <Double> elements, int k) {
        if (k <= 0 || !elements.hasNext()) {
            return null;
        } 
        else if (k >= Integer.MAX_VALUE / 2) {
            List <Double> list = new ArrayList <> ();
            while (elements.hasNext()) {
                list.add(elements.next());
            }
            Collections.sort(list);
            return list.get(k - 1);
        }

        int bufferCap = k * 2;
        Double[] buffer = new Double[bufferCap];
        Double threshold = elements.next();
        buffer[0] = threshold;
        int bufferSize = 1;

        while (bufferSize < k && elements.hasNext()) {
            Double e = elements.next();
            buffer[bufferSize++] = e;
            threshold = Math.max(threshold, e);
        }

        while (elements.hasNext()) {
            Double e = elements.next();
            if (e >= threshold) {
                continue;
            }

            buffer[bufferSize++] = e;
            if (bufferSize == bufferCap) {

                int left = 0;
                int right = bufferCap - 1;

                int minThresholdPosition = 0;

                while (left < right) {
                    int pivotIndex = (left + right + 1) >>> 1;
                    
                    //--- partition
                    Double pivotValue = buffer[pivotIndex];

                    buffer[pivotIndex] = buffer[right];
                    buffer[right] = pivotValue;

                    int pivotNewIndex = left;
                    for (int l = left; l < right; l++) {
                        if (buffer[l] < pivotValue) {
                            Double temp = buffer[pivotNewIndex];
                            buffer[pivotNewIndex] = buffer[l];
                            buffer[l] = temp;
                            pivotNewIndex++;
                        }
                    }

                    Double temp = buffer[right];
                    buffer[right] = buffer[pivotNewIndex];
                    buffer[pivotNewIndex] = temp;
                    //---
        
                    if (pivotNewIndex > k) {
                        right = pivotNewIndex - 1;
                    } 
                    else if (pivotNewIndex < k) {
                        left = Math.max(pivotNewIndex, left + 1);
                        minThresholdPosition = pivotNewIndex;
                    } 
                    else {
                        break;
                    }
                }
                bufferSize = k;

                threshold = buffer[minThresholdPosition];
                for (int i = minThresholdPosition + 1; i < bufferSize; i++) {
                    threshold = Math.max(threshold, buffer[i]);
                }
            }
        }
        
        Arrays.sort(buffer, 0, bufferSize);

        k = Math.min(bufferSize, k);
        
        return buffer[k-1];
    }
1279285
public <E extends WeightedEdge> MultiMap<Integer,Integer> cluster(
              final WeightedGraph<E> graph, int numClusters, Properties props) {
        if (props.getProperty(KEEP_WEIGHT_VECTORS_PROPERTY) != null)
            keepWeightVectors = Boolean.parseBoolean(
                props.getProperty(KEEP_WEIGHT_VECTORS_PROPERTY));
        vertexToWeightVector.clear();
        return super.cluster(graph, numClusters, props);
    }
445510
public Assignments cluster(Matrix matrix, Properties props) {
        int endSize = Integer.parseInt(props.getProperty(
                NUM_CLUSTERS_END, DEFAULT_NUM_CLUSTERS_END));
        return cluster(matrix, endSize, props);
    }
476501
public Clustering<DendrogramModel> run(PointerHierarchyRepresentationResult pointerresult) {
    Clustering<DendrogramModel> result = new Instance(pointerresult).run();
    result.addChildResult(pointerresult);
    return result;
  }
254207
def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol):
    
    membs = np.empty(shape=X.shape[0], dtype=int)
    centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float)
    sse_arr = dict() #-1.0*np.ones(shape=n_clusters, dtype=float)

    ## data structure to store cluster hierarchies
    tree = treelib.Tree()
    tree = _add_tree_node(tree, 0, ilev=0, X=X) 

    km = _kmeans.KMeans(n_clusters=2, n_trials=n_trials, max_iter=max_iter, tol=tol)
    for i in range(1,n_clusters):
        sel_clust_id,sel_memb_ids = _select_cluster_2_split(membs, tree)
        X_sub = X[sel_memb_ids,:]
        km.fit(X_sub)

        #print("Bisecting Step %d    :"%i, sel_clust_id, km.sse_arr_, km.centers_)
        ## Updating the clusters & properties
        #sse_arr[[sel_clust_id,i]] = km.sse_arr_
        #centers[[sel_clust_id,i]] = km.centers_
        tree = _add_tree_node(tree, 2*i-1, i, \
                              size=np.sum(km.labels_ == 0), center=km.centers_[0], \
                              sse=km.sse_arr_[0], parent= sel_clust_id)
        tree = _add_tree_node(tree, 2*i,   i, \
                             size=np.sum(km.labels_ == 1), center=km.centers_[1], \
                             sse=km.sse_arr_[1], parent= sel_clust_id)

        pred_labels = km.labels_
        pred_labels[np.where(pred_labels == 1)[0]] = 2*i
        pred_labels[np.where(pred_labels == 0)[0]] = 2*i - 1
        #if sel_clust_id == 1:
        #    pred_labels[np.where(pred_labels == 0)[0]] = sel_clust_id
        #    pred_labels[np.where(pred_labels == 1)[0]] = i
        #else:
        #    pred_labels[np.where(pred_labels == 1)[0]] = i
        #    pred_labels[np.where(pred_labels == 0)[0]] = sel_clust_id

        membs[sel_memb_ids] = pred_labels


    for n in tree.leaves():
        label = n.data['label']
        centers[label] = n.data['center']
        sse_arr[label] = n.data['sse']

    return(centers, membs, sse_arr, tree)
101808
public int[][] getClusterLabel() {
        if (y == null) {
           throw new IllegalStateException("Neuron cluster labels are not available. Call partition() first.");
        }

        int[][] clusterLabels = new int[height][width];
        for (int i = 0, l = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                clusterLabels[i][j] = y[i*width + j];
            }
        }
        return clusterLabels;
    }