31
31
itself. Indeed, self-loops are allowed. Node index starts from 0.
34
__author__ = """Willem Ligtenberg (w.p.a.ligtenberg@tue.nl)\n Aric Hagberg (hagberg@lanl.gov)"""
35
__date__ = """2008-05-27"""
36
# Copyright (C) 2008 by
34
# Copyright (C) 2008-2012 by
37
35
# Aric Hagberg <hagberg@lanl.gov>
38
36
# Dan Schult <dschult@colgate.edu>
39
37
# Pieter Swart <swart@lanl.gov>
40
38
# All rights reserved.
44
from networkx.utils import is_string_like,_get_fh
41
from networkx.utils import is_string_like,open_file
42
__author__ = '\n'.join(['Willem Ligtenberg (w.p.a.ligtenberg@tue.nl)',
43
'Aric Hagberg (aric.hagberg@gmail.com)'])
46
def write_p2g(G, path):
45
@open_file(1,mode='w')
46
def write_p2g(G, path, encoding = 'utf-8'):
47
47
"""Write NetworkX graph in p2g format.
49
51
This format is meant to be used with directed graphs with
50
52
possible self loops.
52
fh=_get_fh(path,mode='w')
54
fh.write("%s\n"%G.name)
55
fh.write("%s %s\n"%(G.order(),G.size()))
54
path.write(("%s\n"%G.name).encode(encoding))
55
path.write(("%s %s\n"%(G.order(),G.size())).encode(encoding))
59
57
# make dictionary mapping nodes to integers
60
58
nodenumber=dict(zip(nodes,range(len(nodes))))
60
path.write(("%s\n"%n).encode(encoding))
64
61
for nbr in G.neighbors(n):
65
fh.write("%s "%nodenumber[nbr])
62
path.write(("%s "%nodenumber[nbr]).encode(encoding))
63
path.write("\n".encode(encoding))
65
@open_file(0,mode='r')
66
def read_p2g(path, encoding='utf-8'):
70
67
"""Read graph in p2g format from path.
72
Returns an MultiDiGraph.
74
75
If you want a DiGraph (with no self loops allowed and no edge data)
75
76
use D=networkx.DiGraph(read_p2g(path))
77
fh=_get_fh(path,mode='r')
78
lines = (line.decode(encoding) for line in path)
81
82
def parse_p2g(lines):
82
83
"""Parse p2g format graph from string or iterable.
84
Returns an MultiDiGraph.
86
if is_string_like(lines): lines=iter(lines.split('\n'))
87
lines = iter([line.rstrip('\n') for line in lines])
89
description = lines.next()
89
description = next(lines).strip()
90
90
# are multiedges (parallel edges) allowed?
91
91
G=networkx.MultiDiGraph(name=description,selfloops=True)
92
nnodes,nedges=map(int,lines.next().split())
92
nnodes,nedges=map(int,next(lines).split())
96
95
# loop over the nodes keeping track of node labels and out neighbors
97
96
# defer adding edges until all node labels are known
98
97
for i in range(nnodes):
102
nbrs[n]=map(int,lines.next().split())
101
nbrs[n]=map(int,next(lines).split())
104
102
# now we know all of the node labels so we can add the edges
105
103
# with the correct labels