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


Python Graph.add_edge方法代码示例

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


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

示例1: make_prim_mst

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def make_prim_mst(G, generator=None):
	if generator is None:
		mst = Graph()
	else:
		mst = generator()       
	#priorityQ is a list of list (the reverse of the edge tuple with the weight in the front)
	priorityQ = []
	firstNode = G.nodes()[0]
	mst.add_node(firstNode)
	for edge in G.edges_iter(firstNode, data=True):
		if len(edge) != 3 or edge[2] is None:
			raise ValueError, "make_prim_mst accepts a weighted graph only (with numerical weights)"
		heappush(priorityQ, (edge[2], edge))

	while len(mst.edges()) < (G.order()-1):
		w, minEdge = heappop(priorityQ)
		if len(minEdge) != 3 or minEdge[2] is None:
			raise ValueError, "make_prim_mst accepts a weighted graph only (with numerical weights)"
		v1, v2, w = minEdge
		if v1 not in mst:
			for edge in G.edges_iter(v1, data=True):
				if edge == minEdge:
					continue
				heappush(priorityQ, (edge[2], edge))
		elif v2 not in mst:
			for edge in G.edges_iter(v2, data=True):
				if edge == minEdge:
					continue
				heappush(priorityQ, (edge[2], edge))
		else:
			# non-crossing edge 
			continue 
		mst.add_edge(minEdge[0],minEdge[1],minEdge[2])
	return mst
开发者ID:MwrulesC,项目名称:gographer,代码行数:36,代码来源:SteinerTree.py

示例2: summarize

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def summarize(text, sentence_count=5, language='english'):
    processor = LanguageProcessor(language)

    sentence_list = processor.split_sentences(text)
    wordset_list = map(processor.extract_significant_words, sentence_list)
    stemsets = [
        {processor.stem(word) for word in wordset}
        for wordset in wordset_list
    ]

    graph = Graph()
    pairs = combinations(enumerate(stemsets), 2)
    for (index_a, stems_a), (index_b, stems_b) in pairs:
        if stems_a and stems_b:
            similarity = 1 - jaccard(stems_a, stems_b)
            if similarity > 0:
                graph.add_edge(index_a, index_b, weight=similarity)

    ranked_sentence_indexes = list(pagerank(graph).items())
    if ranked_sentence_indexes:
        sentences_by_rank = sorted(
            ranked_sentence_indexes, key=itemgetter(1), reverse=True)
        best_sentences = map(itemgetter(0), sentences_by_rank[:sentence_count])
        best_sentences_in_order = sorted(best_sentences)
    else:
        best_sentences_in_order = range(min(sentence_count, len(sentence_list)))

    return ' '.join(sentence_list[index] for index in best_sentences_in_order)
开发者ID:despawnerer,项目名称:summarize,代码行数:30,代码来源:summarize.py

示例3: network_UKGDS

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def network_UKGDS(filename,header=28):
	"""
	Load Excel file with UKGDS data format and build dict array of bus coordinates
	and graph structure suitable for plotting with the networkx module.
	"""
	from numpy import array,where
	from pandas import ExcelFile
	from networkx import Graph

	data = ExcelFile(filename)
	bus = data.parse("Buses",header=header)
	branch = data.parse("Branches",header=header)
	pos = {}
	for node in range(len(bus["BNU"])):
		pos.update({node:array([bus["BXC"][node],bus["BYC"][node]])})
	net = []
	for k in range(len(branch["CFB"])):
		von = where(bus["BNU"]==branch["CFB"][k])[0][0]
		zu  = where(bus["BNU"]==branch["CTB"][k])[0][0]
		net.append([von,zu])
	nodes = set([n1 for n1,n2 in net] + [n2 for n1,n2 in net])
	G = Graph()
	for node in nodes:
		G.add_node(node)
	for edge in net:
		G.add_edge(edge[0],edge[1])
	return G,pos
开发者ID:alexandroskets,项目名称:GridSens,代码行数:29,代码来源:data_tools.py

