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


Python Graph.add_node方法代码示例

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


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

示例1: network_UKGDS

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例2: add_node

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
    def add_node(self, node=None, pos=None, ori=None, commRange=None):
        """
        Add node to network.

        Attributes:
          `node` -- node to add, default: new node is created
          `pos` -- position (x,y), default: random free position in environment
          `ori` -- orientation from 0 to 2*pi, default: random orientation

        """
        if (not node):
            node = Node(commRange=commRange)
        assert(isinstance(node, Node))
        if not node.network:
            node.network = self
        else:
            logger.warning('Node is already in another network, can\'t add.')
            return None

        pos = pos if pos is not None else self.find_random_pos(n=100)
        ori = ori if ori is not None else rand() * 2 * pi
        ori = ori % (2 * pi)

        if (self._environment.is_space(pos)):
            Graph.add_node(self, node)
            self.pos[node] = array(pos)
            self.ori[node] = ori
            self.labels[node] = str(node.id)
            logger.debug('Node %d is placed on position %s.' % (node.id, pos))
            self.recalculate_edges([node])
        else:
            logger.error('Given position is not free space.')
        return node
开发者ID:engalex,项目名称:pymote,代码行数:35,代码来源:network.py

示例3: network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例4: draw_network

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例5: make_prim_mst

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例6: test_exceptions

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def test_exceptions():
    test = Graph()
    test.add_node('a')
    assert_raises(NetworkXError, asyn_fluidc, test, 'hi')
    assert_raises(NetworkXError, asyn_fluidc, test, -1)
    assert_raises(NetworkXError, asyn_fluidc, test, 3)
    test.add_node('b')
    assert_raises(NetworkXError, asyn_fluidc, test, 1)
开发者ID:boothby,项目名称:networkx,代码行数:10,代码来源:test_asyn_fluid.py

示例7: polygon_skeleton

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例8: main

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [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

示例9: test_single_node

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def test_single_node():
    test = Graph()

    test.add_node('a')

    # ground truth
    ground_truth = set([frozenset(['a'])])

    communities = asyn_fluidc(test, 1)
    result = {frozenset(c) for c in communities}
    assert_equal(result, ground_truth)
开发者ID:aparamon,项目名称:networkx,代码行数:13,代码来源:test_asyn_fluidc.py

示例10: read_gml

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def read_gml(graph_file):
    graph = Graph()

    data = read_gml_data(graph_file)
    for n in data['graph']['node']:
        graph.add_node(int(n['id']))

    for e in data['graph']['edge']:
        graph.add_edge(int(e['source']), int(e['target']))

    return graph
开发者ID:Yang-Ho,项目名称:BEAVr,代码行数:13,代码来源:dataloader.py

示例11: read

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def read(string):

    """
    Read a graph from a string in Dot language and return it. Nodes and
    edges specified in the input will be added to the current graph.
    
    Args:
        - string: Input string in Dot format specifying a graph.
    
    Returns:
        - networkx.Graph object
    """

    lines = string.split("\n")
    first_line = lines.pop(0)
    if not re.match("graph \w+ {$", first_line):
        raise WrongDotFormatException("string contains no parseable graph")

    re_node = re.compile('^"([^"]*)"(?: \[([^]]*)\])?;?$')
    re_edge = re.compile('^"([^"]*)" -- "([^"]*)"(?: \[([^]]*)\])?;?$')

    gr = Graph()

    for line in lines:
        line = line.strip()
        match_node = re_node.search(line)
        match_edge = re_edge.search(line)
        if match_node:
            g = match_node.groups()
            gr.add_node(g[0])
            if g[1]:
                for attribute_string in g[1].split(", "):
                    key, value = attribute_string.split("=")
                    if value == "True":
                        value = True
                    elif value == "False":
                        value = False
                    gr.node[g[0]][key] = value

        elif match_edge:
            g = match_edge.groups()
            gr.add_edge(g[0], g[1])
            if g[2]:
                for attribute_string in g[2].split(", "):
                    key, value = attribute_string.split("=")
                    gr.edge[g[0]][g[1]][key] = value

        elif line != "}" and len(line) > 0:
            raise WrongDotFormatException("Could not parse line:\n\t{0}".format(line))

    return gr
开发者ID:pombredanne,项目名称:qlc,代码行数:53,代码来源:translationgraph.py

示例12: simplify

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def simplify(tree, keepers):
    """ Given a tree and a set of nodes to keep, create a new tree
    where only the nodes to keep and the branch points between them are preserved.
    WARNING: will reroot the tree at the first of the keepers.
    WARNING: keepers can't be empty. """
    # Ensure no repeats
    keepers = set(keepers)
    # Add all keeper nodes to the minified graph
    mini = Graph()
    for node in keepers:
        mini.add_node(node)
    # Pick the first to be the root node of the tree, removing it
    root = keepers.pop()
    reroot(tree, root)
    # For every keeper node, traverse towards the parent until
    # finding one that is in the minified graph, or is a branch node
    children = defaultdict(int)
    seen_branch_nodes = set(keepers) # a copy
    paths = []
    # For all keeper nodes except the root
    for node in keepers:
        path = [node]
        paths.append(path)
        parents = tree.predecessors(node)
        while parents:
            parent = parents[0]
            if parent in mini:
                # Reached one of the keeper nodes
                path.append(parent)
                break
            elif len(tree.successors(parent)) > 1:
                # Reached a branch node
                children[parent] += 1
                path.append(parent)
                if parent in seen_branch_nodes:
                    break
                seen_branch_nodes.add(parent)
            parents = tree.predecessors(parent)
    for path in paths:
        # A path starts and ends with desired nodes for the minified tree.
        # The nodes in the middle of the path are branch nodes
        # that must be added to mini only if they have been visited more than once.
        origin = path[0]
        for i in xrange(1, len(path) -1):
            if children[path[i]] > 1:
                mini.add_edge(origin, path[i])
                origin = path[i]
        mini.add_edge(origin, path[-1])

    return mini
开发者ID:braingram,项目名称:CATMAID,代码行数:52,代码来源:tree_util.py

示例13: polygon_dots_skeleton

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
def polygon_dots_skeleton(polygon, points):
    '''
    '''
    skeleton = Graph()

    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
    
    logging.debug('found %d skeleton edges' % len(skeleton.edge))
    
    return skeleton
开发者ID:Katiesun,项目名称:Skeletron,代码行数:50,代码来源:__init__.py

示例14: add_node

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
    def add_node(self, node=None, pos=None, ori=None, commRange=None, find_random=False):
        """
        Add node to network.

        Attributes:
          `node` -- node to add, default: new node is created
          `pos` -- position (x,y), default: random free position in environment
          `ori` -- orientation from 0 to 2*pi, default: random orientation

        """
        if (not node):
            node = Node(commRange=commRange or self.comm_range)
        if not node.commRange:
            node.commRange = commRange or self.comm_range

        assert(isinstance(node, Node))
        if not node.network:
            node.network = self
        else:
            logger.warning('Node is already in another network, can\'t add.')
            return None

        pos = pos if (pos is not None and not isnan(pos[0])) else self.find_random_pos(n=100)
        ori = ori if ori is not None else rand() * 2 * pi
        ori = ori % (2 * pi)

        got_random = False
        if find_random and not self._environment.is_space(pos):
            pos = self.find_random_pos(n=100)
            got_random = True

        if (self._environment.is_space(pos)):
            Graph.add_node(self, node)
            self.pos[node] = array(pos)
            self.ori[node] = ori
            self.labels[node] = ('C' if node.type == 'C' else "") + str(node.id)
            logger.debug('Node %d is placed on position %s %s %s'
                         % (node.id, pos,
                            '[energy=%5.3f]' %node.power.energy
                                    if node.power.energy != EnergyModel.E_INIT  else '',
                            'Random' if got_random else ''))
            self.recalculate_edges([node])
        else:
            Node.cid -= 1
            logger.error('Given position is not free space. [%s] %s' % (Node.cid, pos))
            node = None
        return node
开发者ID:SoonSYJ,项目名称:pymote2.0,代码行数:49,代码来源:network.py

示例15: get_coauthor_graph_by_author_name

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_node [as 别名]
    def get_coauthor_graph_by_author_name(self, name):
        coauthors = set()
        for p in self.publications:
            for a in p.authors:
                if a == self.author_idx[name]:
                    for a2 in p.authors:
                        if a != a2:
                            coauthors.add(a2)

        graph = Graph()
        # the nodes format will be {"id":int, "name":str}
        graph.add_node(self.author_idx[name], name = name)
        # graph.add_nodes_from([(i, {"name": all_data[0][i][0]}) for i in range(len(all_data[0]))])
        graph.add_nodes_from([(ca, {"name": self.authors[ca].name}) for ca in coauthors])
        graph.add_edges_from([(self.author_idx[name], ca) for ca in coauthors])

        return graph
开发者ID:JeffriesAgile,项目名称:comp61542-2014-lab,代码行数:19,代码来源:database.py


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