Beispiel #1
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
Beispiel #2
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
    """
    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
Beispiel #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
    """
    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
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
Beispiel #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...")
    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
Beispiel #7
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
Beispiel #8
0
    def update_graph_decl(self, root):
        if not self.contains:
            return

        # ... add current block if it is a subroutine or a function
        graph = root.graph_decl
        subgraph   = Digraph(name=self.name)

        attributs = {}
#        attributs["constraint"] = "true"
        attributs["constraint"] = "false"
        attributs["style"]      = "solid"
        attributs["label"]      = self.label

        # ... add edges / nodes for functions/subroutines declarations
        for key, values in self.dict_decl.items():
            keyword = key

            for name in values:
                other = root.get_block_by_filename_name(self.filename, name)

                attributs = {}
#                attributs["constraint"] = "true"
                attributs["style"]      = "dashed"

                if other is not None:
                    subgraph.edge(self, other, attributs=attributs)
        # ...

        # ... update root graph with subgraph
        graph.add_subgraph(subgraph)
Beispiel #9
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
Beispiel #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...")
    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
Beispiel #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...")
    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
Beispiel #12
0
def simpleIterative(nodeCount):
    nodes = []
    graph = Digraph()
    # Digraph object stores a list of nodes and a dictionary of node:childrenList
    for i in range(nodeCount):
        nodes.append(str(i))
        graph.addNode(nodes[i])
    levelCount = int(math.log(nodeCount, 2)) + 1
    extraNodes = nodeCount - 2**(levelCount - 1)

    # attach nodes for all complete levels:
    index = 1
    for level in range(1, levelCount - 1):
        nodes_to_add = 2**level
        parentCount = nodes_to_add // 2
        parents = nodes[index - parentCount:index]
        for parent in parents:
            graph.connect(parent, nodes[index])
            graph.connect(parent, nodes[index + 1])
            index += 2

    # attach nodes for the last, incomplete level
    for node in nodes[index:]:
        parentIndex = index // 2
        parent = nodes[index - 1 - parentIndex]
        graph.connect(parent, node)
        index += 1

    return graph
Beispiel #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
    """
    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
Beispiel #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...")
    # 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
Beispiel #15
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
    """
    map_graph = Digraph()
    print("Loading map from file...")
    with open(mapFilename) as f:
        lines = f.readlines()
        for line in lines:
            node1 = Node(line[0])
            node2 = Node(line[1])
            edge1 = Edge(node1, node2)
            map_graph.addNode(node1)
            map_graph.addNode(node2)
            map_graph.addEdge(edge1)
    return map_graph
Beispiel #16
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
Beispiel #17
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()
    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
Beispiel #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...")
    # 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
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..."

    # Open File
    inFile = open(mapFilename, 'r', 0)

    # MIT: Digraph representing the MIT Map
    MIT = Digraph();
    
    # Generate list of map entries
    mapList = []
    for line in inFile:
        mapList.append(line.split())

    # Generate nodes
    nodes = []
    for entry in mapList:
        if entry[0] not in nodes:
            nodes.append(entry[0])
    for node in nodes:
        MIT.addNode(node)  

    # Generate edges
    edges = []
    for entry in mapList:
        singleEdge = Edge(entry[0], entry[1], int(entry[2]), int(entry[3]))
        edges.append(singleEdge)
    for edge in edges:
        MIT.addEdge(edge)

    # Print report    
    print "  ", len(nodes), "nodes loaded."
    print "  ", len(edges), "edges loaded."

    inFile.close()
    return MIT       
Beispiel #20
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...")
    # initialize a digraph g representing the map
    g = Digraph()
    # open the file contains map data
    with open(map_filename) as file:
        # read data per line and store it into a list
        read_data = file.read().split("\n")
        # the list contains an unnecessary newline character at the end
        read_data = read_data[:-1]
        # loop through each entry in data list
        for entry in read_data:
            # split each entry into source, destination nodes, total_distance and outdoor_distance
            # and store them into a list respectively
            raw_data = entry.split(" ")
            # src = source node, dest = destination, total = total_distance, outdoor = outdoor_distance
            src = Node(raw_data[0])
            dest = Node(raw_data[1])
            total = int(raw_data[2])
            outdoor = int(raw_data[3])
            # check if g already has node src or not
            if not g.has_node(src):
                g.add_node(src)
            # check if g already has node dest or not
            if not g.has_node(dest):
                g.add_node(dest)
            # initialize a weighted edge
            edge = WeightedEdge(src, dest, total, outdoor)
            # add above edge into g
            g.add_edge(edge)
    # close file
    file.close()
    # return the desired directed graph
    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
    """

    #    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
Beispiel #22
0
 def setUp(self):
     self.g = Digraph()
     self.na = Node('a')
     self.nb = Node('b')
     self.nc = Node('c')
     self.g.add_node(self.na)
     self.g.add_node(self.nb)
     self.g.add_node(self.nc)
     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.add_edge(self.e1)
     self.g.add_edge(self.e2)
     self.g.add_edge(self.e3)
Beispiel #23
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
Beispiel #24
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
Beispiel #25
0
    def __init__(self, \
                 filename=None, \
                 dirname=None, \
                 text=None, \
                 dict_constructor=None, \
                 dict_attribut=None, \
                 verbose=0):

        self._dirname = dirname
        self._dict_names = {}
        self._dict_constructor = dict_constructor
        self._dict_attribut = dict_attribut
        self._verbose = verbose
        self._graph_decl = Digraph(name="declarations")
        self._graph_call = Digraph(name="calls")
        self._dict_block = {}
        self._prefix = None
        # ... contains the source code for each filename
        self._dict_text = {}

        if (filename is not None) and (dirname is not None):
            print(
                "Parser cannot be called with both filename and dirname not empty"
            )
            raise ()

        if filename is not None:
            f = open(filename, 'r')
            progtext = f.read()
            self._dict_text[filename] = progtext
            f.close()

        if dirname is not None:
            for root, subdirs, files in os.walk(dirname):
                if self.verbose > 0:
                    print "++ searching in ", root
                if files is not None:
                    for File in files:
                        ext = File.split(".")[-1]
                        if ext in FORTRAN_EXTENSIONS:
                            _filename = os.path.join(root, File)

                            if self.verbose > 0:
                                print "---- filename :", _filename

                            f = open(_filename, "r")
                            progtext = f.read()
                            self._dict_text[_filename] = progtext
                            f.close()
Beispiel #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
    """

    # 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
