• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python networkx.nodes函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

 def __init__(self, graph, sd):
     #We need a deepcopy if the self.graph gets modified.
     self.graph = graph.copy() 
     np.random.seed()
     self.result_graph = nx.Graph()
     
     #Sets with/without monitors.
     self.monitor_set = set()
     self.monitor_free=nx.nodes(self.graph) #Save this list to speed computations.
     
     #Internal dictionaries
     self.next_highest = {}
     self.seen = Counter()
     
     #2-Colored Components
     self.blueseen = 0
     self.redseen = 0
     self.monitor_fancy = list()
     
                     
     #Initialize all fake degrees to degree
     self.fake_degree=dict()
     #for node in self.monitor_free:
     for node in nx.nodes(self.graph):
         self.fake_degree[node]=self.graph.degree(node)
开发者ID:Pelonza,项目名称:Graph_Inference,代码行数:25,代码来源:MUDD.py


示例2: occurenceCounter

def occurenceCounter(charList, graphFile, bookNetworksPath):
    g = nx.read_gexf(graphFile)

    if not charList:
        # Get characters from overall.gexf graph
        overallGraphFile = bookNetworksPath + "overall.gexf"
        overall_g = nx.read_gexf(overallGraphFile)
        overallChars = nx.nodes(overall_g)

        # Sort dictionary by name (key of dictionary)
        sortedChars = sorted(overallChars)

        return sortedChars

    else:
        charList = [item for item in charList]

        for index, item in enumerate(charList):
            currentChar = None
            for node in nx.nodes(g):
                if node == item:
                    occurrence = 1
                    charList[index] = (item, occurrence)
                    currentChar = node
            # If current character is not present in the current chapter assign 0 influence.
            if not currentChar:
                occurrence = 0
                charList[index] = (item, occurrence)

        return charList
开发者ID:pivots,项目名称:networkx-sna-fiction,代码行数:30,代码来源:snaData.py


示例3: write_blast_graph_file

    def write_blast_graph_file(self):
        file_name = "{}/blast_graph.txt".format(self.blast_output_path)
        if len(nx.nodes(self.blast_graph)) > 0:
            with open(file_name, "wb") as f_handle:
                f_handle.write(
                    'Source' + ', Species,' + str(
                        [value for value in self.blast_graph.node[nx.nodes(self.blast_graph)[0]].iterkeys()]).strip(
                        '[]') + ',')
                f_handle.write(
                    'Target' + ', Species,' + str(
                        [value for value in self.blast_graph.node[nx.nodes(self.blast_graph)[0]].iterkeys()]).strip(
                        '[]') + ',')
                f_handle.write(
                    'evalue' + ',' + 'identpct' + ',' + 'mismatchno' + ',' + 'aln' + ',' + 'alnspn' + ',' + 'gapopenno' + ',' + 'bitscore' + '\n')

                for u, v, edata in self.blast_graph.edges(data=True):
                    f_handle.write(
                        str(u) + ',' + self.get_species_name(str(u)) + str(
                            [value for value in self.blast_graph.node[u].itervalues()]).strip(
                            '[]') + ',')
                    f_handle.write(
                        str(v) + ',' + self.get_species_name(str(v)) + str(
                            [value for value in self.blast_graph.node[v].itervalues()]).strip(
                            '[]') + ',')
                    f_handle.write(
                        str(edata['evalue']) + ',' + str(edata['identpct']) + ',' + str(edata['mismatchno']) + ',' +
                        str(edata['aln']) + ',' + str(edata['alnspn']) + ',' +
                        str(edata['gapopenno']) + ',' + str(edata['bitscore']) + '\n')
开发者ID:Falgunithakor,项目名称:BioInfo,代码行数:28,代码来源:SimilarityNetworks.py


示例4: get_region_colors

