#NEWLINE# def _merge_by_size( self , threshold ) : #NEWLINE# #INDENT# '\n        Prune splits from a tree based on size of child nodes. Merge members of\n        child nodes rather than removing them.\n\n        Parameters\n        ----------\n        threshold : numeric\n            Tree branches with fewer members than this will be merged into\n            larger siblings or parents.\n\n        Returns\n        -------\n        tree : LevelSetTree\n            A pruned level set tree. The original tree is unchanged.\n        ' #NEWLINE# tree = _copy . deepcopy ( self ) #NEWLINE# tree . prune_threshold = threshold #NEWLINE# small_roots = [ k for ( k , v ) in tree . nodes . iteritems ( ) if ( ( v . parent is None ) and ( len ( v . members ) <= threshold ) ) ] #NEWLINE# for root in small_roots : #NEWLINE# #INDENT# root_tree = tree . _make_subtree ( root ) #NEWLINE# for ix in root_tree . nodes . iterkeys ( ) : #NEWLINE# #INDENT# del tree . nodes [ ix ] #NEWLINE# #UNINDENT# #UNINDENT# parents = [ k for ( k , v ) in tree . nodes . iteritems ( ) if ( len ( v . children ) >= 1 ) ] #NEWLINE# parents = _np . sort ( parents ) [ : : ( - 1 ) ] #NEWLINE# for ix_parent in parents : #NEWLINE# #INDENT# parent = tree . nodes [ ix_parent ] #NEWLINE# kid_size = { k : len ( tree . nodes [ k ] . members ) for k in parent . children } #NEWLINE# n_bigkid = sum ( ( _np . array ( kid_size . values ( ) ) >= threshold ) ) #NEWLINE# if ( n_bigkid == 0 ) : #NEWLINE# #INDENT# parent . end_level = max ( [ tree . nodes [ k ] . end_level for k in parent . children ] ) #NEWLINE# parent . end_mass = max ( [ tree . nodes [ k ] . end_mass for k in parent . children ] ) #NEWLINE# for k in parent . children : #NEWLINE# #INDENT# del tree . nodes [ k ] #NEWLINE# #UNINDENT# parent . children = [ ] #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( n_bigkid == 1 ) : #NEWLINE# #INDENT# pass #NEWLINE# ix_bigkid = [ k for ( k , v ) in kid_size . iteritems ( ) if ( v >= threshold ) ] [ 0 ] #NEWLINE# bigkid = tree . nodes [ ix_bigkid ] #NEWLINE# parent . end_level = bigkid . end_level #NEWLINE# parent . end_mass = bigkid . end_mass #NEWLINE# for c in bigkid . children : #NEWLINE# #INDENT# tree . nodes [ c ] . parent = ix_parent #NEWLINE# #UNINDENT# for k in parent . children : #NEWLINE# #INDENT# if ( k != ix_bigkid ) : #NEWLINE# #INDENT# del tree . nodes [ tree ] #NEWLINE# #UNINDENT# #UNINDENT# parent . children = bigkid . children #NEWLINE# del tree . nodes [ ix_bigkid ] #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# pass #NEWLINE# #UNINDENT# #UNINDENT# #UNINDENT# return tree