예제 #1
0
    def test_get_vertices(self):

        graph = Graph()
        solution = set()

        # (1) test empty graph
        subject = graph.get_vertices()
        self.assertEqual(subject, solution)

        # (2) test single vertex
        vertex = Vertex('$')
        graph.vertices['$'] = vertex
        solution.add(vertex)
        subject = graph.get_vertices()
        self.assertEqual(subject, solution)

        # (3) test multiple vertices
        graph = Graph()
        solution = set()
        for i, char in enumerate(string.ascii_lowercase):
            vertex = Vertex(char)
            graph.vertices[char] = vertex
            solution.add(vertex)
        subject = graph.get_vertices()
        self.assertEqual(subject, solution)
예제 #2
0
    def test_08_add_to_graph(self):

        graph = Graph()

        # Test creation of single vertex
        graph.add_to_graph('a')
        size = graph.size
        assert size == 1
        subject = graph.get_vertices()
        assert subject == [Vertex('a')]

        graph.add_to_graph('b')
        size = graph.size
        assert size == 2
        subject = graph.get_vertices()
        subject_set = set(subject)
        solution_set = set([Vertex('a'), Vertex('b')])
        assert subject_set == solution_set

        # Test creation of edge between existing vertices
        graph.add_to_graph('a', 'b', 331)
        size = graph.size
        assert size == 2
        subject = graph.get_edges()
        assert subject == [('a', 'b', 331)]

        graph.add_to_graph('b', 'a', 1855)
        size = graph.size
        assert size == 2
        subject = graph.get_edges()
        subject_set = set(subject)
        solution_set = set([('a', 'b', 331), ('b', 'a', 1855)])
        assert subject_set == solution_set
예제 #3
0
    def test_get_edge(self):

        graph = Graph()

        # (1) neither end vertex exists
        subject = graph.get_edge('a', 'b')
        self.assertIsNone(subject)

        # (2) one end vertex exists
        graph.vertices['a'] = Vertex('a')
        subject = graph.get_edge('a', 'b')
        self.assertIsNone(subject)

        # (3) both end vertices exist, but no edge
        graph.vertices['a'] = Vertex('a')
        graph.vertices['b'] = Vertex('b')
        subject = graph.get_edge('a', 'b')
        self.assertIsNone(subject)

        # (4) a -> b exists but b -> a does not
        graph.vertices.get('a').adj['b'] = 331
        subject = graph.get_edge('a', 'b')
        self.assertEqual(subject, ('a', 'b', 331))
        subject = graph.get_edge('b', 'a')
        self.assertIsNone(subject)

        # (5) connect all vertices to center vertex and return all edges
        graph.vertices['$'] = Vertex('$')
        for i, char in enumerate(string.ascii_lowercase):
            graph.vertices[char] = Vertex(char)
            graph.vertices.get('$').adj[char] = i
        for i, char in enumerate(string.ascii_lowercase):
            subject = graph.get_edge('$', char)
            self.assertEqual(subject, ('$', char, i))
예제 #4
0
    def test_14_construct_from_csv(self):

        graph = Graph()

        # Empty csv
        graph.construct_from_csv('test1.csv')
        assert graph == Graph()

        # Varied, different edge weights
        graph.construct_from_csv('test2.csv')
        size = graph.size
        assert size == 3
        e_subject = graph.get_edges()
        e_subject_set = set(e_subject)
        v_subject = graph.get_vertices()
        v_subject_set = set(v_subject)
        vertex_a = Vertex('a')
        vertex_b = Vertex('b')
        vertex_c = Vertex('c')
        vertex_b.adj['a'] = 2.0
        vertex_b.adj['c'] = 3.0
        vertex_c.adj['b'] = 1.0
        vertex_a.adj['b'] = 1.0
        v_solution_set = set([vertex_a, vertex_b, vertex_c])
        e_solution_set = set([('a', 'b', 1.0), ('b', 'a', 2.0),
                              ('c', 'b', 1.0), ('b', 'c', 3.0)])
        assert e_subject_set == e_solution_set
        assert v_subject_set == v_solution_set
