syusim
syusim

Reputation: 143

Sage for Graph Theory, KeyError

I'll start with my code, because this may just be an obvious problem to those with better understanding of the language:

g = graphs.CompleteGraph(60).complement()
for i in range(1,180):
    a = randint(0,59)
    b = randint(0,59)
    h = copy(g)
    h.add_edge(a,b)
    if h.is_circular_planar():
        g.add_edge(a,b)

strong = copy(strong_resolve(g))
S = strong.vertex_cover()
d = {'#00FF00': [], '#FF0000': []}
for v in G.vertices():
    if v in S:
        d['#FF0000'].append(v)
    else:
        d['#00FF00'].append(v)
g.plot(layout="spring", vertex_colors=d).show()     
strong.plot(vertex_colors=d).show()

new_strong = copy(strong)
for w in new_strong.vertices():
    if len(new_strong.neighbors(w)) == 0:          #trying to remove
        new_strong.delete_vertex(w)                #disconnected vertices
new_strong.plot(vertex_colors=d).show()

A couple notes: strong_resolve is a function which takes in a graph and outputs another graph. The first two blocks of code work fine.

My problem is that once I add the third block things don't work anymore. In fiddling around I've gotten variants of this code that when added cause errors, and when removed the errors remain somehow. What happens now is that the for loop seems to go until its end and only then it will give the following error:

Traceback (most recent call last):        if h.is_circular_planar():
  File "", line 1, in <module>

  File "/tmp/tmprzreop/___code___.py", line 30, in <module>
    exec compile(u'new_strong.plot(vertex_colors=d).show()
  File "", line 1, in <module>

  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 550, in wrapper
    return func(*args, **options)
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15706, in plot
    return self.graphplot(**options).plot()
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15407, in graphplot
    return GraphPlot(graph=self, options=options)
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 247, in __init__
    self.set_vertices()
  File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 399, in set_vertices
    pos += [self._pos[j] for j in vertex_colors[i]]
KeyError: 0

this can vary in that KeyError: 0 is occasionally 1 or 2 depending on some unknown factor.

I apologize in advance for my horrible code and acknowledge that I really have no idea what I'm doing but I'd really appreciate if someone could help me out here.

Upvotes: 3

Views: 502

Answers (1)

syusim
syusim

Reputation: 143

I figured it out! It turns out the error came from d having entries that made no sense in new_strong, namely those for vertices that were deleted already. This caused the key error when plot() tried to colour the vertices according to d.

Upvotes: 1

Related Questions