Example #1
0
def main():
    graf1 = nx.connected_watts_strogatz_graph(5, 4, 0.5, seed=1)
    graf2 = nx.connected_watts_strogatz_graph(50, 20, 0.5, seed=1)
    graf3 = nx.connected_watts_strogatz_graph(1000, 50, 0.5, seed=1)
    graph = nx.to_dict_of_lists(graf3)
    g = nx.Graph(graph)
    start = timeit.default_timer()
    print("Vertex cover: ", greedy(graph, g))
    stop = timeit.default_timer()
    print('Time: ', stop - start)
Example #2
0
def test_omega():
    Gl = nx.connected_watts_strogatz_graph(50, 6, 0, seed=rng)
    Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
    Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
    omegal = omega(Gl, niter=1, nrand=1, seed=rng)
    omegar = omega(Gr, niter=1, nrand=1, seed=rng)
    omegas = omega(Gs, niter=1, nrand=1, seed=rng)
    print("omegas, omegal, omegar")
    print(omegas, omegal, omegar)
    assert_true(omegal < omegas and omegas < omegar)
Example #3
0
def main():
    graf1 = nx.connected_watts_strogatz_graph(5, 4, 0.5, seed=1)
    graf2 = nx.connected_watts_strogatz_graph(50, 20, 0.5, seed=1)
    graf3 = nx.connected_watts_strogatz_graph(1000, 50, 0.5, seed=1)
    graph = nx.to_dict_of_lists(graf3)
    g = nx.Graph(graph)
    start = timeit.default_timer()
    print("Vertex cover: ", approx_vertex_cover(graph))
    stop = timeit.default_timer()
    print('Time: ', stop - start)
    nx.draw(g, with_labels=True)
    plt.show()
 def __init__(self, n, seed):
     if seed == 0:
         # 空网络
         self.net = nx.empty_graph()
     elif seed == 1:
         # ER随机图
         self.net = nx.gnp_random_graph(n, 0.012)
     elif seed == 2:
         # ER随机图
         self.net = nx.gnp_random_graph(n, 0.1)
     elif seed == 3:
         # ER随机图
         self.net = nx.gnp_random_graph(n, 0.3)
     elif seed == 4:
         # 规则图
         self.net = nx.watts_strogatz_graph(n, 4, 0)
     elif seed == 5:
         # 规则图
         self.net = nx.watts_strogatz_graph(n, 8, 0)
     elif seed == 6:
         # 规则图
         self.net = nx.watts_strogatz_graph(n, 16, 0)
     elif seed == 7:
         # WS小世界网络
         self.net = nx.connected_watts_strogatz_graph(n, 4, 0.1)
     elif seed == 8:
         # WS小世界网络
         self.net = nx.connected_watts_strogatz_graph(n, 8, 0.1)
     elif seed == 9:
         # WS小世界网络
         self.net = nx.connected_watts_strogatz_graph(n, 16, 0.1)
     elif seed == 10:
         # 无标度网络
         self.net = nx.barabasi_albert_graph(n, 4)
     elif seed == 11:
         # 无标度网络
         self.net = nx.barabasi_albert_graph(n, 8)
     elif seed == 12:
         # 无标度网络
         self.net = nx.barabasi_albert_graph(n, 16)
     elif seed == 13:
         # 高斯随机分块网络
         self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01)
     elif seed == 14:
         # 高斯随机分块网络
         self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01)
     elif seed == 15:
         # 高斯随机分块网络
         self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01)
     else:
         self.net = nx.empty_graph()
Example #5
0
    def random_g(self):
        #n é o numero de vertices
        n = self.quant_vert
        print(n)
        G = nx.connected_watts_strogatz_graph(n, randint(int(n / 2), n - 1),
                                              0.5, 100, randint(1, 100))

        # a é uma lista contendo as arestas do grafo
        a = G.edges()

        #matriz de adj do grafo
        self.matriz = []
        for i in range(n):
            self.matriz.append([0] * n)

        #plotagem do peso gerado aletoriamente na matriz
        for v1, v2 in a:
            n = randint(1, 50)
            self.matriz[v1][v2] = n
            self.matriz[v2][v1] = n
            #atribuição do peso no grafo
            G.edges[v1, v2]['weight'] = n

        self.quant_vert = G.number_of_nodes()

        #G.edges[v1,v2]['weight']=n
        return G
def make_graph(graph_params,
               eta,
               require_connected=True,
               require_invertible=True,
               require_stationary=True):
    while True:
        strongly_connected = False
        invertible = False
        stationary = False

        graph = nx.connected_watts_strogatz_graph(**graph_params)
        g_mat = update_matrix(graph, eta)

        strongly_connected = nx.is_connected(graph)

        invertible = not (np.linalg.det(g_mat) == 0)

        e_vals, e_vects = np.linalg.eig(g_mat)
        stationary = (max(e_vals) < 1.0)

        if (((not require_connected) or strongly_connected)
                and ((not require_invertible) or invertible)
                and ((not require_stationary) or stationary)):
            break

    return graph
Example #7
0
def generate_graph(n, k, p, seed):
    G = nx.connected_watts_strogatz_graph(n, k, p, seed)
    data = json_graph.node_link_data(G)
    with open('./Working/graph.json', 'w') as f:
        json.dump(data, f)
    with open('./Working/graph_flag', mode='w', encoding='utf-8') as fh:
        fh.write("i look at you")
Example #8
0
 def reset_graph(self):
     self.graph = nx.connected_watts_strogatz_graph(self.n_node, self.k_ring, self.p_rewiring)
     self.edgelabel = -np.ones([self.n_node, self.n_node]).astype('int32')
     for i in range(self.n_node):
         rndidx = np.random.permutation(len(self.graph.neighbors(i)))
         for idx, j in enumerate(self.graph.neighbors(i)):
             self.edgelabel[i][j] = rndidx[idx]
