Initialises the clusters by distributing the items from the data.
        evenly across n clusters

        :param input_: the data set (a list of tuples).
        :param clustercount: the amount of clusters (n).
975839
def initialise_clusters(self, input_, clustercount):
        
        # initialise the clusters with empty lists
        self.__clusters = []
        for _ in range(clustercount):
            self.__clusters.append([])

        # distribute the items into the clusters
        count = 0
        for item in input_:
            self.__clusters[count % clustercount].append(item)
            count += 1
76600
def addClusterId(self,line):
        
        if isinstance(line,dict):
            jsonObj = line
        else:
            jsonObj = json.loads(line)
        concat_str=''
        for item in jsonObj['cluster']:
            concat_str += item['uri']
        cluster_id = "http://dig.isi.edu/ht/data/" + str(hash(concat_str)% 982451653)
        for item in jsonObj['cluster']:
            item['cluster_id']=cluster_id
            yield item
686334
def map_cluster(events, cluster):
    
    cluster = np.ascontiguousarray(cluster)
    events = np.ascontiguousarray(events)
    mapped_cluster = np.zeros((events.shape[0], ), dtype=dtype_from_descr(data_struct.ClusterInfoTable))
    mapped_cluster = np.ascontiguousarray(mapped_cluster)
    analysis_functions.map_cluster(events, cluster, mapped_cluster)
    return mapped_cluster
938741
public static <T> DataSet<Tuple2<Integer, Long>> countElementsPerPartition(DataSet<T> input) {
		return input.mapPartition(new RichMapPartitionFunction<T, Tuple2<Integer, Long>>() {
			@Override
			public void mapPartition(Iterable<T> values, Collector<Tuple2<Integer, Long>> out) throws Exception {
				long counter = 0;
				for (T value : values) {
					counter++;
				}
				out.collect(new Tuple2<>(getRuntimeContext().getIndexOfThisSubtask(), counter));
			}
		});
	}
513323
def cluster(args):
    

    args = _check_args(args)
    read_stats_file = op.join(args.dir_out, "read_stats.tsv")
    if file_exists(read_stats_file):
        os.remove(read_stats_file)

    bam_file, seq_obj = _clean_alignment(args)

    logger.info("Parsing matrix file")
    seqL, y, l = parse_ma_file(seq_obj, args.ffile)
    # y, l = _total_counts(seqL.keys(), seqL)
    logger.info("counts after: %s" % sum(y.values()))
    logger.info("# sequences after: %s" % l)
    dt = pd.DataFrame({'sample': y.keys(), 'counts': y.values()})
    dt['step'] = 'aligned'
    dt.to_csv(read_stats_file, sep="\t", index=False, header=False, mode='a')

    if len(seqL.keys()) < 10:
        logger.error("It seems you have low coverage. Please check your fastq files have enough sequences.")
        raise ValueError("So few sequences.")

    logger.info("Cleaning bam file")
    y, l = _total_counts(seqL.keys(), seqL)
    logger.info("counts after: %s" % sum(y.values()))
    logger.info("# sequences after: %s" % l)
    dt = pd.DataFrame({'sample': y.keys(), 'counts': y.values()})
    dt['step'] = 'cleaned'
    dt.to_csv(read_stats_file, sep="\t", index=False, header=False, mode='a')

    clusL = _create_clusters(seqL, bam_file, args)
    y, l = _total_counts(clusL.seq.keys(), clusL.seq, aligned=True)
    logger.info("counts after: %s" % sum(y.values()))
    logger.info("# sequences after: %s" % l)
    dt = pd.DataFrame({'sample': y.keys(), 'counts': y.values()})
    dt['step'] = 'clusters'
    dt.to_csv(read_stats_file, sep="\t", index=False, header=False, mode='a')

    logger.info("Solving multi-mapping events in the network of clusters")
    clusLred = _cleaning(clusL, args.dir_out)
    y, l = _total_counts(clusLred.clus, seqL)
    logger.info("counts after: %s" % sum(y.values()))
    logger.info("# sequences after: %s" % l)
    dt = pd.DataFrame({'sample': y.keys(), 'counts': y.values()})
    dt['step'] = 'meta-cluster'
    dt.to_csv(read_stats_file, sep="\t", index=False, header=False, mode='a')
    logger.info("Clusters up to %s" % (len(clusLred.clus.keys())))

    if args.show:
        logger.info("Creating sequences alignment to precursor")
        clusLred = show_seq(clusLred, args.index)

    clusLred = peak_calling(clusLred)

    clusLred = _annotate(args, clusLred)

    logger.info("Creating json and count matrix")
    json_file = _create_json(clusLred, args)

    logger.info("Output file in: %s" % args.dir_out)

    if args.db:
        name = args.db + ".db"
        logger.info("Create database: database/" + name)
        data = load_data(json_file)
        out_dir = op.join(args.dir_out, "database")
        make_database(data, name, out_dir)
    logger.info("Finished")
