Recursive function for dendrogram line computations
198174
def _generate_dendro(self, current_section, spacing, offsets):
        '''
        '''
        max_dims = self._max_dims
        start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])

        for child in current_section.children:

            segments = child.points

            # number of leaves in child
            terminations = _n_terminations(child)

            # segement lengths
            seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
                                                     segments[1:, COLS.XYZ]), axis=1)

            # segment radii
            radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
                if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))

            y_offset = offsets[1]
            for i, slen in enumerate(seg_lengths):

                # offset update for the vertical segments
                new_offsets = _update_offsets(start_x, spacing, terminations,
                                              (offsets[0], y_offset), slen)

                # segments are drawn vertically, thus only y_offset changes from init offsets
                self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
                                                              new_offsets, spacing, radii[i, :])
                self._n += 1
                y_offset = new_offsets[1]

            if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
                max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)

            self._max_dims = max_dims
            # recursive call to self.
            self._generate_dendro(child, spacing, new_offsets)

            # update the starting position for the next child
            start_x += terminations * spacing[0]

            # write the horizontal lines only for bifurcations, where the are actual horizontal
            # lines and not zero ones
            if offsets[0] != new_offsets[0]:

                # horizontal segment. Thickness is either 0 if show_diameters is false
                # or 1. if show_diameters is true
                self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
                self._n += 1
435820
function tightTree(t, g) {
  function dfs(v) {
    _.forEach(g.nodeEdges(v), function(e) {
      var edgeV = e.v,
        w = (v === edgeV) ? e.w : edgeV;
      if (!t.hasNode(w) && !slack(g, e)) {
        t.setNode(w, {});
        t.setEdge(v, w, {});
        dfs(w);
      }
    });
  }

  _.forEach(t.nodes(), dfs);
  return t.nodeCount();
}
1263238
def face_adjacency_tree(self):
        
        # the (n,6) interleaved bounding box for every line segment
        segment_bounds = np.column_stack((
            self.vertices[self.face_adjacency_edges].min(axis=1),
            self.vertices[self.face_adjacency_edges].max(axis=1)))
        tree = util.bounds_tree(segment_bounds)
        return tree
911855
private void dfs() {
    Deque<Node> stack = new LinkedList<>();
    stack.add(tree.getRootNode());
    while (!stack.isEmpty()) {
      Node node = stack.removeLast();
      node.startSize = list.size();
      if (node.getEdges().isEmpty()) {
        // leaf
        list.add(node.depth);
        node.endSize = list.size();
      } else {
        if (!node.equals(tree.getRootNode())) {
          // inner node = not leaf and not root
          innerNodes.add(node);
        }
        for (Edge edge : node.getEdges()) {
          Node endNode = edge.getEndNode();
          endNode.depth = node.depth + edge.getSpan() + 1;
          stack.addLast(endNode);
        }
      }
    }
    // At this point all inner nodes are ordered by the time of entering, so we visit them from last to first
    ListIterator<Node> iterator = innerNodes.listIterator(innerNodes.size());
    while (iterator.hasPrevious()) {
      Node node = iterator.previous();
      int max = -1;
      for (Edge edge : node.getEdges()) {
        max = Math.max(edge.getEndNode().endSize, max);
      }
      node.endSize = max;
    }
  }
1328796
def plot_dendrogram(self, nclusters=None, leaf_font_size=8, leaf_rotation=90, names=None,
                        title_font_size=16, ):
        

        if not hasattr(self, 'nclusters') and not hasattr(self, 'linkmat'):
            raise ValueError("This instance has no plottable information.")

        if nclusters is None:
            nclusters = self.nclusters

        threshold = _get_threshold(self.linkmat, nclusters)

        import matplotlib.pyplot as plt
        fig = plt.figure(figsize=(11.7, 8.3))

        if names is not None:
            labfn=lambda leaf: names[leaf]
        else:
            labfn=None
            leaf_rotation=0

        dendrogram(
            self.linkmat,
            color_threshold=threshold,
            leaf_font_size=leaf_font_size,
            leaf_rotation=leaf_rotation,
            leaf_label_func=labfn,
            count_sort=True,
            )

        plt.suptitle('Dendrogram', fontsize=title_font_size)
        # plt.title('Distance metric: {0}    Linkage method: {1}    Number of classes: {2}'.format(compound_key[0],
        #           compound_key[1], compound_key[2]), fontsize=12)
        plt.axhline(threshold, color='grey', ls='dashed')
        plt.xlabel('Gene')
        plt.ylabel('Distance')
        return fig
