当前位置: 首页>>代码示例>>Python>>正文


Python Graph类代码示例

本文整理汇总了Python中Graph的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: initGraph

def initGraph(data):
	g = Graph()
	for i in range(len(data)/2):
		g.addNode(i)
		for j in range(i):
			g.addEdge(i, j, distance(float(data[i * 2]) * scale, float(data[i * 2 + 1]) * scale, float(data[j * 2]) * scale, float(data[j * 2 + 1]) * scale))
	return g
开发者ID:samgoree,项目名称:TSPAnts,代码行数:7,代码来源:antColonyOpt.py

示例2: __init__

class Application:

    #. Contructor .#
    def __init__ (self):
        self.interface = Interface(self.ButtonCallBack)    # Create an interface
        self.graph = Graph()                               # Create a graph
        self.graph.formGraph()                             # Form the graph
        
    #. Call back function when button is pressed .#
    def ButtonCallBack(self):
        startName = self.interface.getStartEntry().encode('gbk')
        destName = self.interface.getDestEntry().encode('gbk')
        start = self.graph.findVertex(startName)           # Find the start vertex
        dest = self.graph.findVertex(destName)             # Find the dest vertex
        # If start or dest are not found
        if start == None:
            result = startName.encode('utf8') + ' doesn\'t exist'
        elif dest == None:
            result = destName.encode('utf8') + ' doesn\'t exist'
        else:    # Normal case
            self.graph.BFS(start)
            result = self.graph.shortestPath(dest).encode('utf8')
        self.interface.updateText(result)

    #. Run the program .#
    def run(self):
        mainloop()
开发者ID:Irving-cl,项目名称:ShanghaiSubwayShortestPath,代码行数:27,代码来源:Application.py

示例3: TestFlightGraph

class TestFlightGraph(TestCase):

    def init_tests(self):
        f = open('data.json', 'r')
        parsed_JSON = json.loads(f.read())
        self.graphs = Graph()
        self.graphs.construct_nodes(parsed_JSON['metros'])
        self.graphs.contstruct_edges(parsed_JSON['routes'])
        self.stats = StatInfo()

    def test_init(self):
        assert (self.graphs.nodes.get('SFO').name == 'San Francisco')

    def test_longest_flight(self):
        assert (self.stats.longest_single_flight(self.graphs) == ('SYD', 'LAX', 12051))

    def test_shortest_flight(self):
        assert(self.stats.shortest_single_flight(self.graphs) == ('NYC', 'WAS', 334))

    def test_average_dist(self):
        assert (self.stats.average_network_distance(self.graphs) == 2300)

    def test_largest_pop(self):
        assert self.stats.largest_population(self.graphs) == ('TYO', 34000000)

    def test_smallest_pop(self):
        assert self.stats.smallest_population(self.graphs) == ('ESS', 589900)

    def test_average_network_pop(self):
        assert self.stats.average_network_population(self.graphs) == 11796143
开发者ID:oviya95,项目名称:CSAir,代码行数:30,代码来源:StatInfoTest.py

示例4: create_Graph_from_file

def create_Graph_from_file(file_name):
    graph = Graph()
    with open(file_name) as inputfile:
        next(inputfile)
        for line in inputfile:
            graph.add_node_to_Graph(line)
    return graph
开发者ID:LorenzoBi,项目名称:algorithm_design,代码行数:7,代码来源:hw_1b.py

示例5: main

def main(files):

    cfg   = Config()
    graph = Graph(cfg)

    for file in files:
        print file
        qaida = readFromXmlPrePhrase(file)
        for parta in qaida:
            for matra in parta:
                for i in range(len(matra)-1):
                    graph.createEdge(
                        graph.createNode(matra[i]),
                        graph.createNode(matra[i+1]))

#     for node in graph.nodes: print node
#     for edge in graph.edges: print edge
    
#    dist  = Distort(graph=graph, argo=DistortRandomSimple)
    dist  = Distort(graph=graph, argo=DistortRandomWeight)
    patt  = []
    i     = 0
    while True:
        e = dist.run()
        s = EdgesToStr(e)
        if s not in patt:
            patt.append(s)
            print "%3d %s" % (i, s)
            i += 1
开发者ID:branch-not-equal,项目名称:QaidaGraph,代码行数:29,代码来源:Distort.py

