Skip to content

Instantly share code, notes, and snippets.

@maxastyler
Created February 15, 2022 11:03
Show Gist options
  • Save maxastyler/b6ccce5e230e00116ba20e995917d08d to your computer and use it in GitHub Desktop.
Save maxastyler/b6ccce5e230e00116ba20e995917d08d to your computer and use it in GitHub Desktop.
Function to generate hexagonally packed points within a given radius
import numpy as np
def hexagon(radius: float, spacing: float) -> np.ndarray:
"""take a circle radius and point spacing and return an
[N, 2] shaped array containing the hexagonal-packed points
"""
n_points = int(np.ceil(radius / spacing)) * 2
basis = spacing * np.array([[1, 0], [np.cos(np.pi / 3), np.sin(np.pi / 3)]])
x, y = np.mgrid[
-n_points : n_points : (2 * n_points + 1) * 1j,
-n_points : n_points : (2 * n_points + 1) * 1j,
]
points = (
x[:, :, np.newaxis] * basis[0] + y[:, :, np.newaxis] * basis[1]
).reshape(((2 * n_points + 1) ** 2, -1))
points_filter = (points ** 2).sum(axis=1) <= (radius ** 2)
return points[points_filter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment