def xgrid_graph(col_count: int, row_count: int, with_positions: bool = True) -> Graph: """Builds and returns an x grid. Args: col_count: the number of columns in the lattice. row_count: the number of rows in the lattice. Returns: graph: an x grid with edge weights """ graph = empty_graph(0) if col_count == 0 or row_count == 0: return graph cols = range(col_count + 1) rows = range(row_count + 1) grid_weight = 1.0 diag_weight = math.sqrt(2 * grid_weight**2) print("grid_weight = {}".format(grid_weight)) print("diag_weight = {}".format(diag_weight)) # Make grid graph.add_edges_from( (((c, r), (c + 1, r)) for r in rows for c in cols[:col_count]), weight=grid_weight) graph.add_edges_from( (((c, r), (c, r + 1)) for r in rows[:row_count] for c in cols), weight=grid_weight) # add diagonals graph.add_edges_from((((c, r), (c + 1, r + 1)) for r in rows[:row_count] for c in cols[:col_count]), weight=diag_weight) graph.add_edges_from((((c + 1, r), (c, r + 1)) for r in rows[:row_count] for c in cols[:col_count]), weight=diag_weight) # Add position node attributes if with_positions: pos = {node: node for node in graph} set_node_attributes(graph, pos, 'pos') return graph
def xgrid_graph(col_count: int, row_count: int, granularity: float = None) -> Graph: """Builds and returns an x grid. Args: col_count: the number of columns in the lattice. row_count: the number of rows in the lattice. Returns: graph: an x grid with edge weights """ graph = empty_graph(0) if col_count == 0 or row_count == 0: return graph cols = range(col_count - 1) # why - 1 needed ? rows = range(row_count - 1) grid_weight = 1.0 diag_weight = math.sqrt(2 * grid_weight**2) # Make grid graph.add_edges_from((((c, r), (c + 1, r)) for r in rows for c in cols[:col_count]), weight = grid_weight) graph.add_edges_from((((c, r), (c, r + 1)) for r in rows[:row_count] for c in cols), weight = grid_weight) # add diagonals graph.add_edges_from((((c, r), (c + 1, r + 1)) for r in rows[:row_count] for c in cols[:col_count]), weight = diag_weight) graph.add_edges_from((((c + 1, r), (c, r + 1)) for r in rows[:row_count] for c in cols[:col_count]), weight = diag_weight) # Add position node attributes if granularity != None: pos = {node: (granularity * row, granularity * col) for (row, col) in graph} set_node_attributes(graph, pos, 'pos') return graph
def hexagonal_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None): """Return 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 constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. If graph is directed, edges will point up or right. Returns ------- NetworkX graph The *m* by *n* hexagonal lattice graph. """ G = empty_graph(0, create_using) 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 triangular_lattice_graph( m, n, periodic=False, with_positions=True, create_using=None ): r"""Returns the $m$ by $n$ triangular lattice graph. The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in which each square unit has a diagonal edge (each grid unit has a chord). The returned graph has $m$ rows and $n$ columns of triangles. Rows and columns include both triangles pointing up and down. Rows form a strip of constant height. Columns form a series of diamond shapes, staggered with the columns on either side. Another way to state the size is that the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns. The odd row nodes are shifted horizontally relative to the even rows. Directed graph types have edges pointed up or right. Positions of nodes are computed by default or `with_positions is True`. The position of each node (embedded in a euclidean plane) is stored in the graph using equilateral triangles with sidelength 1. The height between rows of nodes is thus $\sqrt(3)/2$. Nodes lie in the first quadrant with the node $(0, 0)$ at the origin. .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling Parameters ---------- m : int The number of rows in the lattice. n : int The number of columns in the lattice. periodic : bool (default: False) If True, join the boundary vertices of the grid using periodic boundary conditions. The join between boundaries is the final row and column of triangles. This means there is one row and one column fewer nodes for the periodic lattice. Periodic lattices require `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd with_positions : bool (default: True) Store the coordinates of each node in the graph node attribute 'pos'. The coordinates provide a lattice with equilateral triangles. Periodic positions shift the nodes vertically in a nonlinear way so the edges don't overlap so much. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- NetworkX graph The *m* by *n* triangular lattice graph. """ H = empty_graph(0, create_using) if n == 0 or m == 0: return H if periodic: if n < 5 or m < 3: msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}" raise NetworkXError(msg) N = (n + 1) // 2 # number of nodes in row rows = range(m + 1) cols = range(N + 1) # Make grid H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N]) H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols) # add diagonals H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N]) H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N]) # identify boundary nodes if periodic from networkx.algorithms.minors import contracted_nodes if periodic is True: for i in cols: H = contracted_nodes(H, (i, 0), (i, m)) for j in rows[:m]: H = contracted_nodes(H, (0, j), (N, j)) elif n % 2: # remove extra nodes H.remove_nodes_from((N, j) for j in rows[1::2]) # Add position node attributes if with_positions: ii = (i for i in cols for j in rows) jj = (j for i in cols for j in rows) xx = (0.5 * (j % 2) + i for i in cols for j in rows) h = sqrt(3) / 2 if periodic: yy = (h * j + 0.01 * i * i for i in cols for j in rows) else: yy = (h * j for i in cols for j in rows) pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H} set_node_attributes(H, pos, "pos") return H
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 triangular_lattice_graph(m, n, periodic=False, with_positions=True, create_using=None): """Returns the $m$ by $n$ triangular lattice graph. The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in which each square unit has a diagonal edge (each grid unit has a chord). The returned graph has $m$ rows and $n$ columns of triangles. Rows and columns include both triangles pointing up and down. Rows form a strip of constant height. Columns form a series of diamond shapes, staggered with the columns on either side. Another way to state the size is that the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns. The odd row nodes are shifted horizontally relative to the even rows. Directed graph types have edges pointed up or right. Positions of nodes are computed by default or `with_positions is True`. The position of each node (embedded in a euclidean plane) is stored in the graph using equilateral triangles with sidelength 1. The height between rows of nodes is thus $\sqrt(3)/2$. Nodes lie in the first quadrant with the node $(0, 0)$ at the origin. .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling Parameters ---------- m : int The number of rows in the lattice. n : int The number of columns in the lattice. periodic : bool (default: False) If True, join the boundary vertices of the grid using periodic boundary conditions. The join between boundaries is the final row and column of triangles. This means there is one row and one column fewer nodes for the periodic lattice. Periodic lattices require `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd with_positions : bool (default: True) Store the coordinates of each node in the graph node attribute 'pos'. The coordinates provide a lattice with equilateral triangles. 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. Returns ------- NetworkX graph The *m* by *n* triangular lattice graph. """ H = empty_graph(0, create_using) if n == 0 or m == 0: return H if periodic: if n < 5 or m < 3: msg = "m > 2 and n > 4 required for periodic. m={}, n={}" raise NetworkXError(msg.format(m, n)) N = (n + 1) // 2 # number of nodes in row rows = range(m + 1) cols = range(N + 1) # Make grid H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N]) H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols) # add diagonals H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N]) H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N]) # identify boundary nodes if periodic if periodic is True: for i in cols: H = contracted_nodes(H, (i, 0), (i, m)) for j in rows[:m]: H = contracted_nodes(H, (0, j), (N, j)) elif n % 2: # remove extra nodes H.remove_nodes_from(((N, j) for j in rows[1::2])) # Add position node attributes if with_positions: ii = (i for i in cols for j in rows) jj = (j for i in cols for j in rows) xx = (0.5 * (j % 2) + i 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) pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H} set_node_attributes(H, pos, 'pos') return H