def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    digraph = Digraph()
    print("Loading map from file...")
    with open(map_filename, 'r') as file:
        for line in file:
            parts = line.split()
            src = Node(parts[0])
            dest = Node(parts[1])
            edge = WeightedEdge(src, dest, int(parts[2]), int(parts[3]))
            edge = WeightedEdge(src, dest, int(parts[2]), int(parts[3]))
            if not digraph.has_node(src):
                digraph.add_node(src)
            if not digraph.has_node(dest):
                digraph.add_node(dest)
            digraph.add_edge(edge)

    return digraph
Exemple #2
0
    def test_add_edge_to_nonexistent_node_raises(self):
        node_not_in_graph = Node('q')
        no_src = WeightedEdge(self.nb, node_not_in_graph, 5, 5)
        no_dest = WeightedEdge(node_not_in_graph, self.na, 5, 5)

        with self.assertRaises(ValueError):
            self.g.add_edge(no_src)
        with self.assertRaises(ValueError):
            self.g.add_edge(no_dest)
    def setUp(self):
        # set up nodes
        self.na = Node('a')
        self.nb = Node('b')
        self.nc = Node('c')

        # set up weighted edges
        self.e1 = WeightedEdge(self.na, self.nb, 15, 10)
        self.e2 = WeightedEdge(self.na, self.nc, 14, 6)
        self.e3 = WeightedEdge(self.nb, self.nc, 3, 1)

        self.print_strings = ["a->b (15, 10)", 'a->c (14, 6)', 'b->c (3, 1)']
Exemple #4
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    # TODO
    # print("Loading map from file...")
    file = open(map_filename, 'r')  # open the file
    g = Digraph()
    for line in file:  # read each line of the file
        line = line.strip('\n')  # remove the \n character
        line = line.split(' ')
        for i in range(0, 2):
            nod = Node(line[i])
            if not g.has_node(nod):
                g.add_node(nod)
        wei_edge = WeightedEdge(Node(line[0]), Node(line[1]), int(line[2]),
                                int(line[3]))
        g.add_edge(wei_edge)
    file.close()
    return g
Exemple #5
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    # read map-file
    mapFile = open(map_filename, "r")
    mitGraph = Digraph()
    nodeMap = dict()
    # each entry
    for line in mapFile:
        # [src, dest, total dist, outdoot dist]
        info = line.strip("\n").split(" ")
        for i in range(2):
            if not info[i] in nodeMap:
                thisNode = Node(info[i])
                mitGraph.add_node(thisNode)
                nodeMap[info[i]] = thisNode
        mitGraph.add_edge(
            WeightedEdge(nodeMap[info[0]], nodeMap[info[1]], int(info[2]), int(info[3]))
        )
    return mitGraph
Exemple #6
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    # MY_CODE
    map_graph = Digraph()
    with open(map_filename, 'r') as f:
        for line in f:
            src, dest, total_dist, outdoor_dist = line.split(' ')
            src = Node(src)
            dest = Node(dest)
            if not map_graph.has_node(src):
                map_graph.add_node(src)
            if not map_graph.has_node(dest):
                map_graph.add_node(dest)
            edge = WeightedEdge(src, dest, int(total_dist), int(outdoor_dist))
            map_graph.add_edge(edge)
    return map_graph
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    #    print("Loading map from file...")
    inFile = open(map_filename, 'r')
    graph = Digraph()
    for line in inFile:
        linedata = line.split(' ')
        scr = Node(linedata[0])
        des = Node(linedata[1])
        graph.nodes.add(scr)
        graph.nodes.add(des)
        if not scr in graph.edges:
            graph.add_node(scr)
        if not des in graph.edges:
            graph.add_node(des)
        edge = WeightedEdge(scr, des, int(linedata[2]), int(linedata[3]))
        graph.add_edge(edge)
    return graph
Exemple #8
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    g = Digraph()
    with open(map_filename) as f:
        data = f.read().strip()
    dataList = data.split('\n')
    for mapEdge in dataList:
        edgeList = mapEdge.split(' ')  # from to TD, DO
        fromN = Node(edgeList[0])
        toN = Node(edgeList[1])
        if not g.has_node(fromN):
            g.add_node(fromN)
        if not g.has_node(toN):
            g.add_node(toN)
        g.add_edge(WeightedEdge(fromN, toN, edgeList[2], edgeList[3]))
    return g