1016750
function indegree(node){
    var degree = 0;
    function check(v){
      if(v === node){
        degree++;
      }
    }
    Object.keys(edges).forEach(function (u){
      edges[u].forEach(check);
    });
    return degree;
  }
635218
def _L(dfs_data):
    """L(T) = {v | the first w in Adj[v] corresponds to a frond vw}."""
    node_set = set()
    for v, adj in list(dfs_data['adj'].items()):
        w = adj[0]
        if is_frond(v, w, dfs_data):
            node_set.add(v)
    return list(node_set)
1012862
def linear_variogram_model(m, d):
    """"""
    slope = float(m[0])
    nugget = float(m[1])
    return slope * d + nugget
81723
def avl_join_dir_recursive(t1, t2, node, direction):
    
    other_side = 1 - direction
    if _DEBUG_JOIN_DIR:
        print('--JOIN DIR (dir=%r) --' % (direction,))
        ascii_tree(t1, 't1')
        ascii_tree(t2, 't2')

    if direction == 0:
        large, small = t2, t1
    elif direction == 1:
        large, small = t1, t2
    else:
        assert False

    # Follow the spine of the larger tree
    spine = large[direction]
    rest = large[other_side]
    # k_, v_ = large.key, large.value

    hsmall = height(small)
    hspine = height(spine)
    hrest = height(rest)

    if _DEBUG_JOIN_DIR:
        ascii_tree(spine, 'spine')
        ascii_tree(rest, 'rest')
        ascii_tree(small, 'small')

    if hspine <= hsmall + 1:
        t_ = avl_new_top(small, spine, node, direction)
        if _DEBUG_JOIN_DIR:
            print('JOIN DIR (BASE)')
            ascii_tree(t_, 't_')
        if height(t_) <= hrest + 1:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 1)')
            return avl_new_top(t_, rest, large, direction)
        else:
            # Double rotation, but with a new node
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 2)')
            t_rotate = avl_rotate_single(t_, direction)
            if _DEBUG_JOIN_DIR:
                ascii_tree(t_rotate, 't_rotate')
                EulerTourTree(root=t_rotate)._assert_nodes('t_rotate')
            t_merge = avl_new_top(rest, t_rotate, large, other_side)
            if _DEBUG_JOIN_DIR:
                ascii_tree(t_merge, 't_merge')
                EulerTourTree(root=t_merge)._assert_nodes('t_merge')
            new_root = avl_rotate_single(t_merge, other_side)
            if _DEBUG_JOIN_DIR:
                ascii_tree(new_root, 'new_root')
                EulerTourTree(root=new_root)._assert_nodes('new_root')
            return new_root
    else:
        # Traverse down the spine in the appropriate direction
        if _DEBUG_JOIN_DIR:
            print('JOIN DIR (RECURSE)')
        if direction == 0:
            t_ = avl_join_dir_recursive(small, spine, node, direction)
        elif direction == 1:
            t_ = avl_join_dir_recursive(spine, t2, node, direction)
        else:
            raise AssertionError('invalid direction')
        t__ = avl_new_top(t_, rest, large, direction)
        if height(t_) <= hrest + 1:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 3)')
            return t__
        else:
            if _DEBUG_JOIN_DIR:
                print('JOIN DIR (Case 4)')
            return avl_rotate_single(t__, other_side)
    assert False, 'should never get here'
1331533
def add_mpl_dendrogram(dfr, fig, heatmap_gs, orientation="col"):
    
    # Row or column axes?
    if orientation == "row":
        dists = distance.squareform(distance.pdist(dfr))
        spec = heatmap_gs[1, 0]
        orient = "left"
        nrows, ncols = 1, 2
        height_ratios = [1]
    else:  # Column dendrogram
        dists = distance.squareform(distance.pdist(dfr.T))
        spec = heatmap_gs[0, 1]
        orient = "top"
        nrows, ncols = 2, 1
        height_ratios = [1, 0.15]

    # Create row dendrogram axis
    gspec = gridspec.GridSpecFromSubplotSpec(
        nrows,
        ncols,
        subplot_spec=spec,
        wspace=0.0,
        hspace=0.1,
        height_ratios=height_ratios,
    )
    dend_axes = fig.add_subplot(gspec[0, 0])
    dend = sch.dendrogram(
        sch.linkage(distance.squareform(dists), method="complete"),
        color_threshold=np.inf,
        orientation=orient,
    )
    clean_axis(dend_axes)
    return {"dendrogram": dend, "gridspec": gspec}
777092
function tree(d, i) {
    var nodes = hierarchy.call(this, d, i),
        t = nodes[0],
        wt = wrapTree(t);

    wroot = wt;
    zerothWalk(wt, 0);
    firstWalk(wt);
    secondWalk(wt, 0);
    renormalize(wt);

    return nodes;
  }
