Skip to content
Projects

Sphere

Download notebookView on GitHubRun when the site was built.

A ball of a given radius: a probe tip, a dust grain or a spherical electrode.

Sphere(midpoint, radius) has an exact level set, |p - midpoint| - radius, and analytic crossings.

import numpy as np
from simgeometry import Grid, Sphere
ball = Sphere(midpoint=(0.0, 0.0, 0.0), radius=1.0)
print("volume:", ball.volume())
print("distance from (2, 0, 0):", ball.signed_distance((2.0, 0.0, 0.0)))
assert np.isclose(ball.volume(), 4 / 3 * np.pi)
volume: 4.1887902047863905
distance from (2, 0, 0): 1.0

The nodes inside the ball, times the cell volume, approach its volume as the grid is refined.

for n in (11, 21, 41, 81):
grid = Grid(3, (-1.0, -1.0, -1.0), (1.0, 1.0, 1.0), (n, n, n))
cell = np.prod([2.0 / (n - 1)] * 3)
estimate = ball.node_mask(grid).sum() * cell
print(
f"{n:3d}^3 nodes: {estimate:.4f} (error {estimate / ball.volume() - 1:+.2%})"
)
11^3 nodes: 4.0240 (error -3.93%)
21^3 nodes: 4.1570 (error -0.76%)
41^3 nodes: 4.1736 (error -0.36%)
81^3 nodes: 4.1836 (error -0.12%)

show_3d(backend="pyvista") draws the surface with plasma-plots; points= adds labelled point sets, here the nodes of a coarse grid inside the ball.

import plasma_plots
import pyvista as pv
pv.OFF_SCREEN = True # render without a window, e.g. on a docs server
grid = Grid(3, (-1.0, -1.0, -1.0), (1.0, 1.0, 1.0), (13, 11, 9))
inside = grid.node_points()[:, ball.node_mask(grid).ravel()]
plotter = ball.show_3d(
backend="pyvista",
display=False,
resolution=64,
opacity=0.3,
show_bounds=False,
points={"nodes inside": inside},
)
plasma_plots.scene(plotter, alt="A translucent sphere with the grid nodes inside it")
A translucent sphere with the grid nodes inside it
Open in a new tab