コード例 #1
0
ファイル: utils.py プロジェクト: robertour/miller-knowles
def network_structure_calculations(sn):
    g = sn.g

    _transitivity = transitivity(g)
    _average_clustering = average_clustering(g)   
    size_biggest_component = -1
    connected_components = 0
    ave_short_path_biggest = -1
    
    for sg in nx.connected_component_subgraphs(g, False):
        connected_components += 1
        if len(sg) > size_biggest_component:
            size_biggest_component = len(sg)
            ave_short_path_biggest = average_shortest_path_length(sg)
            
    return (_transitivity,_average_clustering,
            connected_components, size_biggest_component,
            ave_short_path_biggest)
コード例 #2
0
ファイル: gstats.py プロジェクト: damons/DeepRank
def runWith(fname) :
  print(fname)
  gm=dr.GraphMaker()
  gm.load(fname)
  # dpr=gm.pagerank()
  dg=gm.graph()
  #for x in dg: print('VERT::', x)

  print('nodes:', dg.number_of_nodes())
  print('edges:', dg.number_of_edges())

  comps=nx.strongly_connected_components(dg)

  print('strongly connected components:',len(list(comps)))

  c = max(nx.strongly_connected_components(dg), key=len)
  mg=dg.subgraph(c)

  print('attracting components:', co.number_attracting_components(dg))
  print('number_weakly_connected_components:',co.number_weakly_connected_components(dg))

  print('Transitivity:',cl.transitivity(dg))

  return

  e=dm.eccentricity(mg)

  dprint('ecc:', e)

  cent=dm.center(mg,e=e)
  print('CENTER',cent)

  p=dm.periphery(mg,e=e)

  print('perif:', len(list(e)))

  #dprint('perif:', e)

  print('diameter:', dm.diameter(nx.Graph(mg)))
  print('radius:', dm.radius(nx.Graph(mg)))

  g = nx.Graph(dg)
  print('omega:', omega(g))
  print('sigma:', sigma(g))
コード例 #3
0
def random_attack2(graph, nodes_number, iteration_removals):
    # lista onde estão os valores de clusterização da rede depois da remoção dos nos
    after_removals = []
    lenght_range = int((nodes_number - iteration_removals)/iteration_removals)
    # retorna um set, com os nos que representam o maior componente conexo da rede
    # print('largest cc: {}'.format(largest_cc))
    for _ in tqdm(range(lenght_range)):
        # se o tamanho do maior componente conexo por menor que o número de nos que quero remover, sair do loop
        largest_cc = max(networkx.connected_components(graph), key=len)
        print(len(largest_cc))
        if len(largest_cc) < iteration_removals:
            break
        removals_set = set(random.sample(largest_cc, iteration_removals))
        # print('remocoes: {}'.format(removals_set))
        largest_cc = largest_cc - removals_set
        # remove iterations_removals do maior componente conexo da rede
        graph.remove_nodes_from(removals_set)
        after_removals.append(nx_cluster.transitivity(graph))
        # after_removals.append(np.mean(list(nx_cluster.transitivity(graph).values())))
    return after_removals
コード例 #4
0
def ii_two_core_test(C, ii_key):
    if core.core_number(C)[ii_key] == 2:
        return (1)
    else:
        return (0)


ii_two_core_test = ii_two_core_test(C, ii_key)
#print(ii_two_core_test)

# [9] Transitivity
# Def : the proportion of all triads that exhibit closure in the network
#   Outputs a float representing 3 (triangles / triads).

transitivity = transitivity.transitivity(C)

# [10] Diameter

# Def : The diameter is the maximum eccentricity.
#   The eccentricity of a node v is the maximum distance from v to all other nodes in G.

diameter = diameter.diameter(C)

# ______________________________________________________________________________

# How to display the network. pylab.show() is necessary if not in the interactive
#   mode. Enter into interactive mode by typing ipython -pylab in the cmd.