1288040
function tinf_decode_trees(d, lt, dt) {
  var hlit, hdist, hclen;
  var i, num, length;

  /* get 5 bits HLIT (257-286) */
  hlit = tinf_read_bits(d, 5, 257);

  /* get 5 bits HDIST (1-32) */
  hdist = tinf_read_bits(d, 5, 1);

  /* get 4 bits HCLEN (4-19) */
  hclen = tinf_read_bits(d, 4, 4);

  for (i = 0; i < 19; ++i) lengths[i] = 0;

  /* read code lengths for code length alphabet */
  for (i = 0; i < hclen; ++i) {
    /* get 3 bits code length (0-7) */
    var clen = tinf_read_bits(d, 3, 0);
    lengths[clcidx[i]] = clen;
  }

  /* build code length tree */
  tinf_build_tree(code_tree, lengths, 0, 19);

  /* decode code lengths for the dynamic trees */
  for (num = 0; num < hlit + hdist;) {
    var sym = tinf_decode_symbol(d, code_tree);

    switch (sym) {
      case 16:
        /* copy previous code length 3-6 times (read 2 bits) */
        var prev = lengths[num - 1];
        for (length = tinf_read_bits(d, 2, 3); length; --length) {
          lengths[num++] = prev;
        }
        break;
      case 17:
        /* repeat code length 0 for 3-10 times (read 3 bits) */
        for (length = tinf_read_bits(d, 3, 3); length; --length) {
          lengths[num++] = 0;
        }
        break;
      case 18:
        /* repeat code length 0 for 11-138 times (read 7 bits) */
        for (length = tinf_read_bits(d, 7, 11); length; --length) {
          lengths[num++] = 0;
        }
        break;
      default:
        /* values 0-15 represent the actual code lengths */
        lengths[num++] = sym;
        break;
    }
  }

  /* build dynamic trees */
  tinf_build_tree(lt, lengths, 0, hlit);
  tinf_build_tree(dt, lengths, hlit, hdist);
}
85212
def _plot_dendrogram(dendro_ax, adata, groupby, dendrogram_key=None, orientation='right', remove_labels=True, ticks=None):
    

    dendrogram_key = _get_dendrogram_key(adata, dendrogram_key, groupby)

    def translate_pos(pos_list, new_ticks, old_ticks):
        """
        transforms the dendrogram coordinates to a given new position.
        The xlabel_pos and orig_ticks should be of the same
        length.

        This is mostly done for the heatmap case, where the position of the
        dendrogram leaves needs to be adjusted dependening on the size of the category.

        Parameters
        ----------
        pos_list :  list of dendrogram positions that should be translated
        new_ticks : sorted list of goal tick positions (e.g. [0,1,2,3] )
        old_ticks: sorted list of original tick positions (e.g. [5, 15, 25, 35]), This list is
                   usually the default position used by scipy.cluster.hierarchy.dendrogram`

        Returns
        -------
        translated list of positions

        Examples
        --------
        >>> translate([5, 15, 20, 21 ], [0, 1, 2, 3], [5, 15, 25, 35])
        ... [0, 1, 1.5, 1.6]

        """
        # of given coordinates.

        if not isinstance(old_ticks, list):
            # assume that the list is a numpy array
            old_ticks = old_ticks.tolist()
        new_xs = []
        for x_val in pos_list:
            if x_val in old_ticks:
                new_x_val = new_ticks[old_ticks.index(x_val)]
            else:
                # find smaller and bigger indices
                idx_next = np.searchsorted(old_ticks, x_val, side="left")
                idx_prev = idx_next - 1
                old_min = old_ticks[idx_prev]
                old_max = old_ticks[idx_next]
                new_min = new_ticks[idx_prev]
                new_max = new_ticks[idx_next]
                new_x_val = ((x_val - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min
            new_xs.append(new_x_val)
        return new_xs

    dendro_info = adata.uns[dendrogram_key]['dendrogram_info']
    leaves = dendro_info["ivl"]
    icoord = np.array(dendro_info['icoord'])
    dcoord = np.array(dendro_info['dcoord'])

    orig_ticks = np.arange(5, len(leaves) * 10 + 5, 10).astype(float)
    # check that ticks has the same length as orig_ticks
    if ticks is not None and len(orig_ticks) != len(ticks):
        logg.warn("ticks argument does not have the same size as orig_ticks. The argument will be ignored")
        ticks = None

    for xs, ys in zip(icoord, dcoord):
        if ticks is not None:
            xs = translate_pos(xs, ticks, orig_ticks)
        if orientation in ['right', 'left']:
            dendro_ax.plot(ys, xs, color='#555555')
        else:
            dendro_ax.plot(xs, ys, color='#555555')

    dendro_ax.tick_params(bottom=False, top=False, left=False, right=False)
    ticks = ticks if ticks is not None else orig_ticks
    if orientation in ['right', 'left']:
        dendro_ax.set_yticks(ticks)
        dendro_ax.set_yticklabels(leaves, fontsize='small', rotation=0)
        dendro_ax.tick_params(labelbottom=False, labeltop=False)
        if orientation == 'left':
            xmin, xmax=dendro_ax.get_xlim()
            dendro_ax.set_xlim(xmax, xmin)
            dendro_ax.tick_params(labelleft=False, labelright=True)
    else:
        dendro_ax.set_xticks(ticks)
        dendro_ax.set_xticklabels(leaves, fontsize='small', rotation=90)
        dendro_ax.tick_params(labelleft=False, labelright=False)
        if orientation == 'bottom':
            ymin, ymax=dendro_ax.get_ylim()
            dendro_ax.set_ylim(ymax, ymin)
            dendro_ax.tick_params(labeltop=True, labelbottom=False)

    if remove_labels:
        dendro_ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)

    dendro_ax.grid(False)

    dendro_ax.spines['right'].set_visible(False)
    dendro_ax.spines['top'].set_visible(False)
    dendro_ax.spines['left'].set_visible(False)
    dendro_ax.spines['bottom'].set_visible(False)
548212
def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
    shfile=None, **kwargs):
    
    from jcvi.graphics.tree import draw_tree

    if shfile:
        SHs = DictFile(shfile, delimiter="\t")

    ntrees = len(trees)
    n = nrow * ncol
    for x in xrange(int(ceil(float(ntrees)/n))):
        fig = plt.figure(1, (iopts.w, iopts.h)) if iopts \
              else plt.figure(1, (5, 5))
        root = fig.add_axes([0, 0, 1, 1])

        xiv = 1. / ncol
        yiv = 1. / nrow
        xstart = list(np.arange(0, 1, xiv)) * nrow
        ystart = list(chain(*zip(*[list(np.arange(0, 1, yiv))[::-1]] * ncol)))
        for i in xrange(n*x, n*(x+1)):
            if i == ntrees:
                break
            ax = fig.add_axes([xstart[i%n], ystart[i%n], xiv, yiv])
            f = trees.keys()[i]
            tree = trees[f]
            try:
                SH = SHs[f]
            except:
                SH = None
            draw_tree(ax, tree, rmargin=rmargin, reroot=False, \
                supportcolor="r", SH=SH, **kwargs)

        root.set_xlim(0, 1)
        root.set_ylim(0, 1)
        root.set_axis_off()

        format = iopts.format if iopts else "pdf"
        dpi = iopts.dpi if iopts else 300
        if n == 1:
            image_name = f.rsplit(".", 1)[0] + "." + format
        else:
            image_name = "trees{0}.{1}".format(x, format)
        image_name = op.join(outdir, image_name)
        savefig(image_name, dpi=dpi, iopts=iopts)
        plt.clf()
