Calculate the hierarchical clustering and store it in dendrogram array
This is the naive implementation (o(n3)) of single linkage clustering as outlined in wikipedia:
http://en.wikipedia.org/wiki/Single-linkage_clustering
184453
private void clusterIt() {

		dendrogram = new LinkedPair[numItems-1];


		logger.debug("Initial matrix: \n"+matrixToString());


		for (int m=0;m<numItems-1;m++) {

			updateIndicesToCheck(m);
			LinkedPair pair = getClosestPair();
			merge(pair);
			dendrogram[m] = pair;

			//if (debug) {
			//	System.out.println("Matrix after iteration "+m+" (merged "+pair.getFirst()+","+pair.getSecond()+")");
			//	printMatrix();
			//}
		}

	}
755027
def computeNodeLinks(cls, element, graph):
        
        index = element.nodes.kdims[-1]
        node_map = {}
        if element.nodes.vdims:
            values = zip(*(element.nodes.dimension_values(d)
                           for d in element.nodes.vdims))
        else:
            values = cycle([tuple()])
        for index, vals in zip(element.nodes.dimension_values(index), values):
            node = {'index': index, 'sourceLinks': [], 'targetLinks': [], 'values': vals}
            graph['nodes'].append(node)
            node_map[index] = node

        links = [element.dimension_values(d) for d in element.dimensions()[:3]]
        for i, (src, tgt, value) in enumerate(zip(*links)):
            source, target = node_map[src], node_map[tgt]
            link = dict(index=i, source=source, target=target, value=value)
            graph['links'].append(link)
            source['sourceLinks'].append(link)
            target['targetLinks'].append(link)
473730
def adjacency(tree):
    
    dd = ids(tree)
    N = len(dd)
    A = np.zeros((N, N))

    def _adj(node):
        if np.isscalar(node):
            return
        elif isinstance(node, tuple) and len(node) == 2:
            A[dd[node], dd[node[0]]] = 1
            A[dd[node[0]], dd[node]] = 1
            _adj(node[0])

            A[dd[node], dd[node[1]]] = 1
            A[dd[node[1]], dd[node]] = 1
            _adj(node[1])

    _adj(tree)
    return A
99191
def n_forking_points(neurites, neurite_type=NeuriteType.all):
    ''''''
    return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.iforking_point)
476501
public Clustering<DendrogramModel> run(PointerHierarchyRepresentationResult pointerresult) {
    Clustering<DendrogramModel> result = new Instance(pointerresult).run();
    result.addChildResult(pointerresult);
    return result;
  }
135212
double[][] initial_centers(KMeansModel model, final Vec[] vecs, final double[] means, final double[] mults, final int[] modes, int k) {

      // Categoricals use a different distance metric than numeric columns.
      model._output._categorical_column_count=0;
      _isCats = new String[vecs.length][];
      for( int v=0; v<vecs.length; v++ ) {
        _isCats[v] = vecs[v].isCategorical() ? new String[0] : null;
        if (_isCats[v] != null) model._output._categorical_column_count++;
      }
      Random rand = water.util.RandomUtils.getRNG(_parms._seed-1);
      double centers[][];    // Cluster centers
      if( null != _parms._user_points ) { // User-specified starting points
        Frame user_points = _parms._user_points.get();
        int numCenters = (int)user_points.numRows();
        int numCols = model._output.nfeatures();
        centers = new double[numCenters][numCols];
        Vec[] centersVecs = user_points.vecs();
        // Get the centers and standardize them if requested
        for (int r=0; r<numCenters; r++) {
          for (int c=0; c<numCols; c++){
            centers[r][c] = centersVecs[c].at(r);
            centers[r][c] = Kmeans_preprocessData(centers[r][c], c, means, mults, modes);
          }
        }
      }
      else { // Random, Furthest, or PlusPlus initialization
        if (_parms._init == Initialization.Random) {
          // Initialize all cluster centers to random rows
          centers = new double[k][model._output.nfeatures()];
          for (double[] center : centers)
            randomRow(vecs, rand, center, means, mults, modes);
        } else {
          centers = new double[1][model._output.nfeatures()];
          // Initialize first cluster center to random row
          randomRow(vecs, rand, centers[0], means, mults, modes);

          model._output._iterations = 0;
          while (model._output._iterations < 5) {
            // Sum squares distances to cluster center
            SumSqr sqr = new SumSqr(centers, means, mults, modes, _isCats).doAll(vecs);

            // Sample with probability inverse to square distance
            Sampler sampler = new Sampler(centers, means, mults, modes, _isCats, sqr._sqr, k * 3, _parms.getOrMakeRealSeed(), hasWeightCol()).doAll(vecs);
            centers = ArrayUtils.append(centers, sampler._sampled);

            // Fill in sample centers into the model
            model._output._centers_raw = destandardize(centers, _isCats, means, mults);
            model._output._tot_withinss = sqr._sqr / _train.numRows();

            model._output._iterations++;     // One iteration done

            model.update(_job); // Make early version of model visible, but don't update progress using update(1)
            if (stop_requested()) {
              if (timeout())
                warn("_max_runtime_secs reached.", "KMeans exited before finishing all iterations.");
              break; // Stopped/cancelled
            }
          }
          // Recluster down to k cluster centers
          centers = recluster(centers, rand, k, _parms._init, _isCats);
          model._output._iterations = 0; // Reset iteration count
        }
      }
      assert(centers.length == k);
      return centers;
    }