예제 #5
0
def get_test_graph():
    """
    Creates and returns a simple test graph
    :return: a Graph.py representation of a set graph
    """
    one = Vertex(0, 0, 0)
    two = Vertex(1, 10, 2)
    one_two = Edge(one, two, 5)
    three = Vertex(2, 20, 65)
    two_three = Edge(two, three, 3)
    four = Vertex(3, 32, 30)
    one_four = Edge(one, four, 1)
    five = Vertex(4, 9, 40)
    four_five = Edge(four, five, 6)
    six = Vertex(5, 50, 44)
    four_six = Edge(four, six, 4)
    seven = Vertex(6, 60, 5)
    six_seven = Edge(six, seven, 9)
    eight = Vertex(7, 0, 70)
    five_eight = Edge(five, eight, 1)
    nine = Vertex(8, 9, 80)
    eight_nine = Edge(eight, nine, 3)
    three_nine = Edge(three, nine, 2)
    return Graph([
        one_two, one_four, two_three, four_five, four_six, six_seven,
        five_eight, eight_nine, three_nine
    ])
예제 #6
0
    def test_10_construct_from_matrix(self):

        graph = Graph()

        # Test empty matrix
        matrix = [[]]
        graph.construct_from_matrix(matrix)
        size = graph.size
        assert size == 0
        v_subject = graph.get_vertices()
        e_subject = graph.get_edges()
        assert v_subject == []
        assert e_subject == []

        # Test single vertex with no connection
        matrix = [[None, 'a'], ['a', None]]
        graph.construct_from_matrix(matrix)
        size = graph.size
        assert size == 1
        v_subject = graph.get_vertices()
        e_subject = graph.get_edges()
        assert v_subject == [Vertex('a')]
        assert e_subject == []

        # Test single vertex with connection
        graph = Graph()
        matrix = [[None, 'a'], ['a', 331]]
        graph.construct_from_matrix(matrix)
        size = graph.size
        assert size == 1
        e_subject = graph.get_edges()
        assert e_subject == [('a', 'a', 331)]

        # Test two vertices with no connection
        graph = Graph()
        matrix = [[None, 'a', 'b'], ['a', None, None], ['b', None, None]]
        graph.construct_from_matrix(matrix)
        size = graph.size
        assert size == 2
        v_subject = graph.get_vertices()
        v_subject_set = set(v_subject)
        e_subject = graph.get_edges()
        assert v_subject_set == set([Vertex('a'), Vertex('b')])
        assert e_subject == []

        # Test two vertices with 2-way connection
        graph = Graph()
        matrix = [[None, 'a', 'b'], ['a', None, 100], ['b', 200, None]]
        graph.construct_from_matrix(matrix)
        size = graph.size
        assert size == 2
        e_subject = graph.get_edges()
        e_subject_set = set(e_subject)
        assert e_subject_set == set([('a', 'b', 100), ('b', 'a', 200)])
예제 #7
0
    def test_reset_vertices(self):

        graph = Graph()

        # (1) visit all vertices then reset
        graph.vertices['a'] = Vertex('a')
        graph.vertices['b'] = Vertex('b')

        for vertex in graph.vertices.values():
            vertex.visited = True
        graph.reset_vertices()
        for vertex in graph.vertices.values():
            self.assertFalse(vertex.visited)
예제 #8
0
def main(script, n='5', *args):

    # create n Vertices
    n = int(n)
    #labels = string.ascii_lowercase + string.ascii_uppercase
    #vs = [Vertex(c) for c in labels[:n]]

    v = Vertex('v')
    v.pos = (1110,-100)

    w = Vertex('w')
    w.pos = (20000,40)

    x = Vertex('x')
    x.pos = (100,-2000)

    y = Vertex('y')
    y.pos = (-15,15000)

    # create a graph and a layout
    g = Graph([v, w, x, y])
    g.add_all_edges()
    # layout = CircleLayout(g)
    # layout = RandomLayout(g)
    layout = CartesianLayout(g)

    # draw the graph
    gw = GraphWorld()
    gw.show_graph(g, layout)
    gw.mainloop()
