예제 #1
0
 def testAddEmptyGraph(self):
     gr1 = pygraph.graph()
     gr1.generate(25, 100)
     gr1c = copy.copy(gr1)
     gr2 = pygraph.graph()
     gr1.add_graph(gr2)
     self.assertTrue(gr1.nodes() == gr1c.nodes())
     self.assertTrue(gr1.edges() == gr1c.edges())
예제 #2
0
 def testAddEmptyGraph(self):
     gr1 = pygraph.graph()
     gr1.generate(25, 100)
     gr1c = copy.copy(gr1)
     gr2 = pygraph.graph()
     gr1.add_graph(gr2)
     self.assertTrue(gr1.nodes() == gr1c.nodes())
     self.assertTrue(gr1.edges() == gr1c.edges())
예제 #3
0
 def testAddGraph(self):
     gr1 = pygraph.graph()
     gr1.generate(25, 100)
     gr2 = pygraph.graph()
     gr2.generate(40, 200)
     gr1.add_graph(gr2)
     for each in gr2.nodes():
         self.assertTrue(each in gr1)
     for each in gr2.edges():
         self.assertTrue(each in gr1.edges())
예제 #4
0
 def testAddGraph(self):
     gr1 = pygraph.graph()
     gr1.generate(25, 100)
     gr2 = pygraph.graph()
     gr2.generate(40, 200)
     gr1.add_graph(gr2)
     for each in gr2.nodes():
         self.assertTrue(each in gr1)
     for each in gr2.edges():
         self.assertTrue(each in gr1.edges())
예제 #5
0
 def testTrivalEquality2(self):
     gr1 = pygraph.graph()
     gr1.add_node(0)
     gr1.add_node(1)
     gr1.add_edge(0,1)
     gr2 = pygraph.graph()
     gr2.add_node(0)
     gr2.add_node(1)
     gr2.add_edge(0,1)
     assert gr1 == gr2, "Two identically constructed graphs should be equivalent to each other."
예제 #6
0
 def testTrivalEquality2(self):
     gr1 = pygraph.graph()
     gr1.add_node(0)
     gr1.add_node(1)
     gr1.add_edge(0, 1)
     gr2 = pygraph.graph()
     gr2.add_node(0)
     gr2.add_node(1)
     gr2.add_edge(0, 1)
     assert gr1 == gr2, "Two identically constructed graphs should be equivalent to each other."
예제 #7
0
def TSP(D, files):

    n = len(files)

    # Set up the graph

    G = graph()
    G.add_nodes(range(n))
    G.complete()

    for i in range(n):
        for j in range(i + 1, n):
            G.set_edge_weight(i, j, sqrt(D[i, j]))

    sys.stderr.write("\tBuilding the MST\n")
    T = algorithms.minmax.minimal_spanning_tree(G)

    M = graph()
    M.add_nodes(range(n))
    M.add_spanning_tree(T)

    class tspApprox(object):
        def __init__(self):
            self.graph = None
            self.spanning_tree = None
            self.visited_set = set()
            self.path = []

        def configure(self, graph, spanning_tree):
            self.graph = graph
            self.spanning_tree = spanning_tree

        def __call__(self, node, parent):

            # Is the node visited already?  If not, add it
            if node not in self.visited_set:
                self.visited_set.add(node)
                self.path.append(node)

            return True

        def getPath(self):
            return self.path

    sys.stderr.write("\tGenerating the playlist\n")

    approximator = tspApprox()
    algorithms.searching.depth_first_search(M, 0, approximator)

    output = []
    for p in approximator.getPath():
        output.append(files[p])

    return output
