Get a random point from the {@link Cluster} with the largest distance variance.

@param clusters the {@link Cluster}s to search
@return a random point from the selected cluster
@throws ConvergenceException if clusters are all empty
5501
function getPointFromLargestVarianceCluster(clusters) {
    var maxVariance = -Number.MAX_VALUE;
    var selected = null;
    for (var clusterIndex = 0; clusterIndex < clusters.length; clusterIndex++) {
      var cluster = clusters[clusterIndex];

      if (cluster.getPoints().length > 0) {

        // compute the distance variance of the current cluster
        var center = cluster.getCenter();
        var points = cluster.getPoints();
        var distances = new Float32Array(points.length);
        for (var i = 0; i < points.length; i++) {
          distances[i] = distance(points[i], center);
        }
        var variance = morpheus.Variance(morpheus.VectorUtil.arrayAsVector(distances));

        // select the cluster with the largest variance
        if (variance > maxVariance) {
          maxVariance = variance;
          selected = cluster;
        }
      }
    }

    // did we find at least one non-empty cluster ?
    if (selected == null) {
      throw 'All clusters are empty';
    }

    // extract a random point from the cluster
    var selectedPoints = selected.getPoints();
    return selectedPoints.splice(nextInt(selectedPoints.length), 1);

  }
21538
Point chooseCentre(treeNode node, MTRandom clustererRandom){

		//How many times should we try to choose a centre ??
		int times = 3;
			
		//stores the nodecost if node is split with the best centre
		double minCost = node.cost;
		Point bestCentre = null;
		
		//loop counter variable
		int i;
		int j;
		
		for(j=0;j<times;j++){
			//sum of the relativ cost of the points
			double sum = 0.0;
			//random number between 0 and 1
			double random = clustererRandom.nextDouble();
			
			for(i=0;i<node.n;i++){
			
				sum += treeNodeCostOfPoint(node,node.points[i]) / node.cost;
				if(sum >= random){
					if(node.points[i].weight == 0.0){
						//printf("ERROR: CHOOSEN DUMMY NODE THOUGH OTHER AVAILABLE \n");
						return null;
					}
					double curCost = treeNodeSplitCost(node,node.centre,node.points[i]);
					if(curCost < minCost){
						bestCentre = node.points[i];
						minCost = curCost;
					}
					break;
				}
			}
		}
		if(bestCentre == null){
			return node.points[0];
		} else {
			return bestCentre;
		}
	}
546076
public static KmeansDataSet createDataModel(List<KmeansPoint> pointList, int clusterNum,
            int maxIteration, double convergenceThres)
    {
        // クラスタ数よりもデータ数が少ない場合、結果はnullとして返す。
        if (pointList.size() < clusterNum)
        {
            return null;
        }

        // 初回の中心点リストを生成する。
        List<KmeansPoint> centroids = createInitialCentroids(pointList, clusterNum);
        long[] clusteredNum = new long[clusterNum];

        // イテレーションを最大回数実行し、収束を試みる。
        for (int exeIndex = 0; exeIndex < maxIteration; exeIndex++)
        {
            Map<Integer, List<KmeansPoint>> assignments = Maps.newHashMap();
            for (int centroidIndex = 0; centroidIndex < clusterNum; centroidIndex++)
            {
                assignments.put(centroidIndex, Lists.<KmeansPoint> newArrayList());
            }

            for (KmeansPoint targetPoint : pointList)
            {
                KmeansResult result = nearestCentroid(targetPoint, centroids);
                assignments.get(result.getCentroidIndex()).add(targetPoint);
            }

            List<KmeansPoint> newCentroids = Lists.newArrayList();
            for (Map.Entry<Integer, List<KmeansPoint>> entry : assignments.entrySet())
            {
                if (entry.getValue().isEmpty())
                {
                    newCentroids.add(centroids.get(entry.getKey()));
                }
                else
                {
                    newCentroids.add(calculateCentroid(entry.getValue()));
                }

                clusteredNum[entry.getKey()] = entry.getValue().size();
            }

            boolean isConvergenced = isConvergenced(centroids, newCentroids, convergenceThres);
            centroids = newCentroids;

            if (isConvergenced == true)
            {

                break;
            }
        }

        double[][] centroidPoints = new double[clusterNum][];

        for (int centroidIndex = 0; centroidIndex < clusterNum; centroidIndex++)
        {
            centroidPoints[centroidIndex] = centroids.get(centroidIndex).getDataPoint();
        }

        KmeansDataSet createdModel = new KmeansDataSet();
        createdModel.setCentroids(centroidPoints);
        createdModel.setClusteredNum(clusteredNum);
        return createdModel;
    }
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_);
    }