예제 #9
0
    def test_degree(self):

        # (1) test a-->b and a-->c
        vertex = Vertex('a')
        vertex.adj['b'] = 1
        self.assertEqual(vertex.degree(), 1)
        vertex.adj['c'] = 3
        assert vertex.degree() == 2

        # (2) test a-->letter for all letters in alphabet
        vertex = Vertex('a')
        for i, char in enumerate(string.ascii_lowercase):
            self.assertEqual(vertex.degree(), i)
            vertex.adj[char] = i
예제 #10
0
    def test_05_reset_vertices(self):

        graph = Graph()

        # Add and visit vertices
        graph.vertices['a'] = Vertex('a')
        graph.vertices['b'] = Vertex('b')

        for vertex in graph.vertices.values():
            vertex.visit()

        # Reset graph and check
        graph.reset_vertices()
        for vertex in graph.vertices.values():
            assert not vertex.visited
예제 #11
0
def main():
    env = XYEnvironment(x_size=10, y_size=10, n_grid_x=30, n_grid_y=30)

    threat1 = GaussThreat(location=(2, 2), shape=(0.5, 0.5), intensity=5)
    threat2 = GaussThreat(location=(6, 5), shape=(1.0, 1.0), intensity=5)
    threat3 = GaussThreat(location=(8, 2), shape=(.25, .5), intensity=10)
    threats = [threat1, threat2, threat3]

    threat_field = GaussThreatField(threats=threats, offset=2)

    threat4 = GaussThreat(location=(2, 8), shape=(0.5, 0.5), intensity=5)
    threat_field.add_threat(threat4)
    env.add_threat_field(threat_field)

    print(env)

    node_list = {}
    for gridpt in range(env.n_grid):
        mx = gridpt % env.n_grid_x
        my = int(gridpt / env.n_grid_x)
        new_node = XYNode(node_id=gridpt)
        new_node.pos_x = mx * env.grid_sep_x
        new_node.pos_y = my * env.grid_sep_y
        node_list[gridpt] = new_node
        print(new_node)

    graph = Graph(env=env)
    graph.add_vertex(node_list[0])
    start_vertex = graph.get_vertex(node_list[0])
    print("Start vertex: ", start_vertex)

    neighbor_list = graph.env.get_neighbors(start_vertex.node)
    print("neighbor_list")
    print(neighbor_list)
    for nbr in neighbor_list:
        print(nbr)
        graph.add_edge(start_vertex.node, nbr, 1.0)

    for neighbor in start_vertex.neighbors:
        print(neighbor)

    print("Run A* search")
    goal_vertex = Vertex(node=node_list[env.n_grid - 1])
    print(goal_vertex.node)

    goal_vertex_found = Astar(graph=graph, start_vertex=start_vertex, goal_vertex=goal_vertex)
    print(goal_vertex_found)

    path = [goal_vertex_found.node]
    reconstruct_path(goal_vertex_found, path)
    print("Path found :")
    for waypoint in path:
        print(waypoint)

    draw_threat_field(env=env, threat_field=threat_field)

    ax2 = draw_threat_field_2D(env=env, threat_field=threat_field)

    draw_path(ax=ax2, path=path)
    plt.show()
예제 #12
0
def makeGraph(n='52', k='5', p='0.1'):
    #create n Vertices
    n = int(n)
    k = int(k)
    p = float(p)

    names = name_generator()
    vs = [Vertex(names.next()) for c in range(n)]

    # create a graph
    g = SmallWorldGraph(vs, k, p)
    start = clock()
    g.char_length()
    charLength1 = clock() - start

    start = clock()
    g.char_length2()
    charLength2 = clock() - start

    start = clock()
    g.char_length3()
    charLength3 = clock() - start

    start = clock()
    g.char_length4()
    charLength4 = clock() - start
    return charLength1, charLength2, charLength3, charLength4