Exemple #9
0
def JohnsonAlgorithm(graph: WeightedDirectedGraph, verbose=True):
    graph_edges_with_extra_node = graph.edges + [
        WeightedEdge('new_node', 0, node) for node in graph.nodes
    ]
    graph_with_extra_node = WeightedDirectedGraph(
        graph_edges_with_extra_node.copy())
    try:
        bf_shortest_distances, predecessors = BellmanFord(
            graph_with_extra_node, 'new_node', verbose=False)
    except Exception as e:
        return str(e)
    for edge in graph.edges:
        edge.weight = edge.weight + bf_shortest_distances[
            edge.head] - bf_shortest_distances[edge.tail]
    all_pairs_shortest_distance = {}
    for source_node in graph.nodes:
        if verbose:
            print('\nShortest Distance with vertex ' + str(source_node) +
                  ' as the source:\n')
        dijkstra_shortest_distances, predecessors = Dijkstra(graph,
                                                             source_node,
                                                             verbose=verbose)
        dijkstra_shortest_distances = {
            k:
            (v + bf_shortest_distances[k] - bf_shortest_distances[source_node])
            for k, v in dijkstra_shortest_distances.items()
        }
        all_pairs_shortest_distance[source_node] = dijkstra_shortest_distances
    return all_pairs_shortest_distance
Exemple #10
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    print("Loading map from file...")
    f=open(map_filename,'r')
    g=Digraph()
    for line in f:
        src, dest, total_distance, outdoor_distance = line.split()
        src_node=Node(src)
        dest_node=Node(dest)
        src_dest=WeightedEdge(src_node, dest_node, total_distance, outdoor_distance)
        if not g.has_node(src_node):
            g.add_node(src_node)
        if not g.has_node(dest_node):
            g.add_node(dest_node)
        g.add_edge(src_dest)
    f.close()
    return g
Exemple #11
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    inFile = open(map_filename, 'r')
    digraph = Digraph()
    for line in inFile:
        mapEntry = line.split()  #mapEntry(list)
        src = Node(mapEntry[0])
        dest = Node(mapEntry[1])
        total_distance = int(mapEntry[2])
        outdoor_distance = int(mapEntry[3])
        edge = WeightedEdge(src, dest, total_distance, outdoor_distance)

        if not digraph.has_node(src):
            digraph.add_node(src)
        if not digraph.has_node(dest):
            digraph.add_node(dest)
        digraph.add_edge(edge)
    return digraph
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    graph = Digraph()
    with open(map_filename) as file:
        for line in file.readlines():
            el = line.strip('\n').split(' ')

            # Add nodes if they're not already in the graph
            for node in el[:2]:
                if not graph.has_node(node):
                    graph.add_node(node)

            graph.add_edge(WeightedEdge(*el))

    return graph
Exemple #13
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    g = Digraph()  # Create a digraph object
    print("Loading map from file...")
    with open(map_filename, "r") as f:
        for passage in f:
            # For each entry, store four info
            From, To, TotalD, OutD = passage.split()
            node_src, node_dest = Node(From), Node(To)
            if not g.has_node(node_src):
                g.add_node(node_src)
            if not g.has_node(node_dest):
                g.add_node(node_dest)

            g.add_edge(
                WeightedEdge(node_src, node_dest, int(TotalD), int(OutD)))
    return g
Exemple #14
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    graph = Digraph()  # 创建空图
    with open(map_filename) as file:
        for line in file:
            elements = line.split()  # 按空格分割成list
            src = Node(elements[0])
            dest = Node(elements[1])
            total_distance = int(elements[2])    # 数字类型
            outdoor_distance = int(elements[3])  # 数字类型

            if not graph.has_node(src):
                graph.add_node(src)
            if not graph.has_node(dest):
                graph.add_node(dest)
            graph.add_edge(WeightedEdge(src, dest, total_distance, outdoor_distance))

    return graph
