示例#1
0
    def test_dual_barabasi_albert(self, m1=1, m2=4, p=0.5):
        """
        Tests that the dual BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky shots

        """
        seed = 42
        repeats = 2

        while repeats:
            repeats -= 1

            # This should be BA with m = m1
            BA1 = barabasi_albert_graph(100, m1, seed)
            DBA1 = dual_barabasi_albert_graph(100, m1, m2, 1, seed)
            assert_equal(BA1.size(), DBA1.size())

            # This should be BA with m = m2
            BA2 = barabasi_albert_graph(100, m2, seed)
            DBA2 = dual_barabasi_albert_graph(100, m1, m2, 0, seed)
            assert_equal(BA2.size(), DBA2.size())

        # Testing exceptions
        dbag = dual_barabasi_albert_graph
        assert_raises(NetworkXError, dbag, m1, m1, m2, 0)
        assert_raises(NetworkXError, dbag, m2, m1, m2, 0)
        assert_raises(NetworkXError, dbag, 100, m1, m2, -0.5)
        assert_raises(NetworkXError, dbag, 100, m1, m2, 1.5)
示例#2
0
    def test_dual_barabasi_albert(self, m1=1, m2=4, p=0.5):
        """
        Tests that the dual BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky shots

        """
        seed = 42
        repeats = 2

        while repeats:
            repeats -= 1

            # This should be BA with m = m1
            BA1 = barabasi_albert_graph(100, m1, seed)
            DBA1 = dual_barabasi_albert_graph(100, m1, m2, 1, seed)
            assert BA1.size() == DBA1.size()

            # This should be BA with m = m2
            BA2 = barabasi_albert_graph(100, m2, seed)
            DBA2 = dual_barabasi_albert_graph(100, m1, m2, 0, seed)
            assert BA2.size() == DBA2.size()

        # Testing exceptions
        dbag = dual_barabasi_albert_graph
        pytest.raises(NetworkXError, dbag, m1, m1, m2, 0)
        pytest.raises(NetworkXError, dbag, m2, m1, m2, 0)
        pytest.raises(NetworkXError, dbag, 100, m1, m2, -0.5)
        pytest.raises(NetworkXError, dbag, 100, m1, m2, 1.5)
