Skip to content

grid

grid(height: int, width: int, dtype: Dtype = float32) -> tuple[array, array]

Returns the edges and node positions of a 2D grid graph of height x width nodes, where each node is connected to itself and to its (up to 8) horizontal, vertical and diagonal neighbors.

Node i is at row i // width and column i % width; rows are numbered from the top, so the position of node i is (i % width, height - 1 - i // width).

Parameters:

Name Type Description Default
height int

Number of rows of the grid.

required
width int

Number of columns of the grid.

required
dtype Dtype

Data type of the positions. Default: mx.float32

float32

Returns:

Type Description
array

A tuple (edge_index, pos) with the sorted int32 edges and the

array

positions, of shape [height * width, 2].

Example:

edge_index, pos = grid(2, 2)
# edge_index: every pair of the 4 nodes, including self-loops
# pos: mx.array([[0, 1], [1, 1], [0, 0], [1, 0]])
Source code in mlx_graphs/utils/generators.py
def grid(
    height: int, width: int, dtype: mx.Dtype = mx.float32
) -> tuple[mx.array, mx.array]:
    """
    Returns the edges and node positions of a 2D grid graph of ``height`` x
    ``width`` nodes, where each node is connected to itself and to its (up to
    8) horizontal, vertical and diagonal neighbors.

    Node ``i`` is at row ``i // width`` and column ``i % width``; rows are
    numbered from the top, so the position of node ``i`` is
    ``(i % width, height - 1 - i // width)``.

    Args:
        height: Number of rows of the grid.
        width: Number of columns of the grid.
        dtype: Data type of the positions. Default: ``mx.float32``

    Returns:
        A tuple ``(edge_index, pos)`` with the sorted int32 edges and the
        positions, of shape ``[height * width, 2]``.

    Example:

    .. code-block:: python

        edge_index, pos = grid(2, 2)
        # edge_index: every pair of the 4 nodes, including self-loops
        # pos: mx.array([[0, 1], [1, 1], [0, 0], [1, 0]])
    """
    num_nodes = height * width
    w = width
    # Same construction as PyG, including its handling of the grid borders.
    kernel = np.array([-w - 1, -1, w - 1, -w, 0, w, -w + 1, 1, w + 1])
    row = np.repeat(np.arange(num_nodes).reshape(-1, 1), kernel.size, axis=1)
    col = row + kernel.reshape(1, -1)
    row, col = row.reshape(height, -1), col.reshape(height, -1)
    index = np.arange(3, row.shape[1] - 3)
    row, col = row[:, index].reshape(-1), col[:, index].reshape(-1)
    mask = (col >= 0) & (col < num_nodes)
    keys = np.unique(row[mask] * num_nodes + col[mask])
    edge_index = np.stack([keys // num_nodes, keys % num_nodes]).astype(np.int32)

    x = np.tile(np.arange(width), height)
    y = np.repeat((height - 1) - np.arange(height), width)
    pos = mx.array(np.stack([x, y], axis=-1)).astype(dtype)
    return mx.array(edge_index), pos

from mlx_graphs.utils import grid · mlx_graphs/utils/generators.py