def test_circular_ladder_graph(self): G = nx.circular_ladder_graph(5) pytest.raises( nx.NetworkXError, nx.circular_ladder_graph, 5, create_using=nx.DiGraph ) mG = nx.circular_ladder_graph(5, create_using=nx.MultiGraph) assert edges_equal(mG.edges(), G.edges())
def test_periodic(self): G = nx.grid_2d_graph(0, 0, periodic=True) assert_equal(dict(G.degree()), {}) for m, n, H in [(2, 2, nx.cycle_graph(4)), (1, 7, nx.cycle_graph(7)), (7, 1, nx.cycle_graph(7)), (2, 5, nx.circular_ladder_graph(5)), (5, 2, nx.circular_ladder_graph(5)), (2, 4, nx.cubical_graph()), (4, 2, nx.cubical_graph())]: G = nx.grid_2d_graph(m, n, periodic=True) assert_true(nx.could_be_isomorphic(G, H))
def GenerateGraphs(size, base): dic=GenerateDic(size,base) for i in range(1,5): for j in range(10): G=AddEdges(nx.wheel_graph(size)) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"wheel"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"wheel"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"wheel"].append(Boyk(G,nodes[0],nodes[1])) G=AddEdges(nx.circular_ladder_graph(size)) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"circ"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"circ"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"circ"].append(Boyk(G,nodes[0],nodes[1])) G=AddEdges(nx.dense_gnm_random_graph(size,int(size*size*0.2 ))) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"comp"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"comp"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"comp"].append(Boyk(G,nodes[0],nodes[1])) size*=base; df=pd.DataFrame(dic) df.to_csv("matrix.csv")
def generate_connection_graph(graph_type, params, count): lower_type = graph_type.lower() if lower_type == 'complete': assert (len(params) == 0) return networkx.complete_graph(count) elif lower_type == 'complete-bipartite': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) n1 = int(round(count * float(params[0]) / float(params[1]))) n2 = int(round(count * float(params[1]) / float(params[0]))) n1 = 1 if n1 < 1 else n1 n2 = 1 if n2 < 1 else n2 return networkx.complete_bipartite_graph(n1, n2) elif lower_type == 'circular-ladder': assert (len(params) == 0) return networkx.circular_ladder_graph(count) elif lower_type == 'cycle': assert (len(params) == 0) return networkx.cycle_graph(count) elif lower_type == 'periodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, True) elif lower_type == 'nonperiodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, False) elif lower_type == 'hypercube': assert (len(params) == 0) return networkx.hypercube_graph(int(round(math.log(count, 2)))) elif lower_type == 'star': assert (len(params) == 0) return networkx.star_graph(count - 1) elif lower_type == 'wheel': assert (len(params) == 0) return networkx.wheel_graph(count) elif lower_type == 'erdos-reyni': assert (len(params) == 1) return networkx.erdos_renyi_graph(count, float(params[0])) elif lower_type == 'watts-strogatz': assert (len(params) == 2) if int(params[0]) >= count / 2: k = int(count / 2 - 1) else: k = int(params[0]) return networkx.connected_watts_strogatz_graph(count, k, int(params[1])) else: print "Unknown graph type {}".format(lower_type) assert False
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 test_relabel_inplace(self): graph = nx.circular_ladder_graph(12) decision_variables = (0, 2, 5) feasible_configurations = {(1, 1, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) mapping = { i: v for i, v in enumerate('abcdefghijklmnopqrstuvwxyz') if i in graph } new_spec = spec.relabel_variables(mapping, copy=False) self.assertIs(new_spec, spec) # should be the same object self.assertIs(new_spec.graph, spec.graph) # create a test spec graph = nx.relabel_nodes(graph, mapping) decision_variables = (mapping[v] for v in decision_variables) test_spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) self.assertEqual(new_spec, test_spec) self.assertEqual(new_spec.ising_linear_ranges, test_spec.ising_linear_ranges) self.assertEqual(new_spec.ising_quadratic_ranges, test_spec.ising_quadratic_ranges)
def test_relabel_copy(self): graph = nx.circular_ladder_graph(12) decision_variables = (0, 2, 5) feasible_configurations = {(1, 1, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) mapping = dict(enumerate('abcdefghijklmnopqrstuvwxyz')) new_spec = spec.relabel_variables(mapping, copy=True) # create a test spec graph = nx.relabel_nodes(graph, mapping) decision_variables = (mapping[v] for v in decision_variables) test_spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) self.assertEqual(new_spec, test_spec) self.assertEqual(new_spec.ising_linear_ranges, test_spec.ising_linear_ranges) self.assertEqual(new_spec.ising_quadratic_ranges, test_spec.ising_quadratic_ranges)
def _getGraph(self, values): n = values['Nodes'] G = nx.circular_ladder_graph(n) nodes = layout.circularNodes(n, 20) + layout.circularNodes(n, 40) return G, nodes
def classic_graphs(): print("Balanced Tree") BG = nx.balanced_tree(3, 2) draw_graph(BG) print("Barbell Graph") BBG = nx.barbell_graph(3, 2) draw_graph(BBG) print("Complete Graph") CG = nx.complete_graph(10) draw_graph(CG) print("Complete Multipartite Graph") CMG = nx.complete_multipartite_graph(1, 2, 10) print([CMG.node[u]['block'] for u in CMG]) print(CMG.edges(0)) print(CMG.edges(2)) print(CMG.edges(4)) draw_graph(CMG) print("Circular Ladder Graph") CLG = nx.circular_ladder_graph(5) draw_graph(CLG) print("Dorogovtsev Goltsev Mendes Graph") DGMG = nx.dorogovtsev_goltsev_mendes_graph(3) draw_graph(DGMG) print("Empty Graph") EG = nx.empty_graph(5, create_using=nx.DiGraph()) draw_graph(EG) print("Grid 2D Graph") G2DG = nx.grid_2d_graph(5, 6) draw_graph(G2DG) print("Grid Graph") GDG = nx.grid_graph(dim=[5, 2]) draw_graph(GDG) print("Hypercube Graph") HG = nx.hypercube_graph(3) draw_graph(HG) print("Ladder Graph") LG = nx.ladder_graph(8) draw_graph(LG) print("Ladder Graph") LG = nx.ladder_graph(8) draw_graph(LG) print("Lollipop Graph") LPG = nx.lollipop_graph(n=6, m=4) draw_graph(LPG) print("Null Graph") NG = nx.null_graph() draw_graph(NG) print("Path Graph") PG = nx.path_graph(16) draw_graph(PG) print("Star Graph") SG = nx.star_graph(16) draw_graph(SG) print("Trivial Graph") TG = nx.trivial_graph() draw_graph(TG) print("Wheel Graph") WG = nx.wheel_graph(n=18) draw_graph(WG)
def generate_struct_mask(struct, n_nodes, shuffle_nodes): # a horrible collection of ifs due to args in nx constructors if struct == "star": g = nx.star_graph(n_nodes) elif struct == "random_tree": g = nx.random_tree(n_nodes) elif struct == "powerlaw_tree": g = nx.powerlaw_tree(n_nodes, gamma=3, seed=None) elif struct == "binary_tree": raise NotImplementedError("Implement a binary tree.") elif struct == "path": g = nx.path_graph(n_nodes) elif struct == "cycle": g = nx.cycle_graph(n_nodes) elif struct == "ladder": g = nx.ladder_graph(n_nodes) elif struct == "grid": m = np.random.choice(range(1, n_nodes+1)) n = n_nodes // m g = nx.grid_2d_graph(m, n) elif struct == "circ_ladder": g = nx.circular_ladder_graph(n_nodes) elif struct == "barbell": assert n_nodes >= 4 m = np.random.choice(range(2, n_nodes-1)) blocks = (m, n_nodes-m) g = nx.barbell_graph(*blocks) elif struct == "loll": assert n_nodes >= 2 m = np.random.choice(range(2, n_nodes+1)) g = nx.lollipop_graph(m, n_nodes-m) elif struct == "wheel": g = nx.wheel_graph(n_nodes) elif struct == "bipart": m = np.random.choice(range(n_nodes)) blocks = (m, n_nodes-m) g = nx.complete_multipartite_graph(*blocks) elif struct == "tripart": # allowed to be zero m, M = np.random.choice(range(n_nodes), size=2) if m > M: m, M = M, m blocks = (m, M-m, n_nodes-M) g = nx.complete_multipartite_graph(*blocks) elif struct == "fc": g = nx.complete_graph(n_nodes) else: raise NotImplementedError("Structure {} not implemented yet.".format(struct)) node_order = list(range(n_nodes)) if shuffle_nodes: np.random.shuffle(node_order) # a weird subclass by default; raises a deprecation warning # with a new update of networkx, this should be updated to # nx.convert_matrix.to_numpy_array np_arr_g = nx.to_numpy_matrix(g, nodelist=node_order) return np_arr_g.astype(int)
def test_relabel_inplace_identity(self): graph = nx.circular_ladder_graph(12) decision_variables = (0, 2, 5) feasible_configurations = {(1, 1, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=pm.SPIN) mapping = {v: v for v in graph} new_spec = spec.relabel_variables(mapping, copy=False)
def test_relabel_inplace_overlap(self): graph = nx.circular_ladder_graph(12) decision_variables = (0, 2, 5) feasible_configurations = {(1, 1, 1): 0.} spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN) mapping = {v: v + 5 for v in graph} new_spec = spec.relabel_variables(mapping, inplace=True)
def create_mixing_matrix(topology, n_cores): """ Builds the communication matrix according to a topology and a number of clients. Params: topology (string): the chosen topology, either ring, grid or centralized n_cores (int): the number of clients constituting the network Returns: W (numpy.array): the generated communication matrix """ assert topology in [ 'ring', 'centralized', 'grid', 'disconnected', 'star', 'ladder' ] if topology == 'ring': W = np.zeros(shape=(n_cores, n_cores)) value = 1. / 3 if n_cores >= 3 else 1. / 2 np.fill_diagonal(W, value) np.fill_diagonal(W[1:], value, wrap=False) np.fill_diagonal(W[:, 1:], value, wrap=False) W[0, n_cores - 1] = value W[n_cores - 1, 0] = value return W elif topology == 'centralized': W = np.ones((n_cores, n_cores), dtype=np.float64) / n_cores return W elif topology == 'grid': #assert int(np.sqrt(n_cores)) ** 2 == n_cores # n_cores must be a square G = nx.generators.lattice.grid_2d_graph(int(np.sqrt(n_cores)), int(np.sqrt(n_cores)), periodic=True) W = nx.adjacency_matrix(G).toarray() for i in range(0, W.shape[0]): W[i][i] = 1 W = W / 5 return W elif topology == 'star': G = nx.star_graph(n_cores - 1) W = nx.adjacency_matrix(G).toarray() for i in range(0, W.shape[0]): W[i][i] = 1 W = W / 2 W[0] = np.full((n_cores), 1. / n_cores) # W[:1] = W[:1] / num_nodes return W elif topology == 'ladder': assert int(n_cores / 2) * 2 == n_cores # n_cores must be even G = nx.circular_ladder_graph(n_cores // 2) W = nx.adjacency_matrix(G).toarray() for i in range(0, W.shape[0]): W[i][i] = 1 W = W / 4 return W else: # topology == 'disconnected' W = np.zeros(shape=(n_cores, n_cores)) np.fill_diagonal(W, 1, wrap=False) return W
def CircularLadderGraph(n): """ Returns a circular ladder graph with 2\*n nodes. A Circular ladder graph is a ladder graph that is connected at the ends, i.e.: a ladder bent around so that top meets bottom. Thus it can be described as two parallel cycle graphs connected at each corresponding node pair. This constructor depends on NetworkX numeric labels. PLOTTING: Upon construction, the position dictionary is filled to override the spring-layout algorithm. By convention, the circular ladder graph is displayed as an inner and outer cycle pair, with the first n nodes drawn on the inner circle. The first (0) node is drawn at the top of the inner-circle, moving clockwise after that. The outer circle is drawn with the (n+1)th node at the top, then counterclockwise as well. EXAMPLES: Construct and show a circular ladder graph with 26 nodes :: sage: g = graphs.CircularLadderGraph(13) sage: g.show() # long time Create several circular ladder graphs in a Sage graphics array :: sage: g = [] sage: j = [] sage: for i in range(9): ....: k = graphs.CircularLadderGraph(i+3) ....: g.append(k) sage: for i in range(3): ....: n = [] ....: for m in range(3): ....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False)) ....: j.append(n) sage: G = sage.plot.graphics.GraphicsArray(j) sage: G.show() # long time """ pos_dict = {} for i in range(n): x = float(cos((pi/2) + ((2*pi)/n)*i)) y = float(sin((pi/2) + ((2*pi)/n)*i)) pos_dict[i] = [x,y] for i in range(n,2*n): x = float(2*(cos((pi/2) + ((2*pi)/n)*(i-n)))) y = float(2*(sin((pi/2) + ((2*pi)/n)*(i-n)))) pos_dict[i] = (x,y) import networkx G = networkx.circular_ladder_graph(n) return graph.Graph(G, pos=pos_dict, name="Circular Ladder graph")
def CircularLadderGraph(n): """ Returns a circular ladder graph with 2\*n nodes. A Circular ladder graph is a ladder graph that is connected at the ends, i.e.: a ladder bent around so that top meets bottom. Thus it can be described as two parallel cycle graphs connected at each corresponding node pair. This constructor depends on NetworkX numeric labels. PLOTTING: Upon construction, the position dictionary is filled to override the spring-layout algorithm. By convention, the circular ladder graph is displayed as an inner and outer cycle pair, with the first n nodes drawn on the inner circle. The first (0) node is drawn at the top of the inner-circle, moving clockwise after that. The outer circle is drawn with the (n+1)th node at the top, then counterclockwise as well. EXAMPLES: Construct and show a circular ladder graph with 26 nodes :: sage: g = graphs.CircularLadderGraph(13) sage: g.show() # long time Create several circular ladder graphs in a Sage graphics array :: sage: g = [] sage: j = [] sage: for i in range(9): ....: k = graphs.CircularLadderGraph(i+3) ....: g.append(k) sage: for i in range(3): ....: n = [] ....: for m in range(3): ....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False)) ....: j.append(n) sage: G = sage.plot.graphics.GraphicsArray(j) sage: G.show() # long time """ pos_dict = {} for i in range(n): x = float(cos((pi / 2) + ((2 * pi) / n) * i)) y = float(sin((pi / 2) + ((2 * pi) / n) * i)) pos_dict[i] = [x, y] for i in range(n, 2 * n): x = float(2 * (cos((pi / 2) + ((2 * pi) / n) * (i - n)))) y = float(2 * (sin((pi / 2) + ((2 * pi) / n) * (i - n)))) pos_dict[i] = (x, y) import networkx G = networkx.circular_ladder_graph(n) return graph.Graph(G, pos=pos_dict, name="Circular Ladder graph")
def compare_times(gtype, n_max, n_min=2, chords=0): """ Compare computational times between the Deletion-Contraction algorithm, and its optimized version :param gtype: <GType> graph type (enum object) :param n_max: maximum number of nodes :param n_min: minimum number of nodes (2 by default) :param chords: number of chords (only in the case of random hamiltonian graphs), 0 by default :return: dictionary with all the times where <key=nodes, value = both times (pair object) """ print("----------------------------------------------", gtype.name, "------------------------------------------------") times = dict() for n in range(n_min, n_max + 1): print("\n-----------> n =", n) if gtype == GType.Hypercube: g = nx.hypercube_graph(n) elif gtype == GType.Grid: g = nx.grid_graph([n, n]) elif gtype == GType.CircularLadder: g = nx.circular_ladder_graph(n) elif gtype == GType.Complete: g = nx.complete_graph(n) elif gtype == GType.RandomHamiltonian: g = GraphTools.gen_random_hamiltonian(n, chords) start1 = time.time() poly = GraphRel.relpoly_binary_basic(g) end1 = time.time() t1 = end1 - start1 print(Utilities.polynomial2binomial(poly)) print("Basic - ", gtype.name, " ", n, ":", t1) start2 = time.time() poly = GraphRel.relpoly_binary_improved(g) end2 = time.time() t2 = end2 - start2 print(Utilities.polynomial2binomial(poly)) print("Advanced - ", gtype.name, " ", n, ":", t2) times[n] = (t1, t2) try: print("SP efficientcy compared to basic: ", round(t1 * 100 / t2, 3), "%") except (ZeroDivisionError): print("SP efficientcy compared to basic: ", round(t1 * 100, 3), "%") print( "-------------------------------------------------------------------------------------------------------" ) return times
def get_test_graphs() -> List[nx.Graph]: # return nx.graph_atlas_g()[1:100] names = [ "Path graph (10)", "Complete graph (30)", "Balanced Tree (2, 3)", "Barbell graph (5, 1)", "Binomial tree (4)", "Circular ladder graph (5)", "Cycle graph (10)", "Star graph (10)", "Wheel graph (6)" ] optimal_colorings = [2, 30, 2, 5, 2, 3, 2, 2, 4] graphs = [ nx.path_graph(10), nx.complete_graph(30), nx.balanced_tree(2, 3), nx.barbell_graph(5, 1), nx.binomial_tree(4), nx.circular_ladder_graph(5), nx.cycle_graph(10), nx.star_graph(10), nx.wheel_graph(6) ] # load graph instances for file in os.listdir("./instances"): new_graph = nx.Graph() with open(os.path.join("instances", file), "r") as f: # data = f.read() edges = [] line = f.readline() line.strip() while line: if " " not in line: break # need indexes to be from 0 edges.append([int(x) - 1 for x in line.split(" ")]) line = f.readline() line.strip() # last line is the optimal coloring if line == '?': continue # ignore graphs for which we don't know the optimal coloring new_graph.add_edges_from(edges) if len(new_graph.nodes) > 200 or len(new_graph.edges) > 5000: continue names.append(file) optimal_colorings.append(line) graphs.append(new_graph) for i, g in enumerate(graphs): g.name = names[i] return graphs, optimal_colorings
def test_n_communities_parameter(): G = nx.circular_ladder_graph(4) # No aggregation: expected = [{k} for k in range(8)] assert greedy_modularity_communities(G, n_communities=8) == expected # Aggregation to half order (number of nodes) expected = [{k, k + 1} for k in range(0, 8, 2)] assert greedy_modularity_communities(G, n_communities=4) == expected # Default aggregation case (here, 2 communities emerge) expected = [frozenset(range(0, 4)), frozenset(range(4, 8))] assert greedy_modularity_communities(G, n_communities=1) == expected
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 == 'circular ladder': return nx.circular_ladder_graph(info['num_nodes']) else: print("Invalid network style received. Aborting...") exit(1)
def make_graph(g_name, n): switcher = { "path": nx.path_graph(n), "complete": nx.complete_graph(n), "binomial tree": nx.binomial_tree(n), "circular ladder": nx.circular_ladder_graph(n), "cycle": nx.cycle_graph(n), "dorogovtsev": nx.dorogovtsev_goltsev_mendes_graph(n), "ladder": nx.ladder_graph(n), "star": nx.star_graph(n), "wheel": nx.wheel_graph(n), "margulis gabber galil": nx.margulis_gabber_galil_graph(n), "chordal cycle": nx.chordal_cycle_graph(n), "hypercube": nx.hypercube_graph(n), "mycielski": nx.mycielski_graph(n) } return switcher.get(g_name)
def graphGenerator(): if args.graph_type == "erdos_renyi": return networkx.erdos_renyi_graph(args.graph_size,args.graph_p) if args.graph_type == "balanced_tree": ndim = int(np.ceil(np.log(args.graph_size)/np.log(args.graph_degree))) return networkx.balanced_tree(args.graph_degree,ndim) if args.graph_type == "cicular_ladder": ndim = int(np.ceil(args.graph_size*0.5)) return networkx.circular_ladder_graph(ndim) if args.graph_type == "cycle": return networkx.cycle_graph(args.graph_size) if args.graph_type == 'grid_2d': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.grid_2d_graph(ndim,ndim) if args.graph_type == 'lollipop': ndim = int(np.ceil(args.graph_size*0.5)) return networkx.lollipop_graph(ndim,ndim) if args.graph_type =='expander': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.margulis_gabber_galil_graph(ndim) if args.graph_type =="hypercube": ndim = int(np.ceil(np.log(args.graph_size)/np.log(2.0))) return networkx.hypercube_graph(ndim) if args.graph_type =="star": ndim = args.graph_size-1 return networkx.star_graph(ndim) if args.graph_type =='barabasi_albert': return networkx.barabasi_albert_graph(args.graph_size,args.graph_degree) if args.graph_type =='watts_strogatz': return networkx.connected_watts_strogatz_graph(args.graph_size,args.graph_degree,args.graph_p) if args.graph_type =='regular': return networkx.random_regular_graph(args.graph_degree,args.graph_size) if args.graph_type =='powerlaw_tree': return networkx.random_powerlaw_tree(args.graph_size) if args.graph_type =='small_world': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.navigable_small_world_graph(ndim) if args.graph_type =='geant': return topologies.GEANT() if args.graph_type =='dtelekom': return topologies.Dtelekom() if args.graph_type =='abilene': return topologies.Abilene() if args.graph_type =='servicenetwork': return topologies.ServiceNetwork()
def ___test_for_special_graphs(graphs, size): cycle = nx.cycle_graph(size) path = nx.path_graph(size) star = nx.star_graph(size) cycl_ladder = nx.circular_ladder_graph(size) ladder = nx.ladder_graph(size) wheel = nx.wheel_graph(size) cycle_found = False path_found = False star_found = False cycl_ladder_found = False ladder_found = False wheel_found = False # Check if we sampled on of this special graphs for g in graphs: if nx.is_isomorphic(g, cycle): cycle_found = True if nx.is_isomorphic(g, path): path_found = True if nx.is_isomorphic(g, star): star_found = True if nx.is_isomorphic(g, cycl_ladder): cycl_ladder_found = True if nx.is_isomorphic(g, ladder): ladder_found = True if nx.is_isomorphic(g, wheel): wheel_found = True print("Sampled cycle............................{}".format(cycle_found)) print("Sampled path.............................{}".format(path_found)) print("Sampled star.............................{}".format(star_found)) print("Sampled circular ladder..................{}".format( cycl_ladder_found)) print("Sampled ladder...........................{}".format(ladder_found)) print("Sampled wheel............................{}".format(wheel_found)) passed = cycle_found and path_found and star_found and cycl_ladder_found and ladder_found and wheel_found return passed
def graphPartition(G, clusterSize): numClusters = math.ceil( len(G) / float(clusterSize) ) # heuristic for # of clusters given approximately equal cluster size print numClusters (edgecuts, parts) = metis.part_graph(G, int(numClusters)) # k-way cut algorithm colors = [ 'red', 'blue', 'green', 'orange', 'yellow', 'purple', 'black', 'maroon', 'brown', 'indigo', 'cyan' ] for i, p in enumerate(parts): #print i, p G.node[i]['color'] = colors[p] nx.drawing.nx_pydot.write_dot( G, 'example.dot') # writes graph partition into dot file format result = pgv.AGraph( 'example.dot' ) # load dot format representation of graph to create visualization result.node_attr.update(shape='circle') result.node_attr.update(label=' ') result.node_attr.update(style='filled') result.layout() # default layout result.draw('example.svg') # writes visualization as svg file print("Wrote example.svg") graphPartition(nx.circular_ladder_graph(25), 10)
def test_result_circular_ladder_graph_5(self): assert (calc_and_compare(NX.circular_ladder_graph(5)))
not_thrown = "{} not thrown".format(negative_cycle) try: impl(G, source) return not_thrown, thrown except Exception as e: if is_negative_cycle_ex(e): return thrown, thrown else: raise tests = [ lambda: sssp_test(dijkstra, with_weight_w(nx.path_graph(10)), 0), # 0 lambda: sssp_test(dijkstra, with_weight_w(nx.star_graph(10), 2.0), 0), # 1 lambda: sssp_test(dijkstra, with_weight_w(nx.complete_graph(10)), 0), # 2 lambda: sssp_test(dijkstra, with_weight_w(nx.circular_ladder_graph(20), 2.0 ), 0), # 3 lambda: sssp_negative_cycle_test(bellman_ford, G_negative_cycle, 0), # 4 lambda: sssp_test(bellman_ford, with_weight_w(nx.path_graph(10)), 0), # 5 lambda: sssp_test(bellman_ford, with_weight_w(nx.star_graph(10), 2.0), 0 ), # 6 lambda: sssp_test(bellman_ford, with_weight_w(nx.complete_graph(10)), 0 ), # 7 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(20), 2.0), 0 ), # 8 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(4), 2.0), 0), # 9 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(6), 2.0), 0 ), # 10
# This example solves a few small examples of a known graph problem, # minimum vertex cover. A vertex cover is a set of vertices such that # each edge of the graph is incident with at least one vertex in the set. # A minimum vertex cover is the vertex cover of smallest size. import networkx as nx s5 = nx.star_graph(4) # Solving classically on a CPU from dimod.reference.samplers import ExactSolver sampler = ExactSolver() import dwave_networkx as dnx print(dnx.min_vertex_cover(s5, sampler)) # Solving on a D-Wave System # A five-node star graph from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite sampler = EmbeddingComposite(DWaveSampler()) print(dnx.min_vertex_cover(s5, sampler)) # Additional problem graphs # A five-node (wheel) graph w5 = nx.wheel_graph(5) print(dnx.min_vertex_cover(w5, sampler)) print(dnx.min_vertex_cover(w5, sampler)) # A ten-node (circular-ladder) graph c5 = nx.circular_ladder_graph(5) print(dnx.min_vertex_cover(c5, sampler)) print(dnx.min_vertex_cover(c5, sampler))
# -*- coding: utf-8 -*- """ Created on Mon Apr 1 11:44:11 2019 @author: maari """ import networkx as nx import matplotlib.pyplot as plt #Grafo con el generador 1 G = nx.circular_ladder_graph(8) nx.draw_networkx(G, node_color='b',node_size=200, edge_color='k',arrowsize=10,width=1, font_size=0) plt.axis('off') plt.savefig("G1.eps") plt.show() #Grafo con el generador 2 H = nx.grid_graph(dim=[4,4]) nx.draw_networkx(H, node_color='b',node_size=200, edge_color='k',arrowsize=10,width=1,
thrown = "{} thrown".format(negative_cycle) not_thrown = "{} not thrown".format(negative_cycle) try: impl(G, source) return not_thrown, thrown except Exception as e: if is_negative_cycle_ex(e): return thrown, thrown else: raise tests = [ lambda: sssp_test(dijkstra, with_weight_w(nx.path_graph(10)), 0), # 0 lambda: sssp_test(dijkstra, with_weight_w(nx.star_graph(10), 2.0), 0), # 1 lambda: sssp_test(dijkstra, with_weight_w(nx.complete_graph(10)), 0), # 2 lambda: sssp_test(dijkstra, with_weight_w(nx.circular_ladder_graph(20), 2.0), 0), # 3 lambda: sssp_negative_cycle_test(bellman_ford, G_negative_cycle, 0), # 4 lambda: sssp_test(bellman_ford, with_weight_w(nx.path_graph(10)), 0), # 5 lambda: sssp_test(bellman_ford, with_weight_w(nx.star_graph(10), 2.0), 0), # 6 lambda: sssp_test(bellman_ford, with_weight_w(nx.complete_graph(10)), 0), # 7 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(20), 2.0), 0), # 8 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(4), 2.0), 0), # 9 lambda: sssp_test(bellman_ford, with_weight_w(nx.circular_ladder_graph(6), 2.0), 0), # 10 lambda: sssp_test(bellman_ford, G_negative_edges, 0), # 11 lambda: sssp_test(dial, with_weight_w(nx.path_graph(10)), 0), # 12 lambda: sssp_test(dial, with_weight_w(nx.star_graph(10), 2.0), 0), # 13 lambda: sssp_test(dial, with_weight_w(nx.complete_graph(10)), 0), # 14 lambda: sssp_test(dial, with_weight_w(nx.circular_ladder_graph(20), 2.0), 0), # 15 lambda: sssp_test(dial, G_spt_different_weights, 0), # 16 lambda: sssp_test(delta_stepping, with_weight_w(nx.path_graph(10)), 0), # 17 lambda: sssp_test(delta_stepping, with_weight_w(nx.star_graph(10), 2.0), 0), # 18
# we can use in-built graph generator to create sample graphs based on different graph model G = nx.complete_graph(50) # this will create a completely connected graph with 50 nodes # %% # plot the graph nx.draw(G) # %% # for demo purpose we plot a few other network types fig, ax = plt.subplots(3, 4, figsize=(15,12)) G = nx.scale_free_graph(50) nx.draw(nx.complete_graph(50), ax=ax[0,0]) nx.draw(nx.star_graph(50), ax=ax[0,1]) nx.draw(nx.circular_ladder_graph(50), ax=ax[0,2]) nx.draw(nx.ladder_graph(50), ax=ax[0,3]) nx.draw(nx.path_graph(50), ax=ax[1,0]) nx.draw(nx.wheel_graph(50), ax=ax[1,1]) nx.draw(nx.erdos_renyi_graph(50, 0.3), ax=ax[1,2]) nx.draw(nx.barabasi_albert_graph(50, 5), ax=ax[1,3]) nx.draw(nx.random_powerlaw_tree(10), ax=ax[2,0]) nx.draw(nx.scale_free_graph(50), ax=ax[2,1]) nx.draw(nx.karate_club_graph(), ax=ax[2,2]) nx.draw(nx.les_miserables_graph(), ax=ax[2,3]) # %% [markdown] # ## Network Statistics
def _gen_circular_ladder(self, n): for _ in range(n): num_v = np.random.randint(self.min_num_v, self.max_num_v) g = nx.circular_ladder_graph(num_v // 2) self.graphs.append(g) self.labels.append(7)
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
for strategy in strategies: try: benchmark(output, graph, graphname, strategy, False) benchmark(output, graph, graphname, strategy, True) except nx.exception.NetworkXPointlessConcept: print "" if not os.path.exists(args.output): os.makedirs(args.output) with open(args.output + '/output.csv', 'w') as output: helper(output, nx.balanced_tree(2, 5), "balanced_tree") # branching factor, height helper(output, nx.barbell_graph(50, 50), "barbell_graph") helper(output, nx.complete_graph(50), "complete_graph") helper(output, nx.complete_bipartite_graph(50, 50), "complete_bipartite_graph") helper(output, nx.circular_ladder_graph(50), "circular_ladder_graph") helper(output, nx.cycle_graph(50), "cycle_graph") helper(output, nx.dorogovtsev_goltsev_mendes_graph(5), "dorogovtsev_goltsev_mendes_graph") helper(output, nx.empty_graph(50), "empty_graph") helper(output, nx.grid_2d_graph(5, 20), "grid_2d_graph") helper(output, nx.grid_graph([2, 3]), "grid_graph") helper(output, nx.hypercube_graph(3), "hypercube_graph") helper(output, nx.ladder_graph(50), "ladder_graph") helper(output, nx.lollipop_graph(5, 20), "lollipop_graph") helper(output, nx.path_graph(50), "path_graph") helper(output, nx.star_graph(50), "star_graph") helper(output, nx.trivial_graph(), "trivial_graph") helper(output, nx.wheel_graph(50), "wheel_graph") helper(output, nx.random_regular_graph(1, 50, 678995), "random_regular_graph_1") helper(output, nx.random_regular_graph(3, 50, 683559), "random_regular_graph_3")
n = 6 hypercube_n = 4 m = 6 r = 2 h = 3 dim = [2, 3] # left out dorogovtsev_goltsev_mendes_graph and null_graph graphs = [ ("balanced_tree", nx.balanced_tree(r, h)), ("barbell_graph", nx.barbell_graph(n, m)), ("complete_graph", nx.complete_graph(n)), ("complete_bipartite_graph", nx.complete_bipartite_graph(n, m)), ("circular_ladder_graph", nx.circular_ladder_graph(n)), ("cycle_graph", nx.cycle_graph(n)), ("empty_graph", nx.empty_graph(n)), ("grid_2d_graph", nx.grid_2d_graph(m, n)), ("grid_graph", nx.grid_graph(dim)), ("hypercube_graph", nx.hypercube_graph(hypercube_n)), ("ladder_graph", nx.ladder_graph(n)), ("lollipop_graph", nx.lollipop_graph(m, n)), ("path_graph", nx.path_graph(n)), ("star_graph", nx.star_graph(n)), ("trivial_graph", nx.trivial_graph()), ("wheel_graph", nx.wheel_graph(n)), ] plot_multigraph(graphs, 4, 4, node_size=50) plt.savefig("graphs/classic.png")
write_json_graph(nx.barbell_graph(5, 2), 'barbell_graph(5,2).json') # write_json_graph(nx.barbell_graph(5, 0), 'barbell_graph(5,0).json') write_json_graph(nx.barbell_graph(50, 20), 'barbell_graph(50,20).json') # write_json_graph(nx.barbell_graph(50, 50), 'barbell_graph(50,50).json') # write_json_graph(nx.dorogovtsev_goltsev_mendes_graph(2), 'dorogovtsev_goltsev_mendes_graph(2).json') # write_json_graph(nx.dorogovtsev_goltsev_mendes_graph(3), 'dorogovtsev_goltsev_mendes_graph(3).json') write_json_graph(nx.dorogovtsev_goltsev_mendes_graph(4), 'dorogovtsev_goltsev_mendes_graph(4).json') write_json_graph(nx.dorogovtsev_goltsev_mendes_graph(5), 'dorogovtsev_goltsev_mendes_graph(5).json') # write_json_graph(nx.navigable_small_world_graph(8), 'navigable_small_world_graph(8).json') # write_json_graph(nx.navigable_small_world_graph(20), 'navigable_small_world_graph(20).json') write_json_graph(nx.circular_ladder_graph(5), 'circular_ladder_graph(5).json') write_json_graph(nx.circular_ladder_graph(100), 'circular_ladder_graph(100).json') write_json_graph(nx.duplication_divergence_graph(50, 0.5, seed=0), 'duplication_divergence_graph(50,0_5).json') write_json_graph(nx.watts_strogatz_graph(100, 3, 0.05), 'watts_strogatz_graph(100,3,0.05).json') write_json_graph(nx.watts_strogatz_graph(100, 3, 0.25), 'watts_strogatz_graph(100,3,0.25).json') # write_json_graph(nx.watts_strogatz_graph(100,3,0.5), 'watts_strogatz_graph(100,3,0.5).json') write_json_graph(nx.watts_strogatz_graph(100, 4, 0.05), 'watts_strogatz_graph(100,4,0.05).json') write_json_graph(nx.watts_strogatz_graph(100, 4, 0.25), 'watts_strogatz_graph(100,4,0.25).json')
g_name = 'NETWORKX.BARABASI_ALBERT_9' elif graph_type == 5: g = nx.barabasi_albert_graph(num_n, 11) g_name = 'NETWORKX.BARABASI_ALBERT_11' elif graph_type == 6: g = nx.barabasi_albert_graph(num_n, 13) g_name = 'NETWORKX.BARABASI_ALBERT_13' elif graph_type == 7: g = nx.barbell_graph(num_n / 2, num_n / 2) g_name = 'NETWORKX.BARBELL_GRAPH_EVEN' elif graph_type == 8: g = nx.barbell_graph(int(2 * num_n / 3), int(num_n / 3)) g_name = 'NETWORKX.BARBELL_GRAPH_ODD' elif graph_type == 9: g = nx.circular_ladder_graph(num_n) g_name = 'NETWORKX.CIRCULAR_LADDER_GRAPH' elif graph_type == 10: g = nx.complete_graph(num_n) g_name = 'NETWORKX.COMPLETE_GRAPH' elif graph_type == 11: 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)