nx.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # This code is part of Grandalf
  2. # Copyright (C) 2014 Axel Tillequin (bdcht3@gmail.com) and others
  3. # published under GPLv2 license or EPLv1 license
  4. # Contributor(s): Fabio Zadrozny
  5. __all__ = [
  6. "convert_grandalf_graph_to_networkx_graph",
  7. "convert_nextworkx_graph_to_grandalf",
  8. ]
  9. # Some utilities to interact with networkx.
  10. # Converts a grandalf graph to a networkx graph.
  11. # Note that the edge concept is the same, but a vertex in grandalf is called a node in networkx.
  12. def convert_grandalf_graph_to_networkx_graph(G):
  13. from networkx import MultiDiGraph
  14. nxg = MultiDiGraph()
  15. for v in G.V():
  16. nxg.add_node(v.data)
  17. for e in G.E():
  18. nxg.add_edge(e.v[0].data, e.v[1].data)
  19. return nxg
  20. # Converts a networkx graph to a grandalf graph.
  21. # Note that the edge concept is the same, but a vertex in grandalf is called a node in networkx.
  22. def convert_nextworkx_graph_to_grandalf(G):
  23. from grandalf.graphs import Graph, Vertex, Edge
  24. V = []
  25. data_to_V = {}
  26. for x in G.nodes():
  27. vertex = Vertex(x)
  28. V.append(vertex)
  29. data_to_V[x] = vertex
  30. E = [Edge(data_to_V[xy[0]], data_to_V[xy[1]], data=xy) for xy in G.edges()]
  31. g = Graph(V, E)
  32. return g