Example #9
0
def generate_connection_graph(graph_type, params, count):
    lower_type = graph_type.lower()
    if lower_type == 'complete':
        assert (len(params) == 0)
        return networkx.complete_graph(count)
    elif lower_type == 'complete-bipartite':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        n1 = int(round(count * float(params[0]) / float(params[1])))
        n2 = int(round(count * float(params[1]) / float(params[0])))
        n1 = 1 if n1 < 1 else n1
        n2 = 1 if n2 < 1 else n2
        return networkx.complete_bipartite_graph(n1, n2)
    elif lower_type == 'circular-ladder':
        assert (len(params) == 0)
        return networkx.circular_ladder_graph(count)
    elif lower_type == 'cycle':
        assert (len(params) == 0)
        return networkx.cycle_graph(count)
    elif lower_type == 'periodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, True)
    elif lower_type == 'nonperiodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, False)
    elif lower_type == 'hypercube':
        assert (len(params) == 0)
        return networkx.hypercube_graph(int(round(math.log(count, 2))))
    elif lower_type == 'star':
        assert (len(params) == 0)
        return networkx.star_graph(count - 1)
    elif lower_type == 'wheel':
        assert (len(params) == 0)
        return networkx.wheel_graph(count)
    elif lower_type == 'erdos-reyni':
        assert (len(params) == 1)
        return networkx.erdos_renyi_graph(count, float(params[0]))
    elif lower_type == 'watts-strogatz':
        assert (len(params) == 2)
        if int(params[0]) >= count / 2:
            k = int(count / 2 - 1)
        else:
            k = int(params[0])
        return networkx.connected_watts_strogatz_graph(count, k, int(params[1]))
    else:
        print "Unknown graph type {}".format(lower_type)
        assert False
def generate_graphs_with_constraints(n=100, k=2, m=2):
    if m < k:
        raise Exception(
            'm (number of constraints) less than k (number of clusters)')
    # G = nx.gnp_random_graph(n, math.pow(math.log(n),1.5)/n) #erdos renyi graph that is probably connected
    # G = nx.powerlaw_cluster_graph(n,int(np.log(n)), 3.0/int(np.log(n)) )
    G = nx.connected_watts_strogatz_graph(n,
                                          k=5,
                                          p=1.25 * np.log(n) / n,
                                          tries=100,
                                          seed=None)
    G = nx.convert_node_labels_to_integers(
        max(nx.connected_component_subgraphs(G),
            key=len))  #returns largest connected component
    constraints = {}
    for i, x in enumerate(
            np.random.choice(nx.number_of_nodes(G), size=m, replace=False)):
        if i < k:
            constraints[x] = i
        else:
            constraints[x] = np.random.randint(k)

    for (u, v) in G.edges():
        weight = np.random.rand()
        G.edge[u][v]['weight'] = weight
        G.edge[v][u]['weight'] = weight

    #make constraint edges full connected:
    # for con in constraints:
    #     for v in G.nodes():
    #         if con!=v:
    #             if np.random.rand() < 1:
    #                 G.add_edge(con, v,{'weight':1})
    return G, constraints
Example #11
0
def gen_graph(num_min, num_max, g_type, path, i, n_type='uniform'):
    cur_n = random.randint(num_max - num_min + 1) + num_min
    if g_type == 'erdos_renyi':
        g = nx.erdos_renyi_graph(n=cur_n, p=0.15)
    elif g_type == 'powerlaw':
        g = nx.powerlaw_cluster_graph(n=cur_n, m=4, p=0.05)
    elif g_type == 'small-world':
        g = nx.connected_watts_strogatz_graph(n=cur_n, k=8, p=0.1)
    elif g_type == 'barabasi_albert':
        g = nx.barabasi_albert_graph(n=cur_n, m=4)

    if n_type != 'uniform':
        if n_type == 'random':
            weights = {}
            for node in g.nodes():
                weights[node] = random.uniform(0, 1)
        else:
            degree = nx.degree_centrality(g)
            maxDegree = max(dict(degree).values())
            weights = {}
            for node in g.nodes():
                weights[node] = degree[node] / maxDegree
        nx.set_node_attributes(g, weights, 'weight')

    path = '%s/%s-%s' % (path, str(num_min), str(num_max))
    if not os.path.exists(path):
        os.mkdir(path)

    nx.write_gml(g, '%s/g_%s' % (path, str(i)))
    def __init__(self,
                 in_channel,
                 out_channel,
                 n=32,
                 k=4,
                 p=0.75,
                 m=1,
                 stride=2,
                 wire_def=None,
                 graph_mode='ws',
                 is_training=True,
                 name=None):
        self.in_channel = in_channel
        self.out_channel = out_channel
        self.stride = stride
        self.is_training = is_training
        self.name = name

        if wire_def is not None:
            tf.logging.info('Load graph from {}'.format(wire_def))
            self.G = nx.read_adjlist(wire_def,
                                     create_using=nx.DiGraph(),
                                     nodetype=int)
        else:
            if graph_mode == 'ws':
                self.G = nx.connected_watts_strogatz_graph(n, k, p)
            elif graph_mode == 'er':
                self.G = nx.erdos_renyi_graph(n, p, directed=True)
            elif graph_mode == 'ba':
                self.G = nx.barabasi_albert_graph(n, m)
            self.G = nx.DiGraph(self.G.edges)
        self.rev_G = self.G.reverse()