예제 #8
0
def TSP(D, files):

    n = len(files)

    # Set up the graph

    G = graph()
    G.add_nodes(range(n))
    G.complete()

    for i in range(n):
        for j in range(i + 1, n):
            G.set_edge_weight(i, j, sqrt(D[i, j]))

    sys.stderr.write("\tBuilding the MST\n")
    T = algorithms.minmax.minimal_spanning_tree(G)

    M = graph()
    M.add_nodes(range(n))
    M.add_spanning_tree(T)

    class tspApprox(object):
        def __init__(self):
            self.graph = None
            self.spanning_tree = None
            self.visited_set = set()
            self.path = []

        def configure(self, graph, spanning_tree):
            self.graph = graph
            self.spanning_tree = spanning_tree

        def __call__(self, node, parent):

            # Is the node visited already?  If not, add it
            if node not in self.visited_set:
                self.visited_set.add(node)
                self.path.append(node)

            return True

        def getPath(self):
            return self.path

    sys.stderr.write("\tGenerating the playlist\n")

    approximator = tspApprox()
    algorithms.searching.depth_first_search(M, 0, approximator)

    output = []
    for p in approximator.getPath():
        output.append(files[p])

    return output
예제 #9
0
 def testAddSpanningTree(self):
     gr = pygraph.graph()
     st = {0: None, 1: 0, 2:0, 3: 1, 4: 2, 5: 3}
     gr.add_spanning_tree(st)
     for each in st:
         self.assertTrue((each, st[each]) in gr.edges() or (each, st[each]) == (0, None))
         self.assertTrue((st[each], each) in gr.edges() or (each, st[each]) == (0, None))
예제 #10
0
 def testGraphComplete(self):
     gr = pygraph.graph()
     gr.add_nodes(xrange(10))
     gr.complete()
     for i in xrange(10):
         for j in range(10):
             self.assertTrue((i, j) in gr.edges() or i == j)
 def testReadGraphDot(self):
     dot = ['graph graphname {', '1;', '2;', '3;', '4;', '5;', '1 -- 2;', '3 -- 2;', '4 -- 5;', '1 -- 5;', '4 -- 2;', '5 -- 3;', '}', '']
     dot = "\n".join(dot)
     gr = pygraph.graph()
     gr.read(dot, 'dot')
     self._check_nodes(gr, dot)
     self._check_edges(gr, dot)
 def testSanityGraph(self):
     G = pygraph.graph()
     G.generate(100, 500)
     st, lo = G.breadth_first_search()
     for each in G:
         if (st[each] != None):
             assert lo.index(each) > lo.index(st[each])
예제 #13
0
 def testGraphComplete(self):
     gr = pygraph.graph()
     gr.add_nodes(xrange(10))
     gr.complete()
     for i in xrange(10):
         for j in range(10):
             self.assertTrue((i, j) in gr.edges() or i == j)
예제 #14
0
 def testNodeRemoval(self):
     gr = pygraph.graph()
     gr.generate(10, 30)
     gr.del_node(0)
     self.assertTrue(0 not in gr)
     for each, other in gr.edges():
         self.assertTrue(each in gr)
         self.assertTrue(other in gr)
 def testSanityGraph(self):
     G = pygraph.graph()
     G.generate(100, 500)
     st, pre, post = G.depth_first_search()
     for each in G:
         if (st[each] != None):
             assert pre.index(each) > pre.index(st[each])
             assert post.index(each) < post.index(st[each])
예제 #16
0
 def testRandomGraph(self):
     gr = pygraph.graph()
     gr.generate(100, 500)
     self.assertEqual(gr.nodes(), range(100))
     self.assertEqual(len(gr.edges()), 500 * 2)
     for each, other in gr.edges():
         self.assertTrue(each in gr)
         self.assertTrue(other in gr)
예제 #17
0
 def testRandomGraph(self):
     gr = pygraph.graph()
     gr.generate(100, 500)
     self.assertEqual(gr.nodes(),range(100))
     self.assertEqual(len(gr.edges()), 500*2)
     for each, other in gr.edges():
         self.assertTrue(each in gr)
         self.assertTrue(other in gr)