1241522
def init_random(X, n_clusters, random_state):
    """"""
    logger.info("Initializing randomly")
    idx = sorted(draw_seed(random_state, 0, len(X), size=n_clusters))
    centers = X[idx].compute()
    return centers
1192509
public static clusterinstance[] get(nitro_service service) throws Exception{
		clusterinstance obj = new clusterinstance();
		clusterinstance[] response = (clusterinstance[])obj.get_resources(service);
		return response;
	}
224037
public void setClusters(java.util.Collection<Cluster> clusters) {
        if (clusters == null) {
            this.clusters = null;
            return;
        }

        this.clusters = new java.util.ArrayList<Cluster>(clusters);
    }
1050612
def cluster(points, radius):
    
    if isinstance(points, vtk.vtkActor):
        poly = points.GetMapper().GetInput()
    else:
        src = vtk.vtkPointSource()
        src.SetNumberOfPoints(len(points))
        src.Update()
        vpts = src.GetOutput().GetPoints()
        for i, p in enumerate(points):
            vpts.SetPoint(i, p)
        poly = src.GetOutput()

    cluster = vtk.vtkEuclideanClusterExtraction()
    cluster.SetInputData(poly)
    cluster.SetExtractionModeToAllClusters()
    cluster.SetRadius(radius)
    cluster.ColorClustersOn()
    cluster.Update()

    idsarr = cluster.GetOutput().GetPointData().GetArray("ClusterId")
    Nc = cluster.GetNumberOfExtractedClusters()

    sets = [[] for i in range(Nc)]
    for i, p in enumerate(points):
        sets[idsarr.GetValue(i)].append(p)

    acts = []
    for i, aset in enumerate(sets):
        acts.append(vs.Points(aset, c=i))

    actor = Assembly(acts)

    actor.info["clusters"] = sets
    print("Nr. of extracted clusters", Nc)
    if Nc > 10:
        print("First ten:")
    for i in range(Nc):
        if i > 9:
            print("...")
            break
        print("Cluster #" + str(i) + ",  N =", len(sets[i]))
    print("Access individual clusters through attribute: actor.cluster")
    return actor
79833
public Cluster getCluster(String clusterId, String zoneId) {
    Cluster response = null;
    for (Cluster cluster : getClusters().getClustersList()) {
      if (cluster.getName().endsWith("/clusters/" + clusterId)
          && cluster.getLocation().endsWith("/locations/" + zoneId)) {
        if (response == null) {
          response = cluster;
        } else {
          throw new IllegalStateException(
              String.format("Got multiple clusters named %s in zone %z.", clusterId, zoneId));
        }
      }
    }
    return Preconditions.checkNotNull(response,
      String.format("Cluster %s in zone %s was not found.", clusterId, zoneId));
  }