980034
@Reference(authors = "D. Pelleg, A. Moore", //
      title = "X-means: Extending K-means with Efficient Estimation on the Number of Clusters", //
      booktitle = "Proc. 17th Int. Conf. on Machine Learning (ICML 2000)", //
      url = "http://www.pelleg.org/shared/hp/download/xmeans.ps", //
      bibkey = "DBLP:conf/icml/PellegM00")
  public static <V extends NumberVector> double logLikelihood(Relation<V> relation, Clustering<? extends MeanModel> clustering, NumberVectorDistanceFunction<? super V> distanceFunction) {
    List<? extends Cluster<? extends MeanModel>> clusters = clustering.getAllClusters();
    // number of clusters
    final int m = clusters.size();

    // number of objects in the clustering
    int n = 0;
    // cluster sizes
    int[] n_i = new int[m];
    // total variance
    double d = 0.;
    // variances
    double[] d_i = new double[m];

    // Iterate over clusters:
    Iterator<? extends Cluster<? extends MeanModel>> it = clusters.iterator();
    for(int i = 0; it.hasNext(); ++i) {
      Cluster<? extends MeanModel> cluster = it.next();
      n += n_i[i] = cluster.size();
      d += d_i[i] = varianceOfCluster(cluster, distanceFunction, relation);
    }

    // No remaining variance, if every point is on its own:
    if(n <= m) {
      return Double.NEGATIVE_INFINITY;
    }

    // Total variance (corrected for bias)
    final double logv = FastMath.log(d / (n - m));

    final int dim = RelationUtil.dimensionality(relation);
    // log likelihood of this clustering
    double logLikelihood = 0.;

    // Aggregate
    for(int i = 0; i < m; i++) {
      logLikelihood += n_i[i] * FastMath.log(n_i[i]) // Post. entropy Rn log Rn
          - n_i[i] * .5 * MathUtil.LOGTWOPI // Rn/2 log2pi
          - n_i[i] * dim * .5 * logv // Rn M/2 log sigma^2
          - (d_i[i] - m) * .5; // (Rn-K)/2
    }
    logLikelihood -= n * FastMath.log(n); // Prior entropy, sum_i Rn log R
    return logLikelihood;
  }
1224654
def cluster_nodes(self, tol=0.2):
        
        lattice = self.structure.lattice

        vfcoords = [v.frac_coords for v in self.vnodes]

        # Manually generate the distance matrix (which needs to take into
        # account PBC.
        dist_matrix = np.array(lattice.get_all_distances(vfcoords, vfcoords))
        dist_matrix = (dist_matrix + dist_matrix.T) / 2
        for i in range(len(dist_matrix)):
            dist_matrix[i, i] = 0
        condensed_m = squareform(dist_matrix)
        z = linkage(condensed_m)
        cn = fcluster(z, tol, criterion="distance")
        merged_vnodes = []
        for n in set(cn):
            poly_indices = set()
            frac_coords = []
            for i, j in enumerate(np.where(cn == n)[0]):
                poly_indices.update(self.vnodes[j].polyhedron_indices)
                if i == 0:
                    frac_coords.append(self.vnodes[j].frac_coords)
                else:
                    fcoords = self.vnodes[j].frac_coords
                    # We need the image to combine the frac_coords properly.
                    d, image = lattice.get_distance_and_image(frac_coords[0],
                                                              fcoords)
                    frac_coords.append(fcoords + image)
            merged_vnodes.append(
                VoronoiPolyhedron(lattice, np.average(frac_coords, axis=0),
                                  poly_indices, self.coords))
        self.vnodes = merged_vnodes
        logger.debug("%d vertices after combination." % len(self.vnodes))
