Esempio n. 1
0
def read_city_graph(filename):
    """
    Args:
        filename (str): Name of file

    Returns:
        AdjacencyGraph: Graph representing the city of Edmonton Roads
    """
    g = AdjacencyGraph()
    __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))

    with open(os.path.join(__location__,filename)) as f:
        for line in f:
            #split line seperated by ','
            line = line.split(',')
            if line[0] == 'V':
                #if line starts with a V, add vertex
                g.add_vertex(int(line[1]))
                latitude  = int(float(line[2])*100000)
                longitude = int(float(line[3])*100000)
                coordinates[int(line[1])] = (latitude, longitude)
            elif line[0] == 'E':
                #if line starts with a E, add edge
                edge = (int(line[1]), int(line[2]))
                g.add_edge(edge)
                streetnames[edge] = line[3]
                edge_weights[edge] = cost_distance(edge[0], edge[1])
            else:
                print('Not an edge nor a vertex')
    return g
Esempio n. 2
0
def read_city_graph(city_graph):
    ''' Turns a comma seperated list into an AdjacencyGraph

    Args:
        city_graph: filename with extension .csv that exists
        in the same directory

    Returns:
        g: an AdjacencyGraph
        lat_lon: the latitude and longitude dictionary associated with the vertice key
        street_name: the street name dictionary associated with the edge key
    '''

    #Read file into a list of tokens from the file.
    with open(city_graph) as f:  # f = open('some.csv')
        reader = csv.reader(f)
        rows = []
        for row in reader:  # reads a line, or "row"
            rows += row  # list of strings
    f.close()

    vertices = []
    edges = []
    street_name = dict()
    #Parse which lines include data about a vertice and
    #which lines include data about an edge.
    #Create two lists of vertices and edges.
    #Creates the dictionary lat_lon, where the vertice number is the key and
    #the latitude and longitude are attched to the key
    #Creates the dictionary street_name, where the edge start and end
    # points tuple is the key, and the street name is attached to the key
    for i in range(len(rows)):
        if rows[i] == 'V':
            vertices.append(int(rows[i + 1]))
            lat_lon[int(rows[i + 1])] = ((int(float(rows[i + 2]) * 100000)),
                                         (int(float(rows[i + 3]) * 100000)))
        if rows[i] == 'E':
            edges.append((int(rows[i + 1]), int(rows[i + 2])))
            street_name[(int(rows[i + 1]), int(rows[i + 2]))] = (rows[i + 3])
        i += 4
    #Construct the AdjacencyGraph from the
    #lists 'vertices' and 'edges'
    g = Graph()
    for v in vertices:
        if not g.is_vertex(v):
            g.add_vertex(v)
    for e in edges:
        if not g.is_edge(e):
            g.add_edge(e)
    return g, lat_lon, street_name
Esempio n. 3
0
def read_city_graph(filename):
    '''Takes the provided CSV file containing the information about
        Edmonton map and contructs an Undirected Graph

    Args:
        filename (CSV_file_name): The file containing the data

    Returns:
        g (graph): The undirected graph
    '''

    g = AdjacencyGraph()
    # opens the file to be read
    with open(filename) as csvfile:
        # separates the file into values
        csv_input = csv.reader(csvfile, delimiter=',')
        for row in csv_input:
            # If first character of line is V add vertex
            if row[0] == 'V':
                g.add_vertex(int(row[1]))
            # If first character of line is E add edge
            elif row[0] == 'E':
                g.add_edge((int(row[1]), int(row[2])))
    return g
Esempio n. 4
0
When you run 
    python3 check_server.py
with just 
    server.py 
    adjacencygraph.py 