Example #13
0
def createGraph(gtype, n, p, ppitype):
    if (gtype == 'ER'):
        return nx.erdos_renyi_graph(n, p)
    elif (gtype == 'BA'):
        return nx.barabasi_albert_graph(n, int(p * n))
    elif (gtype == 'WS'):
        return nx.connected_watts_strogatz_graph(n, 8, p)
    elif (gtype == 'GEO'):
        return graphGen.geoGraphP(n, 3, p)
    elif (gtype == 'VZ'):
        # Vazquez recommends p = 0.1, q = 0.7
        # Gibson suggests p = 0.24, q = 0.887
        qmap = {0.1: 0.7, 0.24: 0.887}
        assert (p in qmap.keys())
        return graphGen.VazquezGraph(n, p, qmap[p])
    elif (gtype == 'EV'):
        qmap = {0.1: 0.7, 0.24: 0.887}
        assert (p in qmap.keys())
        return graphGen.EVGraph(n, p, qmap[p], n // 5, 0.8)
    elif (gtype == 'SL'):
        # values from Sole paper
        return graphGen.SoleGraph(n, 0.53, 0.06)
    elif (gtype == 'PPI'):
        return ppiGen.ppiGraph(n, ppitype)
    else:
        raise ValueError('Invalid graph type')
Example #14
0
def load():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p",
                        "--dump-pcap",
                        help="Dumps pcap of traffic to stdout",
                        action="store_true")
    parser.add_argument("-i", "--input-file", help="JSON input file")
    parser.add_argument(
        "-n",
        "--number",
        help="Number of nodes to generate (if no input file is given)",
        type=int,
        default=5)
    parser.add_argument(
        "-c",
        "--connectedness",
        help=
        "Connectedness [0.2, 1.0) of the network (if now input file is given)",
        type=float,
        default=0.75)
    args = parser.parse_args()
    if (args.input_file):
        mesh = load_mesh(args.input_file)
    else:
        mesh = nx.connected_watts_strogatz_graph(
            args.number, int(args.number * args.connectedness),
            args.connectedness)
    return mesh, args
    def generate_patches_2d_small_world(self):
        # I will generate a small world network graph using this tool from networkx
        # the problem is that I need a graph with Patch nodes while this gives me a graph
        # with tuple nodes, so I need to make a conversion
        sw_graph = nx.connected_watts_strogatz_graph(self.nr_patches, int(math.sqrt(self.nr_patches)), .1)

        # will use this dict to later build the edges in my new graph
        sw_patches = {}
        i = 0
        for sw_node in sw_graph.nodes():
            i += 1
            patch = self.generate_patch(id=i, pos=sw_node)
            sw_patches[sw_node] = patch
            self.graph.add_node(patch)
            self.patches.append(patch)

        # now build the edges in our graph using the small world graph (sw_graph)
        for sw_node, patch in sw_patches.items():
            for sw_friend in sw_graph[sw_node]:
                friend_patch = sw_patches[sw_friend]
                self.graph.add_edge(patch, friend_patch)

        # now we need to generate the positions of the nodes on the image
        positions = nx.spring_layout(self.graph, scale=100)
        for node in self.graph:
            node.pos = positions[node]

        self.set_node_degrees()
Example #16
0
    def __init__(self, upper=1, mu=1/2, sigma=np.sqrt(1/2) / 2, thresh=0.95, prob_adopted=0.5, neighbor_threshold=5/100, sim_thresh=0.15, product_adoption_jitter=np.sqrt(1/2) / 12, n_init=20, path='runs/'):
        self.lower = 0
        self.upper = upper
        self.mu = mu
        self.sigma = sigma
        self.thresh = thresh
        self.prob_adopted = prob_adopted
        self.neighbor_threshold = neighbor_threshold
        self.sim_thresh = sim_thresh
        self.product_adoption_jitter = product_adoption_jitter
        self.product_dist = stats.truncnorm((self.lower - self.mu)/self.sigma, (self.upper - self.mu)/self.sigma, loc=self.mu, scale=self.sigma)
        self.n_init = n_init
        self.path = path
        self.ims = []

        if not os.path.exists(self.path + 'graphs/'):
            os.makedirs(self.path + 'graphs/')
        if not os.path.exists(self.path + 'frames/'):
            os.makedirs(self.path + 'frames/')
        if not os.path.exists(self.path + 'gifs/'):
            os.makedirs(self.path + 'gifs/')

        self.G = nx.connected_watts_strogatz_graph(self.n_init, 3, np.random.rand())
        products = dict([(i, self.random_product()) for i in range(self.n_init)])
        thresholds = dict([(i, np.random.rand()) for i in range(self.n_init)])
        schellings = dict([(i, self.random_schelling()) for i in range(self.n_init)])

        nx.set_node_attributes(self.G, products, 'apt_markakis')
        nx.set_node_attributes(self.G, thresholds, 'threshold')
        nx.set_node_attributes(self.G, schellings, 'schelling')

        nx.write_graphml(self.G, self.path + 'graphs/m0.graphml')
def generate_multi_level_graph(n, w_min, w_max, levels, graph_type, params):
    graph = None
    if graph_type == "watts-strogatz":
        graph = nx.connected_watts_strogatz_graph(n, params['neighbors'],
                                                  params['prob'],
                                                  params['tries'])
    elif graph_type == "erdos-renyi":
        graph = nx.erdos_renyi_graph(n, params['prob'], params['seed'])
    elif graph_type == "barabasi-albert":
        graph = nx.barabasi_albert_graph(n, params['m'])

    terminal_sets = list()
    num_nodes = len(list(graph.nodes))
    num_edges = len(list(graph.edges))
    print('Graph generated has ' + str(num_nodes) + ' nodes and ' +
          str(num_edges))
    for node in list(graph.nodes):
        graph.nodes[node]['weight'] = random.randint(w_min, w_max)
    terminals = list(graph.nodes)
    for i in range(levels):
        num_n = int((num_nodes * 0.2) / (i + 2))
        terminals = random.sample(terminals, num_n)
        terminals.sort()
        terminal_sets.append(terminals)
    terminal_sets.reverse()
    for i in range(levels):
        print('Level ' + str(i) + ' has ' + str(len(terminal_sets[i])) +
              ' terminals')
    return graph, terminal_sets
Example #18
0
def smallworld(n, rewire=0.3, seed=35):
    """Return a watts-strogatz small world graph.

    Mimics the layout of smallworld_topo.SmallWorldTopology.
    """
    graph = nx.connected_watts_strogatz_graph(n, min(4, n/3), rewire, seed=seed)
    return from_graph(graph)