예제 #18
0
 def testNodeRemoval(self):
     gr = pygraph.graph()
     gr.generate(10, 30)
     gr.del_node(0)
     self.assertTrue(0 not in gr)
     for each, other in gr.edges():
         self.assertTrue(each in gr)
         self.assertTrue(other in gr)
예제 #19
0
 def testGraphInverse(self):
     gr = pygraph.graph()
     gr.generate(50, 300)
     inv = gr.inverse()
     for each in gr.edges():
         self.assertTrue(each not in inv.edges())
     for each in inv.edges():
         self.assertTrue(each not in gr.edges())
예제 #20
0
 def testGraphInverse(self):
     gr = pygraph.graph()
     gr.generate(50, 300)
     inv = gr.inverse()
     for each in gr.edges():
         self.assertTrue(each not in inv.edges())
     for each in inv.edges():
         self.assertTrue(each not in gr.edges())
예제 #21
0
 def testAddSpanningTree(self):
     gr = pygraph.graph()
     st = {0: None, 1: 0, 2: 0, 3: 1, 4: 2, 5: 3}
     gr.add_spanning_tree(st)
     for each in st:
         self.assertTrue((each, st[each]) in gr.edges()
                         or (each, st[each]) == (0, None))
         self.assertTrue((st[each], each) in gr.edges()
                         or (each, st[each]) == (0, None))
 def setUp(self):
     self.G = pygraph.graph()
     self.G.add_node('A', [('position',[0,0])])
     self.G.add_node('B', [('position',[2,0])])
     self.G.add_node('C', [('position',[2,3])])
     self.G.add_node('D', [('position',[1,2])])
     self.G.add_edge('A', 'B', wt=4)
     self.G.add_edge('A', 'D', wt=5)
     self.G.add_edge('B', 'C', wt=9)
     self.G.add_edge('D', 'C', wt=2)            
예제 #23
0
 def testGraphBFS(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5])
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(2, 4)
     G.add_edge(4, 5)
     G.add_edge(1, 5)
     G.add_edge(3, 5)
     st, lo = breadth_first_search(G, 1, filter=filters.find(5))
     assert st == {1: None, 2: 1, 5: 1}
예제 #24
0
 def testGraph(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5])
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(2, 4)
     G.add_edge(4, 5)
     G.add_edge(1, 5)
     G.add_edge(3, 5)
     # Cycles: 1-2-4-5, 3-2-4-5 and 1-2-3-5
     assert G.find_cycle() == [2,3,5,4]
 def testWriteGraphXML(self):
     gr = pygraph.graph()
     gr.add_nodes([1, 2, 3, 4, 5])
     gr.add_edge(1, 2)
     gr.add_edge(2, 3)
     gr.add_edge(2, 4)
     gr.add_edge(4, 5)
     gr.add_edge(1, 5)
     gr.add_edge(3, 5)
     xml = markup.write(gr)
     self._check_nodes(gr, xml)
     self._check_edges(gr, xml)
 def testWriteGraphDot(self):
     gr = pygraph.graph()
     gr.add_nodes([1, 2, 3, 4, 5])
     gr.add_edge(1, 2)
     gr.add_edge(2, 3)
     gr.add_edge(2, 4)
     gr.add_edge(4, 5)
     gr.add_edge(1, 5)
     gr.add_edge(3, 5)
     dotstr = dot.write(gr)
     self._check_nodes(gr, dotstr)
     self._check_edges(gr, dotstr)
 def testGraph(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5])
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(2, 4)
     G.add_edge(4, 5)
     G.add_edge(1, 5)
     G.add_edge(3, 5)
     st, lo = G.breadth_first_search(1)
     assert st == {1: None, 2: 1, 3: 2, 4: 2, 5: 1}
     assert lo == [1, 2, 5, 3, 4]
 def testGraph(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5])
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(2, 4)
     G.add_edge(4, 5)
     G.add_edge(1, 5)
     G.add_edge(3, 5)
     st, pre, post = G.depth_first_search()
     assert st == {1: None, 2: 1, 3: 2, 4: 5, 5: 3}
     assert pre == [1, 2, 3, 5, 4]
     assert post == [4, 5, 3, 2, 1]