928549
def computeNodeValues(cls, graph):
        
        for node in graph['nodes']:
            source_val = np.sum([l['value'] for l in node['sourceLinks']])
            target_val = np.sum([l['value'] for l in node['targetLinks']])
            node['value'] = max([source_val, target_val])
657630
protected void determineNumberOfClusters() {
        if (!m_numberOfClustersDetermined
                && (m_cobwebTree != null)) {
            int[] numClusts = new int[1];
            numClusts[0] = 0;
            //  try {
            m_cobwebTree.assignClusterNums(numClusts);
            // }
            // catch (Exception e) {
//	e.printStackTrace();
//	numClusts[0] = 0;
            // }
            m_numberOfClusters = numClusts[0];

            m_numberOfClustersDetermined = true;
        }
    }
352691
protected void bicoCFUpdate(ClusteringTreeNode x) {
		// Starts with the global root node as the current root node
		ClusteringTreeNode r = this.root;
		int i = 1;
		while (true) {
			ClusteringTreeNode y = r.nearestChild(x.getCenter());
			// Checks if the node can not be merged to the current level
			if (r.hasNoChildren()
					|| y == null
					|| Metric.distanceSquared(x.getCenter(), y.getCenter()) > calcRSquared(i)) {
				// Adds the node to the current root node
				x.setThreshold(calcR(i));
				r.addChild(x);
				this.rootCount++;
				break;
			} else {
				// Checks if the node can be merged to the nearest node without
				// exceeding the global threshold
				if (y.getClusteringFeature().calcKMeansCosts(y.getCenter(),
						x.getClusteringFeature()) <= this.T) {
					// Merges the ClusteringFeature of the node to the
					// ClusteringFeature of the nearest node
					y.getClusteringFeature().merge(x.getClusteringFeature());
					break;
				} else {
					// Navigates one level down in the tree
					r = y;
					i++;
				}
			}
		}
	}
1170162
public int partition(int k, int minPts) {
        List<Neuron> data = new ArrayList<>();
        for (Neuron neuron : neurons) {
            neuron.y = OUTLIER;
            if (neuron.n >= minPts) {
                data.add(neuron);
            }
        }
        
        double[][] proximity = new double[data.size()][];
        for (int i = 0; i < data.size(); i++) {
            proximity[i] = new double[i + 1];
            for (int j = 0; j < i; j++) {
                proximity[i][j] = Math.distance(data.get(i).w, data.get(j).w);
            }
        }

        Linkage linkage = new UPGMALinkage(proximity);
        HierarchicalClustering hc = new HierarchicalClustering(linkage);
        int[] y = hc.partition(k);

        for (int i = 0; i < data.size(); i++) {
            data.get(i).y = y[i];
        }
        
        return data.size();
    }
39478
public ClusteringTreeNode nearestChild(double[] pointA) {
		assert (this.center.length == pointA.length);
		double minDistance = Double.POSITIVE_INFINITY;
		ClusteringTreeNode min = null;
		for (ClusteringTreeNode node : this.getChildren()) {
			double d = Metric.distance(pointA, node.getCenter());
			if (d < minDistance) {
				minDistance = d;
				min = node;
			}
		}
		return min;
	}