示例6: genrate_actualtour

 def genrate_actualtour(self, StartCity):
     """
     This method generates the graph of the bestTour. 
     
     It calls the move_branch method with a given StartCity. From the bestTour
     stack it filters out only the interestCities by leaving out all the 
     intersection points. It then creates an instance of graph class in the same
     order as in bestTour.
     """
     tour = Stack()  # create a new stack
     
     self.currentTour.push(StartCity)    # push the startCity in currentTour stack
     self.mark_visit(StartCity)  # mark it visited
     self.move_branch(StartCity) # call move_branch recursive function, with the given city
     
     # The following block of code removes vertices from bestTour and filters out
     # only the interest points and adds it to tour Stack
     while self.bestTour.size() != 0:    
         city = self.bestTour.pop()
         if city in self.interestCities:
             tour.push(city)
             
     # The following block of code generates a Graph object from the tour Stack
     newGraph = Graph(tour.items)    # adds only the vertices in the graph
     for i in range(len(tour.items)-1):
         newEdge = Edge(tour.items[i], tour.items[i+1])  # create an edge within two consecutive vertices
         newGraph.add_edge(newEdge)  # add the edge to the graph
     return newGraph
开发者ID:agarwali,项目名称:CampusTourGuide,代码行数:28,代码来源:best_tour.py

示例7: saveFriesFaceFFCC

def saveFriesFaceFFCC(graph1,graph2,count):

	g1 = graph1.getFaceGraph()
	g2 = graph2.getFaceGraph()

	v1 = makeVertexGraph(g1)
	v2 = makeVertexGraph(g2)

	G1 = Graph(g1,v1)
	G2 = Graph(g2,v2)


	structures1 = assignMatching(G1)
	structures2 = assignMatching(G2)

	Graph.comparison = 'fries'
	structures1.sort()
	structures2.sort()

	h1 = structures1[-1]
	h2 = structures2[-1]

	if not os.path.exists("FFCCConjectureConflicts"):
		os.mkdir("FFCCConjectureConflicts")
	folderName = "FFCCConjectureConflicts/" + str(G1.getNumVertices()) + "_" + str(count)

	#setup folder
	if not os.path.exists(folderName):
		os.mkdir(folderName)
			#print "adding"
	fileName1 = folderName + "/fries1" + ".png"
	fileName2 = folderName + "/fries2" + ".png"
			#print fileName1
	saveSinglePNG(h1,fileName1)
	saveSinglePNG(h2,fileName2)
开发者ID:Jc11235,项目名称:Kekulean_Program,代码行数:35,代码来源:DriverMethods.py

示例8: small_example

def small_example():
    
    graph = g.Graph('Small example graph')
    
    graph.add_node((0,1))
    graph.add_node((0,-1))
    graph.add_node((2,0))
    graph.add_node((4,0))
    graph.add_node((6,0))
    
    graph.add_link(1, 3, 1, delayfunc=g.create_delayfunc('Polynomial',(1.0, 1.0, [0.0])))
    graph.add_link(2, 3, 1, delayfunc=g.create_delayfunc('Polynomial',(2.0, 1.0, [0.0])))
    graph.add_link(3, 4, 1, delayfunc=g.create_delayfunc('Polynomial',(2.0, 1.0, [1.0])))
    graph.add_link(3, 4, 2, delayfunc=g.create_delayfunc('Polynomial',(1.0, 1.0, [2.0])))
    graph.add_link(4, 5, 1, delayfunc=g.create_delayfunc('Polynomial',(1.0, 1.0, [0.0])))
    
    graph.add_od(1, 5, 2.0)
    graph.add_od(2, 5, 3.0)
    
    graph.add_path([(1,3,1), (3,4,1), (4,5,1)])
    graph.add_path([(1,3,1), (3,4,2), (4,5,1)])
    graph.add_path([(2,3,1), (3,4,1), (4,5,1)])
    graph.add_path([(2,3,1), (3,4,2), (4,5,1)])
    
    return graph
开发者ID:cedavidyang,项目名称:bridge_ranking,代码行数:25,代码来源:generate_graph.py

示例9: graph_creationF

class graph_creationF(object):

    def __init__(self, weighted, wgraph):
        self.fname = wgraph
        self.wg = weighted
        self.g = Graph()
  
    def get_file(self, which_alg):
        self.g.alg = which_alg
        try:
            #self.fname = raw_input("Enter graph file: ")
            #self.wg = raw_input("Do you want to create a weighted Graph? ")

            file = open(self.fname, 'r')

            if self.wg[0] == 'y' or self.wg[0] == 'Y':
                for line in file:
                    s = line.split()
                    self.g.addEdge(s[0], s[1], int(s[2]))

            elif self.wg[0] == 'n' or self.wg[0] == 'N':
                for line in file:
                    s = line.split()
                    self.g.addEdge(s[0], s[1], 1)

            file.close()

            return self.g
        except:
            print "-----Graph File does not exist-----"
