lattice.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. """Functions for generating grid graphs and lattices
  2. The :func:`grid_2d_graph`, :func:`triangular_lattice_graph`, and
  3. :func:`hexagonal_lattice_graph` functions correspond to the three
  4. `regular tilings of the plane`_, the square, triangular, and hexagonal
  5. tilings, respectively. :func:`grid_graph` and :func:`hypercube_graph`
  6. are similar for arbitrary dimensions. Useful relevant discussion can
  7. be found about `Triangular Tiling`_, and `Square, Hex and Triangle Grids`_
  8. .. _regular tilings of the plane: https://en.wikipedia.org/wiki/List_of_regular_polytopes_and_compounds#Euclidean_tilings
  9. .. _Square, Hex and Triangle Grids: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
  10. .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
  11. """
  12. from itertools import repeat
  13. from math import sqrt
  14. from networkx.classes import set_node_attributes
  15. from networkx.exception import NetworkXError
  16. from networkx.generators.classic import cycle_graph, empty_graph, path_graph
  17. from networkx.relabel import relabel_nodes
  18. from networkx.utils import flatten, nodes_or_number, pairwise
  19. __all__ = [
  20. "grid_2d_graph",
  21. "grid_graph",
  22. "hypercube_graph",
  23. "triangular_lattice_graph",
  24. "hexagonal_lattice_graph",
  25. ]
  26. @nodes_or_number([0, 1])
  27. def grid_2d_graph(m, n, periodic=False, create_using=None):
  28. """Returns the two-dimensional grid graph.
  29. The grid graph has each node connected to its four nearest neighbors.
  30. Parameters
  31. ----------
  32. m, n : int or iterable container of nodes
  33. If an integer, nodes are from `range(n)`.
  34. If a container, elements become the coordinate of the nodes.
  35. periodic : bool or iterable
  36. If `periodic` is True, both dimensions are periodic. If False, none
  37. are periodic. If `periodic` is iterable, it should yield 2 bool
  38. values indicating whether the 1st and 2nd axes, respectively, are
  39. periodic.
  40. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  41. Graph type to create. If graph instance, then cleared before populated.
  42. Returns
  43. -------
  44. NetworkX graph
  45. The (possibly periodic) grid graph of the specified dimensions.
  46. """
  47. G = empty_graph(0, create_using)
  48. row_name, rows = m
  49. col_name, cols = n
  50. G.add_nodes_from((i, j) for i in rows for j in cols)
  51. G.add_edges_from(((i, j), (pi, j)) for pi, i in pairwise(rows) for j in cols)
  52. G.add_edges_from(((i, j), (i, pj)) for i in rows for pj, j in pairwise(cols))
  53. try:
  54. periodic_r, periodic_c = periodic
  55. except TypeError:
  56. periodic_r = periodic_c = periodic
  57. if periodic_r and len(rows) > 2:
  58. first = rows[0]
  59. last = rows[-1]
  60. G.add_edges_from(((first, j), (last, j)) for j in cols)
  61. if periodic_c and len(cols) > 2:
  62. first = cols[0]
  63. last = cols[-1]
  64. G.add_edges_from(((i, first), (i, last)) for i in rows)
  65. # both directions for directed
  66. if G.is_directed():
  67. G.add_edges_from((v, u) for u, v in G.edges())
  68. return G
  69. def grid_graph(dim, periodic=False):
  70. """Returns the *n*-dimensional grid graph.
  71. The dimension *n* is the length of the list `dim` and the size in
  72. each dimension is the value of the corresponding list element.
  73. Parameters
  74. ----------
  75. dim : list or tuple of numbers or iterables of nodes
  76. 'dim' is a tuple or list with, for each dimension, either a number
  77. that is the size of that dimension or an iterable of nodes for
  78. that dimension. The dimension of the grid_graph is the length
  79. of `dim`.
  80. periodic : bool or iterable
  81. If `periodic` is True, all dimensions are periodic. If False all
  82. dimensions are not periodic. If `periodic` is iterable, it should
  83. yield `dim` bool values each of which indicates whether the
  84. corresponding axis is periodic.
  85. Returns
  86. -------
  87. NetworkX graph
  88. The (possibly periodic) grid graph of the specified dimensions.
  89. Examples
  90. --------
  91. To produce a 2 by 3 by 4 grid graph, a graph on 24 nodes:
  92. >>> from networkx import grid_graph
  93. >>> G = grid_graph(dim=(2, 3, 4))
  94. >>> len(G)
  95. 24
  96. >>> G = grid_graph(dim=(range(7, 9), range(3, 6)))
  97. >>> len(G)
  98. 6
  99. """
  100. from networkx.algorithms.operators.product import cartesian_product
  101. if not dim:
  102. return empty_graph(0)
  103. try:
  104. func = (cycle_graph if p else path_graph for p in periodic)
  105. except TypeError:
  106. func = repeat(cycle_graph if periodic else path_graph)
  107. G = next(func)(dim[0])
  108. for current_dim in dim[1:]:
  109. Gnew = next(func)(current_dim)
  110. G = cartesian_product(Gnew, G)
  111. # graph G is done but has labels of the form (1, (2, (3, 1))) so relabel
  112. H = relabel_nodes(G, flatten)
  113. return H
  114. def hypercube_graph(n):
  115. """Returns the *n*-dimensional hypercube graph.
  116. The nodes are the integers between 0 and ``2 ** n - 1``, inclusive.
  117. For more information on the hypercube graph, see the Wikipedia
  118. article `Hypercube graph`_.
  119. .. _Hypercube graph: https://en.wikipedia.org/wiki/Hypercube_graph
  120. Parameters
  121. ----------
  122. n : int
  123. The dimension of the hypercube.
  124. The number of nodes in the graph will be ``2 ** n``.
  125. Returns
  126. -------
  127. NetworkX graph
  128. The hypercube graph of dimension *n*.
  129. """
  130. dim = n * [2]
  131. G = grid_graph(dim)
  132. return G
  133. def triangular_lattice_graph(
  134. m, n, periodic=False, with_positions=True, create_using=None
  135. ):
  136. r"""Returns the $m$ by $n$ triangular lattice graph.
  137. The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in
  138. which each square unit has a diagonal edge (each grid unit has a chord).
  139. The returned graph has $m$ rows and $n$ columns of triangles. Rows and
  140. columns include both triangles pointing up and down. Rows form a strip
  141. of constant height. Columns form a series of diamond shapes, staggered
  142. with the columns on either side. Another way to state the size is that
  143. the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns.
  144. The odd row nodes are shifted horizontally relative to the even rows.
  145. Directed graph types have edges pointed up or right.
  146. Positions of nodes are computed by default or `with_positions is True`.
  147. The position of each node (embedded in a euclidean plane) is stored in
  148. the graph using equilateral triangles with sidelength 1.
  149. The height between rows of nodes is thus $\sqrt(3)/2$.
  150. Nodes lie in the first quadrant with the node $(0, 0)$ at the origin.
  151. .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html
  152. .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
  153. .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
  154. Parameters
  155. ----------
  156. m : int
  157. The number of rows in the lattice.
  158. n : int
  159. The number of columns in the lattice.
  160. periodic : bool (default: False)
  161. If True, join the boundary vertices of the grid using periodic
  162. boundary conditions. The join between boundaries is the final row
  163. and column of triangles. This means there is one row and one column
  164. fewer nodes for the periodic lattice. Periodic lattices require
  165. `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd
  166. with_positions : bool (default: True)
  167. Store the coordinates of each node in the graph node attribute 'pos'.
  168. The coordinates provide a lattice with equilateral triangles.
  169. Periodic positions shift the nodes vertically in a nonlinear way so
  170. the edges don't overlap so much.
  171. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  172. Graph type to create. If graph instance, then cleared before populated.
  173. Returns
  174. -------
  175. NetworkX graph
  176. The *m* by *n* triangular lattice graph.
  177. """
  178. H = empty_graph(0, create_using)
  179. if n == 0 or m == 0:
  180. return H
  181. if periodic:
  182. if n < 5 or m < 3:
  183. msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}"
  184. raise NetworkXError(msg)
  185. N = (n + 1) // 2 # number of nodes in row
  186. rows = range(m + 1)
  187. cols = range(N + 1)
  188. # Make grid
  189. H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N])
  190. H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols)
  191. # add diagonals
  192. H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N])
  193. H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N])
  194. # identify boundary nodes if periodic
  195. from networkx.algorithms.minors import contracted_nodes
  196. if periodic is True:
  197. for i in cols:
  198. H = contracted_nodes(H, (i, 0), (i, m))
  199. for j in rows[:m]:
  200. H = contracted_nodes(H, (0, j), (N, j))
  201. elif n % 2:
  202. # remove extra nodes
  203. H.remove_nodes_from((N, j) for j in rows[1::2])
  204. # Add position node attributes
  205. if with_positions:
  206. ii = (i for i in cols for j in rows)
  207. jj = (j for i in cols for j in rows)
  208. xx = (0.5 * (j % 2) + i for i in cols for j in rows)
  209. h = sqrt(3) / 2
  210. if periodic:
  211. yy = (h * j + 0.01 * i * i for i in cols for j in rows)
  212. else:
  213. yy = (h * j for i in cols for j in rows)
  214. pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H}
  215. set_node_attributes(H, pos, "pos")
  216. return H
  217. def hexagonal_lattice_graph(
  218. m, n, periodic=False, with_positions=True, create_using=None
  219. ):
  220. """Returns an `m` by `n` hexagonal lattice graph.
  221. The *hexagonal lattice graph* is a graph whose nodes and edges are
  222. the `hexagonal tiling`_ of the plane.
  223. The returned graph will have `m` rows and `n` columns of hexagons.
  224. `Odd numbered columns`_ are shifted up relative to even numbered columns.
  225. Positions of nodes are computed by default or `with_positions is True`.
  226. Node positions creating the standard embedding in the plane
  227. with sidelength 1 and are stored in the node attribute 'pos'.
  228. `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.
  229. .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
  230. .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
  231. Parameters
  232. ----------
  233. m : int
  234. The number of rows of hexagons in the lattice.
  235. n : int
  236. The number of columns of hexagons in the lattice.
  237. periodic : bool
  238. Whether to make a periodic grid by joining the boundary vertices.
  239. For this to work `n` must be even and both `n > 1` and `m > 1`.
  240. The periodic connections create another row and column of hexagons
  241. so these graphs have fewer nodes as boundary nodes are identified.
  242. with_positions : bool (default: True)
  243. Store the coordinates of each node in the graph node attribute 'pos'.
  244. The coordinates provide a lattice with vertical columns of hexagons
  245. offset to interleave and cover the plane.
  246. Periodic positions shift the nodes vertically in a nonlinear way so
  247. the edges don't overlap so much.
  248. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  249. Graph type to create. If graph instance, then cleared before populated.
  250. If graph is directed, edges will point up or right.
  251. Returns
  252. -------
  253. NetworkX graph
  254. The *m* by *n* hexagonal lattice graph.
  255. """
  256. G = empty_graph(0, create_using)
  257. if m == 0 or n == 0:
  258. return G
  259. if periodic and (n % 2 == 1 or m < 2 or n < 2):
  260. msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
  261. raise NetworkXError(msg)
  262. M = 2 * m # twice as many nodes as hexagons vertically
  263. rows = range(M + 2)
  264. cols = range(n + 1)
  265. # make lattice
  266. col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[: M + 1])
  267. row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2)
  268. G.add_edges_from(col_edges)
  269. G.add_edges_from(row_edges)
  270. # Remove corner nodes with one edge
  271. G.remove_node((0, M + 1))
  272. G.remove_node((n, (M + 1) * (n % 2)))
  273. # identify boundary nodes if periodic
  274. from networkx.algorithms.minors import contracted_nodes
  275. if periodic:
  276. for i in cols[:n]:
  277. G = contracted_nodes(G, (i, 0), (i, M))
  278. for i in cols[1:]:
  279. G = contracted_nodes(G, (i, 1), (i, M + 1))
  280. for j in rows[1:M]:
  281. G = contracted_nodes(G, (0, j), (n, j))
  282. G.remove_node((n, M))
  283. # calc position in embedded space
  284. ii = (i for i in cols for j in rows)
  285. jj = (j for i in cols for j in rows)
  286. xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - 0.5) for i in cols for j in rows)
  287. h = sqrt(3) / 2
  288. if periodic:
  289. yy = (h * j + 0.01 * i * i for i in cols for j in rows)
  290. else:
  291. yy = (h * j for i in cols for j in rows)
  292. # exclude nodes not in G
  293. pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
  294. set_node_attributes(G, pos, "pos")
  295. return G