1182778
function tinf_build_fixed_trees(lt, dt) {
  var i;

  /* build fixed length tree */
  for (i = 0; i < 7; ++i) lt.table[i] = 0;

  lt.table[7] = 24;
  lt.table[8] = 152;
  lt.table[9] = 112;

  for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i;
  for (i = 0; i < 144; ++i) lt.trans[24 + i] = i;
  for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i;
  for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i;

  /* build fixed distance tree */
  for (i = 0; i < 5; ++i) dt.table[i] = 0;

  dt.table[5] = 32;

  for (i = 0; i < 32; ++i) dt.trans[i] = i;
}
713236
def dfs(graph, func, head, reverse=None):
    
    todo = deque()
    todo.append(head)
    path = deque()
    done = set()
    while todo:
        node = todo.popleft()
        if node in done:
            path.pop()
            continue

        done.add(node)
        path.append(node)
        result = func(node, path, graph)
        if result:
            if reverse:
                children = graph.get_parents(node)
            else:
                children = graph.get_children(node)
            todo.extend(children)
1358962
private static void recursiveSetSrid(Geometry geometry, int srid) {
		if (geometry != null) {
			geometry.setSrid(srid);
		}
		if (geometry.getGeometries() != null) {
			for (Geometry childGeometry : geometry.getGeometries()) {
				recursiveSetSrid(childGeometry, srid);
			}
		}
	}