lattice.py 14 KB

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