in the local directory you should get the following lines of output:
[1, 3, 6, 5]
[]
[3, 6]
[6, 5, 4, 3]
"""

import server
from adjacencygraph import AdjacencyGraph as Graph

graph = Graph()

verts = {1, 2, 3, 4, 5, 6}

for v in verts:
    graph.add_vertex(v)

edges = [(1, 2), (1, 3), (1, 6), (2, 3), (2, 4), (3, 2), (3, 4), (3, 6),
         (4, 2), (4, 3), (4, 5), (5, 4), (5, 6), (6, 3), (6, 5)]

for e in edges:
    graph.add_edge(e)

weights = {
    (1, 2): 7,
    (1, 3): 9,
from adjacencygraph import AdjacencyGraph
import math
import sys
"""Library import"""
g = AdjacencyGraph()
geo_info = dict()
weights = dict()
cost  = lambda x,y : weights.get((x,y),float("inf"))

class MinHeap:

    def __init__(self):
        self._array = []

    def add(self, key, value):
        self._array.append((key, value))
        self.fix_heap_up(len(self._array)-1)

    def pop_min(self):
        if not self._array:
            raise RuntimeError("Attempt to call pop_min on empty heap")
        retval = self._array[0]
        self._array[0] = self._array[-1]
        del self._array[-1]
        if self._array:
            self.fix_heap_down(0)
        return retval

    def fix_heap_up(self, i):
        if self.isroot(i):
Esempio n. 6
0
# server.py - by Jose Ramirez and Brady Pomerleau- CMPUT 275 Section EB1

from adjacencygraph import AdjacencyGraph
import math
import sys

# this python program is able to use functions that read in data input from a
# .txt file containing latitudes and longitudes of various parts of the city of
# Edmonton

# Here we are building the digraph containing all the edges and vertices inside
# the Edmonton Graph

# create graph g with directed AdjacencyGraph class
g = AdjacencyGraph()

# open the Edmonton Grph .txt file
Edmonton_Graph = open("edmonton-roads-2.0.1.txt")  # read entire .csv file
# read each line to determine whether to add vertices or add edges
vertex_coord = {}
edge_street_name = {}
for i in Edmonton_Graph:
    # split by commas
    i = i.strip().split(",")
    if i[0] == 'V':  # when the line is describing a vertex
        g.add_vertex(int(i[1]))  # add the vertex to the graph
        # Store the latitudes and longitudes into a tuple
        vertex_coord[int(i[1])] = (int(float(i[2]) * 100000),
                                   int(float(i[3]) * 100000))
    elif i[0] == 'E':  # when the line is describing an edge
        g.add_edge((int(i[1]), int(i[2])))  # add the edge to the graph
Esempio n. 7
0
def read_city_graph(filename):
    '''Creates the graph of a CSV (Comma-Separated Values) file
    describing a directed road network.

    Lines of the file can be formatted in two ways:
    1. V,ID,Lat,Lon: Describes a vertex in the graph
        V (character): the character 'V' denoting vertex
        ID (integer): the name or identifier of the vertex
        Lat, Lon (two floating point numbers): correspond to the latitude and
            longitude of a vertex's location on the map.
    2. E,start,end,name: Describes an edge in a graph
        E (character): the character 'E' denoting edge
        start, end (two integers): two vertices corresponding to the beginning
            and end of an edge
        name (string): name of the street on the map

    Args:
        filename (string) : the name of the file to be read, in the form "filename.txt",
            where the file must be in CSV format.

    Returns:
        graph: An instance of a directed graph, including all the vertices and edges read
        from the file.
        cost_distance (function): The nested cost_distance function. For its interface, see the definition
            of cost_distance.
        min_vertex (function): The nested min_vertex function.For its interface, see the definition
            of min_vertex.
        coords (dict): A set of the coordinates of each vertex on the graph in the format
            {vertex ID: (lat, lon)}.
    '''
    g = Graph()
    coords = dict()  # a set of (lat, lon) tuples
    # streetnames = dict() # Not needed for this part but will be needed later
    with open(filename) as f:
        reader = csv.reader(f)
        count = 1  # used to specify the row if a formatting error is found in the CSV file

        for row in reader:
            if row[0] == 'V':
                g.add_vertex(int(row[1]))
                lat = int(float(row[2]) * 100000)
                lon = int(float(row[3]) * 100000)
                coords[int(row[1])] = (lat, lon)

            elif row[0] == 'E':
                t = (int(row[1]), int(row[2]))
                g.add_edge(t)  #autocreation = True
                # streetnames[int(row[1]), int(row[2])] = row[3]
            else:
                raise RuntimeError(
                    "File improperly formatted. Row: {}".format(count))
            count += 1

        def cost_distance(u, v):
            '''Computes and returns the straight-line distance between the two vertices u and v.

            Args:
                u, v: The IDs for two vertices that are the start and end of a valid
                    edge in the graph.

            Returns:
                numeric value: the distance between the two vertices.
            '''
            num = math.sqrt(((coords[u][0] - coords[v][0])**2) +
                            ((coords[u][1] - coords[v][1])**2))
            return num

        def min_vertex(point):
            '''Computes and returns the nearest vertex to a given point on the
                graph.

            Args:
                point (a tuple of two ints): A tuple in the form (lat, lon) that
                    contains the latitude and longitude of the given point.

            Returns:
                vertex: The identifier of the nearest vertex.
            '''
            min_distance = float(
                "inf")  # sets the starting distance to infinity
            for v in g.vertices():
                # computes the distance between a point and each vertex and stores the minimum
                distance = math.sqrt(((point[0] - coords[v][0])**2) +
                                     ((point[1] - coords[v][1])**2))
                if distance < min_distance:
                    min_distance = distance
                    vertex = v
            return vertex

    return (g, cost_distance, min_vertex, coords)