adjacency.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import networkx as nx
  2. __all__ = ["adjacency_data", "adjacency_graph"]
  3. _attrs = {"id": "id", "key": "key"}
  4. def adjacency_data(G, attrs=_attrs):
  5. """Returns data in adjacency format that is suitable for JSON serialization
  6. and use in JavaScript documents.
  7. Parameters
  8. ----------
  9. G : NetworkX graph
  10. attrs : dict
  11. A dictionary that contains two keys 'id' and 'key'. The corresponding
  12. values provide the attribute names for storing NetworkX-internal graph
  13. data. The values should be unique. Default value:
  14. :samp:`dict(id='id', key='key')`.
  15. If some user-defined graph data use these attribute names as data keys,
  16. they may be silently dropped.
  17. Returns
  18. -------
  19. data : dict
  20. A dictionary with adjacency formatted data.
  21. Raises
  22. ------
  23. NetworkXError
  24. If values in attrs are not unique.
  25. Examples
  26. --------
  27. >>> from networkx.readwrite import json_graph
  28. >>> G = nx.Graph([(1, 2)])
  29. >>> data = json_graph.adjacency_data(G)
  30. To serialize with json
  31. >>> import json
  32. >>> s = json.dumps(data)
  33. Notes
  34. -----
  35. Graph, node, and link attributes will be written when using this format
  36. but attribute keys must be strings if you want to serialize the resulting
  37. data with JSON.
  38. The default value of attrs will be changed in a future release of NetworkX.
  39. See Also
  40. --------
  41. adjacency_graph, node_link_data, tree_data
  42. """
  43. multigraph = G.is_multigraph()
  44. id_ = attrs["id"]
  45. # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
  46. key = None if not multigraph else attrs["key"]
  47. if id_ == key:
  48. raise nx.NetworkXError("Attribute names are not unique.")
  49. data = {}
  50. data["directed"] = G.is_directed()
  51. data["multigraph"] = multigraph
  52. data["graph"] = list(G.graph.items())
  53. data["nodes"] = []
  54. data["adjacency"] = []
  55. for n, nbrdict in G.adjacency():
  56. data["nodes"].append({**G.nodes[n], id_: n})
  57. adj = []
  58. if multigraph:
  59. for nbr, keys in nbrdict.items():
  60. for k, d in keys.items():
  61. adj.append({**d, id_: nbr, key: k})
  62. else:
  63. for nbr, d in nbrdict.items():
  64. adj.append({**d, id_: nbr})
  65. data["adjacency"].append(adj)
  66. return data
  67. @nx._dispatchable(graphs=None, returns_graph=True)
  68. def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
  69. """Returns graph from adjacency data format.
  70. Parameters
  71. ----------
  72. data : dict
  73. Adjacency list formatted graph data
  74. directed : bool
  75. If True, and direction not specified in data, return a directed graph.
  76. multigraph : bool
  77. If True, and multigraph not specified in data, return a multigraph.
  78. attrs : dict
  79. A dictionary that contains two keys 'id' and 'key'. The corresponding
  80. values provide the attribute names for storing NetworkX-internal graph
  81. data. The values should be unique. Default value:
  82. :samp:`dict(id='id', key='key')`.
  83. Returns
  84. -------
  85. G : NetworkX graph
  86. A NetworkX graph object
  87. Examples
  88. --------
  89. >>> from networkx.readwrite import json_graph
  90. >>> G = nx.Graph([(1, 2)])
  91. >>> data = json_graph.adjacency_data(G)
  92. >>> H = json_graph.adjacency_graph(data)
  93. Notes
  94. -----
  95. The default value of attrs will be changed in a future release of NetworkX.
  96. See Also
  97. --------
  98. adjacency_graph, node_link_data, tree_data
  99. """
  100. multigraph = data.get("multigraph", multigraph)
  101. directed = data.get("directed", directed)
  102. if multigraph:
  103. graph = nx.MultiGraph()
  104. else:
  105. graph = nx.Graph()
  106. if directed:
  107. graph = graph.to_directed()
  108. id_ = attrs["id"]
  109. # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
  110. key = None if not multigraph else attrs["key"]
  111. graph.graph = dict(data.get("graph", []))
  112. mapping = []
  113. for d in data["nodes"]:
  114. node_data = d.copy()
  115. node = node_data.pop(id_)
  116. mapping.append(node)
  117. graph.add_node(node)
  118. graph.nodes[node].update(node_data)
  119. for i, d in enumerate(data["adjacency"]):
  120. source = mapping[i]
  121. for tdata in d:
  122. target_data = tdata.copy()
  123. target = target_data.pop(id_)
  124. if not multigraph:
  125. graph.add_edge(source, target)
  126. graph[source][target].update(target_data)
  127. else:
  128. ky = target_data.pop(key, None)
  129. graph.add_edge(source, target, key=ky)
  130. graph[source][target][ky].update(target_data)
  131. return graph