示例4: network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def network(qmatrix): 
  """ Creates networkx graph object from a :class:`QMatrix` object.
  
      Vertices have an "open" attribute to indicate whether they are open or shut. Edges have a
      "k+" and "k-" attribute containing the transition rates for the node with smaller index to
      the node with larger index, and vice-versa. 

      :param qmatrix: 
        A :class:`QMatrix` instance for which to construct a graph
      :return: A `networkx.Graph` object which contains all the information held by the qmatrix
               object, but in a graph format.
  """
  from networkx import Graph

  graph = Graph()
  for i in range(qmatrix.nopen): graph.add_node(i, open=True)
  for j in range(qmatrix.nshut): graph.add_node(i+j, open=False)

  for i in range(qmatrix.matrix.shape[0]):
    for j in range(i, qmatrix.matrix.shape[1]):
      if abs(qmatrix.matrix[i,j]) > 1e-8:
        graph.add_edge(i, j)
        graph[i][j]['k+'] = qmatrix.matrix[i, j]
        graph[i][j]['k-'] = qmatrix.matrix[j, i]
  return graph
开发者ID:DCPROGS,项目名称:HJCFIT,代码行数:27,代码来源:_methods.py

示例5: draw_network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def draw_network(bus,branch,bus_names=None,coordinates=None,ax=None):
	"""Generate networkx Graph object and draw network diagram
	It is assumed that bus and branch ordering corresponds to PyPower format
	"""
	from networkx import Graph,draw
	from matplotlib.pyplot import show
	if isinstance(coordinates,np.ndarray):
		pos = {}
		if coordinates.shape[0]==2:
			coordinates = coordinates.T
		for node in range(len(bus)):
			pos.update({node:coordinates[node,:]})
	else:
		pos = None
	net = []
	for k in range(len(branch)):
		von = np.where(bus[:,BUS_I]==branch[k,F_BUS])[0][0]
		zu  = np.where(bus[:,BUS_I]==branch[k,T_BUS])[0][0]
		net.append([von,zu])
	nodes = set([n1 for n1,n2 in net] + [n2 for n1,n2 in net])
	G = Graph()
	for node in nodes:
		G.add_node(node)
	for edge in net:
		G.add_edge(edge[0],edge[1])
	draw(G,pos,ax=ax)
	show()
开发者ID:alexandroskets,项目名称:GridSens,代码行数:29,代码来源:data_tools.py

示例6: fuzz_network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def fuzz_network(G_orig, threshold, b, edge_frac=1.0, nonedge_mult=5.0):
    G = G_orig.copy()
    n = len(G.nodes())
    H = Graph()
    H.add_nodes_from(range(n))
    pairs = n * (n - 1) / 2
    actual_edges = len(G.edges())
    edges = int(edge_frac * actual_edges)
    nonedges = int(edges * nonedge_mult)

    a = b / nonedge_mult

    # though these distributions are normalized to one, by selecting the appropriate number of edges
    # and nonedges, we make these 'distributions' correct
    edge_probs = np.random.beta(a + 1, b, edges)
    nonedge_probs = np.random.beta(a, b + 1, nonedges)

    # picking the right number of edges from the appropriate list
    edge_list = G.edges()
    nonedge_list = list(non_edges(G))
    shuffle(edge_list)
    shuffle(nonedge_list)
    for i in range(len(edge_probs)):
        G[edge_list[i][0]][edge_list[i][1]]["weight"] = edge_probs[i]
        if edge_probs[i] > threshold:
            H.add_edge(edge_list[i][0], edge_list[i][1])
    for i in range(len(nonedge_probs)):
        G.add_edge(nonedge_list[i][0], nonedge_list[i][1], weight=nonedge_probs[i])
        if nonedge_probs[i] > threshold:
            H.add_edge(nonedge_list[i][0], nonedge_list[i][1])

    return G, H
开发者ID:tbmbob,项目名称:uncertain-networks,代码行数:34,代码来源:utils.py

