operations.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. """Operations on trees."""
  2. from functools import partial
  3. from itertools import accumulate, chain
  4. import networkx as nx
  5. __all__ = ["join_trees"]
  6. # Argument types don't match dispatching, but allow manual selection of backend
  7. @nx._dispatchable(graphs=None, returns_graph=True)
  8. def join_trees(rooted_trees, *, label_attribute=None, first_label=0):
  9. """Returns a new rooted tree made by joining `rooted_trees`
  10. Constructs a new tree by joining each tree in `rooted_trees`.
  11. A new root node is added and connected to each of the roots
  12. of the input trees. While copying the nodes from the trees,
  13. relabeling to integers occurs. If the `label_attribute` is provided,
  14. the old node labels will be stored in the new tree under this attribute.
  15. Parameters
  16. ----------
  17. rooted_trees : list
  18. A list of pairs in which each left element is a NetworkX graph
  19. object representing a tree and each right element is the root
  20. node of that tree. The nodes of these trees will be relabeled to
  21. integers.
  22. label_attribute : str
  23. If provided, the old node labels will be stored in the new tree
  24. under this node attribute. If not provided, the original labels
  25. of the nodes in the input trees are not stored.
  26. first_label : int, optional (default=0)
  27. Specifies the label for the new root node. If provided, the root node of the joined tree
  28. will have this label. If not provided, the root node will default to a label of 0.
  29. Returns
  30. -------
  31. NetworkX graph
  32. The rooted tree resulting from joining the provided `rooted_trees`. The new tree has a root node
  33. labeled as specified by `first_label` (defaulting to 0 if not provided). Subtrees from the input
  34. `rooted_trees` are attached to this new root node. Each non-root node, if the `label_attribute`
  35. is provided, has an attribute that indicates the original label of the node in the input tree.
  36. Notes
  37. -----
  38. Trees are stored in NetworkX as NetworkX Graphs. There is no specific
  39. enforcement of the fact that these are trees. Testing for each tree
  40. can be done using :func:`networkx.is_tree`.
  41. Graph, edge, and node attributes are propagated from the given
  42. rooted trees to the created tree. If there are any overlapping graph
  43. attributes, those from later trees will overwrite those from earlier
  44. trees in the tuple of positional arguments.
  45. Examples
  46. --------
  47. Join two full balanced binary trees of height *h* to get a full
  48. balanced binary tree of depth *h* + 1::
  49. >>> h = 4
  50. >>> left = nx.balanced_tree(2, h)
  51. >>> right = nx.balanced_tree(2, h)
  52. >>> joined_tree = nx.join_trees([(left, 0), (right, 0)])
  53. >>> nx.is_isomorphic(joined_tree, nx.balanced_tree(2, h + 1))
  54. True
  55. """
  56. if not rooted_trees:
  57. return nx.empty_graph(1)
  58. # Unzip the zipped list of (tree, root) pairs.
  59. trees, roots = zip(*rooted_trees)
  60. # The join of the trees has the same type as the type of the first tree.
  61. R = type(trees[0])()
  62. lengths = (len(tree) for tree in trees[:-1])
  63. first_labels = list(accumulate(lengths, initial=first_label + 1))
  64. new_roots = []
  65. for tree, root, first_node in zip(trees, roots, first_labels):
  66. new_root = first_node + list(tree.nodes()).index(root)
  67. new_roots.append(new_root)
  68. # Relabel the nodes so that their union is the integers starting at first_label.
  69. relabel = partial(
  70. nx.convert_node_labels_to_integers, label_attribute=label_attribute
  71. )
  72. new_trees = [
  73. relabel(tree, first_label=first_label)
  74. for tree, first_label in zip(trees, first_labels)
  75. ]
  76. # Add all sets of nodes and edges, attributes
  77. for tree in new_trees:
  78. R.update(tree)
  79. # Finally, join the subtrees at the root. We know first_label is unused by
  80. # the way we relabeled the subtrees.
  81. R.add_node(first_label)
  82. R.add_edges_from((first_label, root) for root in new_roots)
  83. return R