Exemple #15
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    g = Digraph()
    with open(map_filename, "r") as file:
        for line in file:
            (src, dst, tot_dist, outdoor_dist) = line.split(' ')
            tot_dist = int(tot_dist)
            outdoor_dist = int(outdoor_dist)
            if not g.has_node(Node(src)):
                g.add_node(Node(src))
            if not g.has_node(Node(dst)):
                g.add_node(Node(dst))
            g.add_edge(WeightedEdge(src, dst, tot_dist, outdoor_dist))
    return g
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    d = Digraph()
    with open(map_filename) as f:
        for line in f:
            data = line.split(' ')
            assert (len(data) == 4)

            src = Node(data[0])
            dest = Node(data[1])
            edge = WeightedEdge(src, dest, data[2], data[3])

            if not d.has_node(src):
                d.add_node(src)
            if not d.has_node(dest):
                d.add_node(dest)
            d.add_edge(edge)
        f.close()
    return d
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    campus_map = Digraph()
    with open(map_filename, 'r') as file_handle:
        for line in file_handle:  # 32 36 70 0
            info = line.strip().split(
            )  # info = ["32","36","70","0"] strip返回一个去掉前后端的line的副本
            from_node = Node(info[0])
            to_node = Node(info[1])
            if not campus_map.has_node(from_node):
                campus_map.add_node(from_node)
            if not campus_map.has_node(to_node):
                campus_map.add_node(to_node)
            cur_edge = WeightedEdge(from_node, to_node, int(info[2]),
                                    int(info[3]))
            # 假设cur_edge不存在重复的情况,也就是说mit_map.txt没有提供重复的数据
            campus_map.add_edge(cur_edge)
    return campus_map
Exemple #18
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    #print("Loading map from file...")
    campus_graph = Digraph()  # 实例化Digraph
    with open(map_filename) as file_object:
        lines = file_object.readlines()
    for line in lines:
        list = line.split()
        if not campus_graph.has_node(Node(list[0])):
            campus_graph.add_node(Node(list[0]))  # 若不在即加入
        if not campus_graph.has_node(Node(list[1])):
            campus_graph.add_node(Node(list[1]))
        campus_graph.add_edge(
            WeightedEdge(  # 将该边加入
                Node(list[0]), Node(list[1]), list[2], list[3]))
    return campus_graph
Exemple #19
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    digraph = Digraph()
    count = 0
    with open(map_filename, 'r') as file:
        for line in file:
            line_list = line.split(' ')
            count += 1
            src = Node(line_list[0])
            dest = Node(line_list[1])
            if not digraph.has_node(src): digraph.add_node(src)
            if not digraph.has_node(dest): digraph.add_node(dest)
            weighted_edge = WeightedEdge(src, dest, line_list[2], line_list[3])
            digraph.add_edge(weighted_edge)
    return digraph