909152
def _build_tree(self):
        
        #find unassigned i*
        istar = np.argmin(self._x)

        #compute distances
        self._d = self.c[istar] - self._v
        _pred = np.zeros(self.n, dtype=np.int) + istar

        #initialize sets
        #READY: set of nodes visited and in the path (whose price gets
        #updated in augment)
        #SCAN: set of nodes at the bottom of the tree, which we need to
        #look at
        #T0DO: unvisited nodes
        _ready = np.zeros(self.n, dtype=np.bool)
        _scan = np.zeros(self.n, dtype=np.bool)
        _todo = np.zeros(self.n, dtype=np.bool) + True

        while True:
            #populate scan with minimum reduced distances
            if True not in _scan:
                mu = np.min(self._d[_todo])
                _scan[self._d == mu] = True
                _todo[_scan] = False
                j = np.argmin(self._y * _scan)
                if self._y[j] == -1 and _scan[j]:
                    return _pred, _ready, istar, j, mu

            #pick jstar from scan (scan always has at least 1)
            _jstar = np.argmax(_scan)

            #pick i associated with jstar
            i = self._y[_jstar]

            _scan[_jstar] = False
            _ready[_jstar] = True

            #find shorter distances
            newdists = mu + self.cred[i, :]
            shorter = np.logical_and(newdists < self._d, _todo)

            #update distances
            self._d[shorter] = newdists[shorter]

            #update predecessors
            _pred[shorter] = i

            for j in np.nonzero(np.logical_and(self._d == mu, _todo))[0]:
                if self._y[j] == -1:
                    return _pred, _ready, istar, j, mu
                _scan[j] = True
                _todo[j] = False
1180216
function clusterByNeighbor(points) {
    const sorted = points.slice().sort((a, b) => {
        if (a.y < b.y) {
            return -1;
        } else if (a.y > b.y) {
            return 1;
        } else {
            if (a.x < b.x) {
                return -1;
            } else if (a.x > b.x) {
                return 1;
            } else {
                return 0;
            }
        }
    });

    const cluster = sorted.reduce((sets, point) => {
        const setContainingNeighbors = sets.find(set => set.some((setPoint) => {
            return getNeighbors(setPoint).some(spn => areEqual(spn, point));
        }));

        if (setContainingNeighbors) {
            setContainingNeighbors.push(point);
        } else {
            sets.push([point]);
        }

        return sets;
    }, []);

    return cluster;
}
320124
def _dendropy_to_dataframe(
    tree,
    add_node_labels=True,
    use_uids=True):
    """"""
    # Maximum distance from root.
    tree.max_distance_from_root()

    # Initialize the data object.
    idx = []
    data = {
        'type': [],
        'id': [],
        'parent': [],
        'length': [],
        'label': [],
        'distance': []}

    if use_uids:
        data['uid'] = []

    # Add labels to internal nodes if set to true.
    if add_node_labels:
        for i, node in enumerate(tree.internal_nodes()):
            node.label = str(i)

    for node in tree.nodes():
        # Get node type
        if node.is_leaf():
            type_ = 'leaf'
            label = str(node.taxon.label).replace(' ', '_')
        elif node.is_internal():
            type_ = 'node'
            label = str(node.label)

        # Set node label and parent.
        id_ = label
        parent_node = node.parent_node
        length = node.edge_length
        distance = node.distance_from_root()

        # Is this node a root?
        if parent_node is None and length is None:
            parent_label = None
            parent_node = None
            length = 0
            distance = 0
            type_ = 'root'

        # Set parent node label
        elif parent_node.is_internal():
            parent_label = str(parent_node.label)

        else:
            raise Exception("Subtree is not attached to tree?")

        # Add this node to the data.
        data['type'].append(type_)
        data['id'].append(id_)
        data['parent'].append(parent_label)
        data['length'].append(length)
        data['label'].append(label)
        data['distance'].append(distance)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Construct dataframe.
    df = pandas.DataFrame(data)
    return df
780374
function cluster(k) {
                var Centroids = this.createCentroids(k);
                var LastDistances = Matrix$d.Zero(this.Observations.rows(), this.Observations.cols());
                var Distances = this.distanceFrom(Centroids);
                var Groups;

                while(!(LastDistances.eql(Distances))) {
                Groups = Distances.minColumnIndexes();
                LastDistances = Distances;

                var newCentroids = [];

                for(var i = 1; i <= Centroids.rows(); i++) {
                    var centroid = [];

                    for(var j = 1; j <= Centroids.cols(); j++) {
                    var sum = 0;
                    var count = 0;

                    for(var l = 1; l <= this.Observations.rows(); l++) {
                        if(Groups.e(l) == i) {
                        count++;
                        sum += this.Observations.e(l, j);
                        }
                    }

                    centroid.push(sum / count);
                    }

                    newCentroids.push(centroid);
                }

                Centroids = $M(newCentroids);
                Distances = this.distanceFrom(Centroids);
                }

                return Groups;
            }