p2g.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """
  2. This module provides the following: read and write of p2g format
  3. used in metabolic pathway studies.
  4. See https://web.archive.org/web/20080626113807/http://www.cs.purdue.edu/homes/koyuturk/pathway/ for a description.
  5. The summary is included here:
  6. A file that describes a uniquely labeled graph (with extension ".gr")
  7. format looks like the following:
  8. name
  9. 3 4
  10. a
  11. 1 2
  12. b
  13. c
  14. 0 2
  15. "name" is simply a description of what the graph corresponds to. The
  16. second line displays the number of nodes and number of edges,
  17. respectively. This sample graph contains three nodes labeled "a", "b",
  18. and "c". The rest of the graph contains two lines for each node. The
  19. first line for a node contains the node label. After the declaration
  20. of the node label, the out-edges of that node in the graph are
  21. provided. For instance, "a" is linked to nodes 1 and 2, which are
  22. labeled "b" and "c", while the node labeled "b" has no outgoing
  23. edges. Observe that node labeled "c" has an outgoing edge to
  24. itself. Indeed, self-loops are allowed. Node index starts from 0.
  25. """
  26. import networkx
  27. from networkx.utils import open_file
  28. @open_file(1, mode="w")
  29. def write_p2g(G, path, encoding="utf-8"):
  30. """Write NetworkX graph in p2g format.
  31. Notes
  32. -----
  33. This format is meant to be used with directed graphs with
  34. possible self loops.
  35. """
  36. path.write((f"{G.name}\n").encode(encoding))
  37. path.write((f"{G.order()} {G.size()}\n").encode(encoding))
  38. nodes = list(G)
  39. # make dictionary mapping nodes to integers
  40. nodenumber = dict(zip(nodes, range(len(nodes))))
  41. for n in nodes:
  42. path.write((f"{n}\n").encode(encoding))
  43. for nbr in G.neighbors(n):
  44. path.write((f"{nodenumber[nbr]} ").encode(encoding))
  45. path.write("\n".encode(encoding))
  46. @open_file(0, mode="r")
  47. def read_p2g(path, encoding="utf-8"):
  48. """Read graph in p2g format from path.
  49. Returns
  50. -------
  51. MultiDiGraph
  52. Notes
  53. -----
  54. If you want a DiGraph (with no self loops allowed and no edge data)
  55. use D=networkx.DiGraph(read_p2g(path))
  56. """
  57. lines = (line.decode(encoding) for line in path)
  58. G = parse_p2g(lines)
  59. return G
  60. def parse_p2g(lines):
  61. """Parse p2g format graph from string or iterable.
  62. Returns
  63. -------
  64. MultiDiGraph
  65. """
  66. description = next(lines).strip()
  67. # are multiedges (parallel edges) allowed?
  68. G = networkx.MultiDiGraph(name=description, selfloops=True)
  69. nnodes, nedges = map(int, next(lines).split())
  70. nodelabel = {}
  71. nbrs = {}
  72. # loop over the nodes keeping track of node labels and out neighbors
  73. # defer adding edges until all node labels are known
  74. for i in range(nnodes):
  75. n = next(lines).strip()
  76. nodelabel[i] = n
  77. G.add_node(n)
  78. nbrs[n] = map(int, next(lines).split())
  79. # now we know all of the node labels so we can add the edges
  80. # with the correct labels
  81. for n in G:
  82. for nbr in nbrs[n]:
  83. G.add_edge(n, nodelabel[nbr])
  84. return G