options = {
    'node_color': 'grey',
コード例 #5
0
 def getGlobalClusteringCoefficient(self) -> float:
     """
     """
     return transitivity(self.graph)
コード例 #6
0
ファイル: gt_metrics.py プロジェクト: gh0stwin/crc-project
    return gt_stats.vertex_hist(g, 'total')[1][-2]
    
def page_rank(g):
    # return gt_stats.vertex_hist(g, gt.pagerank(g))
    return gt.pagerank(g).get_array()

def variance(g):
    degree_hist = gt_stats.vertex_hist(g, 'total')[0] / g.num_vertices()
    second_m = np.sum(degree_hist * (np.arange(len(degree_hist)) ** 2))
    return second_m - avg_degree(g) ** 2

if __name__ == '__main__':
    nx_g = barabasi_albert_graph(int(1e3), 2)
    nx_apl = average_shortest_path_length(nx_g)
    nx_ad = 2 * nx_g.number_of_edges() / nx_g.number_of_nodes()
    nx_gcc = transitivity(nx_g)
    nx_lcc = average_clustering(nx_g)
    nx_md = len(degree_histogram(nx_g)) - 1
    nx_drogc = max(connected_component_subgraphs(nx_g), key=len).number_of_nodes() / nx_g.number_of_nodes()
    second_m = np.sum(np.array(degree_histogram(nx_g)) * (np.arange(len(degree_histogram(nx_g))) ** 2))
    nx_v = math.sqrt(second_m - nx_ad ** 2)
    nx_ap = degree_pearson_correlation_coefficient(nx_g)
    nx_aknn = np.flip(np.array(
        [it[1] for it in sorted(
            average_degree_connectivity(nx_g).items(), reverse=True
        )]
    ))

    nx_dh = np.array(degree_histogram(nx_g)) / nx_g.number_of_nodes()
    nx_cdh = np.flip(np.flip(
        (np.array(degree_histogram(nx_g)) / nx_g.number_of_nodes())
コード例 #7
0
def compute_directed_graph_metrics(G):
    assert type(G) is nx.DiGraph

    n_edges = len(G.edges)

    # in & out degree stats
    in_degrees = np.array([n for _, n in G.in_degree()])
    out_degrees = np.array([n for _, n in G.out_degree()])

    in_degrees_k_freq = np.unique(in_degrees, return_counts=True)[1]
    out_degrees_k_freq = np.unique(out_degrees, return_counts=True)[1]

    out_in_degrees_corr = numeric_attribute_correlation(
        G, dict(G.out_degree), dict(G.in_degree))

    # dyad metrics
    dyad_freq = dyadic_census(G)
    dyad_metrics = compute_dyad_metrics(dyad_freq)

    # reciprocity
    reciprocity = None
    if n_edges > 0:
        # based on networkx definition
        reciprocity = 2 * dyad_freq["2"] / (dyad_freq["1"] +
                                            2 * dyad_freq["2"])

    # clustering
    global_clustering = transitivity(G)
    local_clustering_mean = average_clustering(G)

    # fraction of connected node pairs (any path len)
    f_connected_node_pairs = fraction_of_connected_node_pairs(G)

    # centralization
    cent_metrics = centralization_metrics(G, prefix="_di")

    metrics = {
        "n_edges_di":
        len(G.edges),
        "density_di":
        density(G),
        "reciprocity":
        reciprocity,
        # in_degree
        "in_degrees_mean":
        safe(np.mean, in_degrees),
        "in_degrees_var":
        safe(np.var, in_degrees),
        "in_degrees_hidx":
        safe(h_index, in_degrees),
        "in_degrees_gini":
        safe(gini, in_degrees + eps),
        "in_degrees_f0":
        safe(np.mean, (in_degrees == 0)),
        "in_degrees_pk_ent":
        entropy(in_degrees_k_freq),
        "in_degrees_pk_gini":
        gini(in_degrees_k_freq),
        # out_degree
        "out_degrees_mean":
        safe(np.mean, out_degrees),
        "out_degrees_var":
        safe(np.var, out_degrees),
        "out_degrees_hidx":
        safe(h_index, out_degrees),
        "out_degrees_gini":
        safe(gini, out_degrees + eps),
        "out_degrees_f0":
        safe(np.mean, (out_degrees == 0)),
        "out_degrees_pk_ent":
        entropy(out_degrees_k_freq),
        "out_degrees_pk_gini":
        gini(out_degrees_k_freq),
        # degree assortativity
        "out_in_degrees_corr":
        out_in_degrees_corr,
        # dyad metric
        **dyad_metrics,
        # fraction of connected node pairs with path of any length
        "f_connected_node_pairs_di":
        f_connected_node_pairs,
        # clustering coefficients
        "global_clustering_di":
        global_clustering,
        "local_clustering_mean_di":
        local_clustering_mean,
        # centralization
        **cent_metrics
    }

    return metrics
コード例 #8
0
def compute_undirected_graph_metrics(G):
    assert type(G) is nx.Graph

    # degrees stats
    degrees = np.array([i for _, i in G.degree])
    degrees_k_freq = np.unique(degrees, return_counts=True)[1]
    degrees_corr = numeric_attribute_correlation(G, dict(G.degree),
                                                 dict(G.degree))

    # clustering
    global_clustering = transitivity(G)
    local_clustering_mean = average_clustering(G)

    # fraction of connected node pairs (any path len)
    f_connected_node_pairs = fraction_of_connected_node_pairs(G)

    # centralization
    cent_metrics = centralization_metrics(G, prefix="_ud")

    # modularity
    modularity_metrics = compute_modularity_metrics(G)

    # largest CC
    CC1_nodes = max(connected_components(G), key=len)
    CC1 = G.subgraph(CC1_nodes).copy()
    f_CC1_nodes = len(CC1) / len(G)

    # algebraic_connectivity of the largest CC
    algebraic_connectivity_CC1 = None
    if len(CC1) > 2:
        try:
            algebraic_connectivity_CC1 = algebraic_connectivity(CC1, seed=0)
        except:
            algebraic_connectivity_CC1 = None

    # connected components
    CC = connected_components(G)
    CC_sizes = np.array([len(cc_i) for cc_i in CC])

    CC_metrics = {}
    for k in CC_k_thresholds:
        CC_metrics[f"n_CC_{k}"] = np.sum(CC_sizes >= k)

    # k-core
    k_core_metrics = {}
    G_core_number = core_number(G)

    for k in k_core_ks:
        k_core_subgraph = k_core(G, k=k, core_number=G_core_number)
        k_core_metrics[f"core_{k}_n_nodes"] = len(k_core_subgraph.nodes)
        k_core_metrics[f"core_{k}_n_edges"] = len(k_core_subgraph.edges)
        k_core_metrics[f"core_{k}_density"] = density(k_core_subgraph)
        k_core_metrics[f"core_{k}_n_CC"] = len(
            list(connected_components(k_core_subgraph)))

    # k-truss
    k_truss_metrics = {}

    for k in k_truss_ks:
        k_truss_subgraph = k_truss(G, k=k)
        k_truss_metrics[f"truss_{k}_n_nodes"] = len(k_truss_subgraph.nodes)
        k_truss_metrics[f"truss_{k}_n_edges"] = len(k_truss_subgraph.edges)
        k_truss_metrics[f"truss_{k}_density"] = density(k_truss_subgraph)
        k_truss_metrics[f"truss_{k}_n_CC"] = len(
            list(connected_components(k_truss_subgraph)))

    metrics = {
        "n_edges_ud":
        len(G.edges()),
        "density_ud":
        density(G),
        # degree stats
        "degrees_mean":
        safe(np.mean, degrees),
        "degrees_var":
        safe(np.var, degrees),
        "degrees_hidx":
        safe(h_index, degrees),
        "degrees_gini":
        safe(gini, degrees + eps),
        "degrees_f0":
        safe(np.mean, (degrees == 0)),
        "degrees_corr":
        degrees_corr,
        "degrees_pk_ent":
        entropy(degrees_k_freq),
        "degrees_pk_gini":
        gini(degrees_k_freq),
        # fraction of connected node pairs with path of any length
        "f_connected_node_pairs_ud":
        f_connected_node_pairs,
        # clustering coefficients
        "global_clustering_ud":
        global_clustering,
        "local_clustering_mean_ud":
        local_clustering_mean,
        # centralization
        **cent_metrics,
        # modularity
        **modularity_metrics,
        # fraction of nodes in the largest CC
        "f_CC1_nodes":
        f_CC1_nodes,
        # algebraic connectivity of the largest CC
        "algebraic_connectivity_CC1":
        algebraic_connectivity_CC1,
        # connected components
        **CC_metrics,
        # k-core
        **k_core_metrics,
        # k-truss
        **k_truss_metrics
    }

    return metrics
コード例 #9
0
graph_nx = networkx.waxman_graph(20)
graph_ig = igraph.Graph(len(graph_nx), list(zip(*list(zip(*networkx.to_edgelist(graph_nx)))[:2])))
import numpy as np
import networkx.algorithms.cluster as nx_cluster
cluster_nx = np.mean(list(nx_cluster.clustering(graph_nx).values()))
cluster_nx
nx_cluster.clustering(graph_nx).values()
graph_nx = networkx.waxman_graph(100)  
nx_cluster.clustering(graph_nx).values()
cluster_nx = np.mean(list(nx_cluster.clustering(graph_nx).values()))
cluster_nx
graph_ig = igraph.Graph(len(graph_nx), list(zip(*list(zip(*networkx.to_edgelist(graph_nx)))[:2])))
graph_ig.transitivity_avglocal_undirected()
graph_ig.transitivity_undirected()
graph_ig.transitivity_local_undirected()
cluster_ig = np.mean(graph_ig.transitivity_local_undirected())
cluster_ig
np.mean(graph_ig.transitivity_local_undirected())
graph_ig.transitivity_local_undirected()
cluster_ig = graph_ig.transitivity_local_undirected()
cluster_ig
np.nan_to_num(cluster_ig)
cluster_ig
cluster_ig = np.nan_to_num(cluster_ig)
cluster_ig
np.mean(cluster_ig)
nx_cluster.transitivity(graph_nx)
graph_ig.transitivity_avglocal_undirected()
graph_ig.transitivity_undirected()