示例7: generate_small_world_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
 def generate_small_world_graph(self):
     max_edges = self.NODE_COUNT*(self.NODE_COUNT-1)/2
     if self.EDGE_COUNT > max_edges:
         return complete_graph(self.NODE_COUNT)
     graph = Graph()
     graph.add_nodes_from(range(self.NODE_COUNT))
     edges = performer.edge_indices.flatten()
     probabilities = performer.probabilities.flatten()
     for trial in range(len(edges)-9):
         edge_index = numpy.random.choice(edges, p=probabilities)
         source, destination = self.edge_nodes(edge_index)
         graph.add_edge(source, destination, length = self.link_length(source, destination),
                        weight = self.edge_weight(source, destination))
         probabilities[edge_index] = 0
         probabilities /= sum(probabilities)
         if max(graph.degree().values()) > self.DEGREE_MAX:
             graph.remove_edge(source, destination)
         if graph.number_of_edges() > self.EDGE_COUNT:
             victim = random.choice(graph.edges())
             graph.remove_edge(victim[0], victim[1])
         if self.constraints_satisfied(graph):
             print 'performer.generate_small_world_graph:',
             print self.BENCHMARK, self.NODE_COUNT, self.EDGE_COUNT, trial
             self.process_graph(graph)
             return graph
开发者ID:yuchenhou,项目名称:artificial-architect,代码行数:27,代码来源:architect.py

示例8: build_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def build_graph(ways):
    graph = Graph()
    for way, tags in ways:
        for segment in nwise(way.coords):
            weight = length(segment) * coef(tags)
            graph.add_edge(segment[0], segment[1],
                           weight=weight)
    return graph
开发者ID:mishok13,项目名称:ep2011,代码行数:10,代码来源:routing-networkx.py

示例9: find_rings

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def find_rings(atoms):
    graph = Graph()
    for i, atom1 in enumerate(atoms):
        for atom2 in atoms[i+1:]:
            if is_bound(atom1.cart, atom1.element, atom2.cart, atom2.element):
                graph.add_edge(atom1.name, atom2.name)
    ring_list = cycle_basis(graph)
    return ring_list
开发者ID:JLuebben,项目名称:APD-Toolkit,代码行数:10,代码来源:ringstest.py

示例10: make_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def make_graph(points, neighbor_max_dist=0.01):
    graph = Graph()
    graph.add_nodes_from(range(len(points)))
    for i in xrange(len(points)):
        for j in xrange(i+1, len(points)):
            if euclidian_3d_dist(points[i], points[j])<neighbor_max_dist:
                graph.add_edge(i,j)
    return graph
开发者ID:ChenyuLInx,项目名称:ece490-s2016,代码行数:10,代码来源:common_utils.py

示例11: polygon_skeleton

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def polygon_skeleton(polygon, density=10):
    """ Given a buffer polygon, return a skeleton graph.
    """
    skeleton = Graph()
    points = []
    
    for ring in polygon_rings(polygon):
        points.extend(densify_line(list(ring.coords), density))
    
    if len(points) <= 4:
        # don't bother with this one
        return skeleton
    
    print >> stderr, ' ', len(points), 'perimeter points',
    
    rbox = '\n'.join( ['2', str(len(points))] + ['%.2f %.2f' % (x, y) for (x, y) in points] + [''] )
    
    qvoronoi = Popen('qvoronoi o'.split(), stdin=PIPE, stdout=PIPE)
    output, error = qvoronoi.communicate(rbox)
    voronoi_lines = output.splitlines()
    
    if qvoronoi.returncode:
        raise _QHullFailure('Failed with code %s' % qvoronoi.returncode)
    
    vert_count, poly_count = map(int, voronoi_lines[1].split()[:2])
    
    for (index, line) in enumerate(voronoi_lines[2:2+vert_count]):
        point = Point(*map(float, line.split()[:2]))
        if point.within(polygon):
            skeleton.add_node(index, dict(point=point))
    
    for line in voronoi_lines[2+vert_count:2+vert_count+poly_count]:
        indexes = map(int, line.split()[1:])
        for (v, w) in zip(indexes, indexes[1:] + indexes[:1]):
            if v not in skeleton.node or w not in skeleton.node:
                continue
            v1, v2 = skeleton.node[v]['point'], skeleton.node[w]['point']
            line = LineString([(v1.x, v1.y), (v2.x, v2.y)])
            if line.within(polygon):
                skeleton.add_edge(v, w, dict(line=line, length=line.length))
    
    removing = True
    
    while removing:
        removing = False
    
        for index in skeleton.nodes():
            if skeleton.degree(index) == 1:
                depth = skeleton.node[index].get('depth', 0)
                if depth < 20:
                    other = skeleton.neighbors(index)[0]
                    skeleton.node[other]['depth'] = depth + skeleton.edge[index][other]['line'].length
                    skeleton.remove_node(index)
                    removing = True
    
    print >> stderr, 'contain', len(skeleton.edge), 'internal edges.'
    
    return skeleton
