def _merge_by_size(self, threshold):

        tree = _copy.deepcopy(self)
        tree.prune_threshold = threshold

        ## remove small root branches
        small_roots = [k for k, v in tree.nodes.iteritems()
                       if v.parent is None and len(v.members) <= threshold]

        for root in small_roots:
            root_tree = tree._make_subtree(root)
            for ix in root_tree.nodes.iterkeys():
                del tree.nodes[ix]

        ## main pruning
        parents = [k for k, v in tree.nodes.iteritems()
                   if len(v.children) >= 1]
        parents = _np.sort(parents)[::-1]

        for ix_parent in parents:
            parent = tree.nodes[ix_parent]

            # get size of each child
            kid_size = {k: len(tree.nodes[k].members) for k in parent.children}

            # count children larger than 'threshold'
            n_bigkid = sum(_np.array(kid_size.values()) >= threshold)

            if n_bigkid == 0:
                # update parent's end level and end mass
                parent.end_level = max([tree.nodes[k].end_level
                                        for k in parent.children])
                parent.end_mass = max([tree.nodes[k].end_mass
                                       for k in parent.children])

                # remove small kids from the tree
                for k in parent.children:
                    del tree.nodes[k]
                parent.children = []

            elif n_bigkid == 1:
                pass
                # identify the big kid
                ix_bigkid = [k for k, v in kid_size.iteritems()
                             if v >= threshold][0]
                bigkid = tree.nodes[ix_bigkid]

                # update k's end level and end mass
                parent.end_level = bigkid.end_level
                parent.end_mass = bigkid.end_mass

                # set grandkids' parent to k
                for c in bigkid.children:
                    tree.nodes[c].parent = ix_parent

                # delete small kids
                for k in parent.children:
                    if k != ix_bigkid:
                        del tree.nodes[k]

                # set k's children to grandkids
                parent.children = bigkid.children

                # delete the single big kid
                del tree.nodes[ix_bigkid]

            else:
                pass  # do nothing here

        return tree
Prune splits from a tree based on size of child nodes. Merge members of
dataset/ETHPy150Open CoAxLab/DeBaCl/debacl/level_set_tree.py/LevelSetTree._merge_by_size