adjacency.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. from itertools import chain
  2. import networkx as nx
  3. __all__ = ["adjacency_data", "adjacency_graph"]
  4. _attrs = {"id": "id", "key": "key"}
  5. def adjacency_data(G, attrs=_attrs):
  6. """Returns data in adjacency format that is suitable for JSON serialization
  7. and use in Javascript documents.
  8. Parameters
  9. ----------
  10. G : NetworkX graph
  11. attrs : dict
  12. A dictionary that contains two keys 'id' and 'key'. The corresponding
  13. values provide the attribute names for storing NetworkX-internal graph
  14. data. The values should be unique. Default value:
  15. :samp:`dict(id='id', key='key')`.
  16. If some user-defined graph data use these attribute names as data keys,
  17. they may be silently dropped.
  18. Returns
  19. -------
  20. data : dict
  21. A dictionary with adjacency formatted data.
  22. Raises
  23. ------
  24. NetworkXError
  25. If values in attrs are not unique.
  26. Examples
  27. --------
  28. >>> from networkx.readwrite import json_graph
  29. >>> G = nx.Graph([(1, 2)])
  30. >>> data = json_graph.adjacency_data(G)
  31. To serialize with json
  32. >>> import json
  33. >>> s = json.dumps(data)
  34. Notes
  35. -----
  36. Graph, node, and link attributes will be written when using this format
  37. but attribute keys must be strings if you want to serialize the resulting
  38. data with JSON.
  39. The default value of attrs will be changed in a future release of NetworkX.
  40. See Also
  41. --------
  42. adjacency_graph, node_link_data, tree_data
  43. """
  44. multigraph = G.is_multigraph()
  45. id_ = attrs["id"]
  46. # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
  47. key = None if not multigraph else attrs["key"]
  48. if id_ == key:
  49. raise nx.NetworkXError("Attribute names are not unique.")
  50. data = {}
  51. data["directed"] = G.is_directed()
  52. data["multigraph"] = multigraph
  53. data["graph"] = list(G.graph.items())
  54. data["nodes"] = []
  55. data["adjacency"] = []
  56. for n, nbrdict in G.adjacency():
  57. data["nodes"].append(dict(chain(G.nodes[n].items(), [(id_, n)])))
  58. adj = []
  59. if multigraph:
  60. for nbr, keys in nbrdict.items():
  61. for k, d in keys.items():
  62. adj.append(dict(chain(d.items(), [(id_, nbr), (key, k)])))
  63. else:
  64. for nbr, d in nbrdict.items():
  65. adj.append(dict(chain(d.items(), [(id_, nbr)])))
  66. data["adjacency"].append(adj)
  67. return data
  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(tdata)
  127. else:
  128. ky = target_data.pop(key, None)
  129. graph.add_edge(source, target, key=ky)
  130. graph[source][target][ky].update(tdata)
  131. return graph