Ejemplo n.º 1
0
def test_graph2vec():
    """
    Test the Graph2Vec embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = Graph2Vec()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.dimensions

    graphs = []

    for _ in range(50):
        graph = nx.newman_watts_strogatz_graph(50, 5, 0.3)
        nx.set_node_attributes(graph, {j: str(j)
                                       for j in range(50)}, "feature")
        graphs.append(graph)

    model = Graph2Vec(attributed=True)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray
Ejemplo n.º 2
0
def test_label_propagation():
    """
    Test Label Propagation procedure.
    """
    graph = nx.newman_watts_strogatz_graph(50, 5, 0.3)

    model = LabelPropagation()

    model.fit(graph)
    memberships = model.get_memberships()

    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    graph = nx.newman_watts_strogatz_graph(150, 5, 0.3)

    model = LabelPropagation()

    model.fit(graph)
    memberships = model.get_memberships()

    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict
Ejemplo n.º 3
0
def test_gl2vec():
    """
    Test the GL2Vec embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = GL2Vec()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray

    graphs = [nx.newman_watts_strogatz_graph(150, 5, 0.3) for _ in range(100)]

    model = GL2Vec(dimensions=16)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray
Ejemplo n.º 4
0
def test_fgsd():
    """
    Test the FGSD embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = FGSD()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.hist_bins
    assert type(embedding) == np.ndarray

    graphs = [nx.newman_watts_strogatz_graph(150, 5, 0.3) for _ in range(100)]

    model = FGSD(hist_bins=8)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.hist_bins
    assert type(embedding) == np.ndarray
def test_ldp():
    """
    Test the LDP embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = LDP(bins=8)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == 5 * model.bins
    assert type(embedding) == np.ndarray

    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(1000)]

    model = LDP(bins=128)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == 5 * model.bins
    assert type(embedding) == np.ndarray
def generateNetwork(N,cnType,weighted):
    # Input:
    #   N - number of nodes
    #   cnType  - network type (i.e. scale-free, small-world, Erdos-Renyi random graph)
    #   weighted - weighted or unweighted network
    # Output:
    #   G - a network with random generated topology acoording with the input parameters

    if (cnType == "scale-free"):
        G = nx.powerlaw_cluster_graph(N, 5, 0.3)
        while (nx.is_connected(G) == False):
            G = nx.powerlaw_cluster_graph(N, 5, 0.3)
    if (cnType == "small-world"):
        G = nx.newman_watts_strogatz_graph(N, 6, 0.6)
        while (nx.is_connected(G) == False):
            G = nx.newman_watts_strogatz_graph(N, 6, 0.6)
    if (cnType == "Erdos-Renyi"):
        G = nx.fast_gnp_random_graph(N, 0.01)
        while (nx.is_connected(G) == False):
            G = nx.fast_gnp_random_graph(N, 0.01)

    if (weighted):
        G = generateWeightedNetwork(G)
    else:
        G = generateUnweightedNetwork(G)

    return G