示例#3
0
    def smoke_test_random_graph(self):
        seed = 42
        G=gnp_random_graph(100,0.25,seed)
        G=binomial_graph(100,0.25,seed)
        G=erdos_renyi_graph(100,0.25,seed)
        G=fast_gnp_random_graph(100,0.25,seed)
        G=gnm_random_graph(100,20,seed)
        G=dense_gnm_random_graph(100,20,seed)

        G=watts_strogatz_graph(10,2,0.25,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=connected_watts_strogatz_graph(10,2,0.1,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=watts_strogatz_graph(10,4,0.25,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 20)

        G=newman_watts_strogatz_graph(10,2,0.0,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=newman_watts_strogatz_graph(10,4,0.25,seed)
        assert_equal(len(G), 10)
        assert_true(G.number_of_edges() >= 20)

        G=barabasi_albert_graph(100,1,seed)
        G=barabasi_albert_graph(100,3,seed)
        assert_equal(G.number_of_edges(),(97*3))

        G = extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert_equal(G.number_of_edges(), 99)
        G = extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert_equal(G.number_of_edges(), 97 * 3)
        G = extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert_equal(G.number_of_edges(), 99)
        G = extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert_greater(G.number_of_edges(), 100 * 3)
        assert_less(G.number_of_edges(), 100 * 4)

        G=extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert_greater(G.number_of_edges(), 100 * 2)
        assert_less(G.number_of_edges(), 100 * 4)

        G=powerlaw_cluster_graph(100,1,1.0,seed)
        G=powerlaw_cluster_graph(100,3,0.0,seed)
        assert_equal(G.number_of_edges(),(97*3))

        G=random_regular_graph(10,20,seed)

        assert_raises(NetworkXError, random_regular_graph, 3, 21)

        constructor=[(10,20,0.8),(20,40,0.8)]
        G=random_shell_graph(constructor,seed)

        G=random_lobster(10,0.1,0.5,seed)
示例#4
0
    def smoke_test_random_graph(self):
        seed = 42
        G=gnp_random_graph(100,0.25,seed)
        G=binomial_graph(100,0.25,seed)
        G=erdos_renyi_graph(100,0.25,seed)
        G=fast_gnp_random_graph(100,0.25,seed)
        G=gnm_random_graph(100,20,seed)
        G=dense_gnm_random_graph(100,20,seed)

        G=watts_strogatz_graph(10,2,0.25,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=connected_watts_strogatz_graph(10,2,0.1,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=watts_strogatz_graph(10,4,0.25,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 20)

        G=newman_watts_strogatz_graph(10,2,0.0,seed)
        assert_equal(len(G), 10)
        assert_equal(G.number_of_edges(), 10)

        G=newman_watts_strogatz_graph(10,4,0.25,seed)
        assert_equal(len(G), 10)
        assert_true(G.number_of_edges() >= 20)

        G=barabasi_albert_graph(100,1,seed)
        G=barabasi_albert_graph(100,3,seed)
        assert_equal(G.number_of_edges(),(97*3))

        G = extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert_equal(G.number_of_edges(), 99)
        G = extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert_equal(G.number_of_edges(), 97 * 3)
        G = extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert_equal(G.number_of_edges(), 99)
        G = extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert_greater(G.number_of_edges(), 100 * 3)
        assert_less(G.number_of_edges(), 100 * 4)

        G=extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert_greater(G.number_of_edges(), 100 * 2)
        assert_less(G.number_of_edges(), 100 * 4)

        G=powerlaw_cluster_graph(100,1,1.0,seed)
        G=powerlaw_cluster_graph(100,3,0.0,seed)
        assert_equal(G.number_of_edges(),(97*3))

        G=random_regular_graph(10,20,seed)

        assert_raises(NetworkXError, random_regular_graph, 3, 21)

        constructor=[(10,20,0.8),(20,40,0.8)]
        G=random_shell_graph(constructor,seed)

        G=random_lobster(10,0.1,0.5,seed)
def main():  # ランダムなトポロジを生成(Barabási-Albertモデルに従う)
    print("Requirement: 1 <= complexity < switchNum")
    switchNum = input("スイッチ数(switchNum): ")
    complexity = input("新しいノードから既存のノードに接続するエッジの数(complexity): ")
    # 入力値の妥当性を確認 (1 <= complexity < switchNum)
    if (type(switchNum) is not int) or (type(complexity) is not int) or (not 1 <= complexity < switchNum):
        print("数値以外が入力されたか、上記の制約を満たしていません")
        exit()

    # 指定数のスイッチとホストを生成し接続
    makeSwitch(switchNum)
    makeHostAndLink(switchNum)

    # Barabási-Albertモデルのグラフを生成
    G = barabasi_albert_graph(switchNum, complexity)
    print(G.edges())

    # 生成されたグラフに基づいてスイッチ間を接続
    makeLinks(G.edges())

    # グラフをpngで出力
    networkx.draw(G, with_labels=True)
    pngpath = "test/topo_image/ba_random_" + \
        str(switchNum) + "_" + str(complexity) + ".png"
    pyplot.savefig(pngpath)
    # pyplot.show()

    # ファイルに出力
    path = "test/ba_random_" + str(switchNum) + "_" + str(complexity) + ".conf"
    if os.path.exists(path):
        os.remove(path)
    with open(path, mode='w') as file:
        file.write('\n'.join(conf))
    print "\nDone."
def main():
    # デフォルト引数処理
    if sys.argv and len(sys.argv) == 3:
        switchNum = int(sys.argv[1])
        complexity = int(sys.argv[2])
    else:
        switchNum = 30
        complexity = 2
    # Barabási-Albertモデルのグラフを生成
    tmp = barabasi_albert_graph(switchNum, complexity)
    # ノード番号を1からに
    edges = []
    for edge in tmp.edges():
        e = list(edge)
        e[0] += 1
        e[1] += 1
        edges.append(tuple(e))
    sorted(edges, key=lambda e: (e[0], e[1]))
    print(edges)
    # edgesから無向グラフ作成
    G = networkx.Graph()
    G.add_edges_from(edges)
    # 外部出力
    if os.path.exists('.edges'):
        os.remove('.edges')
    with open('.edges', 'w') as f:
        for l in sorted(G.edges(), key=lambda e: (e[0], e[1])):
            f.write(str(l) + "\n")
示例#7
0
def main():
    # デフォルト引数処理
    if sys.argv and len(sys.argv) == 3:
        switchNum = int(sys.argv[1])
        complexity = int(sys.argv[2])
    else:
        switchNum = 30
        complexity = 2
    # Barabási-Albertモデルのグラフを生成
    tmp = barabasi_albert_graph(switchNum, complexity)
    # ノード番号を1からに
    edges = []
    for edge in tmp.edges():
        e = list(edge)
        e[0] += 1
        e[1] += 1
        edges.append(tuple(e))
    sorted(edges, key=lambda e: (e[0], e[1]))
    print(edges)
    # edgesから無向グラフ作成
    G = networkx.Graph()
    G.add_edges_from(edges)
    # 外部出力
    if os.path.exists('.edges'):
        os.remove('.edges')
    with open('.edges', 'w') as f:
        for l in sorted(G.edges(), key=lambda e: (e[0], e[1])):
            f.write(str(l) + "\n")
    # networkx.nx_agraph.view_pygraphviz(G, prog='dot')
    networkx.draw(G, prog="dot", with_labels=True)
    pngpath = ".topo_ba.png"
    pyplot.savefig(pngpath)
def main(arguments):
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('model',
                        help="Generative model for the random graph",
                        type=str)
    parser.add_argument('node_number', help="Number of nodes", type=int)
    parser.add_argument('-p',
                        '--params',
                        help="Model specific parameter for the graph",
                        type=float,
                        nargs='*')
    parser.add_argument('-s',
                        '--seed',
                        help="Seed for the RNG",
                        type=int,
                        default=42)
    args = parser.parse_args(arguments)

    if args.model == "gnp":
        p = args.params[0]
        g = gg.fast_gnp_random_graph(args.node_number, p, args.seed)
        for e in g.edges():
            print("{0} {1}".format(e[0], e[1]))

    if args.model == "gnm":
        m = args.params[0]
        g = gg.gnm_random_graph(args.node_number, m, args.seed)
        for e in g.edges():
            print("{0} {1}".format(e[0], e[1]))

    elif args.model == "ba":
        m = int(args.params[0])
        g = gg.barabasi_albert_graph(args.node_number, m, args.seed)
        for e in g.edges():
            print("{0} {1}".format(e[0], e[1]))

    elif args.model == "PL":  #random graph with power-law distribution
        kmin = args.params[0]
        exponent = args.params[1]
        kmax = np.sqrt(
            args.node_number) * kmin * (exponent - 1.0) / (exponent - 2.0)
        degree_vector = np.arange(kmin, kmax + 1)
        degree_distribution = degree_vector**(-exponent)
        degree_distribution /= np.sum(degree_distribution)
        degree_distribution = np.concatenate(
            (np.array([0] * int(kmin)), degree_distribution))
        cumulative_degree_distribution = np.array([
            np.sum(degree_distribution[0:i])
            for i in range(len(degree_distribution) + 1)
        ])
        #generate n expected degree from the dist
        u_vec = random(args.node_number)
        expected_degree_sequence = [
            np.searchsorted(cumulative_degree_distribution, u, side='right') -
            1 for u in u_vec
        ]
        output_edge_PL(expected_degree_sequence)
示例#9
0
    def generate_subgraph(self, n_nodes_in_subgraph, **kwargs):
        """
        Generate a subgraph with specified properties.

        Args
            - n_nodes_in_subgraph (int): number of nodes in each subgraph
        
        Return
            - G (networkx object): subgraph
        """

        subgraph_generator = kwargs.pop('subgraph_generator', 'path')

        if subgraph_generator == 'cycle':
            G = nx.cycle_graph(n_nodes_in_subgraph)
        elif subgraph_generator == 'path':
            G = nx.path_graph(n_nodes_in_subgraph)
        elif subgraph_generator == 'house':
            G = nx.house_graph()
        elif subgraph_generator == 'complete':
            G = nx.complete_graph(n_nodes_in_subgraph)
        elif subgraph_generator == 'star':
            G = nx.star_graph(n_nodes_in_subgraph)
        elif subgraph_generator == 'barabasi_albert':
            m = kwargs.get('m', 5)
            G = barabasi_albert_graph(n_nodes_in_subgraph,
                                      m,
                                      seed=config.RANDOM_SEED)
        elif subgraph_generator == 'extended_barabasi_albert':
            m = kwargs.get('m', 5)
            p = kwargs.get('p', 0.5)
            q = kwargs.get('q', 0)
            G = extended_barabasi_albert_graph(n_nodes_in_subgraph,
                                               m,
                                               p,
                                               q,
                                               seed=config.RANDOM_SEED)
        elif subgraph_generator == 'duplication_divergence_graph':
            p = kwargs.get('p', 0.5)
            G = duplication_divergence_graph(n_nodes_in_subgraph, p)
        else:
            raise Exception(
                'The subgraph generator you specified is not implemented.')
        return G
示例#10
0
    def generate_base_graph(self, **kwargs):
        """
        Generate the base graph.

        Return
            - G (networkx object): base graph
        """

        if self.base_graph_type == 'barabasi_albert':
            m = kwargs.get('m', 5)
            n = kwargs.get('n', 500)
            G = barabasi_albert_graph(n, m, seed=config.RANDOM_SEED)
        elif self.base_graph_type == 'duplication_divergence_graph':
            n = kwargs.get('n', 500)
            p = kwargs.get('p', 0.5)
            G = duplication_divergence_graph(n, p, seed=config.RANDOM_SEED)
        else:
            raise Exception('The base graph you specified is not implemented')
        return G
示例#11
0
def main():
    # Deal with arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'N', 
        action="store",
        type=int, 
        help='nodes in BA and DMS'
    )
    parser.add_argument(
        'n_samples', 
        action="store",
        nargs='?',
        default=10,
        type=int, 
        help='number of samples to run'
    )
    args = parser.parse_args()

    N = args.N
    SAMPLES = args.n_samples
    clustersBA = []
    clustersDMS = []
    for n in range(SAMPLES):
        print(str(n) + ' sample started')
        g = barabasi_albert_graph(N, 2)
        print('\tba created')
        cluster1 = nx_average_clustering_per_k(g)
        clustersBA.append(cluster1)
        print('\tba averaged')
        g = create_DMS(N)
        print('\tdms created')
        cluster2 = nx_average_clustering_per_k(g)
        clustersDMS.append(cluster2)
        gc.collect()
        print('\tdms averaged')

    ba = np.asarray(clustersBA)
    dms = np.asarray(clustersDMS)

    np.savetxt('./results/clustering_coefficient/'+ str(N) + '-ba.out', ba, delimiter=',')
    np.savetxt('./results/clustering_coefficient/'+ str(N) + '-dms.out', dms, delimiter=',')
示例#12
0
    def _createGraph(self):
        dlg = PropertyViewer(self.name, self.icon,
            Nodes=Integer(5, 1, 100, 1),
            Degree=Integer(2,1,100,1))

        nodes = []
        edges = []

        if dlg.exec_():
            values = dlg.values()
            n = values['Nodes']
            m = values['Degree']

            G = rnd.barabasi_albert_graph(n, m)

            nodes = layout.circularNodes(n, 25)

            for i in G.edges_iter():
                edges.append(i)

        return nodes, edges
示例#13
0
    def test_extended_barabasi_albert(self, m=2):
        """
        Tests that the extended BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky-shots

        """
        seed = 42
        repeats = 2
        BA_model = barabasi_albert_graph(100, m, seed)
        BA_model_edges = BA_model.number_of_edges()

        while repeats:
            repeats -= 1

            # This behaves just like BA, the number of edges must be the same
            G1 = extended_barabasi_albert_graph(100, m, 0, 0, seed)
            assert_equal(G1.size(), BA_model_edges)

            # More than twice more edges should have been added
            G1 = extended_barabasi_albert_graph(100, m, 0.8, 0, seed)
            assert_greater(G1.size(), BA_model_edges * 2)

            # Only edge rewiring, so the number of edges less than original
            G2 = extended_barabasi_albert_graph(100, m, 0, 0.8, seed)
            assert_equal(G2.size(), BA_model_edges)

            # Mixed scenario: less edges than G1 and more edges than G2
            G3 = extended_barabasi_albert_graph(100, m, 0.3, 0.3, seed)
            assert_greater(G3.size(), G2.size())
            assert_less(G3.size(), G1.size())

        # Testing exceptions
        ebag = extended_barabasi_albert_graph
        assert_raises(NetworkXError, ebag, m, m, 0, 0)
        assert_raises(NetworkXError, ebag, 1, 0.5, 0, 0)
        assert_raises(NetworkXError, ebag, 100, 2, 0.5, 0.5)
示例#14
0
    def test_extended_barabasi_albert(self, m=2):
        """
        Tests that the extended BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky-shots

        """
        seed = 42
        repeats = 2
        BA_model = barabasi_albert_graph(100, m, seed)
        BA_model_edges = BA_model.number_of_edges()

        while repeats:
            repeats -= 1

            # This behaves just like BA, the number of edges must be the same
            G1 = extended_barabasi_albert_graph(100, m, 0, 0, seed)
            assert_equal(G1.size(), BA_model_edges)

            # More than twice more edges should have been added
            G1 = extended_barabasi_albert_graph(100, m, 0.8, 0, seed)
            assert_greater(G1.size(), BA_model_edges * 2)

            # Only edge rewiring, so the number of edges less than original
            G2 = extended_barabasi_albert_graph(100, m, 0, 0.8, seed)
            assert_equal(G2.size(), BA_model_edges)

            # Mixed scenario: less edges than G1 and more edges than G2
            G3 = extended_barabasi_albert_graph(100, m, 0.3, 0.3, seed)
            assert_greater(G3.size(), G2.size())
            assert_less(G3.size(), G1.size())

        # Testing exceptions
        ebag = extended_barabasi_albert_graph
        assert_raises(NetworkXError, ebag, m, m, 0, 0)
        assert_raises(NetworkXError, ebag, 1, 0.5, 0, 0)
        assert_raises(NetworkXError, ebag, 100, 2, 0.5, 0.5)
def barabasi_albert_generator(args):
    return generators.barabasi_albert_graph(args.num_nodes, args.num_edges)
示例#16
0
    def smoke_test_random_graph(self):
        seed = 42
        G = gnp_random_graph(100, 0.25, seed)
        G = gnp_random_graph(100, 0.25, seed, directed=True)
        G = binomial_graph(100, 0.25, seed)
        G = erdos_renyi_graph(100, 0.25, seed)
        G = fast_gnp_random_graph(100, 0.25, seed)
        G = fast_gnp_random_graph(100, 0.25, seed, directed=True)
        G = gnm_random_graph(100, 20, seed)
        G = gnm_random_graph(100, 20, seed, directed=True)
        G = dense_gnm_random_graph(100, 20, seed)

        G = watts_strogatz_graph(10, 2, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10
        pytest.raises(NetworkXError, connected_watts_strogatz_graph, \
                      10, 2, 0.1, tries=0)

        G = watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 20

        G = newman_watts_strogatz_graph(10, 2, 0.0, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = newman_watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() >= 20

        G = barabasi_albert_graph(100, 1, seed)
        G = barabasi_albert_graph(100, 3, seed)
        assert G.number_of_edges() == (97 * 3)

        G = extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert G.number_of_edges() == 99
        G = extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert G.number_of_edges() == 97 * 3
        G = extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert G.number_of_edges() == 99
        G = extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert G.number_of_edges() > 100 * 3
        assert G.number_of_edges() < 100 * 4

        G = extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert G.number_of_edges() > 100 * 2
        assert G.number_of_edges() < 100 * 4

        G = powerlaw_cluster_graph(100, 1, 1.0, seed)
        G = powerlaw_cluster_graph(100, 3, 0.0, seed)
        assert G.number_of_edges() == (97 * 3)

        G = random_regular_graph(10, 20, seed)

        pytest.raises(NetworkXError, random_regular_graph, 3, 21)
        pytest.raises(NetworkXError, random_regular_graph, 33, 21)

        constructor = [(10, 20, 0.8), (20, 40, 0.8)]
        G = random_shell_graph(constructor, seed)

        G = random_lobster(10, 0.1, 0.5, seed)

        # difficult to find seed that requires few tries
        seq = random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
        G = random_powerlaw_tree(10, 3, seed=14, tries=1)
示例#17
0
 def _generate_graph(self, n):
   return barabasi_albert_graph(n, self._params['m'])
示例#18
0
    all_degrees = g.degree()  # list of (vertex, degree)
    for deg in all_degrees:
        deg_hist[deg[1]] += 1
    # average dist
    deg_dist = np.asarray(deg_hist) / g.number_of_nodes()
    return deg_dist


N = 100000
print('Networks of size ' + str(N) + '\n')
SAMPLES = 10
distsBA = []
distsDMS = []
for n in range(SAMPLES):
    print(str(n) + ' sample started')
    g = barabasi_albert_graph(N, 2)
    print('\tba created')
    dist1 = degree_distribution(g)
    distsBA.append(dist1)
    print('\tba averaged')
    g = create_DMS(N)
    print('\tdms created')
    dist2 = degree_distribution(g)
    distsDMS.append(dist2)
    print('\tdms averaged')
    gc.collect()

ba = np.asarray(distsBA)
dms = np.asarray(distsDMS)

degreesBA = []
示例#19
0
    else:
        max_index = int(max_index)

    max_value = Q[action, max_index]
    Q[current_state, action] = R[current_state, action] + gamma * max_value
    print('max_value', R[current_state, action] + gamma * max_value)
    if (np.max(Q) > 0):
        return (np.sum(Q / np.max(Q) * 100))
    else:
        return (0)


# First we generate a random graph holding a power law link distribution. This
# has the aim of keeping entropy sourced phenomena in mind.

Graph = barabasi_albert_graph(MATRIX_SIZE, int(MATRIX_SIZE / LINK_FRACTION))
pos = nx.spring_layout(Graph)
nx.draw_networkx_nodes(Graph, pos)
nx.draw_networkx_edges(Graph, pos)
nx.draw_networkx_labels(Graph, pos)
plt.show()

R = nx.adjacency_matrix(Graph).todense() - 1
Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))
points_list = [t for t in zip(*np.where(R == 0))]

for point in points_list:
    print(point)
    if point[1] == goal:
        R[point] = 100
    else:
示例#20
0
def generate_graph(n,p): 

	g = random_graphs.barabasi_albert_graph(n, p, seed=None) 
	a = nx.adjacency_matrix(g)
	
	return g, a
示例#21
0
def generate_random_graph(n, m):
    print "Building random graph"
    G = barabasi_albert_graph(n, m, 10)
    return G
示例#22
0
import graph_tool
import graph_tool.all as gt
from networkx.generators.random_graphs import barabasi_albert_graph
from networkx.algorithms.shortest_paths.generic import average_shortest_path_length
from networkx.readwrite.gml import write_gml
import numpy as np
import time

if __name__ == '__main__':
    g = barabasi_albert_graph(int(1e4), 1)
    start_t = time.process_time()
    average_shortest_path_length(g)
    print(time.process_time() - start_t)
    write_gml(g, './graph.gml')
    g = gt.load_graph('./graph.gml')
    start_t = time.process_time()
    all_sp = gt.shortest_distance(g)
    vertex_avgs = graph_tool.stats.vertex_average(g, all_sp)
    avg_path = np.sum(vertex_avgs[0]) / (g.num_vertices() - 1)
    print(time.process_time() - start_t)
    start_t = time.process_time()
    sum([sum(i) for i in gt.shortest_distance(g)
         ]) / (g.num_vertices()**2 - g.num_vertices())
    print(time.process_time() - start_t)
示例#23
0
    return gt.local_clustering(g).get_array()

def max_degree(g):
    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
        )]
    ))
