def generate_waxman_network(number_of_node, probability): # create a new substrate network substrate_random_network = Net() number_of_nodes = number_of_node probability = probability # topology = nx.erdos_renyi_graph(number_of_nodes, probability, seed=None, directed=False) topology = nx.waxman_graph(number_of_nodes) network_create_counter = 0 while not nx.is_connected(topology): if network_create_counter >= 10000: break network_create_counter += 1 topology = nx.waxman_graph(number_of_nodes) for edge in topology.edges(): bw = random.randint(50, 100) substrate_random_network.init_bandwidth_capacity(edge[0], edge[1], bw) lt = random.uniform(1, 5) substrate_random_network.init_link_latency(edge[0], edge[1], lt) for node in topology.nodes(): cpu_capacity = random.randint(50, 100) substrate_random_network.init_node_cpu_capacity(node, cpu_capacity) substrate_random_network.pre_get_single_source_minimum_latency_path() substrate_random_network.update() return substrate_random_network
def test_waxman_graph(self): G=nx.waxman_graph(50,0.5,0.1) assert_equal(len(G),50) G=nx.waxman_graph(50,0.5,0.1,L=1) assert_equal(len(G),50) G=nx.waxman_graph(range(50),0.5,0.1) assert_equal(len(G),50)
def gen_topology(num_nodes, alpha, beta, L): graph = nx.waxman_graph(num_nodes, beta, alpha, L) while not nx.is_connected(graph): graph = nx.waxman_graph(num_nodes, beta, alpha, L) return graph
def test_waxman_graph(self): G = nx.waxman_graph(50, 0.5, 0.1) assert_equal(len(G), 50) G = nx.waxman_graph(50, 0.5, 0.1, L=1) assert_equal(len(G), 50) G = nx.waxman_graph(range(50), 0.5, 0.1) assert_equal(len(G), 50)
def generate_graph(n, beta): """ Make one Waxman graph. :param n: number of nodes in the graph :return: graph, value of MST """ # random Waxman graph from NetworkX g = nx.waxman_graph(n, beta) n = {i: d for i, d in g.nodes(data=True)} for node, p in g.nodes(data=True): if g.degree(node) > 0: continue else: d = [np.power(np.sum(np.power(np.array(p['pos']) - np.array(d['pos']), 2)), 0.5) if u != node else 1000. for u, d in g.nodes(data=True)] neighbor = np.argmin(np.array(d)) g.add_edge(node, neighbor) while not nx.is_connected(g): c = sorted(list(nx.connected_components(g)), key=lambda x: len(x)) s = c[0] mn = (None, None, 10000.) for sn in c[1]: d = [(np.power(np.sum(np.power(np.array(g.node[sn]['pos']) - np.array(g.node[u]['pos']), 2)), 0.5), u) for u in s] d.sort(key=lambda x: x[0]) if d[0][0] < mn[2]: mn = (sn, d[0][1], d[0][0]) g.add_edge(mn[0], mn[1]) # assign weight to each edge by its length (L2 distance between nodes) for u, v, d in g.edges(data=True): d['weight'] = np.power(np.sum(np.power(np.array(n[u]['pos']) - np.array(n[v]['pos']), 2)), 0.5) # calculate value of weighted minimum spanning tree m = nx.minimum_spanning_tree(g, weight='weight') mv = sum([d['weight'] for u, v, d in m.edges(data=True)]) return g, mv
class GraphType: BALANCED_TREE = ('Balanced tree', _balanced_tree) BARBELL = ('Barbell', lambda n: nx.barbell_graph(int(n*.4), int(n*.3))) CIRCULAR_LADDER = ('Circular ladder', lambda n: nx.circular_ladder_graph(int(n/2))) COMPLETE = ('Complete', lambda n: nx.complete_graph(int(n))) COMPLETE_BIPARTITE = ('Complete bipartite', lambda n: nx.complete_bipartite_graph(int(n*.6), int(n*.4))) CYCLE = ('Cycle', lambda n: nx.cycle_graph(int(n))) GRID = ('Grid', lambda n: nx.grid_graph([int(np.sqrt(n))]*2)) HYPERCUBE = ('Hypercube', _hypercube) LADDER = ('Ladder', lambda n: nx.ladder_graph(int(n/2))) LOBSTER = ('Lobster', lambda n: nx.random_lobster(int(n / (1 + .7 + .7*.5)), .7, .5)) LOLLIPOP = ('Lollipop', lambda n: nx.lollipop_graph(int(n/2), int(n/2))) PATH = ('Path', lambda n: nx.path_graph(int(n))) REGULAR = ('Regular', lambda n: nx.random_regular_graph(np.random.randint(10)*2, n)) SCALEFREE = ('Scale-free', lambda n: nx.scale_free_graph(int(n))) SHELL = ('Shell', lambda n: nx.random_shell_graph([(int(n*.1), int(n*.1), .2), (int(n*.3), int(n*.3), .8), (int(n*.6), int(n*.6), .5)])) STAR = ('Star', lambda n: nx.star_graph(int(n - 1))) WAXMAN = ('Waxman', lambda n: nx.waxman_graph(int(n))) WHEEL = ('Wheel', lambda n: nx.wheel_graph(int(n))) all = (BALANCED_TREE, BARBELL, CIRCULAR_LADDER, COMPLETE, COMPLETE_BIPARTITE, CYCLE, GRID, HYPERCUBE, LADDER, LOBSTER, LOLLIPOP, PATH, REGULAR, SCALEFREE, SHELL, STAR, WAXMAN, WHEEL)
def generate(self): waxman = nx.waxman_graph(self.nodes, self.alpha, self.beta, self.L, self.domain) self.nx_topology = nx.MultiDiGraph() self.nx_topology.clear() index = 0 nodes = [] for node in waxman.nodes(): #SS nodes.append(node+1) nodes.append(str(node+1)) self.nx_topology.add_nodes_from(nodes) for (n1, n2) in waxman.edges(): n1 = n1 + 1 n2 = n2 + 1 self.sip.update(str(index)) id_ = str(self.sip.hash()) #SSself.nx_topology.add_edge(n1, n2, capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_) self.nx_topology.add_edge(str(n1), str(n2), capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_) index = index + 1 self.sip.update(str(index)) id_ = str(self.sip.hash()) #self.nx_topology.add_edge(n2, n1, capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_) self.nx_topology.add_edge(str(n2), str(n1), capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_) index = index + 1
def wm_graph(n): G=nx.Graph() while True: G=nx.waxman_graph(n,0.55,0.55) if nx.is_connected(G): break return G.to_directed()
def generate_topology(self, num_nodes, type='path', **kwargs): r"""Generate the physical network's topology according to the structure type and number of nodes.""" assert type in ['path', 'waxman', 'random'] self.set_graph_attrs_data({'num_nodes': num_nodes, 'type': type}) if type == 'path': G = nx.path_graph(num_nodes) elif type == 'waxman': wm_alpha = kwargs.get('wm_alpha', 0.5) wm_beta = kwargs.get('wm_beta', 0.2) while True: G = nx.waxman_graph(num_nodes, wm_alpha, wm_beta) if nx.is_connected(G): break self.set_graph_attrs_data({'wm_alpha': num_nodes, 'wm_beta': type}) elif type == 'random': random_prob = kwargs.get('random_prob', 0.5) self.set_graph_attrs_data({'random_prob': random_prob}) G = nx.erdos_renyi_graph(num_nodes, random_prob, directed=False) while True: G = nx.erdos_renyi_graph(num_nodes, random_prob, directed=False) if nx.is_connected(G): break else: raise NotImplementedError self.__dict__['_node'] = G.__dict__['_node'] self.__dict__['_adj'] = G.__dict__['_adj']
def waxman_topology(self): """Generation of the Waxman graph topology Parameters: nnode: int, number of nodes Returns: self.g: nx.Graph(), Waxman graph topology self.length: np.array, lengths of edges """ # graph topology construction self.g = nx.waxman_graph(n=30, alpha=1, beta=0.25, L=1.0, domain=(0, 0, 1, 1), seed=0) self.length = np.zeros(self.g.number_of_edges()) for i, edge in enumerate(self.g.edges()): self.length[i] = distance.euclidean(self.g.nodes[edge[0]]["pos"], self.g.nodes[edge[1]]["pos"]) # right hand side construction dummy_path = " " self.forcing = forcing_generation(self, dummy_path) return self.g, self.length, self.forcing
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. G = nx.waxman_graph(50, 0.5, 0.1, metric=l1dist) assert len(G) == 50
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y)) G = nx.waxman_graph(50, 0.5, 0.1, metric=dist) assert_equal(len(G), 50)
def waxman(n, alpha=0.4, beta=0.1): g = None for i in range(MAX_ITERATION): g = nx.waxman_graph(n, alpha, beta) if (nx.algorithms.components.is_connected(g) == True): break else: g = None return g
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. dist = l1dist G = nx.waxman_graph(50, 0.5, 0.1, metric=dist) assert_equal(len(G), 50)
def waxman(n, alpha=0.4, beta=0.1): g = None for i in range(MAX_ITERATION): g = nx.waxman_graph(n, alpha, beta) if nx.algorithms.components.is_connected(g) == True: break else: g = None return g
def topo_wax(nodes): bws = [1,2,3,4,5,6,7,8,9] network = nx.waxman_graph(nodes,0.5,0.1) # alpha=0.4, beta=0.1 g = nx.Graph() g.add_nodes_from(network.nodes()) for link in network.edges(): bw = random.choice(bws) g.add_edge(link[0],link[1],{'weight':bw}) g.add_edge(link[1],link[0],{'weight':bw}) return g
def waxman( n_nodes: int, *, alpha: float = 0.4, beta: float = 0.2, seed: Optional[int] = None, ) -> DAG: """Create a Waxman random graph, converted to DAG.""" if seed is not None: random.seed(seed) return _make_dag(DAG.from_other(nx.waxman_graph(n=n_nodes, alpha=alpha, beta=beta)))
def make_graph(self): G = nx.waxman_graph(self.n_nodes, self.alpha, self.beta, domain=self.domain) #G = nx.cycle_graph(self.n_nodes) #G = nx.cycle_graph(self.n_nodes) G = self.connect_graph(G) G = self.reduce_degree(G) #On réduit le degré si besoin #G = nx.circular_ladder_graph(self.n_nodes, create_using=None) #G = nx.connected_watts_strogatz_graph(self.n_nodes, 2, 0.2, tries=100, seed=None) return G
def GeneraGrafoRandom(kind, seed=None, dim=60, prob=0.09): if kind not in graph_kind: print "Unknown graph type" exit() if kind == "caveman": if dim <= 15: g = nx.relaxed_caveman_graph(dim, 10, p=prob, seed=seed) else: g = nx.relaxed_caveman_graph(10, dim, p=prob, seed=seed) if kind == "waxman": g = nx.waxman_graph(dim, alpha=1.05, beta=prob) if kind == "erdos": g = nx.gnp_random_graph(dim, p=prob, seed=seed) if kind == "barabasi": g = nx.barabasi_albert_graph(dim, m=prob, seed=seed) rapportoespansione = [False] * 75 + [True] * 25 maxinterfacce = 8 g.remove_nodes_from(nx.isolates(g)) nx.set_node_attributes(g, 'n_interf', 0) nx.set_edge_attributes(g, 'ID', '') for n, d in g.nodes_iter(data=True): if kind == "waxman": del d['pos'] MenoInterf = random.choice(rapportoespansione) if (MenoInterf == False): d['n_interf'] = 1 else: d['n_interf'] = random.randint(1, min(g.degree(n), maxinterfacce)) i = 0 for u, v, d in g.edges(data=True): d['ID'] = 'e' + str(i) d['weight'] = float(np.random.uniform(1.0, 1.1)) i += 1 if nx.is_connected(g) == False: g = GeneraGrafoRandom(kind=kind, seed=seed, dim=dim, prob=prob) mapping = {} for x in g.nodes(): mapping[x] = str(x) g = nx.relabel_nodes(g, mapping, copy=False) return g
def geometric_graphs(): print("Random geometric graphs") G = nx.random_geometric_graph(20, 0.1) draw_graph(G) n = 20 p = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} G = nx.random_geometric_graph(n, 0.2, pos=p) draw_graph(G) print("Geographical threshold graph") n = 10 w = {i: random.expovariate(1.0) for i in range(n)} G = nx.geographical_threshold_graph(n, 30, weight=w) draw_graph(G) print("Waxman graph") G = nx.waxman_graph(27) draw_graph(G) print("Navigable small world graph") G = nx.navigable_small_world_graph(7) draw_graph(G)
def __init__(self, num_switches=5,seed=100): super(WaxmanTopology, self).__init__() num_hosts_per_switch = 2 # Needed so that subsequent calls will generate the same graph random.seed(seed) num_hosts = num_switches*num_hosts_per_switch # build waxman graph wax = nx.waxman_graph(num_switches,.9,.9) # Add switches for s in wax.nodes(): self.add_node(s+1, Node(is_switch=True)) # Add edges for s1, s2 in wax.edges(): print "new edge" self.add_edge(s1+1, s2+1) # Add hosts hostoffset = num_switches+2 for s in wax: # Add host host_base = num_hosts_per_switch*s + hostoffset for host in range(0, num_hosts_per_switch): self.add_node(host_base + host, Node(is_switch=False)) self.add_edge(host_base + host, s+1) # # Globally connected host # self.add_host(9999) # for switch in wax: # self.add_link(9999, switch) # f = open('/home/openflow/workspace/foo.log', 'w') # f.write('hosts: %d\n' % len(self.hosts())) # f.close() # assert(False) self.enable_all()
def make_graph(self, n, c, p, t): """ NetworkXグラフを生成する. :param n: ノード数 :param e: エッジ数(拠点数) :param c: ノードからの接続リンク数 :param p: 確率 :param t: トポロジタイプ :return: NetworkXグラフオブジェクト :rtype: networkx.graph """ if t == 'BA': g = nx.barabasi_albert_graph(n, c) if t == 'powerlaw_cluster': g = nx.powerlaw_cluster_graph(n, c, p) if t == 'gnm_random': g = nx.gnm_random_graph(n,n*c+1, directed=True) if t == 'waxman': g = nx.waxman_graph(n,beta=0.3) if t == 'random_regular': g = nx.random_regular_graph(c,n) return g
def __init__(self, num_switches=5, seed=100): super(WaxmanTopology, self).__init__() num_hosts_per_switch = 2 # Needed so that subsequent calls will generate the same graph random.seed(seed) num_hosts = num_switches * num_hosts_per_switch # build waxman graph wax = nx.waxman_graph(num_switches, .9, .9) # Add switches for s in wax.nodes(): self.add_node(s + 1, Node(is_switch=True)) # Add edges for s1, s2 in wax.edges(): print "new edge" self.add_edge(s1 + 1, s2 + 1) # Add hosts hostoffset = num_switches + 2 for s in wax: # Add host host_base = num_hosts_per_switch * s + hostoffset for host in range(0, num_hosts_per_switch): self.add_node(host_base + host, Node(is_switch=False)) self.add_edge(host_base + host, s + 1) # # Globally connected host # self.add_host(9999) # for switch in wax: # self.add_link(9999, switch) # f = open('/home/openflow/workspace/foo.log', 'w') # f.write('hosts: %d\n' % len(self.hosts())) # f.close() # assert(False) self.enable_all()
import networkx as nx import matplotlib.pyplot as plt G = nx.waxman_graph(10, 1, 1, 1, (-4, 4, -4, 4)) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, 'pos') nx.write_adjlist(G, "test.adjlist") # find node near center (0.5,0.5) dmin = 1 ncenter = 0 for n in pos: print pos[n] x, y = pos[n] d = (x - 0.5)**2 + (y - 0.5)**2 if d < dmin: ncenter = n dmin = d print 'is connected: %s' % (nx.is_connected(G)) print 'is bi-connected: %s' % (nx.is_biconnected(G)) nx.draw(G, pos) plt.show() # color by path length from node near center #p=nx.single_source_shortest_path_length(G,ncenter) #plt.figure(figsize=(8,8)) #nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
def test_number_of_nodes_2(self): G = nx.waxman_graph(50, 0.5, 0.1, L=1) assert_equal(len(G), 50) G = nx.waxman_graph(range(50), 0.5, 0.1, L=1) assert_equal(len(G), 50)
elif option == "rgg": r = float(args[3]) name = "" if len(args) > 4: d = int(args[4]) g = nx.random_geometric_graph(n,r,d) name = 'Random Geometric Graph (n='+str(n)+', r='+str(r)+', d='+str(d)+')' else: g = random_geometric_graph(n,r) name = 'Random Geometric Graph (n='+str(n)+', r='+str(r)+')' elif option == "gtg": t = float(args[3]) g = nx.geographical_threshold_graph(n,t) name = 'Geographical Threshold Graph (n='+str(n)+', t='+str(t)+')' elif option == "wg": g = nx.waxman_graph(n) name = 'Waxman Graph (n='+str(n)+')' elif option == "nswg": g = navigable_small_world_graph(n) name = 'Navigable Small World Graph (n='+str(n)+')' elif option == "l": p1 = 0.5 p2 = 0.5 if len(args) > 4: p1 = float(args[4]) if len(args) > 5: p2 = float(args[5]) g = nx.random_lobster(n, p1, p2) name = 'Lobster ('+str(n)+','+str(p1)+","+str(p2)+')'
elif graph_type == 16: g = nx.random_lobster(num_n, .45, .45) g_name = 'NETWORKX.RANDOM_LOBSTER_45' elif graph_type == 17: g = nx.random_lobster(num_n, .9, .9) g_name = 'NETWORKX.RANDOM_LOBSTER_90' elif graph_type == 18: g = nx.watts_strogatz_graph(num_n, int(num_n * 0.1), 0.1) g_name = 'NETWORKX.WATTS_STROGATZ_10' elif graph_type == 19: g = nx.watts_strogatz_graph(num_n, int(num_n * 0.2), 0.2) g_name = 'NETWORKX.WATTS_STROGATZ_20' elif graph_type == 20: g = nx.waxman_graph(num_n) g_name = 'NETWORKX.WAXMAN_GRAPH' if nx.number_of_nodes(g) > 2000000 or nx.number_of_edges( g) > 2000000: continue #choose different graph print "Running trial", str(g_name) print "Analyzing graph", g_name cluster_nodes = None dendo = None print nx.info(g) #print graph_sql print "Analyzing graph features" with open("data/syn_graphs/synthetic_graphs.csv", "a") as myfile:
import matplotlib.pyplot as plt import networkx as nx import math import random NP = [(100, 0.6, 0.1), (25, 0.9, 0.15), (50, 0.8, 0.105)] def print_graph(G): zop = [] NS = str(G.number_of_nodes()) zop.append(NS + "\n") conn = nx.to_edgelist(G) for (u, v, _) in conn: zop.append(f"{u} {v} {random.randint(1, 99)}\n") with open(NS + ".in", "w") as f: f.writelines(zop) for (N, b, a) in NP: while True: G = nx.waxman_graph(2) while not nx.is_connected(G): G = nx.waxman_graph(N, b, a) nx.draw(G) plt.show() if input() == "yes": print_graph(G) break
def test_number_of_nodes_2(self): G = nx.waxman_graph(50, 0.5, 0.1, L=1) assert len(G) == 50 G = nx.waxman_graph(range(50), 0.5, 0.1, L=1) assert len(G) == 50
def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0,0,1,1)): return EquibelGraph(nx.waxman_graph(n, alpha, beta, L, domain))
def waxman_graph(N, deg, dia, dim, domain): ''' Parameters of the graph: n (int or iterable) – Number of nodes or iterable of nodes beta (float) – Model parameter alpha (float) – Model parameter Average Degree is given by formula: k where P = beta * exp(-d/alpha*L) alpha = (gamma((k/2)+1) * (beta^k))/((n-1)*(pi^(k/2))*gamma(k)) where beta is chosen randomly to satisfy the average degree criterion So we fix the parameter beta = 0.1, and we know the default value of d/L is in range: 0.25 to 0.3 (Empiricially calculated) so we only tweak alpha to get the required avg deg. :return: Graph Object ''' strt_time = time() bands = 10 lower_lim = 2.5 upper_lim = 3.5 tolerance = 0.5 k = 2 curr_avg_deg_error = float('inf') flag = False while curr_avg_deg_error >= tolerance: s_space = np.linspace(lower_lim, upper_lim, bands) avg_deg_error_list = [] s_gap = s_space[1] - s_space[0] for s in s_space: g_s = (k * (pi ** (k / 2)) * special.gamma(k)) / (special.gamma((k / 2) + 1) * (s ** k)) q = deg/((N-1)*g_s) G = nx.waxman_graph(n=N, alpha=s, beta=q) lcc = graph_util.get_lcc_undirected(G)[0] curr_avg_deg = np.mean(list(dict(nx.degree(lcc)).values())) avg_deg_err = abs(curr_avg_deg - deg) if avg_deg_err <= tolerance: best_G = G best_avg_deg = curr_avg_deg best_diam = nx.algorithms.diameter(lcc) flag = True break avg_deg_error_list.append((lcc,avg_deg_err , curr_avg_deg, s)) if flag == True: break sorted_avg_err = sorted(avg_deg_error_list, key=lambda x: x[1]) curr_avg_deg_error = sorted_avg_err[0][1] if sorted_avg_err[0][1] <= tolerance: best_G = sorted_avg_err[0][0] best_avg_deg = sorted_avg_err[0][2] best_diam = nx.algorithms.diameter(best_G) break else: lower_lim = sorted_avg_err[0][3] - s_gap upper_lim = sorted_avg_err[0][3] + s_gap end_time = time() print('Graph_Name: waxman_graph') print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam) print('TIME: ', end_time - strt_time) return best_G, best_avg_deg, best_diam
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False): label = None if cache: print('Loading cached graph') graph = pk.load(open('tmp/g.pk', 'rb')) else: print('Generating graph opt {}'.format(opt)) if 1 == opt: graph = gen_rand_graph(data_num=data_num) if 2 == opt: top_num = random.randint(1, data_num) bottom_num = data_num - top_num graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9) label = [d['bipartite'] for n, d in graph.nodes(data=True)] elif 3 == opt: graph = nx.balanced_tree(4, 5) elif 4 == opt: graph = nx.complete_graph(data_num) elif 5 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.complete_multipartite_graph(no1, no2, no3) elif 6 == opt: graph = nx.circular_ladder_graph(data_num) elif 7 == opt: graph = nx.cycle_graph(data_num) elif 8 == opt: graph = nx.dorogovtsev_goltsev_mendes_graph(5) elif 9 == opt: top_num = int(random.random() * data_num) bottom_num = data_num / top_num graph = nx.grid_2d_graph(top_num, bottom_num) elif 10 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.grid_graph([no1, no2, no3]) elif 11 == opt: graph = nx.hypercube_graph(10) elif 12 == opt: graph = nx.ladder_graph(data_num) elif 13 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.lollipop_graph(top_num, bottom_num) elif 14 == opt: graph = nx.path_graph(data_num) elif 15 == opt: graph = nx.star_graph(data_num) elif 16 == opt: graph = nx.wheel_graph(data_num) elif 17 == opt: graph = nx.margulis_gabber_galil_graph(35) elif 18 == opt: graph = nx.chordal_cycle_graph(data_num) elif 19 == opt: graph = nx.fast_gnp_random_graph(data_num, random.random()) elif 20 == opt: # jump eigen value graph = nx.gnp_random_graph(data_num, random.random()) elif 21 == opt: # disconnected graph graph = nx.dense_gnm_random_graph(data_num, data_num / 2) elif 22 == opt: # disconnected graph graph = nx.gnm_random_graph(data_num, data_num / 2) elif 23 == opt: graph = nx.erdos_renyi_graph(data_num, data_num / 2) elif 24 == opt: graph = nx.binomial_graph(data_num, data_num / 2) elif 25 == opt: graph = nx.newman_watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: graph = nx.watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: # smooth eigen graph = nx.connected_watts_strogatz_graph(data_num, 5, random.random()) elif 27 == opt: # smooth eigen graph = nx.random_regular_graph(5, data_num) elif 28 == opt: # smooth eigen graph = nx.barabasi_albert_graph(data_num, 5) elif 29 == opt: # smooth eigen graph = nx.powerlaw_cluster_graph(data_num, 5, random.random()) elif 30 == opt: # smooth eigen graph = nx.duplication_divergence_graph(data_num, random.random()) elif 31 == opt: p = random.random() q = random.random() graph = nx.random_lobster(data_num, p, q) elif 32 == opt: p = random.random() q = random.random() k = random.random() graph = nx.random_shell_graph([(data_num / 3, 50, p), (data_num / 3, 40, q), (data_num / 3, 30, k)]) elif 33 == opt: # smooth eigen top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.k_random_intersection_graph(top_num, bottom_num, 3) elif 34 == opt: graph = nx.random_geometric_graph(data_num, .1) elif 35 == opt: graph = nx.waxman_graph(data_num) elif 36 == opt: graph = nx.geographical_threshold_graph(data_num, .5) elif 37 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.uniform_random_intersection_graph( top_num, bottom_num, .5) elif 39 == opt: graph = nx.navigable_small_world_graph(data_num) elif 40 == opt: graph = nx.random_powerlaw_tree(data_num, tries=200) elif 41 == opt: graph = nx.karate_club_graph() elif 42 == opt: graph = nx.davis_southern_women_graph() elif 43 == opt: graph = nx.florentine_families_graph() elif 44 == opt: graph = nx.complete_multipartite_graph(data_num, data_num, data_num) # OPT 1 # norm_lap = nx.normalized_laplacian_matrix(graph).toarray() # OPT 2: renormalized # pk.dump(graph, open('tmp/g.pk', 'wb')) # plot_graph(graph, label) # note difference: normalized laplacian and normalzation by eigenvalue norm_lap, eigval, eigvec = normalize_lap(graph) return graph, norm_lap, eigval, eigvec
n = 1000 # Generic random topologies # Simple 3-regular random graphs: unrealistic but useful baseline nx.write_weighted_edgelist(nx.random_regular_graph(3,n), "3reg.dat") # Watts-Strogatz small-world graph nx.write_weighted_edgelist(nx.watts_strogatz_graph(n,2,0.5), "ws.dat") # Barabasi-Albert preferential attachment model nx.write_weighted_edgelist(nx.barabasi_albert_graph(n,1), "ba.dat") # Powerlaw cluster graph nx.write_weighted_edgelist(nx.powerlaw_cluster_graph(n,1,0.1), "pc.dat") # Planar geographic topologies # Navigable small-world planar graph. # Note that this produces nodes named by grid coords rather than integers. #gridn = math.ceil(math.sqrt(n)) #nx.write_weighted_edgelist(nx.navigable_small_world_graph(gridn), "nsw.dat") # Waxman planar graph nx.write_weighted_edgelist(nx.waxman_graph(n), "wax.dat")
import networkx as nx from gerrychain import Graph import matplotlib.pyplot as plt g = Graph.from_json("./BG05.json") n = len(g.nodes()) triangles = [] maxdeg = [] number_leaves = [] diam = [] number_edges = [] for i in range(100): w = nx.waxman_graph(n, 1.25) triangles.append(sum(nx.triangles(w).values())) maxdeg.append(max(dict(nx.degree(w)).values())) number_leaves.append(sum([nx.degree(w)[node] == 1 for node in w.nodes()])) if nx.is_connected(w): diam.append(nx.diameter(w)) number_edges.append(len(w.edges())) plt.figure() plt.hist(triangles) plt.axvline(x=sum(nx.triangles(g).values()), color='r') plt.show() plt.figure() plt.hist(maxdeg) plt.axvline(x=max(dict(nx.degree(g)).values()), color='r')
import networkx as nx import matplotlib.pyplot as plt G=nx.waxman_graph(10,1,1,1,(-4, 4, -4, 4)) # position is stored as node attribute data for random_geometric_graph pos=nx.get_node_attributes(G,'pos') nx.write_adjlist(G, "test.adjlist") # find node near center (0.5,0.5) dmin=1 ncenter=0 for n in pos: print pos[n] x,y=pos[n] d=(x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter=n dmin=d print 'is connected: %s' % (nx.is_connected(G)) print 'is bi-connected: %s' % (nx.is_biconnected(G)) nx.draw(G,pos) plt.show() # color by path length from node near center #p=nx.single_source_shortest_path_length(G,ncenter) #plt.figure(figsize=(8,8)) #nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
#!/usr/bin/python3 # -*- coding: utf-8 - import pickle import igraph as ig import numpy as np import networkx as nx from Manipulate import ManipulateGraph from Attack_Functions import attack_degree_igraph, random_attack_igraph, attack_transitivity_igraph, attack_betweenness_igraph NODES_NUMBER = 10000 ITERATION_REMOVALS = 10 manipulate = ManipulateGraph() waxman_nx = nx.waxman_graph(10000, alpha=0.0057, beta=1, seed=192) waxman_ig = manipulate.convert_networkx_to_igraph(waxman_nx) print(manipulate.degree_average_ig(waxman_ig)) print(manipulate.degree_average_nx(waxman_nx)) largest_cc, transitivity = random_attack_igraph(waxman_ig, ITERATION_REMOVALS) largest_cc1, transitivity1 = attack_degree_igraph(waxman_ig, ITERATION_REMOVALS) # largest_cc2, transitivity2 = attack_transitivity_igraph(waxman_ig, ITERATION_REMOVALS) # np.savetxt('largest_cc_waxman_randomATT', largest_cc) np.savetxt('transitivity_waxman_randomATT', transitivity) np.savetxt('largest_cc_waxman_degreeATT', largest_cc1) np.savetxt('transitivity_waxman_degreeATT', transitivity1) # np.savetxt('largest_cc_waxman_transitivityATT', largest_cc2) # np.savetxt('transitivity_waxman_transitivityATT', transitivity2)
import networkx as nx import pydot from networkx import waxman_graph from matplotlib import pylab, pyplot as plt # G = waxman_graph(10) # nx.draw(G) # print(G) def save_graph(graph, file_name): #initialze Figure nx.draw_networkx(graph) # pos = nx.spring_layout(graph) # nx.draw_networkx_nodes(graph,pos) # nx.draw_networkx_edges(graph,pos) # nx.draw_networkx_labels(graph,pos) plt.xlim(-4, 4) plt.ylim(-4, 4) plt.show() plt.savefig(file_name, bbox_inches="tight") pylab.close() #Assuming that the graph g has nodes and edges entered G = waxman_graph(10, domain=(0, 0, .1, .1)) # G = nx.barbell_graph(3,5) save_graph(G, "my_graph.jpg") #it can also be saved in .svg, .png. or .ps formats
# Generate some relevant model graphs to use in simulation experiments import math import networkx as nx n = 1000 # Generic random topologies # Simple 3-regular random graphs: unrealistic but useful baseline nx.write_weighted_edgelist(nx.random_regular_graph(3, n), "3reg.dat") # Watts-Strogatz small-world graph nx.write_weighted_edgelist(nx.watts_strogatz_graph(n, 2, 0.5), "ws.dat") # Barabasi-Albert preferential attachment model nx.write_weighted_edgelist(nx.barabasi_albert_graph(n, 1), "ba.dat") # Powerlaw cluster graph nx.write_weighted_edgelist(nx.powerlaw_cluster_graph(n, 1, 0.1), "pc.dat") # Planar geographic topologies # Navigable small-world planar graph. # Note that this produces nodes named by grid coords rather than integers. #gridn = math.ceil(math.sqrt(n)) #nx.write_weighted_edgelist(nx.navigable_small_world_graph(gridn), "nsw.dat") # Waxman planar graph nx.write_weighted_edgelist(nx.waxman_graph(n), "wax.dat")
#!/usr/bin/python3 # coding: utf-8 import networkx import igraph graph_nx = networkx.waxman_graph(20) manipulate_graphs = ManipulateGraph() graph_ig = manipulate_graphs.convert_networkx_to_igraph2(graph_nx) manipulate_graphs.print_nx_graph(graph_nx) graph_ig.get_edgelist() graph_ig.delete_edges([4]) graph_ig = graph_ig.delete_edges(4) graph_ig = graph_ig.delete_edges([4]) graph_ig = graph_ig.delete_edges([(4, 6)])
parser.add_argument("-f", dest="file", default="", help="Output file name stem") parser.add_argument("-g", dest="gfile", default="", help="If enabled, writes visualization of the network to gfile") parser.add_argument("-w", dest="waxman", action="store_true", help="Generate Waxman graph") parser.add_argument("-p", type=int, dest="partition", default=1, help="If specified, generates p densely connected components that are loosely connected with few links") parser.add_argument("-oob", dest="is_oob", action="store_true", help="Are controllers 'out-of-band'?") parser.add_argument("--fail_crit", dest="fail_crit", action="store_true", help="Should we fail critical links?") parser.set_defaults(waxman = False) args = parser.parse_args() g = nx.erdos_renyi_graph(0, 0) partition_size = args.n / args.partition partitions = [] for p in xrange(args.partition): _g = None if args.waxman: _g = nx.waxman_graph(partition_size) else: _g = nx.erdos_renyi_graph(partition_size, args.m*1.0/args.n) # No need to fix graph, we take care of fixing up partitions below. #fixGraph(_g) partitions.append(_g) failure_edges = [] partition_nodes = [] for p in partitions: before = len(g.nodes()) g = nx.disjoint_union(g, p) partition_nodes.append(g.nodes()[before:]) while (nx.number_connected_components(g) > 1): nodes = [] for c in nx.connected_components(g):