Exemplo n.º 1
0
def generate_graph(n, max_neighbours=999):
    """
    Guarantees: This is a fully connected graph with one giant component, so one can start anywhere and connect all the nodes.
    """
    assert n >= max_neighbours + 1

    start_node = GraphNode(0)
    nodes = [start_node]
    n_start_neighbours = random.randint(1, max_neighbours - 1)
    nodes += [
        GraphNode(i, [start_node]) for i in range(1, n_start_neighbours + 1)
    ]

    n -= n_start_neighbours + 1

    while n > 0:
        n_neighbours = random.randint(0, max_neighbours)
        n_neighbours = n_neighbours if n_neighbours <= n else n
        lower_bound = random.randint(0, len(nodes) - 1)
        upper_bound = random.randint(lower_bound, len(nodes))
        random_nodes = nodes[lower_bound:upper_bound]

        new_neighbours = [
            GraphNode(random.random(), random_nodes)
            for i in range(n_neighbours)
        ]

        nodes += new_neighbours

        n -= n_neighbours

    #print([(node.data, list(map(lambda x: x.data, node.neighbours))) for node in nodes])
    for node in nodes:
        print(str(node.data) + "    and " + str(node.neighbours))
Exemplo n.º 2
0
    def generateGraph1(self):
        self.a = GraphNode('a')
        self.b = GraphNode('b')
        self.c = GraphNode('c')
        self.b1 = GraphNode('b1')
        self.b2 = GraphNode('b2')

        self.g = Graph(self.a)
        self.g.connect(self.a, [self.b, self.c])
        self.g.connect(self.c, [self.b1])
        self.g.connect(self.c, [self.b2])
        self.g.connect(self.b1, [self.b2])
Exemplo n.º 3
0
    def clone(self, node: 'GraphNode'):
        if not node:
            return None
        
        if node in self.visited:
            return self.visited[node]

        clone_node = GraphNode(node.val, [])
        self.visited[node] = clone_node

        if node.neighbors:
            clone_node.neighbors = [self.clone(n) for n in node.neighbors]
        
        
        return clone_node
Exemplo n.º 4
0
def kruskal(graph):
    sortedE = []

    for lst in graph:
        for edge in lst:
            sortedE.append(edge)

    sortedE.sort(key=lambda e: e.weight)  # sort by weight
    item = GraphNode(6, weighted=True, directed=False)  # 6 is # of numbers (?)

    for edge in sortedE:
        if not item.contains_cyle():
            item.insert(edge.source, edge.dest, edge.weight)

    return item
Exemplo n.º 5
0
    def testGraphCreation(self):
        a = GraphNode('a')
        b = GraphNode('b')
        c = GraphNode('c')
        b1 = GraphNode('b1')

        g = Graph(a)
        g.connect(a, [b, c])
        g.connect(c, [b1])

        edgeList = [a, b, c, b1]
        expectedEdgeSetList = [set([b, c]), set(), set([b1]), set()]
        for edge, expectedEdgeSet in zip(edgeList, expectedEdgeSetList):
            actualEdgeSetList = set(g.edges[edge])
            self.assertTrue(len(expectedEdgeSet - actualEdgeSetList) == 0, "There should not be extra edges")
Exemplo n.º 6
0
def three():
    a = GraphNode('a', A(1, 'a'))
    b = GraphNode('b', B('b'))
    c = GraphNode('c', A(9, 'c'))
    b1 = GraphNode('b1', A(2, 'b1'))
    b2 = GraphNode('b2', B('b2'))

    g = Graph(a)
    g.connect(a, [b, c])
    g.connect(c, [b1])
    g.connect(c, [b2])
    g.connect(b1, [b2])

    Graph.executeGraph(g)

    assert b2.future.result() == 'heckles'
Exemplo n.º 7
0
 def AddSimpleNode(self, id):
     if self.graph.FindNodeById(id):
         id += str(random.randint(1, 9999))
     t, l, w, h = random.randint(0, 100), random.randint(
         0, 100), random.randint(60, 160), random.randint(60, 160)
     node = GraphNode(id, t, l, w, h)
     node = self.graph.AddNode(node)
     return node