示例#24
0
    def test_random_graph(self):
        seed = 42
        G = gnp_random_graph(100, 0.25, seed)
        G = gnp_random_graph(100, 0.25, seed, directed=True)
        G = binomial_graph(100, 0.25, seed)
        G = erdos_renyi_graph(100, 0.25, seed)
        G = fast_gnp_random_graph(100, 0.25, seed)
        G = fast_gnp_random_graph(100, 0.25, seed, directed=True)
        G = gnm_random_graph(100, 20, seed)
        G = gnm_random_graph(100, 20, seed, directed=True)
        G = dense_gnm_random_graph(100, 20, seed)

        G = watts_strogatz_graph(10, 2, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10
        pytest.raises(NetworkXError,
                      connected_watts_strogatz_graph,
                      10,
                      2,
                      0.1,
                      tries=0)

        G = watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 20

        G = newman_watts_strogatz_graph(10, 2, 0.0, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = newman_watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() >= 20

        G = barabasi_albert_graph(100, 1, seed)
        G = barabasi_albert_graph(100, 3, seed)
        assert G.number_of_edges() == (97 * 3)

        G = extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert G.number_of_edges() == 99
        G = extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert G.number_of_edges() == 97 * 3
        G = extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert G.number_of_edges() == 99
        G = extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert G.number_of_edges() > 100 * 3
        assert G.number_of_edges() < 100 * 4

        G = extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert G.number_of_edges() > 100 * 2
        assert G.number_of_edges() < 100 * 4

        G = powerlaw_cluster_graph(100, 1, 1.0, seed)
        G = powerlaw_cluster_graph(100, 3, 0.0, seed)
        assert G.number_of_edges() == (97 * 3)

        G = random_regular_graph(10, 20, seed)

        pytest.raises(NetworkXError, random_regular_graph, 3, 21)
        pytest.raises(NetworkXError, random_regular_graph, 33, 21)

        constructor = [(10, 20, 0.8), (20, 40, 0.8)]
        G = random_shell_graph(constructor, seed)

        def is_caterpillar(g):
            """
            A tree is a caterpillar iff all nodes of degree >=3 are surrounded
            by at most two nodes of degree two or greater.
            ref: http://mathworld.wolfram.com/CaterpillarGraph.html
            """
            deg_over_3 = [n for n in g if g.degree(n) >= 3]
            for n in deg_over_3:
                nbh_deg_over_2 = [
                    nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2
                ]
                if not len(nbh_deg_over_2) <= 2:
                    return False
            return True

        def is_lobster(g):
            """
            A tree is a lobster if it has the property that the removal of leaf
            nodes leaves a caterpillar graph (Gallian 2007)
            ref: http://mathworld.wolfram.com/LobsterGraph.html
            """
            non_leafs = [n for n in g if g.degree(n) > 1]
            return is_caterpillar(g.subgraph(non_leafs))

        G = random_lobster(10, 0.1, 0.5, seed)
        assert max([G.degree(n) for n in G.nodes()]) > 3
        assert is_lobster(G)
        pytest.raises(NetworkXError, random_lobster, 10, 0.1, 1, seed)
        pytest.raises(NetworkXError, random_lobster, 10, 1, 1, seed)
        pytest.raises(NetworkXError, random_lobster, 10, 1, 0.5, seed)

        # docstring says this should be a caterpillar
        G = random_lobster(10, 0.1, 0.0, seed)
        assert is_caterpillar(G)

        # difficult to find seed that requires few tries
        seq = random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
        G = random_powerlaw_tree(10, 3, seed=14, tries=1)
示例#25
0
from networkx.generators.random_graphs import barabasi_albert_graph
from networkx.generators.directed import scale_free_graph

if __name__ == "__main__":
    g = barabasi_albert_graph(300000, 1)
    #g = scale_free_graph(258000)
    with open("scale_free.txt", "w") as random_output:
        for v, neibdict in g.adjacency():
            first = True
            for w, attr in neibdict.items():
                if first:
                    random_output.write(str(w))
                    first = False
                else:
                    random_output.write(" " + str(w))
            random_output.write("\n")