예제 #29
0
 def testGraphDFS(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5])
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(2, 4)
     G.add_edge(4, 5)
     G.add_edge(1, 5)
     G.add_edge(3, 5)
     st, pre, post = depth_first_search(G, 1, filter=filters.find(5))
     assert st == {1: None, 2: 1, 3: 2, 5: 3}
     st, pre, post = depth_first_search(G, 1, filter=filters.find(2))
     assert st == {1: None, 2: 1}
예제 #30
0
 def testGraphDFS(self):
     G = pygraph.graph()
     G.add_nodes([1, 2, 3, 4, 5, 6, 7, 8, 9])
     G.add_edge(1, 2)
     G.add_edge(1, 3)
     G.add_edge(2, 4)
     G.add_edge(3, 5)
     G.add_edge(4, 6)
     G.add_edge(5, 7)
     G.add_edge(1, 8, wt=3)
     G.add_edge(8, 9)
     G.add_edge(3, 9)
     st, pre, post = depth_first_search(G, 1, filter=filters.radius(2))
     assert st == {1: None, 2: 1, 3: 1, 4: 2, 5: 3, 9: 3}
예제 #31
0
def colorMap(m):
    g = pygraph.graph()
    height = len(m)
    width = len(m[0])

    for i in range(height):
        g.add_nodes([(i, x) for x in range(width)])

    for i in range(height):
        for j in range(width):
            candidates = []
            if i != 0:
                candidates.append((i - 1, j))
            if j != 0:
                candidates.append((i, j - 1))
            if j != width - 1:
                candidates.append((i, j + 1))
            if i != height - 1:
                candidates.append((i + 1, j))

            # find the best candidate and add the edge
            # to the graph
            val = m[i][j]
            if len(candidates) == 0:
                continue
            best_candidate = candidates[0]
            best_fall = val - m[best_candidate[0]][best_candidate[1]]

            for k in range(1, len(candidates)):
                new_candidate = candidates[k]
                new_fall = val - m[new_candidate[0]][new_candidate[1]]
                if new_fall > best_fall:
                    best_fall = new_fall
                    best_candidate = new_candidate

            if best_fall > 0:
                g.add_edge((i, j), best_candidate)

    return connected_components(g)
예제 #32
0
def read(string):
    """
    Read a graph from a XML document and return it. Nodes and edges specified in the input will
    be added to the current graph.
    
    @type  string: string
    @param string: Input string in XML format specifying a graph.
    
    @rtype: graph
    @return: Graph
    """
    dom = parseString(string)
    if dom.getElementsByTagName("graph"):
        graph = pygraph.graph()
    elif dom.getElementsByTagName("digraph"):
        graph = pygraph.digraph()
    else:
        raise InvalidGraphType
    
    # Read nodes...
    for each_node in dom.getElementsByTagName("node"):
        graph.add_node(each_node.getAttribute('id'))
        for each_attr in each_node.getElementsByTagName("attribute"):
            graph.add_node_attribute(each_node.getAttribute('id'),
                                     (each_attr.getAttribute('attr'),
                each_attr.getAttribute('value')))

    # Read edges...
    for each_edge in dom.getElementsByTagName("edge"):
        graph.add_edge(each_edge.getAttribute('from'), each_edge.getAttribute('to'), \
            wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
        for each_attr in each_edge.getElementsByTagName("attribute"):
            attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
            if (attr_tuple not in graph.edge_attributes(each_edge.getAttribute('from'), \
                each_edge.getAttribute('to'))):
                graph.add_edge_attribute(each_edge.getAttribute('from'), \
                    each_edge.getAttribute('to'), attr_tuple)
    
    return graph
예제 #33
0
 def testNodeWithEdgeToItselfRemoval(self):
     gr = pygraph.graph()
     gr.add_node(0)
     gr.add_edge(0, 0)
     gr.del_node(0)
 def setUp(self):
     self.G = pygraph.graph()
     nations_of_the_world(self.G)
예제 #35
0
 def testTrivalEquality0(self):
     gr1 = pygraph.graph()
     gr2 = pygraph.graph()
     assert gr1 == gr2, "All zero node graphs should be equivalent to each other."
예제 #36
0
 def testNoCycleGraph(self):
     G = pygraph.graph()
     G.add_nodes([1,2,3])
     G.add_edge(1, 2)
     G.add_edge(1, 3)
     assert G.find_cycle() == []
예제 #37
0
def main():
    #bla = r"D:\Project CodeJam\Test\A-large.in"
    bla = r"D:\Project CodeJam\Test\B-large.in"

    f = open(bla)
    lines = f.readlines()
    f.close()

    f_write = open(r"D:\Project CodeJam\Test\output10.txt", "w")
    num_maps = int(lines[0])

    curr_line = 0
    for map_index in range(1, num_maps + 1):
        curr_line += 1
        line = lines[curr_line]

        (height, width) = tuple(int(x) for x in line.split(" "))
        matrix = []

        for h in range(height + 2):
            matrix.append([])
            for w in range(width + 2):
                matrix[h].append(None)

        for h in range(1, height + 1):
            curr_line += 1
            line = lines[curr_line]
            rainage = line.split(" ")
            for w in range(1, width + 1):
                matrix[h][w] = (False, int(rainage[w - 1]))

        # Now for each of the nodes I need to find the cell to which the stream goes down to

        g = pygraph.graph()

        # Find a better way to do this
        for h in range(1, height + 1):
            for w in range(1, width + 1):
                g.add_nodes([(h, w)])

        for h in range(1, height + 1):
            for w in range(1, width + 1):
                # calc min min_indexes rainage[w],
                (neig_h_index, neig_w_index) = get_min_indices(matrix, h, w)
                if (neig_h_index, neig_w_index) != (h, w):
                    g.add_edge((h, w), (neig_h_index, neig_w_index))

        letter = 'a'
        for h in range(1, height + 1):
            for w in range(1, width + 1):
                if matrix[h][w][0]:  # Already been in this node
                    continue
                st, pre, post = pygraph.algorithms.searching.depth_first_search(
                    g, root=(h, w))
                for (h_go, w_go) in st:
                    matrix[h_go][w_go] = (True, letter)
                letter = chr(ord(letter) + 1)

        new_str = "Case #%d:\n" % (map_index, )
        f_write.write(new_str)
        for h in range(1, height + 1):
            new_str = "%s\n" % " ".join(
                [matrix[h][w_go][1] for w_go in range(1, width + 1)])
            f_write.write(new_str)
    f_write.close()
    print "Done"
예제 #38
0
파일: main.py 프로젝트: mvendra/pygraph
def main():
  mg = pygraph.graph(True)
  mg.debug()
예제 #39
0
 def testEmptyGraphComplete(self):
     gr = pygraph.graph()
     gr.complete()
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])
예제 #40
0
 def testGraphWithOneNodeComplete(self):
     gr = pygraph.graph()
     gr.add_node(0)
     gr.complete()
     self.assertTrue(gr.nodes() == [0])
     self.assertTrue(gr.edges() == [])
예제 #41
0
 def testEmptyGraphInverse(self):
     gr = pygraph.graph()
     inv = gr.inverse()
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])
예제 #42
0
 def testRandomEmptyGraph(self):
     gr = pygraph.graph()
     gr.generate(0, 0)
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])
예제 #43
0
 def testEmptyGraphInverse(self):
     gr = pygraph.graph()
     inv = gr.inverse()
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])
예제 #44
0
 def testEmptyGraphComplete(self):
     gr = pygraph.graph()
     gr.complete()
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])
예제 #45
0
 def testGraphWithOneNodeComplete(self):
     gr = pygraph.graph()
     gr.add_node(0)
     gr.complete()
     self.assertTrue(gr.nodes() == [0])
     self.assertTrue(gr.edges() == [])
