Created
February 15, 2022 11:03
-
-
Save maxastyler/b6ccce5e230e00116ba20e995917d08d to your computer and use it in GitHub Desktop.
Function to generate hexagonally packed points within a given radius
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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