MetisIntro » Graphgen.py
1 
#!/usr/bin/python


2 
# * coding: utf8 *

3 
"""

4 
Graphgen generates a rectangular graph in the METIS graph format

5  
6 
Usage:

7 
Graphgen.py n  generate a square n x n graph

8 
Graphgen.py n m  generate a n x m graph

9  
10 
'n' and 'm' must be integers

11 
"""

12  
13 
__author__ = """Florian Wilhelm (Florian.Wilhelm@kit.edu)""" 
14 
__date__ = """26.03.2009""" 
15  
16 
import sys 
17  
18 
if len(sys.argv) <= 1: 
19 
print __doc__ 
20 
sys.exit(1) 
21 
elif len(sys.argv) == 2: 
22 
u = int(sys.argv[1]) 
23 
v = u 
24 
elif len(sys.argv) >= 3: 
25 
u, v = int(sys.argv[1]), int(sys.argv[2]) 
26  
27 
filename = "graph%sx%s"%(u,v) 
28 
vertices = u * v 
29 
edges = u * (v  1) + v * (u  1) 
30  
31 
fh = open(filename, 'w') 
32 
fh.writelines("%s %s\n"%(vertices, edges)) 
33  
34 
for line in range(1, vertices + 1): 
35 
neighbors = [line  1, line  v, line + v, line + 1] 
36 
if line % v == 1 or v == 1: # left border 
37 
neighbors.remove(line  1) 
38 
if line % v == 0: # right border 
39 
neighbors.remove(line + 1) 
40 
if line <= v: # lower border 
41 
neighbors.remove(line  v) 
42 
if line > u*v  v: # upper border 
43 
neighbors.remove(line + v) 
44 
neighbors = map(str, neighbors) 
45 
fh.writelines(" ".join(neighbors) + "\n") 
46  
47 
fh.close() 
48 