开发者ID:netconstructor,项目名称:Skeletron,代码行数:60,代码来源:__init__.py

示例12: main

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def main(argv):
    
    if len(argv) < 3:
        print("call: translations_spanish_graph.py data_path (bibtex_key|component)")
        sys.exit(1)

    cr = CorpusReaderDict(argv[1])

    dictdata_ids = cr.dictdata_ids_for_bibtex_key(argv[2])
    if len(dictdata_ids) == 0:
        dictdata_ids = cr.dictdata_ids_for_component(argv[2])
        if len(dictdata_ids) == 0:
            print("did not find any dictionary data for the bibtex_key or component {0}.".format(argv[2]))
            sys.exit(1)
        

    for dictdata_id in dictdata_ids:
        gr = Graph()
        src_language_iso = cr.src_languages_iso_for_dictdata_id(dictdata_id)
        tgt_language_iso = cr.tgt_languages_iso_for_dictdata_id(dictdata_id)
        if (src_language_iso != ['spa']) and (tgt_language_iso != ['spa']):
            continue
        
        if (len(src_language_iso) > 1) or (len(tgt_language_iso) > 1):
            continue
        
        language_iso = None
        if tgt_language_iso == [ 'spa' ]:
            language_iso = src_language_iso[0]
        else:
            language_iso = tgt_language_iso[0]
                        
        dictdata_string = cr.dictdata_string_id_for_dictata_id(dictdata_id)
        bibtex_key = dictdata_string.split("_")[0]

        for head, translation in cr.heads_with_translations_for_dictdata_id(dictdata_id):
            if src_language_iso == [ 'spa' ]:
                (head, translation) = (translation, head)
                
            head_with_source = escape_string("{0}|{1}".format(head, bibtex_key))
            translation = escape_string(translation)
            
            #translation_with_language = "{0}|{1}".format(translation, language_iso)
            
            #if head_with_source not in gr:
            gr.add_node(head_with_source, attr_dict={ "lang": language_iso, "source": bibtex_key })
            
            #if translation not in gr:
            gr.add_node(translation, attr_dict={ "lang": "spa" })
                
            #if not gr.has_edge((head_with_source, translation)):
            gr.add_edge(head_with_source, translation)

        output = codecs.open("{0}.dot".format(dictdata_string), "w", "utf-8")
        output.write(write(gr))
        output.close()
开发者ID:pombredanne,项目名称:qlc,代码行数:58,代码来源:translations_spanish_graph.py

示例13: read_rw

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def read_rw():
	"""
	Parses the rare word similarity test collection.
	"""
	G = Graph()
	filename = get_support_data_filename('rw/rw.txt')
	with open(filename) as file:
		for line in file:
			parts = line.split()
			G.add_edge(parts[0], parts[1], weight=(float(parts[2])/10))
开发者ID:KGerring,项目名称:RevealMe,代码行数:12,代码来源:wordsim.py

示例14: read_mc

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def read_mc():
	"""
	Parses the Miller and Charles word similarity test collection.
	"""
	G=Graph()
	filename = get_support_data_filename('mc/EN-MC-30.txt')
	with open(filename) as file:
		for line in file:
			parts = line.split()
			G.add_edge(parts[0], parts[1], weight=float(parts[2]))
开发者ID:KGerring,项目名称:RevealMe,代码行数:12,代码来源:wordsim.py

示例15: read_graphml

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edge [as 别名]
def read_graphml(graph_file):
    from BeautifulSoup import BeautifulSoup as Soup
    soup = Soup(graph_file.read())
    graph = Graph()

    for edge in soup.findAll("edge"):
        source = int(edge['source'])
        target = int(edge['target'])
        graph.add_edge(source, target)
    return graph
开发者ID:Yang-Ho,项目名称:BEAVr,代码行数:12,代码来源:dataloader.py


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