Python networkx 模块,degree() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用networkx.degree()

项目:ride    作者:KyleBenson    | 项目源码 | 文件源码
def draw(self, label_nodes=False):
        """Draw the graph using matplotlib in a color-coordinated manner."""
        try:
            import matplotlib.pyplot as plt
            print 'Node colors: red=core, blue=major-building, green=distribution, yellow=minor-building, cyan=server,' \
                  ' magenta=host, black=floor-switch, white=rack-switch, white=cloud, green=gateway'
            # TODO: ignore building internals?
            colormap = {'c': 'r', 'b': 'b', 'd': 'g', 'm': 'y', 's': 'c', 'h': 'm', 'f': 'k', 'r': 'w', 'x': 'w', 'g': 'g'}
            node_colors = [colormap[node[0]] for node in self.topo.nodes()]
            # shell layout places nodes as a series of concentric circles
            positions = nx.shell_layout(self.topo, [self.core_nodes,
                                                    # sort the building routers by degree in attempt to get ones connected to each other next to each other
                                                    sorted(self.major_building_routers, key=lambda n: nx.degree(self.topo, n)) + self.distribution_routers + self.server_nodes,
                                                    self.hosts + self.minor_building_routers])
            # then do a spring layout, keeping the inner nodes fixed in positions
            positions = nx.spring_layout(self.topo, pos=positions, fixed=self.core_nodes + self.server_nodes + self.major_building_routers + self.distribution_routers)
            nx.draw(self.topo, node_color=node_colors, pos=positions, with_labels=label_nodes)
            plt.show()
        except ImportError:
            print "ERROR: couldn't draw graph as matplotlib.pyplot couldn't be imported!"
项目:taikutsu_blog_works    作者:hokekiyoo    | 项目源码 | 文件源码
def graph_visualize(G, args):
    import networkx as nx
    import numpy as np
    # ???????????????????????????
    pos = nx.spring_layout(G)
    # ?????? ????????????????????
    plt.figure()
    nx.draw_networkx(G, pos, with_labels=False, alpha=0.4,font_size=0.0,node_size=10) 
    plt.savefig(args.directory+"/graph/graph.png")
    nx.write_gml(G, args.directory+"/graph/graph.gml")
    # ??????
    plt.figure() 
    degree_sequence=sorted(nx.degree(G).values(),reverse=True) 
    dmax=max(degree_sequence) 
    dmin =min(degree_sequence)
    kukan=range(0,dmax+2) 
    hist, kukan=np.histogram(degree_sequence,kukan)
    plt.plot(hist,"o-")
    plt.xlabel('degree') 
    plt.ylabel('frequency')
    plt.grid()
    plt.savefig(args.directory+'/graph/degree_hist.png')
项目:analyse_website_dns    作者:mrcheng0910    | 项目源码 | 文件源码
def manage_data(domain_name):

    domain_pkts = get_data(domain_name)
    node_cname, node_ip, visit_total, edges, node_main = get_ip_cname(domain_pkts[0]['details'])
    for i in domain_pkts[0]['details']:
        for v in i['answers']:
            edges.append((v['domain_name'],v['dm_data']))

    DG = nx.DiGraph()
    DG.add_edges_from(edges)

    ass =  nx.degree_assortativity_coefficient(DG)
    nodes_count = len(node_cname)+len(node_ip)+len(node_main)
    print nodes_count
    edges_count = len(edges)
    average_degree = sum(nx.degree(DG).values())
    print domain_name,ass
    print nx.density(DG)
    return nodes_count,edges_count, ass,average_degree,nx.degree_histogram(DG)
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def degree_hist(_degree, filter_zeros=False):
    degree = list(_degree.values()) if type(_degree) is dict else _degree

    max_c = np.max(degree)
    d = np.arange(max_c+1)
    dc = np.bincount(degree, minlength=max_c+1)

    if len(d) == 0:
        return [], []

    if dc[0] > 0:
        lgg.debug('%d unconnected vertex' % dc[0])
    d = d[1:]
    dc = dc[1:]


    if filter_zeros is True:
        #d, dc = zip(*filter(lambda x:x[1] != 0, zip(d, dc)))
        nzv = (dc != 0)
        d = d[nzv]
        dc = dc[nzv]

    return d, dc
项目:ez-segway    作者:thanh-nguyen-dang    | 项目源码 | 文件源码
def draw(self):
        """Draw the topology"""
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            log.warning("matplotlib could not be found")
            return
        node_color = range(len(self.graph.nodes()))

        pos = nx.spring_layout(self.graph,iterations=200)
        nx.draw(self.graph,pos,node_color=node_color,
                node_size=[100*(nx.degree(self.graph,x)**1.25) for x in self.graph.nodes()],
                edge_color=['blue' for x,y,z in self.graph.edges(data=True)],
                edge_cmap=plt.cm.Blues,
                with_labels=True,
                cmap=plt.cm.Blues)
        plt.show()
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def calculate_degree(graph):
    print "\n\tCalculating node degree...\n"
    g = graph
    deg = nx.degree(g)
    nx.set_node_attributes(g, 'degree', deg)
    return g, deg
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def out_degree_centrality(G):
    """Compute the out-degree centrality for nodes.

    The out-degree centrality for a node v is the fraction of nodes its
    outgoing edges are connected to.

    Parameters
    ----------
    G : graph
        A NetworkX graph

    Returns
    -------
    nodes : dictionary
        Dictionary of nodes with out-degree centrality as values.

    See Also
    --------
    degree_centrality, in_degree_centrality

    Notes
    -----
    The degree centrality values are normalized by dividing by the maximum
    possible degree in a simple graph n-1 where n is the number of nodes in G.

    For multigraphs or graphs with self loops the maximum degree might
    be higher than n-1 and values of degree centrality greater than 1
    are possible.
    """
    if not G.is_directed():
        raise nx.NetworkXError( \
            "out_degree_centrality() not defined for undirected graphs.")
    centrality = {}
    s = 1.0 / (len(G) - 1.0)
    centrality = dict((n, d * s) for n, d in G.out_degree_iter())
    return centrality
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def ped_sort(file):
    """
        - Reorders a pedigree (dict) by the Kahn's Algorithm.

     """
    pedgraph = input_diGraph(inFile=file)
    print "\n\tApplying Kahn's Algorithm... "
    in_degree = {u: 0 for u in pedgraph}  # determine in-degree
    for u in pedgraph:  # of each node
        for v in pedgraph[u]:
            in_degree[v] += 1

    Q = deque()  # collect nodes with zero in-degree
    for u in in_degree:
        if in_degree[u] == 0:
            Q.appendleft(u)

    order_list = []  # list for order of nodes

    while Q:
        u = Q.pop()  # choose node of zero in-degree
        order_list.append(u)  # and 'remove' it from graph
        for v in pedgraph[u]:
            in_degree[v] -= 1
            if in_degree[v] == 0:
                Q.appendleft(v)

    if len(order_list) == len(pedgraph):
        return order_list
    else:  # if there is a cycle,
        print "Error: At least one cycle detected!\n"
        return []  # return an empty list
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def degree_histogram(pedgraph):
    """Return a list of the frequency of each degree value.

    Parameters
    ----------
    pedgraph : Networkx graph
       A graph

    Notes
    -----
    Note: the bins are width one, hence len(list) can be large
    (Order(number_of_edges))
    """
    degree_sequence = sorted(nx.degree(pedgraph).values(), reverse=True)  # degree sequence
    # print "Degree sequence", degree_sequence
    dmax = max(degree_sequence)

    plt.loglog(degree_sequence, 'b-', marker='o', markersize=5, markerfacecolor='#FF8C00', antialiased=True,
               color='#000000')
    plt.title("(out)Degree Rank Plot")
    plt.ylabel("(out)Degree")
    plt.xlabel("Rank")

    print "\t   >  Degree histogram plot created in ~/dgRankPlot.png"
    plt.savefig("dgRankPlot.png")
    #plt.show()
项目:tweetopo    作者:zthxxx    | 项目源码 | 文件源码
def __init__(self, edges, measure='pagerank'):
        '''
        Class for analysis graph
        :param edges: weighted_edges The edges must be given as 3-tuples like (u,v,weight)
        :param measure: what measure for analysis to filter,
                        must be one of  'degree' or 'pagerank' or 'clustering'
        '''
        self.measures = ['degree', 'pagerank', 'clustering']
        self.measure = measure
        self.ranks = {}
        self.G = nx.Graph()
        self.import_data(edges)
项目:tweetopo    作者:zthxxx    | 项目源码 | 文件源码
def get_degrees(self):
        degrees = dict(nx.degree(self.G))
        max_degree = max(degrees.values())
        return degrees, max_degree
项目:twitter-social-affiliation-network    作者:zacharykstine    | 项目源码 | 文件源码
def draw_graph(G):
    d = nx.degree(G)
    nx.draw_spectral(G, nodelist=d.keys(), node_size=[v * 100 for v in d.values()])
    plt.show()
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def degree_hist_to_list(d, dc):
    degree = np.repeat(np.round(d).astype(int), np.round(dc).astype(int))
    return degree
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def adj_to_degree(y):
    # @debug: dont' call nxG or do a native integration !

    # To convert normalized degrees to raw degrees
    #ba_c = {k:int(v*(len(ba_g)-1)) for k,v in ba_c.iteritems()}
    G = nxG(y)
    #degree = sorted(nx.degree(G).values(), reverse=True)

    #ba_c = nx.degree_centrality(G)
    return nx.degree(G)
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def log_binning(counter_dict,bin_count=35):
    max_x = np.log10(max(counter_dict.keys()))
    max_y = np.log10(max(counter_dict.values()))
    max_base = max([max_x,max_y])

    min_x = np.log10(min(drop_zeros(counter_dict.keys())))

    bins = np.logspace(min_x,max_base,num=bin_count)

    # Based off of: http://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy
    #bin_means_y = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0] / np.histogram(counter_dict.keys(),bins)[0])
    #bin_means_x = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0] / np.histogram(counter_dict.keys(),bins)[0])
    bin_means_y = np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0]
    bin_means_x = np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0]
    return bin_means_x,bin_means_y

#def plot_degree(y, title=None, noplot=False):
#    if len(y) > 6000:
#        return
#    G = nxG(y)
#    degree = sorted(nx.degree(G).values(), reverse=True)
#    if noplot:
#        return degree
#    #plt.plot(degree)
#    x = np.arange(1, y.shape[0] + 1)
#    fig = plt.figure()
#    plt.loglog(x, degree)
#    if title:
#        plt.title(title)
#    plt.draw()
#
#def plot_degree_(y, title=None):
#    if len(y) > 6000:
#        return
#    G = nxG(y)
#    degree = sorted(nx.degree(G).values(), reverse=True)
#    x = np.arange(1, y.shape[0] + 1)
#    plt.loglog(x, degree)
#    if title:
#        plt.title(title)
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def degree(self):
        g = self.getG()
        return nx.degree(g)
项目:Quadflor    作者:quadflor    | 项目源码 | 文件源码
def __init__(self, method='degree', analyzer=NltkNormalizer().split_and_normalize):
        self.analyze = analyzer
        self.method = method
        self.methods_on_digraph = {'hits', 'pagerank', 'katz'}
        self._get_scores = {'degree': nx.degree, 'betweenness': nx.betweenness_centrality,
                            'pagerank': nx.pagerank_scipy, 'hits': self._hits, 'closeness': nx.closeness_centrality,
                            'katz': nx.katz_centrality}[method]
        # Add a new value when a new vocabulary item is seen
        self.vocabulary = defaultdict()
        self.vocabulary.default_factory = self.vocabulary.__len__
项目:ez-segway    作者:thanh-nguyen-dang    | 项目源码 | 文件源码
def get_highest_degree_node(self):
        highest_degree_id = 0
        highest_degree = 0
        for n in self.graph.nodes():
            if self.graph.degree(n) > highest_degree:
                highest_degree = self.graph.degree(n)
                highest_degree_id = n
        return highest_degree_id, highest_degree
项目:HRG    作者:nddsg    | 项目源码 | 文件源码
def draw_degree_rank_plot(orig_g, mG):
    ori_degree_seq = sorted(nx.degree(orig_g).values(), reverse=True)  # degree sequence
    deg_seqs = []
    for newg in mG:
        deg_seqs.append(sorted(nx.degree(newg).values(), reverse=True))  # degree sequence
    df = pd.DataFrame(deg_seqs)

    plt.xscale('log')
    plt.yscale('log')
    plt.fill_between(df.columns, df.mean() - df.sem(), df.mean() + df.sem(), color='blue', alpha=0.2, label="se")
    h, = plt.plot(df.mean(), color='blue', aa=True, linewidth=4, ls='--', label="H*")
    orig, = plt.plot(ori_degree_seq, color='black', linewidth=4, ls='-', label="H")

    plt.title('Degree Distribution')
    plt.ylabel('Degree')
    plt.ylabel('Ordered Vertices')

    plt.tick_params(
        axis='x',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom='off',  # ticks along the bottom edge are off
        top='off',  # ticks along the top edge are off
        labelbottom='off')  # labels along the bottom edge are off

    plt.legend([orig, h], ['$H$', 'HRG $H^*$'], loc=3)
    # fig = plt.gcf()
    # fig.set_size_inches(5, 4, forward=True)
    plt.show()
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def directed_modularity_matrix(G, nodelist=None):
    """ INCLUDED FOR TESTING PURPOSES - Not implemented yet.

    Return the directed modularity matrix of G.
    The modularity matrix is the matrix B = A - <A>, where A is the adjacency
    matrix and <A> is the expected adjacency matrix, assuming that the graph
    is described by the configuration model.
    More specifically, the element B_ij of B is defined as
        B_ij = A_ij - k_i(out) k_j(in)/m
    where k_i(in) is the in degree of node i, and k_j(out) is the out degree
    of node j, with m the number of edges in the graph.
    Parameters
    ----------
    G : DiGraph
       A NetworkX DiGraph
    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().
    Returns
    -------
    B : Numpy matrix
      The modularity matrix of G.
    Notes
    -----
    NetworkX defines the element A_ij of the adjacency matrix as 1 if there
    is a link going from node i to node j. Leicht and Newman use the opposite
    definition. This explains the different expression for B_ij.
    See Also
    --------
    to_numpy_matrix
    adjacency_matrix
    laplacian_matrix
    modularity_matrix
    References
    ----------
    .. [1] E. A. Leicht, M. E. J. Newman,
       "Community structure in directed networks",
        Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
    """
    if nodelist is None:
        nodelist = G.nodes()
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, format='csr')
    k_in = A.sum(axis=0)
    k_out = A.sum(axis=1)
    m = G.number_of_edges()
    # Expected adjacency matrix
    X = k_out * k_in / m
    return A - X
项目:analyse_website_dns    作者:mrcheng0910    | 项目源码 | 文件源码
def main():
    domain_name = 'baidu.com'
    domain_pkts = get_data(domain_name)
    node_cname, node_ip, visit_total, edges, node_main = get_ip_cname(domain_pkts[0]['details'])
    for i in domain_pkts[0]['details']:
        for v in i['answers']:
            edges.append((v['domain_name'],v['dm_data']))

    DG = nx.DiGraph()
    DG.add_edges_from(edges)

    # ?????????IP?node
    for node in DG:
        if node in node_main and DG.successors(node) in node_ip:
            print node

    # ??cname???IP????
    for node in DG:
        if node in node_cname and DG.successors(node) not in node_cname:  # ???ip?????cname
            print "node",DG.out_degree(node),DG.in_degree(node),DG.degree(node)
    # ?cname???????
    # for node in DG:
    #     if node in node_cname and DG.predecessors(node) not in node_cname:
    #         print len(DG.predecessors(node))

    for node in DG:
        if node in  node_main:
            if len(DG.successors(node)) ==3:
                print node
                print DG.successors(node)
    # print sorted(nx.degree(DG).values())

    print nx.degree_assortativity_coefficient(DG)
    average_degree = sum(nx.degree(DG).values())/(len(node_cname)+len(node_ip)+len(node_main))
    print average_degree
    print len(node_cname)+len(node_ip)+len(node_main)
    print len(edges)
    print nx.degree_histogram(DG)
    # print nx.degree_centrality(DG)
    # print nx.in_degree_centrality(DG)
    # print nx.out_degree_centrality(DG)
    # print nx.closeness_centrality(DG)
    # print nx.load_centrality(DG)
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def plot_degree_2(P, logscale=False, colors=False, line=False, ax=None, title=None):
    """ Plot degree distribution for different configuration"""
    if ax is None:
        # Note: difference betwwen ax and plt method are the get_ and set_ suffix
        ax = plt.gca()

    x, y, yerr = P
    y = np.ma.array(y)
    for i, v in enumerate(y):
        if v == 0:
            y[i] = np.ma.masked
        else:
            break

    c = next(_colors) if colors else 'b'
    m = next(_markers) if colors else 'o'
    l = '--' if line else None

    if yerr is None:
        ax.scatter(x, y, c=c, marker=m)
        if line:
            ax.plot(x, y, c=c, marker=m, ls=l)
    else:
        ax.errorbar(x, y, yerr, c=c, fmt=m, ls=l)

    min_d, max_d = min(x), max(x)

    if logscale:
        ax.set_xscale('log'); ax.set_yscale('log')
        # Ensure that the ticks will be visbile (ie larger than in los step)
        #logspace = 10**np.arange(6)
        #lim =  np.searchsorted(logspace,min_d )
        #if lim == np.searchsorted(logspace,max_d ):
        #    min_d = logspace[lim-1]
        #    max_d = logspace[lim]
    if title:
        ax.set_title(title)

    ax.set_xlim((min_d, max_d+10))
    #ax.set_xlim(left=1)
    ax.set_ylim((.9,1e3))
    ax.set_xlabel('Degree'); ax.set_ylabel('Counts')

##########################
### Graph/Matrix Drawing
##########################