开发者ID:jflinn18,项目名称:DijkAlg,代码行数:30,代码来源:graph_creationF.py

示例10: tridiagonalGraph

def tridiagonalGraph(rows):

    g = Graph(rows)
    for i in range(rows):
        g.insertIndex(i, i)
        if i > 0     : g.insertIndex(i, i-1)
        if i < rows-1: g.insertIndex(i, i+1)

    return g
开发者ID:kanbang,项目名称:myexercise,代码行数:9,代码来源:tridiagonal.py

示例11: main

def main():
  if len(sys.argv) != 4:
    print "usage: python test.py numNodes, numWins, sizeWin"
    return
  
  # Call our initialize test function with 
  Graph.testInitialize(int(sys.argv[1]), \
                       int(sys.argv[2]), \
                       int(sys.argv[3]))
开发者ID:shiryehoshua,项目名称:AITicTacToe,代码行数:9,代码来源:test.py

示例12: EmotionAnalysis

def EmotionAnalysis(epsilon, figure):
    global news, CED
    EM.setEpsilon(epsilon)
    # for each new compute the emotional value and show it
    output = []  # output is a list of tuples with [day,CED of that day]
    for i in range(0, len(dayinterval)):
        EM.computeday(news[i], negativeLex, positiveLex, CED)
        output.append([news[i], CED.copy()])
    Graph.plotallfigure(figure, output, dayinterval)
    # after the execution we need to clean the values of the CED so they doesnt iterfere with next execution
    for word in cedwords:
        CED[word] = 0
开发者ID:gonzarugil,项目名称:BD,代码行数:12,代码来源:main.py

示例13: parse_topology

 def parse_topology(generate_json):
     """"generate JSON file for visualization if generate_json == True"""
     
     tree = ET.parse("abilene-TM" + os.sep + "topo" + os.sep + "Abilene-Topo-10-04-2004.xml")
     root = tree.getroot()
     
     topology = root.find("topology")
     
     node_list = []
     link_list = []
     graph = Graph(node_list, link_list)
     
     if generate_json:
         f = open("data.json", "w")
         output = {"nodes":{}, "links":[]}
     
     for node in topology.iter("node"):
         new_node = Node(node.attrib["id"])
         node_list.append(new_node)   
         
         if generate_json:
             location = node.find("location")
             new_node.set_location(float(location.attrib["latitude"]),
                                   float(location.attrib["longitude"]))
             output["nodes"][new_node.node_id] =\
                 (float(location.attrib["latitude"]), 
                  float(location.attrib["longitude"])) 
                     
     for link in topology.iter("link"):
         link_id = link.attrib["id"]
         link_from = graph.find_node(link.find("from").attrib["node"])
         link_to = graph.find_node(link.find("to").attrib["node"])
         bw = int(link.find("bw").text)
         new_link = Link(link_id, link_from, link_to, bw)
         link_list.append(new_link)
         
         if generate_json:
             output["links"].append(\
                 ((link_from.lat, link_from.lng), 
                  (link_to.lat, link_to.lng)))
             
     igp = root.find("igp").find("links")
     for link in igp.iter("link"):
         link_id = link.attrib["id"]
         link_obj = graph.find_link_by_id(link_id)
         if link_obj != None:
             link_obj.metric = float(link.find("static").find("metric").text)
         
     if generate_json:    
         json.dump(output, f)            
         f.close()
         
     return graph
开发者ID:alexyida,项目名称:ECE1524,代码行数:53,代码来源:Parser.py

示例14: drawWithGraph

    def drawWithGraph(window, audioData):
        global p
        graph = Graph( Point(75, 50), 50)
        graph.draw(window)
        #p = None
        for d in audioData:
            if p:
                p.undraw()

            bx, by = normalize(d[0], d[1], d[2])

            p =  graph.createPoint(bx, by)
            p.draw(window)
开发者ID:TaitMadsen,项目名称:Vowel-Shapes,代码行数:13,代码来源:GraphicsModulePrototype_1_1.py

示例15: __init__

class Control:
    def __init__(self):
        print "Control __init__"
        self.Access = Access()
        self.Graph = Graph()
        self.Player = Player()
        #self.Xml = Xml()
        self.Access.classAddresses(self.Graph,self.Player,self)
        self.Graph.classAddresses(self.Access,self.Player,self)
        self.Player.classAddresses(self.Graph,self.Access,self)
        #self.Xml.classAddresses(self.Graph,self.Access,self.Player,self)
        self.Access.start()
        self.Graph.getCode()
开发者ID:Musinux,项目名称:LinCloud,代码行数:13,代码来源:Control.py


注:本文中的Graph类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。