Exemplo n.º 8
0
 def findCheapestPrice(self, n: int, flights: List[List[int]], src: int,
                       dst: int, K: int) -> int:
     nodes = [GraphNode(i) for i in range(0, n)]
     for flight in flights:
         [n0, n1, price] = flight
         nodes[n0].addEdge(n1, price)
     graph = Graph(nodes)
     price, flights = graph.djikstraK(nodes[src], nodes[dst], K + 2)
     print("Flight from %d to %d with %d stops for $%d -- %s" %
           (src, dst, K, price, flights))
     return price
Exemplo n.º 9
0
    def pixels_to_graph(self) -> List[GraphNode]:
        nodes: Dict[Coordinates, GraphNode] = {}
        for x in range(0, self.size[0]):
            for y in range(0, self.size[1]):
                if self.pixels[x, y]:
                    coords = Coordinates(x, y)
                    node = GraphNode(coords)
                    nodes[coords] = node

        for coords, node in nodes.items():
            # negative is for up and left, positive for down and right
            for direction in [-1, +1]:
                # 0 is for y (up and down), 1 for x (left and right)
                for axis in [0, 1]:
                    look_coords = Coordinates(
                        coords.x + abs(axis - 1) * direction,
                        coords.y + axis * direction)
                    if look_coords in nodes:
                        node.add_neighbour(nodes[look_coords])

        return list(nodes.values())
Exemplo n.º 10
0
def _test():
    pass
    node1 = GraphNode(1)
    node2 = GraphNode(2)
    node3 = GraphNode(3)
    node4 = GraphNode(4)
    node1.adjacent.append(node2)
    node2.adjacent.append(node3)
    node4.adjacent.append(node3)
    graph1 = Graph(node1, node2, node3, node4)
    """
    1 --> 2 --> 3 <-- 4
    """
    assert search(graph1, node1, node4) is False
    graph1.reset()
    assert search(graph1, node2, node3) is True
    graph1.reset()
    assert search2(graph1, node1, node4) is False
    graph1.reset()
    assert search2(graph1, node2, node3) is True
    graph1.reset()
Exemplo n.º 11
0
    def generateGraph2(self):
        five = GraphNode('5')
        seven = GraphNode('7')
        three = GraphNode('3')
        eleven = GraphNode('11')
        eight = GraphNode('8')
        two = GraphNode('2')
        nine = GraphNode('9')
        ten = GraphNode('10')

        self.g2 = Graph(five)
        self.g2.connect(five, [eleven])
        self.g2.connect(seven, [eleven, eight])
        self.g2.connect(three, [eight, ten])
        self.g2.connect(eleven, [two, nine, ten])
        self.g2.connect(eight, [nine])
class Test(unittest.TestCase):
    # 0--->1<----2
    # |  \ |  \  ^
    # v   vv    v|
    # 5    4<----3

    graph = Graph()
    sizegraph = 8
    temp: List[GraphNode] = []

    temp.append(GraphNode("0", 3))
    temp.append(GraphNode("1", 2))
    temp.append(GraphNode("2", 1))
    temp.append(GraphNode("3", 2))
    temp.append(GraphNode("4", 0))
    temp.append(GraphNode("5", 5))
    temp.append(GraphNode("6", 6))
    temp.append(GraphNode("7", 7))

    temp[0].add_adjacent(temp[1])
    temp[0].add_adjacent(temp[4])
    temp[0].add_adjacent(temp[5])
    temp[1].add_adjacent(temp[4])
    temp[1].add_adjacent(temp[3])
    temp[2].add_adjacent(temp[1])
    temp[3].add_adjacent(temp[2])
    temp[3].add_adjacent(temp[4])
    temp[6].add_adjacent(temp[7])

    for i in range(sizegraph):
        graph.add_node(temp[i])

    def test_route_between_nodes(self):
        self.assertEqual(
            True, route_between_nodes(self.graph, self.temp[0], self.temp[3]))
        self.assertEqual(
            False, route_between_nodes(self.graph, self.temp[0], self.temp[6]))