def genNet(n, k=4, pRewire=.1, type='grid'):
	# create net
	if type == 'grid': #wrap the grid
		net = nx.grid_2d_graph(int(n**.5), int(n**.5), periodic=True)
		#net = nx.grid_2d_graph(3, 3, periodic=True)
		#net = nx.grid_2d_graph(2, 2, periodic=False)
		#plotNet(net)
		#print(len(net.edges()))
		#assert(0)
		# rewire
		numRewired = 0
		#while numRewired < (pRewire * nx.number_of_nodes(net)):
		while numRewired < 1:
			tries = 0
			while tries < 100:
				tries = tries + 1
				#print([numRewired, pRewire * nx.number_of_nodes(net), tries])
				v1 = random.choice(net.nodes())
				v2 = random.choice(net.nodes())
				if not( net.has_edge(v1,v2) or v1==v2 or len(net.neighbors(v1)) <= 1): #net.neighbors is sometimes (often?) a blank set, changed so v1 needs 2 nb
					#print net.neighbors(v1)
					break
			v1Neighbors = net.neighbors(v1)
			#print v1Neighbors
			#print v1
			#print v2
			#print(len(net.edges()))
			tobeDeleted = random.choice(v1Neighbors)
			net.remove_edge(v1, tobeDeleted)
			#print(len(net.edges()))
			#print([v1, tobeDeleted, v2])
			net.add_edge(v1, v2)
			numRewired = numRewired + 1
			#plotNet(net)
			#assert(0)
		return net, nx.to_numpy_matrix(net, dtype=np.float)

	elif type == 'smallworld':
		#net = nx.connected_watts_strogatz_graph(n, k, .15)
		net = nx.connected_watts_strogatz_graph(n, k, pRewire)
		return net, nx.to_numpy_matrix(net, dtype=np.float)  
	elif type == 'pref':
		net = nx.barabasi_albert_graph(n, 2)
		return net, nx.to_numpy_matrix(net, dtype=np.float)
	elif type == 'ER':
		#net = nx.erdos_renyi_graph(n, .006)
		targetDegree = 4.
		nEdgesPossible = ((n*n)-n)/2.
		pEdge = (n * targetDegree) / (2. * nEdgesPossible)
		assert(pEdge <= 1)

		# spare networks will likely be disconnected, so try a bunch
		tries = 100
		while tries > 0:
			net = nx.erdos_renyi_graph(n, pEdge)
			if nx.number_connected_components(net) > 1:
				tries = tries - 1
			else:
				break
		return net, nx.to_numpy_matrix(net, dtype=np.float)
Example #20
0
def test_ws_clustering():
    N = 1000
    k = 8
    ps = np.linspace(0, 1, 20)
    n_trials = 40
    p_to_Gs = {
        p:
        [nx.connected_watts_strogatz_graph(N, k, p) for _ in range(n_trials)]
        for p in ps
    }
    expected_clusterings = []
    actual_clusterings = []
    for p, Gs in p_to_Gs.items():
        expected_clusterings.append(ws_clustering(k, p))
        actual_clusterings.append([nx.average_clustering(G) for G in Gs])

    quartiles = np.quantile(actual_clusterings, (.25, .75),
                            axis=1,
                            interpolation='midpoint')
    mean_actual = np.mean(actual_clusterings, axis=1)
    name = f'Comparison of Clustering Estimation vs Reality\nk={k}'
    plt.title(name)
    plt.plot(ps, expected_clusterings)
    plt.plot(ps, mean_actual)
    plt.fill_between(ps, quartiles[0], quartiles[1], alpha=.4, color='orange')
    plt.legend(('Expected', f'Actual (Avg over {n_trials} trials)'))
    plt.xlabel('p')
    plt.ylabel('Clustering')
    plt.savefig(name.replace('\n', ' ') + '.png', format='png')
Example #21
0
def gerar_grafo(num_vertices):
    G = nx.connected_watts_strogatz_graph(num_vertices,25, 0.5)
    #G = nx.complete_graph(num_vertices)
    a = G.edges()
    matriz = []
    for i in range(num_vertices):
        matriz.append([0]*num_vertices)
    for v1,v2 in a:
        n = random.randint(10,100)
        matriz[v1][v2] = n
        matriz[v2][v1] = n
        #atribuição do peso no grafo
        G.edges[v1,v2]['weight']=n
    k = kr()
    A = prim.Graph(num_vertices)
    A.graph = matriz
    
    mst = k.kruskal(G)
    mst_prim = A.primMST()
    

    plt.show()
    nx.draw(G,node_size=5,alpha=1,node_color="black", edge_color = "#1880C7", with_labels=False)
    plt.axis('equal')
    plt.savefig('Grafo.png')
    plt.show()
    plt.figure(figsize=(8,8))
    nx.draw(mst_prim,node_size=5,alpha=1,node_color="black", edge_color = "#1880C7", with_labels=False)
    plt.axis('equal')
    plt.savefig('mst_prim.png')
    plt.show()
    nx.draw(mst,node_size=5,alpha=1,node_color="black", edge_color = "#1880C7", with_labels=False)
    plt.axis('equal')
    plt.savefig('mst_kruskal.png')
    plt.show()
Example #22
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]')
Example #23
0
 def __init__(self, M, fully_connected=False):
     # M: Number of nodes.
     self._num_nodes = M
     if fully_connected:
         self._graph = nx.complete_graph(M)
     else:
         self._graph = nx.connected_watts_strogatz_graph(M, 3, 0.6)
Example #24
0
def genG(n,k,p,tries=1000, seed=None, graphtype="sw"):
    if graphtype=="sw":
        g=nx.connected_watts_strogatz_graph(n,k,p,tries,seed) # networkx graph
        random.seed(randomseed)                               # bug in nx, random seed needs to be reset    
        a=np.array(nx.adjacency_matrix(g).todense())          # adjacency matrix
    else: # erdos-renyi... TODO fix up
        g=nx.erdos_renyi_graph(n,p)
    return g, np.array(a, dtype=np.int32)
Example #25
0
def generate_SM_graph_with_trust(N, p, k, trust_list, filename):
    N_VALS = len(trust_list)
    G = nx.connected_watts_strogatz_graph(N, k, p)
    for (u, v) in G.edges_iter():
        val = random.randint(0, N_VALS - 1)
        G.edge[u][v]['t'] = trust_list[val]

    nx.write_edgelist(G, filename, '#', '\t', True, 'utf-8')
Example #26
0
def generate_SM_graph_with_trust(N, p, k, trust_list, filename):
    N_VALS = len(trust_list)
    G = nx.connected_watts_strogatz_graph(N, k, p)
    for (u,v) in G.edges_iter():
        val = random.randint(0,N_VALS-1)
        G.edge[u][v]['t'] = trust_list[val]
        
    nx.write_edgelist(G, filename, '#', '\t', True, 'utf-8')