Exemple #20
0
def load_map(mapFilename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        mapFilename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a directed graph representing the map
    """

    print "Loading map from file..."

    mitMap = WeightedDigraph()

    f = open('mit_map.txt', 'r')
    for l in f:
        line = l.split()
        mitMap.addNode(line[0])
        mitMap.addNode(line[1])
        newEdge = WeightedEdge(line[0], line[1], line[2], line[3])
        mitMap.addEdge(newEdge)

    return mitMap
Exemple #21
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    D = Digraph()
    with open(map_filename, 'r') as f:
        for count, line in enumerate(f):
            src, dest, total_dist, out_dist = line.split(' ')
            source = Node(src)
            destination = Node(dest)
            we = WeightedEdge(source, destination, total_dist, out_dist)
            D = _add_node(D, source, destination)
            D.add_edge(we)
    return D
Exemple #22
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    print("Loading map from file...")
    graph = Digraph()
    f = open(map_filename, 'r')
    for line in f:
        line = line.split()
        src = Node(line[0])
        dst = Node(line[1])
        for node in [src, dst]:
            if not graph.has_node(node):
                graph.add_node(node)
        edge = WeightedEdge(src, dst, int(line[2]), int(line[3]))
        graph.add_edge(edge)
    f.close()
    return graph
Exemple #23
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    print("\n\nLoading map from file...")

    g = Digraph()
    with open(map_filename) as file:
        for line in file:
            s, t, total, outdoor = line.split()
            s, t = map(Node, (s, t))

            if not g.has_node(s): g.add_node(s)
            if not g.has_node(t): g.add_node(t)

            edge = WeightedEdge(s, t, *map(int, (total, outdoor)))
            g.add_edge(edge)

    return g
Exemple #24
0
    def buildGraph(mapEntries):
        g = Digraph()
        nodelist = []

        #createing nodelist and adding nodes
        for eachEntry in mapEntries:
            eachEntrySource = eachEntry[0]
            eachEntryDest = eachEntry[1]
            if eachEntrySource not in nodelist:  #making sure the node is unique
                nodelist.append(eachEntrySource)
                g.add_node(Node(eachEntrySource))
            if eachEntryDest not in nodelist:
                nodelist.append(eachEntryDest)
                g.add_node(Node(eachEntryDest))

        #creating edges
        for eachEntry in mapEntries:
            src = Node(eachEntry[0])  #eachEntrySource Node
            dest = Node(eachEntry[1])  #"eachEntryDest"
            tD = eachEntry[2]  #eachEntryTotalDistance
            oD = eachEntry[3]  #eachEntryOutdoorDistance
            g.add_edge(WeightedEdge(src, dest, tD,
                                    oD))  #Adding the weighted edge kind

        return g
Exemple #25
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    print("Loading map from file...")
    openfile = open(map_filename, 'r')
    gph = Digraph()
    for line in openfile:
        NewLine = line.strip('\n').split(" ")
        a, b, c, d = NewLine
        a, b = Node(a), Node(b)
        c, d = int(c), int(d)
        if a not in gph.nodes:
            gph.add_node(a)
        if b not in gph.nodes:
            gph.add_node(b)
        DirEdge = WeightedEdge(a, b, c, d)
        gph.add_edge(DirEdge)
    openfile.close()
    return gph
Exemple #26
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """
    print("Loading map from file...")
    graph = Digraph()
    with open(map_filename, 'r') as f1:
        list1 = f1.readlines()
    for item in list1:
        src, dest, total, outdoors = item[0:-1].split(' ')
        if (graph.has_node(Node(src)) == 0):
            graph.add_node(Node(src))
        if (graph.has_node(Node(dest)) == 0):
            graph.add_node(Node(dest))
        graph.add_edge(WeightedEdge(Node(src), Node(dest), total, outdoors))
    # TODO
    return graph
Exemple #27
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    # TODO
    print("Loading map from file...")
    f = open(map_filename)
    line_list = []
    for line in f:
        clean_line = line.rstrip()
        line_list.append(clean_line)

    f.close()

    src_li = []
    dest_li = []
    weighted_edge_li = []

    for string in line_list:
        param = string.split(' ')
        src_li.append(Node(param[0]))
        dest_li.append(Node(param[1]))
        edge = WeightedEdge(src_li[-1], dest_li[-1], int(param[2]),
                            int(param[3]))
        weighted_edge_li.append(edge)

    map = Digraph()
    for i in range(len(src_li)):
        try:
            map.add_node(src_li[i])
            map.add_node(dest_li[i])
        except ValueError as error:
            print(error)
            continue  # will go next iter of this for-loop directly, skipping any code below it

    for i in range(len(src_li)):
        try:
            map.add_edge(weighted_edge_li[i])
        except ValueError as error1:
            print(error1)
            continue

    return map
Exemple #28
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    # TODO
    print("Loading map from file...")
    #     Format for the graph file:
    #     Starting node, destination node, total weight of edge (distance), total distance spent outside
    # So steps:
    # 1. Create graph object
    # For every line:
    #  0. Save all numbers in variables (source, destination, total_distance, outdoor_distance)
    #  1. Create source_node object
    #  2.Create destination node object
    #  3. If graph has not(source_node) object:
    #       add_node to graph
    #     else get node from graph and save in src variable
    #     Do the same for destination object
    # 4. Create weightedEdge object from variables and objects
    # 5. Add edge to graph
    # Problem 2c: Testing load_map
    # Include the lines used to test load_map below, but comment them out
    g = Digraph()
    with open(map_filename) as f:
        for line in f:
            input = line.split()
            source = input[0]
            destination = input[1]
            total_distance = input[2]
            outdoor_distance = input[3]
            src_object = Node(source)
            dest_object = Node(destination)
            if not (g.has_node(src_object)):
                g.add_node(src_object)
            if not (g.has_node(dest_object)):
                g.add_node(dest_object)
            edge_object = WeightedEdge(src_object, dest_object, total_distance,
                                       outdoor_distance)
            if edge_object not in g.get_edges_for_node(src_object):
                g.add_edge(edge_object)

    return g
Exemple #29
0
def make_graph(som, values):
    """make graph from an iterable with vertices and their values
       edge weight between vertices with values a and b
       is defined as min(a, b)
       """
    edges = set()

    for node, value in zip(som.nodes, values):
        if node.x < som.width - 1:
            node2 = som.node_at(node.x + 1, node.y)
            value2 = values[node2.n]
            edges.add(WeightedEdge(node, node2, min(value, value2)))
        if node.y < som.height - 1:
            node2 = som.node_at(node.x, node.y + 1)
            value2 = values[node2.n]
            edges.add(WeightedEdge(node, node2, min(value, value2)))

    return {'vertices': set(som.nodes), 'edges': edges}
Exemple #30
0
def load_map(map_filename):
    """
    Parses the map file and constructs a directed graph

    Parameters:
        map_filename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a Digraph representing the map
    """

    print("Loading map from file...")
    # Open map_filename for reading and parse each line to get the edge parameters
    # Assumes map_filename is properly formatted
    newdigraph = Digraph()  # Initialize new digraph
    with open(map_filename, mode='r') as fID:
        for tline in fID:
            # Split on space
            edge_params = tline.split(' ')

            # edge_params will have the following format:
            #     edge_params[0]: Source Node, string
            #     edge_params[1]: Destination Node, string
            #     edge_params[2]: Total Distance, int
            #     edge_params[3]: Distance Outdoors, int
            for idx, param in enumerate(edge_params):
                if idx < 2:
                    # Node names, staying as strings. Strip newline
                    edge_params[idx] = edge_params[idx].replace('/n', '')
                else:
                    # Distances, cast as integers. This strips the newline
                    edge_params[idx] = int(edge_params[idx])

            # Check to see if our source node is in the digraph we're generating,
            # add if it's not
            if not newdigraph.has_node(edge_params[0]):
                newdigraph.add_node(edge_params[0])

            # Check to see if our destination node is in the digraph we're
            # generating, add if it's not
            if not newdigraph.has_node(edge_params[1]):
                newdigraph.add_node(edge_params[1])

            newdigraph.add_edge(
                WeightedEdge(edge_params[0], edge_params[1], edge_params[2],
                             edge_params[3]))

    return newdigraph
Exemple #31
0
def load_map(mapFilename):
    """ 
    Parses the map file and constructs a directed graph

    Parameters: 
        mapFilename : name of the map file

    Assumes:
        Each entry in the map file consists of the following four positive 
        integers, separated by a blank space:
            From To TotalDistance DistanceOutdoors
        e.g.
            32 76 54 23
        This entry would become an edge from 32 to 76.

    Returns:
        a directed graph representing the map
    """
    # TODO
    print "Loading map from file..."
    infile = open('./' + str(mapFilename), 'r')
    
    graph = WeightedDigraph()
    
    # add nodes
    for line in infile: # each line in file
        line = line.strip() # strip "\n" from line
        line = line.split(' ')
        node1, node2 = line[0], line[1] # take nodes
        #print node1, node2, type(node1), type(node2)
        try:
            graph.addNode(Node(node1)) # note: add a node, not a string!
        except ValueError as e: #node 1 already exist
            pass
        try: 
            graph.addNode(Node(node2))
        except ValueError as e: # node 2 already exist
            pass

    infile.close()
  
      
    # add edges
    infile = open('./' + str(mapFilename), 'r')
    for line in infile: # each line in file
        line = line.strip() # strip "\n" from line
        line = line.split(' ')
        node1, node2 = Node(line[0]), Node(line[1]) # take nodes
        totDist, outDist = int(line[2]), int(line[3])
    
        edge = WeightedEdge(Node(node1), Node(node2), totDist, outDist)

        graph.addEdge(edge)
   
    return graph
class TestWeightedEdge(TestCase):
    def setUp(self):
        # set up nodes
        self.na = Node('a')
        self.nb = Node('b')
        self.nc = Node('c')

        # set up weighted edges
        self.e1 = WeightedEdge(self.na, self.nb, 15, 10)
        self.e2 = WeightedEdge(self.na, self.nc, 14, 6)
        self.e3 = WeightedEdge(self.nb, self.nc, 3, 1)

        self.print_strings = ["a->b (15, 10)", 'a->c (14, 6)', 'b->c (3, 1)']

    def test_getTotalDistance(self):
        self.assertEqual(self.e1.getTotalDistance(), 15)
        self.assertEqual(self.e2.getTotalDistance(), 14)
        self.assertEqual(self.e3.getTotalDistance(), 3)
        e_instance = random.choice([self.e1, self.e2, self.e3])
        self.assertIsInstance(e_instance.getTotalDistance(), int)

    def test_getOutdoorDistance(self):
        self.assertEqual(self.e1.getOutdoorDistance(), 10)
        self.assertEqual(self.e2.getOutdoorDistance(), 6)
        self.assertEqual(self.e3.getOutdoorDistance(), 1)
        e_instance = random.choice([self.e1, self.e2, self.e3])
        self.assertIsInstance(e_instance.getOutdoorDistance(), int)

    def test___str__(self):
        self.assertEqual(str(self.e1), self.print_strings[0])
        self.assertEqual(str(self.e2), self.print_strings[1])
        self.assertEqual(str(self.e3), self.print_strings[2])
    def setUp(self):
        # set up nodes
        self.na = Node('a')
        self.nb = Node('b')
        self.nc = Node('c')

        # set up weighted edges
        self.e1 = WeightedEdge(self.na, self.nb, 15, 10)
        self.e2 = WeightedEdge(self.na, self.nc, 14, 6)
        self.e3 = WeightedEdge(self.nb, self.nc, 3, 1)

        self.g = WeightedDigraph()

        self.g.addNode(self.na)
        self.g.addNode(self.nb)
        self.g.addNode(self.nc)

        self.g.addEdge(self.e1)
        self.g.addEdge(self.e2)
        self.g.addEdge(self.e3)

        self.print_strings = ["a->b (15.0, 10.0)", 'a->c (14.0, 6.0)', 'b->c (3.0, 1.0)']
class TestWeightedDigraph(TestCase):
    def setUp(self):
        # set up nodes
        self.na = Node('a')
        self.nb = Node('b')
        self.nc = Node('c')

        # set up weighted edges
        self.e1 = WeightedEdge(self.na, self.nb, 15, 10)
        self.e2 = WeightedEdge(self.na, self.nc, 14, 6)
        self.e3 = WeightedEdge(self.nb, self.nc, 3, 1)

        self.g = WeightedDigraph()

        self.g.addNode(self.na)
        self.g.addNode(self.nb)
        self.g.addNode(self.nc)

        self.g.addEdge(self.e1)
        self.g.addEdge(self.e2)
        self.g.addEdge(self.e3)

        self.print_strings = ["a->b (15.0, 10.0)", 'a->c (14.0, 6.0)', 'b->c (3.0, 1.0)']

    def test_addEdge(self):
        self.assertEquals(self.g.hasNode(self.e1.getDestination()), True)
        self.assertEquals(self.g.hasNode(self.e1.getSource()), True)

        self.assertEquals(self.g.hasNode(self.e2.getDestination()), True)
        self.assertEquals(self.g.hasNode(self.e2.getSource()), True)

        self.assertEquals(self.g.hasNode(self.e3.getDestination()), True)
        self.assertEquals(self.g.hasNode(self.e3.getSource()), True)

    def test_childrenOf(self):
        for node in self.g.nodes:
            children = self.g.childrenOf(node)
            for child in children:
                self.assertIsInstance(child, Node)

    def test___str__(self):
        my_str = str(self.g)
        test_list = split(str(self.g), '\n')
        print('my_str is: {0}'.format(my_str))
        print('test_list is: {0}'.format(test_list))
        self.assertEqual(test_list[0], self.print_strings[0])
        self.assertEqual(test_list[1], self.print_strings[1])
        self.assertEqual(test_list[2], self.print_strings[2])