def get_region_colors(adjacency_matrix):
    """
    Calculate color for each region in the graph.

    Input: adjacency_matrix - graph adjacency_matrix where [x][y] = 1 means
                              that region x and region y share common border.

    Output: colors_dictionary - dictionary object where key is region number
                                and value is color (witches - 1, vampires - 2, werewolves - 3, hybrids - 4)
    """
    G = nx.Graph()
    colors_dictionary = {}

    if len(adjacency_matrix) == 1:
        colors_dictionary[0] = 1
        return colors_dictionary

    G = create_color_none_graph(adjacency_matrix, G)
    G = set_node_colors(G)

    for node in nx.nodes(G):
        node_color = G.node[node]['color']
        node_color += 1
        G.node[node]['color'] = node_color

    for node in nx.nodes(G):
        colors_dictionary[node] = G.node[node]['color']

    return colors_dictionary
开发者ID:DontSeeSharp,项目名称:PythonExcercises,代码行数:29,代码来源:EX16.py


示例5: gimme

def gimme():
    l = Linkbase(LinkNode)
    l.new_node(u'There once was a man from Nantucket.')
    l.new_node(u'who put all on the line for a bucket.')
    l.link(0,1,0)
    print networkx.nodes(l.store)
    return l
开发者ID:psammetichus,项目名称:lexiabase,代码行数:7,代码来源:linkbase.py


示例6: make_graph

def make_graph(list, density):
    g = nx.DiGraph()
    for i in list:
        g.add_node(i)
    for node in nx.nodes(g):
        while g.out_degree(node)<density:
            rand = random.choice(nx.nodes(g))
            if rand != node:
                g.add_edge(node, rand)
    return g
开发者ID:sverrirth,项目名称:genetic-isomorphism,代码行数:10,代码来源:Isomorphism.py


示例7: execute

    def execute(self, G, epsilon=0.0, weighted=False, min_community_size=1):
        """
        Execute Demon algorithm

        :param G: the networkx graph on which perform Demon
        :param epsilon: the tolerance required in order to merge communities (default 0.25)
        :param weighted: Whether the graph is weighted or not
        :param min_community_size:min nodes needed to form a community
        """

        #######
        self.G = G
        self.epsilon = epsilon
        self.min_community_size = min_community_size
        for n in self.G.nodes():
            G.node[n]['communities'] = [n]
        self.weighted = weighted
        #######

        all_communities = {}

        total_nodes = len(nx.nodes(self.G))
        actual = 0

        for ego in nx.nodes(self.G):
            percentage = float(actual * 100)/total_nodes

            #if (int(percentage) % 1) == 0:
            #    print 'Ego-network analyzed: %d/100 (communities identified: %d)' % (
            #        percentage, len(all_communities))
            actual += 1

            #ego_minus_ego
            ego_minus_ego = nx.ego_graph(self.G, ego, 1, False)
            community_to_nodes = self.__overlapping_label_propagation(ego_minus_ego, ego)

            #merging phase
            for c in community_to_nodes.keys():
                if len(community_to_nodes[c]) > self.min_community_size:
                    actual_community = community_to_nodes[c]
                    all_communities = self.__merge_communities(all_communities, actual_community)

        #print communities
        #out_file_com = open("communities", "w")
        idc = 0
        for c in all_communities.keys():
            #out_file_com.write("%d\t%s\n" % (idc, ','.join([str(x) for x in sorted(c)])))
            print("%d\t%s" % (idc, ','.join([str(x) for x in sorted(c)])))
            idc += 1
        #out_file_com.flush()
        #out_file_com.write("\n")
        #out_file_com.flush()
        #out_file_com.close()

        return
开发者ID:nkfly,项目名称:sna-final,代码行数:55,代码来源:Demon.py


示例8: get_graph

