Source code for celestial_rhapsody.animation

"""Animation of a :class:`~celestial_rhapsody.solvers.Trajectory` (GIF or MP4)."""

from __future__ import annotations

import shutil
from pathlib import Path
from typing import Optional, Union

import matplotlib

matplotlib.use("Agg")  # render without a screen (laptops, servers, CI)
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
from matplotlib import animation  # noqa: E402

from .solvers import Trajectory  # noqa: E402


[docs] def animate( trajectory: Trajectory, output: Union[str, Path] = "movie.gif", fps: int = 30, trail: Optional[int] = None, title: Optional[str] = None, dpi: int = 100, ) -> Path: """Save an animation of the orbits in the x-y plane. The format comes from the file extension: ``.gif`` works everywhere, ``.mp4`` needs `ffmpeg <https://ffmpeg.org>`_. Args: trajectory: Output of :func:`celestial_rhapsody.simulate`. output: File to write, e.g. ``"orbits.gif"``. fps: Frames per second. trail: Number of past frames drawn behind each body. ``None`` (default) draws the whole path; ``0`` draws none. title: Optional plot title. dpi: Resolution. Returns: Path of the written file. """ output = Path(output) suffix = output.suffix.lower() if suffix == ".gif": writer = animation.PillowWriter(fps=fps) elif suffix == ".mp4": if shutil.which("ffmpeg") is None: raise RuntimeError("Saving .mp4 needs ffmpeg installed. Use a .gif output, or install ffmpeg.") writer = animation.FFMpegWriter(fps=fps) else: raise ValueError(f"Unsupported output type '{suffix}'. Use .gif or .mp4.") pos = trajectory.positions[:, :, :2] n_frames, n_bodies, _ = pos.shape fig, ax = plt.subplots(figsize=(6, 6)) lo, hi = pos.min(axis=(0, 1)), pos.max(axis=(0, 1)) half = 0.55 * max(hi - lo) + 1e-9 centre = (lo + hi) / 2 ax.set_xlim(centre[0] - half, centre[0] + half) ax.set_ylim(centre[1] - half, centre[1] + half) ax.set_aspect("equal") ax.set_xlabel("x") ax.set_ylabel("y") if title: ax.set_title(title) colors = plt.cm.tab10(np.arange(n_bodies) % 10) sizes = 30 + 70 * trajectory.masses / trajectory.masses.max() lines = [ax.plot([], [], "-", lw=1.2, color=colors[i], alpha=0.7, label=trajectory.names[i])[0] for i in range(n_bodies)] dots = ax.scatter(pos[0, :, 0], pos[0, :, 1], s=sizes, c=colors, zorder=3) if n_bodies <= 10: ax.legend(loc="upper right", fontsize=8) clock = ax.text(0.02, 0.96, "", transform=ax.transAxes) def update(k: int): start = 0 if trail is None else max(0, k - trail) for i, line in enumerate(lines): line.set_data(pos[start:k + 1, i, 0], pos[start:k + 1, i, 1]) dots.set_offsets(pos[k]) clock.set_text(f"t = {trajectory.times[k]:.2f}") return [*lines, dots, clock] movie = animation.FuncAnimation(fig, update, frames=n_frames, interval=1000 / fps, blit=True) movie.save(str(output), writer=writer, dpi=dpi) plt.close(fig) return output