Ejemplo n.º 7
0
def test_netlsd():
    """
    Test the NetLSD embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = NetLSD()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.scale_steps
    assert type(embedding) == np.ndarray

    graphs = [nx.newman_watts_strogatz_graph(500, 5, 0.3) for _ in range(100)]

    model = NetLSD()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == model.scale_steps
    assert type(embedding) == np.ndarray
def test_egonet_splitter():
    """
    Test the Ego Net splitter procedure.
    """
    graph = nx.newman_watts_strogatz_graph(100, 5, 0.3)

    model = EgoNetSplitter()

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    graph = nx.newman_watts_strogatz_graph(150, 5, 0.3)

    model = EgoNetSplitter()

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict
def test_bane():
    """
    Testing the BANE node embedding.
    """
    graph = nx.newman_watts_strogatz_graph(250, 10, 0.2)

    features = np.random.uniform(0, 1, (250, 256))
    model = BANE()
    model.fit(graph, features)
    embedding = model.get_embedding()

    assert embedding.shape[0] == graph.number_of_nodes()
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray

    graph = nx.newman_watts_strogatz_graph(150, 10, 0.2)

    features = np.random.uniform(0, 1, (150, 256))
    model = BANE(dimensions=8)
    model.fit(graph, features)
    embedding = model.get_embedding()

    assert embedding.shape[0] == graph.number_of_nodes()
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray
Ejemplo n.º 10
0
def test_feather_graph():
    """
    Test the graph level FEATHER embedding.
    """
    graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]

    model = FeatherGraph()

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == 4 * model.order * model.eval_points
    assert type(embedding) == np.ndarray

    graphs = [nx.newman_watts_strogatz_graph(150, 5, 0.3) for _ in range(100)]

    model = FeatherGraph(order=3)

    model.fit(graphs)
    embedding = model.get_embedding()

    assert embedding.shape[0] == len(graphs)
    assert embedding.shape[1] == 4 * model.order * model.eval_points
    assert type(embedding) == np.ndarray
def test_egonet_splitter():
    """
    Test the Ego Net splitter procedure.
    """
    graph = nx.newman_watts_strogatz_graph(100, 5, 0.3)

    model = EgoNetSplitter()

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    graph = nx.newman_watts_strogatz_graph(150, 5, 0.3)

    model = EgoNetSplitter()

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    # Test weighted graph
    graph = nx.les_miserables_graph()
    graph = nx.convert_node_labels_to_integers(graph)
    model = EgoNetSplitter(weight='weight')
    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    # Force unweighted
    graph = nx.les_miserables_graph()
    graph = nx.convert_node_labels_to_integers(graph)
    model = EgoNetSplitter(weight=None)
    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict
Ejemplo n.º 12
0
def sym_bar_like_network(nodes_per_half=7, seed_a=1, seed_b=2):
    """Symmetrical bar bell like network"""
    a = nx.newman_watts_strogatz_graph(nodes_per_half, 4, 0.1, seed=seed_a)
    b = nx.newman_watts_strogatz_graph(nodes_per_half, 4, 0.1, seed=seed_b)
    G = nx.compose(
        a, nx.convert_node_labels_to_integers(b, first_label=nodes_per_half))
    G.add_edge(nodes_per_half - 1, nodes_per_half)
    # nx.draw_kamada_kawai(G)
    # plt.show()
    return G
def test_mnmf():
    """
    Test the MNMF procedure.
    """
    graph = nx.newman_watts_strogatz_graph(100, 5, 0.3)

    model = MNMF()

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    embedding = model.get_embedding()

    assert embedding.shape[0] == graph.number_of_nodes()
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray

    centers = model.get_cluster_centers()

    assert centers.shape[0] == model.clusters
    assert centers.shape[1] == model.dimensions
    assert type(centers) == np.ndarray

    graph = nx.newman_watts_strogatz_graph(200, 5, 0.3)

    model = MNMF(dimensions=8)

    model.fit(graph)
    memberships = model.get_memberships()
    
    indices = [k for k, v in memberships.items()].sort()
    nodes = [node for node in graph.nodes()].sort()

    assert graph.number_of_nodes() == len(memberships)
    assert indices == nodes
    assert type(memberships) == dict

    embedding = model.get_embedding()

    assert embedding.shape[0] == graph.number_of_nodes()
    assert embedding.shape[1] == model.dimensions
    assert type(embedding) == np.ndarray

    centers = model.get_cluster_centers()

    assert centers.shape[0] == model.clusters
    assert centers.shape[1] == model.dimensions
    assert type(centers) == np.ndarray
Ejemplo n.º 14
0
    def test_watts_strogatz_big_k(self):
        # Test to make sure than n <= k
        pytest.raises(nx.NetworkXError, nx.watts_strogatz_graph, 10, 11, 0.25)
        pytest.raises(nx.NetworkXError, nx.newman_watts_strogatz_graph, 10, 11,
                      0.25)

        # could create an infinite loop, now doesn't
        # infinite loop used to occur when a node has degree n-1 and needs to rewire
        nx.watts_strogatz_graph(10, 9, 0.25, seed=0)
        nx.newman_watts_strogatz_graph(10, 9, 0.5, seed=0)

        # Test k==n scenario
        nx.watts_strogatz_graph(10, 10, 0.25, seed=0)
        nx.newman_watts_strogatz_graph(10, 10, 0.25, seed=0)
Ejemplo n.º 15
0
def get_graph(objects, properties):
    graph_type = properties['graph_type']
    n = len(objects)-1
    if 'num_nodes_to_attach' in properties.keys():
        k = properties['num_nodes_to_attach']
    else:
        k = 3
    r = properties['connection_probability']

    tries = 0
    while(True):
        if graph_type == 'random':
            x = nx.fast_gnp_random_graph(n,r)
        elif graph_type == 'erdos_renyi_graph':
            x = nx.erdos_renyi_graph(n,r)
        elif graph_type == 'watts_strogatz_graph':
            x = nx.watts_strogatz_graph(n, k, r)
        elif graph_type == 'newman_watts_strogatz_graph':
            x = nx.newman_watts_strogatz_graph(n, k, r)
        elif graph_type == 'barabasi_albert_graph':
            x = nx.barabasi_albert_graph(n, k, r)
        elif graph_type == 'powerlaw_cluster_graph':
            x = nx.powerlaw_cluster_graph(n, k, r)
        elif graph_type == 'cycle_graph':
            x = nx.cycle_graph(n)
        else: ##Star by default
            x = nx.star_graph(len(objects)-1)
        tries += 1
        cc_conn = nx.connected_components(x)
        if len(cc_conn) == 1 or tries > 5: 
            ##best effort to create a connected graph!
            break
    return x, cc_conn
def small_world_graph(n, k, p, seed=None):
    '''
    n: number of node
    k: number of nearest neighbors in a ring topology
    p: probability of adding a new edge for each edge
    '''
    return nx.newman_watts_strogatz_graph(n, k, p)
Ejemplo n.º 17
0
def make_network(cores, number_of_neurons, netsize, connect_break):
    out_list = []
    test_net = nx.newman_watts_strogatz_graph(1000, netsize, 0)
    factor = 5

    for nn in test_net.nodes():
        if np.min(np.abs(cores - nn)) < 15:
            for i in range(factor):
                rand_core = cores[int(np.round(np.random.random() * 6))]
                test_net.add_edge(nn, np.random.randint(0, 1000))
    for ed in test_net.edges():
        if np.random.random() > connect_break:
            continue
        if np.abs(ed[0] - ed[1]) > 20 and np.abs(ed[0] - ed[1]) < 700:
            rng = np.random.choice([-1, 0, 0, 1])
        elif np.abs(ed[0] - ed[1]) > 700:
            rng = 1000
        else:
            rng = np.random.choice([0, 0, 0, 0, 0])
        if rng == 0:
            out_list.append(ed)
            out_list.append(ed[::-1])
        elif rng == 1:
            out_list.append(ed)
        elif rng == -1:
            out_list.append(ed[::-1])
        else:
            pass
    return out_list
def main():
    G = nx.complete_graph(10)
    #完全グラフ
    G2 = nx.barbell_graph(10, 10)
    #ようわからん
    G3 = nx.watts_strogatz_graph(100, 15, 0.1)
    #small world graph
    #watts_strogatz_graph(n,k,p) n: number of node, k:nearest neoghbors,
    G4 = nx.complete_bipartite_graph(3, 3)
    #完全二部グラフ
    G5 = nx.scale_free_graph(50)
    G6 = nx.newman_watts_strogatz_graph(100, 10, 0.05)
    G7 = nx.binomial_graph(10, 0.2)
    #    z=[int(random.gammavariate(alpha=9.0,beta=2.0)) for i in range(6)]
    #    G8 = nx.configuration_model(z)
    #    aseq = [1,2,1]
    #    bseq = [2,1,1]
    #    G8 = nx.configuration_model(aseq,bseq)
    G8 = bp.random_graph(5, 5, 0.5)

    pos = nx.spring_layout(G6)
    #    pos = nx.circular_layout(G5)
    plt.axis('off')
    nx.draw(G6, pos, with_labels=False)
    plt.show()
Ejemplo n.º 19
0
    def set_graph(self, graphtype, graphparams):
        if graphtype == 'hexagonal':
            self.G = nx.triangular_lattice_graph(**graphparams)

        elif graphtype == 'watts strogatz':
            self.G = nx.watts_strogatz_graph(**graphparams)

        elif graphtype == 'newman watts strogatz':
            self.G = nx.newman_watts_strogatz_graph(**graphparams)

        elif graphtype == 'square':
            self.G = nx.grid_2d_graph(**graphparams)

        elif graphtype == 'random blocks':
            self.G = nx.stochastic_block_model(**graphparams)

        elif graphtype == 'powerlaw cluster':
            self.G = nx.powerlaw_cluster_graph(**graphparams)

        elif graphtype == 'scale-free small world':
            self.G = clustered_scalefree(**graphparams)

        elif graphtype == 'barabasi-albert':
            self.G = nx.barabasi_albert_graph(**graphparams)

        else:
            print('Using complete graph')
            self.G = nx.complete_graph(**graphparams)
Ejemplo n.º 20
0
def test_rand_structure_with_layer_norm_success():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    # Arrange
    random_graph = nx.newman_watts_strogatz_graph(100, 4, 0.5)
    # print("Random graph has %s edges." % len(random_graph.edges))
    structure = deepstruct.graph.CachedLayeredGraph()
    structure.add_edges_from(random_graph.edges)
    structure.add_nodes_from(random_graph.nodes)
    batch_size = 10
    shape_input = (28, 28)
    size_output = 10
    random_input = torch.tensor(
        np.random.random((batch_size, ) + shape_input),
        device=device,
        requires_grad=False,
    )
    model = deepstruct.sparse.MaskedDeepDAN(shape_input,
                                            size_output,
                                            structure,
                                            use_layer_norm=True)
    model.to(device)

    # Act
    model(random_input)

    # Act
    extracted_structure = model.generate_structure(include_input=False,
                                                   include_output=False)
    assert len(structure.nodes) == len(extracted_structure.nodes)
    assert len(structure.edges) == len(extracted_structure.edges)
    assert nx.is_isomorphic(structure, extracted_structure)
def create_newman_WS_graphs(N, betas):
    NUM_NEIGHBORS = 2

    graphs = []
    for beta in betas:
        graphs.append(networkx.newman_watts_strogatz_graph(N, NUM_NEIGHBORS, beta))
    return graphs
Ejemplo n.º 22
0
def walklets(population, neighbors, probability):
    g = nx.newman_watts_strogatz_graph(population, neighbors, probability)
    model = Walklets()
    model.fit(g)
    emb = model.get_embedding()
    #print(emb.shape)
    return [emb.shape]
Ejemplo n.º 23
0
def labelPropagation(population, neighbors, probability):
    g = nx.newman_watts_strogatz_graph(population, neighbors, probability)
    model = LabelPropagation()
    model.fit(g)

    #print(model.get_memberships())
    return [model.get_memberships()]
Ejemplo n.º 24
0
 def init_random(self, n=200, k=10, typ='random', p=.1, weighted=False, seed=None):
     # add n nodes to the network in the start state -> S
     self.add_mult(n, state='S', traced=False)
     # initialize the rewire probability to k/n if p=None provided
     p = k / n if p is None else p
             
     links_to_create_dict = {
         # Generate random pairs (edges) without replacement
         'random': lambda: rand_pairs(n, int(n * k / 2), seed=seed),
         'binomial': lambda: list(nx.fast_gnp_random_graph(n, p, seed=seed).edges),
         # small-world network
         'ws': lambda: list(nx.watts_strogatz_graph(n, k, p, seed=seed).edges),
         'newman-ws': lambda: list(nx.newman_watts_strogatz_graph(n, k, p, seed=seed).edges),
         # scale-free network
         'barabasi': lambda: list(nx.barabasi_albert_graph(n, m=k, seed=seed).edges),
         'powerlaw-cluster': lambda: list(nx.powerlaw_cluster_graph(n, m=k, p=p, seed=seed).edges),
         # fully connected network
         'complete': lambda: list(nx.complete_graph(n).edges),
     }
     try:
         links_to_create = links_to_create_dict[typ]()
     except KeyError:
         print("The inputted network type is not supported. Default to: random", file=stderr)
         links_to_create = links_to_create_dict['random']()
         
     len_links = len(links_to_create)
         
     if weighted:
         # Create random weights from 1 to 10 and append them to the list of edge tuples
         weights = random.choices(range(1,10), k=len_links)
         links_to_create = [links_to_create[i] + (weights[i],) for i in range(len_links)]
         
     # Add the random edges with/without weights depending on 'weighted' parameter
     # we do not update the counts here because they will be updated after the infection has been seeded with first_inf
     self.add_links(links_to_create, update=False)
Ejemplo n.º 25
0
    def test_networkx_roundtrip(self):
        print("\n---------- NetworkX Data Roundtrip Test Start -----------\n")

        g = nx.newman_watts_strogatz_graph(100, 3, 0.5)
        nodes = g.nodes()
        edges = g.edges()

        # Add some attributes
        g.graph["name"] = "original"
        g.graph["density"] = nx.density(g)

        nx.set_node_attributes(g, "betweenness", nx.betweenness_centrality(g))
        nx.set_node_attributes(g, "degree", nx.degree(g))
        nx.set_node_attributes(g, "closeness", nx.closeness_centrality(g))

        nx.set_edge_attributes(g, "eb", nx.edge_betweenness(g))

        cyjs1 = util.from_networkx(g)
        g2 = util.to_networkx(cyjs1)

        self.assertEqual(len(g2.nodes()), len(nodes))
        self.assertEqual(len(g2.edges()), len(edges))

        edge_set = set(list(map(lambda x: (int(x[0]), int(x[1])), g2.edges())))
        self.assertEqual(0, len(edge_set.difference(set(edges))))

        node_original = g.node[1]
        node_generated = g2.node["1"]

        print(node_original)
        print(node_generated)

        self.assertEqual(node_original["degree"], node_generated["degree"])
        self.assertEqual(node_original["betweenness"], node_generated["betweenness"])
        self.assertEqual(node_original["closeness"], node_generated["closeness"])
Ejemplo n.º 26
0
    def test_networkx_roundtrip(self):
        print('\n---------- NetworkX Data Roundtrip Test Start -----------\n')

        g = nx.newman_watts_strogatz_graph(100, 3, 0.5)
        nodes = g.nodes()
        edges = g.edges()

        # Add some attributes
        g.graph['name'] = 'original'
        g.graph['density'] = nx.density(g)

        nx.set_node_attributes(g, 'betweenness', nx.betweenness_centrality(g))
        nx.set_node_attributes(g, 'degree', nx.degree(g))
        nx.set_node_attributes(g, 'closeness', nx.closeness_centrality(g))

        nx.set_edge_attributes(g, 'eb', nx.edge_betweenness(g))

        cyjs1 = util.from_networkx(g)
        g2 = util.to_networkx(cyjs1)

        self.assertEqual(len(g2.nodes()), len(nodes))
        self.assertEqual(len(g2.edges()), len(edges))

        edge_set = set(list(map(lambda x: (int(x[0]), int(x[1])), g2.edges())))
        self.assertEqual(0, len(edge_set.difference(set(edges))))

        node_original = g.node[1]
        node_generated = g2.node['1']

        print(node_original)
        print(node_generated)

        self.assertEqual(node_original['degree'], node_generated['degree'])
        self.assertEqual(node_original['betweenness'], node_generated['betweenness'])
        self.assertEqual(node_original['closeness'], node_generated['closeness'])
Ejemplo n.º 27
0
    def create_graph(self, params):

        # case statements on type of graph

        if self.type == 'small_world':
            self.graph = nx.watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWC += 1
            self.idx = cg.SWC
            self.path = 'smallWorldGraphs'
        elif self.type == 'small_world_connected':
            self.graph = nx.connected_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                100 if len(params) < 4 else int(params[3]),
                None if len(params) < 5 else int(params[4]))
            cg.SWCC += 1
            self.idx = cg.SWCC
            self.path = 'smallWorldConnectedGraphs'
        elif self.type == 'small_world_newman':
            self.graph = nx.newman_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWNC += 1
            self.idx = cg.SWNC
            self.path = 'smallWorldNewmanGraphs'
        elif self.type == 'power_law':
            self.graph = nx.powerlaw_cluster_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.PLC += 1
            self.idx = cg.PLC
            self.path = 'powerLawGraphs'
        elif self.type == 'power_law_tree':
            self.graph = nx.random_powerlaw_tree(
                int(params[0]), 3 if len(params) < 2 else float(params[1]),
                None if len(params) < 3 else int(params[2]),
                100 if len(params) < 4 else int(params[3]))
            cg.PLTC += 1
            self.idx = cg.PLTC
            self.path = 'powerLawTreeGraphs'
        elif self.type == 'random_graph':
            self.graph = nx.gnm_random_graph(
                int(params[0]), int(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.RGC += 1
            self.idx = cg.RGC
            self.path = 'randomGraphs'
        elif self.type == 'erdos_renyi_random':
            self.graph = nx.erdos_renyi_graph(
                int(params[0]), float(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.ERRC += 1
            self.idx = cg.ERRC
            self.path = 'erdosRenyiRandomGraphs'
        else:
            print 'GRAPH TYPE:', self.type
            raise Exception('Invalid Type of Graph input into argv[2]')
Ejemplo n.º 28
0
def get_graph(objects, properties):
    graph_type = properties['graph_type']
    n = len(objects) - 1
    if 'num_nodes_to_attach' in properties.keys():
        k = properties['num_nodes_to_attach']
    else:
        k = 3
    r = properties['connection_probability']

    tries = 0
    while (True):
        if graph_type == 'random':
            x = nx.fast_gnp_random_graph(n, r)
        elif graph_type == 'erdos_renyi_graph':
            x = nx.erdos_renyi_graph(n, r)
        elif graph_type == 'watts_strogatz_graph':
            x = nx.watts_strogatz_graph(n, k, r)
        elif graph_type == 'newman_watts_strogatz_graph':
            x = nx.newman_watts_strogatz_graph(n, k, r)
        elif graph_type == 'barabasi_albert_graph':
            x = nx.barabasi_albert_graph(n, k, r)
        elif graph_type == 'powerlaw_cluster_graph':
            x = nx.powerlaw_cluster_graph(n, k, r)
        elif graph_type == 'cycle_graph':
            x = nx.cycle_graph(n)
        else:  ##Star by default
            x = nx.star_graph(len(objects) - 1)
        tries += 1
        cc_conn = nx.connected_components(x)
        if len(cc_conn) == 1 or tries > 5:
            ##best effort to create a connected graph!
            break
    return x, cc_conn
Ejemplo n.º 29
0
def smallworld(size, neighbors, edgeprob, seed=None):
    assert size > 0
    assert neighbors >= 0
    assert edgeprob >= 0 and edgeprob <= 1

    if seed:
        g = nx.newman_watts_strogatz_graph(n=size, k=neighbors, p=edgeprob,
                                           seed=seed)

    else:
        g = nx.newman_watts_strogatz_graph(n=size, k=neighbors, p=edgeprob)

    g.name = 'Small World network: {s} nodes, {n} neighbors, ' \
             '{p} edge probability'.format(s=size, n=neighbors, p=edgeprob)

    return g
Ejemplo n.º 30
0
    def test_networkx_roundtrip(self):
        print('\n---------- NetworkX Data Roundtrip Test Start -----------\n')

        g = nx.newman_watts_strogatz_graph(100, 3, 0.5)
        nodes = g.nodes()
        edges = g.edges()

        # Add some attributes
        g.graph['name'] = 'original'
        g.graph['density'] = nx.density(g)

        nx.set_node_attributes(g, 'betweenness', nx.betweenness_centrality(g))
        nx.set_node_attributes(g, 'degree', nx.degree(g))
        nx.set_node_attributes(g, 'closeness', nx.closeness_centrality(g))

        nx.set_edge_attributes(g, 'eb', nx.edge_betweenness(g))

        cyjs1 = util.from_networkx(g)
        g2 = util.to_networkx(cyjs1)

        self.assertEqual(len(g2.nodes()), len(nodes))
        self.assertEqual(len(g2.edges()), len(edges))

        edge_set = set(list(map(lambda x: (int(x[0]), int(x[1])), g2.edges())))
        self.assertEqual(0, len(edge_set.difference(set(edges))))

        node_original = g.node[1]
        node_generated = g2.node['1']

        print(node_original)
        print(node_generated)

        self.assertEqual(node_original['degree'], node_generated['degree'])
        self.assertEqual(node_original['betweenness'], node_generated['betweenness'])
        self.assertEqual(node_original['closeness'], node_generated['closeness'])
Ejemplo n.º 31
0
def test_graph_generator():
    n = 400
    m = 5
    seed = 0
    # G = nx.barabasi_albert_graph(n, m, seed)
    G = nx.random_partition_graph([100, 100, 200], .25, .01)
    sizes = [10, 90, 300]
    probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
    G = nx.stochastic_block_model(sizes, probs, seed=0)

    G = nx.newman_watts_strogatz_graph(400, 5, 0.5)

    A = nx.to_numpy_array(G)
    print(A)
    plt.pcolormesh(A)
    plt.show()

    s = sorted(G.degree, key=lambda x: x[1], reverse=True)
    # newmap = {s[i][0]:i for i in range(len(s))}
    # H= nx.relabel_nodes(G,newmap)
    # newmap = generate_node_mapping(G, type='community')
    # H = networkX_reorder_nodes(G, newmap)
    H = networkx_reorder_nodes(G, 'community')

    # B = nx.to_numpy_array(H)
    # # plt.pcolormesh(B)
    # plt.imshow(B)
    # plt.show()

    visualize_graph_matrix(H)
Ejemplo n.º 32
0
def createGraphsAndCommunities():
	g = nx.scale_free_graph(500, alpha=0.40, beta=0.40, gamma=0.20)
	g1 = nx.powerlaw_cluster_graph(500, 10, 0.2)
	g2 = nx.barabasi_albert_graph(500, 10)
	g3 = nx.newman_watts_strogatz_graph(500, 10, 0.2)
	nx.write_graphml (g, direc+"sfg.graphml")
	nx.write_graphml(g1, direc+"pcg.graphml")
	nx.write_graphml(g2, direc+"bag.graphml")
	nx.write_graphml(g3, direc+"nwsg.graphml")

	graphs = {}
	graphs["sfg"] = graph_tool.load_graph(direc+"sfg.graphml")
	graphs["pcg"] = graph_tool.load_graph(direc+"pcg.graphml")
	graphs["bag"] = graph_tool.load_graph(direc+"bag.graphml")
	graphs["nwsg"] = graph_tool.load_graph(direc+"nwsg.graphml")
	graphs["price"] = graph_tool.generation.price_network(1000)
	
	for i,h in graphs.iteritems():
		s = graph_tool.community.minimize_blockmodel_dl(h)
		b = s.b
		graph_tool.draw.graph_draw(h, vertex_fill_color=b, vertex_shape=b, output=direc+"block"+str(i)+".pdf")
		
		com = graph_tool.community.community_structure(h, 10000, 20)
		graph_tool.draw.graph_draw(h, vertex_fill_color=com, vertex_shape=com, output=direc+"community"+str(i)+".pdf")

		state = graph_tool.community.minimize_nested_blockmodel_dl(h)
		graph_tool.draw.draw_hierarchy(state, output=direc+"nestedblock"+str(i)+".pdf")

		pagerank = graph_tool.centrality.pagerank(h)
		graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"pagerank"+str(i)+".pdf")
		h.set_reversed(is_reversed=True)
		pagerank = graph_tool.centrality.pagerank(h)
		graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"reversed_pagerank"+str(i)+".pdf")
Ejemplo n.º 33
0
 def connect_newman_watts_strogatz(self,N,k,p):
     """
     Newman-Watts-Strogatz graph staring with a k-nearest neighbor ring.  Additional edges are added with
     probability p.
     """
     # ditto
     self.connect_empty(N)
     self.add_edges_from(nx.newman_watts_strogatz_graph(N,k,p).edges())
Ejemplo n.º 34
0
    def __gen_smallworld_topology(self, nodes):
        # Each node is joined with its k nearest neighbors in a ring topology
        k = self.__connection_parameter['k']

        # The probability of rewiring each edge
        p = self.__connection_parameter['p']
        #        return nx.connected_watts_strogatz_graph(nodes, k, p)
        return nx.newman_watts_strogatz_graph(nodes, k, p)
Ejemplo n.º 35
0
def graphWave(population, neighbors, probability):
    g = nx.newman_watts_strogatz_graph(population, neighbors, probability)
    model = GraphWave()
    model.fit(g)
    embedding = model.get_embedding()

    #print(embedding)
    return [embedding]
Ejemplo n.º 36
0
def mesh_1d_directed_weighted(n, k):
    
    G=nx.newman_watts_strogatz_graph(n, k, 0, seed=None)
    G.to_directed()
    for (u,v,w) in G.edges(data=True):
        w['weight'] = random.randint(0,1)
        
    return G
    def __init__(self, size, meanDegree, beta):
        self.size = size
        self.meanDegree = meanDegree
        self.beta = beta
        self.network = nx.newman_watts_strogatz_graph(self.size,self.meanDegree,self.beta) #No edges are removed in newman implementation (So, atleast we get a ring lattice)

        # Network stats object
        self.networkStats = Networkstats(self.network, self.size)
def directed_newman_watts_strogatz_graph(n, k, p, seed=None):
    G = nx.newman_watts_strogatz_graph(n, k, p, seed)
    DG = nx.DiGraph()
    DG.add_nodes_from(G.nodes())
    for (u, v) in G.edges_iter():
        r = random.randint(0, 1)
        if r == 0:
            DG.add_edge(u, v)
        else:
            DG.add_edge(v, u)
    return DG
Ejemplo n.º 39
0
def RandomNewmanWattsStrogatz(n, k, p, seed=None):
    """
    Returns a Newman-Watts-Strogatz small world random graph on n
    vertices.

    From the NetworkX documentation: First create a ring over n nodes.
    Then each node in the ring is connected with its k nearest
    neighbors. Then shortcuts are created by adding new edges as
    follows: for each edge u-v in the underlying "n-ring with k nearest
    neighbors"; with probability p add a new edge u-w with
    randomly-chosen existing node w. In contrast with
    watts_strogatz_graph(), no edges are removed.

    INPUT:


    -  ``n`` - number of vertices.

    -  ``k`` - each vertex is connected to its k nearest
       neighbors

    -  ``p`` - the probability of adding a new edge for
       each edge

    -  ``seed`` - for the random number generator


    EXAMPLE: We show the edge list of a random graph on 7 nodes with 2
    "nearest neighbors" and probability `p = 0.2`::

        sage: graphs.RandomNewmanWattsStrogatz(7, 2, 0.2).edges(labels=False)
        [(0, 1), (0, 2), (0, 3), (0, 6), (1, 2), (2, 3), (2, 4), (3, 4), (3, 6), (4, 5), (5, 6)]

    ::

        sage: G = graphs.RandomNewmanWattsStrogatz(12, 2, .3)
        sage: G.show()  # long time

    REFERENCE:

    - [1] Newman, M.E.J., Watts, D.J. and Strogatz, S.H.  Random
      graph models of social networks. Proc. Nat. Acad. Sci. USA
      99, 2566-2572.
    """
    if seed is None:
        seed = current_randstate().long_seed()
    import networkx

    return graph.Graph(networkx.newman_watts_strogatz_graph(n, k, p, seed=seed))
Ejemplo n.º 40
0
	def init_graph(self,g='reg',k=2):
		"""Creates a graph of type g"""
		self.diseasenetwork.add_nodes_from(self.agents)
		#Rewiring of graphs could count as random_mixing 
		#Types of random graphs
		gtype = { 'er':nx.fast_gnp_random_graph(self.population,0.05),
				'nws':nx.newman_watts_strogatz_graph(self.population,k,0.5),
				'ws':nx.watts_strogatz_graph(self.population,k,0.5),
				'cws':nx.connected_watts_strogatz_graph(self.population,k,0.5,10),
				'ba':nx.barabasi_albert_graph(self.population,k),
				'reg':nx.random_regular_graph(k,self.population),
				'grid':nx.grid_2d_graph(self.population/2,self.population/2) }
		#This is causing the trouble need to map each edge to nodes :) 
		if g == 'grid':
			self.diseasenetwork.add_edges_from([ (self.agents[x[0]],self.agents[y[0]]) for x,y in gtype[g].edges() ])
		else:
			self.diseasenetwork.add_edges_from([ (self.agents[x],self.agents[y]) for x,y in gtype[g].edges() ])
Ejemplo n.º 41
0
def small_world():
    G = nx.newman_watts_strogatz_graph(n=121, k=4, p=0.05)
        
    G.graph['name'] = 'small_world'
    for i in xrange(MAX_ROAD_ATTEMPTS):
        n1, n2 = sample(G.nodes(), 2)
        if not nx.has_path(G, n1, n2):
            continue
        sp = nx.shortest_path(G, n1, n2)
        index = random.choice(range(len(sp) - 1))
        u, v = sp[index], sp[index + 1]
        G.remove_edge(u, v)
        if not nx.has_path(G, u, v):
            G.add_edge(u, v)
            continue
        G.add_edge(u, v)
        set_init_road_path(G, n1, n2, u, v)
        return G
Ejemplo n.º 42
0
def build_topology_smallworld(config):
    """Build a small world network"""

    size = config['SmallWorldTopology']['size']
    neighbors = config['SmallWorldTopology']['neighbors']
    edgeprob = config['SmallWorldTopology']['edgeprob']
    seed = config['Simulation']['seed']

    assert size > 0
    assert neighbors >= 0
    assert 0 <= edgeprob <= 1

    top = nx.newman_watts_strogatz_graph(n=size, k=neighbors, p=edgeprob,
                                         seed=seed)
    top.name = 'Small World network: {s} nodes, {n} neighbors, ' \
               '{p} edge probability'.format(s=size, n=neighbors, p=edgeprob)

    return top
    def create_graph(self, params):

        # case statements on type of graph

        if self.type == 'small_world':
            self.graph = nx.watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.SWC += 1
            self.idx = cg.SWC
            self.path = 'smallWorldGraphs'
        elif self.type == 'small_world_connected':
            self.graph = nx.connected_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), 100 if len(params) < 4 else int(params[3]), None if len(params) < 5 else int(params[4]))
            cg.SWCC += 1
            self.idx = cg.SWCC
            self.path = 'smallWorldConnectedGraphs'
        elif self.type == 'small_world_newman':
            self.graph = nx.newman_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.SWNC += 1
            self.idx = cg.SWNC
            self.path = 'smallWorldNewmanGraphs'
        elif self.type == 'power_law':
            self.graph = nx.powerlaw_cluster_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.PLC += 1
            self.idx = cg.PLC
            self.path = 'powerLawGraphs'
        elif self.type == 'power_law_tree':
            self.graph = nx.random_powerlaw_tree(int(params[0]), 3 if len(params) < 2 else float(params[1]), None if len(params) < 3 else int(params[2]), 100 if len(params) < 4 else int(params[3]))
            cg.PLTC += 1
            self.idx = cg.PLTC
            self.path = 'powerLawTreeGraphs'
        elif self.type == 'random_graph':
            self.graph = nx.gnm_random_graph(int(params[0]), int(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3]))
            cg.RGC += 1
            self.idx = cg.RGC
            self.path = 'randomGraphs'
        elif self.type == 'erdos_renyi_random':
            self.graph = nx.erdos_renyi_graph(int(params[0]), float(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3]))
            cg.ERRC += 1
            self.idx = cg.ERRC
            self.path = 'erdosRenyiRandomGraphs'
        else:
            print 'GRAPH TYPE:', self.type
            raise Exception('Invalid Type of Graph input into argv[2]')
def generate_graph(voters):
    
    # generate edges randomly
    # n, k, p, [seed]
    # n = nodes

    ws=nx.newman_watts_strogatz_graph(len(voters),len(voters)/10,1)

    G = nx.DiGraph(ws)
    for i in range(len(voters)):
        G.node[i]['score']=voters[i]['score']
        G.node[i]['error']=voters[i]['error']

    for (a, b) in G.edges():
        
        G.edge[a][b]['weight'] = generate_rating(voters[a],voters[b])

    #nx.draw(G)
    #nx.draw_networkx_edge_labels(G,pos=nx.spring_layout(G))
    #plt.show()

    return G
def correlation_betweenness_degree_on_NW():
    n = 1000
    k = 4
    p = 0.01
    G = nx.newman_watts_strogatz_graph(n, k, p)

    print nx.info(G)
    ND, ND_lambda = ECT.get_number_of_driver_nodes(G)
    print "ND = ", ND
    print "ND lambda:", ND_lambda
    ND, driverNodes = ECT.get_driver_nodes(G)
    print "ND =", ND

    degrees = []
    betweenness = []

    tot_degree = nx.degree_centrality(G)
    tot_betweenness = nx.betweenness_centrality(G,weight=None)

    for node in driverNodes:
        degrees.append(tot_degree[node])
        betweenness.append(tot_betweenness[node])

    with open("results/driver_degree_NW.txt", "w") as f:
        for x in degrees:
            print >> f, x
    with open("results/driver_betweenness_NW.txt", "w") as f:
        for x in betweenness:
            print >> f, x

    with open("results/tot_degree_NW.txt", "w") as f:
        for key, value in tot_degree.iteritems():
            print >> f, value

    with open("results/tot_betweenness_NW.txt", "w") as f:
        for key, value in tot_betweenness.iteritems():
            print >> f, value
Ejemplo n.º 46
0
def get_universe():
    """
    Creates a universe and returns a dict with important universe information
    """

    # Generate a connected network of nodes
    G = nx.newman_watts_strogatz_graph(100,2,0.9)

    # Assign a 2d position to the nodes
    locs = nx.spectral_layout(G)

    # Create the Solar Systems by looping though the node list created by networkx
    systemlist = {}

    for node in G.nodes():
        system = dict()
        system["name"] = 'Unnamed System SX-%s' % node

        dests = []
        for dest in G[node]:
            dests.append(dest)

        system["destinations"] = dests

        system["coordinates"] = locs[node]

        # Determine security level by distance to node 1
        if nx.shortest_path_length(G,source=node, target=1) > 3:
            system["security"] = 0
        else:
            system["security"] = 1

        systemlist[node] = system

    # Create a security zone from

    return systemlist
Ejemplo n.º 47
0
def generate_model_networks(num_nodes):
    networks=[]


    #erdos_renyi_graph n
    for p in np.arange(0.01, 0.99, 0.01):
        G=nx.erdos_renyi_graph(num_nodes,p)
        G.name='Erdos p='+str(p)+' nodes='+str(num_nodes)
        networks.append(G)

    #newman_watts_strogatz_graph
    for p in np.arange(0.01, 0.99, 0.01):
        for n in np.arange(5,np.min([int(num_nodes/2.0),150]), 20):
            G=nx.newman_watts_strogatz_graph(num_nodes,n,p)
            G.name='Newman Watts Strogatz p='+str(p)+' n='+str(n)+' nodes='+str(num_nodes)
            networks.append(G)

    #barabasi
    for n in np.arange(5,num_nodes, 5):#np.arange(5,np.min([int(num_nodes/2.0),150]), 20):
        G=nx.barabasi_albert_graph(num_nodes,n)
        G.name='Barabasi n='+str(n)+' nodes='+str(num_nodes)
        networks.append(G)

    return networks
Ejemplo n.º 48
0
def exportRandomGraph(name, path=''):
    G = nx.newman_watts_strogatz_graph(6,2,0.5)
    nx.draw(G)
    plt.savefig('img_rdm_generate_graph_'+name+'.png')
    plt.clf()
    print(pl.is_planar(G))
Ejemplo n.º 49
0
def random_symmetric_graph(num_nodes, num_joints, num_colors, rewiring_p=0.5):
    """
    random_symmetric_graph(num_nodes, num_joints, num_colors, rewiring_p=0.4):
    makes a symmetric (newman-watts-strogatz) graph.

    Returns:
    nodes, node_centers (in [-1, 1] x [-1, 1]), node_colors, edges
    """

    # Make the first graph
    connected_graph = False
    while not connected_graph:
        g = nx.newman_watts_strogatz_graph(num_nodes, 3, rewiring_p)
        connected_graph = nx.is_connected(g)

    # Make a copy, which we will join to the first graph.
    g2 = g.copy()

    # Rename all vertices in the second graph except the joints
    mapping = dict()
    for i in range(num_joints, num_nodes):
        mapping[i] = (num_nodes + 1) + i
    nx.relabel_nodes(g2, mapping, copy=False)

    # TODO: Need a symmetric layout algorithm.
    """
    Getting the layout of the one-sided graph (g) before composition, and
    reflecting the positions of the other side manually around the LSQ line of
    the joints nodes should work.
    """

    # Get spring-directed layout of one-sided graph.
    g_layout = nx.spring_layout(g, scale=1.0)

    # Get the composition of the two graphs
    g = nx.compose(g, g2)

    # Force-directed graph layout
    g_layout = nx.spring_layout(g, k=1 / np.sqrt(g.number_of_nodes()), iterations=1000, fixed=None, scale=1.0)

    node_centers = []
    for k, v in g_layout.items():
        node_centers.append((v[0], v[1]))

    # Choose node colors
    colors = np.array(
        [("red", "blue", "gray")[0:num_colors] for i in range(np.int(np.ceil(g.number_of_nodes() / num_colors)))]
    )
    colors = colors.flatten()
    color_choices = np.random.choice(colors, g.number_of_nodes(), replace=False)

    node_colors = []
    # Replace string with rgba value.
    for i in range(len(color_choices)):
        if color_choices[i] == "red":
            node_colors.append(COLOR_RED)
        elif color_choices[i] == "blue":
            node_colors.append(COLOR_BLUE)
        elif color_choices[i] == "gray":
            node_colors.append(COLOR_GRAY)

    return g.nodes(), node_centers, node_colors, g.edges()
Ejemplo n.º 50
0
#G = nx.read_edgelist(filename,create_using=nx.DiGraph())

#k = 11
#P = [[.902,.253],[.221,.582]]
#G = product.kronecker_random_graph(k,P)
#for u,v in G.selfloop_edges():
#  G.remove_edge(u,v)

#G = nx.read_edgelist("C:\\Users\\tweninge\\Downloads\\CA-HepTh.txt")
#G = nx.barabasi_albert_graph(500, 1)
#G = nx.powerlaw_cluster_graph(1000,1,.1)
#G = nx.random_regular_graph(10, 1000)
#G = nx.scale_free_graph(1000)
#G = nx.erdos_renyi_graph(1000,.05)
#G = nx.watts_strogatz_graph(3000, 6, .35)
G = nx.newman_watts_strogatz_graph(250, 4, .05)
#G = nx.newman_watts_strogatz_graph(1000, 5, .25)

G = nx.Graph(G)
A = nx.to_numpy_matrix(G)

u, s, v = np.linalg.svd(A)

f, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(3, 3,  sharex='col', sharey='row', figsize=(8,8), dpi=80)

ax1.scatter(u[0],u[1])
ax2.scatter(u[1],u[2])
ax3.scatter(u[2],u[3])
ax4.scatter(u[3],u[4])
ax5.scatter(u[4],u[5])
ax6.scatter(u[5],u[6])
Ejemplo n.º 51
0
import networkx

G = networkx.newman_watts_strogatz_graph(100, 3, 0.5)
Ejemplo n.º 52
0
import networkx as nx

node_ct = 100
graphs = {
    "Erdos-Renyi P=0.1": lambda: nx.erdos_renyi_graph(node_ct, 0.1),
    "Erdos-Renyi P=0.25": lambda: nx.erdos_renyi_graph(node_ct, 0.25),
    "Erdos-Renyi P=0.5": lambda: nx.erdos_renyi_graph(node_ct, 0.5),
    "Newman-Watts-Strogatz P=0.1, k=10/node_ct": lambda: nx.newman_watts_strogatz_graph(
        node_ct, int(10.0 / node_ct), 0.1
    ),
    "Newman-Watts-Strogatz P=0.25, k=10/node_ct": lambda: nx.newman_watts_strogatz_graph(
        node_ct, int(10.0 / node_ct), 0.25
    ),
    "Newman-Watts-Strogatz P=0.5, k=10/node_ct": lambda: nx.newman_watts_strogatz_graph(
        node_ct, int(10.0 / node_ct), 0.5
    ),
    "Random Regular - Degree=1": lambda: nx.random_regular_graph(1, node_ct),
    "Random Regular - Degree=10": lambda: nx.random_regular_graph(10, node_ct),
    "Random Regular - Degree=50": lambda: nx.random_regular_graph(50, node_ct),
    "Barabasi Albert - Edges=1": lambda: nx.barabasi_albert_graph(node_ct, 1),
    "Barabasi Albert - Edges=10": lambda: nx.barabasi_albert_graph(node_ct, 10),
    "Barabasi Albert - Edges=50": lambda: nx.barabasi_albert_graph(node_ct, 50),
}
def EdgeAttackNW():
    start_time = time.time()

    n = 200
    k = 4
    p = 0.1
    fraction = 0.2
    E = 440
    E_rm = 88
    run_cnt = 100

    #******** Run Node Attack 1 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 0
    for i in range(run_cnt):
        G1 = nx.newman_watts_strogatz_graph(n, k, p, seed=rndseed)
        print ">>>>>>>>>>>>>>> Random Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RandomEdgeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack1_NW.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    #******** Run Node Attack 2 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 0
    for i in range(run_cnt):
        G1 = nx.newman_watts_strogatz_graph(n, k, p, seed=rndseed)
        print ">>>>>>>>>>>>>>> Initial Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack2_NW.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    #******** Run Node Attack 3 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 0
    for i in range(run_cnt):
        G1 = nx.newman_watts_strogatz_graph(n, k, p, seed=rndseed)
        print ">>>>>>>>>>>>>>> Recalculated Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RecalculatedEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack3_NW.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))


    #******** Run Node Attack 4 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 0
    for i in range(run_cnt):
        G1 = nx.newman_watts_strogatz_graph(n, k, p, seed=rndseed)
        print ">>>>>>>>>>>>>>> Initial Betweenness Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeBetweennessAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack4_NW.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    #******** Run Node Attack 5 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 0
    for i in range(run_cnt):
        G1 = nx.newman_watts_strogatz_graph(n, k, p, seed=rndseed)
        print ">>>>>>>>>>>>>>> Recalculated Betweenness Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RecalculatedEdgeBetweennessAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack5_NW.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    print "--- cost time %s seconds ---" %(time.time() - start_time)
              [ic, "itertive_compression"],
              # [rn, "randomized_opt"], # disabled because too slow
              [mif, "maximum_induced_forest"]]

graph = nx.erdos_renyi_graph(9, 0.5)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(10, 0.7)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(11, 0.6)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(12, 0.3)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(13, 0.5)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(15, 0.8)
test_algorithms(algorithms, graph)

graph = nx.erdos_renyi_graph(16, 0.8)
test_algorithms(algorithms, graph)

graph = nx.dense_gnm_random_graph(10, 25)
test_algorithms(algorithms, graph)

graph = nx.newman_watts_strogatz_graph(11, 5, 0.2)
test_algorithms(algorithms, graph)
Ejemplo n.º 55
0
import pygraphviz as pgv
import networkx as nx

#普通にnetworkxのグラフを作成
h = nx.newman_watts_strogatz_graph(10,3,0.4)

#これをagraphクラス(PyGraphviz)に変換
g = nx.to_agraph(h)

#file.pdfという名前で出力,レイアウトはcircoを使う
g.draw('file.pdf',prog='circo')
Ejemplo n.º 56
0
def sen(n1, p1, n2, p2, n3, p3, pa, pb):
    """Creates a SEN model with an actor network of n1 elements, with a neighbourhood connectivity of p1, a user network of n2 elements, with a neighbourhood connectivity of p2, and a ecological network of n3 elements with a neighbourhood connectivity of p3. The probability of connections between the actor network and the user netwrok, and between the user network and the ecological network, are respectively passed through pa and pb"""

    # Actor network
    A = nx.newman_watts_strogatz_graph(n1, p1, 1)
    A.graph["Network"] = "Actors"
    # Adding id
    for i in range(len(A)):
        A.node[i]["num"] = i + 1
        # Subnetwork
    for i in range(len(A)):
        A.node[i]["subnetwork"] = 1
        # Adding random class (office dwellers/field people)
    p_class_bureau = 0.75
    for i in range(len(A)):
        if random.random() <= p_class_bureau:
            A.node[i]["group"] = 0
        else:
            A.node[i]["group"] = 0
            # Adding randow weight
    # 	for n,nbrs in A.adjacency_iter():
    # 		for nbr,eattr in nbrs.items():
    # 			A[n][nbr]['weight'] = int(random.random()*8)

    # User network
    U = nx.newman_watts_strogatz_graph(n2, p2, 1)
    U.graph["Network"] = "Actors"
    # Adding id
    for i in range(len(U)):
        U.node[i]["num"] = i + 1001
        # Subnetwork
    for i in range(len(U)):
        U.node[i]["subnetwork"] = 2
        # Adding random class (office dwellers/field people)
    for i in range(len(U)):
        rnd = random.random()
        if rnd <= 0.2:
            U.node[i]["group"] = 1
        if rnd > 0.2 and rnd <= 0.4:
            U.node[i]["group"] = 1
        if rnd > 0.4 and rnd <= 0.6:
            U.node[i]["group"] = 1
        if rnd > 0.6 and rnd <= 0.8:
            U.node[i]["group"] = 1
        if rnd > 0.8:
            U.node[i]["group"] = 1
            # Adding randow weight
    # 	for n,nbrs in U.adjacency_iter():
    # 		for nbr,eattr in nbrs.items():
    # 			U[n][nbr]['weight'] = int(random.random()*8)

    # Ecological network
    E = nx.newman_watts_strogatz_graph(n3, p3, 1)
    E.graph["Network"] = "Actors"
    # Adding id
    for i in range(len(E)):
        E.node[i]["num"] = i + 10001
        # Subnetwork
    for i in range(len(E)):
        E.node[i]["subnetwork"] = 3
        # Adding class
    for i in range(len(E)):
        E.node[i]["group"] = 2
        # Adding weight
    # 	for n,nbrs in E.adjacency_iter():
    # 		for nbr,eattr in nbrs.items():
    # 			E[n][nbr]['weight'] = 5

    # joint the three subnetworks
    G = nx.disjoint_union_all([A, U, E])

    # link some actors to some users
    for i in range(0, len(G)):
        for j in range(0, len(G)):
            if i != j:
                if G.node[i]["subnetwork"] == 1 and G.node[j]["subnetwork"] == 2:
                    # if G.node[i]['group'] == 1 and G.node[j]['group'] == 2:
                    if random.random() < pa:
                        G.add_edge(i, j)

                # link some users to some patches
    for i in range(0, len(G)):
        G.node[i]["degreeold"] = G.degree(i)

    for i in range(0, len(G)):
        for j in range(0, len(G)):
            if i != j:
                # print str(j) + " " + str(G.degree(j))
                if (
                    G.node[i]["subnetwork"] == 2
                    and G.node[j]["subnetwork"] == 3
                    and G.degree(j) - G.node[j]["degreeold"] < 4
                ):
                    if G.degree(j) - G.node[j]["degreeold"] < 4:
                        if random.random() < pb:
                            G.add_edge(i, j)

                # write json formatted data
    d = json_graph.node_link_data(G)
    json.dump(d, open("/Users/Rodolphe/Dropbox/Public/d3/examples/force/force.json", "w"))

    nx.write_graphml(G, "graph.graphml")

    return G
Ejemplo n.º 57
0
from __future__ import division

import random

import matplotlib.pyplot as plt
import networkx as nx

wsg = nx.newman_watts_strogatz_graph(1000, 3, 0.9)
# wsg = nx.barabasi_albert_graph(5000000, 2)
nx.draw(wsg)
plt.show()


def ExpectBroadcastValue(nk=int(), af=float(), path_list=list()):
    start_list = wsg.edge[nk].keys()
    s = int(len(start_list) * af)
    if s == 0:
        return 1
    for node in random.sample(start_list, s):
        if node not in path_list:
            return nk + ExpectBroadcastValue(node, af, path_list)


KOL_list = list()
citizen_list = list()
for k in wsg.edge.iterkeys():
    if len(wsg.edge[k]) > 10:
        KOL_list.append(k)
    elif len(wsg.edge[k]) == 2:
        citizen_list.append(k)
Ejemplo n.º 58
0
    results = pd.DataFrame()
    for seed in range(0, 5):

        # set seed
        axl.seed(seed)

        num_players = random.randint(2, 132)
        # define the graph
        players = random.sample(ordinary_players, num_players)

        for parameter in range(0, 10) :

            p = parameter/100
            # Define graph
            G = nx.newman_watts_strogatz_graph(len(players), 8, p)

            edges = G.edges()

            results = results.append([tournament_results(G, seed, p, players, turns,
                                   edges, repetitions)])

            results = results[cols]

            if not file_exists:
                results.to_hdf(write_out, '{}_{}'.format(experiment, num_neighbors),
                               index=False, header=True)
            else :
                results.to_hdf(write_out, '{}_{}'.format(experiment, num_neighbors),
                               mode='a',  index=False, header=False)
Ejemplo n.º 59
0
import networkx

G = networkx.newman_watts_strogatz_graph(50, 16, 0.3, seed=None)