Search code examples
pythongraphmetis

How to construct graphs in Metis for Python


I am using Metis for Python, a Python wrapper for Metis (a graphs partitioning software). I have everything installed and it seems to work correctly, however I do not understand how can I construct a graph to input.

There is an online example in: http://metis.readthedocs.org/en/latest/#example

>>> import networkx as nx
>>> import metis
>>> G = metis.example_networkx()
>>> (edgecuts, parts) = metis.part_graph(G, 3)
>>> colors = ['red','blue','green']
>>> for i, p in enumerate(parts):
...     G.node[i]['color'] = colors[p]
...
>>> nx.write_dot(G, 'example.dot') # Requires pydot or pygraphviz

I ran this example and it works fine. However in this example they never specify how to construct the graph “example_networkx()”. I have tried to construct graphs by networkx : http://metis.readthedocs.org/en/latest/#metis.networkx_to_metis

my code is:

>>> A=nx.Graph()
>>> A.add_edges_from([(3,1),(2,3),(1,2),(3,4),(4,5),(5,6),(5,7),(7,6),(4,10),(10,8),(10,9),(8,9)])
>>> G = metis.networkx_to_metis(A)
>>> (edgecuts, parts) = metis.part_graph(G, 3)

I get an error in the last line. The error is traced back to these lines in the Metis built-in code:

in part_graph(graph, nparts, tpwgts, ubvec, recursive, **opts)
    graph = adjlist_to_metis(graph, nodew, nodesz)
in adjlist_to_metis(adjlist, nodew, nodesz)
    m2 = sum(map(len, adjlist))
TypeError: object of type 'c_long' has no len()

I have also tried to construct graphs by adjacency list: http://metis.readthedocs.org/en/latest/#metis.adjlist_to_metis but this gives the same error as before.

I was wondering if anyone has had this problem, or has any idea what I'm doing wrong.

I'm using python 2.7 on Centos 6.5


Solution

  • The metis.part_graph accepts both networkx and adjacency list representation of graphs. you were almost right when you constructed a networkx graph. However, you should directly pass this graph to part_graph function rather than first converting it to a metis object since part_graph function does not directly accept a metis type graph. Given an adjajancy matrix A in numpy, an example can be:

    # since weights should all be integers
    G = networkx.from_numpy_matrix(np.int32(A))  
    # otherwise metis will not recognize you have a weighted graph
    G.graph['edge_weight_attr']='weight'         
    [cost, parts] = metis.part_graph(G, nparts=30, recursive=True)