예제 #1
0
def random_planar_graph(n, m):
    G = Graph()

    for _v in xrange(n):
        G.add_vertex()

    Edges = get_maximal_planar_edges(G, n, 0)

    for _i in xrange(m):
        pos = random.randint(0, len(Edges) - 1)
        G.add_edge(Edges[pos][0], Edges[pos][1])
        del Edges[pos]

    return G
예제 #2
0
def load_from_edge_list(strFileName, G = None):
    if G is None: G = Graph()

    with open(strFileName, 'r') as f:
        lines = f.readlines()

    if not G: G = Graph()
    v_list = dict()

    for line in lines:
        if len(line) == 0 or line == '\n': continue
        if line == "": continue
        fields = line.split()
        if not len(fields): continue
        if fields[0] == 'e':
            u = int(fields[1])
            v = int(fields[2])

            if u not in v_list: v_list[u] = G.add_vertex()
            if v not in v_list: v_list[v] = G.add_vertex()

            x, y = v_list[u], v_list[v]
            G.add_edge(x, y)



    return G
예제 #3
0
def octahedron():
    G = Graph()

    v, w, x, y, z1, z2 = (G.add_vertex() for i in xrange(6))

    for i, j in pairwise((v, w, x, y, v)):
        G.add_edge(i, j)
        G.add_edge(i, z1)
        G.add_edge(i, z2)

    G.is_planar()
    return G
예제 #4
0
def reduce_3sat_to_3col(instance, G = None):
    """reduces a 3sat instance to a graph 3-coloring instance
       receives a graph G
        
      for each clause (a,b,c)
      gadget:
      (-a)----(a)---(g1)
                     | \
                     | (g3)---(g4)    (X)             
                     | /       | \   / |
      (-b)----(b)---(g2)       |  (T)  |
                               | /   \ |
      (-c)----(c)-------------(g5)    (F)
      
      X is adjacent to all variables
    """
    G = Graph() if G is None else G

    # add common gadget
    G.add_named_vertex('T')
    G.add_named_vertex('F')
    G.add_named_vertex('X')
    G.add_edge('T', 'F')
    G.add_edge('F', 'X')
    G.add_edge('X', 'T')


    # add gadget for variables
    variables = sorted(set([abs(v) for clause in instance for v in clause]))

    for v in variables:
        G.add_named_vertex(v)
        G.add_named_vertex(-v)
        G.add_edge('X', v)
        G.add_edge('X', -v)
        G.add_edge(v, -v)

    G.set_vertex_index(max(variables) + 1)
    # add the clause gadgets
    for a, b, c in instance:
        g1, g2, g3, g4, g5 = [G.add_vertex() for _i in range(5)]

        # triangle 1,2,3
        G.add_edge(g1, g2)  # 1
        G.add_edge(g2, g3)  # 2
        G.add_edge(g3, g1)  # 3

        # bridge betwen triangle 1,2,3T  and 4,5,T
        G.add_edge(g3, g4)  # 4

        # triangle 3,4,5
        G.add_edge(g4, g5)  # 5
        G.add_edge(g5, 'T')  # 6
        G.add_edge('T', g4)  # 7

        # edges for clause a,b,c
        G.add_edge(a, g1)  # 8
        G.add_edge(b, g2)  # 9
        G.add_edge(c, g5)  # 10

    return G