def test103_lollipop_graph(self): """ Large lollipop graph. """ g = nx.lollipop_graph(17, 11) mate1 = mv.max_cardinality_matching( g ) mate2 = nx.max_weight_matching( g, True ) td.showGraph(g, mate1, "test103_lollipop_graph") self.assertEqual( len(mate1), len(mate2) )
def setUp(self): G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted") G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted") G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted") self.G = nx.union(G1, G2) self.G = nx.union(self.G, G3) self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)]) self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1) self.gc = [] G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5), (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)]) C = [[3, 4, 5, 7], [1, 2, 8], [6]] self.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)]) C = [[2, 3, 4],[1]] self.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)]) C = [[1, 2, 3]] self.gc.append((G,C)) # Eppstein's tests G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]}) C = [[0], [1], [2],[ 3], [4], [5], [6]] self.gc.append((G,C)) G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]}) C = [[0, 1, 2], [3, 4]] self.gc.append((G, C))
def setUp(self): G1=cnlti(nx.grid_2d_graph(2,2),first_label=0,ordering="sorted") G2=cnlti(nx.lollipop_graph(3,3),first_label=4,ordering="sorted") G3=cnlti(nx.house_graph(),first_label=10,ordering="sorted") self.G=nx.union(G1,G2) self.G=nx.union(self.G,G3) self.DG=nx.DiGraph([(1,2),(1,3),(2,3)]) self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1)
def __init__(self): # G1 is a disconnected graph self.G1 = nx.Graph() self.G1.add_nodes_from([1, 2, 3]) # G2 is a cycle graph self.G2 = nx.cycle_graph(4) # G3 is the triangle graph with one additional edge self.G3 = nx.lollipop_graph(3, 1)
def test_using_ego_graph(self): """Test that the ego graph is used when computing local efficiency. For more information, see GitHub issue #2233. """ # This is the triangle graph with one additional edge. G = nx.lollipop_graph(3, 1) assert_equal(nx.local_efficiency(G), 23 / 24)
def LollipopGraph(n1, n2): """ Returns a lollipop graph with n1+n2 nodes. A lollipop graph is a path graph (order n2) connected to a complete graph (order n1). (A barbell graph minus one of the bells). This constructor depends on NetworkX numeric labels. PLOTTING: Upon construction, the position dictionary is filled to override the spring-layout algorithm. By convention, the complete graph will be drawn in the lower-left corner with the (n1)th node at a 45 degree angle above the right horizontal center of the complete graph, leading directly into the path graph. EXAMPLES: Construct and show a lollipop graph Candy = 13, Stick = 4 :: sage: g = graphs.LollipopGraph(13,4) sage: g.show() # long time Create several lollipop graphs in a Sage graphics array :: sage: g = [] sage: j = [] sage: for i in range(6): ....: k = graphs.LollipopGraph(i+3,4) ....: g.append(k) sage: for i in range(2): ....: 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(n1): x = float(cos((pi/4) - ((2*pi)/n1)*i) - n2/2 - 1) y = float(sin((pi/4) - ((2*pi)/n1)*i) - n2/2 - 1) j = n1-1-i pos_dict[j] = (x,y) for i in range(n1, n1+n2): x = float(i - n1 - n2/2 + 1) y = float(i - n1 - n2/2 + 1) pos_dict[i] = (x,y) import networkx G = networkx.lollipop_graph(n1,n2) return graph.Graph(G, pos=pos_dict, name="Lollipop Graph")
def LollipopGraph(n1, n2): """ Returns a lollipop graph with n1+n2 nodes. A lollipop graph is a path graph (order n2) connected to a complete graph (order n1). (A barbell graph minus one of the bells). This constructor depends on NetworkX numeric labels. PLOTTING: Upon construction, the position dictionary is filled to override the spring-layout algorithm. By convention, the complete graph will be drawn in the lower-left corner with the (n1)th node at a 45 degree angle above the right horizontal center of the complete graph, leading directly into the path graph. EXAMPLES: Construct and show a lollipop graph Candy = 13, Stick = 4 :: sage: g = graphs.LollipopGraph(13,4) sage: g.show() # long time Create several lollipop graphs in a Sage graphics array :: sage: g = [] sage: j = [] sage: for i in range(6): ....: k = graphs.LollipopGraph(i+3,4) ....: g.append(k) sage: for i in range(2): ....: 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(n1): x = float(cos((pi / 4) - ((2 * pi) / n1) * i) - n2 / 2 - 1) y = float(sin((pi / 4) - ((2 * pi) / n1) * i) - n2 / 2 - 1) j = n1 - 1 - i pos_dict[j] = (x, y) for i in range(n1, n1 + n2): x = float(i - n1 - n2 / 2 + 1) y = float(i - n1 - n2 / 2 + 1) pos_dict[i] = (x, y) import networkx G = networkx.lollipop_graph(n1, n2) return graph.Graph(G, pos=pos_dict, name="Lollipop Graph")
def 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) g_list = [K_5, K_3_5, barbell, lollipop] for n, g in enumerate(g_list): plt.subplot(221 + n) nx.draw(g, with_labels=True, font_weight='bold') plt.show()
def test_grow_maximal_degree(self, dim): """Test if function grows to expected maximal graph when degree-based node selection is used. The chosen graph is a fully connected graph with only the final node being connected to an additional node. Furthermore, the ``dim - 2`` node is disconnected from the ``dim - 1`` node. Starting from the first ``dim - 3`` nodes, one can either add in the ``dim - 2`` node or the ``dim - 1`` node. The ``dim - 1`` node has a higher degree due to the lollipop graph structure, and hence should be selected.""" graph = nx.lollipop_graph(dim, 1) graph.remove_edge(dim - 2, dim - 1) s = set(range(dim - 2)) target = s | {dim - 1} assert set(resize.clique_grow(s, graph, node_select="degree")) == target
def setup_class(cls): G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted") G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted") G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted") cls.G = nx.union(G1, G2) cls.G = nx.union(cls.G, G3) cls.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)]) cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1) cls.gc = [] G = nx.DiGraph() G.add_edges_from( [ (1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5), (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7), ] ) C = [[3, 4, 5, 7], [1, 2, 8], [6]] cls.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)]) C = [[2, 3, 4], [1]] cls.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)]) C = [[1, 2, 3]] cls.gc.append((G, C)) # Eppstein's tests G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []}) C = [[0], [1], [2], [3], [4], [5], [6]] cls.gc.append((G, C)) G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]}) C = [[0, 1, 2], [3, 4]] cls.gc.append((G, C)) G = nx.DiGraph() C = [] cls.gc.append((G, C))
def test_wires_to_edges(self): """Test that wires_to_edges returns the correct mapping""" g = nx.lollipop_graph(4, 1) r = wires_to_edges(g) assert r == { 0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 2), 4: (1, 3), 5: (2, 3), 6: (3, 4) }
def test_edges_to_wires(self): """Test that edges_to_wires returns the correct mapping""" g = nx.lollipop_graph(4, 1) r = edges_to_wires(g) assert r == { (0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5, (3, 4): 6 }
def createLollipop(self, algorithm_factory, complete_subgraph_size = 100, chain_size = 10, island_size = 20): # type: (Callable, int, int, int) -> Topology ''' Creates a topology from a lollipop graph. ''' # TODO: chain should be one-way g = self._processTopology(nx.lollipop_graph(complete_subgraph_size, chain_size, create_using=nx.Graph()), algorithm_factory, island_size, Topology) # label tail nodes endpoints = set() for n in g.nodes: if len(tuple(g.neighbors(n))) == 1: endpoints.add(n) g.endpoints = tuple(endpoints) return g
def test_expected_growth(self): """Test if function performs a growth and swap phase, followed by another growth and attempted swap phase. This is carried out by starting with a 4+1 node lollipop graph, adding a connection from node 4 to node 2 and starting with the [3, 4] clique. The local search algorithm should first grow to [2, 3, 4] and then swap to either [0, 2, 3] or [1, 2, 3], and then grow again to [0, 1, 2, 3] and being unable to swap, hence returning [0, 1, 2, 3]""" graph = nx.lollipop_graph(4, 1) graph.add_edge(4, 2) c = [3, 4] result = clique.search(c, graph, iterations=100) assert result == [0, 1, 2, 3]
def test_loss_hamiltonian_incomplete(self): """Test if the loss_hamiltonian function returns the expected result on a manually-calculated example of a 4-node incomplete digraph""" g = nx.lollipop_graph(4, 1).to_directed() edge_weight_data = { edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges) } for k, v in edge_weight_data.items(): g[k[0]][k[1]]["weight"] = v h = loss_hamiltonian(g) expected_ops = [ qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2), qml.PauliZ(3), qml.PauliZ(4), qml.PauliZ(5), qml.PauliZ(6), qml.PauliZ(7), qml.PauliZ(8), qml.PauliZ(9), qml.PauliZ(10), qml.PauliZ(11), qml.PauliZ(12), qml.PauliZ(13), ] expected_coeffs = [ np.log(0.5), np.log(1), np.log(1.5), np.log(2), np.log(2.5), np.log(3), np.log(3.5), np.log(4), np.log(4.5), np.log(5), np.log(5.5), np.log(6), np.log(6.5), np.log(7), ] assert expected_coeffs == h.coeffs assert all( [op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)]) assert all( [type(op) is type(exp) for op, exp in zip(h.ops, expected_ops)])
def test_maximal_by_cardinality(self): """Tests that the maximal clique is computed according to maximum cardinality of the sets. For more information, see pull request #1531. """ G = nx.complete_graph(5) G.add_edge(4, 5) clique = max_clique(G) assert_greater(len(clique), 1) G = nx.lollipop_graph(30, 2) clique = max_clique(G) assert_greater(len(clique), 2)
def test_maximal_by_cardinality(self): """Tests that the maximal clique is computed according to maximum cardinality of the sets. For more information, see pull request #1531. """ G = nx.complete_graph(5) G.add_edge(4, 5) clique = max_clique(G) assert len(clique) > 1 G = nx.lollipop_graph(30, 2) clique = max_clique(G) assert len(clique) > 2
def test_swap_degree(self, dim): """Test if function performs correct swap operation when degree-based node selection is used. Input graph is a lollipop graph, consisting of a fully connected graph with a single additional node connected to just one of the nodes in the graph. Additionally, a connection between node ``0`` and ``dim - 1`` is removed as well as a connection between node ``0`` and ``dim - 2``. A clique of the first ``dim - 2`` nodes is then input. In this case, C1 consists of nodes ``dim - 1`` and ``dim - 2``. However, node ``dim - 1`` has greater degree due to the extra node in the lollipop graph. This test confirms that the resultant swap is performed correctly.""" graph = nx.lollipop_graph(dim, 1) graph.remove_edge(0, dim - 1) graph.remove_edge(0, dim - 2) s = list(range(dim - 2)) result = set(resize.clique_swap(s, graph, node_select="degree")) expected = set(range(1, dim - 2)) | {dim - 1} assert result == expected
def test_adapted_type(c=adapted.Connectivity()): dj.errors._switch_adapted_types(True) graphs = [ nx.lollipop_graph(4, 2), nx.star_graph(5), nx.barbell_graph(3, 1), nx.cycle_graph(5), ] c.insert((i, g) for i, g in enumerate(graphs)) returned_graphs = c.fetch("conn_graph", order_by="connid") for g1, g2 in zip(graphs, returned_graphs): assert_true(isinstance(g2, nx.Graph)) assert_equal(len(g1.edges), len(g2.edges)) assert_true(0 == len(nx.symmetric_difference(g1, g2).edges)) c.delete() dj.errors._switch_adapted_types(False)
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 createLollipop(self, algorithm, complete_subgraph_size=100, chain_size=10): # type: (Union[AlgorithmCtorFactory,collections.abc.Sequence,Callable[[],pg.algorithm]], int, int) -> Topology ''' Creates a topology from a lollipop graph. ''' # TODO: chain should be one-way g = self._processTopology( nx.lollipop_graph(complete_subgraph_size, chain_size, create_using=nx.Graph()), algorithm, Topology) # label tail nodes endpoints = set() for n in g.nodes: if len(tuple(g.neighbors(n))) == 1: endpoints.add(g.nodes[n]['island']) g.endpoints = tuple(endpoints) return g
def test_distribution_G_1_dx_dx_l_2(num_samples=100): """Test if connected planar graphs with exactly 4 nodes have the right distribution.""" BoltzmannSamplerBase.oracle = EvaluationOracle(reference_evals) grammar = one_connected_graph_grammar() grammar.init() # All one-connected planar graphs with 4 nodes and the number of their labellings. # See p.15, Fig. 5. cycle_with_chord = nx.cycle_graph(4) cycle_with_chord.add_edge(0, 2) graphs_labs = [(nx.path_graph(4), 12, 3), (nx.star_graph(3), 4, 3), (nx.lollipop_graph(3, 1), 12, 4), (nx.cycle_graph(4), 3, 4), (cycle_with_chord, 6, 5), (nx.complete_graph(4), 1, 6)] test_distribution_for_l_size(grammar, 'G_1_dx_dx', 'x', 'y', 2, graphs_labs, num_samples=num_samples)
def test_edges_to_wires_directed(self): """Test that edges_to_wires returns the correct mapping on a directed graph""" g = nx.lollipop_graph(4, 1).to_directed() r = edges_to_wires(g) assert r == { (0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 0): 3, (1, 2): 4, (1, 3): 5, (2, 0): 6, (2, 1): 7, (2, 3): 8, (3, 0): 9, (3, 1): 10, (3, 2): 11, (3, 4): 12, (4, 3): 13, }
def test_wires_to_edges_directed(self): """Test that wires_to_edges returns the correct mapping on a directed graph""" g = nx.lollipop_graph(4, 1).to_directed() r = wires_to_edges(g) assert r == { 0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2), 12: (3, 4), 13: (4, 3), }
def test_adapted_virtual(): dj.errors._switch_adapted_types(True) c = virtual_module.Connectivity() graphs = [ nx.lollipop_graph(4, 2), nx.star_graph(5), nx.barbell_graph(3, 1), nx.cycle_graph(5), ] c.insert((i, g) for i, g in enumerate(graphs)) c.insert1({"connid": 100}) # test work with NULLs returned_graphs = c.fetch("conn_graph", order_by="connid") for g1, g2 in zip_longest(graphs, returned_graphs): if g1 is None: assert_true(g2 is None) else: assert_true(isinstance(g2, nx.Graph)) assert_equal(len(g1.edges), len(g2.edges)) assert_true(0 == len(nx.symmetric_difference(g1, g2).edges)) c.delete() dj.errors._switch_adapted_types(False)
def test_correct_resize(self): """Test if function correctly resizes on a fixed example where the ideal resizing is known. The example is a lollipop graph of 6 fully connected nodes and 2 nodes on the lollipop stick. An edge between node zero and node ``dim - 1`` (the lollipop node connecting to the stick) is removed and a starting subgraph of nodes ``[2, 3, 4, 5, 6]`` is selected. The objective is to add-on 1 and 2 nodes and remove 1 node.""" dim = 6 g = nx.lollipop_graph(dim, 2) g.remove_edge(0, dim - 1) s = [2, 3, 4, 5, 6] min_size = 4 max_size = 7 ideal = { 4: [2, 3, 4, 5], 5: [2, 3, 4, 5, 6], 6: [1, 2, 3, 4, 5, 6], 7: [0, 1, 2, 3, 4, 5, 6], } resized = subgraph.resize(s, g, min_size, max_size) assert ideal == resized
def test_result_lollipop_graph_200_20(self): assert (calc_and_compare(NX.lollipop_graph(200, 20)))
def test105_lollipop_graph(self): """ Large lollipop graph. """ g = nx.lollipop_graph(51, 51) mate1 = mv.max_cardinality_matching( g ) mate2 = nx.max_weight_matching( g, True ) self.assertEqual( len(mate1), len(mate2) )
import networkx as nx import matplotlib.pyplot as plt # G = nx.DiGraph() k = nx.lollipop_graph(4, 30) poos = nx.circular_layout(k) # G.add_edge("1","2") # G.add_edge("1","3") # G.add_edge("1","4") # G.add_edge("1","5") # G.add_edge("1","6") # pos = nx.circular_layout(G,dim=2,scale=3) # poos = nx.spring_layout(G, iterations=100) # print (nx.info(G)) # nx.draw(G,pos, node_size=800) nx.draw(k, poos, node_size=800) plt.show()
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") helper(output, nx.random_regular_graph(5, 50, 515871), "random_regular_graph_5") helper(output, nx.random_regular_graph(8, 50, 243579), "random_regular_graph_8") helper(output, nx.random_regular_graph(13, 50, 568324), "random_regular_graph_13") helper(output, nx.diamond_graph(), "diamond_graph")
import networkx as nx # Choose random graph to generate G = nx.lollipop_graph(10, 20) # Print graph to file f = open("testGraph.dim", "w") f.write("p edge " + str(G.number_of_nodes()) + " " + str(G.number_of_edges())) f.write("\n") for line in nx.generate_edgelist(G, data=False): print(line) f.write("e " + line + "\n")
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
def test104_lollipop_graph(self): """ Small lollipop graph. """ g = nx.lollipop_graph(13, 13) mate1 = mv.max_cardinality_matching( g ) mate2 = nx.max_weight_matching( g, True ) self.assertEqual( len(mate1), len(mate2) )
# 1. graph n_nodes = 50 # number of nodes d = 3 # dimension of variable at each node # 2. function # objective value np.random.seed(200) v = np.random.rand(n_nodes, d) # optimal value x_opt = v.mean() # 3. simulation setting graphs = [ nx.path_graph(n_nodes), nx.cycle_graph(n_nodes), nx.lollipop_graph(n_nodes // 2, n_nodes - n_nodes // 2), Simulator.erdos_renyi(n_nodes, 0.1) ] graph_name = ['Line', 'Cycle', 'Lollipop', 'ER(p=0.1)'] line_style = ['-rd', '-c^', '-bs', '-go'] best_penalty = [7.5, 3.7, 5.56, 1.4] mode = 'H-CADMM' max_iter = 1000 # start simulation setting = { 'penalty': -1, 'max_iter': max_iter, 'objective': v, 'initial': 0 * np.random.randn(n_nodes, d), 'epsilon': 1e-8, # 'random_hyperedge': [],
# 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') # write_json_graph(nx.petersen_graph(), 'petersen_graph().json') # write_json_graph(nx.octahedral_graph(), 'octahedral_graph().json') # write_json_graph(nx.pappus_graph(), 'pappus_graph().json') write_json_graph(nx.dodecahedral_graph(), 'dodecahedral_graph().json') write_json_graph(nx.frucht_graph(), 'frucht_graph().json') # write_json_graph(nx.star_graph(10), 'star_graph(50).json') # write_json_graph(nx.star_graph(50), 'star_graph(50).json') # write_json_graph(nx.star_graph(100), 'star_graph(50).json') write_json_graph(nx.ring_of_cliques(5, 70), 'ring_of_cliques(5,80).json') write_json_graph(nx.ring_of_cliques(6, 70), 'ring_of_cliques(6,70).json')
#%% # descriptive statistics # assortative coefficient import matplotlib.pyplot as plt import networkx as nx G = nx.lollipop_graph(4, 6) nx.draw(G, with_labels=True) plt.show() pathlengths = [] print("source vertex {target:length}") for v in G.nodes(): spl = nx.shortest_path_length(G, v) print('{} {} '.format(v, spl)) for p in spl: pathlengths.append(spl[p]) # pathlengths #%% print("average shortest path length %s" % (sum(pathlengths) / len(pathlengths))) # histogram of path lengths dist = {} for p in pathlengths: if p in dist: dist[p] += 1 else: dist[p] = 1
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')
node_color='firebrick', alpha=0.8, ) #%% #有向图 DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) print(DG.out_degree(1, weight='weight')) print(DG.degree(1, weight='weight')) print(list(DG.successors(1))) print(list(DG.neighbors(1))) #有向图和无向图的转换 #%% #其他生成图的方法 petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_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) #%% plt.subplot(111) nx.draw(K_3_5, with_labels=True, node_color='firebrick', alpha=0.8) #%%
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")
""" Displays a NetworkX lollipop graph to screen using a ArcPlot. """ import matplotlib.pyplot as plt import networkx as nx import numpy.random as npr from nxviz.plots import ArcPlot G = nx.lollipop_graph(m=10, n=4) for n, d in G.nodes(data=True): G.node[n]['value'] = npr.normal() c = ArcPlot(G, node_color='value', node_order='value') c.draw() plt.show()
totalTests = list() G1S=0 G2S=0 G3S=0 G1T=0 G2T=0 G3T=0 mu=10 sigma=2.5 #Orden logaritmico for logarithmOrder in range(3,5): print('Orden: ',logarithmOrder) log = 2**logarithmOrder ban=True # 3 Metodos de generación distintos G1 = nx.lollipop_graph(log, 2) for e in G1.edges(): G1[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma) G2 = nx.turan_graph(log, 2) for e in G2.edges(): G2[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma) G3 = nx.ladder_graph(log) for e in G3.edges(): G3[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma) for newPair in range(5): print('Pareja: ',newPair) #10 Grafos for graphRepetition in range(10): if ban: ban=False while G1T==G1S:
""" Displays a NetworkX lollipop graph to screen using a CircosPlot. """ from nxviz.plots import CircosPlot import networkx as nx import matplotlib.pyplot as plt G = nx.lollipop_graph(m=10, n=4) c = CircosPlot(G.nodes(), G.edges(), plot_radius=5) c.draw() plt.show()
'alpha': 0.3 } # Drawing Complete Graph G = nx.complete_graph(6) plt.figure() nx.draw_circular(G) plt.savefig("complete_graph.png") # Cycle Graph G = nx.cycle_graph(10) plt.figure() nx.draw_circular(G) plt.savefig("cycle_graph.png") # lollipop Graph G = nx.lollipop_graph(5, 2) plt.figure() nx.draw_circular(G) plt.savefig("lollipop.png") # petersen_graph G = nx.petersen_graph() plt.figure() nx.draw_circular(G) plt.savefig("Peterson_graph.png") # barabasi_albert_graph G = nx.barabasi_albert_graph(100, 3) nx.draw_circular(G, **options_2) plt.savefig("barabasi.png")