-
Notifications
You must be signed in to change notification settings - Fork 2
/
tutte.py
72 lines (59 loc) · 2.15 KB
/
tutte.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import networkx as nx
from subprocess import Popen, PIPE, STDOUT
import re
def to_adj_matrix(G):
"""Return the 01-adjacency matrix of the given graph.
- input: a networkx graph G, assumed to be undirected, loopless, and simple
- output: a string of integers separated by blanks. The first
integer is the graph's order n (i.e., the number of
vertices). Then follow n * n 0s and 1s for the graph's adjacency
matrix, row by row. This is the input format for tutte_bhkk.
"""
l= [str(G.order())]
l.extend( [str(int(G.has_edge(u,v))) for u in G for v in G] )
return ' '.join(l)
def call_tutte_bhkk(G):
p= Popen(['./tutte_bhkk'], stdin=PIPE, stdout=PIPE)
# (out,err)= p.communicate(input=to_adj_matrix(G)) a bytes-like object is required, not 'str'
(out,err)= p.communicate(input=bytes(to_adj_matrix(G), 'utf-8'))
ret = str (out)
#remove the ' and the b
ret = ret[2:-1]
return ret
def sp_power(s,i):
if i==0: return ""
if i==1: return s
return s+"**"+str(i)
def to_sp(lines):
(i,j) = (0,0)
P = []
for line in lines.split('\\n'):
if line == '': continue
for coeff in line.split(' '):
if int(coeff) >= 1:
if i==0 and j==0:
P.append(coeff +"*"+ "1")
elif i==0:
P.append(coeff +"*"+ sp_power('y',j))
elif j==0:
P.append(coeff +"*"+ sp_power('x',i))
else:
P.append(coeff +"*"+ sp_power('x',i) +"*"+ sp_power('y',j))
j += 1
i += 1
j = 0
return " + ".join(P)
def tutte_poly(G, output='sp'):
"""Return the Tutte polynomial of the given graph.
arguments:
G: a networkx graph. Simple, loopless, umweighted, undirected.
output: one of 'raw', or 'sp'.
By default output == 'sp': returns the corresponding sp string
with ** as ^ so it can be interpreted by sympy.
If output == 'raw', returns the raw outpout of tutte_bhkk.
"""
lines = call_tutte_bhkk(G)
if output == 'raw':
return lines
if output == 'sp':
return to_sp(lines)