예제 #13
0
    def single_time_step(self):
        """
        @Args:
            None
        @Returns:
            None
        Executes a single time step in a Barabasi-Albert Graph.
        """
        w = Vertex(self.iter_labels.next())
        self.add_vertex(w)
        #We add an equal number of in and out-arcs, so we need to check
        #if the number of arcs we add is even or odd
        if self.mo % 2 == 1:
            m = self.mo - 1
        else:
            m = self.mo

        #Since the histograms contain more instances of vertices that are more
        #connected, if we randomly sample them, we'll get preferential
        #attachment. Adapted from the NetworkX implementation of
        #Barabasi-Albert graphs.

        for v in random.sample(self._node_in_histogram, m / 2):
            self.add_arc(Arc(w, v))
            self._node_in_histogram.append(v)

        for v in random.sample(self._node_out_histogram, m / 2):
            self.add_arc(Arc(v, w))
            self._node_in_histogram.append(w)
            self._node_out_histogram.append(v)

        #We've created a bunch of out arcs from our new vertex,
        #so we need to add those arcs to our histogram.
        self._node_out_histogram.extend([w for i in range(m / 2)])
예제 #14
0
def read(filename):
    """Returns Vertexes using the data from the file with the given filename"""
    with open(filename) as fp:
        lines = fp.readlines()
    first_line_to_read = [i for i, line in enumerate(lines) if 'NODE_COORD_SECTION' in line][0] + 1
    last_line_to_read = [i for i, line in enumerate(lines) if 'EOF' in line][0]
    cities = list()
    for city_data in lines[first_line_to_read:last_line_to_read]:
        city_data = city_data.split(' ')
        label = city_data[0]
        c = Vertex(label)
        c.x = int(city_data[1])
        c.y = int(city_data[2])
        cities.append(c)

    return cities
예제 #15
0
def main(script, n='1000', *args):

    #     # create n Vertices
    #     n = int(n)
    #     labels = string.ascii_lowercase + string.ascii_uppercase
    #     vs = [Vertex(c) for c in labels[:n]]
    #
    #     # create a graph and a layout
    #     g = RandomGraph(vs)
    #     g.add_random_edges(0.015)
    #     print g.is_connected()
    #     layout = GraphWorld.CircleLayout(g)
    #
    #     # draw the graph
    #     gw = GraphWorld.GraphWorld()
    #     gw.show_graph(g, layout)
    #     gw.mainloop()
    for n in range(100, 10000, 1000):
        for p in range(1, 100):
            p = p / 100.0
            success = 0
            for each in range(1000):
                vs = [Vertex(str(c)) for c in range(n)]
                g = RandomGraph(vs)
                g.add_random_edges(p)
                success += g.is_connected()
            pct = float(success) / 1000
            print 'N: %s\t\tp: %s\t\t pct connected: %s' % (n, p, pct)
예제 #16
0
 def make_helper():
     if solvable():
         queue = deque()
         queue.append(self.graph.V[0])
         while self.graph.search_data(self.target) == -1:
             if self.graph.n_vertex >= 9**4:
                 break
             vertex: Vertex = queue.popleft()
             for index in range(
                     4
             ):  # Generate all adjacent, and add the closest to the target to the queue
                 neg: [int] = vertex.data.copy()
                 pos: [int] = vertex.data.copy()
                 neg[index] -= 1
                 normalize(neg)
                 pos[index] += 1
                 normalize(pos)
                 to_add: [[int]] = [neg, pos]
                 for neighbor in to_add:
                     if neighbor not in self.forbidden:
                         existent = self.graph.search_data(neighbor)
                         if existent == -1:
                             addition_ver = Vertex(neighbor.copy())
                             self.graph.add_vertex(addition_ver)
                             self.graph.add_edge(vertex, addition_ver)
                             if self.graph.search_data(
                                     self.target) != -1:
                                 return
                             queue.append(addition_ver)
                         else:
                             existent = self.graph.V[existent]
                             self.graph.add_edge(vertex, existent)