def get_graph(filename, with_root=False):
    DG = nx.DiGraph()
    f = open(filename, 'r')
    line = None
    edges = []
    coordinates = []
    terms = []
    if with_root:
        root = None
    while line != 'EOF':
        line = f.readline().strip()
        toks = line.split(' ')
        if toks[0] == 'A':
            t = tuple(int(x) for x in toks[1:])
            edges.append(t)
        if toks[0] == 'T':
            terms.append(int(toks[1]))
        if toks[0] == 'Root':
            if with_root:
                root = int(toks[1])
        if toks[0] == 'DD':
            t = tuple(int(x) for x in toks[1:])
            coordinates.append(t)
    for coord in coordinates:
        DG.add_node(coord[0], pos=(coord[1], coord[2]))
    terms.sort()
    DG.add_weighted_edges_from(edges)
    # print_graph(DG)
    # nx.draw(DG, node_size=50)
    # plt.show()
    # f.close()
    if with_root:
        return DG, terms, root
    else:
        print_graph(DG)
        max_len = 0
        max_node = None
        for node in nx.nodes(DG):
            # print(node, tr_cl.out_edges(node))
            descs = nx.descendants(DG, node)
            # desc_numb = len(descs)
            if len(set(terms) & set(descs)) == len(descs):
                # max_len = desc_numb
                max_node = node
        if max_len == len(nx.nodes(DG)):
            return DG, terms, max_node
        else:
            reachable = set(nx.descendants(DG, max_node)) | {max_node}
            unreachable = set(nx.nodes(DG)) - reachable
            for node in unreachable:
                DG.remove_node(node)
        terms = list(set(terms) & reachable)
        print('terms =', len(terms))
        return DG, terms, max_node
开发者ID:kamilsa,项目名称:MST_TG,代码行数:54,代码来源:main.py


示例9: execute

    def execute(self):
        """
        Execute Demon algorithm

        """

        sys.stdout.write('\n[Community Extraction]\n')
        sys.stdout.flush()

        for n in self.g.nodes():
            self.g.node[n]['communities'] = [n]

        all_communities = {}

        total_nodes = len(nx.nodes(self.g))
        old_p = 0
        actual = 1

        bar_length = 20

        for ego in nx.nodes(self.g):

            ego_minus_ego = nx.ego_graph(self.g, ego, 1, False)
            community_to_nodes = self.__overlapping_label_propagation(ego_minus_ego, ego)

            # merging phase
            for c in community_to_nodes.keys():
                if len(community_to_nodes[c]) > self.min_community_size:
                    actual_community = community_to_nodes[c]
                    all_communities = self.__merge_communities(all_communities, actual_community)

            # progress bar update
            percentage = int(float(actual * 100) / total_nodes)
            if percentage > old_p:
                hashes = '#' * int(round(percentage/5))
                spaces = ' ' * (bar_length - len(hashes))
                sys.stdout.write("\rExec: [{0}] {1}%".format(hashes + spaces, int(round(percentage))))
                sys.stdout.flush()
                old_p = percentage
            actual += 1

        if self.file_output:
            out_file_com = open("%s.txt" % self.file_output, "w")
            idc = 0
            for c in all_communities.keys():
                out_file_com.write("%d\t%s\n" % (idc, str(sorted(c))))
                idc += 1
            out_file_com.flush()
            out_file_com.close()
            return all_communities
        else:
            return all_communities
开发者ID:pigna90,项目名称:lastfm_network_analysis,代码行数:52,代码来源:Demon.py


示例10: random_walk

def random_walk(g,start=None,seed=None):
    random.seed(seed)
    if start is None:
        start=random.choice(nx.nodes(g))
    walk=[]
    unused_nodes=set(nx.nodes(g))
    unused_nodes.remove(start)
    while len(unused_nodes) > 0:
        p=start
        start=random.choice([x for x in nx.all_neighbors(g,start)]) # follow random edge
        walk.append((p,start))
        if start in unused_nodes:
            unused_nodes.remove(start)
    return walk
开发者ID:FilipMiscevic,项目名称:randomwalk,代码行数:14,代码来源:rw.py


示例11: findDominatingSet

    def findDominatingSet(self, graph):
        print "Algorithm: Modified greedy"

        modify_graph = copy.deepcopy(graph)
        dominating_set = []
        nodes = nx.nodes(modify_graph)

        while not len(nodes) == 0:
            node = self.findMaxDegreeNode(modify_graph)
            dominating_set.append(node)
            modify_graph = self.removeNodeAndNeighbors(modify_graph, node)
            nodes = nx.nodes(modify_graph)

        return dominating_set
