Beispiel #1
0
def test_complete_graphs():
    for n in range(5, 25, 5):
        G = nx.complete_graph(n)
        assert_equal(n - 1, nx.node_connectivity(G))
        assert_equal(n - 1, nx.node_connectivity(G.to_directed()))
        assert_equal(n - 1, nx.edge_connectivity(G))
        assert_equal(n - 1, nx.edge_connectivity(G.to_directed()))
def cohesiveness(g: nx.Graph, v):
    before = nx.node_connectivity(g)
    copy = g.copy()
    copy.remove_node(v)
    after = nx.node_connectivity(copy)
    # print(f"before: {before} after: {after}, cohesiveness of node {v}: {before - after}")
    return before - after
Beispiel #3
0
def test_complete_graphs():
    for n in range(5, 25, 5):
        G = nx.complete_graph(n)
        assert_equal(n-1, nx.node_connectivity(G))
        assert_equal(n-1, nx.node_connectivity(G.to_directed()))
        assert_equal(n-1, nx.edge_connectivity(G))
        assert_equal(n-1, nx.edge_connectivity(G.to_directed()))
def test_brandes_erlebach():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
                      (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
                      (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        assert_equal(3,
                     local_edge_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(3,
                     nx.edge_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2,
                     local_node_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2,
                     nx.node_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(
            2,
            nx.edge_connectivity(G, **kwargs),  # node 5 has degree 2
            msg=msg.format(flow_func.__name__))
        assert_equal(2,
                     nx.node_connectivity(G, **kwargs),
                     msg=msg.format(flow_func.__name__))
 def test_all_pairs_connectivity(self, nodelist=[0, 1, 2, 3]):
     G = nx.Graph()
     nodes = [0, 1, 2, 3]
     G.add_path(nodes)
     A = numpy.zeros((4, 4), dtype=int)
     for u, v in itertools.combinations(nodes, 2):
         A[u][v] = nx.node_connectivity(G, u, v)
         A[v][u] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity_matrix(G)
     assert_equal(A, C)
Beispiel #6
0
 def test_all_pairs_connectivity(self, nodelist=[0, 1, 2, 3]):
     G = nx.Graph()
     nodes = [0, 1, 2, 3]
     G.add_path(nodes)
     A = numpy.zeros((4, 4), dtype=int)
     for u, v in itertools.combinations(nodes, 2):
         A[u][v] = nx.node_connectivity(G, u, v)
         A[v][u] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity_matrix(G)
     assert_equal(A, C)
Beispiel #7
0
def print_robustness(): #What is the smallest number of nodes that can be removed from this graph in order to disconnect it?
    # 1) whole graph:
    nx.node_connectivity(G) #1 - too small, When higher - it is good
    nx.minimum_node_cut(G) #{'Чкаловская'}
    nx.edge_connectivity(G) # 1
    nx.minimum_edge_cut(G) #{('Марьино', 'Чкаловская')}
    # 2) concrete path
    nx.node_connectivity(G, 'Киевская', 'Чкаловская') #2 - better
    nx.minimum_node_cut(G, 'Киевская', 'Чкаловская') #{'Курская', 'Сретенский бульвар'}
    nx.edge_connectivity(G, 'Киевская', 'Чкаловская') #2 - better
    nx.minimum_edge_cut(G, 'Киевская', 'Чкаловская') #{('Курская', 'Чкаловская'), ('Сретенский бульвар', 'Чкаловская')}
Beispiel #8
0
def calculate_node_connectivity(graph, graph_type):
    if graph_type == 'subscription':
        user_nodes = set(n for n, d in graph.nodes(data=True)
                         if d.get('bipartite') == 0)
        results = [
            nx.node_connectivity(graph, s=start, t=end)
            for start, end in combinations(user_nodes, 2)
        ]
        return min(results) if results else 0

    elif graph_type == 'mention':
        return nx.node_connectivity(graph)
Beispiel #9
0
def test_brandes_erlebach():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(2,3),(2,6),(3,4),
                    (3,6),(4,6),(4,7),(5,7),(6,8),(6,9),(7,8),
                    (7,10),(8,11),(9,10),(9,11),(10,11)])
    assert_equal(3,nx.local_edge_connectivity(G,1,11))
    assert_equal(3,nx.edge_connectivity(G,1,11))
    assert_equal(2,nx.local_node_connectivity(G,1,11))
    assert_equal(2,nx.node_connectivity(G,1,11))
    assert_equal(2,nx.edge_connectivity(G)) # node 5 has degree 2
    assert_equal(2,nx.node_connectivity(G))
def test_complete_graphs():
    for n in range(5, 20, 5):
        for flow_func in flow_funcs:
            G = nx.complete_graph(n)
            errmsg = f"Assertion failed in function: {flow_func.__name__}"
            assert n - 1 == nx.node_connectivity(G,
                                                 flow_func=flow_func), errmsg
            assert n - 1 == nx.node_connectivity(G.to_directed(),
                                                 flow_func=flow_func), errmsg
            assert n - 1 == nx.edge_connectivity(G,
                                                 flow_func=flow_func), errmsg
            assert n - 1 == nx.edge_connectivity(G.to_directed(),
                                                 flow_func=flow_func), errmsg
Beispiel #11
0
def test_brandes_erlebach():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
                      (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
                      (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
    assert_equal(3, nx.local_edge_connectivity(G, 1, 11))
    assert_equal(3, nx.edge_connectivity(G, 1, 11))
    assert_equal(2, nx.local_node_connectivity(G, 1, 11))
    assert_equal(2, nx.node_connectivity(G, 1, 11))
    assert_equal(2, nx.edge_connectivity(G))  # node 5 has degree 2
    assert_equal(2, nx.node_connectivity(G))
def test_complete_graphs():
    for n in range(5, 20, 5):
        for flow_func in flow_funcs:
            G = nx.complete_graph(n)
            assert_equal(n-1, nx.node_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.node_connectivity(G.to_directed(),
                                                   flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.edge_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.edge_connectivity(G.to_directed(),
                                                   flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
def test_complete_graphs():
    for n in range(5, 20, 5):
        for flow_func in flow_funcs:
            G = nx.complete_graph(n)
            assert_equal(n-1, nx.node_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.node_connectivity(G.to_directed(),
                                                   flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.edge_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(n-1, nx.edge_connectivity(G.to_directed(),
                                                   flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for flow_func in flow_funcs:
        for i in range(3):
            G = next(Ggen)
            errmsg = f"Assertion failed in function: {flow_func.__name__}"
            assert nx.node_connectivity(G, flow_func=flow_func) == 1, errmsg
def test_empty_graphs():
    for k in range(5, 25, 5):
        G = nx.empty_graph(k)
        for flow_func in flow_funcs:
            errmsg = f"Assertion failed in function: {flow_func.__name__}"
            assert 0 == nx.node_connectivity(G, flow_func=flow_func), errmsg
            assert 0 == nx.edge_connectivity(G, flow_func=flow_func), errmsg
Beispiel #16
0
    def updateGraphStats(self, graph):

        origgraph = graph
        if nx.is_connected(graph):
            random = 0
        else:
            connectedcomp = nx.connected_component_subgraphs(graph)
            graph = max(connectedcomp)

        if len(graph) > 1:
            pathlength = nx.average_shortest_path_length(graph)
        else:
            pathlength = 0

        # print graph.nodes(), len(graph), nx.is_connected(graph)

        stats = {
            "radius": nx.radius(graph),
            "density": nx.density(graph),
            "nodecount": len(graph.nodes()),
            "center": nx.center(graph),
            "avgcluscoeff": nx.average_clustering(graph),
            "nodeconnectivity": nx.node_connectivity(graph),
            "components": nx.number_connected_components(graph),
            "avgpathlength": pathlength
        }

        # print "updated graph stats", stats
        return stats
Beispiel #17
0
def test_node_cutset_random_graphs():
    for i in range(5):
        G = nx.fast_gnp_random_graph(50,0.2)
        cutset = nx.minimum_node_cut(G)
        assert_equal(nx.node_connectivity(G), len(cutset))
        G.remove_nodes_from(cutset)
        assert_false(nx.is_connected(G))
Beispiel #18
0
def k_connectedness(G):
    # returns (is_conn,k_connectivity) where is_conn (boolean) says if the network is fully connected,
    # if is_conn = False, then k_connectivity is the k value for the GIANT COMPONENT, not the whole thing, whole thing is obviously 0 because it's not connected.
    is_conn = is_connected(G)  # is_conn is boolean

    if is_conn == True:
        k_connectivity = nx.node_connectivity(G)
        return (is_conn, k_connectivity)
    else:
        Gcc = sorted(nx.connected_component_subgraphs(G),
                     key=len,
                     reverse=True)
        G0 = Gcc[0]  # Got the giant component
        k_connectivity = nx.node_connectivity(G0)

    return (is_conn, k_connectivity)
Beispiel #19
0
def q12(G_sc):
    src_nodes = q10(G_sc)
    dst_node = execute_q11()[0]
    return sum([
        nx.node_connectivity(G_sc, src_node, dst_node)
        for src_node in src_nodes
    ])
    def updateGraphStats(self, graph):

        origgraph = graph
        if nx.is_connected(graph):
            random = 0
        else:
            connectedcomp = nx.connected_component_subgraphs(graph)
            graph = max(connectedcomp)

        if len(graph) > 1:
            pathlength = nx.average_shortest_path_length(graph)
        else:
            pathlength = 0

        # print graph.nodes(), len(graph), nx.is_connected(graph)

        stats = {
            "radius": nx.radius(graph),
            "density": nx.density(graph),
            "nodecount": len(graph.nodes()),
            "center": nx.center(graph),
            "avgcluscoeff": nx.average_clustering(graph),
            "nodeconnectivity": nx.node_connectivity(graph),
            "components": nx.number_connected_components(graph),
            "avgpathlength": pathlength
        }

        # print "updated graph stats", stats
        return stats
def main():
    done = [
        'dfn_58.graphml', 'colt_153.graphml', 'gts_ce_149.graphml',
        'intellifiber_73.graphml', 'triangle.graphml'
    ]
    networks = ['abilene_11.graphml']

    for net_file in networks:
        node_connectivity = {}
        edge_connectivity = {}
        graphml_network = nx.read_graphml(net_file, node_type=int)
        for u in graphml_network.nodes():
            u_id = f'pop{u}'
            node_connectivity[u_id] = {}
            edge_connectivity[u_id] = {}
            for v in graphml_network.nodes():
                v_id = f'pop{v}'
                if u_id != v_id:
                    node_connectivity[u_id][v_id] = nx.node_connectivity(
                        graphml_network, s=u, t=v)
                    edge_connectivity[u_id][v_id] = nx.edge_connectivity(
                        graphml_network, s=u, t=v)

        os.makedirs('connectivity/', exist_ok=True)
        with open(f'connectivity/{net_file}_node_con.json', 'w') as fp:
            json.dump(node_connectivity, fp)
        with open(f'connectivity/{net_file}_edge_con.json', 'w') as fp:
            json.dump(edge_connectivity, fp)
def test_tutte():
    G = nx.tutte_graph()
    for flow_func in flow_funcs:
        assert_equal(3, nx.node_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
def test_tutte():
    G = nx.tutte_graph()
    for flow_func in flow_funcs:
        assert_equal(3, nx.node_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
def test_graph_from_pr_2053():
    G = nx.Graph()
    G.add_edges_from([
        ("A", "B"),
        ("A", "D"),
        ("A", "F"),
        ("A", "G"),
        ("B", "C"),
        ("B", "D"),
        ("B", "G"),
        ("C", "D"),
        ("C", "E"),
        ("C", "Z"),
        ("D", "E"),
        ("D", "F"),
        ("E", "F"),
        ("E", "Z"),
        ("F", "Z"),
        ("G", "Z"),
    ])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        errmsg = f"Assertion failed in function: {flow_func.__name__}"
        # edge disjoint paths
        edge_paths = list(nx.edge_disjoint_paths(G, "A", "Z", **kwargs))
        assert are_edge_disjoint_paths(G, edge_paths), errmsg
        assert nx.edge_connectivity(G, "A", "Z") == len(edge_paths), errmsg
        # node disjoint paths
        node_paths = list(nx.node_disjoint_paths(G, "A", "Z", **kwargs))
        assert are_node_disjoint_paths(G, node_paths), errmsg
        assert nx.node_connectivity(G, "A", "Z") == len(node_paths), errmsg
def find_which_nodes_and_edges_to_remove(G, n1, n2):
    a = nx.node_connectivity(G, n1, n2)
    b = nx.minimum_node_cut(G, n1, n2)
    c = nx.edge_connectivity(G, n1, n2)
    d = nx.minimum_edge_cut(G, n1, n2)
    print(a, b, c, d)
    return (a, b, c, d)
Beispiel #26
0
def embed_metrics_connectivity(graph, metrics, g, namefield):
    connectivity = dict()
    print('connectivity_edge')
    connectivity['connectivity_edge'] = networkx.edge_connectivity(g)
    print('connectivity_node')
    connectivity['connectivity_node'] = networkx.node_connectivity(g)
    return connectivity
Beispiel #27
0
def test_petersen():
    G = nx.petersen_graph()
    for flow_func in flow_funcs:
        assert 3 == nx.node_connectivity(G, flow_func=flow_func), msg.format(
            flow_func.__name__)
        assert 3 == nx.edge_connectivity(G, flow_func=flow_func), msg.format(
            flow_func.__name__)
Beispiel #28
0
def test_graph_from_pr_2053():
    G = nx.Graph()
    G.add_edges_from([
        ('A', 'B'), ('A', 'D'), ('A', 'F'), ('A', 'G'),
        ('B', 'C'), ('B', 'D'), ('B', 'G'), ('C', 'D'),
        ('C', 'E'), ('C', 'Z'), ('D', 'E'), ('D', 'F'),
        ('E', 'F'), ('E', 'Z'), ('F', 'Z'), ('G', 'Z')])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge disjoint paths
        edge_paths = list(nx.edge_disjoint_paths(G, 'A', 'Z', **kwargs))
        assert_true(are_edge_disjoint_paths(G, edge_paths), msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.edge_connectivity(G, 'A', 'Z'),
            len(edge_paths),
            msg=msg.format(flow_func.__name__),
        )
        # node disjoint paths
        node_paths = list(nx.node_disjoint_paths(G, 'A', 'Z', **kwargs))
        assert_true(are_node_disjoint_paths(G, node_paths), msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.node_connectivity(G, 'A', 'Z'),
            len(node_paths),
            msg=msg.format(flow_func.__name__),
        )
Beispiel #29
0
def test_octahedral():
    G = nx.octahedral_graph()
    for flow_func in flow_funcs:
        assert 4 == nx.node_connectivity(G, flow_func=flow_func), msg.format(
            flow_func.__name__)
        assert 4 == nx.edge_connectivity(G, flow_func=flow_func), msg.format(
            flow_func.__name__)
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for flow_func in flow_funcs:
        for i in range(3):
            G = next(Ggen)
            assert_equal(nx.node_connectivity(G, flow_func=flow_func), 1,
                         msg=msg.format(flow_func.__name__))
def test_icosahedral():
    G=nx.icosahedral_graph()
    for flow_func in flow_funcs:
        assert_equal(5, nx.node_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(5, nx.edge_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
def draw_graph(nodes, edges, graphs_dir, default_lang='all'):
    lang_graph = nx.MultiDiGraph()
    lang_graph.add_nodes_from(nodes)
    for edge in edges:
        if edges[edge] == 0:
            lang_graph.add_edge(edge[0], edge[1])
        else:
            lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge]))

    # print graph info in stdout
    # degree centrality
    print('-----------------\n\n')
    print(default_lang)
    print(nx.info(lang_graph))
    try:
        # When ties are associated to some positive aspects such as friendship or collaboration,
        #  indegree is often interpreted as a form of popularity, and outdegree as gregariousness.
        DC = nx.degree_centrality(lang_graph)
        max_dc = max(DC.values())
        max_dc_list = [item for item in DC.items() if item[1] == max_dc]
    except ZeroDivisionError:
        max_dc_list = []
    # https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8
    print('maxdc', str(max_dc_list), sep=': ')
    # assortativity coef
    AC = nx.degree_assortativity_coefficient(lang_graph)
    print('AC', str(AC), sep=': ')
    # connectivity
    print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph))
    print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph))
    print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph))
    print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph))
    print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph))
    print("число вершинной связности: ", nx.node_connectivity(lang_graph))
    print("число рёберной связности: ", nx.edge_connectivity(lang_graph))
    # other info
    print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph))
    print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(),
                                              key=itemgetter(1), reverse=True))
    # best for small graphs, and our graphs are pretty small
    print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True))

    plt.figure(figsize=(16.0, 9.0), dpi=80)
    plt.axis('off')
    pos = graphviz_layout(lang_graph)
    nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True)
    nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green')
    nx.draw_networkx_edge_labels(lang_graph, pos, edges)

    # saving file to draw it with dot-graphviz
    # changing overall graph view, default is top-bottom
    lang_graph.graph['graph'] = {'rankdir': 'LR'}
    # marking with blue nodes with maximum degree centrality
    for max_dc_node in max_dc_list:
        lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue'
    write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot'))

    # plt.show()
    plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100)
    plt.close()