예제 #17
0
    def read_graph(vertex_file_path, adjacency_matrix=None):
        # Initialize list and index
        vertices = np.array([])
        vertex_index = 0

        # Try to open the file
        try:
            vertex_file = open(vertex_file_path, "r")

            # If successful, read each line of the file
            for line in vertex_file.readlines():
                # once a first character digit is found, we've reached the data section
                if line[0].isdigit():
                    # split the line into index, x, and y values
                    index, x, y = line.split(" ")
                    # Create a vertex object out of these attributes and append it to the list of vertices
                    vertices = np.concatenate(
                        (vertices, Vertex(vertex_index, float(x), float(y))),
                        axis=None)
                    # Increment the vertex index by 1
                    vertex_index += 1
        # When finished, close the file.
        finally:
            vertex_file.close()

        if adjacency_matrix is None:
            # Create a list of adjacent vertices for all vertices in the list
            for index, vertex in enumerate(vertices):
                vertex.adjacent_vertices = [
                    adjacent_vertex for adjacent_vertex in vertices
                    if adjacent_vertex != vertex
                ]

        # Return the list of Vertex objects
        return vertices
def main(script, n='1000', k='10', *args):

    n = int(n) #number of vertices
    k = int(k) #number of edges in regular graph
    vertices = [Vertex(c) for c in range(n)]

    g = SmallWorldGraph(vertices)
    g.add_regular_edges(k)

    #regular graph's clustering coefficient and avg path length
    c_zero = g.clustering_coefficient()
    l_zero = g.average_path_length()
    print c_zero, l_zero

    f = open("plots/output.csv", "wb")
    print 'p\tC\tL'
    f.write('p,C(p)/C(0),L(p)/L(0)\n')

    #begin rewiring to tease out small-world network characteristics
    for log_exp in numpy.arange(-40, 1, 1): #incrementation scheme for logarithmic exponents
        g = SmallWorldGraph(vertices)
        g.add_regular_edges(k)
        p = numpy.power(10, log_exp/10.0)
        g.rewire(p)
        print '%s\t%s\t%s' % (p, g.clustering_coefficient()/c_zero, g.average_path_length()/l_zero)
        f.write('%s,%s,%s\n' % (p, g.clustering_coefficient()/c_zero, g.average_path_length()/l_zero))
    f.close()
예제 #19
0
    def test_graph(self):
        v = Vertex('v')
        w = Vertex('w')
        self.assertEqual(repr(v), "Vertex('v')")

        e = Edge(v, w)
        self.assertEqual(repr(e), "Edge(Vertex('v'), Vertex('w'))")

        g = Graph([v, w], [e])
        self.assertEqual(
            repr(g),
            "{Vertex('w'): {Vertex('v'): Edge(Vertex('v'), Vertex('w'))}, Vertex('v'): {Vertex('w'): Edge(Vertex('v'), Vertex('w'))}}"
        )

        e2 = g.get_edge(v, w)
        self.assertEqual(e, e2)

        e3 = g.get_edge(v, v)
        self.assertEqual(e3, None)

        vs = [Vertex(c) for c in 'abcd']
        g = Graph(vs)
        g.add_regular_edges(3)

        for v in g.vertices():
            es = g.out_edges(v)
            self.assertEqual(len(es), 3)

            vs = g.out_vertices(v)
            self.assertEqual(len(vs), 3)

        g.remove_edge(Edge(Vertex('a'), Vertex('c')))

        vs = g.vertices()
        self.assertEqual(len(vs), 4)

        es = g.edges()
        self.assertEqual(len(es), 5)

        g.add_all_edges()
        es = g.edges()
        self.assertEqual(len(es), 6)

        g2 = eval(repr(g))
        self.assertEqual(g, g2)
예제 #20
0
 def read_file(self, filename):
     '''
     Pre: An ASCII file where each line will be the vertex number, x-coordinate, and y-coordinate separated by spaces
     Post: Updates self.labels and self.coordinates by extracting the labels from the ASCII file
     '''
     f = open(filename, 'r')
     for i in range(6):
         self.header.append(f.readline())    # reads and stores the header section of the file
     line = f.readline()
     while line != 'EOF':
         sp_line = line.split()
         label = sp_line[0]
         coordinate = (int(sp_line[1]),int(sp_line[2]))
         vertex = Vertex(label)
         vertex.pos = coordinate
         self.coordinates.append(vertex)  # forms tuples with the x and y coordinates at each line and appends to self.coordinates
         line = f.readline()
     self.filename = filename    # updates the filename