1182854
def _kmeans_init(X, n_clusters, method='balanced', rng=None):
    
    n_samples = X.shape[0]
    if rng is None:
        cent_idx = np.random.choice(n_samples, replace=False, size=n_clusters)
    else:
        #print('Generate random centers using RNG')
        cent_idx = rng.choice(n_samples, replace=False, size=n_clusters)
    
    centers = X[cent_idx,:]
    mean_X = np.mean(X, axis=0)
    
    if method == 'balanced':
        centers[n_clusters-1] = n_clusters*mean_X - np.sum(centers[:(n_clusters-1)], axis=0)
    
    return (centers)
1077290
def build_input_partitions(cls, name='inputTablePartitions', input_name='input'):
        
        obj = cls(name)
        obj.exporter = 'get_input_partitions'
        obj.input_name = input_name
        return obj
885522
def _assign_clusters(X, centers):
    
    dist2cents = scipy.spatial.distance.cdist(X, centers, metric='seuclidean')
    membs = np.argmin(dist2cents, axis=1)

    return(membs)
565976
def countContigClusters(clus)
      cur = clus; nxt = 0
      loop do
        nxt = getFatEntry(cur)
        break if nxt != cur + 1
        cur = nxt; redo
      end
      raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED
      cur - clus + 1
    end
399329
private static void initialize(Storage storage, String counterId) {
    LOG.debug("Initializing counter shards for resource {}", counterId);
    for (int startIndex = 0; startIndex < NUM_SHARDS; startIndex += TRANSACTION_GROUP_SIZE) {
      initShardRange(storage, counterId, startIndex,
                     Math.min(NUM_SHARDS, startIndex + TRANSACTION_GROUP_SIZE));
    }
  }
673899
private static void clusterIteration(Matrix matrix,
                                         int numClusters,
                                         KMeansSeed seedType,
                                         CriterionFunction criterion) {
        DoubleVector[] centers = seedType.chooseSeeds(numClusters, matrix);

        // Compute the initial set of assignments for each data point based on
        // the initial assignments.
        int[] initialAssignments = new int[matrix.rows()];

        // If there is to be only one cluster, then everything will be auto
        // assigned to the first cluster.  This is just a special case that only
        // comes up when comparing other solutions to the non-solution.
        if (numClusters != 1) {
            int nc = 0;
            for (int i = 0; i < matrix.rows(); ++i) {

                DoubleVector vector = matrix.getRowVector(i);
                double bestSimilarity = 0;
                for (int c = 0; c < numClusters; ++c) {
                    double similarity = Similarity.cosineSimilarity(
                            centers[c], vector);
                    nc++;
                    if (similarity >= bestSimilarity) {
                        bestSimilarity = similarity;
                        initialAssignments[i] = c;
                    }
                }
            }
        }

        // Setup the criterion function with it's meta data.
        criterion.setup(matrix, initialAssignments, numClusters);

        // Iteratively swap each data point to a better cluster if such an
        // assignment exists.
        List<Integer> indices = new ArrayList<Integer>(matrix.rows());
        for (int i = 0; i < matrix.rows(); ++i)
            indices.add(i);

        // Iterate through each data point in random order.  For each data
        // point, try to assign it to a new cluster.  If no data point is moved
        // in an iteration, end the iterations.
        boolean changed = true;
        while (changed) {
            changed = false;
            Collections.shuffle(indices);
            for (int index : indices)
                changed |= criterion.update(index);
        }
    }
