From b930885f58b5515afa5ea53cbfa72ad3d6fae4b4 Mon Sep 17 00:00:00 2001 From: Travis Yeager Date: Tue, 27 Oct 2026 11:07:59 -0700 Subject: [PATCH 1/3] Speed up plot geometry and texture preparation --- ssatk/plots/_sphere_raster.py | 57 +++++++++++++++-------- ssatk/plots/coverage_analysis.py | 5 +- ssatk/plots/eclipse_cinematic_light_3d.py | 18 ++++++- ssatk/plots/eclipse_space_view_plotly.py | 2 + ssatk/plots/layers.py | 8 ++-- 5 files changed, 65 insertions(+), 25 deletions(-) diff --git a/ssatk/plots/_sphere_raster.py b/ssatk/plots/_sphere_raster.py index 723955c4..967f8b0c 100644 --- a/ssatk/plots/_sphere_raster.py +++ b/ssatk/plots/_sphere_raster.py @@ -44,6 +44,8 @@ def __init__(self, ax, texture, *, zorder=10): self.set_zorder(zorder) ax.add_artist(self) self.set_clip_path(ax.patch) + self._view_geometry_key = None + self._view_geometry = None def set_surface(self, center, radius, rotation, sun_hat, ambient, diffuse): self.center = np.asarray(center, dtype=float) @@ -60,28 +62,45 @@ def draw(self, renderer): ax = self.axes matrix = ax.get_proj() - corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T - corners = self.center+self.radius*corners - projected = np.column_stack((corners, np.ones(8))) @ matrix.T bounds = np.array([[ax.bbox.x0, ax.bbox.y0], [ax.bbox.x1, ax.bbox.y1]]) - # A box entirely in front of the camera bounds the projected sphere. - if np.all(projected[:, 3] > 0): - pixels = ax.transData.transform(projected[:, :2]/projected[:, 3, None]) - bounds[0] = np.maximum(bounds[0], pixels.min(axis=0)-1) - bounds[1] = np.minimum(bounds[1], pixels.max(axis=0)+1) - lower = np.floor(bounds[0]).astype(int) - upper = np.ceil(bounds[1]).astype(int) scale = renderer.get_image_magnification() - width, height = np.ceil((upper-lower)*scale).astype(int) - if width < 2 or height < 2: + key = ( + matrix.shape, matrix.tobytes(), tuple(bounds.ravel()), float(scale), + tuple(self.center), float(self.radius), + ) + if key != self._view_geometry_key: + corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T + corners = self.center+self.radius*corners + projected = np.column_stack((corners, np.ones(8))) @ matrix.T + # A box entirely in front of the camera bounds the projected sphere. + if np.all(projected[:, 3] > 0): + pixels = ax.transData.transform(projected[:, :2]/projected[:, 3, None]) + bounds[0] = np.maximum(bounds[0], pixels.min(axis=0)-1) + bounds[1] = np.minimum(bounds[1], pixels.max(axis=0)+1) + lower = np.floor(bounds[0]).astype(int) + upper = np.ceil(bounds[1]).astype(int) + width, height = np.ceil((upper-lower)*scale).astype(int) + if width < 2 or height < 2: + self._view_geometry = None + else: + x, y = np.meshgrid(lower[0]+(np.arange(width)+.5)/scale, + lower[1]+(np.arange(height)+.5)/scale) + xy = ax.transData.inverted().transform( + np.column_stack((x.ravel(), y.ravel())) + ) + clip = np.column_stack((xy, -np.ones(len(xy)), np.ones(len(xy)))) + world = clip @ np.linalg.inv(matrix).T + points = (world[:, :3]/world[:, 3, None]).reshape(height, width, 3) + camera = _camera(ax, None) + hits, clearance = sphere_intersections( + points, self.center, self.radius, **camera + ) + self._view_geometry = (lower, points, hits, clearance, camera) + self._view_geometry_key = key + if self._view_geometry is None: return - x, y = np.meshgrid(lower[0]+(np.arange(width)+.5)/scale, - lower[1]+(np.arange(height)+.5)/scale) - xy = ax.transData.inverted().transform(np.column_stack((x.ravel(), y.ravel()))) - clip = np.column_stack((xy, -np.ones(len(xy)), np.ones(len(xy)))) - world = clip @ np.linalg.inv(matrix).T - points = (world[:, :3]/world[:, 3, None]).reshape(height, width, 3) - hits, clearance = sphere_intersections(points, self.center, self.radius, **_camera(ax, None)) + lower, points, hits, clearance, camera = self._view_geometry + height, width = clearance.shape # Linear coverage over the boundary pixel avoids a jagged silhouette. dy, dx = np.gradient(clearance) footprint = np.maximum(np.hypot(dx, dy), np.finfo(float).eps*self.radius) diff --git a/ssatk/plots/coverage_analysis.py b/ssatk/plots/coverage_analysis.py index 594b100b..e6af6e95 100644 --- a/ssatk/plots/coverage_analysis.py +++ b/ssatk/plots/coverage_analysis.py @@ -1460,8 +1460,11 @@ def compute_eclipse(r, r_sun): def compute_sun_positions(t): + # SunPosition accepts an array of times and returns (3, N); calling it + # once and transposing is ~150x faster than one Python call per sample + # (measured: 1.18 s vs 0.007 s for 3000 samples), with identical values. sun = SunPosition() - return np.array([sun(ti) for ti in t]) + return np.asarray(sun(t)).T # ═════════════════════════════════════════════════════════════════════════════ diff --git a/ssatk/plots/eclipse_cinematic_light_3d.py b/ssatk/plots/eclipse_cinematic_light_3d.py index 2b1e0861..0773b6f7 100644 --- a/ssatk/plots/eclipse_cinematic_light_3d.py +++ b/ssatk/plots/eclipse_cinematic_light_3d.py @@ -152,8 +152,10 @@ def _definition(kind: str | ReferenceDefinition | ReferenceEvent) -> ReferenceDe return SOLAR_2024 if str(kind).lower().startswith("solar") else LUNAR_2025 -def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, dict[str, object]]: - """Embed a texture as an in-memory WebP derivative of the installed PNG/JPEG.""" +@lru_cache(maxsize=8) +def _texture_uri_cached(path: str, modified_ns: int, size: int, max_width: int, + quality: int) -> tuple[str, dict[str, object]]: + """Build one immutable cache entry for a source texture revision.""" from PIL import Image with Image.open(path) as image: @@ -168,6 +170,18 @@ def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, return uri, {"source_name": Path(path).name, "embedded_bytes": len(buffer.getvalue())} +def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, dict[str, object]]: + """Embed a texture, reusing only an unchanged source/option combination.""" + path = Path(path) + stat = path.stat() + uri, metadata = _texture_uri_cached( + str(path), int(stat.st_mtime_ns), int(stat.st_size), + int(max_width), int(quality), + ) + # Callers may annotate their copy without corrupting future cache hits. + return uri, dict(metadata) + + def _rotation_rows_itrf_to_scene(state: PublicPeakState) -> np.ndarray: """Column-vector rotation matrix from the event-owned ITRF to scene.""" gcrf_rows = np.asarray( diff --git a/ssatk/plots/eclipse_space_view_plotly.py b/ssatk/plots/eclipse_space_view_plotly.py index bbe6dfb3..88458ec0 100644 --- a/ssatk/plots/eclipse_space_view_plotly.py +++ b/ssatk/plots/eclipse_space_view_plotly.py @@ -2055,6 +2055,8 @@ def plot_space_view_animated(mode="lunar", search_days=None, n_frames=26, since this rebuilds full Earth+Moon meshes per frame — n_frames=28 at full 180x360 resolution would be quite slow to generate. """ + if n_frames < 1: + raise ValueError("n_frames must be at least 1") assert mode in ("lunar", "solar") window = _eclipse_window(mode, search_days=search_days, event=event, n_steps=4000, verbose=verbose) t_fine = window["t_s"] diff --git a/ssatk/plots/layers.py b/ssatk/plots/layers.py index 53ae7f1e..76ef3163 100644 --- a/ssatk/plots/layers.py +++ b/ssatk/plots/layers.py @@ -525,7 +525,8 @@ def add_to_plotly(self, fig, orbit_state, traj=None, satellite=None, **kw): verts_x = X.ravel(); verts_y = Y.ravel(); verts_z = Z.ravel() H, W = self.n_lat, self.n_lon i_idx, j_idx, k_idx = [], [], [] - cols = [] + cols = np.empty(2 * (H - 1) * (W - 1), dtype=object) + face = 0 for r in range(H - 1): for c in range(W - 1): v0 = r*W + c; v1 = v0+1; v2 = (r+1)*W + c; v3 = v2+1 @@ -536,11 +537,12 @@ def add_to_plotly(self, fig, orbit_state, traj=None, satellite=None, **kw): col = f"rgb({pixel[0]},{pixel[1]},{pixel[2]})" for tri in [(v0,v1,v2),(v1,v3,v2)]: i_idx.append(tri[0]); j_idx.append(tri[1]); k_idx.append(tri[2]) - cols.append(col) + cols[face] = col + face += 1 fig.add_trace(go.Mesh3d( x=verts_x, y=verts_y, z=verts_z, i=i_idx, j=j_idx, k=k_idx, - facecolor=cols, + facecolor=np.asarray(cols), name="Earth", hoverinfo="skip", showlegend=False, )) else: From 92952d45be48e605cacb5ec700f004eef73bc05b Mon Sep 17 00:00:00 2001 From: Travis Yeager Date: Tue, 27 Oct 2026 11:32:14 -0700 Subject: [PATCH 2/3] Invalidate plot caches on resolved paths and transforms --- ssatk/plots/_sphere_raster.py | 18 +++++++++++++++--- ssatk/plots/coverage_analysis.py | 4 +--- ssatk/plots/eclipse_cinematic_light_3d.py | 2 +- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/ssatk/plots/_sphere_raster.py b/ssatk/plots/_sphere_raster.py index 967f8b0c..ab0d0133 100644 --- a/ssatk/plots/_sphere_raster.py +++ b/ssatk/plots/_sphere_raster.py @@ -64,9 +64,21 @@ def draw(self, renderer): matrix = ax.get_proj() bounds = np.array([[ax.bbox.x0, ax.bbox.y0], [ax.bbox.x1, ax.bbox.y1]]) scale = renderer.get_image_magnification() + data_transform = ax.transData + if data_transform.is_affine: + data_transform_key = ( + "affine", data_transform.get_affine().get_matrix().tobytes() + ) + else: + probes = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.]]) + data_transform_key = ( + "non-affine", + data_transform.transform(probes).tobytes(), + data_transform.inverted().transform(probes).tobytes(), + ) key = ( matrix.shape, matrix.tobytes(), tuple(bounds.ravel()), float(scale), - tuple(self.center), float(self.radius), + data_transform_key, tuple(self.center), float(self.radius), ) if key != self._view_geometry_key: corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T @@ -74,7 +86,7 @@ def draw(self, renderer): projected = np.column_stack((corners, np.ones(8))) @ matrix.T # A box entirely in front of the camera bounds the projected sphere. if np.all(projected[:, 3] > 0): - pixels = ax.transData.transform(projected[:, :2]/projected[:, 3, None]) + pixels = data_transform.transform(projected[:, :2]/projected[:, 3, None]) bounds[0] = np.maximum(bounds[0], pixels.min(axis=0)-1) bounds[1] = np.minimum(bounds[1], pixels.max(axis=0)+1) lower = np.floor(bounds[0]).astype(int) @@ -85,7 +97,7 @@ def draw(self, renderer): else: x, y = np.meshgrid(lower[0]+(np.arange(width)+.5)/scale, lower[1]+(np.arange(height)+.5)/scale) - xy = ax.transData.inverted().transform( + xy = data_transform.inverted().transform( np.column_stack((x.ravel(), y.ravel())) ) clip = np.column_stack((xy, -np.ones(len(xy)), np.ones(len(xy)))) diff --git a/ssatk/plots/coverage_analysis.py b/ssatk/plots/coverage_analysis.py index e6af6e95..199c06e4 100644 --- a/ssatk/plots/coverage_analysis.py +++ b/ssatk/plots/coverage_analysis.py @@ -1460,9 +1460,7 @@ def compute_eclipse(r, r_sun): def compute_sun_positions(t): - # SunPosition accepts an array of times and returns (3, N); calling it - # once and transposing is ~150x faster than one Python call per sample - # (measured: 1.18 s vs 0.007 s for 3000 samples), with identical values. + """Return SunPosition samples as an ``(N, 3)`` array, including empty input.""" sun = SunPosition() return np.asarray(sun(t)).T diff --git a/ssatk/plots/eclipse_cinematic_light_3d.py b/ssatk/plots/eclipse_cinematic_light_3d.py index 0773b6f7..9a637779 100644 --- a/ssatk/plots/eclipse_cinematic_light_3d.py +++ b/ssatk/plots/eclipse_cinematic_light_3d.py @@ -172,7 +172,7 @@ def _texture_uri_cached(path: str, modified_ns: int, size: int, max_width: int, def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, dict[str, object]]: """Embed a texture, reusing only an unchanged source/option combination.""" - path = Path(path) + path = Path(path).expanduser().resolve() stat = path.stat() uri, metadata = _texture_uri_cached( str(path), int(stat.st_mtime_ns), int(stat.st_size), From 646d6967fb3402e2aea29877d9d85227e0f6713a Mon Sep 17 00:00:00 2001 From: Travis Yeager Date: Tue, 27 Oct 2026 11:39:53 -0700 Subject: [PATCH 3/3] Avoid approximate cache keys for nonlinear transforms --- ssatk/plots/_sphere_raster.py | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/ssatk/plots/_sphere_raster.py b/ssatk/plots/_sphere_raster.py index ab0d0133..1556db45 100644 --- a/ssatk/plots/_sphere_raster.py +++ b/ssatk/plots/_sphere_raster.py @@ -65,22 +65,18 @@ def draw(self, renderer): bounds = np.array([[ax.bbox.x0, ax.bbox.y0], [ax.bbox.x1, ax.bbox.y1]]) scale = renderer.get_image_magnification() data_transform = ax.transData - if data_transform.is_affine: - data_transform_key = ( - "affine", data_transform.get_affine().get_matrix().tobytes() - ) - else: - probes = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.]]) - data_transform_key = ( - "non-affine", - data_transform.transform(probes).tobytes(), - data_transform.inverted().transform(probes).tobytes(), - ) + cacheable_transform = data_transform.is_affine + data_transform_key = ( + data_transform.get_affine().get_matrix().tobytes() + if cacheable_transform else None + ) key = ( matrix.shape, matrix.tobytes(), tuple(bounds.ravel()), float(scale), data_transform_key, tuple(self.center), float(self.radius), ) - if key != self._view_geometry_key: + # A nonlinear transform has no compact, exact fingerprint here. Never + # reuse geometry for it rather than approximating its state by probes. + if not cacheable_transform or key != self._view_geometry_key: corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T corners = self.center+self.radius*corners projected = np.column_stack((corners, np.ones(8))) @ matrix.T @@ -108,7 +104,7 @@ def draw(self, renderer): points, self.center, self.radius, **camera ) self._view_geometry = (lower, points, hits, clearance, camera) - self._view_geometry_key = key + self._view_geometry_key = key if cacheable_transform else None if self._view_geometry is None: return lower, points, hits, clearance, camera = self._view_geometry