예제 #21
0
    def insertRecord(
        self, record
    ):  # recieves a line of the text file and is used to build the graph
        tokens = record.split(',')  # splits the line via the split method
        if len(tokens) != 6:  # check regarding whether the line has 6 commas
            print('Incorrect Song Record')
        song = tokens[1]  # assings the song
        artist = tokens[2]  # assings the artist
        neighbors = tokens[5][:len(tokens[5]) - 1].split(
            ';')  # via the split method again, it creates a
        #  list of coArists AKA neighbors

        for i in range(
                0, len(neighbors)
        ):  # This for loop checks if an artist is listed in the list neighbors
            # this prevents repeated edges when creating the graph
            if artist in neighbors:
                neighbors.remove(artist)

        currentVert = None  # inializion of the current vertice
        if artist in self.vertList:  # checks if artist is in the the graph
            currentVert = self.vertList[
                artist]  # the vertice is set to the artist at that postion
        else:
            currentVert = Vertex(artist)  # creation of vertex
            self.vertList[
                artist] = currentVert  # Vertex is conneccted to the node
            self.numVertices += 1  # number of vertices is incremented
        ## insert info  for this artist

        arr = []
        currentVert.addsong(
            song)  # the song is added to the array of songs in the Graph file
        for nb in neighbors:  # iterates through the array neigbors and connects the neighbors together bidirectionally
            nbVert = None
            if nb in self.vertList:
                nbVert = self.vertList[nb]
            else:
                nbVert = Vertex(nb)
                self.vertList[nb] = nbVert
                self.numVertices += 1

            currentVert.addNeighbor(nbVert)
            nbVert.addNeighbor(currentVert)
    def add_prefer_vert(self, vid):
        vs = self.vertices()
        vert = Vertex(vid)
        self.add_vertex(vert)

        for v in vs:
            k_i = len(self[v])
            if random.random() > k_i/float(self.sum_k): continue
            self.add_edge(Edge(vert, v))
            self.sum_k += 1
예제 #23
0
    def add_address(self, a):
        location_file = open('./files/addressIndex.csv', 'r')  # open csv
        reader = csv.reader(location_file)  # reader will be our csv reader
        for row in reader:
            if row[2] == a:
                location = Vertex(int(row[0]), row[1], row[2])  # create a new location/vertex
                map.add_vertex(location)  # add that vertex to the map

            else:
                None
예제 #24
0
def file_read(file_name):
    with open(file_name) as file:
        graph = {}
        line = int(file.readline())
        for i in range(0, line):
            line = file.readline().replace("\n", "").split(" ")
            key = int(line[1])
            value = int(line[0])
            if key in graph:
                vertex = graph.get(key)
                vertex.add_vertex(value)
                graph[key] = vertex
            else:
                vertex = Vertex([value])
                graph[key] = vertex
            if value not in graph:
                vertex = Vertex([])
                graph[value] = vertex
        return graph
    def __init__(self, p, m_0, t):
        vs = [Vertex('v'+str(i)) for i in xrange(m_0)]
        RandomGraph.__init__(self, vs, p)

        self.sum_k = sum([len(self[v]) for v in self])
        [self.add_prefer_vert(str(i+m_0)) for i in xrange(t)]

        self.assign_edge_lengths()
        self.clust = self.clustering_coefficient()
        self.length = self.average_length()
        self.avg_deg = self.average_degree()
예제 #26
0
    def test_get_edges(self):

        graph = Graph()

        # (1) test empty graph
        subject = graph.get_edges()
        self.assertEqual(subject, set())

        # (2) test graph with vertices but no edges
        graph.vertices['a'] = Vertex('a')
        graph.vertices['b'] = Vertex('b')
        subject = graph.get_edges()
        self.assertEqual(subject, set())

        # (3) test graph with one edge
        graph.vertices.get('a').adj['b'] = 331
        subject = graph.get_edges()
        self.assertEqual(subject, {('a', 'b', 331)})

        # (4) test graph with two edges
        graph = Graph()
        graph.vertices['a'] = Vertex('a')
        graph.vertices['b'] = Vertex('b')
        graph.vertices.get('a').adj['b'] = 331
        graph.vertices.get('b').adj['a'] = 1855
        subject = graph.get_edges()
        solution = {('a', 'b', 331), ('b', 'a', 1855)}
        self.assertEqual(subject, solution)

        # (5) test entire alphabet graph
        graph = Graph()
        solution = set()
        for i, char in enumerate(string.ascii_lowercase):
            graph.vertices[char] = Vertex(char)
            for j, jar in enumerate(string.ascii_lowercase):
                if i != j:
                    graph.vertices.get(char).adj[jar] = 26 * i + j
                    solution.add((char, jar, 26 * i + j))

        subject = graph.get_edges()
        self.assertEqual(subject, solution)
