-
-
Notifications
You must be signed in to change notification settings - Fork 674
Description
Hello!
I am not sure I have the energy to do that at the moment but its a nice task that we might want to address at some point. Hence I am leaving some stuff here for further reference.
The current implementation of the chromatic_polynomial uses the deletion-contraction recurrence directly. This gives us an exponential branching tree. The neat thing is that at some point some of the branches compute the chromatic polynomial for the same graphs (multiple - exponential) times!
A very dumb implementation in Python (see below) that is faster than the C code. It takes 700us to compute the chromatic polynomial of a random dense graph of order 15 and 74 minutes (!) with the C code currently used by Sage.
Of course this code needs more work and can be optimized even further (perhaps by calling the C implementation under a threshold) but for now here it is.
global cache
cache = {}
def chrompoly(G):
global cache
s = tuple(G.canonical_label().edges(labels=False))
if s in cache:
return cache[s]
if not G.is_connected():
return prod([chrompoly(C) for C in G.connected_components_subgraphs()])
R = ZZ['x']
x = R.gen()
n = G.order()
m = G.size()
# Since we know that G is connected it is enough to check the number of edges
# to test if it is a tree
if m == n-1:
return x*(x-1)**(n-1)
u,v = G.edge_iterator(labels=False).next()
G.delete_edge(u,v)
p = chrompoly(G)
G.add_edge(u,v)
G2 = G.copy()
G2.add_edges(((u,x) for x in G.neighbor_iterator(v)))
G2.delete_vertex(v)
ret = p - chrompoly(G2)
cache[s] = ret
return ret
CC: @nathanncohen @Stefan @lobiCode @rbeezer @orlitzky
Component: graph theory
Author: Jernej Azarija, David Coudert
Branch/Commit: 66708cc
Reviewer: Michael Orlitzky
Issue created by migration from https://trac.sagemath.org/ticket/14529