示例#1
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()
示例#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
    """

    # 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
示例#3
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
示例#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
    """
    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
示例#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
    """

    #    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
示例#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
    """

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

    digraph = Digraph()

    nodes = remove_duplicates(get_all_nodes_from_map_data(map_filename))
    edges = get_edges_from_map_data(map_filename)

    for each in nodes:
        digraph.add_node(each)
    for each in edges:
        digraph.add_edge(each)

    return digraph
示例#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
    """
    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
示例#8
0
文件: ps2.py 项目: jjuinni/Portfolio
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
示例#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...")
    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
示例#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...")
    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
示例#12
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
示例#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
    """
    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
示例#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
    """
    # 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
示例#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
    """

    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
示例#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
    """
    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
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
示例#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...")
    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
示例#19
0
文件: ps2.py 项目: guoguozy/Python
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
示例#20
0
文件: ps2.py 项目: andy1li/mit-6.0002
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
示例#21
0
def main():
    source = 'Chicago'
    destination = 'Phoenix'
    g = Digraph()
    for name in ('Boston', 'Providence', 'New York', 'Chicago', 'Denver',
                 'Phoenix', 'Los Angeles'):  #Create 7 nodes
        g.addNode(Node(name))
    g.addEdge(Edge(g.getNode('Boston'), g.getNode('Providence')))
    g.addEdge(Edge(g.getNode('Boston'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('Providence'), g.getNode('Boston')))
    g.addEdge(Edge(g.getNode('Providence'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('New York'), g.getNode('Chicago')))
    g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Denver')))
    g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Phoenix')))
    g.addEdge(Edge(g.getNode('Denver'), g.getNode('Phoenix')))
    g.addEdge(Edge(g.getNode('Denver'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('Los Angeles'), g.getNode('Boston')))

    sp = DFS(g,
             g.getNode(source),
             g.getNode(destination), [],
             None,
             toPrint=True)

    if sp != None:
        print('Shortest path from', source, 'to', destination, 'is',
              printPath(sp))
    else:
        print('There is no path from', source, 'to', destination)
示例#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
示例#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
示例#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
    """
    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
示例#25
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)
示例#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...")
    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
示例#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
    """
    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
示例#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...")
    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
示例#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...")
    #     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
示例#30
0
文件: ps2.py 项目: sco1/6-0002
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