예제 #27
0
def AstarPath(env, start, goal):
    start_node = XYNode(0, *start)
    goal_node = XYNode(env.n_grid - 1, *goal)
    graph = Graph(env=env)
    graph.add_vertex(start_node)
    start_vertex = graph.get_vertex(start_node)

    goal_vertex = Vertex(node=goal_node)
    goal_vertex_found = Astar(graph, start_vertex, goal_vertex)
    path = [goal_vertex_found.node]
    reconstruct_path(goal_vertex_found, path)
    return path
예제 #28
0
 def __init__(self, N, k, beta):
     """
     Creates a Watts-Strogatz Directed Graph
     starting with a k-regular graph with N vertices.
     Rewires the graph with probability beta.
     """
     if k % 2 == 1:
         raise ValueError, 'k must be even'
     vs = [Vertex(str(i)) for i in range(N)]
     DirectedGraph.__init__(self, vs, [])
     self.add_regular_arcs(k)
     self.rewire(beta)
예제 #29
0
    def test_get_vertex(self):

        graph = Graph()

        # (1) test basic vertex object
        vertex_a = Vertex('a')
        graph.vertices['a'] = vertex_a
        subject = graph.get_vertex('a')
        self.assertEqual(subject, vertex_a)

        # (2) test empty case
        subject = graph.get_vertex('b')
        self.assertIsNone(subject)

        # (3) test case with adjacencies
        vertex_b = Vertex('b')
        for i, char in enumerate(string.ascii_lowercase):
            vertex_b.adj[char] = i
        graph.vertices['b'] = vertex_b
        subject = graph.get_vertex('b')
        self.assertEqual(subject, vertex_b)
예제 #30
0
    def test_03_get_vertices(self):

        ### get_vertex ###

        graph = Graph()

        # Test basic vertex
        vertex_a = Vertex('a')
        graph.vertices['a'] = vertex_a
        subject = graph.get_vertex('a')
        assert subject == vertex_a

        ### get_vertices ###

        solution = [vertex_a]

        # Check with two vertices
        vertex = Vertex('$')
        graph.vertices['$'] = vertex
        solution.append(vertex)
        subject = graph.get_vertices()
        assert subject == solution
예제 #31
0
    def test_get_edges_vertex(self):

        # (1) test a-->b and a-->c
        vertex = Vertex('a')
        solution = {('b', 1), ('c', 2)}
        vertex.adj['b'] = 1
        vertex.adj['c'] = 2
        subject = vertex.get_edges()
        self.assertEqual(subject, solution)

        # (2) test empty case
        vertex = Vertex('a')
        solution = set()
        subject = vertex.get_edges()
        self.assertEqual(subject, solution)

        # (3) test a-->letter for all letters in alphabet
        for i, char in enumerate(string.ascii_lowercase):
            vertex.adj[char] = i
            solution.add((char, i))
        subject = vertex.get_edges()
        self.assertEqual(subject, solution)
