relabel.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import networkx as nx
  2. __all__ = ["convert_node_labels_to_integers", "relabel_nodes"]
  3. def relabel_nodes(G, mapping, copy=True):
  4. """Relabel the nodes of the graph G according to a given mapping.
  5. The original node ordering may not be preserved if `copy` is `False` and the
  6. mapping includes overlap between old and new labels.
  7. Parameters
  8. ----------
  9. G : graph
  10. A NetworkX graph
  11. mapping : dictionary
  12. A dictionary with the old labels as keys and new labels as values.
  13. A partial mapping is allowed. Mapping 2 nodes to a single node is allowed.
  14. Any non-node keys in the mapping are ignored.
  15. copy : bool (optional, default=True)
  16. If True return a copy, or if False relabel the nodes in place.
  17. Examples
  18. --------
  19. To create a new graph with nodes relabeled according to a given
  20. dictionary:
  21. >>> G = nx.path_graph(3)
  22. >>> sorted(G)
  23. [0, 1, 2]
  24. >>> mapping = {0: "a", 1: "b", 2: "c"}
  25. >>> H = nx.relabel_nodes(G, mapping)
  26. >>> sorted(H)
  27. ['a', 'b', 'c']
  28. Nodes can be relabeled with any hashable object, including numbers
  29. and strings:
  30. >>> import string
  31. >>> G = nx.path_graph(26) # nodes are integers 0 through 25
  32. >>> sorted(G)[:3]
  33. [0, 1, 2]
  34. >>> mapping = dict(zip(G, string.ascii_lowercase))
  35. >>> G = nx.relabel_nodes(G, mapping) # nodes are characters a through z
  36. >>> sorted(G)[:3]
  37. ['a', 'b', 'c']
  38. >>> mapping = dict(zip(G, range(1, 27)))
  39. >>> G = nx.relabel_nodes(G, mapping) # nodes are integers 1 through 26
  40. >>> sorted(G)[:3]
  41. [1, 2, 3]
  42. To perform a partial in-place relabeling, provide a dictionary
  43. mapping only a subset of the nodes, and set the `copy` keyword
  44. argument to False:
  45. >>> G = nx.path_graph(3) # nodes 0-1-2
  46. >>> mapping = {0: "a", 1: "b"} # 0->'a' and 1->'b'
  47. >>> G = nx.relabel_nodes(G, mapping, copy=False)
  48. >>> sorted(G, key=str)
  49. [2, 'a', 'b']
  50. A mapping can also be given as a function:
  51. >>> G = nx.path_graph(3)
  52. >>> H = nx.relabel_nodes(G, lambda x: x ** 2)
  53. >>> list(H)
  54. [0, 1, 4]
  55. In a multigraph, relabeling two or more nodes to the same new node
  56. will retain all edges, but may change the edge keys in the process:
  57. >>> G = nx.MultiGraph()
  58. >>> G.add_edge(0, 1, value="a") # returns the key for this edge
  59. 0
  60. >>> G.add_edge(0, 2, value="b")
  61. 0
  62. >>> G.add_edge(0, 3, value="c")
  63. 0
  64. >>> mapping = {1: 4, 2: 4, 3: 4}
  65. >>> H = nx.relabel_nodes(G, mapping, copy=True)
  66. >>> print(H[0])
  67. {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}}
  68. This works for in-place relabeling too:
  69. >>> G = nx.relabel_nodes(G, mapping, copy=False)
  70. >>> print(G[0])
  71. {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}}
  72. Notes
  73. -----
  74. Only the nodes specified in the mapping will be relabeled.
  75. Any non-node keys in the mapping are ignored.
  76. The keyword setting copy=False modifies the graph in place.
  77. Relabel_nodes avoids naming collisions by building a
  78. directed graph from ``mapping`` which specifies the order of
  79. relabelings. Naming collisions, such as a->b, b->c, are ordered
  80. such that "b" gets renamed to "c" before "a" gets renamed "b".
  81. In cases of circular mappings (e.g. a->b, b->a), modifying the
  82. graph is not possible in-place and an exception is raised.
  83. In that case, use copy=True.
  84. If a relabel operation on a multigraph would cause two or more
  85. edges to have the same source, target and key, the second edge must
  86. be assigned a new key to retain all edges. The new key is set
  87. to the lowest non-negative integer not already used as a key
  88. for edges between these two nodes. Note that this means non-numeric
  89. keys may be replaced by numeric keys.
  90. See Also
  91. --------
  92. convert_node_labels_to_integers
  93. """
  94. # you can pass any callable e.g. f(old_label) -> new_label or
  95. # e.g. str(old_label) -> new_label, but we'll just make a dictionary here regardless
  96. m = {n: mapping(n) for n in G} if callable(mapping) else mapping
  97. if copy:
  98. return _relabel_copy(G, m)
  99. else:
  100. return _relabel_inplace(G, m)
  101. def _relabel_inplace(G, mapping):
  102. if len(mapping.keys() & mapping.values()) > 0:
  103. # labels sets overlap
  104. # can we topological sort and still do the relabeling?
  105. D = nx.DiGraph(list(mapping.items()))
  106. D.remove_edges_from(nx.selfloop_edges(D))
  107. try:
  108. nodes = reversed(list(nx.topological_sort(D)))
  109. except nx.NetworkXUnfeasible as err:
  110. raise nx.NetworkXUnfeasible(
  111. "The node label sets are overlapping and no ordering can "
  112. "resolve the mapping. Use copy=True."
  113. ) from err
  114. else:
  115. # non-overlapping label sets, sort them in the order of G nodes
  116. nodes = [n for n in G if n in mapping]
  117. multigraph = G.is_multigraph()
  118. directed = G.is_directed()
  119. for old in nodes:
  120. # Test that old is in both mapping and G, otherwise ignore.
  121. try:
  122. new = mapping[old]
  123. G.add_node(new, **G.nodes[old])
  124. except KeyError:
  125. continue
  126. if new == old:
  127. continue
  128. if multigraph:
  129. new_edges = [
  130. (new, new if old == target else target, key, data)
  131. for (_, target, key, data) in G.edges(old, data=True, keys=True)
  132. ]
  133. if directed:
  134. new_edges += [
  135. (new if old == source else source, new, key, data)
  136. for (source, _, key, data) in G.in_edges(old, data=True, keys=True)
  137. ]
  138. # Ensure new edges won't overwrite existing ones
  139. seen = set()
  140. for i, (source, target, key, data) in enumerate(new_edges):
  141. if target in G[source] and key in G[source][target]:
  142. new_key = 0 if not isinstance(key, (int, float)) else key
  143. while new_key in G[source][target] or (target, new_key) in seen:
  144. new_key += 1
  145. new_edges[i] = (source, target, new_key, data)
  146. seen.add((target, new_key))
  147. else:
  148. new_edges = [
  149. (new, new if old == target else target, data)
  150. for (_, target, data) in G.edges(old, data=True)
  151. ]
  152. if directed:
  153. new_edges += [
  154. (new if old == source else source, new, data)
  155. for (source, _, data) in G.in_edges(old, data=True)
  156. ]
  157. G.remove_node(old)
  158. G.add_edges_from(new_edges)
  159. return G
  160. def _relabel_copy(G, mapping):
  161. H = G.__class__()
  162. H.add_nodes_from(mapping.get(n, n) for n in G)
  163. H._node.update((mapping.get(n, n), d.copy()) for n, d in G.nodes.items())
  164. if G.is_multigraph():
  165. new_edges = [
  166. (mapping.get(n1, n1), mapping.get(n2, n2), k, d.copy())
  167. for (n1, n2, k, d) in G.edges(keys=True, data=True)
  168. ]
  169. # check for conflicting edge-keys
  170. undirected = not G.is_directed()
  171. seen_edges = set()
  172. for i, (source, target, key, data) in enumerate(new_edges):
  173. while (source, target, key) in seen_edges:
  174. if not isinstance(key, (int, float)):
  175. key = 0
  176. key += 1
  177. seen_edges.add((source, target, key))
  178. if undirected:
  179. seen_edges.add((target, source, key))
  180. new_edges[i] = (source, target, key, data)
  181. H.add_edges_from(new_edges)
  182. else:
  183. H.add_edges_from(
  184. (mapping.get(n1, n1), mapping.get(n2, n2), d.copy())
  185. for (n1, n2, d) in G.edges(data=True)
  186. )
  187. H.graph.update(G.graph)
  188. return H
  189. def convert_node_labels_to_integers(
  190. G, first_label=0, ordering="default", label_attribute=None
  191. ):
  192. """Returns a copy of the graph G with the nodes relabeled using
  193. consecutive integers.
  194. Parameters
  195. ----------
  196. G : graph
  197. A NetworkX graph
  198. first_label : int, optional (default=0)
  199. An integer specifying the starting offset in numbering nodes.
  200. The new integer labels are numbered first_label, ..., n-1+first_label.
  201. ordering : string
  202. "default" : inherit node ordering from G.nodes()
  203. "sorted" : inherit node ordering from sorted(G.nodes())
  204. "increasing degree" : nodes are sorted by increasing degree
  205. "decreasing degree" : nodes are sorted by decreasing degree
  206. label_attribute : string, optional (default=None)
  207. Name of node attribute to store old label. If None no attribute
  208. is created.
  209. Notes
  210. -----
  211. Node and edge attribute data are copied to the new (relabeled) graph.
  212. There is no guarantee that the relabeling of nodes to integers will
  213. give the same two integers for two (even identical graphs).
  214. Use the `ordering` argument to try to preserve the order.
  215. See Also
  216. --------
  217. relabel_nodes
  218. """
  219. N = G.number_of_nodes() + first_label
  220. if ordering == "default":
  221. mapping = dict(zip(G.nodes(), range(first_label, N)))
  222. elif ordering == "sorted":
  223. nlist = sorted(G.nodes())
  224. mapping = dict(zip(nlist, range(first_label, N)))
  225. elif ordering == "increasing degree":
  226. dv_pairs = [(d, n) for (n, d) in G.degree()]
  227. dv_pairs.sort() # in-place sort from lowest to highest degree
  228. mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
  229. elif ordering == "decreasing degree":
  230. dv_pairs = [(d, n) for (n, d) in G.degree()]
  231. dv_pairs.sort() # in-place sort from lowest to highest degree
  232. dv_pairs.reverse()
  233. mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
  234. else:
  235. raise nx.NetworkXError(f"Unknown node ordering: {ordering}")
  236. H = relabel_nodes(G, mapping)
  237. # create node attribute with the old label
  238. if label_attribute is not None:
  239. nx.set_node_attributes(H, {v: k for k, v in mapping.items()}, label_attribute)
  240. return H