Example #27
0
def setup(
        network='random',  # ['complete', 'random', 'Watts-Strogatz', 'connected caveman', 'Barabasi-Albert'] 
        n_agents=40,  # number of agents 
        deg=4,  # number of connections for each agent
        n_beliefs=25,  # number of knowledge graph elements each agent has
        n_concepts=30):
    """
    Generates the initial conditions of the simulation

    Returns
    -------
    g: networkx graph
        primary graph represents the semantic network,
        each individual (node) has an attribute 'M' representing their semantic network

    all_beliefs: an array of tuples, which represents all edges anywhere in the semantic
        network network of any individual. Does not include edges that could be part of the
        semantic network (because they are present in a complete graph with `n_concepts`, 
        but were not selected).
    """
    np.random.seed()

    connected = False
    while not connected:
        if network == 'complete':
            g = nx.complete_graph(n=n_agents)
        elif network == 'random':
            g = nx.gnm_random_graph(n=n_agents, m=int(n_agents * deg / 2))
        elif network == 'random regular':
            g = nx.random_regular_graph(d=deg, n=n_agents)
        elif network == 'Watts-Strogatz':
            g = nx.connected_watts_strogatz_graph(n=n_agents, k=deg,
                                                  p=.02)  # valid for even deg
        elif network == 'connected caveman':
            g = nx.connected_caveman_graph(l=int(n_agents / deg), k=deg + 1)
        elif network == 'Barabasi-Albert':
            g = nx.barabasi_albert_graph(n=n_agents, m=int(
                deg /
                2))  # approximates deg for large n_agents, when deg is even.
        else:
            raise ValueError('%s is not a valid network name' % network)

        connected = nx.is_connected(g)

    # give starting information
    nx.set_node_attributes(
        g,
        name='M',  # M for mind
        values={i: nx.gnm_random_graph(n_concepts, n_beliefs)
                for i in g})

    beliefs = np.unique([
        tuple(sorted(belief)) for agent in g
        for belief in g.nodes[agent]['M'].edges()
    ],
                        axis=0)
    return g, beliefs
def compute_random_graph(nodes, edges, g):

    degrees = sum(g.degree().values())
    avg_degree = (float(degrees) / float(nodes))
    try:
        return nx.connected_watts_strogatz_graph(nodes, int(avg_degree), 0.5)
    except nx.NetworkXPointlessConcept:
        assert (edges == (nodes - 1))
        return g
Example #29
0
 def generate_small_world_graph(output_dir, n_nodes, k_neighbors, p_edge_modify, seed=123, feature_dim=None):
     graph = nx.connected_watts_strogatz_graph(n=n_nodes, k=k_neighbors, p=p_edge_modify, seed=seed)
     features = None
     if feature_dim is not None:
         assert type(feature_dim) == int, "feature_dim must be None or int type"
         features = FullySynthetic.random_features((n_nodes, feature_dim))
     if output_dir is not None:
         FullySynthetic.save_graph(output_dir, graph, features)
     return graph, features
Example #30
0
def generate_watts_strogatz_graph(n, k, p, seed=123):
    g = nx.connected_watts_strogatz_graph(n, k, p, tries=100, seed=seed)
    nx.set_edge_attributes(g, None, 'weight')
    for u, v, weight in g.edges.data('weight'):
        if g[v][u]['weight'] is None:
            g[u][v]['weight'] = random.randint(1, 15)
        else:
            g[u][v]['weight'] = g[v][u]['weight']
    return g
Example #31
0
def random_graphs():
    print("Random graphs")
    print("fast GNP random graph")
    G = nx.fast_gnp_random_graph(n=9, p=0.4)
    draw_graph(G)
    print("GNP random graph")
    G = nx.gnp_random_graph(n=9, p=0.1)
    draw_graph(G)
    print("Dense GNM random graph")
    G = nx.dense_gnm_random_graph(n=19, m=28)
    draw_graph(G)
    print("GNM random graph")
    G = nx.gnm_random_graph(n=11, m=14)
    draw_graph(G)
    print("Erdős Rényi graph")
    G = nx.erdos_renyi_graph(n=11, p=0.4)
    draw_graph(G)
    print("Binomial graph")
    G = nx.binomial_graph(n=45, p=0.4)
    draw_graph(G)
    print("Newman Watts Strogatz")
    G = nx.newman_watts_strogatz_graph(n=9, k=5, p=0.4)
    draw_graph(G)
    print("Watts Strogatz")
    G = nx.watts_strogatz_graph(n=9, k=2, p=0.4)
    draw_graph(G)
    print("Watts Strogatz")
    G = nx.watts_strogatz_graph(n=9, k=2, p=0.4)
    draw_graph(G)
    print("Connected Watts Strogatz")
    G = nx.connected_watts_strogatz_graph(n=8, k=2, p=0.1)
    draw_graph(G)
    print("Random Regular Graph")
    G = nx.random_regular_graph(d=2, n=9)
    draw_graph(G)
    print("Barabasi Albert Graph")
    G = nx.barabasi_albert_graph(n=10, m=2)
    draw_graph(G)
    print("Powerlow Cluster Graph")
    G = nx.powerlaw_cluster_graph(n=10, m=2, p=0.2)
    draw_graph(G)
    print("Duplication Divergence Graph")
    G = nx.duplication_divergence_graph(n=10, p=0.2)
    draw_graph(G)
    print("Random lobster Graph")
    G = nx.random_lobster(n=10, p1=0.2, p2=0.8)
    draw_graph(G)
    print("Random shell Graph")
    constructor = [(10, 20, 0.8), (20, 40, 0.8)]
    G = nx.random_shell_graph(constructor)
    draw_graph(G)
    print("Random Powerlow Tree")
    G = nx.random_powerlaw_tree(n=24, gamma=3)
    draw_graph(G)
    print("Random Powerlow Tree Sequence")
    G = nx.random_powerlaw_tree(n=13, gamma=3)
    draw_graph(G)