开发者ID:Szop-Kradziej,项目名称:GIS_Dominating_Set,代码行数:14,代码来源:ModifiedGreedyAlgorithm.py


示例12: execute

    def execute(self, G, epsilon=0.25, weighted=False, min_community_size=3):
        """
        Execute Demon algorithm

        :param G: the networkx graph on which perform Demon
        :param epsilon: the tolerance required in order to merge communities
        :param weighted: Whether the graph is weighted or not
        :param min_community_size:min nodes needed to form a community
        """

        #######
        self.G = G
        self.epsilon = epsilon
        self.min_community_size = min_community_size
        for n in self.G.nodes():
            G.node[n]['communities'] = [n]
        self.weighted = weighted
        #######

        print  'hello'
        all_communities = {}

        total_nodes = len(list(nx.nodes(self.G)))
        actual = 0
        old_percentage = 0
        for ego in nx.nodes(self.G):
            percentage = float(actual * 100) / total_nodes

            actual += 1

            # ego_minus_ego
            ego_minus_ego = nx.ego_graph(self.G, ego, 1, False)
            community_to_nodes = self.__overlapping_label_propagation(ego_minus_ego, ego)

            # merging phase
            for c in community_to_nodes.keys():
                if len(community_to_nodes[c]) > self.min_community_size:
                    actual_community = community_to_nodes[c]
                    all_communities = self.__merge_communities(all_communities, actual_community)

        # print communities
        out_file_com = open("communities.txt", "w")
        idc = 0
        for c in all_communities.keys():
            out_file_com.write("%d\t%s\n" % (idc, str(sorted(c))))
            idc += 1
        out_file_com.flush()
        out_file_com.close()

        return
开发者ID:BB90,项目名称:CommunityDetectionCodes,代码行数:50,代码来源:Demon.py


示例13: averageNeighDegree

def averageNeighDegree(G):
    sum=0
    l=nx.nodes(G)
    for elt in l:
        sum+=G.degree(elt)
    avg=sum/(nx.number_of_nodes(G))
    return avg
开发者ID:JacquesLine,项目名称:petroglyphs,代码行数:7,代码来源:createVector.py


示例14: give_output_list

	def give_output_list(self, game):
		""" This returns a list of the selected nodes. The twin attack player
		finds the highest degree nodes, and for each, it selects two
		neighbors of that node and"""

		nodes = nx.nodes(game.network)

		nodes.sort(key=lambda x : nx.degree(game.network, x), reverse=True)

		selections = set()

		for node in nodes:

			adjacents = list(nx.all_neighbors(game.network, node))

			for adj_node in adjacents[:2]:

				selections.add(adj_node)
				if len(selections) == game.num_seeds:
					break

			if len(selections) == game.num_seeds:
				break

		assert len(selections) == game.num_seeds
		return list(selections)
开发者ID:BoltonBailey,项目名称:Pandemaniac-Team-Bob,代码行数:26,代码来源:graph.py


示例15: atom_graph

def atom_graph(g):
    # determine if subgroup is attached
    h = nx.Graph()
    v = []
    tris = {}
    edges = {}
    for node,data in g.nodes(data=True):
        g.node[node]['atoms'] = set([])

    # triplet
    for node in nx.nodes(g):
        for each in g[node]:
            if each == node: continue
            neighbors = set(g[node]).intersection(set(g[each]))
            #print(node, each, neighbors, set(g[node]), g[each], set(g[each]))
            for neighbor in neighbors:
                t = tuple(sorted((node, each, neighbor)))
                if t not in list(tris.keys()):
                    nr = len(h.nodes())
                    tris[t] = nr
                    h.add_node(nr)
                    g.node[node]['atoms'].add(nr)
                    g.node[each]['atoms'].add(nr)
                    g.node[neighbor]['atoms'].add(nr)
                    #print(node, each, neighbor)
                    for k in tris:
                        if len(set(k).intersection(set(t))) == 2:
                            h.add_edge(nr, tris[k])
                            edges[tuple(sorted(set(k).intersection(set(t))))] = nr

    #if nx.cycle_basis(h):
    #    extra_nodes = set(h.nodes()).difference(set(np.concatenate(nx.cycle_basis(h))))
    #    for n in extra_nodes:
    #        h.remove_node(n)
    return h