Exemplo n.º 13
0
        self.checkGraphOrdering(g)

        g = self.g2
        self.checkGraphOrdering(g)

    def testGetSortedTiers(self):
        g = self.g

        tiers = Graph.getSortedTiers(g)
        expectedNodeList = [['a'], ['b', 'c'], ['b1'], ['b2']]
        for level in range(len(tiers)):
            self.assertTrue(len(expectedNodeList[level]) == len(tiers[level]), "Tier nodes have different lenghts")
            for actual in tiers[level]:
                self.assertTrue(actual[0].name in expectedNodeList[level], "Unexpected node found in tier")

if __name__ == '__main__':
        a = GraphNode('a')
        b = GraphNode('b')
        c = GraphNode('c')
        b1 = GraphNode('b1')
        b2 = GraphNode('b2')

        g = Graph(a)
        g.connect(a, [b, c])
        g.connect(c, [b1])
        g.connect(c, [b2])
        g.connect(b1, [b2])
        g.connect(b2, [b1])
        print(Graph.getSortedTiers(g))

Exemplo n.º 14
0
 def __init__(self, id, left, top, width=60, height=60, attrs=[], meths=[]):
     GraphNode.__init__(self, id, left, top, width=60, height=60)
     self.attrs = attrs
     self.meths = meths
     self.shape = None
Exemplo n.º 15
0
 def __init__(self, id, left, top, width=60, height=60, comment=""):
     GraphNode.__init__(self, id, left, top, width=60, height=60)
     self.comment = comment
     self.shape = None
Exemplo n.º 16
0
            #print

            if node.left > 20000:
                print '-' * 40, "Something's gone wrong!"
                print "node.layoutPosX, node.layoutPosY", node.layoutPosX, node.layoutPosY
                self.DumpCalibrationInfo(False)
                raise CustomException("Insane x values being generated")


if __name__ == '__main__':

    from graph import Graph, GraphNode

    g = Graph()

    n1 = GraphNode('A', 0, 0, 200, 200)
    n2 = GraphNode('B', 0, 0, 200, 200)
    g.AddEdge(n1, n2)
    """
    coordinate mapper translation tests
    """

    # Force some values
    g.layoutMaxX, g.layoutMinX, g.layoutMaxY, g.layoutMinY = 5.14284838307, -7.11251323652, 4.97268108065, -5.77186339003

    c = CoordinateMapper(g, (784, 739))

    # LayoutToWorld

    res = c.LayoutToWorld((-2.7556504645221258, 0.39995144721675263))
    print res
Exemplo n.º 17
0
 def __init__(self, id, left, top, width=60, height=60, comment=""):
     GraphNode.__init__(self, id, left, top, width=60, height=60)
     self.comment = comment
     self.shape = None
Exemplo n.º 18
0
 def __init__(self, id, left, top, width=60, height=60, attrs=[], meths=[]):
     GraphNode.__init__(self, id, left, top, width=60, height=60)
     self.attrs = attrs
     self.meths = meths
     self.shape = None
Exemplo n.º 19
0
    stack = [root]

    while len(stack) > 0:
        current_node = stack.pop()
        visited.append(current_node)

        if current_node.value == value:
            return current_node
        
        for child in current_node.children:
            if child not in visited:
                stack.append(child)


if __name__ == '__main__':
    nodeG = GraphNode('G')
    nodeR = GraphNode('R')
    nodeA = GraphNode('A')
    nodeP = GraphNode('P')
    nodeH = GraphNode('H')
    nodeS = GraphNode('S')

    graph1 = Graph([nodeS, nodeH, nodeG, nodeP, nodeR, nodeA]) 
    graph1.add_edge(nodeG, nodeR)
    graph1.add_edge(nodeA, nodeR)
    graph1.add_edge(nodeA, nodeG)
    graph1.add_edge(nodeR, nodeP)
    graph1.add_edge(nodeH, nodeG)
    graph1.add_edge(nodeH, nodeP)
    graph1.add_edge(nodeS, nodeR)
Exemplo n.º 20
0
            d[tuple(x)] = x
        return d.values()

    result = [r for r in result if r != None]
    result = remove_duplicates(result)
    return result


if __name__ == '__main__':
    res = FindLineIntersection((0, 0), (200, 200), (10, 10), (10, 50))
    assert res == [10.0, 10.0]

    res = FindLineIntersection((0, 30), (200, 30), (10, 10), (10, 50))
    assert res == [10.0, 30.0]

    node = GraphNode("A", 10, 10, 30, 40)
    assert len(node.lines) == 4
    assert (10, 10) in node.lines[0]
    assert (40, 10) in node.lines[0]
    assert (40, 10) in node.lines[1]
    assert (40, 50) in node.lines[1]
    assert (40, 50) in node.lines[2]
    assert (10, 50) in node.lines[2]
    assert (10, 50) in node.lines[3]
    assert (10, 10) in node.lines[3]

    res = CalcLineIntersectionsWithNode((0, 0), (200, 200), node)
    assert len(res) == 2
    assert [10.0, 10.0] in res
    assert [40.0, 40.0] in res
Exemplo n.º 21
0
                demen[i][j] = demen[i - 1][j - 1]

            else:
                demen[i][j] = 1 + min(demen[i][j - 1],      # Insert
                                      demen[i - 1][j],      # Remove
                                      demen[i - 1][j - 1])  # Replace

    return demen[-1][-1]


s1 = "Hello"
s2 = "Hello"

print(edit_distance(s1, s2))
print()
# Test Cases

n = GraphNode(6, weighted=True, directed=True)
n.insert(4, 4, 1)
n.insert(5, 2, 3)
n.insert(4, 3, 2)
n.insert(3, 4, 1)  # Numbers can change to test
n.insert(2, 5, 0)
n.insert(1, 1, 4)
n.display()

wow = kruskal(n.al)
wow.display()

print(topological_sort(n))
Exemplo n.º 22
0
def route_exists(node1, node2):
    if node1 == node2:
        return True
    if node1 == None:
        return False



    queue = []
    node1.marked = True
    queue.append(node1)

    while len(queue) != 0:
        r = queue.pop(0)
        for n in r.children:
            found_path = found_path or route_exists(n, node2)
            if n.marked:
                n.marked = True
                queue.append(n)

    return found_path

start = GraphNode(1)
end = GraphNode(2)

print(route_exists(start, start))

start.children.append(end)

print(route_exists(start, end))
Exemplo n.º 23
0
def main():
    """main function"""
    node1 = GraphNode(name="1", value=1)
    node2 = GraphNode(name="2", value=2)
    node3 = GraphNode(name="3", value=3)
    node4 = GraphNode(name="4", value=4)

    node1.add_children([(node3, 3), (node4, 10)])
    node3.add_children([(node2, 1), (node1, 2)])
    node4.add_children([(node2, 4)])

    node5 = GraphNode(name="5", value=5, children=[(node1, 10)])

    graph = Graph([node1, node2, node3, node4])
    graph.add_node(node5)
    print(shortest_path(graph, node1, node2, 0, []))
    print("Topological Sorting: ", end="")
    print(list(reversed([n.val for n in res])))


def topo_sort_recursive(n: GraphNode, visited: Dict[GraphNode, bool],
                        res: List[GraphNode]) -> List[GraphNode]:
    visited[n] = True
    for edge in n.edges:
        if not (visited[edge]):
            topo_sort_recursive(edge, visited, res)
    res.append(n)
    return res


# Driver code for an acyclic, connected graph
a = GraphNode(0)
b = GraphNode(1)
c = GraphNode(2)

a.edges.append(b)
a.edges.append(c)
b.edges.append(c)

a.print_edges()
nodes = [a, b, c]

dfs(a)
dfs(b)

bfs(a)