Example #32
0
 def make_connected_WS_graph(self):
     self.G = nx.connected_watts_strogatz_graph(self.n, self.k, self.p)
     #         lam = nx.laplacian_spectrum(G)
     #         print(nx.adjacency_matrix(G))
     #         print (number_of_nodes(G))
     #         (nx.degree(G))
     # print(self.G)
     self.A = np.array(nx.adjacency_matrix(self.G).todense())  # 隣接行列
     self.weight_martix()
def compute_random_graph(nodes, edges, g):

    degrees = sum(g.degree().values())
    avg_degree = (float(degrees)/float(nodes))
    try:
        return nx.connected_watts_strogatz_graph(nodes, int(avg_degree), 0.5)
    except nx.NetworkXPointlessConcept:
        assert (edges == (nodes - 1))
        return g
Example #34
0
def generate_graph_with_bridges(n, sem):
    G = nx.connected_watts_strogatz_graph(n, 4, 0.5)
    G2 = nx.connected_watts_strogatz_graph(n, 4, 0.5)
    G = nx.disjoint_union(G, G2)
    i = 1
    for (e1, e2) in G.edges():
        G.edges[e1, e2].update(R=random.randint(1, 5), no=i, sem=0)
        i += 1
    node = random.randint(0, n - 1)
    node2 = random.randint(0, n - 1)
    while node == node2:
        node2 = random.randint(0, n - 1)
    G.add_edge(node, 2 * n - 1 - node, R=0, no=i, sem=sem)
    G.add_edge(node2,
               2 * n - 1 - node2,
               R=random.randint(1, 5),
               no=i + 1,
               sem=0)
    return G
Example #35
0
 def createGraph(gtype, n, p):
     if (gtype == 'ER'):
         return nx.erdos_renyi_graph(n, p)
     elif (gtype == 'BA'):
         return nx.barabasi_albert_graph(n, int(p * n))
     elif (gtype == 'WS'):
         return nx.connected_watts_strogatz_graph(n, 4, p)
     elif (gtype == 'GEO'):
         return gg.geoGraphP(n, 3, p)
     else:
         raise ValueError('Invalid graph type')
Example #36
0
def test_lattice_reference():
    G = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
    Gl = lattice_reference(G, niter=1, seed=rng)
    L = nx.average_shortest_path_length(G)
    Ll = nx.average_shortest_path_length(Gl)
    assert_true(Ll > L)

    assert_raises(nx.NetworkXError, lattice_reference, nx.Graph())
    assert_raises(nx.NetworkXNotImplemented, lattice_reference, nx.DiGraph())

    H = nx.Graph(((0, 1), (2, 3)))
    Hl = lattice_reference(H, niter=1)
Example #37
0
def test_random_reference():
    G = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
    Gr = random_reference(G, niter=1, seed=rng)
    C = nx.average_clustering(G)
    Cr = nx.average_clustering(Gr)
    assert_true(C > Cr)

    assert_raises(nx.NetworkXError, random_reference, nx.Graph())
    assert_raises(nx.NetworkXNotImplemented, random_reference, nx.DiGraph())

    H = nx.Graph(((0, 1), (2, 3)))
    Hl = random_reference(H, niter=1, seed=rng)
Example #38
0
def generate_network(pathwaysNum, genesNum, connNeighboors, connProbability):
    pathways = []
    for n in range(0, pathwaysNum):
        pathway = nx.connected_watts_strogatz_graph(genesNum, connNeighboors,
                                                    connProbability)
        [pathway.add_node(x) for x in range(genesNum)]
        # Pathways are initialized as independant Watts-Strogatz networks
        mapping = dict(
            zip(pathway.nodes(), [x+genesNum*n for x in pathway.nodes()]))
        pathway = nx.relabel_nodes(pathway, mapping)
        pathways.append(pathway)
    PPI = nx.union_all(pathways)
    return PPI
Example #39
0
    def get_graph(self):

        log.debug("Constructing Watts-Strogatz SW lattice with k=%s and rewiring %s", self.lattice_coordination_number, self.rewiring)
        graph = nx.connected_watts_strogatz_graph(self.simconfig.popsize, self.lattice_coordination_number, self.rewiring)

        # now convert the resulting graph to have simple nodenames to use as keys
        # We need to retain the original nodenames, because they're tuples which represent the position
        # of the node in the lattice.  So we first store them as attribution 'pos' and then convert
        for nodename in graph.nodes():
            graph.node[nodename]['pos'] = nodename

        g = nx.convert_node_labels_to_integers(graph)
        return g
Example #40
0
	def __init__(self, num_nodes, node_degree, rewire_prob, tries=100, seed=None):
		BaseGraph.__init__(self)
		self.num_nodes = num_nodes
		self.node_degree = node_degree
		self.rewire_prob = rewire_prob
		self.tries = tries
		self.seed = seed
		self.structure = nx.connected_watts_strogatz_graph(
			self.num_nodes,
			self.node_degree,
			self.rewire_prob,
			self.tries,
			self.seed
		)
Example #41
0
def smallworld(G):
    n = G.number_of_nodes()
    d=  nx.average_degree_connectivity(G)
    c = sum(i[1] for i in d.items())
    c0 = 0.75*(c-2)/(c-1)
    beta = random.uniform(0.01,0.1)
    try:
        SG= nx.connected_watts_strogatz_graph(n,int(c),beta)
        plot(SG)
        c = ((1-beta)**3)*c0
        print 'Global Clustering: {0}\t'.format(str(c)),
        print 'Average path length : {0}\n'.format(str(nx.average_shortest_path_length(SG)))
    except:
        'Failed attempt to get connected small world graph..Try again!!!'
def init():
	global g, positions
    
	g = nx.connected_watts_strogatz_graph(n, l, p, tries=100, seed=None) #WS connected graph generator
	#g = nx.barabasi_albert_graph(n, l, seed=None)						 #BA graph generator (can be non-connected)
	critical = nx.betweenness_centrality(g)
	keynodes = critical.values()
	
	for nd in g.nodes_iter():
		if keynodes[nd]>0.43: 							#average value of ten highest bc over repeated iterations for WS
		#if keynodes[nd]<0.0001: 						#average value of ten highest bc over repeated iterations for BA
			g.node[nd]['state'] = rnd.choice([1, 2, 3, 4])
		else:
			g.node[nd]['state'] = 0 
	
	positions = nx.circular_layout(g)       #for WS networks