예제 #32
0
def main():
    # Create a 2D environment
    env = XYEnvironment(x_size=10, y_size=10, n_grid_x=30, n_grid_y=30)

    # Create and add some threats to a field
    threat1 = GaussThreat(location=(2, 2), shape=(0.5, 0.5), intensity=5)
    threat2 = GaussThreat(location=(8, 8), shape=(1.0, 1.0), intensity=5)
    threat3 = GaussThreat(location=(8, 2), shape=(1.5, 1.5), intensity=5)
    threat4 = GaussThreat(location=(2, 8), shape=(0.5, 0.5), intensity=5)
    threats = [threat1, threat2, threat3, threat4]
    threat_field = GaussThreatField(threats=threats, offset=2)

    # Add the threat_field to the Environment
    env.add_threat_field(threat_field)
    print(env)

    # Create the Graph based on our environment
    graph = Graph(env=env)

    # Add a starting node and vertex to the graph to begin the search at.
    # Use first node in the environment as start node
    start_node = XYNode(node_id=0, pos_x=0, pos_y=0)
    graph.add_vertex(start_node)
    start_vertex = graph.get_vertex(start_node)
    print("Start vertex: ", start_vertex)

    # Use last node in environment as goal node
    goal_x, goal_y = env.get_location_from_gridpt(env.n_grid - 1)
    goal_node = XYNode(env.n_grid - 1, goal_x, goal_y)
    goal_vertex = Vertex(node=goal_node)
    print("Goal Node: ", goal_vertex.node)

    print("Run A* search")
    goal_vertex_found = Astar(graph=graph, start_vertex=start_vertex, goal_vertex=goal_vertex)
    print(goal_vertex_found)

    # Generate the path from the discovered goal vertex
    path = [goal_vertex_found.node]
    reconstruct_path(goal_vertex_found, path)
    print("Path found :")
    for waypoint in path:
        print(waypoint)

    # Plot the threat field in 3D
    draw_threat_field(env=env, threat_field=threat_field)

    # Plot the threat field as 2D heat map and add path on top
    ax2 = draw_threat_field_2D(env=env, threat_field=threat_field)
    draw_path(ax=ax2, path=path)

    plt.show()
		if printOutput:
			print("Graph Edges (total {m})".format(m=self._graph.numEdges()))
		for (edgeID, edgeObj) in self._graph._edges.items():
			if printOutput:
				print("\t({ID}) {src!s} -- {dest!s}  [{weight:.2f}]".format(
						ID=edgeID, src=self._graph._verts[edgeObj.fromVert],
						dest=self._graph._verts[edgeObj.toVert], weight=edgeObj.weight))
			totalWeight += edgeObj.weight

		if printOutput:
			print("Total weight: {weight:.2f}".format(weight=totalWeight))
		return totalWeight


if __name__ == "__main__":
	a = Vertex(0, 15, "A")
	b = Vertex(5, 20, "B")
	c = Vertex(16,  24, "C")
	d = Vertex(20, 20, "D")
	e = Vertex(33, 25, "E")
	f = Vertex(23, 11, "F")
	g = Vertex(35, 7, "G")
	h = Vertex(25, 0, "H")
	i = Vertex(10, 3, "I")
	grid = NaiveHananSolver([a,b,c,d,e,f,g,h,i])
	grid.addStationWeightFunc(lambda g,v: 1.2 * pow(g.getDegreeOfVertex(v), 1.5))
	grid.solve()
	grid.graphStats(printOutput=True)
	grid.plotGraph()

예제 #34
0
def main():
    g = Graph()
    r = Vertex(g)
    r._id = 'root'
    A = Vertex(g)
    A._id = 'A'
    B = Vertex(g)
    B._id = 'B'
    C = Vertex(g)
    C._id = 'C'
    D = Vertex(g)
    D._id = 'D'
    E = Vertex(g)
    E._id = 'E'
    F = Vertex(g)
    F._id = 'F'
    G = Vertex(g)
    G._id = 'G'
    end = Vertex(g)
    end._id = 'end'

    g.add_edge(r, A)
    g.add_edge(r, end)

    g.add_edge(A, B)
    g.add_edge(A, C)
    g.add_edge(B, C)
    g.add_edge(C, D)
    g.add_edge(C, E)
    g.add_edge(D, F)
    g.add_edge(E, F)
    g.add_edge(F, B)
    g.add_edge(F, G)
    g.add_edge(G, end)
    dt = DominatorTree(r)
    assert (r, end) in dt.e
    assert (r, A) in dt.e
    assert (A, B) in dt.e
    assert (A, C) in dt.e
    assert (A, C) in dt.e
    assert (C, D) in dt.e
    assert (C, E) in dt.e
    assert (C, F) in dt.e
    assert (F, G) in dt.e
    g.entry = r