Beispiel #33
0
def test_get_new_maze(set_seed, iteration):
    # generate a few mazes and check them for consistency
    local_seed = random.randint(1, 2**31 - 1) * iteration
    maze_str = mg.get_new_maze(8, 16, nfood=15, seed=local_seed)
    maze = mg.str_to_maze(maze_str)
    height, width = maze.shape
    # check that the returned maze has all the pacmen
    for pacman in (b'0', b'1', b'2', b'3'):
        assert np.any(maze == pacman)
        # now that we now we have a pacman, check that we have it only once
        # and remove it by putting an empty space instead
        row, col = np.nonzero(maze == pacman)
        assert len(row) == 1
        assert len(col) == 1
        maze[row, col] = mg.E

    # check that we have in total twice nfood in the maze
    assert (maze == mg.F).sum() == 15 * 2
    # remove the food for computing dead ends and chambers
    maze[maze == mg.F] = mg.E

    # check that the returned maze is center-mirror symmetric
    left_maze = np.flipud(np.fliplr(maze[:, width // 2:]))
    assert np.all(left_maze == maze[:, :width // 2])

    # check that we don't have any dead ends
    # no node in the graph should have only one connection
    graph = mg.walls_to_graph(maze)
    for node, degree in graph.degree():
        assert degree > 1

    # now check that we don't have chambers, i.e. the connectivity of the
    # graph is > 1
    assert nx.node_connectivity(graph) > 1
Beispiel #34
0
def get_graph_property(fn, i):
    doc = [
        'Order', 'Index', 'Mean degree', 'Number of connected components',
        'Variance of degree', 'Min degree', 'Max degree', 'Radius', 'Diameter',
        'Density', 'Connectivity', 'Mean eccentricity',
        'Variance of eccentricity', 'Min eccentricity', 'Max eccentricity',
        'Mean clustering', 'Variance of clustering', 'Min clustering',
        'Max clustering'
    ]

    with open('graphproperties_%d.csv' % i, 'ab') as fout:
        fout.write('\t'.join(doc) + '\n')
        if 'sw' in fn: return
        if '10000' not in fn: return

        print 'Processing', fn
        with gzip.open('../graphs/' + fn) as f:
            jdata = json.load(f)

        index = jdata['index']
        del jdata['index']
        order = jdata['order']
        del jdata['order']
        mean_degree = jdata['mean_degree']
        del jdata['mean_degree']
        var_degree = jdata['var_degree']
        del jdata['var_degree']
        del jdata['meanSharedNeighbors']

        G = json_graph.node_link_graph(jdata)
        min_degree = np.min(G.degree().values())
        max_degree = np.max(G.degree().values())

        ecc = nx.eccentricity(G)
        min_ecc = np.min(ecc.values())
        max_ecc = np.max(ecc.values())
        mean_ecc = np.mean(ecc.values())
        var_ecc = np.var(ecc.values())
        radius = min_ecc
        diameter = max_ecc
        #center = nx.center(G)
        #periphery = nx.periphery(G)
        density = nx.density(G)
        connectivity = nx.node_connectivity(G)

        clustering = nx.clustering(G)
        min_clust = np.min(clustering.values())
        max_clust = np.max(clustering.values())
        mean_clust = np.mean(clustering.values())
        var_clust = np.var(clustering.values())
        num_cc = nx.number_connected_components(G)

        row = [
            order, index, mean_degree, num_cc, var_degree, min_degree,
            max_degree, radius, diameter, density, connectivity, mean_ecc,
            var_ecc, min_ecc, max_ecc, mean_clust, var_clust, min_clust,
            max_clust
        ]

        fout.write('\t'.join(map(str, row)) + '\n')
def test_icosahedral():
    G=nx.icosahedral_graph()
    for flow_func in flow_funcs:
        assert_equal(5, nx.node_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(5, nx.edge_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
Beispiel #36
0
def test_graph_from_pr_2053():
    G = nx.Graph()
    G.add_edges_from([
        ('A', 'B'), ('A', 'D'), ('A', 'F'), ('A', 'G'), ('B', 'C'), ('B', 'D'),
        ('B', 'G'), ('C', 'D'), ('C', 'E'), ('C', 'Z'), ('D', 'E'), ('D', 'F'),
        ('E', 'F'), ('E', 'Z'), ('F', 'Z'), ('G', 'Z')
    ])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge disjoint paths
        edge_paths = list(nx.edge_disjoint_paths(G, 'A', 'Z', **kwargs))
        assert_true(are_edge_disjoint_paths(G, edge_paths),
                    msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.edge_connectivity(G, 'A', 'Z'),
            len(edge_paths),
            msg=msg.format(flow_func.__name__),
        )
        # node disjoint paths
        node_paths = list(nx.node_disjoint_paths(G, 'A', 'Z', **kwargs))
        assert_true(are_node_disjoint_paths(G, node_paths),
                    msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.node_connectivity(G, 'A', 'Z'),
            len(node_paths),
            msg=msg.format(flow_func.__name__),
        )
Beispiel #37
0
def test_node_cutset_random_graphs():
    for i in range(5):
        G = nx.fast_gnp_random_graph(50, 0.2)
        cutset = nx.minimum_node_cut(G)
        assert_equal(nx.node_connectivity(G), len(cutset))
        G.remove_nodes_from(cutset)
        assert_false(nx.is_connected(G))
Beispiel #38
0
def test_not_connected():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    for flow_func in flow_funcs:
        assert nx.node_connectivity(G) == 0, msg.format(flow_func.__name__)
        assert nx.edge_connectivity(G) == 0, msg.format(flow_func.__name__)
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for flow_func in flow_funcs:
        for i in range(3):
            G = next(Ggen)
            assert_equal(nx.node_connectivity(G, flow_func=flow_func), 1,
                         msg=msg.format(flow_func.__name__))
def generate_KRegularKConnectedRandomGraph(N, k, f):
    # k-regular k-connected random graph (done)
    done = False
    while not done:
        G = nx.random_regular_graph(k, N)
        done = len(list(nx.connected_components(G))) == 1 and nx.node_connectivity(G) >= 2*f+1
    return G
def test_empty_graphs():
    for k in range(5, 25, 5):
        G = nx.empty_graph(k)
        for flow_func in flow_funcs:
            assert_equal(0, nx.node_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(0, nx.edge_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
Beispiel #42
0
def _check_connectivity(G):
    result = nx.k_components(G)
    for k, components in result.items():
        if k < 3:
            continue
        for component in components:
            C = G.subgraph(component)
            assert_true(nx.node_connectivity(C) >= k)
def test_empty_graphs():
    for k in range(5, 25, 5):
        G = nx.empty_graph(k)
        for flow_func in flow_funcs:
            assert_equal(0, nx.node_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(0, nx.edge_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
Beispiel #44
0
def _check_connectivity(G, k_components):
    for k, components in k_components.items():
        if k < 3:
            continue
        # check that k-components have node connectivity >= k.
        for component in components:
            C = G.subgraph(component)
            K = nx.node_connectivity(C)
            assert_greater_equal(K, k)
def test_not_connected():
    G = nx.Graph()
    G.add_path([1, 2, 3])
    G.add_path([4, 5])
    for flow_func in flow_funcs:
        assert_equal(nx.node_connectivity(G), 0,
                     msg=msg.format(flow_func.__name__))
        assert_equal(nx.edge_connectivity(G), 0,
                     msg=msg.format(flow_func.__name__))
Beispiel #46
0
def _check_separating_sets(G):
    for Gc in nx.connected_component_subgraphs(G):
        if len(Gc) < 3:
            continue
        for cut in nx.all_node_cuts(Gc):
            assert_equal(nx.node_connectivity(Gc), len(cut))
            H = Gc.copy()
            H.remove_nodes_from(cut)
            assert_false(nx.is_connected(H))
Beispiel #47
0
 def test_all_pairs_connectivity_nbunch(self):
     G = nx.complete_graph(5)
     nbunch = [0, 2, 3]
     A = {n: {} for n in nbunch}
     for u, v in itertools.combinations(nbunch, 2):
         A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity(G, nbunch=nbunch)
     assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                  sorted((k, sorted(v)) for k, v in C.items()))
Beispiel #48
0
def _check_connectivity(G):
    result = nx.k_components(G)
    for k, components in result.items():
        if k < 3:
            continue
        for component in components:
            C = G.subgraph(component)
            K = nx.node_connectivity(C)
            assert_greater_equal(K, k)
Beispiel #49
0
def test_white_harary_2():
    # Figure 8 white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.add_edge(0,4)
    # kappa <= lambda <= delta
    assert_equal(3, min(nx.core_number(G).values()))
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(1, nx.edge_connectivity(G))
 def test_all_pairs_connectivity_nbunch_iter(self):
     G = nx.complete_graph(5)
     nbunch = [0, 2, 3]
     A = dict.fromkeys(nbunch, dict())
     for u, v in itertools.combinations(nbunch, 2):
         A[u][v] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity(G, nbunch=iter(nbunch))
     assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                  sorted((k, sorted(v)) for k, v in C.items()))
Beispiel #51
0
def test_alternative_flow_functions():
    graph_funcs = [graph_example_1, nx.davis_southern_women_graph]
    for graph_func in graph_funcs:
        G = graph_func()
        for flow_func in flow_funcs:
            for cut in nx.all_node_cuts(G, flow_func=flow_func):
                assert_equal(nx.node_connectivity(G), len(cut))
                H = G.copy()
                H.remove_nodes_from(cut)
                assert_false(nx.is_connected(H))
 def test_all_pairs_connectivity_directed(self):
     G = nx.DiGraph()
     nodes = [0, 1, 2, 3]
     G.add_path(nodes)
     A = dict.fromkeys(G, dict())
     for u, v in itertools.permutations(nodes, 2):
         A[u][v] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity(G)
     assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                  sorted((k, sorted(v)) for k, v in C.items()))
Beispiel #53
0
 def test_all_pairs_connectivity(self):
     G = nx.Graph()
     nodes = [0, 1, 2, 3]
     nx.add_path(G, nodes)
     A = {n: {} for n in G}
     for u, v in itertools.combinations(nodes,2):
         A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
     C = nx.all_pairs_node_connectivity(G)
     assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                  sorted((k, sorted(v)) for k, v in C.items()))
def test_node_cutset_random_graphs():
    for i in range(5):
        G = nx.fast_gnp_random_graph(50,0.2)
        if not nx.is_connected(G):
            ccs = iter(nx.connected_components(G))
            start = next(ccs)[0]
            G.add_edges_from( (start,c[0]) for c in ccs )
        cutset = nx.minimum_node_cut(G)
        assert_equal(nx.node_connectivity(G), len(cutset))
        G.remove_nodes_from(cutset)
        assert_false(nx.is_connected(G))
def create_3(nodes, edges):
    conn = 1
    loop_count = 0

    while conn < 3 and loop_count < 1000:
        G = nx.gnm_random_graph(nodes, edges)
        conn = nx.node_connectivity(G)

        loop_count = loop_count + 1

    return G
Beispiel #56
0
def _check_separating_sets(G):
    for cc in nx.connected_components(G):
        if len(cc) < 3:
            continue
        Gc = G.subgraph(cc)
        node_conn = nx.node_connectivity(Gc)
        all_cuts = nx.all_node_cuts(Gc)
        # Only test a limited number of cut sets to reduce test time.
        for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST):
            assert_equal(node_conn, len(cut))
            assert_false(nx.is_connected(nx.restricted_view(G, cut, [])))
Beispiel #57
0
def test_alternative_flow_functions():
    graphs = [nx.grid_2d_graph(4, 4),
              nx.cycle_graph(5)]
    for G in graphs:
        node_conn = nx.node_connectivity(G)
        for flow_func in flow_funcs:
            all_cuts = nx.all_node_cuts(G, flow_func=flow_func)
            # Only test a limited number of cut sets to reduce test time.
            for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST):
                assert_equal(node_conn, len(cut))
                assert_false(nx.is_connected(nx.restricted_view(G, cut, [])))
def test_brandes_erlebach():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
                      (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
                      (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        assert_equal(3, local_edge_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(3, nx.edge_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, local_node_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, nx.node_connectivity(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, nx.edge_connectivity(G, **kwargs), # node 5 has degree 2
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, nx.node_connectivity(G, **kwargs),
                     msg=msg.format(flow_func.__name__))
Beispiel #59
0
def test_node_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_node_cut(G, flow_func=flow_func)
            assert_equal(nx.node_connectivity(G), len(cutset), msg=msg.format(flow_func.__name__))
            G.remove_nodes_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__))
Beispiel #60
0
def test_white_harary_1():
    # Figure 1b white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (vertex connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(3, nx.edge_connectivity(G))