Example #43
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() ])
Example #44
0
def asp_and_cc_vs_p():
    N_NODES = 1000
    EPSILON = 0.01

    asp_and_cc_vs_p_dict = dict()
    average_shortest_path_length = []
    clustering_coefficient = []
    probability = []

    n_nodes = N_NODES
    prob = 0.0

    c0 = None
    l0 = None

    while prob <= 1:
        ws_graph = nx.connected_watts_strogatz_graph(n_nodes, 4, prob)  # Using networkx for finding the graph


        avg_shortest_path = nx.average_shortest_path_length(ws_graph)
        average_shortest_path_length.append(float("{0:.2f}".format(avg_shortest_path)))  # Store shortest path of the graph
        print 'avg. shortest path length: ' + str(float("{0:.2f}".format(avg_shortest_path)))

        probability.append(prob)  # Store probability
        print 'probability: ' + str(prob)

        cc = nx.average_clustering(ws_graph)
        clustering_coefficient.append(cc)  # Store clustering coefficient
        print 'clustering coefficient: ' + str(cc)

        if prob == 0.0:   #Only first iteration
            c0 = cc
            l0 = float("{0:.2f}".format(avg_shortest_path))


        prob += EPSILON


    asp_and_cc_vs_p_dict['probability'] = probability
    asp_and_cc_vs_p_dict['average_shortest_path_length'] = average_shortest_path_length
    asp_and_cc_vs_p_dict['clustering_coefficient'] = clustering_coefficient

    return asp_and_cc_vs_p_dict, c0, l0
    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]')
Example #46
0
    def __init__(self, num_switches=None):

        
        super(SmallWorldTopology, self).__init__()
        if not num_switches:
            num_switches = 8
        num_hosts=num_switches*4
        
        # build graphman graph
        graph = nx.connected_watts_strogatz_graph(num_switches, min(4, num_switches/3), float(0.3), seed=35)

        # Add switches
        for s in graph:
            log.debug("Added switch %x" % s)
            self.add_switch(s+1)

        # Add edges
        for s1, s2 in graph.edges():
            self.add_link(s1+1, s2+1)
                         
        # Add hosts
        hostoffset = num_switches+2
        for h in range(1,num_hosts+1):
            # Add host
            host = h + hostoffset
            self.add_host(host)

            # Connect to a "random" switch
            s = graph.nodes()[h % len(graph)]
            self.add_link(host,s+1)
        # Globally connected host
        # self.add_host(999)
        # for switch in graph:
        #     self.add_link(999, switch+1)


        self.finalize()
Example #47
0
def createGraph(gtype, n, p):
    if (gtype == 'ER'):
        return nx.erdos_renyi_graph(n, p)
    elif (gtype == 'BA'):
        return nx.barabasi_albert_graph(n, int(p * n))
    elif (gtype == 'WS'):
        return nx.connected_watts_strogatz_graph(n, 8, p)
    elif (gtype == 'GEO'):
        return graphGen.geoGraphP(n, 3, p)
    elif (gtype == 'VZ'):
        # Vazquez recommends p = 0.1, q = 0.7
        # Gibson suggests p = 0.24, q = 0.887
        qmap = {0.1:0.7, 0.24:0.887}
        assert(p in qmap.keys())
        return graphGen.VazquezGraph(n, p, qmap[p])
    elif (gtype == 'EV'):
        qmap = {0.1:0.7, 0.24:0.887}
        assert(p in qmap.keys())
        return graphGen.EVGraph(n, p, qmap[p], n//5, 0.8)
    elif (gtype == 'SL'):
        # values from Sole paper
        return graphGen.SoleGraph(n, 0.53, 0.06)
    else:
        raise ValueError('Invalid graph type')
Example #48
0
def test_graphtool_distance():
    G = nx.connected_watts_strogatz_graph(n=2000, k=4, p=0.02, tries=100, seed=None)
    print 'NX: %.3f'%average_all_pairs_shortest_path(G)
    print 'GT: %.3f'%average_all_pairs_shortest_path_GT(G)
    print 'NX sampling: %.3f'%average_all_pairs_shortest_path_estimate(G)
    print 'GT sampling: %.3f'%average_all_pairs_shortest_path_estimate_GT(G)
Example #49
0
#Erdos-Renyi
if False:
    G = nx.erdos_renyi_graph(100,.05) #(nodesize, p)

#Barabasi-Albert
if True:
    G = nx.barabasi_albert_graph(500,2) #(nodesize, m)

if False:
    G = nx.watts_strogatz_graph(500, 4, .3, seed=None)

if False:
    G = nx.davis_southern_women_graph()

if False:
    G = nx.connected_watts_strogatz_graph(500, 4, .3, seed=None)

#Graphs too big for me to run (Facebook requires 9GB of available RAM):
#G = nx.read_gexf("ER_random-1.gexf", node_type=int)
#G = nx.read_gexf("barabasi.gexf", node_type=int)
#G = nx.read_gexf("facebook_combined.gexf", node_type=int)
#G = nx.read_gexf("General_Relativity.gexf", node_type=int)

#Setting up the plot
cf = plt.figure(1, figsize=(8,8))
pos = nx.graphviz_layout(G)
ax = cf.add_axes((0,0,1,1))
for n in G:
    G.node[n]['draw'] = nx.draw_networkx_nodes(G,pos,nodelist=[n], with_labels=False,node_size=200,alpha=0.2,node_color='w')
plt.ion()
plt.show()
Example #50
0
def small_world_graph(n_cells, degree, rewiring_p, tries=100):
    g = nx.connected_watts_strogatz_graph(n_cells, degree, rewiring_p, tries)
    for e in g.edges():
        g[e[0]][e[1]]['weight'] = random.gammavariate(1.53, 350)
    return g
Example #51
0
def genG(n,k,p,tries=1000, seed=None):
    g=nx.connected_watts_strogatz_graph(n,k,p,tries,seed) # networkx graph
    a=np.array(nx.adjacency_matrix(g).todense())     # adjacency matrix
    return g, np.array(a, dtype=np.int32)
Example #52
0
def test_sigma():
    Gs = nx.connected_watts_strogatz_graph(100, 6, 0.1)
    Gr = nx.connected_watts_strogatz_graph(100, 6, 1)
    sigmas = sigma(Gs, niter=1, nrand=2)
    sigmar = sigma(Gr, niter=1, nrand=2)
    assert_true(sigmar < sigmas)
Example #53
0
def test_sigma():
    Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
    Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
    sigmas = sigma(Gs, niter=1, nrand=2, seed=rng)
    sigmar = sigma(Gr, niter=1, nrand=2, seed=rng)
    assert_true(sigmar < sigmas)
import os
import random
import networkx as nx
import matplotlib.pyplot as plt

n = 20000
d = 6
p = 0.4

G = nx.connected_watts_strogatz_graph(n, d, p)

edges = G.edges()[:]
random.shuffle(edges)
for edge in edges:
    print edge[0], edge[1], 1

"""
# draw graph
pos = nx.shell_layout(G)
print G.number_of_nodes()
print G.number_of_edges()
print G.edges()
nx.draw(G, pos)
# show graph
plt.show()
"""
Example #55
0
                  zip([G]*num_chunks,
                      [True]*num_chunks,
                      [None]*num_chunks,
                      node_chunks))

    # Reduce the partial solutions
    bt_c = bt_sc[0]
    for bt in bt_sc[1:]:
        for n in bt:
            bt_c[n] += bt[n]
    return bt_c