1343327
function cluster(points) {
    // number of clusters has to be smaller or equal the number of data points
    if (points.length < k) {
      throw 'Too many clusters';
    }

    // create the initial clusters
    var clusters = chooseInitialCenters(points);

    // create an array containing the latest assignment of a point to a cluster
    // no need to initialize the array, as it will be filled with the first assignment
    var assignments = new Int32Array(points.length);
    assignPointsToClusters(clusters, points, assignments);
    // iterate through updating the centers until we're done
    var max = (maxIterations < 0) ? Number.MAX_VALUE : maxIterations;
    for (var count = 0; count < max; count++) {
      var emptyCluster = false;
      var newClusters = [];
      for (var clusterIndex = 0; clusterIndex < clusters.length; clusterIndex++) {
        var cluster = clusters[clusterIndex];
        var newCenter;
        if (cluster.getPoints().length === 0) {
          newCenter = getPointFromLargestVarianceCluster(clusters);
          emptyCluster = true;
        } else {
          newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().getPoint().size());
        }
        newClusters.push(new CentroidCluster(newCenter));
      }
      var changes = assignPointsToClusters(newClusters, points, assignments);
      clusters = newClusters;

      // if there were no more changes in the point-to-cluster assignment
      // and there are no empty clusters left, return the current clusters
      if (changes === 0 && !emptyCluster) {
        return clusters;
      }
    }
    return clusters;
  }
953832
public long getRangeFrom() {
		final long limit = (liveUpdated ? database.getStorage().getClusterDataRange(current.clusterId)[1] : firstClusterPosition) - 1;
		if (rangeFrom > -1)
			return Math.max(rangeFrom, limit);
		return limit;
	}
117828
public Cluster setCluster(Cluster newCluster) {
        // 开始切换
        Cluster old = this.cluster;
        this.cluster = newCluster;
        return old;
    }
904997
public long allocAppend(long cluster)
            throws IOException {
        
        testCluster(cluster);
        
        while (!isEofCluster(entries[(int) cluster])) {
            cluster = entries[(int) cluster];
        }
        
        long newCluster = allocNew();
        entries[(int) cluster] = newCluster;

        return newCluster;
    }
1135592
@Override
    public Cluster createClusterScope() throws PageException {
	Cluster cluster = null;
	try {
	    if (Reflector.isInstaneOf(getClusterClass(), Cluster.class)) {
		cluster = (Cluster) ClassUtil.loadInstance(getClusterClass(), ArrayUtil.OBJECT_EMPTY);
		cluster.init(this);
	    }
	    else if (Reflector.isInstaneOf(getClusterClass(), ClusterRemote.class)) {
		ClusterRemote cb = (ClusterRemote) ClassUtil.loadInstance(getClusterClass(), ArrayUtil.OBJECT_EMPTY);

		cluster = new ClusterWrap(this, cb);
		// cluster.init(cs);
	    }
	}
	catch (Exception e) {
	    throw Caster.toPageException(e);
	}
	return cluster;
    }
532275
public long getRangeTo() {
		final long limit = (liveUpdated ? database.getStorage().getClusterDataRange(current.clusterId)[1] : lastClusterPosition) + 1;
		if (rangeTo > -1)
			return Math.min(rangeTo, limit);
		return limit;
	}
1311401
public void setClusterStates(java.util.Collection<String> clusterStates) {
        if (clusterStates == null) {
            this.clusterStates = null;
            return;
        }

        this.clusterStates = new com.amazonaws.internal.SdkInternalList<String>(clusterStates);
    }
1194574
public List<Cluster> cluster(final Collection<Point2D> points) {
    	final List<Cluster> clusters = new ArrayList<Cluster>();
        final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();

        KDTree<Point2D> tree = new KDTree<Point2D>(2);
        
        // Populate the kdTree
        for (final Point2D point : points) {
        	double[] key = {point.x, point.y};
        	tree.insert(key, point);
        }
                
        for (final Point2D point : points) {
            if (visited.get(point) != null) {
                continue;
            }
            final List<Point2D> neighbors = getNeighbors(point, tree);
            if (neighbors.size() >= minPoints) {
                // DBSCAN does not care about center points
                final Cluster cluster = new Cluster(clusters.size());
                clusters.add(expandCluster(cluster, point, neighbors, tree, visited));
            } else {
                visited.put(point, PointStatus.NOISE);
            }
        }

        for (Cluster cluster : clusters) {
        	cluster.calculateCentroid();
        }
        
        return clusters;
    }