Augusto
Augusto

Reputation: 61

reading input data in networkx

I started using python package 'networkx' today and I'm struggling to understand how you read input data from external files.

The examples shown in the documentation deal with small networks which can be read directly from the shell.

I have a legacy file which specifies a large electric network with this format:

'from_node'  'to_node'  'edge_name'  'edge_capacity'  'flow_cost'

The next set of cards reads:

'node type' (source or sink), 'capacity', 'cost'

I want to solve the max flow problem. How can I read such input data file?

Upvotes: 0

Views: 1099

Answers (1)

juniper-
juniper-

Reputation: 6572

You can read the edges using parse_edgelist:

In [1]: import networkx as nx

In [2]: lines = ["from to name capacity cost", "from1 to1 name1 capacity1 cost1"]

In [3]: G = nx.parse_edgelist(lines, data = (('name', str), ('capacity', str), ('cost', str)))

In [5]: G.edges(data=True)
Out[5]: 
[('from1', 'to1', {'capacity': 'capacity1', 'cost': 'cost1', 'name': 'name1'}),
 ('to', 'from', {'capacity': 'capacity', 'cost': 'cost', 'name': 'name'})]

For the nodes, you can probably just iterate over your text file and annotate the graph. The documentation provides quite a few methods for reading graphs:

http://networkx.github.io/documentation/latest/reference/readwrite.html

Upvotes: 1

Related Questions