def test_create_using_keyword_arguments(self): assert_raises(networkx.exception.NetworkXError, gn_graph, 100, create_using=Graph()) assert_raises(networkx.exception.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph()) assert_raises(networkx.exception.NetworkXError, gnc_graph, 100, create_using=Graph()) assert_raises(networkx.exception.NetworkXError, scale_free_graph, 100, create_using=Graph()) G = gn_graph(100, seed=1) MG = gn_graph(100, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges())) G = gnr_graph(100, 0.5, seed=1) MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges())) G = gnc_graph(100, seed=1) MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges()))
def test_create_using_keyword_arguments(self): assert_raises(nx.NetworkXError, gn_graph, 100, create_using=Graph()) assert_raises(nx.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph()) assert_raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph()) assert_raises(nx.NetworkXError, scale_free_graph, 100, create_using=Graph()) G = gn_graph(100, seed=1) MG = gn_graph(100, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges())) G = gnr_graph(100, 0.5, seed=1) MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges())) G = gnc_graph(100, seed=1) MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1) assert_equal(sorted(G.edges()), sorted(MG.edges())) G = scale_free_graph(100, alpha=0.3, beta=0.4, gamma=0.3, delta_in=0.3, delta_out=0.1, create_using=MultiDiGraph, seed=1) assert_raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3) assert_raises(ValueError, scale_free_graph, 100, alpha=-0.3) assert_raises(ValueError, scale_free_graph, 100, beta=-0.3) assert_raises(ValueError, scale_free_graph, 100, gamma=-0.3)
def empty_graph(n=0, create_using=None): """Return the empty graph with n nodes and zero edges. Parameters ========== n : int or iterable container of nodes (default = 0) If n is an integer, nodes are from `range(n)`. If n is a container of nodes, those nodes appear in the graph. create_using : Graph, optional (default Graph()) If provided this graph is cleared of nodes and edges and filled with the new graph. Usually used to set the type of the graph. For example: >>> G = nx.empty_graph(10) >>> G.number_of_nodes() 10 >>> G.number_of_edges() 0 >>> G = nx.empty_graph("ABC") >>> G.number_of_nodes() 3 >>> sorted(G) ['A', 'B', 'C'] Notes ===== The variable create_using should point to a "graph"-like object that will be cleared (nodes and edges will be removed) and refitted as an empty "graph" with nodes specified in n. This capability is useful for specifying the class-nature of the resulting empty "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.). The variable create_using has two main uses: Firstly, the variable create_using can be used to create an empty digraph, multigraph, etc. For example, >>> n = 10 >>> G = nx.empty_graph(n, create_using=nx.DiGraph()) will create an empty digraph on n nodes. Secondly, one can pass an existing graph (digraph, multigraph, etc.) via create_using. For example, if G is an existing graph (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G) will empty G (i.e. delete all nodes and edges using G.clear()) and then add n nodes and zero edges, and return the modified graph. See also create_empty_copy(G). """ if create_using is None: # default empty graph is a simple graph G = Graph() else: G = create_using G.clear() n_name, nodes = n G.add_nodes_from(nodes) return G
def make_graph(): g = Graph() accounts = listdir(DATA_PATH) for account in accounts: g.add_node(account) direct_connections = open( '../data/instagram/ikeybenz/connections.txt').read().splitlines() for connection in direct_connections: g.add_edge('ikeybenz', connection) g.add_edge(connection, 'ikeybenz') for account in accounts: try: # Some connections have no mutual followers with me mutual_followers_of_account = open( f'{DATA_PATH}/{account}/mutuals_with_ikeybenz.txt').read().splitlines() except: # In that case, skip current account continue for follower in mutual_followers_of_account: g.add_edge(follower, account) return g
def hexagonal_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None): """Returns an `m` by `n` hexagonal lattice graph. The *hexagonal lattice graph* is a graph whose nodes and edges are the `hexagonal tiling`_ of the plane. The returned graph will have `m` rows and `n` columns of hexagons. `Odd numbered columns`_ are shifted up relative to even numbered columns. Positions of nodes are computed by default or `with_positions is True`. Node positions creating the standard embedding in the plane with sidelength 1 and are stored in the node attribute 'pos'. `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing. .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/ Parameters ---------- m : int The number of rows of hexagons in the lattice. n : int The number of columns of hexagons in the lattice. periodic : bool Whether to make a periodic grid by joining the boundary vertices. For this to work `n` must be odd and both `n > 1` and `m > 1`. The periodic connections create another row and column of hexagons so these graphs have fewer nodes as boundary nodes are identified. with_positions : bool (default: True) Store the coordinates of each node in the graph node attribute 'pos'. The coordinates provide a lattice with vertical columns of hexagons offset to interleave and cover the plane. Periodic positions shift the nodes vertically in a nonlinear way so the edges don't overlap so much. create_using : NetworkX graph If specified, this must be an instance of a NetworkX graph class. It will be cleared of nodes and edges and filled with the new graph. Usually used to set the type of the graph. If graph is directed, edges will point up or right. Returns ------- NetworkX graph The *m* by *n* hexagonal lattice graph. """ G = create_using if create_using is not None else Graph() G.clear() if m == 0 or n == 0: return G if periodic and (n % 2 == 1 or m < 2 or n < 2): msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n" raise NetworkXError(msg) M = 2 * m # twice as many nodes as hexagons vertically rows = range(M + 2) cols = range(n + 1) # make lattice col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[:M + 1]) row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2) G.add_edges_from(col_edges) G.add_edges_from(row_edges) # Remove corner nodes with one edge G.remove_node((0, M + 1)) G.remove_node((n, (M + 1) * (n % 2))) # identify boundary nodes if periodic if periodic: for i in cols[:n]: G = contracted_nodes(G, (i, 0), (i, M)) for i in cols[1:]: G = contracted_nodes(G, (i, 1), (i, M + 1)) for j in rows[1:M]: G = contracted_nodes(G, (0, j), (n, j)) G.remove_node((n, M)) # calc position in embedded space ii = (i for i in cols for j in rows) jj = (j for i in cols for j in rows) xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - .5) for i in cols for j in rows) h = sqrt(3) / 2 if periodic: yy = (h * j + .01 * i * i for i in cols for j in rows) else: yy = (h * j for i in cols for j in rows) # exclude nodes not in G pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G} set_node_attributes(G, pos, 'pos') return G
def complete_multipartite_graph(*subset_sizes): """Returns the complete multipartite graph with the specified subset sizes. Parameters ---------- subset_sizes : tuple of integers or tuple of node iterables The arguments can either all be integer number of nodes or they can all be iterables of nodes. If integers, they represent the number of vertices in each subset of the multipartite graph. If iterables, each is used to create the nodes for that subset. The length of subset_sizes is the number of subsets. Returns ------- G : NetworkX Graph Returns the complete multipartite graph with the specified subsets. For each node, the node attribute 'subset' is an integer indicating which subset contains the node. Examples -------- Creating a complete tripartite graph, with subsets of one, two, and three vertices, respectively. >>> import networkx as nx >>> G = nx.complete_multipartite_graph(1, 2, 3) >>> [G.nodes[u]['subset'] for u in G] [0, 1, 1, 2, 2, 2] >>> list(G.edges(0)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)] >>> list(G.edges(2)) [(2, 0), (2, 3), (2, 4), (2, 5)] >>> list(G.edges(4)) [(4, 0), (4, 1), (4, 2)] >>> G = nx.complete_multipartite_graph('a', 'bc', 'def') >>> [G.nodes[u]['subset'] for u in sorted(G)] [0, 1, 1, 2, 2, 2] Notes ----- This function generalizes several other graph generator functions. - If no subset sizes are given, this returns the null graph. - If a single subset size `n` is given, this returns the empty graph on `n` nodes. - If two subset sizes `m` and `n` are given, this returns the complete bipartite graph on `m + n` nodes. - If subset sizes `1` and `n` are given, this returns the star graph on `n + 1` nodes. See also -------- complete_bipartite_graph """ # The complete multipartite graph is an undirected simple graph. G = Graph() if len(subset_sizes) == 0: return G # set up subsets of nodes try: extents = pairwise(accumulate((0, ) + subset_sizes)) subsets = [range(start, end) for start, end in extents] except TypeError: subsets = subset_sizes # add nodes with subset attribute # while checking that ints are not mixed with iterables try: for (i, subset) in enumerate(subsets): G.add_nodes_from(subset, subset=i) except TypeError: raise NetworkXError("Arguments must be all ints or all iterables") # Across subsets, all vertices should be adjacent. # We can use itertools.combinations() because undirected. for subset1, subset2 in itertools.combinations(subsets, 2): G.add_edges_from(itertools.product(subset1, subset2)) return G
def get_graph(self, word_len: int) -> Graph: """ Get a graph by the word length """ return self.graphs.get(word_len, Graph())