def make_random_lobster(N_nodes, p1=0.5, p2=0.5): """random lobster graph with exponentially distributed potentials""" # initialize and add nodes graph_name = nx.random_lobster(N_nodes, p1, p2, seed=None) node_state_sizes = np.random.randint( 2, high=5, size=graph_name.number_of_nodes()) # add indices of node state -- seems like there should be a slick way to # avoid this but can't figure it out for n in graph_name.nodes_iter(): graph_name.node[n]['node_state_indices'] = [ i for i in xrange(node_state_sizes[n])] # add potentials to graph for n in graph_name.nodes_iter(): node_potential = np.random.exponential(1, [node_state_sizes[n], 1]) graph_name.node[n]['node_potential'] = node_potential for i, edge in enumerate(graph_name.edges_iter()): n_a, n_b = edge len_n_a = len(graph_name.node[n_a]['node_potential']) len_n_b = len(graph_name.node[n_b]['node_potential']) edge_potential = np.random.exponential(1, [len_n_a, len_n_b]) graph_name.edge[n_a][n_b]['edge_potential'] = edge_potential return graph_name
def RandomLobster(n, p, q, seed=None): """ Returns a random lobster. A lobster is a tree that reduces to a caterpillar when pruning all leaf vertices. A caterpillar is a tree that reduces to a path when pruning all leaf vertices (q=0). INPUT: - ``n`` - expected number of vertices in the backbone - ``p`` - probability of adding an edge to the backbone - ``q`` - probability of adding an edge (claw) to the arms - ``seed`` - for the random number generator EXAMPLE: We show the edge list of a random graph with 3 backbone nodes and probabilities `p = 0.7` and `q = 0.3`:: sage: graphs.RandomLobster(3, 0.7, 0.3).edges(labels=False) [(0, 1), (1, 2)] :: sage: G = graphs.RandomLobster(9, .6, .3) sage: G.show() # long time """ if seed is None: seed = current_randstate().long_seed() import networkx return graph.Graph(networkx.random_lobster(n, p, q, seed=seed))
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 RandomLobster(n, p, q, seed=None): """ Returns a random lobster. A lobster is a tree that reduces to a caterpillar when pruning all leaf vertices. A caterpillar is a tree that reduces to a path when pruning all leaf vertices (q=0). INPUT: - ``n`` - expected number of vertices in the backbone - ``p`` - probability of adding an edge to the backbone - ``q`` - probability of adding an edge (claw) to the arms - ``seed`` - for the random number generator EXAMPLE: We show the edge list of a random graph with 3 backbone nodes and probabilities `p = 0.7` and `q = 0.3`:: sage: graphs.RandomLobster(3, 0.7, 0.3).edges(labels=False) [(0, 1), (1, 2)] :: sage: G = graphs.RandomLobster(9, .6, .3) sage: G.show() # long time """ if seed is None: seed = current_randstate().long_seed() import networkx return graph.Graph(networkx.random_lobster(n, p, q, seed=seed))
def generateMinerGraph(self): """Generates a miner graph based on the settings in this object. Returns: networkx.Graph -- Graph of miners to be used in simulation. """ graph = None if self.topology_type == TopologyType.STATIC_UNIFORM_DELAY: if not self.static_graph: with open(self.static_file, 'r') as infile: raw_data = json.load(infile, cls=GraphDecoder) self.static_graph = raw_data['graph'] graph = self.static_graph else: while graph is None or not nx.is_connected(graph): if self.topology_type == TopologyType.GEOMETRIC_UNIFORM_DELAY or self.topology_type == TopologyType.LOBSTER_UNIFORM_DELAY: # Graphs with uniform delays for message transmission. if self.topology_type == TopologyType.GEOMETRIC_UNIFORM_DELAY: graph = nx.random_geometric_graph( self.number_of_miners, self.radius) elif self.topology_type == TopologyType.LOBSTER_UNIFORM_DELAY: graph = nx.random_lobster(self.number_of_miners, self.p1, self.p2) else: raise NotImplementedError( "Selected topology type is not implemented.") for edge in graph.edges: graph.edges[edge]['network_delay'] = self.network_delay return graph
def create_graphs(graph_type, data_dir='data', noise=10.0, seed=1234, fname=''): npr = np.random.RandomState(seed) ### load datasets graphs = [] # GRAN examples. Remove this later if graph_type == 'grid': graphs = [] for i in range(10, 20): for j in range(10, 20): graphs.append(nx.grid_2d_graph(i, j)) elif graph_type == 'lobster': graphs = [] p1 = 0.7 p2 = 0.7 count = 0 min_node = 10 max_node = 100 max_edge = 0 mean_node = 80 num_graphs = 100 seed_tmp = seed while count < num_graphs: G = nx.random_lobster(mean_node, p1, p2, seed=seed_tmp) if len(G.nodes()) >= min_node and len(G.nodes()) <= max_node: graphs.append(G) if G.number_of_edges() > max_edge: max_edge = G.number_of_edges() count += 1 seed_tmp += 1 elif graph_type == 'DD': graphs = graph_load_batch(data_dir, min_num_nodes=100, max_num_nodes=500, name='DD', node_attributes=False, graph_labels=True) elif graph_type == 'FIRSTMM_DB': graphs = graph_load_batch(data_dir, min_num_nodes=0, max_num_nodes=10000, name='FIRSTMM_DB', node_attributes=False, graph_labels=True) elif graph_type == 'custom': graphs = pickle.load(open(data_dir + fname, 'rb')) num_nodes = [gg.number_of_nodes() for gg in graphs] num_edges = [gg.number_of_edges() for gg in graphs] print('max # nodes = {} || mean # nodes = {}'.format( max(num_nodes), np.mean(num_nodes))) print('max # edges = {} || mean # edges = {}'.format( max(num_edges), np.mean(num_edges))) return graphs
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)
def __init__(self, **kwargs): # super super(RandomLobster, self).__init__() n = kwargs.get('n', 10) p1 = kwargs.get('p2', 0.7) p2 = kwargs.get('p2', 0.4) # topology view of the network self.ref_g = nx.random_lobster(n,p1,p2) # nx topology definition self.build_nx_topo(self.ref_g)
def random_lobster(nodes, edges): g = nx.MultiDiGraph(nx.random_lobster(nodes, 1.0, 1.0)) for node in g: # if it's a leaf node, add a self edge and an edge back to the spine if len(g.out_edges(node)) == 1: knee = g.in_edges(node)[0][0] spine = g.in_edges(knee)[0][0] g.add_edge(node, spine) if len(g.out_edges(node)) == 2: g.add_edge(node, node) return g
def create_graph(information): if information['style'] == 'simple': return nx.barabasi_albert_graph(information['num_nodes'], information['avg_degree']) elif information['style'] == 'star': return nx.star_graph(information['num_nodes']) elif information['style'] == 'wheel': return nx.wheel_graph(information['num_nodes']) elif information['style'] == 'lobster': return nx.random_lobster(information['num_nodes'], information['prob1'], information['prob2']) else: print("Invalid network style received. Aborting...") exit(1)
def generate_graphs(): """ Generates sample graphs for testing """ #er=nx.erdos_renyi_graph(1000, 0.05) ws=nx.watts_strogatz_graph(3000,3,0.1) save(ws, 'WS_3000_3_01', 2, 10) draw(ws) ba=nx.barabasi_albert_graph(1000,10) save(ba, 'BA_1000_5',2,10) draw(ba) red=nx.random_lobster(1000,0.9,0.10) save(red, 'LOB_1000_09', 2, 10) draw(red)
def create_random_graph(model_name, node_count, terminal_count=5): """Creates a random graph according to some model. Args: model_name: which model to use for the random graph node_count: number of nodes in the graph terminal_count: number of terminals in the graph Returns: graph: the graph in networkx format terminals: the terminals in a list Raises: ValueError: if model_name is not a valid model name """ if model_name == "gnp": graph = nx.gnp_random_graph(node_count, 0.01) elif model_name == "lobster": graph = nx.random_lobster(node_count, 0.1, 0.1) elif model_name == "powerlaw_tree": graph = nx.random_powerlaw_tree(node_count) elif model_name == "powerlaw_cluster": # n = the number of nodes # m = the number of random edges to add for each new node # p = probability of adding a triangle after adding a random edge graph = nx.powerlaw_cluster_graph(node_count, 10, 0.1) elif model_name == "barabasi_albert": graph = nx.barabasi_albert_graph(node_count, 3) elif model_name == "connected_watts_strogatz": graph = nx.connected_watts_strogatz_graph(node_count, 10, 0.1) elif model_name == "newman_watts_strogatz": graph = nx.newman_watts_strogatz_graph(node_count, 10, 0.1) else: raise ValueError("") for edge in graph.edges(): graph[edge[0]][edge[1]]["capacity"] = random.randint(1, 11) terminals = range(terminal_count) return graph, terminals
def generate_data(n_segments, n_timesteps): """ Generate toy data """ # Random lobster looks as messy as typical (german) cities graph = nx.random_lobster(n_segments, 0.9, 0.9) adjacency = torch.from_numpy(nx.to_numpy_array(graph)) # Connections among segments # adjacency = torch.rand(n_segments, n_segments) < 0.1 # # Make connections symetric # adjacency |= adjacency.t() # # Insert diagonal for self-connections # adjacency |= torch.eye(n_segments).byte() loads = torch.softmax(torch.rand(n_timesteps, n_segments), dim=1) # passengers: [timestep, src, dst] # If passenger is on diagonal, src == dst passengers = torch.softmax(torch.rand(n_timesteps, n_segments, n_segments), dim=1) # Inter-segment adjacency is static return adjacency, loads, passengers
def test_random_graph(self): seed = 42 G = nx.gnp_random_graph(100, 0.25, seed) G = nx.gnp_random_graph(100, 0.25, seed, directed=True) G = nx.binomial_graph(100, 0.25, seed) G = nx.erdos_renyi_graph(100, 0.25, seed) G = nx.fast_gnp_random_graph(100, 0.25, seed) G = nx.fast_gnp_random_graph(100, 0.25, seed, directed=True) G = nx.gnm_random_graph(100, 20, seed) G = nx.gnm_random_graph(100, 20, seed, directed=True) G = nx.dense_gnm_random_graph(100, 20, seed) G = nx.watts_strogatz_graph(10, 2, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() == 10 G = nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed) assert len(G) == 10 assert G.number_of_edges() == 10 pytest.raises(nx.NetworkXError, nx.connected_watts_strogatz_graph, 10, 2, 0.1, tries=0) G = nx.watts_strogatz_graph(10, 4, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() == 20 G = nx.newman_watts_strogatz_graph(10, 2, 0.0, seed) assert len(G) == 10 assert G.number_of_edges() == 10 G = nx.newman_watts_strogatz_graph(10, 4, 0.25, seed) assert len(G) == 10 assert G.number_of_edges() >= 20 G = nx.barabasi_albert_graph(100, 1, seed) G = nx.barabasi_albert_graph(100, 3, seed) assert G.number_of_edges() == (97 * 3) G = nx.barabasi_albert_graph(100, 3, seed, nx.complete_graph(5)) assert G.number_of_edges() == (10 + 95 * 3) G = nx.extended_barabasi_albert_graph(100, 1, 0, 0, seed) assert G.number_of_edges() == 99 G = nx.extended_barabasi_albert_graph(100, 3, 0, 0, seed) assert G.number_of_edges() == 97 * 3 G = nx.extended_barabasi_albert_graph(100, 1, 0, 0.5, seed) assert G.number_of_edges() == 99 G = nx.extended_barabasi_albert_graph(100, 2, 0.5, 0, seed) assert G.number_of_edges() > 100 * 3 assert G.number_of_edges() < 100 * 4 G = nx.extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed) assert G.number_of_edges() > 100 * 2 assert G.number_of_edges() < 100 * 4 G = nx.powerlaw_cluster_graph(100, 1, 1.0, seed) G = nx.powerlaw_cluster_graph(100, 3, 0.0, seed) assert G.number_of_edges() == (97 * 3) G = nx.random_regular_graph(10, 20, seed) pytest.raises(nx.NetworkXError, nx.random_regular_graph, 3, 21) pytest.raises(nx.NetworkXError, nx.random_regular_graph, 33, 21) constructor = [(10, 20, 0.8), (20, 40, 0.8)] G = nx.random_shell_graph(constructor, seed) def is_caterpillar(g): """ A tree is a caterpillar iff all nodes of degree >=3 are surrounded by at most two nodes of degree two or greater. ref: http://mathworld.wolfram.com/CaterpillarGraph.html """ deg_over_3 = [n for n in g if g.degree(n) >= 3] for n in deg_over_3: nbh_deg_over_2 = [ nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2 ] if not len(nbh_deg_over_2) <= 2: return False return True def is_lobster(g): """ A tree is a lobster if it has the property that the removal of leaf nodes leaves a caterpillar graph (Gallian 2007) ref: http://mathworld.wolfram.com/LobsterGraph.html """ non_leafs = [n for n in g if g.degree(n) > 1] return is_caterpillar(g.subgraph(non_leafs)) G = nx.random_lobster(10, 0.1, 0.5, seed) assert max([G.degree(n) for n in G.nodes()]) > 3 assert is_lobster(G) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 0.1, 1, seed) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 1, seed) pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 0.5, seed) # docstring says this should be a caterpillar G = nx.random_lobster(10, 0.1, 0.0, seed) assert is_caterpillar(G) # difficult to find seed that requires few tries seq = nx.random_powerlaw_tree_sequence(10, 3, seed=14, tries=1) G = nx.random_powerlaw_tree(10, 3, seed=14, tries=1)
prerential_attachment_graph = nx.barabasi_albert_graph(n, m) outpath = 'preferential_attachment_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(prerential_attachment_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Cluster Graph]') n = 100 m = 5 powerlaw_cluster_graph = nx.powerlaw_cluster_graph(n, m, 0.7) outpath = 'powerlaw_cluster_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Random Lobster]') n = 100 lobster_graph = nx.random_lobster(n, 0.7, 0.7) outpath = 'random_lobster_graph_' + str(n) + '.txt' nx.write_edgelist(lobster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Tree]') n = 100 powerlaw_tree = nx.random_powerlaw_tree(n, 3, None, 10000) outpath = 'powerlaw_tree_' + str(n) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Bipartite Random Graph]') n = 100 m = 20 bipartite_random_graph = nx.bipartite_random_graph(n, m, 0.7)
""" Name: Generate Graph: regular graph Author: Jia_qiu Wang(王佳秋) Data: December, 2016 function: """ import networkx as nx import matplotlib.pyplot as plt red = nx.random_lobster(20, 0.9, 0.9) pos = nx.shell_layout(red) nx.draw(red, pos, with_labels=False, node_size=30) plt.show()
g = cycle_graph(num_n) g_name = 'NETWORKX.CYCLE_GRAPH' elif graph_type == 12: g = nx.erdos_renyi_graph(num_n, .15) g_name = 'NETWORKX.ERDOS_RENYI_15' elif graph_type == 13: g = nx.erdos_renyi_graph(num_n, .30) g_name = 'NETWORKX.ERDOS_RENYI_30' elif graph_type == 14: g = ladder_graph(num_n / 2) g_name = 'NETWORKX.LADDER_GRAPH' elif graph_type == 15: g = path_graph(num_n) g_name = 'NETWORKX.PATH_GRAPH' 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'
tree = nx.balanced_tree(2,10) complete = nx.complete_graph(100) ba=nx.barabasi_albert_graph(100,5) red=nx.random_lobster(100,0.9,0.9) nx.draw(complete) plt.show() graph = complete ''' train = [] num_graphs = 10 model = None stacks_cap = [] ##################################Create Training Data#################################### for i in range(num_graphs): graph = nx.random_lobster(100,0.9,0.9) learned_stack = LearnedDynamicArray() answer = util.dfs_iterative(graph, 1,learned_stack) train.append(learned_stack.history_n) stacks_cap.append(learned_stack.history_capacity) ##################################Format Training Data#################################### buckets = 20 look_ahead_rate = 2 train_x,train_y,choices = util.create_dataset(train,buckets=buckets,look_ahead_rate = look_ahead_rate) train_x = np.expand_dims(train_x ,2) train_y = np.expand_dims(train_y ,2) ##################################Train Model#################################### lstm_units = 4 model = util.build_lstm_model(lstm_units,buckets)
def lobster(): p1 = 0.7 p2 = 0.7 mean_node = 80 G = nx.random_lobster(mean_node, p1, p2) return G
def create(args): ### load datasets graphs = [] # synthetic graphs if args.graph_type == 'ladder': graphs = [] for i in range(100, 201): graphs.append(nx.ladder_graph(i)) args.max_prev_node = 10 elif args.graph_type == 'ladder_small': graphs = [] for i in range(2, 11): graphs.append(nx.ladder_graph(i)) args.max_prev_node = 10 elif args.graph_type == 'tree': graphs = [] for i in range(2, 5): for j in range(3, 5): graphs.append(nx.balanced_tree(i, j)) args.max_prev_node = 256 elif args.graph_type == 'caveman': # graphs = [] # for i in range(5,10): # for j in range(5,25): # for k in range(5): # graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1)) graphs = [] for i in range(2, 3): for j in range(30, 81): for k in range(10): graphs.append(caveman_special(i, j, p_edge=0.3)) args.max_prev_node = 100 elif args.graph_type == 'caveman_small': # graphs = [] # for i in range(2,5): # for j in range(2,6): # for k in range(10): # graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1)) graphs = [] for i in range(2, 3): for j in range(6, 11): for k in range(20): graphs.append(caveman_special(i, j, p_edge=0.8)) # default 0.8 args.max_prev_node = 20 elif args.graph_type == 'caveman_small_single': # graphs = [] # for i in range(2,5): # for j in range(2,6): # for k in range(10): # graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1)) graphs = [] for i in range(2, 3): for j in range(8, 9): for k in range(100): graphs.append(caveman_special(i, j, p_edge=0.5)) args.max_prev_node = 20 elif args.graph_type.startswith('community'): num_communities = int(args.graph_type[-1]) print('Creating dataset with ', num_communities, ' communities') c_sizes = np.random.choice([12, 13, 14, 15, 16, 17], num_communities) #c_sizes = [15] * num_communities for k in range(3000): graphs.append(n_community(c_sizes, p_inter=0.01)) args.max_prev_node = 80 elif args.graph_type == 'grid': graphs = [] for i in range(10, 20): for j in range(10, 20): graphs.append(nx.grid_2d_graph(i, j)) args.max_prev_node = 40 elif args.graph_type == 'grid_small': graphs = [] for i in range(2, 5): for j in range(2, 6): graphs.append(nx.grid_2d_graph(i, j)) args.max_prev_node = 15 elif args.graph_type == 'lobster': graphs = [] p1 = 0.7 p2 = 0.7 count = 0 min_node = 10 max_node = 100 max_edge = 0 mean_node = 80 num_graphs = 100 seed = 1234 seed_tmp = seed while count < num_graphs: G = nx.random_lobster(mean_node, p1, p2, seed=seed_tmp) if len(G.nodes()) >= min_node and len(G.nodes()) <= max_node: graphs.append(G) count += 1 seed_tmp += 1 args.max_prev_node = 40 elif args.graph_type == 'barabasi': graphs = [] for i in range(100, 200): for j in range(4, 5): for k in range(5): graphs.append(nx.barabasi_albert_graph(i, j)) args.max_prev_node = 130 elif args.graph_type == 'barabasi_small': graphs = [] for i in range(4, 21): for j in range(3, 4): for k in range(10): graphs.append(nx.barabasi_albert_graph(i, j)) args.max_prev_node = 20 elif args.graph_type == 'grid_big': graphs = [] for i in range(36, 46): for j in range(36, 46): graphs.append(nx.grid_2d_graph(i, j)) args.max_prev_node = 90 elif 'barabasi_noise' in args.graph_type: graphs = [] for i in range(100, 101): for j in range(4, 5): for k in range(500): graphs.append(nx.barabasi_albert_graph(i, j)) graphs = perturb_new(graphs, p=args.noise / 10.0) args.max_prev_node = 99 # real graphs elif args.graph_type == 'enzymes': graphs = Graph_load_batch(min_num_nodes=10, name='ENZYMES') args.max_prev_node = 25 elif args.graph_type == 'enzymes_small': graphs_raw = Graph_load_batch(min_num_nodes=10, name='ENZYMES') graphs = [] for G in graphs_raw: if G.number_of_nodes() <= 20: graphs.append(G) args.max_prev_node = 15 elif args.graph_type == 'protein': graphs = Graph_load_batch(min_num_nodes=20, name='PROTEINS_full') args.max_prev_node = 80 elif args.graph_type == 'DD': graphs = Graph_load_batch(min_num_nodes=100, max_num_nodes=500, name='DD', node_attributes=False, graph_labels=True) args.max_prev_node = 230 elif args.graph_type == 'citeseer': _, _, G = Graph_load(dataset='citeseer') G = max(nx.connected_component_subgraphs(G), key=len) G = nx.convert_node_labels_to_integers(G) graphs = [] for i in range(G.number_of_nodes()): G_ego = nx.ego_graph(G, i, radius=3) if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400): graphs.append(G_ego) args.max_prev_node = 250 elif args.graph_type == 'citeseer_small': _, _, G = Graph_load(dataset='citeseer') G = max(nx.connected_component_subgraphs(G), key=len) G = nx.convert_node_labels_to_integers(G) graphs = [] for i in range(G.number_of_nodes()): G_ego = nx.ego_graph(G, i, radius=1) if (G_ego.number_of_nodes() >= 4) and (G_ego.number_of_nodes() <= 20): graphs.append(G_ego) shuffle(graphs) graphs = graphs[0:200] args.max_prev_node = 15 return graphs
""" Created on Wed Jul 1 09:45:36 2020 @author: azaldinfreidoon """ import networkx as nx from ContactNetwork import ContactNetwork import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.lines import Line2D fig, ax = plt.subplots() g = nx.random_lobster(10, .9, .9) weights = dict([(e, np.random.sample(1)[0]) for e in g.edges()]) nx.set_edge_attributes(g, weights, 'weight') legend_elements = [ Line2D([0], [0], marker='o', color='w', lw=4, label='Susceptible', markersize=14, markerfacecolor='b'), Line2D([0], [0], marker='o', color='w',
gPrim = Coloring(randomColoringList, G) isoSubTree = checkIfTreeExist(gPrim, T, isoSubTree, order) for a in isoSubTree[0]: if a: mapping = getGraphBack(G, T, isoSubTree, order) print("@@@Printing Mapping@@@") draw_result_save(G, mapping, "result") print("It took: " + str(i) + " attempts") return True return False if __name__ == "__main__": print("@@@@Testy wydajnościowe@@@@") graph = nx.random_lobster(10, 0.75, 0.75) graph2 = nx.nonisomorphic_trees(4) for g in graph2: draw_graph_save(graph, "endurance_small") draw_graph_save(g, "endurance_small") start_time = time.time() print(findTreeInGraph(graph, g)) print("It took " + str(time.time() - start_time) + " to calculate") print("@@@@Testy wydajnościowe duże@@@@") graph = nx.random_lobster(20, 0.75, 0.75) graph2 = nx.nonisomorphic_trees(6) for g in graph2: draw_graph_save(graph, "endurance_small") draw_graph_save(g, "endurance_small") start_time = time.time()
import random import networkx as nx import sys if sys.argv[1] == 'er': #er=nx.erdos_renyi_graph(100,0.15) g=nx.erdos_renyi_graph(int(sys.argv[4]), float(sys.argv[5])) elif sys.argv[1] == 'ws': #ws=nx.watts_strogatz_graph(30,3,0.1) g=nx.watts_strogatz_graph(int(sys.argv[4]), int(sys.argv[5]), float(sys.argv[6])) elif sys.argv[1] == 'ba': #ba=nx.barabasi_albert_graph(100,5) g=nx.barabasi_albert_graph(int(sys.argv[4]), int(sys.argv[5])) elif sys.argv[1] == 'rl': #red=nx.random_lobster(100,0.9,0.9) g=nx.random_lobster(int(sys.argv[4]), float(sys.argv[5]), float(sys.argv[6])) fout = open('input%s.txt' % sys.argv[2], 'w') fout.write('%s\n' % sys.argv[3]) #fout.write("%s\n"%sys.argv[4]) fout.write('N0\n') NN = len(g.nodes()) MM = len(g.edges()) #fout.write('N%s\n' % (int(sys.argv[4])-1)) fout.write('N%s\n' % (int(NN)-1)) fout.write('%s\n' % len(g.edges())) for x,y in g.edges(): fout.write("N%s N%s %s\n" % (x, y, random.randint(1,100))) #fout.write('%s\n' % sys.argv[4]) fout.write('%s\n' % NN) #for i in range((int(sys.argv[4]))): for i in range((int(NN))):
ax=ax1[0]) ax1[0].set_title("Zentraler Graph") G_stern_dezent = nx.star_graph(9) G_stern_dezent = G_stern_dezent.to_directed() nx.draw(G_stern_dezent, pos, arrows=True, ax=ax1[1], node_color="red") nx.draw_networkx_nodes(G_stern_dezent, pos, nodelist=[k for k in range(1, 10)], node_color="blue", ax=ax1[1]) ax1[1].set_title("Dezentraler Graph") plt.show() plt.title("Zufälliger Graph") G_rand = nx.random_lobster(8, 0.66, 0.1, seed=42) pos = nx.spring_layout(G_rand) G_rand = G_rand.to_directed() nx.draw(G_rand, pos, arrows=True, node_color="blue") plt.show() plt.title("Zufälliger Graph") nx.draw(G_rand, pos, arrows=True, node_color="blue", with_labels=False) labels = {} labels[0] = r'$\alpha$' labels[1] = r"$\beta$" labels[2] = r"$\gamma$" labels[11] = r"$\delta$" nx.draw_networkx_labels(G_rand, pos, labels, font_color="red", font_size=16) plt.show()
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 option == "bg": p = 0.1 if len(args) > 4: p = float(args[4]) g = nx.binomial_graph(n, p) name = 'Binomial Graph ('+str(n)+','+str(p)+')' elif option == "bg": p = 0.1 if len(args) > 4: p = float(args[4])
import networkx as nx import matplotlib.pyplot as plt red=nx.random_lobster(100,0.9,0.9) G=nx.sedgewick_maze_graph() #nx.draw(red) #nx.draw_random(red) nx.draw_circular(G) #nx.draw_spectral(G) plt.show(red)
import networkx as nx import matplotlib.pyplot as plt import numpy numpy.random.seed(121) er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) nx.draw(er) plt.show() nx.draw(ws) plt.show() nx.draw(ba) plt.show() nx.draw(red) plt.show()
import matplotlib.pyplot as plt import networkx as nx G = nx.random_lobster(100, 0.6, 0.9) nx.draw(G) plt.show()
def basic_operation_tutorial(): # Create a graph. G = nx.Graph() # Nodes. G.add_node(1) G.add_nodes_from([2, 3]) H = nx.path_graph(10) # Creates a graph. G.add_nodes_from(H) G.add_node(H) #print('G.nodes = {}.'.format(G.nodes)) print('G.nodes = {}.'.format(list(G.nodes))) # Edges. G.add_edge(1, 2) e = (2, 3) G.add_edge(*e) # Unpack edge tuple. G.add_edges_from([(1, 2), (1, 3)]) G.add_edges_from(H.edges) #print('G.edges = {}.'.format(G.edges)) print('G.edges = {}.'.format(list(G.edges))) # Remove all nodes and edges. G.clear() #-------------------- G.add_edges_from([(1, 2), (1, 3)]) G.add_node(1) G.add_edge(1, 2) G.add_node('spam') # Adds node 'spam'. G.add_nodes_from('spam') # Adds 4 nodes: 's', 'p', 'a', 'm'. G.add_edge(3, 'm') print('G.number_of_nodes() = {}.'.format(G.number_of_nodes())) print('G.number_of_edges() = {}.'.format(G.number_of_edges())) # Set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. print('G.adj[1] = {}.'.format(list(G.adj[1]))) # or G.neighbors(1). print('G.degree[1] = {}.'.format( G.degree[1])) # The number of edges incident to 1. # Report the edges and degree from a subset of all nodes using an nbunch. # An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph. print("G.edges([2, 'm']) = {}.".format(G.edges([2, 'm']))) print('G.degree([2, 3]) = {}.'.format(G.degree([2, 3]))) # Remove nodes and edges from the graph in a similar fashion to adding. G.remove_node(2) G.remove_nodes_from('spam') print('G.nodes = {}.'.format(list(G.nodes))) G.remove_edge(1, 3) # When creating a graph structure by instantiating one of the graph classes you can specify data in several formats. G.add_edge(1, 2) H = nx.DiGraph(G) # Creates a DiGraph using the connections from G. print('H.edges() = {}.'.format(list(H.edges()))) edgelist = [(0, 1), (1, 2), (2, 3)] H = nx.Graph(edgelist) #-------------------- # Access edges and neighbors. print('G[1] = {}.'.format(G[1])) # Same as G.adj[1]. print('G[1][2] = {}.'.format(G[1][2])) # Edge 1-2. print('G.edges[1, 2] = {}.'.format(G.edges[1, 2])) # Get/set the attributes of an edge using subscript notation if the edge already exists. G.add_edge(1, 3) G[1][3]['color'] = 'blue' G.edges[1, 2]['color'] = 'red' # Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items(). # Note that for undirected graphs, adjacency iteration sees each edge twice. FG = nx.Graph() FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) for n, nbrs in FG.adj.items(): for nbr, eattr in nbrs.items(): wt = eattr['weight'] if wt < 0.5: print(f'({n}, {nbr}, {wt:.3})') # Convenient access to all edges is achieved with the edges property. for (u, v, wt) in FG.edges.data('weight'): if wt < 0.5: print(f'({u}, {v}, {wt:.3})') #-------------------- # Attributes. # Graph attributes. G = nx.Graph(day='Friday') print('G.graph = {}.'.format(G.graph)) G.graph['day'] = 'Monday' # Node attributes: add_node(), add_nodes_from(), or G.nodes. G.add_node(1, time='5pm') G.add_nodes_from([3], time='2pm') print('G.nodes[1] = {}.'.format(G.nodes[1])) G.nodes[1]['room'] = 714 print('G.nodes.data() = {}.'.format(G.nodes.data())) print('G.nodes[1] = {}.'.format( G.nodes[1])) # List the attributes of a node. print('G.nodes[1].keys() = {}.'.format(G.nodes[1].keys())) #print('G[1] = {}.'.format(G[1])) # G[1] = G.adj[1]. # Edge attributes: add_edge(), add_edges_from(), or subscript notation. G.add_edge(1, 2, weight=4.7) G.add_edges_from([(3, 4), (4, 5)], color='red') G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})]) G[1][2]['weight'] = 4.7 G.edges[3, 4]['weight'] = 4.2 print('G.edges.data() = {}.'.format(G.edges.data())) print('G.edges[3, 4] = {}.'.format( G.edges[3, 4])) # List the attributes of an edge. print('G.edges[3, 4].keys() = {}.'.format(G.edges[3, 4].keys())) #-------------------- # Directed graphs. DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) print("DG.out_degree(1, weight='weight') = {}.".format( DG.out_degree(1, weight='weight'))) print("DG.degree(1, weight='weight') = {}.".format( DG.degree( 1, weight='weight'))) # The sum of in_degree() and out_degree(). print('DG.successors(1) = {}.'.format(list(DG.successors(1)))) print('DG.neighbors(1) = {}.'.format(list(DG.neighbors(1)))) # Convert G to undirected graph. #H = DG.to_undirected() H = nx.Graph(DG) #-------------------- # Multigraphs: Graphs which allow multiple edges between any pair of nodes. MG = nx.MultiGraph() #MDG = nx.MultiDiGraph() MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) print("MG.degree(weight='weight') = {}.".format( dict(MG.degree(weight='weight')))) GG = nx.Graph() for n, nbrs in MG.adjacency(): for nbr, edict in nbrs.items(): minvalue = min([d['weight'] for d in edict.values()]) GG.add_edge(n, nbr, weight=minvalue) print('nx.shortest_path(GG, 1, 3) = {}.'.format(nx.shortest_path(GG, 1, 3))) #-------------------- # Classic graph operations: """ subgraph(G, nbunch): induced subgraph view of G on nodes in nbunch union(G1,G2): graph union disjoint_union(G1,G2): graph union assuming all nodes are different cartesian_product(G1,G2): return Cartesian product graph compose(G1,G2): combine graphs identifying nodes common to both complement(G): graph complement create_empty_copy(G): return an empty copy of the same graph class to_undirected(G): return an undirected representation of G to_directed(G): return a directed representation of G """ #-------------------- # Graph generators. # Use a call to one of the classic small graphs: petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() # Use a (constructive) generator for a classic graph: K_5 = nx.complete_graph(5) K_3_5 = nx.complete_bipartite_graph(3, 5) barbell = nx.barbell_graph(10, 10) lollipop = nx.lollipop_graph(10, 20) # Use a stochastic graph generator: er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) #-------------------- # Read a graph stored in a file using common graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others. nx.write_gml(red, './test.gml') mygraph = nx.read_gml('./test.gml')
def create_graphs(graph_type, data_dir='data', noise=10.0, seed=1234): npr = np.random.RandomState(seed) ### load datasets graphs = [] # synthetic graphs if graph_type == 'grid': graphs = [] for i in range(10, 20): for j in range(10, 20): graphs.append(nx.grid_2d_graph(i, j)) # Added graph for an ektra small grid to train on elif graph_type == 'small_grid': graphs = [] for i in range(3, 9): for j in range(3, 9): graphs.append(nx.grid_2d_graph(i, j)) elif graph_type == 'lobster': graphs = [] p1 = 0.7 p2 = 0.7 count = 0 min_node = 10 max_node = 100 max_edge = 0 mean_node = 80 num_graphs = 100 seed_tmp = seed while count < num_graphs: G = nx.random_lobster(mean_node, p1, p2, seed=seed_tmp) if len(G.nodes()) >= min_node and len(G.nodes()) <= max_node: graphs.append(G) if G.number_of_edges() > max_edge: max_edge = G.number_of_edges() count += 1 seed_tmp += 1 elif graph_type == 'DD': graphs = graph_load_batch(data_dir, min_num_nodes=100, max_num_nodes=500, name='DD', node_attributes=False, graph_labels=True) # args.max_prev_node = 230 elif graph_type == 'FIRSTMM_DB': graphs = graph_load_batch(data_dir, min_num_nodes=0, max_num_nodes=10000, name='FIRSTMM_DB', node_attributes=False, graph_labels=True) elif graph_type == 'Transport': graphs = get_transport_graphs(data_dir) num_nodes = [gg.number_of_nodes() for gg in graphs] num_edges = [gg.number_of_edges() for gg in graphs] print('max # nodes = {} || mean # nodes = {}'.format( max(num_nodes), np.mean(num_nodes))) print('max # edges = {} || mean # edges = {}'.format( max(num_edges), np.mean(num_edges))) return graphs
prerential_attachment_graph = nx.barabasi_albert_graph(n, m) outpath = 'preferential_attachment_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(prerential_attachment_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Cluster Graph]') n = 100 m = 5 powerlaw_cluster_graph = nx.powerlaw_cluster_graph(n, m, 0.7) outpath = 'powerlaw_cluster_graph_' + str(n) + '_' + str(m) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Random Lobster]') n = 100 lobster_graph = nx.random_lobster(n, 0.7, 0.7) outpath = 'random_lobster_graph_' + str(n) + '.txt' nx.write_edgelist(lobster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Powerlaw Tree]') n = 100 powerlaw_tree = nx.random_powerlaw_tree(n, 3, None, 10000) outpath = 'powerlaw_tree_' + str(n) + '.txt' nx.write_edgelist(powerlaw_cluster_graph, outpath, data=False) convert_edgelist_to_graphviz(outpath) print('Generating [Bipartite Random Graph]') n = 100 m = 20 bipartite_random_graph = nx.bipartite_random_graph(n, m, 0.7)
import networkx as nx import matplotlib.pyplot as plt # can add nodes and edges manually G = nx.Graph() G.add_nodes_from([1,2,3]) G.add_edges_from([(1,2),(1,3),(2,3)]) # or generate graphs from built in methods k5 = nx.complete_graph(5) er = nx.erdos_renyi_graph(20, 0.10) red = nx.random_lobster(20, 0.5, 0.5) star = nx.star_graph(10) # get the number of basis cycles in G num_cycle = len(nx.cycle_basis(k5)) print("Number of cycles: " + str(num_cycle)) # draw and show nx.draw_circular(k5, node_size=20) plt.show()
write_json_graph(nx.balanced_tree(4, 4), 'balanced_tree(4,4).json') # write_json_graph(nx.balanced_tree(4, 5), 'balanced_tree(4,5).json') write_json_graph(nx.balanced_tree(4, 6), 'balanced_tree(4,6).json') write_json_graph(nx.balanced_tree(4, 8), 'balanced_tree(4,7).json') # write_json_graph(nx.balanced_tree(5, 2), 'balanced_tree(5,2).json') # write_json_graph(nx.balanced_tree(5, 4), 'balanced_tree(5,4).json') # write_json_graph(nx.barabasi_albert_graph(10, 5), 'barabasi_albert_graph(10,5).json') # write_json_graph(nx.barabasi_albert_graph(20, 3), 'barabasi_albert_graph(20,3).json') # write_json_graph(nx.barabasi_albert_graph(20, 10), 'barabasi_albert_graph(20,10).json') write_json_graph(nx.barabasi_albert_graph(50, 40), 'barabasi_albert_graph(50,40).json') # write_json_graph(nx.random_lobster(5, 0.6, 0.4, seed=0), 'random_lobster(5,0_6,0_4).json') # write_json_graph(nx.random_lobster(5, 0.4, 0.6, seed=0), 'random_lobster(5,0_4,0_6).json') write_json_graph(nx.random_lobster(10, 0.6, 0.4, seed=0), 'random_lobster(10,0_6,0_4).json') # write_json_graph(nx.random_lobster(10, 0.4, 0.6, seed=0), 'random_lobster(10,0_4,0_6).json') write_json_graph(nx.random_lobster(20, 0.6, 0.4, seed=0), 'random_lobster(20,0_6,0_4).json') # write_json_graph(nx.random_lobster(20, 0.4, 0.6, seed=0), 'random_lobster(20,0_4,0_6).json') write_json_graph(nx.random_lobster(50, 0.6, 0.4, seed=0), 'random_lobster(50,0_6,0_4).json') # write_json_graph(nx.random_lobster(50, 0.4, 0.6, seed=0), 'random_lobster(50,0_4,0_6).json') write_json_graph(nx.random_lobster(100, 0.6, 0.4, seed=0), 'random_lobster(100,0_6,0_4).json') # write_json_graph(nx.random_lobster(100, 0.4, 0.6, seed=0), 'random_lobster(100,0_4,0_6).json') # write_json_graph(nx.lollipop_graph(5, 4), 'lollipop_graph(5,4).json') write_json_graph(nx.lollipop_graph(10, 10), 'lollipop_graph(10,10).json') write_json_graph(nx.lollipop_graph(20, 50), 'lollipop_graph(20,50).json')
# Gather a random node from each connected component component_nodes = list() for component in nx.connected_components(G=G1): rand_node = random.choice(seq=list(component)) component_nodes.append(rand_node) # Connecting each selected node and adding edge to link together all other connected components for u, v in list(itertools.product(component_nodes, component_nodes)): if u != v: G1.add_edge(u_of_edge=u, v_of_edge=v) print(f'number of connected components (after): {nx.number_connected_components(G=G1)}') if __name__ == '__main__': g = nx.random_lobster(n=20, p1=0.5, p2=0) nx.draw(G=g, pos=nx.spring_layout(G=g)) plt.show(block=False) plt.savefig(fname='./Output/caterpillar_tree.jpg', format='JPG', dpi=300) g = nx.random_lobster(n=20, p1=0.5, p2=0.25) nx.draw(G=g, pos=nx.spring_layout(G=g)) plt.show(block=False) plt.savefig(fname='./Output/lobster_graph.jpg', format='JPG', dpi=300) # # Preliminary global data values used across all network samplings # start_node = 0 # number_of_nodes = 100 # sample size # n_trials = 10 # Number of repeated scoring for each sampler and scoreing metric pair, which finalizes into a mean over all trials # pool = mp.Pool(processes=mp.cpu_count() * n_trials)
def test104_random_lobster(self): """ Random lobster graph. """ g = nx.random_lobster(101, 0.3, 0.8) mate1 = mv.max_cardinality_matching(g) mate2 = nx.max_weight_matching(g, True) self.assertEqual(len(mate1), len(mate2))
def create_nx_graphs(graph_type, node_order='DFS', seed=1234): # Taken from GRAN: https://github.com/lrjconan/GRAN/blob/master/utils/data_helper.py npr = np.random.RandomState(seed) ### load datasets graphs = [] # synthetic graphs if graph_type == 'grid': graphs = [] for i in range(10, 20): for j in range(10, 20): graphs.append(nx.grid_2d_graph(i, j)) elif graph_type == 'lobster': graphs = [] p1 = 0.7 p2 = 0.7 count = 0 min_node = 20 max_node = 100 max_edge = 0 mean_node = 80 num_graphs = 100 seed_tmp = seed while count < num_graphs: G = nx.random_lobster(mean_node, p1, p2, seed=seed_tmp) if len(G.nodes()) >= min_node and len(G.nodes()) <= max_node: adj_mat = create_node_ordered_graph(G, node_order)[0] G = nx.from_numpy_matrix(adj_mat) graphs.append(G) draw_nx_graph(G, "Lobster_" + str(count)) if G.number_of_edges() > max_edge: max_edge = G.number_of_edges() count += 1 seed_tmp += 1 elif graph_type == 'prufer': graphs = [] count = 0 min_node = 20 max_node = 100 max_edge = 0 num_graphs = 100 save_path = './visualization/plots/Prufer/' seed_tmp = seed while count < num_graphs: num_nodes = np.random.randint(min_node, max_node) G = nx.random_tree(num_nodes, seed=seed_tmp) if len(G.nodes()) >= min_node and len(G.nodes()) <= max_node: adj_mat = create_node_ordered_graph(G, node_order)[0] G = nx.from_numpy_matrix(adj_mat) graphs.append(G) # draw_nx_graph(G,"Prufer_" + str(count), path=save_path) if G.number_of_edges() > max_edge: max_edge = G.number_of_edges() count += 1 seed_tmp += 1 num_nodes = [gg.number_of_nodes() for gg in graphs] num_edges = [gg.number_of_edges() for gg in graphs] print('max # nodes = {} || mean # nodes = {}'.format( max(num_nodes), np.mean(num_nodes))) print('max # edges = {} || mean # edges = {}'.format( max(num_edges), np.mean(num_edges))) return graphs, max(num_nodes), max(num_edges), num_nodes
def create_graph(topology, info): """Create a graph depending on the information in the info struct provided. """ if topology == 'simple': return nx.barabasi_albert_graph(info['num_nodes'], info['avg_degree']) elif topology == 'star': return nx.star_graph(info['num_nodes']) elif topology == 'tree': return nx.random_tree(info['num_nodes']) elif topology == 'lobster': return nx.random_lobster(info['num_nodes'], info['prob1'], info['prob2']) elif topology == "NORDUnet": G = nx.Graph() G.add_nodes_from(np.arange(24)) G.add_edges_from([(0, 2), (1, 5), (2, 4), (2, 5), (2, 6), (3, 4), (4, 6), (5, 6), (4, 8), (5, 11), (6, 8), (6, 9), (7, 8), (7, 15), (8, 9), (8, 10), (8, 11), (10, 11), (10, 12), (11, 13), (11, 14), (12, 13), (13, 14), (14, 15), (14, 17), (14, 22), (14, 23), (15, 16), (15, 18), (16, 18), (18, 19), (18, 23), (19, 21), (21, 20)]) return G elif topology == "GEANT": G = nx.Graph() G.add_nodes_from(np.arange(45)) G.add_edges_from([(0, 23), (1, 10), (2, 10), (2, 33), (2, 42), (2, 35), (2, 5), (2, 18), (2, 17), (2, 38), (2, 23), (3, 10), (4, 31), (4, 41), (5, 19), (5, 35), (5, 29), (6, 33), (7, 10), (7, 23), (7, 15), (7, 43), (8, 10), (8, 41), (9, 10), (9, 19), (10, 31), (10, 44), (10, 33), (10, 16), (10, 19), (10, 40), (10, 21), (10, 25), (11, 32), (11, 37), (11, 44), (11, 31), (11, 22), (12, 44), (12, 26), (13, 15), (13, 43), (13, 34), (14, 37), (15, 41), (16, 19), (17, 23), (18, 19), (18, 38), (19, 39), (19, 35), (19, 40), (19, 36), (19, 28), (20, 41), (21, 41), (22, 41), (23, 30), (23, 43), (24, 26), (24, 33), (25, 31), (27, 35), (29, 35), (31, 44), (32, 37), (34, 41)]) return G elif topology == "SURFnet": G = nx.Graph() G.add_nodes_from(np.arange(64)) G.add_edges_from([(0, 1), (0, 6), (1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (6, 7), (6, 8), (8, 9), (9, 10), (10, 7), (6, 11), (11, 14), (6, 14), (6, 33), (6, 31), (14, 13), (13, 17), (17, 20), (20, 24), (24, 31), (14, 31), (14, 7), (8, 12), (12, 18), (18, 21), (21, 33), (7, 15), (15, 19), (19, 22), (22, 25), (25, 34), (7, 34), (7, 16), (16, 33), (33, 34), (33, 34), (33, 26), (26, 27), (27, 28), (28, 29), (29, 30), (30, 34), (32, 33), (31, 32), (31, 35), (35, 32), (31, 36), (36, 38), (38, 40), (40, 42), (42, 44), (31, 44), (32, 45), (32, 37), (37, 39), (39, 41), (41, 45), (44, 45), (44, 47), (47, 48), (48, 49), (49, 45), (45, 46), (46, 43), (43, 34), (45, 34)]) return G else: print("Invalid network style received. Aborting...") exit(1)
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
import matplotlib.pyplot as plt import networkx as nx class PlotGraph(nx.Graph): def __repr__(self): return "Hey dude." def matrix(self): return nx.to_scipy_sparse_matrix(self) g = nx.random_lobster(10, 0.3, 0.2) def attach_eigen(g): g.eigen = "TODO: compute these" attach_eigen(g) g2 = PlotGraph(g) m = g2.matrix()
def test(): # ## Tutorial # # This guide can help you start working with NetworkX. # # ### Creating a graph # # Create an empty graph with no nodes and no edges. G = nx.Graph() # By definition, a `Graph` is a collection of nodes (vertices) along with # identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can # be any [hashable](https://docs.python.org/3/glossary.html#term-hashable) object e.g., a text string, an image, an XML object, # another Graph, a customized node object, etc. # # # Nodes # # The graph `G` can be grown in several ways. NetworkX includes many graph # generator functions and facilities to read and write graphs in many formats. # To get started though we’ll look at simple manipulations. You can add one node # at a time, G.add_node(1) # or add nodes from any [iterable](https://docs.python.org/3/glossary.html#term-iterable) container, such as a list G.add_nodes_from([2, 3]) # You can also add nodes along with node # attributes if your container yields 2-tuples of the form # `(node, node_attribute_dict)`: # # ``` # >>> G.add_nodes_from([ # ... (4, {"color": "red"}), # ... (5, {"color": "green"}), # ... ]) # ``` # # Node attributes are discussed further below. # # Nodes from one graph can be incorporated into another: H = nx.path_graph(10) G.add_nodes_from(H) # `G` now contains the nodes of `H` as nodes of `G`. # In contrast, you could use the graph `H` as a node in `G`. G.add_node(H) # The graph `G` now contains `H` as a node. This flexibility is very powerful as # it allows graphs of graphs, graphs of files, graphs of functions and much more. # It is worth thinking about how to structure your application so that the nodes # are useful entities. Of course you can always use a unique identifier in `G` # and have a separate dictionary keyed by identifier to the node information if # you prefer. # # # Edges # # `G` can also be grown by adding one edge at a time, G.add_edge(1, 2) e = (2, 3) G.add_edge(*e) # unpack edge tuple* # by adding a list of edges, G.add_edges_from([(1, 2), (1, 3)]) # or by adding any ebunch of edges. An *ebunch* is any iterable # container of edge-tuples. An edge-tuple can be a 2-tuple of nodes or a 3-tuple # with 2 nodes followed by an edge attribute dictionary, e.g., # `(2, 3, {'weight': 3.1415})`. Edge attributes are discussed further # below. G.add_edges_from(H.edges) # There are no complaints when adding existing nodes or edges. For example, # after removing all nodes and edges, G.clear() # we add new nodes/edges and NetworkX quietly ignores any that are # already present. G.add_edges_from([(1, 2), (1, 3)]) G.add_node(1) G.add_edge(1, 2) G.add_node("spam") # adds node "spam" G.add_nodes_from("spam") # adds 4 nodes: 's', 'p', 'a', 'm' G.add_edge(3, 'm') # At this stage the graph `G` consists of 8 nodes and 3 edges, as can be seen by: G.number_of_nodes() G.number_of_edges() # # Examining elements of a graph # # We can examine the nodes and edges. Four basic graph properties facilitate # reporting: `G.nodes`, `G.edges`, `G.adj` and `G.degree`. These # are set-like views of the nodes, edges, neighbors (adjacencies), and degrees # of nodes in a graph. They offer a continually updated read-only view into # the graph structure. They are also dict-like in that you can look up node # and edge data attributes via the views and iterate with data attributes # using methods `.items()`, `.data('span')`. # If you want a specific container type instead of a view, you can specify one. # Here we use lists, though sets, dicts, tuples and other containers may be # better in other contexts. list(G.nodes) list(G.edges) list(G.adj[1]) # or list(G.neighbors(1)) G.degree[1] # the number of edges incident to 1 # One can specify to report the edges and degree from a subset of all nodes # using an nbunch. An *nbunch* is any of: `None` (meaning all nodes), # a node, or an iterable container of nodes that is not itself a node in the # graph. G.edges([2, 'm']) G.degree([2, 3]) # # Removing elements from a graph # # One can remove nodes and edges from the graph in a similar fashion to adding. # Use methods # `Graph.remove_node()`, # `Graph.remove_nodes_from()`, # `Graph.remove_edge()` # and # `Graph.remove_edges_from()`, e.g. G.remove_node(2) G.remove_nodes_from("spam") list(G.nodes) G.remove_edge(1, 3) # # Using the graph constructors # # Graph objects do not have to be built up incrementally - data specifying # graph structure can be passed directly to the constructors of the various # graph classes. # When creating a graph structure by instantiating one of the graph # classes you can specify data in several formats. G.add_edge(1, 2) H = nx.DiGraph(G) # create a DiGraph using the connections from G list(H.edges()) edgelist = [(0, 1), (1, 2), (2, 3)] H = nx.Graph(edgelist) # # What to use as nodes and edges # # You might notice that nodes and edges are not specified as NetworkX # objects. This leaves you free to use meaningful items as nodes and # edges. The most common choices are numbers or strings, but a node can # be any hashable object (except `None`), and an edge can be associated # with any object `x` using `G.add_edge(n1, n2, object=x)`. # # As an example, `n1` and `n2` could be protein objects from the RCSB Protein # Data Bank, and `x` could refer to an XML record of publications detailing # experimental observations of their interaction. # # We have found this power quite useful, but its abuse # can lead to surprising behavior unless one is familiar with Python. # If in doubt, consider using `convert_node_labels_to_integers()` to obtain # a more traditional graph with integer labels. # # # Accessing edges and neighbors # # In addition to the views `Graph.edges`, and `Graph.adj`, # access to edges and neighbors is possible using subscript notation. G = nx.Graph([(1, 2, {"color": "yellow"})]) G[1] # same as G.adj[1] G[1][2] G.edges[1, 2] # You can get/set the attributes of an edge using subscript notation # if the edge already exists. G.add_edge(1, 3) G[1][3]['color'] = "blue" G.edges[1, 2]['color'] = "red" G.edges[1, 2] # Fast examination of all (node, adjacency) pairs is achieved using # `G.adjacency()`, or `G.adj.items()`. # Note that for undirected graphs, adjacency iteration sees each edge twice. FG = nx.Graph() FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) for n, nbrs in FG.adj.items(): for nbr, eattr in nbrs.items(): wt = eattr['weight'] if wt < 0.5: print(f"({n}, {nbr}, {wt:.3})") # Convenient access to all edges is achieved with the edges property. for (u, v, wt) in FG.edges.data('weight'): if wt < 0.5: print(f"({u}, {v}, {wt:.3})") # # Adding attributes to graphs, nodes, and edges # # Attributes such as weights, labels, colors, or whatever Python object you like, # can be attached to graphs, nodes, or edges. # # Each graph, node, and edge can hold key/value attribute pairs in an associated # attribute dictionary (the keys must be hashable). By default these are empty, # but attributes can be added or changed using `add_edge`, `add_node` or direct # manipulation of the attribute dictionaries named `G.graph`, `G.nodes`, and # `G.edges` for a graph `G`. # # ## Graph attributes # # Assign graph attributes when creating a new graph G = nx.Graph(day="Friday") G.graph # Or you can modify attributes later G.graph['day'] = "Monday" G.graph # # Node attributes # # Add node attributes using `add_node()`, `add_nodes_from()`, or `G.nodes` G.add_node(1, time='5pm') G.add_nodes_from([3], time='2pm') G.nodes[1] G.nodes[1]['room'] = 714 G.nodes.data() # Note that adding a node to `G.nodes` does not add it to the graph, use # `G.add_node()` to add new nodes. Similarly for edges. # # # Edge Attributes # # Add/change edge attributes using `add_edge()`, `add_edges_from()`, # or subscript notation. G.add_edge(1, 2, weight=4.7) G.add_edges_from([(3, 4), (4, 5)], color='red') G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})]) G[1][2]['weight'] = 4.7 G.edges[3, 4]['weight'] = 4.2 # The special attribute `weight` should be numeric as it is used by # algorithms requiring weighted edges. # # Directed graphs # # The `DiGraph` class provides additional methods and properties specific # to directed edges, e.g., # `DiGraph.out_edges`, `DiGraph.in_degree`, # `DiGraph.predecessors()`, `DiGraph.successors()` etc. # To allow algorithms to work with both classes easily, the directed versions of # `neighbors()` is equivalent to `successors()` while `degree` reports # the sum of `in_degree` and `out_degree` even though that may feel # inconsistent at times. DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) DG.out_degree(1, weight='weight') DG.degree(1, weight='weight') list(DG.successors(1)) list(DG.neighbors(1)) # Some algorithms work only for directed graphs and others are not well # defined for directed graphs. Indeed the tendency to lump directed # and undirected graphs together is dangerous. If you want to treat # a directed graph as undirected for some measurement you should probably # convert it using `Graph.to_undirected()` or with H = nx.Graph(G) # create an undirected graph H from a directed graph G # # Multigraphs # # NetworkX provides classes for graphs which allow multiple edges # between any pair of nodes. The `MultiGraph` and # `MultiDiGraph` # classes allow you to add the same edge twice, possibly with different # edge data. This can be powerful for some applications, but many # algorithms are not well defined on such graphs. # Where results are well defined, # e.g., `MultiGraph.degree()` we provide the function. Otherwise you # should convert to a standard graph in a way that makes the measurement # well defined. MG = nx.MultiGraph() MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) dict(MG.degree(weight='weight')) GG = nx.Graph() for n, nbrs in MG.adjacency(): for nbr, edict in nbrs.items(): minvalue = min([d['weight'] for d in edict.values()]) GG.add_edge(n, nbr, weight=minvalue) nx.shortest_path(GG, 1, 3) # # Graph generators and graph operations # # In addition to constructing graphs node-by-node or edge-by-edge, they # can also be generated by # # 1. Applying classic graph operations, such as: # # 1. Using a call to one of the classic small graphs, e.g., # # 1. Using a (constructive) generator for a classic graph, e.g., # # like so: K_5 = nx.complete_graph(5) K_3_5 = nx.complete_bipartite_graph(3, 5) barbell = nx.barbell_graph(10, 10) lollipop = nx.lollipop_graph(10, 20) # 1. Using a stochastic graph generator, e.g, # # like so: er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) # 1. Reading a graph stored in a file using common graph formats, # such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others. nx.write_gml(red, "path.to.file") mygraph = nx.read_gml("path.to.file") # For details on graph formats see Reading and writing graphs # and for graph generator functions see Graph generators # # # Analyzing graphs # # The structure of `G` can be analyzed using various graph-theoretic # functions such as: G = nx.Graph() G.add_edges_from([(1, 2), (1, 3)]) G.add_node("spam") # adds node "spam" list(nx.connected_components(G)) sorted(d for n, d in G.degree()) nx.clustering(G) # Some functions with large output iterate over (node, value) 2-tuples. # These are easily stored in a [dict](https://docs.python.org/3/library/stdtypes.html#dict) structure if you desire. sp = dict(nx.all_pairs_shortest_path(G)) sp[3] # See Algorithms for details on graph algorithms # supported. #99 # # Drawing graphs # # NetworkX is not primarily a graph drawing package but basic drawing with # Matplotlib as well as an interface to use the open source Graphviz software # package are included. These are part of the `networkx.drawing` module and will # be imported if possible. # # First import Matplotlib’s plot interface (pylab works too) import matplotlib.pyplot as plt # To test if the import of `networkx.drawing` was successful draw `G` using one of G = nx.petersen_graph() plt.subplot(121) nx.draw(G, with_labels=True, font_weight='bold') plt.subplot(122) nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold') # when drawing to an interactive display. Note that you may need to issue a # Matplotlib plt.show() # command if you are not using matplotlib in interactive mode (see # [Matplotlib FAQ](http://matplotlib.org/faq/installing_faq.html#matplotlib-compiled-fine-but-nothing-shows-up-when-i-use-it) # ). options = { 'node_color': 'black', 'node_size': 100, 'width': 3, } plt.subplot(221) nx.draw_random(G, **options) plt.subplot(222) nx.draw_circular(G, **options) plt.subplot(223) nx.draw_spectral(G, **options) plt.subplot(224) nx.draw_shell(G, nlist=[range(5, 10), range(5)], **options) # You can find additional options via `draw_networkx()` and # layouts via `layout`. # You can use multiple shells with `draw_shell()`. G = nx.dodecahedral_graph() shells = [[2, 3, 4, 5, 6], [8, 1, 0, 19, 18, 17, 16, 15, 14, 7], [9, 10, 11, 12, 13]] nx.draw_shell(G, nlist=shells, **options) # To save drawings to a file, use, for example nx.draw(G) plt.savefig("path.png") # writes to the file `path.png` in the local directory. If Graphviz and # PyGraphviz or pydot, are available on your system, you can also use # `nx_agraph.graphviz_layout(G)` or `nx_pydot.graphviz_layout(G)` to get the # node positions, or write the graph in dot format for further processing. from networkx.drawing.nx_pydot import write_dot pos = nx.nx_agraph.graphviz_layout(G) nx.draw(G, pos=pos) write_dot(G, 'file.dot')