506760
protected void initialize(T input , GrayS32 output ) {
		this.graph = output;
		final int N = input.width*input.height;

		regionSize.resize(N);
		threshold.resize(N);
		for( int i = 0; i < N; i++ ) {
			regionSize.data[i] = 1;
			threshold.data[i] = K;
			graph.data[i] = i; // assign a unique label to each pixel since they are all their own region initially
		}

		edges.reset();
		edgesNotMatched.reset();
	}
1164491
public void initialize( List<Point> dataSet ) {
		bestFitPoints.clear();

		if( dataSet.size() > matchToInput.length ) {
			matchToInput = new int[ dataSet.size() ];
			bestMatchToInput = new int[ dataSet.size() ];
		}
	}
477413
public void setInput(INDArray input) {
        this.input = input;
        if (this.layers == null) {
            init();
        }
        if (input != null) {
            if (input.length() == 0)
                throw new IllegalArgumentException(
                        "Invalid input: length 0 (shape: " + Arrays.toString(input.shape()) + ")");

            // FIXME: int cast
            setInputMiniBatchSize((int) input.size(0));
        }
    }
1295837
def random_init_map(interface, state, label, inp):
    """"""
    import random
    out = interface.output(0)
    centers = {}

    for row in inp:
        row = row.strip().split(state["delimiter"])
        if len(row) > 1:
            x = [(0 if row[i] in state["missing_vals"] else float(row[i])) for i in state["X_indices"]]
            cluster = random.randint(0, state['k'] - 1)
            vertex = state['create'](x, 1.0)
            centers[cluster] = vertex if cluster not in centers else state["update"](centers[cluster], vertex)
    for cluster, values in centers.iteritems():
        out.add(cluster, values)
711046
def _init_mixture_params(X, n_mixtures, init_method):
    

    init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures

    if init_method == 'kmeans':
        km = _kmeans.KMeans(n_clusters = n_mixtures, n_trials=20)
        km.fit(X)
        init_means = km.centers_ 
    else:
        inx_rand = np.random.choice(X.shape[0], size=n_mixtures)
        init_means = X[inx_rand,:]
 
  
    if np.any(np.isnan(init_means)):
        raise ValueError("Init means are NaN! ") 

    n_features = X.shape[1]
    init_covars = np.empty(shape=(n_mixtures, n_features, n_features), dtype=float)
    for i in range(n_mixtures):
        init_covars[i] = np.eye(n_features)

    return(init_priors, init_means, init_covars)
875687
private void clusterDown(){
		int classIndex = this.ltm.classIndex();
		for (int c = 0; c <= this.maxClassValue; c++){
			List<double[]> classSamples = new ArrayList<>();
			for (int i = this.ltm.numInstances()-1; i >-1 ; i--) {
				if (this.ltm.get(i).classValue() == c) {
					classSamples.add(this.ltm.get(i).toDoubleArray());
					this.ltm.delete(i);
				}
			}
			if (classSamples.size() > 0) {
				//used kMeans++ implementation expects the weight of each sample at the first index,
				// make sure that the first value gets the uniform weight 1, overwrite class value
				for (double[] sample : classSamples) {
					if (classIndex != 0) {
						sample[classIndex] = sample[0];
					}
					sample[0] = 1;
				}

				List<double[]> centroids = this.kMeans(classSamples, Math.max(classSamples.size() / 2, 1));

				for (double[] centroid : centroids) {

					double[] attributes = new double[this.ltm.numAttributes()];
					//returned centroids do not contain the weight anymore, but simply the data
					System.arraycopy(centroid, 0, attributes, 1, this.ltm.numAttributes() - 1);
					//switch back if necessary
					if (classIndex != 0) {
						attributes[0] = attributes[classIndex];
					}
					attributes[classIndex] = c;
					Instance inst = new InstanceImpl(1, attributes);
					inst.setDataset(this.ltm);
					this.ltm.add(inst);
				}
			}

		}
	}