예제 #46
0
def read(string):
    """
    Read a graph from a string in Dot language and return it. Nodes and edges specified in the
    input will be added to the current graph.
    
    @type  string: string
    @param string: Input string in Dot format specifying a graph.
    
    @rtype: graph
    @return: Graph
    """
    
    # Lazy import
    try:
        import pydot
    except:
        print "Error: You must first install the pydot package: http://code.google.com/p/pydot/"
        return
    
    dotG = pydot.graph_from_dot_data(string)
    
    if (dotG.get_type() == "graph"):
        graph = pygraph.graph()
    elif (dotG.get_type() == "digraph"):
        graph = pygraph.digraph()
    else:
        raise InvalidGraphType
    
    # Read nodes...
    # Note: If the nodes aren't explicitly listed, they need to be
    for each_node in dotG.get_nodes():
        graph.add_node(each_node.get_name())
        for each_attr_key, each_attr_val in each_node.get_attributes().items():
            graph.add_node_attribute(each_node.get_name(), (each_attr_key, each_attr_val))
    
    # Read edges...
    for each_edge in dotG.get_edges():
        # Check if the nodes have been added
        if not dotG.get_node(each_edge.get_source()):
            graph.add_node(each_edge.get_source())
        if not dotG.get_node(each_edge.get_destination()):
            graph.add_node(each_edge.get_destination())
        
        # See if there's a weight
        if 'weight' in each_edge.get_attributes().keys():
            _wt = each_edge.get_attributes()['weight']
        else:
            _wt = 1
        
        # See if there is a label
        if 'label' in each_edge.get_attributes().keys():
            _label = each_edge.get_attributes()['label']
        else:
            _label = ''
        
        graph.add_edge(each_edge.get_source(), each_edge.get_destination(), wt = _wt, label = _label)
        
        for each_attr_key, each_attr_val in each_edge.get_attributes().items():
            if not each_attr_key in ['weight', 'label']:
                graph.add_edge_attribute(each_edge.get_source(), each_edge.get_destination(), \
                                            (each_attr_key, each_attr_val))
    
    return graph
예제 #47
0
 def testTrivalEquality1(self):
     gr1 = pygraph.graph()
     gr1.add_node(0)
     gr2 = pygraph.graph()
     gr2.add_node(0)
     assert gr1 == gr2, "All one node graphs should be equivalent to each other."
예제 #48
0
#!/usr/bin/env python

# Copyright (c) 2007-2008 Pedro Matiello <*****@*****.**>
# License: MIT (see COPYING file)

import sys
sys.path.append('..')
import pygraph
sys.path.append('/usr/lib/graphviz/python/')
sys.path.append('/usr/lib64/graphviz/python/')
import gv
from pygraph.algorithms.searching import breadth_first_search

# Graph creation
gr = pygraph.graph()

# Add nodes and edges
gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"])
gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"])
gr.add_nodes(["England","Ireland","Scotland","Wales"])

gr.add_edge("Portugal", "Spain")
gr.add_edge("Spain","France")
gr.add_edge("France","Belgium")
gr.add_edge("France","Germany")
gr.add_edge("France","Italy",)
gr.add_edge("Belgium","Netherlands")
gr.add_edge("Germany","Belgium")
gr.add_edge("Germany","Netherlands")
gr.add_edge("England","Wales")
gr.add_edge("England","Scotland")
예제 #49
0
 def testAddEmptySpanningTree(self):
     gr = pygraph.graph()
     st = {}
     gr.add_spanning_tree(st)
     self.assertTrue(gr.nodes() == [])
     self.assertTrue(gr.edges() == [])