if __name__ == "__main__":
    G_ba = nx.barabasi_albert_graph(1000, 3)
    G_er = nx.gnp_random_graph(1000, 0.01)
    G_ws = nx.connected_watts_strogatz_graph(1000, 4, 0.1)
    for G in [G_ba, G_er, G_ws]:
        print("")
        print("Computing betweenness centrality for:")
        print(nx.info(G))
        print("\tParallel version")
        start = time.time()
        bt = betweenness_centrality_parallel(G)
        print("\t\tTime: %.4F" % (time.time()-start))
        print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
        print("\tNon-Parallel version")
        start = time.time()
        bt = nx.betweenness_centrality(G)
        print("\t\tTime: %.4F seconds" % (time.time()-start))
        print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
    print("")
Example #56
0
def generate_SM_graph(N, p, k, filename):
    G = nx.connected_watts_strogatz_graph(N, k, p, None)
    nx.write_edgelist(G, filename, '#', '\t', False, 'utf-8')    
Example #57
0
if match==0:
    deploy_traits_desired *= (np.random.rand()*match_margin + (1.0-match_margin))
    print "total traits, at least: \t", np.sum(np.sum(deploy_traits_desired))

# initialize robots
robots = initialize_robots(deploy_robots_init)

print "total robots, init: \t", np.sum(np.sum(deploy_robots_init))
print "total traits, init: \t", np.sum(np.sum(deploy_traits_init))


# -----------------------------------------------------------------------------#
# initialize graph

if not load_data:
    graph = nx.connected_watts_strogatz_graph(num_nodes, 3, 0.7)
else:
    graph = pickle.load(open(load_prefix+"graph.p", "rb"))

# get the adjencency matrix
adjacency_m = nx.to_numpy_matrix(graph)
adjacency_m = np.squeeze(np.asarray(adjacency_m))

if plot_graph:
    plt.axis('equal')
    fig1 = nxmod.draw_circular(deploy_traits_init, graph,linewidths=3)
    plt.show()
    plt.axis('equal')
    fig2  = nxmod.draw_circular(deploy_traits_desired, graph, linewidths=3)
    plt.show()
Example #58
0
	def __init__(self,N_agents,Ri=2,R=25,U=10,comm_error=0.1,\
		min_gain=lambda: 0.0001,agentClass=None,budget=1,silent=False,turns=1000,G=None,\
		generate_graph=False,selfishness=lambda: 0.5):
		self.silent = silent
		self.comm = MPI.COMM_WORLD
		self.mpi_size = self.comm.Get_size()
		self.rank = self.comm.Get_rank()

		if G is None:
			if self.rank == 0:
				if generate_graph:
					G = nx.connected_watts_strogatz_graph(N_agents,4,0.5)
				else:
					G = nx.cycle_graph(N_agents)
		self._G = self.comm.bcast(G,root=0)

		if agentClass is None:
			agentClass = Agent

		R = float(R) * N_agents
		self._N = N_agents  # Number of global agents
		self._Ri = float(Ri)
		self._R = float(R)
		self._U = float(U)
		self.budget = float(budget)
		self._turns = turns
		

		# number of agents for each worker
		base = np.floor(self._N / float(self.mpi_size))
		
		# hangover
		leftover = self._N % self.mpi_size

		sizes = np.ones(self.mpi_size)*base
		sizes[:leftover]+=1

		offsets = np.zeros(self.mpi_size)
		offsets[1:] = np.cumsum(sizes)[:-1]
		
		
		self.mpi_gather_sizes = sizes 
		self.mpi_gather_offsets = offsets

		start = offsets[self.rank]
		end = start + sizes[self.rank]
		agent_idxs = np.arange(start,end)
		
		self.local_agents = [agentClass(idx=i,R=R,
			s=max([0,min([0.99,selfishness()])]),
			# s=0.9,
			controller=self,
			min_gain=min_gain(),
			turns=turns) for i in agent_idxs]
		
		if not(self.silent):
			print "number of agents in rank {}:{}\n{}".format(self.rank,\
				len(self.local_agents),agent_idxs)
			

		for agent in self.local_agents:
			# print agent.min_gain,agent.s
			agent.k = randint(10)+1
			agent.budget=self.budget/self._N
			agent.alpha = 0.3
			agent.omega = 3+rand()
			# agent.nn = [agent.idx-1,(agent.idx+1)%self._N]
			agent.nn = self._G.neighbors(agent._idx)

			

		self._comm_error = comm_error
		
		

		self._I = []
		self._Pout = []
		self._Us = []
		self._Rg = []
		self._n = 0  # Number of steps we did
		self.is_constrained = True
		self._global_P = [1]
		self._global_dP_list = [1]
		self._global_dP = 0
		self.calc_global_dP = False
		self.globalGameState = {0:np.zeros(self._N,dtype=np.int8)}



		pass