Beispiel #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
    """

    file = open("mit_map.txt")
    content = file.read()
    file.close()
    #split the data into a list of lists
    contentList = content.splitlines()
    mitData = []
    for lines in contentList:
        lineSplit = lines.split(' ')
        mitData.append(lineSplit)
    #print(mitData)

    #create digrapgh
    diG = Digraph()
    #loop through list of list, add nodes and edges to graphs
    for datum in mitData:
        #create node
        node1 = Node(datum[0])
        node2 = Node(datum[1])
        #create edge
        wEdge = WeightedEdge(node1, node2, int(datum[2]), int(datum[3]))
        #add nodes to graph
        if not diG.has_node(node1):
            diG.add_node(node1)
        if not diG.has_node(node2):
            diG.add_node(node2)
        #add weighted edge to graphs
        diG.add_edge(wEdge)
Beispiel #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
    """

    print("Loading map from file...")

    map_data = open(map_filename)
    graph = Digraph()

    for row in map_data:
        node_info = row[:-1].split()

        src_name = node_info[0]
        dest_name = node_info[1]
        total_dist = node_info[2]
        outdoor_dist = node_info[3]

        src = Node(src_name)
        dest = Node(dest_name)
        edge = WeightedEdge(src, dest, total_dist, outdoor_dist)

        if graph.has_node(src) == False:
            graph.add_node(src)

        if graph.has_node(dest) == False:
            graph.add_node(dest)

        graph.add_edge(edge)

    map_data.close()
    return graph
Beispiel #29
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
Beispiel #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...")
    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
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’s nodes represent the numbered buildings 
        Graph’s edges represent the distance (total and outdoor) of each route 
        The distances are asigned as object attributes to instances of WeightedEdge class   

    """
    print("Loading map from file...")
    file = open(map_filename, mode='r')

    g = Digraph()
    for line in file:
        # convert each line (string) to a list of the values in that line
        line_lst = line.split()

        src = Node(line_lst[0])
        dest = Node(line_lst[1])
        tot_dist = int(line_lst[2])
        out_dist = int(line_lst[3])

        if not g.has_node(src):
            g.add_node(src)
        if not g.has_node(dest):
            g.add_node(dest)

        edge = WeightedEdge(src, dest, tot_dist, out_dist)
        g.add_edge(edge)

    return g
Beispiel #32
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
Beispiel #33
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..."

    dataFile = open(mapFilename, "r")
    g = Digraph()

    for line in dataFile:
        if len(line) == 0 or line[0] == "#":
            continue

        dataLine = string.split(line)

        fromBuidling = g.getNode(dataLine[0])
        toBuilding = g.getNode(dataLine[1])
        totalDistance = int(dataLine[2])
        outdoorDistance = int(dataLine[3])

        if fromBuidling is None:
            fromBuidling = Node(dataLine[0])
            g.addNode(fromBuidling)
        if toBuilding is None:
            toBuilding = Node(dataLine[1])
            g.addNode(toBuilding)

        p = Path(fromBuidling, toBuilding, totalDistance, outdoorDistance)

        g.addEdge(p)

    return g
Beispiel #34
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..."
    f = open (mapFilename,"r")
    map_dict = {}
    l = []
    for line in open(mapFilename,"r"):
        name, score, weight1, weight2 = line.split()
        l = [score, weight1, weight2]
        map_dict[name] = l

    graph = Digraph()
    list_of_nodes = []

    for i in map_dict:
        if not (i in list_of_nodes):       
            graph.addNode(i)
        if not (map_dict[i][0] in list_of_nodes):
            graph.addNode(map_dict[i][0])
        list_of_nodes.append(i)
        list_of_nodes.append(map_dict[i][0])   
        edge = Edge(i, map_dict[i][0], map_dict[i][1], map_dict[i][2])
        #print edge
        graph.addEdge(edge)
    return graph
Beispiel #35
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
    """
    mapGraph = Digraph()
    
    print "Loading map from file..."
    inputFile = open(mapFilename)
    for line in inputFile:
        line = line.rstrip()
        splitLine = line.split(' ')
        
        # First, add start node if it doesn't already exist
        if not mapGraph.hasNode(splitLine[0]):
            mapGraph.addNode(splitLine[0])
            
    inputFile.seek(0)        
    
    for line in inputFile:
        line = line.rstrip()
        splitLine = line.split(' ')
            
        # Then, add edge between two nodes
        lineEdge = FeatureEdge(splitLine[0],splitLine[1],splitLine[2],splitLine[3])
        mapGraph.addEdge(lineEdge)
        
    return mapGraph
Beispiel #36
0
	def __init__(self):
		Digraph.__init__(self)
		self.edges = {}