Skip to content
Projects

Polygon

Download notebookView on GitHubRun when the site was built.

A closed polygon through any number of vertices: electrode profiles, wall cross-sections and other shapes made of straight edges.

Polygon(vertices) decides membership by the even-odd rule, so a self-intersecting polygon has holes where its edges overlap. Its level set is the exact signed distance to the nearest edge, at a cost of one pass per edge.

import matplotlib.pyplot as plt
import numpy as np
from simgeometry import Polygon
# an L-shaped electrode and a five-pointed star drawn in one stroke
electrode = Polygon(
[(0.0, 0.0), (1.0, 0.0), (1.0, 0.3), (0.3, 0.3), (0.3, 1.0), (0.0, 1.0)]
)
angles = np.pi / 2 + 4 * np.pi / 5 * np.arange(5)
star = Polygon(
np.stack((2.0 + 0.5 * np.cos(angles), 0.5 + 0.5 * np.sin(angles)), axis=1)
)
print("in the notch of the L:", electrode.contains((0.6, 0.6)))
print("distance from (0.6, 0.6):", electrode.signed_distance((0.6, 0.6)))
print("star centre inside:", star.contains((2.0, 0.5))) # covered twice: a hole
print("star point inside:", star.contains((2.0, 0.9)))
assert not star.contains((2.0, 0.5)) and star.contains((2.0, 0.9))
in the notch of the L: False
distance from (0.6, 0.6): 0.3
star centre inside: False
star point inside: True

The level set sampled around both polygons, with the zero contour drawn in black: the pentagon in the middle of the star is outside.

x = np.linspace(-0.2, 2.7, 291)
y = np.linspace(-0.2, 1.2, 141)
X, Y = np.meshgrid(x, y, indexing="ij")
points = np.stack((X.ravel(), Y.ravel()))
distance = np.minimum(electrode.signed_distance(points), star.signed_distance(points))
fig, ax = plt.subplots(figsize=(7, 3.6), layout="constrained")
image = ax.contourf(X, Y, distance.reshape(X.shape), levels=15, cmap="RdBu_r")
ax.contour(X, Y, distance.reshape(X.shape), levels=[0.0], colors="k")
fig.colorbar(image, ax=ax, label="signed distance")
ax.set(xlabel="x", ylabel="y", title="Two Polygons by the even-odd rule")
ax.set_aspect("equal")
plt.show()
Notebook output