开发者ID:sunhwan,项目名称:graphene,代码行数:35,代码来源:build.py


示例16: printAttributes

def printAttributes(comp,chromo,G):
    #for n in nx.nodes_iter(G):
    for n in nx.nodes(G):
        intensity=G.node[n]['intensity']
        gene=G.node[n]['gene']
        print ("\tcluster->%i,%s" % (comp,intensity))
    return
开发者ID:eritema,项目名称:CISOGPY,代码行数:7,代码来源:autoCIS.py


示例17: fast_approximate_solution_two

def fast_approximate_solution_two(graph):
    """
    Given a graph, construct a solution greedily using approximation methods.
    Performs bad.
    """
    new_graph = nx.Graph()
    degrees = nx.degree_centrality(graph) 
    largest = argmax(degrees)
    new_graph.add_node(largest)
    while new_graph.number_of_edges() < graph.number_of_nodes() - 1:
        degrees = {n: count_uncovered_degree(graph, new_graph, n) for n in nx.nodes(graph)}
        neighbor_list = [nx.neighbors(graph, n) for n in new_graph.nodes()]
        neighbors = set()
        for lst in neighbor_list:
            neighbors = neighbors.union(lst)
        if not neighbors:
            break
        next_largest = argmax_in(degrees, neighbors, exceptions = new_graph.nodes())
        possible_edge_ends = [n for n in nx.neighbors(graph, next_largest) 
                              if graph.has_edge(n, next_largest) 
                              and n in new_graph.nodes()]
        new_graph.add_node(next_largest)
        edge_end = argmax_in(degrees, possible_edge_ends)
        new_graph.add_edge(edge_end, next_largest)

    return new_graph
开发者ID:calebwang,项目名称:mlst,代码行数:26,代码来源:mlst.py


示例18: calculate

def calculate(g, voltage):
    edges_num = nx.number_of_edges(g)
    # sort nodes in edges
    edges = [edge if edge[0] < edge[1] else (edge[1], edge[0])
             for edge in nx.edges(g)]

    a = np.zeros((edges_num, edges_num))
    b = np.zeros((edges_num, 1))
    i = 0
    # first law
    for node in [node for node in nx.nodes(g) if node != 0]:
        for neighbor in nx.all_neighbors(g, node):
            edge = tuple(sorted((node, neighbor)))
            a[i][edges.index(edge)] = 1 if neighbor < node else -1
        i += 1
    # second law
    cycles = nx.cycle_basis(g, 0)
    for cycle in cycles:
        for j in range(0, len(cycle)):
            node = cycle[j]
            next_node = cycle[(j + 1) % len(cycle)]
            edge = tuple(sorted((node, next_node)))
            resistance = g[node][next_node]['weight']
            a[i][edges.index(edge)] = resistance if node < next_node else -resistance
        if 0 in cycle:
            b[i] = voltage
        i += 1
    # solve
    x = np.linalg.solve(a, b)
    for (x1, x2), res in zip(edges, x):
        g[x1][x2]['current'] = res[0]
开发者ID:michalborzecki,项目名称:mownit2,代码行数:31,代码来源:main.py


示例19: getCoverageSets

 def getCoverageSets(self, graph):
     coverage_sets = []
     nodes = nx.nodes(graph)
     for node in nodes:
         coverage_set = self.getCoverageSet(graph, node)
         coverage_sets.append(coverage_set)
     return coverage_sets
开发者ID:Szop-Kradziej,项目名称:GIS_Dominating_Set,代码行数:7,代码来源:ClassicalSetCoverageAlgorithm.py


示例20: select_random_biome

    def select_random_biome(self, adj_list=list()):
        if adj_list:
            the_graph = self.neighbors_subgraph(adj_list)
        else:
            the_graph = self

        return random.choice(nx.nodes(the_graph))
开发者ID:LindaJeanne,项目名称:procgen_proto,代码行数:7,代码来源:biomegraph.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.nodes_iter函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.node_connectivity函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap